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