1 //===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===// 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 "llvm/ADT/DenseMap.h" 10 #include "llvm/ADT/Twine.h" 11 #include "llvm/ADT/iterator_range.h" 12 #include "llvm/BinaryFormat/MachO.h" 13 #include "llvm/MC/MCAsmBackend.h" 14 #include "llvm/MC/MCAsmInfoDarwin.h" 15 #include "llvm/MC/MCAssembler.h" 16 #include "llvm/MC/MCContext.h" 17 #include "llvm/MC/MCDirectives.h" 18 #include "llvm/MC/MCExpr.h" 19 #include "llvm/MC/MCFixupKindInfo.h" 20 #include "llvm/MC/MCFragment.h" 21 #include "llvm/MC/MCMachObjectWriter.h" 22 #include "llvm/MC/MCObjectFileInfo.h" 23 #include "llvm/MC/MCObjectWriter.h" 24 #include "llvm/MC/MCSection.h" 25 #include "llvm/MC/MCSectionMachO.h" 26 #include "llvm/MC/MCSymbol.h" 27 #include "llvm/MC/MCSymbolMachO.h" 28 #include "llvm/MC/MCValue.h" 29 #include "llvm/Support/Alignment.h" 30 #include "llvm/Support/Casting.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/LEB128.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include <algorithm> 37 #include <cassert> 38 #include <cstdint> 39 #include <string> 40 #include <utility> 41 #include <vector> 42 43 using namespace llvm; 44 45 #define DEBUG_TYPE "mc" 46 47 void MachObjectWriter::reset() { 48 Relocations.clear(); 49 IndirectSymBase.clear(); 50 IndirectSymbols.clear(); 51 DataRegions.clear(); 52 SectionAddress.clear(); 53 SectionOrder.clear(); 54 StringTable.clear(); 55 LocalSymbolData.clear(); 56 ExternalSymbolData.clear(); 57 UndefinedSymbolData.clear(); 58 LOHContainer.reset(); 59 VersionInfo.Major = 0; 60 VersionInfo.SDKVersion = VersionTuple(); 61 TargetVariantVersionInfo.Major = 0; 62 TargetVariantVersionInfo.SDKVersion = VersionTuple(); 63 LinkerOptions.clear(); 64 MCObjectWriter::reset(); 65 } 66 67 bool MachObjectWriter::doesSymbolRequireExternRelocation(const MCSymbol &S) { 68 // Undefined symbols are always extern. 69 if (S.isUndefined()) 70 return true; 71 72 // References to weak definitions require external relocation entries; the 73 // definition may not always be the one in the same object file. 74 if (cast<MCSymbolMachO>(S).isWeakDefinition()) 75 return true; 76 77 // Otherwise, we can use an internal relocation. 78 return false; 79 } 80 81 bool MachObjectWriter:: 82 MachSymbolData::operator<(const MachSymbolData &RHS) const { 83 return Symbol->getName() < RHS.Symbol->getName(); 84 } 85 86 bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) { 87 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo( 88 (MCFixupKind) Kind); 89 90 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel; 91 } 92 93 uint64_t 94 MachObjectWriter::getFragmentAddress(const MCAssembler &Asm, 95 const MCFragment *Fragment) const { 96 return getSectionAddress(Fragment->getParent()) + 97 Asm.getFragmentOffset(*Fragment); 98 } 99 100 uint64_t MachObjectWriter::getSymbolAddress(const MCSymbol &S, 101 const MCAssembler &Asm) const { 102 // If this is a variable, then recursively evaluate now. 103 if (S.isVariable()) { 104 if (const MCConstantExpr *C = 105 dyn_cast<const MCConstantExpr>(S.getVariableValue())) 106 return C->getValue(); 107 108 MCValue Target; 109 if (!S.getVariableValue()->evaluateAsRelocatable(Target, &Asm, nullptr)) 110 report_fatal_error("unable to evaluate offset for variable '" + 111 S.getName() + "'"); 112 113 // Verify that any used symbols are defined. 114 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined()) 115 report_fatal_error("unable to evaluate offset to undefined symbol '" + 116 Target.getSymA()->getSymbol().getName() + "'"); 117 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined()) 118 report_fatal_error("unable to evaluate offset to undefined symbol '" + 119 Target.getSymB()->getSymbol().getName() + "'"); 120 121 uint64_t Address = Target.getConstant(); 122 if (Target.getSymA()) 123 Address += getSymbolAddress(Target.getSymA()->getSymbol(), Asm); 124 if (Target.getSymB()) 125 Address += getSymbolAddress(Target.getSymB()->getSymbol(), Asm); 126 return Address; 127 } 128 129 return getSectionAddress(S.getFragment()->getParent()) + 130 Asm.getSymbolOffset(S); 131 } 132 133 uint64_t MachObjectWriter::getPaddingSize(const MCAssembler &Asm, 134 const MCSection *Sec) const { 135 uint64_t EndAddr = getSectionAddress(Sec) + Asm.getSectionAddressSize(*Sec); 136 unsigned Next = cast<MCSectionMachO>(Sec)->getLayoutOrder() + 1; 137 if (Next >= SectionOrder.size()) 138 return 0; 139 140 const MCSection &NextSec = *SectionOrder[Next]; 141 if (NextSec.isVirtualSection()) 142 return 0; 143 return offsetToAlignment(EndAddr, NextSec.getAlign()); 144 } 145 146 static bool isSymbolLinkerVisible(const MCSymbol &Symbol) { 147 // Non-temporary labels should always be visible to the linker. 148 if (!Symbol.isTemporary()) 149 return true; 150 151 if (Symbol.isUsedInReloc()) 152 return true; 153 154 return false; 155 } 156 157 const MCSymbol *MachObjectWriter::getAtom(const MCSymbol &S) const { 158 // Linker visible symbols define atoms. 159 if (isSymbolLinkerVisible(S)) 160 return &S; 161 162 // Absolute and undefined symbols have no defining atom. 163 if (!S.isInSection()) 164 return nullptr; 165 166 // Non-linker visible symbols in sections which can't be atomized have no 167 // defining atom. 168 if (!MCAsmInfoDarwin::isSectionAtomizableBySymbols( 169 *S.getFragment()->getParent())) 170 return nullptr; 171 172 // Otherwise, return the atom for the containing fragment. 173 return S.getFragment()->getAtom(); 174 } 175 176 void MachObjectWriter::writeHeader(MachO::HeaderFileType Type, 177 unsigned NumLoadCommands, 178 unsigned LoadCommandsSize, 179 bool SubsectionsViaSymbols) { 180 uint32_t Flags = 0; 181 182 if (SubsectionsViaSymbols) 183 Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS; 184 185 // struct mach_header (28 bytes) or 186 // struct mach_header_64 (32 bytes) 187 188 uint64_t Start = W.OS.tell(); 189 (void) Start; 190 191 W.write<uint32_t>(is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC); 192 193 W.write<uint32_t>(TargetObjectWriter->getCPUType()); 194 W.write<uint32_t>(TargetObjectWriter->getCPUSubtype()); 195 196 W.write<uint32_t>(Type); 197 W.write<uint32_t>(NumLoadCommands); 198 W.write<uint32_t>(LoadCommandsSize); 199 W.write<uint32_t>(Flags); 200 if (is64Bit()) 201 W.write<uint32_t>(0); // reserved 202 203 assert(W.OS.tell() - Start == (is64Bit() ? sizeof(MachO::mach_header_64) 204 : sizeof(MachO::mach_header))); 205 } 206 207 void MachObjectWriter::writeWithPadding(StringRef Str, uint64_t Size) { 208 assert(Size >= Str.size()); 209 W.OS << Str; 210 W.OS.write_zeros(Size - Str.size()); 211 } 212 213 /// writeSegmentLoadCommand - Write a segment load command. 214 /// 215 /// \param NumSections The number of sections in this segment. 216 /// \param SectionDataSize The total size of the sections. 217 void MachObjectWriter::writeSegmentLoadCommand( 218 StringRef Name, unsigned NumSections, uint64_t VMAddr, uint64_t VMSize, 219 uint64_t SectionDataStartOffset, uint64_t SectionDataSize, uint32_t MaxProt, 220 uint32_t InitProt) { 221 // struct segment_command (56 bytes) or 222 // struct segment_command_64 (72 bytes) 223 224 uint64_t Start = W.OS.tell(); 225 (void) Start; 226 227 unsigned SegmentLoadCommandSize = 228 is64Bit() ? sizeof(MachO::segment_command_64): 229 sizeof(MachO::segment_command); 230 W.write<uint32_t>(is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT); 231 W.write<uint32_t>(SegmentLoadCommandSize + 232 NumSections * (is64Bit() ? sizeof(MachO::section_64) : 233 sizeof(MachO::section))); 234 235 writeWithPadding(Name, 16); 236 if (is64Bit()) { 237 W.write<uint64_t>(VMAddr); // vmaddr 238 W.write<uint64_t>(VMSize); // vmsize 239 W.write<uint64_t>(SectionDataStartOffset); // file offset 240 W.write<uint64_t>(SectionDataSize); // file size 241 } else { 242 W.write<uint32_t>(VMAddr); // vmaddr 243 W.write<uint32_t>(VMSize); // vmsize 244 W.write<uint32_t>(SectionDataStartOffset); // file offset 245 W.write<uint32_t>(SectionDataSize); // file size 246 } 247 // maxprot 248 W.write<uint32_t>(MaxProt); 249 // initprot 250 W.write<uint32_t>(InitProt); 251 W.write<uint32_t>(NumSections); 252 W.write<uint32_t>(0); // flags 253 254 assert(W.OS.tell() - Start == SegmentLoadCommandSize); 255 } 256 257 void MachObjectWriter::writeSection(const MCAssembler &Asm, 258 const MCSection &Sec, uint64_t VMAddr, 259 uint64_t FileOffset, unsigned Flags, 260 uint64_t RelocationsStart, 261 unsigned NumRelocations) { 262 uint64_t SectionSize = Asm.getSectionAddressSize(Sec); 263 const MCSectionMachO &Section = cast<MCSectionMachO>(Sec); 264 265 // The offset is unused for virtual sections. 266 if (Section.isVirtualSection()) { 267 assert(Asm.getSectionFileSize(Sec) == 0 && "Invalid file size!"); 268 FileOffset = 0; 269 } 270 271 // struct section (68 bytes) or 272 // struct section_64 (80 bytes) 273 274 uint64_t Start = W.OS.tell(); 275 (void) Start; 276 277 writeWithPadding(Section.getName(), 16); 278 writeWithPadding(Section.getSegmentName(), 16); 279 if (is64Bit()) { 280 W.write<uint64_t>(VMAddr); // address 281 W.write<uint64_t>(SectionSize); // size 282 } else { 283 W.write<uint32_t>(VMAddr); // address 284 W.write<uint32_t>(SectionSize); // size 285 } 286 assert(isUInt<32>(FileOffset) && "Cannot encode offset of section"); 287 W.write<uint32_t>(FileOffset); 288 289 W.write<uint32_t>(Log2(Section.getAlign())); 290 assert((!NumRelocations || isUInt<32>(RelocationsStart)) && 291 "Cannot encode offset of relocations"); 292 W.write<uint32_t>(NumRelocations ? RelocationsStart : 0); 293 W.write<uint32_t>(NumRelocations); 294 W.write<uint32_t>(Flags); 295 W.write<uint32_t>(IndirectSymBase.lookup(&Sec)); // reserved1 296 W.write<uint32_t>(Section.getStubSize()); // reserved2 297 if (is64Bit()) 298 W.write<uint32_t>(0); // reserved3 299 300 assert(W.OS.tell() - Start == 301 (is64Bit() ? sizeof(MachO::section_64) : sizeof(MachO::section))); 302 } 303 304 void MachObjectWriter::writeSymtabLoadCommand(uint32_t SymbolOffset, 305 uint32_t NumSymbols, 306 uint32_t StringTableOffset, 307 uint32_t StringTableSize) { 308 // struct symtab_command (24 bytes) 309 310 uint64_t Start = W.OS.tell(); 311 (void) Start; 312 313 W.write<uint32_t>(MachO::LC_SYMTAB); 314 W.write<uint32_t>(sizeof(MachO::symtab_command)); 315 W.write<uint32_t>(SymbolOffset); 316 W.write<uint32_t>(NumSymbols); 317 W.write<uint32_t>(StringTableOffset); 318 W.write<uint32_t>(StringTableSize); 319 320 assert(W.OS.tell() - Start == sizeof(MachO::symtab_command)); 321 } 322 323 void MachObjectWriter::writeDysymtabLoadCommand(uint32_t FirstLocalSymbol, 324 uint32_t NumLocalSymbols, 325 uint32_t FirstExternalSymbol, 326 uint32_t NumExternalSymbols, 327 uint32_t FirstUndefinedSymbol, 328 uint32_t NumUndefinedSymbols, 329 uint32_t IndirectSymbolOffset, 330 uint32_t NumIndirectSymbols) { 331 // struct dysymtab_command (80 bytes) 332 333 uint64_t Start = W.OS.tell(); 334 (void) Start; 335 336 W.write<uint32_t>(MachO::LC_DYSYMTAB); 337 W.write<uint32_t>(sizeof(MachO::dysymtab_command)); 338 W.write<uint32_t>(FirstLocalSymbol); 339 W.write<uint32_t>(NumLocalSymbols); 340 W.write<uint32_t>(FirstExternalSymbol); 341 W.write<uint32_t>(NumExternalSymbols); 342 W.write<uint32_t>(FirstUndefinedSymbol); 343 W.write<uint32_t>(NumUndefinedSymbols); 344 W.write<uint32_t>(0); // tocoff 345 W.write<uint32_t>(0); // ntoc 346 W.write<uint32_t>(0); // modtaboff 347 W.write<uint32_t>(0); // nmodtab 348 W.write<uint32_t>(0); // extrefsymoff 349 W.write<uint32_t>(0); // nextrefsyms 350 W.write<uint32_t>(IndirectSymbolOffset); 351 W.write<uint32_t>(NumIndirectSymbols); 352 W.write<uint32_t>(0); // extreloff 353 W.write<uint32_t>(0); // nextrel 354 W.write<uint32_t>(0); // locreloff 355 W.write<uint32_t>(0); // nlocrel 356 357 assert(W.OS.tell() - Start == sizeof(MachO::dysymtab_command)); 358 } 359 360 MachObjectWriter::MachSymbolData * 361 MachObjectWriter::findSymbolData(const MCSymbol &Sym) { 362 for (auto *SymbolData : 363 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData}) 364 for (MachSymbolData &Entry : *SymbolData) 365 if (Entry.Symbol == &Sym) 366 return &Entry; 367 368 return nullptr; 369 } 370 371 const MCSymbol &MachObjectWriter::findAliasedSymbol(const MCSymbol &Sym) const { 372 const MCSymbol *S = &Sym; 373 while (S->isVariable()) { 374 const MCExpr *Value = S->getVariableValue(); 375 const auto *Ref = dyn_cast<MCSymbolRefExpr>(Value); 376 if (!Ref) 377 return *S; 378 S = &Ref->getSymbol(); 379 } 380 return *S; 381 } 382 383 void MachObjectWriter::writeNlist(MachSymbolData &MSD, const MCAssembler &Asm) { 384 const MCSymbol *Symbol = MSD.Symbol; 385 const auto &Data = cast<MCSymbolMachO>(*Symbol); 386 const MCSymbol *AliasedSymbol = &findAliasedSymbol(*Symbol); 387 uint8_t SectionIndex = MSD.SectionIndex; 388 uint8_t Type = 0; 389 uint64_t Address = 0; 390 bool IsAlias = Symbol != AliasedSymbol; 391 392 const MCSymbol &OrigSymbol = *Symbol; 393 MachSymbolData *AliaseeInfo; 394 if (IsAlias) { 395 AliaseeInfo = findSymbolData(*AliasedSymbol); 396 if (AliaseeInfo) 397 SectionIndex = AliaseeInfo->SectionIndex; 398 Symbol = AliasedSymbol; 399 // FIXME: Should this update Data as well? 400 } 401 402 // Set the N_TYPE bits. See <mach-o/nlist.h>. 403 // 404 // FIXME: Are the prebound or indirect fields possible here? 405 if (IsAlias && Symbol->isUndefined()) 406 Type = MachO::N_INDR; 407 else if (Symbol->isUndefined()) 408 Type = MachO::N_UNDF; 409 else if (Symbol->isAbsolute()) 410 Type = MachO::N_ABS; 411 else 412 Type = MachO::N_SECT; 413 414 // FIXME: Set STAB bits. 415 416 if (Data.isPrivateExtern()) 417 Type |= MachO::N_PEXT; 418 419 // Set external bit. 420 if (Data.isExternal() || (!IsAlias && Symbol->isUndefined())) 421 Type |= MachO::N_EXT; 422 423 // Compute the symbol address. 424 if (IsAlias && Symbol->isUndefined()) 425 Address = AliaseeInfo->StringIndex; 426 else if (Symbol->isDefined()) 427 Address = getSymbolAddress(OrigSymbol, Asm); 428 else if (Symbol->isCommon()) { 429 // Common symbols are encoded with the size in the address 430 // field, and their alignment in the flags. 431 Address = Symbol->getCommonSize(); 432 } 433 434 // struct nlist (12 bytes) 435 436 W.write<uint32_t>(MSD.StringIndex); 437 W.OS << char(Type); 438 W.OS << char(SectionIndex); 439 440 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc' 441 // value. 442 bool EncodeAsAltEntry = 443 IsAlias && cast<MCSymbolMachO>(OrigSymbol).isAltEntry(); 444 W.write<uint16_t>(cast<MCSymbolMachO>(Symbol)->getEncodedFlags(EncodeAsAltEntry)); 445 if (is64Bit()) 446 W.write<uint64_t>(Address); 447 else 448 W.write<uint32_t>(Address); 449 } 450 451 void MachObjectWriter::writeLinkeditLoadCommand(uint32_t Type, 452 uint32_t DataOffset, 453 uint32_t DataSize) { 454 uint64_t Start = W.OS.tell(); 455 (void) Start; 456 457 W.write<uint32_t>(Type); 458 W.write<uint32_t>(sizeof(MachO::linkedit_data_command)); 459 W.write<uint32_t>(DataOffset); 460 W.write<uint32_t>(DataSize); 461 462 assert(W.OS.tell() - Start == sizeof(MachO::linkedit_data_command)); 463 } 464 465 static unsigned ComputeLinkerOptionsLoadCommandSize( 466 const std::vector<std::string> &Options, bool is64Bit) 467 { 468 unsigned Size = sizeof(MachO::linker_option_command); 469 for (const std::string &Option : Options) 470 Size += Option.size() + 1; 471 return alignTo(Size, is64Bit ? 8 : 4); 472 } 473 474 void MachObjectWriter::writeLinkerOptionsLoadCommand( 475 const std::vector<std::string> &Options) 476 { 477 unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit()); 478 uint64_t Start = W.OS.tell(); 479 (void) Start; 480 481 W.write<uint32_t>(MachO::LC_LINKER_OPTION); 482 W.write<uint32_t>(Size); 483 W.write<uint32_t>(Options.size()); 484 uint64_t BytesWritten = sizeof(MachO::linker_option_command); 485 for (const std::string &Option : Options) { 486 // Write each string, including the null byte. 487 W.OS << Option << '\0'; 488 BytesWritten += Option.size() + 1; 489 } 490 491 // Pad to a multiple of the pointer size. 492 W.OS.write_zeros( 493 offsetToAlignment(BytesWritten, is64Bit() ? Align(8) : Align(4))); 494 495 assert(W.OS.tell() - Start == Size); 496 } 497 498 static bool isFixupTargetValid(const MCValue &Target) { 499 // Target is (LHS - RHS + cst). 500 // We don't support the form where LHS is null: -RHS + cst 501 if (!Target.getSymA() && Target.getSymB()) 502 return false; 503 return true; 504 } 505 506 void MachObjectWriter::recordRelocation(MCAssembler &Asm, 507 const MCFragment *Fragment, 508 const MCFixup &Fixup, MCValue Target, 509 uint64_t &FixedValue) { 510 if (!isFixupTargetValid(Target)) { 511 Asm.getContext().reportError(Fixup.getLoc(), 512 "unsupported relocation expression"); 513 return; 514 } 515 516 TargetObjectWriter->recordRelocation(this, Asm, Fragment, Fixup, Target, 517 FixedValue); 518 } 519 520 void MachObjectWriter::bindIndirectSymbols(MCAssembler &Asm) { 521 // This is the point where 'as' creates actual symbols for indirect symbols 522 // (in the following two passes). It would be easier for us to do this sooner 523 // when we see the attribute, but that makes getting the order in the symbol 524 // table much more complicated than it is worth. 525 // 526 // FIXME: Revisit this when the dust settles. 527 528 // Report errors for use of .indirect_symbol not in a symbol pointer section 529 // or stub section. 530 for (IndirectSymbolData &ISD : IndirectSymbols) { 531 const MCSectionMachO &Section = cast<MCSectionMachO>(*ISD.Section); 532 533 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS && 534 Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS && 535 Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS && 536 Section.getType() != MachO::S_SYMBOL_STUBS) { 537 MCSymbol &Symbol = *ISD.Symbol; 538 report_fatal_error("indirect symbol '" + Symbol.getName() + 539 "' not in a symbol pointer or stub section"); 540 } 541 } 542 543 // Bind non-lazy symbol pointers first. 544 for (auto [IndirectIndex, ISD] : enumerate(IndirectSymbols)) { 545 const auto &Section = cast<MCSectionMachO>(*ISD.Section); 546 547 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS && 548 Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS) 549 continue; 550 551 // Initialize the section indirect symbol base, if necessary. 552 IndirectSymBase.insert(std::make_pair(ISD.Section, IndirectIndex)); 553 554 Asm.registerSymbol(*ISD.Symbol); 555 } 556 557 // Then lazy symbol pointers and symbol stubs. 558 for (auto [IndirectIndex, ISD] : enumerate(IndirectSymbols)) { 559 const auto &Section = cast<MCSectionMachO>(*ISD.Section); 560 561 if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS && 562 Section.getType() != MachO::S_SYMBOL_STUBS) 563 continue; 564 565 // Initialize the section indirect symbol base, if necessary. 566 IndirectSymBase.insert(std::make_pair(ISD.Section, IndirectIndex)); 567 568 // Set the symbol type to undefined lazy, but only on construction. 569 // 570 // FIXME: Do not hardcode. 571 if (Asm.registerSymbol(*ISD.Symbol)) 572 cast<MCSymbolMachO>(ISD.Symbol)->setReferenceTypeUndefinedLazy(true); 573 } 574 } 575 576 /// computeSymbolTable - Compute the symbol table data 577 void MachObjectWriter::computeSymbolTable( 578 MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData, 579 std::vector<MachSymbolData> &ExternalSymbolData, 580 std::vector<MachSymbolData> &UndefinedSymbolData) { 581 // Build section lookup table. 582 DenseMap<const MCSection*, uint8_t> SectionIndexMap; 583 unsigned Index = 1; 584 for (MCSection &Sec : Asm) 585 SectionIndexMap[&Sec] = Index++; 586 assert(Index <= 256 && "Too many sections!"); 587 588 // Build the string table. 589 for (const MCSymbol &Symbol : Asm.symbols()) { 590 if (!cast<MCSymbolMachO>(Symbol).isSymbolLinkerVisible()) 591 continue; 592 593 StringTable.add(Symbol.getName()); 594 } 595 StringTable.finalize(); 596 597 // Build the symbol arrays but only for non-local symbols. 598 // 599 // The particular order that we collect and then sort the symbols is chosen to 600 // match 'as'. Even though it doesn't matter for correctness, this is 601 // important for letting us diff .o files. 602 for (const MCSymbol &Symbol : Asm.symbols()) { 603 // Ignore non-linker visible symbols. 604 if (!cast<MCSymbolMachO>(Symbol).isSymbolLinkerVisible()) 605 continue; 606 607 if (!Symbol.isExternal() && !Symbol.isUndefined()) 608 continue; 609 610 MachSymbolData MSD; 611 MSD.Symbol = &Symbol; 612 MSD.StringIndex = StringTable.getOffset(Symbol.getName()); 613 614 if (Symbol.isUndefined()) { 615 MSD.SectionIndex = 0; 616 UndefinedSymbolData.push_back(MSD); 617 } else if (Symbol.isAbsolute()) { 618 MSD.SectionIndex = 0; 619 ExternalSymbolData.push_back(MSD); 620 } else { 621 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection()); 622 assert(MSD.SectionIndex && "Invalid section index!"); 623 ExternalSymbolData.push_back(MSD); 624 } 625 } 626 627 // Now add the data for local symbols. 628 for (const MCSymbol &Symbol : Asm.symbols()) { 629 // Ignore non-linker visible symbols. 630 if (!cast<MCSymbolMachO>(Symbol).isSymbolLinkerVisible()) 631 continue; 632 633 if (Symbol.isExternal() || Symbol.isUndefined()) 634 continue; 635 636 MachSymbolData MSD; 637 MSD.Symbol = &Symbol; 638 MSD.StringIndex = StringTable.getOffset(Symbol.getName()); 639 640 if (Symbol.isAbsolute()) { 641 MSD.SectionIndex = 0; 642 LocalSymbolData.push_back(MSD); 643 } else { 644 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection()); 645 assert(MSD.SectionIndex && "Invalid section index!"); 646 LocalSymbolData.push_back(MSD); 647 } 648 } 649 650 // External and undefined symbols are required to be in lexicographic order. 651 llvm::sort(ExternalSymbolData); 652 llvm::sort(UndefinedSymbolData); 653 654 // Set the symbol indices. 655 Index = 0; 656 for (auto *SymbolData : 657 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData}) 658 for (MachSymbolData &Entry : *SymbolData) 659 Entry.Symbol->setIndex(Index++); 660 661 for (const MCSection &Section : Asm) { 662 for (RelAndSymbol &Rel : Relocations[&Section]) { 663 if (!Rel.Sym) 664 continue; 665 666 // Set the Index and the IsExtern bit. 667 unsigned Index = Rel.Sym->getIndex(); 668 assert(isInt<24>(Index)); 669 if (W.Endian == llvm::endianness::little) 670 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27); 671 else 672 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4); 673 } 674 } 675 } 676 677 void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm) { 678 // Assign layout order indices to sections. 679 unsigned i = 0; 680 // Compute the section layout order. Virtual sections must go last. 681 for (MCSection &Sec : Asm) { 682 if (!Sec.isVirtualSection()) { 683 SectionOrder.push_back(&Sec); 684 cast<MCSectionMachO>(Sec).setLayoutOrder(i++); 685 } 686 } 687 for (MCSection &Sec : Asm) { 688 if (Sec.isVirtualSection()) { 689 SectionOrder.push_back(&Sec); 690 cast<MCSectionMachO>(Sec).setLayoutOrder(i++); 691 } 692 } 693 694 uint64_t StartAddress = 0; 695 for (const MCSection *Sec : SectionOrder) { 696 StartAddress = alignTo(StartAddress, Sec->getAlign()); 697 SectionAddress[Sec] = StartAddress; 698 StartAddress += Asm.getSectionAddressSize(*Sec); 699 700 // Explicitly pad the section to match the alignment requirements of the 701 // following one. This is for 'gas' compatibility, it shouldn't 702 /// strictly be necessary. 703 StartAddress += getPaddingSize(Asm, Sec); 704 } 705 } 706 707 void MachObjectWriter::executePostLayoutBinding(MCAssembler &Asm) { 708 computeSectionAddresses(Asm); 709 710 // Create symbol data for any indirect symbols. 711 bindIndirectSymbols(Asm); 712 } 713 714 bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl( 715 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB, 716 bool InSet, bool IsPCRel) const { 717 if (InSet) 718 return true; 719 720 // The effective address is 721 // addr(atom(A)) + offset(A) 722 // - addr(atom(B)) - offset(B) 723 // and the offsets are not relocatable, so the fixup is fully resolved when 724 // addr(atom(A)) - addr(atom(B)) == 0. 725 const MCSymbol &SA = findAliasedSymbol(SymA); 726 const MCSection &SecA = SA.getSection(); 727 const MCSection &SecB = *FB.getParent(); 728 729 if (IsPCRel) { 730 // The simple (Darwin, except on x86_64) way of dealing with this was to 731 // assume that any reference to a temporary symbol *must* be a temporary 732 // symbol in the same atom, unless the sections differ. Therefore, any PCrel 733 // relocation to a temporary symbol (in the same section) is fully 734 // resolved. This also works in conjunction with absolutized .set, which 735 // requires the compiler to use .set to absolutize the differences between 736 // symbols which the compiler knows to be assembly time constants, so we 737 // don't need to worry about considering symbol differences fully resolved. 738 // 739 // If the file isn't using sub-sections-via-symbols, we can make the 740 // same assumptions about any symbol that we normally make about 741 // assembler locals. 742 743 bool hasReliableSymbolDifference = isX86_64(); 744 if (!hasReliableSymbolDifference) { 745 if (!SA.isInSection() || &SecA != &SecB || 746 (!SA.isTemporary() && FB.getAtom() != SA.getFragment()->getAtom() && 747 SubsectionsViaSymbols)) 748 return false; 749 return true; 750 } 751 } 752 753 // If they are not in the same section, we can't compute the diff. 754 if (&SecA != &SecB) 755 return false; 756 757 // If the atoms are the same, they are guaranteed to have the same address. 758 return SA.getFragment()->getAtom() == FB.getAtom(); 759 } 760 761 static MachO::LoadCommandType getLCFromMCVM(MCVersionMinType Type) { 762 switch (Type) { 763 case MCVM_OSXVersionMin: return MachO::LC_VERSION_MIN_MACOSX; 764 case MCVM_IOSVersionMin: return MachO::LC_VERSION_MIN_IPHONEOS; 765 case MCVM_TvOSVersionMin: return MachO::LC_VERSION_MIN_TVOS; 766 case MCVM_WatchOSVersionMin: return MachO::LC_VERSION_MIN_WATCHOS; 767 } 768 llvm_unreachable("Invalid mc version min type"); 769 } 770 771 void MachObjectWriter::populateAddrSigSection(MCAssembler &Asm) { 772 MCSection *AddrSigSection = 773 Asm.getContext().getObjectFileInfo()->getAddrSigSection(); 774 unsigned Log2Size = is64Bit() ? 3 : 2; 775 for (const MCSymbol *S : getAddrsigSyms()) { 776 if (!S->isRegistered()) 777 continue; 778 MachO::any_relocation_info MRE; 779 MRE.r_word0 = 0; 780 MRE.r_word1 = (Log2Size << 25) | (MachO::GENERIC_RELOC_VANILLA << 28); 781 addRelocation(S, AddrSigSection, MRE); 782 } 783 } 784 785 uint64_t MachObjectWriter::writeObject(MCAssembler &Asm) { 786 uint64_t StartOffset = W.OS.tell(); 787 auto NumBytesWritten = [&] { return W.OS.tell() - StartOffset; }; 788 789 populateAddrSigSection(Asm); 790 791 // Compute symbol table information and bind symbol indices. 792 computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData, 793 UndefinedSymbolData); 794 795 if (!CGProfile.empty()) { 796 MCSection *CGProfileSection = Asm.getContext().getMachOSection( 797 "__LLVM", "__cg_profile", 0, SectionKind::getMetadata()); 798 auto &Frag = cast<MCDataFragment>(*CGProfileSection->begin()); 799 Frag.getContents().clear(); 800 raw_svector_ostream OS(Frag.getContents()); 801 for (const MCObjectWriter::CGProfileEntry &CGPE : CGProfile) { 802 uint32_t FromIndex = CGPE.From->getSymbol().getIndex(); 803 uint32_t ToIndex = CGPE.To->getSymbol().getIndex(); 804 support::endian::write(OS, FromIndex, W.Endian); 805 support::endian::write(OS, ToIndex, W.Endian); 806 support::endian::write(OS, CGPE.Count, W.Endian); 807 } 808 } 809 810 unsigned NumSections = Asm.end() - Asm.begin(); 811 812 // The section data starts after the header, the segment load command (and 813 // section headers) and the symbol table. 814 unsigned NumLoadCommands = 1; 815 uint64_t LoadCommandsSize = is64Bit() ? 816 sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64): 817 sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section); 818 819 // Add the deployment target version info load command size, if used. 820 if (VersionInfo.Major != 0) { 821 ++NumLoadCommands; 822 if (VersionInfo.EmitBuildVersion) 823 LoadCommandsSize += sizeof(MachO::build_version_command); 824 else 825 LoadCommandsSize += sizeof(MachO::version_min_command); 826 } 827 828 // Add the target variant version info load command size, if used. 829 if (TargetVariantVersionInfo.Major != 0) { 830 ++NumLoadCommands; 831 assert(TargetVariantVersionInfo.EmitBuildVersion && 832 "target variant should use build version"); 833 LoadCommandsSize += sizeof(MachO::build_version_command); 834 } 835 836 // Add the data-in-code load command size, if used. 837 unsigned NumDataRegions = DataRegions.size(); 838 if (NumDataRegions) { 839 ++NumLoadCommands; 840 LoadCommandsSize += sizeof(MachO::linkedit_data_command); 841 } 842 843 // Add the loh load command size, if used. 844 uint64_t LOHRawSize = LOHContainer.getEmitSize(Asm, *this); 845 uint64_t LOHSize = alignTo(LOHRawSize, is64Bit() ? 8 : 4); 846 if (LOHSize) { 847 ++NumLoadCommands; 848 LoadCommandsSize += sizeof(MachO::linkedit_data_command); 849 } 850 851 // Add the symbol table load command sizes, if used. 852 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() + 853 UndefinedSymbolData.size(); 854 if (NumSymbols) { 855 NumLoadCommands += 2; 856 LoadCommandsSize += (sizeof(MachO::symtab_command) + 857 sizeof(MachO::dysymtab_command)); 858 } 859 860 // Add the linker option load commands sizes. 861 for (const auto &Option : LinkerOptions) { 862 ++NumLoadCommands; 863 LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Option, is64Bit()); 864 } 865 866 // Compute the total size of the section data, as well as its file size and vm 867 // size. 868 uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) : 869 sizeof(MachO::mach_header)) + LoadCommandsSize; 870 uint64_t SectionDataSize = 0; 871 uint64_t SectionDataFileSize = 0; 872 uint64_t VMSize = 0; 873 for (const MCSection &Sec : Asm) { 874 uint64_t Address = getSectionAddress(&Sec); 875 uint64_t Size = Asm.getSectionAddressSize(Sec); 876 uint64_t FileSize = Asm.getSectionFileSize(Sec); 877 FileSize += getPaddingSize(Asm, &Sec); 878 879 VMSize = std::max(VMSize, Address + Size); 880 881 if (Sec.isVirtualSection()) 882 continue; 883 884 SectionDataSize = std::max(SectionDataSize, Address + Size); 885 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize); 886 } 887 888 // The section data is padded to pointer size bytes. 889 // 890 // FIXME: Is this machine dependent? 891 unsigned SectionDataPadding = 892 offsetToAlignment(SectionDataFileSize, is64Bit() ? Align(8) : Align(4)); 893 SectionDataFileSize += SectionDataPadding; 894 895 // Write the prolog, starting with the header and load command... 896 writeHeader(MachO::MH_OBJECT, NumLoadCommands, LoadCommandsSize, 897 SubsectionsViaSymbols); 898 uint32_t Prot = 899 MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE; 900 writeSegmentLoadCommand("", NumSections, 0, VMSize, SectionDataStart, 901 SectionDataSize, Prot, Prot); 902 903 // ... and then the section headers. 904 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize; 905 for (const MCSection &Section : Asm) { 906 const auto &Sec = cast<MCSectionMachO>(Section); 907 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec]; 908 unsigned NumRelocs = Relocs.size(); 909 uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec); 910 unsigned Flags = Sec.getTypeAndAttributes(); 911 if (Sec.hasInstructions()) 912 Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS; 913 if (!cast<MCSectionMachO>(Sec).isVirtualSection() && 914 !isUInt<32>(SectionStart)) { 915 Asm.getContext().reportError( 916 SMLoc(), "cannot encode offset of section; object file too large"); 917 return NumBytesWritten(); 918 } 919 if (NumRelocs && !isUInt<32>(RelocTableEnd)) { 920 Asm.getContext().reportError( 921 SMLoc(), 922 "cannot encode offset of relocations; object file too large"); 923 return NumBytesWritten(); 924 } 925 writeSection(Asm, Sec, getSectionAddress(&Sec), SectionStart, Flags, 926 RelocTableEnd, NumRelocs); 927 RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info); 928 } 929 930 // Write out the deployment target information, if it's available. 931 auto EmitDeploymentTargetVersion = 932 [&](const VersionInfoType &VersionInfo) { 933 auto EncodeVersion = [](VersionTuple V) -> uint32_t { 934 assert(!V.empty() && "empty version"); 935 unsigned Update = V.getSubminor().value_or(0); 936 unsigned Minor = V.getMinor().value_or(0); 937 assert(Update < 256 && "unencodable update target version"); 938 assert(Minor < 256 && "unencodable minor target version"); 939 assert(V.getMajor() < 65536 && "unencodable major target version"); 940 return Update | (Minor << 8) | (V.getMajor() << 16); 941 }; 942 uint32_t EncodedVersion = EncodeVersion(VersionTuple( 943 VersionInfo.Major, VersionInfo.Minor, VersionInfo.Update)); 944 uint32_t SDKVersion = !VersionInfo.SDKVersion.empty() 945 ? EncodeVersion(VersionInfo.SDKVersion) 946 : 0; 947 if (VersionInfo.EmitBuildVersion) { 948 // FIXME: Currently empty tools. Add clang version in the future. 949 W.write<uint32_t>(MachO::LC_BUILD_VERSION); 950 W.write<uint32_t>(sizeof(MachO::build_version_command)); 951 W.write<uint32_t>(VersionInfo.TypeOrPlatform.Platform); 952 W.write<uint32_t>(EncodedVersion); 953 W.write<uint32_t>(SDKVersion); 954 W.write<uint32_t>(0); // Empty tools list. 955 } else { 956 MachO::LoadCommandType LCType = 957 getLCFromMCVM(VersionInfo.TypeOrPlatform.Type); 958 W.write<uint32_t>(LCType); 959 W.write<uint32_t>(sizeof(MachO::version_min_command)); 960 W.write<uint32_t>(EncodedVersion); 961 W.write<uint32_t>(SDKVersion); 962 } 963 }; 964 if (VersionInfo.Major != 0) 965 EmitDeploymentTargetVersion(VersionInfo); 966 if (TargetVariantVersionInfo.Major != 0) 967 EmitDeploymentTargetVersion(TargetVariantVersionInfo); 968 969 // Write the data-in-code load command, if used. 970 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8; 971 if (NumDataRegions) { 972 uint64_t DataRegionsOffset = RelocTableEnd; 973 uint64_t DataRegionsSize = NumDataRegions * 8; 974 writeLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset, 975 DataRegionsSize); 976 } 977 978 // Write the loh load command, if used. 979 uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize; 980 if (LOHSize) 981 writeLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT, 982 DataInCodeTableEnd, LOHSize); 983 984 // Write the symbol table load command, if used. 985 if (NumSymbols) { 986 unsigned FirstLocalSymbol = 0; 987 unsigned NumLocalSymbols = LocalSymbolData.size(); 988 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols; 989 unsigned NumExternalSymbols = ExternalSymbolData.size(); 990 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols; 991 unsigned NumUndefinedSymbols = UndefinedSymbolData.size(); 992 unsigned NumIndirectSymbols = IndirectSymbols.size(); 993 unsigned NumSymTabSymbols = 994 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols; 995 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4; 996 uint64_t IndirectSymbolOffset = 0; 997 998 // If used, the indirect symbols are written after the section data. 999 if (NumIndirectSymbols) 1000 IndirectSymbolOffset = LOHTableEnd; 1001 1002 // The symbol table is written after the indirect symbol data. 1003 uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize; 1004 1005 // The string table is written after symbol table. 1006 uint64_t StringTableOffset = 1007 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ? 1008 sizeof(MachO::nlist_64) : 1009 sizeof(MachO::nlist)); 1010 writeSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols, 1011 StringTableOffset, StringTable.getSize()); 1012 1013 writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols, 1014 FirstExternalSymbol, NumExternalSymbols, 1015 FirstUndefinedSymbol, NumUndefinedSymbols, 1016 IndirectSymbolOffset, NumIndirectSymbols); 1017 } 1018 1019 // Write the linker options load commands. 1020 for (const auto &Option : LinkerOptions) 1021 writeLinkerOptionsLoadCommand(Option); 1022 1023 // Write the actual section data. 1024 for (const MCSection &Sec : Asm) { 1025 Asm.writeSectionData(W.OS, &Sec); 1026 1027 uint64_t Pad = getPaddingSize(Asm, &Sec); 1028 W.OS.write_zeros(Pad); 1029 } 1030 1031 // Write the extra padding. 1032 W.OS.write_zeros(SectionDataPadding); 1033 1034 // Write the relocation entries. 1035 for (const MCSection &Sec : Asm) { 1036 // Write the section relocation entries, in reverse order to match 'as' 1037 // (approximately, the exact algorithm is more complicated than this). 1038 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec]; 1039 for (const RelAndSymbol &Rel : llvm::reverse(Relocs)) { 1040 W.write<uint32_t>(Rel.MRE.r_word0); 1041 W.write<uint32_t>(Rel.MRE.r_word1); 1042 } 1043 } 1044 1045 // Write out the data-in-code region payload, if there is one. 1046 for (DataRegionData Data : DataRegions) { 1047 uint64_t Start = getSymbolAddress(*Data.Start, Asm); 1048 uint64_t End; 1049 if (Data.End) 1050 End = getSymbolAddress(*Data.End, Asm); 1051 else 1052 report_fatal_error("Data region not terminated"); 1053 1054 LLVM_DEBUG(dbgs() << "data in code region-- kind: " << Data.Kind 1055 << " start: " << Start << "(" << Data.Start->getName() 1056 << ")" << " end: " << End << "(" << Data.End->getName() 1057 << ")" << " size: " << End - Start << "\n"); 1058 W.write<uint32_t>(Start); 1059 W.write<uint16_t>(End - Start); 1060 W.write<uint16_t>(Data.Kind); 1061 } 1062 1063 // Write out the loh commands, if there is one. 1064 if (LOHSize) { 1065 #ifndef NDEBUG 1066 unsigned Start = W.OS.tell(); 1067 #endif 1068 LOHContainer.emit(Asm, *this); 1069 // Pad to a multiple of the pointer size. 1070 W.OS.write_zeros( 1071 offsetToAlignment(LOHRawSize, is64Bit() ? Align(8) : Align(4))); 1072 assert(W.OS.tell() - Start == LOHSize); 1073 } 1074 1075 // Write the symbol table data, if used. 1076 if (NumSymbols) { 1077 // Write the indirect symbol entries. 1078 for (auto &ISD : IndirectSymbols) { 1079 // Indirect symbols in the non-lazy symbol pointer section have some 1080 // special handling. 1081 const MCSectionMachO &Section = 1082 static_cast<const MCSectionMachO &>(*ISD.Section); 1083 if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) { 1084 // If this symbol is defined and internal, mark it as such. 1085 if (ISD.Symbol->isDefined() && !ISD.Symbol->isExternal()) { 1086 uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL; 1087 if (ISD.Symbol->isAbsolute()) 1088 Flags |= MachO::INDIRECT_SYMBOL_ABS; 1089 W.write<uint32_t>(Flags); 1090 continue; 1091 } 1092 } 1093 1094 W.write<uint32_t>(ISD.Symbol->getIndex()); 1095 } 1096 1097 // FIXME: Check that offsets match computed ones. 1098 1099 // Write the symbol table entries. 1100 for (auto *SymbolData : 1101 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData}) 1102 for (MachSymbolData &Entry : *SymbolData) 1103 writeNlist(Entry, Asm); 1104 1105 // Write the string table. 1106 StringTable.write(W.OS); 1107 } 1108 1109 return NumBytesWritten(); 1110 } 1111 1112 std::unique_ptr<MCObjectWriter> 1113 llvm::createMachObjectWriter(std::unique_ptr<MCMachObjectTargetWriter> MOTW, 1114 raw_pwrite_stream &OS, bool IsLittleEndian) { 1115 return std::make_unique<MachObjectWriter>(std::move(MOTW), OS, 1116 IsLittleEndian); 1117 } 1118