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