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

source code of lld/ELF/Config.h