Path: blob/main/contrib/llvm-project/lld/ELF/Config.h
34870 views
//===- Config.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//===----------------------------------------------------------------------===//78#ifndef LLD_ELF_CONFIG_H9#define LLD_ELF_CONFIG_H1011#include "lld/Common/ErrorHandler.h"12#include "llvm/ADT/CachedHashString.h"13#include "llvm/ADT/DenseSet.h"14#include "llvm/ADT/MapVector.h"15#include "llvm/ADT/SetVector.h"16#include "llvm/ADT/SmallSet.h"17#include "llvm/ADT/StringRef.h"18#include "llvm/ADT/StringSet.h"19#include "llvm/BinaryFormat/ELF.h"20#include "llvm/Option/ArgList.h"21#include "llvm/Support/CachePruning.h"22#include "llvm/Support/CodeGen.h"23#include "llvm/Support/Compiler.h"24#include "llvm/Support/Compression.h"25#include "llvm/Support/Endian.h"26#include "llvm/Support/FileSystem.h"27#include "llvm/Support/GlobPattern.h"28#include "llvm/Support/PrettyStackTrace.h"29#include <atomic>30#include <memory>31#include <optional>32#include <vector>3334namespace lld::elf {3536class InputFile;37class BinaryFile;38class BitcodeFile;39class ELFFileBase;40class SharedFile;41class InputSectionBase;42class EhInputSection;43class Symbol;44class BitcodeCompiler;4546enum ELFKind : uint8_t {47ELFNoneKind,48ELF32LEKind,49ELF32BEKind,50ELF64LEKind,51ELF64BEKind52};5354// For -Bno-symbolic, -Bsymbolic-non-weak-functions, -Bsymbolic-functions,55// -Bsymbolic-non-weak, -Bsymbolic.56enum class BsymbolicKind { None, NonWeakFunctions, Functions, NonWeak, All };5758// For --build-id.59enum class BuildIdKind { None, Fast, Md5, Sha1, Hexstring, Uuid };6061// For --call-graph-profile-sort={none,hfsort,cdsort}.62enum class CGProfileSortKind { None, Hfsort, Cdsort };6364// For --discard-{all,locals,none}.65enum class DiscardPolicy { Default, All, Locals, None };6667// For --icf={none,safe,all}.68enum class ICFLevel { None, Safe, All };6970// For --strip-{all,debug}.71enum class StripPolicy { None, All, Debug };7273// For --unresolved-symbols.74enum class UnresolvedPolicy { ReportError, Warn, Ignore };7576// For --orphan-handling.77enum class OrphanHandlingPolicy { Place, Warn, Error };7879// For --sort-section and linkerscript sorting rules.80enum class SortSectionPolicy {81Default,82None,83Alignment,84Name,85Priority,86Reverse,87};8889// For --target290enum class Target2Policy { Abs, Rel, GotRel };9192// For tracking ARM Float Argument PCS93enum class ARMVFPArgKind { Default, Base, VFP, ToolChain };9495// For -z noseparate-code, -z separate-code and -z separate-loadable-segments.96enum class SeparateSegmentKind { None, Code, Loadable };9798// For -z *stack99enum class GnuStackKind { None, Exec, NoExec };100101// For --lto=102enum LtoKind : uint8_t {UnifiedThin, UnifiedRegular, Default};103104// For -z gcs=105enum class GcsPolicy { Implicit, Never, Always };106107struct SymbolVersion {108llvm::StringRef name;109bool isExternCpp;110bool hasWildcard;111};112113// This struct contains symbols version definition that114// can be found in version script if it is used for link.115struct VersionDefinition {116llvm::StringRef name;117uint16_t id;118SmallVector<SymbolVersion, 0> nonLocalPatterns;119SmallVector<SymbolVersion, 0> localPatterns;120};121122class LinkerDriver {123public:124void linkerMain(ArrayRef<const char *> args);125void addFile(StringRef path, bool withLOption);126void addLibrary(StringRef name);127128private:129void createFiles(llvm::opt::InputArgList &args);130void inferMachineType();131template <class ELFT> void link(llvm::opt::InputArgList &args);132template <class ELFT> void compileBitcodeFiles(bool skipLinkedOutput);133bool tryAddFatLTOFile(MemoryBufferRef mb, StringRef archiveName,134uint64_t offsetInArchive, bool lazy);135// True if we are in --whole-archive and --no-whole-archive.136bool inWholeArchive = false;137138// True if we are in --start-lib and --end-lib.139bool inLib = false;140141std::unique_ptr<BitcodeCompiler> lto;142std::vector<InputFile *> files;143InputFile *armCmseImpLib = nullptr;144145public:146SmallVector<std::pair<StringRef, unsigned>, 0> archiveFiles;147};148149// This struct contains the global configuration for the linker.150// Most fields are direct mapping from the command line options151// and such fields have the same name as the corresponding options.152// Most fields are initialized by the ctx.driver.153struct Config {154uint8_t osabi = 0;155uint32_t andFeatures = 0;156llvm::CachePruningPolicy thinLTOCachePolicy;157llvm::SetVector<llvm::CachedHashString> dependencyFiles; // for --dependency-file158llvm::StringMap<uint64_t> sectionStartMap;159llvm::StringRef bfdname;160llvm::StringRef chroot;161llvm::StringRef dependencyFile;162llvm::StringRef dwoDir;163llvm::StringRef dynamicLinker;164llvm::StringRef entry;165llvm::StringRef emulation;166llvm::StringRef fini;167llvm::StringRef init;168llvm::StringRef ltoAAPipeline;169llvm::StringRef ltoCSProfileFile;170llvm::StringRef ltoNewPmPasses;171llvm::StringRef ltoObjPath;172llvm::StringRef ltoSampleProfile;173llvm::StringRef mapFile;174llvm::StringRef outputFile;175llvm::StringRef optRemarksFilename;176std::optional<uint64_t> optRemarksHotnessThreshold = 0;177llvm::StringRef optRemarksPasses;178llvm::StringRef optRemarksFormat;179llvm::StringRef optStatsFilename;180llvm::StringRef progName;181llvm::StringRef printArchiveStats;182llvm::StringRef printSymbolOrder;183llvm::StringRef soName;184llvm::StringRef sysroot;185llvm::StringRef thinLTOCacheDir;186llvm::StringRef thinLTOIndexOnlyArg;187llvm::StringRef whyExtract;188llvm::StringRef cmseInputLib;189llvm::StringRef cmseOutputLib;190StringRef zBtiReport = "none";191StringRef zCetReport = "none";192StringRef zPauthReport = "none";193StringRef zGcsReport = "none";194bool ltoBBAddrMap;195llvm::StringRef ltoBasicBlockSections;196std::pair<llvm::StringRef, llvm::StringRef> thinLTOObjectSuffixReplace;197llvm::StringRef thinLTOPrefixReplaceOld;198llvm::StringRef thinLTOPrefixReplaceNew;199llvm::StringRef thinLTOPrefixReplaceNativeObject;200std::string rpath;201llvm::SmallVector<VersionDefinition, 0> versionDefinitions;202llvm::SmallVector<llvm::StringRef, 0> auxiliaryList;203llvm::SmallVector<llvm::StringRef, 0> filterList;204llvm::SmallVector<llvm::StringRef, 0> passPlugins;205llvm::SmallVector<llvm::StringRef, 0> searchPaths;206llvm::SmallVector<llvm::StringRef, 0> symbolOrderingFile;207llvm::SmallVector<llvm::StringRef, 0> thinLTOModulesToCompile;208llvm::SmallVector<llvm::StringRef, 0> undefined;209llvm::SmallVector<SymbolVersion, 0> dynamicList;210llvm::SmallVector<uint8_t, 0> buildIdVector;211llvm::SmallVector<llvm::StringRef, 0> mllvmOpts;212llvm::MapVector<std::pair<const InputSectionBase *, const InputSectionBase *>,213uint64_t>214callGraphProfile;215bool cmseImplib = false;216bool allowMultipleDefinition;217bool fatLTOObjects;218bool androidPackDynRelocs = false;219bool armHasArmISA = false;220bool armHasThumb2ISA = false;221bool armHasBlx = false;222bool armHasMovtMovw = false;223bool armJ1J2BranchEncoding = false;224bool armCMSESupport = false;225bool asNeeded = false;226bool armBe8 = false;227BsymbolicKind bsymbolic = BsymbolicKind::None;228CGProfileSortKind callGraphProfileSort;229bool checkSections;230bool checkDynamicRelocs;231std::optional<llvm::DebugCompressionType> compressDebugSections;232llvm::SmallVector<233std::tuple<llvm::GlobPattern, llvm::DebugCompressionType, unsigned>, 0>234compressSections;235bool cref;236llvm::SmallVector<std::pair<llvm::GlobPattern, uint64_t>, 0>237deadRelocInNonAlloc;238bool debugNames;239bool demangle = true;240bool dependentLibraries;241bool disableVerify;242bool ehFrameHdr;243bool emitLLVM;244bool emitRelocs;245bool enableNewDtags;246bool enableNonContiguousRegions;247bool executeOnly;248bool exportDynamic;249bool fixCortexA53Errata843419;250bool fixCortexA8;251bool formatBinary = false;252bool fortranCommon;253bool gcSections;254bool gdbIndex;255bool gnuHash = false;256bool gnuUnique;257bool hasDynSymTab;258bool ignoreDataAddressEquality;259bool ignoreFunctionAddressEquality;260bool ltoCSProfileGenerate;261bool ltoPGOWarnMismatch;262bool ltoDebugPassManager;263bool ltoEmitAsm;264bool ltoUniqueBasicBlockSectionNames;265bool ltoValidateAllVtablesHaveTypeInfos;266bool ltoWholeProgramVisibility;267bool mergeArmExidx;268bool mipsN32Abi = false;269bool mmapOutputFile;270bool nmagic;271bool noDynamicLinker = false;272bool noinhibitExec;273bool nostdlib;274bool oFormatBinary;275bool omagic;276bool optEB = false;277bool optEL = false;278bool optimizeBBJumps;279bool optRemarksWithHotness;280bool picThunk;281bool pie;282bool printGcSections;283bool printIcfSections;284bool printMemoryUsage;285bool rejectMismatch;286bool relax;287bool relaxGP;288bool relocatable;289bool resolveGroups;290bool relrGlibc = false;291bool relrPackDynRelocs = false;292llvm::DenseSet<llvm::StringRef> saveTempsArgs;293llvm::SmallVector<std::pair<llvm::GlobPattern, uint32_t>, 0> shuffleSections;294bool singleRoRx;295bool shared;296bool symbolic;297bool isStatic = false;298bool sysvHash = false;299bool target1Rel;300bool trace;301bool thinLTOEmitImportsFiles;302bool thinLTOEmitIndexFiles;303bool thinLTOIndexOnly;304bool timeTraceEnabled;305bool tocOptimize;306bool pcRelOptimize;307bool undefinedVersion;308bool unique;309bool useAndroidRelrTags = false;310bool warnBackrefs;311llvm::SmallVector<llvm::GlobPattern, 0> warnBackrefsExclude;312bool warnCommon;313bool warnMissingEntry;314bool warnSymbolOrdering;315bool writeAddends;316bool zCombreloc;317bool zCopyreloc;318bool zForceBti;319bool zForceIbt;320bool zGlobal;321bool zHazardplt;322bool zIfuncNoplt;323bool zInitfirst;324bool zInterpose;325bool zKeepTextSectionPrefix;326bool zLrodataAfterBss;327bool zNodefaultlib;328bool zNodelete;329bool zNodlopen;330bool zNow;331bool zOrigin;332bool zPacPlt;333bool zRelro;334bool zRodynamic;335bool zShstk;336bool zStartStopGC;337uint8_t zStartStopVisibility;338bool zText;339bool zRetpolineplt;340bool zWxneeded;341DiscardPolicy discard;342GnuStackKind zGnustack;343ICFLevel icf;344OrphanHandlingPolicy orphanHandling;345SortSectionPolicy sortSection;346StripPolicy strip;347UnresolvedPolicy unresolvedSymbols;348UnresolvedPolicy unresolvedSymbolsInShlib;349Target2Policy target2;350GcsPolicy zGcs;351bool power10Stubs;352ARMVFPArgKind armVFPArgs = ARMVFPArgKind::Default;353BuildIdKind buildId = BuildIdKind::None;354SeparateSegmentKind zSeparate;355ELFKind ekind = ELFNoneKind;356uint16_t emachine = llvm::ELF::EM_NONE;357std::optional<uint64_t> imageBase;358uint64_t commonPageSize;359uint64_t maxPageSize;360uint64_t mipsGotSize;361uint64_t zStackSize;362unsigned ltoPartitions;363unsigned ltoo;364llvm::CodeGenOptLevel ltoCgo;365unsigned optimize;366StringRef thinLTOJobs;367unsigned timeTraceGranularity;368int32_t splitStackAdjustSize;369StringRef packageMetadata;370371// The following config options do not directly correspond to any372// particular command line options.373374// True if we need to pass through relocations in input files to the375// output file. Usually false because we consume relocations.376bool copyRelocs;377378// True if the target is ELF64. False if ELF32.379bool is64;380381// True if the target is little-endian. False if big-endian.382bool isLE;383384// endianness::little if isLE is true. endianness::big otherwise.385llvm::endianness endianness;386387// True if the target is the little-endian MIPS64.388//389// The reason why we have this variable only for the MIPS is because390// we use this often. Some ELF headers for MIPS64EL are in a391// mixed-endian (which is horrible and I'd say that's a serious spec392// bug), and we need to know whether we are reading MIPS ELF files or393// not in various places.394//395// (Note that MIPS64EL is not a typo for MIPS64LE. This is the official396// name whatever that means. A fun hypothesis is that "EL" is short for397// little-endian written in the little-endian order, but I don't know398// if that's true.)399bool isMips64EL;400401// True if we need to set the DF_STATIC_TLS flag to an output file, which402// works as a hint to the dynamic loader that the shared object contains code403// compiled with the initial-exec TLS model.404bool hasTlsIe = false;405406// Holds set of ELF header flags for the target.407uint32_t eflags = 0;408409// The ELF spec defines two types of relocation table entries, RELA and410// REL. RELA is a triplet of (offset, info, addend) while REL is a411// tuple of (offset, info). Addends for REL are implicit and read from412// the location where the relocations are applied. So, REL is more413// compact than RELA but requires a bit of more work to process.414//415// (From the linker writer's view, this distinction is not necessary.416// If the ELF had chosen whichever and sticked with it, it would have417// been easier to write code to process relocations, but it's too late418// to change the spec.)419//420// Each ABI defines its relocation type. IsRela is true if target421// uses RELA. As far as we know, all 64-bit ABIs are using RELA. A422// few 32-bit ABIs are using RELA too.423bool isRela;424425// True if we are creating position-independent code.426bool isPic;427428// 4 for ELF32, 8 for ELF64.429int wordsize;430431// Mode of MTE to write to the ELF note. Should be one of NT_MEMTAG_ASYNC (for432// async), NT_MEMTAG_SYNC (for sync), or NT_MEMTAG_LEVEL_NONE (for none). If433// async or sync is enabled, write the ELF note specifying the default MTE434// mode.435int androidMemtagMode;436// Signal to the dynamic loader to enable heap MTE.437bool androidMemtagHeap;438// Signal to the dynamic loader that this binary expects stack MTE. Generally,439// this means to map the primary and thread stacks as PROT_MTE. Note: This is440// not supported on Android 11 & 12.441bool androidMemtagStack;442443// When using a unified pre-link LTO pipeline, specify the backend LTO mode.444LtoKind ltoKind = LtoKind::Default;445446unsigned threadCount;447448// If an input file equals a key, remap it to the value.449llvm::DenseMap<llvm::StringRef, llvm::StringRef> remapInputs;450// If an input file matches a wildcard pattern, remap it to the value.451llvm::SmallVector<std::pair<llvm::GlobPattern, llvm::StringRef>, 0>452remapInputsWildcards;453};454struct ConfigWrapper {455Config c;456Config *operator->() { return &c; }457};458459LLVM_LIBRARY_VISIBILITY extern ConfigWrapper config;460461struct DuplicateSymbol {462const Symbol *sym;463const InputFile *file;464InputSectionBase *section;465uint64_t value;466};467468struct Ctx {469LinkerDriver driver;470SmallVector<std::unique_ptr<MemoryBuffer>> memoryBuffers;471SmallVector<ELFFileBase *, 0> objectFiles;472SmallVector<SharedFile *, 0> sharedFiles;473SmallVector<BinaryFile *, 0> binaryFiles;474SmallVector<BitcodeFile *, 0> bitcodeFiles;475SmallVector<BitcodeFile *, 0> lazyBitcodeFiles;476SmallVector<InputSectionBase *, 0> inputSections;477SmallVector<EhInputSection *, 0> ehInputSections;478// Duplicate symbol candidates.479SmallVector<DuplicateSymbol, 0> duplicates;480// Symbols in a non-prevailing COMDAT group which should be changed to an481// Undefined.482SmallVector<std::pair<Symbol *, unsigned>, 0> nonPrevailingSyms;483// A tuple of (reference, extractedFile, sym). Used by --why-extract=.484SmallVector<std::tuple<std::string, const InputFile *, const Symbol &>, 0>485whyExtractRecords;486// A mapping from a symbol to an InputFile referencing it backward. Used by487// --warn-backrefs.488llvm::DenseMap<const Symbol *,489std::pair<const InputFile *, const InputFile *>>490backwardReferences;491llvm::SmallSet<llvm::StringRef, 0> auxiliaryFiles;492// InputFile for linker created symbols with no source location.493InputFile *internalFile;494// True if SHT_LLVM_SYMPART is used.495std::atomic<bool> hasSympart{false};496// True if there are TLS IE relocations. Set DF_STATIC_TLS if -shared.497std::atomic<bool> hasTlsIe{false};498// True if we need to reserve two .got entries for local-dynamic TLS model.499std::atomic<bool> needsTlsLd{false};500// True if all native vtable symbols have corresponding type info symbols501// during LTO.502bool ltoAllVtablesHaveTypeInfos;503504// Each symbol assignment and DEFINED(sym) reference is assigned an increasing505// order. Each DEFINED(sym) evaluation checks whether the reference happens506// before a possible `sym = expr;`.507unsigned scriptSymOrderCounter = 1;508llvm::DenseMap<const Symbol *, unsigned> scriptSymOrder;509510void reset();511512llvm::raw_fd_ostream openAuxiliaryFile(llvm::StringRef, std::error_code &);513514ArrayRef<uint8_t> aarch64PauthAbiCoreInfo;515};516517LLVM_LIBRARY_VISIBILITY extern Ctx ctx;518519// The first two elements of versionDefinitions represent VER_NDX_LOCAL and520// VER_NDX_GLOBAL. This helper returns other elements.521static inline ArrayRef<VersionDefinition> namedVersionDefs() {522return llvm::ArrayRef(config->versionDefinitions).slice(2);523}524525void errorOrWarn(const Twine &msg);526527static inline void internalLinkerError(StringRef loc, const Twine &msg) {528errorOrWarn(loc + "internal linker error: " + msg + "\n" +529llvm::getBugReportMsg());530}531532} // namespace lld::elf533534#endif535536537