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 "AArch64ErrataFix.h" 12 #include "CallGraphSort.h" 13 #include "Config.h" 14 #include "Filesystem.h" 15 #include "LinkerScript.h" 16 #include "MapFile.h" 17 #include "OutputSections.h" 18 #include "Relocations.h" 19 #include "SymbolTable.h" 20 #include "Symbols.h" 21 #include "SyntheticSections.h" 22 #include "Target.h" 23 #include "lld/Common/Memory.h" 24 #include "lld/Common/Strings.h" 25 #include "lld/Common/Threads.h" 26 #include "llvm/ADT/StringMap.h" 27 #include "llvm/ADT/StringSwitch.h" 28 #include <climits> 29 30 using namespace llvm; 31 using namespace llvm::ELF; 32 using namespace llvm::object; 33 using namespace llvm::support; 34 using namespace llvm::support::endian; 35 36 using namespace lld; 37 using namespace lld::elf; 38 39 namespace { 40 // The writer writes a SymbolTable result to a file. 41 template <class ELFT> class Writer { 42 public: 43 Writer() : Buffer(errorHandler().OutputBuffer) {} 44 typedef typename ELFT::Shdr Elf_Shdr; 45 typedef typename ELFT::Ehdr Elf_Ehdr; 46 typedef typename ELFT::Phdr Elf_Phdr; 47 48 void run(); 49 50 private: 51 void copyLocalSymbols(); 52 void addSectionSymbols(); 53 void forEachRelSec(llvm::function_ref<void(InputSectionBase &)> Fn); 54 void sortSections(); 55 void resolveShfLinkOrder(); 56 void sortInputSections(); 57 void finalizeSections(); 58 void setReservedSymbolSections(); 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 checkSections(); 67 void fixSectionAlignments(); 68 void openFile(); 69 void writeTrapInstr(); 70 void writeHeader(); 71 void writeSections(); 72 void writeSectionsBinary(); 73 void writeBuildId(); 74 75 std::unique_ptr<FileOutputBuffer> &Buffer; 76 77 void addRelIpltSymbols(); 78 void addStartEndSymbols(); 79 void addStartStopSymbols(OutputSection *Sec); 80 uint64_t getEntryAddr(); 81 82 std::vector<PhdrEntry *> Phdrs; 83 84 uint64_t FileSize; 85 uint64_t SectionHeaderOff; 86 }; 87 } // anonymous namespace 88 89 static bool isSectionPrefix(StringRef Prefix, StringRef Name) { 90 return Name.startswith(Prefix) || Name == Prefix.drop_back(); 91 } 92 93 StringRef elf::getOutputSectionName(const InputSectionBase *S) { 94 if (Config->Relocatable) 95 return S->Name; 96 97 // This is for --emit-relocs. If .text.foo is emitted as .text.bar, we want 98 // to emit .rela.text.foo as .rela.text.bar for consistency (this is not 99 // technically required, but not doing it is odd). This code guarantees that. 100 if (auto *IS = dyn_cast<InputSection>(S)) { 101 if (InputSectionBase *Rel = IS->getRelocatedSection()) { 102 OutputSection *Out = Rel->getOutputSection(); 103 if (S->Type == SHT_RELA) 104 return Saver.save(".rela" + Out->Name); 105 return Saver.save(".rel" + Out->Name); 106 } 107 } 108 109 // This check is for -z keep-text-section-prefix. This option separates text 110 // sections with prefix ".text.hot", ".text.unlikely", ".text.startup" or 111 // ".text.exit". 112 // When enabled, this allows identifying the hot code region (.text.hot) in 113 // the final binary which can be selectively mapped to huge pages or mlocked, 114 // for instance. 115 if (Config->ZKeepTextSectionPrefix) 116 for (StringRef V : 117 {".text.hot.", ".text.unlikely.", ".text.startup.", ".text.exit."}) { 118 if (isSectionPrefix(V, S->Name)) 119 return V.drop_back(); 120 } 121 122 for (StringRef V : 123 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.", 124 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.", 125 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) { 126 if (isSectionPrefix(V, S->Name)) 127 return V.drop_back(); 128 } 129 130 // CommonSection is identified as "COMMON" in linker scripts. 131 // By default, it should go to .bss section. 132 if (S->Name == "COMMON") 133 return ".bss"; 134 135 return S->Name; 136 } 137 138 static bool needsInterpSection() { 139 return !SharedFiles.empty() && !Config->DynamicLinker.empty() && 140 Script->needsInterpSection(); 141 } 142 143 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); } 144 145 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() { 146 llvm::erase_if(Phdrs, [&](const PhdrEntry *P) { 147 if (P->p_type != PT_LOAD) 148 return false; 149 if (!P->FirstSec) 150 return true; 151 uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr; 152 return Size == 0; 153 }); 154 } 155 156 template <class ELFT> static void combineEhFrameSections() { 157 for (InputSectionBase *&S : InputSections) { 158 EhInputSection *ES = dyn_cast<EhInputSection>(S); 159 if (!ES || !ES->Live) 160 continue; 161 162 InX::EhFrame->addSection<ELFT>(ES); 163 S = nullptr; 164 } 165 166 std::vector<InputSectionBase *> &V = InputSections; 167 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end()); 168 } 169 170 static Defined *addOptionalRegular(StringRef Name, SectionBase *Sec, 171 uint64_t Val, uint8_t StOther = STV_HIDDEN, 172 uint8_t Binding = STB_GLOBAL) { 173 Symbol *S = Symtab->find(Name); 174 if (!S || S->isDefined()) 175 return nullptr; 176 Symbol *Sym = Symtab->addRegular(Name, StOther, STT_NOTYPE, Val, 177 /*Size=*/0, Binding, Sec, 178 /*File=*/nullptr); 179 return cast<Defined>(Sym); 180 } 181 182 // The linker is expected to define some symbols depending on 183 // the linking result. This function defines such symbols. 184 void elf::addReservedSymbols() { 185 if (Config->EMachine == EM_MIPS) { 186 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer 187 // so that it points to an absolute address which by default is relative 188 // to GOT. Default offset is 0x7ff0. 189 // See "Global Data Symbols" in Chapter 6 in the following document: 190 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 191 ElfSym::MipsGp = Symtab->addAbsolute("_gp", STV_HIDDEN, STB_GLOBAL); 192 193 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between 194 // start of function and 'gp' pointer into GOT. 195 if (Symtab->find("_gp_disp")) 196 ElfSym::MipsGpDisp = 197 Symtab->addAbsolute("_gp_disp", STV_HIDDEN, STB_GLOBAL); 198 199 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp' 200 // pointer. This symbol is used in the code generated by .cpload pseudo-op 201 // in case of using -mno-shared option. 202 // https://sourceware.org/ml/binutils/2004-12/msg00094.html 203 if (Symtab->find("__gnu_local_gp")) 204 ElfSym::MipsLocalGp = 205 Symtab->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_GLOBAL); 206 } 207 208 // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which 209 // combines the typical ELF GOT with the small data sections. It commonly 210 // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both 211 // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to 212 // represent the TOC base which is offset by 0x8000 bytes from the start of 213 // the .got section. 214 ElfSym::GlobalOffsetTable = addOptionalRegular( 215 (Config->EMachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_", 216 Out::ElfHeader, Target->GotBaseSymOff); 217 218 // __ehdr_start is the location of ELF file headers. Note that we define 219 // this symbol unconditionally even when using a linker script, which 220 // differs from the behavior implemented by GNU linker which only define 221 // this symbol if ELF headers are in the memory mapped segment. 222 addOptionalRegular("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN); 223 224 // __executable_start is not documented, but the expectation of at 225 // least the Android libc is that it points to the ELF header. 226 addOptionalRegular("__executable_start", Out::ElfHeader, 0, STV_HIDDEN); 227 228 // __dso_handle symbol is passed to cxa_finalize as a marker to identify 229 // each DSO. The address of the symbol doesn't matter as long as they are 230 // different in different DSOs, so we chose the start address of the DSO. 231 addOptionalRegular("__dso_handle", Out::ElfHeader, 0, STV_HIDDEN); 232 233 // If linker script do layout we do not need to create any standart symbols. 234 if (Script->HasSectionsCommand) 235 return; 236 237 auto Add = [](StringRef S, int64_t Pos) { 238 return addOptionalRegular(S, Out::ElfHeader, Pos, STV_DEFAULT); 239 }; 240 241 ElfSym::Bss = Add("__bss_start", 0); 242 ElfSym::End1 = Add("end", -1); 243 ElfSym::End2 = Add("_end", -1); 244 ElfSym::Etext1 = Add("etext", -1); 245 ElfSym::Etext2 = Add("_etext", -1); 246 ElfSym::Edata1 = Add("edata", -1); 247 ElfSym::Edata2 = Add("_edata", -1); 248 } 249 250 static OutputSection *findSection(StringRef Name) { 251 for (BaseCommand *Base : Script->SectionCommands) 252 if (auto *Sec = dyn_cast<OutputSection>(Base)) 253 if (Sec->Name == Name) 254 return Sec; 255 return nullptr; 256 } 257 258 // Initialize Out members. 259 template <class ELFT> static void createSyntheticSections() { 260 // Initialize all pointers with NULL. This is needed because 261 // you can call lld::elf::main more than once as a library. 262 memset(&Out::First, 0, sizeof(Out)); 263 264 auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); }; 265 266 InX::DynStrTab = make<StringTableSection>(".dynstr", true); 267 InX::Dynamic = make<DynamicSection<ELFT>>(); 268 if (Config->AndroidPackDynRelocs) { 269 InX::RelaDyn = make<AndroidPackedRelocationSection<ELFT>>( 270 Config->IsRela ? ".rela.dyn" : ".rel.dyn"); 271 } else { 272 InX::RelaDyn = make<RelocationSection<ELFT>>( 273 Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc); 274 } 275 InX::ShStrTab = make<StringTableSection>(".shstrtab", false); 276 277 Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC); 278 Out::ProgramHeaders->Alignment = Config->Wordsize; 279 280 if (needsInterpSection()) { 281 InX::Interp = createInterpSection(); 282 Add(InX::Interp); 283 } else { 284 InX::Interp = nullptr; 285 } 286 287 if (Config->Strip != StripPolicy::All) { 288 InX::StrTab = make<StringTableSection>(".strtab", false); 289 InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab); 290 InX::SymTabShndx = make<SymtabShndxSection>(); 291 } 292 293 if (Config->BuildId != BuildIdKind::None) { 294 InX::BuildId = make<BuildIdSection>(); 295 Add(InX::BuildId); 296 } 297 298 InX::Bss = make<BssSection>(".bss", 0, 1); 299 Add(InX::Bss); 300 301 // If there is a SECTIONS command and a .data.rel.ro section name use name 302 // .data.rel.ro.bss so that we match in the .data.rel.ro output section. 303 // This makes sure our relro is contiguous. 304 bool HasDataRelRo = Script->HasSectionsCommand && findSection(".data.rel.ro"); 305 InX::BssRelRo = 306 make<BssSection>(HasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1); 307 Add(InX::BssRelRo); 308 309 // Add MIPS-specific sections. 310 if (Config->EMachine == EM_MIPS) { 311 if (!Config->Shared && Config->HasDynSymTab) { 312 InX::MipsRldMap = make<MipsRldMapSection>(); 313 Add(InX::MipsRldMap); 314 } 315 if (auto *Sec = MipsAbiFlagsSection<ELFT>::create()) 316 Add(Sec); 317 if (auto *Sec = MipsOptionsSection<ELFT>::create()) 318 Add(Sec); 319 if (auto *Sec = MipsReginfoSection<ELFT>::create()) 320 Add(Sec); 321 } 322 323 if (Config->HasDynSymTab) { 324 InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab); 325 Add(InX::DynSymTab); 326 327 In<ELFT>::VerSym = make<VersionTableSection<ELFT>>(); 328 Add(In<ELFT>::VerSym); 329 330 if (!Config->VersionDefinitions.empty()) { 331 In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>(); 332 Add(In<ELFT>::VerDef); 333 } 334 335 In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>(); 336 Add(In<ELFT>::VerNeed); 337 338 if (Config->GnuHash) { 339 InX::GnuHashTab = make<GnuHashTableSection>(); 340 Add(InX::GnuHashTab); 341 } 342 343 if (Config->SysvHash) { 344 InX::HashTab = make<HashTableSection>(); 345 Add(InX::HashTab); 346 } 347 348 Add(InX::Dynamic); 349 Add(InX::DynStrTab); 350 Add(InX::RelaDyn); 351 } 352 353 if (Config->RelrPackDynRelocs) { 354 InX::RelrDyn = make<RelrSection<ELFT>>(); 355 Add(InX::RelrDyn); 356 } 357 358 // Add .got. MIPS' .got is so different from the other archs, 359 // it has its own class. 360 if (Config->EMachine == EM_MIPS) { 361 InX::MipsGot = make<MipsGotSection>(); 362 Add(InX::MipsGot); 363 } else { 364 InX::Got = make<GotSection>(); 365 Add(InX::Got); 366 } 367 368 InX::GotPlt = make<GotPltSection>(); 369 Add(InX::GotPlt); 370 InX::IgotPlt = make<IgotPltSection>(); 371 Add(InX::IgotPlt); 372 373 if (Config->GdbIndex) { 374 InX::GdbIndex = GdbIndexSection::create<ELFT>(); 375 Add(InX::GdbIndex); 376 } 377 378 // We always need to add rel[a].plt to output if it has entries. 379 // Even for static linking it can contain R_[*]_IRELATIVE relocations. 380 InX::RelaPlt = make<RelocationSection<ELFT>>( 381 Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/); 382 Add(InX::RelaPlt); 383 384 // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure 385 // that the IRelative relocations are processed last by the dynamic loader. 386 // We cannot place the iplt section in .rel.dyn when Android relocation 387 // packing is enabled because that would cause a section type mismatch. 388 // However, because the Android dynamic loader reads .rel.plt after .rel.dyn, 389 // we can get the desired behaviour by placing the iplt section in .rel.plt. 390 InX::RelaIplt = make<RelocationSection<ELFT>>( 391 (Config->EMachine == EM_ARM && !Config->AndroidPackDynRelocs) 392 ? ".rel.dyn" 393 : InX::RelaPlt->Name, 394 false /*Sort*/); 395 Add(InX::RelaIplt); 396 397 InX::Plt = make<PltSection>(false); 398 Add(InX::Plt); 399 InX::Iplt = make<PltSection>(true); 400 Add(InX::Iplt); 401 402 if (!Config->Relocatable) { 403 if (Config->EhFrameHdr) { 404 InX::EhFrameHdr = make<EhFrameHeader>(); 405 Add(InX::EhFrameHdr); 406 } 407 InX::EhFrame = make<EhFrameSection>(); 408 Add(InX::EhFrame); 409 } 410 411 if (InX::SymTab) 412 Add(InX::SymTab); 413 if (InX::SymTabShndx) 414 Add(InX::SymTabShndx); 415 Add(InX::ShStrTab); 416 if (InX::StrTab) 417 Add(InX::StrTab); 418 419 if (Config->EMachine == EM_ARM && !Config->Relocatable) 420 // Add a sentinel to terminate .ARM.exidx. It helps an unwinder 421 // to find the exact address range of the last entry. 422 Add(make<ARMExidxSentinelSection>()); 423 } 424 425 // The main function of the writer. 426 template <class ELFT> void Writer<ELFT>::run() { 427 // Create linker-synthesized sections such as .got or .plt. 428 // Such sections are of type input section. 429 createSyntheticSections<ELFT>(); 430 431 if (!Config->Relocatable) 432 combineEhFrameSections<ELFT>(); 433 434 // We want to process linker script commands. When SECTIONS command 435 // is given we let it create sections. 436 Script->processSectionCommands(); 437 438 // Linker scripts controls how input sections are assigned to output sections. 439 // Input sections that were not handled by scripts are called "orphans", and 440 // they are assigned to output sections by the default rule. Process that. 441 Script->addOrphanSections(); 442 443 if (Config->Discard != DiscardPolicy::All) 444 copyLocalSymbols(); 445 446 if (Config->CopyRelocs) 447 addSectionSymbols(); 448 449 // Now that we have a complete set of output sections. This function 450 // completes section contents. For example, we need to add strings 451 // to the string table, and add entries to .got and .plt. 452 // finalizeSections does that. 453 finalizeSections(); 454 if (errorCount()) 455 return; 456 457 Script->assignAddresses(); 458 459 // If -compressed-debug-sections is specified, we need to compress 460 // .debug_* sections. Do it right now because it changes the size of 461 // output sections. 462 for (OutputSection *Sec : OutputSections) 463 Sec->maybeCompress<ELFT>(); 464 465 Script->allocateHeaders(Phdrs); 466 467 // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a 468 // 0 sized region. This has to be done late since only after assignAddresses 469 // we know the size of the sections. 470 removeEmptyPTLoad(); 471 472 if (!Config->OFormatBinary) 473 assignFileOffsets(); 474 else 475 assignFileOffsetsBinary(); 476 477 setPhdrs(); 478 479 if (Config->Relocatable) { 480 for (OutputSection *Sec : OutputSections) 481 Sec->Addr = 0; 482 } 483 484 if (Config->CheckSections) 485 checkSections(); 486 487 // It does not make sense try to open the file if we have error already. 488 if (errorCount()) 489 return; 490 // Write the result down to a file. 491 openFile(); 492 if (errorCount()) 493 return; 494 495 if (!Config->OFormatBinary) { 496 writeTrapInstr(); 497 writeHeader(); 498 writeSections(); 499 } else { 500 writeSectionsBinary(); 501 } 502 503 // Backfill .note.gnu.build-id section content. This is done at last 504 // because the content is usually a hash value of the entire output file. 505 writeBuildId(); 506 if (errorCount()) 507 return; 508 509 // Handle -Map and -cref options. 510 writeMapFile(); 511 writeCrossReferenceTable(); 512 if (errorCount()) 513 return; 514 515 if (auto E = Buffer->commit()) 516 error("failed to write to the output file: " + toString(std::move(E))); 517 } 518 519 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName, 520 const Symbol &B) { 521 if (B.isSection()) 522 return false; 523 524 if (Config->Discard == DiscardPolicy::None) 525 return true; 526 527 // In ELF assembly .L symbols are normally discarded by the assembler. 528 // If the assembler fails to do so, the linker discards them if 529 // * --discard-locals is used. 530 // * The symbol is in a SHF_MERGE section, which is normally the reason for 531 // the assembler keeping the .L symbol. 532 if (!SymName.startswith(".L") && !SymName.empty()) 533 return true; 534 535 if (Config->Discard == DiscardPolicy::Locals) 536 return false; 537 538 return !Sec || !(Sec->Flags & SHF_MERGE); 539 } 540 541 static bool includeInSymtab(const Symbol &B) { 542 if (!B.isLocal() && !B.IsUsedInRegularObj) 543 return false; 544 545 if (auto *D = dyn_cast<Defined>(&B)) { 546 // Always include absolute symbols. 547 SectionBase *Sec = D->Section; 548 if (!Sec) 549 return true; 550 Sec = Sec->Repl; 551 // Exclude symbols pointing to garbage-collected sections. 552 if (isa<InputSectionBase>(Sec) && !Sec->Live) 553 return false; 554 if (auto *S = dyn_cast<MergeInputSection>(Sec)) 555 if (!S->getSectionPiece(D->Value)->Live) 556 return false; 557 return true; 558 } 559 return B.Used; 560 } 561 562 // Local symbols are not in the linker's symbol table. This function scans 563 // each object file's symbol table to copy local symbols to the output. 564 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() { 565 if (!InX::SymTab) 566 return; 567 for (InputFile *File : ObjectFiles) { 568 ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File); 569 for (Symbol *B : F->getLocalSymbols()) { 570 if (!B->isLocal()) 571 fatal(toString(F) + 572 ": broken object: getLocalSymbols returns a non-local symbol"); 573 auto *DR = dyn_cast<Defined>(B); 574 575 // No reason to keep local undefined symbol in symtab. 576 if (!DR) 577 continue; 578 if (!includeInSymtab(*B)) 579 continue; 580 581 SectionBase *Sec = DR->Section; 582 if (!shouldKeepInSymtab(Sec, B->getName(), *B)) 583 continue; 584 InX::SymTab->addSymbol(B); 585 } 586 } 587 } 588 589 template <class ELFT> void Writer<ELFT>::addSectionSymbols() { 590 // Create a section symbol for each output section so that we can represent 591 // relocations that point to the section. If we know that no relocation is 592 // referring to a section (that happens if the section is a synthetic one), we 593 // don't create a section symbol for that section. 594 for (BaseCommand *Base : Script->SectionCommands) { 595 auto *Sec = dyn_cast<OutputSection>(Base); 596 if (!Sec) 597 continue; 598 auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) { 599 if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) 600 return !ISD->Sections.empty(); 601 return false; 602 }); 603 if (I == Sec->SectionCommands.end()) 604 continue; 605 InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0]; 606 607 // Relocations are not using REL[A] section symbols. 608 if (IS->Type == SHT_REL || IS->Type == SHT_RELA) 609 continue; 610 611 // Unlike other synthetic sections, mergeable output sections contain data 612 // copied from input sections, and there may be a relocation pointing to its 613 // contents if -r or -emit-reloc are given. 614 if (isa<SyntheticSection>(IS) && !(IS->Flags & SHF_MERGE)) 615 continue; 616 617 auto *Sym = 618 make<Defined>(IS->File, "", STB_LOCAL, /*StOther=*/0, STT_SECTION, 619 /*Value=*/0, /*Size=*/0, IS); 620 InX::SymTab->addSymbol(Sym); 621 } 622 } 623 624 // Today's loaders have a feature to make segments read-only after 625 // processing dynamic relocations to enhance security. PT_GNU_RELRO 626 // is defined for that. 627 // 628 // This function returns true if a section needs to be put into a 629 // PT_GNU_RELRO segment. 630 static bool isRelroSection(const OutputSection *Sec) { 631 if (!Config->ZRelro) 632 return false; 633 634 uint64_t Flags = Sec->Flags; 635 636 // Non-allocatable or non-writable sections don't need RELRO because 637 // they are not writable or not even mapped to memory in the first place. 638 // RELRO is for sections that are essentially read-only but need to 639 // be writable only at process startup to allow dynamic linker to 640 // apply relocations. 641 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE)) 642 return false; 643 644 // Once initialized, TLS data segments are used as data templates 645 // for a thread-local storage. For each new thread, runtime 646 // allocates memory for a TLS and copy templates there. No thread 647 // are supposed to use templates directly. Thus, it can be in RELRO. 648 if (Flags & SHF_TLS) 649 return true; 650 651 // .init_array, .preinit_array and .fini_array contain pointers to 652 // functions that are executed on process startup or exit. These 653 // pointers are set by the static linker, and they are not expected 654 // to change at runtime. But if you are an attacker, you could do 655 // interesting things by manipulating pointers in .fini_array, for 656 // example. So they are put into RELRO. 657 uint32_t Type = Sec->Type; 658 if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY || 659 Type == SHT_PREINIT_ARRAY) 660 return true; 661 662 // .got contains pointers to external symbols. They are resolved by 663 // the dynamic linker when a module is loaded into memory, and after 664 // that they are not expected to change. So, it can be in RELRO. 665 if (InX::Got && Sec == InX::Got->getParent()) 666 return true; 667 668 if (Sec->Name.equals(".toc")) 669 return true; 670 671 // .got.plt contains pointers to external function symbols. They are 672 // by default resolved lazily, so we usually cannot put it into RELRO. 673 // However, if "-z now" is given, the lazy symbol resolution is 674 // disabled, which enables us to put it into RELRO. 675 if (Sec == InX::GotPlt->getParent()) 676 return Config->ZNow; 677 678 // .dynamic section contains data for the dynamic linker, and 679 // there's no need to write to it at runtime, so it's better to put 680 // it into RELRO. 681 if (Sec == InX::Dynamic->getParent()) 682 return true; 683 684 // Sections with some special names are put into RELRO. This is a 685 // bit unfortunate because section names shouldn't be significant in 686 // ELF in spirit. But in reality many linker features depend on 687 // magic section names. 688 StringRef S = Sec->Name; 689 return S == ".data.rel.ro" || S == ".bss.rel.ro" || S == ".ctors" || 690 S == ".dtors" || S == ".jcr" || S == ".eh_frame" || 691 S == ".openbsd.randomdata"; 692 } 693 694 // We compute a rank for each section. The rank indicates where the 695 // section should be placed in the file. Instead of using simple 696 // numbers (0,1,2...), we use a series of flags. One for each decision 697 // point when placing the section. 698 // Using flags has two key properties: 699 // * It is easy to check if a give branch was taken. 700 // * It is easy two see how similar two ranks are (see getRankProximity). 701 enum RankFlags { 702 RF_NOT_ADDR_SET = 1 << 18, 703 RF_NOT_INTERP = 1 << 17, 704 RF_NOT_ALLOC = 1 << 16, 705 RF_WRITE = 1 << 15, 706 RF_EXEC_WRITE = 1 << 14, 707 RF_EXEC = 1 << 13, 708 RF_RODATA = 1 << 12, 709 RF_NON_TLS_BSS = 1 << 11, 710 RF_NON_TLS_BSS_RO = 1 << 10, 711 RF_NOT_TLS = 1 << 9, 712 RF_BSS = 1 << 8, 713 RF_NOTE = 1 << 7, 714 RF_PPC_NOT_TOCBSS = 1 << 6, 715 RF_PPC_TOCL = 1 << 5, 716 RF_PPC_TOC = 1 << 4, 717 RF_PPC_GOT = 1 << 3, 718 RF_PPC_BRANCH_LT = 1 << 2, 719 RF_MIPS_GPREL = 1 << 1, 720 RF_MIPS_NOT_GOT = 1 << 0 721 }; 722 723 static unsigned getSectionRank(const OutputSection *Sec) { 724 unsigned Rank = 0; 725 726 // We want to put section specified by -T option first, so we 727 // can start assigning VA starting from them later. 728 if (Config->SectionStartMap.count(Sec->Name)) 729 return Rank; 730 Rank |= RF_NOT_ADDR_SET; 731 732 // Put .interp first because some loaders want to see that section 733 // on the first page of the executable file when loaded into memory. 734 if (Sec->Name == ".interp") 735 return Rank; 736 Rank |= RF_NOT_INTERP; 737 738 // Allocatable sections go first to reduce the total PT_LOAD size and 739 // so debug info doesn't change addresses in actual code. 740 if (!(Sec->Flags & SHF_ALLOC)) 741 return Rank | RF_NOT_ALLOC; 742 743 // Sort sections based on their access permission in the following 744 // order: R, RX, RWX, RW. This order is based on the following 745 // considerations: 746 // * Read-only sections come first such that they go in the 747 // PT_LOAD covering the program headers at the start of the file. 748 // * Read-only, executable sections come next. 749 // * Writable, executable sections follow such that .plt on 750 // architectures where it needs to be writable will be placed 751 // between .text and .data. 752 // * Writable sections come last, such that .bss lands at the very 753 // end of the last PT_LOAD. 754 bool IsExec = Sec->Flags & SHF_EXECINSTR; 755 bool IsWrite = Sec->Flags & SHF_WRITE; 756 757 if (IsExec) { 758 if (IsWrite) 759 Rank |= RF_EXEC_WRITE; 760 else 761 Rank |= RF_EXEC; 762 } else if (IsWrite) { 763 Rank |= RF_WRITE; 764 } else if (Sec->Type == SHT_PROGBITS) { 765 // Make non-executable and non-writable PROGBITS sections (e.g .rodata 766 // .eh_frame) closer to .text. They likely contain PC or GOT relative 767 // relocations and there could be relocation overflow if other huge sections 768 // (.dynstr .dynsym) were placed in between. 769 Rank |= RF_RODATA; 770 } 771 772 // If we got here we know that both A and B are in the same PT_LOAD. 773 774 bool IsTls = Sec->Flags & SHF_TLS; 775 bool IsNoBits = Sec->Type == SHT_NOBITS; 776 777 // The first requirement we have is to put (non-TLS) nobits sections last. The 778 // reason is that the only thing the dynamic linker will see about them is a 779 // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the 780 // PT_LOAD, so that has to correspond to the nobits sections. 781 bool IsNonTlsNoBits = IsNoBits && !IsTls; 782 if (IsNonTlsNoBits) 783 Rank |= RF_NON_TLS_BSS; 784 785 // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo 786 // sections after r/w ones, so that the RelRo sections are contiguous. 787 bool IsRelRo = isRelroSection(Sec); 788 if (IsNonTlsNoBits && !IsRelRo) 789 Rank |= RF_NON_TLS_BSS_RO; 790 if (!IsNonTlsNoBits && IsRelRo) 791 Rank |= RF_NON_TLS_BSS_RO; 792 793 // The TLS initialization block needs to be a single contiguous block in a R/W 794 // PT_LOAD, so stick TLS sections directly before the other RelRo R/W 795 // sections. The TLS NOBITS sections are placed here as they don't take up 796 // virtual address space in the PT_LOAD. 797 if (!IsTls) 798 Rank |= RF_NOT_TLS; 799 800 // Within the TLS initialization block, the non-nobits sections need to appear 801 // first. 802 if (IsNoBits) 803 Rank |= RF_BSS; 804 805 // We create a NOTE segment for contiguous .note sections, so make 806 // them contigous if there are more than one .note section with the 807 // same attributes. 808 if (Sec->Type == SHT_NOTE) 809 Rank |= RF_NOTE; 810 811 // Some architectures have additional ordering restrictions for sections 812 // within the same PT_LOAD. 813 if (Config->EMachine == EM_PPC64) { 814 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections 815 // that we would like to make sure appear is a specific order to maximize 816 // their coverage by a single signed 16-bit offset from the TOC base 817 // pointer. Conversely, the special .tocbss section should be first among 818 // all SHT_NOBITS sections. This will put it next to the loaded special 819 // PPC64 sections (and, thus, within reach of the TOC base pointer). 820 StringRef Name = Sec->Name; 821 if (Name != ".tocbss") 822 Rank |= RF_PPC_NOT_TOCBSS; 823 824 if (Name == ".toc1") 825 Rank |= RF_PPC_TOCL; 826 827 if (Name == ".toc") 828 Rank |= RF_PPC_TOC; 829 830 if (Name == ".got") 831 Rank |= RF_PPC_GOT; 832 833 if (Name == ".branch_lt") 834 Rank |= RF_PPC_BRANCH_LT; 835 } 836 837 if (Config->EMachine == EM_MIPS) { 838 // All sections with SHF_MIPS_GPREL flag should be grouped together 839 // because data in these sections is addressable with a gp relative address. 840 if (Sec->Flags & SHF_MIPS_GPREL) 841 Rank |= RF_MIPS_GPREL; 842 843 if (Sec->Name != ".got") 844 Rank |= RF_MIPS_NOT_GOT; 845 } 846 847 return Rank; 848 } 849 850 static bool compareSections(const BaseCommand *ACmd, const BaseCommand *BCmd) { 851 const OutputSection *A = cast<OutputSection>(ACmd); 852 const OutputSection *B = cast<OutputSection>(BCmd); 853 if (A->SortRank != B->SortRank) 854 return A->SortRank < B->SortRank; 855 if (!(A->SortRank & RF_NOT_ADDR_SET)) 856 return Config->SectionStartMap.lookup(A->Name) < 857 Config->SectionStartMap.lookup(B->Name); 858 return false; 859 } 860 861 void PhdrEntry::add(OutputSection *Sec) { 862 LastSec = Sec; 863 if (!FirstSec) 864 FirstSec = Sec; 865 p_align = std::max(p_align, Sec->Alignment); 866 if (p_type == PT_LOAD) 867 Sec->PtLoad = this; 868 } 869 870 // The beginning and the ending of .rel[a].plt section are marked 871 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked 872 // executable. The runtime needs these symbols in order to resolve 873 // all IRELATIVE relocs on startup. For dynamic executables, we don't 874 // need these symbols, since IRELATIVE relocs are resolved through GOT 875 // and PLT. For details, see http://www.airs.com/blog/archives/403. 876 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() { 877 if (needsInterpSection()) 878 return; 879 StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start"; 880 addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK); 881 882 S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end"; 883 ElfSym::RelaIpltEnd = 884 addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK); 885 } 886 887 template <class ELFT> 888 void Writer<ELFT>::forEachRelSec( 889 llvm::function_ref<void(InputSectionBase &)> Fn) { 890 // Scan all relocations. Each relocation goes through a series 891 // of tests to determine if it needs special treatment, such as 892 // creating GOT, PLT, copy relocations, etc. 893 // Note that relocations for non-alloc sections are directly 894 // processed by InputSection::relocateNonAlloc. 895 for (InputSectionBase *IS : InputSections) 896 if (IS->Live && isa<InputSection>(IS) && (IS->Flags & SHF_ALLOC)) 897 Fn(*IS); 898 for (EhInputSection *ES : InX::EhFrame->Sections) 899 Fn(*ES); 900 } 901 902 // This function generates assignments for predefined symbols (e.g. _end or 903 // _etext) and inserts them into the commands sequence to be processed at the 904 // appropriate time. This ensures that the value is going to be correct by the 905 // time any references to these symbols are processed and is equivalent to 906 // defining these symbols explicitly in the linker script. 907 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() { 908 if (ElfSym::GlobalOffsetTable) { 909 // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually 910 // to the start of the .got or .got.plt section. 911 InputSection *GotSection = InX::GotPlt; 912 if (!Target->GotBaseSymInGotPlt) 913 GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot) 914 : cast<InputSection>(InX::Got); 915 ElfSym::GlobalOffsetTable->Section = GotSection; 916 } 917 918 if (ElfSym::RelaIpltEnd) 919 ElfSym::RelaIpltEnd->Value = InX::RelaIplt->getSize(); 920 921 PhdrEntry *Last = nullptr; 922 PhdrEntry *LastRO = nullptr; 923 924 for (PhdrEntry *P : Phdrs) { 925 if (P->p_type != PT_LOAD) 926 continue; 927 Last = P; 928 if (!(P->p_flags & PF_W)) 929 LastRO = P; 930 } 931 932 if (LastRO) { 933 // _etext is the first location after the last read-only loadable segment. 934 if (ElfSym::Etext1) 935 ElfSym::Etext1->Section = LastRO->LastSec; 936 if (ElfSym::Etext2) 937 ElfSym::Etext2->Section = LastRO->LastSec; 938 } 939 940 if (Last) { 941 // _edata points to the end of the last mapped initialized section. 942 OutputSection *Edata = nullptr; 943 for (OutputSection *OS : OutputSections) { 944 if (OS->Type != SHT_NOBITS) 945 Edata = OS; 946 if (OS == Last->LastSec) 947 break; 948 } 949 950 if (ElfSym::Edata1) 951 ElfSym::Edata1->Section = Edata; 952 if (ElfSym::Edata2) 953 ElfSym::Edata2->Section = Edata; 954 955 // _end is the first location after the uninitialized data region. 956 if (ElfSym::End1) 957 ElfSym::End1->Section = Last->LastSec; 958 if (ElfSym::End2) 959 ElfSym::End2->Section = Last->LastSec; 960 } 961 962 if (ElfSym::Bss) 963 ElfSym::Bss->Section = findSection(".bss"); 964 965 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should 966 // be equal to the _gp symbol's value. 967 if (ElfSym::MipsGp) { 968 // Find GP-relative section with the lowest address 969 // and use this address to calculate default _gp value. 970 for (OutputSection *OS : OutputSections) { 971 if (OS->Flags & SHF_MIPS_GPREL) { 972 ElfSym::MipsGp->Section = OS; 973 ElfSym::MipsGp->Value = 0x7ff0; 974 break; 975 } 976 } 977 } 978 } 979 980 // We want to find how similar two ranks are. 981 // The more branches in getSectionRank that match, the more similar they are. 982 // Since each branch corresponds to a bit flag, we can just use 983 // countLeadingZeros. 984 static int getRankProximityAux(OutputSection *A, OutputSection *B) { 985 return countLeadingZeros(A->SortRank ^ B->SortRank); 986 } 987 988 static int getRankProximity(OutputSection *A, BaseCommand *B) { 989 if (auto *Sec = dyn_cast<OutputSection>(B)) 990 return getRankProximityAux(A, Sec); 991 return -1; 992 } 993 994 // When placing orphan sections, we want to place them after symbol assignments 995 // so that an orphan after 996 // begin_foo = .; 997 // foo : { *(foo) } 998 // end_foo = .; 999 // doesn't break the intended meaning of the begin/end symbols. 1000 // We don't want to go over sections since findOrphanPos is the 1001 // one in charge of deciding the order of the sections. 1002 // We don't want to go over changes to '.', since doing so in 1003 // rx_sec : { *(rx_sec) } 1004 // . = ALIGN(0x1000); 1005 // /* The RW PT_LOAD starts here*/ 1006 // rw_sec : { *(rw_sec) } 1007 // would mean that the RW PT_LOAD would become unaligned. 1008 static bool shouldSkip(BaseCommand *Cmd) { 1009 if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd)) 1010 return Assign->Name != "."; 1011 return false; 1012 } 1013 1014 // We want to place orphan sections so that they share as much 1015 // characteristics with their neighbors as possible. For example, if 1016 // both are rw, or both are tls. 1017 template <typename ELFT> 1018 static std::vector<BaseCommand *>::iterator 1019 findOrphanPos(std::vector<BaseCommand *>::iterator B, 1020 std::vector<BaseCommand *>::iterator E) { 1021 OutputSection *Sec = cast<OutputSection>(*E); 1022 1023 // Find the first element that has as close a rank as possible. 1024 auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) { 1025 return getRankProximity(Sec, A) < getRankProximity(Sec, B); 1026 }); 1027 if (I == E) 1028 return E; 1029 1030 // Consider all existing sections with the same proximity. 1031 int Proximity = getRankProximity(Sec, *I); 1032 for (; I != E; ++I) { 1033 auto *CurSec = dyn_cast<OutputSection>(*I); 1034 if (!CurSec) 1035 continue; 1036 if (getRankProximity(Sec, CurSec) != Proximity || 1037 Sec->SortRank < CurSec->SortRank) 1038 break; 1039 } 1040 1041 auto IsOutputSec = [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); }; 1042 auto J = std::find_if(llvm::make_reverse_iterator(I), 1043 llvm::make_reverse_iterator(B), IsOutputSec); 1044 I = J.base(); 1045 1046 // As a special case, if the orphan section is the last section, put 1047 // it at the very end, past any other commands. 1048 // This matches bfd's behavior and is convenient when the linker script fully 1049 // specifies the start of the file, but doesn't care about the end (the non 1050 // alloc sections for example). 1051 auto NextSec = std::find_if(I, E, IsOutputSec); 1052 if (NextSec == E) 1053 return E; 1054 1055 while (I != E && shouldSkip(*I)) 1056 ++I; 1057 return I; 1058 } 1059 1060 // Builds section order for handling --symbol-ordering-file. 1061 static DenseMap<const InputSectionBase *, int> buildSectionOrder() { 1062 DenseMap<const InputSectionBase *, int> SectionOrder; 1063 // Use the rarely used option -call-graph-ordering-file to sort sections. 1064 if (!Config->CallGraphProfile.empty()) 1065 return computeCallGraphProfileOrder(); 1066 1067 if (Config->SymbolOrderingFile.empty()) 1068 return SectionOrder; 1069 1070 struct SymbolOrderEntry { 1071 int Priority; 1072 bool Present; 1073 }; 1074 1075 // Build a map from symbols to their priorities. Symbols that didn't 1076 // appear in the symbol ordering file have the lowest priority 0. 1077 // All explicitly mentioned symbols have negative (higher) priorities. 1078 DenseMap<StringRef, SymbolOrderEntry> SymbolOrder; 1079 int Priority = -Config->SymbolOrderingFile.size(); 1080 for (StringRef S : Config->SymbolOrderingFile) 1081 SymbolOrder.insert({S, {Priority++, false}}); 1082 1083 // Build a map from sections to their priorities. 1084 auto AddSym = [&](Symbol &Sym) { 1085 auto It = SymbolOrder.find(Sym.getName()); 1086 if (It == SymbolOrder.end()) 1087 return; 1088 SymbolOrderEntry &Ent = It->second; 1089 Ent.Present = true; 1090 1091 warnUnorderableSymbol(&Sym); 1092 1093 if (auto *D = dyn_cast<Defined>(&Sym)) { 1094 if (auto *Sec = dyn_cast_or_null<InputSectionBase>(D->Section)) { 1095 int &Priority = SectionOrder[cast<InputSectionBase>(Sec->Repl)]; 1096 Priority = std::min(Priority, Ent.Priority); 1097 } 1098 } 1099 }; 1100 // We want both global and local symbols. We get the global ones from the 1101 // symbol table and iterate the object files for the local ones. 1102 for (Symbol *Sym : Symtab->getSymbols()) 1103 if (!Sym->isLazy()) 1104 AddSym(*Sym); 1105 for (InputFile *File : ObjectFiles) 1106 for (Symbol *Sym : File->getSymbols()) 1107 if (Sym->isLocal()) 1108 AddSym(*Sym); 1109 1110 if (Config->WarnSymbolOrdering) 1111 for (auto OrderEntry : SymbolOrder) 1112 if (!OrderEntry.second.Present) 1113 warn("symbol ordering file: no such symbol: " + OrderEntry.first); 1114 1115 return SectionOrder; 1116 } 1117 1118 // Sorts the sections in ISD according to the provided section order. 1119 static void 1120 sortISDBySectionOrder(InputSectionDescription *ISD, 1121 const DenseMap<const InputSectionBase *, int> &Order) { 1122 std::vector<InputSection *> UnorderedSections; 1123 std::vector<std::pair<InputSection *, int>> OrderedSections; 1124 uint64_t UnorderedSize = 0; 1125 1126 for (InputSection *IS : ISD->Sections) { 1127 auto I = Order.find(IS); 1128 if (I == Order.end()) { 1129 UnorderedSections.push_back(IS); 1130 UnorderedSize += IS->getSize(); 1131 continue; 1132 } 1133 OrderedSections.push_back({IS, I->second}); 1134 } 1135 llvm::sort( 1136 OrderedSections.begin(), OrderedSections.end(), 1137 [&](std::pair<InputSection *, int> A, std::pair<InputSection *, int> B) { 1138 return A.second < B.second; 1139 }); 1140 1141 // Find an insertion point for the ordered section list in the unordered 1142 // section list. On targets with limited-range branches, this is the mid-point 1143 // of the unordered section list. This decreases the likelihood that a range 1144 // extension thunk will be needed to enter or exit the ordered region. If the 1145 // ordered section list is a list of hot functions, we can generally expect 1146 // the ordered functions to be called more often than the unordered functions, 1147 // making it more likely that any particular call will be within range, and 1148 // therefore reducing the number of thunks required. 1149 // 1150 // For example, imagine that you have 8MB of hot code and 32MB of cold code. 1151 // If the layout is: 1152 // 1153 // 8MB hot 1154 // 32MB cold 1155 // 1156 // only the first 8-16MB of the cold code (depending on which hot function it 1157 // is actually calling) can call the hot code without a range extension thunk. 1158 // However, if we use this layout: 1159 // 1160 // 16MB cold 1161 // 8MB hot 1162 // 16MB cold 1163 // 1164 // both the last 8-16MB of the first block of cold code and the first 8-16MB 1165 // of the second block of cold code can call the hot code without a thunk. So 1166 // we effectively double the amount of code that could potentially call into 1167 // the hot code without a thunk. 1168 size_t InsPt = 0; 1169 if (Target->getThunkSectionSpacing() && !OrderedSections.empty()) { 1170 uint64_t UnorderedPos = 0; 1171 for (; InsPt != UnorderedSections.size(); ++InsPt) { 1172 UnorderedPos += UnorderedSections[InsPt]->getSize(); 1173 if (UnorderedPos > UnorderedSize / 2) 1174 break; 1175 } 1176 } 1177 1178 ISD->Sections.clear(); 1179 for (InputSection *IS : makeArrayRef(UnorderedSections).slice(0, InsPt)) 1180 ISD->Sections.push_back(IS); 1181 for (std::pair<InputSection *, int> P : OrderedSections) 1182 ISD->Sections.push_back(P.first); 1183 for (InputSection *IS : makeArrayRef(UnorderedSections).slice(InsPt)) 1184 ISD->Sections.push_back(IS); 1185 } 1186 1187 static void sortSection(OutputSection *Sec, 1188 const DenseMap<const InputSectionBase *, int> &Order) { 1189 StringRef Name = Sec->Name; 1190 1191 // Sort input sections by section name suffixes for 1192 // __attribute__((init_priority(N))). 1193 if (Name == ".init_array" || Name == ".fini_array") { 1194 if (!Script->HasSectionsCommand) 1195 Sec->sortInitFini(); 1196 return; 1197 } 1198 1199 // Sort input sections by the special rule for .ctors and .dtors. 1200 if (Name == ".ctors" || Name == ".dtors") { 1201 if (!Script->HasSectionsCommand) 1202 Sec->sortCtorsDtors(); 1203 return; 1204 } 1205 1206 // Never sort these. 1207 if (Name == ".init" || Name == ".fini") 1208 return; 1209 1210 // Sort input sections by priority using the list provided 1211 // by --symbol-ordering-file. 1212 if (!Order.empty()) 1213 for (BaseCommand *B : Sec->SectionCommands) 1214 if (auto *ISD = dyn_cast<InputSectionDescription>(B)) 1215 sortISDBySectionOrder(ISD, Order); 1216 } 1217 1218 // If no layout was provided by linker script, we want to apply default 1219 // sorting for special input sections. This also handles --symbol-ordering-file. 1220 template <class ELFT> void Writer<ELFT>::sortInputSections() { 1221 // Build the order once since it is expensive. 1222 DenseMap<const InputSectionBase *, int> Order = buildSectionOrder(); 1223 for (BaseCommand *Base : Script->SectionCommands) 1224 if (auto *Sec = dyn_cast<OutputSection>(Base)) 1225 sortSection(Sec, Order); 1226 } 1227 1228 template <class ELFT> void Writer<ELFT>::sortSections() { 1229 Script->adjustSectionsBeforeSorting(); 1230 1231 // Don't sort if using -r. It is not necessary and we want to preserve the 1232 // relative order for SHF_LINK_ORDER sections. 1233 if (Config->Relocatable) 1234 return; 1235 1236 sortInputSections(); 1237 1238 for (BaseCommand *Base : Script->SectionCommands) { 1239 auto *OS = dyn_cast<OutputSection>(Base); 1240 if (!OS) 1241 continue; 1242 OS->SortRank = getSectionRank(OS); 1243 1244 // We want to assign rude approximation values to OutSecOff fields 1245 // to know the relative order of the input sections. We use it for 1246 // sorting SHF_LINK_ORDER sections. See resolveShfLinkOrder(). 1247 uint64_t I = 0; 1248 for (InputSection *Sec : getInputSections(OS)) 1249 Sec->OutSecOff = I++; 1250 } 1251 1252 if (!Script->HasSectionsCommand) { 1253 // We know that all the OutputSections are contiguous in this case. 1254 auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); }; 1255 std::stable_sort( 1256 llvm::find_if(Script->SectionCommands, IsSection), 1257 llvm::find_if(llvm::reverse(Script->SectionCommands), IsSection).base(), 1258 compareSections); 1259 return; 1260 } 1261 1262 // Orphan sections are sections present in the input files which are 1263 // not explicitly placed into the output file by the linker script. 1264 // 1265 // The sections in the linker script are already in the correct 1266 // order. We have to figuere out where to insert the orphan 1267 // sections. 1268 // 1269 // The order of the sections in the script is arbitrary and may not agree with 1270 // compareSections. This means that we cannot easily define a strict weak 1271 // ordering. To see why, consider a comparison of a section in the script and 1272 // one not in the script. We have a two simple options: 1273 // * Make them equivalent (a is not less than b, and b is not less than a). 1274 // The problem is then that equivalence has to be transitive and we can 1275 // have sections a, b and c with only b in a script and a less than c 1276 // which breaks this property. 1277 // * Use compareSectionsNonScript. Given that the script order doesn't have 1278 // to match, we can end up with sections a, b, c, d where b and c are in the 1279 // script and c is compareSectionsNonScript less than b. In which case d 1280 // can be equivalent to c, a to b and d < a. As a concrete example: 1281 // .a (rx) # not in script 1282 // .b (rx) # in script 1283 // .c (ro) # in script 1284 // .d (ro) # not in script 1285 // 1286 // The way we define an order then is: 1287 // * Sort only the orphan sections. They are in the end right now. 1288 // * Move each orphan section to its preferred position. We try 1289 // to put each section in the last position where it can share 1290 // a PT_LOAD. 1291 // 1292 // There is some ambiguity as to where exactly a new entry should be 1293 // inserted, because Commands contains not only output section 1294 // commands but also other types of commands such as symbol assignment 1295 // expressions. There's no correct answer here due to the lack of the 1296 // formal specification of the linker script. We use heuristics to 1297 // determine whether a new output command should be added before or 1298 // after another commands. For the details, look at shouldSkip 1299 // function. 1300 1301 auto I = Script->SectionCommands.begin(); 1302 auto E = Script->SectionCommands.end(); 1303 auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) { 1304 if (auto *Sec = dyn_cast<OutputSection>(Base)) 1305 return Sec->SectionIndex == UINT32_MAX; 1306 return false; 1307 }); 1308 1309 // Sort the orphan sections. 1310 std::stable_sort(NonScriptI, E, compareSections); 1311 1312 // As a horrible special case, skip the first . assignment if it is before any 1313 // section. We do this because it is common to set a load address by starting 1314 // the script with ". = 0xabcd" and the expectation is that every section is 1315 // after that. 1316 auto FirstSectionOrDotAssignment = 1317 std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); }); 1318 if (FirstSectionOrDotAssignment != E && 1319 isa<SymbolAssignment>(**FirstSectionOrDotAssignment)) 1320 ++FirstSectionOrDotAssignment; 1321 I = FirstSectionOrDotAssignment; 1322 1323 while (NonScriptI != E) { 1324 auto Pos = findOrphanPos<ELFT>(I, NonScriptI); 1325 OutputSection *Orphan = cast<OutputSection>(*NonScriptI); 1326 1327 // As an optimization, find all sections with the same sort rank 1328 // and insert them with one rotate. 1329 unsigned Rank = Orphan->SortRank; 1330 auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) { 1331 return cast<OutputSection>(Cmd)->SortRank != Rank; 1332 }); 1333 std::rotate(Pos, NonScriptI, End); 1334 NonScriptI = End; 1335 } 1336 1337 Script->adjustSectionsAfterSorting(); 1338 } 1339 1340 static bool compareByFilePosition(InputSection *A, InputSection *B) { 1341 // Synthetic, i. e. a sentinel section, should go last. 1342 if (A->kind() == InputSectionBase::Synthetic || 1343 B->kind() == InputSectionBase::Synthetic) 1344 return A->kind() != InputSectionBase::Synthetic; 1345 InputSection *LA = A->getLinkOrderDep(); 1346 InputSection *LB = B->getLinkOrderDep(); 1347 OutputSection *AOut = LA->getParent(); 1348 OutputSection *BOut = LB->getParent(); 1349 if (AOut != BOut) 1350 return AOut->SectionIndex < BOut->SectionIndex; 1351 return LA->OutSecOff < LB->OutSecOff; 1352 } 1353 1354 // This function is used by the --merge-exidx-entries to detect duplicate 1355 // .ARM.exidx sections. It is Arm only. 1356 // 1357 // The .ARM.exidx section is of the form: 1358 // | PREL31 offset to function | Unwind instructions for function | 1359 // where the unwind instructions are either a small number of unwind 1360 // instructions inlined into the table entry, the special CANT_UNWIND value of 1361 // 0x1 or a PREL31 offset into a .ARM.extab Section that contains unwind 1362 // instructions. 1363 // 1364 // We return true if all the unwind instructions in the .ARM.exidx entries of 1365 // Cur can be merged into the last entry of Prev. 1366 static bool isDuplicateArmExidxSec(InputSection *Prev, InputSection *Cur) { 1367 1368 // References to .ARM.Extab Sections have bit 31 clear and are not the 1369 // special EXIDX_CANTUNWIND bit-pattern. 1370 auto IsExtabRef = [](uint32_t Unwind) { 1371 return (Unwind & 0x80000000) == 0 && Unwind != 0x1; 1372 }; 1373 1374 struct ExidxEntry { 1375 ulittle32_t Fn; 1376 ulittle32_t Unwind; 1377 }; 1378 1379 // Get the last table Entry from the previous .ARM.exidx section. 1380 const ExidxEntry &PrevEntry = Prev->getDataAs<ExidxEntry>().back(); 1381 if (IsExtabRef(PrevEntry.Unwind)) 1382 return false; 1383 1384 // We consider the unwind instructions of an .ARM.exidx table entry 1385 // a duplicate if the previous unwind instructions if: 1386 // - Both are the special EXIDX_CANTUNWIND. 1387 // - Both are the same inline unwind instructions. 1388 // We do not attempt to follow and check links into .ARM.extab tables as 1389 // consecutive identical entries are rare and the effort to check that they 1390 // are identical is high. 1391 1392 for (const ExidxEntry Entry : Cur->getDataAs<ExidxEntry>()) 1393 if (IsExtabRef(Entry.Unwind) || Entry.Unwind != PrevEntry.Unwind) 1394 return false; 1395 // All table entries in this .ARM.exidx Section can be merged into the 1396 // previous Section. 1397 return true; 1398 } 1399 1400 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() { 1401 for (OutputSection *Sec : OutputSections) { 1402 if (!(Sec->Flags & SHF_LINK_ORDER)) 1403 continue; 1404 1405 // Link order may be distributed across several InputSectionDescriptions 1406 // but sort must consider them all at once. 1407 std::vector<InputSection **> ScriptSections; 1408 std::vector<InputSection *> Sections; 1409 for (BaseCommand *Base : Sec->SectionCommands) { 1410 if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) { 1411 for (InputSection *&IS : ISD->Sections) { 1412 ScriptSections.push_back(&IS); 1413 Sections.push_back(IS); 1414 } 1415 } 1416 } 1417 std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition); 1418 1419 if (!Config->Relocatable && Config->EMachine == EM_ARM && 1420 Sec->Type == SHT_ARM_EXIDX) { 1421 1422 if (auto *Sentinel = dyn_cast<ARMExidxSentinelSection>(Sections.back())) { 1423 assert(Sections.size() >= 2 && 1424 "We should create a sentinel section only if there are " 1425 "alive regular exidx sections."); 1426 // The last executable section is required to fill the sentinel. 1427 // Remember it here so that we don't have to find it again. 1428 Sentinel->Highest = Sections[Sections.size() - 2]->getLinkOrderDep(); 1429 } 1430 1431 if (Config->MergeArmExidx) { 1432 // The EHABI for the Arm Architecture permits consecutive identical 1433 // table entries to be merged. We use a simple implementation that 1434 // removes a .ARM.exidx Input Section if it can be merged into the 1435 // previous one. This does not require any rewriting of InputSection 1436 // contents but misses opportunities for fine grained deduplication 1437 // where only a subset of the InputSection contents can be merged. 1438 size_t Prev = 0; 1439 // The last one is a sentinel entry which should not be removed. 1440 for (size_t I = 1; I < Sections.size() - 1; ++I) { 1441 if (isDuplicateArmExidxSec(Sections[Prev], Sections[I])) 1442 Sections[I] = nullptr; 1443 else 1444 Prev = I; 1445 } 1446 } 1447 } 1448 1449 for (int I = 0, N = Sections.size(); I < N; ++I) 1450 *ScriptSections[I] = Sections[I]; 1451 1452 // Remove the Sections we marked as duplicate earlier. 1453 for (BaseCommand *Base : Sec->SectionCommands) 1454 if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) 1455 llvm::erase_if(ISD->Sections, [](InputSection *IS) { return !IS; }); 1456 } 1457 } 1458 1459 static void applySynthetic(const std::vector<SyntheticSection *> &Sections, 1460 llvm::function_ref<void(SyntheticSection *)> Fn) { 1461 for (SyntheticSection *SS : Sections) 1462 if (SS && SS->getParent() && !SS->empty()) 1463 Fn(SS); 1464 } 1465 1466 // In order to allow users to manipulate linker-synthesized sections, 1467 // we had to add synthetic sections to the input section list early, 1468 // even before we make decisions whether they are needed. This allows 1469 // users to write scripts like this: ".mygot : { .got }". 1470 // 1471 // Doing it has an unintended side effects. If it turns out that we 1472 // don't need a .got (for example) at all because there's no 1473 // relocation that needs a .got, we don't want to emit .got. 1474 // 1475 // To deal with the above problem, this function is called after 1476 // scanRelocations is called to remove synthetic sections that turn 1477 // out to be empty. 1478 static void removeUnusedSyntheticSections() { 1479 // All input synthetic sections that can be empty are placed after 1480 // all regular ones. We iterate over them all and exit at first 1481 // non-synthetic. 1482 for (InputSectionBase *S : llvm::reverse(InputSections)) { 1483 SyntheticSection *SS = dyn_cast<SyntheticSection>(S); 1484 if (!SS) 1485 return; 1486 OutputSection *OS = SS->getParent(); 1487 if (!OS || !SS->empty()) 1488 continue; 1489 1490 // If we reach here, then SS is an unused synthetic section and we want to 1491 // remove it from corresponding input section description of output section. 1492 for (BaseCommand *B : OS->SectionCommands) 1493 if (auto *ISD = dyn_cast<InputSectionDescription>(B)) 1494 llvm::erase_if(ISD->Sections, 1495 [=](InputSection *IS) { return IS == SS; }); 1496 } 1497 } 1498 1499 // Returns true if a symbol can be replaced at load-time by a symbol 1500 // with the same name defined in other ELF executable or DSO. 1501 static bool computeIsPreemptible(const Symbol &B) { 1502 assert(!B.isLocal()); 1503 // Only symbols that appear in dynsym can be preempted. 1504 if (!B.includeInDynsym()) 1505 return false; 1506 1507 // Only default visibility symbols can be preempted. 1508 if (B.Visibility != STV_DEFAULT) 1509 return false; 1510 1511 // At this point copy relocations have not been created yet, so any 1512 // symbol that is not defined locally is preemptible. 1513 if (!B.isDefined()) 1514 return true; 1515 1516 // If we have a dynamic list it specifies which local symbols are preemptible. 1517 if (Config->HasDynamicList) 1518 return false; 1519 1520 if (!Config->Shared) 1521 return false; 1522 1523 // -Bsymbolic means that definitions are not preempted. 1524 if (Config->Bsymbolic || (Config->BsymbolicFunctions && B.isFunc())) 1525 return false; 1526 return true; 1527 } 1528 1529 // Create output section objects and add them to OutputSections. 1530 template <class ELFT> void Writer<ELFT>::finalizeSections() { 1531 Out::DebugInfo = findSection(".debug_info"); 1532 Out::PreinitArray = findSection(".preinit_array"); 1533 Out::InitArray = findSection(".init_array"); 1534 Out::FiniArray = findSection(".fini_array"); 1535 1536 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop 1537 // symbols for sections, so that the runtime can get the start and end 1538 // addresses of each section by section name. Add such symbols. 1539 if (!Config->Relocatable) { 1540 addStartEndSymbols(); 1541 for (BaseCommand *Base : Script->SectionCommands) 1542 if (auto *Sec = dyn_cast<OutputSection>(Base)) 1543 addStartStopSymbols(Sec); 1544 } 1545 1546 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type. 1547 // It should be okay as no one seems to care about the type. 1548 // Even the author of gold doesn't remember why gold behaves that way. 1549 // https://sourceware.org/ml/binutils/2002-03/msg00360.html 1550 if (InX::DynSymTab) 1551 Symtab->addRegular("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/, 1552 /*Size=*/0, STB_WEAK, InX::Dynamic, 1553 /*File=*/nullptr); 1554 1555 // Define __rel[a]_iplt_{start,end} symbols if needed. 1556 addRelIpltSymbols(); 1557 1558 // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800 if not defined. 1559 if (Config->EMachine == EM_RISCV) { 1560 ElfSym::RISCVGlobalPointer = 1561 dyn_cast_or_null<Defined>(Symtab->find("__global_pointer$")); 1562 if (!ElfSym::RISCVGlobalPointer) 1563 ElfSym::RISCVGlobalPointer = 1564 addOptionalRegular("__global_pointer$", findSection(".sdata"), 0x800); 1565 } 1566 1567 // This responsible for splitting up .eh_frame section into 1568 // pieces. The relocation scan uses those pieces, so this has to be 1569 // earlier. 1570 applySynthetic({InX::EhFrame}, 1571 [](SyntheticSection *SS) { SS->finalizeContents(); }); 1572 1573 for (Symbol *S : Symtab->getSymbols()) 1574 S->IsPreemptible |= computeIsPreemptible(*S); 1575 1576 // Scan relocations. This must be done after every symbol is declared so that 1577 // we can correctly decide if a dynamic relocation is needed. 1578 if (!Config->Relocatable) 1579 forEachRelSec(scanRelocations<ELFT>); 1580 1581 if (InX::Plt && !InX::Plt->empty()) 1582 InX::Plt->addSymbols(); 1583 if (InX::Iplt && !InX::Iplt->empty()) 1584 InX::Iplt->addSymbols(); 1585 1586 // Now that we have defined all possible global symbols including linker- 1587 // synthesized ones. Visit all symbols to give the finishing touches. 1588 for (Symbol *Sym : Symtab->getSymbols()) { 1589 if (!includeInSymtab(*Sym)) 1590 continue; 1591 if (InX::SymTab) 1592 InX::SymTab->addSymbol(Sym); 1593 1594 if (InX::DynSymTab && Sym->includeInDynsym()) { 1595 InX::DynSymTab->addSymbol(Sym); 1596 if (auto *File = dyn_cast_or_null<SharedFile<ELFT>>(Sym->File)) 1597 if (File->IsNeeded && !Sym->isUndefined()) 1598 In<ELFT>::VerNeed->addSymbol(Sym); 1599 } 1600 } 1601 1602 // Do not proceed if there was an undefined symbol. 1603 if (errorCount()) 1604 return; 1605 1606 if (InX::MipsGot) 1607 InX::MipsGot->build<ELFT>(); 1608 1609 removeUnusedSyntheticSections(); 1610 1611 sortSections(); 1612 1613 // Now that we have the final list, create a list of all the 1614 // OutputSections for convenience. 1615 for (BaseCommand *Base : Script->SectionCommands) 1616 if (auto *Sec = dyn_cast<OutputSection>(Base)) 1617 OutputSections.push_back(Sec); 1618 1619 // Ensure data sections are not mixed with executable sections when 1620 // -execute-only is used. 1621 if (Config->ExecuteOnly) 1622 for (OutputSection *OS : OutputSections) 1623 if (OS->Flags & SHF_EXECINSTR) 1624 for (InputSection *IS : getInputSections(OS)) 1625 if (!(IS->Flags & SHF_EXECINSTR)) 1626 error("-execute-only does not support intermingling data and code"); 1627 1628 // Prefer command line supplied address over other constraints. 1629 for (OutputSection *Sec : OutputSections) { 1630 auto I = Config->SectionStartMap.find(Sec->Name); 1631 if (I != Config->SectionStartMap.end()) 1632 Sec->AddrExpr = [=] { return I->second; }; 1633 } 1634 1635 // This is a bit of a hack. A value of 0 means undef, so we set it 1636 // to 1 to make __ehdr_start defined. The section number is not 1637 // particularly relevant. 1638 Out::ElfHeader->SectionIndex = 1; 1639 1640 unsigned I = 1; 1641 for (OutputSection *Sec : OutputSections) { 1642 Sec->SectionIndex = I++; 1643 Sec->ShName = InX::ShStrTab->addString(Sec->Name); 1644 } 1645 1646 // Binary and relocatable output does not have PHDRS. 1647 // The headers have to be created before finalize as that can influence the 1648 // image base and the dynamic section on mips includes the image base. 1649 if (!Config->Relocatable && !Config->OFormatBinary) { 1650 Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs(); 1651 addPtArmExid(Phdrs); 1652 Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size(); 1653 } 1654 1655 // Some symbols are defined in term of program headers. Now that we 1656 // have the headers, we can find out which sections they point to. 1657 setReservedSymbolSections(); 1658 1659 // Dynamic section must be the last one in this list and dynamic 1660 // symbol table section (DynSymTab) must be the first one. 1661 applySynthetic( 1662 {InX::DynSymTab, InX::Bss, InX::BssRelRo, InX::GnuHashTab, 1663 InX::HashTab, InX::SymTabShndx, InX::ShStrTab, InX::StrTab, 1664 In<ELFT>::VerDef, InX::DynStrTab, InX::Got, InX::MipsGot, 1665 InX::IgotPlt, InX::GotPlt, InX::RelaDyn, InX::RelrDyn, 1666 InX::RelaIplt, InX::RelaPlt, InX::Plt, InX::Iplt, 1667 InX::EhFrameHdr, In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic}, 1668 [](SyntheticSection *SS) { SS->finalizeContents(); }); 1669 1670 if (!Script->HasSectionsCommand && !Config->Relocatable) 1671 fixSectionAlignments(); 1672 1673 // After link order processing .ARM.exidx sections can be deduplicated, which 1674 // needs to be resolved before any other address dependent operation. 1675 resolveShfLinkOrder(); 1676 1677 // Some architectures need to generate content that depends on the address 1678 // of InputSections. For example some architectures use small displacements 1679 // for jump instructions that is the linker's responsibility for creating 1680 // range extension thunks for. As the generation of the content may also 1681 // alter InputSection addresses we must converge to a fixed point. 1682 if (Target->NeedsThunks || Config->AndroidPackDynRelocs || 1683 Config->RelrPackDynRelocs) { 1684 ThunkCreator TC; 1685 AArch64Err843419Patcher A64P; 1686 bool Changed; 1687 do { 1688 Script->assignAddresses(); 1689 Changed = false; 1690 if (Target->NeedsThunks) 1691 Changed |= TC.createThunks(OutputSections); 1692 if (Config->FixCortexA53Errata843419) { 1693 if (Changed) 1694 Script->assignAddresses(); 1695 Changed |= A64P.createFixes(); 1696 } 1697 if (InX::MipsGot) 1698 InX::MipsGot->updateAllocSize(); 1699 Changed |= InX::RelaDyn->updateAllocSize(); 1700 if (InX::RelrDyn) 1701 Changed |= InX::RelrDyn->updateAllocSize(); 1702 } while (Changed); 1703 } 1704 1705 // createThunks may have added local symbols to the static symbol table 1706 applySynthetic({InX::SymTab}, 1707 [](SyntheticSection *SS) { SS->finalizeContents(); }); 1708 1709 // Fill other section headers. The dynamic table is finalized 1710 // at the end because some tags like RELSZ depend on result 1711 // of finalizing other sections. 1712 for (OutputSection *Sec : OutputSections) 1713 Sec->finalize<ELFT>(); 1714 } 1715 1716 // The linker is expected to define SECNAME_start and SECNAME_end 1717 // symbols for a few sections. This function defines them. 1718 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() { 1719 // If a section does not exist, there's ambiguity as to how we 1720 // define _start and _end symbols for an init/fini section. Since 1721 // the loader assume that the symbols are always defined, we need to 1722 // always define them. But what value? The loader iterates over all 1723 // pointers between _start and _end to run global ctors/dtors, so if 1724 // the section is empty, their symbol values don't actually matter 1725 // as long as _start and _end point to the same location. 1726 // 1727 // That said, we don't want to set the symbols to 0 (which is 1728 // probably the simplest value) because that could cause some 1729 // program to fail to link due to relocation overflow, if their 1730 // program text is above 2 GiB. We use the address of the .text 1731 // section instead to prevent that failure. 1732 OutputSection *Default = findSection(".text"); 1733 if (!Default) 1734 Default = Out::ElfHeader; 1735 auto Define = [=](StringRef Start, StringRef End, OutputSection *OS) { 1736 if (OS) { 1737 addOptionalRegular(Start, OS, 0); 1738 addOptionalRegular(End, OS, -1); 1739 } else { 1740 addOptionalRegular(Start, Default, 0); 1741 addOptionalRegular(End, Default, 0); 1742 } 1743 }; 1744 1745 Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray); 1746 Define("__init_array_start", "__init_array_end", Out::InitArray); 1747 Define("__fini_array_start", "__fini_array_end", Out::FiniArray); 1748 1749 if (OutputSection *Sec = findSection(".ARM.exidx")) 1750 Define("__exidx_start", "__exidx_end", Sec); 1751 } 1752 1753 // If a section name is valid as a C identifier (which is rare because of 1754 // the leading '.'), linkers are expected to define __start_<secname> and 1755 // __stop_<secname> symbols. They are at beginning and end of the section, 1756 // respectively. This is not requested by the ELF standard, but GNU ld and 1757 // gold provide the feature, and used by many programs. 1758 template <class ELFT> 1759 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) { 1760 StringRef S = Sec->Name; 1761 if (!isValidCIdentifier(S)) 1762 return; 1763 addOptionalRegular(Saver.save("__start_" + S), Sec, 0, STV_PROTECTED); 1764 addOptionalRegular(Saver.save("__stop_" + S), Sec, -1, STV_PROTECTED); 1765 } 1766 1767 static bool needsPtLoad(OutputSection *Sec) { 1768 if (!(Sec->Flags & SHF_ALLOC) || Sec->Noload) 1769 return false; 1770 1771 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is 1772 // responsible for allocating space for them, not the PT_LOAD that 1773 // contains the TLS initialization image. 1774 if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS) 1775 return false; 1776 return true; 1777 } 1778 1779 // Linker scripts are responsible for aligning addresses. Unfortunately, most 1780 // linker scripts are designed for creating two PT_LOADs only, one RX and one 1781 // RW. This means that there is no alignment in the RO to RX transition and we 1782 // cannot create a PT_LOAD there. 1783 static uint64_t computeFlags(uint64_t Flags) { 1784 if (Config->Omagic) 1785 return PF_R | PF_W | PF_X; 1786 if (Config->ExecuteOnly && (Flags & PF_X)) 1787 return Flags & ~PF_R; 1788 if (Config->SingleRoRx && !(Flags & PF_W)) 1789 return Flags | PF_X; 1790 return Flags; 1791 } 1792 1793 // Decide which program headers to create and which sections to include in each 1794 // one. 1795 template <class ELFT> std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs() { 1796 std::vector<PhdrEntry *> Ret; 1797 auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * { 1798 Ret.push_back(make<PhdrEntry>(Type, Flags)); 1799 return Ret.back(); 1800 }; 1801 1802 // The first phdr entry is PT_PHDR which describes the program header itself. 1803 AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders); 1804 1805 // PT_INTERP must be the second entry if exists. 1806 if (OutputSection *Cmd = findSection(".interp")) 1807 AddHdr(PT_INTERP, Cmd->getPhdrFlags())->add(Cmd); 1808 1809 // Add the first PT_LOAD segment for regular output sections. 1810 uint64_t Flags = computeFlags(PF_R); 1811 PhdrEntry *Load = AddHdr(PT_LOAD, Flags); 1812 1813 // Add the headers. We will remove them if they don't fit. 1814 Load->add(Out::ElfHeader); 1815 Load->add(Out::ProgramHeaders); 1816 1817 for (OutputSection *Sec : OutputSections) { 1818 if (!(Sec->Flags & SHF_ALLOC)) 1819 break; 1820 if (!needsPtLoad(Sec)) 1821 continue; 1822 1823 // Segments are contiguous memory regions that has the same attributes 1824 // (e.g. executable or writable). There is one phdr for each segment. 1825 // Therefore, we need to create a new phdr when the next section has 1826 // different flags or is loaded at a discontiguous address or memory 1827 // region using AT or AT> linker script command, respectively. At the same 1828 // time, we don't want to create a separate load segment for the headers, 1829 // even if the first output section has an AT or AT> attribute. 1830 uint64_t NewFlags = computeFlags(Sec->getPhdrFlags()); 1831 if (((Sec->LMAExpr || 1832 (Sec->LMARegion && (Sec->LMARegion != Load->FirstSec->LMARegion))) && 1833 Load->LastSec != Out::ProgramHeaders) || 1834 Sec->MemRegion != Load->FirstSec->MemRegion || Flags != NewFlags) { 1835 1836 Load = AddHdr(PT_LOAD, NewFlags); 1837 Flags = NewFlags; 1838 } 1839 1840 Load->add(Sec); 1841 } 1842 1843 // Add a TLS segment if any. 1844 PhdrEntry *TlsHdr = make<PhdrEntry>(PT_TLS, PF_R); 1845 for (OutputSection *Sec : OutputSections) 1846 if (Sec->Flags & SHF_TLS) 1847 TlsHdr->add(Sec); 1848 if (TlsHdr->FirstSec) 1849 Ret.push_back(TlsHdr); 1850 1851 // Add an entry for .dynamic. 1852 if (InX::DynSymTab) 1853 AddHdr(PT_DYNAMIC, InX::Dynamic->getParent()->getPhdrFlags()) 1854 ->add(InX::Dynamic->getParent()); 1855 1856 // PT_GNU_RELRO includes all sections that should be marked as 1857 // read-only by dynamic linker after proccessing relocations. 1858 // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give 1859 // an error message if more than one PT_GNU_RELRO PHDR is required. 1860 PhdrEntry *RelRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R); 1861 bool InRelroPhdr = false; 1862 bool IsRelroFinished = false; 1863 for (OutputSection *Sec : OutputSections) { 1864 if (!needsPtLoad(Sec)) 1865 continue; 1866 if (isRelroSection(Sec)) { 1867 InRelroPhdr = true; 1868 if (!IsRelroFinished) 1869 RelRo->add(Sec); 1870 else 1871 error("section: " + Sec->Name + " is not contiguous with other relro" + 1872 " sections"); 1873 } else if (InRelroPhdr) { 1874 InRelroPhdr = false; 1875 IsRelroFinished = true; 1876 } 1877 } 1878 if (RelRo->FirstSec) 1879 Ret.push_back(RelRo); 1880 1881 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr. 1882 if (!InX::EhFrame->empty() && InX::EhFrameHdr && InX::EhFrame->getParent() && 1883 InX::EhFrameHdr->getParent()) 1884 AddHdr(PT_GNU_EH_FRAME, InX::EhFrameHdr->getParent()->getPhdrFlags()) 1885 ->add(InX::EhFrameHdr->getParent()); 1886 1887 // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes 1888 // the dynamic linker fill the segment with random data. 1889 if (OutputSection *Cmd = findSection(".openbsd.randomdata")) 1890 AddHdr(PT_OPENBSD_RANDOMIZE, Cmd->getPhdrFlags())->add(Cmd); 1891 1892 // PT_GNU_STACK is a special section to tell the loader to make the 1893 // pages for the stack non-executable. If you really want an executable 1894 // stack, you can pass -z execstack, but that's not recommended for 1895 // security reasons. 1896 unsigned Perm = PF_R | PF_W; 1897 if (Config->ZExecstack) 1898 Perm |= PF_X; 1899 AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize; 1900 1901 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable 1902 // is expected to perform W^X violations, such as calling mprotect(2) or 1903 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on 1904 // OpenBSD. 1905 if (Config->ZWxneeded) 1906 AddHdr(PT_OPENBSD_WXNEEDED, PF_X); 1907 1908 // Create one PT_NOTE per a group of contiguous .note sections. 1909 PhdrEntry *Note = nullptr; 1910 for (OutputSection *Sec : OutputSections) { 1911 if (Sec->Type == SHT_NOTE && (Sec->Flags & SHF_ALLOC)) { 1912 if (!Note || Sec->LMAExpr) 1913 Note = AddHdr(PT_NOTE, PF_R); 1914 Note->add(Sec); 1915 } else { 1916 Note = nullptr; 1917 } 1918 } 1919 return Ret; 1920 } 1921 1922 template <class ELFT> 1923 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry *> &Phdrs) { 1924 if (Config->EMachine != EM_ARM) 1925 return; 1926 auto I = llvm::find_if(OutputSections, [](OutputSection *Cmd) { 1927 return Cmd->Type == SHT_ARM_EXIDX; 1928 }); 1929 if (I == OutputSections.end()) 1930 return; 1931 1932 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME 1933 PhdrEntry *ARMExidx = make<PhdrEntry>(PT_ARM_EXIDX, PF_R); 1934 ARMExidx->add(*I); 1935 Phdrs.push_back(ARMExidx); 1936 } 1937 1938 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the 1939 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic 1940 // linker can set the permissions. 1941 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() { 1942 auto PageAlign = [](OutputSection *Cmd) { 1943 if (Cmd && !Cmd->AddrExpr) 1944 Cmd->AddrExpr = [=] { 1945 return alignTo(Script->getDot(), Config->MaxPageSize); 1946 }; 1947 }; 1948 1949 for (const PhdrEntry *P : Phdrs) 1950 if (P->p_type == PT_LOAD && P->FirstSec) 1951 PageAlign(P->FirstSec); 1952 1953 for (const PhdrEntry *P : Phdrs) { 1954 if (P->p_type != PT_GNU_RELRO) 1955 continue; 1956 if (P->FirstSec) 1957 PageAlign(P->FirstSec); 1958 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we 1959 // have to align it to a page. 1960 auto End = OutputSections.end(); 1961 auto I = std::find(OutputSections.begin(), End, P->LastSec); 1962 if (I == End || (I + 1) == End) 1963 continue; 1964 OutputSection *Cmd = (*(I + 1)); 1965 if (needsPtLoad(Cmd)) 1966 PageAlign(Cmd); 1967 } 1968 } 1969 1970 // Adjusts the file alignment for a given output section and returns 1971 // its new file offset. The file offset must be the same with its 1972 // virtual address (modulo the page size) so that the loader can load 1973 // executables without any address adjustment. 1974 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Cmd) { 1975 OutputSection *First = Cmd->PtLoad ? Cmd->PtLoad->FirstSec : nullptr; 1976 // The first section in a PT_LOAD has to have congruent offset and address 1977 // module the page size. 1978 if (Cmd == First) 1979 return alignTo(Off, std::max<uint64_t>(Cmd->Alignment, Config->MaxPageSize), 1980 Cmd->Addr); 1981 1982 // For SHT_NOBITS we don't want the alignment of the section to impact the 1983 // offset of the sections that follow. Since nothing seems to care about the 1984 // sh_offset of the SHT_NOBITS section itself, just ignore it. 1985 if (Cmd->Type == SHT_NOBITS) 1986 return Off; 1987 1988 // If the section is not in a PT_LOAD, we just have to align it. 1989 if (!Cmd->PtLoad) 1990 return alignTo(Off, Cmd->Alignment); 1991 1992 // If two sections share the same PT_LOAD the file offset is calculated 1993 // using this formula: Off2 = Off1 + (VA2 - VA1). 1994 return First->Offset + Cmd->Addr - First->Addr; 1995 } 1996 1997 static uint64_t setOffset(OutputSection *Cmd, uint64_t Off) { 1998 Off = getFileAlignment(Off, Cmd); 1999 Cmd->Offset = Off; 2000 2001 // For SHT_NOBITS we should not count the size. 2002 if (Cmd->Type == SHT_NOBITS) 2003 return Off; 2004 2005 return Off + Cmd->Size; 2006 } 2007 2008 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() { 2009 uint64_t Off = 0; 2010 for (OutputSection *Sec : OutputSections) 2011 if (Sec->Flags & SHF_ALLOC) 2012 Off = setOffset(Sec, Off); 2013 FileSize = alignTo(Off, Config->Wordsize); 2014 } 2015 2016 static std::string rangeToString(uint64_t Addr, uint64_t Len) { 2017 return "[0x" + utohexstr(Addr) + ", 0x" + utohexstr(Addr + Len - 1) + "]"; 2018 } 2019 2020 // Assign file offsets to output sections. 2021 template <class ELFT> void Writer<ELFT>::assignFileOffsets() { 2022 uint64_t Off = 0; 2023 Off = setOffset(Out::ElfHeader, Off); 2024 Off = setOffset(Out::ProgramHeaders, Off); 2025 2026 PhdrEntry *LastRX = nullptr; 2027 for (PhdrEntry *P : Phdrs) 2028 if (P->p_type == PT_LOAD && (P->p_flags & PF_X)) 2029 LastRX = P; 2030 2031 for (OutputSection *Sec : OutputSections) { 2032 Off = setOffset(Sec, Off); 2033 if (Script->HasSectionsCommand) 2034 continue; 2035 // If this is a last section of the last executable segment and that 2036 // segment is the last loadable segment, align the offset of the 2037 // following section to avoid loading non-segments parts of the file. 2038 if (LastRX && LastRX->LastSec == Sec) 2039 Off = alignTo(Off, Target->PageSize); 2040 } 2041 2042 SectionHeaderOff = alignTo(Off, Config->Wordsize); 2043 FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr); 2044 2045 // Our logic assumes that sections have rising VA within the same segment. 2046 // With use of linker scripts it is possible to violate this rule and get file 2047 // offset overlaps or overflows. That should never happen with a valid script 2048 // which does not move the location counter backwards and usually scripts do 2049 // not do that. Unfortunately, there are apps in the wild, for example, Linux 2050 // kernel, which control segment distribution explicitly and move the counter 2051 // backwards, so we have to allow doing that to support linking them. We 2052 // perform non-critical checks for overlaps in checkSectionOverlap(), but here 2053 // we want to prevent file size overflows because it would crash the linker. 2054 for (OutputSection *Sec : OutputSections) { 2055 if (Sec->Type == SHT_NOBITS) 2056 continue; 2057 if ((Sec->Offset > FileSize) || (Sec->Offset + Sec->Size > FileSize)) 2058 error("unable to place section " + Sec->Name + " at file offset " + 2059 rangeToString(Sec->Offset, Sec->Size) + 2060 "; check your linker script for overflows"); 2061 } 2062 } 2063 2064 // Finalize the program headers. We call this function after we assign 2065 // file offsets and VAs to all sections. 2066 template <class ELFT> void Writer<ELFT>::setPhdrs() { 2067 for (PhdrEntry *P : Phdrs) { 2068 OutputSection *First = P->FirstSec; 2069 OutputSection *Last = P->LastSec; 2070 if (First) { 2071 P->p_filesz = Last->Offset - First->Offset; 2072 if (Last->Type != SHT_NOBITS) 2073 P->p_filesz += Last->Size; 2074 P->p_memsz = Last->Addr + Last->Size - First->Addr; 2075 P->p_offset = First->Offset; 2076 P->p_vaddr = First->Addr; 2077 if (!P->HasLMA) 2078 P->p_paddr = First->getLMA(); 2079 } 2080 if (P->p_type == PT_LOAD) 2081 P->p_align = std::max<uint64_t>(P->p_align, Config->MaxPageSize); 2082 else if (P->p_type == PT_GNU_RELRO) { 2083 P->p_align = 1; 2084 // The glibc dynamic loader rounds the size down, so we need to round up 2085 // to protect the last page. This is a no-op on FreeBSD which always 2086 // rounds up. 2087 P->p_memsz = alignTo(P->p_memsz, Target->PageSize); 2088 } 2089 2090 // The TLS pointer goes after PT_TLS. At least glibc will align it, 2091 // so round up the size to make sure the offsets are correct. 2092 if (P->p_type == PT_TLS) { 2093 Out::TlsPhdr = P; 2094 if (P->p_memsz) 2095 P->p_memsz = alignTo(P->p_memsz, P->p_align); 2096 } 2097 } 2098 } 2099 2100 // A helper struct for checkSectionOverlap. 2101 namespace { 2102 struct SectionOffset { 2103 OutputSection *Sec; 2104 uint64_t Offset; 2105 }; 2106 } // namespace 2107 2108 // Check whether sections overlap for a specific address range (file offsets, 2109 // load and virtual adresses). 2110 static void checkOverlap(StringRef Name, std::vector<SectionOffset> &Sections, 2111 bool IsVirtualAddr) { 2112 llvm::sort(Sections.begin(), Sections.end(), 2113 [=](const SectionOffset &A, const SectionOffset &B) { 2114 return A.Offset < B.Offset; 2115 }); 2116 2117 // Finding overlap is easy given a vector is sorted by start position. 2118 // If an element starts before the end of the previous element, they overlap. 2119 for (size_t I = 1, End = Sections.size(); I < End; ++I) { 2120 SectionOffset A = Sections[I - 1]; 2121 SectionOffset B = Sections[I]; 2122 if (B.Offset >= A.Offset + A.Sec->Size) 2123 continue; 2124 2125 // If both sections are in OVERLAY we allow the overlapping of virtual 2126 // addresses, because it is what OVERLAY was designed for. 2127 if (IsVirtualAddr && A.Sec->InOverlay && B.Sec->InOverlay) 2128 continue; 2129 2130 errorOrWarn("section " + A.Sec->Name + " " + Name + 2131 " range overlaps with " + B.Sec->Name + "\n>>> " + A.Sec->Name + 2132 " range is " + rangeToString(A.Offset, A.Sec->Size) + "\n>>> " + 2133 B.Sec->Name + " range is " + 2134 rangeToString(B.Offset, B.Sec->Size)); 2135 } 2136 } 2137 2138 // Check for overlapping sections and address overflows. 2139 // 2140 // In this function we check that none of the output sections have overlapping 2141 // file offsets. For SHF_ALLOC sections we also check that the load address 2142 // ranges and the virtual address ranges don't overlap 2143 template <class ELFT> void Writer<ELFT>::checkSections() { 2144 // First, check that section's VAs fit in available address space for target. 2145 for (OutputSection *OS : OutputSections) 2146 if ((OS->Addr + OS->Size < OS->Addr) || 2147 (!ELFT::Is64Bits && OS->Addr + OS->Size > UINT32_MAX)) 2148 errorOrWarn("section " + OS->Name + " at 0x" + utohexstr(OS->Addr) + 2149 " of size 0x" + utohexstr(OS->Size) + 2150 " exceeds available address space"); 2151 2152 // Check for overlapping file offsets. In this case we need to skip any 2153 // section marked as SHT_NOBITS. These sections don't actually occupy space in 2154 // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat 2155 // binary is specified only add SHF_ALLOC sections are added to the output 2156 // file so we skip any non-allocated sections in that case. 2157 std::vector<SectionOffset> FileOffs; 2158 for (OutputSection *Sec : OutputSections) 2159 if (Sec->Size > 0 && Sec->Type != SHT_NOBITS && 2160 (!Config->OFormatBinary || (Sec->Flags & SHF_ALLOC))) 2161 FileOffs.push_back({Sec, Sec->Offset}); 2162 checkOverlap("file", FileOffs, false); 2163 2164 // When linking with -r there is no need to check for overlapping virtual/load 2165 // addresses since those addresses will only be assigned when the final 2166 // executable/shared object is created. 2167 if (Config->Relocatable) 2168 return; 2169 2170 // Checking for overlapping virtual and load addresses only needs to take 2171 // into account SHF_ALLOC sections since others will not be loaded. 2172 // Furthermore, we also need to skip SHF_TLS sections since these will be 2173 // mapped to other addresses at runtime and can therefore have overlapping 2174 // ranges in the file. 2175 std::vector<SectionOffset> VMAs; 2176 for (OutputSection *Sec : OutputSections) 2177 if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS)) 2178 VMAs.push_back({Sec, Sec->Addr}); 2179 checkOverlap("virtual address", VMAs, true); 2180 2181 // Finally, check that the load addresses don't overlap. This will usually be 2182 // the same as the virtual addresses but can be different when using a linker 2183 // script with AT(). 2184 std::vector<SectionOffset> LMAs; 2185 for (OutputSection *Sec : OutputSections) 2186 if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS)) 2187 LMAs.push_back({Sec, Sec->getLMA()}); 2188 checkOverlap("load address", LMAs, false); 2189 } 2190 2191 // The entry point address is chosen in the following ways. 2192 // 2193 // 1. the '-e' entry command-line option; 2194 // 2. the ENTRY(symbol) command in a linker control script; 2195 // 3. the value of the symbol _start, if present; 2196 // 4. the number represented by the entry symbol, if it is a number; 2197 // 5. the address of the first byte of the .text section, if present; 2198 // 6. the address 0. 2199 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() { 2200 // Case 1, 2 or 3 2201 if (Symbol *B = Symtab->find(Config->Entry)) 2202 return B->getVA(); 2203 2204 // Case 4 2205 uint64_t Addr; 2206 if (to_integer(Config->Entry, Addr)) 2207 return Addr; 2208 2209 // Case 5 2210 if (OutputSection *Sec = findSection(".text")) { 2211 if (Config->WarnMissingEntry) 2212 warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" + 2213 utohexstr(Sec->Addr)); 2214 return Sec->Addr; 2215 } 2216 2217 // Case 6 2218 if (Config->WarnMissingEntry) 2219 warn("cannot find entry symbol " + Config->Entry + 2220 "; not setting start address"); 2221 return 0; 2222 } 2223 2224 static uint16_t getELFType() { 2225 if (Config->Pic) 2226 return ET_DYN; 2227 if (Config->Relocatable) 2228 return ET_REL; 2229 return ET_EXEC; 2230 } 2231 2232 static uint8_t getAbiVersion() { 2233 // MIPS non-PIC executable gets ABI version 1. 2234 if (Config->EMachine == EM_MIPS && getELFType() == ET_EXEC && 2235 (Config->EFlags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC) 2236 return 1; 2237 return 0; 2238 } 2239 2240 template <class ELFT> void Writer<ELFT>::writeHeader() { 2241 uint8_t *Buf = Buffer->getBufferStart(); 2242 // For executable segments, the trap instructions are written before writing 2243 // the header. Setting Elf header bytes to zero ensures that any unused bytes 2244 // in header are zero-cleared, instead of having trap instructions. 2245 memset(Buf, 0, sizeof(Elf_Ehdr)); 2246 memcpy(Buf, "\177ELF", 4); 2247 2248 // Write the ELF header. 2249 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf); 2250 EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32; 2251 EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB; 2252 EHdr->e_ident[EI_VERSION] = EV_CURRENT; 2253 EHdr->e_ident[EI_OSABI] = Config->OSABI; 2254 EHdr->e_ident[EI_ABIVERSION] = getAbiVersion(); 2255 EHdr->e_type = getELFType(); 2256 EHdr->e_machine = Config->EMachine; 2257 EHdr->e_version = EV_CURRENT; 2258 EHdr->e_entry = getEntryAddr(); 2259 EHdr->e_shoff = SectionHeaderOff; 2260 EHdr->e_flags = Config->EFlags; 2261 EHdr->e_ehsize = sizeof(Elf_Ehdr); 2262 EHdr->e_phnum = Phdrs.size(); 2263 EHdr->e_shentsize = sizeof(Elf_Shdr); 2264 2265 if (!Config->Relocatable) { 2266 EHdr->e_phoff = sizeof(Elf_Ehdr); 2267 EHdr->e_phentsize = sizeof(Elf_Phdr); 2268 } 2269 2270 // Write the program header table. 2271 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff); 2272 for (PhdrEntry *P : Phdrs) { 2273 HBuf->p_type = P->p_type; 2274 HBuf->p_flags = P->p_flags; 2275 HBuf->p_offset = P->p_offset; 2276 HBuf->p_vaddr = P->p_vaddr; 2277 HBuf->p_paddr = P->p_paddr; 2278 HBuf->p_filesz = P->p_filesz; 2279 HBuf->p_memsz = P->p_memsz; 2280 HBuf->p_align = P->p_align; 2281 ++HBuf; 2282 } 2283 2284 // Write the section header table. 2285 // 2286 // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum 2287 // and e_shstrndx fields. When the value of one of these fields exceeds 2288 // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and 2289 // use fields in the section header at index 0 to store 2290 // the value. The sentinel values and fields are: 2291 // e_shnum = 0, SHdrs[0].sh_size = number of sections. 2292 // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index. 2293 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff); 2294 size_t Num = OutputSections.size() + 1; 2295 if (Num >= SHN_LORESERVE) 2296 SHdrs->sh_size = Num; 2297 else 2298 EHdr->e_shnum = Num; 2299 2300 uint32_t StrTabIndex = InX::ShStrTab->getParent()->SectionIndex; 2301 if (StrTabIndex >= SHN_LORESERVE) { 2302 SHdrs->sh_link = StrTabIndex; 2303 EHdr->e_shstrndx = SHN_XINDEX; 2304 } else { 2305 EHdr->e_shstrndx = StrTabIndex; 2306 } 2307 2308 for (OutputSection *Sec : OutputSections) 2309 Sec->writeHeaderTo<ELFT>(++SHdrs); 2310 } 2311 2312 // Open a result file. 2313 template <class ELFT> void Writer<ELFT>::openFile() { 2314 if (!Config->Is64 && FileSize > UINT32_MAX) { 2315 error("output file too large: " + Twine(FileSize) + " bytes"); 2316 return; 2317 } 2318 2319 unlinkAsync(Config->OutputFile); 2320 unsigned Flags = 0; 2321 if (!Config->Relocatable) 2322 Flags = FileOutputBuffer::F_executable; 2323 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr = 2324 FileOutputBuffer::create(Config->OutputFile, FileSize, Flags); 2325 2326 if (!BufferOrErr) 2327 error("failed to open " + Config->OutputFile + ": " + 2328 llvm::toString(BufferOrErr.takeError())); 2329 else 2330 Buffer = std::move(*BufferOrErr); 2331 } 2332 2333 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() { 2334 uint8_t *Buf = Buffer->getBufferStart(); 2335 for (OutputSection *Sec : OutputSections) 2336 if (Sec->Flags & SHF_ALLOC) 2337 Sec->writeTo<ELFT>(Buf + Sec->Offset); 2338 } 2339 2340 static void fillTrap(uint8_t *I, uint8_t *End) { 2341 for (; I + 4 <= End; I += 4) 2342 memcpy(I, &Target->TrapInstr, 4); 2343 } 2344 2345 // Fill the last page of executable segments with trap instructions 2346 // instead of leaving them as zero. Even though it is not required by any 2347 // standard, it is in general a good thing to do for security reasons. 2348 // 2349 // We'll leave other pages in segments as-is because the rest will be 2350 // overwritten by output sections. 2351 template <class ELFT> void Writer<ELFT>::writeTrapInstr() { 2352 if (Script->HasSectionsCommand) 2353 return; 2354 2355 // Fill the last page. 2356 uint8_t *Buf = Buffer->getBufferStart(); 2357 for (PhdrEntry *P : Phdrs) 2358 if (P->p_type == PT_LOAD && (P->p_flags & PF_X)) 2359 fillTrap(Buf + alignDown(P->p_offset + P->p_filesz, Target->PageSize), 2360 Buf + alignTo(P->p_offset + P->p_filesz, Target->PageSize)); 2361 2362 // Round up the file size of the last segment to the page boundary iff it is 2363 // an executable segment to ensure that other tools don't accidentally 2364 // trim the instruction padding (e.g. when stripping the file). 2365 PhdrEntry *Last = nullptr; 2366 for (PhdrEntry *P : Phdrs) 2367 if (P->p_type == PT_LOAD) 2368 Last = P; 2369 2370 if (Last && (Last->p_flags & PF_X)) 2371 Last->p_memsz = Last->p_filesz = alignTo(Last->p_filesz, Target->PageSize); 2372 } 2373 2374 // Write section contents to a mmap'ed file. 2375 template <class ELFT> void Writer<ELFT>::writeSections() { 2376 uint8_t *Buf = Buffer->getBufferStart(); 2377 2378 OutputSection *EhFrameHdr = nullptr; 2379 if (InX::EhFrameHdr && !InX::EhFrameHdr->empty()) 2380 EhFrameHdr = InX::EhFrameHdr->getParent(); 2381 2382 // In -r or -emit-relocs mode, write the relocation sections first as in 2383 // ELf_Rel targets we might find out that we need to modify the relocated 2384 // section while doing it. 2385 for (OutputSection *Sec : OutputSections) 2386 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA) 2387 Sec->writeTo<ELFT>(Buf + Sec->Offset); 2388 2389 for (OutputSection *Sec : OutputSections) 2390 if (Sec != EhFrameHdr && Sec->Type != SHT_REL && Sec->Type != SHT_RELA) 2391 Sec->writeTo<ELFT>(Buf + Sec->Offset); 2392 2393 // The .eh_frame_hdr depends on .eh_frame section contents, therefore 2394 // it should be written after .eh_frame is written. 2395 if (EhFrameHdr) 2396 EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset); 2397 } 2398 2399 template <class ELFT> void Writer<ELFT>::writeBuildId() { 2400 if (!InX::BuildId || !InX::BuildId->getParent()) 2401 return; 2402 2403 // Compute a hash of all sections of the output file. 2404 uint8_t *Start = Buffer->getBufferStart(); 2405 uint8_t *End = Start + FileSize; 2406 InX::BuildId->writeBuildId({Start, End}); 2407 } 2408 2409 template void elf::writeResult<ELF32LE>(); 2410 template void elf::writeResult<ELF32BE>(); 2411 template void elf::writeResult<ELF64LE>(); 2412 template void elf::writeResult<ELF64BE>(); 2413