]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/Symbols.h
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / ELF / Symbols.h
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 // This file defines various types of Symbols.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLD_ELF_SYMBOLS_H
15 #define LLD_ELF_SYMBOLS_H
16
17 #include "InputSection.h"
18 #include "lld/Common/LLVM.h"
19 #include "lld/Common/Strings.h"
20 #include "llvm/Object/Archive.h"
21 #include "llvm/Object/ELF.h"
22
23 namespace lld {
24 namespace elf {
25 class Symbol;
26 class InputFile;
27 } // namespace elf
28
29 std::string toString(const elf::Symbol &);
30 std::string toString(const elf::InputFile *);
31
32 namespace elf {
33
34 class ArchiveFile;
35 class BitcodeFile;
36 class BssSection;
37 class InputFile;
38 class LazyObjFile;
39 template <class ELFT> class ObjFile;
40 class OutputSection;
41 template <class ELFT> class SharedFile;
42
43 // This is a StringRef-like container that doesn't run strlen().
44 //
45 // ELF string tables contain a lot of null-terminated strings. Most of them
46 // are not necessary for the linker because they are names of local symbols,
47 // and the linker doesn't use local symbol names for name resolution. So, we
48 // use this class to represents strings read from string tables.
49 struct StringRefZ {
50   StringRefZ(const char *S) : Data(S), Size(-1) {}
51   StringRefZ(StringRef S) : Data(S.data()), Size(S.size()) {}
52
53   const char *Data;
54   const uint32_t Size;
55 };
56
57 // The base class for real symbol classes.
58 class Symbol {
59 public:
60   enum Kind {
61     PlaceholderKind,
62     DefinedKind,
63     SharedKind,
64     UndefinedKind,
65     LazyArchiveKind,
66     LazyObjectKind,
67   };
68
69   Kind kind() const { return static_cast<Kind>(SymbolKind); }
70
71   // The file from which this symbol was created.
72   InputFile *File;
73
74 protected:
75   const char *NameData;
76   mutable uint32_t NameSize;
77
78 public:
79   uint32_t DynsymIndex = 0;
80   uint32_t GotIndex = -1;
81   uint32_t PltIndex = -1;
82
83   uint32_t GlobalDynIndex = -1;
84
85   // This field is a index to the symbol's version definition.
86   uint32_t VerdefIndex = -1;
87
88   // Version definition index.
89   uint16_t VersionId;
90
91   // An index into the .branch_lt section on PPC64.
92   uint16_t PPC64BranchltIndex = -1;
93
94   // Symbol binding. This is not overwritten by replaceSymbol to track
95   // changes during resolution. In particular:
96   //  - An undefined weak is still weak when it resolves to a shared library.
97   //  - An undefined weak will not fetch archive members, but we have to
98   //    remember it is weak.
99   uint8_t Binding;
100
101   // The following fields have the same meaning as the ELF symbol attributes.
102   uint8_t Type;    // symbol type
103   uint8_t StOther; // st_other field value
104
105   uint8_t SymbolKind;
106
107   // Symbol visibility. This is the computed minimum visibility of all
108   // observed non-DSO symbols.
109   unsigned Visibility : 2;
110
111   // True if the symbol was used for linking and thus need to be added to the
112   // output file's symbol table. This is true for all symbols except for
113   // unreferenced DSO symbols and bitcode symbols that are unreferenced except
114   // by other bitcode objects.
115   unsigned IsUsedInRegularObj : 1;
116
117   // If this flag is true and the symbol has protected or default visibility, it
118   // will appear in .dynsym. This flag is set by interposable DSO symbols in
119   // executables, by most symbols in DSOs and executables built with
120   // --export-dynamic, and by dynamic lists.
121   unsigned ExportDynamic : 1;
122
123   // False if LTO shouldn't inline whatever this symbol points to. If a symbol
124   // is overwritten after LTO, LTO shouldn't inline the symbol because it
125   // doesn't know the final contents of the symbol.
126   unsigned CanInline : 1;
127
128   // True if this symbol is specified by --trace-symbol option.
129   unsigned Traced : 1;
130
131   bool includeInDynsym() const;
132   uint8_t computeBinding() const;
133   bool isWeak() const { return Binding == llvm::ELF::STB_WEAK; }
134
135   bool isUndefined() const { return SymbolKind == UndefinedKind; }
136   bool isDefined() const { return SymbolKind == DefinedKind; }
137   bool isShared() const { return SymbolKind == SharedKind; }
138   bool isLocal() const { return Binding == llvm::ELF::STB_LOCAL; }
139
140   bool isLazy() const {
141     return SymbolKind == LazyArchiveKind || SymbolKind == LazyObjectKind;
142   }
143
144   // True if this is an undefined weak symbol. This only works once
145   // all input files have been added.
146   bool isUndefWeak() const {
147     // See comment on lazy symbols for details.
148     return isWeak() && (isUndefined() || isLazy());
149   }
150
151   StringRef getName() const {
152     if (NameSize == (uint32_t)-1)
153       NameSize = strlen(NameData);
154     return {NameData, NameSize};
155   }
156
157   void setName(StringRef S) {
158     NameData = S.data();
159     NameSize = S.size();
160   }
161
162   void parseSymbolVersion();
163
164   bool isInGot() const { return GotIndex != -1U; }
165   bool isInPlt() const { return PltIndex != -1U; }
166   bool isInPPC64Branchlt() const { return PPC64BranchltIndex != 0xffff; }
167
168   uint64_t getVA(int64_t Addend = 0) const;
169
170   uint64_t getGotOffset() const;
171   uint64_t getGotVA() const;
172   uint64_t getGotPltOffset() const;
173   uint64_t getGotPltVA() const;
174   uint64_t getPltVA() const;
175   uint64_t getPPC64LongBranchTableVA() const;
176   uint64_t getPPC64LongBranchOffset() const;
177   uint64_t getSize() const;
178   OutputSection *getOutputSection() const;
179
180 protected:
181   Symbol(Kind K, InputFile *File, StringRefZ Name, uint8_t Binding,
182          uint8_t StOther, uint8_t Type)
183       : File(File), NameData(Name.Data), NameSize(Name.Size), Binding(Binding),
184         Type(Type), StOther(StOther), SymbolKind(K), NeedsPltAddr(false),
185         IsInIplt(false), IsInIgot(false), IsPreemptible(false),
186         Used(!Config->GcSections), NeedsTocRestore(false),
187         ScriptDefined(false) {}
188
189 public:
190   // True the symbol should point to its PLT entry.
191   // For SharedSymbol only.
192   unsigned NeedsPltAddr : 1;
193
194   // True if this symbol is in the Iplt sub-section of the Plt.
195   unsigned IsInIplt : 1;
196
197   // True if this symbol is in the Igot sub-section of the .got.plt or .got.
198   unsigned IsInIgot : 1;
199
200   // True if this symbol is preemptible at load time.
201   unsigned IsPreemptible : 1;
202
203   // True if an undefined or shared symbol is used from a live section.
204   unsigned Used : 1;
205
206   // True if a call to this symbol needs to be followed by a restore of the
207   // PPC64 toc pointer.
208   unsigned NeedsTocRestore : 1;
209
210   // True if this symbol is defined by a linker script.
211   unsigned ScriptDefined : 1;
212
213   bool isSection() const { return Type == llvm::ELF::STT_SECTION; }
214   bool isTls() const { return Type == llvm::ELF::STT_TLS; }
215   bool isFunc() const { return Type == llvm::ELF::STT_FUNC; }
216   bool isGnuIFunc() const { return Type == llvm::ELF::STT_GNU_IFUNC; }
217   bool isObject() const { return Type == llvm::ELF::STT_OBJECT; }
218   bool isFile() const { return Type == llvm::ELF::STT_FILE; }
219 };
220
221 // Represents a symbol that is defined in the current output file.
222 class Defined : public Symbol {
223 public:
224   Defined(InputFile *File, StringRefZ Name, uint8_t Binding, uint8_t StOther,
225           uint8_t Type, uint64_t Value, uint64_t Size, SectionBase *Section)
226       : Symbol(DefinedKind, File, Name, Binding, StOther, Type), Value(Value),
227         Size(Size), Section(Section) {}
228
229   static bool classof(const Symbol *S) { return S->isDefined(); }
230
231   uint64_t Value;
232   uint64_t Size;
233   SectionBase *Section;
234 };
235
236 class Undefined : public Symbol {
237 public:
238   Undefined(InputFile *File, StringRefZ Name, uint8_t Binding, uint8_t StOther,
239             uint8_t Type)
240       : Symbol(UndefinedKind, File, Name, Binding, StOther, Type) {}
241
242   static bool classof(const Symbol *S) { return S->kind() == UndefinedKind; }
243 };
244
245 class SharedSymbol : public Symbol {
246 public:
247   static bool classof(const Symbol *S) { return S->kind() == SharedKind; }
248
249   SharedSymbol(InputFile &File, StringRef Name, uint8_t Binding,
250                uint8_t StOther, uint8_t Type, uint64_t Value, uint64_t Size,
251                uint32_t Alignment, uint32_t VerdefIndex)
252       : Symbol(SharedKind, &File, Name, Binding, StOther, Type),
253         Alignment(Alignment), Value(Value), Size(Size) {
254     this->VerdefIndex = VerdefIndex;
255     // GNU ifunc is a mechanism to allow user-supplied functions to
256     // resolve PLT slot values at load-time. This is contrary to the
257     // regular symbol resolution scheme in which symbols are resolved just
258     // by name. Using this hook, you can program how symbols are solved
259     // for you program. For example, you can make "memcpy" to be resolved
260     // to a SSE-enabled version of memcpy only when a machine running the
261     // program supports the SSE instruction set.
262     //
263     // Naturally, such symbols should always be called through their PLT
264     // slots. What GNU ifunc symbols point to are resolver functions, and
265     // calling them directly doesn't make sense (unless you are writing a
266     // loader).
267     //
268     // For DSO symbols, we always call them through PLT slots anyway.
269     // So there's no difference between GNU ifunc and regular function
270     // symbols if they are in DSOs. So we can handle GNU_IFUNC as FUNC.
271     if (this->Type == llvm::ELF::STT_GNU_IFUNC)
272       this->Type = llvm::ELF::STT_FUNC;
273   }
274
275   template <class ELFT> SharedFile<ELFT> &getFile() const {
276     return *cast<SharedFile<ELFT>>(File);
277   }
278
279   uint32_t Alignment;
280
281   uint64_t Value; // st_value
282   uint64_t Size;  // st_size
283 };
284
285 // LazyArchive and LazyObject represent a symbols that is not yet in the link,
286 // but we know where to find it if needed. If the resolver finds both Undefined
287 // and Lazy for the same name, it will ask the Lazy to load a file.
288 //
289 // A special complication is the handling of weak undefined symbols. They should
290 // not load a file, but we have to remember we have seen both the weak undefined
291 // and the lazy. We represent that with a lazy symbol with a weak binding. This
292 // means that code looking for undefined symbols normally also has to take lazy
293 // symbols into consideration.
294
295 // This class represents a symbol defined in an archive file. It is
296 // created from an archive file header, and it knows how to load an
297 // object file from an archive to replace itself with a defined
298 // symbol.
299 class LazyArchive : public Symbol {
300 public:
301   LazyArchive(InputFile &File, uint8_t Type,
302               const llvm::object::Archive::Symbol S)
303       : Symbol(LazyArchiveKind, &File, S.getName(), llvm::ELF::STB_GLOBAL,
304                llvm::ELF::STV_DEFAULT, Type),
305         Sym(S) {}
306
307   static bool classof(const Symbol *S) { return S->kind() == LazyArchiveKind; }
308
309   InputFile *fetch();
310   MemoryBufferRef getMemberBuffer();
311
312 private:
313   const llvm::object::Archive::Symbol Sym;
314 };
315
316 // LazyObject symbols represents symbols in object files between
317 // --start-lib and --end-lib options.
318 class LazyObject : public Symbol {
319 public:
320   LazyObject(InputFile &File, uint8_t Type, StringRef Name)
321       : Symbol(LazyObjectKind, &File, Name, llvm::ELF::STB_GLOBAL,
322                llvm::ELF::STV_DEFAULT, Type) {}
323
324   static bool classof(const Symbol *S) { return S->kind() == LazyObjectKind; }
325 };
326
327 // Some linker-generated symbols need to be created as
328 // Defined symbols.
329 struct ElfSym {
330   // __bss_start
331   static Defined *Bss;
332
333   // etext and _etext
334   static Defined *Etext1;
335   static Defined *Etext2;
336
337   // edata and _edata
338   static Defined *Edata1;
339   static Defined *Edata2;
340
341   // end and _end
342   static Defined *End1;
343   static Defined *End2;
344
345   // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
346   // be at some offset from the base of the .got section, usually 0 or
347   // the end of the .got.
348   static Defined *GlobalOffsetTable;
349
350   // _gp, _gp_disp and __gnu_local_gp symbols. Only for MIPS.
351   static Defined *MipsGp;
352   static Defined *MipsGpDisp;
353   static Defined *MipsLocalGp;
354
355   // __rel{,a}_iplt_{start,end} symbols.
356   static Defined *RelaIpltStart;
357   static Defined *RelaIpltEnd;
358 };
359
360 // A buffer class that is large enough to hold any Symbol-derived
361 // object. We allocate memory using this class and instantiate a symbol
362 // using the placement new.
363 union SymbolUnion {
364   alignas(Defined) char A[sizeof(Defined)];
365   alignas(Undefined) char C[sizeof(Undefined)];
366   alignas(SharedSymbol) char D[sizeof(SharedSymbol)];
367   alignas(LazyArchive) char E[sizeof(LazyArchive)];
368   alignas(LazyObject) char F[sizeof(LazyObject)];
369 };
370
371 void printTraceSymbol(Symbol *Sym);
372
373 template <typename T, typename... ArgT>
374 void replaceSymbol(Symbol *S, ArgT &&... Arg) {
375   using llvm::ELF::STT_TLS;
376
377   static_assert(std::is_trivially_destructible<T>(),
378                 "Symbol types must be trivially destructible");
379   static_assert(sizeof(T) <= sizeof(SymbolUnion), "SymbolUnion too small");
380   static_assert(alignof(T) <= alignof(SymbolUnion),
381                 "SymbolUnion not aligned enough");
382   assert(static_cast<Symbol *>(static_cast<T *>(nullptr)) == nullptr &&
383          "Not a Symbol");
384
385   Symbol Sym = *S;
386
387   new (S) T(std::forward<ArgT>(Arg)...);
388
389   S->VersionId = Sym.VersionId;
390   S->Visibility = Sym.Visibility;
391   S->IsUsedInRegularObj = Sym.IsUsedInRegularObj;
392   S->ExportDynamic = Sym.ExportDynamic;
393   S->CanInline = Sym.CanInline;
394   S->Traced = Sym.Traced;
395   S->ScriptDefined = Sym.ScriptDefined;
396
397   // Symbols representing thread-local variables must be referenced by
398   // TLS-aware relocations, and non-TLS symbols must be reference by
399   // non-TLS relocations, so there's a clear distinction between TLS
400   // and non-TLS symbols. It is an error if the same symbol is defined
401   // as a TLS symbol in one file and as a non-TLS symbol in other file.
402   bool TlsMismatch = (Sym.Type == STT_TLS && S->Type != STT_TLS) ||
403                      (Sym.Type != STT_TLS && S->Type == STT_TLS);
404
405   if (Sym.SymbolKind != Symbol::PlaceholderKind && TlsMismatch && !Sym.isLazy())
406     error("TLS attribute mismatch: " + toString(Sym) + "\n>>> defined in " +
407           toString(Sym.File) + "\n>>> defined in " + toString(S->File));
408
409   // Print out a log message if --trace-symbol was specified.
410   // This is for debugging.
411   if (S->Traced)
412     printTraceSymbol(S);
413 }
414
415 void maybeWarnUnorderableSymbol(const Symbol *Sym);
416 } // namespace elf
417 } // namespace lld
418
419 #endif