xref: /freebsd/contrib/llvm-project/lld/ELF/Config.h (revision 9f23cbd6cae82fd77edfad7173432fa8dccd0a95)
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 zNodefaultlib;
286   bool zNodelete;
287   bool zNodlopen;
288   bool zNow;
289   bool zOrigin;
290   bool zPacPlt;
291   bool zRelro;
292   bool zRodynamic;
293   bool zShstk;
294   bool zStartStopGC;
295   uint8_t zStartStopVisibility;
296   bool zText;
297   bool zRetpolineplt;
298   bool zWxneeded;
299   DiscardPolicy discard;
300   GnuStackKind zGnustack;
301   ICFLevel icf;
302   OrphanHandlingPolicy orphanHandling;
303   SortSectionPolicy sortSection;
304   StripPolicy strip;
305   UnresolvedPolicy unresolvedSymbols;
306   UnresolvedPolicy unresolvedSymbolsInShlib;
307   Target2Policy target2;
308   bool power10Stubs;
309   ARMVFPArgKind armVFPArgs = ARMVFPArgKind::Default;
310   BuildIdKind buildId = BuildIdKind::None;
311   SeparateSegmentKind zSeparate;
312   ELFKind ekind = ELFNoneKind;
313   uint16_t emachine = llvm::ELF::EM_NONE;
314   std::optional<uint64_t> imageBase;
315   uint64_t commonPageSize;
316   uint64_t maxPageSize;
317   uint64_t mipsGotSize;
318   uint64_t zStackSize;
319   unsigned ltoPartitions;
320   unsigned ltoo;
321   unsigned optimize;
322   StringRef thinLTOJobs;
323   unsigned timeTraceGranularity;
324   int32_t splitStackAdjustSize;
325   StringRef packageMetadata;
326 
327   // The following config options do not directly correspond to any
328   // particular command line options.
329 
330   // True if we need to pass through relocations in input files to the
331   // output file. Usually false because we consume relocations.
332   bool copyRelocs;
333 
334   // True if the target is ELF64. False if ELF32.
335   bool is64;
336 
337   // True if the target is little-endian. False if big-endian.
338   bool isLE;
339 
340   // endianness::little if isLE is true. endianness::big otherwise.
341   llvm::support::endianness endianness;
342 
343   // True if the target is the little-endian MIPS64.
344   //
345   // The reason why we have this variable only for the MIPS is because
346   // we use this often.  Some ELF headers for MIPS64EL are in a
347   // mixed-endian (which is horrible and I'd say that's a serious spec
348   // bug), and we need to know whether we are reading MIPS ELF files or
349   // not in various places.
350   //
351   // (Note that MIPS64EL is not a typo for MIPS64LE. This is the official
352   // name whatever that means. A fun hypothesis is that "EL" is short for
353   // little-endian written in the little-endian order, but I don't know
354   // if that's true.)
355   bool isMips64EL;
356 
357   // True if we need to set the DF_STATIC_TLS flag to an output file, which
358   // works as a hint to the dynamic loader that the shared object contains code
359   // compiled with the initial-exec TLS model.
360   bool hasTlsIe = false;
361 
362   // Holds set of ELF header flags for the target.
363   uint32_t eflags = 0;
364 
365   // The ELF spec defines two types of relocation table entries, RELA and
366   // REL. RELA is a triplet of (offset, info, addend) while REL is a
367   // tuple of (offset, info). Addends for REL are implicit and read from
368   // the location where the relocations are applied. So, REL is more
369   // compact than RELA but requires a bit of more work to process.
370   //
371   // (From the linker writer's view, this distinction is not necessary.
372   // If the ELF had chosen whichever and sticked with it, it would have
373   // been easier to write code to process relocations, but it's too late
374   // to change the spec.)
375   //
376   // Each ABI defines its relocation type. IsRela is true if target
377   // uses RELA. As far as we know, all 64-bit ABIs are using RELA. A
378   // few 32-bit ABIs are using RELA too.
379   bool isRela;
380 
381   // True if we are creating position-independent code.
382   bool isPic;
383 
384   // 4 for ELF32, 8 for ELF64.
385   int wordsize;
386 
387   // Mode of MTE to write to the ELF note. Should be one of NT_MEMTAG_ASYNC (for
388   // async), NT_MEMTAG_SYNC (for sync), or NT_MEMTAG_LEVEL_NONE (for none). If
389   // async or sync is enabled, write the ELF note specifying the default MTE
390   // mode.
391   int androidMemtagMode;
392   // Signal to the dynamic loader to enable heap MTE.
393   bool androidMemtagHeap;
394   // Signal to the dynamic loader that this binary expects stack MTE. Generally,
395   // this means to map the primary and thread stacks as PROT_MTE. Note: This is
396   // not supported on Android 11 & 12.
397   bool androidMemtagStack;
398 
399   unsigned threadCount;
400 };
401 struct ConfigWrapper {
402   Config c;
403   Config *operator->() { return &c; }
404 };
405 
406 LLVM_LIBRARY_VISIBILITY extern ConfigWrapper config;
407 
408 struct DuplicateSymbol {
409   const Symbol *sym;
410   const InputFile *file;
411   InputSectionBase *section;
412   uint64_t value;
413 };
414 
415 struct Ctx {
416   LinkerDriver driver;
417   SmallVector<std::unique_ptr<MemoryBuffer>> memoryBuffers;
418   SmallVector<ELFFileBase *, 0> objectFiles;
419   SmallVector<SharedFile *, 0> sharedFiles;
420   SmallVector<BinaryFile *, 0> binaryFiles;
421   SmallVector<BitcodeFile *, 0> bitcodeFiles;
422   SmallVector<BitcodeFile *, 0> lazyBitcodeFiles;
423   SmallVector<InputSectionBase *, 0> inputSections;
424   SmallVector<EhInputSection *, 0> ehInputSections;
425   // Duplicate symbol candidates.
426   SmallVector<DuplicateSymbol, 0> duplicates;
427   // Symbols in a non-prevailing COMDAT group which should be changed to an
428   // Undefined.
429   SmallVector<std::pair<Symbol *, unsigned>, 0> nonPrevailingSyms;
430   // A tuple of (reference, extractedFile, sym). Used by --why-extract=.
431   SmallVector<std::tuple<std::string, const InputFile *, const Symbol &>, 0>
432       whyExtractRecords;
433   // A mapping from a symbol to an InputFile referencing it backward. Used by
434   // --warn-backrefs.
435   llvm::DenseMap<const Symbol *,
436                  std::pair<const InputFile *, const InputFile *>>
437       backwardReferences;
438   // True if SHT_LLVM_SYMPART is used.
439   std::atomic<bool> hasSympart{false};
440   // True if there are TLS IE relocations. Set DF_STATIC_TLS if -shared.
441   std::atomic<bool> hasTlsIe{false};
442   // True if we need to reserve two .got entries for local-dynamic TLS model.
443   std::atomic<bool> needsTlsLd{false};
444 
445   void reset();
446 };
447 
448 LLVM_LIBRARY_VISIBILITY extern Ctx ctx;
449 
450 // The first two elements of versionDefinitions represent VER_NDX_LOCAL and
451 // VER_NDX_GLOBAL. This helper returns other elements.
452 static inline ArrayRef<VersionDefinition> namedVersionDefs() {
453   return llvm::ArrayRef(config->versionDefinitions).slice(2);
454 }
455 
456 void errorOrWarn(const Twine &msg);
457 
458 static inline void internalLinkerError(StringRef loc, const Twine &msg) {
459   errorOrWarn(loc + "internal linker error: " + msg + "\n" +
460               llvm::getBugReportMsg());
461 }
462 
463 } // namespace lld::elf
464 
465 #endif
466