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 
wrap(Symbol * sym,Symbol * real,Symbol * wrap)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.
insert(StringRef name)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 
addSymbol(const Symbol & newSym)98 Symbol *SymbolTable::addSymbol(const Symbol &newSym) {
99   Symbol *sym = insert(newSym.getName());
100   sym->resolve(newSym);
101   return sym;
102 }
103 
find(StringRef name)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.
canBeVersioned(const Symbol & sym)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.
getDemangledSyms()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 
findByVersion(SymbolVersion ver)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 
findAllByVersion(SymbolVersion ver,bool includeNonDefault)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 // Handles -dynamic-list.
handleDynamicList()192 void SymbolTable::handleDynamicList() {
193   for (SymbolVersion &ver : config->dynamicList) {
194     std::vector<Symbol *> syms;
195     if (ver.hasWildcard)
196       syms = findAllByVersion(ver, /*includeNonDefault=*/true);
197     else
198       syms = findByVersion(ver);
199 
200     for (Symbol *sym : syms)
201       sym->inDynamicList = true;
202   }
203 }
204 
205 // Set symbol versions to symbols. This function handles patterns containing no
206 // wildcard characters. Return false if no symbol definition matches ver.
assignExactVersion(SymbolVersion ver,uint16_t versionId,StringRef versionName,bool includeNonDefault)207 bool SymbolTable::assignExactVersion(SymbolVersion ver, uint16_t versionId,
208                                      StringRef versionName,
209                                      bool includeNonDefault) {
210   // Get a list of symbols which we need to assign the version to.
211   std::vector<Symbol *> syms = findByVersion(ver);
212 
213   auto getName = [](uint16_t ver) -> std::string {
214     if (ver == VER_NDX_LOCAL)
215       return "VER_NDX_LOCAL";
216     if (ver == VER_NDX_GLOBAL)
217       return "VER_NDX_GLOBAL";
218     return ("version '" + config->versionDefinitions[ver].name + "'").str();
219   };
220 
221   // Assign the version.
222   for (Symbol *sym : syms) {
223     // For a non-local versionId, skip symbols containing version info because
224     // symbol versions specified by symbol names take precedence over version
225     // scripts. See parseSymbolVersion().
226     if (!includeNonDefault && versionId != VER_NDX_LOCAL &&
227         sym->getName().contains('@'))
228       continue;
229 
230     // If the version has not been assigned, verdefIndex is -1. Use an arbitrary
231     // number (0) to indicate the version has been assigned.
232     if (sym->verdefIndex == UINT32_C(-1)) {
233       sym->verdefIndex = 0;
234       sym->versionId = versionId;
235     }
236     if (sym->versionId == versionId)
237       continue;
238 
239     warn("attempt to reassign symbol '" + ver.name + "' of " +
240          getName(sym->versionId) + " to " + getName(versionId));
241   }
242   return !syms.empty();
243 }
244 
assignWildcardVersion(SymbolVersion ver,uint16_t versionId,bool includeNonDefault)245 void SymbolTable::assignWildcardVersion(SymbolVersion ver, uint16_t versionId,
246                                         bool includeNonDefault) {
247   // Exact matching takes precedence over fuzzy matching,
248   // so we set a version to a symbol only if no version has been assigned
249   // to the symbol. This behavior is compatible with GNU.
250   for (Symbol *sym : findAllByVersion(ver, includeNonDefault))
251     if (sym->verdefIndex == UINT32_C(-1)) {
252       sym->verdefIndex = 0;
253       sym->versionId = versionId;
254     }
255 }
256 
257 // This function processes version scripts by updating the versionId
258 // member of symbols.
259 // If there's only one anonymous version definition in a version
260 // script file, the script does not actually define any symbol version,
261 // but just specifies symbols visibilities.
scanVersionScript()262 void SymbolTable::scanVersionScript() {
263   SmallString<128> buf;
264   // First, we assign versions to exact matching symbols,
265   // i.e. version definitions not containing any glob meta-characters.
266   std::vector<Symbol *> syms;
267   for (VersionDefinition &v : config->versionDefinitions) {
268     auto assignExact = [&](SymbolVersion pat, uint16_t id, StringRef ver) {
269       bool found =
270           assignExactVersion(pat, id, ver, /*includeNonDefault=*/false);
271       buf.clear();
272       found |= assignExactVersion({(pat.name + "@" + v.name).toStringRef(buf),
273                                    pat.isExternCpp, /*hasWildCard=*/false},
274                                   id, ver, /*includeNonDefault=*/true);
275       if (!found && !config->undefinedVersion)
276         errorOrWarn("version script assignment of '" + ver + "' to symbol '" +
277                     pat.name + "' failed: symbol not defined");
278     };
279     for (SymbolVersion &pat : v.nonLocalPatterns)
280       if (!pat.hasWildcard)
281         assignExact(pat, v.id, v.name);
282     for (SymbolVersion pat : v.localPatterns)
283       if (!pat.hasWildcard)
284         assignExact(pat, VER_NDX_LOCAL, "local");
285   }
286 
287   // Next, assign versions to wildcards that are not "*". Note that because the
288   // last match takes precedence over previous matches, we iterate over the
289   // definitions in the reverse order.
290   auto assignWildcard = [&](SymbolVersion pat, uint16_t id, StringRef ver) {
291     assignWildcardVersion(pat, id, /*includeNonDefault=*/false);
292     buf.clear();
293     assignWildcardVersion({(pat.name + "@" + ver).toStringRef(buf),
294                            pat.isExternCpp, /*hasWildCard=*/true},
295                           id,
296                           /*includeNonDefault=*/true);
297   };
298   for (VersionDefinition &v : llvm::reverse(config->versionDefinitions)) {
299     for (SymbolVersion &pat : v.nonLocalPatterns)
300       if (pat.hasWildcard && pat.name != "*")
301         assignWildcard(pat, v.id, v.name);
302     for (SymbolVersion &pat : v.localPatterns)
303       if (pat.hasWildcard && pat.name != "*")
304         assignWildcard(pat, VER_NDX_LOCAL, v.name);
305   }
306 
307   // Then, assign versions to "*". In GNU linkers they have lower priority than
308   // other wildcards.
309   for (VersionDefinition &v : config->versionDefinitions) {
310     for (SymbolVersion &pat : v.nonLocalPatterns)
311       if (pat.hasWildcard && pat.name == "*")
312         assignWildcard(pat, v.id, v.name);
313     for (SymbolVersion &pat : v.localPatterns)
314       if (pat.hasWildcard && pat.name == "*")
315         assignWildcard(pat, VER_NDX_LOCAL, v.name);
316   }
317 
318   // Symbol themselves might know their versions because symbols
319   // can contain versions in the form of <name>@<version>.
320   // Let them parse and update their names to exclude version suffix.
321   for (Symbol *sym : symVector)
322     sym->parseSymbolVersion();
323 
324   // isPreemptible is false at this point. To correctly compute the binding of a
325   // Defined (which is used by includeInDynsym()), we need to know if it is
326   // VER_NDX_LOCAL or not. Compute symbol versions before handling
327   // --dynamic-list.
328   handleDynamicList();
329 }
330