1366 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 9#include <map>10#include <set>11 12#include "lldb/Core/DataFileCache.h"13#include "lldb/Core/Module.h"14#include "lldb/Core/RichManglingContext.h"15#include "lldb/Core/Section.h"16#include "lldb/Symbol/ObjectFile.h"17#include "lldb/Symbol/Symbol.h"18#include "lldb/Symbol/SymbolContext.h"19#include "lldb/Symbol/Symtab.h"20#include "lldb/Target/Language.h"21#include "lldb/Utility/DataEncoder.h"22#include "lldb/Utility/Endian.h"23#include "lldb/Utility/RegularExpression.h"24#include "lldb/Utility/Stream.h"25#include "lldb/Utility/Timer.h"26 27#include "llvm/ADT/ArrayRef.h"28#include "llvm/ADT/StringRef.h"29#include "llvm/Support/DJB.h"30 31using namespace lldb;32using namespace lldb_private;33 34Symtab::Symtab(ObjectFile *objfile)35 : m_objfile(objfile), m_symbols(), m_file_addr_to_index(*this),36 m_name_to_symbol_indices(), m_mutex(),37 m_file_addr_to_index_computed(false), m_name_indexes_computed(false),38 m_loaded_from_cache(false), m_saved_to_cache(false) {39 m_name_to_symbol_indices.emplace(std::make_pair(40 lldb::eFunctionNameTypeNone, UniqueCStringMap<uint32_t>()));41 m_name_to_symbol_indices.emplace(std::make_pair(42 lldb::eFunctionNameTypeBase, UniqueCStringMap<uint32_t>()));43 m_name_to_symbol_indices.emplace(std::make_pair(44 lldb::eFunctionNameTypeMethod, UniqueCStringMap<uint32_t>()));45 m_name_to_symbol_indices.emplace(std::make_pair(46 lldb::eFunctionNameTypeSelector, UniqueCStringMap<uint32_t>()));47}48 49Symtab::~Symtab() = default;50 51void Symtab::Reserve(size_t count) {52 // Clients should grab the mutex from this symbol table and lock it manually53 // when calling this function to avoid performance issues.54 m_symbols.reserve(count);55}56 57Symbol *Symtab::Resize(size_t count) {58 // Clients should grab the mutex from this symbol table and lock it manually59 // when calling this function to avoid performance issues.60 m_symbols.resize(count);61 return m_symbols.empty() ? nullptr : &m_symbols[0];62}63 64uint32_t Symtab::AddSymbol(const Symbol &symbol) {65 // Clients should grab the mutex from this symbol table and lock it manually66 // when calling this function to avoid performance issues.67 uint32_t symbol_idx = m_symbols.size();68 auto &name_to_index = GetNameToSymbolIndexMap(lldb::eFunctionNameTypeNone);69 name_to_index.Clear();70 m_file_addr_to_index.Clear();71 m_symbols.push_back(symbol);72 m_file_addr_to_index_computed = false;73 m_name_indexes_computed = false;74 return symbol_idx;75}76 77size_t Symtab::GetNumSymbols() const {78 std::lock_guard<std::recursive_mutex> guard(m_mutex);79 return m_symbols.size();80}81 82void Symtab::SectionFileAddressesChanged() {83 m_file_addr_to_index.Clear();84 m_file_addr_to_index_computed = false;85}86 87void Symtab::Dump(Stream *s, Target *target, SortOrder sort_order,88 Mangled::NamePreference name_preference) {89 std::lock_guard<std::recursive_mutex> guard(m_mutex);90 91 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);92 s->Indent();93 const FileSpec &file_spec = m_objfile->GetFileSpec();94 const char *object_name = nullptr;95 if (m_objfile->GetModule())96 object_name = m_objfile->GetModule()->GetObjectName().GetCString();97 98 if (file_spec)99 s->Printf("Symtab, file = %s%s%s%s, num_symbols = %" PRIu64,100 file_spec.GetPath().c_str(), object_name ? "(" : "",101 object_name ? object_name : "", object_name ? ")" : "",102 (uint64_t)m_symbols.size());103 else104 s->Printf("Symtab, num_symbols = %" PRIu64 "", (uint64_t)m_symbols.size());105 106 if (!m_symbols.empty()) {107 switch (sort_order) {108 case eSortOrderNone: {109 s->PutCString(":\n");110 DumpSymbolHeader(s);111 const_iterator begin = m_symbols.begin();112 const_iterator end = m_symbols.end();113 for (const_iterator pos = m_symbols.begin(); pos != end; ++pos) {114 s->Indent();115 pos->Dump(s, target, std::distance(begin, pos), name_preference);116 }117 }118 break;119 120 case eSortOrderByName: {121 // Although we maintain a lookup by exact name map, the table isn't122 // sorted by name. So we must make the ordered symbol list up ourselves.123 s->PutCString(" (sorted by name):\n");124 DumpSymbolHeader(s);125 126 std::multimap<llvm::StringRef, const Symbol *> name_map;127 for (const Symbol &symbol : m_symbols)128 name_map.emplace(symbol.GetName().GetStringRef(), &symbol);129 130 for (const auto &name_to_symbol : name_map) {131 const Symbol *symbol = name_to_symbol.second;132 s->Indent();133 symbol->Dump(s, target, symbol - &m_symbols[0], name_preference);134 }135 } break;136 137 case eSortOrderBySize: {138 s->PutCString(" (sorted by size):\n");139 DumpSymbolHeader(s);140 141 std::multimap<size_t, const Symbol *, std::greater<size_t>> size_map;142 for (const Symbol &symbol : m_symbols)143 size_map.emplace(symbol.GetByteSize(), &symbol);144 145 size_t idx = 0;146 for (const auto &size_to_symbol : size_map) {147 const Symbol *symbol = size_to_symbol.second;148 s->Indent();149 symbol->Dump(s, target, idx++, name_preference);150 }151 } break;152 153 case eSortOrderByAddress:154 s->PutCString(" (sorted by address):\n");155 DumpSymbolHeader(s);156 if (!m_file_addr_to_index_computed)157 InitAddressIndexes();158 const size_t num_entries = m_file_addr_to_index.GetSize();159 for (size_t i = 0; i < num_entries; ++i) {160 s->Indent();161 const uint32_t symbol_idx = m_file_addr_to_index.GetEntryRef(i).data;162 m_symbols[symbol_idx].Dump(s, target, symbol_idx, name_preference);163 }164 break;165 }166 } else {167 s->PutCString("\n");168 }169}170 171void Symtab::Dump(Stream *s, Target *target, std::vector<uint32_t> &indexes,172 Mangled::NamePreference name_preference) const {173 std::lock_guard<std::recursive_mutex> guard(m_mutex);174 175 const size_t num_symbols = GetNumSymbols();176 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);177 s->Indent();178 s->Printf("Symtab %" PRIu64 " symbol indexes (%" PRIu64 " symbols total):\n",179 (uint64_t)indexes.size(), (uint64_t)m_symbols.size());180 s->IndentMore();181 182 if (!indexes.empty()) {183 std::vector<uint32_t>::const_iterator pos;184 std::vector<uint32_t>::const_iterator end = indexes.end();185 DumpSymbolHeader(s);186 for (pos = indexes.begin(); pos != end; ++pos) {187 size_t idx = *pos;188 if (idx < num_symbols) {189 s->Indent();190 m_symbols[idx].Dump(s, target, idx, name_preference);191 }192 }193 }194 s->IndentLess();195}196 197void Symtab::DumpSymbolHeader(Stream *s) {198 s->Indent(" Debug symbol\n");199 s->Indent(" |Synthetic symbol\n");200 s->Indent(" ||Externally Visible\n");201 s->Indent(" |||\n");202 s->Indent("Index UserID DSX Type File Address/Value Load "203 "Address Size Flags Name\n");204 s->Indent("------- ------ --- --------------- ------------------ "205 "------------------ ------------------ ---------- "206 "----------------------------------\n");207}208 209static int CompareSymbolID(const void *key, const void *p) {210 const user_id_t match_uid = *(const user_id_t *)key;211 const user_id_t symbol_uid = ((const Symbol *)p)->GetID();212 if (match_uid < symbol_uid)213 return -1;214 if (match_uid > symbol_uid)215 return 1;216 return 0;217}218 219Symbol *Symtab::FindSymbolByID(lldb::user_id_t symbol_uid) const {220 std::lock_guard<std::recursive_mutex> guard(m_mutex);221 222 Symbol *symbol =223 (Symbol *)::bsearch(&symbol_uid, &m_symbols[0], m_symbols.size(),224 sizeof(m_symbols[0]), CompareSymbolID);225 return symbol;226}227 228Symbol *Symtab::SymbolAtIndex(size_t idx) {229 // Clients should grab the mutex from this symbol table and lock it manually230 // when calling this function to avoid performance issues.231 if (idx < m_symbols.size())232 return &m_symbols[idx];233 return nullptr;234}235 236const Symbol *Symtab::SymbolAtIndex(size_t idx) const {237 // Clients should grab the mutex from this symbol table and lock it manually238 // when calling this function to avoid performance issues.239 if (idx < m_symbols.size())240 return &m_symbols[idx];241 return nullptr;242}243 244static bool lldb_skip_name(llvm::StringRef mangled,245 Mangled::ManglingScheme scheme) {246 switch (scheme) {247 case Mangled::eManglingSchemeItanium: {248 if (mangled.size() < 3 || !mangled.starts_with("_Z"))249 return true;250 251 // Avoid the following types of symbols in the index.252 switch (mangled[2]) {253 case 'G': // guard variables254 case 'T': // virtual tables, VTT structures, typeinfo structures + names255 case 'Z': // named local entities (if we eventually handle256 // eSymbolTypeData, we will want this back)257 return true;258 259 default:260 break;261 }262 263 // Include this name in the index.264 return false;265 }266 267 // No filters for this scheme yet. Include all names in indexing.268 case Mangled::eManglingSchemeMSVC:269 case Mangled::eManglingSchemeRustV0:270 case Mangled::eManglingSchemeD:271 case Mangled::eManglingSchemeSwift:272 return false;273 274 // Don't try and demangle things we can't categorize.275 case Mangled::eManglingSchemeNone:276 return true;277 }278 llvm_unreachable("unknown scheme!");279}280 281void Symtab::InitNameIndexes() {282 // Protected function, no need to lock mutex...283 if (!m_name_indexes_computed) {284 m_name_indexes_computed = true;285 ElapsedTime elapsed(m_objfile->GetModule()->GetSymtabIndexTime());286 LLDB_SCOPED_TIMER();287 288 // Collect all loaded language plugins.289 std::vector<Language *> languages;290 Language::ForEach([&languages](Language *l) {291 languages.push_back(l);292 return IterationAction::Continue;293 });294 295 auto &name_to_index = GetNameToSymbolIndexMap(lldb::eFunctionNameTypeNone);296 auto &basename_to_index =297 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeBase);298 auto &method_to_index =299 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeMethod);300 auto &selector_to_index =301 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeSelector);302 // Create the name index vector to be able to quickly search by name303 const size_t num_symbols = m_symbols.size();304 name_to_index.Reserve(num_symbols);305 306 // The "const char *" in "class_contexts" and backlog::value_type::second307 // must come from a ConstString::GetCString()308 std::set<const char *> class_contexts;309 std::vector<std::pair<NameToIndexMap::Entry, const char *>> backlog;310 backlog.reserve(num_symbols / 2);311 312 // Instantiation of the demangler is expensive, so better use a single one313 // for all entries during batch processing.314 RichManglingContext rmc;315 for (uint32_t value = 0; value < num_symbols; ++value) {316 Symbol *symbol = &m_symbols[value];317 318 // Don't let trampolines get into the lookup by name map If we ever need319 // the trampoline symbols to be searchable by name we can remove this and320 // then possibly add a new bool to any of the Symtab functions that321 // lookup symbols by name to indicate if they want trampolines. We also322 // don't want any synthetic symbols with auto generated names in the323 // name lookups.324 if (symbol->IsTrampoline() || symbol->IsSyntheticWithAutoGeneratedName())325 continue;326 327 // If the symbol's name string matched a Mangled::ManglingScheme, it is328 // stored in the mangled field.329 Mangled &mangled = symbol->GetMangled();330 if (ConstString name = mangled.GetMangledName()) {331 name_to_index.Append(name, value);332 333 if (symbol->ContainsLinkerAnnotations()) {334 // If the symbol has linker annotations, also add the version without335 // the annotations.336 ConstString stripped = ConstString(337 m_objfile->StripLinkerSymbolAnnotations(name.GetStringRef()));338 name_to_index.Append(stripped, value);339 }340 341 const SymbolType type = symbol->GetType();342 if (type == eSymbolTypeCode || type == eSymbolTypeResolver) {343 if (mangled.GetRichManglingInfo(rmc, lldb_skip_name)) {344 RegisterMangledNameEntry(value, class_contexts, backlog, rmc);345 continue;346 }347 }348 }349 350 // Symbol name strings that didn't match a Mangled::ManglingScheme, are351 // stored in the demangled field.352 if (ConstString name = mangled.GetDemangledName()) {353 name_to_index.Append(name, value);354 355 if (symbol->ContainsLinkerAnnotations()) {356 // If the symbol has linker annotations, also add the version without357 // the annotations.358 name = ConstString(359 m_objfile->StripLinkerSymbolAnnotations(name.GetStringRef()));360 name_to_index.Append(name, value);361 }362 363 // If the demangled name turns out to be an ObjC name, and is a category364 // name, add the version without categories to the index too.365 for (Language *lang : languages) {366 for (auto variant : lang->GetMethodNameVariants(name)) {367 if (variant.GetType() & lldb::eFunctionNameTypeSelector)368 selector_to_index.Append(variant.GetName(), value);369 else if (variant.GetType() & lldb::eFunctionNameTypeFull)370 name_to_index.Append(variant.GetName(), value);371 else if (variant.GetType() & lldb::eFunctionNameTypeMethod)372 method_to_index.Append(variant.GetName(), value);373 else if (variant.GetType() & lldb::eFunctionNameTypeBase)374 basename_to_index.Append(variant.GetName(), value);375 }376 }377 }378 }379 380 for (const auto &record : backlog) {381 RegisterBacklogEntry(record.first, record.second, class_contexts);382 }383 384 name_to_index.Sort();385 name_to_index.SizeToFit();386 selector_to_index.Sort();387 selector_to_index.SizeToFit();388 basename_to_index.Sort();389 basename_to_index.SizeToFit();390 method_to_index.Sort();391 method_to_index.SizeToFit();392 }393}394 395void Symtab::RegisterMangledNameEntry(396 uint32_t value, std::set<const char *> &class_contexts,397 std::vector<std::pair<NameToIndexMap::Entry, const char *>> &backlog,398 RichManglingContext &rmc) {399 // Only register functions that have a base name.400 llvm::StringRef base_name = rmc.ParseFunctionBaseName();401 if (base_name.empty())402 return;403 404 // The base name will be our entry's name.405 NameToIndexMap::Entry entry(ConstString(base_name), value);406 llvm::StringRef decl_context = rmc.ParseFunctionDeclContextName();407 408 // Register functions with no context.409 if (decl_context.empty()) {410 // This has to be a basename411 auto &basename_to_index =412 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeBase);413 basename_to_index.Append(entry);414 // If there is no context (no namespaces or class scopes that come before415 // the function name) then this also could be a fullname.416 auto &name_to_index = GetNameToSymbolIndexMap(lldb::eFunctionNameTypeNone);417 name_to_index.Append(entry);418 return;419 }420 421 // Make sure we have a pool-string pointer and see if we already know the422 // context name.423 const char *decl_context_ccstr = ConstString(decl_context).GetCString();424 auto it = class_contexts.find(decl_context_ccstr);425 426 auto &method_to_index =427 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeMethod);428 // Register constructors and destructors. They are methods and create429 // declaration contexts.430 if (rmc.IsCtorOrDtor()) {431 method_to_index.Append(entry);432 if (it == class_contexts.end())433 class_contexts.insert(it, decl_context_ccstr);434 return;435 }436 437 // Register regular methods with a known declaration context.438 if (it != class_contexts.end()) {439 method_to_index.Append(entry);440 return;441 }442 443 // Regular methods in unknown declaration contexts are put to the backlog. We444 // will revisit them once we processed all remaining symbols.445 backlog.push_back(std::make_pair(entry, decl_context_ccstr));446}447 448void Symtab::RegisterBacklogEntry(449 const NameToIndexMap::Entry &entry, const char *decl_context,450 const std::set<const char *> &class_contexts) {451 auto &method_to_index =452 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeMethod);453 auto it = class_contexts.find(decl_context);454 if (it != class_contexts.end()) {455 method_to_index.Append(entry);456 } else {457 // If we got here, we have something that had a context (was inside458 // a namespace or class) yet we don't know the entry459 method_to_index.Append(entry);460 auto &basename_to_index =461 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeBase);462 basename_to_index.Append(entry);463 }464}465 466void Symtab::PreloadSymbols() {467 std::lock_guard<std::recursive_mutex> guard(m_mutex);468 InitNameIndexes();469}470 471void Symtab::AppendSymbolNamesToMap(const IndexCollection &indexes,472 bool add_demangled, bool add_mangled,473 NameToIndexMap &name_to_index_map) const {474 LLDB_SCOPED_TIMER();475 if (add_demangled || add_mangled) {476 std::lock_guard<std::recursive_mutex> guard(m_mutex);477 478 // Create the name index vector to be able to quickly search by name479 const size_t num_indexes = indexes.size();480 for (size_t i = 0; i < num_indexes; ++i) {481 uint32_t value = indexes[i];482 assert(i < m_symbols.size());483 const Symbol *symbol = &m_symbols[value];484 485 const Mangled &mangled = symbol->GetMangled();486 if (add_demangled) {487 if (ConstString name = mangled.GetDemangledName())488 name_to_index_map.Append(name, value);489 }490 491 if (add_mangled) {492 if (ConstString name = mangled.GetMangledName())493 name_to_index_map.Append(name, value);494 }495 }496 }497}498 499uint32_t Symtab::AppendSymbolIndexesWithType(SymbolType symbol_type,500 std::vector<uint32_t> &indexes,501 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 || m_symbols[i].GetType() == symbol_type)511 indexes.push_back(i);512 }513 514 return indexes.size() - prev_size;515}516 517uint32_t Symtab::AppendSymbolIndexesWithTypeAndFlagsValue(518 SymbolType symbol_type, uint32_t flags_value,519 std::vector<uint32_t> &indexes, uint32_t start_idx,520 uint32_t end_index) const {521 std::lock_guard<std::recursive_mutex> guard(m_mutex);522 523 uint32_t prev_size = indexes.size();524 525 const uint32_t count = std::min<uint32_t>(m_symbols.size(), end_index);526 527 for (uint32_t i = start_idx; i < count; ++i) {528 if ((symbol_type == eSymbolTypeAny ||529 m_symbols[i].GetType() == symbol_type) &&530 m_symbols[i].GetFlags() == flags_value)531 indexes.push_back(i);532 }533 534 return indexes.size() - prev_size;535}536 537uint32_t Symtab::AppendSymbolIndexesWithType(SymbolType symbol_type,538 Debug symbol_debug_type,539 Visibility symbol_visibility,540 std::vector<uint32_t> &indexes,541 uint32_t start_idx,542 uint32_t end_index) const {543 std::lock_guard<std::recursive_mutex> guard(m_mutex);544 545 uint32_t prev_size = indexes.size();546 547 const uint32_t count = std::min<uint32_t>(m_symbols.size(), end_index);548 549 for (uint32_t i = start_idx; i < count; ++i) {550 if (symbol_type == eSymbolTypeAny ||551 m_symbols[i].GetType() == symbol_type) {552 if (CheckSymbolAtIndex(i, symbol_debug_type, symbol_visibility))553 indexes.push_back(i);554 }555 }556 557 return indexes.size() - prev_size;558}559 560uint32_t Symtab::GetIndexForSymbol(const Symbol *symbol) const {561 if (!m_symbols.empty()) {562 const Symbol *first_symbol = &m_symbols[0];563 if (symbol >= first_symbol && symbol < first_symbol + m_symbols.size())564 return symbol - first_symbol;565 }566 return UINT32_MAX;567}568 569struct SymbolSortInfo {570 const bool sort_by_load_addr;571 const Symbol *symbols;572};573 574namespace {575struct SymbolIndexComparator {576 const std::vector<Symbol> &symbols;577 std::vector<lldb::addr_t> &addr_cache;578 579 // Getting from the symbol to the Address to the File Address involves some580 // work. Since there are potentially many symbols here, and we're using this581 // for sorting so we're going to be computing the address many times, cache582 // that in addr_cache. The array passed in has to be the same size as the583 // symbols array passed into the member variable symbols, and should be584 // initialized with LLDB_INVALID_ADDRESS.585 // NOTE: You have to make addr_cache externally and pass it in because586 // std::stable_sort587 // makes copies of the comparator it is initially passed in, and you end up588 // spending huge amounts of time copying this array...589 590 SymbolIndexComparator(const std::vector<Symbol> &s,591 std::vector<lldb::addr_t> &a)592 : symbols(s), addr_cache(a) {593 assert(symbols.size() == addr_cache.size());594 }595 bool operator()(uint32_t index_a, uint32_t index_b) {596 addr_t value_a = addr_cache[index_a];597 if (value_a == LLDB_INVALID_ADDRESS) {598 value_a = symbols[index_a].GetAddressRef().GetFileAddress();599 addr_cache[index_a] = value_a;600 }601 602 addr_t value_b = addr_cache[index_b];603 if (value_b == LLDB_INVALID_ADDRESS) {604 value_b = symbols[index_b].GetAddressRef().GetFileAddress();605 addr_cache[index_b] = value_b;606 }607 608 if (value_a == value_b) {609 // The if the values are equal, use the original symbol user ID610 lldb::user_id_t uid_a = symbols[index_a].GetID();611 lldb::user_id_t uid_b = symbols[index_b].GetID();612 if (uid_a < uid_b)613 return true;614 if (uid_a > uid_b)615 return false;616 return false;617 } else if (value_a < value_b)618 return true;619 620 return false;621 }622};623}624 625void Symtab::SortSymbolIndexesByValue(std::vector<uint32_t> &indexes,626 bool remove_duplicates) const {627 std::lock_guard<std::recursive_mutex> guard(m_mutex);628 LLDB_SCOPED_TIMER();629 // No need to sort if we have zero or one items...630 if (indexes.size() <= 1)631 return;632 633 // Sort the indexes in place using std::stable_sort.634 // NOTE: The use of std::stable_sort instead of llvm::sort here is strictly635 // for performance, not correctness. The indexes vector tends to be "close"636 // to sorted, which the stable sort handles better.637 638 std::vector<lldb::addr_t> addr_cache(m_symbols.size(), LLDB_INVALID_ADDRESS);639 640 SymbolIndexComparator comparator(m_symbols, addr_cache);641 llvm::stable_sort(indexes, comparator);642 643 // Remove any duplicates if requested644 if (remove_duplicates) {645 auto last = llvm::unique(indexes);646 indexes.erase(last, indexes.end());647 }648}649 650uint32_t Symtab::GetNameIndexes(ConstString symbol_name,651 std::vector<uint32_t> &indexes) {652 auto &name_to_index = GetNameToSymbolIndexMap(lldb::eFunctionNameTypeNone);653 const uint32_t count = name_to_index.GetValues(symbol_name, indexes);654 if (count)655 return count;656 // Synthetic symbol names are not added to the name indexes, but they start657 // with a prefix and end with the symbol file address. This allows users to658 // find these symbols without having to add them to the name indexes. These659 // queries will not happen very often since the names don't mean anything, so660 // performance is not paramount in this case.661 llvm::StringRef name = symbol_name.GetStringRef();662 // String the synthetic prefix if the name starts with it.663 if (!name.consume_front(Symbol::GetSyntheticSymbolPrefix()))664 return 0; // Not a synthetic symbol name665 666 // Extract the file address from the symbol name667 unsigned long long file_address = 0;668 if (getAsUnsignedInteger(name, /*Radix=*/16, file_address))669 return 0; // Failed to extract the user ID as an integer670 671 Symbol *symbol = FindSymbolAtFileAddress(static_cast<addr_t>(file_address));672 if (symbol == nullptr)673 return 0;674 const uint32_t symbol_idx = GetIndexForSymbol(symbol);675 if (symbol_idx == UINT32_MAX)676 return 0;677 indexes.push_back(symbol_idx);678 return 1;679}680 681uint32_t Symtab::AppendSymbolIndexesWithName(ConstString symbol_name,682 std::vector<uint32_t> &indexes) {683 std::lock_guard<std::recursive_mutex> guard(m_mutex);684 685 if (symbol_name) {686 if (!m_name_indexes_computed)687 InitNameIndexes();688 689 return GetNameIndexes(symbol_name, indexes);690 }691 return 0;692}693 694uint32_t Symtab::AppendSymbolIndexesWithName(ConstString symbol_name,695 Debug symbol_debug_type,696 Visibility symbol_visibility,697 std::vector<uint32_t> &indexes) {698 std::lock_guard<std::recursive_mutex> guard(m_mutex);699 700 LLDB_SCOPED_TIMER();701 if (symbol_name) {702 const size_t old_size = indexes.size();703 if (!m_name_indexes_computed)704 InitNameIndexes();705 706 std::vector<uint32_t> all_name_indexes;707 const size_t name_match_count =708 GetNameIndexes(symbol_name, all_name_indexes);709 for (size_t i = 0; i < name_match_count; ++i) {710 if (CheckSymbolAtIndex(all_name_indexes[i], symbol_debug_type,711 symbol_visibility))712 indexes.push_back(all_name_indexes[i]);713 }714 return indexes.size() - old_size;715 }716 return 0;717}718 719uint32_t720Symtab::AppendSymbolIndexesWithNameAndType(ConstString symbol_name,721 SymbolType symbol_type,722 std::vector<uint32_t> &indexes) {723 std::lock_guard<std::recursive_mutex> guard(m_mutex);724 725 if (AppendSymbolIndexesWithName(symbol_name, indexes) > 0 &&726 symbol_type != eSymbolTypeAny) {727 llvm::erase_if(indexes, [this, symbol_type](uint32_t index) {728 return m_symbols[index].GetType() != symbol_type;729 });730 }731 return indexes.size();732}733 734uint32_t Symtab::AppendSymbolIndexesWithNameAndType(735 ConstString symbol_name, SymbolType symbol_type,736 Debug symbol_debug_type, Visibility symbol_visibility,737 std::vector<uint32_t> &indexes) {738 std::lock_guard<std::recursive_mutex> guard(m_mutex);739 740 if (AppendSymbolIndexesWithName(symbol_name, symbol_debug_type,741 symbol_visibility, indexes) > 0 &&742 symbol_type != eSymbolTypeAny) {743 llvm::erase_if(indexes, [this, symbol_type](uint32_t index) {744 return m_symbols[index].GetType() != symbol_type;745 });746 }747 return indexes.size();748}749 750uint32_t Symtab::AppendSymbolIndexesMatchingRegExAndType(751 const RegularExpression ®exp, SymbolType symbol_type,752 std::vector<uint32_t> &indexes, Mangled::NamePreference name_preference) {753 std::lock_guard<std::recursive_mutex> guard(m_mutex);754 755 uint32_t prev_size = indexes.size();756 uint32_t sym_end = m_symbols.size();757 758 for (uint32_t i = 0; i < sym_end; i++) {759 if (symbol_type == eSymbolTypeAny ||760 m_symbols[i].GetType() == symbol_type) {761 const char *name =762 m_symbols[i].GetMangled().GetName(name_preference).AsCString();763 if (name) {764 if (regexp.Execute(name))765 indexes.push_back(i);766 }767 }768 }769 return indexes.size() - prev_size;770}771 772uint32_t Symtab::AppendSymbolIndexesMatchingRegExAndType(773 const RegularExpression ®exp, SymbolType symbol_type,774 Debug symbol_debug_type, Visibility symbol_visibility,775 std::vector<uint32_t> &indexes, Mangled::NamePreference name_preference) {776 std::lock_guard<std::recursive_mutex> guard(m_mutex);777 778 uint32_t prev_size = indexes.size();779 uint32_t sym_end = m_symbols.size();780 781 for (uint32_t i = 0; i < sym_end; i++) {782 if (symbol_type == eSymbolTypeAny ||783 m_symbols[i].GetType() == symbol_type) {784 if (!CheckSymbolAtIndex(i, symbol_debug_type, symbol_visibility))785 continue;786 787 const char *name =788 m_symbols[i].GetMangled().GetName(name_preference).AsCString();789 if (name) {790 if (regexp.Execute(name))791 indexes.push_back(i);792 }793 }794 }795 return indexes.size() - prev_size;796}797 798Symbol *Symtab::FindSymbolWithType(SymbolType symbol_type,799 Debug symbol_debug_type,800 Visibility symbol_visibility,801 uint32_t &start_idx) {802 std::lock_guard<std::recursive_mutex> guard(m_mutex);803 804 const size_t count = m_symbols.size();805 for (size_t idx = start_idx; idx < count; ++idx) {806 if (symbol_type == eSymbolTypeAny ||807 m_symbols[idx].GetType() == symbol_type) {808 if (CheckSymbolAtIndex(idx, symbol_debug_type, symbol_visibility)) {809 start_idx = idx;810 return &m_symbols[idx];811 }812 }813 }814 return nullptr;815}816 817void818Symtab::FindAllSymbolsWithNameAndType(ConstString name,819 SymbolType symbol_type,820 std::vector<uint32_t> &symbol_indexes) {821 std::lock_guard<std::recursive_mutex> guard(m_mutex);822 823 // Initialize all of the lookup by name indexes before converting NAME to a824 // uniqued string NAME_STR below.825 if (!m_name_indexes_computed)826 InitNameIndexes();827 828 if (name) {829 // The string table did have a string that matched, but we need to check830 // the symbols and match the symbol_type if any was given.831 AppendSymbolIndexesWithNameAndType(name, symbol_type, symbol_indexes);832 }833}834 835void Symtab::FindAllSymbolsWithNameAndType(836 ConstString name, SymbolType symbol_type, Debug symbol_debug_type,837 Visibility symbol_visibility, std::vector<uint32_t> &symbol_indexes) {838 std::lock_guard<std::recursive_mutex> guard(m_mutex);839 840 LLDB_SCOPED_TIMER();841 // Initialize all of the lookup by name indexes before converting NAME to a842 // uniqued string NAME_STR below.843 if (!m_name_indexes_computed)844 InitNameIndexes();845 846 if (name) {847 // The string table did have a string that matched, but we need to check848 // the symbols and match the symbol_type if any was given.849 AppendSymbolIndexesWithNameAndType(name, symbol_type, symbol_debug_type,850 symbol_visibility, symbol_indexes);851 }852}853 854void Symtab::FindAllSymbolsMatchingRexExAndType(855 const RegularExpression ®ex, SymbolType symbol_type,856 Debug symbol_debug_type, Visibility symbol_visibility,857 std::vector<uint32_t> &symbol_indexes,858 Mangled::NamePreference name_preference) {859 std::lock_guard<std::recursive_mutex> guard(m_mutex);860 861 AppendSymbolIndexesMatchingRegExAndType(regex, symbol_type, symbol_debug_type,862 symbol_visibility, symbol_indexes,863 name_preference);864}865 866Symbol *Symtab::FindFirstSymbolWithNameAndType(ConstString name,867 SymbolType symbol_type,868 Debug symbol_debug_type,869 Visibility symbol_visibility) {870 std::lock_guard<std::recursive_mutex> guard(m_mutex);871 LLDB_SCOPED_TIMER();872 if (!m_name_indexes_computed)873 InitNameIndexes();874 875 if (name) {876 std::vector<uint32_t> matching_indexes;877 // The string table did have a string that matched, but we need to check878 // the symbols and match the symbol_type if any was given.879 if (AppendSymbolIndexesWithNameAndType(name, symbol_type, symbol_debug_type,880 symbol_visibility,881 matching_indexes)) {882 std::vector<uint32_t>::const_iterator pos, end = matching_indexes.end();883 for (pos = matching_indexes.begin(); pos != end; ++pos) {884 Symbol *symbol = SymbolAtIndex(*pos);885 886 if (symbol->Compare(name, symbol_type))887 return symbol;888 }889 }890 }891 return nullptr;892}893 894typedef struct {895 const Symtab *symtab;896 const addr_t file_addr;897 Symbol *match_symbol;898 const uint32_t *match_index_ptr;899 addr_t match_offset;900} SymbolSearchInfo;901 902// Add all the section file start address & size to the RangeVector, recusively903// adding any children sections.904static void AddSectionsToRangeMap(SectionList *sectlist,905 RangeVector<addr_t, addr_t> §ion_ranges) {906 const int num_sections = sectlist->GetNumSections(0);907 for (int i = 0; i < num_sections; i++) {908 SectionSP sect_sp = sectlist->GetSectionAtIndex(i);909 if (sect_sp) {910 SectionList &child_sectlist = sect_sp->GetChildren();911 912 // If this section has children, add the children to the RangeVector.913 // Else add this section to the RangeVector.914 if (child_sectlist.GetNumSections(0) > 0) {915 AddSectionsToRangeMap(&child_sectlist, section_ranges);916 } else {917 size_t size = sect_sp->GetByteSize();918 if (size > 0) {919 addr_t base_addr = sect_sp->GetFileAddress();920 RangeVector<addr_t, addr_t>::Entry entry;921 entry.SetRangeBase(base_addr);922 entry.SetByteSize(size);923 section_ranges.Append(entry);924 }925 }926 }927 }928}929 930void Symtab::InitAddressIndexes() {931 // Protected function, no need to lock mutex...932 if (!m_file_addr_to_index_computed && !m_symbols.empty()) {933 m_file_addr_to_index_computed = true;934 935 FileRangeToIndexMap::Entry entry;936 const_iterator begin = m_symbols.begin();937 const_iterator end = m_symbols.end();938 for (const_iterator pos = m_symbols.begin(); pos != end; ++pos) {939 if (pos->ValueIsAddress()) {940 entry.SetRangeBase(pos->GetAddressRef().GetFileAddress());941 entry.SetByteSize(pos->GetByteSize());942 entry.data = std::distance(begin, pos);943 m_file_addr_to_index.Append(entry);944 }945 }946 const size_t num_entries = m_file_addr_to_index.GetSize();947 if (num_entries > 0) {948 m_file_addr_to_index.Sort();949 950 // Create a RangeVector with the start & size of all the sections for951 // this objfile. We'll need to check this for any FileRangeToIndexMap952 // entries with an uninitialized size, which could potentially be a large953 // number so reconstituting the weak pointer is busywork when it is954 // invariant information.955 SectionList *sectlist = m_objfile->GetSectionList();956 RangeVector<addr_t, addr_t> section_ranges;957 if (sectlist) {958 AddSectionsToRangeMap(sectlist, section_ranges);959 section_ranges.Sort();960 }961 962 // Iterate through the FileRangeToIndexMap and fill in the size for any963 // entries that didn't already have a size from the Symbol (e.g. if we964 // have a plain linker symbol with an address only, instead of debug info965 // where we get an address and a size and a type, etc.)966 for (size_t i = 0; i < num_entries; i++) {967 FileRangeToIndexMap::Entry *entry =968 m_file_addr_to_index.GetMutableEntryAtIndex(i);969 if (entry->GetByteSize() == 0) {970 addr_t curr_base_addr = entry->GetRangeBase();971 const RangeVector<addr_t, addr_t>::Entry *containing_section =972 section_ranges.FindEntryThatContains(curr_base_addr);973 974 // Use the end of the section as the default max size of the symbol975 addr_t sym_size = 0;976 if (containing_section) {977 sym_size =978 containing_section->GetByteSize() -979 (entry->GetRangeBase() - containing_section->GetRangeBase());980 }981 982 for (size_t j = i; j < num_entries; j++) {983 FileRangeToIndexMap::Entry *next_entry =984 m_file_addr_to_index.GetMutableEntryAtIndex(j);985 addr_t next_base_addr = next_entry->GetRangeBase();986 if (next_base_addr > curr_base_addr) {987 addr_t size_to_next_symbol = next_base_addr - curr_base_addr;988 989 // Take the difference between this symbol and the next one as990 // its size, if it is less than the size of the section.991 if (sym_size == 0 || size_to_next_symbol < sym_size) {992 sym_size = size_to_next_symbol;993 }994 break;995 }996 }997 998 if (sym_size > 0) {999 entry->SetByteSize(sym_size);1000 Symbol &symbol = m_symbols[entry->data];1001 symbol.SetByteSize(sym_size);1002 symbol.SetSizeIsSynthesized(true);1003 }1004 }1005 }1006 1007 // Sort again in case the range size changes the ordering1008 m_file_addr_to_index.Sort();1009 }1010 }1011}1012 1013void Symtab::Finalize() {1014 std::lock_guard<std::recursive_mutex> guard(m_mutex);1015 // Calculate the size of symbols inside InitAddressIndexes.1016 InitAddressIndexes();1017 // Shrink to fit the symbols so we don't waste memory1018 m_symbols.shrink_to_fit();1019 SaveToCache();1020}1021 1022Symbol *Symtab::FindSymbolAtFileAddress(addr_t file_addr) {1023 std::lock_guard<std::recursive_mutex> guard(m_mutex);1024 if (!m_file_addr_to_index_computed)1025 InitAddressIndexes();1026 1027 const FileRangeToIndexMap::Entry *entry =1028 m_file_addr_to_index.FindEntryStartsAt(file_addr);1029 if (entry) {1030 Symbol *symbol = SymbolAtIndex(entry->data);1031 if (symbol->GetFileAddress() == file_addr)1032 return symbol;1033 }1034 return nullptr;1035}1036 1037Symbol *Symtab::FindSymbolContainingFileAddress(addr_t file_addr) {1038 std::lock_guard<std::recursive_mutex> guard(m_mutex);1039 1040 if (!m_file_addr_to_index_computed)1041 InitAddressIndexes();1042 1043 const FileRangeToIndexMap::Entry *entry =1044 m_file_addr_to_index.FindEntryThatContains(file_addr);1045 if (entry) {1046 Symbol *symbol = SymbolAtIndex(entry->data);1047 if (symbol->ContainsFileAddress(file_addr))1048 return symbol;1049 }1050 return nullptr;1051}1052 1053void Symtab::ForEachSymbolContainingFileAddress(1054 addr_t file_addr, std::function<bool(Symbol *)> const &callback) {1055 std::lock_guard<std::recursive_mutex> guard(m_mutex);1056 1057 if (!m_file_addr_to_index_computed)1058 InitAddressIndexes();1059 1060 std::vector<uint32_t> all_addr_indexes;1061 1062 // Get all symbols with file_addr1063 const size_t addr_match_count =1064 m_file_addr_to_index.FindEntryIndexesThatContain(file_addr,1065 all_addr_indexes);1066 1067 for (size_t i = 0; i < addr_match_count; ++i) {1068 Symbol *symbol = SymbolAtIndex(all_addr_indexes[i]);1069 if (symbol->ContainsFileAddress(file_addr)) {1070 if (!callback(symbol))1071 break;1072 }1073 }1074}1075 1076void Symtab::SymbolIndicesToSymbolContextList(1077 std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list) {1078 // No need to protect this call using m_mutex all other method calls are1079 // already thread safe.1080 1081 const bool merge_symbol_into_function = true;1082 size_t num_indices = symbol_indexes.size();1083 if (num_indices > 0) {1084 SymbolContext sc;1085 sc.module_sp = m_objfile->GetModule();1086 for (size_t i = 0; i < num_indices; i++) {1087 sc.symbol = SymbolAtIndex(symbol_indexes[i]);1088 if (sc.symbol)1089 sc_list.AppendIfUnique(sc, merge_symbol_into_function);1090 }1091 }1092}1093 1094void Symtab::FindFunctionSymbols(ConstString name, uint32_t name_type_mask,1095 SymbolContextList &sc_list) {1096 std::vector<uint32_t> symbol_indexes;1097 1098 // eFunctionNameTypeAuto should be pre-resolved by a call to1099 // Module::LookupInfo::LookupInfo()1100 assert((name_type_mask & eFunctionNameTypeAuto) == 0);1101 1102 if (name_type_mask & (eFunctionNameTypeBase | eFunctionNameTypeFull)) {1103 std::vector<uint32_t> temp_symbol_indexes;1104 FindAllSymbolsWithNameAndType(name, eSymbolTypeAny, temp_symbol_indexes);1105 1106 unsigned temp_symbol_indexes_size = temp_symbol_indexes.size();1107 if (temp_symbol_indexes_size > 0) {1108 std::lock_guard<std::recursive_mutex> guard(m_mutex);1109 for (unsigned i = 0; i < temp_symbol_indexes_size; i++) {1110 SymbolContext sym_ctx;1111 sym_ctx.symbol = SymbolAtIndex(temp_symbol_indexes[i]);1112 if (sym_ctx.symbol) {1113 switch (sym_ctx.symbol->GetType()) {1114 case eSymbolTypeCode:1115 case eSymbolTypeResolver:1116 case eSymbolTypeReExported:1117 case eSymbolTypeAbsolute:1118 symbol_indexes.push_back(temp_symbol_indexes[i]);1119 break;1120 default:1121 break;1122 }1123 }1124 }1125 }1126 }1127 1128 if (!m_name_indexes_computed)1129 InitNameIndexes();1130 1131 for (lldb::FunctionNameType type :1132 {lldb::eFunctionNameTypeBase, lldb::eFunctionNameTypeMethod,1133 lldb::eFunctionNameTypeSelector}) {1134 if (name_type_mask & type) {1135 auto map = GetNameToSymbolIndexMap(type);1136 1137 const UniqueCStringMap<uint32_t>::Entry *match;1138 for (match = map.FindFirstValueForName(name); match != nullptr;1139 match = map.FindNextValueForName(match)) {1140 symbol_indexes.push_back(match->value);1141 }1142 }1143 }1144 1145 if (!symbol_indexes.empty()) {1146 llvm::sort(symbol_indexes);1147 symbol_indexes.erase(llvm::unique(symbol_indexes), symbol_indexes.end());1148 SymbolIndicesToSymbolContextList(symbol_indexes, sc_list);1149 }1150}1151 1152const Symbol *Symtab::GetParent(Symbol *child_symbol) const {1153 uint32_t child_idx = GetIndexForSymbol(child_symbol);1154 if (child_idx != UINT32_MAX && child_idx > 0) {1155 for (uint32_t idx = child_idx - 1; idx != UINT32_MAX; --idx) {1156 const Symbol *symbol = SymbolAtIndex(idx);1157 const uint32_t sibling_idx = symbol->GetSiblingIndex();1158 if (sibling_idx != UINT32_MAX && sibling_idx > child_idx)1159 return symbol;1160 }1161 }1162 return nullptr;1163}1164 1165std::string Symtab::GetCacheKey() {1166 std::string key;1167 llvm::raw_string_ostream strm(key);1168 // Symbol table can come from different object files for the same module. A1169 // module can have one object file as the main executable and might have1170 // another object file in a separate symbol file.1171 strm << m_objfile->GetModule()->GetCacheKey() << "-symtab-"1172 << llvm::format_hex(m_objfile->GetCacheHash(), 10);1173 return key;1174}1175 1176void Symtab::SaveToCache() {1177 DataFileCache *cache = Module::GetIndexCache();1178 if (!cache)1179 return; // Caching is not enabled.1180 InitNameIndexes(); // Init the name indexes so we can cache them as well.1181 const auto byte_order = endian::InlHostByteOrder();1182 DataEncoder file(byte_order, /*addr_size=*/8);1183 // Encode will return false if the symbol table's object file doesn't have1184 // anything to make a signature from.1185 if (Encode(file))1186 if (cache->SetCachedData(GetCacheKey(), file.GetData()))1187 SetWasSavedToCache();1188}1189 1190constexpr llvm::StringLiteral kIdentifierCStrMap("CMAP");1191 1192static void EncodeCStrMap(DataEncoder &encoder, ConstStringTable &strtab,1193 const UniqueCStringMap<uint32_t> &cstr_map) {1194 encoder.AppendData(kIdentifierCStrMap);1195 encoder.AppendU32(cstr_map.GetSize());1196 for (const auto &entry: cstr_map) {1197 // Make sure there are no empty strings.1198 assert((bool)entry.cstring);1199 encoder.AppendU32(strtab.Add(entry.cstring));1200 encoder.AppendU32(entry.value);1201 }1202}1203 1204bool DecodeCStrMap(const DataExtractor &data, lldb::offset_t *offset_ptr,1205 const StringTableReader &strtab,1206 UniqueCStringMap<uint32_t> &cstr_map) {1207 llvm::StringRef identifier((const char *)data.GetData(offset_ptr, 4), 4);1208 if (identifier != kIdentifierCStrMap)1209 return false;1210 const uint32_t count = data.GetU32(offset_ptr);1211 cstr_map.Reserve(count);1212 for (uint32_t i=0; i<count; ++i)1213 {1214 llvm::StringRef str(strtab.Get(data.GetU32(offset_ptr)));1215 uint32_t value = data.GetU32(offset_ptr);1216 // No empty strings in the name indexes in Symtab1217 if (str.empty())1218 return false;1219 cstr_map.Append(ConstString(str), value);1220 }1221 // We must sort the UniqueCStringMap after decoding it since it is a vector1222 // of UniqueCStringMap::Entry objects which contain a ConstString and type T.1223 // ConstString objects are sorted by "const char *" and then type T and1224 // the "const char *" are point values that will depend on the order in which1225 // ConstString objects are created and in which of the 256 string pools they1226 // are created in. So after we decode all of the entries, we must sort the1227 // name map to ensure name lookups succeed. If we encode and decode within1228 // the same process we wouldn't need to sort, so unit testing didn't catch1229 // this issue when first checked in.1230 cstr_map.Sort();1231 return true;1232}1233 1234constexpr llvm::StringLiteral kIdentifierSymbolTable("SYMB");1235constexpr uint32_t CURRENT_CACHE_VERSION = 1;1236 1237/// The encoding format for the symbol table is as follows:1238///1239/// Signature signature;1240/// ConstStringTable strtab;1241/// Identifier four character code: 'SYMB'1242/// uint32_t version;1243/// uint32_t num_symbols;1244/// Symbol symbols[num_symbols];1245/// uint8_t num_cstr_maps;1246/// UniqueCStringMap<uint32_t> cstr_maps[num_cstr_maps]1247bool Symtab::Encode(DataEncoder &encoder) const {1248 // Name indexes must be computed before calling this function.1249 assert(m_name_indexes_computed);1250 1251 // Encode the object file's signature1252 CacheSignature signature(m_objfile);1253 if (!signature.Encode(encoder))1254 return false;1255 ConstStringTable strtab;1256 1257 // Encoder the symbol table into a separate encoder first. This allows us1258 // gather all of the strings we willl need in "strtab" as we will need to1259 // write the string table out before the symbol table.1260 DataEncoder symtab_encoder(encoder.GetByteOrder(),1261 encoder.GetAddressByteSize());1262 symtab_encoder.AppendData(kIdentifierSymbolTable);1263 // Encode the symtab data version.1264 symtab_encoder.AppendU32(CURRENT_CACHE_VERSION);1265 // Encode the number of symbols.1266 symtab_encoder.AppendU32(m_symbols.size());1267 // Encode the symbol data for all symbols.1268 for (const auto &symbol: m_symbols)1269 symbol.Encode(symtab_encoder, strtab);1270 1271 // Emit a byte for how many C string maps we emit. We will fix this up after1272 // we emit the C string maps since we skip emitting C string maps if they are1273 // empty.1274 size_t num_cmaps_offset = symtab_encoder.GetByteSize();1275 uint8_t num_cmaps = 0;1276 symtab_encoder.AppendU8(0);1277 for (const auto &pair: m_name_to_symbol_indices) {1278 if (pair.second.IsEmpty())1279 continue;1280 ++num_cmaps;1281 symtab_encoder.AppendU8(pair.first);1282 EncodeCStrMap(symtab_encoder, strtab, pair.second);1283 }1284 if (num_cmaps > 0)1285 symtab_encoder.PutU8(num_cmaps_offset, num_cmaps);1286 1287 // Now that all strings have been gathered, we will emit the string table.1288 strtab.Encode(encoder);1289 // Followed by the symbol table data.1290 encoder.AppendData(symtab_encoder.GetData());1291 return true;1292}1293 1294bool Symtab::Decode(const DataExtractor &data, lldb::offset_t *offset_ptr,1295 bool &signature_mismatch) {1296 signature_mismatch = false;1297 CacheSignature signature;1298 StringTableReader strtab;1299 { // Scope for "elapsed" object below so it can measure the time parse.1300 ElapsedTime elapsed(m_objfile->GetModule()->GetSymtabParseTime());1301 if (!signature.Decode(data, offset_ptr))1302 return false;1303 if (CacheSignature(m_objfile) != signature) {1304 signature_mismatch = true;1305 return false;1306 }1307 // We now decode the string table for all strings in the data cache file.1308 if (!strtab.Decode(data, offset_ptr))1309 return false;1310 1311 // And now we can decode the symbol table with string table we just decoded.1312 llvm::StringRef identifier((const char *)data.GetData(offset_ptr, 4), 4);1313 if (identifier != kIdentifierSymbolTable)1314 return false;1315 const uint32_t version = data.GetU32(offset_ptr);1316 if (version != CURRENT_CACHE_VERSION)1317 return false;1318 const uint32_t num_symbols = data.GetU32(offset_ptr);1319 if (num_symbols == 0)1320 return true;1321 m_symbols.resize(num_symbols);1322 SectionList *sections = m_objfile->GetModule()->GetSectionList();1323 for (uint32_t i=0; i<num_symbols; ++i) {1324 if (!m_symbols[i].Decode(data, offset_ptr, sections, strtab))1325 return false;1326 }1327 }1328 1329 { // Scope for "elapsed" object below so it can measure the time to index.1330 ElapsedTime elapsed(m_objfile->GetModule()->GetSymtabIndexTime());1331 const uint8_t num_cstr_maps = data.GetU8(offset_ptr);1332 for (uint8_t i=0; i<num_cstr_maps; ++i) {1333 uint8_t type = data.GetU8(offset_ptr);1334 UniqueCStringMap<uint32_t> &cstr_map =1335 GetNameToSymbolIndexMap((lldb::FunctionNameType)type);1336 if (!DecodeCStrMap(data, offset_ptr, strtab, cstr_map))1337 return false;1338 }1339 m_name_indexes_computed = true;1340 }1341 return true;1342}1343 1344bool Symtab::LoadFromCache() {1345 DataFileCache *cache = Module::GetIndexCache();1346 if (!cache)1347 return false;1348 1349 std::unique_ptr<llvm::MemoryBuffer> mem_buffer_up =1350 cache->GetCachedData(GetCacheKey());1351 if (!mem_buffer_up)1352 return false;1353 DataExtractor data(mem_buffer_up->getBufferStart(),1354 mem_buffer_up->getBufferSize(),1355 m_objfile->GetByteOrder(),1356 m_objfile->GetAddressByteSize());1357 bool signature_mismatch = false;1358 lldb::offset_t offset = 0;1359 const bool result = Decode(data, &offset, signature_mismatch);1360 if (signature_mismatch)1361 cache->RemoveCacheFile(GetCacheKey());1362 if (result)1363 SetWasLoadedFromCache();1364 return result;1365}1366