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