1 //===- Symbols.h ------------------------------------------------*- C++ -*-===//
2 //
3 // The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLD_COFF_SYMBOLS_H
11 #define LLD_COFF_SYMBOLS_H
12
13 #include "Chunks.h"
14 #include "Config.h"
15 #include "lld/Common/LLVM.h"
16 #include "lld/Common/Memory.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/Object/Archive.h"
19 #include "llvm/Object/COFF.h"
20 #include <atomic>
21 #include <memory>
22 #include <vector>
23
24 namespace lld {
25 namespace coff {
26
27 using llvm::object::Archive;
28 using llvm::object::COFFSymbolRef;
29 using llvm::object::coff_import_header;
30 using llvm::object::coff_symbol_generic;
31
32 class ArchiveFile;
33 class InputFile;
34 class ObjFile;
35 class SymbolTable;
36
37 // The base class for real symbol classes.
38 class Symbol {
39 public:
40 enum Kind {
41 // The order of these is significant. We start with the regular defined
42 // symbols as those are the most prevalent and the zero tag is the cheapest
43 // to set. Among the defined kinds, the lower the kind is preferred over
44 // the higher kind when testing whether one symbol should take precedence
45 // over another.
46 DefinedRegularKind = 0,
47 DefinedCommonKind,
48 DefinedLocalImportKind,
49 DefinedImportThunkKind,
50 DefinedImportDataKind,
51 DefinedAbsoluteKind,
52 DefinedSyntheticKind,
53
54 UndefinedKind,
55 LazyKind,
56
57 LastDefinedCOFFKind = DefinedCommonKind,
58 LastDefinedKind = DefinedSyntheticKind,
59 };
60
kind()61 Kind kind() const { return static_cast<Kind>(SymbolKind); }
62
63 // Returns true if this is an external symbol.
isExternal()64 bool isExternal() { return IsExternal; }
65
66 // Returns the symbol name.
67 StringRef getName();
68
69 void replaceKeepingName(Symbol *Other, size_t Size);
70
71 // Returns the file from which this symbol was created.
72 InputFile *getFile();
73
74 // Indicates that this symbol will be included in the final image. Only valid
75 // after calling markLive.
76 bool isLive() const;
77
78 protected:
79 friend SymbolTable;
80 explicit Symbol(Kind K, StringRef N = "")
SymbolKind(K)81 : SymbolKind(K), IsExternal(true), IsCOMDAT(false),
82 WrittenToSymtab(false), PendingArchiveLoad(false), IsGCRoot(false),
83 IsRuntimePseudoReloc(false), Name(N) {}
84
85 const unsigned SymbolKind : 8;
86 unsigned IsExternal : 1;
87
88 // This bit is used by the \c DefinedRegular subclass.
89 unsigned IsCOMDAT : 1;
90
91 public:
92 // This bit is used by Writer::createSymbolAndStringTable() to prevent
93 // symbols from being written to the symbol table more than once.
94 unsigned WrittenToSymtab : 1;
95
96 // True if this symbol was referenced by a regular (non-bitcode) object.
97 unsigned IsUsedInRegularObj : 1;
98
99 // True if we've seen both a lazy and an undefined symbol with this symbol
100 // name, which means that we have enqueued an archive member load and should
101 // not load any more archive members to resolve the same symbol.
102 unsigned PendingArchiveLoad : 1;
103
104 /// True if we've already added this symbol to the list of GC roots.
105 unsigned IsGCRoot : 1;
106
107 unsigned IsRuntimePseudoReloc : 1;
108
109 protected:
110 StringRef Name;
111 };
112
113 // The base class for any defined symbols, including absolute symbols,
114 // etc.
115 class Defined : public Symbol {
116 public:
Defined(Kind K,StringRef N)117 Defined(Kind K, StringRef N) : Symbol(K, N) {}
118
classof(const Symbol * S)119 static bool classof(const Symbol *S) { return S->kind() <= LastDefinedKind; }
120
121 // Returns the RVA (relative virtual address) of this symbol. The
122 // writer sets and uses RVAs.
123 uint64_t getRVA();
124
125 // Returns the chunk containing this symbol. Absolute symbols and __ImageBase
126 // do not have chunks, so this may return null.
127 Chunk *getChunk();
128 };
129
130 // Symbols defined via a COFF object file or bitcode file. For COFF files, this
131 // stores a coff_symbol_generic*, and names of internal symbols are lazily
132 // loaded through that. For bitcode files, Sym is nullptr and the name is stored
133 // as a StringRef.
134 class DefinedCOFF : public Defined {
135 friend Symbol;
136
137 public:
DefinedCOFF(Kind K,InputFile * F,StringRef N,const coff_symbol_generic * S)138 DefinedCOFF(Kind K, InputFile *F, StringRef N, const coff_symbol_generic *S)
139 : Defined(K, N), File(F), Sym(S) {}
140
classof(const Symbol * S)141 static bool classof(const Symbol *S) {
142 return S->kind() <= LastDefinedCOFFKind;
143 }
144
getFile()145 InputFile *getFile() { return File; }
146
147 COFFSymbolRef getCOFFSymbol();
148
149 InputFile *File;
150
151 protected:
152 const coff_symbol_generic *Sym;
153 };
154
155 // Regular defined symbols read from object file symbol tables.
156 class DefinedRegular : public DefinedCOFF {
157 public:
158 DefinedRegular(InputFile *F, StringRef N, bool IsCOMDAT,
159 bool IsExternal = false,
160 const coff_symbol_generic *S = nullptr,
161 SectionChunk *C = nullptr)
DefinedCOFF(DefinedRegularKind,F,N,S)162 : DefinedCOFF(DefinedRegularKind, F, N, S), Data(C ? &C->Repl : nullptr) {
163 this->IsExternal = IsExternal;
164 this->IsCOMDAT = IsCOMDAT;
165 }
166
classof(const Symbol * S)167 static bool classof(const Symbol *S) {
168 return S->kind() == DefinedRegularKind;
169 }
170
getRVA()171 uint64_t getRVA() const { return (*Data)->getRVA() + Sym->Value; }
isCOMDAT()172 bool isCOMDAT() const { return IsCOMDAT; }
getChunk()173 SectionChunk *getChunk() const { return *Data; }
getValue()174 uint32_t getValue() const { return Sym->Value; }
175
176 SectionChunk **Data;
177 };
178
179 class DefinedCommon : public DefinedCOFF {
180 public:
181 DefinedCommon(InputFile *F, StringRef N, uint64_t Size,
182 const coff_symbol_generic *S = nullptr,
183 CommonChunk *C = nullptr)
DefinedCOFF(DefinedCommonKind,F,N,S)184 : DefinedCOFF(DefinedCommonKind, F, N, S), Data(C), Size(Size) {
185 this->IsExternal = true;
186 }
187
classof(const Symbol * S)188 static bool classof(const Symbol *S) {
189 return S->kind() == DefinedCommonKind;
190 }
191
getRVA()192 uint64_t getRVA() { return Data->getRVA(); }
getChunk()193 CommonChunk *getChunk() { return Data; }
194
195 private:
196 friend SymbolTable;
getSize()197 uint64_t getSize() const { return Size; }
198 CommonChunk *Data;
199 uint64_t Size;
200 };
201
202 // Absolute symbols.
203 class DefinedAbsolute : public Defined {
204 public:
DefinedAbsolute(StringRef N,COFFSymbolRef S)205 DefinedAbsolute(StringRef N, COFFSymbolRef S)
206 : Defined(DefinedAbsoluteKind, N), VA(S.getValue()) {
207 IsExternal = S.isExternal();
208 }
209
DefinedAbsolute(StringRef N,uint64_t V)210 DefinedAbsolute(StringRef N, uint64_t V)
211 : Defined(DefinedAbsoluteKind, N), VA(V) {}
212
classof(const Symbol * S)213 static bool classof(const Symbol *S) {
214 return S->kind() == DefinedAbsoluteKind;
215 }
216
getRVA()217 uint64_t getRVA() { return VA - Config->ImageBase; }
setVA(uint64_t V)218 void setVA(uint64_t V) { VA = V; }
219
220 // Section index relocations against absolute symbols resolve to
221 // this 16 bit number, and it is the largest valid section index
222 // plus one. This variable keeps it.
223 static uint16_t NumOutputSections;
224
225 private:
226 uint64_t VA;
227 };
228
229 // This symbol is used for linker-synthesized symbols like __ImageBase and
230 // __safe_se_handler_table.
231 class DefinedSynthetic : public Defined {
232 public:
DefinedSynthetic(StringRef Name,Chunk * C)233 explicit DefinedSynthetic(StringRef Name, Chunk *C)
234 : Defined(DefinedSyntheticKind, Name), C(C) {}
235
classof(const Symbol * S)236 static bool classof(const Symbol *S) {
237 return S->kind() == DefinedSyntheticKind;
238 }
239
240 // A null chunk indicates that this is __ImageBase. Otherwise, this is some
241 // other synthesized chunk, like SEHTableChunk.
getRVA()242 uint32_t getRVA() { return C ? C->getRVA() : 0; }
getChunk()243 Chunk *getChunk() { return C; }
244
245 private:
246 Chunk *C;
247 };
248
249 // This class represents a symbol defined in an archive file. It is
250 // created from an archive file header, and it knows how to load an
251 // object file from an archive to replace itself with a defined
252 // symbol. If the resolver finds both Undefined and Lazy for
253 // the same name, it will ask the Lazy to load a file.
254 class Lazy : public Symbol {
255 public:
Lazy(ArchiveFile * F,const Archive::Symbol S)256 Lazy(ArchiveFile *F, const Archive::Symbol S)
257 : Symbol(LazyKind, S.getName()), File(F), Sym(S) {}
258
classof(const Symbol * S)259 static bool classof(const Symbol *S) { return S->kind() == LazyKind; }
260
261 ArchiveFile *File;
262
263 private:
264 friend SymbolTable;
265
266 private:
267 const Archive::Symbol Sym;
268 };
269
270 // Undefined symbols.
271 class Undefined : public Symbol {
272 public:
Undefined(StringRef N)273 explicit Undefined(StringRef N) : Symbol(UndefinedKind, N) {}
274
classof(const Symbol * S)275 static bool classof(const Symbol *S) { return S->kind() == UndefinedKind; }
276
277 // An undefined symbol can have a fallback symbol which gives an
278 // undefined symbol a second chance if it would remain undefined.
279 // If it remains undefined, it'll be replaced with whatever the
280 // Alias pointer points to.
281 Symbol *WeakAlias = nullptr;
282
283 // If this symbol is external weak, try to resolve it to a defined
284 // symbol by searching the chain of fallback symbols. Returns the symbol if
285 // successful, otherwise returns null.
286 Defined *getWeakAlias();
287 };
288
289 // Windows-specific classes.
290
291 // This class represents a symbol imported from a DLL. This has two
292 // names for internal use and external use. The former is used for
293 // name resolution, and the latter is used for the import descriptor
294 // table in an output. The former has "__imp_" prefix.
295 class DefinedImportData : public Defined {
296 public:
DefinedImportData(StringRef N,ImportFile * F)297 DefinedImportData(StringRef N, ImportFile *F)
298 : Defined(DefinedImportDataKind, N), File(F) {
299 }
300
classof(const Symbol * S)301 static bool classof(const Symbol *S) {
302 return S->kind() == DefinedImportDataKind;
303 }
304
getRVA()305 uint64_t getRVA() { return File->Location->getRVA(); }
getChunk()306 Chunk *getChunk() { return File->Location; }
setLocation(Chunk * AddressTable)307 void setLocation(Chunk *AddressTable) { File->Location = AddressTable; }
308
getDLLName()309 StringRef getDLLName() { return File->DLLName; }
getExternalName()310 StringRef getExternalName() { return File->ExternalName; }
getOrdinal()311 uint16_t getOrdinal() { return File->Hdr->OrdinalHint; }
312
313 ImportFile *File;
314 };
315
316 // This class represents a symbol for a jump table entry which jumps
317 // to a function in a DLL. Linker are supposed to create such symbols
318 // without "__imp_" prefix for all function symbols exported from
319 // DLLs, so that you can call DLL functions as regular functions with
320 // a regular name. A function pointer is given as a DefinedImportData.
321 class DefinedImportThunk : public Defined {
322 public:
323 DefinedImportThunk(StringRef Name, DefinedImportData *S, uint16_t Machine);
324
classof(const Symbol * S)325 static bool classof(const Symbol *S) {
326 return S->kind() == DefinedImportThunkKind;
327 }
328
getRVA()329 uint64_t getRVA() { return Data->getRVA(); }
getChunk()330 Chunk *getChunk() { return Data; }
331
332 DefinedImportData *WrappedSym;
333
334 private:
335 Chunk *Data;
336 };
337
338 // If you have a symbol "foo" in your object file, a symbol name
339 // "__imp_foo" becomes automatically available as a pointer to "foo".
340 // This class is for such automatically-created symbols.
341 // Yes, this is an odd feature. We didn't intend to implement that.
342 // This is here just for compatibility with MSVC.
343 class DefinedLocalImport : public Defined {
344 public:
DefinedLocalImport(StringRef N,Defined * S)345 DefinedLocalImport(StringRef N, Defined *S)
346 : Defined(DefinedLocalImportKind, N), Data(make<LocalImportChunk>(S)) {}
347
classof(const Symbol * S)348 static bool classof(const Symbol *S) {
349 return S->kind() == DefinedLocalImportKind;
350 }
351
getRVA()352 uint64_t getRVA() { return Data->getRVA(); }
getChunk()353 Chunk *getChunk() { return Data; }
354
355 private:
356 LocalImportChunk *Data;
357 };
358
getRVA()359 inline uint64_t Defined::getRVA() {
360 switch (kind()) {
361 case DefinedAbsoluteKind:
362 return cast<DefinedAbsolute>(this)->getRVA();
363 case DefinedSyntheticKind:
364 return cast<DefinedSynthetic>(this)->getRVA();
365 case DefinedImportDataKind:
366 return cast<DefinedImportData>(this)->getRVA();
367 case DefinedImportThunkKind:
368 return cast<DefinedImportThunk>(this)->getRVA();
369 case DefinedLocalImportKind:
370 return cast<DefinedLocalImport>(this)->getRVA();
371 case DefinedCommonKind:
372 return cast<DefinedCommon>(this)->getRVA();
373 case DefinedRegularKind:
374 return cast<DefinedRegular>(this)->getRVA();
375 case LazyKind:
376 case UndefinedKind:
377 llvm_unreachable("Cannot get the address for an undefined symbol.");
378 }
379 llvm_unreachable("unknown symbol kind");
380 }
381
getChunk()382 inline Chunk *Defined::getChunk() {
383 switch (kind()) {
384 case DefinedRegularKind:
385 return cast<DefinedRegular>(this)->getChunk();
386 case DefinedAbsoluteKind:
387 return nullptr;
388 case DefinedSyntheticKind:
389 return cast<DefinedSynthetic>(this)->getChunk();
390 case DefinedImportDataKind:
391 return cast<DefinedImportData>(this)->getChunk();
392 case DefinedImportThunkKind:
393 return cast<DefinedImportThunk>(this)->getChunk();
394 case DefinedLocalImportKind:
395 return cast<DefinedLocalImport>(this)->getChunk();
396 case DefinedCommonKind:
397 return cast<DefinedCommon>(this)->getChunk();
398 case LazyKind:
399 case UndefinedKind:
400 llvm_unreachable("Cannot get the chunk of an undefined symbol.");
401 }
402 llvm_unreachable("unknown symbol kind");
403 }
404
405 // A buffer class that is large enough to hold any Symbol-derived
406 // object. We allocate memory using this class and instantiate a symbol
407 // using the placement new.
408 union SymbolUnion {
409 alignas(DefinedRegular) char A[sizeof(DefinedRegular)];
410 alignas(DefinedCommon) char B[sizeof(DefinedCommon)];
411 alignas(DefinedAbsolute) char C[sizeof(DefinedAbsolute)];
412 alignas(DefinedSynthetic) char D[sizeof(DefinedSynthetic)];
413 alignas(Lazy) char E[sizeof(Lazy)];
414 alignas(Undefined) char F[sizeof(Undefined)];
415 alignas(DefinedImportData) char G[sizeof(DefinedImportData)];
416 alignas(DefinedImportThunk) char H[sizeof(DefinedImportThunk)];
417 alignas(DefinedLocalImport) char I[sizeof(DefinedLocalImport)];
418 };
419
420 template <typename T, typename... ArgT>
replaceSymbol(Symbol * S,ArgT &&...Arg)421 void replaceSymbol(Symbol *S, ArgT &&... Arg) {
422 static_assert(std::is_trivially_destructible<T>(),
423 "Symbol types must be trivially destructible");
424 static_assert(sizeof(T) <= sizeof(SymbolUnion), "Symbol too small");
425 static_assert(alignof(T) <= alignof(SymbolUnion),
426 "SymbolUnion not aligned enough");
427 assert(static_cast<Symbol *>(static_cast<T *>(nullptr)) == nullptr &&
428 "Not a Symbol");
429 new (S) T(std::forward<ArgT>(Arg)...);
430 }
431 } // namespace coff
432
433 std::string toString(coff::Symbol &B);
434 } // namespace lld
435
436 #endif
437