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