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 // Symbol table is a bag of all known symbols. We put all symbols of
11 // all input files to the symbol table. The symbol table is basically
12 // a hash table with the logic to resolve symbol name conflicts using
13 // the symbol types.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "SymbolTable.h"
18 #include "Config.h"
19 #include "Error.h"
20 #include "Symbols.h"
21 #include "llvm/Bitcode/ReaderWriter.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/Linker/Linker.h"
24 #include "llvm/Support/StringSaver.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Target/TargetMachine.h"
27 
28 using namespace llvm;
29 using namespace llvm::object;
30 using namespace llvm::ELF;
31 
32 using namespace lld;
33 using namespace lld::elf;
34 
35 // All input object files must be for the same architecture
36 // (e.g. it does not make sense to link x86 object files with
37 // MIPS object files.) This function checks for that error.
38 template <class ELFT> static bool isCompatible(InputFile *FileP) {
39   auto *F = dyn_cast<ELFFileBase<ELFT>>(FileP);
40   if (!F)
41     return true;
42   if (F->getELFKind() == Config->EKind && F->getEMachine() == Config->EMachine)
43     return true;
44   StringRef A = F->getName();
45   StringRef B = Config->Emulation;
46   if (B.empty())
47     B = Config->FirstElf->getName();
48   error(A + " is incompatible with " + B);
49   return false;
50 }
51 
52 // Add symbols in File to the symbol table.
53 template <class ELFT>
54 void SymbolTable<ELFT>::addFile(std::unique_ptr<InputFile> File) {
55   InputFile *FileP = File.get();
56   if (!isCompatible<ELFT>(FileP))
57     return;
58 
59   // .a file
60   if (auto *F = dyn_cast<ArchiveFile>(FileP)) {
61     ArchiveFiles.emplace_back(cast<ArchiveFile>(File.release()));
62     F->parse();
63     for (Lazy &Sym : F->getLazySymbols())
64       addLazy(&Sym);
65     return;
66   }
67 
68   // .so file
69   if (auto *F = dyn_cast<SharedFile<ELFT>>(FileP)) {
70     // DSOs are uniquified not by filename but by soname.
71     F->parseSoName();
72     if (!SoNames.insert(F->getSoName()).second)
73       return;
74 
75     SharedFiles.emplace_back(cast<SharedFile<ELFT>>(File.release()));
76     F->parseRest();
77     for (SharedSymbol<ELFT> &B : F->getSharedSymbols())
78       resolve(&B);
79     return;
80   }
81 
82   // LLVM bitcode file.
83   if (auto *F = dyn_cast<BitcodeFile>(FileP)) {
84     BitcodeFiles.emplace_back(cast<BitcodeFile>(File.release()));
85     F->parse();
86     for (SymbolBody *B : F->getSymbols())
87       resolve(B);
88     return;
89   }
90 
91   // .o file
92   auto *F = cast<ObjectFile<ELFT>>(FileP);
93   ObjectFiles.emplace_back(cast<ObjectFile<ELFT>>(File.release()));
94   F->parse(ComdatGroups);
95   for (SymbolBody *B : F->getSymbols())
96     resolve(B);
97 }
98 
99 // Codegen the module M and returns the resulting InputFile.
100 template <class ELFT>
101 std::unique_ptr<InputFile> SymbolTable<ELFT>::codegen(Module &M) {
102   StringRef TripleStr = M.getTargetTriple();
103   Triple TheTriple(TripleStr);
104 
105   // FIXME: Should we have a default triple? The gold plugin uses
106   // sys::getDefaultTargetTriple(), but that is probably wrong given that this
107   // might be a cross linker.
108 
109   std::string ErrMsg;
110   const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
111   if (!TheTarget)
112     fatal("Target not found: " + ErrMsg);
113 
114   TargetOptions Options;
115   std::unique_ptr<TargetMachine> TM(
116       TheTarget->createTargetMachine(TripleStr, "", "", Options));
117 
118   raw_svector_ostream OS(OwningLTOData);
119   legacy::PassManager CodeGenPasses;
120   if (TM->addPassesToEmitFile(CodeGenPasses, OS,
121                               TargetMachine::CGFT_ObjectFile))
122     fatal("Failed to setup codegen");
123   CodeGenPasses.run(M);
124   LtoBuffer = MemoryBuffer::getMemBuffer(OwningLTOData, "", false);
125   return createObjectFile(*LtoBuffer);
126 }
127 
128 // Merge all the bitcode files we have seen, codegen the result and return
129 // the resulting ObjectFile.
130 template <class ELFT>
131 ObjectFile<ELFT> *SymbolTable<ELFT>::createCombinedLtoObject() {
132   LLVMContext Context;
133   Module Combined("ld-temp.o", Context);
134   Linker L(Combined);
135   for (const std::unique_ptr<BitcodeFile> &F : BitcodeFiles) {
136     std::unique_ptr<MemoryBuffer> Buffer =
137         MemoryBuffer::getMemBuffer(F->MB, false);
138     ErrorOr<std::unique_ptr<Module>> MOrErr =
139         getLazyBitcodeModule(std::move(Buffer), Context,
140                              /*ShouldLazyLoadMetadata*/ true);
141     fatal(MOrErr);
142     std::unique_ptr<Module> &M = *MOrErr;
143     L.linkInModule(std::move(M));
144   }
145   std::unique_ptr<InputFile> F = codegen(Combined);
146   ObjectFiles.emplace_back(cast<ObjectFile<ELFT>>(F.release()));
147   return &*ObjectFiles.back();
148 }
149 
150 template <class ELFT> void SymbolTable<ELFT>::addCombinedLtoObject() {
151   if (BitcodeFiles.empty())
152     return;
153   ObjectFile<ELFT> *Obj = createCombinedLtoObject();
154   // FIXME: We probably have to ignore comdats here.
155   Obj->parse(ComdatGroups);
156   for (SymbolBody *Body : Obj->getSymbols()) {
157     Symbol *Sym = insert(Body);
158     assert(isa<DefinedBitcode>(Sym->Body));
159     Sym->Body = Body;
160   }
161 }
162 
163 // Add an undefined symbol.
164 template <class ELFT>
165 SymbolBody *SymbolTable<ELFT>::addUndefined(StringRef Name) {
166   auto *Sym = new (Alloc) Undefined(Name, false, STV_DEFAULT, false);
167   resolve(Sym);
168   return Sym;
169 }
170 
171 // Add an undefined symbol. Unlike addUndefined, that symbol
172 // doesn't have to be resolved, thus "opt" (optional).
173 template <class ELFT>
174 SymbolBody *SymbolTable<ELFT>::addUndefinedOpt(StringRef Name) {
175   auto *Sym = new (Alloc) Undefined(Name, false, STV_HIDDEN, true);
176   resolve(Sym);
177   return Sym;
178 }
179 
180 template <class ELFT>
181 SymbolBody *SymbolTable<ELFT>::addAbsolute(StringRef Name, Elf_Sym &ESym) {
182   // Pass nullptr because absolute symbols have no corresponding input sections.
183   auto *Sym = new (Alloc) DefinedRegular<ELFT>(Name, ESym, nullptr);
184   resolve(Sym);
185   return Sym;
186 }
187 
188 template <class ELFT>
189 SymbolBody *SymbolTable<ELFT>::addSynthetic(StringRef Name,
190                                             OutputSectionBase<ELFT> &Section,
191                                             uintX_t Value) {
192   auto *Sym = new (Alloc) DefinedSynthetic<ELFT>(Name, Value, Section);
193   resolve(Sym);
194   return Sym;
195 }
196 
197 // Add Name as an "ignored" symbol. An ignored symbol is a regular
198 // linker-synthesized defined symbol, but it is not recorded to the output
199 // file's symbol table. Such symbols are useful for some linker-defined symbols.
200 template <class ELFT>
201 SymbolBody *SymbolTable<ELFT>::addIgnored(StringRef Name) {
202   return addAbsolute(Name, ElfSym<ELFT>::Ignored);
203 }
204 
205 // Rename SYM as __wrap_SYM. The original symbol is preserved as __real_SYM.
206 // Used to implement --wrap.
207 template <class ELFT> void SymbolTable<ELFT>::wrap(StringRef Name) {
208   if (Symtab.count(Name) == 0)
209     return;
210   StringSaver Saver(Alloc);
211   Symbol *Sym = addUndefined(Name)->getSymbol();
212   Symbol *Real = addUndefined(Saver.save("__real_" + Name))->getSymbol();
213   Symbol *Wrap = addUndefined(Saver.save("__wrap_" + Name))->getSymbol();
214   Real->Body = Sym->Body;
215   Sym->Body = Wrap->Body;
216 }
217 
218 // Returns a file from which symbol B was created.
219 // If B does not belong to any file, returns a nullptr.
220 template <class ELFT> InputFile *SymbolTable<ELFT>::findFile(SymbolBody *B) {
221   for (const std::unique_ptr<ObjectFile<ELFT>> &F : ObjectFiles) {
222     ArrayRef<SymbolBody *> Syms = F->getSymbols();
223     if (std::find(Syms.begin(), Syms.end(), B) != Syms.end())
224       return F.get();
225   }
226   for (const std::unique_ptr<BitcodeFile> &F : BitcodeFiles) {
227     ArrayRef<SymbolBody *> Syms = F->getSymbols();
228     if (std::find(Syms.begin(), Syms.end(), B) != Syms.end())
229       return F.get();
230   }
231   return nullptr;
232 }
233 
234 // Returns "(internal)", "foo.a(bar.o)" or "baz.o".
235 static std::string getFilename(InputFile *F) {
236   if (!F)
237     return "(internal)";
238   if (!F->ArchiveName.empty())
239     return (F->ArchiveName + "(" + F->getName() + ")").str();
240   return F->getName();
241 }
242 
243 // Construct a string in the form of "Sym in File1 and File2".
244 // Used to construct an error message.
245 template <class ELFT>
246 std::string SymbolTable<ELFT>::conflictMsg(SymbolBody *Old, SymbolBody *New) {
247   InputFile *F1 = findFile(Old);
248   InputFile *F2 = findFile(New);
249   StringRef Sym = Old->getName();
250   return demangle(Sym) + " in " + getFilename(F1) + " and " + getFilename(F2);
251 }
252 
253 // This function resolves conflicts if there's an existing symbol with
254 // the same name. Decisions are made based on symbol type.
255 template <class ELFT> void SymbolTable<ELFT>::resolve(SymbolBody *New) {
256   Symbol *Sym = insert(New);
257   if (Sym->Body == New)
258     return;
259 
260   SymbolBody *Existing = Sym->Body;
261 
262   if (Lazy *L = dyn_cast<Lazy>(Existing)) {
263     if (auto *Undef = dyn_cast<Undefined>(New)) {
264       addMemberFile(Undef, L);
265       return;
266     }
267     // Found a definition for something also in an archive.
268     // Ignore the archive definition.
269     Sym->Body = New;
270     return;
271   }
272 
273   if (New->IsTls != Existing->IsTls) {
274     error("TLS attribute mismatch for symbol: " + conflictMsg(Existing, New));
275     return;
276   }
277 
278   // compare() returns -1, 0, or 1 if the lhs symbol is less preferable,
279   // equivalent (conflicting), or more preferable, respectively.
280   int Comp = Existing->compare<ELFT>(New);
281   if (Comp == 0) {
282     std::string S = "duplicate symbol: " + conflictMsg(Existing, New);
283     if (Config->AllowMultipleDefinition)
284       warning(S);
285     else
286       error(S);
287     return;
288   }
289   if (Comp < 0)
290     Sym->Body = New;
291 }
292 
293 // Find an existing symbol or create and insert a new one.
294 template <class ELFT> Symbol *SymbolTable<ELFT>::insert(SymbolBody *New) {
295   StringRef Name = New->getName();
296   Symbol *&Sym = Symtab[Name];
297   if (!Sym)
298     Sym = new (Alloc) Symbol{New};
299   New->setBackref(Sym);
300   return Sym;
301 }
302 
303 template <class ELFT> SymbolBody *SymbolTable<ELFT>::find(StringRef Name) {
304   auto It = Symtab.find(Name);
305   if (It == Symtab.end())
306     return nullptr;
307   return It->second->Body;
308 }
309 
310 template <class ELFT> void SymbolTable<ELFT>::addLazy(Lazy *L) {
311   Symbol *Sym = insert(L);
312   if (Sym->Body == L)
313     return;
314   if (auto *Undef = dyn_cast<Undefined>(Sym->Body)) {
315     Sym->Body = L;
316     addMemberFile(Undef, L);
317   }
318 }
319 
320 template <class ELFT>
321 void SymbolTable<ELFT>::addMemberFile(Undefined *Undef, Lazy *L) {
322   // Weak undefined symbols should not fetch members from archives.
323   // If we were to keep old symbol we would not know that an archive member was
324   // available if a strong undefined symbol shows up afterwards in the link.
325   // If a strong undefined symbol never shows up, this lazy symbol will
326   // get to the end of the link and must be treated as the weak undefined one.
327   // We set UsedInRegularObj in a similar way to what is done with shared
328   // symbols and copy information to reduce how many special cases are needed.
329   if (Undef->isWeak()) {
330     L->setUsedInRegularObj();
331     L->setWeak();
332 
333     // FIXME: Do we need to copy more?
334     L->IsTls = Undef->IsTls;
335     return;
336   }
337 
338   // Fetch a member file that has the definition for L.
339   // getMember returns nullptr if the member was already read from the library.
340   if (std::unique_ptr<InputFile> File = L->getMember())
341     addFile(std::move(File));
342 }
343 
344 // This function takes care of the case in which shared libraries depend on
345 // the user program (not the other way, which is usual). Shared libraries
346 // may have undefined symbols, expecting that the user program provides
347 // the definitions for them. An example is BSD's __progname symbol.
348 // We need to put such symbols to the main program's .dynsym so that
349 // shared libraries can find them.
350 // Except this, we ignore undefined symbols in DSOs.
351 template <class ELFT> void SymbolTable<ELFT>::scanShlibUndefined() {
352   for (std::unique_ptr<SharedFile<ELFT>> &File : SharedFiles)
353     for (StringRef U : File->getUndefinedSymbols())
354       if (SymbolBody *Sym = find(U))
355         if (Sym->isDefined())
356           Sym->MustBeInDynSym = true;
357 }
358 
359 template class elf::SymbolTable<ELF32LE>;
360 template class elf::SymbolTable<ELF32BE>;
361 template class elf::SymbolTable<ELF64LE>;
362 template class elf::SymbolTable<ELF64BE>;
363