xref: /freebsd/contrib/llvm-project/lld/ELF/Config.h (revision fcaf7f8644a9988098ac6be2165bce3ea4786e91)
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 
294   // The following config options do not directly correspond to any
295   // particular command line options.
296 
297   // True if we need to pass through relocations in input files to the
298   // output file. Usually false because we consume relocations.
299   bool copyRelocs;
300 
301   // True if the target is ELF64. False if ELF32.
302   bool is64;
303 
304   // True if the target is little-endian. False if big-endian.
305   bool isLE;
306 
307   // endianness::little if isLE is true. endianness::big otherwise.
308   llvm::support::endianness endianness;
309 
310   // True if the target is the little-endian MIPS64.
311   //
312   // The reason why we have this variable only for the MIPS is because
313   // we use this often.  Some ELF headers for MIPS64EL are in a
314   // mixed-endian (which is horrible and I'd say that's a serious spec
315   // bug), and we need to know whether we are reading MIPS ELF files or
316   // not in various places.
317   //
318   // (Note that MIPS64EL is not a typo for MIPS64LE. This is the official
319   // name whatever that means. A fun hypothesis is that "EL" is short for
320   // little-endian written in the little-endian order, but I don't know
321   // if that's true.)
322   bool isMips64EL;
323 
324   // True if we need to reserve two .got entries for local-dynamic TLS model.
325   bool needsTlsLd = false;
326 
327   // True if we need to set the DF_STATIC_TLS flag to an output file, which
328   // works as a hint to the dynamic loader that the shared object contains code
329   // compiled with the initial-exec TLS model.
330   bool hasTlsIe = false;
331 
332   // Holds set of ELF header flags for the target.
333   uint32_t eflags = 0;
334 
335   // The ELF spec defines two types of relocation table entries, RELA and
336   // REL. RELA is a triplet of (offset, info, addend) while REL is a
337   // tuple of (offset, info). Addends for REL are implicit and read from
338   // the location where the relocations are applied. So, REL is more
339   // compact than RELA but requires a bit of more work to process.
340   //
341   // (From the linker writer's view, this distinction is not necessary.
342   // If the ELF had chosen whichever and sticked with it, it would have
343   // been easier to write code to process relocations, but it's too late
344   // to change the spec.)
345   //
346   // Each ABI defines its relocation type. IsRela is true if target
347   // uses RELA. As far as we know, all 64-bit ABIs are using RELA. A
348   // few 32-bit ABIs are using RELA too.
349   bool isRela;
350 
351   // True if we are creating position-independent code.
352   bool isPic;
353 
354   // 4 for ELF32, 8 for ELF64.
355   int wordsize;
356 
357   // Mode of MTE to write to the ELF note. Should be one of NT_MEMTAG_ASYNC (for
358   // async), NT_MEMTAG_SYNC (for sync), or NT_MEMTAG_LEVEL_NONE (for none). If
359   // async or sync is enabled, write the ELF note specifying the default MTE
360   // mode.
361   int androidMemtagMode;
362   // Signal to the dynamic loader to enable heap MTE.
363   bool androidMemtagHeap;
364   // Signal to the dynamic loader that this binary expects stack MTE. Generally,
365   // this means to map the primary and thread stacks as PROT_MTE. Note: This is
366   // not supported on Android 11 & 12.
367   bool androidMemtagStack;
368 };
369 
370 // The only instance of Configuration struct.
371 extern std::unique_ptr<Configuration> config;
372 
373 struct DuplicateSymbol {
374   const Symbol *sym;
375   const InputFile *file;
376   InputSectionBase *section;
377   uint64_t value;
378 };
379 
380 struct Ctx {
381   SmallVector<std::unique_ptr<MemoryBuffer>> memoryBuffers;
382   SmallVector<ELFFileBase *, 0> objectFiles;
383   SmallVector<SharedFile *, 0> sharedFiles;
384   SmallVector<BinaryFile *, 0> binaryFiles;
385   SmallVector<BitcodeFile *, 0> bitcodeFiles;
386   SmallVector<BitcodeFile *, 0> lazyBitcodeFiles;
387   // Duplicate symbol candidates.
388   SmallVector<DuplicateSymbol, 0> duplicates;
389   // Symbols in a non-prevailing COMDAT group which should be changed to an
390   // Undefined.
391   SmallVector<std::pair<Symbol *, unsigned>, 0> nonPrevailingSyms;
392   // True if SHT_LLVM_SYMPART is used.
393   std::atomic<bool> hasSympart{false};
394   // A tuple of (reference, extractedFile, sym). Used by --why-extract=.
395   SmallVector<std::tuple<std::string, const InputFile *, const Symbol &>, 0>
396       whyExtractRecords;
397   // A mapping from a symbol to an InputFile referencing it backward. Used by
398   // --warn-backrefs.
399   llvm::DenseMap<const Symbol *,
400                  std::pair<const InputFile *, const InputFile *>>
401       backwardReferences;
402 };
403 
404 // The only instance of Ctx struct.
405 extern std::unique_ptr<Ctx> ctx;
406 
407 // The first two elements of versionDefinitions represent VER_NDX_LOCAL and
408 // VER_NDX_GLOBAL. This helper returns other elements.
409 static inline ArrayRef<VersionDefinition> namedVersionDefs() {
410   return llvm::makeArrayRef(config->versionDefinitions).slice(2);
411 }
412 
413 void errorOrWarn(const Twine &msg);
414 
415 static inline void internalLinkerError(StringRef loc, const Twine &msg) {
416   errorOrWarn(loc + "internal linker error: " + msg + "\n" +
417               llvm::getBugReportMsg());
418 }
419 
420 } // namespace elf
421 } // namespace lld
422 
423 #endif
424