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(ComdatGroups);
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   Reloc::Model R = Config->Shared ? Reloc::PIC_ : Reloc::Static;
116   std::unique_ptr<TargetMachine> TM(
117       TheTarget->createTargetMachine(TripleStr, "", "", Options, R));
118 
119   raw_svector_ostream OS(OwningLTOData);
120   legacy::PassManager CodeGenPasses;
121   if (TM->addPassesToEmitFile(CodeGenPasses, OS,
122                               TargetMachine::CGFT_ObjectFile))
123     fatal("Failed to setup codegen");
124   CodeGenPasses.run(M);
125   LtoBuffer = MemoryBuffer::getMemBuffer(OwningLTOData, "", false);
126   return createObjectFile(*LtoBuffer);
127 }
128 
129 // Merge all the bitcode files we have seen, codegen the result and return
130 // the resulting ObjectFile.
131 template <class ELFT>
132 ObjectFile<ELFT> *SymbolTable<ELFT>::createCombinedLtoObject() {
133   LLVMContext Context;
134   Module Combined("ld-temp.o", Context);
135   Linker L(Combined);
136   for (const std::unique_ptr<BitcodeFile> &F : BitcodeFiles) {
137     std::unique_ptr<MemoryBuffer> Buffer =
138         MemoryBuffer::getMemBuffer(F->MB, false);
139     ErrorOr<std::unique_ptr<Module>> MOrErr =
140         getLazyBitcodeModule(std::move(Buffer), Context,
141                              /*ShouldLazyLoadMetadata*/ true);
142     fatal(MOrErr);
143     std::unique_ptr<Module> &M = *MOrErr;
144     L.linkInModule(std::move(M));
145   }
146   std::unique_ptr<InputFile> F = codegen(Combined);
147   ObjectFiles.emplace_back(cast<ObjectFile<ELFT>>(F.release()));
148   return &*ObjectFiles.back();
149 }
150 
151 template <class ELFT> void SymbolTable<ELFT>::addCombinedLtoObject() {
152   if (BitcodeFiles.empty())
153     return;
154   ObjectFile<ELFT> *Obj = createCombinedLtoObject();
155   llvm::DenseSet<StringRef> DummyGroups;
156   Obj->parse(DummyGroups);
157   for (SymbolBody *Body : Obj->getSymbols()) {
158     Symbol *Sym = insert(Body);
159     if (!Sym->Body->isUndefined() && Body->isUndefined())
160       continue;
161     Sym->Body = Body;
162   }
163 }
164 
165 // Add an undefined symbol.
166 template <class ELFT>
167 SymbolBody *SymbolTable<ELFT>::addUndefined(StringRef Name) {
168   auto *Sym = new (Alloc) Undefined(Name, false, STV_DEFAULT, false);
169   resolve(Sym);
170   return Sym;
171 }
172 
173 // Add an undefined symbol. Unlike addUndefined, that symbol
174 // doesn't have to be resolved, thus "opt" (optional).
175 template <class ELFT>
176 SymbolBody *SymbolTable<ELFT>::addUndefinedOpt(StringRef Name) {
177   auto *Sym = new (Alloc) Undefined(Name, false, STV_HIDDEN, true);
178   resolve(Sym);
179   return Sym;
180 }
181 
182 template <class ELFT>
183 SymbolBody *SymbolTable<ELFT>::addAbsolute(StringRef Name, Elf_Sym &ESym) {
184   // Pass nullptr because absolute symbols have no corresponding input sections.
185   auto *Sym = new (Alloc) DefinedRegular<ELFT>(Name, ESym, nullptr);
186   resolve(Sym);
187   return Sym;
188 }
189 
190 template <class ELFT>
191 SymbolBody *SymbolTable<ELFT>::addSynthetic(StringRef Name,
192                                             OutputSectionBase<ELFT> &Sec,
193                                             uintX_t Val, uint8_t Visibility) {
194   auto *Sym = new (Alloc) DefinedSynthetic<ELFT>(Name, Val, Sec, Visibility);
195   resolve(Sym);
196   return Sym;
197 }
198 
199 // Add Name as an "ignored" symbol. An ignored symbol is a regular
200 // linker-synthesized defined symbol, but it is not recorded to the output
201 // file's symbol table. Such symbols are useful for some linker-defined symbols.
202 template <class ELFT>
203 SymbolBody *SymbolTable<ELFT>::addIgnored(StringRef Name) {
204   return addAbsolute(Name, ElfSym<ELFT>::Ignored);
205 }
206 
207 // Rename SYM as __wrap_SYM. The original symbol is preserved as __real_SYM.
208 // Used to implement --wrap.
209 template <class ELFT> void SymbolTable<ELFT>::wrap(StringRef Name) {
210   if (Symtab.count(Name) == 0)
211     return;
212   StringSaver Saver(Alloc);
213   Symbol *Sym = addUndefined(Name)->getSymbol();
214   Symbol *Real = addUndefined(Saver.save("__real_" + Name))->getSymbol();
215   Symbol *Wrap = addUndefined(Saver.save("__wrap_" + Name))->getSymbol();
216   Real->Body = Sym->Body;
217   Sym->Body = Wrap->Body;
218 }
219 
220 // Returns a file from which symbol B was created.
221 // If B does not belong to any file, returns a nullptr.
222 template <class ELFT> InputFile *SymbolTable<ELFT>::findFile(SymbolBody *B) {
223   for (const std::unique_ptr<ObjectFile<ELFT>> &F : ObjectFiles) {
224     ArrayRef<SymbolBody *> Syms = F->getSymbols();
225     if (std::find(Syms.begin(), Syms.end(), B) != Syms.end())
226       return F.get();
227   }
228   for (const std::unique_ptr<BitcodeFile> &F : BitcodeFiles) {
229     ArrayRef<SymbolBody *> Syms = F->getSymbols();
230     if (std::find(Syms.begin(), Syms.end(), B) != Syms.end())
231       return F.get();
232   }
233   return nullptr;
234 }
235 
236 // Returns "(internal)", "foo.a(bar.o)" or "baz.o".
237 static std::string getFilename(InputFile *F) {
238   if (!F)
239     return "(internal)";
240   if (!F->ArchiveName.empty())
241     return (F->ArchiveName + "(" + F->getName() + ")").str();
242   return F->getName();
243 }
244 
245 // Construct a string in the form of "Sym in File1 and File2".
246 // Used to construct an error message.
247 template <class ELFT>
248 std::string SymbolTable<ELFT>::conflictMsg(SymbolBody *Old, SymbolBody *New) {
249   InputFile *F1 = findFile(Old);
250   InputFile *F2 = findFile(New);
251   StringRef Sym = Old->getName();
252   return demangle(Sym) + " in " + getFilename(F1) + " and " + getFilename(F2);
253 }
254 
255 // This function resolves conflicts if there's an existing symbol with
256 // the same name. Decisions are made based on symbol type.
257 template <class ELFT> void SymbolTable<ELFT>::resolve(SymbolBody *New) {
258   Symbol *Sym = insert(New);
259   if (Sym->Body == New)
260     return;
261 
262   SymbolBody *Existing = Sym->Body;
263 
264   if (Lazy *L = dyn_cast<Lazy>(Existing)) {
265     if (auto *Undef = dyn_cast<Undefined>(New)) {
266       addMemberFile(Undef, L);
267       return;
268     }
269     // Found a definition for something also in an archive.
270     // Ignore the archive definition.
271     Sym->Body = New;
272     return;
273   }
274 
275   if (New->IsTls != Existing->IsTls) {
276     error("TLS attribute mismatch for symbol: " + conflictMsg(Existing, New));
277     return;
278   }
279 
280   // compare() returns -1, 0, or 1 if the lhs symbol is less preferable,
281   // equivalent (conflicting), or more preferable, respectively.
282   int Comp = Existing->compare<ELFT>(New);
283   if (Comp == 0) {
284     std::string S = "duplicate symbol: " + conflictMsg(Existing, New);
285     if (Config->AllowMultipleDefinition)
286       warning(S);
287     else
288       error(S);
289     return;
290   }
291   if (Comp < 0)
292     Sym->Body = New;
293 }
294 
295 // Find an existing symbol or create and insert a new one.
296 template <class ELFT> Symbol *SymbolTable<ELFT>::insert(SymbolBody *New) {
297   StringRef Name = New->getName();
298   Symbol *&Sym = Symtab[Name];
299   if (!Sym)
300     Sym = new (Alloc) Symbol{New};
301   New->setBackref(Sym);
302   return Sym;
303 }
304 
305 template <class ELFT> SymbolBody *SymbolTable<ELFT>::find(StringRef Name) {
306   auto It = Symtab.find(Name);
307   if (It == Symtab.end())
308     return nullptr;
309   return It->second->Body;
310 }
311 
312 template <class ELFT> void SymbolTable<ELFT>::addLazy(Lazy *L) {
313   Symbol *Sym = insert(L);
314   if (Sym->Body == L)
315     return;
316   if (auto *Undef = dyn_cast<Undefined>(Sym->Body)) {
317     Sym->Body = L;
318     addMemberFile(Undef, L);
319   }
320 }
321 
322 template <class ELFT>
323 void SymbolTable<ELFT>::addMemberFile(Undefined *Undef, Lazy *L) {
324   // Weak undefined symbols should not fetch members from archives.
325   // If we were to keep old symbol we would not know that an archive member was
326   // available if a strong undefined symbol shows up afterwards in the link.
327   // If a strong undefined symbol never shows up, this lazy symbol will
328   // get to the end of the link and must be treated as the weak undefined one.
329   // We set UsedInRegularObj in a similar way to what is done with shared
330   // symbols and copy information to reduce how many special cases are needed.
331   if (Undef->isWeak()) {
332     L->setUsedInRegularObj();
333     L->setWeak();
334 
335     // FIXME: Do we need to copy more?
336     L->IsTls = Undef->IsTls;
337     return;
338   }
339 
340   // Fetch a member file that has the definition for L.
341   // getMember returns nullptr if the member was already read from the library.
342   if (std::unique_ptr<InputFile> File = L->getMember())
343     addFile(std::move(File));
344 }
345 
346 // This function takes care of the case in which shared libraries depend on
347 // the user program (not the other way, which is usual). Shared libraries
348 // may have undefined symbols, expecting that the user program provides
349 // the definitions for them. An example is BSD's __progname symbol.
350 // We need to put such symbols to the main program's .dynsym so that
351 // shared libraries can find them.
352 // Except this, we ignore undefined symbols in DSOs.
353 template <class ELFT> void SymbolTable<ELFT>::scanShlibUndefined() {
354   for (std::unique_ptr<SharedFile<ELFT>> &File : SharedFiles)
355     for (StringRef U : File->getUndefinedSymbols())
356       if (SymbolBody *Sym = find(U))
357         if (Sym->isDefined())
358           Sym->MustBeInDynSym = true;
359 }
360 
361 template class elf::SymbolTable<ELF32LE>;
362 template class elf::SymbolTable<ELF32BE>;
363 template class elf::SymbolTable<ELF64LE>;
364 template class elf::SymbolTable<ELF64BE>;
365