1 //===- SymbolTable.cpp ----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Symbol table is a bag of all known symbols. We put all symbols of
10 // all input files to the symbol table. The symbol table is basically
11 // a hash table with the logic to resolve symbol name conflicts using
12 // the symbol types.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "SymbolTable.h"
17 #include "Config.h"
18 #include "InputFiles.h"
19 #include "Symbols.h"
20 #include "lld/Common/ErrorHandler.h"
21 #include "lld/Common/Memory.h"
22 #include "lld/Common/Strings.h"
23 #include "llvm/ADT/STLExtras.h"
24 
25 using namespace llvm;
26 using namespace llvm::object;
27 using namespace llvm::ELF;
28 using namespace lld;
29 using namespace lld::elf;
30 
31 std::unique_ptr<SymbolTable> elf::symtab;
32 
33 void SymbolTable::wrap(Symbol *sym, Symbol *real, Symbol *wrap) {
34   // Redirect __real_foo to the original foo and foo to the original __wrap_foo.
35   int &idx1 = symMap[CachedHashStringRef(sym->getName())];
36   int &idx2 = symMap[CachedHashStringRef(real->getName())];
37   int &idx3 = symMap[CachedHashStringRef(wrap->getName())];
38 
39   idx2 = idx1;
40   idx1 = idx3;
41 
42   if (!real->isUsedInRegularObj && sym->isUndefined())
43     sym->isUsedInRegularObj = false;
44 
45   // Now renaming is complete, and no one refers to real. We drop real from
46   // .symtab and .dynsym. If real is undefined, it is important that we don't
47   // leave it in .dynsym, because otherwise it might lead to an undefined symbol
48   // error in a subsequent link. If real is defined, we could emit real as an
49   // alias for sym, but that could degrade the user experience of some tools
50   // that can print out only one symbol for each location: sym is a preferred
51   // name than real, but they might print out real instead.
52   memcpy(real, sym, sizeof(SymbolUnion));
53   real->isUsedInRegularObj = false;
54 }
55 
56 // Find an existing symbol or create a new one.
57 Symbol *SymbolTable::insert(StringRef name) {
58   // <name>@@<version> means the symbol is the default version. In that
59   // case <name>@@<version> will be used to resolve references to <name>.
60   //
61   // Since this is a hot path, the following string search code is
62   // optimized for speed. StringRef::find(char) is much faster than
63   // StringRef::find(StringRef).
64   StringRef stem = name;
65   size_t pos = name.find('@');
66   if (pos != StringRef::npos && pos + 1 < name.size() && name[pos + 1] == '@')
67     stem = name.take_front(pos);
68 
69   auto p = symMap.insert({CachedHashStringRef(stem), (int)symVector.size()});
70   if (!p.second) {
71     Symbol *sym = symVector[p.first->second];
72     if (stem.size() != name.size()) {
73       sym->setName(name);
74       sym->hasVersionSuffix = true;
75     }
76     return sym;
77   }
78 
79   Symbol *sym = reinterpret_cast<Symbol *>(make<SymbolUnion>());
80   symVector.push_back(sym);
81 
82   // *sym was not initialized by a constructor. Fields that may get referenced
83   // when it is a placeholder must be initialized here.
84   sym->setName(name);
85   sym->symbolKind = Symbol::PlaceholderKind;
86   sym->partition = 1;
87   sym->visibility = STV_DEFAULT;
88   sym->isUsedInRegularObj = false;
89   sym->exportDynamic = false;
90   sym->inDynamicList = false;
91   sym->referenced = false;
92   sym->traced = false;
93   sym->scriptDefined = false;
94   sym->versionId = VER_NDX_GLOBAL;
95   if (pos != StringRef::npos)
96     sym->hasVersionSuffix = true;
97   return sym;
98 }
99 
100 Symbol *SymbolTable::addSymbol(const Symbol &newSym) {
101   Symbol *sym = insert(newSym.getName());
102   sym->resolve(newSym);
103   return sym;
104 }
105 
106 // This variant of addSymbol is used by BinaryFile::parse to check duplicate
107 // symbol errors.
108 Symbol *SymbolTable::addAndCheckDuplicate(const Defined &newSym) {
109   Symbol *sym = insert(newSym.getName());
110   if (sym->isDefined())
111     sym->checkDuplicate(newSym);
112   sym->resolve(newSym);
113   sym->isUsedInRegularObj = true;
114   return sym;
115 }
116 
117 Symbol *SymbolTable::find(StringRef name) {
118   auto it = symMap.find(CachedHashStringRef(name));
119   if (it == symMap.end())
120     return nullptr;
121   return symVector[it->second];
122 }
123 
124 // A version script/dynamic list is only meaningful for a Defined symbol.
125 // A CommonSymbol will be converted to a Defined in replaceCommonSymbols().
126 // A lazy symbol may be made Defined if an LTO libcall extracts it.
127 static bool canBeVersioned(const Symbol &sym) {
128   return sym.isDefined() || sym.isCommon() || sym.isLazy();
129 }
130 
131 // Initialize demangledSyms with a map from demangled symbols to symbol
132 // objects. Used to handle "extern C++" directive in version scripts.
133 //
134 // The map will contain all demangled symbols. That can be very large,
135 // and in LLD we generally want to avoid do anything for each symbol.
136 // Then, why are we doing this? Here's why.
137 //
138 // Users can use "extern C++ {}" directive to match against demangled
139 // C++ symbols. For example, you can write a pattern such as
140 // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this
141 // other than trying to match a pattern against all demangled symbols.
142 // So, if "extern C++" feature is used, we need to demangle all known
143 // symbols.
144 StringMap<SmallVector<Symbol *, 0>> &SymbolTable::getDemangledSyms() {
145   if (!demangledSyms) {
146     demangledSyms.emplace();
147     std::string demangled;
148     for (Symbol *sym : symVector)
149       if (canBeVersioned(*sym)) {
150         StringRef name = sym->getName();
151         size_t pos = name.find('@');
152         if (pos == std::string::npos)
153           demangled = demangle(name, config->demangle);
154         else if (pos + 1 == name.size() || name[pos + 1] == '@')
155           demangled = demangle(name.substr(0, pos), config->demangle);
156         else
157           demangled = (demangle(name.substr(0, pos), config->demangle) +
158                        name.substr(pos))
159                           .str();
160         (*demangledSyms)[demangled].push_back(sym);
161       }
162   }
163   return *demangledSyms;
164 }
165 
166 SmallVector<Symbol *, 0> SymbolTable::findByVersion(SymbolVersion ver) {
167   if (ver.isExternCpp)
168     return getDemangledSyms().lookup(ver.name);
169   if (Symbol *sym = find(ver.name))
170     if (canBeVersioned(*sym))
171       return {sym};
172   return {};
173 }
174 
175 SmallVector<Symbol *, 0> SymbolTable::findAllByVersion(SymbolVersion ver,
176                                                        bool includeNonDefault) {
177   SmallVector<Symbol *, 0> res;
178   SingleStringMatcher m(ver.name);
179   auto check = [&](StringRef name) {
180     size_t pos = name.find('@');
181     if (!includeNonDefault)
182       return pos == StringRef::npos;
183     return !(pos + 1 < name.size() && name[pos + 1] == '@');
184   };
185 
186   if (ver.isExternCpp) {
187     for (auto &p : getDemangledSyms())
188       if (m.match(p.first()))
189         for (Symbol *sym : p.second)
190           if (check(sym->getName()))
191             res.push_back(sym);
192     return res;
193   }
194 
195   for (Symbol *sym : symVector)
196     if (canBeVersioned(*sym) && check(sym->getName()) &&
197         m.match(sym->getName()))
198       res.push_back(sym);
199   return res;
200 }
201 
202 void SymbolTable::handleDynamicList() {
203   SmallVector<Symbol *, 0> syms;
204   for (SymbolVersion &ver : config->dynamicList) {
205     if (ver.hasWildcard)
206       syms = findAllByVersion(ver, /*includeNonDefault=*/true);
207     else
208       syms = findByVersion(ver);
209 
210     for (Symbol *sym : syms)
211       sym->inDynamicList = true;
212   }
213 }
214 
215 // Set symbol versions to symbols. This function handles patterns containing no
216 // wildcard characters. Return false if no symbol definition matches ver.
217 bool SymbolTable::assignExactVersion(SymbolVersion ver, uint16_t versionId,
218                                      StringRef versionName,
219                                      bool includeNonDefault) {
220   // Get a list of symbols which we need to assign the version to.
221   SmallVector<Symbol *, 0> syms = findByVersion(ver);
222 
223   auto getName = [](uint16_t ver) -> std::string {
224     if (ver == VER_NDX_LOCAL)
225       return "VER_NDX_LOCAL";
226     if (ver == VER_NDX_GLOBAL)
227       return "VER_NDX_GLOBAL";
228     return ("version '" + config->versionDefinitions[ver].name + "'").str();
229   };
230 
231   // Assign the version.
232   for (Symbol *sym : syms) {
233     // For a non-local versionId, skip symbols containing version info because
234     // symbol versions specified by symbol names take precedence over version
235     // scripts. See parseSymbolVersion().
236     if (!includeNonDefault && versionId != VER_NDX_LOCAL &&
237         sym->getName().contains('@'))
238       continue;
239 
240     // If the version has not been assigned, verdefIndex is -1. Use an arbitrary
241     // number (0) to indicate the version has been assigned.
242     if (sym->verdefIndex == uint16_t(-1)) {
243       sym->verdefIndex = 0;
244       sym->versionId = versionId;
245     }
246     if (sym->versionId == versionId)
247       continue;
248 
249     warn("attempt to reassign symbol '" + ver.name + "' of " +
250          getName(sym->versionId) + " to " + getName(versionId));
251   }
252   return !syms.empty();
253 }
254 
255 void SymbolTable::assignWildcardVersion(SymbolVersion ver, uint16_t versionId,
256                                         bool includeNonDefault) {
257   // Exact matching takes precedence over fuzzy matching,
258   // so we set a version to a symbol only if no version has been assigned
259   // to the symbol. This behavior is compatible with GNU.
260   for (Symbol *sym : findAllByVersion(ver, includeNonDefault))
261     if (sym->verdefIndex == uint16_t(-1)) {
262       sym->verdefIndex = 0;
263       sym->versionId = versionId;
264     }
265 }
266 
267 // This function processes version scripts by updating the versionId
268 // member of symbols.
269 // If there's only one anonymous version definition in a version
270 // script file, the script does not actually define any symbol version,
271 // but just specifies symbols visibilities.
272 void SymbolTable::scanVersionScript() {
273   SmallString<128> buf;
274   // First, we assign versions to exact matching symbols,
275   // i.e. version definitions not containing any glob meta-characters.
276   for (VersionDefinition &v : config->versionDefinitions) {
277     auto assignExact = [&](SymbolVersion pat, uint16_t id, StringRef ver) {
278       bool found =
279           assignExactVersion(pat, id, ver, /*includeNonDefault=*/false);
280       buf.clear();
281       found |= assignExactVersion({(pat.name + "@" + v.name).toStringRef(buf),
282                                    pat.isExternCpp, /*hasWildCard=*/false},
283                                   id, ver, /*includeNonDefault=*/true);
284       if (!found && !config->undefinedVersion)
285         errorOrWarn("version script assignment of '" + ver + "' to symbol '" +
286                     pat.name + "' failed: symbol not defined");
287     };
288     for (SymbolVersion &pat : v.nonLocalPatterns)
289       if (!pat.hasWildcard)
290         assignExact(pat, v.id, v.name);
291     for (SymbolVersion pat : v.localPatterns)
292       if (!pat.hasWildcard)
293         assignExact(pat, VER_NDX_LOCAL, "local");
294   }
295 
296   // Next, assign versions to wildcards that are not "*". Note that because the
297   // last match takes precedence over previous matches, we iterate over the
298   // definitions in the reverse order.
299   auto assignWildcard = [&](SymbolVersion pat, uint16_t id, StringRef ver) {
300     assignWildcardVersion(pat, id, /*includeNonDefault=*/false);
301     buf.clear();
302     assignWildcardVersion({(pat.name + "@" + ver).toStringRef(buf),
303                            pat.isExternCpp, /*hasWildCard=*/true},
304                           id,
305                           /*includeNonDefault=*/true);
306   };
307   for (VersionDefinition &v : llvm::reverse(config->versionDefinitions)) {
308     for (SymbolVersion &pat : v.nonLocalPatterns)
309       if (pat.hasWildcard && pat.name != "*")
310         assignWildcard(pat, v.id, v.name);
311     for (SymbolVersion &pat : v.localPatterns)
312       if (pat.hasWildcard && pat.name != "*")
313         assignWildcard(pat, VER_NDX_LOCAL, v.name);
314   }
315 
316   // Then, assign versions to "*". In GNU linkers they have lower priority than
317   // other wildcards.
318   for (VersionDefinition &v : config->versionDefinitions) {
319     for (SymbolVersion &pat : v.nonLocalPatterns)
320       if (pat.hasWildcard && pat.name == "*")
321         assignWildcard(pat, v.id, v.name);
322     for (SymbolVersion &pat : v.localPatterns)
323       if (pat.hasWildcard && pat.name == "*")
324         assignWildcard(pat, VER_NDX_LOCAL, v.name);
325   }
326 
327   // Symbol themselves might know their versions because symbols
328   // can contain versions in the form of <name>@<version>.
329   // Let them parse and update their names to exclude version suffix.
330   for (Symbol *sym : symVector)
331     if (sym->hasVersionSuffix)
332       sym->parseSymbolVersion();
333 
334   // isPreemptible is false at this point. To correctly compute the binding of a
335   // Defined (which is used by includeInDynsym()), we need to know if it is
336   // VER_NDX_LOCAL or not. Compute symbol versions before handling
337   // --dynamic-list.
338   handleDynamicList();
339 }
340