1 //===- SymbolTable.cpp ----------------------------------------------------===//
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 #include "SymbolTable.h"
10 #include "Config.h"
11 #include "Driver.h"
12 #include "LTO.h"
13 #include "PDB.h"
14 #include "Symbols.h"
15 #include "lld/Common/ErrorHandler.h"
16 #include "lld/Common/Memory.h"
17 #include "lld/Common/Timer.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <utility>
22 
23 using namespace llvm;
24 
25 namespace lld {
26 namespace coff {
27 
28 static Timer LTOTimer("LTO", Timer::root());
29 
30 SymbolTable *Symtab;
31 
32 void SymbolTable::addFile(InputFile *File) {
33   log("Reading " + toString(File));
34   File->parse();
35 
36   MachineTypes MT = File->getMachineType();
37   if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
38     Config->Machine = MT;
39   } else if (MT != IMAGE_FILE_MACHINE_UNKNOWN && Config->Machine != MT) {
40     error(toString(File) + ": machine type " + machineToStr(MT) +
41           " conflicts with " + machineToStr(Config->Machine));
42     return;
43   }
44 
45   if (auto *F = dyn_cast<ObjFile>(File)) {
46     ObjFile::Instances.push_back(F);
47   } else if (auto *F = dyn_cast<BitcodeFile>(File)) {
48     BitcodeFile::Instances.push_back(F);
49   } else if (auto *F = dyn_cast<ImportFile>(File)) {
50     ImportFile::Instances.push_back(F);
51   }
52 
53   StringRef S = File->getDirectives();
54   if (S.empty())
55     return;
56 
57   log("Directives: " + toString(File) + ": " + S);
58   Driver->parseDirectives(S);
59 }
60 
61 static void errorOrWarn(const Twine &S) {
62   if (Config->ForceUnresolved)
63     warn(S);
64   else
65     error(S);
66 }
67 
68 // Returns the symbol in SC whose value is <= Addr that is closest to Addr.
69 // This is generally the global variable or function whose definition contains
70 // Addr.
71 static Symbol *getSymbol(SectionChunk *SC, uint32_t Addr) {
72   DefinedRegular *Candidate = nullptr;
73 
74   for (Symbol *S : SC->File->getSymbols()) {
75     auto *D = dyn_cast_or_null<DefinedRegular>(S);
76     if (!D || D->getChunk() != SC || D->getValue() > Addr ||
77         (Candidate && D->getValue() < Candidate->getValue()))
78       continue;
79 
80     Candidate = D;
81   }
82 
83   return Candidate;
84 }
85 
86 std::string getSymbolLocations(ObjFile *File, uint32_t SymIndex) {
87   struct Location {
88     Symbol *Sym;
89     std::pair<StringRef, uint32_t> FileLine;
90   };
91   std::vector<Location> Locations;
92 
93   for (Chunk *C : File->getChunks()) {
94     auto *SC = dyn_cast<SectionChunk>(C);
95     if (!SC)
96       continue;
97     for (const coff_relocation &R : SC->Relocs) {
98       if (R.SymbolTableIndex != SymIndex)
99         continue;
100       std::pair<StringRef, uint32_t> FileLine =
101           getFileLine(SC, R.VirtualAddress);
102       Symbol *Sym = getSymbol(SC, R.VirtualAddress);
103       if (!FileLine.first.empty() || Sym)
104         Locations.push_back({Sym, FileLine});
105     }
106   }
107 
108   if (Locations.empty())
109     return "\n>>> referenced by " + toString(File);
110 
111   std::string Out;
112   llvm::raw_string_ostream OS(Out);
113   for (Location Loc : Locations) {
114     OS << "\n>>> referenced by ";
115     if (!Loc.FileLine.first.empty())
116       OS << Loc.FileLine.first << ":" << Loc.FileLine.second
117          << "\n>>>               ";
118     OS << toString(File);
119     if (Loc.Sym)
120       OS << ":(" << toString(*Loc.Sym) << ')';
121   }
122   return OS.str();
123 }
124 
125 void SymbolTable::loadMinGWAutomaticImports() {
126   for (auto &I : SymMap) {
127     Symbol *Sym = I.second;
128     auto *Undef = dyn_cast<Undefined>(Sym);
129     if (!Undef)
130       continue;
131     if (!Sym->IsUsedInRegularObj)
132       continue;
133 
134     StringRef Name = Undef->getName();
135 
136     if (Name.startswith("__imp_"))
137       continue;
138     // If we have an undefined symbol, but we have a Lazy representing a
139     // symbol we could load from file, make sure to load that.
140     Lazy *L = dyn_cast_or_null<Lazy>(find(("__imp_" + Name).str()));
141     if (!L || L->PendingArchiveLoad)
142       continue;
143 
144     log("Loading lazy " + L->getName() + " from " + L->File->getName() +
145         " for automatic import");
146     L->PendingArchiveLoad = true;
147     L->File->addMember(&L->Sym);
148   }
149 }
150 
151 bool SymbolTable::handleMinGWAutomaticImport(Symbol *Sym, StringRef Name) {
152   if (Name.startswith("__imp_"))
153     return false;
154   Defined *Imp = dyn_cast_or_null<Defined>(find(("__imp_" + Name).str()));
155   if (!Imp)
156     return false;
157 
158   // Replace the reference directly to a variable with a reference
159   // to the import address table instead. This obviously isn't right,
160   // but we mark the symbol as IsRuntimePseudoReloc, and a later pass
161   // will add runtime pseudo relocations for every relocation against
162   // this Symbol. The runtime pseudo relocation framework expects the
163   // reference itself to point at the IAT entry.
164   size_t ImpSize = 0;
165   if (isa<DefinedImportData>(Imp)) {
166     log("Automatically importing " + Name + " from " +
167         cast<DefinedImportData>(Imp)->getDLLName());
168     ImpSize = sizeof(DefinedImportData);
169   } else if (isa<DefinedRegular>(Imp)) {
170     log("Automatically importing " + Name + " from " +
171         toString(cast<DefinedRegular>(Imp)->File));
172     ImpSize = sizeof(DefinedRegular);
173   } else {
174     warn("unable to automatically import " + Name + " from " + Imp->getName() +
175          " from " + toString(cast<DefinedRegular>(Imp)->File) +
176          "; unexpected symbol type");
177     return false;
178   }
179   Sym->replaceKeepingName(Imp, ImpSize);
180   Sym->IsRuntimePseudoReloc = true;
181 
182   // There may exist symbols named .refptr.<name> which only consist
183   // of a single pointer to <name>. If it turns out <name> is
184   // automatically imported, we don't need to keep the .refptr.<name>
185   // pointer at all, but redirect all accesses to it to the IAT entry
186   // for __imp_<name> instead, and drop the whole .refptr.<name> chunk.
187   DefinedRegular *Refptr =
188       dyn_cast_or_null<DefinedRegular>(find((".refptr." + Name).str()));
189   if (Refptr && Refptr->getChunk()->getSize() == Config->Wordsize) {
190     SectionChunk *SC = dyn_cast_or_null<SectionChunk>(Refptr->getChunk());
191     if (SC && SC->Relocs.size() == 1 && *SC->symbols().begin() == Sym) {
192       log("Replacing .refptr." + Name + " with " + Imp->getName());
193       Refptr->getChunk()->Live = false;
194       Refptr->replaceKeepingName(Imp, ImpSize);
195     }
196   }
197   return true;
198 }
199 
200 void SymbolTable::reportRemainingUndefines() {
201   SmallPtrSet<Symbol *, 8> Undefs;
202   DenseMap<Symbol *, Symbol *> LocalImports;
203 
204   for (auto &I : SymMap) {
205     Symbol *Sym = I.second;
206     auto *Undef = dyn_cast<Undefined>(Sym);
207     if (!Undef)
208       continue;
209     if (!Sym->IsUsedInRegularObj)
210       continue;
211 
212     StringRef Name = Undef->getName();
213 
214     // A weak alias may have been resolved, so check for that.
215     if (Defined *D = Undef->getWeakAlias()) {
216       // We want to replace Sym with D. However, we can't just blindly
217       // copy sizeof(SymbolUnion) bytes from D to Sym because D may be an
218       // internal symbol, and internal symbols are stored as "unparented"
219       // Symbols. For that reason we need to check which type of symbol we
220       // are dealing with and copy the correct number of bytes.
221       if (isa<DefinedRegular>(D))
222         memcpy(Sym, D, sizeof(DefinedRegular));
223       else if (isa<DefinedAbsolute>(D))
224         memcpy(Sym, D, sizeof(DefinedAbsolute));
225       else
226         memcpy(Sym, D, sizeof(SymbolUnion));
227       continue;
228     }
229 
230     // If we can resolve a symbol by removing __imp_ prefix, do that.
231     // This odd rule is for compatibility with MSVC linker.
232     if (Name.startswith("__imp_")) {
233       Symbol *Imp = find(Name.substr(strlen("__imp_")));
234       if (Imp && isa<Defined>(Imp)) {
235         auto *D = cast<Defined>(Imp);
236         replaceSymbol<DefinedLocalImport>(Sym, Name, D);
237         LocalImportChunks.push_back(cast<DefinedLocalImport>(Sym)->getChunk());
238         LocalImports[Sym] = D;
239         continue;
240       }
241     }
242 
243     // We don't want to report missing Microsoft precompiled headers symbols.
244     // A proper message will be emitted instead in PDBLinker::aquirePrecompObj
245     if (Name.contains("_PchSym_"))
246       continue;
247 
248     if (Config->MinGW && handleMinGWAutomaticImport(Sym, Name))
249       continue;
250 
251     // Remaining undefined symbols are not fatal if /force is specified.
252     // They are replaced with dummy defined symbols.
253     if (Config->ForceUnresolved)
254       replaceSymbol<DefinedAbsolute>(Sym, Name, 0);
255     Undefs.insert(Sym);
256   }
257 
258   if (Undefs.empty() && LocalImports.empty())
259     return;
260 
261   for (Symbol *B : Config->GCRoot) {
262     if (Undefs.count(B))
263       errorOrWarn("<root>: undefined symbol: " + toString(*B));
264     if (Config->WarnLocallyDefinedImported)
265       if (Symbol *Imp = LocalImports.lookup(B))
266         warn("<root>: locally defined symbol imported: " + toString(*Imp) +
267              " (defined in " + toString(Imp->getFile()) + ") [LNK4217]");
268   }
269 
270   for (ObjFile *File : ObjFile::Instances) {
271     size_t SymIndex = (size_t)-1;
272     for (Symbol *Sym : File->getSymbols()) {
273       ++SymIndex;
274       if (!Sym)
275         continue;
276       if (Undefs.count(Sym))
277         errorOrWarn("undefined symbol: " + toString(*Sym) +
278                     getSymbolLocations(File, SymIndex));
279       if (Config->WarnLocallyDefinedImported)
280         if (Symbol *Imp = LocalImports.lookup(Sym))
281           warn(toString(File) +
282                ": locally defined symbol imported: " + toString(*Imp) +
283                " (defined in " + toString(Imp->getFile()) + ") [LNK4217]");
284     }
285   }
286 }
287 
288 std::pair<Symbol *, bool> SymbolTable::insert(StringRef Name) {
289   bool Inserted = false;
290   Symbol *&Sym = SymMap[CachedHashStringRef(Name)];
291   if (!Sym) {
292     Sym = reinterpret_cast<Symbol *>(make<SymbolUnion>());
293     Sym->IsUsedInRegularObj = false;
294     Sym->PendingArchiveLoad = false;
295     Inserted = true;
296   }
297   return {Sym, Inserted};
298 }
299 
300 std::pair<Symbol *, bool> SymbolTable::insert(StringRef Name, InputFile *File) {
301   std::pair<Symbol *, bool> Result = insert(Name);
302   if (!File || !isa<BitcodeFile>(File))
303     Result.first->IsUsedInRegularObj = true;
304   return Result;
305 }
306 
307 Symbol *SymbolTable::addUndefined(StringRef Name, InputFile *F,
308                                   bool IsWeakAlias) {
309   Symbol *S;
310   bool WasInserted;
311   std::tie(S, WasInserted) = insert(Name, F);
312   if (WasInserted || (isa<Lazy>(S) && IsWeakAlias)) {
313     replaceSymbol<Undefined>(S, Name);
314     return S;
315   }
316   if (auto *L = dyn_cast<Lazy>(S)) {
317     if (!S->PendingArchiveLoad) {
318       S->PendingArchiveLoad = true;
319       L->File->addMember(&L->Sym);
320     }
321   }
322   return S;
323 }
324 
325 void SymbolTable::addLazy(ArchiveFile *F, const Archive::Symbol Sym) {
326   StringRef Name = Sym.getName();
327   Symbol *S;
328   bool WasInserted;
329   std::tie(S, WasInserted) = insert(Name);
330   if (WasInserted) {
331     replaceSymbol<Lazy>(S, F, Sym);
332     return;
333   }
334   auto *U = dyn_cast<Undefined>(S);
335   if (!U || U->WeakAlias || S->PendingArchiveLoad)
336     return;
337   S->PendingArchiveLoad = true;
338   F->addMember(&Sym);
339 }
340 
341 void SymbolTable::reportDuplicate(Symbol *Existing, InputFile *NewFile) {
342   std::string Msg = "duplicate symbol: " + toString(*Existing) + " in " +
343                     toString(Existing->getFile()) + " and in " +
344                     toString(NewFile);
345 
346   if (Config->ForceMultiple)
347     warn(Msg);
348   else
349     error(Msg);
350 }
351 
352 Symbol *SymbolTable::addAbsolute(StringRef N, COFFSymbolRef Sym) {
353   Symbol *S;
354   bool WasInserted;
355   std::tie(S, WasInserted) = insert(N, nullptr);
356   S->IsUsedInRegularObj = true;
357   if (WasInserted || isa<Undefined>(S) || isa<Lazy>(S))
358     replaceSymbol<DefinedAbsolute>(S, N, Sym);
359   else if (!isa<DefinedCOFF>(S))
360     reportDuplicate(S, nullptr);
361   return S;
362 }
363 
364 Symbol *SymbolTable::addAbsolute(StringRef N, uint64_t VA) {
365   Symbol *S;
366   bool WasInserted;
367   std::tie(S, WasInserted) = insert(N, nullptr);
368   S->IsUsedInRegularObj = true;
369   if (WasInserted || isa<Undefined>(S) || isa<Lazy>(S))
370     replaceSymbol<DefinedAbsolute>(S, N, VA);
371   else if (!isa<DefinedCOFF>(S))
372     reportDuplicate(S, nullptr);
373   return S;
374 }
375 
376 Symbol *SymbolTable::addSynthetic(StringRef N, Chunk *C) {
377   Symbol *S;
378   bool WasInserted;
379   std::tie(S, WasInserted) = insert(N, nullptr);
380   S->IsUsedInRegularObj = true;
381   if (WasInserted || isa<Undefined>(S) || isa<Lazy>(S))
382     replaceSymbol<DefinedSynthetic>(S, N, C);
383   else if (!isa<DefinedCOFF>(S))
384     reportDuplicate(S, nullptr);
385   return S;
386 }
387 
388 Symbol *SymbolTable::addRegular(InputFile *F, StringRef N,
389                                 const coff_symbol_generic *Sym,
390                                 SectionChunk *C) {
391   Symbol *S;
392   bool WasInserted;
393   std::tie(S, WasInserted) = insert(N, F);
394   if (WasInserted || !isa<DefinedRegular>(S))
395     replaceSymbol<DefinedRegular>(S, F, N, /*IsCOMDAT*/ false,
396                                   /*IsExternal*/ true, Sym, C);
397   else
398     reportDuplicate(S, F);
399   return S;
400 }
401 
402 std::pair<DefinedRegular *, bool>
403 SymbolTable::addComdat(InputFile *F, StringRef N,
404                        const coff_symbol_generic *Sym) {
405   Symbol *S;
406   bool WasInserted;
407   std::tie(S, WasInserted) = insert(N, F);
408   if (WasInserted || !isa<DefinedRegular>(S)) {
409     replaceSymbol<DefinedRegular>(S, F, N, /*IsCOMDAT*/ true,
410                                   /*IsExternal*/ true, Sym, nullptr);
411     return {cast<DefinedRegular>(S), true};
412   }
413   auto *ExistingSymbol = cast<DefinedRegular>(S);
414   if (!ExistingSymbol->isCOMDAT())
415     reportDuplicate(S, F);
416   return {ExistingSymbol, false};
417 }
418 
419 Symbol *SymbolTable::addCommon(InputFile *F, StringRef N, uint64_t Size,
420                                const coff_symbol_generic *Sym, CommonChunk *C) {
421   Symbol *S;
422   bool WasInserted;
423   std::tie(S, WasInserted) = insert(N, F);
424   if (WasInserted || !isa<DefinedCOFF>(S))
425     replaceSymbol<DefinedCommon>(S, F, N, Size, Sym, C);
426   else if (auto *DC = dyn_cast<DefinedCommon>(S))
427     if (Size > DC->getSize())
428       replaceSymbol<DefinedCommon>(S, F, N, Size, Sym, C);
429   return S;
430 }
431 
432 Symbol *SymbolTable::addImportData(StringRef N, ImportFile *F) {
433   Symbol *S;
434   bool WasInserted;
435   std::tie(S, WasInserted) = insert(N, nullptr);
436   S->IsUsedInRegularObj = true;
437   if (WasInserted || isa<Undefined>(S) || isa<Lazy>(S)) {
438     replaceSymbol<DefinedImportData>(S, N, F);
439     return S;
440   }
441 
442   reportDuplicate(S, F);
443   return nullptr;
444 }
445 
446 Symbol *SymbolTable::addImportThunk(StringRef Name, DefinedImportData *ID,
447                                     uint16_t Machine) {
448   Symbol *S;
449   bool WasInserted;
450   std::tie(S, WasInserted) = insert(Name, nullptr);
451   S->IsUsedInRegularObj = true;
452   if (WasInserted || isa<Undefined>(S) || isa<Lazy>(S)) {
453     replaceSymbol<DefinedImportThunk>(S, Name, ID, Machine);
454     return S;
455   }
456 
457   reportDuplicate(S, ID->File);
458   return nullptr;
459 }
460 
461 std::vector<Chunk *> SymbolTable::getChunks() {
462   std::vector<Chunk *> Res;
463   for (ObjFile *File : ObjFile::Instances) {
464     ArrayRef<Chunk *> V = File->getChunks();
465     Res.insert(Res.end(), V.begin(), V.end());
466   }
467   return Res;
468 }
469 
470 Symbol *SymbolTable::find(StringRef Name) {
471   return SymMap.lookup(CachedHashStringRef(Name));
472 }
473 
474 Symbol *SymbolTable::findUnderscore(StringRef Name) {
475   if (Config->Machine == I386)
476     return find(("_" + Name).str());
477   return find(Name);
478 }
479 
480 StringRef SymbolTable::findByPrefix(StringRef Prefix) {
481   for (auto Pair : SymMap) {
482     StringRef Name = Pair.first.val();
483     if (Name.startswith(Prefix))
484       return Name;
485   }
486   return "";
487 }
488 
489 StringRef SymbolTable::findMangle(StringRef Name) {
490   if (Symbol *Sym = find(Name))
491     if (!isa<Undefined>(Sym))
492       return Name;
493   if (Config->Machine != I386)
494     return findByPrefix(("?" + Name + "@@Y").str());
495   if (!Name.startswith("_"))
496     return "";
497   // Search for x86 stdcall function.
498   StringRef S = findByPrefix((Name + "@").str());
499   if (!S.empty())
500     return S;
501   // Search for x86 fastcall function.
502   S = findByPrefix(("@" + Name.substr(1) + "@").str());
503   if (!S.empty())
504     return S;
505   // Search for x86 vectorcall function.
506   S = findByPrefix((Name.substr(1) + "@@").str());
507   if (!S.empty())
508     return S;
509   // Search for x86 C++ non-member function.
510   return findByPrefix(("?" + Name.substr(1) + "@@Y").str());
511 }
512 
513 void SymbolTable::mangleMaybe(Symbol *B) {
514   auto *U = dyn_cast<Undefined>(B);
515   if (!U || U->WeakAlias)
516     return;
517   StringRef Alias = findMangle(U->getName());
518   if (!Alias.empty()) {
519     log(U->getName() + " aliased to " + Alias);
520     U->WeakAlias = addUndefined(Alias);
521   }
522 }
523 
524 Symbol *SymbolTable::addUndefined(StringRef Name) {
525   return addUndefined(Name, nullptr, false);
526 }
527 
528 std::vector<StringRef> SymbolTable::compileBitcodeFiles() {
529   LTO.reset(new BitcodeCompiler);
530   for (BitcodeFile *F : BitcodeFile::Instances)
531     LTO->add(*F);
532   return LTO->compile();
533 }
534 
535 void SymbolTable::addCombinedLTOObjects() {
536   if (BitcodeFile::Instances.empty())
537     return;
538 
539   ScopedTimer T(LTOTimer);
540   for (StringRef Object : compileBitcodeFiles()) {
541     auto *Obj = make<ObjFile>(MemoryBufferRef(Object, "lto.tmp"));
542     Obj->parse();
543     ObjFile::Instances.push_back(Obj);
544   }
545 }
546 
547 } // namespace coff
548 } // namespace lld
549