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