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/ErrorHandler.h"
13 #include "llvm/ADT/MapVector.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/StringSet.h"
16 #include "llvm/BinaryFormat/ELF.h"
17 #include "llvm/Support/CachePruning.h"
18 #include "llvm/Support/CodeGen.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/GlobPattern.h"
21 #include <atomic>
22 #include <vector>
23
24 namespace lld {
25 namespace elf {
26
27 class InputFile;
28 class InputSectionBase;
29
30 enum ELFKind {
31 ELFNoneKind,
32 ELF32LEKind,
33 ELF32BEKind,
34 ELF64LEKind,
35 ELF64BEKind
36 };
37
38 // For --build-id.
39 enum class BuildIdKind { None, Fast, Md5, Sha1, Hexstring, Uuid };
40
41 enum class CapRelocsMode { Legacy, ElfReloc, CBuildCap };
42
43 enum class CapTableScopePolicy { All, File, Function };
44
45 // For --discard-{all,locals,none}.
46 enum class DiscardPolicy { Default, All, Locals, None };
47
48 // For --icf={none,safe,all}.
49 enum class ICFLevel { None, Safe, All };
50
51 // For --strip-{all,debug}.
52 enum class StripPolicy { None, All, Debug };
53
54 // For --unresolved-symbols.
55 enum class UnresolvedPolicy { ReportError, Warn, Ignore };
56
57 // For --orphan-handling.
58 enum class OrphanHandlingPolicy { Place, Warn, Error };
59
60 // For --sort-section and linkerscript sorting rules.
61 enum class SortSectionPolicy { Default, None, Alignment, Name, Priority };
62
63 // For --target2
64 enum class Target2Policy { Abs, Rel, GotRel };
65
66 // For tracking ARM Float Argument PCS
67 enum class ARMVFPArgKind { Default, Base, VFP, ToolChain };
68
69 // For -z noseparate-code, -z separate-code and -z separate-loadable-segments.
70 enum class SeparateSegmentKind { None, Code, Loadable };
71
72 // For -z *stack
73 enum class GnuStackKind { None, Exec, NoExec };
74
75 struct SymbolVersion {
76 llvm::StringRef name;
77 bool isExternCpp;
78 bool hasWildcard;
79 };
80
81 // This struct contains symbols version definition that
82 // can be found in version script if it is used for link.
83 struct VersionDefinition {
84 llvm::StringRef name;
85 uint16_t id;
86 std::vector<SymbolVersion> patterns;
87 };
88
89 // This struct contains the global configuration for the linker.
90 // Most fields are direct mapping from the command line options
91 // and such fields have the same name as the corresponding options.
92 // Most fields are initialized by the driver.
93 struct Configuration {
94 uint8_t osabi = 0;
95 uint32_t andFeatures = 0;
96 llvm::CachePruningPolicy thinLTOCachePolicy;
97 llvm::StringMap<uint64_t> sectionStartMap;
98 llvm::StringRef bfdname;
99 llvm::StringRef chroot;
100 llvm::StringRef dynamicLinker;
101 llvm::StringRef dwoDir;
102 llvm::StringRef entry;
103 llvm::StringRef emulation;
104 llvm::StringRef fini;
105 llvm::StringRef init;
106 llvm::StringRef ltoAAPipeline;
107 llvm::StringRef ltoCSProfileFile;
108 llvm::StringRef ltoNewPmPasses;
109 llvm::StringRef ltoObjPath;
110 llvm::StringRef ltoSampleProfile;
111 llvm::StringRef mapFile;
112 llvm::StringRef outputFile;
113 llvm::StringRef optRemarksFilename;
114 llvm::StringRef optRemarksPasses;
115 llvm::StringRef optRemarksFormat;
116 llvm::StringRef progName;
117 llvm::StringRef printArchiveStats;
118 llvm::StringRef printSymbolOrder;
119 llvm::StringRef soName;
120 llvm::StringRef sysroot;
121 llvm::StringRef thinLTOCacheDir;
122 llvm::StringRef thinLTOIndexOnlyArg;
123 llvm::StringRef ltoBasicBlockSections;
124 std::pair<llvm::StringRef, llvm::StringRef> thinLTOObjectSuffixReplace;
125 std::pair<llvm::StringRef, llvm::StringRef> thinLTOPrefixReplace;
126 std::string rpath;
127 std::vector<VersionDefinition> versionDefinitions;
128 std::vector<llvm::StringRef> auxiliaryList;
129 std::vector<llvm::StringRef> filterList;
130 std::vector<llvm::StringRef> searchPaths;
131 std::vector<llvm::StringRef> symbolOrderingFile;
132 std::vector<llvm::StringRef> thinLTOModulesToCompile;
133 std::vector<llvm::StringRef> undefined;
134 std::vector<llvm::StringRef> warnIfFileLinked;
135 std::vector<SymbolVersion> dynamicList;
136 std::vector<uint8_t> buildIdVector;
137 llvm::MapVector<std::pair<const InputSectionBase *, const InputSectionBase *>,
138 uint64_t>
139 callGraphProfile;
140 bool allowMultipleDefinition;
141 bool allowShlibUndefined;
142 bool allowUndefinedCapRelocs = false;
143 bool androidPackDynRelocs;
144 bool armHasBlx = false;
145 bool armHasMovtMovw = false;
146 bool armJ1J2BranchEncoding = false;
147 bool asNeeded = false;
148 bool bsymbolic;
149 bool bsymbolicFunctions;
150 // make dynamic relocations that are not supported by
151 // FreeBSD _rtld_relocate_nonplt_self an error.
152 bool buildingFreeBSDRtld;
153 bool callGraphProfileSort;
154 bool checkSections;
155 bool compressDebugSections;
156 bool cref;
157 std::vector<std::pair<llvm::GlobPattern, uint64_t>> deadRelocInNonAlloc;
158 bool defineCommon;
159 bool demangle = true;
160 bool dependentLibraries;
161 bool disableVerify;
162 bool ehFrameHdr;
163 bool emitLLVM;
164 bool emitRelocs;
165 bool enableNewDtags;
166 bool executeOnly;
167 bool exportDynamic;
168 bool fixCortexA53Errata843419;
169 bool fixCortexA8;
170 bool formatBinary = false;
171 bool gcSections;
172 bool gdbIndex;
173 bool gnuHash = false;
174 bool gnuUnique;
175 bool hasDynSymTab;
176 bool ignoreDataAddressEquality;
177 bool ignoreFunctionAddressEquality;
178 bool ltoCSProfileGenerate;
179 bool ltoDebugPassManager;
180 bool ltoEmitAsm;
181 bool ltoNewPassManager;
182 bool ltoUniqueBasicBlockSectionNames;
183 bool ltoWholeProgramVisibility;
184 bool mergeArmExidx;
185 bool mipsN32Abi = false;
186 bool mmapOutputFile;
187 bool nmagic;
188 bool noDynamicLinker = false;
189 bool noinhibitExec;
190 bool nostdlib;
191 bool oFormatBinary;
192 bool omagic;
193 bool optimizeBBJumps;
194 bool optRemarksWithHotness;
195 bool picThunk;
196 bool pie;
197 bool printGcSections;
198 bool printIcfSections;
199 bool relocatable;
200 bool relrPackDynRelocs;
201 bool saveTemps;
202 llvm::Optional<uint32_t> shuffleSectionSeed;
203 bool sortCapRelocs;
204 bool singleRoRx;
205 bool shared;
206 bool symbolic;
207 bool isStatic = false;
208 bool sysvHash = false;
209 bool target1Rel;
210 bool trace;
211 bool thinLTOEmitImportsFiles;
212 bool thinLTOIndexOnly;
213 bool timeTraceEnabled;
214 bool tocOptimize;
215 bool undefinedVersion;
216 bool unique;
217 bool useAndroidRelrTags = false;
218 bool verboseCapRelocs = false;
219 bool warnBackrefs;
220 std::vector<llvm::GlobPattern> warnBackrefsExclude;
221 bool warnCommon;
222 bool warnIfuncTextrel;
223 bool warnMissingEntry;
224 bool warnSymbolOrdering;
225 bool writeAddends;
226 // -z captabledebug: add additional symbols $captable_load_<symbols> before
227 // each captable clc instruction that indicates which symbol should be loaded
228 bool zCapTableDebug;
229 bool zCombreloc;
230 bool zCopyreloc;
231 bool zForceBti;
232 bool zForceIbt;
233 bool zGlobal;
234 bool zHazardplt;
235 bool zIfuncNoplt;
236 bool zInitfirst;
237 bool zInterpose;
238 bool zKeepTextSectionPrefix;
239 bool zNodefaultlib;
240 bool zNodelete;
241 bool zNodlopen;
242 bool zNow;
243 bool zOrigin;
244 bool zPacPlt;
245 bool zRelro;
246 bool zRodynamic;
247 bool zShstk;
248 uint8_t zStartStopVisibility;
249 bool zText;
250 bool zRetpolineplt;
251 bool zWxneeded;
252 DiscardPolicy discard;
253 GnuStackKind zGnustack;
254 ICFLevel icf;
255 OrphanHandlingPolicy orphanHandling;
256 SortSectionPolicy sortSection;
257 StripPolicy strip;
258 UnresolvedPolicy unresolvedSymbols;
259 Target2Policy target2;
260 // Method used for capability relocations for preemptible symbols
261 CapRelocsMode preemptibleCapRelocsMode;
262 // Method used for capability relocations for non-preemptible symbols
263 CapRelocsMode localCapRelocsMode;
264 CapTableScopePolicy capTableScope;
265 bool relativeCapRelocsOnly;
266
267 ARMVFPArgKind armVFPArgs = ARMVFPArgKind::Default;
268 BuildIdKind buildId = BuildIdKind::None;
269 SeparateSegmentKind zSeparate;
270 ELFKind ekind = ELFNoneKind;
271 uint16_t emachine = llvm::ELF::EM_NONE;
272 llvm::Optional<uint64_t> imageBase;
273 uint64_t commonPageSize;
274 uint64_t maxPageSize;
275 uint64_t mipsGotSize;
276 uint64_t zStackSize;
277 unsigned ltoPartitions;
278 unsigned ltoo;
279 unsigned optimize;
280 StringRef thinLTOJobs;
281 unsigned timeTraceGranularity;
282 int32_t splitStackAdjustSize;
283
284 // The following config options do not directly correspond to any
285 // particular command line options.
286
287 // True if we need to pass through relocations in input files to the
288 // output file. Usually false because we consume relocations.
289 bool copyRelocs;
290
291 // True if the target is ELF64. False if ELF32.
292 bool is64;
293
294 // True if the target is little-endian. False if big-endian.
295 bool isLE;
296
297 // endianness::little if isLE is true. endianness::big otherwise.
298 llvm::support::endianness endianness;
299
300 // True if the target is the little-endian MIPS64.
301 //
302 // The reason why we have this variable only for the MIPS is because
303 // we use this often. Some ELF headers for MIPS64EL are in a
304 // mixed-endian (which is horrible and I'd say that's a serious spec
305 // bug), and we need to know whether we are reading MIPS ELF files or
306 // not in various places.
307 //
308 // (Note that MIPS64EL is not a typo for MIPS64LE. This is the official
309 // name whatever that means. A fun hypothesis is that "EL" is short for
310 // little-endian written in the little-endian order, but I don't know
311 // if that's true.)
312 bool isMips64EL;
313
314 // True if we need to set the DF_STATIC_TLS flag to an output file,
315 // which works as a hint to the dynamic loader that the file contains
316 // code compiled with the static TLS model. The thread-local variable
317 // compiled with the static TLS model is faster but less flexible, and
318 // it may not be loaded using dlopen().
319 //
320 // We set this flag to true when we see a relocation for the static TLS
321 // model. Once this becomes true, it will never become false.
322 //
323 // Since the flag is updated by multi-threaded code, we use std::atomic.
324 // (Writing to a variable is not considered thread-safe even if the
325 // variable is boolean and we always set the same value from all threads.)
326 std::atomic<bool> hasStaticTlsModel{false};
327
328 // Holds set of ELF header flags for the target.
329 uint32_t eflags = 0;
330
331 // The ELF spec defines two types of relocation table entries, RELA and
332 // REL. RELA is a triplet of (offset, info, addend) while REL is a
333 // tuple of (offset, info). Addends for REL are implicit and read from
334 // the location where the relocations are applied. So, REL is more
335 // compact than RELA but requires a bit of more work to process.
336 //
337 // (From the linker writer's view, this distinction is not necessary.
338 // If the ELF had chosen whichever and sticked with it, it would have
339 // been easier to write code to process relocations, but it's too late
340 // to change the spec.)
341 //
342 // Each ABI defines its relocation type. IsRela is true if target
343 // uses RELA. As far as we know, all 64-bit ABIs are using RELA. A
344 // few 32-bit ABIs are using RELA too.
345 bool isRela;
346
347 // True if we are creating position-independent code.
348 bool isPic;
349
350 // 4 for ELF32, 8 for ELF64.
351 int wordsize;
352
353 // Size of a CHERI capability
354 int capabilitySize = 0;
355
356 // True if we are creating a pure-capability CheriABI output.
357 bool isCheriAbi = false;
358 };
359
360 // The only instance of Configuration struct.
361 extern Configuration *config;
362
363 // The first two elements of versionDefinitions represent VER_NDX_LOCAL and
364 // VER_NDX_GLOBAL. This helper returns other elements.
namedVersionDefs()365 static inline ArrayRef<VersionDefinition> namedVersionDefs() {
366 return llvm::makeArrayRef(config->versionDefinitions).slice(2);
367 }
368
errorOrWarn(const Twine & msg)369 static inline void errorOrWarn(const Twine &msg) {
370 if (!config->noinhibitExec)
371 error(msg);
372 else
373 warn(msg);
374 }
375 } // namespace elf
376 } // namespace lld
377
378 #endif
379