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