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