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 "LTO.h"
15 #include "Memory.h"
16 #include "Symbols.h"
17 #include "llvm/IR/LLVMContext.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 enum SymbolPreference {
28   SP_EXISTING = -1,
29   SP_CONFLICT = 0,
30   SP_NEW = 1,
31 };
32 
33 /// Checks if an existing symbol S should be kept or replaced by a new symbol.
34 /// Returns SP_EXISTING when S should be kept, SP_NEW when the new symbol
35 /// should be kept, and SP_CONFLICT if no valid resolution exists.
36 static SymbolPreference compareDefined(Symbol *S, bool WasInserted,
37                                        bool NewIsCOMDAT) {
38   // If the symbol wasn't previously known, the new symbol wins by default.
39   if (WasInserted || !isa<Defined>(S->body()))
40     return SP_NEW;
41 
42   // If the existing symbol is a DefinedRegular, both it and the new symbol
43   // must be comdats. In that case, we have no reason to prefer one symbol
44   // over the other, and we keep the existing one. If one of the symbols
45   // is not a comdat, we report a conflict.
46   if (auto *R = dyn_cast<DefinedRegular>(S->body())) {
47     if (NewIsCOMDAT && R->isCOMDAT())
48       return SP_EXISTING;
49     else
50       return SP_CONFLICT;
51   }
52 
53   // Existing symbol is not a DefinedRegular; new symbol wins.
54   return SP_NEW;
55 }
56 
57 SymbolTable *Symtab;
58 
59 void SymbolTable::addFile(InputFile *File) {
60   if (Config->Verbose)
61     outs() << "Reading " << toString(File) << "\n";
62   File->parse();
63 
64   MachineTypes MT = File->getMachineType();
65   if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
66     Config->Machine = MT;
67   } else if (MT != IMAGE_FILE_MACHINE_UNKNOWN && Config->Machine != MT) {
68     fatal(toString(File) + ": machine type " + machineToStr(MT) +
69           " conflicts with " + machineToStr(Config->Machine));
70   }
71 
72   if (auto *F = dyn_cast<ObjectFile>(File)) {
73     ObjectFiles.push_back(F);
74   } else if (auto *F = dyn_cast<BitcodeFile>(File)) {
75     BitcodeFiles.push_back(F);
76   } else if (auto *F = dyn_cast<ImportFile>(File)) {
77     ImportFiles.push_back(F);
78   }
79 
80   StringRef S = File->getDirectives();
81   if (S.empty())
82     return;
83 
84   if (Config->Verbose)
85     outs() << "Directives: " << toString(File) << ": " << S << "\n";
86   Driver->parseDirectives(S);
87 }
88 
89 void SymbolTable::reportRemainingUndefines() {
90   SmallPtrSet<SymbolBody *, 8> Undefs;
91   for (auto &I : Symtab) {
92     Symbol *Sym = I.second;
93     auto *Undef = dyn_cast<Undefined>(Sym->body());
94     if (!Undef)
95       continue;
96     if (!Sym->IsUsedInRegularObj)
97       continue;
98     StringRef Name = Undef->getName();
99     // A weak alias may have been resolved, so check for that.
100     if (Defined *D = Undef->getWeakAlias()) {
101       // We resolve weak aliases by replacing the alias's SymbolBody with the
102       // target's SymbolBody. This causes all SymbolBody pointers referring to
103       // the old symbol to instead refer to the new symbol. However, we can't
104       // just blindly copy sizeof(Symbol::Body) bytes from D to Sym->Body
105       // because D may be an internal symbol, and internal symbols are stored as
106       // "unparented" SymbolBodies. For that reason we need to check which type
107       // of symbol we are dealing with and copy the correct number of bytes.
108       if (isa<DefinedRegular>(D))
109         memcpy(Sym->Body.buffer, D, sizeof(DefinedRegular));
110       else if (isa<DefinedAbsolute>(D))
111         memcpy(Sym->Body.buffer, D, sizeof(DefinedAbsolute));
112       else
113         // No other internal symbols are possible.
114         Sym->Body = D->symbol()->Body;
115       continue;
116     }
117     // If we can resolve a symbol by removing __imp_ prefix, do that.
118     // This odd rule is for compatibility with MSVC linker.
119     if (Name.startswith("__imp_")) {
120       Symbol *Imp = find(Name.substr(strlen("__imp_")));
121       if (Imp && isa<Defined>(Imp->body())) {
122         auto *D = cast<Defined>(Imp->body());
123         replaceBody<DefinedLocalImport>(Sym, Name, D);
124         LocalImportChunks.push_back(
125             cast<DefinedLocalImport>(Sym->body())->getChunk());
126         continue;
127       }
128     }
129     // Remaining undefined symbols are not fatal if /force is specified.
130     // They are replaced with dummy defined symbols.
131     if (Config->Force)
132       replaceBody<DefinedAbsolute>(Sym, Name, 0);
133     Undefs.insert(Sym->body());
134   }
135   if (Undefs.empty())
136     return;
137   for (SymbolBody *B : Config->GCRoot)
138     if (Undefs.count(B))
139       errs() << "<root>: undefined symbol: " << B->getName() << "\n";
140   for (ObjectFile *File : ObjectFiles)
141     for (SymbolBody *Sym : File->getSymbols())
142       if (Undefs.count(Sym))
143         errs() << toString(File) << ": undefined symbol: " << Sym->getName()
144                << "\n";
145   if (!Config->Force)
146     fatal("link failed");
147 }
148 
149 std::pair<Symbol *, bool> SymbolTable::insert(StringRef Name) {
150   Symbol *&Sym = Symtab[CachedHashStringRef(Name)];
151   if (Sym)
152     return {Sym, false};
153   Sym = make<Symbol>();
154   Sym->IsUsedInRegularObj = false;
155   Sym->PendingArchiveLoad = false;
156   return {Sym, true};
157 }
158 
159 Symbol *SymbolTable::addUndefined(StringRef Name, InputFile *F,
160                                   bool IsWeakAlias) {
161   Symbol *S;
162   bool WasInserted;
163   std::tie(S, WasInserted) = insert(Name);
164   if (!F || !isa<BitcodeFile>(F))
165     S->IsUsedInRegularObj = true;
166   if (WasInserted || (isa<Lazy>(S->body()) && IsWeakAlias)) {
167     replaceBody<Undefined>(S, Name);
168     return S;
169   }
170   if (auto *L = dyn_cast<Lazy>(S->body())) {
171     if (!S->PendingArchiveLoad) {
172       S->PendingArchiveLoad = true;
173       L->File->addMember(&L->Sym);
174     }
175   }
176   return S;
177 }
178 
179 void SymbolTable::addLazy(ArchiveFile *F, const Archive::Symbol Sym) {
180   StringRef Name = Sym.getName();
181   Symbol *S;
182   bool WasInserted;
183   std::tie(S, WasInserted) = insert(Name);
184   if (WasInserted) {
185     replaceBody<Lazy>(S, F, Sym);
186     return;
187   }
188   auto *U = dyn_cast<Undefined>(S->body());
189   if (!U || U->WeakAlias || S->PendingArchiveLoad)
190     return;
191   S->PendingArchiveLoad = true;
192   F->addMember(&Sym);
193 }
194 
195 void SymbolTable::reportDuplicate(Symbol *Existing, InputFile *NewFile) {
196   fatal("duplicate symbol: " + toString(*Existing->body()) + " in " +
197         toString(Existing->body()->getFile()) + " and in " +
198         (NewFile ? toString(NewFile) : "(internal)"));
199 }
200 
201 Symbol *SymbolTable::addAbsolute(StringRef N, COFFSymbolRef Sym) {
202   Symbol *S;
203   bool WasInserted;
204   std::tie(S, WasInserted) = insert(N);
205   S->IsUsedInRegularObj = true;
206   if (WasInserted || isa<Undefined>(S->body()) || isa<Lazy>(S->body()))
207     replaceBody<DefinedAbsolute>(S, N, Sym);
208   else if (!isa<DefinedCOFF>(S->body()))
209     reportDuplicate(S, nullptr);
210   return S;
211 }
212 
213 Symbol *SymbolTable::addAbsolute(StringRef N, uint64_t VA) {
214   Symbol *S;
215   bool WasInserted;
216   std::tie(S, WasInserted) = insert(N);
217   S->IsUsedInRegularObj = true;
218   if (WasInserted || isa<Undefined>(S->body()) || isa<Lazy>(S->body()))
219     replaceBody<DefinedAbsolute>(S, N, VA);
220   else if (!isa<DefinedCOFF>(S->body()))
221     reportDuplicate(S, nullptr);
222   return S;
223 }
224 
225 Symbol *SymbolTable::addRelative(StringRef N, uint64_t VA) {
226   Symbol *S;
227   bool WasInserted;
228   std::tie(S, WasInserted) = insert(N);
229   S->IsUsedInRegularObj = true;
230   if (WasInserted || isa<Undefined>(S->body()) || isa<Lazy>(S->body()))
231     replaceBody<DefinedRelative>(S, N, VA);
232   else if (!isa<DefinedCOFF>(S->body()))
233     reportDuplicate(S, nullptr);
234   return S;
235 }
236 
237 Symbol *SymbolTable::addRegular(InputFile *F, StringRef N, bool IsCOMDAT,
238                                 const coff_symbol_generic *Sym,
239                                 SectionChunk *C) {
240   Symbol *S;
241   bool WasInserted;
242   std::tie(S, WasInserted) = insert(N);
243   if (!isa<BitcodeFile>(F))
244     S->IsUsedInRegularObj = true;
245   SymbolPreference SP = compareDefined(S, WasInserted, IsCOMDAT);
246   if (SP == SP_CONFLICT) {
247     reportDuplicate(S, F);
248   } else if (SP == SP_NEW) {
249     replaceBody<DefinedRegular>(S, F, N, IsCOMDAT, /*IsExternal*/ true, Sym, C);
250   }
251   return S;
252 }
253 
254 Symbol *SymbolTable::addCommon(InputFile *F, StringRef N, uint64_t Size,
255                                const coff_symbol_generic *Sym, CommonChunk *C) {
256   Symbol *S;
257   bool WasInserted;
258   std::tie(S, WasInserted) = insert(N);
259   if (!isa<BitcodeFile>(F))
260     S->IsUsedInRegularObj = true;
261   if (WasInserted || !isa<DefinedCOFF>(S->body()))
262     replaceBody<DefinedCommon>(S, F, N, Size, Sym, C);
263   else if (auto *DC = dyn_cast<DefinedCommon>(S->body()))
264     if (Size > DC->getSize())
265       replaceBody<DefinedCommon>(S, F, N, Size, Sym, C);
266   return S;
267 }
268 
269 Symbol *SymbolTable::addImportData(StringRef N, ImportFile *F) {
270   Symbol *S;
271   bool WasInserted;
272   std::tie(S, WasInserted) = insert(N);
273   S->IsUsedInRegularObj = true;
274   if (WasInserted || isa<Undefined>(S->body()) || isa<Lazy>(S->body()))
275     replaceBody<DefinedImportData>(S, N, F);
276   else if (!isa<DefinedCOFF>(S->body()))
277     reportDuplicate(S, nullptr);
278   return S;
279 }
280 
281 Symbol *SymbolTable::addImportThunk(StringRef Name, DefinedImportData *ID,
282                                     uint16_t Machine) {
283   Symbol *S;
284   bool WasInserted;
285   std::tie(S, WasInserted) = insert(Name);
286   S->IsUsedInRegularObj = true;
287   if (WasInserted || isa<Undefined>(S->body()) || isa<Lazy>(S->body()))
288     replaceBody<DefinedImportThunk>(S, Name, ID, Machine);
289   else if (!isa<DefinedCOFF>(S->body()))
290     reportDuplicate(S, nullptr);
291   return S;
292 }
293 
294 std::vector<Chunk *> SymbolTable::getChunks() {
295   std::vector<Chunk *> Res;
296   for (ObjectFile *File : ObjectFiles) {
297     std::vector<Chunk *> &V = File->getChunks();
298     Res.insert(Res.end(), V.begin(), V.end());
299   }
300   return Res;
301 }
302 
303 Symbol *SymbolTable::find(StringRef Name) {
304   auto It = Symtab.find(CachedHashStringRef(Name));
305   if (It == Symtab.end())
306     return nullptr;
307   return It->second;
308 }
309 
310 Symbol *SymbolTable::findUnderscore(StringRef Name) {
311   if (Config->Machine == I386)
312     return find(("_" + Name).str());
313   return find(Name);
314 }
315 
316 StringRef SymbolTable::findByPrefix(StringRef Prefix) {
317   for (auto Pair : Symtab) {
318     StringRef Name = Pair.first.val();
319     if (Name.startswith(Prefix))
320       return Name;
321   }
322   return "";
323 }
324 
325 StringRef SymbolTable::findMangle(StringRef Name) {
326   if (Symbol *Sym = find(Name))
327     if (!isa<Undefined>(Sym->body()))
328       return Name;
329   if (Config->Machine != I386)
330     return findByPrefix(("?" + Name + "@@Y").str());
331   if (!Name.startswith("_"))
332     return "";
333   // Search for x86 C function.
334   StringRef S = findByPrefix((Name + "@").str());
335   if (!S.empty())
336     return S;
337   // Search for x86 C++ non-member function.
338   return findByPrefix(("?" + Name.substr(1) + "@@Y").str());
339 }
340 
341 void SymbolTable::mangleMaybe(SymbolBody *B) {
342   auto *U = dyn_cast<Undefined>(B);
343   if (!U || U->WeakAlias)
344     return;
345   StringRef Alias = findMangle(U->getName());
346   if (!Alias.empty())
347     U->WeakAlias = addUndefined(Alias);
348 }
349 
350 SymbolBody *SymbolTable::addUndefined(StringRef Name) {
351   return addUndefined(Name, nullptr, false)->body();
352 }
353 
354 void SymbolTable::addCombinedLTOObjects() {
355   if (BitcodeFiles.empty())
356     return;
357 
358   LTO.reset(new BitcodeCompiler);
359   for (BitcodeFile *F : BitcodeFiles)
360     LTO->add(*F);
361 
362   for (auto *File : LTO->compile()) {
363     auto *Obj = cast<ObjectFile>(File);
364     ObjectFiles.push_back(Obj);
365     Obj->parse();
366   }
367 }
368 } // namespace coff
369 } // namespace lld
370