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