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