Path: blob/main/contrib/llvm-project/lld/ELF/SyntheticSections.h
34870 views
//===- SyntheticSection.h ---------------------------------------*- C++ -*-===//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//===----------------------------------------------------------------------===//7//8// Synthetic sections represent chunks of linker-created data. If you9// need to create a chunk of data that to be included in some section10// in the result, you probably want to create that as a synthetic section.11//12// Synthetic sections are designed as input sections as opposed to13// output sections because we want to allow them to be manipulated14// using linker scripts just like other input sections from regular15// files.16//17//===----------------------------------------------------------------------===//1819#ifndef LLD_ELF_SYNTHETIC_SECTIONS_H20#define LLD_ELF_SYNTHETIC_SECTIONS_H2122#include "Config.h"23#include "DWARF.h"24#include "InputSection.h"25#include "Symbols.h"26#include "llvm/ADT/DenseSet.h"27#include "llvm/ADT/FoldingSet.h"28#include "llvm/ADT/MapVector.h"29#include "llvm/ADT/STLFunctionalExtras.h"30#include "llvm/BinaryFormat/ELF.h"31#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"32#include "llvm/MC/StringTableBuilder.h"33#include "llvm/Support/Allocator.h"34#include "llvm/Support/Compiler.h"35#include "llvm/Support/Endian.h"36#include "llvm/Support/Parallel.h"37#include "llvm/Support/Threading.h"3839namespace lld::elf {40class Defined;41struct PhdrEntry;42class SymbolTableBaseSection;4344struct CieRecord {45EhSectionPiece *cie = nullptr;46SmallVector<EhSectionPiece *, 0> fdes;47};4849// Section for .eh_frame.50class EhFrameSection final : public SyntheticSection {51public:52EhFrameSection();53void writeTo(uint8_t *buf) override;54void finalizeContents() override;55bool isNeeded() const override { return !sections.empty(); }56size_t getSize() const override { return size; }5758static bool classof(const SectionBase *d) {59return SyntheticSection::classof(d) && d->name == ".eh_frame";60}6162SmallVector<EhInputSection *, 0> sections;63size_t numFdes = 0;6465struct FdeData {66uint32_t pcRel;67uint32_t fdeVARel;68};6970SmallVector<FdeData, 0> getFdeData() const;71ArrayRef<CieRecord *> getCieRecords() const { return cieRecords; }72template <class ELFT>73void iterateFDEWithLSDA(llvm::function_ref<void(InputSection &)> fn);7475private:76// This is used only when parsing EhInputSection. We keep it here to avoid77// allocating one for each EhInputSection.78llvm::DenseMap<size_t, CieRecord *> offsetToCie;7980uint64_t size = 0;8182template <class ELFT, class RelTy>83void addRecords(EhInputSection *s, llvm::ArrayRef<RelTy> rels);84template <class ELFT> void addSectionAux(EhInputSection *s);85template <class ELFT, class RelTy>86void iterateFDEWithLSDAAux(EhInputSection &sec, ArrayRef<RelTy> rels,87llvm::DenseSet<size_t> &ciesWithLSDA,88llvm::function_ref<void(InputSection &)> fn);8990template <class ELFT, class RelTy>91CieRecord *addCie(EhSectionPiece &piece, ArrayRef<RelTy> rels);9293template <class ELFT, class RelTy>94Defined *isFdeLive(EhSectionPiece &piece, ArrayRef<RelTy> rels);9596uint64_t getFdePc(uint8_t *buf, size_t off, uint8_t enc) const;9798SmallVector<CieRecord *, 0> cieRecords;99100// CIE records are uniquified by their contents and personality functions.101llvm::DenseMap<std::pair<ArrayRef<uint8_t>, Symbol *>, CieRecord *> cieMap;102};103104class GotSection final : public SyntheticSection {105public:106GotSection();107size_t getSize() const override { return size; }108void finalizeContents() override;109bool isNeeded() const override;110void writeTo(uint8_t *buf) override;111112void addConstant(const Relocation &r);113void addEntry(const Symbol &sym);114bool addTlsDescEntry(const Symbol &sym);115bool addDynTlsEntry(const Symbol &sym);116bool addTlsIndex();117uint32_t getTlsDescOffset(const Symbol &sym) const;118uint64_t getTlsDescAddr(const Symbol &sym) const;119uint64_t getGlobalDynAddr(const Symbol &b) const;120uint64_t getGlobalDynOffset(const Symbol &b) const;121122uint64_t getTlsIndexVA() { return this->getVA() + tlsIndexOff; }123uint32_t getTlsIndexOff() const { return tlsIndexOff; }124125// Flag to force GOT to be in output if we have relocations126// that relies on its address.127std::atomic<bool> hasGotOffRel = false;128129protected:130size_t numEntries = 0;131uint32_t tlsIndexOff = -1;132uint64_t size = 0;133};134135// .note.GNU-stack section.136class GnuStackSection : public SyntheticSection {137public:138GnuStackSection()139: SyntheticSection(0, llvm::ELF::SHT_PROGBITS, 1, ".note.GNU-stack") {}140void writeTo(uint8_t *buf) override {}141size_t getSize() const override { return 0; }142};143144class GnuPropertySection final : public SyntheticSection {145public:146GnuPropertySection();147void writeTo(uint8_t *buf) override;148size_t getSize() const override;149};150151// .note.gnu.build-id section.152class BuildIdSection : public SyntheticSection {153// First 16 bytes are a header.154static const unsigned headerSize = 16;155156public:157const size_t hashSize;158BuildIdSection();159void writeTo(uint8_t *buf) override;160size_t getSize() const override { return headerSize + hashSize; }161void writeBuildId(llvm::ArrayRef<uint8_t> buf);162163private:164uint8_t *hashBuf;165};166167// BssSection is used to reserve space for copy relocations and common symbols.168// We create three instances of this class for .bss, .bss.rel.ro and "COMMON",169// that are used for writable symbols, read-only symbols and common symbols,170// respectively.171class BssSection final : public SyntheticSection {172public:173BssSection(StringRef name, uint64_t size, uint32_t addralign);174void writeTo(uint8_t *) override {}175bool isNeeded() const override { return size != 0; }176size_t getSize() const override { return size; }177178static bool classof(const SectionBase *s) { return s->bss; }179uint64_t size;180};181182class MipsGotSection final : public SyntheticSection {183public:184MipsGotSection();185void writeTo(uint8_t *buf) override;186size_t getSize() const override { return size; }187bool updateAllocSize() override;188void finalizeContents() override;189bool isNeeded() const override;190191// Join separate GOTs built for each input file to generate192// primary and optional multiple secondary GOTs.193void build();194195void addEntry(InputFile &file, Symbol &sym, int64_t addend, RelExpr expr);196void addDynTlsEntry(InputFile &file, Symbol &sym);197void addTlsIndex(InputFile &file);198199uint64_t getPageEntryOffset(const InputFile *f, const Symbol &s,200int64_t addend) const;201uint64_t getSymEntryOffset(const InputFile *f, const Symbol &s,202int64_t addend) const;203uint64_t getGlobalDynOffset(const InputFile *f, const Symbol &s) const;204uint64_t getTlsIndexOffset(const InputFile *f) const;205206// Returns the symbol which corresponds to the first entry of the global part207// of GOT on MIPS platform. It is required to fill up MIPS-specific dynamic208// table properties.209// Returns nullptr if the global part is empty.210const Symbol *getFirstGlobalEntry() const;211212// Returns the number of entries in the local part of GOT including213// the number of reserved entries.214unsigned getLocalEntriesNum() const;215216// Return _gp value for primary GOT (nullptr) or particular input file.217uint64_t getGp(const InputFile *f = nullptr) const;218219private:220// MIPS GOT consists of three parts: local, global and tls. Each part221// contains different types of entries. Here is a layout of GOT:222// - Header entries |223// - Page entries | Local part224// - Local entries (16-bit access) |225// - Local entries (32-bit access) |226// - Normal global entries || Global part227// - Reloc-only global entries ||228// - TLS entries ||| TLS part229//230// Header:231// Two entries hold predefined value 0x0 and 0x80000000.232// Page entries:233// These entries created by R_MIPS_GOT_PAGE relocation and R_MIPS_GOT16234// relocation against local symbols. They are initialized by higher 16-bit235// of the corresponding symbol's value. So each 64kb of address space236// requires a single GOT entry.237// Local entries (16-bit access):238// These entries created by GOT relocations against global non-preemptible239// symbols so dynamic linker is not necessary to resolve the symbol's240// values. "16-bit access" means that corresponding relocations address241// GOT using 16-bit index. Each unique Symbol-Addend pair has its own242// GOT entry.243// Local entries (32-bit access):244// These entries are the same as above but created by relocations which245// address GOT using 32-bit index (R_MIPS_GOT_HI16/LO16 etc).246// Normal global entries:247// These entries created by GOT relocations against preemptible global248// symbols. They need to be initialized by dynamic linker and they ordered249// exactly as the corresponding entries in the dynamic symbols table.250// Reloc-only global entries:251// These entries created for symbols that are referenced by dynamic252// relocations R_MIPS_REL32. These entries are not accessed with gp-relative253// addressing, but MIPS ABI requires that these entries be present in GOT.254// TLS entries:255// Entries created by TLS relocations.256//257// If the sum of local, global and tls entries is less than 64K only single258// got is enough. Otherwise, multi-got is created. Series of primary and259// multiple secondary GOTs have the following layout:260// - Primary GOT261// Header262// Local entries263// Global entries264// Relocation only entries265// TLS entries266//267// - Secondary GOT268// Local entries269// Global entries270// TLS entries271// ...272//273// All GOT entries required by relocations from a single input file entirely274// belong to either primary or one of secondary GOTs. To reference GOT entries275// each GOT has its own _gp value points to the "middle" of the GOT.276// In the code this value loaded to the register which is used for GOT access.277//278// MIPS 32 function's prologue:279// lui v0,0x0280// 0: R_MIPS_HI16 _gp_disp281// addiu v0,v0,0282// 4: R_MIPS_LO16 _gp_disp283//284// MIPS 64:285// lui at,0x0286// 14: R_MIPS_GPREL16 main287//288// Dynamic linker does not know anything about secondary GOTs and cannot289// use a regular MIPS mechanism for GOT entries initialization. So we have290// to use an approach accepted by other architectures and create dynamic291// relocations R_MIPS_REL32 to initialize global entries (and local in case292// of PIC code) in secondary GOTs. But ironically MIPS dynamic linker293// requires GOT entries and correspondingly ordered dynamic symbol table294// entries to deal with dynamic relocations. To handle this problem295// relocation-only section in the primary GOT contains entries for all296// symbols referenced in global parts of secondary GOTs. Although the sum297// of local and normal global entries of the primary got should be less298// than 64K, the size of the primary got (including relocation-only entries299// can be greater than 64K, because parts of the primary got that overflow300// the 64K limit are used only by the dynamic linker at dynamic link-time301// and not by 16-bit gp-relative addressing at run-time.302//303// For complete multi-GOT description see the following link304// https://dmz-portal.mips.com/wiki/MIPS_Multi_GOT305306// Number of "Header" entries.307static const unsigned headerEntriesNum = 2;308309uint64_t size = 0;310311// Symbol and addend.312using GotEntry = std::pair<Symbol *, int64_t>;313314struct FileGot {315InputFile *file = nullptr;316size_t startIndex = 0;317318struct PageBlock {319size_t firstIndex;320size_t count;321PageBlock() : firstIndex(0), count(0) {}322};323324// Map output sections referenced by MIPS GOT relocations325// to the description (index/count) "page" entries allocated326// for this section.327llvm::SmallMapVector<const OutputSection *, PageBlock, 16> pagesMap;328// Maps from Symbol+Addend pair or just Symbol to the GOT entry index.329llvm::MapVector<GotEntry, size_t> local16;330llvm::MapVector<GotEntry, size_t> local32;331llvm::MapVector<Symbol *, size_t> global;332llvm::MapVector<Symbol *, size_t> relocs;333llvm::MapVector<Symbol *, size_t> tls;334// Set of symbols referenced by dynamic TLS relocations.335llvm::MapVector<Symbol *, size_t> dynTlsSymbols;336337// Total number of all entries.338size_t getEntriesNum() const;339// Number of "page" entries.340size_t getPageEntriesNum() const;341// Number of entries require 16-bit index to access.342size_t getIndexedEntriesNum() const;343};344345// Container of GOT created for each input file.346// After building a final series of GOTs this container347// holds primary and secondary GOT's.348std::vector<FileGot> gots;349350// Return (and create if necessary) `FileGot`.351FileGot &getGot(InputFile &f);352353// Try to merge two GOTs. In case of success the `Dst` contains354// result of merging and the function returns true. In case of355// overflow the `Dst` is unchanged and the function returns false.356bool tryMergeGots(FileGot & dst, FileGot & src, bool isPrimary);357};358359class GotPltSection final : public SyntheticSection {360public:361GotPltSection();362void addEntry(Symbol &sym);363size_t getSize() const override;364void writeTo(uint8_t *buf) override;365bool isNeeded() const override;366367// Flag to force GotPlt to be in output if we have relocations368// that relies on its address.369std::atomic<bool> hasGotPltOffRel = false;370371private:372SmallVector<const Symbol *, 0> entries;373};374375// The IgotPltSection is a Got associated with the PltSection for GNU Ifunc376// Symbols that will be relocated by Target->IRelativeRel.377// On most Targets the IgotPltSection will immediately follow the GotPltSection378// on ARM the IgotPltSection will immediately follow the GotSection.379class IgotPltSection final : public SyntheticSection {380public:381IgotPltSection();382void addEntry(Symbol &sym);383size_t getSize() const override;384void writeTo(uint8_t *buf) override;385bool isNeeded() const override { return !entries.empty(); }386387private:388SmallVector<const Symbol *, 0> entries;389};390391class StringTableSection final : public SyntheticSection {392public:393StringTableSection(StringRef name, bool dynamic);394unsigned addString(StringRef s, bool hashIt = true);395void writeTo(uint8_t *buf) override;396size_t getSize() const override { return size; }397bool isDynamic() const { return dynamic; }398399private:400const bool dynamic;401402uint64_t size = 0;403404llvm::DenseMap<llvm::CachedHashStringRef, unsigned> stringMap;405SmallVector<StringRef, 0> strings;406};407408class DynamicReloc {409public:410enum Kind {411/// The resulting dynamic relocation does not reference a symbol (#sym must412/// be nullptr) and uses #addend as the result of computeAddend().413AddendOnly,414/// The resulting dynamic relocation will not reference a symbol: #sym is415/// only used to compute the addend with InputSection::getRelocTargetVA().416/// Useful for various relative and TLS relocations (e.g. R_X86_64_TPOFF64).417AddendOnlyWithTargetVA,418/// The resulting dynamic relocation references symbol #sym from the dynamic419/// symbol table and uses #addend as the value of computeAddend().420AgainstSymbol,421/// The resulting dynamic relocation references symbol #sym from the dynamic422/// symbol table and uses InputSection::getRelocTargetVA() + #addend for the423/// final addend. It can be used for relocations that write the symbol VA as424// the addend (e.g. R_MIPS_TLS_TPREL64) but still reference the symbol.425AgainstSymbolWithTargetVA,426/// This is used by the MIPS multi-GOT implementation. It relocates427/// addresses of 64kb pages that lie inside the output section.428MipsMultiGotPage,429};430/// This constructor records a relocation against a symbol.431DynamicReloc(RelType type, const InputSectionBase *inputSec,432uint64_t offsetInSec, Kind kind, Symbol &sym, int64_t addend,433RelExpr expr)434: sym(&sym), inputSec(inputSec), offsetInSec(offsetInSec), type(type),435addend(addend), kind(kind), expr(expr) {}436/// This constructor records a relative relocation with no symbol.437DynamicReloc(RelType type, const InputSectionBase *inputSec,438uint64_t offsetInSec, int64_t addend = 0)439: sym(nullptr), inputSec(inputSec), offsetInSec(offsetInSec), type(type),440addend(addend), kind(AddendOnly), expr(R_ADDEND) {}441/// This constructor records dynamic relocation settings used by the MIPS442/// multi-GOT implementation.443DynamicReloc(RelType type, const InputSectionBase *inputSec,444uint64_t offsetInSec, const OutputSection *outputSec,445int64_t addend)446: sym(nullptr), outputSec(outputSec), inputSec(inputSec),447offsetInSec(offsetInSec), type(type), addend(addend),448kind(MipsMultiGotPage), expr(R_ADDEND) {}449450uint64_t getOffset() const;451uint32_t getSymIndex(SymbolTableBaseSection *symTab) const;452bool needsDynSymIndex() const {453return kind == AgainstSymbol || kind == AgainstSymbolWithTargetVA;454}455456/// Computes the addend of the dynamic relocation. Note that this is not the457/// same as the #addend member variable as it may also include the symbol458/// address/the address of the corresponding GOT entry/etc.459int64_t computeAddend() const;460461void computeRaw(SymbolTableBaseSection *symtab);462463Symbol *sym;464const OutputSection *outputSec = nullptr;465const InputSectionBase *inputSec;466uint64_t offsetInSec;467uint64_t r_offset;468RelType type;469uint32_t r_sym;470// Initially input addend, then the output addend after471// RelocationSection<ELFT>::writeTo.472int64_t addend;473474private:475Kind kind;476// The kind of expression used to calculate the added (required e.g. for477// relative GOT relocations).478RelExpr expr;479};480481template <class ELFT> class DynamicSection final : public SyntheticSection {482LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)483484public:485DynamicSection();486void finalizeContents() override;487void writeTo(uint8_t *buf) override;488size_t getSize() const override { return size; }489490private:491std::vector<std::pair<int32_t, uint64_t>> computeContents();492uint64_t size = 0;493};494495class RelocationBaseSection : public SyntheticSection {496public:497RelocationBaseSection(StringRef name, uint32_t type, int32_t dynamicTag,498int32_t sizeDynamicTag, bool combreloc,499unsigned concurrency);500/// Add a dynamic relocation without writing an addend to the output section.501/// This overload can be used if the addends are written directly instead of502/// using relocations on the input section (e.g. MipsGotSection::writeTo()).503template <bool shard = false> void addReloc(const DynamicReloc &reloc) {504relocs.push_back(reloc);505}506/// Add a dynamic relocation against \p sym with an optional addend.507void addSymbolReloc(RelType dynType, InputSectionBase &isec,508uint64_t offsetInSec, Symbol &sym, int64_t addend = 0,509std::optional<RelType> addendRelType = {});510/// Add a relative dynamic relocation that uses the target address of \p sym511/// (i.e. InputSection::getRelocTargetVA()) + \p addend as the addend.512/// This function should only be called for non-preemptible symbols or513/// RelExpr values that refer to an address inside the output file (e.g. the514/// address of the GOT entry for a potentially preemptible symbol).515template <bool shard = false>516void addRelativeReloc(RelType dynType, InputSectionBase &isec,517uint64_t offsetInSec, Symbol &sym, int64_t addend,518RelType addendRelType, RelExpr expr) {519assert(expr != R_ADDEND && "expected non-addend relocation expression");520addReloc<shard>(DynamicReloc::AddendOnlyWithTargetVA, dynType, isec,521offsetInSec, sym, addend, expr, addendRelType);522}523/// Add a dynamic relocation using the target address of \p sym as the addend524/// if \p sym is non-preemptible. Otherwise add a relocation against \p sym.525void addAddendOnlyRelocIfNonPreemptible(RelType dynType, GotSection &sec,526uint64_t offsetInSec, Symbol &sym,527RelType addendRelType);528template <bool shard = false>529void addReloc(DynamicReloc::Kind kind, RelType dynType, InputSectionBase &sec,530uint64_t offsetInSec, Symbol &sym, int64_t addend, RelExpr expr,531RelType addendRelType) {532// Write the addends to the relocated address if required. We skip533// it if the written value would be zero.534if (config->writeAddends && (expr != R_ADDEND || addend != 0))535sec.addReloc({expr, addendRelType, offsetInSec, addend, &sym});536addReloc<shard>({dynType, &sec, offsetInSec, kind, sym, addend, expr});537}538bool isNeeded() const override {539return !relocs.empty() ||540llvm::any_of(relocsVec, [](auto &v) { return !v.empty(); });541}542size_t getSize() const override { return relocs.size() * this->entsize; }543size_t getRelativeRelocCount() const { return numRelativeRelocs; }544void mergeRels();545void partitionRels();546void finalizeContents() override;547static bool classof(const SectionBase *d) {548return SyntheticSection::classof(d) &&549(d->type == llvm::ELF::SHT_RELA || d->type == llvm::ELF::SHT_REL ||550d->type == llvm::ELF::SHT_RELR ||551(d->type == llvm::ELF::SHT_AARCH64_AUTH_RELR &&552config->emachine == llvm::ELF::EM_AARCH64));553}554int32_t dynamicTag, sizeDynamicTag;555SmallVector<DynamicReloc, 0> relocs;556557protected:558void computeRels();559// Used when parallel relocation scanning adds relocations. The elements560// will be moved into relocs by mergeRel().561SmallVector<SmallVector<DynamicReloc, 0>, 0> relocsVec;562size_t numRelativeRelocs = 0; // used by -z combreloc563bool combreloc;564};565566template <>567inline void RelocationBaseSection::addReloc<true>(const DynamicReloc &reloc) {568relocsVec[llvm::parallel::getThreadIndex()].push_back(reloc);569}570571template <class ELFT>572class RelocationSection final : public RelocationBaseSection {573using Elf_Rel = typename ELFT::Rel;574using Elf_Rela = typename ELFT::Rela;575576public:577RelocationSection(StringRef name, bool combreloc, unsigned concurrency);578void writeTo(uint8_t *buf) override;579};580581template <class ELFT>582class AndroidPackedRelocationSection final : public RelocationBaseSection {583using Elf_Rel = typename ELFT::Rel;584using Elf_Rela = typename ELFT::Rela;585586public:587AndroidPackedRelocationSection(StringRef name, unsigned concurrency);588589bool updateAllocSize() override;590size_t getSize() const override { return relocData.size(); }591void writeTo(uint8_t *buf) override {592memcpy(buf, relocData.data(), relocData.size());593}594595private:596SmallVector<char, 0> relocData;597};598599struct RelativeReloc {600uint64_t getOffset() const {601return inputSec->getVA(inputSec->relocs()[relocIdx].offset);602}603604const InputSectionBase *inputSec;605size_t relocIdx;606};607608class RelrBaseSection : public SyntheticSection {609public:610RelrBaseSection(unsigned concurrency, bool isAArch64Auth = false);611void mergeRels();612bool isNeeded() const override {613return !relocs.empty() ||614llvm::any_of(relocsVec, [](auto &v) { return !v.empty(); });615}616SmallVector<RelativeReloc, 0> relocs;617SmallVector<SmallVector<RelativeReloc, 0>, 0> relocsVec;618};619620// RelrSection is used to encode offsets for relative relocations.621// Proposal for adding SHT_RELR sections to generic-abi is here:622// https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg623// For more details, see the comment in RelrSection::updateAllocSize().624template <class ELFT> class RelrSection final : public RelrBaseSection {625using Elf_Relr = typename ELFT::Relr;626627public:628RelrSection(unsigned concurrency, bool isAArch64Auth = false);629630bool updateAllocSize() override;631size_t getSize() const override { return relrRelocs.size() * this->entsize; }632void writeTo(uint8_t *buf) override {633memcpy(buf, relrRelocs.data(), getSize());634}635636private:637SmallVector<Elf_Relr, 0> relrRelocs;638};639640struct SymbolTableEntry {641Symbol *sym;642size_t strTabOffset;643};644645class SymbolTableBaseSection : public SyntheticSection {646public:647SymbolTableBaseSection(StringTableSection &strTabSec);648void finalizeContents() override;649size_t getSize() const override { return getNumSymbols() * entsize; }650void addSymbol(Symbol *sym);651unsigned getNumSymbols() const { return symbols.size() + 1; }652size_t getSymbolIndex(const Symbol &sym);653ArrayRef<SymbolTableEntry> getSymbols() const { return symbols; }654655protected:656void sortSymTabSymbols();657658// A vector of symbols and their string table offsets.659SmallVector<SymbolTableEntry, 0> symbols;660661StringTableSection &strTabSec;662663llvm::once_flag onceFlag;664llvm::DenseMap<Symbol *, size_t> symbolIndexMap;665llvm::DenseMap<OutputSection *, size_t> sectionIndexMap;666};667668template <class ELFT>669class SymbolTableSection final : public SymbolTableBaseSection {670using Elf_Sym = typename ELFT::Sym;671672public:673SymbolTableSection(StringTableSection &strTabSec);674void writeTo(uint8_t *buf) override;675};676677class SymtabShndxSection final : public SyntheticSection {678public:679SymtabShndxSection();680681void writeTo(uint8_t *buf) override;682size_t getSize() const override;683bool isNeeded() const override;684void finalizeContents() override;685};686687// Outputs GNU Hash section. For detailed explanation see:688// https://blogs.oracle.com/ali/entry/gnu_hash_elf_sections689class GnuHashTableSection final : public SyntheticSection {690public:691GnuHashTableSection();692void finalizeContents() override;693void writeTo(uint8_t *buf) override;694size_t getSize() const override { return size; }695696// Adds symbols to the hash table.697// Sorts the input to satisfy GNU hash section requirements.698void addSymbols(llvm::SmallVectorImpl<SymbolTableEntry> &symbols);699700private:701// See the comment in writeBloomFilter.702enum { Shift2 = 26 };703704struct Entry {705Symbol *sym;706size_t strTabOffset;707uint32_t hash;708uint32_t bucketIdx;709};710711SmallVector<Entry, 0> symbols;712size_t maskWords;713size_t nBuckets = 0;714size_t size = 0;715};716717class HashTableSection final : public SyntheticSection {718public:719HashTableSection();720void finalizeContents() override;721void writeTo(uint8_t *buf) override;722size_t getSize() const override { return size; }723724private:725size_t size = 0;726};727728// Used for PLT entries. It usually has a PLT header for lazy binding. Each PLT729// entry is associated with a JUMP_SLOT relocation, which may be resolved lazily730// at runtime.731//732// On PowerPC, this section contains lazy symbol resolvers. A branch instruction733// jumps to a PLT call stub, which will then jump to the target (BIND_NOW) or a734// lazy symbol resolver.735//736// On x86 when IBT is enabled, this section (.plt.sec) contains PLT call stubs.737// A call instruction jumps to a .plt.sec entry, which will then jump to the738// target (BIND_NOW) or a .plt entry.739class PltSection : public SyntheticSection {740public:741PltSection();742void writeTo(uint8_t *buf) override;743size_t getSize() const override;744bool isNeeded() const override;745void addSymbols();746void addEntry(Symbol &sym);747size_t getNumEntries() const { return entries.size(); }748749size_t headerSize;750751SmallVector<const Symbol *, 0> entries;752};753754// Used for non-preemptible ifuncs. It does not have a header. Each entry is755// associated with an IRELATIVE relocation, which will be resolved eagerly at756// runtime. PltSection can only contain entries associated with JUMP_SLOT757// relocations, so IPLT entries are in a separate section.758class IpltSection final : public SyntheticSection {759SmallVector<const Symbol *, 0> entries;760761public:762IpltSection();763void writeTo(uint8_t *buf) override;764size_t getSize() const override;765bool isNeeded() const override { return !entries.empty(); }766void addSymbols();767void addEntry(Symbol &sym);768};769770class PPC32GlinkSection : public PltSection {771public:772PPC32GlinkSection();773void writeTo(uint8_t *buf) override;774size_t getSize() const override;775776SmallVector<const Symbol *, 0> canonical_plts;777static constexpr size_t footerSize = 64;778};779780// This is x86-only.781class IBTPltSection : public SyntheticSection {782public:783IBTPltSection();784void writeTo(uint8_t *Buf) override;785bool isNeeded() const override;786size_t getSize() const override;787};788789// Used to align the end of the PT_GNU_RELRO segment and the associated PT_LOAD790// segment to a common-page-size boundary. This padding section ensures that all791// pages in the PT_LOAD segment is covered by at least one section.792class RelroPaddingSection final : public SyntheticSection {793public:794RelroPaddingSection();795size_t getSize() const override { return 0; }796void writeTo(uint8_t *buf) override {}797};798799// Used by the merged DWARF32 .debug_names (a per-module index). If we800// move to DWARF64, most of this data will need to be re-sized.801class DebugNamesBaseSection : public SyntheticSection {802public:803struct Abbrev : llvm::FoldingSetNode {804uint32_t code;805uint32_t tag;806SmallVector<llvm::DWARFDebugNames::AttributeEncoding, 2> attributes;807808void Profile(llvm::FoldingSetNodeID &id) const;809};810811struct AttrValue {812uint32_t attrValue;813uint8_t attrSize;814};815816struct IndexEntry {817uint32_t abbrevCode;818uint32_t poolOffset;819union {820uint64_t parentOffset = 0;821IndexEntry *parentEntry;822};823SmallVector<AttrValue, 3> attrValues;824};825826struct NameEntry {827const char *name;828uint32_t hashValue;829uint32_t stringOffset;830uint32_t entryOffset;831// Used to relocate `stringOffset` in the merged section.832uint32_t chunkIdx;833SmallVector<IndexEntry *, 0> indexEntries;834835llvm::iterator_range<836llvm::pointee_iterator<typename SmallVector<IndexEntry *, 0>::iterator>>837entries() {838return llvm::make_pointee_range(indexEntries);839}840};841842// The contents of one input .debug_names section. An InputChunk843// typically contains one NameData, but might contain more, especially844// in LTO builds.845struct NameData {846llvm::DWARFDebugNames::Header hdr;847llvm::DenseMap<uint32_t, uint32_t> abbrevCodeMap;848SmallVector<NameEntry, 0> nameEntries;849};850851// InputChunk and OutputChunk hold per-file contributions to the merged index.852// InputChunk instances will be discarded after `init` completes.853struct InputChunk {854uint32_t baseCuIdx;855LLDDWARFSection section;856SmallVector<NameData, 0> nameData;857std::optional<llvm::DWARFDebugNames> llvmDebugNames;858};859860struct OutputChunk {861// Pointer to the .debug_info section that contains compile units, used to862// compute the relocated CU offsets.863InputSection *infoSec;864// This initially holds section offsets. After relocation, the section865// offsets are changed to CU offsets relative the the output section.866SmallVector<uint32_t, 0> compUnits;867};868869DebugNamesBaseSection();870size_t getSize() const override { return size; }871bool isNeeded() const override { return numChunks > 0; }872873protected:874void init(llvm::function_ref<void(InputFile *, InputChunk &, OutputChunk &)>);875static void876parseDebugNames(InputChunk &inputChunk, OutputChunk &chunk,877llvm::DWARFDataExtractor &namesExtractor,878llvm::DataExtractor &strExtractor,879llvm::function_ref<SmallVector<uint32_t, 0>(880uint32_t numCUs, const llvm::DWARFDebugNames::Header &hdr,881const llvm::DWARFDebugNames::DWARFDebugNamesOffsets &)>882readOffsets);883void computeHdrAndAbbrevTable(MutableArrayRef<InputChunk> inputChunks);884std::pair<uint32_t, uint32_t>885computeEntryPool(MutableArrayRef<InputChunk> inputChunks);886887// Input .debug_names sections for relocating string offsets in the name table888// in `finalizeContents`.889SmallVector<InputSection *, 0> inputSections;890891llvm::DWARFDebugNames::Header hdr;892size_t numChunks;893std::unique_ptr<OutputChunk[]> chunks;894llvm::SpecificBumpPtrAllocator<Abbrev> abbrevAlloc;895SmallVector<Abbrev *, 0> abbrevTable;896SmallVector<char, 0> abbrevTableBuf;897898ArrayRef<OutputChunk> getChunks() const {899return ArrayRef(chunks.get(), numChunks);900}901902// Sharded name entries that will be used to compute bucket_count and the903// count name table.904static constexpr size_t numShards = 32;905SmallVector<NameEntry, 0> nameVecs[numShards];906};907908// Complement DebugNamesBaseSection for ELFT-aware code: reading offsets,909// relocating string offsets, and writeTo.910template <class ELFT>911class DebugNamesSection final : public DebugNamesBaseSection {912public:913DebugNamesSection();914void finalizeContents() override;915void writeTo(uint8_t *buf) override;916917template <class RelTy>918void getNameRelocs(const InputFile &file,919llvm::DenseMap<uint32_t, uint32_t> &relocs,920Relocs<RelTy> rels);921922private:923static void readOffsets(InputChunk &inputChunk, OutputChunk &chunk,924llvm::DWARFDataExtractor &namesExtractor,925llvm::DataExtractor &strExtractor);926};927928class GdbIndexSection final : public SyntheticSection {929public:930struct AddressEntry {931InputSection *section;932uint64_t lowAddress;933uint64_t highAddress;934uint32_t cuIndex;935};936937struct CuEntry {938uint64_t cuOffset;939uint64_t cuLength;940};941942struct NameAttrEntry {943llvm::CachedHashStringRef name;944uint32_t cuIndexAndAttrs;945};946947struct GdbChunk {948InputSection *sec;949SmallVector<AddressEntry, 0> addressAreas;950SmallVector<CuEntry, 0> compilationUnits;951};952953struct GdbSymbol {954llvm::CachedHashStringRef name;955SmallVector<uint32_t, 0> cuVector;956uint32_t nameOff;957uint32_t cuVectorOff;958};959960GdbIndexSection();961template <typename ELFT> static std::unique_ptr<GdbIndexSection> create();962void writeTo(uint8_t *buf) override;963size_t getSize() const override { return size; }964bool isNeeded() const override;965966private:967struct GdbIndexHeader {968llvm::support::ulittle32_t version;969llvm::support::ulittle32_t cuListOff;970llvm::support::ulittle32_t cuTypesOff;971llvm::support::ulittle32_t addressAreaOff;972llvm::support::ulittle32_t symtabOff;973llvm::support::ulittle32_t constantPoolOff;974};975976size_t computeSymtabSize() const;977978// Each chunk contains information gathered from debug sections of a979// single object file.980SmallVector<GdbChunk, 0> chunks;981982// A symbol table for this .gdb_index section.983SmallVector<GdbSymbol, 0> symbols;984985size_t size;986};987988// --eh-frame-hdr option tells linker to construct a header for all the989// .eh_frame sections. This header is placed to a section named .eh_frame_hdr990// and also to a PT_GNU_EH_FRAME segment.991// At runtime the unwinder then can find all the PT_GNU_EH_FRAME segments by992// calling dl_iterate_phdr.993// This section contains a lookup table for quick binary search of FDEs.994// Detailed info about internals can be found in Ian Lance Taylor's blog:995// http://www.airs.com/blog/archives/460 (".eh_frame")996// http://www.airs.com/blog/archives/462 (".eh_frame_hdr")997class EhFrameHeader final : public SyntheticSection {998public:999EhFrameHeader();1000void write();1001void writeTo(uint8_t *buf) override;1002size_t getSize() const override;1003bool isNeeded() const override;1004};10051006// For more information about .gnu.version and .gnu.version_r see:1007// https://www.akkadia.org/drepper/symbol-versioning10081009// The .gnu.version_d section which has a section type of SHT_GNU_verdef shall1010// contain symbol version definitions. The number of entries in this section1011// shall be contained in the DT_VERDEFNUM entry of the .dynamic section.1012// The section shall contain an array of Elf_Verdef structures, optionally1013// followed by an array of Elf_Verdaux structures.1014class VersionDefinitionSection final : public SyntheticSection {1015public:1016VersionDefinitionSection();1017void finalizeContents() override;1018size_t getSize() const override;1019void writeTo(uint8_t *buf) override;10201021private:1022enum { EntrySize = 28 };1023void writeOne(uint8_t *buf, uint32_t index, StringRef name, size_t nameOff);1024StringRef getFileDefName();10251026unsigned fileDefNameOff;1027SmallVector<unsigned, 0> verDefNameOffs;1028};10291030// The .gnu.version section specifies the required version of each symbol in the1031// dynamic symbol table. It contains one Elf_Versym for each dynamic symbol1032// table entry. An Elf_Versym is just a 16-bit integer that refers to a version1033// identifier defined in the either .gnu.version_r or .gnu.version_d section.1034// The values 0 and 1 are reserved. All other values are used for versions in1035// the own object or in any of the dependencies.1036class VersionTableSection final : public SyntheticSection {1037public:1038VersionTableSection();1039void finalizeContents() override;1040size_t getSize() const override;1041void writeTo(uint8_t *buf) override;1042bool isNeeded() const override;1043};10441045// The .gnu.version_r section defines the version identifiers used by1046// .gnu.version. It contains a linked list of Elf_Verneed data structures. Each1047// Elf_Verneed specifies the version requirements for a single DSO, and contains1048// a reference to a linked list of Elf_Vernaux data structures which define the1049// mapping from version identifiers to version names.1050template <class ELFT>1051class VersionNeedSection final : public SyntheticSection {1052using Elf_Verneed = typename ELFT::Verneed;1053using Elf_Vernaux = typename ELFT::Vernaux;10541055struct Vernaux {1056uint64_t hash;1057uint32_t verneedIndex;1058uint64_t nameStrTab;1059};10601061struct Verneed {1062uint64_t nameStrTab;1063std::vector<Vernaux> vernauxs;1064};10651066SmallVector<Verneed, 0> verneeds;10671068public:1069VersionNeedSection();1070void finalizeContents() override;1071void writeTo(uint8_t *buf) override;1072size_t getSize() const override;1073bool isNeeded() const override;1074};10751076// MergeSyntheticSection is a class that allows us to put mergeable sections1077// with different attributes in a single output sections. To do that1078// we put them into MergeSyntheticSection synthetic input sections which are1079// attached to regular output sections.1080class MergeSyntheticSection : public SyntheticSection {1081public:1082void addSection(MergeInputSection *ms);1083SmallVector<MergeInputSection *, 0> sections;10841085protected:1086MergeSyntheticSection(StringRef name, uint32_t type, uint64_t flags,1087uint32_t addralign)1088: SyntheticSection(flags, type, addralign, name) {}1089};10901091class MergeTailSection final : public MergeSyntheticSection {1092public:1093MergeTailSection(StringRef name, uint32_t type, uint64_t flags,1094uint32_t addralign);10951096size_t getSize() const override;1097void writeTo(uint8_t *buf) override;1098void finalizeContents() override;10991100private:1101llvm::StringTableBuilder builder;1102};11031104class MergeNoTailSection final : public MergeSyntheticSection {1105public:1106MergeNoTailSection(StringRef name, uint32_t type, uint64_t flags,1107uint32_t addralign)1108: MergeSyntheticSection(name, type, flags, addralign) {}11091110size_t getSize() const override { return size; }1111void writeTo(uint8_t *buf) override;1112void finalizeContents() override;11131114private:1115// We use the most significant bits of a hash as a shard ID.1116// The reason why we don't want to use the least significant bits is1117// because DenseMap also uses lower bits to determine a bucket ID.1118// If we use lower bits, it significantly increases the probability of1119// hash collisions.1120size_t getShardId(uint32_t hash) {1121assert((hash >> 31) == 0);1122return hash >> (31 - llvm::countr_zero(numShards));1123}11241125// Section size1126size_t size;11271128// String table contents1129constexpr static size_t numShards = 32;1130SmallVector<llvm::StringTableBuilder, 0> shards;1131size_t shardOffsets[numShards];1132};11331134// .MIPS.abiflags section.1135template <class ELFT>1136class MipsAbiFlagsSection final : public SyntheticSection {1137using Elf_Mips_ABIFlags = llvm::object::Elf_Mips_ABIFlags<ELFT>;11381139public:1140static std::unique_ptr<MipsAbiFlagsSection> create();11411142MipsAbiFlagsSection(Elf_Mips_ABIFlags flags);1143size_t getSize() const override { return sizeof(Elf_Mips_ABIFlags); }1144void writeTo(uint8_t *buf) override;11451146private:1147Elf_Mips_ABIFlags flags;1148};11491150// .MIPS.options section.1151template <class ELFT> class MipsOptionsSection final : public SyntheticSection {1152using Elf_Mips_Options = llvm::object::Elf_Mips_Options<ELFT>;1153using Elf_Mips_RegInfo = llvm::object::Elf_Mips_RegInfo<ELFT>;11541155public:1156static std::unique_ptr<MipsOptionsSection<ELFT>> create();11571158MipsOptionsSection(Elf_Mips_RegInfo reginfo);1159void writeTo(uint8_t *buf) override;11601161size_t getSize() const override {1162return sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);1163}11641165private:1166Elf_Mips_RegInfo reginfo;1167};11681169// MIPS .reginfo section.1170template <class ELFT> class MipsReginfoSection final : public SyntheticSection {1171using Elf_Mips_RegInfo = llvm::object::Elf_Mips_RegInfo<ELFT>;11721173public:1174static std::unique_ptr<MipsReginfoSection> create();11751176MipsReginfoSection(Elf_Mips_RegInfo reginfo);1177size_t getSize() const override { return sizeof(Elf_Mips_RegInfo); }1178void writeTo(uint8_t *buf) override;11791180private:1181Elf_Mips_RegInfo reginfo;1182};11831184// This is a MIPS specific section to hold a space within the data segment1185// of executable file which is pointed to by the DT_MIPS_RLD_MAP entry.1186// See "Dynamic section" in Chapter 5 in the following document:1187// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf1188class MipsRldMapSection final : public SyntheticSection {1189public:1190MipsRldMapSection();1191size_t getSize() const override { return config->wordsize; }1192void writeTo(uint8_t *buf) override {}1193};11941195// Representation of the combined .ARM.Exidx input sections. We process these1196// as a SyntheticSection like .eh_frame as we need to merge duplicate entries1197// and add terminating sentinel entries.1198//1199// The .ARM.exidx input sections after SHF_LINK_ORDER processing is done form1200// a table that the unwinder can derive (Addresses are encoded as offsets from1201// table):1202// | Address of function | Unwind instructions for function |1203// where the unwind instructions are either a small number of unwind or the1204// special EXIDX_CANTUNWIND entry representing no unwinding information.1205// When an exception is thrown from an address A, the unwinder searches the1206// table for the closest table entry with Address of function <= A. This means1207// that for two consecutive table entries:1208// | A1 | U1 |1209// | A2 | U2 |1210// The range of addresses described by U1 is [A1, A2)1211//1212// There are two cases where we need a linker generated table entry to fixup1213// the address ranges in the table1214// Case 1:1215// - A sentinel entry added with an address higher than all1216// executable sections. This was needed to work around libunwind bug pr31091.1217// - After address assignment we need to find the highest addressed executable1218// section and use the limit of that section so that the unwinder never1219// matches it.1220// Case 2:1221// - InputSections without a .ARM.exidx section (usually from Assembly)1222// need a table entry so that they terminate the range of the previously1223// function. This is pr40277.1224//1225// Instead of storing pointers to the .ARM.exidx InputSections from1226// InputObjects, we store pointers to the executable sections that need1227// .ARM.exidx sections. We can then use the dependentSections of these to1228// either find the .ARM.exidx section or know that we need to generate one.1229class ARMExidxSyntheticSection : public SyntheticSection {1230public:1231ARMExidxSyntheticSection();12321233// Add an input section to the ARMExidxSyntheticSection. Returns whether the1234// section needs to be removed from the main input section list.1235bool addSection(InputSection *isec);12361237size_t getSize() const override { return size; }1238void writeTo(uint8_t *buf) override;1239bool isNeeded() const override;1240// Sort and remove duplicate entries.1241void finalizeContents() override;1242InputSection *getLinkOrderDep() const;12431244static bool classof(const SectionBase *sec) {1245return sec->kind() == InputSectionBase::Synthetic &&1246sec->type == llvm::ELF::SHT_ARM_EXIDX;1247}12481249// Links to the ARMExidxSections so we can transfer the relocations once the1250// layout is known.1251SmallVector<InputSection *, 0> exidxSections;12521253private:1254size_t size = 0;12551256// Instead of storing pointers to the .ARM.exidx InputSections from1257// InputObjects, we store pointers to the executable sections that need1258// .ARM.exidx sections. We can then use the dependentSections of these to1259// either find the .ARM.exidx section or know that we need to generate one.1260SmallVector<InputSection *, 0> executableSections;12611262// Value of executableSecitons before finalizeContents(), so that it can be1263// run repeateadly during fixed point iteration.1264SmallVector<InputSection *, 0> originalExecutableSections;12651266// The executable InputSection with the highest address to use for the1267// sentinel. We store separately from ExecutableSections as merging of1268// duplicate entries may mean this InputSection is removed from1269// ExecutableSections.1270InputSection *sentinel = nullptr;1271};12721273// A container for one or more linker generated thunks. Instances of these1274// thunks including ARM interworking and Mips LA25 PI to non-PI thunks.1275class ThunkSection final : public SyntheticSection {1276public:1277// ThunkSection in OS, with desired outSecOff of Off1278ThunkSection(OutputSection *os, uint64_t off);12791280// Add a newly created Thunk to this container:1281// Thunk is given offset from start of this InputSection1282// Thunk defines a symbol in this InputSection that can be used as target1283// of a relocation1284void addThunk(Thunk *t);1285size_t getSize() const override;1286void writeTo(uint8_t *buf) override;1287InputSection *getTargetInputSection() const;1288bool assignOffsets();12891290// When true, round up reported size of section to 4 KiB. See comment1291// in addThunkSection() for more details.1292bool roundUpSizeForErrata = false;12931294private:1295SmallVector<Thunk *, 0> thunks;1296size_t size = 0;1297};12981299// Cortex-M Security Extensions. Prefix for functions that should be exported1300// for the non-secure world.1301const char ACLESESYM_PREFIX[] = "__acle_se_";1302const int ACLESESYM_SIZE = 8;13031304class ArmCmseSGVeneer;13051306class ArmCmseSGSection final : public SyntheticSection {1307public:1308ArmCmseSGSection();1309bool isNeeded() const override { return !entries.empty(); }1310size_t getSize() const override;1311void writeTo(uint8_t *buf) override;1312void addSGVeneer(Symbol *sym, Symbol *ext_sym);1313void addMappingSymbol();1314void finalizeContents() override;1315void exportEntries(SymbolTableBaseSection *symTab);1316uint64_t impLibMaxAddr = 0;13171318private:1319SmallVector<std::pair<Symbol *, Symbol *>, 0> entries;1320SmallVector<ArmCmseSGVeneer *, 0> sgVeneers;1321uint64_t newEntries = 0;1322};13231324// Used to compute outSecOff of .got2 in each object file. This is needed to1325// synthesize PLT entries for PPC32 Secure PLT ABI.1326class PPC32Got2Section final : public SyntheticSection {1327public:1328PPC32Got2Section();1329size_t getSize() const override { return 0; }1330bool isNeeded() const override;1331void finalizeContents() override;1332void writeTo(uint8_t *buf) override {}1333};13341335// This section is used to store the addresses of functions that are called1336// in range-extending thunks on PowerPC64. When producing position dependent1337// code the addresses are link-time constants and the table is written out to1338// the binary. When producing position-dependent code the table is allocated and1339// filled in by the dynamic linker.1340class PPC64LongBranchTargetSection final : public SyntheticSection {1341public:1342PPC64LongBranchTargetSection();1343uint64_t getEntryVA(const Symbol *sym, int64_t addend);1344std::optional<uint32_t> addEntry(const Symbol *sym, int64_t addend);1345size_t getSize() const override;1346void writeTo(uint8_t *buf) override;1347bool isNeeded() const override;1348void finalizeContents() override { finalized = true; }13491350private:1351SmallVector<std::pair<const Symbol *, int64_t>, 0> entries;1352llvm::DenseMap<std::pair<const Symbol *, int64_t>, uint32_t> entry_index;1353bool finalized = false;1354};13551356template <typename ELFT>1357class PartitionElfHeaderSection final : public SyntheticSection {1358public:1359PartitionElfHeaderSection();1360size_t getSize() const override;1361void writeTo(uint8_t *buf) override;1362};13631364template <typename ELFT>1365class PartitionProgramHeadersSection final : public SyntheticSection {1366public:1367PartitionProgramHeadersSection();1368size_t getSize() const override;1369void writeTo(uint8_t *buf) override;1370};13711372class PartitionIndexSection final : public SyntheticSection {1373public:1374PartitionIndexSection();1375size_t getSize() const override;1376void finalizeContents() override;1377void writeTo(uint8_t *buf) override;1378};13791380// See the following link for the Android-specific loader code that operates on1381// this section:1382// https://cs.android.com/android/platform/superproject/+/master:bionic/libc/bionic/libc_init_static.cpp;drc=9425b16978f9c5aa8f2c50c873db470819480d1d;l=1921383class MemtagAndroidNote final : public SyntheticSection {1384public:1385MemtagAndroidNote()1386: SyntheticSection(llvm::ELF::SHF_ALLOC, llvm::ELF::SHT_NOTE,1387/*alignment=*/4, ".note.android.memtag") {}1388void writeTo(uint8_t *buf) override;1389size_t getSize() const override;1390};13911392class PackageMetadataNote final : public SyntheticSection {1393public:1394PackageMetadataNote()1395: SyntheticSection(llvm::ELF::SHF_ALLOC, llvm::ELF::SHT_NOTE,1396/*alignment=*/4, ".note.package") {}1397void writeTo(uint8_t *buf) override;1398size_t getSize() const override;1399};14001401class MemtagGlobalDescriptors final : public SyntheticSection {1402public:1403MemtagGlobalDescriptors()1404: SyntheticSection(llvm::ELF::SHF_ALLOC,1405llvm::ELF::SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC,1406/*alignment=*/4, ".memtag.globals.dynamic") {}1407void writeTo(uint8_t *buf) override;1408// The size of the section is non-computable until all addresses are1409// synthetized, because the section's contents contain a sorted1410// varint-compressed list of pointers to global variables. We only know the1411// final size after `finalizeAddressDependentContent()`.1412size_t getSize() const override;1413bool updateAllocSize() override;14141415void addSymbol(const Symbol &sym) {1416symbols.push_back(&sym);1417}14181419bool isNeeded() const override {1420return !symbols.empty();1421}14221423private:1424SmallVector<const Symbol *, 0> symbols;1425};14261427template <class ELFT> void createSyntheticSections();1428InputSection *createInterpSection();1429MergeInputSection *createCommentSection();1430template <class ELFT> void splitSections();1431void combineEhSections();14321433bool hasMemtag();1434bool canHaveMemtagGlobals();14351436template <typename ELFT> void writeEhdr(uint8_t *buf, Partition &part);1437template <typename ELFT> void writePhdrs(uint8_t *buf, Partition &part);14381439Defined *addSyntheticLocal(StringRef name, uint8_t type, uint64_t value,1440uint64_t size, InputSectionBase §ion);14411442void addVerneed(Symbol *ss);14431444// Linker generated per-partition sections.1445struct Partition {1446StringRef name;1447uint64_t nameStrTab;14481449std::unique_ptr<SyntheticSection> elfHeader;1450std::unique_ptr<SyntheticSection> programHeaders;1451SmallVector<PhdrEntry *, 0> phdrs;14521453std::unique_ptr<ARMExidxSyntheticSection> armExidx;1454std::unique_ptr<BuildIdSection> buildId;1455std::unique_ptr<SyntheticSection> dynamic;1456std::unique_ptr<StringTableSection> dynStrTab;1457std::unique_ptr<SymbolTableBaseSection> dynSymTab;1458std::unique_ptr<EhFrameHeader> ehFrameHdr;1459std::unique_ptr<EhFrameSection> ehFrame;1460std::unique_ptr<GnuHashTableSection> gnuHashTab;1461std::unique_ptr<HashTableSection> hashTab;1462std::unique_ptr<MemtagAndroidNote> memtagAndroidNote;1463std::unique_ptr<MemtagGlobalDescriptors> memtagGlobalDescriptors;1464std::unique_ptr<PackageMetadataNote> packageMetadataNote;1465std::unique_ptr<RelocationBaseSection> relaDyn;1466std::unique_ptr<RelrBaseSection> relrDyn;1467std::unique_ptr<RelrBaseSection> relrAuthDyn;1468std::unique_ptr<VersionDefinitionSection> verDef;1469std::unique_ptr<SyntheticSection> verNeed;1470std::unique_ptr<VersionTableSection> verSym;14711472unsigned getNumber() const { return this - &partitions[0] + 1; }1473};14741475LLVM_LIBRARY_VISIBILITY extern Partition *mainPart;14761477inline Partition &SectionBase::getPartition() const {1478assert(isLive());1479return partitions[partition - 1];1480}14811482// Linker generated sections which can be used as inputs and are not specific to1483// a partition.1484struct InStruct {1485std::unique_ptr<InputSection> attributes;1486std::unique_ptr<SyntheticSection> riscvAttributes;1487std::unique_ptr<BssSection> bss;1488std::unique_ptr<BssSection> bssRelRo;1489std::unique_ptr<GotSection> got;1490std::unique_ptr<GotPltSection> gotPlt;1491std::unique_ptr<IgotPltSection> igotPlt;1492std::unique_ptr<RelroPaddingSection> relroPadding;1493std::unique_ptr<SyntheticSection> armCmseSGSection;1494std::unique_ptr<PPC64LongBranchTargetSection> ppc64LongBranchTarget;1495std::unique_ptr<SyntheticSection> mipsAbiFlags;1496std::unique_ptr<MipsGotSection> mipsGot;1497std::unique_ptr<SyntheticSection> mipsOptions;1498std::unique_ptr<SyntheticSection> mipsReginfo;1499std::unique_ptr<MipsRldMapSection> mipsRldMap;1500std::unique_ptr<SyntheticSection> partEnd;1501std::unique_ptr<SyntheticSection> partIndex;1502std::unique_ptr<PltSection> plt;1503std::unique_ptr<IpltSection> iplt;1504std::unique_ptr<PPC32Got2Section> ppc32Got2;1505std::unique_ptr<IBTPltSection> ibtPlt;1506std::unique_ptr<RelocationBaseSection> relaPlt;1507// Non-SHF_ALLOC sections1508std::unique_ptr<SyntheticSection> debugNames;1509std::unique_ptr<GdbIndexSection> gdbIndex;1510std::unique_ptr<StringTableSection> shStrTab;1511std::unique_ptr<StringTableSection> strTab;1512std::unique_ptr<SymbolTableBaseSection> symTab;1513std::unique_ptr<SymtabShndxSection> symTabShndx;15141515void reset();1516};15171518LLVM_LIBRARY_VISIBILITY extern InStruct in;15191520} // namespace lld::elf15211522#endif152315241525