xref: /openbsd-src/gnu/llvm/lld/ELF/SymbolTable.cpp (revision 3374c67d44f9b75b98444cbf63020f777792342e)
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   // Swap symbols as instructed by -wrap.
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->gwarn = false;
94   sym->scriptDefined = false;
95   sym->partition = 1;
96   return sym;
97 }
98 
99 Symbol *SymbolTable::addSymbol(const Symbol &newSym) {
100   Symbol *sym = insert(newSym.getName());
101   sym->resolve(newSym);
102   return sym;
103 }
104 
105 Symbol *SymbolTable::find(StringRef name) {
106   auto it = symMap.find(CachedHashStringRef(name));
107   if (it == symMap.end())
108     return nullptr;
109   Symbol *sym = symVector[it->second];
110   if (sym->isPlaceholder())
111     return nullptr;
112   return sym;
113 }
114 
115 // A version script/dynamic list is only meaningful for a Defined symbol.
116 // A CommonSymbol will be converted to a Defined in replaceCommonSymbols().
117 // A lazy symbol may be made Defined if an LTO libcall fetches it.
118 static bool canBeVersioned(const Symbol &sym) {
119   return sym.isDefined() || sym.isCommon() || sym.isLazy();
120 }
121 
122 // Initialize demangledSyms with a map from demangled symbols to symbol
123 // objects. Used to handle "extern C++" directive in version scripts.
124 //
125 // The map will contain all demangled symbols. That can be very large,
126 // and in LLD we generally want to avoid do anything for each symbol.
127 // Then, why are we doing this? Here's why.
128 //
129 // Users can use "extern C++ {}" directive to match against demangled
130 // C++ symbols. For example, you can write a pattern such as
131 // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this
132 // other than trying to match a pattern against all demangled symbols.
133 // So, if "extern C++" feature is used, we need to demangle all known
134 // symbols.
135 StringMap<std::vector<Symbol *>> &SymbolTable::getDemangledSyms() {
136   if (!demangledSyms) {
137     demangledSyms.emplace();
138     std::string demangled;
139     for (Symbol *sym : symVector)
140       if (canBeVersioned(*sym)) {
141         StringRef name = sym->getName();
142         size_t pos = name.find('@');
143         if (pos == std::string::npos)
144           demangled = demangleItanium(name);
145         else if (pos + 1 == name.size() || name[pos + 1] == '@')
146           demangled = demangleItanium(name.substr(0, pos));
147         else
148           demangled =
149               (demangleItanium(name.substr(0, pos)) + name.substr(pos)).str();
150         (*demangledSyms)[demangled].push_back(sym);
151       }
152   }
153   return *demangledSyms;
154 }
155 
156 std::vector<Symbol *> SymbolTable::findByVersion(SymbolVersion ver) {
157   if (ver.isExternCpp)
158     return getDemangledSyms().lookup(ver.name);
159   if (Symbol *sym = find(ver.name))
160     if (canBeVersioned(*sym))
161       return {sym};
162   return {};
163 }
164 
165 std::vector<Symbol *> SymbolTable::findAllByVersion(SymbolVersion ver,
166                                                     bool includeNonDefault) {
167   std::vector<Symbol *> res;
168   SingleStringMatcher m(ver.name);
169   auto check = [&](StringRef name) {
170     size_t pos = name.find('@');
171     if (!includeNonDefault)
172       return pos == StringRef::npos;
173     return !(pos + 1 < name.size() && name[pos + 1] == '@');
174   };
175 
176   if (ver.isExternCpp) {
177     for (auto &p : getDemangledSyms())
178       if (m.match(p.first()))
179         for (Symbol *sym : p.second)
180           if (check(sym->getName()))
181             res.push_back(sym);
182     return res;
183   }
184 
185   for (Symbol *sym : symVector)
186     if (canBeVersioned(*sym) && check(sym->getName()) &&
187         m.match(sym->getName()))
188       res.push_back(sym);
189   return res;
190 }
191 
192 // Handles -dynamic-list.
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 == UINT32_C(-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 == UINT32_C(-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