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