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