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