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