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/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" |
27 | |
28 | namespace llvm { |
29 | namespace dsymutil { |
30 | namespace MachOUtils { |
31 | |
32 | llvm::Error ArchAndFile::createTempFile() { |
33 | SmallString<256> SS; |
34 | std::error_code EC = sys::fs::createTemporaryFile(Prefix: "dsym" , Suffix: "dwarf" , ResultFD&: FD, ResultPath&: SS); |
35 | |
36 | if (EC) |
37 | return errorCodeToError(EC); |
38 | |
39 | Path = SS.str(); |
40 | |
41 | return Error::success(); |
42 | } |
43 | |
44 | llvm::StringRef ArchAndFile::getPath() const { |
45 | assert(!Path.empty() && "path called before createTempFile" ); |
46 | return Path; |
47 | } |
48 | |
49 | int ArchAndFile::getFD() const { |
50 | assert((FD != -1) && "path called before createTempFile" ); |
51 | return FD; |
52 | } |
53 | |
54 | ArchAndFile::~ArchAndFile() { |
55 | if (!Path.empty()) |
56 | sys::fs::remove(path: Path); |
57 | } |
58 | |
59 | std::string getArchName(StringRef Arch) { |
60 | if (Arch.starts_with(Prefix: "thumb" )) |
61 | return (llvm::Twine("arm" ) + Arch.drop_front(N: 5)).str(); |
62 | return std::string(Arch); |
63 | } |
64 | |
65 | static bool runLipo(StringRef SDKPath, SmallVectorImpl<StringRef> &Args) { |
66 | auto Path = sys::findProgramByName(Name: "lipo" , Paths: ArrayRef(SDKPath)); |
67 | if (!Path) |
68 | Path = sys::findProgramByName(Name: "lipo" ); |
69 | |
70 | if (!Path) { |
71 | WithColor::error() << "lipo: " << Path.getError().message() << "\n" ; |
72 | return false; |
73 | } |
74 | |
75 | std::string ErrMsg; |
76 | int result = |
77 | sys::ExecuteAndWait(Program: *Path, Args, Env: std::nullopt, Redirects: {}, SecondsToWait: 0, MemoryLimit: 0, ErrMsg: &ErrMsg); |
78 | if (result) { |
79 | WithColor::error() << "lipo: " << ErrMsg << "\n" ; |
80 | return false; |
81 | } |
82 | |
83 | return true; |
84 | } |
85 | |
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(from: TmpPath, to: OutputFileName)) { |
94 | // If we can't rename, try to copy to work around cross-device link |
95 | // issues. |
96 | EC = sys::fs::copy_file(From: TmpPath, To: OutputFileName); |
97 | if (EC) { |
98 | WithColor::error() << "while keeping " << TmpPath << " as " |
99 | << OutputFileName << ": " << EC.message() << "\n" ; |
100 | return false; |
101 | } |
102 | sys::fs::remove(path: TmpPath); |
103 | } |
104 | return true; |
105 | } |
106 | |
107 | SmallVector<StringRef, 8> Args; |
108 | Args.push_back(Elt: "lipo" ); |
109 | Args.push_back(Elt: "-create" ); |
110 | |
111 | for (auto &Thin : ArchFiles) |
112 | Args.push_back(Elt: Thin.getPath()); |
113 | |
114 | // Align segments to match dsymutil-classic alignment. |
115 | for (auto &Thin : ArchFiles) { |
116 | Thin.Arch = getArchName(Arch: Thin.Arch); |
117 | Args.push_back(Elt: "-segalign" ); |
118 | Args.push_back(Elt: Thin.Arch); |
119 | Args.push_back(Elt: "20" ); |
120 | } |
121 | |
122 | // Use a 64-bit fat header if requested. |
123 | if (Fat64) |
124 | Args.push_back(Elt: "-fat64" ); |
125 | |
126 | Args.push_back(Elt: "-output" ); |
127 | Args.push_back(Elt: OutputFileName.data()); |
128 | |
129 | if (Options.Verbose) { |
130 | outs() << "Running lipo\n" ; |
131 | for (auto Arg : Args) |
132 | outs() << ' ' << Arg; |
133 | outs() << "\n" ; |
134 | } |
135 | |
136 | return Options.NoOutput ? true : runLipo(SDKPath, Args); |
137 | } |
138 | |
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(dest: Seg64.segname, src: Seg.segname, n: 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; |
156 | } |
157 | |
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(Seg: Obj.getSegmentLoadCommand(L: LCI)); |
166 | else if (LCI.C.cmd == MachO::LC_SEGMENT_64) |
167 | Segment = Obj.getSegment64LoadCommand(L: LCI); |
168 | else |
169 | continue; |
170 | |
171 | Handler(Segment); |
172 | } |
173 | } |
174 | |
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; |
186 | |
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; |
191 | |
192 | StringRef Name = StringRef(Strings.begin() + NList.n_strx); |
193 | |
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; |
203 | } |
204 | |
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(S: Name) + 1; |
209 | if (IsLittleEndian != sys::IsLittleEndianHost) |
210 | MachO::swapStruct(NList); |
211 | |
212 | NewSymtab.append(in_start: reinterpret_cast<char *>(&NList), |
213 | in_end: reinterpret_cast<char *>(&NList + 1)); |
214 | return true; |
215 | } |
216 | |
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; |
227 | |
228 | if (Obj.is64Bit()) { |
229 | for (const object::SymbolRef &Symbol : Obj.symbols()) { |
230 | object::DataRefImpl DRI = Symbol.getRawDataRefImpl(); |
231 | if (transferSymbol(NList: Obj.getSymbol64TableEntry(DRI), IsLittleEndian, |
232 | Strings, NewSymtab, NewStrings, InDebugNote)) |
233 | ++Syms; |
234 | } |
235 | } else { |
236 | for (const object::SymbolRef &Symbol : Obj.symbols()) { |
237 | object::DataRefImpl DRI = Symbol.getRawDataRefImpl(); |
238 | if (transferSymbol(NList: Obj.getSymbolTableEntry(DRI), IsLittleEndian, Strings, |
239 | NewSymtab, NewStrings, InDebugNote)) |
240 | ++Syms; |
241 | } |
242 | } |
243 | return Syms; |
244 | } |
245 | |
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(L: LCI, Index: Idx); |
251 | } |
252 | |
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(L: LCI, Index: Idx); |
258 | } |
259 | |
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. |
263 | // |
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. |
267 | // |
268 | // When the __LINKEDIT segment is transferred, its offset and size are set resp. |
269 | // to \a LinkeditOffset and \a LinkeditSize. |
270 | // |
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; |
282 | |
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(Value: LinkeditSize, Align: 0x1000); |
291 | } else { |
292 | Segment.fileoff = Segment.filesize = 0; |
293 | } |
294 | |
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(Value: EndAddress, Align: 0x1000); |
300 | if (GapForDwarf == UINT64_MAX && Segment.vmaddr > EndAddress && |
301 | Segment.vmaddr - EndAddress >= DwarfSegmentSize) |
302 | GapForDwarf = EndAddress; |
303 | |
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(Ptr: reinterpret_cast<char *>(&Segment), Size: 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; |
318 | } |
319 | if (Obj.isLittleEndian() != sys::IsLittleEndianHost) |
320 | MachO::swapStruct(Sect); |
321 | Writer.W.OS.write(Ptr: reinterpret_cast<char *>(&Sect), Size: sizeof(Sect)); |
322 | } |
323 | } |
324 | |
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(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 = Layout.getSectionOrder().size(); i != n; ++i) { |
335 | MCSection *Sec = Layout.getSectionOrder()[i]; |
336 | if (Sec->begin() == Sec->end() || !Layout.getSectionFileSize(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 | if (FileOffset > UINT32_MAX) |
344 | return error(Error: "section " + Sec->getName() + |
345 | "'s file offset exceeds 4GB." |
346 | " Refusing to produce an invalid Mach-O file." ); |
347 | } |
348 | Writer.writeSection(Layout, Sec: *Sec, VMAddr, FileOffset, Flags: 0, RelocationsStart: 0, NumRelocations: 0); |
349 | |
350 | FileOffset += Layout.getSectionAddressSize(Sec); |
351 | VMAddr += Layout.getSectionAddressSize(Sec); |
352 | } |
353 | return true; |
354 | } |
355 | |
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; |
361 | } |
362 | |
363 | static unsigned segmentLoadCommandSize(bool Is64Bit, unsigned NumSections) { |
364 | if (Is64Bit) |
365 | return sizeof(MachO::segment_command_64) + |
366 | NumSections * sizeof(MachO::section_64); |
367 | |
368 | return sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section); |
369 | } |
370 | |
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 | 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()); |
382 | |
383 | // Layout but don't emit. |
384 | ObjectStreamer.flushPendingLabels(); |
385 | MCAsmLayout Layout(MCAsm); |
386 | MCAsm.layout(Layout); |
387 | |
388 | BinaryHolder InputBinaryHolder(VFS, false); |
389 | |
390 | auto ObjectEntry = InputBinaryHolder.getObjectEntry(Filename: DM.getBinaryPath()); |
391 | if (!ObjectEntry) { |
392 | auto Err = ObjectEntry.takeError(); |
393 | return error(Error: Twine("opening " ) + DM.getBinaryPath() + ": " + |
394 | toString(E: std::move(Err)), |
395 | Context: "output file streaming" ); |
396 | } |
397 | |
398 | auto Object = |
399 | ObjectEntry->getObjectAs<object::MachOObjectFile>(T: DM.getTriple()); |
400 | if (!Object) { |
401 | auto Err = Object.takeError(); |
402 | return error(Error: Twine("opening " ) + DM.getBinaryPath() + ": " + |
403 | toString(E: std::move(Err)), |
404 | Context: "output file streaming" ); |
405 | } |
406 | |
407 | auto &InputBinary = *Object; |
408 | |
409 | bool Is64Bit = Writer.is64Bit(); |
410 | MachO::symtab_command SymtabCmd = InputBinary.getSymtabLoadCommand(); |
411 | |
412 | // Compute the number of load commands we will need. |
413 | unsigned LoadCommandSize = 0; |
414 | unsigned NumLoadCommands = 0; |
415 | |
416 | bool HasSymtab = false; |
417 | |
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(s: &UUIDCmd, c: 0, n: 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(Error: "Binary contains more than one UUID" ); |
427 | UUIDCmd = InputBinary.getUuidCommand(L: LCI); |
428 | ++NumLoadCommands; |
429 | LoadCommandSize += sizeof(UUIDCmd); |
430 | break; |
431 | case MachO::LC_BUILD_VERSION: { |
432 | MachO::build_version_command Cmd; |
433 | memset(s: &Cmd, c: 0, n: sizeof(Cmd)); |
434 | Cmd = InputBinary.getBuildVersionLoadCommand(L: 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(Elt: Cmd); |
440 | break; |
441 | } |
442 | case MachO::LC_SYMTAB: |
443 | HasSymtab = true; |
444 | break; |
445 | default: |
446 | break; |
447 | } |
448 | } |
449 | |
450 | // If we have a valid symtab to copy, do it. |
451 | bool ShouldEmitSymtab = HasSymtab && isExecutable(Obj: InputBinary); |
452 | if (ShouldEmitSymtab) { |
453 | LoadCommandSize += sizeof(MachO::symtab_command); |
454 | ++NumLoadCommands; |
455 | } |
456 | |
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(Err: NameOrErr.takeError()); |
464 | continue; |
465 | } |
466 | StringRef SectionName = *NameOrErr; |
467 | SectionName = SectionName.substr(Start: SectionName.find_first_not_of(Chars: "._" )); |
468 | if (SectionName == "eh_frame" ) { |
469 | if (Expected<StringRef> ContentsOrErr = Section.getContents()) { |
470 | EHFrameData = *ContentsOrErr; |
471 | EHFrameSize = Section.getSize(); |
472 | } else { |
473 | consumeError(Err: ContentsOrErr.takeError()); |
474 | } |
475 | } |
476 | } |
477 | |
478 | unsigned = |
479 | Is64Bit ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header); |
480 | // We will copy every segment that isn't __DWARF. |
481 | iterateOnSegments(Obj: InputBinary, Handler: [&](const MachO::segment_command_64 &Segment) { |
482 | if (StringRef("__DWARF" ) == Segment.segname) |
483 | return; |
484 | |
485 | ++NumLoadCommands; |
486 | LoadCommandSize += segmentLoadCommandSize(Is64Bit, NumSections: Segment.nsects); |
487 | }); |
488 | |
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; |
493 | |
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; |
498 | |
499 | if (uint64_t Size = Layout.getSectionFileSize(Sec)) { |
500 | DwarfSegmentSize = alignTo(Size: DwarfSegmentSize, A: Sec->getAlign()); |
501 | DwarfSegmentSize += Size; |
502 | ++NumDwarfSections; |
503 | } |
504 | } |
505 | |
506 | if (NumDwarfSections) { |
507 | ++NumLoadCommands; |
508 | LoadCommandSize += segmentLoadCommandSize(Is64Bit, NumSections: NumDwarfSections); |
509 | } |
510 | |
511 | SmallString<0> NewSymtab; |
512 | // Legacy dsymutil puts an empty string at the start of the line table. |
513 | // thus we set NonRelocatableStringpool(,PutEmptyString=true) |
514 | NonRelocatableStringpool NewStrings(true); |
515 | unsigned NListSize = Is64Bit ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist); |
516 | unsigned NumSyms = 0; |
517 | uint64_t NewStringsSize = 0; |
518 | if (ShouldEmitSymtab) { |
519 | NewSymtab.reserve(N: SymtabCmd.nsyms * NListSize / 2); |
520 | NumSyms = transferSymbols(Obj: InputBinary, NewSymtab, NewStrings); |
521 | NewStringsSize = NewStrings.getSize() + 1; |
522 | } |
523 | |
524 | uint64_t SymtabStart = LoadCommandSize; |
525 | SymtabStart += HeaderSize; |
526 | SymtabStart = alignTo(Value: SymtabStart, Align: 0x1000); |
527 | |
528 | // We gathered all the information we need, start emitting the output file. |
529 | Writer.writeHeader(Type: MachO::MH_DSYM, NumLoadCommands, LoadCommandsSize: LoadCommandSize, SubsectionsViaSymbols: false); |
530 | |
531 | // Write the load commands. |
532 | assert(OutFile.tell() == HeaderSize); |
533 | if (UUIDCmd.cmd != 0) { |
534 | Writer.W.write<uint32_t>(Val: UUIDCmd.cmd); |
535 | Writer.W.write<uint32_t>(Val: sizeof(UUIDCmd)); |
536 | OutFile.write(Ptr: reinterpret_cast<const char *>(UUIDCmd.uuid), Size: 16); |
537 | assert(OutFile.tell() == HeaderSize + sizeof(UUIDCmd)); |
538 | } |
539 | for (auto Cmd : BuildVersionCmd) { |
540 | Writer.W.write<uint32_t>(Val: Cmd.cmd); |
541 | Writer.W.write<uint32_t>(Val: sizeof(Cmd)); |
542 | Writer.W.write<uint32_t>(Val: Cmd.platform); |
543 | Writer.W.write<uint32_t>(Val: Cmd.minos); |
544 | Writer.W.write<uint32_t>(Val: Cmd.sdk); |
545 | Writer.W.write<uint32_t>(Val: Cmd.ntools); |
546 | } |
547 | |
548 | assert(SymtabCmd.cmd && "No symbol table." ); |
549 | uint64_t StringStart = SymtabStart + NumSyms * NListSize; |
550 | if (ShouldEmitSymtab) |
551 | Writer.writeSymtabLoadCommand(SymbolOffset: SymtabStart, NumSymbols: NumSyms, StringTableOffset: StringStart, |
552 | StringTableSize: NewStringsSize); |
553 | |
554 | uint64_t EHFrameStart = StringStart + NewStringsSize; |
555 | EHFrameStart = alignTo(Value: EHFrameStart, Align: 0x1000); |
556 | |
557 | uint64_t DwarfSegmentStart = EHFrameStart + EHFrameSize; |
558 | DwarfSegmentStart = alignTo(Value: DwarfSegmentStart, Align: 0x1000); |
559 | |
560 | // Write the load commands for the segments and sections we 'import' from |
561 | // the original binary. |
562 | uint64_t EndAddress = 0; |
563 | uint64_t GapForDwarf = UINT64_MAX; |
564 | for (auto &LCI : InputBinary.load_commands()) { |
565 | if (LCI.C.cmd == MachO::LC_SEGMENT) |
566 | transferSegmentAndSections( |
567 | LCI, Segment: InputBinary.getSegmentLoadCommand(L: LCI), Obj: InputBinary, Writer, |
568 | LinkeditOffset: SymtabStart, LinkeditSize: StringStart + NewStringsSize - SymtabStart, EHFrameOffset: EHFrameStart, |
569 | EHFrameSize, DwarfSegmentSize, GapForDwarf, EndAddress); |
570 | else if (LCI.C.cmd == MachO::LC_SEGMENT_64) |
571 | transferSegmentAndSections( |
572 | LCI, Segment: InputBinary.getSegment64LoadCommand(L: LCI), Obj: InputBinary, Writer, |
573 | LinkeditOffset: SymtabStart, LinkeditSize: StringStart + NewStringsSize - SymtabStart, EHFrameOffset: EHFrameStart, |
574 | EHFrameSize, DwarfSegmentSize, GapForDwarf, EndAddress); |
575 | } |
576 | |
577 | uint64_t DwarfVMAddr = alignTo(Value: EndAddress, Align: 0x1000); |
578 | uint64_t DwarfVMMax = Is64Bit ? UINT64_MAX : UINT32_MAX; |
579 | if (DwarfVMAddr + DwarfSegmentSize > DwarfVMMax || |
580 | DwarfVMAddr + DwarfSegmentSize < DwarfVMAddr /* Overflow */) { |
581 | // There is no room for the __DWARF segment at the end of the |
582 | // address space. Look through segments to find a gap. |
583 | DwarfVMAddr = GapForDwarf; |
584 | if (DwarfVMAddr == UINT64_MAX) |
585 | warn(Warning: "not enough VM space for the __DWARF segment." , |
586 | Context: "output file streaming" ); |
587 | } |
588 | |
589 | // Write the load command for the __DWARF segment. |
590 | if (!createDwarfSegment(VMAddr: DwarfVMAddr, FileOffset: DwarfSegmentStart, FileSize: DwarfSegmentSize, |
591 | NumSections: NumDwarfSections, Layout, Writer)) |
592 | return false; |
593 | |
594 | assert(OutFile.tell() == LoadCommandSize + HeaderSize); |
595 | OutFile.write_zeros(NumZeros: SymtabStart - (LoadCommandSize + HeaderSize)); |
596 | assert(OutFile.tell() == SymtabStart); |
597 | |
598 | // Transfer symbols. |
599 | if (ShouldEmitSymtab) { |
600 | OutFile << NewSymtab.str(); |
601 | assert(OutFile.tell() == StringStart); |
602 | |
603 | // Transfer string table. |
604 | // FIXME: The NonRelocatableStringpool starts with an empty string, but |
605 | // dsymutil-classic starts the reconstructed string table with 2 of these. |
606 | // Reproduce that behavior for now (there is corresponding code in |
607 | // transferSymbol). |
608 | OutFile << '\0'; |
609 | std::vector<DwarfStringPoolEntryRef> Strings = |
610 | NewStrings.getEntriesForEmission(); |
611 | for (auto EntryRef : Strings) { |
612 | OutFile.write(Ptr: EntryRef.getString().data(), |
613 | Size: EntryRef.getString().size() + 1); |
614 | } |
615 | } |
616 | assert(OutFile.tell() == StringStart + NewStringsSize); |
617 | |
618 | // Pad till the EH frame start. |
619 | OutFile.write_zeros(NumZeros: EHFrameStart - (StringStart + NewStringsSize)); |
620 | assert(OutFile.tell() == EHFrameStart); |
621 | |
622 | // Transfer eh_frame. |
623 | if (EHFrameSize > 0) |
624 | OutFile << EHFrameData; |
625 | assert(OutFile.tell() == EHFrameStart + EHFrameSize); |
626 | |
627 | // Pad till the Dwarf segment start. |
628 | OutFile.write_zeros(NumZeros: DwarfSegmentStart - (EHFrameStart + EHFrameSize)); |
629 | assert(OutFile.tell() == DwarfSegmentStart); |
630 | |
631 | // Emit the Dwarf sections contents. |
632 | for (const MCSection &Sec : MCAsm) { |
633 | if (Sec.begin() == Sec.end()) |
634 | continue; |
635 | |
636 | uint64_t Pos = OutFile.tell(); |
637 | OutFile.write_zeros(NumZeros: alignTo(Size: Pos, A: Sec.getAlign()) - Pos); |
638 | MCAsm.writeSectionData(OS&: OutFile, Section: &Sec, Layout); |
639 | } |
640 | |
641 | // Apply relocations to the contents of the DWARF segment. |
642 | // We do this here because the final value written depend on the DWARF vm |
643 | // addr, which is only calculated in this function. |
644 | if (!RelocationsToApply.empty()) { |
645 | if (!OutFile.supportsSeeking()) |
646 | report_fatal_error( |
647 | reason: "Cannot apply relocations to file that doesn't support seeking!" ); |
648 | |
649 | uint64_t Pos = OutFile.tell(); |
650 | for (auto &RelocationToApply : RelocationsToApply) { |
651 | OutFile.seek(off: DwarfSegmentStart + RelocationToApply.AddressFromDwarfStart); |
652 | int32_t Value = RelocationToApply.Value; |
653 | if (RelocationToApply.ShouldSubtractDwarfVM) |
654 | Value -= DwarfVMAddr; |
655 | OutFile.write(Ptr: (char *)&Value, Size: sizeof(int32_t)); |
656 | } |
657 | OutFile.seek(off: Pos); |
658 | } |
659 | |
660 | return true; |
661 | } |
662 | } // namespace MachOUtils |
663 | } // namespace dsymutil |
664 | } // namespace llvm |
665 | |