OSDN Git Service

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