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