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