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/CommonLinkerContext.h"
13#include "lld/Common/ErrorHandler.h"
14#include "llvm/ADT/CachedHashString.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/StringSet.h"
21#include "llvm/BinaryFormat/ELF.h"
22#include "llvm/Option/ArgList.h"
23#include "llvm/Support/CachePruning.h"
24#include "llvm/Support/CodeGen.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/Compression.h"
27#include "llvm/Support/Endian.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/GlobPattern.h"
30#include "llvm/Support/TarWriter.h"
31#include <atomic>
32#include <memory>
33#include <mutex>
34#include <optional>
35#include <vector>
36
37namespace lld::elf {
38
39class InputFile;
40class BinaryFile;
41class BitcodeFile;
42class ELFFileBase;
43class SharedFile;
44class InputSectionBase;
45class EhInputSection;
46class Defined;
47class Undefined;
48class Symbol;
49class SymbolTable;
50class BitcodeCompiler;
51class OutputSection;
52class LinkerScript;
53class TargetInfo;
54struct Ctx;
55struct Partition;
56struct PhdrEntry;
57
58class BssSection;
59class GdbIndexSection;
60class GotPltSection;
61class GotSection;
62class IBTPltSection;
63class IgotPltSection;
64class InputSection;
65class IpltSection;
66class MipsGotSection;
67class MipsRldMapSection;
68class PPC32Got2Section;
69class PPC64LongBranchTargetSection;
70class PltSection;
71class RelocationBaseSection;
72class RelroPaddingSection;
73class StringTableSection;
74class SymbolTableBaseSection;
75class SymtabShndxSection;
76class SyntheticSection;
77
78enum ELFKind : uint8_t {
79 ELFNoneKind,
80 ELF32LEKind,
81 ELF32BEKind,
82 ELF64LEKind,
83 ELF64BEKind
84};
85
86// For -Bno-symbolic, -Bsymbolic-non-weak-functions, -Bsymbolic-functions,
87// -Bsymbolic-non-weak, -Bsymbolic.
88enum class BsymbolicKind { None, NonWeakFunctions, Functions, NonWeak, All };
89
90// For --build-id.
91enum class BuildIdKind { None, Fast, Md5, Sha1, Hexstring, Uuid };
92
93// For --call-graph-profile-sort={none,hfsort,cdsort}.
94enum class CGProfileSortKind { None, Hfsort, Cdsort };
95
96// For --discard-{all,locals,none}.
97enum class DiscardPolicy { Default, All, Locals, None };
98
99// For --icf={none,safe,all}.
100enum class ICFLevel { None, Safe, All };
101
102// For --strip-{all,debug}.
103enum class StripPolicy { None, All, Debug };
104
105// For --unresolved-symbols.
106enum class UnresolvedPolicy { ReportError, Warn, Ignore };
107
108// For --orphan-handling.
109enum class OrphanHandlingPolicy { Place, Warn, Error };
110
111// For --sort-section and linkerscript sorting rules.
112enum class SortSectionPolicy {
113 Default,
114 None,
115 Alignment,
116 Name,
117 Priority,
118 Reverse,
119};
120
121// For --target2
122enum class Target2Policy { Abs, Rel, GotRel };
123
124// For tracking ARM Float Argument PCS
125enum class ARMVFPArgKind { Default, Base, VFP, ToolChain };
126
127// For -z noseparate-code, -z separate-code and -z separate-loadable-segments.
128enum class SeparateSegmentKind { None, Code, Loadable };
129
130// For -z *stack
131enum class GnuStackKind { None, Exec, NoExec };
132
133// For --lto=
134enum LtoKind : uint8_t {UnifiedThin, UnifiedRegular, Default};
135
136// For -z gcs=
137enum class GcsPolicy { Implicit, Never, Always };
138
139// For some options that resemble -z bti-report={none,warning,error}
140enum class ReportPolicy { None, Warning, Error };
141
142struct SymbolVersion {
143 llvm::StringRef name;
144 bool isExternCpp;
145 bool hasWildcard;
146};
147
148// This struct contains symbols version definition that
149// can be found in version script if it is used for link.
150struct VersionDefinition {
151 llvm::StringRef name;
152 uint16_t id;
153 SmallVector<SymbolVersion, 0> nonLocalPatterns;
154 SmallVector<SymbolVersion, 0> localPatterns;
155};
156
157class LinkerDriver {
158public:
159 LinkerDriver(Ctx &ctx);
160 LinkerDriver(LinkerDriver &) = delete;
161 void linkerMain(ArrayRef<const char *> args);
162 void addFile(StringRef path, bool withLOption);
163 void addLibrary(StringRef name);
164
165private:
166 Ctx &ctx;
167 void createFiles(llvm::opt::InputArgList &args);
168 void inferMachineType();
169 template <class ELFT> void link(llvm::opt::InputArgList &args);
170 template <class ELFT> void compileBitcodeFiles(bool skipLinkedOutput);
171 bool tryAddFatLTOFile(MemoryBufferRef mb, StringRef archiveName,
172 uint64_t offsetInArchive, bool lazy);
173 // True if we are in --whole-archive and --no-whole-archive.
174 bool inWholeArchive = false;
175
176 // True if we are in --start-lib and --end-lib.
177 bool inLib = false;
178
179 std::unique_ptr<BitcodeCompiler> lto;
180 SmallVector<std::unique_ptr<InputFile>, 0> files, ltoObjectFiles;
181
182public:
183 // See InputFile::groupId.
184 uint32_t nextGroupId;
185 bool isInGroup;
186 std::unique_ptr<InputFile> armCmseImpLib;
187 SmallVector<std::pair<StringRef, unsigned>, 0> archiveFiles;
188};
189
190// This struct contains the global configuration for the linker.
191// Most fields are direct mapping from the command line options
192// and such fields have the same name as the corresponding options.
193// Most fields are initialized by the ctx.driver.
194struct Config {
195 uint8_t osabi = 0;
196 uint32_t andFeatures = 0;
197 llvm::CachePruningPolicy thinLTOCachePolicy;
198 llvm::SetVector<llvm::CachedHashString> dependencyFiles; // for --dependency-file
199 llvm::StringMap<uint64_t> sectionStartMap;
200 llvm::StringRef bfdname;
201 llvm::StringRef chroot;
202 llvm::StringRef dependencyFile;
203 llvm::StringRef dwoDir;
204 llvm::StringRef dynamicLinker;
205 llvm::StringRef entry;
206 llvm::StringRef emulation;
207 llvm::StringRef fini;
208 llvm::StringRef init;
209 llvm::StringRef ltoAAPipeline;
210 llvm::StringRef ltoCSProfileFile;
211 llvm::StringRef ltoNewPmPasses;
212 llvm::StringRef ltoObjPath;
213 llvm::StringRef ltoSampleProfile;
214 llvm::StringRef mapFile;
215 llvm::StringRef outputFile;
216 llvm::StringRef optRemarksFilename;
217 std::optional<uint64_t> optRemarksHotnessThreshold = 0;
218 llvm::StringRef optRemarksPasses;
219 llvm::StringRef optRemarksFormat;
220 llvm::StringRef optStatsFilename;
221 llvm::StringRef progName;
222 llvm::StringRef printArchiveStats;
223 llvm::StringRef printSymbolOrder;
224 llvm::StringRef soName;
225 llvm::StringRef sysroot;
226 llvm::StringRef thinLTOCacheDir;
227 llvm::StringRef thinLTOIndexOnlyArg;
228 llvm::StringRef whyExtract;
229 llvm::SmallVector<llvm::GlobPattern, 0> whyLive;
230 llvm::StringRef cmseInputLib;
231 llvm::StringRef cmseOutputLib;
232 ReportPolicy zBtiReport = ReportPolicy::None;
233 ReportPolicy zCetReport = ReportPolicy::None;
234 ReportPolicy zPauthReport = ReportPolicy::None;
235 ReportPolicy zGcsReport = ReportPolicy::None;
236 ReportPolicy zGcsReportDynamic = ReportPolicy::None;
237 ReportPolicy zExecuteOnlyReport = ReportPolicy::None;
238 ReportPolicy zZicfilpUnlabeledReport = ReportPolicy::None;
239 ReportPolicy zZicfilpFuncSigReport = ReportPolicy::None;
240 ReportPolicy zZicfissReport = ReportPolicy::None;
241 bool ltoBBAddrMap;
242 llvm::StringRef ltoBasicBlockSections;
243 std::pair<llvm::StringRef, llvm::StringRef> thinLTOObjectSuffixReplace;
244 llvm::StringRef thinLTOPrefixReplaceOld;
245 llvm::StringRef thinLTOPrefixReplaceNew;
246 llvm::StringRef thinLTOPrefixReplaceNativeObject;
247 std::string rpath;
248 llvm::SmallVector<VersionDefinition, 0> versionDefinitions;
249 llvm::SmallVector<llvm::StringRef, 0> auxiliaryList;
250 llvm::SmallVector<llvm::StringRef, 0> filterList;
251 llvm::SmallVector<llvm::StringRef, 0> passPlugins;
252 llvm::SmallVector<llvm::StringRef, 0> searchPaths;
253 llvm::SmallVector<llvm::StringRef, 0> symbolOrderingFile;
254 llvm::SmallVector<llvm::StringRef, 0> thinLTOModulesToCompile;
255 llvm::SmallVector<llvm::StringRef, 0> undefined;
256 llvm::SmallVector<SymbolVersion, 0> dynamicList;
257 llvm::SmallVector<uint8_t, 0> buildIdVector;
258 llvm::SmallVector<llvm::StringRef, 0> mllvmOpts;
259 llvm::MapVector<std::pair<const InputSectionBase *, const InputSectionBase *>,
260 uint64_t>
261 callGraphProfile;
262 bool cmseImplib = false;
263 bool allowMultipleDefinition;
264 bool fatLTOObjects;
265 bool androidPackDynRelocs = false;
266 bool armHasArmISA = false;
267 bool armHasThumb2ISA = false;
268 bool armHasBlx = false;
269 bool armHasMovtMovw = false;
270 bool armJ1J2BranchEncoding = false;
271 bool armCMSESupport = false;
272 bool asNeeded = false;
273 bool armBe8 = false;
274 BsymbolicKind bsymbolic = BsymbolicKind::None;
275 CGProfileSortKind callGraphProfileSort;
276 llvm::StringRef irpgoProfilePath;
277 bool bpStartupFunctionSort = false;
278 bool bpCompressionSortStartupFunctions = false;
279 bool bpFunctionOrderForCompression = false;
280 bool bpDataOrderForCompression = false;
281 bool bpVerboseSectionOrderer = false;
282 bool checkSections;
283 bool checkDynamicRelocs;
284 std::optional<llvm::DebugCompressionType> compressDebugSections;
285 llvm::SmallVector<
286 std::tuple<llvm::GlobPattern, llvm::DebugCompressionType, unsigned>, 0>
287 compressSections;
288 bool cref;
289 llvm::SmallVector<std::pair<llvm::GlobPattern, uint64_t>, 0>
290 deadRelocInNonAlloc;
291 bool debugNames;
292 bool demangle = true;
293 bool dependentLibraries;
294 bool disableVerify;
295 bool ehFrameHdr;
296 bool emitLLVM;
297 bool emitRelocs;
298 bool enableNewDtags;
299 bool enableNonContiguousRegions;
300 bool executeOnly;
301 bool exportDynamic;
302 bool fixCortexA53Errata843419;
303 bool fixCortexA8;
304 bool formatBinary = false;
305 bool fortranCommon;
306 bool gcSections;
307 bool gdbIndex;
308 bool gnuHash = false;
309 bool gnuUnique;
310 bool ignoreDataAddressEquality;
311 bool ignoreFunctionAddressEquality;
312 bool ltoCSProfileGenerate;
313 bool ltoPGOWarnMismatch;
314 bool ltoDebugPassManager;
315 bool ltoEmitAsm;
316 bool ltoUniqueBasicBlockSectionNames;
317 bool ltoValidateAllVtablesHaveTypeInfos;
318 bool ltoWholeProgramVisibility;
319 bool mergeArmExidx;
320 bool mipsN32Abi = false;
321 bool mmapOutputFile;
322 bool nmagic;
323 bool noinhibitExec;
324 bool nostdlib;
325 bool oFormatBinary;
326 bool omagic;
327 bool optEB = false;
328 bool optEL = false;
329 bool optimizeBBJumps;
330 bool optRemarksWithHotness;
331 bool picThunk;
332 bool pie;
333 bool printGcSections;
334 bool printIcfSections;
335 bool printMemoryUsage;
336 std::optional<uint64_t> randomizeSectionPadding;
337 bool rejectMismatch;
338 bool relax;
339 bool relaxGP;
340 bool relocatable;
341 bool resolveGroups;
342 bool relrGlibc = false;
343 bool relrPackDynRelocs = false;
344 llvm::DenseSet<llvm::StringRef> saveTempsArgs;
345 llvm::SmallVector<std::pair<llvm::GlobPattern, uint32_t>, 0> shuffleSections;
346 bool singleRoRx;
347 bool singleXoRx;
348 bool shared;
349 bool symbolic;
350 bool isStatic = false;
351 bool sysvHash = false;
352 bool target1Rel;
353 bool trace;
354 bool thinLTOEmitImportsFiles;
355 bool thinLTOEmitIndexFiles;
356 bool thinLTOIndexOnly;
357 bool timeTraceEnabled;
358 bool tocOptimize;
359 bool pcRelOptimize;
360 bool undefinedVersion;
361 bool unique;
362 bool useAndroidRelrTags = false;
363 bool warnBackrefs;
364 llvm::SmallVector<llvm::GlobPattern, 0> warnBackrefsExclude;
365 bool warnCommon;
366 bool warnMissingEntry;
367 bool warnSymbolOrdering;
368 bool writeAddends;
369 bool zCombreloc;
370 bool zCopyreloc;
371 bool zForceBti;
372 bool zForceIbt;
373 bool zGlobal;
374 bool zHazardplt;
375 bool zIfuncNoplt;
376 bool zInitfirst;
377 bool zInterpose;
378 bool zKeepTextSectionPrefix;
379 bool zLrodataAfterBss;
380 bool zNoBtCfi;
381 bool zNodefaultlib;
382 bool zNodelete;
383 bool zNodlopen;
384 bool zNow;
385 bool zOrigin;
386 bool zPacPlt;
387 bool zRelro;
388 bool zRodynamic;
389 bool zSectionHeader;
390 bool zShstk;
391 bool zStartStopGC;
392 uint8_t zStartStopVisibility;
393 bool zText;
394 bool zRetpolineplt;
395 bool zWxneeded;
396 DiscardPolicy discard;
397 GnuStackKind zGnustack;
398 ICFLevel icf;
399 OrphanHandlingPolicy orphanHandling;
400 SortSectionPolicy sortSection;
401 StripPolicy strip;
402 UnresolvedPolicy unresolvedSymbols;
403 UnresolvedPolicy unresolvedSymbolsInShlib;
404 Target2Policy target2;
405 GcsPolicy zGcs;
406 bool power10Stubs;
407 ARMVFPArgKind armVFPArgs = ARMVFPArgKind::Default;
408 BuildIdKind buildId = BuildIdKind::None;
409 SeparateSegmentKind zSeparate;
410 ELFKind ekind = ELFNoneKind;
411 uint16_t emachine = llvm::ELF::EM_NONE;
412 std::optional<uint64_t> imageBase;
413 uint64_t commonPageSize;
414 uint64_t maxPageSize;
415 uint64_t mipsGotSize;
416 uint64_t zStackSize;
417 unsigned ltoPartitions;
418 unsigned ltoo;
419 llvm::CodeGenOptLevel ltoCgo;
420 unsigned optimize;
421 StringRef thinLTOJobs;
422 unsigned timeTraceGranularity;
423 int32_t splitStackAdjustSize;
424 SmallVector<uint8_t, 0> packageMetadata;
425
426 // The following config options do not directly correspond to any
427 // particular command line options.
428
429 // True if we need to pass through relocations in input files to the
430 // output file. Usually false because we consume relocations.
431 bool copyRelocs;
432
433 // True if the target is ELF64. False if ELF32.
434 bool is64;
435
436 // True if the target is little-endian. False if big-endian.
437 bool isLE;
438
439 // endianness::little if isLE is true. endianness::big otherwise.
440 llvm::endianness endianness;
441
442 // True if the target is the little-endian MIPS64.
443 //
444 // The reason why we have this variable only for the MIPS is because
445 // we use this often. Some ELF headers for MIPS64EL are in a
446 // mixed-endian (which is horrible and I'd say that's a serious spec
447 // bug), and we need to know whether we are reading MIPS ELF files or
448 // not in various places.
449 //
450 // (Note that MIPS64EL is not a typo for MIPS64LE. This is the official
451 // name whatever that means. A fun hypothesis is that "EL" is short for
452 // little-endian written in the little-endian order, but I don't know
453 // if that's true.)
454 bool isMips64EL;
455
456 // True if we need to set the DF_STATIC_TLS flag to an output file, which
457 // works as a hint to the dynamic loader that the shared object contains code
458 // compiled with the initial-exec TLS model.
459 bool hasTlsIe = false;
460
461 // Holds set of ELF header flags for the target.
462 uint32_t eflags = 0;
463
464 // The ELF spec defines two types of relocation table entries, RELA and
465 // REL. RELA is a triplet of (offset, info, addend) while REL is a
466 // tuple of (offset, info). Addends for REL are implicit and read from
467 // the location where the relocations are applied. So, REL is more
468 // compact than RELA but requires a bit of more work to process.
469 //
470 // (From the linker writer's view, this distinction is not necessary.
471 // If the ELF had chosen whichever and sticked with it, it would have
472 // been easier to write code to process relocations, but it's too late
473 // to change the spec.)
474 //
475 // Each ABI defines its relocation type. IsRela is true if target
476 // uses RELA. As far as we know, all 64-bit ABIs are using RELA. A
477 // few 32-bit ABIs are using RELA too.
478 bool isRela;
479
480 // True if we are creating position-independent code.
481 bool isPic;
482
483 // 4 for ELF32, 8 for ELF64.
484 int wordsize;
485
486 // Mode of MTE to write to the ELF note. Should be one of NT_MEMTAG_ASYNC (for
487 // async), NT_MEMTAG_SYNC (for sync), or NT_MEMTAG_LEVEL_NONE (for none). If
488 // async or sync is enabled, write the ELF note specifying the default MTE
489 // mode.
490 int androidMemtagMode;
491 // Signal to the dynamic loader to enable heap MTE.
492 bool androidMemtagHeap;
493 // Signal to the dynamic loader that this binary expects stack MTE. Generally,
494 // this means to map the primary and thread stacks as PROT_MTE. Note: This is
495 // not supported on Android 11 & 12.
496 bool androidMemtagStack;
497
498 // When using a unified pre-link LTO pipeline, specify the backend LTO mode.
499 LtoKind ltoKind = LtoKind::Default;
500
501 unsigned threadCount;
502
503 // If an input file equals a key, remap it to the value.
504 llvm::DenseMap<llvm::StringRef, llvm::StringRef> remapInputs;
505 // If an input file matches a wildcard pattern, remap it to the value.
506 llvm::SmallVector<std::pair<llvm::GlobPattern, llvm::StringRef>, 0>
507 remapInputsWildcards;
508};
509
510// Some index properties of a symbol are stored separately in this auxiliary
511// struct to decrease sizeof(SymbolUnion) in the majority of cases.
512struct SymbolAux {
513 uint32_t gotIdx = -1;
514 uint32_t pltIdx = -1;
515 uint32_t tlsDescIdx = -1;
516 uint32_t tlsGdIdx = -1;
517};
518
519struct DuplicateSymbol {
520 const Symbol *sym;
521 const InputFile *file;
522 InputSectionBase *section;
523 uint64_t value;
524};
525
526struct UndefinedDiag {
527 Undefined *sym;
528 struct Loc {
529 InputSectionBase *sec;
530 uint64_t offset;
531 };
532 SmallVector<Loc, 0> locs;
533 bool isWarning;
534};
535
536// Linker generated sections which can be used as inputs and are not specific to
537// a partition.
538struct InStruct {
539 std::unique_ptr<InputSection> attributes;
540 std::unique_ptr<SyntheticSection> riscvAttributes;
541 std::unique_ptr<BssSection> bss;
542 std::unique_ptr<BssSection> bssRelRo;
543 std::unique_ptr<SyntheticSection> gnuProperty;
544 std::unique_ptr<SyntheticSection> gnuStack;
545 std::unique_ptr<GotSection> got;
546 std::unique_ptr<GotPltSection> gotPlt;
547 std::unique_ptr<IgotPltSection> igotPlt;
548 std::unique_ptr<RelroPaddingSection> relroPadding;
549 std::unique_ptr<SyntheticSection> armCmseSGSection;
550 std::unique_ptr<PPC64LongBranchTargetSection> ppc64LongBranchTarget;
551 std::unique_ptr<SyntheticSection> mipsAbiFlags;
552 std::unique_ptr<MipsGotSection> mipsGot;
553 std::unique_ptr<SyntheticSection> mipsOptions;
554 std::unique_ptr<SyntheticSection> mipsReginfo;
555 std::unique_ptr<MipsRldMapSection> mipsRldMap;
556 std::unique_ptr<SyntheticSection> partEnd;
557 std::unique_ptr<SyntheticSection> partIndex;
558 std::unique_ptr<PltSection> plt;
559 std::unique_ptr<IpltSection> iplt;
560 std::unique_ptr<PPC32Got2Section> ppc32Got2;
561 std::unique_ptr<IBTPltSection> ibtPlt;
562 std::unique_ptr<RelocationBaseSection> relaPlt;
563 // Non-SHF_ALLOC sections
564 std::unique_ptr<SyntheticSection> debugNames;
565 std::unique_ptr<GdbIndexSection> gdbIndex;
566 std::unique_ptr<StringTableSection> shStrTab;
567 std::unique_ptr<StringTableSection> strTab;
568 std::unique_ptr<SymbolTableBaseSection> symTab;
569 std::unique_ptr<SymtabShndxSection> symTabShndx;
570};
571
572struct Ctx : CommonLinkerContext {
573 Config arg;
574 LinkerDriver driver;
575 LinkerScript *script;
576 std::unique_ptr<TargetInfo> target;
577
578 // These variables are initialized by Writer and should not be used before
579 // Writer is initialized.
580 uint8_t *bufferStart = nullptr;
581 Partition *mainPart = nullptr;
582 PhdrEntry *tlsPhdr = nullptr;
583 struct OutSections {
584 std::unique_ptr<OutputSection> elfHeader;
585 std::unique_ptr<OutputSection> programHeaders;
586 OutputSection *preinitArray = nullptr;
587 OutputSection *initArray = nullptr;
588 OutputSection *finiArray = nullptr;
589 };
590 OutSections out;
591 SmallVector<OutputSection *, 0> outputSections;
592 std::vector<Partition> partitions;
593
594 InStruct in;
595
596 // Some linker-generated symbols need to be created as
597 // Defined symbols.
598 struct ElfSym {
599 // __bss_start
600 Defined *bss;
601
602 // etext and _etext
603 Defined *etext1;
604 Defined *etext2;
605
606 // edata and _edata
607 Defined *edata1;
608 Defined *edata2;
609
610 // end and _end
611 Defined *end1;
612 Defined *end2;
613
614 // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
615 // be at some offset from the base of the .got section, usually 0 or
616 // the end of the .got.
617 Defined *globalOffsetTable;
618
619 // _gp, _gp_disp and __gnu_local_gp symbols. Only for MIPS.
620 Defined *mipsGp;
621 Defined *mipsGpDisp;
622 Defined *mipsLocalGp;
623
624 // __global_pointer$ for RISC-V.
625 Defined *riscvGlobalPointer;
626
627 // __rel{,a}_iplt_{start,end} symbols.
628 Defined *relaIpltStart;
629 Defined *relaIpltEnd;
630
631 // _TLS_MODULE_BASE_ on targets that support TLSDESC.
632 Defined *tlsModuleBase;
633 };
634 ElfSym sym{};
635 std::unique_ptr<SymbolTable> symtab;
636 SmallVector<Symbol *, 0> synthesizedSymbols;
637
638 SmallVector<std::unique_ptr<MemoryBuffer>> memoryBuffers;
639 SmallVector<ELFFileBase *, 0> objectFiles;
640 SmallVector<SharedFile *, 0> sharedFiles;
641 SmallVector<BinaryFile *, 0> binaryFiles;
642 SmallVector<BitcodeFile *, 0> bitcodeFiles;
643 SmallVector<BitcodeFile *, 0> lazyBitcodeFiles;
644 SmallVector<InputSectionBase *, 0> inputSections;
645 SmallVector<EhInputSection *, 0> ehInputSections;
646
647 SmallVector<SymbolAux, 0> symAux;
648 // Duplicate symbol candidates.
649 SmallVector<DuplicateSymbol, 0> duplicates;
650 // Undefined diagnostics are collected in a vector and emitted once all of
651 // them are known, so that some postprocessing on the list of undefined
652 // symbols can happen before lld emits diagnostics.
653 std::mutex relocMutex;
654 SmallVector<UndefinedDiag, 0> undefErrs;
655 // Symbols in a non-prevailing COMDAT group which should be changed to an
656 // Undefined.
657 SmallVector<std::pair<Symbol *, unsigned>, 0> nonPrevailingSyms;
658 // A tuple of (reference, extractedFile, sym). Used by --why-extract=.
659 SmallVector<std::tuple<std::string, const InputFile *, const Symbol &>, 0>
660 whyExtractRecords;
661 // A mapping from a symbol to an InputFile referencing it backward. Used by
662 // --warn-backrefs.
663 llvm::DenseMap<const Symbol *,
664 std::pair<const InputFile *, const InputFile *>>
665 backwardReferences;
666 llvm::SmallSet<llvm::StringRef, 0> auxiliaryFiles;
667 // If --reproduce is specified, all input files are written to this tar
668 // archive.
669 std::unique_ptr<llvm::TarWriter> tar;
670 // InputFile for linker created symbols with no source location.
671 InputFile *internalFile = nullptr;
672 // True if symbols can be exported (isExported) or preemptible.
673 bool hasDynsym = false;
674 // True if SHT_LLVM_SYMPART is used.
675 std::atomic<bool> hasSympart{false};
676 // True if there are TLS IE relocations. Set DF_STATIC_TLS if -shared.
677 std::atomic<bool> hasTlsIe{false};
678 // True if we need to reserve two .got entries for local-dynamic TLS model.
679 std::atomic<bool> needsTlsLd{false};
680 // True if all native vtable symbols have corresponding type info symbols
681 // during LTO.
682 bool ltoAllVtablesHaveTypeInfos = false;
683 // Number of Vernaux entries (needed shared object names).
684 uint32_t vernauxNum = 0;
685
686 // Each symbol assignment and DEFINED(sym) reference is assigned an increasing
687 // order. Each DEFINED(sym) evaluation checks whether the reference happens
688 // before a possible `sym = expr;`.
689 unsigned scriptSymOrderCounter = 1;
690 llvm::DenseMap<const Symbol *, unsigned> scriptSymOrder;
691
692 // The set of TOC entries (.toc + addend) for which we should not apply
693 // toc-indirect to toc-relative relaxation. const Symbol * refers to the
694 // STT_SECTION symbol associated to the .toc input section.
695 llvm::DenseSet<std::pair<const Symbol *, uint64_t>> ppc64noTocRelax;
696
697 Ctx();
698
699 llvm::raw_fd_ostream openAuxiliaryFile(llvm::StringRef, std::error_code &);
700
701 ArrayRef<uint8_t> aarch64PauthAbiCoreInfo;
702};
703
704// The first two elements of versionDefinitions represent VER_NDX_LOCAL and
705// VER_NDX_GLOBAL. This helper returns other elements.
706static inline ArrayRef<VersionDefinition> namedVersionDefs(Ctx &ctx) {
707 return llvm::ArrayRef(ctx.arg.versionDefinitions).slice(N: 2);
708}
709
710struct ELFSyncStream : SyncStream {
711 Ctx &ctx;
712 ELFSyncStream(Ctx &ctx, DiagLevel level)
713 : SyncStream(ctx.e, level), ctx(ctx) {}
714};
715
716template <typename T>
717std::enable_if_t<!std::is_pointer_v<std::remove_reference_t<T>>,
718 const ELFSyncStream &>
719operator<<(const ELFSyncStream &s, T &&v) {
720 s.os << std::forward<T>(v);
721 return s;
722}
723
724inline const ELFSyncStream &operator<<(const ELFSyncStream &s, const char *v) {
725 s.os << v;
726 return s;
727}
728
729inline const ELFSyncStream &operator<<(const ELFSyncStream &s, Error v) {
730 s.os << llvm::toString(E: std::move(v));
731 return s;
732}
733
734// Report a log if --verbose is specified.
735ELFSyncStream Log(Ctx &ctx);
736
737// Print a message to stdout.
738ELFSyncStream Msg(Ctx &ctx);
739
740// Report a warning. Upgraded to an error if --fatal-warnings is specified.
741ELFSyncStream Warn(Ctx &ctx);
742
743// Report an error that will suppress the output file generation. Downgraded to
744// a warning if --noinhibit-exec is specified.
745ELFSyncStream Err(Ctx &ctx);
746
747// Report an error regardless of --noinhibit-exec.
748ELFSyncStream ErrAlways(Ctx &ctx);
749
750// Report a fatal error that exits immediately. This should generally be avoided
751// in favor of Err.
752ELFSyncStream Fatal(Ctx &ctx);
753
754uint64_t errCount(Ctx &ctx);
755
756ELFSyncStream InternalErr(Ctx &ctx, const uint8_t *buf);
757
758#define CHECK2(E, S) lld::check2((E), [&] { return toStr(ctx, S); })
759
760inline DiagLevel toDiagLevel(ReportPolicy policy) {
761 if (policy == ReportPolicy::Error)
762 return DiagLevel::Err;
763 else if (policy == ReportPolicy::Warning)
764 return DiagLevel::Warn;
765 return DiagLevel::None;
766}
767
768} // namespace lld::elf
769
770#endif
771

source code of lld/ELF/Config.h