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