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