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