1 //===-- MachOUtils.cpp - Mach-o specific helpers for dsymutil  ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "MachOUtils.h"
10 #include "BinaryHolder.h"
11 #include "DebugMap.h"
12 #include "LinkUtils.h"
13 #include "llvm/CodeGen/NonRelocatableStringpool.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCAssembler.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/MC/MCSubtargetInfo.h"
21 #include "llvm/Object/MachO.h"
22 #include "llvm/Support/FileUtilities.h"
23 #include "llvm/Support/Program.h"
24 #include "llvm/Support/WithColor.h"
25 #include "llvm/Support/raw_ostream.h"
26 
27 namespace llvm {
28 namespace dsymutil {
29 namespace MachOUtils {
30 
createTempFile()31 llvm::Error ArchAndFile::createTempFile() {
32   llvm::SmallString<128> TmpModel;
33   llvm::sys::path::system_temp_directory(true, TmpModel);
34   llvm::sys::path::append(TmpModel, "dsym.tmp%%%%%.dwarf");
35   Expected<sys::fs::TempFile> T = sys::fs::TempFile::create(TmpModel);
36 
37   if (!T)
38     return T.takeError();
39 
40   File = std::make_unique<sys::fs::TempFile>(std::move(*T));
41   return Error::success();
42 }
43 
path() const44 llvm::StringRef ArchAndFile::path() const { return File->TmpName; }
45 
~ArchAndFile()46 ArchAndFile::~ArchAndFile() {
47   if (File)
48     if (auto E = File->discard())
49       llvm::consumeError(std::move(E));
50 }
51 
getArchName(StringRef Arch)52 std::string getArchName(StringRef Arch) {
53   if (Arch.startswith("thumb"))
54     return (llvm::Twine("arm") + Arch.drop_front(5)).str();
55   return std::string(Arch);
56 }
57 
runLipo(StringRef SDKPath,SmallVectorImpl<StringRef> & Args)58 static bool runLipo(StringRef SDKPath, SmallVectorImpl<StringRef> &Args) {
59   auto Path = sys::findProgramByName("lipo", makeArrayRef(SDKPath));
60   if (!Path)
61     Path = sys::findProgramByName("lipo");
62 
63   if (!Path) {
64     WithColor::error() << "lipo: " << Path.getError().message() << "\n";
65     return false;
66   }
67 
68   std::string ErrMsg;
69   int result = sys::ExecuteAndWait(*Path, Args, None, {}, 0, 0, &ErrMsg);
70   if (result) {
71     WithColor::error() << "lipo: " << ErrMsg << "\n";
72     return false;
73   }
74 
75   return true;
76 }
77 
generateUniversalBinary(SmallVectorImpl<ArchAndFile> & ArchFiles,StringRef OutputFileName,const LinkOptions & Options,StringRef SDKPath)78 bool generateUniversalBinary(SmallVectorImpl<ArchAndFile> &ArchFiles,
79                              StringRef OutputFileName,
80                              const LinkOptions &Options, StringRef SDKPath) {
81   // No need to merge one file into a universal fat binary.
82   if (ArchFiles.size() == 1) {
83     if (auto E = ArchFiles.front().File->keep(OutputFileName)) {
84       WithColor::error() << "while keeping " << ArchFiles.front().path()
85                          << " as " << OutputFileName << ": "
86                          << toString(std::move(E)) << "\n";
87       return false;
88     }
89     return true;
90   }
91 
92   SmallVector<StringRef, 8> Args;
93   Args.push_back("lipo");
94   Args.push_back("-create");
95 
96   for (auto &Thin : ArchFiles)
97     Args.push_back(Thin.path());
98 
99   // Align segments to match dsymutil-classic alignment
100   for (auto &Thin : ArchFiles) {
101     Thin.Arch = getArchName(Thin.Arch);
102     Args.push_back("-segalign");
103     Args.push_back(Thin.Arch);
104     Args.push_back("20");
105   }
106 
107   Args.push_back("-output");
108   Args.push_back(OutputFileName.data());
109 
110   if (Options.Verbose) {
111     outs() << "Running lipo\n";
112     for (auto Arg : Args)
113       outs() << ' ' << Arg;
114     outs() << "\n";
115   }
116 
117   return Options.NoOutput ? true : runLipo(SDKPath, Args);
118 }
119 
120 // Return a MachO::segment_command_64 that holds the same values as the passed
121 // MachO::segment_command. We do that to avoid having to duplicate the logic
122 // for 32bits and 64bits segments.
adaptFrom32bits(MachO::segment_command Seg)123 struct MachO::segment_command_64 adaptFrom32bits(MachO::segment_command Seg) {
124   MachO::segment_command_64 Seg64;
125   Seg64.cmd = Seg.cmd;
126   Seg64.cmdsize = Seg.cmdsize;
127   memcpy(Seg64.segname, Seg.segname, sizeof(Seg.segname));
128   Seg64.vmaddr = Seg.vmaddr;
129   Seg64.vmsize = Seg.vmsize;
130   Seg64.fileoff = Seg.fileoff;
131   Seg64.filesize = Seg.filesize;
132   Seg64.maxprot = Seg.maxprot;
133   Seg64.initprot = Seg.initprot;
134   Seg64.nsects = Seg.nsects;
135   Seg64.flags = Seg.flags;
136   return Seg64;
137 }
138 
139 // Iterate on all \a Obj segments, and apply \a Handler to them.
140 template <typename FunctionTy>
iterateOnSegments(const object::MachOObjectFile & Obj,FunctionTy Handler)141 static void iterateOnSegments(const object::MachOObjectFile &Obj,
142                               FunctionTy Handler) {
143   for (const auto &LCI : Obj.load_commands()) {
144     MachO::segment_command_64 Segment;
145     if (LCI.C.cmd == MachO::LC_SEGMENT)
146       Segment = adaptFrom32bits(Obj.getSegmentLoadCommand(LCI));
147     else if (LCI.C.cmd == MachO::LC_SEGMENT_64)
148       Segment = Obj.getSegment64LoadCommand(LCI);
149     else
150       continue;
151 
152     Handler(Segment);
153   }
154 }
155 
156 // Transfer the symbols described by \a NList to \a NewSymtab which is just the
157 // raw contents of the symbol table for the dSYM companion file. \returns
158 // whether the symbol was transferred or not.
159 template <typename NListTy>
transferSymbol(NListTy NList,bool IsLittleEndian,StringRef Strings,SmallVectorImpl<char> & NewSymtab,NonRelocatableStringpool & NewStrings,bool & InDebugNote)160 static bool transferSymbol(NListTy NList, bool IsLittleEndian,
161                            StringRef Strings, SmallVectorImpl<char> &NewSymtab,
162                            NonRelocatableStringpool &NewStrings,
163                            bool &InDebugNote) {
164   // Do not transfer undefined symbols, we want real addresses.
165   if ((NList.n_type & MachO::N_TYPE) == MachO::N_UNDF)
166     return false;
167 
168   // Do not transfer N_AST symbols as their content is copied into a section of
169   // the Mach-O companion file.
170   if (NList.n_type == MachO::N_AST)
171     return false;
172 
173   StringRef Name = StringRef(Strings.begin() + NList.n_strx);
174 
175   // An N_SO with a filename opens a debugging scope and another one without a
176   // name closes it. Don't transfer anything in the debugging scope.
177   if (InDebugNote) {
178     InDebugNote =
179         (NList.n_type != MachO::N_SO) || (!Name.empty() && Name[0] != '\0');
180     return false;
181   } else if (NList.n_type == MachO::N_SO) {
182     InDebugNote = true;
183     return false;
184   }
185 
186   // FIXME: The + 1 is here to mimic dsymutil-classic that has 2 empty
187   // strings at the start of the generated string table (There is
188   // corresponding code in the string table emission).
189   NList.n_strx = NewStrings.getStringOffset(Name) + 1;
190   if (IsLittleEndian != sys::IsLittleEndianHost)
191     MachO::swapStruct(NList);
192 
193   NewSymtab.append(reinterpret_cast<char *>(&NList),
194                    reinterpret_cast<char *>(&NList + 1));
195   return true;
196 }
197 
198 // Wrapper around transferSymbol to transfer all of \a Obj symbols
199 // to \a NewSymtab. This function does not write in the output file.
200 // \returns the number of symbols in \a NewSymtab.
transferSymbols(const object::MachOObjectFile & Obj,SmallVectorImpl<char> & NewSymtab,NonRelocatableStringpool & NewStrings)201 static unsigned transferSymbols(const object::MachOObjectFile &Obj,
202                                 SmallVectorImpl<char> &NewSymtab,
203                                 NonRelocatableStringpool &NewStrings) {
204   unsigned Syms = 0;
205   StringRef Strings = Obj.getStringTableData();
206   bool IsLittleEndian = Obj.isLittleEndian();
207   bool InDebugNote = false;
208 
209   if (Obj.is64Bit()) {
210     for (const object::SymbolRef &Symbol : Obj.symbols()) {
211       object::DataRefImpl DRI = Symbol.getRawDataRefImpl();
212       if (transferSymbol(Obj.getSymbol64TableEntry(DRI), IsLittleEndian,
213                          Strings, NewSymtab, NewStrings, InDebugNote))
214         ++Syms;
215     }
216   } else {
217     for (const object::SymbolRef &Symbol : Obj.symbols()) {
218       object::DataRefImpl DRI = Symbol.getRawDataRefImpl();
219       if (transferSymbol(Obj.getSymbolTableEntry(DRI), IsLittleEndian, Strings,
220                          NewSymtab, NewStrings, InDebugNote))
221         ++Syms;
222     }
223   }
224   return Syms;
225 }
226 
227 static MachO::section
getSection(const object::MachOObjectFile & Obj,const MachO::segment_command & Seg,const object::MachOObjectFile::LoadCommandInfo & LCI,unsigned Idx)228 getSection(const object::MachOObjectFile &Obj,
229            const MachO::segment_command &Seg,
230            const object::MachOObjectFile::LoadCommandInfo &LCI, unsigned Idx) {
231   return Obj.getSection(LCI, Idx);
232 }
233 
234 static MachO::section_64
getSection(const object::MachOObjectFile & Obj,const MachO::segment_command_64 & Seg,const object::MachOObjectFile::LoadCommandInfo & LCI,unsigned Idx)235 getSection(const object::MachOObjectFile &Obj,
236            const MachO::segment_command_64 &Seg,
237            const object::MachOObjectFile::LoadCommandInfo &LCI, unsigned Idx) {
238   return Obj.getSection64(LCI, Idx);
239 }
240 
241 // Transfer \a Segment from \a Obj to the output file. This calls into \a Writer
242 // to write these load commands directly in the output file at the current
243 // position.
244 //
245 // The function also tries to find a hole in the address map to fit the __DWARF
246 // segment of \a DwarfSegmentSize size. \a EndAddress is updated to point at the
247 // highest segment address.
248 //
249 // When the __LINKEDIT segment is transferred, its offset and size are set resp.
250 // to \a LinkeditOffset and \a LinkeditSize.
251 //
252 // When the eh_frame section is transferred, its offset and size are set resp.
253 // to \a EHFrameOffset and \a EHFrameSize.
254 template <typename SegmentTy>
transferSegmentAndSections(const object::MachOObjectFile::LoadCommandInfo & LCI,SegmentTy Segment,const object::MachOObjectFile & Obj,MachObjectWriter & Writer,uint64_t LinkeditOffset,uint64_t LinkeditSize,uint64_t EHFrameOffset,uint64_t EHFrameSize,uint64_t DwarfSegmentSize,uint64_t & GapForDwarf,uint64_t & EndAddress)255 static void transferSegmentAndSections(
256     const object::MachOObjectFile::LoadCommandInfo &LCI, SegmentTy Segment,
257     const object::MachOObjectFile &Obj, MachObjectWriter &Writer,
258     uint64_t LinkeditOffset, uint64_t LinkeditSize, uint64_t EHFrameOffset,
259     uint64_t EHFrameSize, uint64_t DwarfSegmentSize, uint64_t &GapForDwarf,
260     uint64_t &EndAddress) {
261   if (StringRef("__DWARF") == Segment.segname)
262     return;
263 
264   if (StringRef("__TEXT") == Segment.segname && EHFrameSize > 0) {
265     Segment.fileoff = EHFrameOffset;
266     Segment.filesize = EHFrameSize;
267   } else if (StringRef("__LINKEDIT") == Segment.segname) {
268     Segment.fileoff = LinkeditOffset;
269     Segment.filesize = LinkeditSize;
270     // Resize vmsize by rounding to the page size.
271     Segment.vmsize = alignTo(LinkeditSize, 0x1000);
272   } else {
273     Segment.fileoff = Segment.filesize = 0;
274   }
275 
276   // Check if the end address of the last segment and our current
277   // start address leave a sufficient gap to store the __DWARF
278   // segment.
279   uint64_t PrevEndAddress = EndAddress;
280   EndAddress = alignTo(EndAddress, 0x1000);
281   if (GapForDwarf == UINT64_MAX && Segment.vmaddr > EndAddress &&
282       Segment.vmaddr - EndAddress >= DwarfSegmentSize)
283     GapForDwarf = EndAddress;
284 
285   // The segments are not necessarily sorted by their vmaddr.
286   EndAddress =
287       std::max<uint64_t>(PrevEndAddress, Segment.vmaddr + Segment.vmsize);
288   unsigned nsects = Segment.nsects;
289   if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
290     MachO::swapStruct(Segment);
291   Writer.W.OS.write(reinterpret_cast<char *>(&Segment), sizeof(Segment));
292   for (unsigned i = 0; i < nsects; ++i) {
293     auto Sect = getSection(Obj, Segment, LCI, i);
294     if (StringRef("__eh_frame") == Sect.sectname) {
295       Sect.offset = EHFrameOffset;
296       Sect.reloff = Sect.nreloc = 0;
297     } else {
298       Sect.offset = Sect.reloff = Sect.nreloc = 0;
299     }
300     if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
301       MachO::swapStruct(Sect);
302     Writer.W.OS.write(reinterpret_cast<char *>(&Sect), sizeof(Sect));
303   }
304 }
305 
306 // Write the __DWARF segment load command to the output file.
createDwarfSegment(uint64_t VMAddr,uint64_t FileOffset,uint64_t FileSize,unsigned NumSections,MCAsmLayout & Layout,MachObjectWriter & Writer)307 static bool createDwarfSegment(uint64_t VMAddr, uint64_t FileOffset,
308                                uint64_t FileSize, unsigned NumSections,
309                                MCAsmLayout &Layout, MachObjectWriter &Writer) {
310   Writer.writeSegmentLoadCommand("__DWARF", NumSections, VMAddr,
311                                  alignTo(FileSize, 0x1000), FileOffset,
312                                  FileSize, /* MaxProt */ 7,
313                                  /* InitProt =*/3);
314 
315   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
316     MCSection *Sec = Layout.getSectionOrder()[i];
317     if (Sec->begin() == Sec->end() || !Layout.getSectionFileSize(Sec))
318       continue;
319 
320     unsigned Align = Sec->getAlignment();
321     if (Align > 1) {
322       VMAddr = alignTo(VMAddr, Align);
323       FileOffset = alignTo(FileOffset, Align);
324       if (FileOffset > UINT32_MAX)
325         return error("section " + Sec->getName() + "'s file offset exceeds 4GB."
326             " Refusing to produce an invalid Mach-O file.");
327     }
328     Writer.writeSection(Layout, *Sec, VMAddr, FileOffset, 0, 0, 0);
329 
330     FileOffset += Layout.getSectionAddressSize(Sec);
331     VMAddr += Layout.getSectionAddressSize(Sec);
332   }
333   return true;
334 }
335 
isExecutable(const object::MachOObjectFile & Obj)336 static bool isExecutable(const object::MachOObjectFile &Obj) {
337   if (Obj.is64Bit())
338     return Obj.getHeader64().filetype != MachO::MH_OBJECT;
339   else
340     return Obj.getHeader().filetype != MachO::MH_OBJECT;
341 }
342 
segmentLoadCommandSize(bool Is64Bit,unsigned NumSections)343 static unsigned segmentLoadCommandSize(bool Is64Bit, unsigned NumSections) {
344   if (Is64Bit)
345     return sizeof(MachO::segment_command_64) +
346            NumSections * sizeof(MachO::section_64);
347 
348   return sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
349 }
350 
351 // Stream a dSYM companion binary file corresponding to the binary referenced
352 // by \a DM to \a OutFile. The passed \a MS MCStreamer is setup to write to
353 // \a OutFile and it must be using a MachObjectWriter object to do so.
generateDsymCompanion(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,const DebugMap & DM,SymbolMapTranslator & Translator,MCStreamer & MS,raw_fd_ostream & OutFile,const std::vector<MachOUtils::DwarfRelocationApplicationInfo> & RelocationsToApply)354 bool generateDsymCompanion(
355     llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, const DebugMap &DM,
356     SymbolMapTranslator &Translator, MCStreamer &MS, raw_fd_ostream &OutFile,
357     const std::vector<MachOUtils::DwarfRelocationApplicationInfo>
358         &RelocationsToApply) {
359   auto &ObjectStreamer = static_cast<MCObjectStreamer &>(MS);
360   MCAssembler &MCAsm = ObjectStreamer.getAssembler();
361   auto &Writer = static_cast<MachObjectWriter &>(MCAsm.getWriter());
362 
363   // Layout but don't emit.
364   ObjectStreamer.flushPendingLabels();
365   MCAsmLayout Layout(MCAsm);
366   MCAsm.layout(Layout);
367 
368   BinaryHolder InputBinaryHolder(VFS, false);
369 
370   auto ObjectEntry = InputBinaryHolder.getObjectEntry(DM.getBinaryPath());
371   if (!ObjectEntry) {
372     auto Err = ObjectEntry.takeError();
373     return error(Twine("opening ") + DM.getBinaryPath() + ": " +
374                      toString(std::move(Err)),
375                  "output file streaming");
376   }
377 
378   auto Object =
379       ObjectEntry->getObjectAs<object::MachOObjectFile>(DM.getTriple());
380   if (!Object) {
381     auto Err = Object.takeError();
382     return error(Twine("opening ") + DM.getBinaryPath() + ": " +
383                      toString(std::move(Err)),
384                  "output file streaming");
385   }
386 
387   auto &InputBinary = *Object;
388 
389   bool Is64Bit = Writer.is64Bit();
390   MachO::symtab_command SymtabCmd = InputBinary.getSymtabLoadCommand();
391 
392   // Compute the number of load commands we will need.
393   unsigned LoadCommandSize = 0;
394   unsigned NumLoadCommands = 0;
395 
396   bool HasSymtab = false;
397 
398   // Check LC_SYMTAB and get LC_UUID and LC_BUILD_VERSION.
399   MachO::uuid_command UUIDCmd;
400   SmallVector<MachO::build_version_command, 2> BuildVersionCmd;
401   memset(&UUIDCmd, 0, sizeof(UUIDCmd));
402   for (auto &LCI : InputBinary.load_commands()) {
403     switch (LCI.C.cmd) {
404     case MachO::LC_UUID:
405       if (UUIDCmd.cmd)
406         return error("Binary contains more than one UUID");
407       UUIDCmd = InputBinary.getUuidCommand(LCI);
408       ++NumLoadCommands;
409       LoadCommandSize += sizeof(UUIDCmd);
410       break;
411    case MachO::LC_BUILD_VERSION: {
412       MachO::build_version_command Cmd;
413       memset(&Cmd, 0, sizeof(Cmd));
414       Cmd = InputBinary.getBuildVersionLoadCommand(LCI);
415       ++NumLoadCommands;
416       LoadCommandSize += sizeof(Cmd);
417       // LLDB doesn't care about the build tools for now.
418       Cmd.ntools = 0;
419       BuildVersionCmd.push_back(Cmd);
420       break;
421     }
422     case MachO::LC_SYMTAB:
423       HasSymtab = true;
424       break;
425     default:
426       break;
427     }
428   }
429 
430   // If we have a valid symtab to copy, do it.
431   bool ShouldEmitSymtab = HasSymtab && isExecutable(InputBinary);
432   if (ShouldEmitSymtab) {
433     LoadCommandSize += sizeof(MachO::symtab_command);
434     ++NumLoadCommands;
435   }
436 
437   // If we have a valid eh_frame to copy, do it.
438   uint64_t EHFrameSize = 0;
439   StringRef EHFrameData;
440   for (const object::SectionRef &Section : InputBinary.sections()) {
441     Expected<StringRef> NameOrErr = Section.getName();
442     if (!NameOrErr) {
443       consumeError(NameOrErr.takeError());
444       continue;
445     }
446     StringRef SectionName = *NameOrErr;
447     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
448     if (SectionName == "eh_frame") {
449       if (Expected<StringRef> ContentsOrErr = Section.getContents()) {
450         EHFrameData = *ContentsOrErr;
451         EHFrameSize = Section.getSize();
452       } else {
453         consumeError(ContentsOrErr.takeError());
454       }
455     }
456   }
457 
458   unsigned HeaderSize =
459       Is64Bit ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header);
460   // We will copy every segment that isn't __DWARF.
461   iterateOnSegments(InputBinary, [&](const MachO::segment_command_64 &Segment) {
462     if (StringRef("__DWARF") == Segment.segname)
463       return;
464 
465     ++NumLoadCommands;
466     LoadCommandSize += segmentLoadCommandSize(Is64Bit, Segment.nsects);
467   });
468 
469   // We will add our own brand new __DWARF segment if we have debug
470   // info.
471   unsigned NumDwarfSections = 0;
472   uint64_t DwarfSegmentSize = 0;
473 
474   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
475     MCSection *Sec = Layout.getSectionOrder()[i];
476     if (Sec->begin() == Sec->end())
477       continue;
478 
479     if (uint64_t Size = Layout.getSectionFileSize(Sec)) {
480       DwarfSegmentSize = alignTo(DwarfSegmentSize, Sec->getAlignment());
481       DwarfSegmentSize += Size;
482       ++NumDwarfSections;
483     }
484   }
485 
486   if (NumDwarfSections) {
487     ++NumLoadCommands;
488     LoadCommandSize += segmentLoadCommandSize(Is64Bit, NumDwarfSections);
489   }
490 
491   SmallString<0> NewSymtab;
492   std::function<StringRef(StringRef)> TranslationLambda =
493       Translator ? [&](StringRef Input) { return Translator(Input); }
494                  : static_cast<std::function<StringRef(StringRef)>>(nullptr);
495   // Legacy dsymutil puts an empty string at the start of the line table.
496   // thus we set NonRelocatableStringpool(,PutEmptyString=true)
497   NonRelocatableStringpool NewStrings(TranslationLambda, true);
498   unsigned NListSize = Is64Bit ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
499   unsigned NumSyms = 0;
500   uint64_t NewStringsSize = 0;
501   if (ShouldEmitSymtab) {
502     NewSymtab.reserve(SymtabCmd.nsyms * NListSize / 2);
503     NumSyms = transferSymbols(InputBinary, NewSymtab, NewStrings);
504     NewStringsSize = NewStrings.getSize() + 1;
505   }
506 
507   uint64_t SymtabStart = LoadCommandSize;
508   SymtabStart += HeaderSize;
509   SymtabStart = alignTo(SymtabStart, 0x1000);
510 
511   // We gathered all the information we need, start emitting the output file.
512   Writer.writeHeader(MachO::MH_DSYM, NumLoadCommands, LoadCommandSize, false);
513 
514   // Write the load commands.
515   assert(OutFile.tell() == HeaderSize);
516   if (UUIDCmd.cmd != 0) {
517     Writer.W.write<uint32_t>(UUIDCmd.cmd);
518     Writer.W.write<uint32_t>(sizeof(UUIDCmd));
519     OutFile.write(reinterpret_cast<const char *>(UUIDCmd.uuid), 16);
520     assert(OutFile.tell() == HeaderSize + sizeof(UUIDCmd));
521   }
522   for (auto Cmd : BuildVersionCmd) {
523     Writer.W.write<uint32_t>(Cmd.cmd);
524     Writer.W.write<uint32_t>(sizeof(Cmd));
525     Writer.W.write<uint32_t>(Cmd.platform);
526     Writer.W.write<uint32_t>(Cmd.minos);
527     Writer.W.write<uint32_t>(Cmd.sdk);
528     Writer.W.write<uint32_t>(Cmd.ntools);
529   }
530 
531   assert(SymtabCmd.cmd && "No symbol table.");
532   uint64_t StringStart = SymtabStart + NumSyms * NListSize;
533   if (ShouldEmitSymtab)
534     Writer.writeSymtabLoadCommand(SymtabStart, NumSyms, StringStart,
535                                   NewStringsSize);
536 
537   uint64_t EHFrameStart = StringStart + NewStringsSize;
538   EHFrameStart = alignTo(EHFrameStart, 0x1000);
539 
540   uint64_t DwarfSegmentStart = EHFrameStart + EHFrameSize;
541   DwarfSegmentStart = alignTo(DwarfSegmentStart, 0x1000);
542 
543   // Write the load commands for the segments and sections we 'import' from
544   // the original binary.
545   uint64_t EndAddress = 0;
546   uint64_t GapForDwarf = UINT64_MAX;
547   for (auto &LCI : InputBinary.load_commands()) {
548     if (LCI.C.cmd == MachO::LC_SEGMENT)
549       transferSegmentAndSections(
550           LCI, InputBinary.getSegmentLoadCommand(LCI), InputBinary, Writer,
551           SymtabStart, StringStart + NewStringsSize - SymtabStart, EHFrameStart,
552           EHFrameSize, DwarfSegmentSize, GapForDwarf, EndAddress);
553     else if (LCI.C.cmd == MachO::LC_SEGMENT_64)
554       transferSegmentAndSections(
555           LCI, InputBinary.getSegment64LoadCommand(LCI), InputBinary, Writer,
556           SymtabStart, StringStart + NewStringsSize - SymtabStart, EHFrameStart,
557           EHFrameSize, DwarfSegmentSize, GapForDwarf, EndAddress);
558   }
559 
560   uint64_t DwarfVMAddr = alignTo(EndAddress, 0x1000);
561   uint64_t DwarfVMMax = Is64Bit ? UINT64_MAX : UINT32_MAX;
562   if (DwarfVMAddr + DwarfSegmentSize > DwarfVMMax ||
563       DwarfVMAddr + DwarfSegmentSize < DwarfVMAddr /* Overflow */) {
564     // There is no room for the __DWARF segment at the end of the
565     // address space. Look through segments to find a gap.
566     DwarfVMAddr = GapForDwarf;
567     if (DwarfVMAddr == UINT64_MAX)
568       warn("not enough VM space for the __DWARF segment.",
569            "output file streaming");
570   }
571 
572   // Write the load command for the __DWARF segment.
573   if (!createDwarfSegment(DwarfVMAddr, DwarfSegmentStart, DwarfSegmentSize,
574                           NumDwarfSections, Layout, Writer))
575     return false;
576 
577   assert(OutFile.tell() == LoadCommandSize + HeaderSize);
578   OutFile.write_zeros(SymtabStart - (LoadCommandSize + HeaderSize));
579   assert(OutFile.tell() == SymtabStart);
580 
581   // Transfer symbols.
582   if (ShouldEmitSymtab) {
583     OutFile << NewSymtab.str();
584     assert(OutFile.tell() == StringStart);
585 
586     // Transfer string table.
587     // FIXME: The NonRelocatableStringpool starts with an empty string, but
588     // dsymutil-classic starts the reconstructed string table with 2 of these.
589     // Reproduce that behavior for now (there is corresponding code in
590     // transferSymbol).
591     OutFile << '\0';
592     std::vector<DwarfStringPoolEntryRef> Strings =
593         NewStrings.getEntriesForEmission();
594     for (auto EntryRef : Strings) {
595       OutFile.write(EntryRef.getString().data(),
596                     EntryRef.getString().size() + 1);
597     }
598   }
599   assert(OutFile.tell() == StringStart + NewStringsSize);
600 
601   // Pad till the EH frame start.
602   OutFile.write_zeros(EHFrameStart - (StringStart + NewStringsSize));
603   assert(OutFile.tell() == EHFrameStart);
604 
605   // Transfer eh_frame.
606   if (EHFrameSize > 0)
607     OutFile << EHFrameData;
608   assert(OutFile.tell() == EHFrameStart + EHFrameSize);
609 
610   // Pad till the Dwarf segment start.
611   OutFile.write_zeros(DwarfSegmentStart - (EHFrameStart + EHFrameSize));
612   assert(OutFile.tell() == DwarfSegmentStart);
613 
614   // Emit the Dwarf sections contents.
615   for (const MCSection &Sec : MCAsm) {
616     if (Sec.begin() == Sec.end())
617       continue;
618 
619     uint64_t Pos = OutFile.tell();
620     OutFile.write_zeros(alignTo(Pos, Sec.getAlignment()) - Pos);
621     MCAsm.writeSectionData(OutFile, &Sec, Layout);
622   }
623 
624   // Apply relocations to the contents of the DWARF segment.
625   // We do this here because the final value written depend on the DWARF vm
626   // addr, which is only calculated in this function.
627   if (!RelocationsToApply.empty()) {
628     if (!OutFile.supportsSeeking())
629       report_fatal_error(
630           "Cannot apply relocations to file that doesn't support seeking!");
631 
632     uint64_t Pos = OutFile.tell();
633     for (auto &RelocationToApply : RelocationsToApply) {
634       OutFile.seek(DwarfSegmentStart + RelocationToApply.AddressFromDwarfStart);
635       int32_t Value = RelocationToApply.Value;
636       if (RelocationToApply.ShouldSubtractDwarfVM)
637         Value -= DwarfVMAddr;
638       OutFile.write((char *)&Value, sizeof(int32_t));
639     }
640     OutFile.seek(Pos);
641   }
642 
643   return true;
644 }
645 } // namespace MachOUtils
646 } // namespace dsymutil
647 } // namespace llvm
648