Symbols.h revision 360784
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
23namespace lld {
24
25std::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.
30std::string toCOFFString(const coff::Archive::Symbol &b);
31
32namespace coff {
33
34using llvm::object::Archive;
35using llvm::object::COFFSymbolRef;
36using llvm::object::coff_import_header;
37using llvm::object::coff_symbol_generic;
38
39class ArchiveFile;
40class InputFile;
41class ObjFile;
42class SymbolTable;
43
44// The base class for real symbol classes.
45class Symbol {
46public:
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
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
83  bool isLazy() const {
84    return symbolKind == LazyArchiveKind || symbolKind == LazyObjectKind;
85  }
86
87protected:
88  friend SymbolTable;
89  explicit Symbol(Kind k, StringRef n = "")
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
98public:
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
119protected:
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.
128class Defined : public Symbol {
129public:
130  Defined(Kind k, StringRef n) : Symbol(k, n) {}
131
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.
147class DefinedCOFF : public Defined {
148  friend Symbol;
149
150public:
151  DefinedCOFF(Kind k, InputFile *f, StringRef n, const coff_symbol_generic *s)
152      : Defined(k, n), file(f), sym(s) {}
153
154  static bool classof(const Symbol *s) {
155    return s->kind() <= LastDefinedCOFFKind;
156  }
157
158  InputFile *getFile() { return file; }
159
160  COFFSymbolRef getCOFFSymbol();
161
162  InputFile *file;
163
164protected:
165  const coff_symbol_generic *sym;
166};
167
168// Regular defined symbols read from object file symbol tables.
169class DefinedRegular : public DefinedCOFF {
170public:
171  DefinedRegular(InputFile *f, StringRef n, bool isCOMDAT,
172                 bool isExternal = false,
173                 const coff_symbol_generic *s = nullptr,
174                 SectionChunk *c = nullptr)
175      : DefinedCOFF(DefinedRegularKind, f, n, s), data(c ? &c->repl : nullptr) {
176    this->isExternal = isExternal;
177    this->isCOMDAT = isCOMDAT;
178  }
179
180  static bool classof(const Symbol *s) {
181    return s->kind() == DefinedRegularKind;
182  }
183
184  uint64_t getRVA() const { return (*data)->getRVA() + sym->Value; }
185  SectionChunk *getChunk() const { return *data; }
186  uint32_t getValue() const { return sym->Value; }
187
188  SectionChunk **data;
189};
190
191class DefinedCommon : public DefinedCOFF {
192public:
193  DefinedCommon(InputFile *f, StringRef n, uint64_t size,
194                const coff_symbol_generic *s = nullptr,
195                CommonChunk *c = nullptr)
196      : DefinedCOFF(DefinedCommonKind, f, n, s), data(c), size(size) {
197    this->isExternal = true;
198  }
199
200  static bool classof(const Symbol *s) {
201    return s->kind() == DefinedCommonKind;
202  }
203
204  uint64_t getRVA() { return data->getRVA(); }
205  CommonChunk *getChunk() { return data; }
206
207private:
208  friend SymbolTable;
209  uint64_t getSize() const { return size; }
210  CommonChunk *data;
211  uint64_t size;
212};
213
214// Absolute symbols.
215class DefinedAbsolute : public Defined {
216public:
217  DefinedAbsolute(StringRef n, COFFSymbolRef s)
218      : Defined(DefinedAbsoluteKind, n), va(s.getValue()) {
219    isExternal = s.isExternal();
220  }
221
222  DefinedAbsolute(StringRef n, uint64_t v)
223      : Defined(DefinedAbsoluteKind, n), va(v) {}
224
225  static bool classof(const Symbol *s) {
226    return s->kind() == DefinedAbsoluteKind;
227  }
228
229  uint64_t getRVA() { return va - config->imageBase; }
230  void setVA(uint64_t v) { va = v; }
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
238private:
239  uint64_t va;
240};
241
242// This symbol is used for linker-synthesized symbols like __ImageBase and
243// __safe_se_handler_table.
244class DefinedSynthetic : public Defined {
245public:
246  explicit DefinedSynthetic(StringRef name, Chunk *c)
247      : Defined(DefinedSyntheticKind, name), c(c) {}
248
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.
255  uint32_t getRVA() { return c ? c->getRVA() : 0; }
256  Chunk *getChunk() { return c; }
257
258private:
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.
267class LazyArchive : public Symbol {
268public:
269  LazyArchive(ArchiveFile *f, const Archive::Symbol s)
270      : Symbol(LazyArchiveKind, s.getName()), file(f), sym(s) {}
271
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
280class LazyObject : public Symbol {
281public:
282  LazyObject(LazyObjFile *f, StringRef n)
283      : Symbol(LazyObjectKind, n), file(f) {}
284  static bool classof(const Symbol *s) { return s->kind() == LazyObjectKind; }
285  LazyObjFile *file;
286};
287
288// Undefined symbols.
289class Undefined : public Symbol {
290public:
291  explicit Undefined(StringRef n) : Symbol(UndefinedKind, n) {}
292
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.
313class DefinedImportData : public Defined {
314public:
315  DefinedImportData(StringRef n, ImportFile *f)
316      : Defined(DefinedImportDataKind, n), file(f) {
317  }
318
319  static bool classof(const Symbol *s) {
320    return s->kind() == DefinedImportDataKind;
321  }
322
323  uint64_t getRVA() { return file->location->getRVA(); }
324  Chunk *getChunk() { return file->location; }
325  void setLocation(Chunk *addressTable) { file->location = addressTable; }
326
327  StringRef getDLLName() { return file->dllName; }
328  StringRef getExternalName() { return file->externalName; }
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.
339class DefinedImportThunk : public Defined {
340public:
341  DefinedImportThunk(StringRef name, DefinedImportData *s, uint16_t machine);
342
343  static bool classof(const Symbol *s) {
344    return s->kind() == DefinedImportThunkKind;
345  }
346
347  uint64_t getRVA() { return data->getRVA(); }
348  Chunk *getChunk() { return data; }
349
350  DefinedImportData *wrappedSym;
351
352private:
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.
361class DefinedLocalImport : public Defined {
362public:
363  DefinedLocalImport(StringRef n, Defined *s)
364      : Defined(DefinedLocalImportKind, n), data(make<LocalImportChunk>(s)) {}
365
366  static bool classof(const Symbol *s) {
367    return s->kind() == DefinedLocalImportKind;
368  }
369
370  uint64_t getRVA() { return data->getRVA(); }
371  Chunk *getChunk() { return data; }
372
373private:
374  LocalImportChunk *data;
375};
376
377inline 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
401inline 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.
428union 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
441template <typename T, typename... ArgT>
442void 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