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 = demangleItanium(name);
147         else if (pos + 1 == name.size() || name[pos + 1] == '@')
148           demangled = demangleItanium(name.substr(0, pos));
149         else
150           demangled =
151               (demangleItanium(name.substr(0, pos)) + name.substr(pos)).str();
152         (*demangledSyms)[demangled].push_back(sym);
153       }
154   }
155   return *demangledSyms;
156 }
157 
158 SmallVector<Symbol *, 0> SymbolTable::findByVersion(SymbolVersion ver) {
159   if (ver.isExternCpp)
160     return getDemangledSyms().lookup(ver.name);
161   if (Symbol *sym = find(ver.name))
162     if (canBeVersioned(*sym))
163       return {sym};
164   return {};
165 }
166 
167 SmallVector<Symbol *, 0> SymbolTable::findAllByVersion(SymbolVersion ver,
168                                                        bool includeNonDefault) {
169   SmallVector<Symbol *, 0> res;
170   SingleStringMatcher m(ver.name);
171   auto check = [&](StringRef name) {
172     size_t pos = name.find('@');
173     if (!includeNonDefault)
174       return pos == StringRef::npos;
175     return !(pos + 1 < name.size() && name[pos + 1] == '@');
176   };
177 
178   if (ver.isExternCpp) {
179     for (auto &p : getDemangledSyms())
180       if (m.match(p.first()))
181         for (Symbol *sym : p.second)
182           if (check(sym->getName()))
183             res.push_back(sym);
184     return res;
185   }
186 
187   for (Symbol *sym : symVector)
188     if (canBeVersioned(*sym) && check(sym->getName()) &&
189         m.match(sym->getName()))
190       res.push_back(sym);
191   return res;
192 }
193 
194 void SymbolTable::handleDynamicList() {
195   SmallVector<Symbol *, 0> syms;
196   for (SymbolVersion &ver : config->dynamicList) {
197     if (ver.hasWildcard)
198       syms = findAllByVersion(ver, /*includeNonDefault=*/true);
199     else
200       syms = findByVersion(ver);
201 
202     for (Symbol *sym : syms)
203       sym->inDynamicList = true;
204   }
205 }
206 
207 // Set symbol versions to symbols. This function handles patterns containing no
208 // wildcard characters. Return false if no symbol definition matches ver.
209 bool SymbolTable::assignExactVersion(SymbolVersion ver, uint16_t versionId,
210                                      StringRef versionName,
211                                      bool includeNonDefault) {
212   // Get a list of symbols which we need to assign the version to.
213   SmallVector<Symbol *, 0> syms = findByVersion(ver);
214 
215   auto getName = [](uint16_t ver) -> std::string {
216     if (ver == VER_NDX_LOCAL)
217       return "VER_NDX_LOCAL";
218     if (ver == VER_NDX_GLOBAL)
219       return "VER_NDX_GLOBAL";
220     return ("version '" + config->versionDefinitions[ver].name + "'").str();
221   };
222 
223   // Assign the version.
224   for (Symbol *sym : syms) {
225     // For a non-local versionId, skip symbols containing version info because
226     // symbol versions specified by symbol names take precedence over version
227     // scripts. See parseSymbolVersion().
228     if (!includeNonDefault && versionId != VER_NDX_LOCAL &&
229         sym->getName().contains('@'))
230       continue;
231 
232     // If the version has not been assigned, verdefIndex is -1. Use an arbitrary
233     // number (0) to indicate the version has been assigned.
234     if (sym->verdefIndex == uint16_t(-1)) {
235       sym->verdefIndex = 0;
236       sym->versionId = versionId;
237     }
238     if (sym->versionId == versionId)
239       continue;
240 
241     warn("attempt to reassign symbol '" + ver.name + "' of " +
242          getName(sym->versionId) + " to " + getName(versionId));
243   }
244   return !syms.empty();
245 }
246 
247 void SymbolTable::assignWildcardVersion(SymbolVersion ver, uint16_t versionId,
248                                         bool includeNonDefault) {
249   // Exact matching takes precedence over fuzzy matching,
250   // so we set a version to a symbol only if no version has been assigned
251   // to the symbol. This behavior is compatible with GNU.
252   for (Symbol *sym : findAllByVersion(ver, includeNonDefault))
253     if (sym->verdefIndex == uint16_t(-1)) {
254       sym->verdefIndex = 0;
255       sym->versionId = versionId;
256     }
257 }
258 
259 // This function processes version scripts by updating the versionId
260 // member of symbols.
261 // If there's only one anonymous version definition in a version
262 // script file, the script does not actually define any symbol version,
263 // but just specifies symbols visibilities.
264 void SymbolTable::scanVersionScript() {
265   SmallString<128> buf;
266   // First, we assign versions to exact matching symbols,
267   // i.e. version definitions not containing any glob meta-characters.
268   for (VersionDefinition &v : config->versionDefinitions) {
269     auto assignExact = [&](SymbolVersion pat, uint16_t id, StringRef ver) {
270       bool found =
271           assignExactVersion(pat, id, ver, /*includeNonDefault=*/false);
272       buf.clear();
273       found |= assignExactVersion({(pat.name + "@" + v.name).toStringRef(buf),
274                                    pat.isExternCpp, /*hasWildCard=*/false},
275                                   id, ver, /*includeNonDefault=*/true);
276       if (!found && !config->undefinedVersion)
277         errorOrWarn("version script assignment of '" + ver + "' to symbol '" +
278                     pat.name + "' failed: symbol not defined");
279     };
280     for (SymbolVersion &pat : v.nonLocalPatterns)
281       if (!pat.hasWildcard)
282         assignExact(pat, v.id, v.name);
283     for (SymbolVersion pat : v.localPatterns)
284       if (!pat.hasWildcard)
285         assignExact(pat, VER_NDX_LOCAL, "local");
286   }
287 
288   // Next, assign versions to wildcards that are not "*". Note that because the
289   // last match takes precedence over previous matches, we iterate over the
290   // definitions in the reverse order.
291   auto assignWildcard = [&](SymbolVersion pat, uint16_t id, StringRef ver) {
292     assignWildcardVersion(pat, id, /*includeNonDefault=*/false);
293     buf.clear();
294     assignWildcardVersion({(pat.name + "@" + ver).toStringRef(buf),
295                            pat.isExternCpp, /*hasWildCard=*/true},
296                           id,
297                           /*includeNonDefault=*/true);
298   };
299   for (VersionDefinition &v : llvm::reverse(config->versionDefinitions)) {
300     for (SymbolVersion &pat : v.nonLocalPatterns)
301       if (pat.hasWildcard && pat.name != "*")
302         assignWildcard(pat, v.id, v.name);
303     for (SymbolVersion &pat : v.localPatterns)
304       if (pat.hasWildcard && pat.name != "*")
305         assignWildcard(pat, VER_NDX_LOCAL, v.name);
306   }
307 
308   // Then, assign versions to "*". In GNU linkers they have lower priority than
309   // other wildcards.
310   for (VersionDefinition &v : config->versionDefinitions) {
311     for (SymbolVersion &pat : v.nonLocalPatterns)
312       if (pat.hasWildcard && pat.name == "*")
313         assignWildcard(pat, v.id, v.name);
314     for (SymbolVersion &pat : v.localPatterns)
315       if (pat.hasWildcard && pat.name == "*")
316         assignWildcard(pat, VER_NDX_LOCAL, v.name);
317   }
318 
319   // Symbol themselves might know their versions because symbols
320   // can contain versions in the form of <name>@<version>.
321   // Let them parse and update their names to exclude version suffix.
322   for (Symbol *sym : symVector)
323     if (sym->hasVersionSuffix)
324       sym->parseSymbolVersion();
325 
326   // isPreemptible is false at this point. To correctly compute the binding of a
327   // Defined (which is used by includeInDynsym()), we need to know if it is
328   // VER_NDX_LOCAL or not. Compute symbol versions before handling
329   // --dynamic-list.
330   handleDynamicList();
331 }
332