1 //===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/MC/MCMachObjectWriter.h" 11 #include "llvm/ADT/StringMap.h" 12 #include "llvm/ADT/Twine.h" 13 #include "llvm/MC/MCAsmBackend.h" 14 #include "llvm/MC/MCAsmLayout.h" 15 #include "llvm/MC/MCAssembler.h" 16 #include "llvm/MC/MCExpr.h" 17 #include "llvm/MC/MCFixupKindInfo.h" 18 #include "llvm/MC/MCMachOSymbolFlags.h" 19 #include "llvm/MC/MCObjectWriter.h" 20 #include "llvm/MC/MCSectionMachO.h" 21 #include "llvm/MC/MCSymbol.h" 22 #include "llvm/MC/MCValue.h" 23 #include "llvm/Object/MachOFormat.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/ErrorHandling.h" 26 #include <vector> 27 using namespace llvm; 28 using namespace llvm::object; 29 30 bool MachObjectWriter:: 31 doesSymbolRequireExternRelocation(const MCSymbolData *SD) { 32 // Undefined symbols are always extern. 33 if (SD->Symbol->isUndefined()) 34 return true; 35 36 // References to weak definitions require external relocation entries; the 37 // definition may not always be the one in the same object file. 38 if (SD->getFlags() & SF_WeakDefinition) 39 return true; 40 41 // Otherwise, we can use an internal relocation. 42 return false; 43 } 44 45 bool MachObjectWriter:: 46 MachSymbolData::operator<(const MachSymbolData &RHS) const { 47 return SymbolData->getSymbol().getName() < 48 RHS.SymbolData->getSymbol().getName(); 49 } 50 51 bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) { 52 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo( 53 (MCFixupKind) Kind); 54 55 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel; 56 } 57 58 uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment, 59 const MCAsmLayout &Layout) const { 60 return getSectionAddress(Fragment->getParent()) + 61 Layout.getFragmentOffset(Fragment); 62 } 63 64 uint64_t MachObjectWriter::getSymbolAddress(const MCSymbolData* SD, 65 const MCAsmLayout &Layout) const { 66 const MCSymbol &S = SD->getSymbol(); 67 68 // If this is a variable, then recursively evaluate now. 69 if (S.isVariable()) { 70 if (const MCConstantExpr *C = 71 dyn_cast<const MCConstantExpr>(S.getVariableValue())) 72 return C->getValue(); 73 74 75 MCValue Target; 76 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, Layout)) 77 report_fatal_error("unable to evaluate offset for variable '" + 78 S.getName() + "'"); 79 80 // Verify that any used symbols are defined. 81 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined()) 82 report_fatal_error("unable to evaluate offset to undefined symbol '" + 83 Target.getSymA()->getSymbol().getName() + "'"); 84 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined()) 85 report_fatal_error("unable to evaluate offset to undefined symbol '" + 86 Target.getSymB()->getSymbol().getName() + "'"); 87 88 uint64_t Address = Target.getConstant(); 89 if (Target.getSymA()) 90 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData( 91 Target.getSymA()->getSymbol()), Layout); 92 if (Target.getSymB()) 93 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData( 94 Target.getSymB()->getSymbol()), Layout); 95 return Address; 96 } 97 98 return getSectionAddress(SD->getFragment()->getParent()) + 99 Layout.getSymbolOffset(SD); 100 } 101 102 uint64_t MachObjectWriter::getPaddingSize(const MCSectionData *SD, 103 const MCAsmLayout &Layout) const { 104 uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD); 105 unsigned Next = SD->getLayoutOrder() + 1; 106 if (Next >= Layout.getSectionOrder().size()) 107 return 0; 108 109 const MCSectionData &NextSD = *Layout.getSectionOrder()[Next]; 110 if (NextSD.getSection().isVirtualSection()) 111 return 0; 112 return OffsetToAlignment(EndAddr, NextSD.getAlignment()); 113 } 114 115 void MachObjectWriter::WriteHeader(unsigned NumLoadCommands, 116 unsigned LoadCommandsSize, 117 bool SubsectionsViaSymbols) { 118 uint32_t Flags = 0; 119 120 if (SubsectionsViaSymbols) 121 Flags |= macho::HF_SubsectionsViaSymbols; 122 123 // struct mach_header (28 bytes) or 124 // struct mach_header_64 (32 bytes) 125 126 uint64_t Start = OS.tell(); 127 (void) Start; 128 129 Write32(is64Bit() ? macho::HM_Object64 : macho::HM_Object32); 130 131 Write32(TargetObjectWriter->getCPUType()); 132 Write32(TargetObjectWriter->getCPUSubtype()); 133 134 Write32(macho::HFT_Object); 135 Write32(NumLoadCommands); 136 Write32(LoadCommandsSize); 137 Write32(Flags); 138 if (is64Bit()) 139 Write32(0); // reserved 140 141 assert(OS.tell() - Start == 142 (is64Bit() ? macho::Header64Size : macho::Header32Size)); 143 } 144 145 /// WriteSegmentLoadCommand - Write a segment load command. 146 /// 147 /// \param NumSections The number of sections in this segment. 148 /// \param SectionDataSize The total size of the sections. 149 void MachObjectWriter::WriteSegmentLoadCommand(unsigned NumSections, 150 uint64_t VMSize, 151 uint64_t SectionDataStartOffset, 152 uint64_t SectionDataSize) { 153 // struct segment_command (56 bytes) or 154 // struct segment_command_64 (72 bytes) 155 156 uint64_t Start = OS.tell(); 157 (void) Start; 158 159 unsigned SegmentLoadCommandSize = 160 is64Bit() ? macho::SegmentLoadCommand64Size: 161 macho::SegmentLoadCommand32Size; 162 Write32(is64Bit() ? macho::LCT_Segment64 : macho::LCT_Segment); 163 Write32(SegmentLoadCommandSize + 164 NumSections * (is64Bit() ? macho::Section64Size : 165 macho::Section32Size)); 166 167 WriteBytes("", 16); 168 if (is64Bit()) { 169 Write64(0); // vmaddr 170 Write64(VMSize); // vmsize 171 Write64(SectionDataStartOffset); // file offset 172 Write64(SectionDataSize); // file size 173 } else { 174 Write32(0); // vmaddr 175 Write32(VMSize); // vmsize 176 Write32(SectionDataStartOffset); // file offset 177 Write32(SectionDataSize); // file size 178 } 179 Write32(0x7); // maxprot 180 Write32(0x7); // initprot 181 Write32(NumSections); 182 Write32(0); // flags 183 184 assert(OS.tell() - Start == SegmentLoadCommandSize); 185 } 186 187 void MachObjectWriter::WriteSection(const MCAssembler &Asm, 188 const MCAsmLayout &Layout, 189 const MCSectionData &SD, 190 uint64_t FileOffset, 191 uint64_t RelocationsStart, 192 unsigned NumRelocations) { 193 uint64_t SectionSize = Layout.getSectionAddressSize(&SD); 194 195 // The offset is unused for virtual sections. 196 if (SD.getSection().isVirtualSection()) { 197 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!"); 198 FileOffset = 0; 199 } 200 201 // struct section (68 bytes) or 202 // struct section_64 (80 bytes) 203 204 uint64_t Start = OS.tell(); 205 (void) Start; 206 207 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection()); 208 WriteBytes(Section.getSectionName(), 16); 209 WriteBytes(Section.getSegmentName(), 16); 210 if (is64Bit()) { 211 Write64(getSectionAddress(&SD)); // address 212 Write64(SectionSize); // size 213 } else { 214 Write32(getSectionAddress(&SD)); // address 215 Write32(SectionSize); // size 216 } 217 Write32(FileOffset); 218 219 unsigned Flags = Section.getTypeAndAttributes(); 220 if (SD.hasInstructions()) 221 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS; 222 223 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!"); 224 Write32(Log2_32(SD.getAlignment())); 225 Write32(NumRelocations ? RelocationsStart : 0); 226 Write32(NumRelocations); 227 Write32(Flags); 228 Write32(IndirectSymBase.lookup(&SD)); // reserved1 229 Write32(Section.getStubSize()); // reserved2 230 if (is64Bit()) 231 Write32(0); // reserved3 232 233 assert(OS.tell() - Start == (is64Bit() ? macho::Section64Size : 234 macho::Section32Size)); 235 } 236 237 void MachObjectWriter::WriteSymtabLoadCommand(uint32_t SymbolOffset, 238 uint32_t NumSymbols, 239 uint32_t StringTableOffset, 240 uint32_t StringTableSize) { 241 // struct symtab_command (24 bytes) 242 243 uint64_t Start = OS.tell(); 244 (void) Start; 245 246 Write32(macho::LCT_Symtab); 247 Write32(macho::SymtabLoadCommandSize); 248 Write32(SymbolOffset); 249 Write32(NumSymbols); 250 Write32(StringTableOffset); 251 Write32(StringTableSize); 252 253 assert(OS.tell() - Start == macho::SymtabLoadCommandSize); 254 } 255 256 void MachObjectWriter::WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol, 257 uint32_t NumLocalSymbols, 258 uint32_t FirstExternalSymbol, 259 uint32_t NumExternalSymbols, 260 uint32_t FirstUndefinedSymbol, 261 uint32_t NumUndefinedSymbols, 262 uint32_t IndirectSymbolOffset, 263 uint32_t NumIndirectSymbols) { 264 // struct dysymtab_command (80 bytes) 265 266 uint64_t Start = OS.tell(); 267 (void) Start; 268 269 Write32(macho::LCT_Dysymtab); 270 Write32(macho::DysymtabLoadCommandSize); 271 Write32(FirstLocalSymbol); 272 Write32(NumLocalSymbols); 273 Write32(FirstExternalSymbol); 274 Write32(NumExternalSymbols); 275 Write32(FirstUndefinedSymbol); 276 Write32(NumUndefinedSymbols); 277 Write32(0); // tocoff 278 Write32(0); // ntoc 279 Write32(0); // modtaboff 280 Write32(0); // nmodtab 281 Write32(0); // extrefsymoff 282 Write32(0); // nextrefsyms 283 Write32(IndirectSymbolOffset); 284 Write32(NumIndirectSymbols); 285 Write32(0); // extreloff 286 Write32(0); // nextrel 287 Write32(0); // locreloff 288 Write32(0); // nlocrel 289 290 assert(OS.tell() - Start == macho::DysymtabLoadCommandSize); 291 } 292 293 void MachObjectWriter::WriteNlist(MachSymbolData &MSD, 294 const MCAsmLayout &Layout) { 295 MCSymbolData &Data = *MSD.SymbolData; 296 const MCSymbol &Symbol = Data.getSymbol(); 297 uint8_t Type = 0; 298 uint16_t Flags = Data.getFlags(); 299 uint64_t Address = 0; 300 301 // Set the N_TYPE bits. See <mach-o/nlist.h>. 302 // 303 // FIXME: Are the prebound or indirect fields possible here? 304 if (Symbol.isUndefined()) 305 Type = macho::STT_Undefined; 306 else if (Symbol.isAbsolute()) 307 Type = macho::STT_Absolute; 308 else 309 Type = macho::STT_Section; 310 311 // FIXME: Set STAB bits. 312 313 if (Data.isPrivateExtern()) 314 Type |= macho::STF_PrivateExtern; 315 316 // Set external bit. 317 if (Data.isExternal() || Symbol.isUndefined()) 318 Type |= macho::STF_External; 319 320 // Compute the symbol address. 321 if (Symbol.isDefined()) { 322 Address = getSymbolAddress(&Data, Layout); 323 } else if (Data.isCommon()) { 324 // Common symbols are encoded with the size in the address 325 // field, and their alignment in the flags. 326 Address = Data.getCommonSize(); 327 328 // Common alignment is packed into the 'desc' bits. 329 if (unsigned Align = Data.getCommonAlignment()) { 330 unsigned Log2Size = Log2_32(Align); 331 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!"); 332 if (Log2Size > 15) 333 report_fatal_error("invalid 'common' alignment '" + 334 Twine(Align) + "'"); 335 // FIXME: Keep this mask with the SymbolFlags enumeration. 336 Flags = (Flags & 0xF0FF) | (Log2Size << 8); 337 } 338 } 339 340 // struct nlist (12 bytes) 341 342 Write32(MSD.StringIndex); 343 Write8(Type); 344 Write8(MSD.SectionIndex); 345 346 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc' 347 // value. 348 Write16(Flags); 349 if (is64Bit()) 350 Write64(Address); 351 else 352 Write32(Address); 353 } 354 355 void MachObjectWriter::WriteLinkeditLoadCommand(uint32_t Type, 356 uint32_t DataOffset, 357 uint32_t DataSize) { 358 uint64_t Start = OS.tell(); 359 (void) Start; 360 361 Write32(Type); 362 Write32(macho::LinkeditLoadCommandSize); 363 Write32(DataOffset); 364 Write32(DataSize); 365 366 assert(OS.tell() - Start == macho::LinkeditLoadCommandSize); 367 } 368 369 370 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm, 371 const MCAsmLayout &Layout, 372 const MCFragment *Fragment, 373 const MCFixup &Fixup, 374 MCValue Target, 375 uint64_t &FixedValue) { 376 TargetObjectWriter->RecordRelocation(this, Asm, Layout, Fragment, Fixup, 377 Target, FixedValue); 378 } 379 380 void MachObjectWriter::BindIndirectSymbols(MCAssembler &Asm) { 381 // This is the point where 'as' creates actual symbols for indirect symbols 382 // (in the following two passes). It would be easier for us to do this sooner 383 // when we see the attribute, but that makes getting the order in the symbol 384 // table much more complicated than it is worth. 385 // 386 // FIXME: Revisit this when the dust settles. 387 388 // Bind non lazy symbol pointers first. 389 unsigned IndirectIndex = 0; 390 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(), 391 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) { 392 const MCSectionMachO &Section = 393 cast<MCSectionMachO>(it->SectionData->getSection()); 394 395 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) 396 continue; 397 398 // Initialize the section indirect symbol base, if necessary. 399 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex)); 400 401 Asm.getOrCreateSymbolData(*it->Symbol); 402 } 403 404 // Then lazy symbol pointers and symbol stubs. 405 IndirectIndex = 0; 406 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(), 407 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) { 408 const MCSectionMachO &Section = 409 cast<MCSectionMachO>(it->SectionData->getSection()); 410 411 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS && 412 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS) 413 continue; 414 415 // Initialize the section indirect symbol base, if necessary. 416 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex)); 417 418 // Set the symbol type to undefined lazy, but only on construction. 419 // 420 // FIXME: Do not hardcode. 421 bool Created; 422 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created); 423 if (Created) 424 Entry.setFlags(Entry.getFlags() | 0x0001); 425 } 426 } 427 428 /// ComputeSymbolTable - Compute the symbol table data 429 /// 430 /// \param StringTable [out] - The string table data. 431 /// \param StringIndexMap [out] - Map from symbol names to offsets in the 432 /// string table. 433 void MachObjectWriter:: 434 ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable, 435 std::vector<MachSymbolData> &LocalSymbolData, 436 std::vector<MachSymbolData> &ExternalSymbolData, 437 std::vector<MachSymbolData> &UndefinedSymbolData) { 438 // Build section lookup table. 439 DenseMap<const MCSection*, uint8_t> SectionIndexMap; 440 unsigned Index = 1; 441 for (MCAssembler::iterator it = Asm.begin(), 442 ie = Asm.end(); it != ie; ++it, ++Index) 443 SectionIndexMap[&it->getSection()] = Index; 444 assert(Index <= 256 && "Too many sections!"); 445 446 // Index 0 is always the empty string. 447 StringMap<uint64_t> StringIndexMap; 448 StringTable += '\x00'; 449 450 // Build the symbol arrays and the string table, but only for non-local 451 // symbols. 452 // 453 // The particular order that we collect the symbols and create the string 454 // table, then sort the symbols is chosen to match 'as'. Even though it 455 // doesn't matter for correctness, this is important for letting us diff .o 456 // files. 457 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(), 458 ie = Asm.symbol_end(); it != ie; ++it) { 459 const MCSymbol &Symbol = it->getSymbol(); 460 461 // Ignore non-linker visible symbols. 462 if (!Asm.isSymbolLinkerVisible(it->getSymbol())) 463 continue; 464 465 if (!it->isExternal() && !Symbol.isUndefined()) 466 continue; 467 468 uint64_t &Entry = StringIndexMap[Symbol.getName()]; 469 if (!Entry) { 470 Entry = StringTable.size(); 471 StringTable += Symbol.getName(); 472 StringTable += '\x00'; 473 } 474 475 MachSymbolData MSD; 476 MSD.SymbolData = it; 477 MSD.StringIndex = Entry; 478 479 if (Symbol.isUndefined()) { 480 MSD.SectionIndex = 0; 481 UndefinedSymbolData.push_back(MSD); 482 } else if (Symbol.isAbsolute()) { 483 MSD.SectionIndex = 0; 484 ExternalSymbolData.push_back(MSD); 485 } else { 486 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection()); 487 assert(MSD.SectionIndex && "Invalid section index!"); 488 ExternalSymbolData.push_back(MSD); 489 } 490 } 491 492 // Now add the data for local symbols. 493 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(), 494 ie = Asm.symbol_end(); it != ie; ++it) { 495 const MCSymbol &Symbol = it->getSymbol(); 496 497 // Ignore non-linker visible symbols. 498 if (!Asm.isSymbolLinkerVisible(it->getSymbol())) 499 continue; 500 501 if (it->isExternal() || Symbol.isUndefined()) 502 continue; 503 504 uint64_t &Entry = StringIndexMap[Symbol.getName()]; 505 if (!Entry) { 506 Entry = StringTable.size(); 507 StringTable += Symbol.getName(); 508 StringTable += '\x00'; 509 } 510 511 MachSymbolData MSD; 512 MSD.SymbolData = it; 513 MSD.StringIndex = Entry; 514 515 if (Symbol.isAbsolute()) { 516 MSD.SectionIndex = 0; 517 LocalSymbolData.push_back(MSD); 518 } else { 519 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection()); 520 assert(MSD.SectionIndex && "Invalid section index!"); 521 LocalSymbolData.push_back(MSD); 522 } 523 } 524 525 // External and undefined symbols are required to be in lexicographic order. 526 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end()); 527 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end()); 528 529 // Set the symbol indices. 530 Index = 0; 531 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) 532 LocalSymbolData[i].SymbolData->setIndex(Index++); 533 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) 534 ExternalSymbolData[i].SymbolData->setIndex(Index++); 535 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) 536 UndefinedSymbolData[i].SymbolData->setIndex(Index++); 537 538 // The string table is padded to a multiple of 4. 539 while (StringTable.size() % 4) 540 StringTable += '\x00'; 541 } 542 543 void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm, 544 const MCAsmLayout &Layout) { 545 uint64_t StartAddress = 0; 546 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder(); 547 for (int i = 0, n = Order.size(); i != n ; ++i) { 548 const MCSectionData *SD = Order[i]; 549 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment()); 550 SectionAddress[SD] = StartAddress; 551 StartAddress += Layout.getSectionAddressSize(SD); 552 553 // Explicitly pad the section to match the alignment requirements of the 554 // following one. This is for 'gas' compatibility, it shouldn't 555 /// strictly be necessary. 556 StartAddress += getPaddingSize(SD, Layout); 557 } 558 } 559 560 void MachObjectWriter::markAbsoluteVariableSymbols(MCAssembler &Asm, 561 const MCAsmLayout &Layout) { 562 for (MCAssembler::symbol_iterator i = Asm.symbol_begin(), 563 e = Asm.symbol_end(); 564 i != e; ++i) { 565 MCSymbolData &SD = *i; 566 if (!SD.getSymbol().isVariable()) 567 continue; 568 569 // Is the variable is a symbol difference (SA - SB + C) expression, 570 // and neither symbol is external, mark the variable as absolute. 571 const MCExpr *Expr = SD.getSymbol().getVariableValue(); 572 MCValue Value; 573 if (Expr->EvaluateAsRelocatable(Value, Layout)) { 574 if (Value.getSymA() && Value.getSymB()) 575 const_cast<MCSymbol*>(&SD.getSymbol())->setAbsolute(); 576 } 577 } 578 } 579 580 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm, 581 const MCAsmLayout &Layout) { 582 computeSectionAddresses(Asm, Layout); 583 584 // Create symbol data for any indirect symbols. 585 BindIndirectSymbols(Asm); 586 587 // Mark symbol difference expressions in variables (from .set or = directives) 588 // as absolute. 589 markAbsoluteVariableSymbols(Asm, Layout); 590 591 // Compute symbol table information and bind symbol indices. 592 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData, 593 UndefinedSymbolData); 594 } 595 596 bool MachObjectWriter:: 597 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm, 598 const MCSymbolData &DataA, 599 const MCFragment &FB, 600 bool InSet, 601 bool IsPCRel) const { 602 if (InSet) 603 return true; 604 605 // The effective address is 606 // addr(atom(A)) + offset(A) 607 // - addr(atom(B)) - offset(B) 608 // and the offsets are not relocatable, so the fixup is fully resolved when 609 // addr(atom(A)) - addr(atom(B)) == 0. 610 const MCSymbolData *A_Base = 0, *B_Base = 0; 611 612 const MCSymbol &SA = DataA.getSymbol().AliasedSymbol(); 613 const MCSection &SecA = SA.getSection(); 614 const MCSection &SecB = FB.getParent()->getSection(); 615 616 if (IsPCRel) { 617 // The simple (Darwin, except on x86_64) way of dealing with this was to 618 // assume that any reference to a temporary symbol *must* be a temporary 619 // symbol in the same atom, unless the sections differ. Therefore, any PCrel 620 // relocation to a temporary symbol (in the same section) is fully 621 // resolved. This also works in conjunction with absolutized .set, which 622 // requires the compiler to use .set to absolutize the differences between 623 // symbols which the compiler knows to be assembly time constants, so we 624 // don't need to worry about considering symbol differences fully resolved. 625 // 626 // If the file isn't using sub-sections-via-symbols, we can make the 627 // same assumptions about any symbol that we normally make about 628 // assembler locals. 629 630 if (!Asm.getBackend().hasReliableSymbolDifference()) { 631 if (!SA.isInSection() || &SecA != &SecB || 632 (!SA.isTemporary() && 633 FB.getAtom() != Asm.getSymbolData(SA).getFragment()->getAtom() && 634 Asm.getSubsectionsViaSymbols())) 635 return false; 636 return true; 637 } 638 // For Darwin x86_64, there is one special case when the reference IsPCRel. 639 // If the fragment with the reference does not have a base symbol but meets 640 // the simple way of dealing with this, in that it is a temporary symbol in 641 // the same atom then it is assumed to be fully resolved. This is needed so 642 // a relocation entry is not created and so the static linker does not 643 // mess up the reference later. 644 else if(!FB.getAtom() && 645 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){ 646 return true; 647 } 648 } else { 649 if (!TargetObjectWriter->useAggressiveSymbolFolding()) 650 return false; 651 } 652 653 const MCFragment *FA = Asm.getSymbolData(SA).getFragment(); 654 655 // Bail if the symbol has no fragment. 656 if (!FA) 657 return false; 658 659 A_Base = FA->getAtom(); 660 if (!A_Base) 661 return false; 662 663 B_Base = FB.getAtom(); 664 if (!B_Base) 665 return false; 666 667 // If the atoms are the same, they are guaranteed to have the same address. 668 if (A_Base == B_Base) 669 return true; 670 671 // Otherwise, we can't prove this is fully resolved. 672 return false; 673 } 674 675 void MachObjectWriter::WriteObject(MCAssembler &Asm, 676 const MCAsmLayout &Layout) { 677 unsigned NumSections = Asm.size(); 678 679 // The section data starts after the header, the segment load command (and 680 // section headers) and the symbol table. 681 unsigned NumLoadCommands = 1; 682 uint64_t LoadCommandsSize = is64Bit() ? 683 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size : 684 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size; 685 686 // Add the symbol table load command sizes, if used. 687 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() + 688 UndefinedSymbolData.size(); 689 if (NumSymbols) { 690 NumLoadCommands += 2; 691 LoadCommandsSize += (macho::SymtabLoadCommandSize + 692 macho::DysymtabLoadCommandSize); 693 } 694 695 // Add the data-in-code load command size, if used. 696 unsigned NumDataRegions = Asm.getDataRegions().size(); 697 if (NumDataRegions) { 698 ++NumLoadCommands; 699 LoadCommandsSize += macho::LinkeditLoadCommandSize; 700 } 701 702 // Compute the total size of the section data, as well as its file size and vm 703 // size. 704 uint64_t SectionDataStart = (is64Bit() ? macho::Header64Size : 705 macho::Header32Size) + LoadCommandsSize; 706 uint64_t SectionDataSize = 0; 707 uint64_t SectionDataFileSize = 0; 708 uint64_t VMSize = 0; 709 for (MCAssembler::const_iterator it = Asm.begin(), 710 ie = Asm.end(); it != ie; ++it) { 711 const MCSectionData &SD = *it; 712 uint64_t Address = getSectionAddress(&SD); 713 uint64_t Size = Layout.getSectionAddressSize(&SD); 714 uint64_t FileSize = Layout.getSectionFileSize(&SD); 715 FileSize += getPaddingSize(&SD, Layout); 716 717 VMSize = std::max(VMSize, Address + Size); 718 719 if (SD.getSection().isVirtualSection()) 720 continue; 721 722 SectionDataSize = std::max(SectionDataSize, Address + Size); 723 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize); 724 } 725 726 // The section data is padded to 4 bytes. 727 // 728 // FIXME: Is this machine dependent? 729 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4); 730 SectionDataFileSize += SectionDataPadding; 731 732 // Write the prolog, starting with the header and load command... 733 WriteHeader(NumLoadCommands, LoadCommandsSize, 734 Asm.getSubsectionsViaSymbols()); 735 WriteSegmentLoadCommand(NumSections, VMSize, 736 SectionDataStart, SectionDataSize); 737 738 // ... and then the section headers. 739 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize; 740 for (MCAssembler::const_iterator it = Asm.begin(), 741 ie = Asm.end(); it != ie; ++it) { 742 std::vector<macho::RelocationEntry> &Relocs = Relocations[it]; 743 unsigned NumRelocs = Relocs.size(); 744 uint64_t SectionStart = SectionDataStart + getSectionAddress(it); 745 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs); 746 RelocTableEnd += NumRelocs * macho::RelocationInfoSize; 747 } 748 749 // Write the data-in-code load command, if used. 750 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8; 751 if (NumDataRegions) { 752 uint64_t DataRegionsOffset = RelocTableEnd; 753 uint64_t DataRegionsSize = NumDataRegions * 8; 754 WriteLinkeditLoadCommand(macho::LCT_DataInCode, DataRegionsOffset, 755 DataRegionsSize); 756 } 757 758 // Write the symbol table load command, if used. 759 if (NumSymbols) { 760 unsigned FirstLocalSymbol = 0; 761 unsigned NumLocalSymbols = LocalSymbolData.size(); 762 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols; 763 unsigned NumExternalSymbols = ExternalSymbolData.size(); 764 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols; 765 unsigned NumUndefinedSymbols = UndefinedSymbolData.size(); 766 unsigned NumIndirectSymbols = Asm.indirect_symbol_size(); 767 unsigned NumSymTabSymbols = 768 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols; 769 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4; 770 uint64_t IndirectSymbolOffset = 0; 771 772 // If used, the indirect symbols are written after the section data. 773 if (NumIndirectSymbols) 774 IndirectSymbolOffset = DataInCodeTableEnd; 775 776 // The symbol table is written after the indirect symbol data. 777 uint64_t SymbolTableOffset = DataInCodeTableEnd + IndirectSymbolSize; 778 779 // The string table is written after symbol table. 780 uint64_t StringTableOffset = 781 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ? macho::Nlist64Size : 782 macho::Nlist32Size); 783 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols, 784 StringTableOffset, StringTable.size()); 785 786 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols, 787 FirstExternalSymbol, NumExternalSymbols, 788 FirstUndefinedSymbol, NumUndefinedSymbols, 789 IndirectSymbolOffset, NumIndirectSymbols); 790 } 791 792 // Write the actual section data. 793 for (MCAssembler::const_iterator it = Asm.begin(), 794 ie = Asm.end(); it != ie; ++it) { 795 Asm.writeSectionData(it, Layout); 796 797 uint64_t Pad = getPaddingSize(it, Layout); 798 for (unsigned int i = 0; i < Pad; ++i) 799 Write8(0); 800 } 801 802 // Write the extra padding. 803 WriteZeros(SectionDataPadding); 804 805 // Write the relocation entries. 806 for (MCAssembler::const_iterator it = Asm.begin(), 807 ie = Asm.end(); it != ie; ++it) { 808 // Write the section relocation entries, in reverse order to match 'as' 809 // (approximately, the exact algorithm is more complicated than this). 810 std::vector<macho::RelocationEntry> &Relocs = Relocations[it]; 811 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) { 812 Write32(Relocs[e - i - 1].Word0); 813 Write32(Relocs[e - i - 1].Word1); 814 } 815 } 816 817 // Write out the data-in-code region payload, if there is one. 818 for (MCAssembler::const_data_region_iterator 819 it = Asm.data_region_begin(), ie = Asm.data_region_end(); 820 it != ie; ++it) { 821 const DataRegionData *Data = &(*it); 822 uint64_t Start = 823 getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->Start), 824 Layout); 825 uint64_t End = 826 getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->End), 827 Layout); 828 DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind 829 << " start: " << Start << "(" << Data->Start->getName() << ")" 830 << " end: " << End << "(" << Data->End->getName() << ")" 831 << " size: " << End - Start 832 << "\n"); 833 Write32(Start); 834 Write16(End - Start); 835 Write16(Data->Kind); 836 } 837 838 // Write the symbol table data, if used. 839 if (NumSymbols) { 840 // Write the indirect symbol entries. 841 for (MCAssembler::const_indirect_symbol_iterator 842 it = Asm.indirect_symbol_begin(), 843 ie = Asm.indirect_symbol_end(); it != ie; ++it) { 844 // Indirect symbols in the non lazy symbol pointer section have some 845 // special handling. 846 const MCSectionMachO &Section = 847 static_cast<const MCSectionMachO&>(it->SectionData->getSection()); 848 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) { 849 // If this symbol is defined and internal, mark it as such. 850 if (it->Symbol->isDefined() && 851 !Asm.getSymbolData(*it->Symbol).isExternal()) { 852 uint32_t Flags = macho::ISF_Local; 853 if (it->Symbol->isAbsolute()) 854 Flags |= macho::ISF_Absolute; 855 Write32(Flags); 856 continue; 857 } 858 } 859 860 Write32(Asm.getSymbolData(*it->Symbol).getIndex()); 861 } 862 863 // FIXME: Check that offsets match computed ones. 864 865 // Write the symbol table entries. 866 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) 867 WriteNlist(LocalSymbolData[i], Layout); 868 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) 869 WriteNlist(ExternalSymbolData[i], Layout); 870 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) 871 WriteNlist(UndefinedSymbolData[i], Layout); 872 873 // Write the string table. 874 OS << StringTable.str(); 875 } 876 } 877 878 MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW, 879 raw_ostream &OS, 880 bool IsLittleEndian) { 881 return new MachObjectWriter(MOTW, OS, IsLittleEndian); 882 } 883