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 "Error.h"
14 #include "Symbols.h"
15 #include "lld/Core/Parallel.h"
16 #include "lld/Support/Memory.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/LTO/legacy/LTOCodeGenerator.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 void SymbolTable::addFile(InputFile *File) {
29 #if LLVM_ENABLE_THREADS
30   std::launch Policy = std::launch::async;
31 #else
32   std::launch Policy = std::launch::deferred;
33 #endif
34 
35   Files.push_back(File);
36   if (auto *F = dyn_cast<ArchiveFile>(File)) {
37     ArchiveQueue.push_back(
38         std::async(Policy, [=]() { F->parse(); return F; }));
39     return;
40   }
41   ObjectQueue.push_back(
42       std::async(Policy, [=]() { File->parse(); return File; }));
43   if (auto *F = dyn_cast<ObjectFile>(File)) {
44     ObjectFiles.push_back(F);
45   } else if (auto *F = dyn_cast<BitcodeFile>(File)) {
46     BitcodeFiles.push_back(F);
47   } else {
48     ImportFiles.push_back(cast<ImportFile>(File));
49   }
50 }
51 
52 void SymbolTable::step() {
53   if (queueEmpty())
54     return;
55   readObjects();
56   readArchives();
57 }
58 
59 void SymbolTable::run() {
60   while (!queueEmpty())
61     step();
62 }
63 
64 void SymbolTable::readArchives() {
65   if (ArchiveQueue.empty())
66     return;
67 
68   // Add lazy symbols to the symbol table. Lazy symbols that conflict
69   // with existing undefined symbols are accumulated in LazySyms.
70   std::vector<Symbol *> LazySyms;
71   for (std::future<ArchiveFile *> &Future : ArchiveQueue) {
72     ArchiveFile *File = Future.get();
73     if (Config->Verbose)
74       outs() << "Reading " << toString(File) << "\n";
75     for (Lazy &Sym : File->getLazySymbols())
76       addLazy(&Sym, &LazySyms);
77   }
78   ArchiveQueue.clear();
79 
80   // Add archive member files to ObjectQueue that should resolve
81   // existing undefined symbols.
82   for (Symbol *Sym : LazySyms)
83     addMemberFile(cast<Lazy>(Sym->Body));
84 }
85 
86 void SymbolTable::readObjects() {
87   if (ObjectQueue.empty())
88     return;
89 
90   // Add defined and undefined symbols to the symbol table.
91   std::vector<StringRef> Directives;
92   for (size_t I = 0; I < ObjectQueue.size(); ++I) {
93     InputFile *File = ObjectQueue[I].get();
94     if (Config->Verbose)
95       outs() << "Reading " << toString(File) << "\n";
96     // Adding symbols may add more files to ObjectQueue
97     // (but not to ArchiveQueue).
98     for (SymbolBody *Sym : File->getSymbols())
99       if (Sym->isExternal())
100         addSymbol(Sym);
101     StringRef S = File->getDirectives();
102     if (!S.empty()) {
103       Directives.push_back(S);
104       if (Config->Verbose)
105         outs() << "Directives: " << toString(File) << ": " << S << "\n";
106     }
107   }
108   ObjectQueue.clear();
109 
110   // Parse directive sections. This may add files to
111   // ArchiveQueue and ObjectQueue.
112   for (StringRef S : Directives)
113     Driver->parseDirectives(S);
114 }
115 
116 bool SymbolTable::queueEmpty() {
117   return ArchiveQueue.empty() && ObjectQueue.empty();
118 }
119 
120 void SymbolTable::reportRemainingUndefines(bool Resolve) {
121   SmallPtrSet<SymbolBody *, 8> Undefs;
122   for (auto &I : Symtab) {
123     Symbol *Sym = I.second;
124     auto *Undef = dyn_cast<Undefined>(Sym->Body);
125     if (!Undef)
126       continue;
127     StringRef Name = Undef->getName();
128     // A weak alias may have been resolved, so check for that.
129     if (Defined *D = Undef->getWeakAlias()) {
130       if (Resolve)
131         Sym->Body = D;
132       continue;
133     }
134     // If we can resolve a symbol by removing __imp_ prefix, do that.
135     // This odd rule is for compatibility with MSVC linker.
136     if (Name.startswith("__imp_")) {
137       Symbol *Imp = find(Name.substr(strlen("__imp_")));
138       if (Imp && isa<Defined>(Imp->Body)) {
139         if (!Resolve)
140           continue;
141         auto *D = cast<Defined>(Imp->Body);
142         auto *S = new (Alloc) DefinedLocalImport(Name, D);
143         LocalImportChunks.push_back(S->getChunk());
144         Sym->Body = S;
145         continue;
146       }
147     }
148     // Remaining undefined symbols are not fatal if /force is specified.
149     // They are replaced with dummy defined symbols.
150     if (Config->Force && Resolve)
151       Sym->Body = new (Alloc) DefinedAbsolute(Name, 0);
152     Undefs.insert(Sym->Body);
153   }
154   if (Undefs.empty())
155     return;
156   for (Undefined *U : Config->GCRoot)
157     if (Undefs.count(U->repl()))
158       errs() << "<root>: undefined symbol: " << U->getName() << "\n";
159   for (InputFile *File : Files)
160     if (!isa<ArchiveFile>(File))
161       for (SymbolBody *Sym : File->getSymbols())
162         if (Undefs.count(Sym->repl()))
163           errs() << toString(File) << ": undefined symbol: " << Sym->getName()
164                  << "\n";
165   if (!Config->Force)
166     fatal("link failed");
167 }
168 
169 void SymbolTable::addLazy(Lazy *New, std::vector<Symbol *> *Accum) {
170   Symbol *Sym = insert(New);
171   if (Sym->Body == New)
172     return;
173   SymbolBody *Existing = Sym->Body;
174   if (isa<Defined>(Existing))
175     return;
176   if (Lazy *L = dyn_cast<Lazy>(Existing))
177     if (L->getFileIndex() < New->getFileIndex())
178       return;
179   Sym->Body = New;
180   New->setBackref(Sym);
181   if (isa<Undefined>(Existing))
182     Accum->push_back(Sym);
183 }
184 
185 void SymbolTable::addSymbol(SymbolBody *New) {
186   // Find an existing symbol or create and insert a new one.
187   assert(isa<Defined>(New) || isa<Undefined>(New));
188   Symbol *Sym = insert(New);
189   if (Sym->Body == New)
190     return;
191   SymbolBody *Existing = Sym->Body;
192 
193   // If we have an undefined symbol and a lazy symbol,
194   // let the lazy symbol to read a member file.
195   if (auto *L = dyn_cast<Lazy>(Existing)) {
196     // Undefined symbols with weak aliases need not to be resolved,
197     // since they would be replaced with weak aliases if they remain
198     // undefined.
199     if (auto *U = dyn_cast<Undefined>(New)) {
200       if (!U->WeakAlias) {
201         addMemberFile(L);
202         return;
203       }
204     }
205     Sym->Body = New;
206     return;
207   }
208 
209   // compare() returns -1, 0, or 1 if the lhs symbol is less preferable,
210   // equivalent (conflicting), or more preferable, respectively.
211   int Comp = Existing->compare(New);
212   if (Comp == 0)
213     fatal("duplicate symbol: " + toString(*Existing) + " in " +
214           toString(Existing->getFile()) + " and in " +
215           toString(New->getFile()));
216   if (Comp < 0)
217     Sym->Body = New;
218 }
219 
220 Symbol *SymbolTable::insert(SymbolBody *New) {
221   Symbol *&Sym = Symtab[New->getName()];
222   if (Sym) {
223     New->setBackref(Sym);
224     return Sym;
225   }
226   Sym = new (Alloc) Symbol(New);
227   New->setBackref(Sym);
228   return Sym;
229 }
230 
231 // Reads an archive member file pointed by a given symbol.
232 void SymbolTable::addMemberFile(Lazy *Body) {
233   InputFile *File = Body->getMember();
234 
235   // getMember returns an empty buffer if the member was already
236   // read from the library.
237   if (!File)
238     return;
239   if (Config->Verbose)
240     outs() << "Loaded " << toString(File) << " for " << Body->getName() << "\n";
241   addFile(File);
242 }
243 
244 std::vector<Chunk *> SymbolTable::getChunks() {
245   std::vector<Chunk *> Res;
246   for (ObjectFile *File : ObjectFiles) {
247     std::vector<Chunk *> &V = File->getChunks();
248     Res.insert(Res.end(), V.begin(), V.end());
249   }
250   return Res;
251 }
252 
253 Symbol *SymbolTable::find(StringRef Name) {
254   auto It = Symtab.find(Name);
255   if (It == Symtab.end())
256     return nullptr;
257   return It->second;
258 }
259 
260 Symbol *SymbolTable::findUnderscore(StringRef Name) {
261   if (Config->Machine == I386)
262     return find(("_" + Name).str());
263   return find(Name);
264 }
265 
266 StringRef SymbolTable::findByPrefix(StringRef Prefix) {
267   for (auto Pair : Symtab) {
268     StringRef Name = Pair.first;
269     if (Name.startswith(Prefix))
270       return Name;
271   }
272   return "";
273 }
274 
275 StringRef SymbolTable::findMangle(StringRef Name) {
276   if (Symbol *Sym = find(Name))
277     if (!isa<Undefined>(Sym->Body))
278       return Name;
279   if (Config->Machine != I386)
280     return findByPrefix(("?" + Name + "@@Y").str());
281   if (!Name.startswith("_"))
282     return "";
283   // Search for x86 C function.
284   StringRef S = findByPrefix((Name + "@").str());
285   if (!S.empty())
286     return S;
287   // Search for x86 C++ non-member function.
288   return findByPrefix(("?" + Name.substr(1) + "@@Y").str());
289 }
290 
291 void SymbolTable::mangleMaybe(Undefined *U) {
292   if (U->WeakAlias)
293     return;
294   if (!isa<Undefined>(U->repl()))
295     return;
296   StringRef Alias = findMangle(U->getName());
297   if (!Alias.empty())
298     U->WeakAlias = addUndefined(Alias);
299 }
300 
301 Undefined *SymbolTable::addUndefined(StringRef Name) {
302   auto *New = new (Alloc) Undefined(Name);
303   addSymbol(New);
304   if (auto *U = dyn_cast<Undefined>(New->repl()))
305     return U;
306   return New;
307 }
308 
309 DefinedRelative *SymbolTable::addRelative(StringRef Name, uint64_t VA) {
310   auto *New = new (Alloc) DefinedRelative(Name, VA);
311   addSymbol(New);
312   return New;
313 }
314 
315 DefinedAbsolute *SymbolTable::addAbsolute(StringRef Name, uint64_t VA) {
316   auto *New = new (Alloc) DefinedAbsolute(Name, VA);
317   addSymbol(New);
318   return New;
319 }
320 
321 void SymbolTable::printMap(llvm::raw_ostream &OS) {
322   for (ObjectFile *File : ObjectFiles) {
323     OS << toString(File) << ":\n";
324     for (SymbolBody *Body : File->getSymbols())
325       if (auto *R = dyn_cast<DefinedRegular>(Body))
326         if (R->getChunk()->isLive())
327           OS << Twine::utohexstr(Config->ImageBase + R->getRVA())
328              << " " << R->getName() << "\n";
329   }
330 }
331 
332 void SymbolTable::addCombinedLTOObject(ObjectFile *Obj) {
333   for (SymbolBody *Body : Obj->getSymbols()) {
334     if (!Body->isExternal())
335       continue;
336     // We should not see any new undefined symbols at this point, but we'll
337     // diagnose them later in reportRemainingUndefines().
338     StringRef Name = Body->getName();
339     Symbol *Sym = insert(Body);
340     SymbolBody *Existing = Sym->Body;
341 
342     if (Existing == Body)
343       continue;
344 
345     if (isa<DefinedBitcode>(Existing)) {
346       Sym->Body = Body;
347       continue;
348     }
349     if (isa<Undefined>(Body)) {
350       if (auto *L = dyn_cast<Lazy>(Existing)) {
351         // We may see new references to runtime library symbols such as __chkstk
352         // here. These symbols must be wholly defined in non-bitcode files.
353         addMemberFile(L);
354         continue;
355       }
356     }
357 
358     int Comp = Existing->compare(Body);
359     if (Comp == 0)
360       fatal("LTO: unexpected duplicate symbol: " + Name);
361     if (Comp < 0)
362       Sym->Body = Body;
363   }
364 }
365 
366 void SymbolTable::addCombinedLTOObjects() {
367   if (BitcodeFiles.empty())
368     return;
369 
370   // Diagnose any undefined symbols early, but do not resolve weak externals,
371   // as resolution breaks the invariant that each Symbol points to a unique
372   // SymbolBody, which we rely on to replace DefinedBitcode symbols correctly.
373   reportRemainingUndefines(/*Resolve=*/false);
374 
375   // Create an object file and add it to the symbol table by replacing any
376   // DefinedBitcode symbols with the definitions in the object file.
377   LTOCodeGenerator CG(BitcodeFile::Context);
378   CG.setOptLevel(Config->LTOOptLevel);
379   std::vector<ObjectFile *> Objs = createLTOObjects(&CG);
380 
381   for (ObjectFile *Obj : Objs)
382     addCombinedLTOObject(Obj);
383 
384   size_t NumBitcodeFiles = BitcodeFiles.size();
385   run();
386   if (BitcodeFiles.size() != NumBitcodeFiles)
387     fatal("LTO: late loaded symbol created new bitcode reference");
388 }
389 
390 // Combine and compile bitcode files and then return the result
391 // as a vector of regular COFF object files.
392 std::vector<ObjectFile *> SymbolTable::createLTOObjects(LTOCodeGenerator *CG) {
393   // All symbols referenced by non-bitcode objects must be preserved.
394   for (ObjectFile *File : ObjectFiles)
395     for (SymbolBody *Body : File->getSymbols())
396       if (auto *S = dyn_cast<DefinedBitcode>(Body->repl()))
397         CG->addMustPreserveSymbol(S->getName());
398 
399   // Likewise for bitcode symbols which we initially resolved to non-bitcode.
400   for (BitcodeFile *File : BitcodeFiles)
401     for (SymbolBody *Body : File->getSymbols())
402       if (isa<DefinedBitcode>(Body) && !isa<DefinedBitcode>(Body->repl()))
403         CG->addMustPreserveSymbol(Body->getName());
404 
405   // Likewise for other symbols that must be preserved.
406   for (Undefined *U : Config->GCRoot) {
407     if (auto *S = dyn_cast<DefinedBitcode>(U->repl()))
408       CG->addMustPreserveSymbol(S->getName());
409     else if (auto *S = dyn_cast_or_null<DefinedBitcode>(U->getWeakAlias()))
410       CG->addMustPreserveSymbol(S->getName());
411   }
412 
413   CG->setModule(BitcodeFiles[0]->takeModule());
414   for (unsigned I = 1, E = BitcodeFiles.size(); I != E; ++I)
415     CG->addModule(BitcodeFiles[I]->takeModule().get());
416 
417   bool DisableVerify = true;
418 #ifdef NDEBUG
419   DisableVerify = false;
420 #endif
421   if (!CG->optimize(DisableVerify, false, false, false))
422     fatal(""); // optimize() should have emitted any error message.
423 
424   Objs.resize(Config->LTOJobs);
425   // Use std::list to avoid invalidation of pointers in OSPtrs.
426   std::list<raw_svector_ostream> OSs;
427   std::vector<raw_pwrite_stream *> OSPtrs;
428   for (SmallString<0> &Obj : Objs) {
429     OSs.emplace_back(Obj);
430     OSPtrs.push_back(&OSs.back());
431   }
432 
433   if (!CG->compileOptimized(OSPtrs))
434     fatal(""); // compileOptimized() should have emitted any error message.
435 
436   std::vector<ObjectFile *> ObjFiles;
437   for (SmallString<0> &Obj : Objs) {
438     auto *ObjFile = new ObjectFile(MemoryBufferRef(Obj, "<LTO object>"));
439     Files.emplace_back(ObjFile);
440     ObjectFiles.push_back(ObjFile);
441     ObjFile->parse();
442     ObjFiles.push_back(ObjFile);
443   }
444 
445   return ObjFiles;
446 }
447 
448 } // namespace coff
449 } // namespace lld
450