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