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