xref: /freebsd/contrib/llvm-project/lld/ELF/SymbolTable.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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 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   size_t pos = name.find('@');
68   if (pos != StringRef::npos && pos + 1 < name.size() && name[pos + 1] == '@')
69     name = name.take_front(pos);
70 
71   auto p = symMap.insert({CachedHashStringRef(name), (int)symVector.size()});
72   int &symIndex = p.first->second;
73   bool isNew = p.second;
74 
75   if (!isNew)
76     return symVector[symIndex];
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->versionId = VER_NDX_GLOBAL;
86   sym->visibility = STV_DEFAULT;
87   sym->isUsedInRegularObj = false;
88   sym->exportDynamic = false;
89   sym->inDynamicList = false;
90   sym->canInline = true;
91   sym->referenced = false;
92   sym->traced = false;
93   sym->scriptDefined = false;
94   sym->partition = 1;
95   return sym;
96 }
97 
98 Symbol *SymbolTable::addSymbol(const Symbol &newSym) {
99   Symbol *sym = insert(newSym.getName());
100   sym->resolve(newSym);
101   return sym;
102 }
103 
104 Symbol *SymbolTable::find(StringRef name) {
105   auto it = symMap.find(CachedHashStringRef(name));
106   if (it == symMap.end())
107     return nullptr;
108   Symbol *sym = symVector[it->second];
109   if (sym->isPlaceholder())
110     return nullptr;
111   return sym;
112 }
113 
114 // A version script/dynamic list is only meaningful for a Defined symbol.
115 // A CommonSymbol will be converted to a Defined in replaceCommonSymbols().
116 // A lazy symbol may be made Defined if an LTO libcall fetches it.
117 static bool canBeVersioned(const Symbol &sym) {
118   return sym.isDefined() || sym.isCommon() || sym.isLazy();
119 }
120 
121 // Initialize demangledSyms with a map from demangled symbols to symbol
122 // objects. Used to handle "extern C++" directive in version scripts.
123 //
124 // The map will contain all demangled symbols. That can be very large,
125 // and in LLD we generally want to avoid do anything for each symbol.
126 // Then, why are we doing this? Here's why.
127 //
128 // Users can use "extern C++ {}" directive to match against demangled
129 // C++ symbols. For example, you can write a pattern such as
130 // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this
131 // other than trying to match a pattern against all demangled symbols.
132 // So, if "extern C++" feature is used, we need to demangle all known
133 // symbols.
134 StringMap<std::vector<Symbol *>> &SymbolTable::getDemangledSyms() {
135   if (!demangledSyms) {
136     demangledSyms.emplace();
137     std::string demangled;
138     for (Symbol *sym : symVector)
139       if (canBeVersioned(*sym)) {
140         StringRef name = sym->getName();
141         size_t pos = name.find('@');
142         if (pos == std::string::npos)
143           demangled = demangleItanium(name);
144         else if (pos + 1 == name.size() || name[pos + 1] == '@')
145           demangled = demangleItanium(name.substr(0, pos));
146         else
147           demangled =
148               (demangleItanium(name.substr(0, pos)) + name.substr(pos)).str();
149         (*demangledSyms)[demangled].push_back(sym);
150       }
151   }
152   return *demangledSyms;
153 }
154 
155 std::vector<Symbol *> SymbolTable::findByVersion(SymbolVersion ver) {
156   if (ver.isExternCpp)
157     return getDemangledSyms().lookup(ver.name);
158   if (Symbol *sym = find(ver.name))
159     if (canBeVersioned(*sym))
160       return {sym};
161   return {};
162 }
163 
164 std::vector<Symbol *> SymbolTable::findAllByVersion(SymbolVersion ver,
165                                                     bool includeNonDefault) {
166   std::vector<Symbol *> res;
167   SingleStringMatcher m(ver.name);
168   auto check = [&](StringRef name) {
169     size_t pos = name.find('@');
170     if (!includeNonDefault)
171       return pos == StringRef::npos;
172     return !(pos + 1 < name.size() && name[pos + 1] == '@');
173   };
174 
175   if (ver.isExternCpp) {
176     for (auto &p : getDemangledSyms())
177       if (m.match(p.first()))
178         for (Symbol *sym : p.second)
179           if (check(sym->getName()))
180             res.push_back(sym);
181     return res;
182   }
183 
184   for (Symbol *sym : symVector)
185     if (canBeVersioned(*sym) && check(sym->getName()) &&
186         m.match(sym->getName()))
187       res.push_back(sym);
188   return res;
189 }
190 
191 void SymbolTable::handleDynamicList() {
192   for (SymbolVersion &ver : config->dynamicList) {
193     std::vector<Symbol *> syms;
194     if (ver.hasWildcard)
195       syms = findAllByVersion(ver, /*includeNonDefault=*/true);
196     else
197       syms = findByVersion(ver);
198 
199     for (Symbol *sym : syms)
200       sym->inDynamicList = true;
201   }
202 }
203 
204 // Set symbol versions to symbols. This function handles patterns containing no
205 // wildcard characters. Return false if no symbol definition matches ver.
206 bool SymbolTable::assignExactVersion(SymbolVersion ver, uint16_t versionId,
207                                      StringRef versionName,
208                                      bool includeNonDefault) {
209   // Get a list of symbols which we need to assign the version to.
210   std::vector<Symbol *> syms = findByVersion(ver);
211 
212   auto getName = [](uint16_t ver) -> std::string {
213     if (ver == VER_NDX_LOCAL)
214       return "VER_NDX_LOCAL";
215     if (ver == VER_NDX_GLOBAL)
216       return "VER_NDX_GLOBAL";
217     return ("version '" + config->versionDefinitions[ver].name + "'").str();
218   };
219 
220   // Assign the version.
221   for (Symbol *sym : syms) {
222     // For a non-local versionId, skip symbols containing version info because
223     // symbol versions specified by symbol names take precedence over version
224     // scripts. See parseSymbolVersion().
225     if (!includeNonDefault && versionId != VER_NDX_LOCAL &&
226         sym->getName().contains('@'))
227       continue;
228 
229     // If the version has not been assigned, verdefIndex is -1. Use an arbitrary
230     // number (0) to indicate the version has been assigned.
231     if (sym->verdefIndex == UINT32_C(-1)) {
232       sym->verdefIndex = 0;
233       sym->versionId = versionId;
234     }
235     if (sym->versionId == versionId)
236       continue;
237 
238     warn("attempt to reassign symbol '" + ver.name + "' of " +
239          getName(sym->versionId) + " to " + getName(versionId));
240   }
241   return !syms.empty();
242 }
243 
244 void SymbolTable::assignWildcardVersion(SymbolVersion ver, uint16_t versionId,
245                                         bool includeNonDefault) {
246   // Exact matching takes precedence over fuzzy matching,
247   // so we set a version to a symbol only if no version has been assigned
248   // to the symbol. This behavior is compatible with GNU.
249   for (Symbol *sym : findAllByVersion(ver, includeNonDefault))
250     if (sym->verdefIndex == UINT32_C(-1)) {
251       sym->verdefIndex = 0;
252       sym->versionId = versionId;
253     }
254 }
255 
256 // This function processes version scripts by updating the versionId
257 // member of symbols.
258 // If there's only one anonymous version definition in a version
259 // script file, the script does not actually define any symbol version,
260 // but just specifies symbols visibilities.
261 void SymbolTable::scanVersionScript() {
262   SmallString<128> buf;
263   // First, we assign versions to exact matching symbols,
264   // i.e. version definitions not containing any glob meta-characters.
265   std::vector<Symbol *> syms;
266   for (VersionDefinition &v : config->versionDefinitions) {
267     auto assignExact = [&](SymbolVersion pat, uint16_t id, StringRef ver) {
268       bool found =
269           assignExactVersion(pat, id, ver, /*includeNonDefault=*/false);
270       buf.clear();
271       found |= assignExactVersion({(pat.name + "@" + v.name).toStringRef(buf),
272                                    pat.isExternCpp, /*hasWildCard=*/false},
273                                   id, ver, /*includeNonDefault=*/true);
274       if (!found && !config->undefinedVersion)
275         errorOrWarn("version script assignment of '" + ver + "' to symbol '" +
276                     pat.name + "' failed: symbol not defined");
277     };
278     for (SymbolVersion &pat : v.nonLocalPatterns)
279       if (!pat.hasWildcard)
280         assignExact(pat, v.id, v.name);
281     for (SymbolVersion pat : v.localPatterns)
282       if (!pat.hasWildcard)
283         assignExact(pat, VER_NDX_LOCAL, "local");
284   }
285 
286   // Next, assign versions to wildcards that are not "*". Note that because the
287   // last match takes precedence over previous matches, we iterate over the
288   // definitions in the reverse order.
289   auto assignWildcard = [&](SymbolVersion pat, uint16_t id, StringRef ver) {
290     assignWildcardVersion(pat, id, /*includeNonDefault=*/false);
291     buf.clear();
292     assignWildcardVersion({(pat.name + "@" + ver).toStringRef(buf),
293                            pat.isExternCpp, /*hasWildCard=*/true},
294                           id,
295                           /*includeNonDefault=*/true);
296   };
297   for (VersionDefinition &v : llvm::reverse(config->versionDefinitions)) {
298     for (SymbolVersion &pat : v.nonLocalPatterns)
299       if (pat.hasWildcard && pat.name != "*")
300         assignWildcard(pat, v.id, v.name);
301     for (SymbolVersion &pat : v.localPatterns)
302       if (pat.hasWildcard && pat.name != "*")
303         assignWildcard(pat, VER_NDX_LOCAL, v.name);
304   }
305 
306   // Then, assign versions to "*". In GNU linkers they have lower priority than
307   // other wildcards.
308   for (VersionDefinition &v : config->versionDefinitions) {
309     for (SymbolVersion &pat : v.nonLocalPatterns)
310       if (pat.hasWildcard && pat.name == "*")
311         assignWildcard(pat, v.id, v.name);
312     for (SymbolVersion &pat : v.localPatterns)
313       if (pat.hasWildcard && pat.name == "*")
314         assignWildcard(pat, VER_NDX_LOCAL, v.name);
315   }
316 
317   // Symbol themselves might know their versions because symbols
318   // can contain versions in the form of <name>@<version>.
319   // Let them parse and update their names to exclude version suffix.
320   for (Symbol *sym : symVector)
321     sym->parseSymbolVersion();
322 
323   // isPreemptible is false at this point. To correctly compute the binding of a
324   // Defined (which is used by includeInDynsym()), we need to know if it is
325   // VER_NDX_LOCAL or not. Compute symbol versions before handling
326   // --dynamic-list.
327   handleDynamicList();
328 }
329