Path: blob/main/contrib/llvm-project/lld/ELF/Writer.cpp
34878 views
//===- Writer.cpp ---------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "Writer.h"9#include "AArch64ErrataFix.h"10#include "ARMErrataFix.h"11#include "CallGraphSort.h"12#include "Config.h"13#include "InputFiles.h"14#include "LinkerScript.h"15#include "MapFile.h"16#include "OutputSections.h"17#include "Relocations.h"18#include "SymbolTable.h"19#include "Symbols.h"20#include "SyntheticSections.h"21#include "Target.h"22#include "lld/Common/Arrays.h"23#include "lld/Common/CommonLinkerContext.h"24#include "lld/Common/Filesystem.h"25#include "lld/Common/Strings.h"26#include "llvm/ADT/STLExtras.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>3435#define DEBUG_TYPE "lld"3637using namespace llvm;38using namespace llvm::ELF;39using namespace llvm::object;40using namespace llvm::support;41using namespace llvm::support::endian;42using namespace lld;43using namespace lld::elf;4445namespace {46// The writer writes a SymbolTable result to a file.47template <class ELFT> class Writer {48public:49LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)5051Writer() : buffer(errorHandler().outputBuffer) {}5253void run();5455private:56void addSectionSymbols();57void sortSections();58void resolveShfLinkOrder();59void finalizeAddressDependentContent();60void optimizeBasicBlockJumps();61void sortInputSections();62void sortOrphanSections();63void finalizeSections();64void checkExecuteOnly();65void setReservedSymbolSections();6667SmallVector<PhdrEntry *, 0> createPhdrs(Partition &part);68void addPhdrForSection(Partition &part, unsigned shType, unsigned pType,69unsigned pFlags);70void assignFileOffsets();71void assignFileOffsetsBinary();72void setPhdrs(Partition &part);73void checkSections();74void fixSectionAlignments();75void openFile();76void writeTrapInstr();77void writeHeader();78void writeSections();79void writeSectionsBinary();80void writeBuildId();8182std::unique_ptr<FileOutputBuffer> &buffer;8384void addRelIpltSymbols();85void addStartEndSymbols();86void addStartStopSymbols(OutputSection &osec);8788uint64_t fileSize;89uint64_t sectionHeaderOff;90};91} // anonymous namespace9293template <class ELFT> void elf::writeResult() {94Writer<ELFT>().run();95}9697static void removeEmptyPTLoad(SmallVector<PhdrEntry *, 0> &phdrs) {98auto it = std::stable_partition(99phdrs.begin(), phdrs.end(), [&](const PhdrEntry *p) {100if (p->p_type != PT_LOAD)101return true;102if (!p->firstSec)103return false;104uint64_t size = p->lastSec->addr + p->lastSec->size - p->firstSec->addr;105return size != 0;106});107108// Clear OutputSection::ptLoad for sections contained in removed109// segments.110DenseSet<PhdrEntry *> removed(it, phdrs.end());111for (OutputSection *sec : outputSections)112if (removed.count(sec->ptLoad))113sec->ptLoad = nullptr;114phdrs.erase(it, phdrs.end());115}116117void elf::copySectionsIntoPartitions() {118SmallVector<InputSectionBase *, 0> newSections;119const size_t ehSize = ctx.ehInputSections.size();120for (unsigned part = 2; part != partitions.size() + 1; ++part) {121for (InputSectionBase *s : ctx.inputSections) {122if (!(s->flags & SHF_ALLOC) || !s->isLive() || s->type != SHT_NOTE)123continue;124auto *copy = make<InputSection>(cast<InputSection>(*s));125copy->partition = part;126newSections.push_back(copy);127}128for (size_t i = 0; i != ehSize; ++i) {129assert(ctx.ehInputSections[i]->isLive());130auto *copy = make<EhInputSection>(*ctx.ehInputSections[i]);131copy->partition = part;132ctx.ehInputSections.push_back(copy);133}134}135136ctx.inputSections.insert(ctx.inputSections.end(), newSections.begin(),137newSections.end());138}139140static Defined *addOptionalRegular(StringRef name, SectionBase *sec,141uint64_t val, uint8_t stOther = STV_HIDDEN) {142Symbol *s = symtab.find(name);143if (!s || s->isDefined() || s->isCommon())144return nullptr;145146s->resolve(Defined{ctx.internalFile, StringRef(), STB_GLOBAL, stOther,147STT_NOTYPE, val,148/*size=*/0, sec});149s->isUsedInRegularObj = true;150return cast<Defined>(s);151}152153// The linker is expected to define some symbols depending on154// the linking result. This function defines such symbols.155void elf::addReservedSymbols() {156if (config->emachine == EM_MIPS) {157auto addAbsolute = [](StringRef name) {158Symbol *sym =159symtab.addSymbol(Defined{ctx.internalFile, name, STB_GLOBAL,160STV_HIDDEN, STT_NOTYPE, 0, 0, nullptr});161sym->isUsedInRegularObj = true;162return cast<Defined>(sym);163};164// Define _gp for MIPS. st_value of _gp symbol will be updated by Writer165// so that it points to an absolute address which by default is relative166// to GOT. Default offset is 0x7ff0.167// See "Global Data Symbols" in Chapter 6 in the following document:168// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf169ElfSym::mipsGp = addAbsolute("_gp");170171// On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between172// start of function and 'gp' pointer into GOT.173if (symtab.find("_gp_disp"))174ElfSym::mipsGpDisp = addAbsolute("_gp_disp");175176// The __gnu_local_gp is a magic symbol equal to the current value of 'gp'177// pointer. This symbol is used in the code generated by .cpload pseudo-op178// in case of using -mno-shared option.179// https://sourceware.org/ml/binutils/2004-12/msg00094.html180if (symtab.find("__gnu_local_gp"))181ElfSym::mipsLocalGp = addAbsolute("__gnu_local_gp");182} else if (config->emachine == EM_PPC) {183// glibc *crt1.o has a undefined reference to _SDA_BASE_. Since we don't184// support Small Data Area, define it arbitrarily as 0.185addOptionalRegular("_SDA_BASE_", nullptr, 0, STV_HIDDEN);186} else if (config->emachine == EM_PPC64) {187addPPC64SaveRestore();188}189190// The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which191// combines the typical ELF GOT with the small data sections. It commonly192// includes .got .toc .sdata .sbss. The .TOC. symbol replaces both193// _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to194// represent the TOC base which is offset by 0x8000 bytes from the start of195// the .got section.196// We do not allow _GLOBAL_OFFSET_TABLE_ to be defined by input objects as the197// correctness of some relocations depends on its value.198StringRef gotSymName =199(config->emachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_";200201if (Symbol *s = symtab.find(gotSymName)) {202if (s->isDefined()) {203error(toString(s->file) + " cannot redefine linker defined symbol '" +204gotSymName + "'");205return;206}207208uint64_t gotOff = 0;209if (config->emachine == EM_PPC64)210gotOff = 0x8000;211212s->resolve(Defined{ctx.internalFile, StringRef(), STB_GLOBAL, STV_HIDDEN,213STT_NOTYPE, gotOff, /*size=*/0, Out::elfHeader});214ElfSym::globalOffsetTable = cast<Defined>(s);215}216217// __ehdr_start is the location of ELF file headers. Note that we define218// this symbol unconditionally even when using a linker script, which219// differs from the behavior implemented by GNU linker which only define220// this symbol if ELF headers are in the memory mapped segment.221addOptionalRegular("__ehdr_start", Out::elfHeader, 0, STV_HIDDEN);222223// __executable_start is not documented, but the expectation of at224// least the Android libc is that it points to the ELF header.225addOptionalRegular("__executable_start", Out::elfHeader, 0, STV_HIDDEN);226227// __dso_handle symbol is passed to cxa_finalize as a marker to identify228// each DSO. The address of the symbol doesn't matter as long as they are229// different in different DSOs, so we chose the start address of the DSO.230addOptionalRegular("__dso_handle", Out::elfHeader, 0, STV_HIDDEN);231232// If linker script do layout we do not need to create any standard symbols.233if (script->hasSectionsCommand)234return;235236auto add = [](StringRef s, int64_t pos) {237return addOptionalRegular(s, Out::elfHeader, pos, STV_DEFAULT);238};239240ElfSym::bss = add("__bss_start", 0);241ElfSym::end1 = add("end", -1);242ElfSym::end2 = add("_end", -1);243ElfSym::etext1 = add("etext", -1);244ElfSym::etext2 = add("_etext", -1);245ElfSym::edata1 = add("edata", -1);246ElfSym::edata2 = add("_edata", -1);247}248249static void demoteDefined(Defined &sym, DenseMap<SectionBase *, size_t> &map) {250if (map.empty())251for (auto [i, sec] : llvm::enumerate(sym.file->getSections()))252map.try_emplace(sec, i);253// Change WEAK to GLOBAL so that if a scanned relocation references sym,254// maybeReportUndefined will report an error.255uint8_t binding = sym.isWeak() ? uint8_t(STB_GLOBAL) : sym.binding;256Undefined(sym.file, sym.getName(), binding, sym.stOther, sym.type,257/*discardedSecIdx=*/map.lookup(sym.section))258.overwrite(sym);259// Eliminate from the symbol table, otherwise we would leave an undefined260// symbol if the symbol is unreferenced in the absence of GC.261sym.isUsedInRegularObj = false;262}263264// If all references to a DSO happen to be weak, the DSO is not added to265// DT_NEEDED. If that happens, replace ShardSymbol with Undefined to avoid266// dangling references to an unneeded DSO. Use a weak binding to avoid267// --no-allow-shlib-undefined diagnostics. Similarly, demote lazy symbols.268//269// In addition, demote symbols defined in discarded sections, so that270// references to /DISCARD/ discarded symbols will lead to errors.271static void demoteSymbolsAndComputeIsPreemptible() {272llvm::TimeTraceScope timeScope("Demote symbols");273DenseMap<InputFile *, DenseMap<SectionBase *, size_t>> sectionIndexMap;274for (Symbol *sym : symtab.getSymbols()) {275if (auto *d = dyn_cast<Defined>(sym)) {276if (d->section && !d->section->isLive())277demoteDefined(*d, sectionIndexMap[d->file]);278} else {279auto *s = dyn_cast<SharedSymbol>(sym);280if (sym->isLazy() || (s && !cast<SharedFile>(s->file)->isNeeded)) {281uint8_t binding = sym->isLazy() ? sym->binding : uint8_t(STB_WEAK);282Undefined(ctx.internalFile, sym->getName(), binding, sym->stOther,283sym->type)284.overwrite(*sym);285sym->versionId = VER_NDX_GLOBAL;286}287}288289if (config->hasDynSymTab)290sym->isPreemptible = computeIsPreemptible(*sym);291}292}293294static OutputSection *findSection(StringRef name, unsigned partition = 1) {295for (SectionCommand *cmd : script->sectionCommands)296if (auto *osd = dyn_cast<OutputDesc>(cmd))297if (osd->osec.name == name && osd->osec.partition == partition)298return &osd->osec;299return nullptr;300}301302// The main function of the writer.303template <class ELFT> void Writer<ELFT>::run() {304// Now that we have a complete set of output sections. This function305// completes section contents. For example, we need to add strings306// to the string table, and add entries to .got and .plt.307// finalizeSections does that.308finalizeSections();309checkExecuteOnly();310311// If --compressed-debug-sections is specified, compress .debug_* sections.312// Do it right now because it changes the size of output sections.313for (OutputSection *sec : outputSections)314sec->maybeCompress<ELFT>();315316if (script->hasSectionsCommand)317script->allocateHeaders(mainPart->phdrs);318319// Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a320// 0 sized region. This has to be done late since only after assignAddresses321// we know the size of the sections.322for (Partition &part : partitions)323removeEmptyPTLoad(part.phdrs);324325if (!config->oFormatBinary)326assignFileOffsets();327else328assignFileOffsetsBinary();329330for (Partition &part : partitions)331setPhdrs(part);332333// Handle --print-map(-M)/--Map and --cref. Dump them before checkSections()334// because the files may be useful in case checkSections() or openFile()335// fails, for example, due to an erroneous file size.336writeMapAndCref();337338// Handle --print-memory-usage option.339if (config->printMemoryUsage)340script->printMemoryUsage(lld::outs());341342if (config->checkSections)343checkSections();344345// It does not make sense try to open the file if we have error already.346if (errorCount())347return;348349{350llvm::TimeTraceScope timeScope("Write output file");351// Write the result down to a file.352openFile();353if (errorCount())354return;355356if (!config->oFormatBinary) {357if (config->zSeparate != SeparateSegmentKind::None)358writeTrapInstr();359writeHeader();360writeSections();361} else {362writeSectionsBinary();363}364365// Backfill .note.gnu.build-id section content. This is done at last366// because the content is usually a hash value of the entire output file.367writeBuildId();368if (errorCount())369return;370371if (auto e = buffer->commit())372fatal("failed to write output '" + buffer->getPath() +373"': " + toString(std::move(e)));374375if (!config->cmseOutputLib.empty())376writeARMCmseImportLib<ELFT>();377}378}379380template <class ELFT, class RelTy>381static void markUsedLocalSymbolsImpl(ObjFile<ELFT> *file,382llvm::ArrayRef<RelTy> rels) {383for (const RelTy &rel : rels) {384Symbol &sym = file->getRelocTargetSym(rel);385if (sym.isLocal())386sym.used = true;387}388}389390// The function ensures that the "used" field of local symbols reflects the fact391// that the symbol is used in a relocation from a live section.392template <class ELFT> static void markUsedLocalSymbols() {393// With --gc-sections, the field is already filled.394// See MarkLive<ELFT>::resolveReloc().395if (config->gcSections)396return;397for (ELFFileBase *file : ctx.objectFiles) {398ObjFile<ELFT> *f = cast<ObjFile<ELFT>>(file);399for (InputSectionBase *s : f->getSections()) {400InputSection *isec = dyn_cast_or_null<InputSection>(s);401if (!isec)402continue;403if (isec->type == SHT_REL) {404markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rel>());405} else if (isec->type == SHT_RELA) {406markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rela>());407} else if (isec->type == SHT_CREL) {408// The is64=true variant also works with ELF32 since only the r_symidx409// member is used.410for (Elf_Crel_Impl<true> r : RelocsCrel<true>(isec->content_)) {411Symbol &sym = file->getSymbol(r.r_symidx);412if (sym.isLocal())413sym.used = true;414}415}416}417}418}419420static bool shouldKeepInSymtab(const Defined &sym) {421if (sym.isSection())422return false;423424// If --emit-reloc or -r is given, preserve symbols referenced by relocations425// from live sections.426if (sym.used && config->copyRelocs)427return true;428429// Exclude local symbols pointing to .ARM.exidx sections.430// They are probably mapping symbols "$d", which are optional for these431// sections. After merging the .ARM.exidx sections, some of these symbols432// may become dangling. The easiest way to avoid the issue is not to add433// them to the symbol table from the beginning.434if (config->emachine == EM_ARM && sym.section &&435sym.section->type == SHT_ARM_EXIDX)436return false;437438if (config->discard == DiscardPolicy::None)439return true;440if (config->discard == DiscardPolicy::All)441return false;442443// In ELF assembly .L symbols are normally discarded by the assembler.444// If the assembler fails to do so, the linker discards them if445// * --discard-locals is used.446// * The symbol is in a SHF_MERGE section, which is normally the reason for447// the assembler keeping the .L symbol.448if (sym.getName().starts_with(".L") &&449(config->discard == DiscardPolicy::Locals ||450(sym.section && (sym.section->flags & SHF_MERGE))))451return false;452return true;453}454455bool lld::elf::includeInSymtab(const Symbol &b) {456if (auto *d = dyn_cast<Defined>(&b)) {457// Always include absolute symbols.458SectionBase *sec = d->section;459if (!sec)460return true;461assert(sec->isLive());462463if (auto *s = dyn_cast<MergeInputSection>(sec))464return s->getSectionPiece(d->value).live;465return true;466}467return b.used || !config->gcSections;468}469470// Scan local symbols to:471//472// - demote symbols defined relative to /DISCARD/ discarded input sections so473// that relocations referencing them will lead to errors.474// - copy eligible symbols to .symTab475static void demoteAndCopyLocalSymbols() {476llvm::TimeTraceScope timeScope("Add local symbols");477for (ELFFileBase *file : ctx.objectFiles) {478DenseMap<SectionBase *, size_t> sectionIndexMap;479for (Symbol *b : file->getLocalSymbols()) {480assert(b->isLocal() && "should have been caught in initializeSymbols()");481auto *dr = dyn_cast<Defined>(b);482if (!dr)483continue;484485if (dr->section && !dr->section->isLive())486demoteDefined(*dr, sectionIndexMap);487else if (in.symTab && includeInSymtab(*b) && shouldKeepInSymtab(*dr))488in.symTab->addSymbol(b);489}490}491}492493// Create a section symbol for each output section so that we can represent494// relocations that point to the section. If we know that no relocation is495// referring to a section (that happens if the section is a synthetic one), we496// don't create a section symbol for that section.497template <class ELFT> void Writer<ELFT>::addSectionSymbols() {498for (SectionCommand *cmd : script->sectionCommands) {499auto *osd = dyn_cast<OutputDesc>(cmd);500if (!osd)501continue;502OutputSection &osec = osd->osec;503InputSectionBase *isec = nullptr;504// Iterate over all input sections and add a STT_SECTION symbol if any input505// section may be a relocation target.506for (SectionCommand *cmd : osec.commands) {507auto *isd = dyn_cast<InputSectionDescription>(cmd);508if (!isd)509continue;510for (InputSectionBase *s : isd->sections) {511// Relocations are not using REL[A] section symbols.512if (isStaticRelSecType(s->type))513continue;514515// Unlike other synthetic sections, mergeable output sections contain516// data copied from input sections, and there may be a relocation517// pointing to its contents if -r or --emit-reloc is given.518if (isa<SyntheticSection>(s) && !(s->flags & SHF_MERGE))519continue;520521isec = s;522break;523}524}525if (!isec)526continue;527528// Set the symbol to be relative to the output section so that its st_value529// equals the output section address. Note, there may be a gap between the530// start of the output section and isec.531in.symTab->addSymbol(makeDefined(isec->file, "", STB_LOCAL, /*stOther=*/0,532STT_SECTION,533/*value=*/0, /*size=*/0, &osec));534}535}536537// Today's loaders have a feature to make segments read-only after538// processing dynamic relocations to enhance security. PT_GNU_RELRO539// is defined for that.540//541// This function returns true if a section needs to be put into a542// PT_GNU_RELRO segment.543static bool isRelroSection(const OutputSection *sec) {544if (!config->zRelro)545return false;546if (sec->relro)547return true;548549uint64_t flags = sec->flags;550551// Non-allocatable or non-writable sections don't need RELRO because552// they are not writable or not even mapped to memory in the first place.553// RELRO is for sections that are essentially read-only but need to554// be writable only at process startup to allow dynamic linker to555// apply relocations.556if (!(flags & SHF_ALLOC) || !(flags & SHF_WRITE))557return false;558559// Once initialized, TLS data segments are used as data templates560// for a thread-local storage. For each new thread, runtime561// allocates memory for a TLS and copy templates there. No thread562// are supposed to use templates directly. Thus, it can be in RELRO.563if (flags & SHF_TLS)564return true;565566// .init_array, .preinit_array and .fini_array contain pointers to567// functions that are executed on process startup or exit. These568// pointers are set by the static linker, and they are not expected569// to change at runtime. But if you are an attacker, you could do570// interesting things by manipulating pointers in .fini_array, for571// example. So they are put into RELRO.572uint32_t type = sec->type;573if (type == SHT_INIT_ARRAY || type == SHT_FINI_ARRAY ||574type == SHT_PREINIT_ARRAY)575return true;576577// .got contains pointers to external symbols. They are resolved by578// the dynamic linker when a module is loaded into memory, and after579// that they are not expected to change. So, it can be in RELRO.580if (in.got && sec == in.got->getParent())581return true;582583// .toc is a GOT-ish section for PowerPC64. Their contents are accessed584// through r2 register, which is reserved for that purpose. Since r2 is used585// for accessing .got as well, .got and .toc need to be close enough in the586// virtual address space. Usually, .toc comes just after .got. Since we place587// .got into RELRO, .toc needs to be placed into RELRO too.588if (sec->name == ".toc")589return true;590591// .got.plt contains pointers to external function symbols. They are592// by default resolved lazily, so we usually cannot put it into RELRO.593// However, if "-z now" is given, the lazy symbol resolution is594// disabled, which enables us to put it into RELRO.595if (sec == in.gotPlt->getParent())596return config->zNow;597598if (in.relroPadding && sec == in.relroPadding->getParent())599return true;600601// .dynamic section contains data for the dynamic linker, and602// there's no need to write to it at runtime, so it's better to put603// it into RELRO.604if (sec->name == ".dynamic")605return true;606607// Sections with some special names are put into RELRO. This is a608// bit unfortunate because section names shouldn't be significant in609// ELF in spirit. But in reality many linker features depend on610// magic section names.611StringRef s = sec->name;612613bool abiAgnostic = s == ".data.rel.ro" || s == ".bss.rel.ro" ||614s == ".ctors" || s == ".dtors" || s == ".jcr" ||615s == ".eh_frame" || s == ".fini_array" ||616s == ".init_array" || s == ".preinit_array";617618bool abiSpecific =619config->osabi == ELFOSABI_OPENBSD && s == ".openbsd.randomdata";620621return abiAgnostic || abiSpecific;622}623624// We compute a rank for each section. The rank indicates where the625// section should be placed in the file. Instead of using simple626// numbers (0,1,2...), we use a series of flags. One for each decision627// point when placing the section.628// Using flags has two key properties:629// * It is easy to check if a give branch was taken.630// * It is easy two see how similar two ranks are (see getRankProximity).631enum RankFlags {632RF_NOT_ADDR_SET = 1 << 27,633RF_NOT_ALLOC = 1 << 26,634RF_PARTITION = 1 << 18, // Partition number (8 bits)635RF_LARGE_ALT = 1 << 15,636RF_WRITE = 1 << 14,637RF_EXEC_WRITE = 1 << 13,638RF_EXEC = 1 << 12,639RF_RODATA = 1 << 11,640RF_LARGE = 1 << 10,641RF_NOT_RELRO = 1 << 9,642RF_NOT_TLS = 1 << 8,643RF_BSS = 1 << 7,644};645646unsigned elf::getSectionRank(OutputSection &osec) {647unsigned rank = osec.partition * RF_PARTITION;648649// We want to put section specified by -T option first, so we650// can start assigning VA starting from them later.651if (config->sectionStartMap.count(osec.name))652return rank;653rank |= RF_NOT_ADDR_SET;654655// Allocatable sections go first to reduce the total PT_LOAD size and656// so debug info doesn't change addresses in actual code.657if (!(osec.flags & SHF_ALLOC))658return rank | RF_NOT_ALLOC;659660// Sort sections based on their access permission in the following661// order: R, RX, RXW, RW(RELRO), RW(non-RELRO).662//663// Read-only sections come first such that they go in the PT_LOAD covering the664// program headers at the start of the file.665//666// The layout for writable sections is PT_LOAD(PT_GNU_RELRO(.data.rel.ro667// .bss.rel.ro) | .data .bss), where | marks where page alignment happens.668// An alternative ordering is PT_LOAD(.data | PT_GNU_RELRO( .data.rel.ro669// .bss.rel.ro) | .bss), but it may waste more bytes due to 2 alignment670// places.671bool isExec = osec.flags & SHF_EXECINSTR;672bool isWrite = osec.flags & SHF_WRITE;673674if (!isWrite && !isExec) {675// Among PROGBITS sections, place .lrodata further from .text.676// For -z lrodata-after-bss, place .lrodata after .lbss like GNU ld. This677// layout has one extra PT_LOAD, but alleviates relocation overflow678// pressure for absolute relocations referencing small data from -fno-pic679// relocatable files.680if (osec.flags & SHF_X86_64_LARGE && config->emachine == EM_X86_64)681rank |= config->zLrodataAfterBss ? RF_LARGE_ALT : 0;682else683rank |= config->zLrodataAfterBss ? 0 : RF_LARGE;684685if (osec.type == SHT_LLVM_PART_EHDR)686;687else if (osec.type == SHT_LLVM_PART_PHDR)688rank |= 1;689else if (osec.name == ".interp")690rank |= 2;691// Put .note sections at the beginning so that they are likely to be692// included in a truncate core file. In particular, .note.gnu.build-id, if693// available, can identify the object file.694else if (osec.type == SHT_NOTE)695rank |= 3;696// Make PROGBITS sections (e.g .rodata .eh_frame) closer to .text to697// alleviate relocation overflow pressure. Large special sections such as698// .dynstr and .dynsym can be away from .text.699else if (osec.type != SHT_PROGBITS)700rank |= 4;701else702rank |= RF_RODATA;703} else if (isExec) {704rank |= isWrite ? RF_EXEC_WRITE : RF_EXEC;705} else {706rank |= RF_WRITE;707// The TLS initialization block needs to be a single contiguous block. Place708// TLS sections directly before the other RELRO sections.709if (!(osec.flags & SHF_TLS))710rank |= RF_NOT_TLS;711if (isRelroSection(&osec))712osec.relro = true;713else714rank |= RF_NOT_RELRO;715// Place .ldata and .lbss after .bss. Making .bss closer to .text716// alleviates relocation overflow pressure.717// For -z lrodata-after-bss, place .lbss/.lrodata/.ldata after .bss.718// .bss/.lbss being adjacent reuses the NOBITS size optimization.719if (osec.flags & SHF_X86_64_LARGE && config->emachine == EM_X86_64) {720rank |= config->zLrodataAfterBss721? (osec.type == SHT_NOBITS ? 1 : RF_LARGE_ALT)722: RF_LARGE;723}724}725726// Within TLS sections, or within other RelRo sections, or within non-RelRo727// sections, place non-NOBITS sections first.728if (osec.type == SHT_NOBITS)729rank |= RF_BSS;730731// Some architectures have additional ordering restrictions for sections732// within the same PT_LOAD.733if (config->emachine == EM_PPC64) {734// PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections735// that we would like to make sure appear is a specific order to maximize736// their coverage by a single signed 16-bit offset from the TOC base737// pointer.738StringRef name = osec.name;739if (name == ".got")740rank |= 1;741else if (name == ".toc")742rank |= 2;743}744745if (config->emachine == EM_MIPS) {746if (osec.name != ".got")747rank |= 1;748// All sections with SHF_MIPS_GPREL flag should be grouped together749// because data in these sections is addressable with a gp relative address.750if (osec.flags & SHF_MIPS_GPREL)751rank |= 2;752}753754if (config->emachine == EM_RISCV) {755// .sdata and .sbss are placed closer to make GP relaxation more profitable756// and match GNU ld.757StringRef name = osec.name;758if (name == ".sdata" || (osec.type == SHT_NOBITS && name != ".sbss"))759rank |= 1;760}761762return rank;763}764765static bool compareSections(const SectionCommand *aCmd,766const SectionCommand *bCmd) {767const OutputSection *a = &cast<OutputDesc>(aCmd)->osec;768const OutputSection *b = &cast<OutputDesc>(bCmd)->osec;769770if (a->sortRank != b->sortRank)771return a->sortRank < b->sortRank;772773if (!(a->sortRank & RF_NOT_ADDR_SET))774return config->sectionStartMap.lookup(a->name) <775config->sectionStartMap.lookup(b->name);776return false;777}778779void PhdrEntry::add(OutputSection *sec) {780lastSec = sec;781if (!firstSec)782firstSec = sec;783p_align = std::max(p_align, sec->addralign);784if (p_type == PT_LOAD)785sec->ptLoad = this;786}787788// A statically linked position-dependent executable should only contain789// IRELATIVE relocations and no other dynamic relocations. Encapsulation symbols790// __rel[a]_iplt_{start,end} will be defined for .rel[a].dyn, to be791// processed by the libc runtime. Other executables or DSOs use dynamic tags792// instead.793template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {794if (config->isPic)795return;796797// __rela_iplt_{start,end} are initially defined relative to dummy section 0.798// We'll override Out::elfHeader with relaDyn later when we are sure that799// .rela.dyn will be present in the output.800std::string name = config->isRela ? "__rela_iplt_start" : "__rel_iplt_start";801ElfSym::relaIpltStart =802addOptionalRegular(name, Out::elfHeader, 0, STV_HIDDEN);803name.replace(name.size() - 5, 5, "end");804ElfSym::relaIpltEnd = addOptionalRegular(name, Out::elfHeader, 0, STV_HIDDEN);805}806807// This function generates assignments for predefined symbols (e.g. _end or808// _etext) and inserts them into the commands sequence to be processed at the809// appropriate time. This ensures that the value is going to be correct by the810// time any references to these symbols are processed and is equivalent to811// defining these symbols explicitly in the linker script.812template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {813if (ElfSym::globalOffsetTable) {814// The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually815// to the start of the .got or .got.plt section.816InputSection *sec = in.gotPlt.get();817if (!target->gotBaseSymInGotPlt)818sec = in.mipsGot ? cast<InputSection>(in.mipsGot.get())819: cast<InputSection>(in.got.get());820ElfSym::globalOffsetTable->section = sec;821}822823// .rela_iplt_{start,end} mark the start and the end of .rel[a].dyn.824if (ElfSym::relaIpltStart && mainPart->relaDyn->isNeeded()) {825ElfSym::relaIpltStart->section = mainPart->relaDyn.get();826ElfSym::relaIpltEnd->section = mainPart->relaDyn.get();827ElfSym::relaIpltEnd->value = mainPart->relaDyn->getSize();828}829830PhdrEntry *last = nullptr;831OutputSection *lastRO = nullptr;832auto isLarge = [](OutputSection *osec) {833return config->emachine == EM_X86_64 && osec->flags & SHF_X86_64_LARGE;834};835for (Partition &part : partitions) {836for (PhdrEntry *p : part.phdrs) {837if (p->p_type != PT_LOAD)838continue;839last = p;840if (!(p->p_flags & PF_W) && p->lastSec && !isLarge(p->lastSec))841lastRO = p->lastSec;842}843}844845if (lastRO) {846// _etext is the first location after the last read-only loadable segment847// that does not contain large sections.848if (ElfSym::etext1)849ElfSym::etext1->section = lastRO;850if (ElfSym::etext2)851ElfSym::etext2->section = lastRO;852}853854if (last) {855// _edata points to the end of the last non-large mapped initialized856// section.857OutputSection *edata = nullptr;858for (OutputSection *os : outputSections) {859if (os->type != SHT_NOBITS && !isLarge(os))860edata = os;861if (os == last->lastSec)862break;863}864865if (ElfSym::edata1)866ElfSym::edata1->section = edata;867if (ElfSym::edata2)868ElfSym::edata2->section = edata;869870// _end is the first location after the uninitialized data region.871if (ElfSym::end1)872ElfSym::end1->section = last->lastSec;873if (ElfSym::end2)874ElfSym::end2->section = last->lastSec;875}876877if (ElfSym::bss) {878// On RISC-V, set __bss_start to the start of .sbss if present.879OutputSection *sbss =880config->emachine == EM_RISCV ? findSection(".sbss") : nullptr;881ElfSym::bss->section = sbss ? sbss : findSection(".bss");882}883884// Setup MIPS _gp_disp/__gnu_local_gp symbols which should885// be equal to the _gp symbol's value.886if (ElfSym::mipsGp) {887// Find GP-relative section with the lowest address888// and use this address to calculate default _gp value.889for (OutputSection *os : outputSections) {890if (os->flags & SHF_MIPS_GPREL) {891ElfSym::mipsGp->section = os;892ElfSym::mipsGp->value = 0x7ff0;893break;894}895}896}897}898899// We want to find how similar two ranks are.900// The more branches in getSectionRank that match, the more similar they are.901// Since each branch corresponds to a bit flag, we can just use902// countLeadingZeros.903static int getRankProximity(OutputSection *a, SectionCommand *b) {904auto *osd = dyn_cast<OutputDesc>(b);905return (osd && osd->osec.hasInputSections)906? llvm::countl_zero(a->sortRank ^ osd->osec.sortRank)907: -1;908}909910// When placing orphan sections, we want to place them after symbol assignments911// so that an orphan after912// begin_foo = .;913// foo : { *(foo) }914// end_foo = .;915// doesn't break the intended meaning of the begin/end symbols.916// We don't want to go over sections since findOrphanPos is the917// one in charge of deciding the order of the sections.918// We don't want to go over changes to '.', since doing so in919// rx_sec : { *(rx_sec) }920// . = ALIGN(0x1000);921// /* The RW PT_LOAD starts here*/922// rw_sec : { *(rw_sec) }923// would mean that the RW PT_LOAD would become unaligned.924static bool shouldSkip(SectionCommand *cmd) {925if (auto *assign = dyn_cast<SymbolAssignment>(cmd))926return assign->name != ".";927return false;928}929930// We want to place orphan sections so that they share as much931// characteristics with their neighbors as possible. For example, if932// both are rw, or both are tls.933static SmallVectorImpl<SectionCommand *>::iterator934findOrphanPos(SmallVectorImpl<SectionCommand *>::iterator b,935SmallVectorImpl<SectionCommand *>::iterator e) {936// Place non-alloc orphan sections at the end. This matches how we assign file937// offsets to non-alloc sections.938OutputSection *sec = &cast<OutputDesc>(*e)->osec;939if (!(sec->flags & SHF_ALLOC))940return e;941942// As a special case, place .relro_padding before the SymbolAssignment using943// DATA_SEGMENT_RELRO_END, if present.944if (in.relroPadding && sec == in.relroPadding->getParent()) {945auto i = std::find_if(b, e, [=](SectionCommand *a) {946if (auto *assign = dyn_cast<SymbolAssignment>(a))947return assign->dataSegmentRelroEnd;948return false;949});950if (i != e)951return i;952}953954// Find the most similar output section as the anchor. Rank Proximity is a955// value in the range [-1, 32] where [0, 32] indicates potential anchors (0:956// least similar; 32: identical). -1 means not an anchor.957//958// In the event of proximity ties, we select the first or last section959// depending on whether the orphan's rank is smaller.960int maxP = 0;961auto i = e;962for (auto j = b; j != e; ++j) {963int p = getRankProximity(sec, *j);964if (p > maxP ||965(p == maxP && cast<OutputDesc>(*j)->osec.sortRank <= sec->sortRank)) {966maxP = p;967i = j;968}969}970if (i == e)971return e;972973auto isOutputSecWithInputSections = [](SectionCommand *cmd) {974auto *osd = dyn_cast<OutputDesc>(cmd);975return osd && osd->osec.hasInputSections;976};977978// Then, scan backward or forward through the script for a suitable insertion979// point. If i's rank is larger, the orphan section can be placed before i.980//981// However, don't do this if custom program headers are defined. Otherwise,982// adding the orphan to a previous segment can change its flags, for example,983// making a read-only segment writable. If memory regions are defined, an984// orphan section should continue the same region as the found section to985// better resemble the behavior of GNU ld.986bool mustAfter = script->hasPhdrsCommands() || !script->memoryRegions.empty();987if (cast<OutputDesc>(*i)->osec.sortRank <= sec->sortRank || mustAfter) {988for (auto j = ++i; j != e; ++j) {989if (!isOutputSecWithInputSections(*j))990continue;991if (getRankProximity(sec, *j) != maxP)992break;993i = j + 1;994}995} else {996for (; i != b; --i)997if (isOutputSecWithInputSections(i[-1]))998break;999}10001001// As a special case, if the orphan section is the last section, put1002// it at the very end, past any other commands.1003// This matches bfd's behavior and is convenient when the linker script fully1004// specifies the start of the file, but doesn't care about the end (the non1005// alloc sections for example).1006if (std::find_if(i, e, isOutputSecWithInputSections) == e)1007return e;10081009while (i != e && shouldSkip(*i))1010++i;1011return i;1012}10131014// Adds random priorities to sections not already in the map.1015static void maybeShuffle(DenseMap<const InputSectionBase *, int> &order) {1016if (config->shuffleSections.empty())1017return;10181019SmallVector<InputSectionBase *, 0> matched, sections = ctx.inputSections;1020matched.reserve(sections.size());1021for (const auto &patAndSeed : config->shuffleSections) {1022matched.clear();1023for (InputSectionBase *sec : sections)1024if (patAndSeed.first.match(sec->name))1025matched.push_back(sec);1026const uint32_t seed = patAndSeed.second;1027if (seed == UINT32_MAX) {1028// If --shuffle-sections <section-glob>=-1, reverse the section order. The1029// section order is stable even if the number of sections changes. This is1030// useful to catch issues like static initialization order fiasco1031// reliably.1032std::reverse(matched.begin(), matched.end());1033} else {1034std::mt19937 g(seed ? seed : std::random_device()());1035llvm::shuffle(matched.begin(), matched.end(), g);1036}1037size_t i = 0;1038for (InputSectionBase *&sec : sections)1039if (patAndSeed.first.match(sec->name))1040sec = matched[i++];1041}10421043// Existing priorities are < 0, so use priorities >= 0 for the missing1044// sections.1045int prio = 0;1046for (InputSectionBase *sec : sections) {1047if (order.try_emplace(sec, prio).second)1048++prio;1049}1050}10511052// Builds section order for handling --symbol-ordering-file.1053static DenseMap<const InputSectionBase *, int> buildSectionOrder() {1054DenseMap<const InputSectionBase *, int> sectionOrder;1055// Use the rarely used option --call-graph-ordering-file to sort sections.1056if (!config->callGraphProfile.empty())1057return computeCallGraphProfileOrder();10581059if (config->symbolOrderingFile.empty())1060return sectionOrder;10611062struct SymbolOrderEntry {1063int priority;1064bool present;1065};10661067// Build a map from symbols to their priorities. Symbols that didn't1068// appear in the symbol ordering file have the lowest priority 0.1069// All explicitly mentioned symbols have negative (higher) priorities.1070DenseMap<CachedHashStringRef, SymbolOrderEntry> symbolOrder;1071int priority = -config->symbolOrderingFile.size();1072for (StringRef s : config->symbolOrderingFile)1073symbolOrder.insert({CachedHashStringRef(s), {priority++, false}});10741075// Build a map from sections to their priorities.1076auto addSym = [&](Symbol &sym) {1077auto it = symbolOrder.find(CachedHashStringRef(sym.getName()));1078if (it == symbolOrder.end())1079return;1080SymbolOrderEntry &ent = it->second;1081ent.present = true;10821083maybeWarnUnorderableSymbol(&sym);10841085if (auto *d = dyn_cast<Defined>(&sym)) {1086if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) {1087int &priority = sectionOrder[cast<InputSectionBase>(sec)];1088priority = std::min(priority, ent.priority);1089}1090}1091};10921093// We want both global and local symbols. We get the global ones from the1094// symbol table and iterate the object files for the local ones.1095for (Symbol *sym : symtab.getSymbols())1096addSym(*sym);10971098for (ELFFileBase *file : ctx.objectFiles)1099for (Symbol *sym : file->getLocalSymbols())1100addSym(*sym);11011102if (config->warnSymbolOrdering)1103for (auto orderEntry : symbolOrder)1104if (!orderEntry.second.present)1105warn("symbol ordering file: no such symbol: " + orderEntry.first.val());11061107return sectionOrder;1108}11091110// Sorts the sections in ISD according to the provided section order.1111static void1112sortISDBySectionOrder(InputSectionDescription *isd,1113const DenseMap<const InputSectionBase *, int> &order,1114bool executableOutputSection) {1115SmallVector<InputSection *, 0> unorderedSections;1116SmallVector<std::pair<InputSection *, int>, 0> orderedSections;1117uint64_t unorderedSize = 0;1118uint64_t totalSize = 0;11191120for (InputSection *isec : isd->sections) {1121if (executableOutputSection)1122totalSize += isec->getSize();1123auto i = order.find(isec);1124if (i == order.end()) {1125unorderedSections.push_back(isec);1126unorderedSize += isec->getSize();1127continue;1128}1129orderedSections.push_back({isec, i->second});1130}1131llvm::sort(orderedSections, llvm::less_second());11321133// Find an insertion point for the ordered section list in the unordered1134// section list. On targets with limited-range branches, this is the mid-point1135// of the unordered section list. This decreases the likelihood that a range1136// extension thunk will be needed to enter or exit the ordered region. If the1137// ordered section list is a list of hot functions, we can generally expect1138// the ordered functions to be called more often than the unordered functions,1139// making it more likely that any particular call will be within range, and1140// therefore reducing the number of thunks required.1141//1142// For example, imagine that you have 8MB of hot code and 32MB of cold code.1143// If the layout is:1144//1145// 8MB hot1146// 32MB cold1147//1148// only the first 8-16MB of the cold code (depending on which hot function it1149// is actually calling) can call the hot code without a range extension thunk.1150// However, if we use this layout:1151//1152// 16MB cold1153// 8MB hot1154// 16MB cold1155//1156// both the last 8-16MB of the first block of cold code and the first 8-16MB1157// of the second block of cold code can call the hot code without a thunk. So1158// we effectively double the amount of code that could potentially call into1159// the hot code without a thunk.1160//1161// The above is not necessary if total size of input sections in this "isd"1162// is small. Note that we assume all input sections are executable if the1163// output section is executable (which is not always true but supposed to1164// cover most cases).1165size_t insPt = 0;1166if (executableOutputSection && !orderedSections.empty() &&1167target->getThunkSectionSpacing() &&1168totalSize >= target->getThunkSectionSpacing()) {1169uint64_t unorderedPos = 0;1170for (; insPt != unorderedSections.size(); ++insPt) {1171unorderedPos += unorderedSections[insPt]->getSize();1172if (unorderedPos > unorderedSize / 2)1173break;1174}1175}11761177isd->sections.clear();1178for (InputSection *isec : ArrayRef(unorderedSections).slice(0, insPt))1179isd->sections.push_back(isec);1180for (std::pair<InputSection *, int> p : orderedSections)1181isd->sections.push_back(p.first);1182for (InputSection *isec : ArrayRef(unorderedSections).slice(insPt))1183isd->sections.push_back(isec);1184}11851186static void sortSection(OutputSection &osec,1187const DenseMap<const InputSectionBase *, int> &order) {1188StringRef name = osec.name;11891190// Never sort these.1191if (name == ".init" || name == ".fini")1192return;11931194// Sort input sections by priority using the list provided by1195// --symbol-ordering-file or --shuffle-sections=. This is a least significant1196// digit radix sort. The sections may be sorted stably again by a more1197// significant key.1198if (!order.empty())1199for (SectionCommand *b : osec.commands)1200if (auto *isd = dyn_cast<InputSectionDescription>(b))1201sortISDBySectionOrder(isd, order, osec.flags & SHF_EXECINSTR);12021203if (script->hasSectionsCommand)1204return;12051206if (name == ".init_array" || name == ".fini_array") {1207osec.sortInitFini();1208} else if (name == ".ctors" || name == ".dtors") {1209osec.sortCtorsDtors();1210} else if (config->emachine == EM_PPC64 && name == ".toc") {1211// .toc is allocated just after .got and is accessed using GOT-relative1212// relocations. Object files compiled with small code model have an1213// addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations.1214// To reduce the risk of relocation overflow, .toc contents are sorted so1215// that sections having smaller relocation offsets are at beginning of .toc1216assert(osec.commands.size() == 1);1217auto *isd = cast<InputSectionDescription>(osec.commands[0]);1218llvm::stable_sort(isd->sections,1219[](const InputSection *a, const InputSection *b) -> bool {1220return a->file->ppc64SmallCodeModelTocRelocs &&1221!b->file->ppc64SmallCodeModelTocRelocs;1222});1223}1224}12251226// If no layout was provided by linker script, we want to apply default1227// sorting for special input sections. This also handles --symbol-ordering-file.1228template <class ELFT> void Writer<ELFT>::sortInputSections() {1229// Build the order once since it is expensive.1230DenseMap<const InputSectionBase *, int> order = buildSectionOrder();1231maybeShuffle(order);1232for (SectionCommand *cmd : script->sectionCommands)1233if (auto *osd = dyn_cast<OutputDesc>(cmd))1234sortSection(osd->osec, order);1235}12361237template <class ELFT> void Writer<ELFT>::sortSections() {1238llvm::TimeTraceScope timeScope("Sort sections");12391240// Don't sort if using -r. It is not necessary and we want to preserve the1241// relative order for SHF_LINK_ORDER sections.1242if (config->relocatable) {1243script->adjustOutputSections();1244return;1245}12461247sortInputSections();12481249for (SectionCommand *cmd : script->sectionCommands)1250if (auto *osd = dyn_cast<OutputDesc>(cmd))1251osd->osec.sortRank = getSectionRank(osd->osec);1252if (!script->hasSectionsCommand) {1253// OutputDescs are mostly contiguous, but may be interleaved with1254// SymbolAssignments in the presence of INSERT commands.1255auto mid = std::stable_partition(1256script->sectionCommands.begin(), script->sectionCommands.end(),1257[](SectionCommand *cmd) { return isa<OutputDesc>(cmd); });1258std::stable_sort(script->sectionCommands.begin(), mid, compareSections);1259}12601261// Process INSERT commands and update output section attributes. From this1262// point onwards the order of script->sectionCommands is fixed.1263script->processInsertCommands();1264script->adjustOutputSections();12651266if (script->hasSectionsCommand)1267sortOrphanSections();12681269script->adjustSectionsAfterSorting();1270}12711272template <class ELFT> void Writer<ELFT>::sortOrphanSections() {1273// Orphan sections are sections present in the input files which are1274// not explicitly placed into the output file by the linker script.1275//1276// The sections in the linker script are already in the correct1277// order. We have to figuere out where to insert the orphan1278// sections.1279//1280// The order of the sections in the script is arbitrary and may not agree with1281// compareSections. This means that we cannot easily define a strict weak1282// ordering. To see why, consider a comparison of a section in the script and1283// one not in the script. We have a two simple options:1284// * Make them equivalent (a is not less than b, and b is not less than a).1285// The problem is then that equivalence has to be transitive and we can1286// have sections a, b and c with only b in a script and a less than c1287// which breaks this property.1288// * Use compareSectionsNonScript. Given that the script order doesn't have1289// to match, we can end up with sections a, b, c, d where b and c are in the1290// script and c is compareSectionsNonScript less than b. In which case d1291// can be equivalent to c, a to b and d < a. As a concrete example:1292// .a (rx) # not in script1293// .b (rx) # in script1294// .c (ro) # in script1295// .d (ro) # not in script1296//1297// The way we define an order then is:1298// * Sort only the orphan sections. They are in the end right now.1299// * Move each orphan section to its preferred position. We try1300// to put each section in the last position where it can share1301// a PT_LOAD.1302//1303// There is some ambiguity as to where exactly a new entry should be1304// inserted, because Commands contains not only output section1305// commands but also other types of commands such as symbol assignment1306// expressions. There's no correct answer here due to the lack of the1307// formal specification of the linker script. We use heuristics to1308// determine whether a new output command should be added before or1309// after another commands. For the details, look at shouldSkip1310// function.13111312auto i = script->sectionCommands.begin();1313auto e = script->sectionCommands.end();1314auto nonScriptI = std::find_if(i, e, [](SectionCommand *cmd) {1315if (auto *osd = dyn_cast<OutputDesc>(cmd))1316return osd->osec.sectionIndex == UINT32_MAX;1317return false;1318});13191320// Sort the orphan sections.1321std::stable_sort(nonScriptI, e, compareSections);13221323// As a horrible special case, skip the first . assignment if it is before any1324// section. We do this because it is common to set a load address by starting1325// the script with ". = 0xabcd" and the expectation is that every section is1326// after that.1327auto firstSectionOrDotAssignment =1328std::find_if(i, e, [](SectionCommand *cmd) { return !shouldSkip(cmd); });1329if (firstSectionOrDotAssignment != e &&1330isa<SymbolAssignment>(**firstSectionOrDotAssignment))1331++firstSectionOrDotAssignment;1332i = firstSectionOrDotAssignment;13331334while (nonScriptI != e) {1335auto pos = findOrphanPos(i, nonScriptI);1336OutputSection *orphan = &cast<OutputDesc>(*nonScriptI)->osec;13371338// As an optimization, find all sections with the same sort rank1339// and insert them with one rotate.1340unsigned rank = orphan->sortRank;1341auto end = std::find_if(nonScriptI + 1, e, [=](SectionCommand *cmd) {1342return cast<OutputDesc>(cmd)->osec.sortRank != rank;1343});1344std::rotate(pos, nonScriptI, end);1345nonScriptI = end;1346}1347}13481349static bool compareByFilePosition(InputSection *a, InputSection *b) {1350InputSection *la = a->flags & SHF_LINK_ORDER ? a->getLinkOrderDep() : nullptr;1351InputSection *lb = b->flags & SHF_LINK_ORDER ? b->getLinkOrderDep() : nullptr;1352// SHF_LINK_ORDER sections with non-zero sh_link are ordered before1353// non-SHF_LINK_ORDER sections and SHF_LINK_ORDER sections with zero sh_link.1354if (!la || !lb)1355return la && !lb;1356OutputSection *aOut = la->getParent();1357OutputSection *bOut = lb->getParent();13581359if (aOut == bOut)1360return la->outSecOff < lb->outSecOff;1361if (aOut->addr == bOut->addr)1362return aOut->sectionIndex < bOut->sectionIndex;1363return aOut->addr < bOut->addr;1364}13651366template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {1367llvm::TimeTraceScope timeScope("Resolve SHF_LINK_ORDER");1368for (OutputSection *sec : outputSections) {1369if (!(sec->flags & SHF_LINK_ORDER))1370continue;13711372// The ARM.exidx section use SHF_LINK_ORDER, but we have consolidated1373// this processing inside the ARMExidxsyntheticsection::finalizeContents().1374if (!config->relocatable && config->emachine == EM_ARM &&1375sec->type == SHT_ARM_EXIDX)1376continue;13771378// Link order may be distributed across several InputSectionDescriptions.1379// Sorting is performed separately.1380SmallVector<InputSection **, 0> scriptSections;1381SmallVector<InputSection *, 0> sections;1382for (SectionCommand *cmd : sec->commands) {1383auto *isd = dyn_cast<InputSectionDescription>(cmd);1384if (!isd)1385continue;1386bool hasLinkOrder = false;1387scriptSections.clear();1388sections.clear();1389for (InputSection *&isec : isd->sections) {1390if (isec->flags & SHF_LINK_ORDER) {1391InputSection *link = isec->getLinkOrderDep();1392if (link && !link->getParent())1393error(toString(isec) + ": sh_link points to discarded section " +1394toString(link));1395hasLinkOrder = true;1396}1397scriptSections.push_back(&isec);1398sections.push_back(isec);1399}1400if (hasLinkOrder && errorCount() == 0) {1401llvm::stable_sort(sections, compareByFilePosition);1402for (int i = 0, n = sections.size(); i != n; ++i)1403*scriptSections[i] = sections[i];1404}1405}1406}1407}14081409static void finalizeSynthetic(SyntheticSection *sec) {1410if (sec && sec->isNeeded() && sec->getParent()) {1411llvm::TimeTraceScope timeScope("Finalize synthetic sections", sec->name);1412sec->finalizeContents();1413}1414}14151416// We need to generate and finalize the content that depends on the address of1417// InputSections. As the generation of the content may also alter InputSection1418// addresses we must converge to a fixed point. We do that here. See the comment1419// in Writer<ELFT>::finalizeSections().1420template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() {1421llvm::TimeTraceScope timeScope("Finalize address dependent content");1422ThunkCreator tc;1423AArch64Err843419Patcher a64p;1424ARMErr657417Patcher a32p;1425script->assignAddresses();14261427// .ARM.exidx and SHF_LINK_ORDER do not require precise addresses, but they1428// do require the relative addresses of OutputSections because linker scripts1429// can assign Virtual Addresses to OutputSections that are not monotonically1430// increasing. Anything here must be repeatable, since spilling may change1431// section order.1432const auto finalizeOrderDependentContent = [this] {1433for (Partition &part : partitions)1434finalizeSynthetic(part.armExidx.get());1435resolveShfLinkOrder();1436};1437finalizeOrderDependentContent();14381439// Converts call x@GDPLT to call __tls_get_addr1440if (config->emachine == EM_HEXAGON)1441hexagonTLSSymbolUpdate(outputSections);14421443uint32_t pass = 0, assignPasses = 0;1444for (;;) {1445bool changed = target->needsThunks ? tc.createThunks(pass, outputSections)1446: target->relaxOnce(pass);1447bool spilled = script->spillSections();1448changed |= spilled;1449++pass;14501451// With Thunk Size much smaller than branch range we expect to1452// converge quickly; if we get to 30 something has gone wrong.1453if (changed && pass >= 30) {1454error(target->needsThunks ? "thunk creation not converged"1455: "relaxation not converged");1456break;1457}14581459if (config->fixCortexA53Errata843419) {1460if (changed)1461script->assignAddresses();1462changed |= a64p.createFixes();1463}1464if (config->fixCortexA8) {1465if (changed)1466script->assignAddresses();1467changed |= a32p.createFixes();1468}14691470finalizeSynthetic(in.got.get());1471if (in.mipsGot)1472in.mipsGot->updateAllocSize();14731474for (Partition &part : partitions) {1475// The R_AARCH64_AUTH_RELATIVE has a smaller addend field as bits [63:32]1476// encode the signing schema. We've put relocations in .relr.auth.dyn1477// during RelocationScanner::processAux, but the target VA for some of1478// them might be wider than 32 bits. We can only know the final VA at this1479// point, so move relocations with large values from .relr.auth.dyn to1480// .rela.dyn. See also AArch64::relocate.1481if (part.relrAuthDyn) {1482auto it = llvm::remove_if(1483part.relrAuthDyn->relocs, [&part](const RelativeReloc &elem) {1484const Relocation &reloc = elem.inputSec->relocs()[elem.relocIdx];1485if (isInt<32>(reloc.sym->getVA(reloc.addend)))1486return false;1487part.relaDyn->addReloc({R_AARCH64_AUTH_RELATIVE, elem.inputSec,1488reloc.offset,1489DynamicReloc::AddendOnlyWithTargetVA,1490*reloc.sym, reloc.addend, R_ABS});1491return true;1492});1493changed |= (it != part.relrAuthDyn->relocs.end());1494part.relrAuthDyn->relocs.erase(it, part.relrAuthDyn->relocs.end());1495}1496if (part.relaDyn)1497changed |= part.relaDyn->updateAllocSize();1498if (part.relrDyn)1499changed |= part.relrDyn->updateAllocSize();1500if (part.relrAuthDyn)1501changed |= part.relrAuthDyn->updateAllocSize();1502if (part.memtagGlobalDescriptors)1503changed |= part.memtagGlobalDescriptors->updateAllocSize();1504}15051506std::pair<const OutputSection *, const Defined *> changes =1507script->assignAddresses();1508if (!changed) {1509// Some symbols may be dependent on section addresses. When we break the1510// loop, the symbol values are finalized because a previous1511// assignAddresses() finalized section addresses.1512if (!changes.first && !changes.second)1513break;1514if (++assignPasses == 5) {1515if (changes.first)1516errorOrWarn("address (0x" + Twine::utohexstr(changes.first->addr) +1517") of section '" + changes.first->name +1518"' does not converge");1519if (changes.second)1520errorOrWarn("assignment to symbol " + toString(*changes.second) +1521" does not converge");1522break;1523}1524} else if (spilled) {1525// Spilling can change relative section order.1526finalizeOrderDependentContent();1527}1528}1529if (!config->relocatable)1530target->finalizeRelax(pass);15311532if (config->relocatable)1533for (OutputSection *sec : outputSections)1534sec->addr = 0;15351536// If addrExpr is set, the address may not be a multiple of the alignment.1537// Warn because this is error-prone.1538for (SectionCommand *cmd : script->sectionCommands)1539if (auto *osd = dyn_cast<OutputDesc>(cmd)) {1540OutputSection *osec = &osd->osec;1541if (osec->addr % osec->addralign != 0)1542warn("address (0x" + Twine::utohexstr(osec->addr) + ") of section " +1543osec->name + " is not a multiple of alignment (" +1544Twine(osec->addralign) + ")");1545}15461547// Sizes are no longer allowed to grow, so all allowable spills have been1548// taken. Remove any leftover potential spills.1549script->erasePotentialSpillSections();1550}15511552// If Input Sections have been shrunk (basic block sections) then1553// update symbol values and sizes associated with these sections. With basic1554// block sections, input sections can shrink when the jump instructions at1555// the end of the section are relaxed.1556static void fixSymbolsAfterShrinking() {1557for (InputFile *File : ctx.objectFiles) {1558parallelForEach(File->getSymbols(), [&](Symbol *Sym) {1559auto *def = dyn_cast<Defined>(Sym);1560if (!def)1561return;15621563const SectionBase *sec = def->section;1564if (!sec)1565return;15661567const InputSectionBase *inputSec = dyn_cast<InputSectionBase>(sec);1568if (!inputSec || !inputSec->bytesDropped)1569return;15701571const size_t OldSize = inputSec->content().size();1572const size_t NewSize = OldSize - inputSec->bytesDropped;15731574if (def->value > NewSize && def->value <= OldSize) {1575LLVM_DEBUG(llvm::dbgs()1576<< "Moving symbol " << Sym->getName() << " from "1577<< def->value << " to "1578<< def->value - inputSec->bytesDropped << " bytes\n");1579def->value -= inputSec->bytesDropped;1580return;1581}15821583if (def->value + def->size > NewSize && def->value <= OldSize &&1584def->value + def->size <= OldSize) {1585LLVM_DEBUG(llvm::dbgs()1586<< "Shrinking symbol " << Sym->getName() << " from "1587<< def->size << " to " << def->size - inputSec->bytesDropped1588<< " bytes\n");1589def->size -= inputSec->bytesDropped;1590}1591});1592}1593}15941595// If basic block sections exist, there are opportunities to delete fall thru1596// jumps and shrink jump instructions after basic block reordering. This1597// relaxation pass does that. It is only enabled when --optimize-bb-jumps1598// option is used.1599template <class ELFT> void Writer<ELFT>::optimizeBasicBlockJumps() {1600assert(config->optimizeBBJumps);1601SmallVector<InputSection *, 0> storage;16021603script->assignAddresses();1604// For every output section that has executable input sections, this1605// does the following:1606// 1. Deletes all direct jump instructions in input sections that1607// jump to the following section as it is not required.1608// 2. If there are two consecutive jump instructions, it checks1609// if they can be flipped and one can be deleted.1610for (OutputSection *osec : outputSections) {1611if (!(osec->flags & SHF_EXECINSTR))1612continue;1613ArrayRef<InputSection *> sections = getInputSections(*osec, storage);1614size_t numDeleted = 0;1615// Delete all fall through jump instructions. Also, check if two1616// consecutive jump instructions can be flipped so that a fall1617// through jmp instruction can be deleted.1618for (size_t i = 0, e = sections.size(); i != e; ++i) {1619InputSection *next = i + 1 < sections.size() ? sections[i + 1] : nullptr;1620InputSection &sec = *sections[i];1621numDeleted += target->deleteFallThruJmpInsn(sec, sec.file, next);1622}1623if (numDeleted > 0) {1624script->assignAddresses();1625LLVM_DEBUG(llvm::dbgs()1626<< "Removing " << numDeleted << " fall through jumps\n");1627}1628}16291630fixSymbolsAfterShrinking();16311632for (OutputSection *osec : outputSections)1633for (InputSection *is : getInputSections(*osec, storage))1634is->trim();1635}16361637// In order to allow users to manipulate linker-synthesized sections,1638// we had to add synthetic sections to the input section list early,1639// even before we make decisions whether they are needed. This allows1640// users to write scripts like this: ".mygot : { .got }".1641//1642// Doing it has an unintended side effects. If it turns out that we1643// don't need a .got (for example) at all because there's no1644// relocation that needs a .got, we don't want to emit .got.1645//1646// To deal with the above problem, this function is called after1647// scanRelocations is called to remove synthetic sections that turn1648// out to be empty.1649static void removeUnusedSyntheticSections() {1650// All input synthetic sections that can be empty are placed after1651// all regular ones. Reverse iterate to find the first synthetic section1652// after a non-synthetic one which will be our starting point.1653auto start =1654llvm::find_if(llvm::reverse(ctx.inputSections), [](InputSectionBase *s) {1655return !isa<SyntheticSection>(s);1656}).base();16571658// Remove unused synthetic sections from ctx.inputSections;1659DenseSet<InputSectionBase *> unused;1660auto end =1661std::remove_if(start, ctx.inputSections.end(), [&](InputSectionBase *s) {1662auto *sec = cast<SyntheticSection>(s);1663if (sec->getParent() && sec->isNeeded())1664return false;1665// .relr.auth.dyn relocations may be moved to .rela.dyn in1666// finalizeAddressDependentContent, making .rela.dyn no longer empty.1667// Conservatively keep .rela.dyn. .relr.auth.dyn can be made empty, but1668// we would fail to remove it here.1669if (config->emachine == EM_AARCH64 && config->relrPackDynRelocs)1670if (auto *relSec = dyn_cast<RelocationBaseSection>(sec))1671if (relSec == mainPart->relaDyn.get())1672return false;1673unused.insert(sec);1674return true;1675});1676ctx.inputSections.erase(end, ctx.inputSections.end());16771678// Remove unused synthetic sections from the corresponding input section1679// description and orphanSections.1680for (auto *sec : unused)1681if (OutputSection *osec = cast<SyntheticSection>(sec)->getParent())1682for (SectionCommand *cmd : osec->commands)1683if (auto *isd = dyn_cast<InputSectionDescription>(cmd))1684llvm::erase_if(isd->sections, [&](InputSection *isec) {1685return unused.count(isec);1686});1687llvm::erase_if(script->orphanSections, [&](const InputSectionBase *sec) {1688return unused.count(sec);1689});1690}16911692// Create output section objects and add them to OutputSections.1693template <class ELFT> void Writer<ELFT>::finalizeSections() {1694if (!config->relocatable) {1695Out::preinitArray = findSection(".preinit_array");1696Out::initArray = findSection(".init_array");1697Out::finiArray = findSection(".fini_array");16981699// The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop1700// symbols for sections, so that the runtime can get the start and end1701// addresses of each section by section name. Add such symbols.1702addStartEndSymbols();1703for (SectionCommand *cmd : script->sectionCommands)1704if (auto *osd = dyn_cast<OutputDesc>(cmd))1705addStartStopSymbols(osd->osec);17061707// Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.1708// It should be okay as no one seems to care about the type.1709// Even the author of gold doesn't remember why gold behaves that way.1710// https://sourceware.org/ml/binutils/2002-03/msg00360.html1711if (mainPart->dynamic->parent) {1712Symbol *s = symtab.addSymbol(Defined{1713ctx.internalFile, "_DYNAMIC", STB_WEAK, STV_HIDDEN, STT_NOTYPE,1714/*value=*/0, /*size=*/0, mainPart->dynamic.get()});1715s->isUsedInRegularObj = true;1716}17171718// Define __rel[a]_iplt_{start,end} symbols if needed.1719addRelIpltSymbols();17201721// RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800. This symbol1722// should only be defined in an executable. If .sdata does not exist, its1723// value/section does not matter but it has to be relative, so set its1724// st_shndx arbitrarily to 1 (Out::elfHeader).1725if (config->emachine == EM_RISCV) {1726ElfSym::riscvGlobalPointer = nullptr;1727if (!config->shared) {1728OutputSection *sec = findSection(".sdata");1729addOptionalRegular(1730"__global_pointer$", sec ? sec : Out::elfHeader, 0x800, STV_DEFAULT);1731// Set riscvGlobalPointer to be used by the optional global pointer1732// relaxation.1733if (config->relaxGP) {1734Symbol *s = symtab.find("__global_pointer$");1735if (s && s->isDefined())1736ElfSym::riscvGlobalPointer = cast<Defined>(s);1737}1738}1739}17401741if (config->emachine == EM_386 || config->emachine == EM_X86_64) {1742// On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a1743// way that:1744//1745// 1) Without relaxation: it produces a dynamic TLSDESC relocation that1746// computes 0.1747// 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address1748// in the TLS block).1749//1750// 2) is special cased in @tpoff computation. To satisfy 1), we define it1751// as an absolute symbol of zero. This is different from GNU linkers which1752// define _TLS_MODULE_BASE_ relative to the first TLS section.1753Symbol *s = symtab.find("_TLS_MODULE_BASE_");1754if (s && s->isUndefined()) {1755s->resolve(Defined{ctx.internalFile, StringRef(), STB_GLOBAL,1756STV_HIDDEN, STT_TLS, /*value=*/0, 0,1757/*section=*/nullptr});1758ElfSym::tlsModuleBase = cast<Defined>(s);1759}1760}17611762// This responsible for splitting up .eh_frame section into1763// pieces. The relocation scan uses those pieces, so this has to be1764// earlier.1765{1766llvm::TimeTraceScope timeScope("Finalize .eh_frame");1767for (Partition &part : partitions)1768finalizeSynthetic(part.ehFrame.get());1769}1770}17711772demoteSymbolsAndComputeIsPreemptible();17731774if (config->copyRelocs && config->discard != DiscardPolicy::None)1775markUsedLocalSymbols<ELFT>();1776demoteAndCopyLocalSymbols();17771778if (config->copyRelocs)1779addSectionSymbols();17801781// Change values of linker-script-defined symbols from placeholders (assigned1782// by declareSymbols) to actual definitions.1783script->processSymbolAssignments();17841785if (!config->relocatable) {1786llvm::TimeTraceScope timeScope("Scan relocations");1787// Scan relocations. This must be done after every symbol is declared so1788// that we can correctly decide if a dynamic relocation is needed. This is1789// called after processSymbolAssignments() because it needs to know whether1790// a linker-script-defined symbol is absolute.1791ppc64noTocRelax.clear();1792scanRelocations<ELFT>();1793reportUndefinedSymbols();1794postScanRelocations();17951796if (in.plt && in.plt->isNeeded())1797in.plt->addSymbols();1798if (in.iplt && in.iplt->isNeeded())1799in.iplt->addSymbols();18001801if (config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) {1802auto diagnose =1803config->unresolvedSymbolsInShlib == UnresolvedPolicy::ReportError1804? errorOrWarn1805: warn;1806// Error on undefined symbols in a shared object, if all of its DT_NEEDED1807// entries are seen. These cases would otherwise lead to runtime errors1808// reported by the dynamic linker.1809//1810// ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker1811// to catch more cases. That is too much for us. Our approach resembles1812// the one used in ld.gold, achieves a good balance to be useful but not1813// too smart.1814//1815// If a DSO reference is resolved by a SharedSymbol, but the SharedSymbol1816// is overridden by a hidden visibility Defined (which is later discarded1817// due to GC), don't report the diagnostic. However, this may indicate an1818// unintended SharedSymbol.1819for (SharedFile *file : ctx.sharedFiles) {1820bool allNeededIsKnown =1821llvm::all_of(file->dtNeeded, [&](StringRef needed) {1822return symtab.soNames.count(CachedHashStringRef(needed));1823});1824if (!allNeededIsKnown)1825continue;1826for (Symbol *sym : file->requiredSymbols) {1827if (sym->dsoDefined)1828continue;1829if (sym->isUndefined() && !sym->isWeak()) {1830diagnose("undefined reference: " + toString(*sym) +1831"\n>>> referenced by " + toString(file) +1832" (disallowed by --no-allow-shlib-undefined)");1833} else if (sym->isDefined() && sym->computeBinding() == STB_LOCAL) {1834diagnose("non-exported symbol '" + toString(*sym) + "' in '" +1835toString(sym->file) + "' is referenced by DSO '" +1836toString(file) + "'");1837}1838}1839}1840}1841}18421843{1844llvm::TimeTraceScope timeScope("Add symbols to symtabs");1845// Now that we have defined all possible global symbols including linker-1846// synthesized ones. Visit all symbols to give the finishing touches.1847for (Symbol *sym : symtab.getSymbols()) {1848if (!sym->isUsedInRegularObj || !includeInSymtab(*sym))1849continue;1850if (!config->relocatable)1851sym->binding = sym->computeBinding();1852if (in.symTab)1853in.symTab->addSymbol(sym);18541855if (sym->includeInDynsym()) {1856partitions[sym->partition - 1].dynSymTab->addSymbol(sym);1857if (auto *file = dyn_cast_or_null<SharedFile>(sym->file))1858if (file->isNeeded && !sym->isUndefined())1859addVerneed(sym);1860}1861}18621863// We also need to scan the dynamic relocation tables of the other1864// partitions and add any referenced symbols to the partition's dynsym.1865for (Partition &part : MutableArrayRef<Partition>(partitions).slice(1)) {1866DenseSet<Symbol *> syms;1867for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())1868syms.insert(e.sym);1869for (DynamicReloc &reloc : part.relaDyn->relocs)1870if (reloc.sym && reloc.needsDynSymIndex() &&1871syms.insert(reloc.sym).second)1872part.dynSymTab->addSymbol(reloc.sym);1873}1874}18751876if (in.mipsGot)1877in.mipsGot->build();18781879removeUnusedSyntheticSections();1880script->diagnoseOrphanHandling();1881script->diagnoseMissingSGSectionAddress();18821883sortSections();18841885// Create a list of OutputSections, assign sectionIndex, and populate1886// in.shStrTab.1887for (SectionCommand *cmd : script->sectionCommands)1888if (auto *osd = dyn_cast<OutputDesc>(cmd)) {1889OutputSection *osec = &osd->osec;1890outputSections.push_back(osec);1891osec->sectionIndex = outputSections.size();1892osec->shName = in.shStrTab->addString(osec->name);1893}18941895// Prefer command line supplied address over other constraints.1896for (OutputSection *sec : outputSections) {1897auto i = config->sectionStartMap.find(sec->name);1898if (i != config->sectionStartMap.end())1899sec->addrExpr = [=] { return i->second; };1900}19011902// With the outputSections available check for GDPLT relocations1903// and add __tls_get_addr symbol if needed.1904if (config->emachine == EM_HEXAGON && hexagonNeedsTLSSymbol(outputSections)) {1905Symbol *sym =1906symtab.addSymbol(Undefined{ctx.internalFile, "__tls_get_addr",1907STB_GLOBAL, STV_DEFAULT, STT_NOTYPE});1908sym->isPreemptible = true;1909partitions[0].dynSymTab->addSymbol(sym);1910}19111912// This is a bit of a hack. A value of 0 means undef, so we set it1913// to 1 to make __ehdr_start defined. The section number is not1914// particularly relevant.1915Out::elfHeader->sectionIndex = 1;1916Out::elfHeader->size = sizeof(typename ELFT::Ehdr);19171918// Binary and relocatable output does not have PHDRS.1919// The headers have to be created before finalize as that can influence the1920// image base and the dynamic section on mips includes the image base.1921if (!config->relocatable && !config->oFormatBinary) {1922for (Partition &part : partitions) {1923part.phdrs = script->hasPhdrsCommands() ? script->createPhdrs()1924: createPhdrs(part);1925if (config->emachine == EM_ARM) {1926// PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME1927addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);1928}1929if (config->emachine == EM_MIPS) {1930// Add separate segments for MIPS-specific sections.1931addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);1932addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);1933addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);1934}1935if (config->emachine == EM_RISCV)1936addPhdrForSection(part, SHT_RISCV_ATTRIBUTES, PT_RISCV_ATTRIBUTES,1937PF_R);1938}1939Out::programHeaders->size = sizeof(Elf_Phdr) * mainPart->phdrs.size();19401941// Find the TLS segment. This happens before the section layout loop so that1942// Android relocation packing can look up TLS symbol addresses. We only need1943// to care about the main partition here because all TLS symbols were moved1944// to the main partition (see MarkLive.cpp).1945for (PhdrEntry *p : mainPart->phdrs)1946if (p->p_type == PT_TLS)1947Out::tlsPhdr = p;1948}19491950// Some symbols are defined in term of program headers. Now that we1951// have the headers, we can find out which sections they point to.1952setReservedSymbolSections();19531954if (script->noCrossRefs.size()) {1955llvm::TimeTraceScope timeScope("Check NOCROSSREFS");1956checkNoCrossRefs<ELFT>();1957}19581959{1960llvm::TimeTraceScope timeScope("Finalize synthetic sections");19611962finalizeSynthetic(in.bss.get());1963finalizeSynthetic(in.bssRelRo.get());1964finalizeSynthetic(in.symTabShndx.get());1965finalizeSynthetic(in.shStrTab.get());1966finalizeSynthetic(in.strTab.get());1967finalizeSynthetic(in.got.get());1968finalizeSynthetic(in.mipsGot.get());1969finalizeSynthetic(in.igotPlt.get());1970finalizeSynthetic(in.gotPlt.get());1971finalizeSynthetic(in.relaPlt.get());1972finalizeSynthetic(in.plt.get());1973finalizeSynthetic(in.iplt.get());1974finalizeSynthetic(in.ppc32Got2.get());1975finalizeSynthetic(in.partIndex.get());19761977// Dynamic section must be the last one in this list and dynamic1978// symbol table section (dynSymTab) must be the first one.1979for (Partition &part : partitions) {1980if (part.relaDyn) {1981part.relaDyn->mergeRels();1982// Compute DT_RELACOUNT to be used by part.dynamic.1983part.relaDyn->partitionRels();1984finalizeSynthetic(part.relaDyn.get());1985}1986if (part.relrDyn) {1987part.relrDyn->mergeRels();1988finalizeSynthetic(part.relrDyn.get());1989}1990if (part.relrAuthDyn) {1991part.relrAuthDyn->mergeRels();1992finalizeSynthetic(part.relrAuthDyn.get());1993}19941995finalizeSynthetic(part.dynSymTab.get());1996finalizeSynthetic(part.gnuHashTab.get());1997finalizeSynthetic(part.hashTab.get());1998finalizeSynthetic(part.verDef.get());1999finalizeSynthetic(part.ehFrameHdr.get());2000finalizeSynthetic(part.verSym.get());2001finalizeSynthetic(part.verNeed.get());2002finalizeSynthetic(part.dynamic.get());2003}2004}20052006if (!script->hasSectionsCommand && !config->relocatable)2007fixSectionAlignments();20082009// This is used to:2010// 1) Create "thunks":2011// Jump instructions in many ISAs have small displacements, and therefore2012// they cannot jump to arbitrary addresses in memory. For example, RISC-V2013// JAL instruction can target only +-1 MiB from PC. It is a linker's2014// responsibility to create and insert small pieces of code between2015// sections to extend the ranges if jump targets are out of range. Such2016// code pieces are called "thunks".2017//2018// We add thunks at this stage. We couldn't do this before this point2019// because this is the earliest point where we know sizes of sections and2020// their layouts (that are needed to determine if jump targets are in2021// range).2022//2023// 2) Update the sections. We need to generate content that depends on the2024// address of InputSections. For example, MIPS GOT section content or2025// android packed relocations sections content.2026//2027// 3) Assign the final values for the linker script symbols. Linker scripts2028// sometimes using forward symbol declarations. We want to set the correct2029// values. They also might change after adding the thunks.2030finalizeAddressDependentContent();20312032// All information needed for OutputSection part of Map file is available.2033if (errorCount())2034return;20352036{2037llvm::TimeTraceScope timeScope("Finalize synthetic sections");2038// finalizeAddressDependentContent may have added local symbols to the2039// static symbol table.2040finalizeSynthetic(in.symTab.get());2041finalizeSynthetic(in.debugNames.get());2042finalizeSynthetic(in.ppc64LongBranchTarget.get());2043finalizeSynthetic(in.armCmseSGSection.get());2044}20452046// Relaxation to delete inter-basic block jumps created by basic block2047// sections. Run after in.symTab is finalized as optimizeBasicBlockJumps2048// can relax jump instructions based on symbol offset.2049if (config->optimizeBBJumps)2050optimizeBasicBlockJumps();20512052// Fill other section headers. The dynamic table is finalized2053// at the end because some tags like RELSZ depend on result2054// of finalizing other sections.2055for (OutputSection *sec : outputSections)2056sec->finalize();20572058script->checkFinalScriptConditions();20592060if (config->emachine == EM_ARM && !config->isLE && config->armBe8) {2061addArmInputSectionMappingSymbols();2062sortArmMappingSymbols();2063}2064}20652066// Ensure data sections are not mixed with executable sections when2067// --execute-only is used. --execute-only make pages executable but not2068// readable.2069template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {2070if (!config->executeOnly)2071return;20722073SmallVector<InputSection *, 0> storage;2074for (OutputSection *osec : outputSections)2075if (osec->flags & SHF_EXECINSTR)2076for (InputSection *isec : getInputSections(*osec, storage))2077if (!(isec->flags & SHF_EXECINSTR))2078error("cannot place " + toString(isec) + " into " +2079toString(osec->name) +2080": --execute-only does not support intermingling data and code");2081}20822083// The linker is expected to define SECNAME_start and SECNAME_end2084// symbols for a few sections. This function defines them.2085template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {2086// If the associated output section does not exist, there is ambiguity as to2087// how we define _start and _end symbols for an init/fini section. Users2088// expect no "undefined symbol" linker errors and loaders expect equal2089// st_value but do not particularly care whether the symbols are defined or2090// not. We retain the output section so that the section indexes will be2091// correct.2092auto define = [=](StringRef start, StringRef end, OutputSection *os) {2093if (os) {2094Defined *startSym = addOptionalRegular(start, os, 0);2095Defined *stopSym = addOptionalRegular(end, os, -1);2096if (startSym || stopSym)2097os->usedInExpression = true;2098} else {2099addOptionalRegular(start, Out::elfHeader, 0);2100addOptionalRegular(end, Out::elfHeader, 0);2101}2102};21032104define("__preinit_array_start", "__preinit_array_end", Out::preinitArray);2105define("__init_array_start", "__init_array_end", Out::initArray);2106define("__fini_array_start", "__fini_array_end", Out::finiArray);21072108// As a special case, don't unnecessarily retain .ARM.exidx, which would2109// create an empty PT_ARM_EXIDX.2110if (OutputSection *sec = findSection(".ARM.exidx"))2111define("__exidx_start", "__exidx_end", sec);2112}21132114// If a section name is valid as a C identifier (which is rare because of2115// the leading '.'), linkers are expected to define __start_<secname> and2116// __stop_<secname> symbols. They are at beginning and end of the section,2117// respectively. This is not requested by the ELF standard, but GNU ld and2118// gold provide the feature, and used by many programs.2119template <class ELFT>2120void Writer<ELFT>::addStartStopSymbols(OutputSection &osec) {2121StringRef s = osec.name;2122if (!isValidCIdentifier(s))2123return;2124Defined *startSym = addOptionalRegular(saver().save("__start_" + s), &osec, 0,2125config->zStartStopVisibility);2126Defined *stopSym = addOptionalRegular(saver().save("__stop_" + s), &osec, -1,2127config->zStartStopVisibility);2128if (startSym || stopSym)2129osec.usedInExpression = true;2130}21312132static bool needsPtLoad(OutputSection *sec) {2133if (!(sec->flags & SHF_ALLOC))2134return false;21352136// Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is2137// responsible for allocating space for them, not the PT_LOAD that2138// contains the TLS initialization image.2139if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)2140return false;2141return true;2142}21432144// Adjust phdr flags according to certain options.2145static uint64_t computeFlags(uint64_t flags) {2146if (config->omagic)2147return PF_R | PF_W | PF_X;2148if (config->executeOnly && (flags & PF_X))2149return flags & ~PF_R;2150return flags;2151}21522153// Decide which program headers to create and which sections to include in each2154// one.2155template <class ELFT>2156SmallVector<PhdrEntry *, 0> Writer<ELFT>::createPhdrs(Partition &part) {2157SmallVector<PhdrEntry *, 0> ret;2158auto addHdr = [&](unsigned type, unsigned flags) -> PhdrEntry * {2159ret.push_back(make<PhdrEntry>(type, flags));2160return ret.back();2161};21622163unsigned partNo = part.getNumber();2164bool isMain = partNo == 1;21652166// Add the first PT_LOAD segment for regular output sections.2167uint64_t flags = computeFlags(PF_R);2168PhdrEntry *load = nullptr;21692170// nmagic or omagic output does not have PT_PHDR, PT_INTERP, or the readonly2171// PT_LOAD.2172if (!config->nmagic && !config->omagic) {2173// The first phdr entry is PT_PHDR which describes the program header2174// itself.2175if (isMain)2176addHdr(PT_PHDR, PF_R)->add(Out::programHeaders);2177else2178addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());21792180// PT_INTERP must be the second entry if exists.2181if (OutputSection *cmd = findSection(".interp", partNo))2182addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);21832184// Add the headers. We will remove them if they don't fit.2185// In the other partitions the headers are ordinary sections, so they don't2186// need to be added here.2187if (isMain) {2188load = addHdr(PT_LOAD, flags);2189load->add(Out::elfHeader);2190load->add(Out::programHeaders);2191}2192}21932194// PT_GNU_RELRO includes all sections that should be marked as2195// read-only by dynamic linker after processing relocations.2196// Current dynamic loaders only support one PT_GNU_RELRO PHDR, give2197// an error message if more than one PT_GNU_RELRO PHDR is required.2198PhdrEntry *relRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);2199bool inRelroPhdr = false;2200OutputSection *relroEnd = nullptr;2201for (OutputSection *sec : outputSections) {2202if (sec->partition != partNo || !needsPtLoad(sec))2203continue;2204if (isRelroSection(sec)) {2205inRelroPhdr = true;2206if (!relroEnd)2207relRo->add(sec);2208else2209error("section: " + sec->name + " is not contiguous with other relro" +2210" sections");2211} else if (inRelroPhdr) {2212inRelroPhdr = false;2213relroEnd = sec;2214}2215}2216relRo->p_align = 1;22172218for (OutputSection *sec : outputSections) {2219if (!needsPtLoad(sec))2220continue;22212222// Normally, sections in partitions other than the current partition are2223// ignored. But partition number 255 is a special case: it contains the2224// partition end marker (.part.end). It needs to be added to the main2225// partition so that a segment is created for it in the main partition,2226// which will cause the dynamic loader to reserve space for the other2227// partitions.2228if (sec->partition != partNo) {2229if (isMain && sec->partition == 255)2230addHdr(PT_LOAD, computeFlags(sec->getPhdrFlags()))->add(sec);2231continue;2232}22332234// Segments are contiguous memory regions that has the same attributes2235// (e.g. executable or writable). There is one phdr for each segment.2236// Therefore, we need to create a new phdr when the next section has2237// incompatible flags or is loaded at a discontiguous address or memory2238// region using AT or AT> linker script command, respectively.2239//2240// As an exception, we don't create a separate load segment for the ELF2241// headers, even if the first "real" output has an AT or AT> attribute.2242//2243// In addition, NOBITS sections should only be placed at the end of a LOAD2244// segment (since it's represented as p_filesz < p_memsz). If we have a2245// not-NOBITS section after a NOBITS, we create a new LOAD for the latter2246// even if flags match, so as not to require actually writing the2247// supposed-to-be-NOBITS section to the output file. (However, we cannot do2248// so when hasSectionsCommand, since we cannot introduce the extra alignment2249// needed to create a new LOAD)2250uint64_t newFlags = computeFlags(sec->getPhdrFlags());2251// When --no-rosegment is specified, RO and RX sections are compatible.2252uint32_t incompatible = flags ^ newFlags;2253if (config->singleRoRx && !(newFlags & PF_W))2254incompatible &= ~PF_X;2255if (incompatible)2256load = nullptr;22572258bool sameLMARegion =2259load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion;2260if (load && sec != relroEnd &&2261sec->memRegion == load->firstSec->memRegion &&2262(sameLMARegion || load->lastSec == Out::programHeaders) &&2263(script->hasSectionsCommand || sec->type == SHT_NOBITS ||2264load->lastSec->type != SHT_NOBITS)) {2265load->p_flags |= newFlags;2266} else {2267load = addHdr(PT_LOAD, newFlags);2268flags = newFlags;2269}22702271load->add(sec);2272}22732274// Add a TLS segment if any.2275PhdrEntry *tlsHdr = make<PhdrEntry>(PT_TLS, PF_R);2276for (OutputSection *sec : outputSections)2277if (sec->partition == partNo && sec->flags & SHF_TLS)2278tlsHdr->add(sec);2279if (tlsHdr->firstSec)2280ret.push_back(tlsHdr);22812282// Add an entry for .dynamic.2283if (OutputSection *sec = part.dynamic->getParent())2284addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);22852286if (relRo->firstSec)2287ret.push_back(relRo);22882289// PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.2290if (part.ehFrame->isNeeded() && part.ehFrameHdr &&2291part.ehFrame->getParent() && part.ehFrameHdr->getParent())2292addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())2293->add(part.ehFrameHdr->getParent());22942295if (config->osabi == ELFOSABI_OPENBSD) {2296// PT_OPENBSD_MUTABLE makes the dynamic linker fill the segment with2297// zero data, like bss, but it can be treated differently.2298if (OutputSection *cmd = findSection(".openbsd.mutable", partNo))2299addHdr(PT_OPENBSD_MUTABLE, cmd->getPhdrFlags())->add(cmd);23002301// PT_OPENBSD_RANDOMIZE makes the dynamic linker fill the segment2302// with random data.2303if (OutputSection *cmd = findSection(".openbsd.randomdata", partNo))2304addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);23052306// PT_OPENBSD_SYSCALLS makes the kernel and dynamic linker register2307// system call sites.2308if (OutputSection *cmd = findSection(".openbsd.syscalls", partNo))2309addHdr(PT_OPENBSD_SYSCALLS, cmd->getPhdrFlags())->add(cmd);2310}23112312if (config->zGnustack != GnuStackKind::None) {2313// PT_GNU_STACK is a special section to tell the loader to make the2314// pages for the stack non-executable. If you really want an executable2315// stack, you can pass -z execstack, but that's not recommended for2316// security reasons.2317unsigned perm = PF_R | PF_W;2318if (config->zGnustack == GnuStackKind::Exec)2319perm |= PF_X;2320addHdr(PT_GNU_STACK, perm)->p_memsz = config->zStackSize;2321}23222323// PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable2324// is expected to perform W^X violations, such as calling mprotect(2) or2325// mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on2326// OpenBSD.2327if (config->zWxneeded)2328addHdr(PT_OPENBSD_WXNEEDED, PF_X);23292330if (OutputSection *cmd = findSection(".note.gnu.property", partNo))2331addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);23322333// Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the2334// same alignment.2335PhdrEntry *note = nullptr;2336for (OutputSection *sec : outputSections) {2337if (sec->partition != partNo)2338continue;2339if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {2340if (!note || sec->lmaExpr || note->lastSec->addralign != sec->addralign)2341note = addHdr(PT_NOTE, PF_R);2342note->add(sec);2343} else {2344note = nullptr;2345}2346}2347return ret;2348}23492350template <class ELFT>2351void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,2352unsigned pType, unsigned pFlags) {2353unsigned partNo = part.getNumber();2354auto i = llvm::find_if(outputSections, [=](OutputSection *cmd) {2355return cmd->partition == partNo && cmd->type == shType;2356});2357if (i == outputSections.end())2358return;23592360PhdrEntry *entry = make<PhdrEntry>(pType, pFlags);2361entry->add(*i);2362part.phdrs.push_back(entry);2363}23642365// Place the first section of each PT_LOAD to a different page (of maxPageSize).2366// This is achieved by assigning an alignment expression to addrExpr of each2367// such section.2368template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {2369const PhdrEntry *prev;2370auto pageAlign = [&](const PhdrEntry *p) {2371OutputSection *cmd = p->firstSec;2372if (!cmd)2373return;2374cmd->alignExpr = [align = cmd->addralign]() { return align; };2375if (!cmd->addrExpr) {2376// Prefer advancing to align(dot, maxPageSize) + dot%maxPageSize to avoid2377// padding in the file contents.2378//2379// When -z separate-code is used we must not have any overlap in pages2380// between an executable segment and a non-executable segment. We align to2381// the next maximum page size boundary on transitions between executable2382// and non-executable segments.2383//2384// SHT_LLVM_PART_EHDR marks the start of a partition. The partition2385// sections will be extracted to a separate file. Align to the next2386// maximum page size boundary so that we can find the ELF header at the2387// start. We cannot benefit from overlapping p_offset ranges with the2388// previous segment anyway.2389if (config->zSeparate == SeparateSegmentKind::Loadable ||2390(config->zSeparate == SeparateSegmentKind::Code && prev &&2391(prev->p_flags & PF_X) != (p->p_flags & PF_X)) ||2392cmd->type == SHT_LLVM_PART_EHDR)2393cmd->addrExpr = [] {2394return alignToPowerOf2(script->getDot(), config->maxPageSize);2395};2396// PT_TLS is at the start of the first RW PT_LOAD. If `p` includes PT_TLS,2397// it must be the RW. Align to p_align(PT_TLS) to make sure2398// p_vaddr(PT_LOAD)%p_align(PT_LOAD) = 0. Otherwise, if2399// sh_addralign(.tdata) < sh_addralign(.tbss), we will set p_align(PT_TLS)2400// to sh_addralign(.tbss), while p_vaddr(PT_TLS)=p_vaddr(PT_LOAD) may not2401// be congruent to 0 modulo p_align(PT_TLS).2402//2403// Technically this is not required, but as of 2019, some dynamic loaders2404// don't handle p_vaddr%p_align != 0 correctly, e.g. glibc (i386 and2405// x86-64) doesn't make runtime address congruent to p_vaddr modulo2406// p_align for dynamic TLS blocks (PR/24606), FreeBSD rtld has the same2407// bug, musl (TLS Variant 1 architectures) before 1.1.23 handled TLS2408// blocks correctly. We need to keep the workaround for a while.2409else if (Out::tlsPhdr && Out::tlsPhdr->firstSec == p->firstSec)2410cmd->addrExpr = [] {2411return alignToPowerOf2(script->getDot(), config->maxPageSize) +2412alignToPowerOf2(script->getDot() % config->maxPageSize,2413Out::tlsPhdr->p_align);2414};2415else2416cmd->addrExpr = [] {2417return alignToPowerOf2(script->getDot(), config->maxPageSize) +2418script->getDot() % config->maxPageSize;2419};2420}2421};24222423for (Partition &part : partitions) {2424prev = nullptr;2425for (const PhdrEntry *p : part.phdrs)2426if (p->p_type == PT_LOAD && p->firstSec) {2427pageAlign(p);2428prev = p;2429}2430}2431}24322433// Compute an in-file position for a given section. The file offset must be the2434// same with its virtual address modulo the page size, so that the loader can2435// load executables without any address adjustment.2436static uint64_t computeFileOffset(OutputSection *os, uint64_t off) {2437// The first section in a PT_LOAD has to have congruent offset and address2438// modulo the maximum page size.2439if (os->ptLoad && os->ptLoad->firstSec == os)2440return alignTo(off, os->ptLoad->p_align, os->addr);24412442// File offsets are not significant for .bss sections other than the first one2443// in a PT_LOAD/PT_TLS. By convention, we keep section offsets monotonically2444// increasing rather than setting to zero.2445if (os->type == SHT_NOBITS &&2446(!Out::tlsPhdr || Out::tlsPhdr->firstSec != os))2447return off;24482449// If the section is not in a PT_LOAD, we just have to align it.2450if (!os->ptLoad)2451return alignToPowerOf2(off, os->addralign);24522453// If two sections share the same PT_LOAD the file offset is calculated2454// using this formula: Off2 = Off1 + (VA2 - VA1).2455OutputSection *first = os->ptLoad->firstSec;2456return first->offset + os->addr - first->addr;2457}24582459template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {2460// Compute the minimum LMA of all non-empty non-NOBITS sections as minAddr.2461auto needsOffset = [](OutputSection &sec) {2462return sec.type != SHT_NOBITS && (sec.flags & SHF_ALLOC) && sec.size > 0;2463};2464uint64_t minAddr = UINT64_MAX;2465for (OutputSection *sec : outputSections)2466if (needsOffset(*sec)) {2467sec->offset = sec->getLMA();2468minAddr = std::min(minAddr, sec->offset);2469}24702471// Sections are laid out at LMA minus minAddr.2472fileSize = 0;2473for (OutputSection *sec : outputSections)2474if (needsOffset(*sec)) {2475sec->offset -= minAddr;2476fileSize = std::max(fileSize, sec->offset + sec->size);2477}2478}24792480static std::string rangeToString(uint64_t addr, uint64_t len) {2481return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";2482}24832484// Assign file offsets to output sections.2485template <class ELFT> void Writer<ELFT>::assignFileOffsets() {2486Out::programHeaders->offset = Out::elfHeader->size;2487uint64_t off = Out::elfHeader->size + Out::programHeaders->size;24882489PhdrEntry *lastRX = nullptr;2490for (Partition &part : partitions)2491for (PhdrEntry *p : part.phdrs)2492if (p->p_type == PT_LOAD && (p->p_flags & PF_X))2493lastRX = p;24942495// Layout SHF_ALLOC sections before non-SHF_ALLOC sections. A non-SHF_ALLOC2496// will not occupy file offsets contained by a PT_LOAD.2497for (OutputSection *sec : outputSections) {2498if (!(sec->flags & SHF_ALLOC))2499continue;2500off = computeFileOffset(sec, off);2501sec->offset = off;2502if (sec->type != SHT_NOBITS)2503off += sec->size;25042505// If this is a last section of the last executable segment and that2506// segment is the last loadable segment, align the offset of the2507// following section to avoid loading non-segments parts of the file.2508if (config->zSeparate != SeparateSegmentKind::None && lastRX &&2509lastRX->lastSec == sec)2510off = alignToPowerOf2(off, config->maxPageSize);2511}2512for (OutputSection *osec : outputSections) {2513if (osec->flags & SHF_ALLOC)2514continue;2515osec->offset = alignToPowerOf2(off, osec->addralign);2516off = osec->offset + osec->size;2517}25182519sectionHeaderOff = alignToPowerOf2(off, config->wordsize);2520fileSize = sectionHeaderOff + (outputSections.size() + 1) * sizeof(Elf_Shdr);25212522// Our logic assumes that sections have rising VA within the same segment.2523// With use of linker scripts it is possible to violate this rule and get file2524// offset overlaps or overflows. That should never happen with a valid script2525// which does not move the location counter backwards and usually scripts do2526// not do that. Unfortunately, there are apps in the wild, for example, Linux2527// kernel, which control segment distribution explicitly and move the counter2528// backwards, so we have to allow doing that to support linking them. We2529// perform non-critical checks for overlaps in checkSectionOverlap(), but here2530// we want to prevent file size overflows because it would crash the linker.2531for (OutputSection *sec : outputSections) {2532if (sec->type == SHT_NOBITS)2533continue;2534if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))2535error("unable to place section " + sec->name + " at file offset " +2536rangeToString(sec->offset, sec->size) +2537"; check your linker script for overflows");2538}2539}25402541// Finalize the program headers. We call this function after we assign2542// file offsets and VAs to all sections.2543template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {2544for (PhdrEntry *p : part.phdrs) {2545OutputSection *first = p->firstSec;2546OutputSection *last = p->lastSec;25472548// .ARM.exidx sections may not be within a single .ARM.exidx2549// output section. We always want to describe just the2550// SyntheticSection.2551if (part.armExidx && p->p_type == PT_ARM_EXIDX) {2552p->p_filesz = part.armExidx->getSize();2553p->p_memsz = part.armExidx->getSize();2554p->p_offset = first->offset + part.armExidx->outSecOff;2555p->p_vaddr = first->addr + part.armExidx->outSecOff;2556p->p_align = part.armExidx->addralign;2557if (part.elfHeader)2558p->p_offset -= part.elfHeader->getParent()->offset;25592560if (!p->hasLMA)2561p->p_paddr = first->getLMA() + part.armExidx->outSecOff;2562return;2563}25642565if (first) {2566p->p_filesz = last->offset - first->offset;2567if (last->type != SHT_NOBITS)2568p->p_filesz += last->size;25692570p->p_memsz = last->addr + last->size - first->addr;2571p->p_offset = first->offset;2572p->p_vaddr = first->addr;25732574// File offsets in partitions other than the main partition are relative2575// to the offset of the ELF headers. Perform that adjustment now.2576if (part.elfHeader)2577p->p_offset -= part.elfHeader->getParent()->offset;25782579if (!p->hasLMA)2580p->p_paddr = first->getLMA();2581}2582}2583}25842585// A helper struct for checkSectionOverlap.2586namespace {2587struct SectionOffset {2588OutputSection *sec;2589uint64_t offset;2590};2591} // namespace25922593// Check whether sections overlap for a specific address range (file offsets,2594// load and virtual addresses).2595static void checkOverlap(StringRef name, std::vector<SectionOffset> §ions,2596bool isVirtualAddr) {2597llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {2598return a.offset < b.offset;2599});26002601// Finding overlap is easy given a vector is sorted by start position.2602// If an element starts before the end of the previous element, they overlap.2603for (size_t i = 1, end = sections.size(); i < end; ++i) {2604SectionOffset a = sections[i - 1];2605SectionOffset b = sections[i];2606if (b.offset >= a.offset + a.sec->size)2607continue;26082609// If both sections are in OVERLAY we allow the overlapping of virtual2610// addresses, because it is what OVERLAY was designed for.2611if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)2612continue;26132614errorOrWarn("section " + a.sec->name + " " + name +2615" range overlaps with " + b.sec->name + "\n>>> " + a.sec->name +2616" range is " + rangeToString(a.offset, a.sec->size) + "\n>>> " +2617b.sec->name + " range is " +2618rangeToString(b.offset, b.sec->size));2619}2620}26212622// Check for overlapping sections and address overflows.2623//2624// In this function we check that none of the output sections have overlapping2625// file offsets. For SHF_ALLOC sections we also check that the load address2626// ranges and the virtual address ranges don't overlap2627template <class ELFT> void Writer<ELFT>::checkSections() {2628// First, check that section's VAs fit in available address space for target.2629for (OutputSection *os : outputSections)2630if ((os->addr + os->size < os->addr) ||2631(!ELFT::Is64Bits && os->addr + os->size > uint64_t(UINT32_MAX) + 1))2632errorOrWarn("section " + os->name + " at 0x" + utohexstr(os->addr) +2633" of size 0x" + utohexstr(os->size) +2634" exceeds available address space");26352636// Check for overlapping file offsets. In this case we need to skip any2637// section marked as SHT_NOBITS. These sections don't actually occupy space in2638// the file so Sec->Offset + Sec->Size can overlap with others. If --oformat2639// binary is specified only add SHF_ALLOC sections are added to the output2640// file so we skip any non-allocated sections in that case.2641std::vector<SectionOffset> fileOffs;2642for (OutputSection *sec : outputSections)2643if (sec->size > 0 && sec->type != SHT_NOBITS &&2644(!config->oFormatBinary || (sec->flags & SHF_ALLOC)))2645fileOffs.push_back({sec, sec->offset});2646checkOverlap("file", fileOffs, false);26472648// When linking with -r there is no need to check for overlapping virtual/load2649// addresses since those addresses will only be assigned when the final2650// executable/shared object is created.2651if (config->relocatable)2652return;26532654// Checking for overlapping virtual and load addresses only needs to take2655// into account SHF_ALLOC sections since others will not be loaded.2656// Furthermore, we also need to skip SHF_TLS sections since these will be2657// mapped to other addresses at runtime and can therefore have overlapping2658// ranges in the file.2659std::vector<SectionOffset> vmas;2660for (OutputSection *sec : outputSections)2661if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))2662vmas.push_back({sec, sec->addr});2663checkOverlap("virtual address", vmas, true);26642665// Finally, check that the load addresses don't overlap. This will usually be2666// the same as the virtual addresses but can be different when using a linker2667// script with AT().2668std::vector<SectionOffset> lmas;2669for (OutputSection *sec : outputSections)2670if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))2671lmas.push_back({sec, sec->getLMA()});2672checkOverlap("load address", lmas, false);2673}26742675// The entry point address is chosen in the following ways.2676//2677// 1. the '-e' entry command-line option;2678// 2. the ENTRY(symbol) command in a linker control script;2679// 3. the value of the symbol _start, if present;2680// 4. the number represented by the entry symbol, if it is a number;2681// 5. the address 0.2682static uint64_t getEntryAddr() {2683// Case 1, 2 or 32684if (Symbol *b = symtab.find(config->entry))2685return b->getVA();26862687// Case 42688uint64_t addr;2689if (to_integer(config->entry, addr))2690return addr;26912692// Case 52693if (config->warnMissingEntry)2694warn("cannot find entry symbol " + config->entry +2695"; not setting start address");2696return 0;2697}26982699static uint16_t getELFType() {2700if (config->isPic)2701return ET_DYN;2702if (config->relocatable)2703return ET_REL;2704return ET_EXEC;2705}27062707template <class ELFT> void Writer<ELFT>::writeHeader() {2708writeEhdr<ELFT>(Out::bufferStart, *mainPart);2709writePhdrs<ELFT>(Out::bufferStart + sizeof(Elf_Ehdr), *mainPart);27102711auto *eHdr = reinterpret_cast<Elf_Ehdr *>(Out::bufferStart);2712eHdr->e_type = getELFType();2713eHdr->e_entry = getEntryAddr();2714eHdr->e_shoff = sectionHeaderOff;27152716// Write the section header table.2717//2718// The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum2719// and e_shstrndx fields. When the value of one of these fields exceeds2720// SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and2721// use fields in the section header at index 0 to store2722// the value. The sentinel values and fields are:2723// e_shnum = 0, SHdrs[0].sh_size = number of sections.2724// e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.2725auto *sHdrs = reinterpret_cast<Elf_Shdr *>(Out::bufferStart + eHdr->e_shoff);2726size_t num = outputSections.size() + 1;2727if (num >= SHN_LORESERVE)2728sHdrs->sh_size = num;2729else2730eHdr->e_shnum = num;27312732uint32_t strTabIndex = in.shStrTab->getParent()->sectionIndex;2733if (strTabIndex >= SHN_LORESERVE) {2734sHdrs->sh_link = strTabIndex;2735eHdr->e_shstrndx = SHN_XINDEX;2736} else {2737eHdr->e_shstrndx = strTabIndex;2738}27392740for (OutputSection *sec : outputSections)2741sec->writeHeaderTo<ELFT>(++sHdrs);2742}27432744// Open a result file.2745template <class ELFT> void Writer<ELFT>::openFile() {2746uint64_t maxSize = config->is64 ? INT64_MAX : UINT32_MAX;2747if (fileSize != size_t(fileSize) || maxSize < fileSize) {2748std::string msg;2749raw_string_ostream s(msg);2750s << "output file too large: " << Twine(fileSize) << " bytes\n"2751<< "section sizes:\n";2752for (OutputSection *os : outputSections)2753s << os->name << ' ' << os->size << "\n";2754error(s.str());2755return;2756}27572758unlinkAsync(config->outputFile);2759unsigned flags = 0;2760if (!config->relocatable)2761flags |= FileOutputBuffer::F_executable;2762if (!config->mmapOutputFile)2763flags |= FileOutputBuffer::F_no_mmap;2764Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =2765FileOutputBuffer::create(config->outputFile, fileSize, flags);27662767if (!bufferOrErr) {2768error("failed to open " + config->outputFile + ": " +2769llvm::toString(bufferOrErr.takeError()));2770return;2771}2772buffer = std::move(*bufferOrErr);2773Out::bufferStart = buffer->getBufferStart();2774}27752776template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {2777parallel::TaskGroup tg;2778for (OutputSection *sec : outputSections)2779if (sec->flags & SHF_ALLOC)2780sec->writeTo<ELFT>(Out::bufferStart + sec->offset, tg);2781}27822783static void fillTrap(uint8_t *i, uint8_t *end) {2784for (; i + 4 <= end; i += 4)2785memcpy(i, &target->trapInstr, 4);2786}27872788// Fill the last page of executable segments with trap instructions2789// instead of leaving them as zero. Even though it is not required by any2790// standard, it is in general a good thing to do for security reasons.2791//2792// We'll leave other pages in segments as-is because the rest will be2793// overwritten by output sections.2794template <class ELFT> void Writer<ELFT>::writeTrapInstr() {2795for (Partition &part : partitions) {2796// Fill the last page.2797for (PhdrEntry *p : part.phdrs)2798if (p->p_type == PT_LOAD && (p->p_flags & PF_X))2799fillTrap(Out::bufferStart +2800alignDown(p->firstSec->offset + p->p_filesz, 4),2801Out::bufferStart +2802alignToPowerOf2(p->firstSec->offset + p->p_filesz,2803config->maxPageSize));28042805// Round up the file size of the last segment to the page boundary iff it is2806// an executable segment to ensure that other tools don't accidentally2807// trim the instruction padding (e.g. when stripping the file).2808PhdrEntry *last = nullptr;2809for (PhdrEntry *p : part.phdrs)2810if (p->p_type == PT_LOAD)2811last = p;28122813if (last && (last->p_flags & PF_X))2814last->p_memsz = last->p_filesz =2815alignToPowerOf2(last->p_filesz, config->maxPageSize);2816}2817}28182819// Write section contents to a mmap'ed file.2820template <class ELFT> void Writer<ELFT>::writeSections() {2821llvm::TimeTraceScope timeScope("Write sections");28222823{2824// In -r or --emit-relocs mode, write the relocation sections first as in2825// ELf_Rel targets we might find out that we need to modify the relocated2826// section while doing it.2827parallel::TaskGroup tg;2828for (OutputSection *sec : outputSections)2829if (isStaticRelSecType(sec->type))2830sec->writeTo<ELFT>(Out::bufferStart + sec->offset, tg);2831}2832{2833parallel::TaskGroup tg;2834for (OutputSection *sec : outputSections)2835if (!isStaticRelSecType(sec->type))2836sec->writeTo<ELFT>(Out::bufferStart + sec->offset, tg);2837}28382839// Finally, check that all dynamic relocation addends were written correctly.2840if (config->checkDynamicRelocs && config->writeAddends) {2841for (OutputSection *sec : outputSections)2842if (isStaticRelSecType(sec->type))2843sec->checkDynRelAddends(Out::bufferStart);2844}2845}28462847// Computes a hash value of Data using a given hash function.2848// In order to utilize multiple cores, we first split data into 1MB2849// chunks, compute a hash for each chunk, and then compute a hash value2850// of the hash values.2851static void2852computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,2853llvm::ArrayRef<uint8_t> data,2854std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {2855std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);2856const size_t hashesSize = chunks.size() * hashBuf.size();2857std::unique_ptr<uint8_t[]> hashes(new uint8_t[hashesSize]);28582859// Compute hash values.2860parallelFor(0, chunks.size(), [&](size_t i) {2861hashFn(hashes.get() + i * hashBuf.size(), chunks[i]);2862});28632864// Write to the final output buffer.2865hashFn(hashBuf.data(), ArrayRef(hashes.get(), hashesSize));2866}28672868template <class ELFT> void Writer<ELFT>::writeBuildId() {2869if (!mainPart->buildId || !mainPart->buildId->getParent())2870return;28712872if (config->buildId == BuildIdKind::Hexstring) {2873for (Partition &part : partitions)2874part.buildId->writeBuildId(config->buildIdVector);2875return;2876}28772878// Compute a hash of all sections of the output file.2879size_t hashSize = mainPart->buildId->hashSize;2880std::unique_ptr<uint8_t[]> buildId(new uint8_t[hashSize]);2881MutableArrayRef<uint8_t> output(buildId.get(), hashSize);2882llvm::ArrayRef<uint8_t> input{Out::bufferStart, size_t(fileSize)};28832884// Fedora introduced build ID as "approximation of true uniqueness across all2885// binaries that might be used by overlapping sets of people". It does not2886// need some security goals that some hash algorithms strive to provide, e.g.2887// (second-)preimage and collision resistance. In practice people use 'md5'2888// and 'sha1' just for different lengths. Implement them with the more2889// efficient BLAKE3.2890switch (config->buildId) {2891case BuildIdKind::Fast:2892computeHash(output, input, [](uint8_t *dest, ArrayRef<uint8_t> arr) {2893write64le(dest, xxh3_64bits(arr));2894});2895break;2896case BuildIdKind::Md5:2897computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {2898memcpy(dest, BLAKE3::hash<16>(arr).data(), hashSize);2899});2900break;2901case BuildIdKind::Sha1:2902computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {2903memcpy(dest, BLAKE3::hash<20>(arr).data(), hashSize);2904});2905break;2906case BuildIdKind::Uuid:2907if (auto ec = llvm::getRandomBytes(buildId.get(), hashSize))2908error("entropy source failure: " + ec.message());2909break;2910default:2911llvm_unreachable("unknown BuildIdKind");2912}2913for (Partition &part : partitions)2914part.buildId->writeBuildId(output);2915}29162917template void elf::writeResult<ELF32LE>();2918template void elf::writeResult<ELF32BE>();2919template void elf::writeResult<ELF64LE>();2920template void elf::writeResult<ELF64BE>();292129222923