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