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