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