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