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