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 = VER_NDX_GLOBAL; 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 // Handles -dynamic-list. 157 void SymbolTable::handleDynamicList() { 158 for (SymbolVersion &ver : config->dynamicList) { 159 std::vector<Symbol *> syms; 160 if (ver.hasWildcard) 161 syms = findAllByVersion(ver); 162 else 163 syms = findByVersion(ver); 164 165 for (Symbol *b : syms) { 166 if (!config->shared) 167 b->exportDynamic = true; 168 else if (b->includeInDynsym()) 169 b->isPreemptible = true; 170 } 171 } 172 } 173 174 // Set symbol versions to symbols. This function handles patterns 175 // containing no wildcard characters. 176 void SymbolTable::assignExactVersion(SymbolVersion ver, uint16_t versionId, 177 StringRef versionName) { 178 if (ver.hasWildcard) 179 return; 180 181 // Get a list of symbols which we need to assign the version to. 182 std::vector<Symbol *> syms = findByVersion(ver); 183 if (syms.empty()) { 184 if (!config->undefinedVersion) 185 error("version script assignment of '" + versionName + "' to symbol '" + 186 ver.name + "' failed: symbol not defined"); 187 return; 188 } 189 190 auto getName = [](uint16_t ver) -> std::string { 191 if (ver == VER_NDX_LOCAL) 192 return "VER_NDX_LOCAL"; 193 if (ver == VER_NDX_GLOBAL) 194 return "VER_NDX_GLOBAL"; 195 return ("version '" + config->versionDefinitions[ver].name + "'").str(); 196 }; 197 198 // Assign the version. 199 for (Symbol *sym : syms) { 200 // Skip symbols containing version info because symbol versions 201 // specified by symbol names take precedence over version scripts. 202 // See parseSymbolVersion(). 203 if (sym->getName().contains('@')) 204 continue; 205 206 // If the version has not been assigned, verdefIndex is -1. Use an arbitrary 207 // number (0) to indicate the version has been assigned. 208 if (sym->verdefIndex == UINT32_C(-1)) { 209 sym->verdefIndex = 0; 210 sym->versionId = versionId; 211 } 212 if (sym->versionId == versionId) 213 continue; 214 215 warn("attempt to reassign symbol '" + ver.name + "' of " + 216 getName(sym->versionId) + " to " + getName(versionId)); 217 } 218 } 219 220 void SymbolTable::assignWildcardVersion(SymbolVersion ver, uint16_t versionId) { 221 // Exact matching takes precendence over fuzzy matching, 222 // so we set a version to a symbol only if no version has been assigned 223 // to the symbol. This behavior is compatible with GNU. 224 for (Symbol *sym : findAllByVersion(ver)) 225 if (sym->verdefIndex == UINT32_C(-1)) { 226 sym->verdefIndex = 0; 227 sym->versionId = versionId; 228 } 229 } 230 231 // This function processes version scripts by updating the versionId 232 // member of symbols. 233 // If there's only one anonymous version definition in a version 234 // script file, the script does not actually define any symbol version, 235 // but just specifies symbols visibilities. 236 void SymbolTable::scanVersionScript() { 237 // First, we assign versions to exact matching symbols, 238 // i.e. version definitions not containing any glob meta-characters. 239 for (VersionDefinition &v : config->versionDefinitions) 240 for (SymbolVersion &pat : v.patterns) 241 assignExactVersion(pat, v.id, v.name); 242 243 // Next, assign versions to wildcards that are not "*". Note that because the 244 // last match takes precedence over previous matches, we iterate over the 245 // definitions in the reverse order. 246 for (VersionDefinition &v : llvm::reverse(config->versionDefinitions)) 247 for (SymbolVersion &pat : v.patterns) 248 if (pat.hasWildcard && pat.name != "*") 249 assignWildcardVersion(pat, v.id); 250 251 // Then, assign versions to "*". In GNU linkers they have lower priority than 252 // other wildcards. 253 for (VersionDefinition &v : config->versionDefinitions) 254 for (SymbolVersion &pat : v.patterns) 255 if (pat.hasWildcard && pat.name == "*") 256 assignWildcardVersion(pat, v.id); 257 258 // Symbol themselves might know their versions because symbols 259 // can contain versions in the form of <name>@<version>. 260 // Let them parse and update their names to exclude version suffix. 261 for (Symbol *sym : symVector) 262 sym->parseSymbolVersion(); 263 264 // isPreemptible is false at this point. To correctly compute the binding of a 265 // Defined (which is used by includeInDynsym()), we need to know if it is 266 // VER_NDX_LOCAL or not. Compute symbol versions before handling 267 // --dynamic-list. 268 handleDynamicList(); 269 } 270