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