comparison lld/ELF/Symbols.h @ 150:1d019706d866

LLVM10
author anatofuz
date Thu, 13 Feb 2020 15:10:13 +0900
parents
children 0572611fdcc8
comparison
equal deleted inserted replaced
147:c2174574ed3a 150:1d019706d866
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 // This file defines various types of Symbols.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLD_ELF_SYMBOLS_H
14 #define LLD_ELF_SYMBOLS_H
15
16 #include "InputFiles.h"
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 std::string toString(const elf::Symbol &);
25
26 // There are two different ways to convert an Archive::Symbol to a string:
27 // One for Microsoft name mangling and one for Itanium name mangling.
28 // Call the functions toCOFFString and toELFString, not just toString.
29 std::string toELFString(const llvm::object::Archive::Symbol &);
30
31 namespace elf {
32 class CommonSymbol;
33 class Defined;
34 class InputFile;
35 class LazyArchive;
36 class LazyObject;
37 class SharedSymbol;
38 class Symbol;
39 class Undefined;
40
41 // This is a StringRef-like container that doesn't run strlen().
42 //
43 // ELF string tables contain a lot of null-terminated strings. Most of them
44 // are not necessary for the linker because they are names of local symbols,
45 // and the linker doesn't use local symbol names for name resolution. So, we
46 // use this class to represents strings read from string tables.
47 struct StringRefZ {
48 StringRefZ(const char *s) : data(s), size(-1) {}
49 StringRefZ(StringRef s) : data(s.data()), size(s.size()) {}
50
51 const char *data;
52 const uint32_t size;
53 };
54
55 // The base class for real symbol classes.
56 class Symbol {
57 public:
58 enum Kind {
59 PlaceholderKind,
60 DefinedKind,
61 CommonKind,
62 SharedKind,
63 UndefinedKind,
64 LazyArchiveKind,
65 LazyObjectKind,
66 };
67
68 Kind kind() const { return static_cast<Kind>(symbolKind); }
69
70 // The file from which this symbol was created.
71 InputFile *file;
72
73 protected:
74 const char *nameData;
75 mutable uint32_t nameSize;
76
77 public:
78 uint32_t dynsymIndex = 0;
79 uint32_t gotIndex = -1;
80 uint32_t pltIndex = -1;
81
82 uint32_t globalDynIndex = -1;
83
84 // This field is a index to the symbol's version definition.
85 uint32_t verdefIndex = -1;
86
87 // Version definition index.
88 uint16_t versionId;
89
90 // Symbol binding. This is not overwritten by replace() to track
91 // changes during resolution. In particular:
92 // - An undefined weak is still weak when it resolves to a shared library.
93 // - An undefined weak will not fetch archive members, but we have to
94 // remember it is weak.
95 uint8_t binding;
96
97 // The following fields have the same meaning as the ELF symbol attributes.
98 uint8_t type; // symbol type
99 uint8_t stOther; // st_other field value
100
101 uint8_t symbolKind;
102
103 // Symbol visibility. This is the computed minimum visibility of all
104 // observed non-DSO symbols.
105 uint8_t visibility : 2;
106
107 // True if the symbol was used for linking and thus need to be added to the
108 // output file's symbol table. This is true for all symbols except for
109 // unreferenced DSO symbols, lazy (archive) symbols, and bitcode symbols that
110 // are unreferenced except by other bitcode objects.
111 uint8_t isUsedInRegularObj : 1;
112
113 // Used by a Defined symbol with protected or default visibility, to record
114 // whether it is required to be exported into .dynsym. This is set when any of
115 // the following conditions hold:
116 //
117 // - If there is an interposable symbol from a DSO.
118 // - If -shared or --export-dynamic is specified, any symbol in an object
119 // file/bitcode sets this property, unless suppressed by LTO
120 // canBeOmittedFromSymbolTable().
121 uint8_t exportDynamic : 1;
122
123 // True if the symbol is in the --dynamic-list file. A Defined symbol with
124 // protected or default visibility with this property is required to be
125 // exported into .dynsym.
126 uint8_t inDynamicList : 1;
127
128 // False if LTO shouldn't inline whatever this symbol points to. If a symbol
129 // is overwritten after LTO, LTO shouldn't inline the symbol because it
130 // doesn't know the final contents of the symbol.
131 uint8_t canInline : 1;
132
133 // Used by Undefined and SharedSymbol to track if there has been at least one
134 // undefined reference to the symbol. The binding may change to STB_WEAK if
135 // the first undefined reference from a non-shared object is weak.
136 uint8_t referenced : 1;
137
138 // True if this symbol is specified by --trace-symbol option.
139 uint8_t traced : 1;
140
141 inline void replace(const Symbol &newSym);
142
143 bool includeInDynsym() const;
144 uint8_t computeBinding() const;
145 bool isWeak() const { return binding == llvm::ELF::STB_WEAK; }
146
147 bool isUndefined() const { return symbolKind == UndefinedKind; }
148 bool isCommon() const { return symbolKind == CommonKind; }
149 bool isDefined() const { return symbolKind == DefinedKind; }
150 bool isShared() const { return symbolKind == SharedKind; }
151 bool isPlaceholder() const { return symbolKind == PlaceholderKind; }
152
153 bool isLocal() const { return binding == llvm::ELF::STB_LOCAL; }
154
155 bool isLazy() const {
156 return symbolKind == LazyArchiveKind || symbolKind == LazyObjectKind;
157 }
158
159 // True if this is an undefined weak symbol. This only works once
160 // all input files have been added.
161 bool isUndefWeak() const {
162 // See comment on lazy symbols for details.
163 return isWeak() && (isUndefined() || isLazy());
164 }
165
166 StringRef getName() const {
167 if (nameSize == (uint32_t)-1)
168 nameSize = strlen(nameData);
169 return {nameData, nameSize};
170 }
171
172 void setName(StringRef s) {
173 nameData = s.data();
174 nameSize = s.size();
175 }
176
177 void parseSymbolVersion();
178
179 bool isInGot() const { return gotIndex != -1U; }
180 bool isInPlt() const { return pltIndex != -1U; }
181
182 uint64_t getVA(int64_t addend = 0) const;
183
184 uint64_t getGotOffset() const;
185 uint64_t getGotVA() const;
186 uint64_t getGotPltOffset() const;
187 uint64_t getGotPltVA() const;
188 uint64_t getPltVA() const;
189 uint64_t getSize() const;
190 OutputSection *getOutputSection() const;
191
192 // The following two functions are used for symbol resolution.
193 //
194 // You are expected to call mergeProperties for all symbols in input
195 // files so that attributes that are attached to names rather than
196 // indivisual symbol (such as visibility) are merged together.
197 //
198 // Every time you read a new symbol from an input, you are supposed
199 // to call resolve() with the new symbol. That function replaces
200 // "this" object as a result of name resolution if the new symbol is
201 // more appropriate to be included in the output.
202 //
203 // For example, if "this" is an undefined symbol and a new symbol is
204 // a defined symbol, "this" is replaced with the new symbol.
205 void mergeProperties(const Symbol &other);
206 void resolve(const Symbol &other);
207
208 // If this is a lazy symbol, fetch an input file and add the symbol
209 // in the file to the symbol table. Calling this function on
210 // non-lazy object causes a runtime error.
211 void fetch() const;
212
213 private:
214 static bool isExportDynamic(Kind k, uint8_t visibility) {
215 if (k == SharedKind)
216 return visibility == llvm::ELF::STV_DEFAULT;
217 return config->shared || config->exportDynamic;
218 }
219
220 void resolveUndefined(const Undefined &other);
221 void resolveCommon(const CommonSymbol &other);
222 void resolveDefined(const Defined &other);
223 template <class LazyT> void resolveLazy(const LazyT &other);
224 void resolveShared(const SharedSymbol &other);
225
226 int compare(const Symbol *other) const;
227
228 inline size_t getSymbolSize() const;
229
230 protected:
231 Symbol(Kind k, InputFile *file, StringRefZ name, uint8_t binding,
232 uint8_t stOther, uint8_t type)
233 : file(file), nameData(name.data), nameSize(name.size), binding(binding),
234 type(type), stOther(stOther), symbolKind(k), visibility(stOther & 3),
235 isUsedInRegularObj(!file || file->kind() == InputFile::ObjKind),
236 exportDynamic(isExportDynamic(k, visibility)), inDynamicList(false),
237 canInline(false), referenced(false), traced(false), needsPltAddr(false),
238 isInIplt(false), gotInIgot(false), isPreemptible(false),
239 used(!config->gcSections), needsTocRestore(false),
240 scriptDefined(false) {}
241
242 public:
243 // True the symbol should point to its PLT entry.
244 // For SharedSymbol only.
245 uint8_t needsPltAddr : 1;
246
247 // True if this symbol is in the Iplt sub-section of the Plt and the Igot
248 // sub-section of the .got.plt or .got.
249 uint8_t isInIplt : 1;
250
251 // True if this symbol needs a GOT entry and its GOT entry is actually in
252 // Igot. This will be true only for certain non-preemptible ifuncs.
253 uint8_t gotInIgot : 1;
254
255 // True if this symbol is preemptible at load time.
256 uint8_t isPreemptible : 1;
257
258 // True if an undefined or shared symbol is used from a live section.
259 uint8_t used : 1;
260
261 // True if a call to this symbol needs to be followed by a restore of the
262 // PPC64 toc pointer.
263 uint8_t needsTocRestore : 1;
264
265 // True if this symbol is defined by a linker script.
266 uint8_t scriptDefined : 1;
267
268 // The partition whose dynamic symbol table contains this symbol's definition.
269 uint8_t partition = 1;
270
271 bool isSection() const { return type == llvm::ELF::STT_SECTION; }
272 bool isTls() const { return type == llvm::ELF::STT_TLS; }
273 bool isFunc() const { return type == llvm::ELF::STT_FUNC; }
274 bool isGnuIFunc() const { return type == llvm::ELF::STT_GNU_IFUNC; }
275 bool isObject() const { return type == llvm::ELF::STT_OBJECT; }
276 bool isFile() const { return type == llvm::ELF::STT_FILE; }
277 };
278
279 // Represents a symbol that is defined in the current output file.
280 class Defined : public Symbol {
281 public:
282 Defined(InputFile *file, StringRefZ name, uint8_t binding, uint8_t stOther,
283 uint8_t type, uint64_t value, uint64_t size, SectionBase *section)
284 : Symbol(DefinedKind, file, name, binding, stOther, type), value(value),
285 size(size), section(section) {}
286
287 static bool classof(const Symbol *s) { return s->isDefined(); }
288
289 uint64_t value;
290 uint64_t size;
291 SectionBase *section;
292 };
293
294 // Represents a common symbol.
295 //
296 // On Unix, it is traditionally allowed to write variable definitions
297 // without initialization expressions (such as "int foo;") to header
298 // files. Such definition is called "tentative definition".
299 //
300 // Using tentative definition is usually considered a bad practice
301 // because you should write only declarations (such as "extern int
302 // foo;") to header files. Nevertheless, the linker and the compiler
303 // have to do something to support bad code by allowing duplicate
304 // definitions for this particular case.
305 //
306 // Common symbols represent variable definitions without initializations.
307 // The compiler creates common symbols when it sees variable definitions
308 // without initialization (you can suppress this behavior and let the
309 // compiler create a regular defined symbol by -fno-common).
310 //
311 // The linker allows common symbols to be replaced by regular defined
312 // symbols. If there are remaining common symbols after name resolution is
313 // complete, they are converted to regular defined symbols in a .bss
314 // section. (Therefore, the later passes don't see any CommonSymbols.)
315 class CommonSymbol : public Symbol {
316 public:
317 CommonSymbol(InputFile *file, StringRefZ name, uint8_t binding,
318 uint8_t stOther, uint8_t type, uint64_t alignment, uint64_t size)
319 : Symbol(CommonKind, file, name, binding, stOther, type),
320 alignment(alignment), size(size) {}
321
322 static bool classof(const Symbol *s) { return s->isCommon(); }
323
324 uint32_t alignment;
325 uint64_t size;
326 };
327
328 class Undefined : public Symbol {
329 public:
330 Undefined(InputFile *file, StringRefZ name, uint8_t binding, uint8_t stOther,
331 uint8_t type, uint32_t discardedSecIdx = 0)
332 : Symbol(UndefinedKind, file, name, binding, stOther, type),
333 discardedSecIdx(discardedSecIdx) {}
334
335 static bool classof(const Symbol *s) { return s->kind() == UndefinedKind; }
336
337 // The section index if in a discarded section, 0 otherwise.
338 uint32_t discardedSecIdx;
339 };
340
341 class SharedSymbol : public Symbol {
342 public:
343 static bool classof(const Symbol *s) { return s->kind() == SharedKind; }
344
345 SharedSymbol(InputFile &file, StringRef name, uint8_t binding,
346 uint8_t stOther, uint8_t type, uint64_t value, uint64_t size,
347 uint32_t alignment, uint32_t verdefIndex)
348 : Symbol(SharedKind, &file, name, binding, stOther, type), value(value),
349 size(size), alignment(alignment) {
350 this->verdefIndex = verdefIndex;
351 // GNU ifunc is a mechanism to allow user-supplied functions to
352 // resolve PLT slot values at load-time. This is contrary to the
353 // regular symbol resolution scheme in which symbols are resolved just
354 // by name. Using this hook, you can program how symbols are solved
355 // for you program. For example, you can make "memcpy" to be resolved
356 // to a SSE-enabled version of memcpy only when a machine running the
357 // program supports the SSE instruction set.
358 //
359 // Naturally, such symbols should always be called through their PLT
360 // slots. What GNU ifunc symbols point to are resolver functions, and
361 // calling them directly doesn't make sense (unless you are writing a
362 // loader).
363 //
364 // For DSO symbols, we always call them through PLT slots anyway.
365 // So there's no difference between GNU ifunc and regular function
366 // symbols if they are in DSOs. So we can handle GNU_IFUNC as FUNC.
367 if (this->type == llvm::ELF::STT_GNU_IFUNC)
368 this->type = llvm::ELF::STT_FUNC;
369 }
370
371 SharedFile &getFile() const { return *cast<SharedFile>(file); }
372
373 uint64_t value; // st_value
374 uint64_t size; // st_size
375 uint32_t alignment;
376 };
377
378 // LazyArchive and LazyObject represent a symbols that is not yet in the link,
379 // but we know where to find it if needed. If the resolver finds both Undefined
380 // and Lazy for the same name, it will ask the Lazy to load a file.
381 //
382 // A special complication is the handling of weak undefined symbols. They should
383 // not load a file, but we have to remember we have seen both the weak undefined
384 // and the lazy. We represent that with a lazy symbol with a weak binding. This
385 // means that code looking for undefined symbols normally also has to take lazy
386 // symbols into consideration.
387
388 // This class represents a symbol defined in an archive file. It is
389 // created from an archive file header, and it knows how to load an
390 // object file from an archive to replace itself with a defined
391 // symbol.
392 class LazyArchive : public Symbol {
393 public:
394 LazyArchive(InputFile &file, const llvm::object::Archive::Symbol s)
395 : Symbol(LazyArchiveKind, &file, s.getName(), llvm::ELF::STB_GLOBAL,
396 llvm::ELF::STV_DEFAULT, llvm::ELF::STT_NOTYPE),
397 sym(s) {}
398
399 static bool classof(const Symbol *s) { return s->kind() == LazyArchiveKind; }
400
401 MemoryBufferRef getMemberBuffer();
402
403 const llvm::object::Archive::Symbol sym;
404 };
405
406 // LazyObject symbols represents symbols in object files between
407 // --start-lib and --end-lib options.
408 class LazyObject : public Symbol {
409 public:
410 LazyObject(InputFile &file, StringRef name)
411 : Symbol(LazyObjectKind, &file, name, llvm::ELF::STB_GLOBAL,
412 llvm::ELF::STV_DEFAULT, llvm::ELF::STT_NOTYPE) {}
413
414 static bool classof(const Symbol *s) { return s->kind() == LazyObjectKind; }
415 };
416
417 // Some linker-generated symbols need to be created as
418 // Defined symbols.
419 struct ElfSym {
420 // __bss_start
421 static Defined *bss;
422
423 // etext and _etext
424 static Defined *etext1;
425 static Defined *etext2;
426
427 // edata and _edata
428 static Defined *edata1;
429 static Defined *edata2;
430
431 // end and _end
432 static Defined *end1;
433 static Defined *end2;
434
435 // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
436 // be at some offset from the base of the .got section, usually 0 or
437 // the end of the .got.
438 static Defined *globalOffsetTable;
439
440 // _gp, _gp_disp and __gnu_local_gp symbols. Only for MIPS.
441 static Defined *mipsGp;
442 static Defined *mipsGpDisp;
443 static Defined *mipsLocalGp;
444
445 // __rel{,a}_iplt_{start,end} symbols.
446 static Defined *relaIpltStart;
447 static Defined *relaIpltEnd;
448
449 // __global_pointer$ for RISC-V.
450 static Defined *riscvGlobalPointer;
451
452 // _TLS_MODULE_BASE_ on targets that support TLSDESC.
453 static Defined *tlsModuleBase;
454 };
455
456 // A buffer class that is large enough to hold any Symbol-derived
457 // object. We allocate memory using this class and instantiate a symbol
458 // using the placement new.
459 union SymbolUnion {
460 alignas(Defined) char a[sizeof(Defined)];
461 alignas(CommonSymbol) char b[sizeof(CommonSymbol)];
462 alignas(Undefined) char c[sizeof(Undefined)];
463 alignas(SharedSymbol) char d[sizeof(SharedSymbol)];
464 alignas(LazyArchive) char e[sizeof(LazyArchive)];
465 alignas(LazyObject) char f[sizeof(LazyObject)];
466 };
467
468 // It is important to keep the size of SymbolUnion small for performance and
469 // memory usage reasons. 80 bytes is a soft limit based on the size of Defined
470 // on a 64-bit system.
471 static_assert(sizeof(SymbolUnion) <= 80, "SymbolUnion too large");
472
473 template <typename T> struct AssertSymbol {
474 static_assert(std::is_trivially_destructible<T>(),
475 "Symbol types must be trivially destructible");
476 static_assert(sizeof(T) <= sizeof(SymbolUnion), "SymbolUnion too small");
477 static_assert(alignof(T) <= alignof(SymbolUnion),
478 "SymbolUnion not aligned enough");
479 };
480
481 static inline void assertSymbols() {
482 AssertSymbol<Defined>();
483 AssertSymbol<CommonSymbol>();
484 AssertSymbol<Undefined>();
485 AssertSymbol<SharedSymbol>();
486 AssertSymbol<LazyArchive>();
487 AssertSymbol<LazyObject>();
488 }
489
490 void printTraceSymbol(const Symbol *sym);
491
492 size_t Symbol::getSymbolSize() const {
493 switch (kind()) {
494 case CommonKind:
495 return sizeof(CommonSymbol);
496 case DefinedKind:
497 return sizeof(Defined);
498 case LazyArchiveKind:
499 return sizeof(LazyArchive);
500 case LazyObjectKind:
501 return sizeof(LazyObject);
502 case SharedKind:
503 return sizeof(SharedSymbol);
504 case UndefinedKind:
505 return sizeof(Undefined);
506 case PlaceholderKind:
507 return sizeof(Symbol);
508 }
509 llvm_unreachable("unknown symbol kind");
510 }
511
512 // replace() replaces "this" object with a given symbol by memcpy'ing
513 // it over to "this". This function is called as a result of name
514 // resolution, e.g. to replace an undefind symbol with a defined symbol.
515 void Symbol::replace(const Symbol &newSym) {
516 using llvm::ELF::STT_TLS;
517
518 // Symbols representing thread-local variables must be referenced by
519 // TLS-aware relocations, and non-TLS symbols must be reference by
520 // non-TLS relocations, so there's a clear distinction between TLS
521 // and non-TLS symbols. It is an error if the same symbol is defined
522 // as a TLS symbol in one file and as a non-TLS symbol in other file.
523 if (symbolKind != PlaceholderKind && !isLazy() && !newSym.isLazy() &&
524 (type == STT_TLS) != (newSym.type == STT_TLS))
525 error("TLS attribute mismatch: " + toString(*this) + "\n>>> defined in " +
526 toString(newSym.file) + "\n>>> defined in " + toString(file));
527
528 Symbol old = *this;
529 memcpy(this, &newSym, newSym.getSymbolSize());
530
531 // old may be a placeholder. The referenced fields must be initialized in
532 // SymbolTable::insert.
533 versionId = old.versionId;
534 visibility = old.visibility;
535 isUsedInRegularObj = old.isUsedInRegularObj;
536 exportDynamic = old.exportDynamic;
537 inDynamicList = old.inDynamicList;
538 canInline = old.canInline;
539 referenced = old.referenced;
540 traced = old.traced;
541 isPreemptible = old.isPreemptible;
542 scriptDefined = old.scriptDefined;
543 partition = old.partition;
544
545 // Symbol length is computed lazily. If we already know a symbol length,
546 // propagate it.
547 if (nameData == old.nameData && nameSize == 0 && old.nameSize != 0)
548 nameSize = old.nameSize;
549
550 // Print out a log message if --trace-symbol was specified.
551 // This is for debugging.
552 if (traced)
553 printTraceSymbol(this);
554 }
555
556 void maybeWarnUnorderableSymbol(const Symbol *sym);
557 bool computeIsPreemptible(const Symbol &sym);
558
559 } // namespace elf
560 } // namespace lld
561
562 #endif