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