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->ThunkSectionSpacing && !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 // This responsible for splitting up .eh_frame section into 1559 // pieces. The relocation scan uses those pieces, so this has to be 1560 // earlier. 1561 applySynthetic({InX::EhFrame}, 1562 [](SyntheticSection *SS) { SS->finalizeContents(); }); 1563 1564 for (Symbol *S : Symtab->getSymbols()) 1565 S->IsPreemptible |= computeIsPreemptible(*S); 1566 1567 // Scan relocations. This must be done after every symbol is declared so that 1568 // we can correctly decide if a dynamic relocation is needed. 1569 if (!Config->Relocatable) 1570 forEachRelSec(scanRelocations<ELFT>); 1571 1572 if (InX::Plt && !InX::Plt->empty()) 1573 InX::Plt->addSymbols(); 1574 if (InX::Iplt && !InX::Iplt->empty()) 1575 InX::Iplt->addSymbols(); 1576 1577 // Now that we have defined all possible global symbols including linker- 1578 // synthesized ones. Visit all symbols to give the finishing touches. 1579 for (Symbol *Sym : Symtab->getSymbols()) { 1580 if (!includeInSymtab(*Sym)) 1581 continue; 1582 if (InX::SymTab) 1583 InX::SymTab->addSymbol(Sym); 1584 1585 if (InX::DynSymTab && Sym->includeInDynsym()) { 1586 InX::DynSymTab->addSymbol(Sym); 1587 if (auto *File = dyn_cast_or_null<SharedFile<ELFT>>(Sym->File)) 1588 if (File->IsNeeded && !Sym->isUndefined()) 1589 In<ELFT>::VerNeed->addSymbol(Sym); 1590 } 1591 } 1592 1593 // Do not proceed if there was an undefined symbol. 1594 if (errorCount()) 1595 return; 1596 1597 if (InX::MipsGot) 1598 InX::MipsGot->build<ELFT>(); 1599 1600 removeUnusedSyntheticSections(); 1601 1602 sortSections(); 1603 1604 // Now that we have the final list, create a list of all the 1605 // OutputSections for convenience. 1606 for (BaseCommand *Base : Script->SectionCommands) 1607 if (auto *Sec = dyn_cast<OutputSection>(Base)) 1608 OutputSections.push_back(Sec); 1609 1610 // Ensure data sections are not mixed with executable sections when 1611 // -execute-only is used. 1612 if (Config->ExecuteOnly) 1613 for (OutputSection *OS : OutputSections) 1614 if (OS->Flags & SHF_EXECINSTR) 1615 for (InputSection *IS : getInputSections(OS)) 1616 if (!(IS->Flags & SHF_EXECINSTR)) 1617 error("-execute-only does not support intermingling data and code"); 1618 1619 // Prefer command line supplied address over other constraints. 1620 for (OutputSection *Sec : OutputSections) { 1621 auto I = Config->SectionStartMap.find(Sec->Name); 1622 if (I != Config->SectionStartMap.end()) 1623 Sec->AddrExpr = [=] { return I->second; }; 1624 } 1625 1626 // This is a bit of a hack. A value of 0 means undef, so we set it 1627 // to 1 to make __ehdr_start defined. The section number is not 1628 // particularly relevant. 1629 Out::ElfHeader->SectionIndex = 1; 1630 1631 unsigned I = 1; 1632 for (OutputSection *Sec : OutputSections) { 1633 Sec->SectionIndex = I++; 1634 Sec->ShName = InX::ShStrTab->addString(Sec->Name); 1635 } 1636 1637 // Binary and relocatable output does not have PHDRS. 1638 // The headers have to be created before finalize as that can influence the 1639 // image base and the dynamic section on mips includes the image base. 1640 if (!Config->Relocatable && !Config->OFormatBinary) { 1641 Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs(); 1642 addPtArmExid(Phdrs); 1643 Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size(); 1644 } 1645 1646 // Some symbols are defined in term of program headers. Now that we 1647 // have the headers, we can find out which sections they point to. 1648 setReservedSymbolSections(); 1649 1650 // Dynamic section must be the last one in this list and dynamic 1651 // symbol table section (DynSymTab) must be the first one. 1652 applySynthetic( 1653 {InX::DynSymTab, InX::Bss, InX::BssRelRo, InX::GnuHashTab, 1654 InX::HashTab, InX::SymTab, InX::SymTabShndx, InX::ShStrTab, 1655 InX::StrTab, In<ELFT>::VerDef, InX::DynStrTab, InX::Got, 1656 InX::MipsGot, InX::IgotPlt, InX::GotPlt, InX::RelaDyn, 1657 InX::RelrDyn, InX::RelaIplt, InX::RelaPlt, InX::Plt, 1658 InX::Iplt, InX::EhFrameHdr, In<ELFT>::VerSym, In<ELFT>::VerNeed, 1659 InX::Dynamic}, 1660 [](SyntheticSection *SS) { SS->finalizeContents(); }); 1661 1662 if (!Script->HasSectionsCommand && !Config->Relocatable) 1663 fixSectionAlignments(); 1664 1665 // After link order processing .ARM.exidx sections can be deduplicated, which 1666 // needs to be resolved before any other address dependent operation. 1667 resolveShfLinkOrder(); 1668 1669 // Some architectures need to generate content that depends on the address 1670 // of InputSections. For example some architectures use small displacements 1671 // for jump instructions that is the linker's responsibility for creating 1672 // range extension thunks for. As the generation of the content may also 1673 // alter InputSection addresses we must converge to a fixed point. 1674 if (Target->NeedsThunks || Config->AndroidPackDynRelocs || 1675 Config->RelrPackDynRelocs) { 1676 ThunkCreator TC; 1677 AArch64Err843419Patcher A64P; 1678 bool Changed; 1679 do { 1680 Script->assignAddresses(); 1681 Changed = false; 1682 if (Target->NeedsThunks) 1683 Changed |= TC.createThunks(OutputSections); 1684 if (Config->FixCortexA53Errata843419) { 1685 if (Changed) 1686 Script->assignAddresses(); 1687 Changed |= A64P.createFixes(); 1688 } 1689 if (InX::MipsGot) 1690 InX::MipsGot->updateAllocSize(); 1691 Changed |= InX::RelaDyn->updateAllocSize(); 1692 if (InX::RelrDyn) 1693 Changed |= InX::RelrDyn->updateAllocSize(); 1694 } while (Changed); 1695 } 1696 1697 // createThunks may have added local symbols to the static symbol table 1698 applySynthetic({InX::SymTab}, 1699 [](SyntheticSection *SS) { SS->postThunkContents(); }); 1700 1701 // Fill other section headers. The dynamic table is finalized 1702 // at the end because some tags like RELSZ depend on result 1703 // of finalizing other sections. 1704 for (OutputSection *Sec : OutputSections) 1705 Sec->finalize<ELFT>(); 1706 } 1707 1708 // The linker is expected to define SECNAME_start and SECNAME_end 1709 // symbols for a few sections. This function defines them. 1710 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() { 1711 // If a section does not exist, there's ambiguity as to how we 1712 // define _start and _end symbols for an init/fini section. Since 1713 // the loader assume that the symbols are always defined, we need to 1714 // always define them. But what value? The loader iterates over all 1715 // pointers between _start and _end to run global ctors/dtors, so if 1716 // the section is empty, their symbol values don't actually matter 1717 // as long as _start and _end point to the same location. 1718 // 1719 // That said, we don't want to set the symbols to 0 (which is 1720 // probably the simplest value) because that could cause some 1721 // program to fail to link due to relocation overflow, if their 1722 // program text is above 2 GiB. We use the address of the .text 1723 // section instead to prevent that failure. 1724 OutputSection *Default = findSection(".text"); 1725 if (!Default) 1726 Default = Out::ElfHeader; 1727 auto Define = [=](StringRef Start, StringRef End, OutputSection *OS) { 1728 if (OS) { 1729 addOptionalRegular(Start, OS, 0); 1730 addOptionalRegular(End, OS, -1); 1731 } else { 1732 addOptionalRegular(Start, Default, 0); 1733 addOptionalRegular(End, Default, 0); 1734 } 1735 }; 1736 1737 Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray); 1738 Define("__init_array_start", "__init_array_end", Out::InitArray); 1739 Define("__fini_array_start", "__fini_array_end", Out::FiniArray); 1740 1741 if (OutputSection *Sec = findSection(".ARM.exidx")) 1742 Define("__exidx_start", "__exidx_end", Sec); 1743 } 1744 1745 // If a section name is valid as a C identifier (which is rare because of 1746 // the leading '.'), linkers are expected to define __start_<secname> and 1747 // __stop_<secname> symbols. They are at beginning and end of the section, 1748 // respectively. This is not requested by the ELF standard, but GNU ld and 1749 // gold provide the feature, and used by many programs. 1750 template <class ELFT> 1751 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) { 1752 StringRef S = Sec->Name; 1753 if (!isValidCIdentifier(S)) 1754 return; 1755 addOptionalRegular(Saver.save("__start_" + S), Sec, 0, STV_PROTECTED); 1756 addOptionalRegular(Saver.save("__stop_" + S), Sec, -1, STV_PROTECTED); 1757 } 1758 1759 static bool needsPtLoad(OutputSection *Sec) { 1760 if (!(Sec->Flags & SHF_ALLOC) || Sec->Noload) 1761 return false; 1762 1763 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is 1764 // responsible for allocating space for them, not the PT_LOAD that 1765 // contains the TLS initialization image. 1766 if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS) 1767 return false; 1768 return true; 1769 } 1770 1771 // Linker scripts are responsible for aligning addresses. Unfortunately, most 1772 // linker scripts are designed for creating two PT_LOADs only, one RX and one 1773 // RW. This means that there is no alignment in the RO to RX transition and we 1774 // cannot create a PT_LOAD there. 1775 static uint64_t computeFlags(uint64_t Flags) { 1776 if (Config->Omagic) 1777 return PF_R | PF_W | PF_X; 1778 if (Config->ExecuteOnly && (Flags & PF_X)) 1779 return Flags & ~PF_R; 1780 if (Config->SingleRoRx && !(Flags & PF_W)) 1781 return Flags | PF_X; 1782 return Flags; 1783 } 1784 1785 // Decide which program headers to create and which sections to include in each 1786 // one. 1787 template <class ELFT> std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs() { 1788 std::vector<PhdrEntry *> Ret; 1789 auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * { 1790 Ret.push_back(make<PhdrEntry>(Type, Flags)); 1791 return Ret.back(); 1792 }; 1793 1794 // The first phdr entry is PT_PHDR which describes the program header itself. 1795 AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders); 1796 1797 // PT_INTERP must be the second entry if exists. 1798 if (OutputSection *Cmd = findSection(".interp")) 1799 AddHdr(PT_INTERP, Cmd->getPhdrFlags())->add(Cmd); 1800 1801 // Add the first PT_LOAD segment for regular output sections. 1802 uint64_t Flags = computeFlags(PF_R); 1803 PhdrEntry *Load = AddHdr(PT_LOAD, Flags); 1804 1805 // Add the headers. We will remove them if they don't fit. 1806 Load->add(Out::ElfHeader); 1807 Load->add(Out::ProgramHeaders); 1808 1809 for (OutputSection *Sec : OutputSections) { 1810 if (!(Sec->Flags & SHF_ALLOC)) 1811 break; 1812 if (!needsPtLoad(Sec)) 1813 continue; 1814 1815 // Segments are contiguous memory regions that has the same attributes 1816 // (e.g. executable or writable). There is one phdr for each segment. 1817 // Therefore, we need to create a new phdr when the next section has 1818 // different flags or is loaded at a discontiguous address or memory 1819 // region using AT or AT> linker script command, respectively. At the same 1820 // time, we don't want to create a separate load segment for the headers, 1821 // even if the first output section has an AT or AT> attribute. 1822 uint64_t NewFlags = computeFlags(Sec->getPhdrFlags()); 1823 if (((Sec->LMAExpr || 1824 (Sec->LMARegion && (Sec->LMARegion != Load->FirstSec->LMARegion))) && 1825 Load->LastSec != Out::ProgramHeaders) || 1826 Sec->MemRegion != Load->FirstSec->MemRegion || Flags != NewFlags) { 1827 1828 Load = AddHdr(PT_LOAD, NewFlags); 1829 Flags = NewFlags; 1830 } 1831 1832 Load->add(Sec); 1833 } 1834 1835 // Add a TLS segment if any. 1836 PhdrEntry *TlsHdr = make<PhdrEntry>(PT_TLS, PF_R); 1837 for (OutputSection *Sec : OutputSections) 1838 if (Sec->Flags & SHF_TLS) 1839 TlsHdr->add(Sec); 1840 if (TlsHdr->FirstSec) 1841 Ret.push_back(TlsHdr); 1842 1843 // Add an entry for .dynamic. 1844 if (InX::DynSymTab) 1845 AddHdr(PT_DYNAMIC, InX::Dynamic->getParent()->getPhdrFlags()) 1846 ->add(InX::Dynamic->getParent()); 1847 1848 // PT_GNU_RELRO includes all sections that should be marked as 1849 // read-only by dynamic linker after proccessing relocations. 1850 // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give 1851 // an error message if more than one PT_GNU_RELRO PHDR is required. 1852 PhdrEntry *RelRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R); 1853 bool InRelroPhdr = false; 1854 bool IsRelroFinished = false; 1855 for (OutputSection *Sec : OutputSections) { 1856 if (!needsPtLoad(Sec)) 1857 continue; 1858 if (isRelroSection(Sec)) { 1859 InRelroPhdr = true; 1860 if (!IsRelroFinished) 1861 RelRo->add(Sec); 1862 else 1863 error("section: " + Sec->Name + " is not contiguous with other relro" + 1864 " sections"); 1865 } else if (InRelroPhdr) { 1866 InRelroPhdr = false; 1867 IsRelroFinished = true; 1868 } 1869 } 1870 if (RelRo->FirstSec) 1871 Ret.push_back(RelRo); 1872 1873 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr. 1874 if (!InX::EhFrame->empty() && InX::EhFrameHdr && InX::EhFrame->getParent() && 1875 InX::EhFrameHdr->getParent()) 1876 AddHdr(PT_GNU_EH_FRAME, InX::EhFrameHdr->getParent()->getPhdrFlags()) 1877 ->add(InX::EhFrameHdr->getParent()); 1878 1879 // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes 1880 // the dynamic linker fill the segment with random data. 1881 if (OutputSection *Cmd = findSection(".openbsd.randomdata")) 1882 AddHdr(PT_OPENBSD_RANDOMIZE, Cmd->getPhdrFlags())->add(Cmd); 1883 1884 // PT_GNU_STACK is a special section to tell the loader to make the 1885 // pages for the stack non-executable. If you really want an executable 1886 // stack, you can pass -z execstack, but that's not recommended for 1887 // security reasons. 1888 unsigned Perm = PF_R | PF_W; 1889 if (Config->ZExecstack) 1890 Perm |= PF_X; 1891 AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize; 1892 1893 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable 1894 // is expected to perform W^X violations, such as calling mprotect(2) or 1895 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on 1896 // OpenBSD. 1897 if (Config->ZWxneeded) 1898 AddHdr(PT_OPENBSD_WXNEEDED, PF_X); 1899 1900 // Create one PT_NOTE per a group of contiguous .note sections. 1901 PhdrEntry *Note = nullptr; 1902 for (OutputSection *Sec : OutputSections) { 1903 if (Sec->Type == SHT_NOTE && (Sec->Flags & SHF_ALLOC)) { 1904 if (!Note || Sec->LMAExpr) 1905 Note = AddHdr(PT_NOTE, PF_R); 1906 Note->add(Sec); 1907 } else { 1908 Note = nullptr; 1909 } 1910 } 1911 return Ret; 1912 } 1913 1914 template <class ELFT> 1915 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry *> &Phdrs) { 1916 if (Config->EMachine != EM_ARM) 1917 return; 1918 auto I = llvm::find_if(OutputSections, [](OutputSection *Cmd) { 1919 return Cmd->Type == SHT_ARM_EXIDX; 1920 }); 1921 if (I == OutputSections.end()) 1922 return; 1923 1924 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME 1925 PhdrEntry *ARMExidx = make<PhdrEntry>(PT_ARM_EXIDX, PF_R); 1926 ARMExidx->add(*I); 1927 Phdrs.push_back(ARMExidx); 1928 } 1929 1930 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the 1931 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic 1932 // linker can set the permissions. 1933 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() { 1934 auto PageAlign = [](OutputSection *Cmd) { 1935 if (Cmd && !Cmd->AddrExpr) 1936 Cmd->AddrExpr = [=] { 1937 return alignTo(Script->getDot(), Config->MaxPageSize); 1938 }; 1939 }; 1940 1941 for (const PhdrEntry *P : Phdrs) 1942 if (P->p_type == PT_LOAD && P->FirstSec) 1943 PageAlign(P->FirstSec); 1944 1945 for (const PhdrEntry *P : Phdrs) { 1946 if (P->p_type != PT_GNU_RELRO) 1947 continue; 1948 if (P->FirstSec) 1949 PageAlign(P->FirstSec); 1950 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we 1951 // have to align it to a page. 1952 auto End = OutputSections.end(); 1953 auto I = std::find(OutputSections.begin(), End, P->LastSec); 1954 if (I == End || (I + 1) == End) 1955 continue; 1956 OutputSection *Cmd = (*(I + 1)); 1957 if (needsPtLoad(Cmd)) 1958 PageAlign(Cmd); 1959 } 1960 } 1961 1962 // Adjusts the file alignment for a given output section and returns 1963 // its new file offset. The file offset must be the same with its 1964 // virtual address (modulo the page size) so that the loader can load 1965 // executables without any address adjustment. 1966 static uint64_t getFileAlignment(uint64_t Off, OutputSection *Cmd) { 1967 OutputSection *First = Cmd->PtLoad ? Cmd->PtLoad->FirstSec : nullptr; 1968 // The first section in a PT_LOAD has to have congruent offset and address 1969 // module the page size. 1970 if (Cmd == First) 1971 return alignTo(Off, std::max<uint64_t>(Cmd->Alignment, Config->MaxPageSize), 1972 Cmd->Addr); 1973 1974 // For SHT_NOBITS we don't want the alignment of the section to impact the 1975 // offset of the sections that follow. Since nothing seems to care about the 1976 // sh_offset of the SHT_NOBITS section itself, just ignore it. 1977 if (Cmd->Type == SHT_NOBITS) 1978 return Off; 1979 1980 // If the section is not in a PT_LOAD, we just have to align it. 1981 if (!Cmd->PtLoad) 1982 return alignTo(Off, Cmd->Alignment); 1983 1984 // If two sections share the same PT_LOAD the file offset is calculated 1985 // using this formula: Off2 = Off1 + (VA2 - VA1). 1986 return First->Offset + Cmd->Addr - First->Addr; 1987 } 1988 1989 static uint64_t setOffset(OutputSection *Cmd, uint64_t Off) { 1990 Off = getFileAlignment(Off, Cmd); 1991 Cmd->Offset = Off; 1992 1993 // For SHT_NOBITS we should not count the size. 1994 if (Cmd->Type == SHT_NOBITS) 1995 return Off; 1996 1997 return Off + Cmd->Size; 1998 } 1999 2000 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() { 2001 uint64_t Off = 0; 2002 for (OutputSection *Sec : OutputSections) 2003 if (Sec->Flags & SHF_ALLOC) 2004 Off = setOffset(Sec, Off); 2005 FileSize = alignTo(Off, Config->Wordsize); 2006 } 2007 2008 static std::string rangeToString(uint64_t Addr, uint64_t Len) { 2009 return "[0x" + utohexstr(Addr) + ", 0x" + utohexstr(Addr + Len - 1) + "]"; 2010 } 2011 2012 // Assign file offsets to output sections. 2013 template <class ELFT> void Writer<ELFT>::assignFileOffsets() { 2014 uint64_t Off = 0; 2015 Off = setOffset(Out::ElfHeader, Off); 2016 Off = setOffset(Out::ProgramHeaders, Off); 2017 2018 PhdrEntry *LastRX = nullptr; 2019 for (PhdrEntry *P : Phdrs) 2020 if (P->p_type == PT_LOAD && (P->p_flags & PF_X)) 2021 LastRX = P; 2022 2023 for (OutputSection *Sec : OutputSections) { 2024 Off = setOffset(Sec, Off); 2025 if (Script->HasSectionsCommand) 2026 continue; 2027 // If this is a last section of the last executable segment and that 2028 // segment is the last loadable segment, align the offset of the 2029 // following section to avoid loading non-segments parts of the file. 2030 if (LastRX && LastRX->LastSec == Sec) 2031 Off = alignTo(Off, Target->PageSize); 2032 } 2033 2034 SectionHeaderOff = alignTo(Off, Config->Wordsize); 2035 FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr); 2036 2037 // Our logic assumes that sections have rising VA within the same segment. 2038 // With use of linker scripts it is possible to violate this rule and get file 2039 // offset overlaps or overflows. That should never happen with a valid script 2040 // which does not move the location counter backwards and usually scripts do 2041 // not do that. Unfortunately, there are apps in the wild, for example, Linux 2042 // kernel, which control segment distribution explicitly and move the counter 2043 // backwards, so we have to allow doing that to support linking them. We 2044 // perform non-critical checks for overlaps in checkSectionOverlap(), but here 2045 // we want to prevent file size overflows because it would crash the linker. 2046 for (OutputSection *Sec : OutputSections) { 2047 if (Sec->Type == SHT_NOBITS) 2048 continue; 2049 if ((Sec->Offset > FileSize) || (Sec->Offset + Sec->Size > FileSize)) 2050 error("unable to place section " + Sec->Name + " at file offset " + 2051 rangeToString(Sec->Offset, Sec->Size) + 2052 "; check your linker script for overflows"); 2053 } 2054 } 2055 2056 // Finalize the program headers. We call this function after we assign 2057 // file offsets and VAs to all sections. 2058 template <class ELFT> void Writer<ELFT>::setPhdrs() { 2059 for (PhdrEntry *P : Phdrs) { 2060 OutputSection *First = P->FirstSec; 2061 OutputSection *Last = P->LastSec; 2062 if (First) { 2063 P->p_filesz = Last->Offset - First->Offset; 2064 if (Last->Type != SHT_NOBITS) 2065 P->p_filesz += Last->Size; 2066 P->p_memsz = Last->Addr + Last->Size - First->Addr; 2067 P->p_offset = First->Offset; 2068 P->p_vaddr = First->Addr; 2069 if (!P->HasLMA) 2070 P->p_paddr = First->getLMA(); 2071 } 2072 if (P->p_type == PT_LOAD) 2073 P->p_align = std::max<uint64_t>(P->p_align, Config->MaxPageSize); 2074 else if (P->p_type == PT_GNU_RELRO) { 2075 P->p_align = 1; 2076 // The glibc dynamic loader rounds the size down, so we need to round up 2077 // to protect the last page. This is a no-op on FreeBSD which always 2078 // rounds up. 2079 P->p_memsz = alignTo(P->p_memsz, Target->PageSize); 2080 } 2081 2082 // The TLS pointer goes after PT_TLS. At least glibc will align it, 2083 // so round up the size to make sure the offsets are correct. 2084 if (P->p_type == PT_TLS) { 2085 Out::TlsPhdr = P; 2086 if (P->p_memsz) 2087 P->p_memsz = alignTo(P->p_memsz, P->p_align); 2088 } 2089 } 2090 } 2091 2092 // A helper struct for checkSectionOverlap. 2093 namespace { 2094 struct SectionOffset { 2095 OutputSection *Sec; 2096 uint64_t Offset; 2097 }; 2098 } // namespace 2099 2100 // Check whether sections overlap for a specific address range (file offsets, 2101 // load and virtual adresses). 2102 static void checkOverlap(StringRef Name, std::vector<SectionOffset> &Sections, 2103 bool IsVirtualAddr) { 2104 llvm::sort(Sections.begin(), Sections.end(), 2105 [=](const SectionOffset &A, const SectionOffset &B) { 2106 return A.Offset < B.Offset; 2107 }); 2108 2109 // Finding overlap is easy given a vector is sorted by start position. 2110 // If an element starts before the end of the previous element, they overlap. 2111 for (size_t I = 1, End = Sections.size(); I < End; ++I) { 2112 SectionOffset A = Sections[I - 1]; 2113 SectionOffset B = Sections[I]; 2114 if (B.Offset >= A.Offset + A.Sec->Size) 2115 continue; 2116 2117 // If both sections are in OVERLAY we allow the overlapping of virtual 2118 // addresses, because it is what OVERLAY was designed for. 2119 if (IsVirtualAddr && A.Sec->InOverlay && B.Sec->InOverlay) 2120 continue; 2121 2122 errorOrWarn("section " + A.Sec->Name + " " + Name + 2123 " range overlaps with " + B.Sec->Name + "\n>>> " + A.Sec->Name + 2124 " range is " + rangeToString(A.Offset, A.Sec->Size) + "\n>>> " + 2125 B.Sec->Name + " range is " + 2126 rangeToString(B.Offset, B.Sec->Size)); 2127 } 2128 } 2129 2130 // Check for overlapping sections and address overflows. 2131 // 2132 // In this function we check that none of the output sections have overlapping 2133 // file offsets. For SHF_ALLOC sections we also check that the load address 2134 // ranges and the virtual address ranges don't overlap 2135 template <class ELFT> void Writer<ELFT>::checkSections() { 2136 // First, check that section's VAs fit in available address space for target. 2137 for (OutputSection *OS : OutputSections) 2138 if ((OS->Addr + OS->Size < OS->Addr) || 2139 (!ELFT::Is64Bits && OS->Addr + OS->Size > UINT32_MAX)) 2140 errorOrWarn("section " + OS->Name + " at 0x" + utohexstr(OS->Addr) + 2141 " of size 0x" + utohexstr(OS->Size) + 2142 " exceeds available address space"); 2143 2144 // Check for overlapping file offsets. In this case we need to skip any 2145 // section marked as SHT_NOBITS. These sections don't actually occupy space in 2146 // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat 2147 // binary is specified only add SHF_ALLOC sections are added to the output 2148 // file so we skip any non-allocated sections in that case. 2149 std::vector<SectionOffset> FileOffs; 2150 for (OutputSection *Sec : OutputSections) 2151 if (Sec->Size > 0 && Sec->Type != SHT_NOBITS && 2152 (!Config->OFormatBinary || (Sec->Flags & SHF_ALLOC))) 2153 FileOffs.push_back({Sec, Sec->Offset}); 2154 checkOverlap("file", FileOffs, false); 2155 2156 // When linking with -r there is no need to check for overlapping virtual/load 2157 // addresses since those addresses will only be assigned when the final 2158 // executable/shared object is created. 2159 if (Config->Relocatable) 2160 return; 2161 2162 // Checking for overlapping virtual and load addresses only needs to take 2163 // into account SHF_ALLOC sections since others will not be loaded. 2164 // Furthermore, we also need to skip SHF_TLS sections since these will be 2165 // mapped to other addresses at runtime and can therefore have overlapping 2166 // ranges in the file. 2167 std::vector<SectionOffset> VMAs; 2168 for (OutputSection *Sec : OutputSections) 2169 if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS)) 2170 VMAs.push_back({Sec, Sec->Addr}); 2171 checkOverlap("virtual address", VMAs, true); 2172 2173 // Finally, check that the load addresses don't overlap. This will usually be 2174 // the same as the virtual addresses but can be different when using a linker 2175 // script with AT(). 2176 std::vector<SectionOffset> LMAs; 2177 for (OutputSection *Sec : OutputSections) 2178 if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS)) 2179 LMAs.push_back({Sec, Sec->getLMA()}); 2180 checkOverlap("load address", LMAs, false); 2181 } 2182 2183 // The entry point address is chosen in the following ways. 2184 // 2185 // 1. the '-e' entry command-line option; 2186 // 2. the ENTRY(symbol) command in a linker control script; 2187 // 3. the value of the symbol _start, if present; 2188 // 4. the number represented by the entry symbol, if it is a number; 2189 // 5. the address of the first byte of the .text section, if present; 2190 // 6. the address 0. 2191 template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() { 2192 // Case 1, 2 or 3 2193 if (Symbol *B = Symtab->find(Config->Entry)) 2194 return B->getVA(); 2195 2196 // Case 4 2197 uint64_t Addr; 2198 if (to_integer(Config->Entry, Addr)) 2199 return Addr; 2200 2201 // Case 5 2202 if (OutputSection *Sec = findSection(".text")) { 2203 if (Config->WarnMissingEntry) 2204 warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" + 2205 utohexstr(Sec->Addr)); 2206 return Sec->Addr; 2207 } 2208 2209 // Case 6 2210 if (Config->WarnMissingEntry) 2211 warn("cannot find entry symbol " + Config->Entry + 2212 "; not setting start address"); 2213 return 0; 2214 } 2215 2216 static uint16_t getELFType() { 2217 if (Config->Pic) 2218 return ET_DYN; 2219 if (Config->Relocatable) 2220 return ET_REL; 2221 return ET_EXEC; 2222 } 2223 2224 static uint8_t getAbiVersion() { 2225 // MIPS non-PIC executable gets ABI version 1. 2226 if (Config->EMachine == EM_MIPS && getELFType() == ET_EXEC && 2227 (Config->EFlags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC) 2228 return 1; 2229 return 0; 2230 } 2231 2232 template <class ELFT> void Writer<ELFT>::writeHeader() { 2233 uint8_t *Buf = Buffer->getBufferStart(); 2234 // For executable segments, the trap instructions are written before writing 2235 // the header. Setting Elf header bytes to zero ensures that any unused bytes 2236 // in header are zero-cleared, instead of having trap instructions. 2237 memset(Buf, 0, sizeof(Elf_Ehdr)); 2238 memcpy(Buf, "\177ELF", 4); 2239 2240 // Write the ELF header. 2241 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf); 2242 EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32; 2243 EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB; 2244 EHdr->e_ident[EI_VERSION] = EV_CURRENT; 2245 EHdr->e_ident[EI_OSABI] = Config->OSABI; 2246 EHdr->e_ident[EI_ABIVERSION] = getAbiVersion(); 2247 EHdr->e_type = getELFType(); 2248 EHdr->e_machine = Config->EMachine; 2249 EHdr->e_version = EV_CURRENT; 2250 EHdr->e_entry = getEntryAddr(); 2251 EHdr->e_shoff = SectionHeaderOff; 2252 EHdr->e_flags = Config->EFlags; 2253 EHdr->e_ehsize = sizeof(Elf_Ehdr); 2254 EHdr->e_phnum = Phdrs.size(); 2255 EHdr->e_shentsize = sizeof(Elf_Shdr); 2256 2257 if (!Config->Relocatable) { 2258 EHdr->e_phoff = sizeof(Elf_Ehdr); 2259 EHdr->e_phentsize = sizeof(Elf_Phdr); 2260 } 2261 2262 // Write the program header table. 2263 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff); 2264 for (PhdrEntry *P : Phdrs) { 2265 HBuf->p_type = P->p_type; 2266 HBuf->p_flags = P->p_flags; 2267 HBuf->p_offset = P->p_offset; 2268 HBuf->p_vaddr = P->p_vaddr; 2269 HBuf->p_paddr = P->p_paddr; 2270 HBuf->p_filesz = P->p_filesz; 2271 HBuf->p_memsz = P->p_memsz; 2272 HBuf->p_align = P->p_align; 2273 ++HBuf; 2274 } 2275 2276 // Write the section header table. 2277 // 2278 // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum 2279 // and e_shstrndx fields. When the value of one of these fields exceeds 2280 // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and 2281 // use fields in the section header at index 0 to store 2282 // the value. The sentinel values and fields are: 2283 // e_shnum = 0, SHdrs[0].sh_size = number of sections. 2284 // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index. 2285 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff); 2286 size_t Num = OutputSections.size() + 1; 2287 if (Num >= SHN_LORESERVE) 2288 SHdrs->sh_size = Num; 2289 else 2290 EHdr->e_shnum = Num; 2291 2292 uint32_t StrTabIndex = InX::ShStrTab->getParent()->SectionIndex; 2293 if (StrTabIndex >= SHN_LORESERVE) { 2294 SHdrs->sh_link = StrTabIndex; 2295 EHdr->e_shstrndx = SHN_XINDEX; 2296 } else { 2297 EHdr->e_shstrndx = StrTabIndex; 2298 } 2299 2300 for (OutputSection *Sec : OutputSections) 2301 Sec->writeHeaderTo<ELFT>(++SHdrs); 2302 } 2303 2304 // Open a result file. 2305 template <class ELFT> void Writer<ELFT>::openFile() { 2306 if (!Config->Is64 && FileSize > UINT32_MAX) { 2307 error("output file too large: " + Twine(FileSize) + " bytes"); 2308 return; 2309 } 2310 2311 unlinkAsync(Config->OutputFile); 2312 unsigned Flags = 0; 2313 if (!Config->Relocatable) 2314 Flags = FileOutputBuffer::F_executable; 2315 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr = 2316 FileOutputBuffer::create(Config->OutputFile, FileSize, Flags); 2317 2318 if (!BufferOrErr) 2319 error("failed to open " + Config->OutputFile + ": " + 2320 llvm::toString(BufferOrErr.takeError())); 2321 else 2322 Buffer = std::move(*BufferOrErr); 2323 } 2324 2325 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() { 2326 uint8_t *Buf = Buffer->getBufferStart(); 2327 for (OutputSection *Sec : OutputSections) 2328 if (Sec->Flags & SHF_ALLOC) 2329 Sec->writeTo<ELFT>(Buf + Sec->Offset); 2330 } 2331 2332 static void fillTrap(uint8_t *I, uint8_t *End) { 2333 for (; I + 4 <= End; I += 4) 2334 memcpy(I, &Target->TrapInstr, 4); 2335 } 2336 2337 // Fill the last page of executable segments with trap instructions 2338 // instead of leaving them as zero. Even though it is not required by any 2339 // standard, it is in general a good thing to do for security reasons. 2340 // 2341 // We'll leave other pages in segments as-is because the rest will be 2342 // overwritten by output sections. 2343 template <class ELFT> void Writer<ELFT>::writeTrapInstr() { 2344 if (Script->HasSectionsCommand) 2345 return; 2346 2347 // Fill the last page. 2348 uint8_t *Buf = Buffer->getBufferStart(); 2349 for (PhdrEntry *P : Phdrs) 2350 if (P->p_type == PT_LOAD && (P->p_flags & PF_X)) 2351 fillTrap(Buf + alignDown(P->p_offset + P->p_filesz, Target->PageSize), 2352 Buf + alignTo(P->p_offset + P->p_filesz, Target->PageSize)); 2353 2354 // Round up the file size of the last segment to the page boundary iff it is 2355 // an executable segment to ensure that other tools don't accidentally 2356 // trim the instruction padding (e.g. when stripping the file). 2357 PhdrEntry *Last = nullptr; 2358 for (PhdrEntry *P : Phdrs) 2359 if (P->p_type == PT_LOAD) 2360 Last = P; 2361 2362 if (Last && (Last->p_flags & PF_X)) 2363 Last->p_memsz = Last->p_filesz = alignTo(Last->p_filesz, Target->PageSize); 2364 } 2365 2366 // Write section contents to a mmap'ed file. 2367 template <class ELFT> void Writer<ELFT>::writeSections() { 2368 uint8_t *Buf = Buffer->getBufferStart(); 2369 2370 OutputSection *EhFrameHdr = nullptr; 2371 if (InX::EhFrameHdr && !InX::EhFrameHdr->empty()) 2372 EhFrameHdr = InX::EhFrameHdr->getParent(); 2373 2374 // In -r or -emit-relocs mode, write the relocation sections first as in 2375 // ELf_Rel targets we might find out that we need to modify the relocated 2376 // section while doing it. 2377 for (OutputSection *Sec : OutputSections) 2378 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA) 2379 Sec->writeTo<ELFT>(Buf + Sec->Offset); 2380 2381 for (OutputSection *Sec : OutputSections) 2382 if (Sec != EhFrameHdr && Sec->Type != SHT_REL && Sec->Type != SHT_RELA) 2383 Sec->writeTo<ELFT>(Buf + Sec->Offset); 2384 2385 // The .eh_frame_hdr depends on .eh_frame section contents, therefore 2386 // it should be written after .eh_frame is written. 2387 if (EhFrameHdr) 2388 EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset); 2389 } 2390 2391 template <class ELFT> void Writer<ELFT>::writeBuildId() { 2392 if (!InX::BuildId || !InX::BuildId->getParent()) 2393 return; 2394 2395 // Compute a hash of all sections of the output file. 2396 uint8_t *Start = Buffer->getBufferStart(); 2397 uint8_t *End = Start + FileSize; 2398 InX::BuildId->writeBuildId({Start, End}); 2399 } 2400 2401 template void elf::writeResult<ELF32LE>(); 2402 template void elf::writeResult<ELF32BE>(); 2403 template void elf::writeResult<ELF64LE>(); 2404 template void elf::writeResult<ELF64BE>(); 2405