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