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