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     return sym;
78   }
79 
80   Symbol *sym = reinterpret_cast<Symbol *>(make<SymbolUnion>());
81   symVector.push_back(sym);
82 
83   // *sym was not initialized by a constructor. Fields that may get referenced
84   // when it is a placeholder must be initialized here.
85   sym->setName(name);
86   sym->symbolKind = Symbol::PlaceholderKind;
87   sym->versionId = VER_NDX_GLOBAL;
88   sym->visibility = STV_DEFAULT;
89   sym->isUsedInRegularObj = false;
90   sym->exportDynamic = false;
91   sym->inDynamicList = false;
92   sym->canInline = true;
93   sym->referenced = false;
94   sym->traced = false;
95   sym->scriptDefined = false;
96   sym->partition = 1;
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 Symbol *SymbolTable::find(StringRef name) {
107   auto it = symMap.find(CachedHashStringRef(name));
108   if (it == symMap.end())
109     return nullptr;
110   return symVector[it->second];
111 }
112 
113 // A version script/dynamic list is only meaningful for a Defined symbol.
114 // A CommonSymbol will be converted to a Defined in replaceCommonSymbols().
115 // A lazy symbol may be made Defined if an LTO libcall extracts it.
116 static bool canBeVersioned(const Symbol &sym) {
117   return sym.isDefined() || sym.isCommon() || sym.isLazy();
118 }
119 
120 // Initialize demangledSyms with a map from demangled symbols to symbol
121 // objects. Used to handle "extern C++" directive in version scripts.
122 //
123 // The map will contain all demangled symbols. That can be very large,
124 // and in LLD we generally want to avoid do anything for each symbol.
125 // Then, why are we doing this? Here's why.
126 //
127 // Users can use "extern C++ {}" directive to match against demangled
128 // C++ symbols. For example, you can write a pattern such as
129 // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this
130 // other than trying to match a pattern against all demangled symbols.
131 // So, if "extern C++" feature is used, we need to demangle all known
132 // symbols.
133 StringMap<SmallVector<Symbol *, 0>> &SymbolTable::getDemangledSyms() {
134   if (!demangledSyms) {
135     demangledSyms.emplace();
136     std::string demangled;
137     for (Symbol *sym : symVector)
138       if (canBeVersioned(*sym)) {
139         StringRef name = sym->getName();
140         size_t pos = name.find('@');
141         if (pos == std::string::npos)
142           demangled = demangleItanium(name);
143         else if (pos + 1 == name.size() || name[pos + 1] == '@')
144           demangled = demangleItanium(name.substr(0, pos));
145         else
146           demangled =
147               (demangleItanium(name.substr(0, pos)) + name.substr(pos)).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     sym->parseSymbolVersion();
320 
321   // isPreemptible is false at this point. To correctly compute the binding of a
322   // Defined (which is used by includeInDynsym()), we need to know if it is
323   // VER_NDX_LOCAL or not. Compute symbol versions before handling
324   // --dynamic-list.
325   handleDynamicList();
326 }
327