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