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