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