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