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