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 
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 
44 llvm::StringRef ArchAndFile::path() const { return File->TmpName; }
45 
46 ArchAndFile::~ArchAndFile() {
47   if (File)
48     if (auto E = File->discard())
49       llvm::consumeError(std::move(E));
50 }
51 
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 
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 
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.
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>
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>
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.
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
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
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>
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.
307 static void 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     }
325     Writer.writeSection(Layout, *Sec, VMAddr, FileOffset, 0, 0, 0);
326 
327     FileOffset += Layout.getSectionAddressSize(Sec);
328     VMAddr += Layout.getSectionAddressSize(Sec);
329   }
330 }
331 
332 static bool isExecutable(const object::MachOObjectFile &Obj) {
333   if (Obj.is64Bit())
334     return Obj.getHeader64().filetype != MachO::MH_OBJECT;
335   else
336     return Obj.getHeader().filetype != MachO::MH_OBJECT;
337 }
338 
339 static unsigned segmentLoadCommandSize(bool Is64Bit, unsigned NumSections) {
340   if (Is64Bit)
341     return sizeof(MachO::segment_command_64) +
342            NumSections * sizeof(MachO::section_64);
343 
344   return sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
345 }
346 
347 // Stream a dSYM companion binary file corresponding to the binary referenced
348 // by \a DM to \a OutFile. The passed \a MS MCStreamer is setup to write to
349 // \a OutFile and it must be using a MachObjectWriter object to do so.
350 bool generateDsymCompanion(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
351                            const DebugMap &DM, SymbolMapTranslator &Translator,
352                            MCStreamer &MS, raw_fd_ostream &OutFile) {
353   auto &ObjectStreamer = static_cast<MCObjectStreamer &>(MS);
354   MCAssembler &MCAsm = ObjectStreamer.getAssembler();
355   auto &Writer = static_cast<MachObjectWriter &>(MCAsm.getWriter());
356 
357   // Layout but don't emit.
358   ObjectStreamer.flushPendingLabels();
359   MCAsmLayout Layout(MCAsm);
360   MCAsm.layout(Layout);
361 
362   BinaryHolder InputBinaryHolder(VFS, false);
363 
364   auto ObjectEntry = InputBinaryHolder.getObjectEntry(DM.getBinaryPath());
365   if (!ObjectEntry) {
366     auto Err = ObjectEntry.takeError();
367     return error(Twine("opening ") + DM.getBinaryPath() + ": " +
368                      toString(std::move(Err)),
369                  "output file streaming");
370   }
371 
372   auto Object =
373       ObjectEntry->getObjectAs<object::MachOObjectFile>(DM.getTriple());
374   if (!Object) {
375     auto Err = Object.takeError();
376     return error(Twine("opening ") + DM.getBinaryPath() + ": " +
377                      toString(std::move(Err)),
378                  "output file streaming");
379   }
380 
381   auto &InputBinary = *Object;
382 
383   bool Is64Bit = Writer.is64Bit();
384   MachO::symtab_command SymtabCmd = InputBinary.getSymtabLoadCommand();
385 
386   // Compute the number of load commands we will need.
387   unsigned LoadCommandSize = 0;
388   unsigned NumLoadCommands = 0;
389 
390   bool HasSymtab = false;
391 
392   // Check LC_SYMTAB and get LC_UUID and LC_BUILD_VERSION.
393   MachO::uuid_command UUIDCmd;
394   SmallVector<MachO::build_version_command, 2> BuildVersionCmd;
395   memset(&UUIDCmd, 0, sizeof(UUIDCmd));
396   for (auto &LCI : InputBinary.load_commands()) {
397     switch (LCI.C.cmd) {
398     case MachO::LC_UUID:
399       if (UUIDCmd.cmd)
400         return error("Binary contains more than one UUID");
401       UUIDCmd = InputBinary.getUuidCommand(LCI);
402       ++NumLoadCommands;
403       LoadCommandSize += sizeof(UUIDCmd);
404       break;
405    case MachO::LC_BUILD_VERSION: {
406       MachO::build_version_command Cmd;
407       memset(&Cmd, 0, sizeof(Cmd));
408       Cmd = InputBinary.getBuildVersionLoadCommand(LCI);
409       ++NumLoadCommands;
410       LoadCommandSize += sizeof(Cmd);
411       // LLDB doesn't care about the build tools for now.
412       Cmd.ntools = 0;
413       BuildVersionCmd.push_back(Cmd);
414       break;
415     }
416     case MachO::LC_SYMTAB:
417       HasSymtab = true;
418       break;
419     default:
420       break;
421     }
422   }
423 
424   // If we have a valid symtab to copy, do it.
425   bool ShouldEmitSymtab = HasSymtab && isExecutable(InputBinary);
426   if (ShouldEmitSymtab) {
427     LoadCommandSize += sizeof(MachO::symtab_command);
428     ++NumLoadCommands;
429   }
430 
431   // If we have a valid eh_frame to copy, do it.
432   uint64_t EHFrameSize = 0;
433   StringRef EHFrameData;
434   for (const object::SectionRef &Section : InputBinary.sections()) {
435     Expected<StringRef> NameOrErr = Section.getName();
436     if (!NameOrErr) {
437       consumeError(NameOrErr.takeError());
438       continue;
439     }
440     StringRef SectionName = *NameOrErr;
441     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
442     if (SectionName == "eh_frame") {
443       if (Expected<StringRef> ContentsOrErr = Section.getContents()) {
444         EHFrameData = *ContentsOrErr;
445         EHFrameSize = Section.getSize();
446       } else {
447         consumeError(ContentsOrErr.takeError());
448       }
449     }
450   }
451 
452   unsigned HeaderSize =
453       Is64Bit ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header);
454   // We will copy every segment that isn't __DWARF.
455   iterateOnSegments(InputBinary, [&](const MachO::segment_command_64 &Segment) {
456     if (StringRef("__DWARF") == Segment.segname)
457       return;
458 
459     ++NumLoadCommands;
460     LoadCommandSize += segmentLoadCommandSize(Is64Bit, Segment.nsects);
461   });
462 
463   // We will add our own brand new __DWARF segment if we have debug
464   // info.
465   unsigned NumDwarfSections = 0;
466   uint64_t DwarfSegmentSize = 0;
467 
468   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
469     MCSection *Sec = Layout.getSectionOrder()[i];
470     if (Sec->begin() == Sec->end())
471       continue;
472 
473     if (uint64_t Size = Layout.getSectionFileSize(Sec)) {
474       DwarfSegmentSize = alignTo(DwarfSegmentSize, Sec->getAlignment());
475       DwarfSegmentSize += Size;
476       ++NumDwarfSections;
477     }
478   }
479 
480   if (NumDwarfSections) {
481     ++NumLoadCommands;
482     LoadCommandSize += segmentLoadCommandSize(Is64Bit, NumDwarfSections);
483   }
484 
485   SmallString<0> NewSymtab;
486   std::function<StringRef(StringRef)> TranslationLambda =
487       Translator ? [&](StringRef Input) { return Translator(Input); }
488                  : static_cast<std::function<StringRef(StringRef)>>(nullptr);
489   // Legacy dsymutil puts an empty string at the start of the line table.
490   // thus we set NonRelocatableStringpool(,PutEmptyString=true)
491   NonRelocatableStringpool NewStrings(TranslationLambda, true);
492   unsigned NListSize = Is64Bit ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
493   unsigned NumSyms = 0;
494   uint64_t NewStringsSize = 0;
495   if (ShouldEmitSymtab) {
496     NewSymtab.reserve(SymtabCmd.nsyms * NListSize / 2);
497     NumSyms = transferSymbols(InputBinary, NewSymtab, NewStrings);
498     NewStringsSize = NewStrings.getSize() + 1;
499   }
500 
501   uint64_t SymtabStart = LoadCommandSize;
502   SymtabStart += HeaderSize;
503   SymtabStart = alignTo(SymtabStart, 0x1000);
504 
505   // We gathered all the information we need, start emitting the output file.
506   Writer.writeHeader(MachO::MH_DSYM, NumLoadCommands, LoadCommandSize, false);
507 
508   // Write the load commands.
509   assert(OutFile.tell() == HeaderSize);
510   if (UUIDCmd.cmd != 0) {
511     Writer.W.write<uint32_t>(UUIDCmd.cmd);
512     Writer.W.write<uint32_t>(sizeof(UUIDCmd));
513     OutFile.write(reinterpret_cast<const char *>(UUIDCmd.uuid), 16);
514     assert(OutFile.tell() == HeaderSize + sizeof(UUIDCmd));
515   }
516   for (auto Cmd : BuildVersionCmd) {
517     Writer.W.write<uint32_t>(Cmd.cmd);
518     Writer.W.write<uint32_t>(sizeof(Cmd));
519     Writer.W.write<uint32_t>(Cmd.platform);
520     Writer.W.write<uint32_t>(Cmd.minos);
521     Writer.W.write<uint32_t>(Cmd.sdk);
522     Writer.W.write<uint32_t>(Cmd.ntools);
523   }
524 
525   assert(SymtabCmd.cmd && "No symbol table.");
526   uint64_t StringStart = SymtabStart + NumSyms * NListSize;
527   if (ShouldEmitSymtab)
528     Writer.writeSymtabLoadCommand(SymtabStart, NumSyms, StringStart,
529                                   NewStringsSize);
530 
531   uint64_t EHFrameStart = StringStart + NewStringsSize;
532   EHFrameStart = alignTo(EHFrameStart, 0x1000);
533 
534   uint64_t DwarfSegmentStart = EHFrameStart + EHFrameSize;
535   DwarfSegmentStart = alignTo(DwarfSegmentStart, 0x1000);
536 
537   // Write the load commands for the segments and sections we 'import' from
538   // the original binary.
539   uint64_t EndAddress = 0;
540   uint64_t GapForDwarf = UINT64_MAX;
541   for (auto &LCI : InputBinary.load_commands()) {
542     if (LCI.C.cmd == MachO::LC_SEGMENT)
543       transferSegmentAndSections(
544           LCI, InputBinary.getSegmentLoadCommand(LCI), InputBinary, Writer,
545           SymtabStart, StringStart + NewStringsSize - SymtabStart, EHFrameStart,
546           EHFrameSize, DwarfSegmentSize, GapForDwarf, EndAddress);
547     else if (LCI.C.cmd == MachO::LC_SEGMENT_64)
548       transferSegmentAndSections(
549           LCI, InputBinary.getSegment64LoadCommand(LCI), InputBinary, Writer,
550           SymtabStart, StringStart + NewStringsSize - SymtabStart, EHFrameStart,
551           EHFrameSize, DwarfSegmentSize, GapForDwarf, EndAddress);
552   }
553 
554   uint64_t DwarfVMAddr = alignTo(EndAddress, 0x1000);
555   uint64_t DwarfVMMax = Is64Bit ? UINT64_MAX : UINT32_MAX;
556   if (DwarfVMAddr + DwarfSegmentSize > DwarfVMMax ||
557       DwarfVMAddr + DwarfSegmentSize < DwarfVMAddr /* Overflow */) {
558     // There is no room for the __DWARF segment at the end of the
559     // address space. Look through segments to find a gap.
560     DwarfVMAddr = GapForDwarf;
561     if (DwarfVMAddr == UINT64_MAX)
562       warn("not enough VM space for the __DWARF segment.",
563            "output file streaming");
564   }
565 
566   // Write the load command for the __DWARF segment.
567   createDwarfSegment(DwarfVMAddr, DwarfSegmentStart, DwarfSegmentSize,
568                      NumDwarfSections, Layout, Writer);
569 
570   assert(OutFile.tell() == LoadCommandSize + HeaderSize);
571   OutFile.write_zeros(SymtabStart - (LoadCommandSize + HeaderSize));
572   assert(OutFile.tell() == SymtabStart);
573 
574   // Transfer symbols.
575   if (ShouldEmitSymtab) {
576     OutFile << NewSymtab.str();
577     assert(OutFile.tell() == StringStart);
578 
579     // Transfer string table.
580     // FIXME: The NonRelocatableStringpool starts with an empty string, but
581     // dsymutil-classic starts the reconstructed string table with 2 of these.
582     // Reproduce that behavior for now (there is corresponding code in
583     // transferSymbol).
584     OutFile << '\0';
585     std::vector<DwarfStringPoolEntryRef> Strings =
586         NewStrings.getEntriesForEmission();
587     for (auto EntryRef : Strings) {
588       OutFile.write(EntryRef.getString().data(),
589                     EntryRef.getString().size() + 1);
590     }
591   }
592   assert(OutFile.tell() == StringStart + NewStringsSize);
593 
594   // Pad till the EH frame start.
595   OutFile.write_zeros(EHFrameStart - (StringStart + NewStringsSize));
596   assert(OutFile.tell() == EHFrameStart);
597 
598   // Transfer eh_frame.
599   if (EHFrameSize > 0)
600     OutFile << EHFrameData;
601   assert(OutFile.tell() == EHFrameStart + EHFrameSize);
602 
603   // Pad till the Dwarf segment start.
604   OutFile.write_zeros(DwarfSegmentStart - (EHFrameStart + EHFrameSize));
605   assert(OutFile.tell() == DwarfSegmentStart);
606 
607   // Emit the Dwarf sections contents.
608   for (const MCSection &Sec : MCAsm) {
609     if (Sec.begin() == Sec.end())
610       continue;
611 
612     uint64_t Pos = OutFile.tell();
613     OutFile.write_zeros(alignTo(Pos, Sec.getAlignment()) - Pos);
614     MCAsm.writeSectionData(OutFile, &Sec, Layout);
615   }
616 
617   return true;
618 }
619 } // namespace MachOUtils
620 } // namespace dsymutil
621 } // namespace llvm
622