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 
30 using namespace lld;
31 using namespace lld::elf;
32 
33 SymbolTable *elf::symtab;
34 
35 void SymbolTable::wrap(Symbol *sym, Symbol *real, Symbol *wrap) {
36   // Swap symbols as instructed by -wrap.
37   int &idx1 = symMap[CachedHashStringRef(sym->getName())];
38   int &idx2 = symMap[CachedHashStringRef(real->getName())];
39   int &idx3 = symMap[CachedHashStringRef(wrap->getName())];
40 
41   idx2 = idx1;
42   idx1 = idx3;
43 
44   // Now renaming is complete. No one refers Real symbol. We could leave
45   // Real as-is, but if Real is written to the symbol table, that may
46   // contain irrelevant values. So, we copy all values from Sym to Real.
47   StringRef s = real->getName();
48   memcpy(real, sym, sizeof(SymbolUnion));
49   real->setName(s);
50 }
51 
52 // Find an existing symbol or create a new one.
53 Symbol *SymbolTable::insert(StringRef name) {
54   // <name>@@<version> means the symbol is the default version. In that
55   // case <name>@@<version> will be used to resolve references to <name>.
56   //
57   // Since this is a hot path, the following string search code is
58   // optimized for speed. StringRef::find(char) is much faster than
59   // StringRef::find(StringRef).
60   size_t pos = name.find('@');
61   if (pos != StringRef::npos && pos + 1 < name.size() && name[pos + 1] == '@')
62     name = name.take_front(pos);
63 
64   auto p = symMap.insert({CachedHashStringRef(name), (int)symVector.size()});
65   int &symIndex = p.first->second;
66   bool isNew = p.second;
67 
68   if (!isNew)
69     return symVector[symIndex];
70 
71   Symbol *sym = reinterpret_cast<Symbol *>(make<SymbolUnion>());
72   symVector.push_back(sym);
73 
74   sym->setName(name);
75   sym->symbolKind = Symbol::PlaceholderKind;
76   sym->versionId = config->defaultSymbolVersion;
77   sym->visibility = STV_DEFAULT;
78   sym->isUsedInRegularObj = false;
79   sym->exportDynamic = false;
80   sym->canInline = true;
81   sym->scriptDefined = false;
82   sym->partition = 1;
83   return sym;
84 }
85 
86 Symbol *SymbolTable::addSymbol(const Symbol &New) {
87   Symbol *sym = symtab->insert(New.getName());
88   sym->resolve(New);
89   return sym;
90 }
91 
92 Symbol *SymbolTable::find(StringRef name) {
93   auto it = symMap.find(CachedHashStringRef(name));
94   if (it == symMap.end())
95     return nullptr;
96   Symbol *sym = symVector[it->second];
97   if (sym->isPlaceholder())
98     return nullptr;
99   return sym;
100 }
101 
102 // Initialize DemangledSyms with a map from demangled symbols to symbol
103 // objects. Used to handle "extern C++" directive in version scripts.
104 //
105 // The map will contain all demangled symbols. That can be very large,
106 // and in LLD we generally want to avoid do anything for each symbol.
107 // Then, why are we doing this? Here's why.
108 //
109 // Users can use "extern C++ {}" directive to match against demangled
110 // C++ symbols. For example, you can write a pattern such as
111 // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this
112 // other than trying to match a pattern against all demangled symbols.
113 // So, if "extern C++" feature is used, we need to demangle all known
114 // symbols.
115 StringMap<std::vector<Symbol *>> &SymbolTable::getDemangledSyms() {
116   if (!demangledSyms) {
117     demangledSyms.emplace();
118     for (Symbol *sym : symVector) {
119       if (!sym->isDefined() && !sym->isCommon())
120         continue;
121       if (Optional<std::string> s = demangleItanium(sym->getName()))
122         (*demangledSyms)[*s].push_back(sym);
123       else
124         (*demangledSyms)[sym->getName()].push_back(sym);
125     }
126   }
127   return *demangledSyms;
128 }
129 
130 std::vector<Symbol *> SymbolTable::findByVersion(SymbolVersion ver) {
131   if (ver.isExternCpp)
132     return getDemangledSyms().lookup(ver.name);
133   if (Symbol *b = find(ver.name))
134     if (b->isDefined() || b->isCommon())
135       return {b};
136   return {};
137 }
138 
139 std::vector<Symbol *> SymbolTable::findAllByVersion(SymbolVersion ver) {
140   std::vector<Symbol *> res;
141   StringMatcher m(ver.name);
142 
143   if (ver.isExternCpp) {
144     for (auto &p : getDemangledSyms())
145       if (m.match(p.first()))
146         res.insert(res.end(), p.second.begin(), p.second.end());
147     return res;
148   }
149 
150   for (Symbol *sym : symVector)
151     if ((sym->isDefined() || sym->isCommon()) && m.match(sym->getName()))
152       res.push_back(sym);
153   return res;
154 }
155 
156 // If there's only one anonymous version definition in a version
157 // script file, the script does not actually define any symbol version,
158 // but just specifies symbols visibilities.
159 void SymbolTable::handleAnonymousVersion() {
160   for (SymbolVersion &ver : config->versionScriptGlobals)
161     assignExactVersion(ver, VER_NDX_GLOBAL, "global");
162   for (SymbolVersion &ver : config->versionScriptGlobals)
163     assignWildcardVersion(ver, VER_NDX_GLOBAL);
164   for (SymbolVersion &ver : config->versionScriptLocals)
165     assignExactVersion(ver, VER_NDX_LOCAL, "local");
166   for (SymbolVersion &ver : config->versionScriptLocals)
167     assignWildcardVersion(ver, VER_NDX_LOCAL);
168 }
169 
170 // Handles -dynamic-list.
171 void SymbolTable::handleDynamicList() {
172   for (SymbolVersion &ver : config->dynamicList) {
173     std::vector<Symbol *> syms;
174     if (ver.hasWildcard)
175       syms = findAllByVersion(ver);
176     else
177       syms = findByVersion(ver);
178 
179     for (Symbol *b : syms) {
180       if (!config->shared)
181         b->exportDynamic = true;
182       else if (b->includeInDynsym())
183         b->isPreemptible = true;
184     }
185   }
186 }
187 
188 // Set symbol versions to symbols. This function handles patterns
189 // containing no wildcard characters.
190 void SymbolTable::assignExactVersion(SymbolVersion ver, uint16_t versionId,
191                                      StringRef versionName) {
192   if (ver.hasWildcard)
193     return;
194 
195   // Get a list of symbols which we need to assign the version to.
196   std::vector<Symbol *> syms = findByVersion(ver);
197   if (syms.empty()) {
198     if (!config->undefinedVersion)
199       error("version script assignment of '" + versionName + "' to symbol '" +
200             ver.name + "' failed: symbol not defined");
201     return;
202   }
203 
204   // Assign the version.
205   for (Symbol *sym : syms) {
206     // Skip symbols containing version info because symbol versions
207     // specified by symbol names take precedence over version scripts.
208     // See parseSymbolVersion().
209     if (sym->getName().contains('@'))
210       continue;
211 
212     if (sym->versionId != config->defaultSymbolVersion &&
213         sym->versionId != versionId)
214       error("duplicate symbol '" + ver.name + "' in version script");
215     sym->versionId = versionId;
216   }
217 }
218 
219 void SymbolTable::assignWildcardVersion(SymbolVersion ver, uint16_t versionId) {
220   if (!ver.hasWildcard)
221     return;
222 
223   // Exact matching takes precendence over fuzzy matching,
224   // so we set a version to a symbol only if no version has been assigned
225   // to the symbol. This behavior is compatible with GNU.
226   for (Symbol *b : findAllByVersion(ver))
227     if (b->versionId == config->defaultSymbolVersion)
228       b->versionId = versionId;
229 }
230 
231 // This function processes version scripts by updating VersionId
232 // member of symbols.
233 void SymbolTable::scanVersionScript() {
234   // Handle edge cases first.
235   handleAnonymousVersion();
236   handleDynamicList();
237 
238   // Now we have version definitions, so we need to set version ids to symbols.
239   // Each version definition has a glob pattern, and all symbols that match
240   // with the pattern get that version.
241 
242   // First, we assign versions to exact matching symbols,
243   // i.e. version definitions not containing any glob meta-characters.
244   for (VersionDefinition &v : config->versionDefinitions)
245     for (SymbolVersion &ver : v.globals)
246       assignExactVersion(ver, v.id, v.name);
247 
248   // Next, we assign versions to fuzzy matching symbols,
249   // i.e. version definitions containing glob meta-characters.
250   // Note that because the last match takes precedence over previous matches,
251   // we iterate over the definitions in the reverse order.
252   for (VersionDefinition &v : llvm::reverse(config->versionDefinitions))
253     for (SymbolVersion &ver : v.globals)
254       assignWildcardVersion(ver, v.id);
255 
256   // Symbol themselves might know their versions because symbols
257   // can contain versions in the form of <name>@<version>.
258   // Let them parse and update their names to exclude version suffix.
259   for (Symbol *sym : symVector)
260     sym->parseSymbolVersion();
261 }
262