1 //===- Config.h -------------------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #ifndef LLD_ELF_CONFIG_H
10 #define LLD_ELF_CONFIG_H
12 #include "lld/Common/ErrorHandler.h"
13 #include "llvm/ADT/CachedHashString.h"
14 #include "llvm/ADT/DenseSet.h"
15 #include "llvm/ADT/MapVector.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/StringSet.h"
20 #include "llvm/BinaryFormat/ELF.h"
21 #include "llvm/Option/ArgList.h"
22 #include "llvm/Support/CachePruning.h"
23 #include "llvm/Support/CodeGen.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Compression.h"
26 #include "llvm/Support/Endian.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/GlobPattern.h"
29 #include "llvm/Support/PrettyStackTrace.h"
42 class InputSectionBase
;
45 class BitcodeCompiler
;
47 enum ELFKind
: uint8_t {
55 // For -Bno-symbolic, -Bsymbolic-non-weak-functions, -Bsymbolic-functions,
56 // -Bsymbolic-non-weak, -Bsymbolic.
57 enum class BsymbolicKind
{ None
, NonWeakFunctions
, Functions
, NonWeak
, All
};
60 enum class BuildIdKind
{ None
, Fast
, Md5
, Sha1
, Hexstring
, Uuid
};
62 // For --call-graph-profile-sort={none,hfsort,cdsort}.
63 enum class CGProfileSortKind
{ None
, Hfsort
, Cdsort
};
65 // For --discard-{all,locals,none}.
66 enum class DiscardPolicy
{ Default
, All
, Locals
, None
};
68 // For --icf={none,safe,all}.
69 enum class ICFLevel
{ None
, Safe
, All
};
71 // For --strip-{all,debug}.
72 enum class StripPolicy
{ None
, All
, Debug
};
74 // For --unresolved-symbols.
75 enum class UnresolvedPolicy
{ ReportError
, Warn
, Ignore
};
77 // For --orphan-handling.
78 enum class OrphanHandlingPolicy
{ Place
, Warn
, Error
};
80 // For --sort-section and linkerscript sorting rules.
81 enum class SortSectionPolicy
{
91 enum class Target2Policy
{ Abs
, Rel
, GotRel
};
93 // For tracking ARM Float Argument PCS
94 enum class ARMVFPArgKind
{ Default
, Base
, VFP
, ToolChain
};
96 // For -z noseparate-code, -z separate-code and -z separate-loadable-segments.
97 enum class SeparateSegmentKind
{ None
, Code
, Loadable
};
100 enum class GnuStackKind
{ None
, Exec
, NoExec
};
103 enum LtoKind
: uint8_t {UnifiedThin
, UnifiedRegular
, Default
};
106 enum class GcsPolicy
{ Implicit
, Never
, Always
};
108 struct SymbolVersion
{
109 llvm::StringRef name
;
114 // This struct contains symbols version definition that
115 // can be found in version script if it is used for link.
116 struct VersionDefinition
{
117 llvm::StringRef name
;
119 SmallVector
<SymbolVersion
, 0> nonLocalPatterns
;
120 SmallVector
<SymbolVersion
, 0> localPatterns
;
125 void linkerMain(ArrayRef
<const char *> args
);
126 void addFile(StringRef path
, bool withLOption
);
127 void addLibrary(StringRef name
);
130 void createFiles(llvm::opt::InputArgList
&args
);
131 void inferMachineType();
132 template <class ELFT
> void link(llvm::opt::InputArgList
&args
);
133 template <class ELFT
> void compileBitcodeFiles(bool skipLinkedOutput
);
134 bool tryAddFatLTOFile(MemoryBufferRef mb
, StringRef archiveName
,
135 uint64_t offsetInArchive
, bool lazy
);
136 // True if we are in --whole-archive and --no-whole-archive.
137 bool inWholeArchive
= false;
139 // True if we are in --start-lib and --end-lib.
142 std::unique_ptr
<BitcodeCompiler
> lto
;
143 std::vector
<InputFile
*> files
;
144 InputFile
*armCmseImpLib
= nullptr;
147 SmallVector
<std::pair
<StringRef
, unsigned>, 0> archiveFiles
;
150 // This struct contains the global configuration for the linker.
151 // Most fields are direct mapping from the command line options
152 // and such fields have the same name as the corresponding options.
153 // Most fields are initialized by the ctx.driver.
156 uint32_t andFeatures
= 0;
157 llvm::CachePruningPolicy thinLTOCachePolicy
;
158 llvm::SetVector
<llvm::CachedHashString
> dependencyFiles
; // for --dependency-file
159 llvm::StringMap
<uint64_t> sectionStartMap
;
160 llvm::StringRef bfdname
;
161 llvm::StringRef chroot
;
162 llvm::StringRef dependencyFile
;
163 llvm::StringRef dwoDir
;
164 llvm::StringRef dynamicLinker
;
165 llvm::StringRef entry
;
166 llvm::StringRef emulation
;
167 llvm::StringRef fini
;
168 llvm::StringRef init
;
169 llvm::StringRef ltoAAPipeline
;
170 llvm::StringRef ltoCSProfileFile
;
171 llvm::StringRef ltoNewPmPasses
;
172 llvm::StringRef ltoObjPath
;
173 llvm::StringRef ltoSampleProfile
;
174 llvm::StringRef mapFile
;
175 llvm::StringRef outputFile
;
176 llvm::StringRef optRemarksFilename
;
177 std::optional
<uint64_t> optRemarksHotnessThreshold
= 0;
178 llvm::StringRef optRemarksPasses
;
179 llvm::StringRef optRemarksFormat
;
180 llvm::StringRef optStatsFilename
;
181 llvm::StringRef progName
;
182 llvm::StringRef printArchiveStats
;
183 llvm::StringRef printSymbolOrder
;
184 llvm::StringRef soName
;
185 llvm::StringRef sysroot
;
186 llvm::StringRef thinLTOCacheDir
;
187 llvm::StringRef thinLTOIndexOnlyArg
;
188 llvm::StringRef whyExtract
;
189 llvm::StringRef cmseInputLib
;
190 llvm::StringRef cmseOutputLib
;
191 StringRef zBtiReport
= "none";
192 StringRef zCetReport
= "none";
193 StringRef zPauthReport
= "none";
194 StringRef zGcsReport
= "none";
196 llvm::StringRef ltoBasicBlockSections
;
197 std::pair
<llvm::StringRef
, llvm::StringRef
> thinLTOObjectSuffixReplace
;
198 llvm::StringRef thinLTOPrefixReplaceOld
;
199 llvm::StringRef thinLTOPrefixReplaceNew
;
200 llvm::StringRef thinLTOPrefixReplaceNativeObject
;
202 llvm::SmallVector
<VersionDefinition
, 0> versionDefinitions
;
203 llvm::SmallVector
<llvm::StringRef
, 0> auxiliaryList
;
204 llvm::SmallVector
<llvm::StringRef
, 0> filterList
;
205 llvm::SmallVector
<llvm::StringRef
, 0> passPlugins
;
206 llvm::SmallVector
<llvm::StringRef
, 0> searchPaths
;
207 llvm::SmallVector
<llvm::StringRef
, 0> symbolOrderingFile
;
208 llvm::SmallVector
<llvm::StringRef
, 0> thinLTOModulesToCompile
;
209 llvm::SmallVector
<llvm::StringRef
, 0> undefined
;
210 llvm::SmallVector
<SymbolVersion
, 0> dynamicList
;
211 llvm::SmallVector
<uint8_t, 0> buildIdVector
;
212 llvm::SmallVector
<llvm::StringRef
, 0> mllvmOpts
;
213 llvm::MapVector
<std::pair
<const InputSectionBase
*, const InputSectionBase
*>,
216 bool cmseImplib
= false;
217 bool allowMultipleDefinition
;
219 bool androidPackDynRelocs
= false;
220 bool armThumbPLTs
= false;
221 bool armHasBlx
= false;
222 bool armHasMovtMovw
= false;
223 bool armJ1J2BranchEncoding
= false;
224 bool armCMSESupport
= false;
225 bool asNeeded
= false;
227 BsymbolicKind bsymbolic
= BsymbolicKind::None
;
228 CGProfileSortKind callGraphProfileSort
;
230 bool checkDynamicRelocs
;
231 std::optional
<llvm::DebugCompressionType
> compressDebugSections
;
233 std::tuple
<llvm::GlobPattern
, llvm::DebugCompressionType
, unsigned>, 0>
236 llvm::SmallVector
<std::pair
<llvm::GlobPattern
, uint64_t>, 0>
239 bool demangle
= true;
240 bool dependentLibraries
;
246 bool enableNonContiguousRegions
;
249 bool fixCortexA53Errata843419
;
251 bool formatBinary
= false;
255 bool gnuHash
= false;
258 bool ignoreDataAddressEquality
;
259 bool ignoreFunctionAddressEquality
;
260 bool ltoCSProfileGenerate
;
261 bool ltoPGOWarnMismatch
;
262 bool ltoDebugPassManager
;
264 bool ltoUniqueBasicBlockSectionNames
;
265 bool ltoValidateAllVtablesHaveTypeInfos
;
266 bool ltoWholeProgramVisibility
;
268 bool mipsN32Abi
= false;
271 bool noDynamicLinker
= false;
278 bool optimizeBBJumps
;
279 bool optRemarksWithHotness
;
282 bool printGcSections
;
283 bool printIcfSections
;
284 bool printMemoryUsage
;
290 bool relrGlibc
= false;
291 bool relrPackDynRelocs
= false;
292 llvm::DenseSet
<llvm::StringRef
> saveTempsArgs
;
293 llvm::SmallVector
<std::pair
<llvm::GlobPattern
, uint32_t>, 0> shuffleSections
;
297 bool isStatic
= false;
298 bool sysvHash
= false;
301 bool thinLTOEmitImportsFiles
;
302 bool thinLTOEmitIndexFiles
;
303 bool thinLTOIndexOnly
;
304 bool timeTraceEnabled
;
307 bool undefinedVersion
;
309 bool useAndroidRelrTags
= false;
311 llvm::SmallVector
<llvm::GlobPattern
, 0> warnBackrefsExclude
;
313 bool warnMissingEntry
;
314 bool warnSymbolOrdering
;
325 bool zKeepTextSectionPrefix
;
326 bool zLrodataAfterBss
;
337 uint8_t zStartStopVisibility
;
341 DiscardPolicy discard
;
342 GnuStackKind zGnustack
;
344 OrphanHandlingPolicy orphanHandling
;
345 SortSectionPolicy sortSection
;
347 UnresolvedPolicy unresolvedSymbols
;
348 UnresolvedPolicy unresolvedSymbolsInShlib
;
349 Target2Policy target2
;
352 ARMVFPArgKind armVFPArgs
= ARMVFPArgKind::Default
;
353 BuildIdKind buildId
= BuildIdKind::None
;
354 SeparateSegmentKind zSeparate
;
355 ELFKind ekind
= ELFNoneKind
;
356 uint16_t emachine
= llvm::ELF::EM_NONE
;
357 std::optional
<uint64_t> imageBase
;
358 uint64_t commonPageSize
;
359 uint64_t maxPageSize
;
360 uint64_t mipsGotSize
;
362 unsigned ltoPartitions
;
364 llvm::CodeGenOptLevel ltoCgo
;
366 StringRef thinLTOJobs
;
367 unsigned timeTraceGranularity
;
368 int32_t splitStackAdjustSize
;
369 StringRef packageMetadata
;
371 // The following config options do not directly correspond to any
372 // particular command line options.
374 // True if we need to pass through relocations in input files to the
375 // output file. Usually false because we consume relocations.
378 // True if the target is ELF64. False if ELF32.
381 // True if the target is little-endian. False if big-endian.
384 // endianness::little if isLE is true. endianness::big otherwise.
385 llvm::endianness endianness
;
387 // True if the target is the little-endian MIPS64.
389 // The reason why we have this variable only for the MIPS is because
390 // we use this often. Some ELF headers for MIPS64EL are in a
391 // mixed-endian (which is horrible and I'd say that's a serious spec
392 // bug), and we need to know whether we are reading MIPS ELF files or
393 // not in various places.
395 // (Note that MIPS64EL is not a typo for MIPS64LE. This is the official
396 // name whatever that means. A fun hypothesis is that "EL" is short for
397 // little-endian written in the little-endian order, but I don't know
401 // True if we need to set the DF_STATIC_TLS flag to an output file, which
402 // works as a hint to the dynamic loader that the shared object contains code
403 // compiled with the initial-exec TLS model.
404 bool hasTlsIe
= false;
406 // Holds set of ELF header flags for the target.
409 // The ELF spec defines two types of relocation table entries, RELA and
410 // REL. RELA is a triplet of (offset, info, addend) while REL is a
411 // tuple of (offset, info). Addends for REL are implicit and read from
412 // the location where the relocations are applied. So, REL is more
413 // compact than RELA but requires a bit of more work to process.
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 have
417 // been easier to write code to process relocations, but it's too late
418 // to change the spec.)
420 // Each ABI defines its relocation type. IsRela is true if target
421 // uses RELA. As far as we know, all 64-bit ABIs are using RELA. A
422 // few 32-bit ABIs are using RELA too.
425 // True if we are creating position-independent code.
428 // 4 for ELF32, 8 for ELF64.
431 // Mode of MTE to write to the ELF note. Should be one of NT_MEMTAG_ASYNC (for
432 // async), NT_MEMTAG_SYNC (for sync), or NT_MEMTAG_LEVEL_NONE (for none). If
433 // async or sync is enabled, write the ELF note specifying the default MTE
435 int androidMemtagMode
;
436 // Signal to the dynamic loader to enable heap MTE.
437 bool 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 is
440 // not supported on Android 11 & 12.
441 bool androidMemtagStack
;
443 // When using a unified pre-link LTO pipeline, specify the backend LTO mode.
444 LtoKind ltoKind
= LtoKind::Default
;
446 unsigned threadCount
;
448 // If an input file equals a key, remap it to the value.
449 llvm::DenseMap
<llvm::StringRef
, llvm::StringRef
> remapInputs
;
450 // If an input file matches a wildcard pattern, remap it to the value.
451 llvm::SmallVector
<std::pair
<llvm::GlobPattern
, llvm::StringRef
>, 0>
452 remapInputsWildcards
;
454 struct ConfigWrapper
{
456 Config
*operator->() { return &c
; }
459 LLVM_LIBRARY_VISIBILITY
extern ConfigWrapper config
;
461 struct DuplicateSymbol
{
463 const InputFile
*file
;
464 InputSectionBase
*section
;
470 SmallVector
<std::unique_ptr
<MemoryBuffer
>> memoryBuffers
;
471 SmallVector
<ELFFileBase
*, 0> objectFiles
;
472 SmallVector
<SharedFile
*, 0> sharedFiles
;
473 SmallVector
<BinaryFile
*, 0> binaryFiles
;
474 SmallVector
<BitcodeFile
*, 0> bitcodeFiles
;
475 SmallVector
<BitcodeFile
*, 0> lazyBitcodeFiles
;
476 SmallVector
<InputSectionBase
*, 0> inputSections
;
477 SmallVector
<EhInputSection
*, 0> ehInputSections
;
478 // Duplicate symbol candidates.
479 SmallVector
<DuplicateSymbol
, 0> duplicates
;
480 // Symbols in a non-prevailing COMDAT group which should be changed to an
482 SmallVector
<std::pair
<Symbol
*, unsigned>, 0> nonPrevailingSyms
;
483 // A tuple of (reference, extractedFile, sym). Used by --why-extract=.
484 SmallVector
<std::tuple
<std::string
, const InputFile
*, const Symbol
&>, 0>
486 // A mapping from a symbol to an InputFile referencing it backward. Used by
488 llvm::DenseMap
<const Symbol
*,
489 std::pair
<const InputFile
*, const InputFile
*>>
491 llvm::SmallSet
<llvm::StringRef
, 0> auxiliaryFiles
;
492 // InputFile for linker created symbols with no source location.
493 InputFile
*internalFile
;
494 // True if SHT_LLVM_SYMPART is used.
495 std::atomic
<bool> hasSympart
{false};
496 // True if there are TLS IE relocations. Set DF_STATIC_TLS if -shared.
497 std::atomic
<bool> hasTlsIe
{false};
498 // True if we need to reserve two .got entries for local-dynamic TLS model.
499 std::atomic
<bool> needsTlsLd
{false};
500 // True if all native vtable symbols have corresponding type info symbols
502 bool ltoAllVtablesHaveTypeInfos
;
504 // Each symbol assignment and DEFINED(sym) reference is assigned an increasing
505 // order. Each DEFINED(sym) evaluation checks whether the reference happens
506 // before a possible `sym = expr;`.
507 unsigned scriptSymOrderCounter
= 1;
508 llvm::DenseMap
<const Symbol
*, unsigned> scriptSymOrder
;
512 llvm::raw_fd_ostream
openAuxiliaryFile(llvm::StringRef
, std::error_code
&);
514 ArrayRef
<uint8_t> aarch64PauthAbiCoreInfo
;
517 LLVM_LIBRARY_VISIBILITY
extern Ctx ctx
;
519 // The first two elements of versionDefinitions represent VER_NDX_LOCAL and
520 // VER_NDX_GLOBAL. This helper returns other elements.
521 static inline ArrayRef
<VersionDefinition
> namedVersionDefs() {
522 return llvm::ArrayRef(config
->versionDefinitions
).slice(2);
525 void errorOrWarn(const Twine
&msg
);
527 static inline void internalLinkerError(StringRef loc
, const Twine
&msg
) {
528 errorOrWarn(loc
+ "internal linker error: " + msg
+ "\n" +
529 llvm::getBugReportMsg());
532 } // namespace lld::elf