xref: /freebsd/contrib/llvm-project/lld/ELF/Config.h (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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/MapVector.h"
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/BinaryFormat/ELF.h"
19 #include "llvm/Support/CachePruning.h"
20 #include "llvm/Support/CodeGen.h"
21 #include "llvm/Support/Endian.h"
22 #include "llvm/Support/GlobPattern.h"
23 #include "llvm/Support/PrettyStackTrace.h"
24 #include <atomic>
25 #include <vector>
26 
27 namespace lld {
28 namespace elf {
29 
30 class InputFile;
31 class InputSectionBase;
32 
33 enum ELFKind {
34   ELFNoneKind,
35   ELF32LEKind,
36   ELF32BEKind,
37   ELF64LEKind,
38   ELF64BEKind
39 };
40 
41 // For -Bno-symbolic, -Bsymbolic-non-weak-functions, -Bsymbolic-functions,
42 // -Bsymbolic.
43 enum class BsymbolicKind { None, NonWeakFunctions, Functions, All };
44 
45 // For --build-id.
46 enum class BuildIdKind { None, Fast, Md5, Sha1, Hexstring, Uuid };
47 
48 // For --discard-{all,locals,none}.
49 enum class DiscardPolicy { Default, All, Locals, None };
50 
51 // For --icf={none,safe,all}.
52 enum class ICFLevel { None, Safe, All };
53 
54 // For --strip-{all,debug}.
55 enum class StripPolicy { None, All, Debug };
56 
57 // For --unresolved-symbols.
58 enum class UnresolvedPolicy { ReportError, Warn, Ignore };
59 
60 // For --orphan-handling.
61 enum class OrphanHandlingPolicy { Place, Warn, Error };
62 
63 // For --sort-section and linkerscript sorting rules.
64 enum class SortSectionPolicy { Default, None, Alignment, Name, Priority };
65 
66 // For --target2
67 enum class Target2Policy { Abs, Rel, GotRel };
68 
69 // For tracking ARM Float Argument PCS
70 enum class ARMVFPArgKind { Default, Base, VFP, ToolChain };
71 
72 // For -z noseparate-code, -z separate-code and -z separate-loadable-segments.
73 enum class SeparateSegmentKind { None, Code, Loadable };
74 
75 // For -z *stack
76 enum class GnuStackKind { None, Exec, NoExec };
77 
78 struct SymbolVersion {
79   llvm::StringRef name;
80   bool isExternCpp;
81   bool hasWildcard;
82 };
83 
84 // This struct contains symbols version definition that
85 // can be found in version script if it is used for link.
86 struct VersionDefinition {
87   llvm::StringRef name;
88   uint16_t id;
89   std::vector<SymbolVersion> nonLocalPatterns;
90   std::vector<SymbolVersion> localPatterns;
91 };
92 
93 // This struct contains the global configuration for the linker.
94 // Most fields are direct mapping from the command line options
95 // and such fields have the same name as the corresponding options.
96 // Most fields are initialized by the driver.
97 struct Configuration {
98   uint8_t osabi = 0;
99   uint32_t andFeatures = 0;
100   llvm::CachePruningPolicy thinLTOCachePolicy;
101   llvm::SetVector<llvm::CachedHashString> dependencyFiles; // for --dependency-file
102   llvm::StringMap<uint64_t> sectionStartMap;
103   llvm::StringRef bfdname;
104   llvm::StringRef chroot;
105   llvm::StringRef dependencyFile;
106   llvm::StringRef dwoDir;
107   llvm::StringRef dynamicLinker;
108   llvm::StringRef entry;
109   llvm::StringRef emulation;
110   llvm::StringRef fini;
111   llvm::StringRef init;
112   llvm::StringRef ltoAAPipeline;
113   llvm::StringRef ltoCSProfileFile;
114   llvm::StringRef ltoNewPmPasses;
115   llvm::StringRef ltoObjPath;
116   llvm::StringRef ltoSampleProfile;
117   llvm::StringRef mapFile;
118   llvm::StringRef outputFile;
119   llvm::StringRef optRemarksFilename;
120   llvm::Optional<uint64_t> optRemarksHotnessThreshold = 0;
121   llvm::StringRef optRemarksPasses;
122   llvm::StringRef optRemarksFormat;
123   llvm::StringRef progName;
124   llvm::StringRef printArchiveStats;
125   llvm::StringRef printSymbolOrder;
126   llvm::StringRef soName;
127   llvm::StringRef sysroot;
128   llvm::StringRef thinLTOCacheDir;
129   llvm::StringRef thinLTOIndexOnlyArg;
130   llvm::StringRef whyExtract;
131   llvm::StringRef ltoBasicBlockSections;
132   std::pair<llvm::StringRef, llvm::StringRef> thinLTOObjectSuffixReplace;
133   std::pair<llvm::StringRef, llvm::StringRef> thinLTOPrefixReplace;
134   std::string rpath;
135   std::vector<VersionDefinition> versionDefinitions;
136   std::vector<llvm::StringRef> auxiliaryList;
137   std::vector<llvm::StringRef> filterList;
138   std::vector<llvm::StringRef> searchPaths;
139   std::vector<llvm::StringRef> symbolOrderingFile;
140   std::vector<llvm::StringRef> thinLTOModulesToCompile;
141   std::vector<llvm::StringRef> undefined;
142   std::vector<SymbolVersion> dynamicList;
143   std::vector<uint8_t> buildIdVector;
144   llvm::MapVector<std::pair<const InputSectionBase *, const InputSectionBase *>,
145                   uint64_t>
146       callGraphProfile;
147   bool allowMultipleDefinition;
148   bool androidPackDynRelocs;
149   bool armHasBlx = false;
150   bool armHasMovtMovw = false;
151   bool armJ1J2BranchEncoding = false;
152   bool asNeeded = false;
153   BsymbolicKind bsymbolic = BsymbolicKind::None;
154   bool callGraphProfileSort;
155   bool checkSections;
156   bool checkDynamicRelocs;
157   bool compressDebugSections;
158   bool cref;
159   std::vector<std::pair<llvm::GlobPattern, uint64_t>> deadRelocInNonAlloc;
160   bool defineCommon;
161   bool demangle = true;
162   bool dependentLibraries;
163   bool disableVerify;
164   bool ehFrameHdr;
165   bool emitLLVM;
166   bool emitRelocs;
167   bool enableNewDtags;
168   bool executeOnly;
169   bool exportDynamic;
170   bool fixCortexA53Errata843419;
171   bool fixCortexA8;
172   bool formatBinary = false;
173   bool fortranCommon;
174   bool gcSections;
175   bool gdbIndex;
176   bool gnuHash = false;
177   bool gnuUnique;
178   bool hasDynSymTab;
179   bool ignoreDataAddressEquality;
180   bool ignoreFunctionAddressEquality;
181   bool ltoCSProfileGenerate;
182   bool ltoPGOWarnMismatch;
183   bool ltoDebugPassManager;
184   bool ltoEmitAsm;
185   bool ltoNewPassManager;
186   bool ltoUniqueBasicBlockSectionNames;
187   bool ltoWholeProgramVisibility;
188   bool mergeArmExidx;
189   bool mipsN32Abi = false;
190   bool mmapOutputFile;
191   bool nmagic;
192   bool noDynamicLinker = false;
193   bool noinhibitExec;
194   bool nostdlib;
195   bool oFormatBinary;
196   bool omagic;
197   bool optEB = false;
198   bool optEL = false;
199   bool optimizeBBJumps;
200   bool optRemarksWithHotness;
201   bool picThunk;
202   bool pie;
203   bool printGcSections;
204   bool printIcfSections;
205   bool relax;
206   bool relocatable;
207   bool relrPackDynRelocs;
208   bool saveTemps;
209   std::vector<std::pair<llvm::GlobPattern, uint32_t>> shuffleSections;
210   bool singleRoRx;
211   bool shared;
212   bool symbolic;
213   bool isStatic = false;
214   bool sysvHash = false;
215   bool target1Rel;
216   bool trace;
217   bool thinLTOEmitImportsFiles;
218   bool thinLTOIndexOnly;
219   bool timeTraceEnabled;
220   bool tocOptimize;
221   bool pcRelOptimize;
222   bool undefinedVersion;
223   bool unique;
224   bool useAndroidRelrTags = false;
225   bool warnBackrefs;
226   std::vector<llvm::GlobPattern> warnBackrefsExclude;
227   bool warnCommon;
228   bool warnMissingEntry;
229   bool warnSymbolOrdering;
230   bool writeAddends;
231   bool zCombreloc;
232   bool zCopyreloc;
233   bool zForceBti;
234   bool zForceIbt;
235   bool zGlobal;
236   bool zHazardplt;
237   bool zIfuncNoplt;
238   bool zInitfirst;
239   bool zInterpose;
240   bool zKeepTextSectionPrefix;
241   bool zNodefaultlib;
242   bool zNodelete;
243   bool zNodlopen;
244   bool zNow;
245   bool zOrigin;
246   bool zPacPlt;
247   bool zRelro;
248   bool zRodynamic;
249   bool zShstk;
250   bool zStartStopGC;
251   uint8_t zStartStopVisibility;
252   bool zText;
253   bool zRetpolineplt;
254   bool zWxneeded;
255   DiscardPolicy discard;
256   GnuStackKind zGnustack;
257   ICFLevel icf;
258   OrphanHandlingPolicy orphanHandling;
259   SortSectionPolicy sortSection;
260   StripPolicy strip;
261   UnresolvedPolicy unresolvedSymbols;
262   UnresolvedPolicy unresolvedSymbolsInShlib;
263   Target2Policy target2;
264   bool Power10Stub;
265   ARMVFPArgKind armVFPArgs = ARMVFPArgKind::Default;
266   BuildIdKind buildId = BuildIdKind::None;
267   SeparateSegmentKind zSeparate;
268   ELFKind ekind = ELFNoneKind;
269   uint16_t emachine = llvm::ELF::EM_NONE;
270   llvm::Optional<uint64_t> imageBase;
271   uint64_t commonPageSize;
272   uint64_t maxPageSize;
273   uint64_t mipsGotSize;
274   uint64_t zStackSize;
275   unsigned ltoPartitions;
276   unsigned ltoo;
277   unsigned optimize;
278   StringRef thinLTOJobs;
279   unsigned timeTraceGranularity;
280   int32_t splitStackAdjustSize;
281 
282   // The following config options do not directly correspond to any
283   // particular command line options.
284 
285   // True if we need to pass through relocations in input files to the
286   // output file. Usually false because we consume relocations.
287   bool copyRelocs;
288 
289   // True if the target is ELF64. False if ELF32.
290   bool is64;
291 
292   // True if the target is little-endian. False if big-endian.
293   bool isLE;
294 
295   // endianness::little if isLE is true. endianness::big otherwise.
296   llvm::support::endianness endianness;
297 
298   // True if the target is the little-endian MIPS64.
299   //
300   // The reason why we have this variable only for the MIPS is because
301   // we use this often.  Some ELF headers for MIPS64EL are in a
302   // mixed-endian (which is horrible and I'd say that's a serious spec
303   // bug), and we need to know whether we are reading MIPS ELF files or
304   // not in various places.
305   //
306   // (Note that MIPS64EL is not a typo for MIPS64LE. This is the official
307   // name whatever that means. A fun hypothesis is that "EL" is short for
308   // little-endian written in the little-endian order, but I don't know
309   // if that's true.)
310   bool isMips64EL;
311 
312   // True if we need to set the DF_STATIC_TLS flag to an output file,
313   // which works as a hint to the dynamic loader that the file contains
314   // code compiled with the static TLS model. The thread-local variable
315   // compiled with the static TLS model is faster but less flexible, and
316   // it may not be loaded using dlopen().
317   //
318   // We set this flag to true when we see a relocation for the static TLS
319   // model. Once this becomes true, it will never become false.
320   //
321   // Since the flag is updated by multi-threaded code, we use std::atomic.
322   // (Writing to a variable is not considered thread-safe even if the
323   // variable is boolean and we always set the same value from all threads.)
324   std::atomic<bool> hasStaticTlsModel{false};
325 
326   // Holds set of ELF header flags for the target.
327   uint32_t eflags = 0;
328 
329   // The ELF spec defines two types of relocation table entries, RELA and
330   // REL. RELA is a triplet of (offset, info, addend) while REL is a
331   // tuple of (offset, info). Addends for REL are implicit and read from
332   // the location where the relocations are applied. So, REL is more
333   // compact than RELA but requires a bit of more work to process.
334   //
335   // (From the linker writer's view, this distinction is not necessary.
336   // If the ELF had chosen whichever and sticked with it, it would have
337   // been easier to write code to process relocations, but it's too late
338   // to change the spec.)
339   //
340   // Each ABI defines its relocation type. IsRela is true if target
341   // uses RELA. As far as we know, all 64-bit ABIs are using RELA. A
342   // few 32-bit ABIs are using RELA too.
343   bool isRela;
344 
345   // True if we are creating position-independent code.
346   bool isPic;
347 
348   // 4 for ELF32, 8 for ELF64.
349   int wordsize;
350 };
351 
352 // The only instance of Configuration struct.
353 extern Configuration *config;
354 
355 // The first two elements of versionDefinitions represent VER_NDX_LOCAL and
356 // VER_NDX_GLOBAL. This helper returns other elements.
357 static inline ArrayRef<VersionDefinition> namedVersionDefs() {
358   return llvm::makeArrayRef(config->versionDefinitions).slice(2);
359 }
360 
361 static inline void errorOrWarn(const Twine &msg) {
362   if (!config->noinhibitExec)
363     error(msg);
364   else
365     warn(msg);
366 }
367 
368 static inline void internalLinkerError(StringRef loc, const Twine &msg) {
369   errorOrWarn(loc + "internal linker error: " + msg + "\n" +
370               llvm::getBugReportMsg());
371 }
372 
373 } // namespace elf
374 } // namespace lld
375 
376 #endif
377