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   int &symIndex = p.first->second;
74   bool isNew = p.second;
75 
76   if (!isNew) {
77     Symbol *sym = symVector[symIndex];
78     if (stem.size() != name.size())
79       sym->setName(name);
80     return sym;
81   }
82 
83   Symbol *sym = reinterpret_cast<Symbol *>(make<SymbolUnion>());
84   symVector.push_back(sym);
85 
86   // *sym was not initialized by a constructor. Fields that may get referenced
87   // when it is a placeholder must be initialized here.
88   sym->setName(name);
89   sym->symbolKind = Symbol::PlaceholderKind;
90   sym->versionId = VER_NDX_GLOBAL;
91   sym->visibility = STV_DEFAULT;
92   sym->isUsedInRegularObj = false;
93   sym->exportDynamic = false;
94   sym->inDynamicList = false;
95   sym->canInline = true;
96   sym->referenced = false;
97   sym->traced = false;
98   sym->scriptDefined = false;
99   sym->partition = 1;
100   return sym;
101 }
102 
103 Symbol *SymbolTable::addSymbol(const Symbol &newSym) {
104   Symbol *sym = insert(newSym.getName());
105   sym->resolve(newSym);
106   return sym;
107 }
108 
109 Symbol *SymbolTable::find(StringRef name) {
110   auto it = symMap.find(CachedHashStringRef(name));
111   if (it == symMap.end())
112     return nullptr;
113   return symVector[it->second];
114 }
115 
116 // A version script/dynamic list is only meaningful for a Defined symbol.
117 // A CommonSymbol will be converted to a Defined in replaceCommonSymbols().
118 // A lazy symbol may be made Defined if an LTO libcall extracts it.
119 static bool canBeVersioned(const Symbol &sym) {
120   return sym.isDefined() || sym.isCommon() || sym.isLazy();
121 }
122 
123 // Initialize demangledSyms with a map from demangled symbols to symbol
124 // objects. Used to handle "extern C++" directive in version scripts.
125 //
126 // The map will contain all demangled symbols. That can be very large,
127 // and in LLD we generally want to avoid do anything for each symbol.
128 // Then, why are we doing this? Here's why.
129 //
130 // Users can use "extern C++ {}" directive to match against demangled
131 // C++ symbols. For example, you can write a pattern such as
132 // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this
133 // other than trying to match a pattern against all demangled symbols.
134 // So, if "extern C++" feature is used, we need to demangle all known
135 // symbols.
136 StringMap<std::vector<Symbol *>> &SymbolTable::getDemangledSyms() {
137   if (!demangledSyms) {
138     demangledSyms.emplace();
139     std::string demangled;
140     for (Symbol *sym : symVector)
141       if (canBeVersioned(*sym)) {
142         StringRef name = sym->getName();
143         size_t pos = name.find('@');
144         if (pos == std::string::npos)
145           demangled = demangleItanium(name);
146         else if (pos + 1 == name.size() || name[pos + 1] == '@')
147           demangled = demangleItanium(name.substr(0, pos));
148         else
149           demangled =
150               (demangleItanium(name.substr(0, pos)) + name.substr(pos)).str();
151         (*demangledSyms)[demangled].push_back(sym);
152       }
153   }
154   return *demangledSyms;
155 }
156 
157 std::vector<Symbol *> SymbolTable::findByVersion(SymbolVersion ver) {
158   if (ver.isExternCpp)
159     return getDemangledSyms().lookup(ver.name);
160   if (Symbol *sym = find(ver.name))
161     if (canBeVersioned(*sym))
162       return {sym};
163   return {};
164 }
165 
166 std::vector<Symbol *> SymbolTable::findAllByVersion(SymbolVersion ver,
167                                                     bool includeNonDefault) {
168   std::vector<Symbol *> res;
169   SingleStringMatcher m(ver.name);
170   auto check = [&](StringRef name) {
171     size_t pos = name.find('@');
172     if (!includeNonDefault)
173       return pos == StringRef::npos;
174     return !(pos + 1 < name.size() && name[pos + 1] == '@');
175   };
176 
177   if (ver.isExternCpp) {
178     for (auto &p : getDemangledSyms())
179       if (m.match(p.first()))
180         for (Symbol *sym : p.second)
181           if (check(sym->getName()))
182             res.push_back(sym);
183     return res;
184   }
185 
186   for (Symbol *sym : symVector)
187     if (canBeVersioned(*sym) && check(sym->getName()) &&
188         m.match(sym->getName()))
189       res.push_back(sym);
190   return res;
191 }
192 
193 void SymbolTable::handleDynamicList() {
194   for (SymbolVersion &ver : config->dynamicList) {
195     std::vector<Symbol *> syms;
196     if (ver.hasWildcard)
197       syms = findAllByVersion(ver, /*includeNonDefault=*/true);
198     else
199       syms = findByVersion(ver);
200 
201     for (Symbol *sym : syms)
202       sym->inDynamicList = true;
203   }
204 }
205 
206 // Set symbol versions to symbols. This function handles patterns containing no
207 // wildcard characters. Return false if no symbol definition matches ver.
208 bool SymbolTable::assignExactVersion(SymbolVersion ver, uint16_t versionId,
209                                      StringRef versionName,
210                                      bool includeNonDefault) {
211   // Get a list of symbols which we need to assign the version to.
212   std::vector<Symbol *> syms = findByVersion(ver);
213 
214   auto getName = [](uint16_t ver) -> std::string {
215     if (ver == VER_NDX_LOCAL)
216       return "VER_NDX_LOCAL";
217     if (ver == VER_NDX_GLOBAL)
218       return "VER_NDX_GLOBAL";
219     return ("version '" + config->versionDefinitions[ver].name + "'").str();
220   };
221 
222   // Assign the version.
223   for (Symbol *sym : syms) {
224     // For a non-local versionId, skip symbols containing version info because
225     // symbol versions specified by symbol names take precedence over version
226     // scripts. See parseSymbolVersion().
227     if (!includeNonDefault && versionId != VER_NDX_LOCAL &&
228         sym->getName().contains('@'))
229       continue;
230 
231     // If the version has not been assigned, verdefIndex is -1. Use an arbitrary
232     // number (0) to indicate the version has been assigned.
233     if (sym->verdefIndex == uint16_t(-1)) {
234       sym->verdefIndex = 0;
235       sym->versionId = versionId;
236     }
237     if (sym->versionId == versionId)
238       continue;
239 
240     warn("attempt to reassign symbol '" + ver.name + "' of " +
241          getName(sym->versionId) + " to " + getName(versionId));
242   }
243   return !syms.empty();
244 }
245 
246 void SymbolTable::assignWildcardVersion(SymbolVersion ver, uint16_t versionId,
247                                         bool includeNonDefault) {
248   // Exact matching takes precedence over fuzzy matching,
249   // so we set a version to a symbol only if no version has been assigned
250   // to the symbol. This behavior is compatible with GNU.
251   for (Symbol *sym : findAllByVersion(ver, includeNonDefault))
252     if (sym->verdefIndex == uint16_t(-1)) {
253       sym->verdefIndex = 0;
254       sym->versionId = versionId;
255     }
256 }
257 
258 // This function processes version scripts by updating the versionId
259 // member of symbols.
260 // If there's only one anonymous version definition in a version
261 // script file, the script does not actually define any symbol version,
262 // but just specifies symbols visibilities.
263 void SymbolTable::scanVersionScript() {
264   SmallString<128> buf;
265   // First, we assign versions to exact matching symbols,
266   // i.e. version definitions not containing any glob meta-characters.
267   std::vector<Symbol *> syms;
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     sym->parseSymbolVersion();
324 
325   // isPreemptible is false at this point. To correctly compute the binding of a
326   // Defined (which is used by includeInDynsym()), we need to know if it is
327   // VER_NDX_LOCAL or not. Compute symbol versions before handling
328   // --dynamic-list.
329   handleDynamicList();
330 }
331