1 //===-- MachOUtils.cpp - Mach-o specific helpers for dsymutil  ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "MachOUtils.h"
11 #include "BinaryHolder.h"
12 #include "DebugMap.h"
13 #include "LinkUtils.h"
14 #include "NonRelocatableStringpool.h"
15 #include "llvm/MC/MCAsmLayout.h"
16 #include "llvm/MC/MCMachObjectWriter.h"
17 #include "llvm/MC/MCObjectStreamer.h"
18 #include "llvm/MC/MCSectionMachO.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/Object/MachO.h"
21 #include "llvm/Support/FileUtilities.h"
22 #include "llvm/Support/Program.h"
23 #include "llvm/Support/WithColor.h"
24 #include "llvm/Support/raw_ostream.h"
25 
26 namespace llvm {
27 namespace dsymutil {
28 namespace MachOUtils {
29 
30 std::string getArchName(StringRef Arch) {
31   if (Arch.startswith("thumb"))
32     return (llvm::Twine("arm") + Arch.drop_front(5)).str();
33   return Arch;
34 }
35 
36 static bool runLipo(StringRef SDKPath, SmallVectorImpl<StringRef> &Args) {
37   auto Path = sys::findProgramByName("lipo", makeArrayRef(SDKPath));
38   if (!Path)
39     Path = sys::findProgramByName("lipo");
40 
41   if (!Path) {
42     WithColor::error() << "lipo: " << Path.getError().message() << "\n";
43     return false;
44   }
45 
46   std::string ErrMsg;
47   int result = sys::ExecuteAndWait(*Path, Args, None, {}, 0, 0, &ErrMsg);
48   if (result) {
49     WithColor::error() << "lipo: " << ErrMsg << "\n";
50     return false;
51   }
52 
53   return true;
54 }
55 
56 bool generateUniversalBinary(SmallVectorImpl<ArchAndFilename> &ArchFiles,
57                              StringRef OutputFileName,
58                              const LinkOptions &Options, StringRef SDKPath) {
59   // No need to merge one file into a universal fat binary. First, try
60   // to move it (rename) to the final location. If that fails because
61   // of cross-device link issues then copy and delete.
62   if (ArchFiles.size() == 1) {
63     StringRef From(ArchFiles.front().Path);
64     if (sys::fs::rename(From, OutputFileName)) {
65       if (std::error_code EC = sys::fs::copy_file(From, OutputFileName)) {
66         WithColor::error() << "while copying " << From << " to "
67                            << OutputFileName << ": " << EC.message() << "\n";
68         return false;
69       }
70       sys::fs::remove(From);
71     }
72     return true;
73   }
74 
75   SmallVector<StringRef, 8> Args;
76   Args.push_back("lipo");
77   Args.push_back("-create");
78 
79   for (auto &Thin : ArchFiles)
80     Args.push_back(Thin.Path);
81 
82   // Align segments to match dsymutil-classic alignment
83   for (auto &Thin : ArchFiles) {
84     Thin.Arch = getArchName(Thin.Arch);
85     Args.push_back("-segalign");
86     Args.push_back(Thin.Arch);
87     Args.push_back("20");
88   }
89 
90   Args.push_back("-output");
91   Args.push_back(OutputFileName.data());
92 
93   if (Options.Verbose) {
94     outs() << "Running lipo\n";
95     for (auto Arg : Args)
96       outs() << ' ' << Arg;
97     outs() << "\n";
98   }
99 
100   return Options.NoOutput ? true : runLipo(SDKPath, Args);
101 }
102 
103 // Return a MachO::segment_command_64 that holds the same values as the passed
104 // MachO::segment_command. We do that to avoid having to duplicate the logic
105 // for 32bits and 64bits segments.
106 struct MachO::segment_command_64 adaptFrom32bits(MachO::segment_command Seg) {
107   MachO::segment_command_64 Seg64;
108   Seg64.cmd = Seg.cmd;
109   Seg64.cmdsize = Seg.cmdsize;
110   memcpy(Seg64.segname, Seg.segname, sizeof(Seg.segname));
111   Seg64.vmaddr = Seg.vmaddr;
112   Seg64.vmsize = Seg.vmsize;
113   Seg64.fileoff = Seg.fileoff;
114   Seg64.filesize = Seg.filesize;
115   Seg64.maxprot = Seg.maxprot;
116   Seg64.initprot = Seg.initprot;
117   Seg64.nsects = Seg.nsects;
118   Seg64.flags = Seg.flags;
119   return Seg64;
120 }
121 
122 // Iterate on all \a Obj segments, and apply \a Handler to them.
123 template <typename FunctionTy>
124 static void iterateOnSegments(const object::MachOObjectFile &Obj,
125                               FunctionTy Handler) {
126   for (const auto &LCI : Obj.load_commands()) {
127     MachO::segment_command_64 Segment;
128     if (LCI.C.cmd == MachO::LC_SEGMENT)
129       Segment = adaptFrom32bits(Obj.getSegmentLoadCommand(LCI));
130     else if (LCI.C.cmd == MachO::LC_SEGMENT_64)
131       Segment = Obj.getSegment64LoadCommand(LCI);
132     else
133       continue;
134 
135     Handler(Segment);
136   }
137 }
138 
139 // Transfer the symbols described by \a NList to \a NewSymtab which is just the
140 // raw contents of the symbol table for the dSYM companion file. \returns
141 // whether the symbol was transferred or not.
142 template <typename NListTy>
143 static bool transferSymbol(NListTy NList, bool IsLittleEndian,
144                            StringRef Strings, SmallVectorImpl<char> &NewSymtab,
145                            NonRelocatableStringpool &NewStrings,
146                            bool &InDebugNote) {
147   // Do not transfer undefined symbols, we want real addresses.
148   if ((NList.n_type & MachO::N_TYPE) == MachO::N_UNDF)
149     return false;
150 
151   StringRef Name = StringRef(Strings.begin() + NList.n_strx);
152   if (InDebugNote) {
153     InDebugNote =
154         (NList.n_type != MachO::N_SO) || (!Name.empty() && Name[0] != '\0');
155     return false;
156   } else if (NList.n_type == MachO::N_SO) {
157     InDebugNote = true;
158     return false;
159   }
160 
161   // FIXME: The + 1 is here to mimic dsymutil-classic that has 2 empty
162   // strings at the start of the generated string table (There is
163   // corresponding code in the string table emission).
164   NList.n_strx = NewStrings.getStringOffset(Name) + 1;
165   if (IsLittleEndian != sys::IsLittleEndianHost)
166     MachO::swapStruct(NList);
167 
168   NewSymtab.append(reinterpret_cast<char *>(&NList),
169                    reinterpret_cast<char *>(&NList + 1));
170   return true;
171 }
172 
173 // Wrapper around transferSymbol to transfer all of \a Obj symbols
174 // to \a NewSymtab. This function does not write in the output file.
175 // \returns the number of symbols in \a NewSymtab.
176 static unsigned transferSymbols(const object::MachOObjectFile &Obj,
177                                 SmallVectorImpl<char> &NewSymtab,
178                                 NonRelocatableStringpool &NewStrings) {
179   unsigned Syms = 0;
180   StringRef Strings = Obj.getStringTableData();
181   bool IsLittleEndian = Obj.isLittleEndian();
182   bool InDebugNote = false;
183 
184   if (Obj.is64Bit()) {
185     for (const object::SymbolRef &Symbol : Obj.symbols()) {
186       object::DataRefImpl DRI = Symbol.getRawDataRefImpl();
187       if (transferSymbol(Obj.getSymbol64TableEntry(DRI), IsLittleEndian,
188                          Strings, NewSymtab, NewStrings, InDebugNote))
189         ++Syms;
190     }
191   } else {
192     for (const object::SymbolRef &Symbol : Obj.symbols()) {
193       object::DataRefImpl DRI = Symbol.getRawDataRefImpl();
194       if (transferSymbol(Obj.getSymbolTableEntry(DRI), IsLittleEndian, Strings,
195                          NewSymtab, NewStrings, InDebugNote))
196         ++Syms;
197     }
198   }
199   return Syms;
200 }
201 
202 static MachO::section
203 getSection(const object::MachOObjectFile &Obj,
204            const MachO::segment_command &Seg,
205            const object::MachOObjectFile::LoadCommandInfo &LCI, unsigned Idx) {
206   return Obj.getSection(LCI, Idx);
207 }
208 
209 static MachO::section_64
210 getSection(const object::MachOObjectFile &Obj,
211            const MachO::segment_command_64 &Seg,
212            const object::MachOObjectFile::LoadCommandInfo &LCI, unsigned Idx) {
213   return Obj.getSection64(LCI, Idx);
214 }
215 
216 // Transfer \a Segment from \a Obj to the output file. This calls into \a Writer
217 // to write these load commands directly in the output file at the current
218 // position.
219 // The function also tries to find a hole in the address map to fit the __DWARF
220 // segment of \a DwarfSegmentSize size. \a EndAddress is updated to point at the
221 // highest segment address.
222 // When the __LINKEDIT segment is transferred, its offset and size are set resp.
223 // to \a LinkeditOffset and \a LinkeditSize.
224 template <typename SegmentTy>
225 static void transferSegmentAndSections(
226     const object::MachOObjectFile::LoadCommandInfo &LCI, SegmentTy Segment,
227     const object::MachOObjectFile &Obj, MachObjectWriter &Writer,
228     uint64_t LinkeditOffset, uint64_t LinkeditSize, uint64_t DwarfSegmentSize,
229     uint64_t &GapForDwarf, uint64_t &EndAddress) {
230   if (StringRef("__DWARF") == Segment.segname)
231     return;
232 
233   Segment.fileoff = Segment.filesize = 0;
234 
235   if (StringRef("__LINKEDIT") == Segment.segname) {
236     Segment.fileoff = LinkeditOffset;
237     Segment.filesize = LinkeditSize;
238     // Resize vmsize by rounding to the page size.
239     Segment.vmsize = alignTo(LinkeditSize, 0x1000);
240   }
241 
242   // Check if the end address of the last segment and our current
243   // start address leave a sufficient gap to store the __DWARF
244   // segment.
245   uint64_t PrevEndAddress = EndAddress;
246   EndAddress = alignTo(EndAddress, 0x1000);
247   if (GapForDwarf == UINT64_MAX && Segment.vmaddr > EndAddress &&
248       Segment.vmaddr - EndAddress >= DwarfSegmentSize)
249     GapForDwarf = EndAddress;
250 
251   // The segments are not necessarily sorted by their vmaddr.
252   EndAddress =
253       std::max<uint64_t>(PrevEndAddress, Segment.vmaddr + Segment.vmsize);
254   unsigned nsects = Segment.nsects;
255   if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
256     MachO::swapStruct(Segment);
257   Writer.W.OS.write(reinterpret_cast<char *>(&Segment), sizeof(Segment));
258   for (unsigned i = 0; i < nsects; ++i) {
259     auto Sect = getSection(Obj, Segment, LCI, i);
260     Sect.offset = Sect.reloff = Sect.nreloc = 0;
261     if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
262       MachO::swapStruct(Sect);
263     Writer.W.OS.write(reinterpret_cast<char *>(&Sect), sizeof(Sect));
264   }
265 }
266 
267 // Write the __DWARF segment load command to the output file.
268 static void createDwarfSegment(uint64_t VMAddr, uint64_t FileOffset,
269                                uint64_t FileSize, unsigned NumSections,
270                                MCAsmLayout &Layout, MachObjectWriter &Writer) {
271   Writer.writeSegmentLoadCommand("__DWARF", NumSections, VMAddr,
272                                  alignTo(FileSize, 0x1000), FileOffset,
273                                  FileSize, /* MaxProt */ 7,
274                                  /* InitProt =*/3);
275 
276   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
277     MCSection *Sec = Layout.getSectionOrder()[i];
278     if (Sec->begin() == Sec->end() || !Layout.getSectionFileSize(Sec))
279       continue;
280 
281     unsigned Align = Sec->getAlignment();
282     if (Align > 1) {
283       VMAddr = alignTo(VMAddr, Align);
284       FileOffset = alignTo(FileOffset, Align);
285     }
286     Writer.writeSection(Layout, *Sec, VMAddr, FileOffset, 0, 0, 0);
287 
288     FileOffset += Layout.getSectionAddressSize(Sec);
289     VMAddr += Layout.getSectionAddressSize(Sec);
290   }
291 }
292 
293 static bool isExecutable(const object::MachOObjectFile &Obj) {
294   if (Obj.is64Bit())
295     return Obj.getHeader64().filetype != MachO::MH_OBJECT;
296   else
297     return Obj.getHeader().filetype != MachO::MH_OBJECT;
298 }
299 
300 static bool hasLinkEditSegment(const object::MachOObjectFile &Obj) {
301   bool HasLinkEditSegment = false;
302   iterateOnSegments(Obj, [&](const MachO::segment_command_64 &Segment) {
303     if (StringRef("__LINKEDIT") == Segment.segname)
304       HasLinkEditSegment = true;
305   });
306   return HasLinkEditSegment;
307 }
308 
309 static unsigned segmentLoadCommandSize(bool Is64Bit, unsigned NumSections) {
310   if (Is64Bit)
311     return sizeof(MachO::segment_command_64) +
312            NumSections * sizeof(MachO::section_64);
313 
314   return sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
315 }
316 
317 // Stream a dSYM companion binary file corresponding to the binary referenced
318 // by \a DM to \a OutFile. The passed \a MS MCStreamer is setup to write to
319 // \a OutFile and it must be using a MachObjectWriter object to do so.
320 bool generateDsymCompanion(const DebugMap &DM, MCStreamer &MS,
321                            raw_fd_ostream &OutFile) {
322   auto &ObjectStreamer = static_cast<MCObjectStreamer &>(MS);
323   MCAssembler &MCAsm = ObjectStreamer.getAssembler();
324   auto &Writer = static_cast<MachObjectWriter &>(MCAsm.getWriter());
325 
326   // Layout but don't emit.
327   ObjectStreamer.flushPendingLabels();
328   MCAsmLayout Layout(MCAsm);
329   MCAsm.layout(Layout);
330 
331   BinaryHolder InputBinaryHolder(false);
332 
333   auto ObjectEntry = InputBinaryHolder.getObjectEntry(DM.getBinaryPath());
334   if (!ObjectEntry) {
335     auto Err = ObjectEntry.takeError();
336     return error(Twine("opening ") + DM.getBinaryPath() + ": " +
337                      toString(std::move(Err)),
338                  "output file streaming");
339   }
340 
341   auto Object =
342       ObjectEntry->getObjectAs<object::MachOObjectFile>(DM.getTriple());
343   if (!Object) {
344     auto Err = Object.takeError();
345     return error(Twine("opening ") + DM.getBinaryPath() + ": " +
346                      toString(std::move(Err)),
347                  "output file streaming");
348   }
349 
350   auto &InputBinary = *Object;
351 
352   bool Is64Bit = Writer.is64Bit();
353   MachO::symtab_command SymtabCmd = InputBinary.getSymtabLoadCommand();
354 
355   // Get UUID.
356   MachO::uuid_command UUIDCmd;
357   memset(&UUIDCmd, 0, sizeof(UUIDCmd));
358   UUIDCmd.cmd = MachO::LC_UUID;
359   UUIDCmd.cmdsize = sizeof(MachO::uuid_command);
360   for (auto &LCI : InputBinary.load_commands()) {
361     if (LCI.C.cmd == MachO::LC_UUID) {
362       UUIDCmd = InputBinary.getUuidCommand(LCI);
363       break;
364     }
365   }
366 
367   // Compute the number of load commands we will need.
368   unsigned LoadCommandSize = 0;
369   unsigned NumLoadCommands = 0;
370   // We will copy the UUID if there is one.
371   if (UUIDCmd.cmd != 0) {
372     ++NumLoadCommands;
373     LoadCommandSize += sizeof(MachO::uuid_command);
374   }
375 
376   // If we have a valid symtab to copy, do it.
377   bool ShouldEmitSymtab =
378       isExecutable(InputBinary) && hasLinkEditSegment(InputBinary);
379   if (ShouldEmitSymtab) {
380     LoadCommandSize += sizeof(MachO::symtab_command);
381     ++NumLoadCommands;
382   }
383 
384   unsigned HeaderSize =
385       Is64Bit ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header);
386   // We will copy every segment that isn't __DWARF.
387   iterateOnSegments(InputBinary, [&](const MachO::segment_command_64 &Segment) {
388     if (StringRef("__DWARF") == Segment.segname)
389       return;
390 
391     ++NumLoadCommands;
392     LoadCommandSize += segmentLoadCommandSize(Is64Bit, Segment.nsects);
393   });
394 
395   // We will add our own brand new __DWARF segment if we have debug
396   // info.
397   unsigned NumDwarfSections = 0;
398   uint64_t DwarfSegmentSize = 0;
399 
400   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
401     MCSection *Sec = Layout.getSectionOrder()[i];
402     if (Sec->begin() == Sec->end())
403       continue;
404 
405     if (uint64_t Size = Layout.getSectionFileSize(Sec)) {
406       DwarfSegmentSize = alignTo(DwarfSegmentSize, Sec->getAlignment());
407       DwarfSegmentSize += Size;
408       ++NumDwarfSections;
409     }
410   }
411 
412   if (NumDwarfSections) {
413     ++NumLoadCommands;
414     LoadCommandSize += segmentLoadCommandSize(Is64Bit, NumDwarfSections);
415   }
416 
417   SmallString<0> NewSymtab;
418   NonRelocatableStringpool NewStrings;
419   unsigned NListSize = Is64Bit ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
420   unsigned NumSyms = 0;
421   uint64_t NewStringsSize = 0;
422   if (ShouldEmitSymtab) {
423     NewSymtab.reserve(SymtabCmd.nsyms * NListSize / 2);
424     NumSyms = transferSymbols(InputBinary, NewSymtab, NewStrings);
425     NewStringsSize = NewStrings.getSize() + 1;
426   }
427 
428   uint64_t SymtabStart = LoadCommandSize;
429   SymtabStart += HeaderSize;
430   SymtabStart = alignTo(SymtabStart, 0x1000);
431 
432   // We gathered all the information we need, start emitting the output file.
433   Writer.writeHeader(MachO::MH_DSYM, NumLoadCommands, LoadCommandSize, false);
434 
435   // Write the load commands.
436   assert(OutFile.tell() == HeaderSize);
437   if (UUIDCmd.cmd != 0) {
438     Writer.W.write<uint32_t>(UUIDCmd.cmd);
439     Writer.W.write<uint32_t>(UUIDCmd.cmdsize);
440     OutFile.write(reinterpret_cast<const char *>(UUIDCmd.uuid), 16);
441     assert(OutFile.tell() == HeaderSize + sizeof(UUIDCmd));
442   }
443 
444   assert(SymtabCmd.cmd && "No symbol table.");
445   uint64_t StringStart = SymtabStart + NumSyms * NListSize;
446   if (ShouldEmitSymtab)
447     Writer.writeSymtabLoadCommand(SymtabStart, NumSyms, StringStart,
448                                   NewStringsSize);
449 
450   uint64_t DwarfSegmentStart = StringStart + NewStringsSize;
451   DwarfSegmentStart = alignTo(DwarfSegmentStart, 0x1000);
452 
453   // Write the load commands for the segments and sections we 'import' from
454   // the original binary.
455   uint64_t EndAddress = 0;
456   uint64_t GapForDwarf = UINT64_MAX;
457   for (auto &LCI : InputBinary.load_commands()) {
458     if (LCI.C.cmd == MachO::LC_SEGMENT)
459       transferSegmentAndSections(LCI, InputBinary.getSegmentLoadCommand(LCI),
460                                  InputBinary, Writer, SymtabStart,
461                                  StringStart + NewStringsSize - SymtabStart,
462                                  DwarfSegmentSize, GapForDwarf, EndAddress);
463     else if (LCI.C.cmd == MachO::LC_SEGMENT_64)
464       transferSegmentAndSections(LCI, InputBinary.getSegment64LoadCommand(LCI),
465                                  InputBinary, Writer, SymtabStart,
466                                  StringStart + NewStringsSize - SymtabStart,
467                                  DwarfSegmentSize, GapForDwarf, EndAddress);
468   }
469 
470   uint64_t DwarfVMAddr = alignTo(EndAddress, 0x1000);
471   uint64_t DwarfVMMax = Is64Bit ? UINT64_MAX : UINT32_MAX;
472   if (DwarfVMAddr + DwarfSegmentSize > DwarfVMMax ||
473       DwarfVMAddr + DwarfSegmentSize < DwarfVMAddr /* Overflow */) {
474     // There is no room for the __DWARF segment at the end of the
475     // address space. Look through segments to find a gap.
476     DwarfVMAddr = GapForDwarf;
477     if (DwarfVMAddr == UINT64_MAX)
478       warn("not enough VM space for the __DWARF segment.",
479            "output file streaming");
480   }
481 
482   // Write the load command for the __DWARF segment.
483   createDwarfSegment(DwarfVMAddr, DwarfSegmentStart, DwarfSegmentSize,
484                      NumDwarfSections, Layout, Writer);
485 
486   assert(OutFile.tell() == LoadCommandSize + HeaderSize);
487   OutFile.write_zeros(SymtabStart - (LoadCommandSize + HeaderSize));
488   assert(OutFile.tell() == SymtabStart);
489 
490   // Transfer symbols.
491   if (ShouldEmitSymtab) {
492     OutFile << NewSymtab.str();
493     assert(OutFile.tell() == StringStart);
494 
495     // Transfer string table.
496     // FIXME: The NonRelocatableStringpool starts with an empty string, but
497     // dsymutil-classic starts the reconstructed string table with 2 of these.
498     // Reproduce that behavior for now (there is corresponding code in
499     // transferSymbol).
500     OutFile << '\0';
501     std::vector<DwarfStringPoolEntryRef> Strings = NewStrings.getEntries();
502     for (auto EntryRef : Strings) {
503       if (EntryRef.getIndex() == -1U)
504         break;
505       OutFile.write(EntryRef.getString().data(),
506                     EntryRef.getString().size() + 1);
507     }
508   }
509 
510   assert(OutFile.tell() == StringStart + NewStringsSize);
511 
512   // Pad till the Dwarf segment start.
513   OutFile.write_zeros(DwarfSegmentStart - (StringStart + NewStringsSize));
514   assert(OutFile.tell() == DwarfSegmentStart);
515 
516   // Emit the Dwarf sections contents.
517   for (const MCSection &Sec : MCAsm) {
518     if (Sec.begin() == Sec.end())
519       continue;
520 
521     uint64_t Pos = OutFile.tell();
522     OutFile.write_zeros(alignTo(Pos, Sec.getAlignment()) - Pos);
523     MCAsm.writeSectionData(OutFile, &Sec, Layout);
524   }
525 
526   return true;
527 }
528 } // namespace MachOUtils
529 } // namespace dsymutil
530 } // namespace llvm
531