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/Support/Memory.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/LTO/legacy/LTOCodeGenerator.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include <utility>
21 
22 using namespace llvm;
23 
24 namespace lld {
25 namespace coff {
26 
27 SymbolTable *Symtab;
28 
29 void SymbolTable::addFile(InputFile *File) {
30   if (Config->Verbose)
31     outs() << "Reading " << toString(File) << "\n";
32   File->parse();
33 
34   MachineTypes MT = File->getMachineType();
35   if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
36     Config->Machine = MT;
37   } else if (MT != IMAGE_FILE_MACHINE_UNKNOWN && Config->Machine != MT) {
38     fatal(toString(File) + ": machine type " + machineToStr(MT) +
39           " conflicts with " + machineToStr(Config->Machine));
40   }
41 
42   if (auto *F = dyn_cast<ObjectFile>(File)) {
43     ObjectFiles.push_back(F);
44   } else if (auto *F = dyn_cast<BitcodeFile>(File)) {
45     BitcodeFiles.push_back(F);
46   } else if (auto *F = dyn_cast<ImportFile>(File)) {
47     ImportFiles.push_back(F);
48   }
49 
50   StringRef S = File->getDirectives();
51   if (S.empty())
52     return;
53 
54   if (Config->Verbose)
55     outs() << "Directives: " << toString(File) << ": " << S << "\n";
56   Driver->parseDirectives(S);
57 }
58 
59 void SymbolTable::reportRemainingUndefines() {
60   SmallPtrSet<SymbolBody *, 8> Undefs;
61   for (auto &I : Symtab) {
62     Symbol *Sym = I.second;
63     auto *Undef = dyn_cast<Undefined>(Sym->body());
64     if (!Undef)
65       continue;
66     if (!Sym->IsUsedInRegularObj)
67       continue;
68     StringRef Name = Undef->getName();
69     // A weak alias may have been resolved, so check for that.
70     if (Defined *D = Undef->getWeakAlias()) {
71       // We resolve weak aliases by replacing the alias's SymbolBody with the
72       // target's SymbolBody. This causes all SymbolBody pointers referring to
73       // the old symbol to instead refer to the new symbol. However, we can't
74       // just blindly copy sizeof(Symbol::Body) bytes from D to Sym->Body
75       // because D may be an internal symbol, and internal symbols are stored as
76       // "unparented" SymbolBodies. For that reason we need to check which type
77       // of symbol we are dealing with and copy the correct number of bytes.
78       if (isa<DefinedRegular>(D))
79         memcpy(Sym->Body.buffer, D, sizeof(DefinedRegular));
80       else if (isa<DefinedAbsolute>(D))
81         memcpy(Sym->Body.buffer, D, sizeof(DefinedAbsolute));
82       else
83         // No other internal symbols are possible.
84         Sym->Body = D->symbol()->Body;
85       continue;
86     }
87     // If we can resolve a symbol by removing __imp_ prefix, do that.
88     // This odd rule is for compatibility with MSVC linker.
89     if (Name.startswith("__imp_")) {
90       Symbol *Imp = find(Name.substr(strlen("__imp_")));
91       if (Imp && isa<Defined>(Imp->body())) {
92         auto *D = cast<Defined>(Imp->body());
93         replaceBody<DefinedLocalImport>(Sym, Name, D);
94         LocalImportChunks.push_back(
95             cast<DefinedLocalImport>(Sym->body())->getChunk());
96         continue;
97       }
98     }
99     // Remaining undefined symbols are not fatal if /force is specified.
100     // They are replaced with dummy defined symbols.
101     if (Config->Force)
102       replaceBody<DefinedAbsolute>(Sym, Name, 0);
103     Undefs.insert(Sym->body());
104   }
105   if (Undefs.empty())
106     return;
107   for (SymbolBody *B : Config->GCRoot)
108     if (Undefs.count(B))
109       errs() << "<root>: undefined symbol: " << B->getName() << "\n";
110   for (ObjectFile *File : ObjectFiles)
111     for (SymbolBody *Sym : File->getSymbols())
112       if (Undefs.count(Sym))
113         errs() << toString(File) << ": undefined symbol: " << Sym->getName()
114                << "\n";
115   if (!Config->Force)
116     fatal("link failed");
117 }
118 
119 std::pair<Symbol *, bool> SymbolTable::insert(StringRef Name) {
120   Symbol *&Sym = Symtab[CachedHashStringRef(Name)];
121   if (Sym)
122     return {Sym, false};
123   Sym = make<Symbol>();
124   Sym->IsUsedInRegularObj = false;
125   return {Sym, true};
126 }
127 
128 Symbol *SymbolTable::addUndefined(StringRef Name, InputFile *F,
129                                   bool IsWeakAlias) {
130   Symbol *S;
131   bool WasInserted;
132   std::tie(S, WasInserted) = insert(Name);
133   if (!F || !isa<BitcodeFile>(F))
134     S->IsUsedInRegularObj = true;
135   if (WasInserted || (isa<Lazy>(S->body()) && IsWeakAlias)) {
136     replaceBody<Undefined>(S, Name);
137     return S;
138   }
139   if (auto *L = dyn_cast<Lazy>(S->body()))
140     addMemberFile(L->File, L->Sym);
141   return S;
142 }
143 
144 void SymbolTable::addLazy(ArchiveFile *F, const Archive::Symbol Sym) {
145   StringRef Name = Sym.getName();
146   Symbol *S;
147   bool WasInserted;
148   std::tie(S, WasInserted) = insert(Name);
149   if (WasInserted) {
150     replaceBody<Lazy>(S, F, Sym);
151     return;
152   }
153   auto *U = dyn_cast<Undefined>(S->body());
154   if (!U || U->WeakAlias)
155     return;
156   addMemberFile(F, Sym);
157 }
158 
159 void SymbolTable::reportDuplicate(Symbol *Existing, InputFile *NewFile) {
160   fatal("duplicate symbol: " + toString(*Existing->body()) + " in " +
161         toString(Existing->body()->getFile()) + " and in " +
162         (NewFile ? toString(NewFile) : "(internal)"));
163 }
164 
165 Symbol *SymbolTable::addAbsolute(StringRef N, COFFSymbolRef Sym) {
166   Symbol *S;
167   bool WasInserted;
168   std::tie(S, WasInserted) = insert(N);
169   S->IsUsedInRegularObj = true;
170   if (WasInserted || isa<Undefined>(S->body()) || isa<Lazy>(S->body()))
171     replaceBody<DefinedAbsolute>(S, N, Sym);
172   else if (!isa<DefinedCOFF>(S->body()))
173     reportDuplicate(S, nullptr);
174   return S;
175 }
176 
177 Symbol *SymbolTable::addAbsolute(StringRef N, uint64_t VA) {
178   Symbol *S;
179   bool WasInserted;
180   std::tie(S, WasInserted) = insert(N);
181   S->IsUsedInRegularObj = true;
182   if (WasInserted || isa<Undefined>(S->body()) || isa<Lazy>(S->body()))
183     replaceBody<DefinedAbsolute>(S, N, VA);
184   else if (!isa<DefinedCOFF>(S->body()))
185     reportDuplicate(S, nullptr);
186   return S;
187 }
188 
189 Symbol *SymbolTable::addRelative(StringRef N, uint64_t VA) {
190   Symbol *S;
191   bool WasInserted;
192   std::tie(S, WasInserted) = insert(N);
193   S->IsUsedInRegularObj = true;
194   if (WasInserted || isa<Undefined>(S->body()) || isa<Lazy>(S->body()))
195     replaceBody<DefinedRelative>(S, N, VA);
196   else if (!isa<DefinedCOFF>(S->body()))
197     reportDuplicate(S, nullptr);
198   return S;
199 }
200 
201 Symbol *SymbolTable::addRegular(ObjectFile *F, COFFSymbolRef Sym,
202                                 SectionChunk *C) {
203   StringRef Name;
204   F->getCOFFObj()->getSymbolName(Sym, Name);
205   Symbol *S;
206   bool WasInserted;
207   std::tie(S, WasInserted) = insert(Name);
208   S->IsUsedInRegularObj = true;
209   if (WasInserted || isa<Undefined>(S->body()) || isa<Lazy>(S->body()))
210     replaceBody<DefinedRegular>(S, F, Sym, C);
211   else if (auto *R = dyn_cast<DefinedRegular>(S->body())) {
212     if (!C->isCOMDAT() || !R->isCOMDAT())
213       reportDuplicate(S, F);
214   } else if (auto *B = dyn_cast<DefinedBitcode>(S->body())) {
215     if (B->IsReplaceable)
216       replaceBody<DefinedRegular>(S, F, Sym, C);
217     else if (!C->isCOMDAT())
218       reportDuplicate(S, F);
219   } else
220     replaceBody<DefinedRegular>(S, F, Sym, C);
221   return S;
222 }
223 
224 Symbol *SymbolTable::addBitcode(BitcodeFile *F, StringRef N, bool IsReplaceable) {
225   Symbol *S;
226   bool WasInserted;
227   std::tie(S, WasInserted) = insert(N);
228   if (WasInserted || isa<Undefined>(S->body()) || isa<Lazy>(S->body())) {
229     replaceBody<DefinedBitcode>(S, F, N, IsReplaceable);
230     return S;
231   }
232   if (isa<DefinedCommon>(S->body()))
233     return S;
234   if (IsReplaceable)
235     if (isa<DefinedRegular>(S->body()) || isa<DefinedBitcode>(S->body()))
236       return S;
237   reportDuplicate(S, F);
238   return S;
239 }
240 
241 Symbol *SymbolTable::addCommon(ObjectFile *F, COFFSymbolRef Sym,
242                                CommonChunk *C) {
243   StringRef Name;
244   F->getCOFFObj()->getSymbolName(Sym, Name);
245   Symbol *S;
246   bool WasInserted;
247   std::tie(S, WasInserted) = insert(Name);
248   S->IsUsedInRegularObj = true;
249   if (WasInserted || !isa<DefinedCOFF>(S->body()))
250     replaceBody<DefinedCommon>(S, F, Sym, C);
251   else if (auto *DC = dyn_cast<DefinedCommon>(S->body()))
252     if (Sym.getValue() > DC->getSize())
253       replaceBody<DefinedCommon>(S, F, Sym, C);
254   return S;
255 }
256 
257 Symbol *SymbolTable::addImportData(StringRef N, ImportFile *F) {
258   Symbol *S;
259   bool WasInserted;
260   std::tie(S, WasInserted) = insert(N);
261   S->IsUsedInRegularObj = true;
262   if (WasInserted || isa<Undefined>(S->body()) || isa<Lazy>(S->body()))
263     replaceBody<DefinedImportData>(S, N, F);
264   else if (!isa<DefinedCOFF>(S->body()))
265     reportDuplicate(S, nullptr);
266   return S;
267 }
268 
269 Symbol *SymbolTable::addImportThunk(StringRef Name, DefinedImportData *ID,
270                                     uint16_t Machine) {
271   Symbol *S;
272   bool WasInserted;
273   std::tie(S, WasInserted) = insert(Name);
274   S->IsUsedInRegularObj = true;
275   if (WasInserted || isa<Undefined>(S->body()) || isa<Lazy>(S->body()))
276     replaceBody<DefinedImportThunk>(S, Name, ID, Machine);
277   else if (!isa<DefinedCOFF>(S->body()))
278     reportDuplicate(S, nullptr);
279   return S;
280 }
281 
282 // Reads an archive member file pointed by a given symbol.
283 void SymbolTable::addMemberFile(ArchiveFile *F, const Archive::Symbol Sym) {
284   InputFile *File = F->getMember(&Sym);
285 
286   // getMember returns an empty buffer if the member was already
287   // read from the library.
288   if (!File)
289     return;
290   if (Config->Verbose)
291     outs() << "Loaded " << toString(File) << " for " << Sym.getName() << "\n";
292   addFile(File);
293 }
294 
295 std::vector<Chunk *> SymbolTable::getChunks() {
296   std::vector<Chunk *> Res;
297   for (ObjectFile *File : ObjectFiles) {
298     std::vector<Chunk *> &V = File->getChunks();
299     Res.insert(Res.end(), V.begin(), V.end());
300   }
301   return Res;
302 }
303 
304 Symbol *SymbolTable::find(StringRef Name) {
305   auto It = Symtab.find(CachedHashStringRef(Name));
306   if (It == Symtab.end())
307     return nullptr;
308   return It->second;
309 }
310 
311 Symbol *SymbolTable::findUnderscore(StringRef Name) {
312   if (Config->Machine == I386)
313     return find(("_" + Name).str());
314   return find(Name);
315 }
316 
317 StringRef SymbolTable::findByPrefix(StringRef Prefix) {
318   for (auto Pair : Symtab) {
319     StringRef Name = Pair.first.val();
320     if (Name.startswith(Prefix))
321       return Name;
322   }
323   return "";
324 }
325 
326 StringRef SymbolTable::findMangle(StringRef Name) {
327   if (Symbol *Sym = find(Name))
328     if (!isa<Undefined>(Sym->body()))
329       return Name;
330   if (Config->Machine != I386)
331     return findByPrefix(("?" + Name + "@@Y").str());
332   if (!Name.startswith("_"))
333     return "";
334   // Search for x86 C function.
335   StringRef S = findByPrefix((Name + "@").str());
336   if (!S.empty())
337     return S;
338   // Search for x86 C++ non-member function.
339   return findByPrefix(("?" + Name.substr(1) + "@@Y").str());
340 }
341 
342 void SymbolTable::mangleMaybe(SymbolBody *B) {
343   auto *U = dyn_cast<Undefined>(B);
344   if (!U || U->WeakAlias)
345     return;
346   StringRef Alias = findMangle(U->getName());
347   if (!Alias.empty())
348     U->WeakAlias = addUndefined(Alias);
349 }
350 
351 SymbolBody *SymbolTable::addUndefined(StringRef Name) {
352   return addUndefined(Name, nullptr, false)->body();
353 }
354 
355 void SymbolTable::printMap(llvm::raw_ostream &OS) {
356   for (ObjectFile *File : ObjectFiles) {
357     OS << toString(File) << ":\n";
358     for (SymbolBody *Body : File->getSymbols())
359       if (auto *R = dyn_cast<DefinedRegular>(Body))
360         if (R->getChunk()->isLive())
361           OS << Twine::utohexstr(Config->ImageBase + R->getRVA())
362              << " " << R->getName() << "\n";
363   }
364 }
365 
366 void SymbolTable::addCombinedLTOObjects() {
367   if (BitcodeFiles.empty())
368     return;
369 
370   // Create an object file and add it to the symbol table by replacing any
371   // DefinedBitcode symbols with the definitions in the object file.
372   LTOCodeGenerator CG(BitcodeFile::Context);
373   CG.setOptLevel(Config->LTOOptLevel);
374   std::vector<ObjectFile *> Objs = createLTOObjects(&CG);
375 
376   size_t NumBitcodeFiles = BitcodeFiles.size();
377   for (ObjectFile *Obj : Objs)
378     Obj->parse();
379   if (BitcodeFiles.size() != NumBitcodeFiles)
380     fatal("LTO: late loaded symbol created new bitcode reference");
381 }
382 
383 // Combine and compile bitcode files and then return the result
384 // as a vector of regular COFF object files.
385 std::vector<ObjectFile *> SymbolTable::createLTOObjects(LTOCodeGenerator *CG) {
386   // All symbols referenced by non-bitcode objects, including GC roots, must be
387   // preserved. We must also replace bitcode symbols with undefined symbols so
388   // that they may be replaced with real definitions without conflicting.
389   for (BitcodeFile *File : BitcodeFiles)
390     for (SymbolBody *Body : File->getSymbols()) {
391       if (!isa<DefinedBitcode>(Body))
392         continue;
393       if (Body->symbol()->IsUsedInRegularObj)
394         CG->addMustPreserveSymbol(Body->getName());
395       replaceBody<Undefined>(Body->symbol(), Body->getName());
396     }
397 
398   CG->setModule(BitcodeFiles[0]->takeModule());
399   for (unsigned I = 1, E = BitcodeFiles.size(); I != E; ++I)
400     CG->addModule(BitcodeFiles[I]->takeModule().get());
401 
402   bool DisableVerify = true;
403 #ifdef NDEBUG
404   DisableVerify = false;
405 #endif
406   if (!CG->optimize(DisableVerify, false, false, false))
407     fatal(""); // optimize() should have emitted any error message.
408 
409   Objs.resize(Config->LTOJobs);
410   // Use std::list to avoid invalidation of pointers in OSPtrs.
411   std::list<raw_svector_ostream> OSs;
412   std::vector<raw_pwrite_stream *> OSPtrs;
413   for (SmallString<0> &Obj : Objs) {
414     OSs.emplace_back(Obj);
415     OSPtrs.push_back(&OSs.back());
416   }
417 
418   if (!CG->compileOptimized(OSPtrs))
419     fatal(""); // compileOptimized() should have emitted any error message.
420 
421   std::vector<ObjectFile *> ObjFiles;
422   for (SmallString<0> &Obj : Objs) {
423     auto *ObjFile = new ObjectFile(MemoryBufferRef(Obj, "<LTO object>"));
424     ObjectFiles.push_back(ObjFile);
425     ObjFiles.push_back(ObjFile);
426   }
427 
428   return ObjFiles;
429 }
430 
431 } // namespace coff
432 } // namespace lld
433