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