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     LazyDLLSymbolKind,
65 
66     LastDefinedCOFFKind = DefinedCommonKind,
67     LastDefinedKind = DefinedSyntheticKind,
68   };
69 
kind()70   Kind kind() const { return static_cast<Kind>(symbolKind); }
71 
72   // Returns the symbol name.
getName()73   StringRef getName() {
74     // COFF symbol names are read lazily for a performance reason.
75     // Non-external symbol names are never used by the linker except for logging
76     // or debugging. Their internal references are resolved not by name but by
77     // symbol index. And because they are not external, no one can refer them by
78     // name. Object files contain lots of non-external symbols, and creating
79     // StringRefs for them (which involves lots of strlen() on the string table)
80     // is a waste of time.
81     if (nameData == nullptr)
82       computeName();
83     return StringRef(nameData, nameSize);
84   }
85 
86   void replaceKeepingName(Symbol *other, size_t size);
87 
88   // Returns the file from which this symbol was created.
89   InputFile *getFile();
90 
91   // Indicates that this symbol will be included in the final image. Only valid
92   // after calling markLive.
93   bool isLive() const;
94 
isLazy()95   bool isLazy() const {
96     return symbolKind == LazyArchiveKind || symbolKind == LazyObjectKind ||
97            symbolKind == LazyDLLSymbolKind;
98   }
99 
100 private:
101   void computeName();
102 
103 protected:
104   friend SymbolTable;
105   explicit Symbol(Kind k, StringRef n = "")
symbolKind(k)106       : symbolKind(k), isExternal(true), isCOMDAT(false),
107         writtenToSymtab(false), pendingArchiveLoad(false), isGCRoot(false),
108         isRuntimePseudoReloc(false), deferUndefined(false), canInline(true),
109         nameSize(n.size()), nameData(n.empty() ? nullptr : n.data()) {}
110 
111   const unsigned symbolKind : 8;
112   unsigned isExternal : 1;
113 
114 public:
115   // This bit is used by the \c DefinedRegular subclass.
116   unsigned isCOMDAT : 1;
117 
118   // This bit is used by Writer::createSymbolAndStringTable() to prevent
119   // symbols from being written to the symbol table more than once.
120   unsigned writtenToSymtab : 1;
121 
122   // True if this symbol was referenced by a regular (non-bitcode) object.
123   unsigned isUsedInRegularObj : 1;
124 
125   // True if we've seen both a lazy and an undefined symbol with this symbol
126   // name, which means that we have enqueued an archive member load and should
127   // not load any more archive members to resolve the same symbol.
128   unsigned pendingArchiveLoad : 1;
129 
130   /// True if we've already added this symbol to the list of GC roots.
131   unsigned isGCRoot : 1;
132 
133   unsigned isRuntimePseudoReloc : 1;
134 
135   // True if we want to allow this symbol to be undefined in the early
136   // undefined check pass in SymbolTable::reportUnresolvable(), as it
137   // might be fixed up later.
138   unsigned deferUndefined : 1;
139 
140   // False if LTO shouldn't inline whatever this symbol points to. If a symbol
141   // is overwritten after LTO, LTO shouldn't inline the symbol because it
142   // doesn't know the final contents of the symbol.
143   unsigned canInline : 1;
144 
145 protected:
146   // Symbol name length. Assume symbol lengths fit in a 32-bit integer.
147   uint32_t nameSize;
148 
149   const char *nameData;
150 };
151 
152 // The base class for any defined symbols, including absolute symbols,
153 // etc.
154 class Defined : public Symbol {
155 public:
Defined(Kind k,StringRef n)156   Defined(Kind k, StringRef n) : Symbol(k, n) {}
157 
classof(const Symbol * s)158   static bool classof(const Symbol *s) { return s->kind() <= LastDefinedKind; }
159 
160   // Returns the RVA (relative virtual address) of this symbol. The
161   // writer sets and uses RVAs.
162   uint64_t getRVA();
163 
164   // Returns the chunk containing this symbol. Absolute symbols and __ImageBase
165   // do not have chunks, so this may return null.
166   Chunk *getChunk();
167 };
168 
169 // Symbols defined via a COFF object file or bitcode file.  For COFF files, this
170 // stores a coff_symbol_generic*, and names of internal symbols are lazily
171 // loaded through that. For bitcode files, Sym is nullptr and the name is stored
172 // as a decomposed StringRef.
173 class DefinedCOFF : public Defined {
174   friend Symbol;
175 
176 public:
DefinedCOFF(Kind k,InputFile * f,StringRef n,const coff_symbol_generic * s)177   DefinedCOFF(Kind k, InputFile *f, StringRef n, const coff_symbol_generic *s)
178       : Defined(k, n), file(f), sym(s) {}
179 
classof(const Symbol * s)180   static bool classof(const Symbol *s) {
181     return s->kind() <= LastDefinedCOFFKind;
182   }
183 
getFile()184   InputFile *getFile() { return file; }
185 
186   COFFSymbolRef getCOFFSymbol();
187 
188   InputFile *file;
189 
190 protected:
191   const coff_symbol_generic *sym;
192 };
193 
194 // Regular defined symbols read from object file symbol tables.
195 class DefinedRegular : public DefinedCOFF {
196 public:
197   DefinedRegular(InputFile *f, StringRef n, bool isCOMDAT,
198                  bool isExternal = false,
199                  const coff_symbol_generic *s = nullptr,
200                  SectionChunk *c = nullptr)
DefinedCOFF(DefinedRegularKind,f,n,s)201       : DefinedCOFF(DefinedRegularKind, f, n, s), data(c ? &c->repl : nullptr) {
202     this->isExternal = isExternal;
203     this->isCOMDAT = isCOMDAT;
204   }
205 
classof(const Symbol * s)206   static bool classof(const Symbol *s) {
207     return s->kind() == DefinedRegularKind;
208   }
209 
getRVA()210   uint64_t getRVA() const { return (*data)->getRVA() + sym->Value; }
getChunk()211   SectionChunk *getChunk() const { return *data; }
getValue()212   uint32_t getValue() const { return sym->Value; }
213 
214   SectionChunk **data;
215 };
216 
217 class DefinedCommon : public DefinedCOFF {
218 public:
219   DefinedCommon(InputFile *f, StringRef n, uint64_t size,
220                 const coff_symbol_generic *s = nullptr,
221                 CommonChunk *c = nullptr)
DefinedCOFF(DefinedCommonKind,f,n,s)222       : DefinedCOFF(DefinedCommonKind, f, n, s), data(c), size(size) {
223     this->isExternal = true;
224   }
225 
classof(const Symbol * s)226   static bool classof(const Symbol *s) {
227     return s->kind() == DefinedCommonKind;
228   }
229 
getRVA()230   uint64_t getRVA() { return data->getRVA(); }
getChunk()231   CommonChunk *getChunk() { return data; }
232 
233 private:
234   friend SymbolTable;
getSize()235   uint64_t getSize() const { return size; }
236   CommonChunk *data;
237   uint64_t size;
238 };
239 
240 // Absolute symbols.
241 class DefinedAbsolute : public Defined {
242 public:
DefinedAbsolute(StringRef n,COFFSymbolRef s)243   DefinedAbsolute(StringRef n, COFFSymbolRef s)
244       : Defined(DefinedAbsoluteKind, n), va(s.getValue()) {
245     isExternal = s.isExternal();
246   }
247 
DefinedAbsolute(StringRef n,uint64_t v)248   DefinedAbsolute(StringRef n, uint64_t v)
249       : Defined(DefinedAbsoluteKind, n), va(v) {}
250 
classof(const Symbol * s)251   static bool classof(const Symbol *s) {
252     return s->kind() == DefinedAbsoluteKind;
253   }
254 
getRVA()255   uint64_t getRVA() { return va - config->imageBase; }
setVA(uint64_t v)256   void setVA(uint64_t v) { va = v; }
getVA()257   uint64_t getVA() const { return va; }
258 
259   // Section index relocations against absolute symbols resolve to
260   // this 16 bit number, and it is the largest valid section index
261   // plus one. This variable keeps it.
262   static uint16_t numOutputSections;
263 
264 private:
265   uint64_t va;
266 };
267 
268 // This symbol is used for linker-synthesized symbols like __ImageBase and
269 // __safe_se_handler_table.
270 class DefinedSynthetic : public Defined {
271 public:
DefinedSynthetic(StringRef name,Chunk * c)272   explicit DefinedSynthetic(StringRef name, Chunk *c)
273       : Defined(DefinedSyntheticKind, name), c(c) {}
274 
classof(const Symbol * s)275   static bool classof(const Symbol *s) {
276     return s->kind() == DefinedSyntheticKind;
277   }
278 
279   // A null chunk indicates that this is __ImageBase. Otherwise, this is some
280   // other synthesized chunk, like SEHTableChunk.
getRVA()281   uint32_t getRVA() { return c ? c->getRVA() : 0; }
getChunk()282   Chunk *getChunk() { return c; }
283 
284 private:
285   Chunk *c;
286 };
287 
288 // This class represents a symbol defined in an archive file. It is
289 // created from an archive file header, and it knows how to load an
290 // object file from an archive to replace itself with a defined
291 // symbol. If the resolver finds both Undefined and LazyArchive for
292 // the same name, it will ask the LazyArchive to load a file.
293 class LazyArchive : public Symbol {
294 public:
LazyArchive(ArchiveFile * f,const Archive::Symbol s)295   LazyArchive(ArchiveFile *f, const Archive::Symbol s)
296       : Symbol(LazyArchiveKind, s.getName()), file(f), sym(s) {}
297 
classof(const Symbol * s)298   static bool classof(const Symbol *s) { return s->kind() == LazyArchiveKind; }
299 
300   MemoryBufferRef getMemberBuffer();
301 
302   ArchiveFile *file;
303   const Archive::Symbol sym;
304 };
305 
306 class LazyObject : public Symbol {
307 public:
LazyObject(LazyObjFile * f,StringRef n)308   LazyObject(LazyObjFile *f, StringRef n)
309       : Symbol(LazyObjectKind, n), file(f) {}
classof(const Symbol * s)310   static bool classof(const Symbol *s) { return s->kind() == LazyObjectKind; }
311   LazyObjFile *file;
312 };
313 
314 // MinGW only.
315 class LazyDLLSymbol : public Symbol {
316 public:
LazyDLLSymbol(DLLFile * f,DLLFile::Symbol * s,StringRef n)317   LazyDLLSymbol(DLLFile *f, DLLFile::Symbol *s, StringRef n)
318       : Symbol(LazyDLLSymbolKind, n), file(f), sym(s) {}
classof(const Symbol * s)319   static bool classof(const Symbol *s) {
320     return s->kind() == LazyDLLSymbolKind;
321   }
322 
323   DLLFile *file;
324   DLLFile::Symbol *sym;
325 };
326 
327 // Undefined symbols.
328 class Undefined : public Symbol {
329 public:
Undefined(StringRef n)330   explicit Undefined(StringRef n) : Symbol(UndefinedKind, n) {}
331 
classof(const Symbol * s)332   static bool classof(const Symbol *s) { return s->kind() == UndefinedKind; }
333 
334   // An undefined symbol can have a fallback symbol which gives an
335   // undefined symbol a second chance if it would remain undefined.
336   // If it remains undefined, it'll be replaced with whatever the
337   // Alias pointer points to.
338   Symbol *weakAlias = nullptr;
339 
340   // If this symbol is external weak, try to resolve it to a defined
341   // symbol by searching the chain of fallback symbols. Returns the symbol if
342   // successful, otherwise returns null.
343   Defined *getWeakAlias();
344 };
345 
346 // Windows-specific classes.
347 
348 // This class represents a symbol imported from a DLL. This has two
349 // names for internal use and external use. The former is used for
350 // name resolution, and the latter is used for the import descriptor
351 // table in an output. The former has "__imp_" prefix.
352 class DefinedImportData : public Defined {
353 public:
DefinedImportData(StringRef n,ImportFile * f)354   DefinedImportData(StringRef n, ImportFile *f)
355       : Defined(DefinedImportDataKind, n), file(f) {
356   }
357 
classof(const Symbol * s)358   static bool classof(const Symbol *s) {
359     return s->kind() == DefinedImportDataKind;
360   }
361 
getRVA()362   uint64_t getRVA() { return file->location->getRVA(); }
getChunk()363   Chunk *getChunk() { return file->location; }
setLocation(Chunk * addressTable)364   void setLocation(Chunk *addressTable) { file->location = addressTable; }
365 
getDLLName()366   StringRef getDLLName() { return file->dllName; }
getExternalName()367   StringRef getExternalName() { return file->externalName; }
getOrdinal()368   uint16_t getOrdinal() { return file->hdr->OrdinalHint; }
369 
370   ImportFile *file;
371 
372   // This is a pointer to the synthetic symbol associated with the load thunk
373   // for this symbol that will be called if the DLL is delay-loaded. This is
374   // needed for Control Flow Guard because if this DefinedImportData symbol is a
375   // valid call target, the corresponding load thunk must also be marked as a
376   // valid call target.
377   DefinedSynthetic *loadThunkSym = nullptr;
378 };
379 
380 // This class represents a symbol for a jump table entry which jumps
381 // to a function in a DLL. Linker are supposed to create such symbols
382 // without "__imp_" prefix for all function symbols exported from
383 // DLLs, so that you can call DLL functions as regular functions with
384 // a regular name. A function pointer is given as a DefinedImportData.
385 class DefinedImportThunk : public Defined {
386 public:
387   DefinedImportThunk(StringRef name, DefinedImportData *s, uint16_t machine);
388 
classof(const Symbol * s)389   static bool classof(const Symbol *s) {
390     return s->kind() == DefinedImportThunkKind;
391   }
392 
getRVA()393   uint64_t getRVA() { return data->getRVA(); }
getChunk()394   Chunk *getChunk() { return data; }
395 
396   DefinedImportData *wrappedSym;
397 
398 private:
399   Chunk *data;
400 };
401 
402 // If you have a symbol "foo" in your object file, a symbol name
403 // "__imp_foo" becomes automatically available as a pointer to "foo".
404 // This class is for such automatically-created symbols.
405 // Yes, this is an odd feature. We didn't intend to implement that.
406 // This is here just for compatibility with MSVC.
407 class DefinedLocalImport : public Defined {
408 public:
DefinedLocalImport(StringRef n,Defined * s)409   DefinedLocalImport(StringRef n, Defined *s)
410       : Defined(DefinedLocalImportKind, n), data(make<LocalImportChunk>(s)) {}
411 
classof(const Symbol * s)412   static bool classof(const Symbol *s) {
413     return s->kind() == DefinedLocalImportKind;
414   }
415 
getRVA()416   uint64_t getRVA() { return data->getRVA(); }
getChunk()417   Chunk *getChunk() { return data; }
418 
419 private:
420   LocalImportChunk *data;
421 };
422 
getRVA()423 inline uint64_t Defined::getRVA() {
424   switch (kind()) {
425   case DefinedAbsoluteKind:
426     return cast<DefinedAbsolute>(this)->getRVA();
427   case DefinedSyntheticKind:
428     return cast<DefinedSynthetic>(this)->getRVA();
429   case DefinedImportDataKind:
430     return cast<DefinedImportData>(this)->getRVA();
431   case DefinedImportThunkKind:
432     return cast<DefinedImportThunk>(this)->getRVA();
433   case DefinedLocalImportKind:
434     return cast<DefinedLocalImport>(this)->getRVA();
435   case DefinedCommonKind:
436     return cast<DefinedCommon>(this)->getRVA();
437   case DefinedRegularKind:
438     return cast<DefinedRegular>(this)->getRVA();
439   case LazyArchiveKind:
440   case LazyObjectKind:
441   case LazyDLLSymbolKind:
442   case UndefinedKind:
443     llvm_unreachable("Cannot get the address for an undefined symbol.");
444   }
445   llvm_unreachable("unknown symbol kind");
446 }
447 
getChunk()448 inline Chunk *Defined::getChunk() {
449   switch (kind()) {
450   case DefinedRegularKind:
451     return cast<DefinedRegular>(this)->getChunk();
452   case DefinedAbsoluteKind:
453     return nullptr;
454   case DefinedSyntheticKind:
455     return cast<DefinedSynthetic>(this)->getChunk();
456   case DefinedImportDataKind:
457     return cast<DefinedImportData>(this)->getChunk();
458   case DefinedImportThunkKind:
459     return cast<DefinedImportThunk>(this)->getChunk();
460   case DefinedLocalImportKind:
461     return cast<DefinedLocalImport>(this)->getChunk();
462   case DefinedCommonKind:
463     return cast<DefinedCommon>(this)->getChunk();
464   case LazyArchiveKind:
465   case LazyObjectKind:
466   case LazyDLLSymbolKind:
467   case UndefinedKind:
468     llvm_unreachable("Cannot get the chunk of an undefined symbol.");
469   }
470   llvm_unreachable("unknown symbol kind");
471 }
472 
473 // A buffer class that is large enough to hold any Symbol-derived
474 // object. We allocate memory using this class and instantiate a symbol
475 // using the placement new.
476 union SymbolUnion {
477   alignas(DefinedRegular) char a[sizeof(DefinedRegular)];
478   alignas(DefinedCommon) char b[sizeof(DefinedCommon)];
479   alignas(DefinedAbsolute) char c[sizeof(DefinedAbsolute)];
480   alignas(DefinedSynthetic) char d[sizeof(DefinedSynthetic)];
481   alignas(LazyArchive) char e[sizeof(LazyArchive)];
482   alignas(Undefined) char f[sizeof(Undefined)];
483   alignas(DefinedImportData) char g[sizeof(DefinedImportData)];
484   alignas(DefinedImportThunk) char h[sizeof(DefinedImportThunk)];
485   alignas(DefinedLocalImport) char i[sizeof(DefinedLocalImport)];
486   alignas(LazyObject) char j[sizeof(LazyObject)];
487   alignas(LazyDLLSymbol) char k[sizeof(LazyDLLSymbol)];
488 };
489 
490 template <typename T, typename... ArgT>
replaceSymbol(Symbol * s,ArgT &&...arg)491 void replaceSymbol(Symbol *s, ArgT &&... arg) {
492   static_assert(std::is_trivially_destructible<T>(),
493                 "Symbol types must be trivially destructible");
494   static_assert(sizeof(T) <= sizeof(SymbolUnion), "Symbol too small");
495   static_assert(alignof(T) <= alignof(SymbolUnion),
496                 "SymbolUnion not aligned enough");
497   assert(static_cast<Symbol *>(static_cast<T *>(nullptr)) == nullptr &&
498          "Not a Symbol");
499   bool canInline = s->canInline;
500   new (s) T(std::forward<ArgT>(arg)...);
501   s->canInline = canInline;
502 }
503 } // namespace coff
504 
505 } // namespace lld
506 
507 #endif
508