1 | //===- Config.h -------------------------------------------------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | #ifndef LLD_ELF_CONFIG_H |
10 | #define LLD_ELF_CONFIG_H |
11 | |
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" |
30 | #include <atomic> |
31 | #include <memory> |
32 | #include <optional> |
33 | #include <vector> |
34 | |
35 | namespace lld::elf { |
36 | |
37 | class InputFile; |
38 | class BinaryFile; |
39 | class BitcodeFile; |
40 | class ELFFileBase; |
41 | class SharedFile; |
42 | class InputSectionBase; |
43 | class EhInputSection; |
44 | class Symbol; |
45 | class BitcodeCompiler; |
46 | |
47 | enum ELFKind : uint8_t { |
48 | ELFNoneKind, |
49 | ELF32LEKind, |
50 | ELF32BEKind, |
51 | ELF64LEKind, |
52 | ELF64BEKind |
53 | }; |
54 | |
55 | // For -Bno-symbolic, -Bsymbolic-non-weak-functions, -Bsymbolic-functions, |
56 | // -Bsymbolic-non-weak, -Bsymbolic. |
57 | enum class BsymbolicKind { None, NonWeakFunctions, Functions, NonWeak, All }; |
58 | |
59 | // For --build-id. |
60 | enum class BuildIdKind { None, Fast, Md5, Sha1, Hexstring, Uuid }; |
61 | |
62 | // For --call-graph-profile-sort={none,hfsort,cdsort}. |
63 | enum class CGProfileSortKind { None, Hfsort, Cdsort }; |
64 | |
65 | // For --discard-{all,locals,none}. |
66 | enum class DiscardPolicy { Default, All, Locals, None }; |
67 | |
68 | // For --icf={none,safe,all}. |
69 | enum class ICFLevel { None, Safe, All }; |
70 | |
71 | // For --strip-{all,debug}. |
72 | enum class StripPolicy { None, All, Debug }; |
73 | |
74 | // For --unresolved-symbols. |
75 | enum class UnresolvedPolicy { ReportError, Warn, Ignore }; |
76 | |
77 | // For --orphan-handling. |
78 | enum class OrphanHandlingPolicy { Place, Warn, Error }; |
79 | |
80 | // For --sort-section and linkerscript sorting rules. |
81 | enum class SortSectionPolicy { |
82 | Default, |
83 | None, |
84 | Alignment, |
85 | Name, |
86 | Priority, |
87 | Reverse, |
88 | }; |
89 | |
90 | // For --target2 |
91 | enum class Target2Policy { Abs, Rel, GotRel }; |
92 | |
93 | // For tracking ARM Float Argument PCS |
94 | enum class ARMVFPArgKind { Default, Base, VFP, ToolChain }; |
95 | |
96 | // For -z noseparate-code, -z separate-code and -z separate-loadable-segments. |
97 | enum class SeparateSegmentKind { None, Code, Loadable }; |
98 | |
99 | // For -z *stack |
100 | enum class GnuStackKind { None, Exec, NoExec }; |
101 | |
102 | // For --lto= |
103 | enum LtoKind : uint8_t {UnifiedThin, UnifiedRegular, Default}; |
104 | |
105 | struct SymbolVersion { |
106 | llvm::StringRef name; |
107 | bool isExternCpp; |
108 | bool hasWildcard; |
109 | }; |
110 | |
111 | // This struct contains symbols version definition that |
112 | // can be found in version script if it is used for link. |
113 | struct VersionDefinition { |
114 | llvm::StringRef name; |
115 | uint16_t id; |
116 | SmallVector<SymbolVersion, 0> nonLocalPatterns; |
117 | SmallVector<SymbolVersion, 0> localPatterns; |
118 | }; |
119 | |
120 | class LinkerDriver { |
121 | public: |
122 | void linkerMain(ArrayRef<const char *> args); |
123 | void addFile(StringRef path, bool withLOption); |
124 | void addLibrary(StringRef name); |
125 | |
126 | private: |
127 | void createFiles(llvm::opt::InputArgList &args); |
128 | void inferMachineType(); |
129 | template <class ELFT> void link(llvm::opt::InputArgList &args); |
130 | template <class ELFT> void compileBitcodeFiles(bool skipLinkedOutput); |
131 | bool tryAddFatLTOFile(MemoryBufferRef mb, StringRef archiveName, |
132 | uint64_t offsetInArchive, bool lazy); |
133 | // True if we are in --whole-archive and --no-whole-archive. |
134 | bool inWholeArchive = false; |
135 | |
136 | // True if we are in --start-lib and --end-lib. |
137 | bool inLib = false; |
138 | |
139 | std::unique_ptr<BitcodeCompiler> lto; |
140 | std::vector<InputFile *> files; |
141 | InputFile *armCmseImpLib = nullptr; |
142 | |
143 | public: |
144 | SmallVector<std::pair<StringRef, unsigned>, 0> archiveFiles; |
145 | }; |
146 | |
147 | // This struct contains the global configuration for the linker. |
148 | // Most fields are direct mapping from the command line options |
149 | // and such fields have the same name as the corresponding options. |
150 | // Most fields are initialized by the ctx.driver. |
151 | struct Config { |
152 | uint8_t osabi = 0; |
153 | uint32_t andFeatures = 0; |
154 | llvm::CachePruningPolicy thinLTOCachePolicy; |
155 | llvm::SetVector<llvm::CachedHashString> dependencyFiles; // for --dependency-file |
156 | llvm::StringMap<uint64_t> sectionStartMap; |
157 | llvm::StringRef bfdname; |
158 | llvm::StringRef chroot; |
159 | llvm::StringRef dependencyFile; |
160 | llvm::StringRef dwoDir; |
161 | llvm::StringRef dynamicLinker; |
162 | llvm::StringRef entry; |
163 | llvm::StringRef emulation; |
164 | llvm::StringRef fini; |
165 | llvm::StringRef init; |
166 | llvm::StringRef ltoAAPipeline; |
167 | llvm::StringRef ltoCSProfileFile; |
168 | llvm::StringRef ltoNewPmPasses; |
169 | llvm::StringRef ltoObjPath; |
170 | llvm::StringRef ltoSampleProfile; |
171 | llvm::StringRef mapFile; |
172 | llvm::StringRef outputFile; |
173 | llvm::StringRef ; |
174 | std::optional<uint64_t> = 0; |
175 | llvm::StringRef ; |
176 | llvm::StringRef ; |
177 | llvm::StringRef optStatsFilename; |
178 | llvm::StringRef progName; |
179 | llvm::StringRef printArchiveStats; |
180 | llvm::StringRef printSymbolOrder; |
181 | llvm::StringRef soName; |
182 | llvm::StringRef sysroot; |
183 | llvm::StringRef thinLTOCacheDir; |
184 | llvm::StringRef thinLTOIndexOnlyArg; |
185 | llvm::StringRef ; |
186 | llvm::StringRef cmseInputLib; |
187 | llvm::StringRef cmseOutputLib; |
188 | StringRef zBtiReport = "none" ; |
189 | StringRef zCetReport = "none" ; |
190 | StringRef zPauthReport = "none" ; |
191 | bool ltoBBAddrMap; |
192 | llvm::StringRef ltoBasicBlockSections; |
193 | std::pair<llvm::StringRef, llvm::StringRef> thinLTOObjectSuffixReplace; |
194 | llvm::StringRef thinLTOPrefixReplaceOld; |
195 | llvm::StringRef thinLTOPrefixReplaceNew; |
196 | llvm::StringRef thinLTOPrefixReplaceNativeObject; |
197 | std::string rpath; |
198 | llvm::SmallVector<VersionDefinition, 0> versionDefinitions; |
199 | llvm::SmallVector<llvm::StringRef, 0> auxiliaryList; |
200 | llvm::SmallVector<llvm::StringRef, 0> filterList; |
201 | llvm::SmallVector<llvm::StringRef, 0> passPlugins; |
202 | llvm::SmallVector<llvm::StringRef, 0> searchPaths; |
203 | llvm::SmallVector<llvm::StringRef, 0> symbolOrderingFile; |
204 | llvm::SmallVector<llvm::StringRef, 0> thinLTOModulesToCompile; |
205 | llvm::SmallVector<llvm::StringRef, 0> undefined; |
206 | llvm::SmallVector<SymbolVersion, 0> dynamicList; |
207 | llvm::SmallVector<uint8_t, 0> buildIdVector; |
208 | llvm::SmallVector<llvm::StringRef, 0> mllvmOpts; |
209 | llvm::MapVector<std::pair<const InputSectionBase *, const InputSectionBase *>, |
210 | uint64_t> |
211 | callGraphProfile; |
212 | bool cmseImplib = false; |
213 | bool allowMultipleDefinition; |
214 | bool fatLTOObjects; |
215 | bool androidPackDynRelocs = false; |
216 | bool armHasBlx = false; |
217 | bool armHasMovtMovw = false; |
218 | bool armJ1J2BranchEncoding = false; |
219 | bool armCMSESupport = false; |
220 | bool asNeeded = false; |
221 | bool armBe8 = false; |
222 | BsymbolicKind bsymbolic = BsymbolicKind::None; |
223 | CGProfileSortKind callGraphProfileSort; |
224 | bool checkSections; |
225 | bool checkDynamicRelocs; |
226 | std::optional<llvm::DebugCompressionType> compressDebugSections; |
227 | llvm::SmallVector<std::pair<llvm::GlobPattern, llvm::DebugCompressionType>, 0> |
228 | compressSections; |
229 | bool cref; |
230 | llvm::SmallVector<std::pair<llvm::GlobPattern, uint64_t>, 0> |
231 | deadRelocInNonAlloc; |
232 | bool debugNames; |
233 | bool demangle = true; |
234 | bool dependentLibraries; |
235 | bool disableVerify; |
236 | bool ehFrameHdr; |
237 | bool emitLLVM; |
238 | bool emitRelocs; |
239 | bool enableNewDtags; |
240 | bool executeOnly; |
241 | bool exportDynamic; |
242 | bool fixCortexA53Errata843419; |
243 | bool fixCortexA8; |
244 | bool formatBinary = false; |
245 | bool fortranCommon; |
246 | bool gcSections; |
247 | bool gdbIndex; |
248 | bool gnuHash = false; |
249 | bool gnuUnique; |
250 | bool hasDynSymTab; |
251 | bool ignoreDataAddressEquality; |
252 | bool ignoreFunctionAddressEquality; |
253 | bool ltoCSProfileGenerate; |
254 | bool ltoPGOWarnMismatch; |
255 | bool ltoDebugPassManager; |
256 | bool ltoEmitAsm; |
257 | bool ltoUniqueBasicBlockSectionNames; |
258 | bool ltoValidateAllVtablesHaveTypeInfos; |
259 | bool ltoWholeProgramVisibility; |
260 | bool mergeArmExidx; |
261 | bool mipsN32Abi = false; |
262 | bool mmapOutputFile; |
263 | bool nmagic; |
264 | bool noDynamicLinker = false; |
265 | bool noinhibitExec; |
266 | bool nostdlib; |
267 | bool oFormatBinary; |
268 | bool omagic; |
269 | bool optEB = false; |
270 | bool optEL = false; |
271 | bool optimizeBBJumps; |
272 | bool ; |
273 | bool picThunk; |
274 | bool pie; |
275 | bool printGcSections; |
276 | bool printIcfSections; |
277 | bool printMemoryUsage; |
278 | bool rejectMismatch; |
279 | bool relax; |
280 | bool relaxGP; |
281 | bool relocatable; |
282 | bool relrGlibc = false; |
283 | bool relrPackDynRelocs = false; |
284 | llvm::DenseSet<llvm::StringRef> saveTempsArgs; |
285 | llvm::SmallVector<std::pair<llvm::GlobPattern, uint32_t>, 0> shuffleSections; |
286 | bool singleRoRx; |
287 | bool shared; |
288 | bool symbolic; |
289 | bool isStatic = false; |
290 | bool sysvHash = false; |
291 | bool target1Rel; |
292 | bool trace; |
293 | bool thinLTOEmitImportsFiles; |
294 | bool thinLTOEmitIndexFiles; |
295 | bool thinLTOIndexOnly; |
296 | bool timeTraceEnabled; |
297 | bool tocOptimize; |
298 | bool pcRelOptimize; |
299 | bool undefinedVersion; |
300 | bool unique; |
301 | bool useAndroidRelrTags = false; |
302 | bool warnBackrefs; |
303 | llvm::SmallVector<llvm::GlobPattern, 0> warnBackrefsExclude; |
304 | bool warnCommon; |
305 | bool warnMissingEntry; |
306 | bool warnSymbolOrdering; |
307 | bool writeAddends; |
308 | bool zCombreloc; |
309 | bool zCopyreloc; |
310 | bool zForceBti; |
311 | bool zForceIbt; |
312 | bool zGlobal; |
313 | bool zHazardplt; |
314 | bool zIfuncNoplt; |
315 | bool zInitfirst; |
316 | bool zInterpose; |
317 | bool zKeepTextSectionPrefix; |
318 | bool zLrodataAfterBss; |
319 | bool zNodefaultlib; |
320 | bool zNodelete; |
321 | bool zNodlopen; |
322 | bool zNow; |
323 | bool zOrigin; |
324 | bool zPacPlt; |
325 | bool zRelro; |
326 | bool zRodynamic; |
327 | bool zShstk; |
328 | bool zStartStopGC; |
329 | uint8_t zStartStopVisibility; |
330 | bool zText; |
331 | bool zRetpolineplt; |
332 | bool zWxneeded; |
333 | DiscardPolicy discard; |
334 | GnuStackKind zGnustack; |
335 | ICFLevel icf; |
336 | OrphanHandlingPolicy orphanHandling; |
337 | SortSectionPolicy sortSection; |
338 | StripPolicy strip; |
339 | UnresolvedPolicy unresolvedSymbols; |
340 | UnresolvedPolicy unresolvedSymbolsInShlib; |
341 | Target2Policy target2; |
342 | bool power10Stubs; |
343 | ARMVFPArgKind armVFPArgs = ARMVFPArgKind::Default; |
344 | BuildIdKind buildId = BuildIdKind::None; |
345 | SeparateSegmentKind zSeparate; |
346 | ELFKind ekind = ELFNoneKind; |
347 | uint16_t emachine = llvm::ELF::EM_NONE; |
348 | std::optional<uint64_t> imageBase; |
349 | uint64_t commonPageSize; |
350 | uint64_t maxPageSize; |
351 | uint64_t mipsGotSize; |
352 | uint64_t zStackSize; |
353 | unsigned ltoPartitions; |
354 | unsigned ltoo; |
355 | llvm::CodeGenOptLevel ltoCgo; |
356 | unsigned optimize; |
357 | StringRef thinLTOJobs; |
358 | unsigned timeTraceGranularity; |
359 | int32_t splitStackAdjustSize; |
360 | StringRef packageMetadata; |
361 | |
362 | // The following config options do not directly correspond to any |
363 | // particular command line options. |
364 | |
365 | // True if we need to pass through relocations in input files to the |
366 | // output file. Usually false because we consume relocations. |
367 | bool copyRelocs; |
368 | |
369 | // True if the target is ELF64. False if ELF32. |
370 | bool is64; |
371 | |
372 | // True if the target is little-endian. False if big-endian. |
373 | bool isLE; |
374 | |
375 | // endianness::little if isLE is true. endianness::big otherwise. |
376 | llvm::endianness endianness; |
377 | |
378 | // True if the target is the little-endian MIPS64. |
379 | // |
380 | // The reason why we have this variable only for the MIPS is because |
381 | // we use this often. Some ELF headers for MIPS64EL are in a |
382 | // mixed-endian (which is horrible and I'd say that's a serious spec |
383 | // bug), and we need to know whether we are reading MIPS ELF files or |
384 | // not in various places. |
385 | // |
386 | // (Note that MIPS64EL is not a typo for MIPS64LE. This is the official |
387 | // name whatever that means. A fun hypothesis is that "EL" is short for |
388 | // little-endian written in the little-endian order, but I don't know |
389 | // if that's true.) |
390 | bool isMips64EL; |
391 | |
392 | // True if we need to set the DF_STATIC_TLS flag to an output file, which |
393 | // works as a hint to the dynamic loader that the shared object contains code |
394 | // compiled with the initial-exec TLS model. |
395 | bool hasTlsIe = false; |
396 | |
397 | // Holds set of ELF header flags for the target. |
398 | uint32_t eflags = 0; |
399 | |
400 | // The ELF spec defines two types of relocation table entries, RELA and |
401 | // REL. RELA is a triplet of (offset, info, addend) while REL is a |
402 | // tuple of (offset, info). Addends for REL are implicit and read from |
403 | // the location where the relocations are applied. So, REL is more |
404 | // compact than RELA but requires a bit of more work to process. |
405 | // |
406 | // (From the linker writer's view, this distinction is not necessary. |
407 | // If the ELF had chosen whichever and sticked with it, it would have |
408 | // been easier to write code to process relocations, but it's too late |
409 | // to change the spec.) |
410 | // |
411 | // Each ABI defines its relocation type. IsRela is true if target |
412 | // uses RELA. As far as we know, all 64-bit ABIs are using RELA. A |
413 | // few 32-bit ABIs are using RELA too. |
414 | bool isRela; |
415 | |
416 | // True if we are creating position-independent code. |
417 | bool isPic; |
418 | |
419 | // 4 for ELF32, 8 for ELF64. |
420 | int wordsize; |
421 | |
422 | // Mode of MTE to write to the ELF note. Should be one of NT_MEMTAG_ASYNC (for |
423 | // async), NT_MEMTAG_SYNC (for sync), or NT_MEMTAG_LEVEL_NONE (for none). If |
424 | // async or sync is enabled, write the ELF note specifying the default MTE |
425 | // mode. |
426 | int androidMemtagMode; |
427 | // Signal to the dynamic loader to enable heap MTE. |
428 | bool androidMemtagHeap; |
429 | // Signal to the dynamic loader that this binary expects stack MTE. Generally, |
430 | // this means to map the primary and thread stacks as PROT_MTE. Note: This is |
431 | // not supported on Android 11 & 12. |
432 | bool androidMemtagStack; |
433 | |
434 | // When using a unified pre-link LTO pipeline, specify the backend LTO mode. |
435 | LtoKind ltoKind = LtoKind::Default; |
436 | |
437 | unsigned threadCount; |
438 | |
439 | // If an input file equals a key, remap it to the value. |
440 | llvm::DenseMap<llvm::StringRef, llvm::StringRef> remapInputs; |
441 | // If an input file matches a wildcard pattern, remap it to the value. |
442 | llvm::SmallVector<std::pair<llvm::GlobPattern, llvm::StringRef>, 0> |
443 | remapInputsWildcards; |
444 | }; |
445 | struct ConfigWrapper { |
446 | Config c; |
447 | Config *operator->() { return &c; } |
448 | }; |
449 | |
450 | LLVM_LIBRARY_VISIBILITY extern ConfigWrapper config; |
451 | |
452 | struct DuplicateSymbol { |
453 | const Symbol *sym; |
454 | const InputFile *file; |
455 | InputSectionBase *section; |
456 | uint64_t value; |
457 | }; |
458 | |
459 | struct Ctx { |
460 | LinkerDriver driver; |
461 | SmallVector<std::unique_ptr<MemoryBuffer>> memoryBuffers; |
462 | SmallVector<ELFFileBase *, 0> objectFiles; |
463 | SmallVector<SharedFile *, 0> sharedFiles; |
464 | SmallVector<BinaryFile *, 0> binaryFiles; |
465 | SmallVector<BitcodeFile *, 0> bitcodeFiles; |
466 | SmallVector<BitcodeFile *, 0> lazyBitcodeFiles; |
467 | SmallVector<InputSectionBase *, 0> inputSections; |
468 | SmallVector<EhInputSection *, 0> ehInputSections; |
469 | // Duplicate symbol candidates. |
470 | SmallVector<DuplicateSymbol, 0> duplicates; |
471 | // Symbols in a non-prevailing COMDAT group which should be changed to an |
472 | // Undefined. |
473 | SmallVector<std::pair<Symbol *, unsigned>, 0> nonPrevailingSyms; |
474 | // A tuple of (reference, extractedFile, sym). Used by --why-extract=. |
475 | SmallVector<std::tuple<std::string, const InputFile *, const Symbol &>, 0> |
476 | ; |
477 | // A mapping from a symbol to an InputFile referencing it backward. Used by |
478 | // --warn-backrefs. |
479 | llvm::DenseMap<const Symbol *, |
480 | std::pair<const InputFile *, const InputFile *>> |
481 | backwardReferences; |
482 | llvm::SmallSet<llvm::StringRef, 0> auxiliaryFiles; |
483 | // InputFile for linker created symbols with no source location. |
484 | InputFile *internalFile; |
485 | // True if SHT_LLVM_SYMPART is used. |
486 | std::atomic<bool> hasSympart{false}; |
487 | // True if there are TLS IE relocations. Set DF_STATIC_TLS if -shared. |
488 | std::atomic<bool> hasTlsIe{false}; |
489 | // True if we need to reserve two .got entries for local-dynamic TLS model. |
490 | std::atomic<bool> needsTlsLd{false}; |
491 | // True if all native vtable symbols have corresponding type info symbols |
492 | // during LTO. |
493 | bool ltoAllVtablesHaveTypeInfos; |
494 | |
495 | // Each symbol assignment and DEFINED(sym) reference is assigned an increasing |
496 | // order. Each DEFINED(sym) evaluation checks whether the reference happens |
497 | // before a possible `sym = expr;`. |
498 | unsigned scriptSymOrderCounter = 1; |
499 | llvm::DenseMap<const Symbol *, unsigned> scriptSymOrder; |
500 | |
501 | void reset(); |
502 | |
503 | llvm::raw_fd_ostream openAuxiliaryFile(llvm::StringRef, std::error_code &); |
504 | |
505 | ArrayRef<uint8_t> aarch64PauthAbiCoreInfo; |
506 | }; |
507 | |
508 | LLVM_LIBRARY_VISIBILITY extern Ctx ctx; |
509 | |
510 | // The first two elements of versionDefinitions represent VER_NDX_LOCAL and |
511 | // VER_NDX_GLOBAL. This helper returns other elements. |
512 | static inline ArrayRef<VersionDefinition> namedVersionDefs() { |
513 | return llvm::ArrayRef(config->versionDefinitions).slice(N: 2); |
514 | } |
515 | |
516 | void errorOrWarn(const Twine &msg); |
517 | |
518 | static inline void internalLinkerError(StringRef loc, const Twine &msg) { |
519 | errorOrWarn(msg: loc + "internal linker error: " + msg + "\n" + |
520 | llvm::getBugReportMsg()); |
521 | } |
522 | |
523 | } // namespace lld::elf |
524 | |
525 | #endif |
526 | |