1 //===-- Symtab.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 #include <map> 10 #include <set> 11 12 #include "lldb/Core/Module.h" 13 #include "lldb/Core/RichManglingContext.h" 14 #include "lldb/Core/Section.h" 15 #include "lldb/Symbol/ObjectFile.h" 16 #include "lldb/Symbol/Symbol.h" 17 #include "lldb/Symbol/SymbolContext.h" 18 #include "lldb/Symbol/Symtab.h" 19 #include "lldb/Target/Language.h" 20 #include "lldb/Utility/RegularExpression.h" 21 #include "lldb/Utility/Stream.h" 22 #include "lldb/Utility/Timer.h" 23 24 #include "llvm/ADT/StringRef.h" 25 26 using namespace lldb; 27 using namespace lldb_private; 28 29 Symtab::Symtab(ObjectFile *objfile) 30 : m_objfile(objfile), m_symbols(), m_file_addr_to_index(*this), 31 m_name_to_symbol_indices(), m_mutex(), 32 m_file_addr_to_index_computed(false), m_name_indexes_computed(false) { 33 m_name_to_symbol_indices.emplace(std::make_pair( 34 lldb::eFunctionNameTypeNone, UniqueCStringMap<uint32_t>())); 35 m_name_to_symbol_indices.emplace(std::make_pair( 36 lldb::eFunctionNameTypeBase, UniqueCStringMap<uint32_t>())); 37 m_name_to_symbol_indices.emplace(std::make_pair( 38 lldb::eFunctionNameTypeMethod, UniqueCStringMap<uint32_t>())); 39 m_name_to_symbol_indices.emplace(std::make_pair( 40 lldb::eFunctionNameTypeSelector, UniqueCStringMap<uint32_t>())); 41 } 42 43 Symtab::~Symtab() = default; 44 45 void Symtab::Reserve(size_t count) { 46 // Clients should grab the mutex from this symbol table and lock it manually 47 // when calling this function to avoid performance issues. 48 m_symbols.reserve(count); 49 } 50 51 Symbol *Symtab::Resize(size_t count) { 52 // Clients should grab the mutex from this symbol table and lock it manually 53 // when calling this function to avoid performance issues. 54 m_symbols.resize(count); 55 return m_symbols.empty() ? nullptr : &m_symbols[0]; 56 } 57 58 uint32_t Symtab::AddSymbol(const Symbol &symbol) { 59 // Clients should grab the mutex from this symbol table and lock it manually 60 // when calling this function to avoid performance issues. 61 uint32_t symbol_idx = m_symbols.size(); 62 auto &name_to_index = GetNameToSymbolIndexMap(lldb::eFunctionNameTypeNone); 63 name_to_index.Clear(); 64 m_file_addr_to_index.Clear(); 65 m_symbols.push_back(symbol); 66 m_file_addr_to_index_computed = false; 67 m_name_indexes_computed = false; 68 return symbol_idx; 69 } 70 71 size_t Symtab::GetNumSymbols() const { 72 std::lock_guard<std::recursive_mutex> guard(m_mutex); 73 return m_symbols.size(); 74 } 75 76 void Symtab::SectionFileAddressesChanged() { 77 auto &name_to_index = GetNameToSymbolIndexMap(lldb::eFunctionNameTypeNone); 78 name_to_index.Clear(); 79 m_file_addr_to_index_computed = false; 80 } 81 82 void Symtab::Dump(Stream *s, Target *target, SortOrder sort_order, 83 Mangled::NamePreference name_preference) { 84 std::lock_guard<std::recursive_mutex> guard(m_mutex); 85 86 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this); 87 s->Indent(); 88 const FileSpec &file_spec = m_objfile->GetFileSpec(); 89 const char *object_name = nullptr; 90 if (m_objfile->GetModule()) 91 object_name = m_objfile->GetModule()->GetObjectName().GetCString(); 92 93 if (file_spec) 94 s->Printf("Symtab, file = %s%s%s%s, num_symbols = %" PRIu64, 95 file_spec.GetPath().c_str(), object_name ? "(" : "", 96 object_name ? object_name : "", object_name ? ")" : "", 97 (uint64_t)m_symbols.size()); 98 else 99 s->Printf("Symtab, num_symbols = %" PRIu64 "", (uint64_t)m_symbols.size()); 100 101 if (!m_symbols.empty()) { 102 switch (sort_order) { 103 case eSortOrderNone: { 104 s->PutCString(":\n"); 105 DumpSymbolHeader(s); 106 const_iterator begin = m_symbols.begin(); 107 const_iterator end = m_symbols.end(); 108 for (const_iterator pos = m_symbols.begin(); pos != end; ++pos) { 109 s->Indent(); 110 pos->Dump(s, target, std::distance(begin, pos), name_preference); 111 } 112 } break; 113 114 case eSortOrderByName: { 115 // Although we maintain a lookup by exact name map, the table isn't 116 // sorted by name. So we must make the ordered symbol list up ourselves. 117 s->PutCString(" (sorted by name):\n"); 118 DumpSymbolHeader(s); 119 120 std::multimap<llvm::StringRef, const Symbol *> name_map; 121 for (const_iterator pos = m_symbols.begin(), end = m_symbols.end(); 122 pos != end; ++pos) { 123 const char *name = pos->GetName().AsCString(); 124 if (name && name[0]) 125 name_map.insert(std::make_pair(name, &(*pos))); 126 } 127 128 for (const auto &name_to_symbol : name_map) { 129 const Symbol *symbol = name_to_symbol.second; 130 s->Indent(); 131 symbol->Dump(s, target, symbol - &m_symbols[0], name_preference); 132 } 133 } break; 134 135 case eSortOrderByAddress: 136 s->PutCString(" (sorted by address):\n"); 137 DumpSymbolHeader(s); 138 if (!m_file_addr_to_index_computed) 139 InitAddressIndexes(); 140 const size_t num_entries = m_file_addr_to_index.GetSize(); 141 for (size_t i = 0; i < num_entries; ++i) { 142 s->Indent(); 143 const uint32_t symbol_idx = m_file_addr_to_index.GetEntryRef(i).data; 144 m_symbols[symbol_idx].Dump(s, target, symbol_idx, name_preference); 145 } 146 break; 147 } 148 } else { 149 s->PutCString("\n"); 150 } 151 } 152 153 void Symtab::Dump(Stream *s, Target *target, std::vector<uint32_t> &indexes, 154 Mangled::NamePreference name_preference) const { 155 std::lock_guard<std::recursive_mutex> guard(m_mutex); 156 157 const size_t num_symbols = GetNumSymbols(); 158 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this); 159 s->Indent(); 160 s->Printf("Symtab %" PRIu64 " symbol indexes (%" PRIu64 " symbols total):\n", 161 (uint64_t)indexes.size(), (uint64_t)m_symbols.size()); 162 s->IndentMore(); 163 164 if (!indexes.empty()) { 165 std::vector<uint32_t>::const_iterator pos; 166 std::vector<uint32_t>::const_iterator end = indexes.end(); 167 DumpSymbolHeader(s); 168 for (pos = indexes.begin(); pos != end; ++pos) { 169 size_t idx = *pos; 170 if (idx < num_symbols) { 171 s->Indent(); 172 m_symbols[idx].Dump(s, target, idx, name_preference); 173 } 174 } 175 } 176 s->IndentLess(); 177 } 178 179 void Symtab::DumpSymbolHeader(Stream *s) { 180 s->Indent(" Debug symbol\n"); 181 s->Indent(" |Synthetic symbol\n"); 182 s->Indent(" ||Externally Visible\n"); 183 s->Indent(" |||\n"); 184 s->Indent("Index UserID DSX Type File Address/Value Load " 185 "Address Size Flags Name\n"); 186 s->Indent("------- ------ --- --------------- ------------------ " 187 "------------------ ------------------ ---------- " 188 "----------------------------------\n"); 189 } 190 191 static int CompareSymbolID(const void *key, const void *p) { 192 const user_id_t match_uid = *(const user_id_t *)key; 193 const user_id_t symbol_uid = ((const Symbol *)p)->GetID(); 194 if (match_uid < symbol_uid) 195 return -1; 196 if (match_uid > symbol_uid) 197 return 1; 198 return 0; 199 } 200 201 Symbol *Symtab::FindSymbolByID(lldb::user_id_t symbol_uid) const { 202 std::lock_guard<std::recursive_mutex> guard(m_mutex); 203 204 Symbol *symbol = 205 (Symbol *)::bsearch(&symbol_uid, &m_symbols[0], m_symbols.size(), 206 sizeof(m_symbols[0]), CompareSymbolID); 207 return symbol; 208 } 209 210 Symbol *Symtab::SymbolAtIndex(size_t idx) { 211 // Clients should grab the mutex from this symbol table and lock it manually 212 // when calling this function to avoid performance issues. 213 if (idx < m_symbols.size()) 214 return &m_symbols[idx]; 215 return nullptr; 216 } 217 218 const Symbol *Symtab::SymbolAtIndex(size_t idx) const { 219 // Clients should grab the mutex from this symbol table and lock it manually 220 // when calling this function to avoid performance issues. 221 if (idx < m_symbols.size()) 222 return &m_symbols[idx]; 223 return nullptr; 224 } 225 226 static bool lldb_skip_name(llvm::StringRef mangled, 227 Mangled::ManglingScheme scheme) { 228 switch (scheme) { 229 case Mangled::eManglingSchemeItanium: { 230 if (mangled.size() < 3 || !mangled.startswith("_Z")) 231 return true; 232 233 // Avoid the following types of symbols in the index. 234 switch (mangled[2]) { 235 case 'G': // guard variables 236 case 'T': // virtual tables, VTT structures, typeinfo structures + names 237 case 'Z': // named local entities (if we eventually handle 238 // eSymbolTypeData, we will want this back) 239 return true; 240 241 default: 242 break; 243 } 244 245 // Include this name in the index. 246 return false; 247 } 248 249 // No filters for this scheme yet. Include all names in indexing. 250 case Mangled::eManglingSchemeMSVC: 251 case Mangled::eManglingSchemeRustV0: 252 case Mangled::eManglingSchemeD: 253 return false; 254 255 // Don't try and demangle things we can't categorize. 256 case Mangled::eManglingSchemeNone: 257 return true; 258 } 259 llvm_unreachable("unknown scheme!"); 260 } 261 262 void Symtab::InitNameIndexes() { 263 // Protected function, no need to lock mutex... 264 if (!m_name_indexes_computed) { 265 m_name_indexes_computed = true; 266 ElapsedTime elapsed(m_objfile->GetModule()->GetSymtabIndexTime()); 267 LLDB_SCOPED_TIMER(); 268 269 // Collect all loaded language plugins. 270 std::vector<Language *> languages; 271 Language::ForEach([&languages](Language *l) { 272 languages.push_back(l); 273 return true; 274 }); 275 276 auto &name_to_index = GetNameToSymbolIndexMap(lldb::eFunctionNameTypeNone); 277 auto &basename_to_index = 278 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeBase); 279 auto &method_to_index = 280 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeMethod); 281 auto &selector_to_index = 282 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeSelector); 283 // Create the name index vector to be able to quickly search by name 284 const size_t num_symbols = m_symbols.size(); 285 name_to_index.Reserve(num_symbols); 286 287 // The "const char *" in "class_contexts" and backlog::value_type::second 288 // must come from a ConstString::GetCString() 289 std::set<const char *> class_contexts; 290 std::vector<std::pair<NameToIndexMap::Entry, const char *>> backlog; 291 backlog.reserve(num_symbols / 2); 292 293 // Instantiation of the demangler is expensive, so better use a single one 294 // for all entries during batch processing. 295 RichManglingContext rmc; 296 for (uint32_t value = 0; value < num_symbols; ++value) { 297 Symbol *symbol = &m_symbols[value]; 298 299 // Don't let trampolines get into the lookup by name map If we ever need 300 // the trampoline symbols to be searchable by name we can remove this and 301 // then possibly add a new bool to any of the Symtab functions that 302 // lookup symbols by name to indicate if they want trampolines. We also 303 // don't want any synthetic symbols with auto generated names in the 304 // name lookups. 305 if (symbol->IsTrampoline() || symbol->IsSyntheticWithAutoGeneratedName()) 306 continue; 307 308 // If the symbol's name string matched a Mangled::ManglingScheme, it is 309 // stored in the mangled field. 310 Mangled &mangled = symbol->GetMangled(); 311 if (ConstString name = mangled.GetMangledName()) { 312 name_to_index.Append(name, value); 313 314 if (symbol->ContainsLinkerAnnotations()) { 315 // If the symbol has linker annotations, also add the version without 316 // the annotations. 317 ConstString stripped = ConstString( 318 m_objfile->StripLinkerSymbolAnnotations(name.GetStringRef())); 319 name_to_index.Append(stripped, value); 320 } 321 322 const SymbolType type = symbol->GetType(); 323 if (type == eSymbolTypeCode || type == eSymbolTypeResolver) { 324 if (mangled.DemangleWithRichManglingInfo(rmc, lldb_skip_name)) 325 RegisterMangledNameEntry(value, class_contexts, backlog, rmc); 326 } 327 } 328 329 // Symbol name strings that didn't match a Mangled::ManglingScheme, are 330 // stored in the demangled field. 331 if (ConstString name = mangled.GetDemangledName()) { 332 name_to_index.Append(name, value); 333 334 if (symbol->ContainsLinkerAnnotations()) { 335 // If the symbol has linker annotations, also add the version without 336 // the annotations. 337 name = ConstString( 338 m_objfile->StripLinkerSymbolAnnotations(name.GetStringRef())); 339 name_to_index.Append(name, value); 340 } 341 342 // If the demangled name turns out to be an ObjC name, and is a category 343 // name, add the version without categories to the index too. 344 for (Language *lang : languages) { 345 for (auto variant : lang->GetMethodNameVariants(name)) { 346 if (variant.GetType() & lldb::eFunctionNameTypeSelector) 347 selector_to_index.Append(variant.GetName(), value); 348 else if (variant.GetType() & lldb::eFunctionNameTypeFull) 349 name_to_index.Append(variant.GetName(), value); 350 else if (variant.GetType() & lldb::eFunctionNameTypeMethod) 351 method_to_index.Append(variant.GetName(), value); 352 else if (variant.GetType() & lldb::eFunctionNameTypeBase) 353 basename_to_index.Append(variant.GetName(), value); 354 } 355 } 356 } 357 } 358 359 for (const auto &record : backlog) { 360 RegisterBacklogEntry(record.first, record.second, class_contexts); 361 } 362 363 name_to_index.Sort(); 364 name_to_index.SizeToFit(); 365 selector_to_index.Sort(); 366 selector_to_index.SizeToFit(); 367 basename_to_index.Sort(); 368 basename_to_index.SizeToFit(); 369 method_to_index.Sort(); 370 method_to_index.SizeToFit(); 371 } 372 } 373 374 void Symtab::RegisterMangledNameEntry( 375 uint32_t value, std::set<const char *> &class_contexts, 376 std::vector<std::pair<NameToIndexMap::Entry, const char *>> &backlog, 377 RichManglingContext &rmc) { 378 // Only register functions that have a base name. 379 rmc.ParseFunctionBaseName(); 380 llvm::StringRef base_name = rmc.GetBufferRef(); 381 if (base_name.empty()) 382 return; 383 384 // The base name will be our entry's name. 385 NameToIndexMap::Entry entry(ConstString(base_name), value); 386 387 rmc.ParseFunctionDeclContextName(); 388 llvm::StringRef decl_context = rmc.GetBufferRef(); 389 390 // Register functions with no context. 391 if (decl_context.empty()) { 392 // This has to be a basename 393 auto &basename_to_index = 394 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeBase); 395 basename_to_index.Append(entry); 396 // If there is no context (no namespaces or class scopes that come before 397 // the function name) then this also could be a fullname. 398 auto &name_to_index = GetNameToSymbolIndexMap(lldb::eFunctionNameTypeNone); 399 name_to_index.Append(entry); 400 return; 401 } 402 403 // Make sure we have a pool-string pointer and see if we already know the 404 // context name. 405 const char *decl_context_ccstr = ConstString(decl_context).GetCString(); 406 auto it = class_contexts.find(decl_context_ccstr); 407 408 auto &method_to_index = 409 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeMethod); 410 // Register constructors and destructors. They are methods and create 411 // declaration contexts. 412 if (rmc.IsCtorOrDtor()) { 413 method_to_index.Append(entry); 414 if (it == class_contexts.end()) 415 class_contexts.insert(it, decl_context_ccstr); 416 return; 417 } 418 419 // Register regular methods with a known declaration context. 420 if (it != class_contexts.end()) { 421 method_to_index.Append(entry); 422 return; 423 } 424 425 // Regular methods in unknown declaration contexts are put to the backlog. We 426 // will revisit them once we processed all remaining symbols. 427 backlog.push_back(std::make_pair(entry, decl_context_ccstr)); 428 } 429 430 void Symtab::RegisterBacklogEntry( 431 const NameToIndexMap::Entry &entry, const char *decl_context, 432 const std::set<const char *> &class_contexts) { 433 auto &method_to_index = 434 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeMethod); 435 auto it = class_contexts.find(decl_context); 436 if (it != class_contexts.end()) { 437 method_to_index.Append(entry); 438 } else { 439 // If we got here, we have something that had a context (was inside 440 // a namespace or class) yet we don't know the entry 441 method_to_index.Append(entry); 442 auto &basename_to_index = 443 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeBase); 444 basename_to_index.Append(entry); 445 } 446 } 447 448 void Symtab::PreloadSymbols() { 449 std::lock_guard<std::recursive_mutex> guard(m_mutex); 450 InitNameIndexes(); 451 } 452 453 void Symtab::AppendSymbolNamesToMap(const IndexCollection &indexes, 454 bool add_demangled, bool add_mangled, 455 NameToIndexMap &name_to_index_map) const { 456 LLDB_SCOPED_TIMER(); 457 if (add_demangled || add_mangled) { 458 std::lock_guard<std::recursive_mutex> guard(m_mutex); 459 460 // Create the name index vector to be able to quickly search by name 461 const size_t num_indexes = indexes.size(); 462 for (size_t i = 0; i < num_indexes; ++i) { 463 uint32_t value = indexes[i]; 464 assert(i < m_symbols.size()); 465 const Symbol *symbol = &m_symbols[value]; 466 467 const Mangled &mangled = symbol->GetMangled(); 468 if (add_demangled) { 469 if (ConstString name = mangled.GetDemangledName()) 470 name_to_index_map.Append(name, value); 471 } 472 473 if (add_mangled) { 474 if (ConstString name = mangled.GetMangledName()) 475 name_to_index_map.Append(name, value); 476 } 477 } 478 } 479 } 480 481 uint32_t Symtab::AppendSymbolIndexesWithType(SymbolType symbol_type, 482 std::vector<uint32_t> &indexes, 483 uint32_t start_idx, 484 uint32_t end_index) const { 485 std::lock_guard<std::recursive_mutex> guard(m_mutex); 486 487 uint32_t prev_size = indexes.size(); 488 489 const uint32_t count = std::min<uint32_t>(m_symbols.size(), end_index); 490 491 for (uint32_t i = start_idx; i < count; ++i) { 492 if (symbol_type == eSymbolTypeAny || m_symbols[i].GetType() == symbol_type) 493 indexes.push_back(i); 494 } 495 496 return indexes.size() - prev_size; 497 } 498 499 uint32_t Symtab::AppendSymbolIndexesWithTypeAndFlagsValue( 500 SymbolType symbol_type, uint32_t flags_value, 501 std::vector<uint32_t> &indexes, uint32_t start_idx, 502 uint32_t end_index) const { 503 std::lock_guard<std::recursive_mutex> guard(m_mutex); 504 505 uint32_t prev_size = indexes.size(); 506 507 const uint32_t count = std::min<uint32_t>(m_symbols.size(), end_index); 508 509 for (uint32_t i = start_idx; i < count; ++i) { 510 if ((symbol_type == eSymbolTypeAny || 511 m_symbols[i].GetType() == symbol_type) && 512 m_symbols[i].GetFlags() == flags_value) 513 indexes.push_back(i); 514 } 515 516 return indexes.size() - prev_size; 517 } 518 519 uint32_t Symtab::AppendSymbolIndexesWithType(SymbolType symbol_type, 520 Debug symbol_debug_type, 521 Visibility symbol_visibility, 522 std::vector<uint32_t> &indexes, 523 uint32_t start_idx, 524 uint32_t end_index) const { 525 std::lock_guard<std::recursive_mutex> guard(m_mutex); 526 527 uint32_t prev_size = indexes.size(); 528 529 const uint32_t count = std::min<uint32_t>(m_symbols.size(), end_index); 530 531 for (uint32_t i = start_idx; i < count; ++i) { 532 if (symbol_type == eSymbolTypeAny || 533 m_symbols[i].GetType() == symbol_type) { 534 if (CheckSymbolAtIndex(i, symbol_debug_type, symbol_visibility)) 535 indexes.push_back(i); 536 } 537 } 538 539 return indexes.size() - prev_size; 540 } 541 542 uint32_t Symtab::GetIndexForSymbol(const Symbol *symbol) const { 543 if (!m_symbols.empty()) { 544 const Symbol *first_symbol = &m_symbols[0]; 545 if (symbol >= first_symbol && symbol < first_symbol + m_symbols.size()) 546 return symbol - first_symbol; 547 } 548 return UINT32_MAX; 549 } 550 551 struct SymbolSortInfo { 552 const bool sort_by_load_addr; 553 const Symbol *symbols; 554 }; 555 556 namespace { 557 struct SymbolIndexComparator { 558 const std::vector<Symbol> &symbols; 559 std::vector<lldb::addr_t> &addr_cache; 560 561 // Getting from the symbol to the Address to the File Address involves some 562 // work. Since there are potentially many symbols here, and we're using this 563 // for sorting so we're going to be computing the address many times, cache 564 // that in addr_cache. The array passed in has to be the same size as the 565 // symbols array passed into the member variable symbols, and should be 566 // initialized with LLDB_INVALID_ADDRESS. 567 // NOTE: You have to make addr_cache externally and pass it in because 568 // std::stable_sort 569 // makes copies of the comparator it is initially passed in, and you end up 570 // spending huge amounts of time copying this array... 571 572 SymbolIndexComparator(const std::vector<Symbol> &s, 573 std::vector<lldb::addr_t> &a) 574 : symbols(s), addr_cache(a) { 575 assert(symbols.size() == addr_cache.size()); 576 } 577 bool operator()(uint32_t index_a, uint32_t index_b) { 578 addr_t value_a = addr_cache[index_a]; 579 if (value_a == LLDB_INVALID_ADDRESS) { 580 value_a = symbols[index_a].GetAddressRef().GetFileAddress(); 581 addr_cache[index_a] = value_a; 582 } 583 584 addr_t value_b = addr_cache[index_b]; 585 if (value_b == LLDB_INVALID_ADDRESS) { 586 value_b = symbols[index_b].GetAddressRef().GetFileAddress(); 587 addr_cache[index_b] = value_b; 588 } 589 590 if (value_a == value_b) { 591 // The if the values are equal, use the original symbol user ID 592 lldb::user_id_t uid_a = symbols[index_a].GetID(); 593 lldb::user_id_t uid_b = symbols[index_b].GetID(); 594 if (uid_a < uid_b) 595 return true; 596 if (uid_a > uid_b) 597 return false; 598 return false; 599 } else if (value_a < value_b) 600 return true; 601 602 return false; 603 } 604 }; 605 } 606 607 void Symtab::SortSymbolIndexesByValue(std::vector<uint32_t> &indexes, 608 bool remove_duplicates) const { 609 std::lock_guard<std::recursive_mutex> guard(m_mutex); 610 LLDB_SCOPED_TIMER(); 611 // No need to sort if we have zero or one items... 612 if (indexes.size() <= 1) 613 return; 614 615 // Sort the indexes in place using std::stable_sort. 616 // NOTE: The use of std::stable_sort instead of llvm::sort here is strictly 617 // for performance, not correctness. The indexes vector tends to be "close" 618 // to sorted, which the stable sort handles better. 619 620 std::vector<lldb::addr_t> addr_cache(m_symbols.size(), LLDB_INVALID_ADDRESS); 621 622 SymbolIndexComparator comparator(m_symbols, addr_cache); 623 std::stable_sort(indexes.begin(), indexes.end(), comparator); 624 625 // Remove any duplicates if requested 626 if (remove_duplicates) { 627 auto last = std::unique(indexes.begin(), indexes.end()); 628 indexes.erase(last, indexes.end()); 629 } 630 } 631 632 uint32_t Symtab::GetNameIndexes(ConstString symbol_name, 633 std::vector<uint32_t> &indexes) { 634 auto &name_to_index = GetNameToSymbolIndexMap(lldb::eFunctionNameTypeNone); 635 const uint32_t count = name_to_index.GetValues(symbol_name, indexes); 636 if (count) 637 return count; 638 // Synthetic symbol names are not added to the name indexes, but they start 639 // with a prefix and end with a the symbol UserID. This allows users to find 640 // these symbols without having to add them to the name indexes. These 641 // queries will not happen very often since the names don't mean anything, so 642 // performance is not paramount in this case. 643 llvm::StringRef name = symbol_name.GetStringRef(); 644 // String the synthetic prefix if the name starts with it. 645 if (!name.consume_front(Symbol::GetSyntheticSymbolPrefix())) 646 return 0; // Not a synthetic symbol name 647 648 // Extract the user ID from the symbol name 649 unsigned long long uid = 0; 650 if (getAsUnsignedInteger(name, /*Radix=*/10, uid)) 651 return 0; // Failed to extract the user ID as an integer 652 Symbol *symbol = FindSymbolByID(uid); 653 if (symbol == nullptr) 654 return 0; 655 const uint32_t symbol_idx = GetIndexForSymbol(symbol); 656 if (symbol_idx == UINT32_MAX) 657 return 0; 658 indexes.push_back(symbol_idx); 659 return 1; 660 } 661 662 uint32_t Symtab::AppendSymbolIndexesWithName(ConstString symbol_name, 663 std::vector<uint32_t> &indexes) { 664 std::lock_guard<std::recursive_mutex> guard(m_mutex); 665 666 LLDB_SCOPED_TIMER(); 667 if (symbol_name) { 668 if (!m_name_indexes_computed) 669 InitNameIndexes(); 670 671 return GetNameIndexes(symbol_name, indexes); 672 } 673 return 0; 674 } 675 676 uint32_t Symtab::AppendSymbolIndexesWithName(ConstString symbol_name, 677 Debug symbol_debug_type, 678 Visibility symbol_visibility, 679 std::vector<uint32_t> &indexes) { 680 std::lock_guard<std::recursive_mutex> guard(m_mutex); 681 682 LLDB_SCOPED_TIMER(); 683 if (symbol_name) { 684 const size_t old_size = indexes.size(); 685 if (!m_name_indexes_computed) 686 InitNameIndexes(); 687 688 std::vector<uint32_t> all_name_indexes; 689 const size_t name_match_count = 690 GetNameIndexes(symbol_name, all_name_indexes); 691 for (size_t i = 0; i < name_match_count; ++i) { 692 if (CheckSymbolAtIndex(all_name_indexes[i], symbol_debug_type, 693 symbol_visibility)) 694 indexes.push_back(all_name_indexes[i]); 695 } 696 return indexes.size() - old_size; 697 } 698 return 0; 699 } 700 701 uint32_t 702 Symtab::AppendSymbolIndexesWithNameAndType(ConstString symbol_name, 703 SymbolType symbol_type, 704 std::vector<uint32_t> &indexes) { 705 std::lock_guard<std::recursive_mutex> guard(m_mutex); 706 707 if (AppendSymbolIndexesWithName(symbol_name, indexes) > 0) { 708 std::vector<uint32_t>::iterator pos = indexes.begin(); 709 while (pos != indexes.end()) { 710 if (symbol_type == eSymbolTypeAny || 711 m_symbols[*pos].GetType() == symbol_type) 712 ++pos; 713 else 714 pos = indexes.erase(pos); 715 } 716 } 717 return indexes.size(); 718 } 719 720 uint32_t Symtab::AppendSymbolIndexesWithNameAndType( 721 ConstString symbol_name, SymbolType symbol_type, 722 Debug symbol_debug_type, Visibility symbol_visibility, 723 std::vector<uint32_t> &indexes) { 724 std::lock_guard<std::recursive_mutex> guard(m_mutex); 725 726 if (AppendSymbolIndexesWithName(symbol_name, symbol_debug_type, 727 symbol_visibility, indexes) > 0) { 728 std::vector<uint32_t>::iterator pos = indexes.begin(); 729 while (pos != indexes.end()) { 730 if (symbol_type == eSymbolTypeAny || 731 m_symbols[*pos].GetType() == symbol_type) 732 ++pos; 733 else 734 pos = indexes.erase(pos); 735 } 736 } 737 return indexes.size(); 738 } 739 740 uint32_t Symtab::AppendSymbolIndexesMatchingRegExAndType( 741 const RegularExpression ®exp, SymbolType symbol_type, 742 std::vector<uint32_t> &indexes) { 743 std::lock_guard<std::recursive_mutex> guard(m_mutex); 744 745 uint32_t prev_size = indexes.size(); 746 uint32_t sym_end = m_symbols.size(); 747 748 for (uint32_t i = 0; i < sym_end; i++) { 749 if (symbol_type == eSymbolTypeAny || 750 m_symbols[i].GetType() == symbol_type) { 751 const char *name = m_symbols[i].GetName().AsCString(); 752 if (name) { 753 if (regexp.Execute(name)) 754 indexes.push_back(i); 755 } 756 } 757 } 758 return indexes.size() - prev_size; 759 } 760 761 uint32_t Symtab::AppendSymbolIndexesMatchingRegExAndType( 762 const RegularExpression ®exp, SymbolType symbol_type, 763 Debug symbol_debug_type, Visibility symbol_visibility, 764 std::vector<uint32_t> &indexes) { 765 std::lock_guard<std::recursive_mutex> guard(m_mutex); 766 767 uint32_t prev_size = indexes.size(); 768 uint32_t sym_end = m_symbols.size(); 769 770 for (uint32_t i = 0; i < sym_end; i++) { 771 if (symbol_type == eSymbolTypeAny || 772 m_symbols[i].GetType() == symbol_type) { 773 if (!CheckSymbolAtIndex(i, symbol_debug_type, symbol_visibility)) 774 continue; 775 776 const char *name = m_symbols[i].GetName().AsCString(); 777 if (name) { 778 if (regexp.Execute(name)) 779 indexes.push_back(i); 780 } 781 } 782 } 783 return indexes.size() - prev_size; 784 } 785 786 Symbol *Symtab::FindSymbolWithType(SymbolType symbol_type, 787 Debug symbol_debug_type, 788 Visibility symbol_visibility, 789 uint32_t &start_idx) { 790 std::lock_guard<std::recursive_mutex> guard(m_mutex); 791 792 const size_t count = m_symbols.size(); 793 for (size_t idx = start_idx; idx < count; ++idx) { 794 if (symbol_type == eSymbolTypeAny || 795 m_symbols[idx].GetType() == symbol_type) { 796 if (CheckSymbolAtIndex(idx, symbol_debug_type, symbol_visibility)) { 797 start_idx = idx; 798 return &m_symbols[idx]; 799 } 800 } 801 } 802 return nullptr; 803 } 804 805 void 806 Symtab::FindAllSymbolsWithNameAndType(ConstString name, 807 SymbolType symbol_type, 808 std::vector<uint32_t> &symbol_indexes) { 809 std::lock_guard<std::recursive_mutex> guard(m_mutex); 810 811 LLDB_SCOPED_TIMER(); 812 // Initialize all of the lookup by name indexes before converting NAME to a 813 // uniqued string NAME_STR below. 814 if (!m_name_indexes_computed) 815 InitNameIndexes(); 816 817 if (name) { 818 // The string table did have a string that matched, but we need to check 819 // the symbols and match the symbol_type if any was given. 820 AppendSymbolIndexesWithNameAndType(name, symbol_type, symbol_indexes); 821 } 822 } 823 824 void Symtab::FindAllSymbolsWithNameAndType( 825 ConstString name, SymbolType symbol_type, Debug symbol_debug_type, 826 Visibility symbol_visibility, std::vector<uint32_t> &symbol_indexes) { 827 std::lock_guard<std::recursive_mutex> guard(m_mutex); 828 829 LLDB_SCOPED_TIMER(); 830 // Initialize all of the lookup by name indexes before converting NAME to a 831 // uniqued string NAME_STR below. 832 if (!m_name_indexes_computed) 833 InitNameIndexes(); 834 835 if (name) { 836 // The string table did have a string that matched, but we need to check 837 // the symbols and match the symbol_type if any was given. 838 AppendSymbolIndexesWithNameAndType(name, symbol_type, symbol_debug_type, 839 symbol_visibility, symbol_indexes); 840 } 841 } 842 843 void Symtab::FindAllSymbolsMatchingRexExAndType( 844 const RegularExpression ®ex, SymbolType symbol_type, 845 Debug symbol_debug_type, Visibility symbol_visibility, 846 std::vector<uint32_t> &symbol_indexes) { 847 std::lock_guard<std::recursive_mutex> guard(m_mutex); 848 849 AppendSymbolIndexesMatchingRegExAndType(regex, symbol_type, symbol_debug_type, 850 symbol_visibility, symbol_indexes); 851 } 852 853 Symbol *Symtab::FindFirstSymbolWithNameAndType(ConstString name, 854 SymbolType symbol_type, 855 Debug symbol_debug_type, 856 Visibility symbol_visibility) { 857 std::lock_guard<std::recursive_mutex> guard(m_mutex); 858 LLDB_SCOPED_TIMER(); 859 if (!m_name_indexes_computed) 860 InitNameIndexes(); 861 862 if (name) { 863 std::vector<uint32_t> matching_indexes; 864 // The string table did have a string that matched, but we need to check 865 // the symbols and match the symbol_type if any was given. 866 if (AppendSymbolIndexesWithNameAndType(name, symbol_type, symbol_debug_type, 867 symbol_visibility, 868 matching_indexes)) { 869 std::vector<uint32_t>::const_iterator pos, end = matching_indexes.end(); 870 for (pos = matching_indexes.begin(); pos != end; ++pos) { 871 Symbol *symbol = SymbolAtIndex(*pos); 872 873 if (symbol->Compare(name, symbol_type)) 874 return symbol; 875 } 876 } 877 } 878 return nullptr; 879 } 880 881 typedef struct { 882 const Symtab *symtab; 883 const addr_t file_addr; 884 Symbol *match_symbol; 885 const uint32_t *match_index_ptr; 886 addr_t match_offset; 887 } SymbolSearchInfo; 888 889 // Add all the section file start address & size to the RangeVector, recusively 890 // adding any children sections. 891 static void AddSectionsToRangeMap(SectionList *sectlist, 892 RangeVector<addr_t, addr_t> §ion_ranges) { 893 const int num_sections = sectlist->GetNumSections(0); 894 for (int i = 0; i < num_sections; i++) { 895 SectionSP sect_sp = sectlist->GetSectionAtIndex(i); 896 if (sect_sp) { 897 SectionList &child_sectlist = sect_sp->GetChildren(); 898 899 // If this section has children, add the children to the RangeVector. 900 // Else add this section to the RangeVector. 901 if (child_sectlist.GetNumSections(0) > 0) { 902 AddSectionsToRangeMap(&child_sectlist, section_ranges); 903 } else { 904 size_t size = sect_sp->GetByteSize(); 905 if (size > 0) { 906 addr_t base_addr = sect_sp->GetFileAddress(); 907 RangeVector<addr_t, addr_t>::Entry entry; 908 entry.SetRangeBase(base_addr); 909 entry.SetByteSize(size); 910 section_ranges.Append(entry); 911 } 912 } 913 } 914 } 915 } 916 917 void Symtab::InitAddressIndexes() { 918 // Protected function, no need to lock mutex... 919 if (!m_file_addr_to_index_computed && !m_symbols.empty()) { 920 m_file_addr_to_index_computed = true; 921 922 FileRangeToIndexMap::Entry entry; 923 const_iterator begin = m_symbols.begin(); 924 const_iterator end = m_symbols.end(); 925 for (const_iterator pos = m_symbols.begin(); pos != end; ++pos) { 926 if (pos->ValueIsAddress()) { 927 entry.SetRangeBase(pos->GetAddressRef().GetFileAddress()); 928 entry.SetByteSize(pos->GetByteSize()); 929 entry.data = std::distance(begin, pos); 930 m_file_addr_to_index.Append(entry); 931 } 932 } 933 const size_t num_entries = m_file_addr_to_index.GetSize(); 934 if (num_entries > 0) { 935 m_file_addr_to_index.Sort(); 936 937 // Create a RangeVector with the start & size of all the sections for 938 // this objfile. We'll need to check this for any FileRangeToIndexMap 939 // entries with an uninitialized size, which could potentially be a large 940 // number so reconstituting the weak pointer is busywork when it is 941 // invariant information. 942 SectionList *sectlist = m_objfile->GetSectionList(); 943 RangeVector<addr_t, addr_t> section_ranges; 944 if (sectlist) { 945 AddSectionsToRangeMap(sectlist, section_ranges); 946 section_ranges.Sort(); 947 } 948 949 // Iterate through the FileRangeToIndexMap and fill in the size for any 950 // entries that didn't already have a size from the Symbol (e.g. if we 951 // have a plain linker symbol with an address only, instead of debug info 952 // where we get an address and a size and a type, etc.) 953 for (size_t i = 0; i < num_entries; i++) { 954 FileRangeToIndexMap::Entry *entry = 955 m_file_addr_to_index.GetMutableEntryAtIndex(i); 956 if (entry->GetByteSize() == 0) { 957 addr_t curr_base_addr = entry->GetRangeBase(); 958 const RangeVector<addr_t, addr_t>::Entry *containing_section = 959 section_ranges.FindEntryThatContains(curr_base_addr); 960 961 // Use the end of the section as the default max size of the symbol 962 addr_t sym_size = 0; 963 if (containing_section) { 964 sym_size = 965 containing_section->GetByteSize() - 966 (entry->GetRangeBase() - containing_section->GetRangeBase()); 967 } 968 969 for (size_t j = i; j < num_entries; j++) { 970 FileRangeToIndexMap::Entry *next_entry = 971 m_file_addr_to_index.GetMutableEntryAtIndex(j); 972 addr_t next_base_addr = next_entry->GetRangeBase(); 973 if (next_base_addr > curr_base_addr) { 974 addr_t size_to_next_symbol = next_base_addr - curr_base_addr; 975 976 // Take the difference between this symbol and the next one as 977 // its size, if it is less than the size of the section. 978 if (sym_size == 0 || size_to_next_symbol < sym_size) { 979 sym_size = size_to_next_symbol; 980 } 981 break; 982 } 983 } 984 985 if (sym_size > 0) { 986 entry->SetByteSize(sym_size); 987 Symbol &symbol = m_symbols[entry->data]; 988 symbol.SetByteSize(sym_size); 989 symbol.SetSizeIsSynthesized(true); 990 } 991 } 992 } 993 994 // Sort again in case the range size changes the ordering 995 m_file_addr_to_index.Sort(); 996 } 997 } 998 } 999 1000 void Symtab::CalculateSymbolSizes() { 1001 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1002 // Size computation happens inside InitAddressIndexes. 1003 InitAddressIndexes(); 1004 } 1005 1006 Symbol *Symtab::FindSymbolAtFileAddress(addr_t file_addr) { 1007 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1008 if (!m_file_addr_to_index_computed) 1009 InitAddressIndexes(); 1010 1011 const FileRangeToIndexMap::Entry *entry = 1012 m_file_addr_to_index.FindEntryStartsAt(file_addr); 1013 if (entry) { 1014 Symbol *symbol = SymbolAtIndex(entry->data); 1015 if (symbol->GetFileAddress() == file_addr) 1016 return symbol; 1017 } 1018 return nullptr; 1019 } 1020 1021 Symbol *Symtab::FindSymbolContainingFileAddress(addr_t file_addr) { 1022 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1023 1024 if (!m_file_addr_to_index_computed) 1025 InitAddressIndexes(); 1026 1027 const FileRangeToIndexMap::Entry *entry = 1028 m_file_addr_to_index.FindEntryThatContains(file_addr); 1029 if (entry) { 1030 Symbol *symbol = SymbolAtIndex(entry->data); 1031 if (symbol->ContainsFileAddress(file_addr)) 1032 return symbol; 1033 } 1034 return nullptr; 1035 } 1036 1037 void Symtab::ForEachSymbolContainingFileAddress( 1038 addr_t file_addr, std::function<bool(Symbol *)> const &callback) { 1039 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1040 1041 if (!m_file_addr_to_index_computed) 1042 InitAddressIndexes(); 1043 1044 std::vector<uint32_t> all_addr_indexes; 1045 1046 // Get all symbols with file_addr 1047 const size_t addr_match_count = 1048 m_file_addr_to_index.FindEntryIndexesThatContain(file_addr, 1049 all_addr_indexes); 1050 1051 for (size_t i = 0; i < addr_match_count; ++i) { 1052 Symbol *symbol = SymbolAtIndex(all_addr_indexes[i]); 1053 if (symbol->ContainsFileAddress(file_addr)) { 1054 if (!callback(symbol)) 1055 break; 1056 } 1057 } 1058 } 1059 1060 void Symtab::SymbolIndicesToSymbolContextList( 1061 std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list) { 1062 // No need to protect this call using m_mutex all other method calls are 1063 // already thread safe. 1064 1065 const bool merge_symbol_into_function = true; 1066 size_t num_indices = symbol_indexes.size(); 1067 if (num_indices > 0) { 1068 SymbolContext sc; 1069 sc.module_sp = m_objfile->GetModule(); 1070 for (size_t i = 0; i < num_indices; i++) { 1071 sc.symbol = SymbolAtIndex(symbol_indexes[i]); 1072 if (sc.symbol) 1073 sc_list.AppendIfUnique(sc, merge_symbol_into_function); 1074 } 1075 } 1076 } 1077 1078 void Symtab::FindFunctionSymbols(ConstString name, uint32_t name_type_mask, 1079 SymbolContextList &sc_list) { 1080 std::vector<uint32_t> symbol_indexes; 1081 1082 // eFunctionNameTypeAuto should be pre-resolved by a call to 1083 // Module::LookupInfo::LookupInfo() 1084 assert((name_type_mask & eFunctionNameTypeAuto) == 0); 1085 1086 if (name_type_mask & (eFunctionNameTypeBase | eFunctionNameTypeFull)) { 1087 std::vector<uint32_t> temp_symbol_indexes; 1088 FindAllSymbolsWithNameAndType(name, eSymbolTypeAny, temp_symbol_indexes); 1089 1090 unsigned temp_symbol_indexes_size = temp_symbol_indexes.size(); 1091 if (temp_symbol_indexes_size > 0) { 1092 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1093 for (unsigned i = 0; i < temp_symbol_indexes_size; i++) { 1094 SymbolContext sym_ctx; 1095 sym_ctx.symbol = SymbolAtIndex(temp_symbol_indexes[i]); 1096 if (sym_ctx.symbol) { 1097 switch (sym_ctx.symbol->GetType()) { 1098 case eSymbolTypeCode: 1099 case eSymbolTypeResolver: 1100 case eSymbolTypeReExported: 1101 case eSymbolTypeAbsolute: 1102 symbol_indexes.push_back(temp_symbol_indexes[i]); 1103 break; 1104 default: 1105 break; 1106 } 1107 } 1108 } 1109 } 1110 } 1111 1112 if (!m_name_indexes_computed) 1113 InitNameIndexes(); 1114 1115 for (lldb::FunctionNameType type : 1116 {lldb::eFunctionNameTypeBase, lldb::eFunctionNameTypeMethod, 1117 lldb::eFunctionNameTypeSelector}) { 1118 if (name_type_mask & type) { 1119 auto map = GetNameToSymbolIndexMap(type); 1120 1121 const UniqueCStringMap<uint32_t>::Entry *match; 1122 for (match = map.FindFirstValueForName(name); match != nullptr; 1123 match = map.FindNextValueForName(match)) { 1124 symbol_indexes.push_back(match->value); 1125 } 1126 } 1127 } 1128 1129 if (!symbol_indexes.empty()) { 1130 llvm::sort(symbol_indexes.begin(), symbol_indexes.end()); 1131 symbol_indexes.erase( 1132 std::unique(symbol_indexes.begin(), symbol_indexes.end()), 1133 symbol_indexes.end()); 1134 SymbolIndicesToSymbolContextList(symbol_indexes, sc_list); 1135 } 1136 } 1137 1138 const Symbol *Symtab::GetParent(Symbol *child_symbol) const { 1139 uint32_t child_idx = GetIndexForSymbol(child_symbol); 1140 if (child_idx != UINT32_MAX && child_idx > 0) { 1141 for (uint32_t idx = child_idx - 1; idx != UINT32_MAX; --idx) { 1142 const Symbol *symbol = SymbolAtIndex(idx); 1143 const uint32_t sibling_idx = symbol->GetSiblingIndex(); 1144 if (sibling_idx != UINT32_MAX && sibling_idx > child_idx) 1145 return symbol; 1146 } 1147 } 1148 return nullptr; 1149 } 1150