1 //===- Symbols.h ------------------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines various types of Symbols.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLD_ELF_SYMBOLS_H
14 #define LLD_ELF_SYMBOLS_H
17 #include "lld/Common/LLVM.h"
18 #include "lld/Common/Memory.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/Object/ELF.h"
21 #include "llvm/Support/Compiler.h"
29 class InputSectionBase
;
36 // Returns a string representation for a symbol for diagnostics.
37 std::string
toStr(Ctx
&, const Symbol
&);
38 const ELFSyncStream
&operator<<(const ELFSyncStream
&, const Symbol
*);
40 void printTraceSymbol(const Symbol
&sym
, StringRef name
);
45 HAS_DIRECT_RELOC
= 1 << 2,
46 // True if this symbol needs a canonical PLT entry, or (during
47 // postScanRelocations) a copy relocation.
49 NEEDS_TLSDESC
= 1 << 4,
51 NEEDS_TLSGD_TO_IE
= 1 << 6,
52 NEEDS_GOT_DTPREL
= 1 << 7,
54 NEEDS_GOT_AUTH
= 1 << 9,
55 NEEDS_GOT_NONAUTH
= 1 << 10,
58 // The base class for real symbol classes.
70 Kind
kind() const { return static_cast<Kind
>(symbolKind
); }
72 // The file from which this symbol was created.
75 // The default copy constructor is deleted due to atomic flags. Define one for
76 // places where no atomic is needed.
77 Symbol(const Symbol
&o
) { memcpy(static_cast<void *>(this), &o
, sizeof(o
)); }
81 // 32-bit size saves space.
85 // The next three fields have the same meaning as the ELF symbol attributes.
86 // type and binding are placed in this order to optimize generating st_info,
87 // which is defined as (binding << 4) + (type & 0xf), on a little-endian
89 uint8_t type
: 4; // symbol type
91 // Symbol binding. This is not overwritten by replace() to track
92 // changes during resolution. In particular:
93 // - An undefined weak is still weak when it resolves to a shared library.
94 // - An undefined weak will not extract archive members, but we have to
95 // remember it is weak.
98 uint8_t stOther
; // st_other field value
102 // The partition whose dynamic symbol table contains this symbol's definition.
105 // True if this symbol is preemptible at load time.
106 LLVM_PREFERRED_TYPE(bool)
107 uint8_t isPreemptible
: 1;
109 // True if the symbol was used for linking and thus need to be added to the
110 // output file's symbol table. This is true for all symbols except for
111 // unreferenced DSO symbols, lazy (archive) symbols, and bitcode symbols that
112 // are unreferenced except by other bitcode objects.
113 LLVM_PREFERRED_TYPE(bool)
114 uint8_t isUsedInRegularObj
: 1;
116 // True if an undefined or shared symbol is used from a live section.
118 // NOTE: In Writer.cpp the field is used to mark local defined symbols
119 // which are referenced by relocations when -r or --emit-relocs is given.
120 LLVM_PREFERRED_TYPE(bool)
123 // Used by a Defined symbol with protected or default visibility, to record
124 // whether it is required to be exported into .dynsym. This is set when any of
125 // the following conditions hold:
127 // - If there is an interposable symbol from a DSO. Note: We also do this for
128 // STV_PROTECTED symbols which can't be interposed (to match BFD behavior).
129 // - If -shared or --export-dynamic is specified, any symbol in an object
130 // file/bitcode sets this property, unless suppressed by LTO
131 // canBeOmittedFromSymbolTable().
133 // Primarily set in two locations, (a) after parseSymbolVersion and
134 // (b) during demoteSymbols.
135 LLVM_PREFERRED_TYPE(bool)
136 uint8_t isExported
: 1;
138 // Used to compute isExported. Set when defined or referenced by a SharedFile.
139 LLVM_PREFERRED_TYPE(bool)
140 uint8_t exportDynamic
: 1;
142 LLVM_PREFERRED_TYPE(bool)
143 uint8_t ltoCanOmit
: 1;
145 // True if this symbol is specified by --trace-symbol option.
146 LLVM_PREFERRED_TYPE(bool)
149 // True if the name contains '@'.
150 LLVM_PREFERRED_TYPE(bool)
151 uint8_t hasVersionSuffix
: 1;
153 // Symbol visibility. This is the computed minimum visibility of all
154 // observed non-DSO symbols.
155 uint8_t visibility() const { return stOther
& 3; }
156 void setVisibility(uint8_t visibility
) {
157 stOther
= (stOther
& ~3) | visibility
;
160 bool includeInDynsym(Ctx
&) const;
161 uint8_t computeBinding(Ctx
&) const;
162 bool isGlobal() const { return binding
== llvm::ELF::STB_GLOBAL
; }
163 bool isWeak() const { return binding
== llvm::ELF::STB_WEAK
; }
165 bool isUndefined() const { return symbolKind
== UndefinedKind
; }
166 bool isCommon() const { return symbolKind
== CommonKind
; }
167 bool isDefined() const { return symbolKind
== DefinedKind
; }
168 bool isShared() const { return symbolKind
== SharedKind
; }
169 bool isPlaceholder() const { return symbolKind
== PlaceholderKind
; }
171 bool isLocal() const { return binding
== llvm::ELF::STB_LOCAL
; }
173 bool isLazy() const { return symbolKind
== LazyKind
; }
175 // True if this is an undefined weak symbol. This only works once
176 // all input files have been added.
177 bool isUndefWeak() const { return isWeak() && isUndefined(); }
179 StringRef
getName() const { return {nameData
, nameSize
}; }
181 void setName(StringRef s
) {
186 void parseSymbolVersion(Ctx
&);
188 // Get the NUL-terminated version suffix ("", "@...", or "@@...").
190 // For @@, the name has been truncated by insert(). For @, the name has been
191 // truncated by Symbol::parseSymbolVersion(ctx).
192 const char *getVersionSuffix() const { return nameData
+ nameSize
; }
194 uint32_t getGotIdx(Ctx
&ctx
) const { return ctx
.symAux
[auxIdx
].gotIdx
; }
195 uint32_t getPltIdx(Ctx
&ctx
) const { return ctx
.symAux
[auxIdx
].pltIdx
; }
196 uint32_t getTlsDescIdx(Ctx
&ctx
) const {
197 return ctx
.symAux
[auxIdx
].tlsDescIdx
;
199 uint32_t getTlsGdIdx(Ctx
&ctx
) const { return ctx
.symAux
[auxIdx
].tlsGdIdx
; }
201 bool isInGot(Ctx
&ctx
) const { return getGotIdx(ctx
) != uint32_t(-1); }
202 bool isInPlt(Ctx
&ctx
) const { return getPltIdx(ctx
) != uint32_t(-1); }
204 uint64_t getVA(Ctx
&, int64_t addend
= 0) const;
206 uint64_t getGotOffset(Ctx
&) const;
207 uint64_t getGotVA(Ctx
&) const;
208 uint64_t getGotPltOffset(Ctx
&) const;
209 uint64_t getGotPltVA(Ctx
&) const;
210 uint64_t getPltVA(Ctx
&) const;
211 uint64_t getSize() const;
212 OutputSection
*getOutputSection() const;
214 // The following two functions are used for symbol resolution.
216 // You are expected to call mergeProperties for all symbols in input
217 // files so that attributes that are attached to names rather than
218 // indivisual symbol (such as visibility) are merged together.
220 // Every time you read a new symbol from an input, you are supposed
221 // to call resolve() with the new symbol. That function replaces
222 // "this" object as a result of name resolution if the new symbol is
223 // more appropriate to be included in the output.
225 // For example, if "this" is an undefined symbol and a new symbol is
226 // a defined symbol, "this" is replaced with the new symbol.
227 void mergeProperties(const Symbol
&other
);
228 void resolve(Ctx
&, const Undefined
&other
);
229 void resolve(Ctx
&, const CommonSymbol
&other
);
230 void resolve(Ctx
&, const Defined
&other
);
231 void resolve(Ctx
&, const LazySymbol
&other
);
232 void resolve(Ctx
&, const SharedSymbol
&other
);
234 // If this is a lazy symbol, extract an input file and add the symbol
235 // in the file to the symbol table. Calling this function on
236 // non-lazy object causes a runtime error.
237 void extract(Ctx
&) const;
239 void checkDuplicate(Ctx
&, const Defined
&other
) const;
242 bool shouldReplace(Ctx
&, const Defined
&other
) const;
245 Symbol(Kind k
, InputFile
*file
, StringRef name
, uint8_t binding
,
246 uint8_t stOther
, uint8_t type
)
247 : file(file
), nameData(name
.data()), nameSize(name
.size()), type(type
),
248 binding(binding
), stOther(stOther
), symbolKind(k
), exportDynamic(false),
249 ltoCanOmit(false), archSpecificBit(false) {}
251 void overwrite(Symbol
&sym
, Kind k
) const {
253 printTraceSymbol(*this, sym
.getName());
256 sym
.binding
= binding
;
257 sym
.stOther
= (stOther
& ~3) | sym
.visibility();
262 // True if this symbol is in the Iplt sub-section of the Plt and the Igot
263 // sub-section of the .got.plt or .got.
264 LLVM_PREFERRED_TYPE(bool)
265 uint8_t isInIplt
: 1;
267 // True if this symbol needs a GOT entry and its GOT entry is actually in
268 // Igot. This will be true only for certain non-preemptible ifuncs.
269 LLVM_PREFERRED_TYPE(bool)
270 uint8_t gotInIgot
: 1;
272 // True if defined relative to a section discarded by ICF.
273 LLVM_PREFERRED_TYPE(bool)
276 // Allow reuse of a bit between architecture-exclusive symbol flags.
277 // - needsTocRestore(): On PPC64, true if a call to this symbol needs to be
278 // followed by a restore of the toc pointer.
279 // - isTagged(): On AArch64, true if the symbol needs special relocation and
280 // metadata semantics because it's tagged, under the AArch64 MemtagABI.
281 LLVM_PREFERRED_TYPE(bool)
282 uint8_t archSpecificBit
: 1;
283 bool needsTocRestore() const { return archSpecificBit
; }
284 bool isTagged() const { return archSpecificBit
; }
285 void setNeedsTocRestore(bool v
) { archSpecificBit
= v
; }
286 void setIsTagged(bool v
) {
290 // True if this symbol is defined by a symbol assignment or wrapped by --wrap.
292 // LTO shouldn't inline the symbol because it doesn't know the final content
294 LLVM_PREFERRED_TYPE(bool)
295 uint8_t scriptDefined
: 1;
297 // True if defined in a DSO. There may also be a definition in a relocatable
299 LLVM_PREFERRED_TYPE(bool)
300 uint8_t dsoDefined
: 1;
302 // True if defined in a DSO as protected visibility.
303 LLVM_PREFERRED_TYPE(bool)
304 uint8_t dsoProtected
: 1;
306 // Temporary flags used to communicate which symbol entries need PLT and GOT
307 // entries during postScanRelocations();
308 std::atomic
<uint16_t> flags
;
310 // A ctx.symAux index used to access GOT/PLT entry indexes. This is allocated
311 // in postScanRelocations().
313 uint32_t dynsymIndex
;
315 // If `file` is SharedFile (for SharedSymbol or copy-relocated Defined), this
316 // represents the Verdef index within the input DSO, which will be converted
317 // to a Verneed index in the output. Otherwise, this represents the Verdef
318 // index (VER_NDX_LOCAL, VER_NDX_GLOBAL, or a named version).
320 LLVM_PREFERRED_TYPE(bool)
321 uint8_t versionScriptAssigned
: 1;
323 // True if targeted by a range extension thunk.
324 LLVM_PREFERRED_TYPE(bool)
325 uint8_t thunkAccessed
: 1;
327 // True if the symbol is in the --dynamic-list file. A Defined symbol with
328 // protected or default visibility with this property is required to be
329 // exported into .dynsym.
330 LLVM_PREFERRED_TYPE(bool)
331 uint8_t inDynamicList
: 1;
333 // Used to track if there has been at least one undefined reference to the
334 // symbol. For Undefined and SharedSymbol, the binding may change to STB_WEAK
335 // if the first undefined reference from a non-shared object is weak.
336 LLVM_PREFERRED_TYPE(bool)
337 uint8_t referenced
: 1;
339 // Used to track if this symbol will be referenced after wrapping is performed
340 // (i.e. this will be true for foo if __real_foo is referenced, and will be
341 // true for __wrap_foo if foo is referenced).
342 LLVM_PREFERRED_TYPE(bool)
343 uint8_t referencedAfterWrap
: 1;
345 void setFlags(uint16_t bits
) {
346 flags
.fetch_or(bits
, std::memory_order_relaxed
);
348 bool hasFlag(uint16_t bit
) const {
349 assert(bit
&& (bit
& (bit
- 1)) == 0 && "bit must be a power of 2");
350 return flags
.load(std::memory_order_relaxed
) & bit
;
353 bool needsDynReloc() const {
354 return flags
.load(std::memory_order_relaxed
) &
355 (NEEDS_COPY
| NEEDS_GOT
| NEEDS_PLT
| NEEDS_TLSDESC
| NEEDS_TLSGD
|
356 NEEDS_TLSGD_TO_IE
| NEEDS_GOT_DTPREL
| NEEDS_TLSIE
);
358 void allocateAux(Ctx
&ctx
) {
360 auxIdx
= ctx
.symAux
.size();
361 ctx
.symAux
.emplace_back();
364 bool isSection() const { return type
== llvm::ELF::STT_SECTION
; }
365 bool isTls() const { return type
== llvm::ELF::STT_TLS
; }
366 bool isFunc() const { return type
== llvm::ELF::STT_FUNC
; }
367 bool isGnuIFunc() const { return type
== llvm::ELF::STT_GNU_IFUNC
; }
368 bool isObject() const { return type
== llvm::ELF::STT_OBJECT
; }
369 bool isFile() const { return type
== llvm::ELF::STT_FILE
; }
372 // Represents a symbol that is defined in the current output file.
373 class Defined
: public Symbol
{
375 Defined(Ctx
&ctx
, InputFile
*file
, StringRef name
, uint8_t binding
,
376 uint8_t stOther
, uint8_t type
, uint64_t value
, uint64_t size
,
377 SectionBase
*section
)
378 : Symbol(DefinedKind
, file
, name
, binding
, stOther
, type
), value(value
),
379 size(size
), section(section
) {
381 void overwrite(Symbol
&sym
) const;
383 static bool classof(const Symbol
*s
) { return s
->isDefined(); }
387 SectionBase
*section
;
390 // Represents a common symbol.
392 // On Unix, it is traditionally allowed to write variable definitions
393 // without initialization expressions (such as "int foo;") to header
394 // files. Such definition is called "tentative definition".
396 // Using tentative definition is usually considered a bad practice
397 // because you should write only declarations (such as "extern int
398 // foo;") to header files. Nevertheless, the linker and the compiler
399 // have to do something to support bad code by allowing duplicate
400 // definitions for this particular case.
402 // Common symbols represent variable definitions without initializations.
403 // The compiler creates common symbols when it sees variable definitions
404 // without initialization (you can suppress this behavior and let the
405 // compiler create a regular defined symbol by -fno-common).
407 // The linker allows common symbols to be replaced by regular defined
408 // symbols. If there are remaining common symbols after name resolution is
409 // complete, they are converted to regular defined symbols in a .bss
410 // section. (Therefore, the later passes don't see any CommonSymbols.)
411 class CommonSymbol
: public Symbol
{
413 CommonSymbol(Ctx
&ctx
, InputFile
*file
, StringRef name
, uint8_t binding
,
414 uint8_t stOther
, uint8_t type
, uint64_t alignment
, uint64_t size
)
415 : Symbol(CommonKind
, file
, name
, binding
, stOther
, type
),
416 alignment(alignment
), size(size
) {
418 void overwrite(Symbol
&sym
) const {
419 Symbol::overwrite(sym
, CommonKind
);
420 auto &s
= static_cast<CommonSymbol
&>(sym
);
421 s
.alignment
= alignment
;
425 static bool classof(const Symbol
*s
) { return s
->isCommon(); }
431 class Undefined
: public Symbol
{
433 Undefined(InputFile
*file
, StringRef name
, uint8_t binding
, uint8_t stOther
,
434 uint8_t type
, uint32_t discardedSecIdx
= 0)
435 : Symbol(UndefinedKind
, file
, name
, binding
, stOther
, type
),
436 discardedSecIdx(discardedSecIdx
) {}
437 void overwrite(Symbol
&sym
) const {
438 Symbol::overwrite(sym
, UndefinedKind
);
439 auto &s
= static_cast<Undefined
&>(sym
);
440 s
.discardedSecIdx
= discardedSecIdx
;
441 s
.nonPrevailing
= nonPrevailing
;
444 static bool classof(const Symbol
*s
) { return s
->kind() == UndefinedKind
; }
446 // The section index if in a discarded section, 0 otherwise.
447 uint32_t discardedSecIdx
;
448 bool nonPrevailing
= false;
451 class SharedSymbol
: public Symbol
{
453 static bool classof(const Symbol
*s
) { return s
->kind() == SharedKind
; }
455 SharedSymbol(InputFile
&file
, StringRef name
, uint8_t binding
,
456 uint8_t stOther
, uint8_t type
, uint64_t value
, uint64_t size
,
458 : Symbol(SharedKind
, &file
, name
, binding
, stOther
, type
), value(value
),
459 size(size
), alignment(alignment
) {
460 dsoProtected
= visibility() == llvm::ELF::STV_PROTECTED
;
461 // GNU ifunc is a mechanism to allow user-supplied functions to
462 // resolve PLT slot values at load-time. This is contrary to the
463 // regular symbol resolution scheme in which symbols are resolved just
464 // by name. Using this hook, you can program how symbols are solved
465 // for you program. For example, you can make "memcpy" to be resolved
466 // to a SSE-enabled version of memcpy only when a machine running the
467 // program supports the SSE instruction set.
469 // Naturally, such symbols should always be called through their PLT
470 // slots. What GNU ifunc symbols point to are resolver functions, and
471 // calling them directly doesn't make sense (unless you are writing a
474 // For DSO symbols, we always call them through PLT slots anyway.
475 // So there's no difference between GNU ifunc and regular function
476 // symbols if they are in DSOs. So we can handle GNU_IFUNC as FUNC.
477 if (this->type
== llvm::ELF::STT_GNU_IFUNC
)
478 this->type
= llvm::ELF::STT_FUNC
;
480 void overwrite(Symbol
&sym
) const {
481 Symbol::overwrite(sym
, SharedKind
);
482 auto &s
= static_cast<SharedSymbol
&>(sym
);
483 s
.dsoProtected
= dsoProtected
;
486 s
.alignment
= alignment
;
489 uint64_t value
; // st_value
490 uint64_t size
; // st_size
494 // LazySymbol symbols represent symbols in object files between --start-lib and
495 // --end-lib options. LLD also handles traditional archives as if all the files
496 // in the archive are surrounded by --start-lib and --end-lib.
498 // A special complication is the handling of weak undefined symbols. They should
499 // not load a file, but we have to remember we have seen both the weak undefined
500 // and the lazy. We represent that with a lazy symbol with a weak binding. This
501 // means that code looking for undefined symbols normally also has to take lazy
502 // symbols into consideration.
503 class LazySymbol
: public Symbol
{
505 LazySymbol(InputFile
&file
)
506 : Symbol(LazyKind
, &file
, {}, llvm::ELF::STB_GLOBAL
,
507 llvm::ELF::STV_DEFAULT
, llvm::ELF::STT_NOTYPE
) {}
508 void overwrite(Symbol
&sym
) const { Symbol::overwrite(sym
, LazyKind
); }
510 static bool classof(const Symbol
*s
) { return s
->kind() == LazyKind
; }
513 // A buffer class that is large enough to hold any Symbol-derived
514 // object. We allocate memory using this class and instantiate a symbol
515 // using the placement new.
517 // It is important to keep the size of SymbolUnion small for performance and
518 // memory usage reasons. 64 bytes is a soft limit based on the size of Defined
519 // on a 64-bit system. This is enforced by a static_assert in Symbols.cpp.
521 alignas(Defined
) char a
[sizeof(Defined
)];
522 alignas(CommonSymbol
) char b
[sizeof(CommonSymbol
)];
523 alignas(Undefined
) char c
[sizeof(Undefined
)];
524 alignas(SharedSymbol
) char d
[sizeof(SharedSymbol
)];
525 alignas(LazySymbol
) char e
[sizeof(LazySymbol
)];
528 template <typename
... T
> Defined
*makeDefined(T
&&...args
) {
529 auto *sym
= getSpecificAllocSingleton
<SymbolUnion
>().Allocate();
530 memset(sym
, 0, sizeof(Symbol
));
531 auto &s
= *new (reinterpret_cast<Defined
*>(sym
)) Defined(std::forward
<T
>(args
)...);
535 void reportDuplicate(Ctx
&, const Symbol
&sym
, const InputFile
*newFile
,
536 InputSectionBase
*errSec
, uint64_t errOffset
);
537 void maybeWarnUnorderableSymbol(Ctx
&, const Symbol
*sym
);
538 bool computeIsPreemptible(Ctx
&, const Symbol
&sym
);
539 void parseVersionAndComputeIsPreemptible(Ctx
&);
541 } // namespace lld::elf