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 #ifndef LLD_COFF_SYMBOLS_H
10 #define LLD_COFF_SYMBOLS_H
14 #include "lld/Common/LLVM.h"
15 #include "lld/Common/Memory.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/Object/Archive.h"
18 #include "llvm/Object/COFF.h"
27 using llvm::object::Archive
;
28 using llvm::object::COFFSymbolRef
;
29 using llvm::object::coff_import_header
;
30 using llvm::object::coff_symbol_generic
;
33 class COFFLinkerContext
;
38 // The base class for real symbol classes.
42 // The order of these is significant. We start with the regular defined
43 // symbols as those are the most prevalent and the zero tag is the cheapest
44 // to set. Among the defined kinds, the lower the kind is preferred over
45 // the higher kind when testing whether one symbol should take precedence
47 DefinedRegularKind
= 0,
49 DefinedLocalImportKind
,
50 DefinedImportThunkKind
,
51 DefinedImportDataKind
,
60 LastDefinedCOFFKind
= DefinedCommonKind
,
61 LastDefinedKind
= DefinedSyntheticKind
,
64 Kind
kind() const { return static_cast<Kind
>(symbolKind
); }
66 // Returns the symbol name.
68 // COFF symbol names are read lazily for a performance reason.
69 // Non-external symbol names are never used by the linker except for logging
70 // or debugging. Their internal references are resolved not by name but by
71 // symbol index. And because they are not external, no one can refer them by
72 // name. Object files contain lots of non-external symbols, and creating
73 // StringRefs for them (which involves lots of strlen() on the string table)
74 // is a waste of time.
75 if (nameData
== nullptr)
77 return StringRef(nameData
, nameSize
);
80 void replaceKeepingName(Symbol
*other
, size_t size
);
82 // Returns the file from which this symbol was created.
85 // Indicates that this symbol will be included in the final image. Only valid
86 // after calling markLive.
90 return symbolKind
== LazyArchiveKind
|| symbolKind
== LazyObjectKind
||
91 symbolKind
== LazyDLLSymbolKind
;
99 explicit Symbol(Kind k
, StringRef n
= "")
100 : symbolKind(k
), isExternal(true), isCOMDAT(false),
101 writtenToSymtab(false), isUsedInRegularObj(false),
102 pendingArchiveLoad(false), isGCRoot(false), isRuntimePseudoReloc(false),
103 deferUndefined(false), canInline(true), isWeak(false), isAntiDep(false),
104 nameSize(n
.size()), nameData(n
.empty() ? nullptr : n
.data()) {
105 assert((!n
.empty() || k
<= LastDefinedCOFFKind
) &&
106 "If the name is empty, the Symbol must be a DefinedCOFF.");
109 unsigned symbolKind
: 8;
110 unsigned isExternal
: 1;
113 // This bit is used by the \c DefinedRegular subclass.
114 unsigned isCOMDAT
: 1;
116 // This bit is used by Writer::createSymbolAndStringTable() to prevent
117 // symbols from being written to the symbol table more than once.
118 unsigned writtenToSymtab
: 1;
120 // True if this symbol was referenced by a regular (non-bitcode) object.
121 unsigned isUsedInRegularObj
: 1;
123 // True if we've seen both a lazy and an undefined symbol with this symbol
124 // name, which means that we have enqueued an archive member load and should
125 // not load any more archive members to resolve the same symbol.
126 unsigned pendingArchiveLoad
: 1;
128 /// True if we've already added this symbol to the list of GC roots.
129 unsigned isGCRoot
: 1;
131 unsigned isRuntimePseudoReloc
: 1;
133 // True if we want to allow this symbol to be undefined in the early
134 // undefined check pass in SymbolTable::reportUnresolvable(), as it
135 // might be fixed up later.
136 unsigned deferUndefined
: 1;
138 // False if LTO shouldn't inline whatever this symbol points to. If a symbol
139 // is overwritten after LTO, LTO shouldn't inline the symbol because it
140 // doesn't know the final contents of the symbol.
141 unsigned canInline
: 1;
143 // True if the symbol is weak. This is only tracked for bitcode/LTO symbols.
144 // This information isn't written to the output; rather, it's used for
145 // managing weak symbol overrides.
148 // True if the symbol is an anti-dependency.
149 unsigned isAntiDep
: 1;
152 // Symbol name length. Assume symbol lengths fit in a 32-bit integer.
155 const char *nameData
;
158 // The base class for any defined symbols, including absolute symbols,
160 class Defined
: public Symbol
{
162 Defined(Kind k
, StringRef n
) : Symbol(k
, n
) {}
164 static bool classof(const Symbol
*s
) { return s
->kind() <= LastDefinedKind
; }
166 // Returns the RVA (relative virtual address) of this symbol. The
167 // writer sets and uses RVAs.
170 // Returns the chunk containing this symbol. Absolute symbols and __ImageBase
171 // do not have chunks, so this may return null.
175 // Symbols defined via a COFF object file or bitcode file. For COFF files, this
176 // stores a coff_symbol_generic*, and names of internal symbols are lazily
177 // loaded through that. For bitcode files, Sym is nullptr and the name is stored
178 // as a decomposed StringRef.
179 class DefinedCOFF
: public Defined
{
183 DefinedCOFF(Kind k
, InputFile
*f
, StringRef n
, const coff_symbol_generic
*s
)
184 : Defined(k
, n
), file(f
), sym(s
) {}
186 static bool classof(const Symbol
*s
) {
187 return s
->kind() <= LastDefinedCOFFKind
;
190 InputFile
*getFile() { return file
; }
192 COFFSymbolRef
getCOFFSymbol();
197 const coff_symbol_generic
*sym
;
200 // Regular defined symbols read from object file symbol tables.
201 class DefinedRegular
: public DefinedCOFF
{
203 DefinedRegular(InputFile
*f
, StringRef n
, bool isCOMDAT
,
204 bool isExternal
= false,
205 const coff_symbol_generic
*s
= nullptr,
206 SectionChunk
*c
= nullptr, bool isWeak
= false)
207 : DefinedCOFF(DefinedRegularKind
, f
, n
, s
), data(c
? &c
->repl
: nullptr) {
208 this->isExternal
= isExternal
;
209 this->isCOMDAT
= isCOMDAT
;
210 this->isWeak
= isWeak
;
213 static bool classof(const Symbol
*s
) {
214 return s
->kind() == DefinedRegularKind
;
217 uint64_t getRVA() const { return (*data
)->getRVA() + sym
->Value
; }
218 SectionChunk
*getChunk() const { return *data
; }
219 uint32_t getValue() const { return sym
->Value
; }
224 class DefinedCommon
: public DefinedCOFF
{
226 DefinedCommon(InputFile
*f
, StringRef n
, uint64_t size
,
227 const coff_symbol_generic
*s
= nullptr,
228 CommonChunk
*c
= nullptr)
229 : DefinedCOFF(DefinedCommonKind
, f
, n
, s
), data(c
), size(size
) {
230 this->isExternal
= true;
233 static bool classof(const Symbol
*s
) {
234 return s
->kind() == DefinedCommonKind
;
237 uint64_t getRVA() { return data
->getRVA(); }
238 CommonChunk
*getChunk() { return data
; }
242 uint64_t getSize() const { return size
; }
248 class DefinedAbsolute
: public Defined
{
250 DefinedAbsolute(const COFFLinkerContext
&c
, StringRef n
, COFFSymbolRef s
)
251 : Defined(DefinedAbsoluteKind
, n
), va(s
.getValue()), ctx(c
) {
252 isExternal
= s
.isExternal();
255 DefinedAbsolute(const COFFLinkerContext
&c
, StringRef n
, uint64_t v
)
256 : Defined(DefinedAbsoluteKind
, n
), va(v
), ctx(c
) {}
258 static bool classof(const Symbol
*s
) {
259 return s
->kind() == DefinedAbsoluteKind
;
263 void setVA(uint64_t v
) { va
= v
; }
264 uint64_t getVA() const { return va
; }
268 const COFFLinkerContext
&ctx
;
271 // This symbol is used for linker-synthesized symbols like __ImageBase and
272 // __safe_se_handler_table.
273 class DefinedSynthetic
: public Defined
{
275 explicit DefinedSynthetic(StringRef name
, Chunk
*c
, uint32_t offset
= 0)
276 : Defined(DefinedSyntheticKind
, name
), c(c
), offset(offset
) {}
278 static bool classof(const Symbol
*s
) {
279 return s
->kind() == DefinedSyntheticKind
;
282 // A null chunk indicates that this is __ImageBase. Otherwise, this is some
283 // other synthesized chunk, like SEHTableChunk.
284 uint32_t getRVA() { return c
? c
->getRVA() + offset
: 0; }
285 Chunk
*getChunk() { return c
; }
292 // This class represents a symbol defined in an archive file. It is
293 // created from an archive file header, and it knows how to load an
294 // object file from an archive to replace itself with a defined
295 // symbol. If the resolver finds both Undefined and LazyArchive for
296 // the same name, it will ask the LazyArchive to load a file.
297 class LazyArchive
: public Symbol
{
299 LazyArchive(ArchiveFile
*f
, const Archive::Symbol s
)
300 : Symbol(LazyArchiveKind
, s
.getName()), file(f
), sym(s
) {}
302 static bool classof(const Symbol
*s
) { return s
->kind() == LazyArchiveKind
; }
304 MemoryBufferRef
getMemberBuffer();
307 const Archive::Symbol sym
;
310 class LazyObject
: public Symbol
{
312 LazyObject(InputFile
*f
, StringRef n
) : Symbol(LazyObjectKind
, n
), file(f
) {}
313 static bool classof(const Symbol
*s
) { return s
->kind() == LazyObjectKind
; }
318 class LazyDLLSymbol
: public Symbol
{
320 LazyDLLSymbol(DLLFile
*f
, DLLFile::Symbol
*s
, StringRef n
)
321 : Symbol(LazyDLLSymbolKind
, n
), file(f
), sym(s
) {}
322 static bool classof(const Symbol
*s
) {
323 return s
->kind() == LazyDLLSymbolKind
;
327 DLLFile::Symbol
*sym
;
330 // Undefined symbols.
331 class Undefined
: public Symbol
{
333 explicit Undefined(StringRef n
) : Symbol(UndefinedKind
, n
) {}
335 static bool classof(const Symbol
*s
) { return s
->kind() == UndefinedKind
; }
337 // An undefined symbol can have a fallback symbol which gives an
338 // undefined symbol a second chance if it would remain undefined.
339 // If it remains undefined, it'll be replaced with whatever the
340 // Alias pointer points to.
341 Symbol
*weakAlias
= nullptr;
343 // If this symbol is external weak, try to resolve it to a defined
344 // symbol by searching the chain of fallback symbols. Returns the symbol if
345 // successful, otherwise returns null.
346 Symbol
*getWeakAlias();
347 Defined
*getDefinedWeakAlias() {
348 return dyn_cast_or_null
<Defined
>(getWeakAlias());
351 void setWeakAlias(Symbol
*sym
, bool antiDep
= false) {
356 bool isECAlias(MachineTypes machine
) const {
357 return weakAlias
&& isAntiDep
&& isArm64EC(machine
);
360 // If this symbol is external weak, replace this object with aliased symbol.
361 bool resolveWeakAlias();
364 // Windows-specific classes.
366 // This class represents a symbol imported from a DLL. This has two
367 // names for internal use and external use. The former is used for
368 // name resolution, and the latter is used for the import descriptor
369 // table in an output. The former has "__imp_" prefix.
370 class DefinedImportData
: public Defined
{
372 DefinedImportData(StringRef n
, ImportFile
*file
, Chunk
*&location
)
373 : Defined(DefinedImportDataKind
, n
), file(file
), location(location
) {}
375 static bool classof(const Symbol
*s
) {
376 return s
->kind() == DefinedImportDataKind
;
379 uint64_t getRVA() { return getChunk()->getRVA(); }
380 Chunk
*getChunk() { return location
; }
381 void setLocation(Chunk
*addressTable
) { location
= addressTable
; }
383 StringRef
getDLLName() { return file
->dllName
; }
384 StringRef
getExternalName() { return file
->externalName
; }
385 uint16_t getOrdinal() { return file
->hdr
->OrdinalHint
; }
390 // This is a pointer to the synthetic symbol associated with the load thunk
391 // for this symbol that will be called if the DLL is delay-loaded. This is
392 // needed for Control Flow Guard because if this DefinedImportData symbol is a
393 // valid call target, the corresponding load thunk must also be marked as a
394 // valid call target.
395 DefinedSynthetic
*loadThunkSym
= nullptr;
398 // This class represents a symbol for a jump table entry which jumps
399 // to a function in a DLL. Linker are supposed to create such symbols
400 // without "__imp_" prefix for all function symbols exported from
401 // DLLs, so that you can call DLL functions as regular functions with
402 // a regular name. A function pointer is given as a DefinedImportData.
403 class DefinedImportThunk
: public Defined
{
405 DefinedImportThunk(COFFLinkerContext
&ctx
, StringRef name
,
406 DefinedImportData
*s
, ImportThunkChunk
*chunk
);
408 static bool classof(const Symbol
*s
) {
409 return s
->kind() == DefinedImportThunkKind
;
412 uint64_t getRVA() { return data
->getRVA(); }
413 ImportThunkChunk
*getChunk() const { return data
; }
415 DefinedImportData
*wrappedSym
;
418 ImportThunkChunk
*data
;
421 // If you have a symbol "foo" in your object file, a symbol name
422 // "__imp_foo" becomes automatically available as a pointer to "foo".
423 // This class is for such automatically-created symbols.
424 // Yes, this is an odd feature. We didn't intend to implement that.
425 // This is here just for compatibility with MSVC.
426 class DefinedLocalImport
: public Defined
{
428 DefinedLocalImport(COFFLinkerContext
&ctx
, StringRef n
, Defined
*s
)
429 : Defined(DefinedLocalImportKind
, n
),
430 data(make
<LocalImportChunk
>(ctx
, s
)) {}
432 static bool classof(const Symbol
*s
) {
433 return s
->kind() == DefinedLocalImportKind
;
436 uint64_t getRVA() { return data
->getRVA(); }
437 Chunk
*getChunk() { return data
; }
440 LocalImportChunk
*data
;
443 inline uint64_t Defined::getRVA() {
445 case DefinedAbsoluteKind
:
446 return cast
<DefinedAbsolute
>(this)->getRVA();
447 case DefinedSyntheticKind
:
448 return cast
<DefinedSynthetic
>(this)->getRVA();
449 case DefinedImportDataKind
:
450 return cast
<DefinedImportData
>(this)->getRVA();
451 case DefinedImportThunkKind
:
452 return cast
<DefinedImportThunk
>(this)->getRVA();
453 case DefinedLocalImportKind
:
454 return cast
<DefinedLocalImport
>(this)->getRVA();
455 case DefinedCommonKind
:
456 return cast
<DefinedCommon
>(this)->getRVA();
457 case DefinedRegularKind
:
458 return cast
<DefinedRegular
>(this)->getRVA();
459 case LazyArchiveKind
:
461 case LazyDLLSymbolKind
:
463 llvm_unreachable("Cannot get the address for an undefined symbol.");
465 llvm_unreachable("unknown symbol kind");
468 inline Chunk
*Defined::getChunk() {
470 case DefinedRegularKind
:
471 return cast
<DefinedRegular
>(this)->getChunk();
472 case DefinedAbsoluteKind
:
474 case DefinedSyntheticKind
:
475 return cast
<DefinedSynthetic
>(this)->getChunk();
476 case DefinedImportDataKind
:
477 return cast
<DefinedImportData
>(this)->getChunk();
478 case DefinedImportThunkKind
:
479 return cast
<DefinedImportThunk
>(this)->getChunk();
480 case DefinedLocalImportKind
:
481 return cast
<DefinedLocalImport
>(this)->getChunk();
482 case DefinedCommonKind
:
483 return cast
<DefinedCommon
>(this)->getChunk();
484 case LazyArchiveKind
:
486 case LazyDLLSymbolKind
:
488 llvm_unreachable("Cannot get the chunk of an undefined symbol.");
490 llvm_unreachable("unknown symbol kind");
493 // A buffer class that is large enough to hold any Symbol-derived
494 // object. We allocate memory using this class and instantiate a symbol
495 // using the placement new.
497 alignas(DefinedRegular
) char a
[sizeof(DefinedRegular
)];
498 alignas(DefinedCommon
) char b
[sizeof(DefinedCommon
)];
499 alignas(DefinedAbsolute
) char c
[sizeof(DefinedAbsolute
)];
500 alignas(DefinedSynthetic
) char d
[sizeof(DefinedSynthetic
)];
501 alignas(LazyArchive
) char e
[sizeof(LazyArchive
)];
502 alignas(Undefined
) char f
[sizeof(Undefined
)];
503 alignas(DefinedImportData
) char g
[sizeof(DefinedImportData
)];
504 alignas(DefinedImportThunk
) char h
[sizeof(DefinedImportThunk
)];
505 alignas(DefinedLocalImport
) char i
[sizeof(DefinedLocalImport
)];
506 alignas(LazyObject
) char j
[sizeof(LazyObject
)];
507 alignas(LazyDLLSymbol
) char k
[sizeof(LazyDLLSymbol
)];
510 template <typename T
, typename
... ArgT
>
511 void replaceSymbol(Symbol
*s
, ArgT
&&... arg
) {
512 static_assert(std::is_trivially_destructible
<T
>(),
513 "Symbol types must be trivially destructible");
514 static_assert(sizeof(T
) <= sizeof(SymbolUnion
), "Symbol too small");
515 static_assert(alignof(T
) <= alignof(SymbolUnion
),
516 "SymbolUnion not aligned enough");
517 assert(static_cast<Symbol
*>(static_cast<T
*>(nullptr)) == nullptr &&
519 bool canInline
= s
->canInline
;
520 bool isUsedInRegularObj
= s
->isUsedInRegularObj
;
521 new (s
) T(std::forward
<ArgT
>(arg
)...);
522 s
->canInline
= canInline
;
523 s
->isUsedInRegularObj
= isUsedInRegularObj
;
527 std::string
toString(const coff::COFFLinkerContext
&ctx
, coff::Symbol
&b
);
528 std::string
toCOFFString(const coff::COFFLinkerContext
&ctx
,
529 const llvm::object::Archive::Symbol
&b
);