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