1 //===- Writer.cpp ---------------------------------------------------------===// 2 // 3 // The LLVM Linker 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 "Writer.h" 11 #include "Config.h" 12 #include "Filesystem.h" 13 #include "LinkerScript.h" 14 #include "MapFile.h" 15 #include "Memory.h" 16 #include "OutputSections.h" 17 #include "Relocations.h" 18 #include "Strings.h" 19 #include "SymbolTable.h" 20 #include "SyntheticSections.h" 21 #include "Target.h" 22 #include "Threads.h" 23 #include "llvm/ADT/StringMap.h" 24 #include "llvm/ADT/StringSwitch.h" 25 #include "llvm/Support/FileOutputBuffer.h" 26 #include "llvm/Support/raw_ostream.h" 27 #include <climits> 28 29 using namespace llvm; 30 using namespace llvm::ELF; 31 using namespace llvm::object; 32 using namespace llvm::support; 33 using namespace llvm::support::endian; 34 35 using namespace lld; 36 using namespace lld::elf; 37 38 namespace { 39 // The writer writes a SymbolTable result to a file. 40 template <class ELFT> class Writer { 41 public: 42 typedef typename ELFT::Shdr Elf_Shdr; 43 typedef typename ELFT::Ehdr Elf_Ehdr; 44 typedef typename ELFT::Phdr Elf_Phdr; 45 46 void run(); 47 48 private: 49 void clearOutputSections(); 50 void createSyntheticSections(); 51 void copyLocalSymbols(); 52 void addSectionSymbols(); 53 void addReservedSymbols(); 54 void createSections(); 55 void forEachRelSec(std::function<void(InputSectionBase &)> Fn); 56 void sortSections(); 57 void finalizeSections(); 58 void addPredefinedSections(); 59 60 std::vector<PhdrEntry> createPhdrs(); 61 void removeEmptyPTLoad(); 62 void addPtArmExid(std::vector<PhdrEntry> &Phdrs); 63 void assignFileOffsets(); 64 void assignFileOffsetsBinary(); 65 void setPhdrs(); 66 void fixSectionAlignments(); 67 void fixPredefinedSymbols(); 68 void openFile(); 69 void writeHeader(); 70 void writeSections(); 71 void writeSectionsBinary(); 72 void writeBuildId(); 73 74 std::unique_ptr<FileOutputBuffer> Buffer; 75 76 OutputSectionFactory Factory{OutputSections}; 77 78 void addRelIpltSymbols(); 79 void addStartEndSymbols(); 80 void addStartStopSymbols(OutputSection *Sec); 81 uint64_t getEntryAddr(); 82 OutputSection *findSection(StringRef Name); 83 OutputSection *findSectionInScript(StringRef Name); 84 OutputSectionCommand *findSectionCommand(StringRef Name); 85 86 std::vector<PhdrEntry> Phdrs; 87 88 uint64_t FileSize; 89 uint64_t SectionHeaderOff; 90 91 bool HasGotBaseSym = false; 92 }; 93 } // anonymous namespace 94 95 StringRef elf::getOutputSectionName(StringRef Name) { 96 // ".zdebug_" is a prefix for ZLIB-compressed sections. 97 // Because we decompressed input sections, we want to remove 'z'. 98 if (Name.startswith(".zdebug_")) 99 return Saver.save("." + Name.substr(2)); 100 101 if (Config->Relocatable) 102 return Name; 103 104 for (StringRef V : 105 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.", 106 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.", 107 ".gcc_except_table.", ".tdata.", ".ARM.exidx."}) { 108 StringRef Prefix = V.drop_back(); 109 if (Name.startswith(V) || Name == Prefix) 110 return Prefix; 111 } 112 113 // CommonSection is identified as "COMMON" in linker scripts. 114 // By default, it should go to .bss section. 115 if (Name == "COMMON") 116 return ".bss"; 117 118 return Name; 119 } 120 121 template <class ELFT> static bool needsInterpSection() { 122 return !Symtab<ELFT>::X->getSharedFiles().empty() && 123 !Config->DynamicLinker.empty() && !Script->ignoreInterpSection(); 124 } 125 126 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); } 127 128 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() { 129 auto I = std::remove_if(Phdrs.begin(), Phdrs.end(), [&](const PhdrEntry &P) { 130 if (P.p_type != PT_LOAD) 131 return false; 132 if (!P.First) 133 return true; 134 uint64_t Size = P.Last->Addr + P.Last->Size - P.First->Addr; 135 return Size == 0; 136 }); 137 Phdrs.erase(I, Phdrs.end()); 138 } 139 140 template <class ELFT> static void combineEhFrameSections() { 141 for (InputSectionBase *&S : InputSections) { 142 EhInputSection *ES = dyn_cast<EhInputSection>(S); 143 if (!ES || !ES->Live) 144 continue; 145 146 In<ELFT>::EhFrame->addSection(ES); 147 S = nullptr; 148 } 149 150 std::vector<InputSectionBase *> &V = InputSections; 151 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end()); 152 } 153 154 template <class ELFT> void Writer<ELFT>::clearOutputSections() { 155 if (Script->Opt.HasSections) 156 Script->createOrphanCommands(); 157 else 158 Script->fabricateDefaultCommands(); 159 // Clear the OutputSections to make sure it is not used anymore. Any 160 // code from this point on should be using the linker script 161 // commands. 162 for (OutputSection *Sec : OutputSections) 163 Sec->Sections.clear(); 164 OutputSections.clear(); 165 } 166 167 // The main function of the writer. 168 template <class ELFT> void Writer<ELFT>::run() { 169 // Create linker-synthesized sections such as .got or .plt. 170 // Such sections are of type input section. 171 createSyntheticSections(); 172 173 if (!Config->Relocatable) 174 combineEhFrameSections<ELFT>(); 175 176 // We need to create some reserved symbols such as _end. Create them. 177 if (!Config->Relocatable) 178 addReservedSymbols(); 179 180 // Create output sections. 181 if (Script->Opt.HasSections) { 182 // If linker script contains SECTIONS commands, let it create sections. 183 Script->processCommands(Factory); 184 185 // Linker scripts may have left some input sections unassigned. 186 // Assign such sections using the default rule. 187 Script->addOrphanSections(Factory); 188 } else { 189 // If linker script does not contain SECTIONS commands, create 190 // output sections by default rules. We still need to give the 191 // linker script a chance to run, because it might contain 192 // non-SECTIONS commands such as ASSERT. 193 createSections(); 194 Script->processCommands(Factory); 195 } 196 197 if (Config->Discard != DiscardPolicy::All) 198 copyLocalSymbols(); 199 200 if (Config->CopyRelocs) 201 addSectionSymbols(); 202 203 // Now that we have a complete set of output sections. This function 204 // completes section contents. For example, we need to add strings 205 // to the string table, and add entries to .got and .plt. 206 // finalizeSections does that. 207 finalizeSections(); 208 if (ErrorCount) 209 return; 210 211 if (!Script->Opt.HasSections && !Config->Relocatable) 212 fixSectionAlignments(); 213 214 // If -compressed-debug-sections is specified, we need to compress 215 // .debug_* sections. Do it right now because it changes the size of 216 // output sections. 217 parallelForEach( 218 OutputSectionCommands.begin(), OutputSectionCommands.end(), 219 [](OutputSectionCommand *Cmd) { Cmd->maybeCompress<ELFT>(); }); 220 221 Script->assignAddresses(Phdrs); 222 223 // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a 224 // 0 sized region. This has to be done late since only after assignAddresses 225 // we know the size of the sections. 226 removeEmptyPTLoad(); 227 228 if (!Config->OFormatBinary) 229 assignFileOffsets(); 230 else 231 assignFileOffsetsBinary(); 232 233 setPhdrs(); 234 235 if (Config->Relocatable) { 236 for (OutputSectionCommand *Cmd : OutputSectionCommands) 237 Cmd->Sec->Addr = 0; 238 } else { 239 fixPredefinedSymbols(); 240 } 241 242 // It does not make sense try to open the file if we have error already. 243 if (ErrorCount) 244 return; 245 // Write the result down to a file. 246 openFile(); 247 if (ErrorCount) 248 return; 249 250 if (!Config->OFormatBinary) { 251 writeHeader(); 252 writeSections(); 253 } else { 254 writeSectionsBinary(); 255 } 256 257 // Backfill .note.gnu.build-id section content. This is done at last 258 // because the content is usually a hash value of the entire output file. 259 writeBuildId(); 260 if (ErrorCount) 261 return; 262 263 264 // Handle -Map option. 265 writeMapFile<ELFT>(OutputSectionCommands); 266 if (ErrorCount) 267 return; 268 269 if (auto EC = Buffer->commit()) 270 error("failed to write to the output file: " + EC.message()); 271 272 // Flush the output streams and exit immediately. A full shutdown 273 // is a good test that we are keeping track of all allocated memory, 274 // but actually freeing it is a waste of time in a regular linker run. 275 if (Config->ExitEarly) 276 exitLld(0); 277 } 278 279 // Initialize Out members. 280 template <class ELFT> void Writer<ELFT>::createSyntheticSections() { 281 // Initialize all pointers with NULL. This is needed because 282 // you can call lld::elf::main more than once as a library. 283 memset(&Out::First, 0, sizeof(Out)); 284 285 auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); }; 286 287 InX::DynStrTab = make<StringTableSection>(".dynstr", true); 288 InX::Dynamic = make<DynamicSection<ELFT>>(); 289 In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>( 290 Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc); 291 InX::ShStrTab = make<StringTableSection>(".shstrtab", false); 292 293 Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC); 294 Out::ElfHeader->Size = sizeof(Elf_Ehdr); 295 Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC); 296 Out::ProgramHeaders->updateAlignment(Config->Wordsize); 297 298 if (needsInterpSection<ELFT>()) { 299 InX::Interp = createInterpSection(); 300 Add(InX::Interp); 301 } else { 302 InX::Interp = nullptr; 303 } 304 305 if (Config->Strip != StripPolicy::All) { 306 InX::StrTab = make<StringTableSection>(".strtab", false); 307 InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab); 308 } 309 310 if (Config->BuildId != BuildIdKind::None) { 311 InX::BuildId = make<BuildIdSection>(); 312 Add(InX::BuildId); 313 } 314 315 InX::Common = createCommonSection<ELFT>(); 316 if (InX::Common) 317 Add(InX::Common); 318 319 InX::Bss = make<BssSection>(".bss"); 320 Add(InX::Bss); 321 InX::BssRelRo = make<BssSection>(".bss.rel.ro"); 322 Add(InX::BssRelRo); 323 324 // Add MIPS-specific sections. 325 bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() || 326 Config->Pic || Config->ExportDynamic; 327 if (Config->EMachine == EM_MIPS) { 328 if (!Config->Shared && HasDynSymTab) { 329 InX::MipsRldMap = make<MipsRldMapSection>(); 330 Add(InX::MipsRldMap); 331 } 332 if (auto *Sec = MipsAbiFlagsSection<ELFT>::create()) 333 Add(Sec); 334 if (auto *Sec = MipsOptionsSection<ELFT>::create()) 335 Add(Sec); 336 if (auto *Sec = MipsReginfoSection<ELFT>::create()) 337 Add(Sec); 338 } 339 340 if (HasDynSymTab) { 341 InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab); 342 Add(InX::DynSymTab); 343 344 In<ELFT>::VerSym = make<VersionTableSection<ELFT>>(); 345 Add(In<ELFT>::VerSym); 346 347 if (!Config->VersionDefinitions.empty()) { 348 In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>(); 349 Add(In<ELFT>::VerDef); 350 } 351 352 In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>(); 353 Add(In<ELFT>::VerNeed); 354 355 if (Config->GnuHash) { 356 InX::GnuHashTab = make<GnuHashTableSection>(); 357 Add(InX::GnuHashTab); 358 } 359 360 if (Config->SysvHash) { 361 In<ELFT>::HashTab = make<HashTableSection<ELFT>>(); 362 Add(In<ELFT>::HashTab); 363 } 364 365 Add(InX::Dynamic); 366 Add(InX::DynStrTab); 367 Add(In<ELFT>::RelaDyn); 368 } 369 370 // Add .got. MIPS' .got is so different from the other archs, 371 // it has its own class. 372 if (Config->EMachine == EM_MIPS) { 373 InX::MipsGot = make<MipsGotSection>(); 374 Add(InX::MipsGot); 375 } else { 376 InX::Got = make<GotSection>(); 377 Add(InX::Got); 378 } 379 380 InX::GotPlt = make<GotPltSection>(); 381 Add(InX::GotPlt); 382 InX::IgotPlt = make<IgotPltSection>(); 383 Add(InX::IgotPlt); 384 385 if (Config->GdbIndex) { 386 InX::GdbIndex = make<GdbIndexSection>(); 387 Add(InX::GdbIndex); 388 } 389 390 // We always need to add rel[a].plt to output if it has entries. 391 // Even for static linking it can contain R_[*]_IRELATIVE relocations. 392 In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>( 393 Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/); 394 Add(In<ELFT>::RelaPlt); 395 396 // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure 397 // that the IRelative relocations are processed last by the dynamic loader 398 In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>( 399 (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name, 400 false /*Sort*/); 401 Add(In<ELFT>::RelaIplt); 402 403 InX::Plt = make<PltSection>(Target->PltHeaderSize); 404 Add(InX::Plt); 405 InX::Iplt = make<PltSection>(0); 406 Add(InX::Iplt); 407 408 if (!Config->Relocatable) { 409 if (Config->EhFrameHdr) { 410 In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>(); 411 Add(In<ELFT>::EhFrameHdr); 412 } 413 In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>(); 414 Add(In<ELFT>::EhFrame); 415 } 416 417 if (InX::SymTab) 418 Add(InX::SymTab); 419 Add(InX::ShStrTab); 420 if (InX::StrTab) 421 Add(InX::StrTab); 422 } 423 424 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName, 425 const SymbolBody &B) { 426 if (B.isFile() || B.isSection()) 427 return false; 428 429 // If sym references a section in a discarded group, don't keep it. 430 if (Sec == &InputSection::Discarded) 431 return false; 432 433 if (Config->Discard == DiscardPolicy::None) 434 return true; 435 436 // In ELF assembly .L symbols are normally discarded by the assembler. 437 // If the assembler fails to do so, the linker discards them if 438 // * --discard-locals is used. 439 // * The symbol is in a SHF_MERGE section, which is normally the reason for 440 // the assembler keeping the .L symbol. 441 if (!SymName.startswith(".L") && !SymName.empty()) 442 return true; 443 444 if (Config->Discard == DiscardPolicy::Locals) 445 return false; 446 447 return !Sec || !(Sec->Flags & SHF_MERGE); 448 } 449 450 static bool includeInSymtab(const SymbolBody &B) { 451 if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj) 452 return false; 453 454 if (auto *D = dyn_cast<DefinedRegular>(&B)) { 455 // Always include absolute symbols. 456 SectionBase *Sec = D->Section; 457 if (!Sec) 458 return true; 459 if (auto *IS = dyn_cast<InputSectionBase>(Sec)) { 460 Sec = IS->Repl; 461 IS = cast<InputSectionBase>(Sec); 462 // Exclude symbols pointing to garbage-collected sections. 463 if (!IS->Live) 464 return false; 465 } 466 if (auto *S = dyn_cast<MergeInputSection>(Sec)) 467 if (!S->getSectionPiece(D->Value)->Live) 468 return false; 469 } 470 return true; 471 } 472 473 // Local symbols are not in the linker's symbol table. This function scans 474 // each object file's symbol table to copy local symbols to the output. 475 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() { 476 if (!InX::SymTab) 477 return; 478 for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) { 479 for (SymbolBody *B : F->getLocalSymbols()) { 480 if (!B->IsLocal) 481 fatal(toString(F) + 482 ": broken object: getLocalSymbols returns a non-local symbol"); 483 auto *DR = dyn_cast<DefinedRegular>(B); 484 485 // No reason to keep local undefined symbol in symtab. 486 if (!DR) 487 continue; 488 if (!includeInSymtab(*B)) 489 continue; 490 491 SectionBase *Sec = DR->Section; 492 if (!shouldKeepInSymtab(Sec, B->getName(), *B)) 493 continue; 494 InX::SymTab->addSymbol(B); 495 } 496 } 497 } 498 499 template <class ELFT> void Writer<ELFT>::addSectionSymbols() { 500 // Create one STT_SECTION symbol for each output section we might 501 // have a relocation with. 502 for (OutputSection *Sec : OutputSections) { 503 if (Sec->Sections.empty()) 504 continue; 505 506 InputSection *IS = Sec->Sections[0]; 507 if (isa<SyntheticSection>(IS) || IS->Type == SHT_REL || 508 IS->Type == SHT_RELA) 509 continue; 510 511 auto *Sym = 512 make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION, 513 /*Value=*/0, /*Size=*/0, IS, nullptr); 514 InX::SymTab->addSymbol(Sym); 515 } 516 } 517 518 // Today's loaders have a feature to make segments read-only after 519 // processing dynamic relocations to enhance security. PT_GNU_RELRO 520 // is defined for that. 521 // 522 // This function returns true if a section needs to be put into a 523 // PT_GNU_RELRO segment. 524 bool elf::isRelroSection(const OutputSection *Sec) { 525 if (!Config->ZRelro) 526 return false; 527 528 uint64_t Flags = Sec->Flags; 529 530 // Non-allocatable or non-writable sections don't need RELRO because 531 // they are not writable or not even mapped to memory in the first place. 532 // RELRO is for sections that are essentially read-only but need to 533 // be writable only at process startup to allow dynamic linker to 534 // apply relocations. 535 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE)) 536 return false; 537 538 // Once initialized, TLS data segments are used as data templates 539 // for a thread-local storage. For each new thread, runtime 540 // allocates memory for a TLS and copy templates there. No thread 541 // are supposed to use templates directly. Thus, it can be in RELRO. 542 if (Flags & SHF_TLS) 543 return true; 544 545 // .init_array, .preinit_array and .fini_array contain pointers to 546 // functions that are executed on process startup or exit. These 547 // pointers are set by the static linker, and they are not expected 548 // to change at runtime. But if you are an attacker, you could do 549 // interesting things by manipulating pointers in .fini_array, for 550 // example. So they are put into RELRO. 551 uint32_t Type = Sec->Type; 552 if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY || 553 Type == SHT_PREINIT_ARRAY) 554 return true; 555 556 // .got contains pointers to external symbols. They are resolved by 557 // the dynamic linker when a module is loaded into memory, and after 558 // that they are not expected to change. So, it can be in RELRO. 559 if (InX::Got && Sec == InX::Got->getParent()) 560 return true; 561 562 // .got.plt contains pointers to external function symbols. They are 563 // by default resolved lazily, so we usually cannot put it into RELRO. 564 // However, if "-z now" is given, the lazy symbol resolution is 565 // disabled, which enables us to put it into RELRO. 566 if (Sec == InX::GotPlt->getParent()) 567 return Config->ZNow; 568 569 // .dynamic section contains data for the dynamic linker, and 570 // there's no need to write to it at runtime, so it's better to put 571 // it into RELRO. 572 if (Sec == InX::Dynamic->getParent()) 573 return true; 574 575 // .bss.rel.ro is used for copy relocations for read-only symbols. 576 // Since the dynamic linker needs to process copy relocations, the 577 // section cannot be read-only, but once initialized, they shouldn't 578 // change. 579 if (Sec == InX::BssRelRo->getParent()) 580 return true; 581 582 // Sections with some special names are put into RELRO. This is a 583 // bit unfortunate because section names shouldn't be significant in 584 // ELF in spirit. But in reality many linker features depend on 585 // magic section names. 586 StringRef S = Sec->Name; 587 return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" || 588 S == ".eh_frame" || S == ".openbsd.randomdata"; 589 } 590 591 // We compute a rank for each section. The rank indicates where the 592 // section should be placed in the file. Instead of using simple 593 // numbers (0,1,2...), we use a series of flags. One for each decision 594 // point when placing the section. 595 // Using flags has two key properties: 596 // * It is easy to check if a give branch was taken. 597 // * It is easy two see how similar two ranks are (see getRankProximity). 598 enum RankFlags { 599 RF_NOT_ADDR_SET = 1 << 16, 600 RF_NOT_INTERP = 1 << 15, 601 RF_NOT_ALLOC = 1 << 14, 602 RF_WRITE = 1 << 13, 603 RF_EXEC_WRITE = 1 << 12, 604 RF_EXEC = 1 << 11, 605 RF_NON_TLS_BSS = 1 << 10, 606 RF_NON_TLS_BSS_RO = 1 << 9, 607 RF_NOT_TLS = 1 << 8, 608 RF_BSS = 1 << 7, 609 RF_PPC_NOT_TOCBSS = 1 << 6, 610 RF_PPC_OPD = 1 << 5, 611 RF_PPC_TOCL = 1 << 4, 612 RF_PPC_TOC = 1 << 3, 613 RF_PPC_BRANCH_LT = 1 << 2, 614 RF_MIPS_GPREL = 1 << 1, 615 RF_MIPS_NOT_GOT = 1 << 0 616 }; 617 618 static unsigned getSectionRank(const OutputSection *Sec) { 619 unsigned Rank = 0; 620 621 // We want to put section specified by -T option first, so we 622 // can start assigning VA starting from them later. 623 if (Config->SectionStartMap.count(Sec->Name)) 624 return Rank; 625 Rank |= RF_NOT_ADDR_SET; 626 627 // Put .interp first because some loaders want to see that section 628 // on the first page of the executable file when loaded into memory. 629 if (Sec->Name == ".interp") 630 return Rank; 631 Rank |= RF_NOT_INTERP; 632 633 // Allocatable sections go first to reduce the total PT_LOAD size and 634 // so debug info doesn't change addresses in actual code. 635 if (!(Sec->Flags & SHF_ALLOC)) 636 return Rank | RF_NOT_ALLOC; 637 638 // Sort sections based on their access permission in the following 639 // order: R, RX, RWX, RW. This order is based on the following 640 // considerations: 641 // * Read-only sections come first such that they go in the 642 // PT_LOAD covering the program headers at the start of the file. 643 // * Read-only, executable sections come next, unless the 644 // -no-rosegment option is used. 645 // * Writable, executable sections follow such that .plt on 646 // architectures where it needs to be writable will be placed 647 // between .text and .data. 648 // * Writable sections come last, such that .bss lands at the very 649 // end of the last PT_LOAD. 650 bool IsExec = Sec->Flags & SHF_EXECINSTR; 651 bool IsWrite = Sec->Flags & SHF_WRITE; 652 653 if (IsExec) { 654 if (IsWrite) 655 Rank |= RF_EXEC_WRITE; 656 else if (!Config->SingleRoRx) 657 Rank |= RF_EXEC; 658 } else { 659 if (IsWrite) 660 Rank |= RF_WRITE; 661 } 662 663 // If we got here we know that both A and B are in the same PT_LOAD. 664 665 bool IsTls = Sec->Flags & SHF_TLS; 666 bool IsNoBits = Sec->Type == SHT_NOBITS; 667 668 // The first requirement we have is to put (non-TLS) nobits sections last. The 669 // reason is that the only thing the dynamic linker will see about them is a 670 // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the 671 // PT_LOAD, so that has to correspond to the nobits sections. 672 bool IsNonTlsNoBits = IsNoBits && !IsTls; 673 if (IsNonTlsNoBits) 674 Rank |= RF_NON_TLS_BSS; 675 676 // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo 677 // sections after r/w ones, so that the RelRo sections are contiguous. 678 bool IsRelRo = isRelroSection(Sec); 679 if (IsNonTlsNoBits && !IsRelRo) 680 Rank |= RF_NON_TLS_BSS_RO; 681 if (!IsNonTlsNoBits && IsRelRo) 682 Rank |= RF_NON_TLS_BSS_RO; 683 684 // The TLS initialization block needs to be a single contiguous block in a R/W 685 // PT_LOAD, so stick TLS sections directly before the other RelRo R/W 686 // sections. The TLS NOBITS sections are placed here as they don't take up 687 // virtual address space in the PT_LOAD. 688 if (!IsTls) 689 Rank |= RF_NOT_TLS; 690 691 // Within the TLS initialization block, the non-nobits sections need to appear 692 // first. 693 if (IsNoBits) 694 Rank |= RF_BSS; 695 696 // // Some architectures have additional ordering restrictions for sections 697 // // within the same PT_LOAD. 698 if (Config->EMachine == EM_PPC64) { 699 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections 700 // that we would like to make sure appear is a specific order to maximize 701 // their coverage by a single signed 16-bit offset from the TOC base 702 // pointer. Conversely, the special .tocbss section should be first among 703 // all SHT_NOBITS sections. This will put it next to the loaded special 704 // PPC64 sections (and, thus, within reach of the TOC base pointer). 705 StringRef Name = Sec->Name; 706 if (Name != ".tocbss") 707 Rank |= RF_PPC_NOT_TOCBSS; 708 709 if (Name == ".opd") 710 Rank |= RF_PPC_OPD; 711 712 if (Name == ".toc1") 713 Rank |= RF_PPC_TOCL; 714 715 if (Name == ".toc") 716 Rank |= RF_PPC_TOC; 717 718 if (Name == ".branch_lt") 719 Rank |= RF_PPC_BRANCH_LT; 720 } 721 if (Config->EMachine == EM_MIPS) { 722 // All sections with SHF_MIPS_GPREL flag should be grouped together 723 // because data in these sections is addressable with a gp relative address. 724 if (Sec->Flags & SHF_MIPS_GPREL) 725 Rank |= RF_MIPS_GPREL; 726 727 if (Sec->Name != ".got") 728 Rank |= RF_MIPS_NOT_GOT; 729 } 730 731 return Rank; 732 } 733 734 static bool compareSections(const BaseCommand *ACmd, const BaseCommand *BCmd) { 735 const OutputSection *A = cast<OutputSectionCommand>(ACmd)->Sec; 736 const OutputSection *B = cast<OutputSectionCommand>(BCmd)->Sec; 737 if (A->SortRank != B->SortRank) 738 return A->SortRank < B->SortRank; 739 if (!(A->SortRank & RF_NOT_ADDR_SET)) 740 return Config->SectionStartMap.lookup(A->Name) < 741 Config->SectionStartMap.lookup(B->Name); 742 return false; 743 } 744 745 void PhdrEntry::add(OutputSection *Sec) { 746 Last = Sec; 747 if (!First) 748 First = Sec; 749 p_align = std::max(p_align, Sec->Alignment); 750 if (p_type == PT_LOAD) 751 Sec->FirstInPtLoad = First; 752 } 753 754 template <class ELFT> 755 static Symbol *addRegular(StringRef Name, SectionBase *Sec, uint64_t Value, 756 uint8_t StOther = STV_HIDDEN, 757 uint8_t Binding = STB_WEAK) { 758 // The linker generated symbols are added as STB_WEAK to allow user defined 759 // ones to override them. 760 return Symtab<ELFT>::X->addRegular(Name, StOther, STT_NOTYPE, Value, 761 /*Size=*/0, Binding, Sec, 762 /*File=*/nullptr); 763 } 764 765 template <class ELFT> 766 static DefinedRegular * 767 addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val, 768 uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) { 769 SymbolBody *S = Symtab<ELFT>::X->find(Name); 770 if (!S) 771 return nullptr; 772 if (S->isInCurrentDSO()) 773 return nullptr; 774 return cast<DefinedRegular>( 775 addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body()); 776 } 777 778 // The beginning and the ending of .rel[a].plt section are marked 779 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked 780 // executable. The runtime needs these symbols in order to resolve 781 // all IRELATIVE relocs on startup. For dynamic executables, we don't 782 // need these symbols, since IRELATIVE relocs are resolved through GOT 783 // and PLT. For details, see http://www.airs.com/blog/archives/403. 784 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() { 785 if (InX::DynSymTab) 786 return; 787 StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start"; 788 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK); 789 790 S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end"; 791 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK); 792 } 793 794 // The linker is expected to define some symbols depending on 795 // the linking result. This function defines such symbols. 796 template <class ELFT> void Writer<ELFT>::addReservedSymbols() { 797 if (Config->EMachine == EM_MIPS) { 798 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer 799 // so that it points to an absolute address which by default is relative 800 // to GOT. Default offset is 0x7ff0. 801 // See "Global Data Symbols" in Chapter 6 in the following document: 802 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 803 ElfSym::MipsGp = Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL); 804 805 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between 806 // start of function and 'gp' pointer into GOT. 807 if (Symtab<ELFT>::X->find("_gp_disp")) 808 ElfSym::MipsGpDisp = 809 Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL); 810 811 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp' 812 // pointer. This symbol is used in the code generated by .cpload pseudo-op 813 // in case of using -mno-shared option. 814 // https://sourceware.org/ml/binutils/2004-12/msg00094.html 815 if (Symtab<ELFT>::X->find("__gnu_local_gp")) 816 ElfSym::MipsLocalGp = 817 Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL); 818 } 819 820 // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to 821 // be at some offset from the base of the .got section, usually 0 or the end 822 // of the .got 823 InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot) 824 : cast<InputSection>(InX::Got); 825 ElfSym::GlobalOffsetTable = addOptionalRegular<ELFT>( 826 "_GLOBAL_OFFSET_TABLE_", GotSection, Target->GotBaseSymOff); 827 828 // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For 829 // static linking the linker is required to optimize away any references to 830 // __tls_get_addr, so it's not defined anywhere. Create a hidden definition 831 // to avoid the undefined symbol error. 832 if (!InX::DynSymTab) 833 Symtab<ELFT>::X->addIgnored("__tls_get_addr"); 834 835 // __ehdr_start is the location of ELF file headers. Note that we define 836 // this symbol unconditionally even when using a linker script, which 837 // differs from the behavior implemented by GNU linker which only define 838 // this symbol if ELF headers are in the memory mapped segment. 839 // __executable_start is not documented, but the expectation of at 840 // least the android libc is that it points to the elf header too. 841 // __dso_handle symbol is passed to cxa_finalize as a marker to identify 842 // each DSO. The address of the symbol doesn't matter as long as they are 843 // different in different DSOs, so we chose the start address of the DSO. 844 for (const char *Name : 845 {"__ehdr_start", "__executable_start", "__dso_handle"}) 846 addOptionalRegular<ELFT>(Name, Out::ElfHeader, 0, STV_HIDDEN); 847 848 // If linker script do layout we do not need to create any standart symbols. 849 if (Script->Opt.HasSections) 850 return; 851 852 auto Add = [](StringRef S) { 853 return addOptionalRegular<ELFT>(S, Out::ElfHeader, 0, STV_DEFAULT); 854 }; 855 856 ElfSym::Bss = Add("__bss_start"); 857 ElfSym::End1 = Add("end"); 858 ElfSym::End2 = Add("_end"); 859 ElfSym::Etext1 = Add("etext"); 860 ElfSym::Etext2 = Add("_etext"); 861 ElfSym::Edata1 = Add("edata"); 862 ElfSym::Edata2 = Add("_edata"); 863 } 864 865 // Sort input sections by section name suffixes for 866 // __attribute__((init_priority(N))). 867 static void sortInitFini(OutputSection *S) { 868 if (S) 869 reinterpret_cast<OutputSection *>(S)->sortInitFini(); 870 } 871 872 // Sort input sections by the special rule for .ctors and .dtors. 873 static void sortCtorsDtors(OutputSection *S) { 874 if (S) 875 reinterpret_cast<OutputSection *>(S)->sortCtorsDtors(); 876 } 877 878 // Sort input sections using the list provided by --symbol-ordering-file. 879 template <class ELFT> 880 static void sortBySymbolsOrder(ArrayRef<OutputSection *> OutputSections) { 881 if (Config->SymbolOrderingFile.empty()) 882 return; 883 884 // Build a map from symbols to their priorities. Symbols that didn't 885 // appear in the symbol ordering file have the lowest priority 0. 886 // All explicitly mentioned symbols have negative (higher) priorities. 887 DenseMap<StringRef, int> SymbolOrder; 888 int Priority = -Config->SymbolOrderingFile.size(); 889 for (StringRef S : Config->SymbolOrderingFile) 890 SymbolOrder.insert({S, Priority++}); 891 892 // Build a map from sections to their priorities. 893 DenseMap<SectionBase *, int> SectionOrder; 894 for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) { 895 for (SymbolBody *Body : File->getSymbols()) { 896 auto *D = dyn_cast<DefinedRegular>(Body); 897 if (!D || !D->Section) 898 continue; 899 int &Priority = SectionOrder[D->Section]; 900 Priority = std::min(Priority, SymbolOrder.lookup(D->getName())); 901 } 902 } 903 904 // Sort sections by priority. 905 for (OutputSection *Base : OutputSections) 906 if (auto *Sec = dyn_cast<OutputSection>(Base)) 907 Sec->sort([&](InputSectionBase *S) { return SectionOrder.lookup(S); }); 908 } 909 910 template <class ELFT> 911 void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) { 912 for (InputSectionBase *IS : InputSections) { 913 if (!IS->Live) 914 continue; 915 // Scan all relocations. Each relocation goes through a series 916 // of tests to determine if it needs special treatment, such as 917 // creating GOT, PLT, copy relocations, etc. 918 // Note that relocations for non-alloc sections are directly 919 // processed by InputSection::relocateNonAlloc. 920 if (!(IS->Flags & SHF_ALLOC)) 921 continue; 922 if (isa<InputSection>(IS) || isa<EhInputSection>(IS)) 923 Fn(*IS); 924 } 925 926 if (!Config->Relocatable) { 927 for (EhInputSection *ES : In<ELFT>::EhFrame->Sections) 928 Fn(*ES); 929 } 930 } 931 932 template <class ELFT> void Writer<ELFT>::createSections() { 933 for (InputSectionBase *IS : InputSections) 934 if (IS) 935 Factory.addInputSec(IS, getOutputSectionName(IS->Name)); 936 937 sortBySymbolsOrder<ELFT>(OutputSections); 938 sortInitFini(findSection(".init_array")); 939 sortInitFini(findSection(".fini_array")); 940 sortCtorsDtors(findSection(".ctors")); 941 sortCtorsDtors(findSection(".dtors")); 942 } 943 944 // We want to find how similar two ranks are. 945 // The more branches in getSectionRank that match, the more similar they are. 946 // Since each branch corresponds to a bit flag, we can just use 947 // countLeadingZeros. 948 static int getRankProximity(OutputSection *A, OutputSection *B) { 949 return countLeadingZeros(A->SortRank ^ B->SortRank); 950 } 951 952 static int getRankProximity(OutputSection *A, BaseCommand *B) { 953 if (auto *Cmd = dyn_cast<OutputSectionCommand>(B)) 954 if (Cmd->Sec) 955 return getRankProximity(A, Cmd->Sec); 956 return -1; 957 } 958 959 // When placing orphan sections, we want to place them after symbol assignments 960 // so that an orphan after 961 // begin_foo = .; 962 // foo : { *(foo) } 963 // end_foo = .; 964 // doesn't break the intended meaning of the begin/end symbols. 965 // We don't want to go over sections since findOrphanPos is the 966 // one in charge of deciding the order of the sections. 967 // We don't want to go over changes to '.', since doing so in 968 // rx_sec : { *(rx_sec) } 969 // . = ALIGN(0x1000); 970 // /* The RW PT_LOAD starts here*/ 971 // rw_sec : { *(rw_sec) } 972 // would mean that the RW PT_LOAD would become unaligned. 973 static bool shouldSkip(BaseCommand *Cmd) { 974 if (isa<OutputSectionCommand>(Cmd)) 975 return false; 976 if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd)) 977 return Assign->Name != "."; 978 return true; 979 } 980 981 // We want to place orphan sections so that they share as much 982 // characteristics with their neighbors as possible. For example, if 983 // both are rw, or both are tls. 984 template <typename ELFT> 985 static std::vector<BaseCommand *>::iterator 986 findOrphanPos(std::vector<BaseCommand *>::iterator B, 987 std::vector<BaseCommand *>::iterator E) { 988 OutputSection *Sec = cast<OutputSectionCommand>(*E)->Sec; 989 990 // Find the first element that has as close a rank as possible. 991 auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) { 992 return getRankProximity(Sec, A) < getRankProximity(Sec, B); 993 }); 994 if (I == E) 995 return E; 996 997 // Consider all existing sections with the same proximity. 998 int Proximity = getRankProximity(Sec, *I); 999 for (; I != E; ++I) { 1000 auto *Cmd = dyn_cast<OutputSectionCommand>(*I); 1001 if (!Cmd || !Cmd->Sec) 1002 continue; 1003 if (getRankProximity(Sec, Cmd->Sec) != Proximity || 1004 Sec->SortRank < Cmd->Sec->SortRank) 1005 break; 1006 } 1007 auto J = std::find_if( 1008 llvm::make_reverse_iterator(I), llvm::make_reverse_iterator(B), 1009 [](BaseCommand *Cmd) { return isa<OutputSectionCommand>(Cmd); }); 1010 I = J.base(); 1011 while (I != E && shouldSkip(*I)) 1012 ++I; 1013 return I; 1014 } 1015 1016 template <class ELFT> void Writer<ELFT>::sortSections() { 1017 // Don't sort if using -r. It is not necessary and we want to preserve the 1018 // relative order for SHF_LINK_ORDER sections. 1019 if (Config->Relocatable) 1020 return; 1021 1022 if (Script->Opt.HasSections) 1023 Script->adjustSectionsBeforeSorting(); 1024 1025 for (BaseCommand *Base : Script->Opt.Commands) 1026 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) 1027 if (OutputSection *Sec = Cmd->Sec) 1028 Sec->SortRank = getSectionRank(Sec); 1029 1030 if (!Script->Opt.HasSections) { 1031 // We know that all the OutputSectionCommands are contiguous in 1032 // this case. 1033 auto E = Script->Opt.Commands.end(); 1034 auto I = Script->Opt.Commands.begin(); 1035 auto IsSection = [](BaseCommand *Base) { 1036 return isa<OutputSectionCommand>(Base); 1037 }; 1038 I = std::find_if(I, E, IsSection); 1039 E = std::find_if(llvm::make_reverse_iterator(E), 1040 llvm::make_reverse_iterator(I), IsSection) 1041 .base(); 1042 std::stable_sort(I, E, compareSections); 1043 return; 1044 } 1045 1046 // Orphan sections are sections present in the input files which are 1047 // not explicitly placed into the output file by the linker script. 1048 // 1049 // The sections in the linker script are already in the correct 1050 // order. We have to figuere out where to insert the orphan 1051 // sections. 1052 // 1053 // The order of the sections in the script is arbitrary and may not agree with 1054 // compareSections. This means that we cannot easily define a strict weak 1055 // ordering. To see why, consider a comparison of a section in the script and 1056 // one not in the script. We have a two simple options: 1057 // * Make them equivalent (a is not less than b, and b is not less than a). 1058 // The problem is then that equivalence has to be transitive and we can 1059 // have sections a, b and c with only b in a script and a less than c 1060 // which breaks this property. 1061 // * Use compareSectionsNonScript. Given that the script order doesn't have 1062 // to match, we can end up with sections a, b, c, d where b and c are in the 1063 // script and c is compareSectionsNonScript less than b. In which case d 1064 // can be equivalent to c, a to b and d < a. As a concrete example: 1065 // .a (rx) # not in script 1066 // .b (rx) # in script 1067 // .c (ro) # in script 1068 // .d (ro) # not in script 1069 // 1070 // The way we define an order then is: 1071 // * Sort only the orphan sections. They are in the end right now. 1072 // * Move each orphan section to its preferred position. We try 1073 // to put each section in the last position where it it can share 1074 // a PT_LOAD. 1075 // 1076 // There is some ambiguity as to where exactly a new entry should be 1077 // inserted, because Opt.Commands contains not only output section 1078 // commands but also other types of commands such as symbol assignment 1079 // expressions. There's no correct answer here due to the lack of the 1080 // formal specification of the linker script. We use heuristics to 1081 // determine whether a new output command should be added before or 1082 // after another commands. For the details, look at shouldSkip 1083 // function. 1084 1085 auto I = Script->Opt.Commands.begin(); 1086 auto E = Script->Opt.Commands.end(); 1087 auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) { 1088 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) 1089 return Cmd->Sec && Cmd->Sec->SectionIndex == INT_MAX; 1090 return false; 1091 }); 1092 1093 // Sort the orphan sections. 1094 std::stable_sort(NonScriptI, E, compareSections); 1095 1096 // As a horrible special case, skip the first . assignment if it is before any 1097 // section. We do this because it is common to set a load address by starting 1098 // the script with ". = 0xabcd" and the expectation is that every section is 1099 // after that. 1100 auto FirstSectionOrDotAssignment = 1101 std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); }); 1102 if (FirstSectionOrDotAssignment != E && 1103 isa<SymbolAssignment>(**FirstSectionOrDotAssignment)) 1104 ++FirstSectionOrDotAssignment; 1105 I = FirstSectionOrDotAssignment; 1106 1107 while (NonScriptI != E) { 1108 auto Pos = findOrphanPos<ELFT>(I, NonScriptI); 1109 OutputSection *Orphan = cast<OutputSectionCommand>(*NonScriptI)->Sec; 1110 1111 // As an optimization, find all sections with the same sort rank 1112 // and insert them with one rotate. 1113 unsigned Rank = Orphan->SortRank; 1114 auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) { 1115 return cast<OutputSectionCommand>(Cmd)->Sec->SortRank != Rank; 1116 }); 1117 std::rotate(Pos, NonScriptI, End); 1118 NonScriptI = End; 1119 } 1120 1121 Script->adjustSectionsAfterSorting(); 1122 } 1123 1124 static void applySynthetic(const std::vector<SyntheticSection *> &Sections, 1125 std::function<void(SyntheticSection *)> Fn) { 1126 for (SyntheticSection *SS : Sections) 1127 if (SS && SS->getParent() && !SS->empty()) 1128 Fn(SS); 1129 } 1130 1131 // We need to add input synthetic sections early in createSyntheticSections() 1132 // to make them visible from linkescript side. But not all sections are always 1133 // required to be in output. For example we don't need dynamic section content 1134 // sometimes. This function filters out such unused sections from the output. 1135 static void removeUnusedSyntheticSections(std::vector<OutputSection *> &V) { 1136 // All input synthetic sections that can be empty are placed after 1137 // all regular ones. We iterate over them all and exit at first 1138 // non-synthetic. 1139 for (InputSectionBase *S : llvm::reverse(InputSections)) { 1140 SyntheticSection *SS = dyn_cast<SyntheticSection>(S); 1141 if (!SS) 1142 return; 1143 OutputSection *OS = SS->getParent(); 1144 if (!SS->empty() || !OS) 1145 continue; 1146 if ((SS == InX::Got || SS == InX::MipsGot) && ElfSym::GlobalOffsetTable) 1147 continue; 1148 OS->Sections.erase(std::find(OS->Sections.begin(), OS->Sections.end(), SS)); 1149 SS->Live = false; 1150 // If there are no other sections in the output section, remove it from the 1151 // output. 1152 if (OS->Sections.empty()) 1153 V.erase(std::find(V.begin(), V.end(), OS)); 1154 } 1155 } 1156 1157 // Create output section objects and add them to OutputSections. 1158 template <class ELFT> void Writer<ELFT>::finalizeSections() { 1159 Out::DebugInfo = findSection(".debug_info"); 1160 Out::PreinitArray = findSection(".preinit_array"); 1161 Out::InitArray = findSection(".init_array"); 1162 Out::FiniArray = findSection(".fini_array"); 1163 1164 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop 1165 // symbols for sections, so that the runtime can get the start and end 1166 // addresses of each section by section name. Add such symbols. 1167 if (!Config->Relocatable) { 1168 addStartEndSymbols(); 1169 for (OutputSection *Sec : OutputSections) 1170 addStartStopSymbols(Sec); 1171 } 1172 1173 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type. 1174 // It should be okay as no one seems to care about the type. 1175 // Even the author of gold doesn't remember why gold behaves that way. 1176 // https://sourceware.org/ml/binutils/2002-03/msg00360.html 1177 if (InX::DynSymTab) 1178 addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0); 1179 1180 // Define __rel[a]_iplt_{start,end} symbols if needed. 1181 addRelIpltSymbols(); 1182 1183 // This responsible for splitting up .eh_frame section into 1184 // pieces. The relocation scan uses those pieces, so this has to be 1185 // earlier. 1186 applySynthetic({In<ELFT>::EhFrame}, 1187 [](SyntheticSection *SS) { SS->finalizeContents(); }); 1188 1189 // Scan relocations. This must be done after every symbol is declared so that 1190 // we can correctly decide if a dynamic relocation is needed. 1191 forEachRelSec(scanRelocations<ELFT>); 1192 1193 if (InX::Plt && !InX::Plt->empty()) 1194 InX::Plt->addSymbols(); 1195 if (InX::Iplt && !InX::Iplt->empty()) 1196 InX::Iplt->addSymbols(); 1197 1198 // Now that we have defined all possible global symbols including linker- 1199 // synthesized ones. Visit all symbols to give the finishing touches. 1200 for (Symbol *S : Symtab<ELFT>::X->getSymbols()) { 1201 SymbolBody *Body = S->body(); 1202 1203 if (!includeInSymtab(*Body)) 1204 continue; 1205 if (InX::SymTab) 1206 InX::SymTab->addSymbol(Body); 1207 1208 if (InX::DynSymTab && S->includeInDynsym()) { 1209 InX::DynSymTab->addSymbol(Body); 1210 if (auto *SS = dyn_cast<SharedSymbol>(Body)) 1211 if (cast<SharedFile<ELFT>>(SS->File)->isNeeded()) 1212 In<ELFT>::VerNeed->addSymbol(SS); 1213 } 1214 } 1215 1216 // Do not proceed if there was an undefined symbol. 1217 if (ErrorCount) 1218 return; 1219 1220 addPredefinedSections(); 1221 removeUnusedSyntheticSections(OutputSections); 1222 1223 clearOutputSections(); 1224 sortSections(); 1225 1226 // Now that we have the final list, create a list of all the 1227 // OutputSectionCommands for convenience. 1228 for (BaseCommand *Base : Script->Opt.Commands) 1229 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) 1230 OutputSectionCommands.push_back(Cmd); 1231 1232 // Prefer command line supplied address over other constraints. 1233 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 1234 auto I = Config->SectionStartMap.find(Cmd->Name); 1235 if (I != Config->SectionStartMap.end()) 1236 Cmd->AddrExpr = [=] { return I->second; }; 1237 } 1238 1239 // This is a bit of a hack. A value of 0 means undef, so we set it 1240 // to 1 t make __ehdr_start defined. The section number is not 1241 // particularly relevant. 1242 Out::ElfHeader->SectionIndex = 1; 1243 1244 unsigned I = 1; 1245 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 1246 OutputSection *Sec = Cmd->Sec; 1247 Sec->SectionIndex = I++; 1248 Sec->ShName = InX::ShStrTab->addString(Sec->Name); 1249 } 1250 1251 // Binary and relocatable output does not have PHDRS. 1252 // The headers have to be created before finalize as that can influence the 1253 // image base and the dynamic section on mips includes the image base. 1254 if (!Config->Relocatable && !Config->OFormatBinary) { 1255 Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs(); 1256 addPtArmExid(Phdrs); 1257 Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size(); 1258 } 1259 1260 // Compute the size of .rela.dyn and .rela.plt early since we need 1261 // them to populate .dynamic. 1262 for (SyntheticSection *SS : {In<ELFT>::RelaDyn, In<ELFT>::RelaPlt}) 1263 if (SS->getParent() && !SS->empty()) 1264 SS->getParent()->assignOffsets(); 1265 1266 // Dynamic section must be the last one in this list and dynamic 1267 // symbol table section (DynSymTab) must be the first one. 1268 applySynthetic({InX::DynSymTab, InX::Bss, InX::BssRelRo, 1269 InX::GnuHashTab, In<ELFT>::HashTab, InX::SymTab, 1270 InX::ShStrTab, InX::StrTab, In<ELFT>::VerDef, 1271 InX::DynStrTab, InX::GdbIndex, InX::Got, 1272 InX::MipsGot, InX::IgotPlt, InX::GotPlt, 1273 In<ELFT>::RelaDyn, In<ELFT>::RelaIplt, In<ELFT>::RelaPlt, 1274 InX::Plt, InX::Iplt, In<ELFT>::EhFrameHdr, 1275 In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic}, 1276 [](SyntheticSection *SS) { SS->finalizeContents(); }); 1277 1278 // Some architectures use small displacements for jump instructions. 1279 // It is linker's responsibility to create thunks containing long 1280 // jump instructions if jump targets are too far. Create thunks. 1281 if (Target->NeedsThunks) { 1282 // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented, 1283 // these 1284 // do not require address information. To support range extension Thunks 1285 // we need to assign addresses so that we can tell if jump instructions 1286 // are out of range. This will need to turn into a loop that converges 1287 // when no more Thunks are added 1288 ThunkCreator TC; 1289 if (TC.createThunks(OutputSectionCommands)) { 1290 applySynthetic({InX::MipsGot}, 1291 [](SyntheticSection *SS) { SS->updateAllocSize(); }); 1292 if (TC.createThunks(OutputSectionCommands)) 1293 fatal("All non-range thunks should be created in first call"); 1294 } 1295 } 1296 1297 // Fill other section headers. The dynamic table is finalized 1298 // at the end because some tags like RELSZ depend on result 1299 // of finalizing other sections. 1300 for (OutputSectionCommand *Cmd : OutputSectionCommands) 1301 Cmd->finalize<ELFT>(); 1302 1303 // createThunks may have added local symbols to the static symbol table 1304 applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab}, 1305 [](SyntheticSection *SS) { SS->postThunkContents(); }); 1306 } 1307 1308 template <class ELFT> void Writer<ELFT>::addPredefinedSections() { 1309 // ARM ABI requires .ARM.exidx to be terminated by some piece of data. 1310 // We have the terminater synthetic section class. Add that at the end. 1311 auto *OS = dyn_cast_or_null<OutputSection>(findSection(".ARM.exidx")); 1312 if (!OS || OS->Sections.empty() || Config->Relocatable) 1313 return; 1314 1315 auto *Sentinel = make<ARMExidxSentinelSection>(); 1316 OS->addSection(Sentinel); 1317 // If there are linker script commands existing at this point then add the 1318 // sentinel to the last of these too. 1319 if (OutputSectionCommand *C = Script->getCmd(OS)) { 1320 auto ISD = std::find_if(C->Commands.rbegin(), C->Commands.rend(), 1321 [](const BaseCommand *Base) { 1322 return isa<InputSectionDescription>(Base); 1323 }); 1324 cast<InputSectionDescription>(*ISD)->Sections.push_back(Sentinel); 1325 } 1326 } 1327 1328 // The linker is expected to define SECNAME_start and SECNAME_end 1329 // symbols for a few sections. This function defines them. 1330 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() { 1331 auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) { 1332 // These symbols resolve to the image base if the section does not exist. 1333 // A special value -1 indicates end of the section. 1334 if (OS) { 1335 addOptionalRegular<ELFT>(Start, OS, 0); 1336 addOptionalRegular<ELFT>(End, OS, -1); 1337 } else { 1338 if (Config->Pic) 1339 OS = Out::ElfHeader; 1340 addOptionalRegular<ELFT>(Start, OS, 0); 1341 addOptionalRegular<ELFT>(End, OS, 0); 1342 } 1343 }; 1344 1345 Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray); 1346 Define("__init_array_start", "__init_array_end", Out::InitArray); 1347 Define("__fini_array_start", "__fini_array_end", Out::FiniArray); 1348 1349 if (OutputSection *Sec = findSection(".ARM.exidx")) 1350 Define("__exidx_start", "__exidx_end", Sec); 1351 } 1352 1353 // If a section name is valid as a C identifier (which is rare because of 1354 // the leading '.'), linkers are expected to define __start_<secname> and 1355 // __stop_<secname> symbols. They are at beginning and end of the section, 1356 // respectively. This is not requested by the ELF standard, but GNU ld and 1357 // gold provide the feature, and used by many programs. 1358 template <class ELFT> 1359 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) { 1360 StringRef S = Sec->Name; 1361 if (!isValidCIdentifier(S)) 1362 return; 1363 addOptionalRegular<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT); 1364 addOptionalRegular<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT); 1365 } 1366 1367 template <class ELFT> 1368 OutputSectionCommand *Writer<ELFT>::findSectionCommand(StringRef Name) { 1369 for (OutputSectionCommand *Cmd : OutputSectionCommands) 1370 if (Cmd->Name == Name) 1371 return Cmd; 1372 return nullptr; 1373 } 1374 1375 template <class ELFT> OutputSection *Writer<ELFT>::findSectionInScript(StringRef Name) { 1376 if (OutputSectionCommand *Cmd = findSectionCommand(Name)) 1377 return Cmd->Sec; 1378 return nullptr; 1379 } 1380 1381 template <class ELFT> OutputSection *Writer<ELFT>::findSection(StringRef Name) { 1382 for (OutputSection *Sec : OutputSections) 1383 if (Sec->Name == Name) 1384 return Sec; 1385 return nullptr; 1386 } 1387 1388 static bool needsPtLoad(OutputSection *Sec) { 1389 if (!(Sec->Flags & SHF_ALLOC)) 1390 return false; 1391 1392 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is 1393 // responsible for allocating space for them, not the PT_LOAD that 1394 // contains the TLS initialization image. 1395 if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS) 1396 return false; 1397 return true; 1398 } 1399 1400 // Linker scripts are responsible for aligning addresses. Unfortunately, most 1401 // linker scripts are designed for creating two PT_LOADs only, one RX and one 1402 // RW. This means that there is no alignment in the RO to RX transition and we 1403 // cannot create a PT_LOAD there. 1404 static uint64_t computeFlags(uint64_t Flags) { 1405 if (Config->Omagic) 1406 return PF_R | PF_W | PF_X; 1407 if (Config->SingleRoRx && !(Flags & PF_W)) 1408 return Flags | PF_X; 1409 return Flags; 1410 } 1411 1412 // Decide which program headers to create and which sections to include in each 1413 // one. 1414 template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() { 1415 std::vector<PhdrEntry> Ret; 1416 auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * { 1417 Ret.emplace_back(Type, Flags); 1418 return &Ret.back(); 1419 }; 1420 1421 // The first phdr entry is PT_PHDR which describes the program header itself. 1422 AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders); 1423 1424 // PT_INTERP must be the second entry if exists. 1425 if (OutputSection *Sec = findSectionInScript(".interp")) 1426 AddHdr(PT_INTERP, Sec->getPhdrFlags())->add(Sec); 1427 1428 // Add the first PT_LOAD segment for regular output sections. 1429 uint64_t Flags = computeFlags(PF_R); 1430 PhdrEntry *Load = AddHdr(PT_LOAD, Flags); 1431 1432 // Add the headers. We will remove them if they don't fit. 1433 Load->add(Out::ElfHeader); 1434 Load->add(Out::ProgramHeaders); 1435 1436 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 1437 OutputSection *Sec = Cmd->Sec; 1438 if (!(Sec->Flags & SHF_ALLOC)) 1439 break; 1440 if (!needsPtLoad(Sec)) 1441 continue; 1442 1443 // Segments are contiguous memory regions that has the same attributes 1444 // (e.g. executable or writable). There is one phdr for each segment. 1445 // Therefore, we need to create a new phdr when the next section has 1446 // different flags or is loaded at a discontiguous address using AT linker 1447 // script command. 1448 uint64_t NewFlags = computeFlags(Sec->getPhdrFlags()); 1449 if (Script->hasLMA(Sec) || Flags != NewFlags) { 1450 Load = AddHdr(PT_LOAD, NewFlags); 1451 Flags = NewFlags; 1452 } 1453 1454 Load->add(Sec); 1455 } 1456 1457 // Add a TLS segment if any. 1458 PhdrEntry TlsHdr(PT_TLS, PF_R); 1459 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 1460 OutputSection *Sec = Cmd->Sec; 1461 if (Sec->Flags & SHF_TLS) 1462 TlsHdr.add(Sec); 1463 } 1464 if (TlsHdr.First) 1465 Ret.push_back(std::move(TlsHdr)); 1466 1467 // Add an entry for .dynamic. 1468 if (InX::DynSymTab) 1469 AddHdr(PT_DYNAMIC, InX::Dynamic->getParent()->getPhdrFlags()) 1470 ->add(InX::Dynamic->getParent()); 1471 1472 // PT_GNU_RELRO includes all sections that should be marked as 1473 // read-only by dynamic linker after proccessing relocations. 1474 PhdrEntry RelRo(PT_GNU_RELRO, PF_R); 1475 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 1476 OutputSection *Sec = Cmd->Sec; 1477 if (needsPtLoad(Sec) && isRelroSection(Sec)) 1478 RelRo.add(Sec); 1479 } 1480 if (RelRo.First) 1481 Ret.push_back(std::move(RelRo)); 1482 1483 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr. 1484 if (!In<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr && 1485 In<ELFT>::EhFrame->getParent() && In<ELFT>::EhFrameHdr->getParent()) 1486 AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->getParent()->getPhdrFlags()) 1487 ->add(In<ELFT>::EhFrameHdr->getParent()); 1488 1489 // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes 1490 // the dynamic linker fill the segment with random data. 1491 if (OutputSection *Sec = findSectionInScript(".openbsd.randomdata")) 1492 AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags())->add(Sec); 1493 1494 // PT_GNU_STACK is a special section to tell the loader to make the 1495 // pages for the stack non-executable. If you really want an executable 1496 // stack, you can pass -z execstack, but that's not recommended for 1497 // security reasons. 1498 unsigned Perm; 1499 if (Config->ZExecstack) 1500 Perm = PF_R | PF_W | PF_X; 1501 else 1502 Perm = PF_R | PF_W; 1503 AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize; 1504 1505 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable 1506 // is expected to perform W^X violations, such as calling mprotect(2) or 1507 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on 1508 // OpenBSD. 1509 if (Config->ZWxneeded) 1510 AddHdr(PT_OPENBSD_WXNEEDED, PF_X); 1511 1512 // Create one PT_NOTE per a group of contiguous .note sections. 1513 PhdrEntry *Note = nullptr; 1514 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 1515 OutputSection *Sec = Cmd->Sec; 1516 if (Sec->Type == SHT_NOTE) { 1517 if (!Note || Script->hasLMA(Sec)) 1518 Note = AddHdr(PT_NOTE, PF_R); 1519 Note->add(Sec); 1520 } else { 1521 Note = nullptr; 1522 } 1523 } 1524 return Ret; 1525 } 1526 1527 template <class ELFT> 1528 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) { 1529 if (Config->EMachine != EM_ARM) 1530 return; 1531 auto I = 1532 std::find_if(OutputSectionCommands.begin(), OutputSectionCommands.end(), 1533 [](OutputSectionCommand *Cmd) { 1534 return Cmd->Sec->Type == SHT_ARM_EXIDX; 1535 }); 1536 if (I == OutputSectionCommands.end()) 1537 return; 1538 1539 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME 1540 PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R); 1541 ARMExidx.add((*I)->Sec); 1542 Phdrs.push_back(ARMExidx); 1543 } 1544 1545 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the 1546 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic 1547 // linker can set the permissions. 1548 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() { 1549 auto PageAlign = [](OutputSection *Sec) { 1550 OutputSectionCommand *Cmd = Script->getCmd(Sec); 1551 if (Cmd && !Cmd->AddrExpr) 1552 Cmd->AddrExpr = [=] { 1553 return alignTo(Script->getDot(), Config->MaxPageSize); 1554 }; 1555 }; 1556 1557 for (const PhdrEntry &P : Phdrs) 1558 if (P.p_type == PT_LOAD && P.First) 1559 PageAlign(P.First); 1560 1561 for (const PhdrEntry &P : Phdrs) { 1562 if (P.p_type != PT_GNU_RELRO) 1563 continue; 1564 if (P.First) 1565 PageAlign(P.First); 1566 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we 1567 // have to align it to a page. 1568 auto End = OutputSectionCommands.end(); 1569 auto I = 1570 std::find(OutputSectionCommands.begin(), End, Script->getCmd(P.Last)); 1571 if (I == End || (I + 1) == End) 1572 continue; 1573 OutputSection *Sec = (*(I + 1))->Sec; 1574 if (needsPtLoad(Sec)) 1575 PageAlign(Sec); 1576 } 1577 } 1578 1579 // Adjusts the file alignment for a given output section and returns 1580 // its new file offset. The file offset must be the same with its 1581 // virtual address (modulo the page size) so that the loader can load 1582 // executables without any address adjustment. 1583 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Sec) { 1584 OutputSection *First = Sec->FirstInPtLoad; 1585 // If the section is not in a PT_LOAD, we just have to align it. 1586 if (!First) 1587 return alignTo(Off, Sec->Alignment); 1588 1589 // The first section in a PT_LOAD has to have congruent offset and address 1590 // module the page size. 1591 if (Sec == First) 1592 return alignTo(Off, Config->MaxPageSize, Sec->Addr); 1593 1594 // If two sections share the same PT_LOAD the file offset is calculated 1595 // using this formula: Off2 = Off1 + (VA2 - VA1). 1596 return First->Offset + Sec->Addr - First->Addr; 1597 } 1598 1599 static uint64_t setOffset(OutputSection *Sec, uint64_t Off) { 1600 if (Sec->Type == SHT_NOBITS) { 1601 Sec->Offset = Off; 1602 return Off; 1603 } 1604 1605 Off = getFileAlignment(Off, Sec); 1606 Sec->Offset = Off; 1607 return Off + Sec->Size; 1608 } 1609 1610 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() { 1611 uint64_t Off = 0; 1612 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 1613 OutputSection *Sec = Cmd->Sec; 1614 if (Sec->Flags & SHF_ALLOC) 1615 Off = setOffset(Sec, Off); 1616 } 1617 FileSize = alignTo(Off, Config->Wordsize); 1618 } 1619 1620 // Assign file offsets to output sections. 1621 template <class ELFT> void Writer<ELFT>::assignFileOffsets() { 1622 uint64_t Off = 0; 1623 Off = setOffset(Out::ElfHeader, Off); 1624 Off = setOffset(Out::ProgramHeaders, Off); 1625 1626 for (OutputSectionCommand *Cmd : OutputSectionCommands) 1627 Off = setOffset(Cmd->Sec, Off); 1628 1629 SectionHeaderOff = alignTo(Off, Config->Wordsize); 1630 FileSize = 1631 SectionHeaderOff + (OutputSectionCommands.size() + 1) * sizeof(Elf_Shdr); 1632 } 1633 1634 // Finalize the program headers. We call this function after we assign 1635 // file offsets and VAs to all sections. 1636 template <class ELFT> void Writer<ELFT>::setPhdrs() { 1637 for (PhdrEntry &P : Phdrs) { 1638 OutputSection *First = P.First; 1639 OutputSection *Last = P.Last; 1640 if (First) { 1641 P.p_filesz = Last->Offset - First->Offset; 1642 if (Last->Type != SHT_NOBITS) 1643 P.p_filesz += Last->Size; 1644 P.p_memsz = Last->Addr + Last->Size - First->Addr; 1645 P.p_offset = First->Offset; 1646 P.p_vaddr = First->Addr; 1647 if (!P.HasLMA) 1648 P.p_paddr = First->getLMA(); 1649 } 1650 if (P.p_type == PT_LOAD) 1651 P.p_align = Config->MaxPageSize; 1652 else if (P.p_type == PT_GNU_RELRO) { 1653 P.p_align = 1; 1654 // The glibc dynamic loader rounds the size down, so we need to round up 1655 // to protect the last page. This is a no-op on FreeBSD which always 1656 // rounds up. 1657 P.p_memsz = alignTo(P.p_memsz, Target->PageSize); 1658 } 1659 1660 // The TLS pointer goes after PT_TLS. At least glibc will align it, 1661 // so round up the size to make sure the offsets are correct. 1662 if (P.p_type == PT_TLS) { 1663 Out::TlsPhdr = &P; 1664 if (P.p_memsz) 1665 P.p_memsz = alignTo(P.p_memsz, P.p_align); 1666 } 1667 } 1668 } 1669 1670 // The entry point address is chosen in the following ways. 1671 // 1672 // 1. the '-e' entry command-line option; 1673 // 2. the ENTRY(symbol) command in a linker control script; 1674 // 3. the value of the symbol start, if present; 1675 // 4. the address of the first byte of the .text section, if present; 1676 // 5. the address 0. 1677 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() { 1678 // Case 1, 2 or 3. As a special case, if the symbol is actually 1679 // a number, we'll use that number as an address. 1680 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry)) 1681 return B->getVA(); 1682 uint64_t Addr; 1683 if (to_integer(Config->Entry, Addr)) 1684 return Addr; 1685 1686 // Case 4 1687 if (OutputSection *Sec = findSectionInScript(".text")) { 1688 if (Config->WarnMissingEntry) 1689 warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" + 1690 utohexstr(Sec->Addr)); 1691 return Sec->Addr; 1692 } 1693 1694 // Case 5 1695 if (Config->WarnMissingEntry) 1696 warn("cannot find entry symbol " + Config->Entry + 1697 "; not setting start address"); 1698 return 0; 1699 } 1700 1701 static uint16_t getELFType() { 1702 if (Config->Pic) 1703 return ET_DYN; 1704 if (Config->Relocatable) 1705 return ET_REL; 1706 return ET_EXEC; 1707 } 1708 1709 // This function is called after we have assigned address and size 1710 // to each section. This function fixes some predefined 1711 // symbol values that depend on section address and size. 1712 template <class ELFT> void Writer<ELFT>::fixPredefinedSymbols() { 1713 // _etext is the first location after the last read-only loadable segment. 1714 // _edata is the first location after the last read-write loadable segment. 1715 // _end is the first location after the uninitialized data region. 1716 PhdrEntry *Last = nullptr; 1717 PhdrEntry *LastRO = nullptr; 1718 PhdrEntry *LastRW = nullptr; 1719 for (PhdrEntry &P : Phdrs) { 1720 if (P.p_type != PT_LOAD) 1721 continue; 1722 Last = &P; 1723 if (P.p_flags & PF_W) 1724 LastRW = &P; 1725 else 1726 LastRO = &P; 1727 } 1728 1729 auto Set = [](DefinedRegular *S, OutputSection *Sec, uint64_t Value) { 1730 if (S) { 1731 S->Section = Sec; 1732 S->Value = Value; 1733 } 1734 }; 1735 1736 if (Last) { 1737 Set(ElfSym::End1, Last->First, Last->p_memsz); 1738 Set(ElfSym::End2, Last->First, Last->p_memsz); 1739 } 1740 if (LastRO) { 1741 Set(ElfSym::Etext1, LastRO->First, LastRO->p_filesz); 1742 Set(ElfSym::Etext2, LastRO->First, LastRO->p_filesz); 1743 } 1744 if (LastRW) { 1745 Set(ElfSym::Edata1, LastRW->First, LastRW->p_filesz); 1746 Set(ElfSym::Edata2, LastRW->First, LastRW->p_filesz); 1747 } 1748 1749 if (ElfSym::Bss) 1750 ElfSym::Bss->Section = findSectionInScript(".bss"); 1751 1752 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should 1753 // be equal to the _gp symbol's value. 1754 if (Config->EMachine == EM_MIPS && !ElfSym::MipsGp->Value) { 1755 // Find GP-relative section with the lowest address 1756 // and use this address to calculate default _gp value. 1757 for (const OutputSectionCommand *Cmd : OutputSectionCommands) { 1758 OutputSection *OS = Cmd->Sec; 1759 if (OS->Flags & SHF_MIPS_GPREL) { 1760 ElfSym::MipsGp->Value = OS->Addr + 0x7ff0; 1761 break; 1762 } 1763 } 1764 } 1765 } 1766 1767 template <class ELFT> void Writer<ELFT>::writeHeader() { 1768 uint8_t *Buf = Buffer->getBufferStart(); 1769 memcpy(Buf, "\177ELF", 4); 1770 1771 // Write the ELF header. 1772 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf); 1773 EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32; 1774 EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB; 1775 EHdr->e_ident[EI_VERSION] = EV_CURRENT; 1776 EHdr->e_ident[EI_OSABI] = Config->OSABI; 1777 EHdr->e_type = getELFType(); 1778 EHdr->e_machine = Config->EMachine; 1779 EHdr->e_version = EV_CURRENT; 1780 EHdr->e_entry = getEntryAddr(); 1781 EHdr->e_shoff = SectionHeaderOff; 1782 EHdr->e_ehsize = sizeof(Elf_Ehdr); 1783 EHdr->e_phnum = Phdrs.size(); 1784 EHdr->e_shentsize = sizeof(Elf_Shdr); 1785 EHdr->e_shnum = OutputSectionCommands.size() + 1; 1786 EHdr->e_shstrndx = InX::ShStrTab->getParent()->SectionIndex; 1787 1788 if (Config->EMachine == EM_ARM) 1789 // We don't currently use any features incompatible with EF_ARM_EABI_VER5, 1790 // but we don't have any firm guarantees of conformance. Linux AArch64 1791 // kernels (as of 2016) require an EABI version to be set. 1792 EHdr->e_flags = EF_ARM_EABI_VER5; 1793 else if (Config->EMachine == EM_MIPS) 1794 EHdr->e_flags = getMipsEFlags<ELFT>(); 1795 1796 if (!Config->Relocatable) { 1797 EHdr->e_phoff = sizeof(Elf_Ehdr); 1798 EHdr->e_phentsize = sizeof(Elf_Phdr); 1799 } 1800 1801 // Write the program header table. 1802 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff); 1803 for (PhdrEntry &P : Phdrs) { 1804 HBuf->p_type = P.p_type; 1805 HBuf->p_flags = P.p_flags; 1806 HBuf->p_offset = P.p_offset; 1807 HBuf->p_vaddr = P.p_vaddr; 1808 HBuf->p_paddr = P.p_paddr; 1809 HBuf->p_filesz = P.p_filesz; 1810 HBuf->p_memsz = P.p_memsz; 1811 HBuf->p_align = P.p_align; 1812 ++HBuf; 1813 } 1814 1815 // Write the section header table. Note that the first table entry is null. 1816 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff); 1817 for (OutputSectionCommand *Cmd : OutputSectionCommands) 1818 Cmd->Sec->writeHeaderTo<ELFT>(++SHdrs); 1819 } 1820 1821 // Open a result file. 1822 template <class ELFT> void Writer<ELFT>::openFile() { 1823 if (!Config->Is64 && FileSize > UINT32_MAX) { 1824 error("output file too large: " + Twine(FileSize) + " bytes"); 1825 return; 1826 } 1827 1828 unlinkAsync(Config->OutputFile); 1829 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr = 1830 FileOutputBuffer::create(Config->OutputFile, FileSize, 1831 FileOutputBuffer::F_executable); 1832 1833 if (auto EC = BufferOrErr.getError()) 1834 error("failed to open " + Config->OutputFile + ": " + EC.message()); 1835 else 1836 Buffer = std::move(*BufferOrErr); 1837 } 1838 1839 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() { 1840 uint8_t *Buf = Buffer->getBufferStart(); 1841 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 1842 OutputSection *Sec = Cmd->Sec; 1843 if (Sec->Flags & SHF_ALLOC) 1844 Cmd->writeTo<ELFT>(Buf + Sec->Offset); 1845 } 1846 } 1847 1848 // Write section contents to a mmap'ed file. 1849 template <class ELFT> void Writer<ELFT>::writeSections() { 1850 uint8_t *Buf = Buffer->getBufferStart(); 1851 1852 // PPC64 needs to process relocations in the .opd section 1853 // before processing relocations in code-containing sections. 1854 if (auto *OpdCmd = findSectionCommand(".opd")) { 1855 Out::Opd = OpdCmd->Sec; 1856 Out::OpdBuf = Buf + Out::Opd->Offset; 1857 OpdCmd->template writeTo<ELFT>(Buf + Out::Opd->Offset); 1858 } 1859 1860 OutputSection *EhFrameHdr = 1861 (In<ELFT>::EhFrameHdr && !In<ELFT>::EhFrameHdr->empty()) 1862 ? In<ELFT>::EhFrameHdr->getParent() 1863 : nullptr; 1864 1865 // In -r or -emit-relocs mode, write the relocation sections first as in 1866 // ELf_Rel targets we might find out that we need to modify the relocated 1867 // section while doing it. 1868 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 1869 OutputSection *Sec = Cmd->Sec; 1870 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA) 1871 Cmd->writeTo<ELFT>(Buf + Sec->Offset); 1872 } 1873 1874 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 1875 OutputSection *Sec = Cmd->Sec; 1876 if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL && 1877 Sec->Type != SHT_RELA) 1878 Cmd->writeTo<ELFT>(Buf + Sec->Offset); 1879 } 1880 1881 // The .eh_frame_hdr depends on .eh_frame section contents, therefore 1882 // it should be written after .eh_frame is written. 1883 if (EhFrameHdr) { 1884 OutputSectionCommand *Cmd = Script->getCmd(EhFrameHdr); 1885 Cmd->writeTo<ELFT>(Buf + EhFrameHdr->Offset); 1886 } 1887 } 1888 1889 template <class ELFT> void Writer<ELFT>::writeBuildId() { 1890 if (!InX::BuildId || !InX::BuildId->getParent()) 1891 return; 1892 1893 // Compute a hash of all sections of the output file. 1894 uint8_t *Start = Buffer->getBufferStart(); 1895 uint8_t *End = Start + FileSize; 1896 InX::BuildId->writeBuildId({Start, End}); 1897 } 1898 1899 template void elf::writeResult<ELF32LE>(); 1900 template void elf::writeResult<ELF32BE>(); 1901 template void elf::writeResult<ELF64LE>(); 1902 template void elf::writeResult<ELF64BE>(); 1903