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