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