| 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 | |
| 27 | namespace llvm { |
| 28 | namespace dsymutil { |
| 29 | namespace MachOUtils { |
| 30 | |
| 31 | llvm::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 | |
| 43 | llvm::StringRef ArchAndFile::getPath() const { |
| 44 | assert(!Path.empty() && "path called before createTempFile" ); |
| 45 | return Path; |
| 46 | } |
| 47 | |
| 48 | int ArchAndFile::getFD() const { |
| 49 | assert((FD != -1) && "path called before createTempFile" ); |
| 50 | return FD; |
| 51 | } |
| 52 | |
| 53 | ArchAndFile::~ArchAndFile() { |
| 54 | if (!Path.empty()) |
| 55 | sys::fs::remove(path: Path); |
| 56 | } |
| 57 | |
| 58 | std::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 | |
| 64 | static 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 | |
| 85 | bool 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. |
| 141 | struct 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. |
| 158 | template <typename FunctionTy> |
| 159 | static 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. |
| 177 | template <typename NListTy> |
| 178 | static 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. |
| 219 | static 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 | |
| 245 | static MachO::section |
| 246 | getSection(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 | |
| 252 | static MachO::section_64 |
| 253 | getSection(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. |
| 272 | // |
| 273 | // When the __PSEUDO_PROBE segment is transferred, its offset and size are set |
| 274 | // resp. to \a PseudoProbeOffset and \a PseudoProbeSize, and its sections' |
| 275 | // offsets are updated using \a PseudoProbeProbesOffset for __probes and |
| 276 | // \a PseudoProbeDescsOffset for __probe_descs. |
| 277 | template <typename SegmentTy> |
| 278 | static void transferSegmentAndSections( |
| 279 | const object::MachOObjectFile::LoadCommandInfo &LCI, SegmentTy Segment, |
| 280 | const object::MachOObjectFile &Obj, MachObjectWriter &Writer, |
| 281 | uint64_t LinkeditOffset, uint64_t LinkeditSize, uint64_t EHFrameOffset, |
| 282 | uint64_t EHFrameSize, uint64_t PseudoProbeOffset, uint64_t PseudoProbeSize, |
| 283 | uint64_t PseudoProbeProbesOffset, uint64_t PseudoProbeDescsOffset, |
| 284 | uint64_t DwarfSegmentSize, uint64_t &GapForDwarf, uint64_t &EndAddress) { |
| 285 | if (StringRef("__DWARF" ) == Segment.segname) |
| 286 | return; |
| 287 | |
| 288 | if (StringRef("__TEXT" ) == Segment.segname && EHFrameSize > 0) { |
| 289 | Segment.fileoff = EHFrameOffset; |
| 290 | Segment.filesize = EHFrameSize; |
| 291 | } else if (StringRef("__LINKEDIT" ) == Segment.segname) { |
| 292 | Segment.fileoff = LinkeditOffset; |
| 293 | Segment.filesize = LinkeditSize; |
| 294 | // Resize vmsize by rounding to the page size. |
| 295 | Segment.vmsize = alignTo(Value: LinkeditSize, Align: 0x1000); |
| 296 | } else if (StringRef("__PSEUDO_PROBE" ) == Segment.segname && |
| 297 | PseudoProbeSize > 0) { |
| 298 | Segment.fileoff = PseudoProbeOffset; |
| 299 | Segment.filesize = PseudoProbeSize; |
| 300 | } else { |
| 301 | Segment.fileoff = Segment.filesize = 0; |
| 302 | } |
| 303 | |
| 304 | // Check if the end address of the last segment and our current |
| 305 | // start address leave a sufficient gap to store the __DWARF |
| 306 | // segment. |
| 307 | uint64_t PrevEndAddress = EndAddress; |
| 308 | EndAddress = alignTo(Value: EndAddress, Align: 0x1000); |
| 309 | if (GapForDwarf == UINT64_MAX && Segment.vmaddr > EndAddress && |
| 310 | Segment.vmaddr - EndAddress >= DwarfSegmentSize) |
| 311 | GapForDwarf = EndAddress; |
| 312 | |
| 313 | // The segments are not necessarily sorted by their vmaddr. |
| 314 | EndAddress = |
| 315 | std::max<uint64_t>(PrevEndAddress, Segment.vmaddr + Segment.vmsize); |
| 316 | unsigned nsects = Segment.nsects; |
| 317 | if (Obj.isLittleEndian() != sys::IsLittleEndianHost) |
| 318 | MachO::swapStruct(Segment); |
| 319 | Writer.W.OS.write(Ptr: reinterpret_cast<char *>(&Segment), Size: sizeof(Segment)); |
| 320 | for (unsigned i = 0; i < nsects; ++i) { |
| 321 | auto Sect = getSection(Obj, Segment, LCI, i); |
| 322 | if (StringRef("__eh_frame" ) == Sect.sectname) { |
| 323 | Sect.offset = EHFrameOffset; |
| 324 | Sect.reloff = Sect.nreloc = 0; |
| 325 | } else if (StringRef("__probes" ) == Sect.sectname && |
| 326 | PseudoProbeProbesOffset > 0) { |
| 327 | Sect.offset = PseudoProbeProbesOffset; |
| 328 | Sect.reloff = Sect.nreloc = 0; |
| 329 | } else if (StringRef("__probe_descs" ) == Sect.sectname && |
| 330 | PseudoProbeDescsOffset > 0) { |
| 331 | Sect.offset = PseudoProbeDescsOffset; |
| 332 | Sect.reloff = Sect.nreloc = 0; |
| 333 | } else { |
| 334 | Sect.offset = Sect.reloff = Sect.nreloc = 0; |
| 335 | } |
| 336 | if (Obj.isLittleEndian() != sys::IsLittleEndianHost) |
| 337 | MachO::swapStruct(Sect); |
| 338 | Writer.W.OS.write(Ptr: reinterpret_cast<char *>(&Sect), Size: sizeof(Sect)); |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | // Write the __DWARF segment load command to the output file. |
| 343 | static bool createDwarfSegment(const MCAssembler &Asm, uint64_t VMAddr, |
| 344 | uint64_t FileOffset, uint64_t FileSize, |
| 345 | unsigned NumSections, MachObjectWriter &Writer, |
| 346 | bool ) { |
| 347 | Writer.writeSegmentLoadCommand(Name: "__DWARF" , NumSections, VMAddr, |
| 348 | VMSize: alignTo(Value: FileSize, Align: 0x1000), SectionDataStartOffset: FileOffset, |
| 349 | SectionDataSize: FileSize, /* MaxProt */ 7, |
| 350 | /* InitProt =*/3); |
| 351 | |
| 352 | for (unsigned int i = 0, n = Writer.getSectionOrder().size(); i != n; ++i) { |
| 353 | auto *Sec = static_cast<MCSectionMachO *>(Writer.getSectionOrder()[i]); |
| 354 | if (!Asm.getSectionFileSize(Sec: *Sec)) |
| 355 | continue; |
| 356 | |
| 357 | Align Alignment = Sec->getAlign(); |
| 358 | if (Alignment > 1) { |
| 359 | VMAddr = alignTo(Size: VMAddr, A: Alignment); |
| 360 | FileOffset = alignTo(Size: FileOffset, A: Alignment); |
| 361 | } |
| 362 | // Mach-O section headers store the file offset in a 32-bit field |
| 363 | // (section.offset). For large dSYM files, a section can start beyond 4GB |
| 364 | // (UINT32_MAX), so the on-disk offset value may wrap/truncate. Within a |
| 365 | // single slice, sections are emitted in file order. If we allow emitting |
| 366 | // such non-standard Mach-O, compatible readers can reconstruct the true |
| 367 | // 64-bit offsets by walking sections in order and accumulating the sizes of |
| 368 | // preceding sections. |
| 369 | if (FileOffset > UINT32_MAX && !AllowSectionHeaderOffsetOverflow) |
| 370 | return error(Error: "section " + Sec->getName() + |
| 371 | "'s file offset exceeds 4GB." |
| 372 | " Refusing to produce an invalid Mach-O file." ); |
| 373 | Writer.writeSection(Asm, Sec: *Sec, VMAddr, FileOffset, Flags: 0, RelocationsStart: 0, NumRelocations: 0); |
| 374 | |
| 375 | FileOffset += Asm.getSectionAddressSize(Sec: *Sec); |
| 376 | VMAddr += Asm.getSectionAddressSize(Sec: *Sec); |
| 377 | } |
| 378 | return true; |
| 379 | } |
| 380 | |
| 381 | static bool isExecutable(const object::MachOObjectFile &Obj) { |
| 382 | if (Obj.is64Bit()) |
| 383 | return Obj.getHeader64().filetype != MachO::MH_OBJECT; |
| 384 | else |
| 385 | return Obj.getHeader().filetype != MachO::MH_OBJECT; |
| 386 | } |
| 387 | |
| 388 | static unsigned segmentLoadCommandSize(bool Is64Bit, unsigned NumSections) { |
| 389 | if (Is64Bit) |
| 390 | return sizeof(MachO::segment_command_64) + |
| 391 | NumSections * sizeof(MachO::section_64); |
| 392 | |
| 393 | return sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section); |
| 394 | } |
| 395 | |
| 396 | // Stream a dSYM companion binary file corresponding to the binary referenced |
| 397 | // by \a DM to \a OutFile. The passed \a MS MCStreamer is setup to write to |
| 398 | // \a OutFile and it must be using a MachObjectWriter object to do so. |
| 399 | bool generateDsymCompanion( |
| 400 | llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, const DebugMap &DM, |
| 401 | MCStreamer &MS, raw_fd_ostream &OutFile, |
| 402 | const std::vector<MachOUtils::DwarfRelocationApplicationInfo> |
| 403 | &RelocationsToApply, |
| 404 | bool ) { |
| 405 | auto &ObjectStreamer = static_cast<MCObjectStreamer &>(MS); |
| 406 | MCAssembler &MCAsm = ObjectStreamer.getAssembler(); |
| 407 | auto &Writer = static_cast<MachObjectWriter &>(MCAsm.getWriter()); |
| 408 | |
| 409 | // Layout but don't emit. |
| 410 | MCAsm.layout(); |
| 411 | |
| 412 | BinaryHolder InputBinaryHolder(VFS, false); |
| 413 | |
| 414 | auto ObjectEntry = InputBinaryHolder.getObjectEntry(Filename: DM.getBinaryPath()); |
| 415 | if (!ObjectEntry) { |
| 416 | auto Err = ObjectEntry.takeError(); |
| 417 | return error(Error: Twine("opening " ) + DM.getBinaryPath() + ": " + |
| 418 | toString(E: std::move(Err)), |
| 419 | Context: "output file streaming" ); |
| 420 | } |
| 421 | |
| 422 | auto Object = |
| 423 | ObjectEntry->getObjectAs<object::MachOObjectFile>(T: DM.getTriple()); |
| 424 | if (!Object) { |
| 425 | auto Err = Object.takeError(); |
| 426 | return error(Error: Twine("opening " ) + DM.getBinaryPath() + ": " + |
| 427 | toString(E: std::move(Err)), |
| 428 | Context: "output file streaming" ); |
| 429 | } |
| 430 | |
| 431 | auto &InputBinary = *Object; |
| 432 | |
| 433 | bool Is64Bit = Writer.is64Bit(); |
| 434 | MachO::symtab_command SymtabCmd = InputBinary.getSymtabLoadCommand(); |
| 435 | |
| 436 | // Compute the number of load commands we will need. |
| 437 | unsigned LoadCommandSize = 0; |
| 438 | unsigned NumLoadCommands = 0; |
| 439 | |
| 440 | bool HasSymtab = false; |
| 441 | |
| 442 | // Check LC_SYMTAB and get LC_UUID and LC_BUILD_VERSION. |
| 443 | MachO::uuid_command UUIDCmd; |
| 444 | SmallVector<MachO::build_version_command, 2> BuildVersionCmd; |
| 445 | memset(s: &UUIDCmd, c: 0, n: sizeof(UUIDCmd)); |
| 446 | for (auto &LCI : InputBinary.load_commands()) { |
| 447 | switch (LCI.C.cmd) { |
| 448 | case MachO::LC_UUID: |
| 449 | if (UUIDCmd.cmd) |
| 450 | return error(Error: "Binary contains more than one UUID" ); |
| 451 | UUIDCmd = InputBinary.getUuidCommand(L: LCI); |
| 452 | ++NumLoadCommands; |
| 453 | LoadCommandSize += sizeof(UUIDCmd); |
| 454 | break; |
| 455 | case MachO::LC_BUILD_VERSION: { |
| 456 | MachO::build_version_command Cmd; |
| 457 | memset(s: &Cmd, c: 0, n: sizeof(Cmd)); |
| 458 | Cmd = InputBinary.getBuildVersionLoadCommand(L: LCI); |
| 459 | ++NumLoadCommands; |
| 460 | LoadCommandSize += sizeof(Cmd); |
| 461 | // LLDB doesn't care about the build tools for now. |
| 462 | Cmd.ntools = 0; |
| 463 | BuildVersionCmd.push_back(Elt: Cmd); |
| 464 | break; |
| 465 | } |
| 466 | case MachO::LC_SYMTAB: |
| 467 | HasSymtab = true; |
| 468 | break; |
| 469 | default: |
| 470 | break; |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | // If we have a valid symtab to copy, do it. |
| 475 | bool ShouldEmitSymtab = HasSymtab && isExecutable(Obj: InputBinary); |
| 476 | if (ShouldEmitSymtab) { |
| 477 | LoadCommandSize += sizeof(MachO::symtab_command); |
| 478 | ++NumLoadCommands; |
| 479 | } |
| 480 | |
| 481 | // If we have a valid eh_frame to copy, do it. |
| 482 | uint64_t EHFrameSize = 0; |
| 483 | StringRef EHFrameData; |
| 484 | StringRef PseudoProbeProbesData; |
| 485 | uint64_t PseudoProbeProbesSize = 0; |
| 486 | StringRef PseudoProbeDescsData; |
| 487 | uint64_t PseudoProbeDescsSize = 0; |
| 488 | for (const object::SectionRef &Section : InputBinary.sections()) { |
| 489 | Expected<StringRef> NameOrErr = Section.getName(); |
| 490 | if (!NameOrErr) { |
| 491 | consumeError(Err: NameOrErr.takeError()); |
| 492 | continue; |
| 493 | } |
| 494 | StringRef SectionName = *NameOrErr; |
| 495 | SectionName = SectionName.substr(Start: SectionName.find_first_not_of(Chars: "._" )); |
| 496 | if (SectionName == "eh_frame" ) { |
| 497 | if (Expected<StringRef> ContentsOrErr = Section.getContents()) { |
| 498 | EHFrameData = *ContentsOrErr; |
| 499 | EHFrameSize = Section.getSize(); |
| 500 | } else { |
| 501 | consumeError(Err: ContentsOrErr.takeError()); |
| 502 | } |
| 503 | } else if (SectionName == "probes" ) { |
| 504 | if (Expected<StringRef> ContentsOrErr = Section.getContents()) { |
| 505 | PseudoProbeProbesData = *ContentsOrErr; |
| 506 | PseudoProbeProbesSize = Section.getSize(); |
| 507 | } else { |
| 508 | consumeError(Err: ContentsOrErr.takeError()); |
| 509 | } |
| 510 | } else if (SectionName == "probe_descs" ) { |
| 511 | if (Expected<StringRef> ContentsOrErr = Section.getContents()) { |
| 512 | PseudoProbeDescsData = *ContentsOrErr; |
| 513 | PseudoProbeDescsSize = Section.getSize(); |
| 514 | } else { |
| 515 | consumeError(Err: ContentsOrErr.takeError()); |
| 516 | } |
| 517 | } |
| 518 | } |
| 519 | uint64_t PseudoProbeSize = PseudoProbeProbesSize + PseudoProbeDescsSize; |
| 520 | |
| 521 | unsigned = |
| 522 | Is64Bit ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header); |
| 523 | // We will copy every segment that isn't __DWARF. |
| 524 | iterateOnSegments(Obj: InputBinary, Handler: [&](const MachO::segment_command_64 &Segment) { |
| 525 | if (StringRef("__DWARF" ) == Segment.segname) |
| 526 | return; |
| 527 | |
| 528 | ++NumLoadCommands; |
| 529 | LoadCommandSize += segmentLoadCommandSize(Is64Bit, NumSections: Segment.nsects); |
| 530 | }); |
| 531 | |
| 532 | // We will add our own brand new __DWARF segment if we have debug |
| 533 | // info. |
| 534 | unsigned NumDwarfSections = 0; |
| 535 | uint64_t DwarfSegmentSize = 0; |
| 536 | |
| 537 | for (unsigned int i = 0, n = Writer.getSectionOrder().size(); i != n; ++i) { |
| 538 | MCSection *Sec = Writer.getSectionOrder()[i]; |
| 539 | if (Sec->begin() == Sec->end()) |
| 540 | continue; |
| 541 | |
| 542 | if (uint64_t Size = MCAsm.getSectionFileSize(Sec: *Sec)) { |
| 543 | DwarfSegmentSize = alignTo(Size: DwarfSegmentSize, A: Sec->getAlign()); |
| 544 | DwarfSegmentSize += Size; |
| 545 | ++NumDwarfSections; |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | if (NumDwarfSections) { |
| 550 | ++NumLoadCommands; |
| 551 | LoadCommandSize += segmentLoadCommandSize(Is64Bit, NumSections: NumDwarfSections); |
| 552 | } |
| 553 | |
| 554 | SmallString<0> NewSymtab; |
| 555 | // Legacy dsymutil puts an empty string at the start of the line table. |
| 556 | // thus we set NonRelocatableStringpool(,PutEmptyString=true) |
| 557 | NonRelocatableStringpool NewStrings(true); |
| 558 | unsigned NListSize = Is64Bit ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist); |
| 559 | unsigned NumSyms = 0; |
| 560 | uint64_t NewStringsSize = 0; |
| 561 | if (ShouldEmitSymtab) { |
| 562 | NewSymtab.reserve(N: SymtabCmd.nsyms * NListSize / 2); |
| 563 | NumSyms = transferSymbols(Obj: InputBinary, NewSymtab, NewStrings); |
| 564 | NewStringsSize = NewStrings.getSize() + 1; |
| 565 | } |
| 566 | |
| 567 | uint64_t SymtabStart = LoadCommandSize; |
| 568 | SymtabStart += HeaderSize; |
| 569 | SymtabStart = alignTo(Value: SymtabStart, Align: 0x1000); |
| 570 | |
| 571 | // We gathered all the information we need, start emitting the output file. |
| 572 | Writer.writeHeader(Type: MachO::MH_DSYM, NumLoadCommands, LoadCommandsSize: LoadCommandSize, |
| 573 | /*SubsectionsViaSymbols=*/false); |
| 574 | |
| 575 | // Write the load commands. |
| 576 | assert(OutFile.tell() == HeaderSize); |
| 577 | if (UUIDCmd.cmd != 0) { |
| 578 | Writer.W.write<uint32_t>(Val: UUIDCmd.cmd); |
| 579 | Writer.W.write<uint32_t>(Val: sizeof(UUIDCmd)); |
| 580 | OutFile.write(Ptr: reinterpret_cast<const char *>(UUIDCmd.uuid), Size: 16); |
| 581 | assert(OutFile.tell() == HeaderSize + sizeof(UUIDCmd)); |
| 582 | } |
| 583 | for (auto Cmd : BuildVersionCmd) { |
| 584 | Writer.W.write<uint32_t>(Val: Cmd.cmd); |
| 585 | Writer.W.write<uint32_t>(Val: sizeof(Cmd)); |
| 586 | Writer.W.write<uint32_t>(Val: Cmd.platform); |
| 587 | Writer.W.write<uint32_t>(Val: Cmd.minos); |
| 588 | Writer.W.write<uint32_t>(Val: Cmd.sdk); |
| 589 | Writer.W.write<uint32_t>(Val: Cmd.ntools); |
| 590 | } |
| 591 | |
| 592 | assert(SymtabCmd.cmd && "No symbol table." ); |
| 593 | uint64_t StringStart = SymtabStart + NumSyms * NListSize; |
| 594 | if (ShouldEmitSymtab) |
| 595 | Writer.writeSymtabLoadCommand(SymbolOffset: SymtabStart, NumSymbols: NumSyms, StringTableOffset: StringStart, |
| 596 | StringTableSize: NewStringsSize); |
| 597 | |
| 598 | uint64_t EHFrameStart = StringStart + NewStringsSize; |
| 599 | EHFrameStart = alignTo(Value: EHFrameStart, Align: 0x1000); |
| 600 | |
| 601 | // Place pseudo probe data after the EH frame. |
| 602 | uint64_t PseudoProbeStart = PseudoProbeSize > 0 |
| 603 | ? alignTo(Value: EHFrameStart + EHFrameSize, Align: 0x1000) |
| 604 | : EHFrameStart + EHFrameSize; |
| 605 | |
| 606 | uint64_t PseudoProbeProbesStart = PseudoProbeStart; |
| 607 | uint64_t PseudoProbeDescsStart = PseudoProbeStart + PseudoProbeProbesSize; |
| 608 | |
| 609 | uint64_t DwarfSegmentStart = |
| 610 | alignTo(Value: PseudoProbeStart + PseudoProbeSize, Align: 0x1000); |
| 611 | |
| 612 | // Write the load commands for the segments and sections we 'import' from |
| 613 | // the original binary. |
| 614 | uint64_t EndAddress = 0; |
| 615 | uint64_t GapForDwarf = UINT64_MAX; |
| 616 | for (auto &LCI : InputBinary.load_commands()) { |
| 617 | if (LCI.C.cmd == MachO::LC_SEGMENT) |
| 618 | transferSegmentAndSections( |
| 619 | LCI, Segment: InputBinary.getSegmentLoadCommand(L: LCI), Obj: InputBinary, Writer, |
| 620 | LinkeditOffset: SymtabStart, LinkeditSize: StringStart + NewStringsSize - SymtabStart, EHFrameOffset: EHFrameStart, |
| 621 | EHFrameSize, PseudoProbeOffset: PseudoProbeStart, PseudoProbeSize, |
| 622 | PseudoProbeProbesOffset: PseudoProbeProbesStart, PseudoProbeDescsOffset: PseudoProbeDescsStart, DwarfSegmentSize, |
| 623 | GapForDwarf, EndAddress); |
| 624 | else if (LCI.C.cmd == MachO::LC_SEGMENT_64) |
| 625 | transferSegmentAndSections( |
| 626 | LCI, Segment: InputBinary.getSegment64LoadCommand(L: LCI), Obj: InputBinary, Writer, |
| 627 | LinkeditOffset: SymtabStart, LinkeditSize: StringStart + NewStringsSize - SymtabStart, EHFrameOffset: EHFrameStart, |
| 628 | EHFrameSize, PseudoProbeOffset: PseudoProbeStart, PseudoProbeSize, |
| 629 | PseudoProbeProbesOffset: PseudoProbeProbesStart, PseudoProbeDescsOffset: PseudoProbeDescsStart, DwarfSegmentSize, |
| 630 | GapForDwarf, EndAddress); |
| 631 | } |
| 632 | |
| 633 | uint64_t DwarfVMAddr = alignTo(Value: EndAddress, Align: 0x1000); |
| 634 | uint64_t DwarfVMMax = Is64Bit ? UINT64_MAX : UINT32_MAX; |
| 635 | if (DwarfVMAddr + DwarfSegmentSize > DwarfVMMax || |
| 636 | DwarfVMAddr + DwarfSegmentSize < DwarfVMAddr /* Overflow */) { |
| 637 | // There is no room for the __DWARF segment at the end of the |
| 638 | // address space. Look through segments to find a gap. |
| 639 | DwarfVMAddr = GapForDwarf; |
| 640 | if (DwarfVMAddr == UINT64_MAX) |
| 641 | warn(Warning: "not enough VM space for the __DWARF segment." , |
| 642 | Context: "output file streaming" ); |
| 643 | } |
| 644 | |
| 645 | // Write the load command for the __DWARF segment. |
| 646 | if (!createDwarfSegment(Asm: MCAsm, VMAddr: DwarfVMAddr, FileOffset: DwarfSegmentStart, |
| 647 | FileSize: DwarfSegmentSize, NumSections: NumDwarfSections, Writer, |
| 648 | AllowSectionHeaderOffsetOverflow)) |
| 649 | return false; |
| 650 | |
| 651 | assert(OutFile.tell() == LoadCommandSize + HeaderSize); |
| 652 | OutFile.write_zeros(NumZeros: SymtabStart - (LoadCommandSize + HeaderSize)); |
| 653 | assert(OutFile.tell() == SymtabStart); |
| 654 | |
| 655 | // Transfer symbols. |
| 656 | if (ShouldEmitSymtab) { |
| 657 | OutFile << NewSymtab.str(); |
| 658 | assert(OutFile.tell() == StringStart); |
| 659 | |
| 660 | // Transfer string table. |
| 661 | // FIXME: The NonRelocatableStringpool starts with an empty string, but |
| 662 | // dsymutil-classic starts the reconstructed string table with 2 of these. |
| 663 | // Reproduce that behavior for now (there is corresponding code in |
| 664 | // transferSymbol). |
| 665 | OutFile << '\0'; |
| 666 | std::vector<DwarfStringPoolEntryRef> Strings = |
| 667 | NewStrings.getEntriesForEmission(); |
| 668 | for (auto EntryRef : Strings) { |
| 669 | OutFile.write(Ptr: EntryRef.getString().data(), |
| 670 | Size: EntryRef.getString().size() + 1); |
| 671 | } |
| 672 | } |
| 673 | assert(OutFile.tell() == StringStart + NewStringsSize); |
| 674 | |
| 675 | // Pad till the EH frame start. |
| 676 | OutFile.write_zeros(NumZeros: EHFrameStart - (StringStart + NewStringsSize)); |
| 677 | assert(OutFile.tell() == EHFrameStart); |
| 678 | |
| 679 | // Transfer eh_frame. |
| 680 | if (EHFrameSize > 0) |
| 681 | OutFile << EHFrameData; |
| 682 | assert(OutFile.tell() == EHFrameStart + EHFrameSize); |
| 683 | |
| 684 | // Transfer pseudo probe. |
| 685 | if (PseudoProbeSize > 0) { |
| 686 | OutFile.write_zeros(NumZeros: PseudoProbeStart - (EHFrameStart + EHFrameSize)); |
| 687 | assert(OutFile.tell() == PseudoProbeStart); |
| 688 | OutFile << PseudoProbeProbesData; |
| 689 | OutFile << PseudoProbeDescsData; |
| 690 | assert(OutFile.tell() == PseudoProbeStart + PseudoProbeSize); |
| 691 | } |
| 692 | |
| 693 | // Pad till the Dwarf segment start. |
| 694 | OutFile.write_zeros(NumZeros: DwarfSegmentStart - OutFile.tell()); |
| 695 | assert(OutFile.tell() == DwarfSegmentStart); |
| 696 | |
| 697 | // Emit the Dwarf sections contents. |
| 698 | for (const MCSection &Sec : MCAsm) { |
| 699 | uint64_t Pos = OutFile.tell(); |
| 700 | OutFile.write_zeros(NumZeros: alignTo(Size: Pos, A: Sec.getAlign()) - Pos); |
| 701 | MCAsm.writeSectionData(OS&: OutFile, Section: &Sec); |
| 702 | } |
| 703 | |
| 704 | // Apply relocations to the contents of the DWARF segment. |
| 705 | // We do this here because the final value written depend on the DWARF vm |
| 706 | // addr, which is only calculated in this function. |
| 707 | if (!RelocationsToApply.empty()) { |
| 708 | if (!OutFile.supportsSeeking()) |
| 709 | report_fatal_error( |
| 710 | reason: "Cannot apply relocations to file that doesn't support seeking!" ); |
| 711 | |
| 712 | uint64_t Pos = OutFile.tell(); |
| 713 | for (auto &RelocationToApply : RelocationsToApply) { |
| 714 | OutFile.seek(off: DwarfSegmentStart + RelocationToApply.AddressFromDwarfStart); |
| 715 | int32_t Value = RelocationToApply.Value; |
| 716 | if (RelocationToApply.ShouldSubtractDwarfVM) |
| 717 | Value -= DwarfVMAddr; |
| 718 | OutFile.write(Ptr: (char *)&Value, Size: sizeof(int32_t)); |
| 719 | } |
| 720 | OutFile.seek(off: Pos); |
| 721 | } |
| 722 | |
| 723 | return true; |
| 724 | } |
| 725 | } // namespace MachOUtils |
| 726 | } // namespace dsymutil |
| 727 | } // namespace llvm |
| 728 | |