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