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