LLDB mainline
Symtab.cpp
Go to the documentation of this file.
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 <array>
10#include <bitset>
11#include <map>
12#include <set>
13
15#include "lldb/Core/Module.h"
16#include "lldb/Core/Section.h"
18#include "lldb/Symbol/Symbol.h"
20#include "lldb/Symbol/Symtab.h"
23#include "lldb/Utility/Endian.h"
25#include "lldb/Utility/Stream.h"
26#include "lldb/Utility/Timer.h"
27
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/StringRef.h"
30#include "llvm/Support/DJB.h"
31
32using namespace lldb;
33using namespace lldb_private;
34
36 : m_objfile(objfile), m_file_addr_to_index(*this) {
37 m_name_to_symbol_indices.emplace(std::make_pair(
38 lldb::eFunctionNameTypeNone, UniqueCStringMap<uint32_t>()));
39 m_name_to_symbol_indices.emplace(std::make_pair(
40 lldb::eFunctionNameTypeBase, UniqueCStringMap<uint32_t>()));
41 m_name_to_symbol_indices.emplace(std::make_pair(
42 lldb::eFunctionNameTypeMethod, UniqueCStringMap<uint32_t>()));
43 m_name_to_symbol_indices.emplace(std::make_pair(
44 lldb::eFunctionNameTypeSelector, UniqueCStringMap<uint32_t>()));
45}
46
47Symtab::~Symtab() = default;
48
49void Symtab::Reserve(size_t count) {
50 // Clients should grab the mutex from this symbol table and lock it manually
51 // when calling this function to avoid performance issues.
52 m_symbols.reserve(count);
53}
54
55Symbol *Symtab::Resize(size_t count) {
56 // Clients should grab the mutex from this symbol table and lock it manually
57 // when calling this function to avoid performance issues.
58 m_symbols.resize(count);
59 // Callers fill in the new symbols through the returned pointer, and one of
60 // them may be a source file symbol. If we already know there are source
61 // files, that stays true. Otherwise calculate this again when it is
62 // requested, unless the object file plug-in sets it.
63 if (!m_has_source_files.value_or(false))
64 m_has_source_files.reset();
65 return m_symbols.empty() ? nullptr : &m_symbols[0];
66}
67
68uint32_t Symtab::AddSymbol(const Symbol &symbol) {
69 // Clients should grab the mutex from this symbol table and lock it manually
70 // when calling this function to avoid performance issues.
71 uint32_t symbol_idx = m_symbols.size();
72 auto &name_to_index = GetNameToSymbolIndexMap(lldb::eFunctionNameTypeNone);
73 name_to_index.Clear();
75 m_symbols.push_back(symbol);
78 if (symbol.GetType() == eSymbolTypeSourceFile)
79 m_has_source_files = true;
80 return symbol_idx;
81}
82
83size_t Symtab::GetNumSymbols() const {
84 std::lock_guard<std::recursive_mutex> guard(m_mutex);
85 return m_symbols.size();
86}
87
89 m_has_source_files = llvm::any_of(m_symbols, [](const Symbol &symbol) {
90 return symbol.GetType() == eSymbolTypeSourceFile;
91 });
92}
93
94void Symtab::SetHasDebugMap(bool has_debug_map) {
95 std::lock_guard<std::recursive_mutex> guard(m_mutex);
96 m_has_debug_map = has_debug_map;
97}
98
99bool Symtab::HasDebugMap() const {
100 std::lock_guard<std::recursive_mutex> guard(m_mutex);
101 return m_has_debug_map;
102}
103
104void Symtab::SetHasSourceFiles(bool has_source_files) {
105 std::lock_guard<std::recursive_mutex> guard(m_mutex);
106 m_has_source_files = has_source_files;
107}
108
110 std::lock_guard<std::recursive_mutex> guard(m_mutex);
113 return *m_has_source_files;
114}
115
120
121void Symtab::Dump(Stream *s, Target *target, SortOrder sort_order,
122 Mangled::NamePreference name_preference) {
123 std::lock_guard<std::recursive_mutex> guard(m_mutex);
124
125 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
126 s->Indent();
127 const FileSpec &file_spec = m_objfile->GetFileSpec();
128 llvm::StringRef object_name;
129 if (m_objfile->GetModule())
130 object_name = m_objfile->GetModule()->GetObjectName();
131
132 if (file_spec)
133 s->Format("Symtab, file = {0}{1}{2}{3}, num_symbols = {4}",
134 file_spec.GetPath(), !object_name.empty() ? "(" : "",
135 !object_name.empty() ? object_name : "",
136 !object_name.empty() ? ")" : "", (uint64_t)m_symbols.size());
137 else
138 s->Printf("Symtab, num_symbols = %" PRIu64 "", (uint64_t)m_symbols.size());
139
140 if (!m_symbols.empty()) {
141 switch (sort_order) {
142 case eSortOrderNone: {
143 s->PutCString(":\n");
145 const_iterator begin = m_symbols.begin();
146 const_iterator end = m_symbols.end();
147 for (const_iterator pos = m_symbols.begin(); pos != end; ++pos) {
148 s->Indent();
149 pos->Dump(s, target, std::distance(begin, pos), name_preference);
150 }
151 }
152 break;
153
154 case eSortOrderByName: {
155 // Although we maintain a lookup by exact name map, the table isn't
156 // sorted by name. So we must make the ordered symbol list up ourselves.
157 s->PutCString(" (sorted by name):\n");
159
160 std::multimap<llvm::StringRef, const Symbol *> name_map;
161 for (const Symbol &symbol : m_symbols)
162 name_map.emplace(symbol.GetName().GetStringRef(), &symbol);
163
164 for (const auto &name_to_symbol : name_map) {
165 const Symbol *symbol = name_to_symbol.second;
166 s->Indent();
167 symbol->Dump(s, target, symbol - &m_symbols[0], name_preference);
168 }
169 } break;
170
171 case eSortOrderBySize: {
172 s->PutCString(" (sorted by size):\n");
174
175 std::multimap<size_t, const Symbol *, std::greater<size_t>> size_map;
176 for (const Symbol &symbol : m_symbols)
177 size_map.emplace(symbol.GetByteSize(), &symbol);
178
179 size_t idx = 0;
180 for (const auto &size_to_symbol : size_map) {
181 const Symbol *symbol = size_to_symbol.second;
182 s->Indent();
183 symbol->Dump(s, target, idx++, name_preference);
184 }
185 } break;
186
188 s->PutCString(" (sorted by address):\n");
192 const size_t num_entries = m_file_addr_to_index.GetSize();
193 for (size_t i = 0; i < num_entries; ++i) {
194 s->Indent();
195 const uint32_t symbol_idx = m_file_addr_to_index.GetEntryRef(i).data;
196 m_symbols[symbol_idx].Dump(s, target, symbol_idx, name_preference);
197 }
198 break;
199 }
200 } else {
201 s->PutCString("\n");
202 }
203}
204
205void Symtab::Dump(Stream *s, Target *target, std::vector<uint32_t> &indexes,
206 Mangled::NamePreference name_preference) const {
207 std::lock_guard<std::recursive_mutex> guard(m_mutex);
208
209 const size_t num_symbols = GetNumSymbols();
210 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
211 s->Indent();
212 s->Printf("Symtab %" PRIu64 " symbol indexes (%" PRIu64 " symbols total):\n",
213 (uint64_t)indexes.size(), (uint64_t)m_symbols.size());
214 s->IndentMore();
215
216 if (!indexes.empty()) {
217 std::vector<uint32_t>::const_iterator pos;
218 std::vector<uint32_t>::const_iterator end = indexes.end();
220 for (pos = indexes.begin(); pos != end; ++pos) {
221 size_t idx = *pos;
222 if (idx < num_symbols) {
223 s->Indent();
224 m_symbols[idx].Dump(s, target, idx, name_preference);
225 }
226 }
227 }
228 s->IndentLess();
229}
230
232 s->Indent(" Debug symbol\n");
233 s->Indent(" |Synthetic symbol\n");
234 s->Indent(" ||Externally Visible\n");
235 s->Indent(" |||\n");
236 s->Indent("Index UserID DSX Type File Address/Value Load "
237 "Address Size Flags Name\n");
238 s->Indent("------- ------ --- --------------- ------------------ "
239 "------------------ ------------------ ---------- "
240 "----------------------------------\n");
241}
242
243static int CompareSymbolID(const void *key, const void *p) {
244 const user_id_t match_uid = *(const user_id_t *)key;
245 const user_id_t symbol_uid = ((const Symbol *)p)->GetID();
246 if (match_uid < symbol_uid)
247 return -1;
248 if (match_uid > symbol_uid)
249 return 1;
250 return 0;
251}
252
254 std::lock_guard<std::recursive_mutex> guard(m_mutex);
255
256 Symbol *symbol =
257 (Symbol *)::bsearch(&symbol_uid, &m_symbols[0], m_symbols.size(),
258 sizeof(m_symbols[0]), CompareSymbolID);
259 return symbol;
260}
261
263 // Clients should grab the mutex from this symbol table and lock it manually
264 // when calling this function to avoid performance issues.
265 if (idx < m_symbols.size())
266 return &m_symbols[idx];
267 return nullptr;
268}
269
270const Symbol *Symtab::SymbolAtIndex(size_t idx) const {
271 // Clients should grab the mutex from this symbol table and lock it manually
272 // when calling this function to avoid performance issues.
273 if (idx < m_symbols.size())
274 return &m_symbols[idx];
275 return nullptr;
276}
277
279 // Protected function, no need to lock mutex...
281 return;
282
284 ElapsedTime elapsed(m_objfile->GetModule()->GetSymtabIndexTime());
286
287 // Collect all loaded language plugins.
288 std::vector<Language *> languages;
289 Language::ForEach([&languages](Language *l) {
290 languages.push_back(l);
292 });
293
294 auto &name_to_index = GetNameToSymbolIndexMap(lldb::eFunctionNameTypeNone);
295 auto &basename_to_index =
296 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeBase);
297 auto &method_to_index =
298 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeMethod);
299 auto &selector_to_index =
300 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeSelector);
301 // Create the name index vector to be able to quickly search by name
302 const size_t num_symbols = m_symbols.size();
303 name_to_index.Reserve(num_symbols);
304
305 // The "const char *" in "class_contexts" and backlog::value_type::second
306 // must come from a ConstString::GetCString()
307 std::set<const char *> class_contexts;
308 std::vector<std::pair<NameToIndexMap::Entry, const char *>> backlog;
309 backlog.reserve(num_symbols / 2);
310
311 // A single parser per mangling scheme handles all of its names, so that it
312 // can reuse its demangler. Parsers are only created for the schemes that
313 // occur, and a nullptr means that no language parses the scheme.
314 std::array<std::unique_ptr<Language::MangledNameParser>,
316 parsers;
317 std::bitset<Mangled::g_num_mangling_schemes> created_parsers;
318 auto parse_function_name =
319 [&](const Mangled &mangled) -> std::optional<Mangled::FunctionNameParts> {
321 Mangled::GetManglingScheme(mangled.GetMangledName().GetStringRef());
322 if (!created_parsers.test(scheme)) {
323 created_parsers.set(scheme);
325 parsers[scheme] = lang->CreateMangledNameParser(scheme);
326 }
327 if (!parsers[scheme])
328 return std::nullopt;
329 return parsers[scheme]->Parse(mangled);
330 };
331 for (size_t value = 0; value < num_symbols; ++value) {
332 Symbol *symbol = &m_symbols[value];
333
334 // Don't let trampolines get into the lookup by name map If we ever need
335 // the trampoline symbols to be searchable by name we can remove this and
336 // then possibly add a new bool to any of the Symtab functions that
337 // lookup symbols by name to indicate if they want trampolines. We also
338 // don't want any synthetic symbols with auto generated names in the
339 // name lookups.
340 if (symbol->IsTrampoline() || symbol->IsSyntheticWithAutoGeneratedName())
341 continue;
342
343 // If the symbol's name string matched a Mangled::ManglingScheme, it is
344 // stored in the mangled field.
345 Mangled &mangled = symbol->GetMangled();
346 if (ConstString name = mangled.GetMangledName()) {
347 name_to_index.Append(name, value);
348
349 if (symbol->ContainsLinkerAnnotations()) {
350 // If the symbol has linker annotations, also add the version without
351 // the annotations.
352 ConstString stripped = ConstString(
353 m_objfile->StripLinkerSymbolAnnotations(name.GetStringRef()));
354 name_to_index.Append(stripped, value);
355 }
356
357 const SymbolType type = symbol->GetType();
358 if (type == eSymbolTypeCode || type == eSymbolTypeResolver) {
359 if (std::optional<Mangled::FunctionNameParts> parts =
360 parse_function_name(mangled)) {
361 RegisterMangledNameEntry(value, *parts, class_contexts, backlog);
362 continue;
363 }
364 }
365 }
366
367 // Symbol name strings that didn't match a Mangled::ManglingScheme, are
368 // stored in the demangled field.
369 if (ConstString name = mangled.GetDemangledName()) {
370 name_to_index.Append(name, value);
371
372 if (symbol->ContainsLinkerAnnotations()) {
373 // If the symbol has linker annotations, also add the version without
374 // the annotations.
375 name = ConstString(
376 m_objfile->StripLinkerSymbolAnnotations(name.GetStringRef()));
377 name_to_index.Append(name, value);
378 }
379
380 // If the demangled name turns out to be an ObjC name, and is a category
381 // name, add the version without categories to the index too.
382 for (Language *lang : languages) {
383 for (auto variant : lang->GetMethodNameVariants(name)) {
384 if (variant.GetType() & lldb::eFunctionNameTypeSelector)
385 selector_to_index.Append(ConstString(variant.GetName()), value);
386 else if (variant.GetType() & lldb::eFunctionNameTypeFull)
387 name_to_index.Append(ConstString(variant.GetName()), value);
388 else if (variant.GetType() & lldb::eFunctionNameTypeMethod)
389 method_to_index.Append(ConstString(variant.GetName()), value);
390 else if (variant.GetType() & lldb::eFunctionNameTypeBase)
391 basename_to_index.Append(ConstString(variant.GetName()), value);
392 }
393 }
394 }
395 }
396
397 for (const auto &record : backlog)
398 RegisterBacklogEntry(record.first, record.second, class_contexts);
399
400 name_to_index.Sort();
401 name_to_index.SizeToFit();
402 selector_to_index.Sort();
403 selector_to_index.SizeToFit();
404 basename_to_index.Sort();
405 basename_to_index.SizeToFit();
406 method_to_index.Sort();
407 method_to_index.SizeToFit();
408}
409
411 uint32_t value, const Mangled::FunctionNameParts &parts,
412 std::set<const char *> &class_contexts,
413 std::vector<std::pair<NameToIndexMap::Entry, const char *>> &backlog) {
414 // Only register functions that have a base name.
415 if (!parts.basename)
416 return;
417
418 // The base name will be our entry's name.
419 NameToIndexMap::Entry entry(parts.basename, value);
420
421 switch (parts.kind) {
423 // This has to be a basename
424 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeBase).Append(entry);
425 // If there is no context (no namespaces or class scopes that come before
426 // the function name) then this also could be a fullname.
427 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeNone).Append(entry);
428 return;
429
431 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeBase).Append(entry);
432 return;
433
435 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeMethod).Append(entry);
436 return;
437
438 // Register constructors and destructors. They are methods and create
439 // declaration contexts.
441 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeMethod).Append(entry);
442 class_contexts.insert(parts.decl_context.GetCString());
443 return;
444
446 const char *decl_context_ccstr = parts.decl_context.GetCString();
447
448 // Register regular methods with a known declaration context.
449 if (class_contexts.count(decl_context_ccstr)) {
450 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeMethod).Append(entry);
451 return;
452 }
453
454 // Regular methods in unknown declaration contexts are put to the backlog.
455 // We will revisit them once we processed all remaining symbols.
456 backlog.push_back(std::make_pair(entry, decl_context_ccstr));
457 return;
458 }
459 }
460 llvm_unreachable("unknown function name kind");
461}
462
464 const NameToIndexMap::Entry &entry, const char *decl_context,
465 const std::set<const char *> &class_contexts) {
466 auto &method_to_index =
467 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeMethod);
468 auto it = class_contexts.find(decl_context);
469 if (it != class_contexts.end()) {
470 method_to_index.Append(entry);
471 } else {
472 // If we got here, we have something that had a context (was inside
473 // a namespace or class) yet we don't know the entry
474 method_to_index.Append(entry);
475 auto &basename_to_index =
476 GetNameToSymbolIndexMap(lldb::eFunctionNameTypeBase);
477 basename_to_index.Append(entry);
478 }
479}
480
482 std::lock_guard<std::recursive_mutex> guard(m_mutex);
484}
485
487 std::vector<uint32_t> &indexes,
488 uint32_t start_idx,
489 uint32_t end_index) const {
490 std::lock_guard<std::recursive_mutex> guard(m_mutex);
491
492 uint32_t prev_size = indexes.size();
493
494 const uint32_t count = std::min<uint32_t>(m_symbols.size(), end_index);
495
496 for (uint32_t i = start_idx; i < count; ++i) {
497 if (symbol_type == eSymbolTypeAny || m_symbols[i].GetType() == symbol_type)
498 indexes.push_back(i);
499 }
500
501 return indexes.size() - prev_size;
502}
503
505 SymbolType symbol_type, uint32_t flags_value,
506 std::vector<uint32_t> &indexes, uint32_t start_idx,
507 uint32_t end_index) const {
508 std::lock_guard<std::recursive_mutex> guard(m_mutex);
509
510 uint32_t prev_size = indexes.size();
511
512 const uint32_t count = std::min<uint32_t>(m_symbols.size(), end_index);
513
514 for (uint32_t i = start_idx; i < count; ++i) {
515 if ((symbol_type == eSymbolTypeAny ||
516 m_symbols[i].GetType() == symbol_type) &&
517 m_symbols[i].GetFlags() == flags_value)
518 indexes.push_back(i);
519 }
520
521 return indexes.size() - prev_size;
522}
523
525 Debug symbol_debug_type,
526 Visibility symbol_visibility,
527 std::vector<uint32_t> &indexes,
528 uint32_t start_idx,
529 uint32_t end_index) const {
530 std::lock_guard<std::recursive_mutex> guard(m_mutex);
531
532 uint32_t prev_size = indexes.size();
533
534 const uint32_t count = std::min<uint32_t>(m_symbols.size(), end_index);
535
536 for (uint32_t i = start_idx; i < count; ++i) {
537 if (symbol_type == eSymbolTypeAny ||
538 m_symbols[i].GetType() == symbol_type) {
539 if (CheckSymbolAtIndex(i, symbol_debug_type, symbol_visibility))
540 indexes.push_back(i);
541 }
542 }
543
544 return indexes.size() - prev_size;
545}
546
547uint32_t Symtab::GetIndexForSymbol(const Symbol *symbol) const {
548 if (!m_symbols.empty()) {
549 const Symbol *first_symbol = &m_symbols[0];
550 if (symbol >= first_symbol && symbol < first_symbol + m_symbols.size())
551 return symbol - first_symbol;
552 }
553 return UINT32_MAX;
554}
555
559};
560
561namespace {
562struct SymbolIndexComparator {
563 const std::vector<Symbol> &symbols;
564 std::vector<lldb::addr_t> &addr_cache;
565
566 // Getting from the symbol to the Address to the File Address involves some
567 // work. Since there are potentially many symbols here, and we're using this
568 // for sorting so we're going to be computing the address many times, cache
569 // that in addr_cache. The array passed in has to be the same size as the
570 // symbols array passed into the member variable symbols, and should be
571 // initialized with LLDB_INVALID_ADDRESS.
572 // NOTE: You have to make addr_cache externally and pass it in because
573 // std::stable_sort
574 // makes copies of the comparator it is initially passed in, and you end up
575 // spending huge amounts of time copying this array...
576
577 SymbolIndexComparator(const std::vector<Symbol> &s,
578 std::vector<lldb::addr_t> &a)
579 : symbols(s), addr_cache(a) {
580 assert(symbols.size() == addr_cache.size());
581 }
582 bool operator()(uint32_t index_a, uint32_t index_b) {
583 addr_t value_a = addr_cache[index_a];
584 if (value_a == LLDB_INVALID_ADDRESS) {
585 value_a = symbols[index_a].GetAddressRef().GetFileAddress();
586 addr_cache[index_a] = value_a;
587 }
588
589 addr_t value_b = addr_cache[index_b];
590 if (value_b == LLDB_INVALID_ADDRESS) {
591 value_b = symbols[index_b].GetAddressRef().GetFileAddress();
592 addr_cache[index_b] = value_b;
593 }
594
595 if (value_a == value_b) {
596 // The if the values are equal, use the original symbol user ID
597 lldb::user_id_t uid_a = symbols[index_a].GetID();
598 lldb::user_id_t uid_b = symbols[index_b].GetID();
599 if (uid_a < uid_b)
600 return true;
601 if (uid_a > uid_b)
602 return false;
603 return false;
604 } else if (value_a < value_b)
605 return true;
606
607 return false;
608 }
609};
610}
611
612void Symtab::SortSymbolIndexesByValue(std::vector<uint32_t> &indexes,
613 bool remove_duplicates) const {
614 std::lock_guard<std::recursive_mutex> guard(m_mutex);
616 // No need to sort if we have zero or one items...
617 if (indexes.size() <= 1)
618 return;
619
620 // Sort the indexes in place using std::stable_sort.
621 // NOTE: The use of std::stable_sort instead of llvm::sort here is strictly
622 // for performance, not correctness. The indexes vector tends to be "close"
623 // to sorted, which the stable sort handles better.
624
625 std::vector<lldb::addr_t> addr_cache(m_symbols.size(), LLDB_INVALID_ADDRESS);
626
627 SymbolIndexComparator comparator(m_symbols, addr_cache);
628 llvm::stable_sort(indexes, comparator);
629
630 // Remove any duplicates if requested
631 if (remove_duplicates) {
632 auto last = llvm::unique(indexes);
633 indexes.erase(last, indexes.end());
634 }
635}
636
638 std::vector<uint32_t> &indexes) {
639 auto &name_to_index = GetNameToSymbolIndexMap(lldb::eFunctionNameTypeNone);
640 const uint32_t count = name_to_index.GetValues(symbol_name, indexes);
641 if (count)
642 return count;
643 // Synthetic symbol names are not added to the name indexes, but they start
644 // with a prefix and end with the symbol file address. This allows users to
645 // find these symbols without having to add them to the name indexes. These
646 // queries will not happen very often since the names don't mean anything, so
647 // performance is not paramount in this case.
648 llvm::StringRef name = symbol_name.GetStringRef();
649 // String the synthetic prefix if the name starts with it.
650 if (!name.consume_front(Symbol::GetSyntheticSymbolPrefix()))
651 return 0; // Not a synthetic symbol name
652
653 // Extract the file address from the symbol name
654 unsigned long long file_address = 0;
655 if (getAsUnsignedInteger(name, /*Radix=*/16, file_address))
656 return 0; // Failed to extract the user ID as an integer
657
658 const Symbol *symbol =
659 FindSymbolAtFileAddress(static_cast<addr_t>(file_address));
660 if (symbol == nullptr)
661 return 0;
662 const uint32_t symbol_idx = GetIndexForSymbol(symbol);
663 if (symbol_idx == UINT32_MAX)
664 return 0;
665 indexes.push_back(symbol_idx);
666 return 1;
667}
668
670 std::vector<uint32_t> &indexes) {
671 std::lock_guard<std::recursive_mutex> guard(m_mutex);
672
673 if (symbol_name) {
675
676 return GetNameIndexes(symbol_name, indexes);
677 }
678 return 0;
679}
680
682 Debug symbol_debug_type,
683 Visibility symbol_visibility,
684 std::vector<uint32_t> &indexes) {
685 std::lock_guard<std::recursive_mutex> guard(m_mutex);
686
688 if (symbol_name) {
689 const size_t old_size = indexes.size();
691
692 std::vector<uint32_t> all_name_indexes;
693 const size_t name_match_count =
694 GetNameIndexes(symbol_name, all_name_indexes);
695 for (size_t i = 0; i < name_match_count; ++i) {
696 if (CheckSymbolAtIndex(all_name_indexes[i], symbol_debug_type,
697 symbol_visibility))
698 indexes.push_back(all_name_indexes[i]);
699 }
700 return indexes.size() - old_size;
701 }
702 return 0;
703}
704
705uint32_t
707 SymbolType symbol_type,
708 std::vector<uint32_t> &indexes) {
709 std::lock_guard<std::recursive_mutex> guard(m_mutex);
710
711 if (AppendSymbolIndexesWithName(symbol_name, indexes) > 0 &&
712 symbol_type != eSymbolTypeAny) {
713 llvm::erase_if(indexes, [this, symbol_type](uint32_t index) {
714 return m_symbols[index].GetType() != symbol_type;
715 });
716 }
717 return indexes.size();
718}
719
721 ConstString symbol_name, SymbolType symbol_type,
722 Debug symbol_debug_type, Visibility symbol_visibility,
723 std::vector<uint32_t> &indexes) {
724 std::lock_guard<std::recursive_mutex> guard(m_mutex);
725
726 if (AppendSymbolIndexesWithName(symbol_name, symbol_debug_type,
727 symbol_visibility, indexes) > 0 &&
728 symbol_type != eSymbolTypeAny) {
729 llvm::erase_if(indexes, [this, symbol_type](uint32_t index) {
730 return m_symbols[index].GetType() != symbol_type;
731 });
732 }
733 return indexes.size();
734}
735
737 const RegularExpression &regexp, SymbolType symbol_type,
738 std::vector<uint32_t> &indexes, Mangled::NamePreference name_preference) {
739 std::lock_guard<std::recursive_mutex> guard(m_mutex);
740
741 uint32_t prev_size = indexes.size();
742 uint32_t sym_end = m_symbols.size();
743
744 for (uint32_t i = 0; i < sym_end; i++) {
745 if (symbol_type == eSymbolTypeAny ||
746 m_symbols[i].GetType() == symbol_type) {
747 const char *name =
748 m_symbols[i].GetMangled().GetName(name_preference).AsCString(nullptr);
749 if (name) {
750 if (regexp.Execute(name))
751 indexes.push_back(i);
752 }
753 }
754 }
755 return indexes.size() - prev_size;
756}
757
759 const RegularExpression &regexp, SymbolType symbol_type,
760 Debug symbol_debug_type, Visibility symbol_visibility,
761 std::vector<uint32_t> &indexes, Mangled::NamePreference name_preference) {
762 std::lock_guard<std::recursive_mutex> guard(m_mutex);
763
764 uint32_t prev_size = indexes.size();
765 uint32_t sym_end = m_symbols.size();
766
767 for (uint32_t i = 0; i < sym_end; i++) {
768 if (symbol_type == eSymbolTypeAny ||
769 m_symbols[i].GetType() == symbol_type) {
770 if (!CheckSymbolAtIndex(i, symbol_debug_type, symbol_visibility))
771 continue;
772
773 const char *name =
774 m_symbols[i].GetMangled().GetName(name_preference).AsCString(nullptr);
775 if (name) {
776 if (regexp.Execute(name))
777 indexes.push_back(i);
778 }
779 }
780 }
781 return indexes.size() - prev_size;
782}
783
785 Debug symbol_debug_type,
786 Visibility symbol_visibility,
787 uint32_t &start_idx) {
788 std::lock_guard<std::recursive_mutex> guard(m_mutex);
789
790 const size_t count = m_symbols.size();
791 for (size_t idx = start_idx; idx < count; ++idx) {
792 if (symbol_type == eSymbolTypeAny ||
793 m_symbols[idx].GetType() == symbol_type) {
794 if (CheckSymbolAtIndex(idx, symbol_debug_type, symbol_visibility)) {
795 start_idx = idx;
796 return &m_symbols[idx];
797 }
798 }
799 }
800 return nullptr;
801}
802
803void
805 SymbolType symbol_type,
806 std::vector<uint32_t> &symbol_indexes) {
807 std::lock_guard<std::recursive_mutex> guard(m_mutex);
808
809 // Initialize all of the lookup by name indexes before converting NAME to a
810 // uniqued string NAME_STR below.
812
813 if (name) {
814 // The string table did have a string that matched, but we need to check
815 // the symbols and match the symbol_type if any was given.
816 AppendSymbolIndexesWithNameAndType(name, symbol_type, symbol_indexes);
817 }
818}
819
821 ConstString name, SymbolType symbol_type, Debug symbol_debug_type,
822 Visibility symbol_visibility, std::vector<uint32_t> &symbol_indexes) {
823 std::lock_guard<std::recursive_mutex> guard(m_mutex);
824
826 // Initialize all of the lookup by name indexes before converting NAME to a
827 // uniqued string NAME_STR below.
829
830 if (name) {
831 // The string table did have a string that matched, but we need to check
832 // the symbols and match the symbol_type if any was given.
833 AppendSymbolIndexesWithNameAndType(name, symbol_type, symbol_debug_type,
834 symbol_visibility, symbol_indexes);
835 }
836}
837
839 const RegularExpression &regex, SymbolType symbol_type,
840 Debug symbol_debug_type, Visibility symbol_visibility,
841 std::vector<uint32_t> &symbol_indexes,
842 Mangled::NamePreference name_preference) {
843 std::lock_guard<std::recursive_mutex> guard(m_mutex);
844
845 AppendSymbolIndexesMatchingRegExAndType(regex, symbol_type, symbol_debug_type,
846 symbol_visibility, symbol_indexes,
847 name_preference);
848}
849
851 SymbolType symbol_type,
852 Debug symbol_debug_type,
853 Visibility symbol_visibility) {
854 std::lock_guard<std::recursive_mutex> guard(m_mutex);
857
858 if (name) {
859 std::vector<uint32_t> matching_indexes;
860 // The string table did have a string that matched, but we need to check
861 // the symbols and match the symbol_type if any was given.
862 if (AppendSymbolIndexesWithNameAndType(name, symbol_type, symbol_debug_type,
863 symbol_visibility,
864 matching_indexes)) {
865 std::vector<uint32_t>::const_iterator pos, end = matching_indexes.end();
866 for (pos = matching_indexes.begin(); pos != end; ++pos) {
867 Symbol *symbol = SymbolAtIndex(*pos);
868
869 if (symbol->Compare(name, symbol_type))
870 return symbol;
871 }
872 }
873 }
874 return nullptr;
875}
876
884
885// Add all the section file start address & size to the RangeVector, recusively
886// adding any children sections.
887static void AddSectionsToRangeMap(SectionList *sectlist,
888 RangeVector<addr_t, addr_t> &section_ranges) {
889 const int num_sections = sectlist->GetNumSections(0);
890 for (int i = 0; i < num_sections; i++) {
891 SectionSP sect_sp = sectlist->GetSectionAtIndex(i);
892 if (sect_sp) {
893 SectionList &child_sectlist = sect_sp->GetChildren();
894
895 // If this section has children, add the children to the RangeVector.
896 // Else add this section to the RangeVector.
897 if (child_sectlist.GetNumSections(0) > 0) {
898 AddSectionsToRangeMap(&child_sectlist, section_ranges);
899 } else {
900 // Debug info sections can share addresses with the sections that
901 // symbols are defined in.
902 size_t size = sect_sp->GetByteSize();
903 if (size > 0 && !sect_sp->ContainsOnlyDebugInfo()) {
904 addr_t base_addr = sect_sp->GetFileAddress();
906 entry.SetRangeBase(base_addr);
907 entry.SetByteSize(size);
908 section_ranges.Append(entry);
909 }
910 }
911 }
912 }
913}
914
916 // Protected function, no need to lock mutex...
917 if (!m_file_addr_to_index_computed && !m_symbols.empty()) {
919
921 const_iterator begin = m_symbols.begin();
922 const_iterator end = m_symbols.end();
923 for (const_iterator pos = m_symbols.begin(); pos != end; ++pos) {
924 if (pos->ValueIsAddress()) {
925 entry.SetRangeBase(pos->GetAddressRef().GetFileAddress());
926 entry.SetByteSize(pos->GetByteSize());
927 entry.data = std::distance(begin, pos);
928 m_file_addr_to_index.Append(entry);
929 }
930 }
931 const size_t num_entries = m_file_addr_to_index.GetSize();
932 if (num_entries > 0) {
934
935 // Create a RangeVector with the start & size of all the sections for
936 // this objfile. We'll need to check this for any FileRangeToIndexMap
937 // entries with an uninitialized size, which could potentially be a large
938 // number so reconstituting the weak pointer is busywork when it is
939 // invariant information.
940 SectionList *sectlist = m_objfile->GetSectionList();
941 RangeVector<addr_t, addr_t> section_ranges;
942 if (sectlist) {
943 AddSectionsToRangeMap(sectlist, section_ranges);
944 section_ranges.Sort();
945 }
946
947 // Iterate through the FileRangeToIndexMap and fill in the size for any
948 // entries that didn't already have a size from the Symbol (e.g. if we
949 // have a plain linker symbol with an address only, instead of debug info
950 // where we get an address and a size and a type, etc.)
951 for (size_t i = 0; i < num_entries; i++) {
953 m_file_addr_to_index.GetMutableEntryAtIndex(i);
954 if (entry->GetByteSize() == 0) {
955 addr_t curr_base_addr = entry->GetRangeBase();
956 const RangeVector<addr_t, addr_t>::Entry *containing_section =
957 section_ranges.FindEntryThatContains(curr_base_addr);
958
959 // Use the end of the section as the default max size of the symbol
960 addr_t sym_size = 0;
961 if (containing_section) {
962 sym_size =
963 containing_section->GetByteSize() -
964 (entry->GetRangeBase() - containing_section->GetRangeBase());
965 }
966
967 for (size_t j = i; j < num_entries; j++) {
968 FileRangeToIndexMap::Entry *next_entry =
969 m_file_addr_to_index.GetMutableEntryAtIndex(j);
970 addr_t next_base_addr = next_entry->GetRangeBase();
971 if (next_base_addr > curr_base_addr) {
972 addr_t size_to_next_symbol = next_base_addr - curr_base_addr;
973
974 // Take the difference between this symbol and the next one as
975 // its size, if it is less than the size of the section.
976 if (sym_size == 0 || size_to_next_symbol < sym_size) {
977 sym_size = size_to_next_symbol;
978 }
979 break;
980 }
981 }
982
983 if (sym_size > 0) {
984 entry->SetByteSize(sym_size);
985 Symbol &symbol = m_symbols[entry->data];
986 symbol.SetByteSize(sym_size);
987 symbol.SetSizeIsSynthesized(true);
988 }
989 }
990 }
991
992 // Sort again in case the range size changes the ordering
994 }
995 }
996}
997
999 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1000 // Calculate the size of symbols inside InitAddressIndexes.
1002 // Shrink to fit the symbols so we don't waste memory
1003 m_symbols.shrink_to_fit();
1004 SaveToCache();
1005}
1006
1008 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1011
1012 const FileRangeToIndexMap::Entry *entry =
1013 m_file_addr_to_index.FindEntryStartsAt(file_addr);
1014 if (entry) {
1015 Symbol *symbol = SymbolAtIndex(entry->data);
1016 if (symbol->GetFileAddress() == file_addr)
1017 return symbol;
1018 }
1019 return nullptr;
1020}
1021
1023 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1024
1027
1028 const FileRangeToIndexMap::Entry *entry =
1029 m_file_addr_to_index.FindEntryThatContains(file_addr);
1030 if (entry) {
1031 Symbol *symbol = SymbolAtIndex(entry->data);
1032 if (symbol->ContainsFileAddress(file_addr))
1033 return symbol;
1034 }
1035 return nullptr;
1036}
1037
1039 addr_t file_addr, std::function<bool(Symbol *)> const &callback) {
1040 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1041
1044
1045 std::vector<uint32_t> all_addr_indexes;
1046
1047 // Get all symbols with file_addr
1048 const size_t addr_match_count =
1049 m_file_addr_to_index.FindEntryIndexesThatContain(file_addr,
1050 all_addr_indexes);
1051
1052 for (size_t i = 0; i < addr_match_count; ++i) {
1053 Symbol *symbol = SymbolAtIndex(all_addr_indexes[i]);
1054 if (symbol->ContainsFileAddress(file_addr)) {
1055 if (!callback(symbol))
1056 break;
1057 }
1058 }
1059}
1060
1062 std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list) {
1063 // No need to protect this call using m_mutex all other method calls are
1064 // already thread safe.
1065
1066 const bool merge_symbol_into_function = true;
1067 size_t num_indices = symbol_indexes.size();
1068 if (num_indices > 0) {
1069 SymbolContext sc;
1070 sc.module_sp = m_objfile->GetModule();
1071 for (size_t i = 0; i < num_indices; i++) {
1072 sc.symbol = SymbolAtIndex(symbol_indexes[i]);
1073 if (sc.symbol)
1074 sc_list.AppendIfUnique(sc, merge_symbol_into_function);
1075 }
1076 }
1077}
1078
1079void Symtab::FindFunctionSymbols(ConstString name, uint32_t name_type_mask,
1080 SymbolContextList &sc_list) {
1081 std::vector<uint32_t> symbol_indexes;
1082
1083 // eFunctionNameTypeAuto should be pre-resolved by a call to
1084 // Module::LookupInfo::LookupInfo()
1085 assert((name_type_mask & eFunctionNameTypeAuto) == 0);
1086
1087 if (name_type_mask & (eFunctionNameTypeBase | eFunctionNameTypeFull)) {
1088 std::vector<uint32_t> temp_symbol_indexes;
1089 FindAllSymbolsWithNameAndType(name, eSymbolTypeAny, temp_symbol_indexes);
1090
1091 unsigned temp_symbol_indexes_size = temp_symbol_indexes.size();
1092 if (temp_symbol_indexes_size > 0) {
1093 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1094 for (unsigned i = 0; i < temp_symbol_indexes_size; i++) {
1095 SymbolContext sym_ctx;
1096 sym_ctx.symbol = SymbolAtIndex(temp_symbol_indexes[i]);
1097 if (sym_ctx.symbol) {
1098 switch (sym_ctx.symbol->GetType()) {
1099 case eSymbolTypeCode:
1103 symbol_indexes.push_back(temp_symbol_indexes[i]);
1104 break;
1105 default:
1106 break;
1107 }
1108 }
1109 }
1110 }
1111 }
1112
1113 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1115
1116 for (lldb::FunctionNameType type :
1117 {lldb::eFunctionNameTypeBase, lldb::eFunctionNameTypeMethod,
1118 lldb::eFunctionNameTypeSelector}) {
1119 if (name_type_mask & type) {
1120 auto map = GetNameToSymbolIndexMap(type);
1121
1123 for (match = map.FindFirstValueForName(name); match != nullptr;
1124 match = map.FindNextValueForName(match)) {
1125 symbol_indexes.push_back(match->value);
1126 }
1127 }
1128 }
1129
1130 if (!symbol_indexes.empty()) {
1131 llvm::sort(symbol_indexes);
1132 symbol_indexes.erase(llvm::unique(symbol_indexes), symbol_indexes.end());
1133 SymbolIndicesToSymbolContextList(symbol_indexes, sc_list);
1134 }
1135}
1136
1137const Symbol *Symtab::GetParent(Symbol *child_symbol) const {
1138 uint32_t child_idx = GetIndexForSymbol(child_symbol);
1139 if (child_idx != UINT32_MAX && child_idx > 0) {
1140 for (uint32_t idx = child_idx - 1; idx != UINT32_MAX; --idx) {
1141 const Symbol *symbol = SymbolAtIndex(idx);
1142 const uint32_t sibling_idx = symbol->GetSiblingIndex();
1143 if (sibling_idx != UINT32_MAX && sibling_idx > child_idx)
1144 return symbol;
1145 }
1146 }
1147 return nullptr;
1148}
1149
1150std::string Symtab::GetCacheKey() {
1151 std::string key;
1152 llvm::raw_string_ostream strm(key);
1153 // Symbol table can come from different object files for the same module. A
1154 // module can have one object file as the main executable and might have
1155 // another object file in a separate symbol file.
1156 strm << m_objfile->GetModule()->GetCacheKey() << "-symtab-"
1157 << llvm::format_hex(m_objfile->GetCacheHash(), 10);
1158 return key;
1159}
1160
1163 if (m_objfile->IsInMemory()) {
1164 if (m_objfile->GetDisableMemorySymtabCaching())
1165 return;
1166 else
1168 }
1169
1170 DataFileCache *cache = Module::GetIndexCache(type);
1171 if (!cache)
1172 return; // Caching is not enabled.
1173
1174 // Init the name indexes so we can cache them as well.
1176 const auto byte_order = endian::InlHostByteOrder();
1177 DataEncoder file(byte_order, /*addr_size=*/8);
1178 // Encode will return false if the symbol table's object file doesn't have
1179 // anything to make a signature from.
1180 if (Encode(file))
1181 if (cache->SetCachedData(GetCacheKey(), file.GetData()))
1183}
1184
1185constexpr llvm::StringLiteral kIdentifierCStrMap("CMAP");
1186
1187static void EncodeCStrMap(DataEncoder &encoder, ConstStringTable &strtab,
1188 const UniqueCStringMap<uint32_t> &cstr_map) {
1190 encoder.AppendU32(cstr_map.GetSize());
1191 for (const auto &entry: cstr_map) {
1192 // Make sure there are no empty strings.
1193 assert((bool)entry.cstring);
1194 encoder.AppendU32(strtab.Add(entry.cstring));
1195 encoder.AppendU32(entry.value);
1196 }
1197}
1198
1199bool DecodeCStrMap(const DataExtractor &data, lldb::offset_t *offset_ptr,
1200 const StringTableReader &strtab,
1201 UniqueCStringMap<uint32_t> &cstr_map) {
1202 llvm::StringRef identifier((const char *)data.GetData(offset_ptr, 4), 4);
1203 if (identifier != kIdentifierCStrMap)
1204 return false;
1205 const uint32_t count = data.GetU32(offset_ptr);
1206 cstr_map.Reserve(count);
1207 for (uint32_t i=0; i<count; ++i)
1208 {
1209 llvm::StringRef str(strtab.Get(data.GetU32(offset_ptr)));
1210 uint32_t value = data.GetU32(offset_ptr);
1211 // No empty strings in the name indexes in Symtab
1212 if (str.empty())
1213 return false;
1214 cstr_map.Append(ConstString(str), value);
1215 }
1216 // We must sort the UniqueCStringMap after decoding it since it is a vector
1217 // of UniqueCStringMap::Entry objects which contain a ConstString and type T.
1218 // ConstString objects are sorted by "const char *" and then type T and
1219 // the "const char *" are point values that will depend on the order in which
1220 // ConstString objects are created and in which of the 256 string pools they
1221 // are created in. So after we decode all of the entries, we must sort the
1222 // name map to ensure name lookups succeed. If we encode and decode within
1223 // the same process we wouldn't need to sort, so unit testing didn't catch
1224 // this issue when first checked in.
1225 cstr_map.Sort();
1226 return true;
1227}
1228
1229constexpr llvm::StringLiteral kIdentifierSymbolTable("SYMB");
1230constexpr uint32_t CURRENT_CACHE_VERSION = 5;
1231
1232// Bits in the flags byte of the encoded symbol table.
1233constexpr uint8_t kSymtabFlagHasDebugMap = 1u << 0;
1234constexpr uint8_t kSymtabFlagHasSourceFiles = 1u << 1;
1235
1236// If the size of the Symbol object changes, the serialized
1237// format likely also needs to change so the
1238// CURRENT_CACHE_VERSION number will need to be incremented.
1239#if __SIZEOF_POINTER__ == 8
1240static_assert(
1241 sizeof(lldb_private::Symbol) == 72,
1242 "Symbol size has changed, DataFileCache version likely needs updating");
1243#endif
1244
1245/// The encoding format for the symbol table is as follows:
1246///
1247/// Signature signature;
1248/// ConstStringTable strtab;
1249/// Identifier four character code: 'SYMB'
1250/// uint32_t version;
1251/// uint8_t flags; // kSymtabFlagHasDebugMap, kSymtabFlagHasSourceFiles
1252/// uint32_t num_symbols;
1253/// Symbol symbols[num_symbols];
1254/// uint8_t num_cstr_maps;
1255/// UniqueCStringMap<uint32_t> cstr_maps[num_cstr_maps]
1256bool Symtab::Encode(DataEncoder &encoder) const {
1257 // Name indexes must be computed before calling this function.
1259
1260 // Encode the object file's signature
1261 CacheSignature signature(m_objfile);
1262 if (!signature.Encode(encoder))
1263 return false;
1264 ConstStringTable strtab;
1265
1266 // Encode the symbol table into a separate encoder first. This allows us
1267 // gather all of the strings we will need in "strtab" as we will need to
1268 // write the string table out before the symbol table.
1269 DataEncoder symtab_encoder(encoder.GetByteOrder(),
1270 encoder.GetAddressByteSize());
1271 symtab_encoder.AppendData(kIdentifierSymbolTable);
1272 // Encode the symtab data version.
1273 symtab_encoder.AppendU32(CURRENT_CACHE_VERSION);
1274 // Encode the values the object file plug-in found when it parsed the symbol
1275 // table, so they don't need to be calculated after decoding.
1276 uint8_t symtab_flags = 0;
1277 if (m_has_debug_map)
1278 symtab_flags |= kSymtabFlagHasDebugMap;
1279 if (HasSourceFiles())
1280 symtab_flags |= kSymtabFlagHasSourceFiles;
1281 symtab_encoder.AppendU8(symtab_flags);
1282 // Encode the number of symbols.
1283 symtab_encoder.AppendU32(m_symbols.size());
1284 // Encode the symbol data for all symbols.
1285 for (const auto &symbol: m_symbols)
1286 symbol.Encode(symtab_encoder, strtab);
1287
1288 // Emit a byte for how many C string maps we emit. We will fix this up after
1289 // we emit the C string maps since we skip emitting C string maps if they are
1290 // empty.
1291 size_t num_cmaps_offset = symtab_encoder.GetByteSize();
1292 uint8_t num_cmaps = 0;
1293 symtab_encoder.AppendU8(0);
1294 for (const auto &pair: m_name_to_symbol_indices) {
1295 if (pair.second.IsEmpty())
1296 continue;
1297 ++num_cmaps;
1298 symtab_encoder.AppendU8(pair.first);
1299 EncodeCStrMap(symtab_encoder, strtab, pair.second);
1300 }
1301 if (num_cmaps > 0)
1302 symtab_encoder.PutU8(num_cmaps_offset, num_cmaps);
1303
1304 // Now that all strings have been gathered, we will emit the string table.
1305 strtab.Encode(encoder);
1306 // Followed by the symbol table data.
1307 encoder.AppendData(symtab_encoder.GetData());
1308 return true;
1309}
1310
1311bool Symtab::Decode(const DataExtractor &data, lldb::offset_t *offset_ptr) {
1312 CacheSignature signature;
1313 StringTableReader strtab;
1314 // Only set these once the symbol table has been decoded successfully.
1315 bool has_debug_map = false;
1316 bool has_source_files = false;
1317 { // Scope for "elapsed" object below so it can measure the time parse.
1318 ElapsedTime elapsed(m_objfile->GetModule()->GetSymtabParseTime());
1319 if (!signature.Decode(data, offset_ptr))
1320 return false;
1321 if (CacheSignature(m_objfile) != signature)
1322 return false;
1323 // We now decode the string table for all strings in the data cache file.
1324 if (!strtab.Decode(data, offset_ptr))
1325 return false;
1326
1327 // And now we can decode the symbol table with string table we just decoded.
1328 llvm::StringRef identifier((const char *)data.GetData(offset_ptr, 4), 4);
1329 if (identifier != kIdentifierSymbolTable)
1330 return false;
1331 const uint32_t version = data.GetU32(offset_ptr);
1332 if (version != CURRENT_CACHE_VERSION)
1333 return false;
1334 const uint8_t symtab_flags = data.GetU8(offset_ptr);
1335 has_debug_map = (symtab_flags & kSymtabFlagHasDebugMap) != 0;
1336 has_source_files = (symtab_flags & kSymtabFlagHasSourceFiles) != 0;
1337 const uint32_t num_symbols = data.GetU32(offset_ptr);
1338 if (num_symbols == 0) {
1339 m_has_debug_map = has_debug_map;
1340 m_has_source_files = has_source_files;
1341 return true;
1342 }
1343 m_symbols.resize(num_symbols);
1344 SectionList *sections = m_objfile->GetModule()->GetSectionList();
1345 for (uint32_t i=0; i<num_symbols; ++i) {
1346 if (!m_symbols[i].Decode(data, offset_ptr, sections, strtab)) {
1347 // Don't leave partially decoded symbols behind for the caller to
1348 // parse the symbol table on top of.
1349 m_symbols.clear();
1350 return false;
1351 }
1352 }
1353 }
1354
1355 { // Scope for "elapsed" object below so it can measure the time to index.
1356 ElapsedTime elapsed(m_objfile->GetModule()->GetSymtabIndexTime());
1357 const uint8_t num_cstr_maps = data.GetU8(offset_ptr);
1358 for (uint8_t i=0; i<num_cstr_maps; ++i) {
1359 uint8_t type = data.GetU8(offset_ptr);
1360 auto cstr_map =
1361 m_name_to_symbol_indices.find((lldb::FunctionNameType)type);
1362 if (cstr_map == m_name_to_symbol_indices.end() ||
1363 !DecodeCStrMap(data, offset_ptr, strtab, cstr_map->second)) {
1364 // Don't leave decoded symbols or name indexes behind for the caller
1365 // to parse the symbol table on top of.
1366 m_symbols.clear();
1367 for (auto &pair : m_name_to_symbol_indices)
1368 pair.second.Clear();
1369 return false;
1370 }
1371 }
1373 }
1374 m_has_debug_map = has_debug_map;
1375 m_has_source_files = has_source_files;
1376 return true;
1377}
1378
1381 if (m_objfile->IsInMemory()) {
1382 if (m_objfile->GetDisableMemorySymtabCaching())
1383 return false;
1384 else
1386 }
1387 DataFileCache *cache = Module::GetIndexCache(type);
1388 if (!cache)
1389 return false;
1390
1391 std::unique_ptr<llvm::MemoryBuffer> mem_buffer_up =
1392 cache->GetCachedData(GetCacheKey());
1393 if (!mem_buffer_up)
1394 return false;
1395 DataExtractor data(mem_buffer_up->getBufferStart(),
1396 mem_buffer_up->getBufferSize(),
1397 m_objfile->GetByteOrder(),
1398 m_objfile->GetAddressByteSize());
1399 lldb::offset_t offset = 0;
1400 const bool result = Decode(data, &offset);
1401 // SaveToCache won't overwrite an existing cache file, so remove any file
1402 // that can't be used or it will stop this symbol table from being cached.
1403 if (!result)
1404 cache->RemoveCacheFile(GetCacheKey());
1405 if (result)
1407 return result;
1408}
static constexpr uint32_t CURRENT_CACHE_VERSION
static double elapsed(const StatsTimepoint &start, const StatsTimepoint &end)
constexpr llvm::StringLiteral kIdentifierSymbolTable("SYMB")
bool DecodeCStrMap(const DataExtractor &data, lldb::offset_t *offset_ptr, const StringTableReader &strtab, UniqueCStringMap< uint32_t > &cstr_map)
Definition Symtab.cpp:1199
static int CompareSymbolID(const void *key, const void *p)
Definition Symtab.cpp:243
static void EncodeCStrMap(DataEncoder &encoder, ConstStringTable &strtab, const UniqueCStringMap< uint32_t > &cstr_map)
Definition Symtab.cpp:1187
static void AddSectionsToRangeMap(SectionList *sectlist, RangeVector< addr_t, addr_t > &section_ranges)
Definition Symtab.cpp:887
constexpr uint8_t kSymtabFlagHasSourceFiles
Definition Symtab.cpp:1234
constexpr uint8_t kSymtabFlagHasDebugMap
Definition Symtab.cpp:1233
constexpr llvm::StringLiteral kIdentifierCStrMap("CMAP")
#define LLDB_SCOPED_TIMER()
Definition Timer.h:88
Many cache files require string tables to store data efficiently.
bool Encode(DataEncoder &encoder)
uint32_t Add(ConstString s)
Add a string into the string table.
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const char * GetCString() const
Get the string value as a C string.
An binary data encoding class.
Definition DataEncoder.h:42
lldb::ByteOrder GetByteOrder() const
uint32_t PutU8(uint32_t offset, uint8_t value)
Encode an unsigned integer at offset offset.
llvm::ArrayRef< uint8_t > GetData() const
Get a access to the bytes that this references.
void AppendU32(uint32_t value)
size_t GetByteSize() const
Get the number of bytes contained in this object.
void AppendU8(uint8_t value)
Append a unsigned integer to the end of the owned data.
void AppendData(llvm::StringRef data)
Append bytes to the end of the owned data.
uint8_t GetAddressByteSize() const
The address size to use when encoding pointers or addresses.
An data extractor class.
virtual const void * GetData(lldb::offset_t *offset_ptr, lldb::offset_t length) const
Extract length bytes from *offset_ptr.
uint32_t GetU32(lldb::offset_t *offset_ptr) const
Extract a uint32_t value from *offset_ptr.
uint8_t GetU8(lldb::offset_t *offset_ptr) const
Extract a uint8_t value from *offset_ptr.
This class enables data to be cached into a directory using the llvm caching code.
std::unique_ptr< llvm::MemoryBuffer > GetCachedData(llvm::StringRef key)
Get cached data from the cache directory for the specified key.
bool SetCachedData(llvm::StringRef key, llvm::ArrayRef< uint8_t > data)
Set cached data for the specified key.
Status RemoveCacheFile(llvm::StringRef key)
Remove the cache file associated with the key.
A class that measures elapsed time in an exception safe way.
Definition Statistics.h:76
A file utility class.
Definition FileSpec.h:56
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
static void ForEach(llvm::function_ref< IterationAction(Language *)> callback)
Definition Language.cpp:109
static Language * FindPluginForManglingScheme(Mangled::ManglingScheme scheme)
Returns the Language that registered scheme with Mangled::RegisterManglingScheme(),...
Definition Language.cpp:88
A class that handles mangled names.
Definition Mangled.h:36
ConstString GetMangledName() const
Mangled name get accessor.
Definition Mangled.h:169
ConstString GetDemangledName() const
Demangled name get accessor.
Definition Mangled.cpp:238
static constexpr size_t g_num_mangling_schemes
The number of possible mangling schemes, which sizes the tables that are indexed by ManglingScheme.
Definition Mangled.h:51
static Mangled::ManglingScheme GetManglingScheme(llvm::StringRef name)
Try to identify the mangling scheme used.
Definition Mangled.cpp:182
@ eLLDBIndexTypeMemoryModuleSymtab
Definition Module.h:1088
static DataFileCache * GetIndexCache(LLDBIndexType type)
Get the global index file cache.
Definition Module.cpp:1736
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:47
const Entry * FindEntryThatContains(B addr) const
Definition RangeMap.h:338
void Append(const Entry &entry)
Definition RangeMap.h:179
bool Execute(llvm::StringRef string, llvm::SmallVectorImpl< llvm::StringRef > *matches=nullptr) const
Execute a regular expression match using the compiled regular expression that is already in this obje...
size_t GetNumSections(uint32_t depth) const
Definition Section.cpp:544
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:555
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:157
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:204
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:201
Many cache files require string tables to store data efficiently.
bool Decode(const DataExtractor &data, lldb::offset_t *offset_ptr)
llvm::StringRef Get(uint32_t offset) const
Defines a list of symbol context objects.
bool AppendIfUnique(const SymbolContext &sc, bool merge_symbol_into_function)
Defines a symbol context baton that can be handed other debug core functions.
lldb::ModuleSP module_sp
The Module for a given query.
Symbol * symbol
The Symbol for a given query.
uint32_t GetSiblingIndex() const
Definition Symbol.cpp:242
void SetSizeIsSynthesized(bool b)
Definition Symbol.h:219
bool ContainsLinkerAnnotations() const
Definition Symbol.h:267
lldb::addr_t GetFileAddress() const
Definition Symbol.cpp:601
bool ContainsFileAddress(lldb::addr_t file_addr) const
Definition Symbol.cpp:687
Mangled & GetMangled()
Definition Symbol.h:162
bool IsTrampoline() const
Definition Symbol.cpp:248
bool IsSyntheticWithAutoGeneratedName() const
Definition Symbol.cpp:692
bool Compare(ConstString name, lldb::SymbolType type) const
Definition Symbol.cpp:425
static llvm::StringRef GetSyntheticSymbolPrefix()
Definition Symbol.h:296
lldb::SymbolType GetType() const
Definition Symbol.h:197
void SetByteSize(lldb::addr_t size)
Definition Symbol.h:241
void Dump(Stream *s, Target *target, uint32_t index, Mangled::NamePreference name_preference=Mangled::ePreferDemangled) const
Definition Symbol.cpp:300
Symbol * FindSymbolByID(lldb::user_id_t uid) const
Definition Symtab.cpp:253
void RegisterMangledNameEntry(uint32_t value, const Mangled::FunctionNameParts &parts, std::set< const char * > &class_contexts, std::vector< std::pair< NameToIndexMap::Entry, const char * > > &backlog)
Definition Symtab.cpp:410
Symbol * SymbolAtIndex(size_t idx)
Definition Symtab.cpp:262
Symbol * FindFirstSymbolWithNameAndType(ConstString name, lldb::SymbolType symbol_type, Debug symbol_debug_type, Visibility symbol_visibility)
Definition Symtab.cpp:850
bool m_name_indexes_computed
Definition Symtab.h:325
void ForEachSymbolContainingFileAddress(lldb::addr_t file_addr, std::function< bool(Symbol *)> const &callback)
Definition Symtab.cpp:1038
Symbol * Resize(size_t count)
Definition Symtab.cpp:55
Symbol * FindSymbolAtFileAddress(lldb::addr_t file_addr)
Definition Symtab.cpp:1007
Symbol * FindSymbolContainingFileAddress(lldb::addr_t file_addr)
Definition Symtab.cpp:1022
FileRangeToIndexMap m_file_addr_to_index
Definition Symtab.h:319
std::recursive_mutex m_mutex
Provide thread safety for this symbol table.
Definition Symtab.h:315
Symbol * FindSymbolWithType(lldb::SymbolType symbol_type, Debug symbol_debug_type, Visibility symbol_visibility, uint32_t &start_idx)
Definition Symtab.cpp:784
void SortSymbolIndexesByValue(std::vector< uint32_t > &indexes, bool remove_duplicates) const
Definition Symtab.cpp:612
uint32_t AddSymbol(const Symbol &symbol)
Definition Symtab.cpp:68
std::optional< bool > m_has_source_files
Set by the object file plug-in, or calculated and cached by HasSourceFiles().
Definition Symtab.h:332
void FindAllSymbolsMatchingRexExAndType(const RegularExpression &regex, lldb::SymbolType symbol_type, Debug symbol_debug_type, Visibility symbol_visibility, std::vector< uint32_t > &symbol_indexes, Mangled::NamePreference name_preference=Mangled::ePreferDemangled)
Definition Symtab.cpp:838
uint32_t GetNameIndexes(ConstString symbol_name, std::vector< uint32_t > &indexes)
A helper function that looks up full function names.
Definition Symtab.cpp:637
bool HasDebugMap() const
Check if this symbol table has a debug map, see SetHasDebugMap().
Definition Symtab.cpp:99
void Dump(Stream *s, Target *target, SortOrder sort_type, Mangled::NamePreference name_preference=Mangled::ePreferDemangled)
Definition Symtab.cpp:121
uint32_t AppendSymbolIndexesWithName(ConstString symbol_name, std::vector< uint32_t > &matches)
Definition Symtab.cpp:669
void RegisterBacklogEntry(const NameToIndexMap::Entry &entry, const char *decl_context, const std::set< const char * > &class_contexts)
Definition Symtab.cpp:463
static void DumpSymbolHeader(Stream *s)
Definition Symtab.cpp:231
uint32_t AppendSymbolIndexesWithType(lldb::SymbolType symbol_type, std::vector< uint32_t > &indexes, uint32_t start_idx=0, uint32_t end_index=UINT32_MAX) const
Definition Symtab.cpp:486
void SetHasDebugMap(bool has_debug_map)
Set whether this symbol table has a debug map.
Definition Symtab.cpp:94
void SaveToCache()
Save the symbol table data out into a cache.
Definition Symtab.cpp:1161
void SetWasLoadedFromCache()
Accessors for the bool that indicates if the debug info index was loaded from, or saved to the module...
Definition Symtab.h:263
bool m_has_debug_map
Set by the object file plug-in, see SetHasDebugMap().
Definition Symtab.h:328
bool Decode(const DataExtractor &data, lldb::offset_t *offset_ptr)
Decode a serialized version of this object from data.
Definition Symtab.cpp:1311
size_t GetNumSymbols() const
Definition Symtab.cpp:83
ObjectFile * m_objfile
Definition Symtab.h:317
uint32_t GetIndexForSymbol(const Symbol *symbol) const
Definition Symtab.cpp:547
void SectionFileAddressesChanged()
Definition Symtab.cpp:116
bool m_file_addr_to_index_computed
Definition Symtab.h:324
bool CheckSymbolAtIndex(size_t idx, Debug symbol_debug_type, Visibility symbol_visibility) const
Definition Symtab.h:345
Symtab(ObjectFile *objfile)
Definition Symtab.cpp:35
std::map< lldb::FunctionNameType, UniqueCStringMap< uint32_t > > m_name_to_symbol_indices
Maps function names to symbol indices (grouped by FunctionNameTypes)
Definition Symtab.h:323
void FindAllSymbolsWithNameAndType(ConstString name, lldb::SymbolType symbol_type, std::vector< uint32_t > &symbol_indexes)
Definition Symtab.cpp:804
void SetHasSourceFiles(bool has_source_files)
Set whether this symbol table contains any source file symbols.
Definition Symtab.cpp:104
bool HasSourceFiles() const
Check if this symbol table contains any source file symbols.
Definition Symtab.cpp:109
uint32_t AppendSymbolIndexesWithTypeAndFlagsValue(lldb::SymbolType symbol_type, uint32_t flags_value, std::vector< uint32_t > &indexes, uint32_t start_idx=0, uint32_t end_index=UINT32_MAX) const
Definition Symtab.cpp:504
void InitAddressIndexes()
Definition Symtab.cpp:915
std::string GetCacheKey()
Get the cache key string for this symbol table.
Definition Symtab.cpp:1150
void Reserve(size_t count)
Definition Symtab.cpp:49
const Symbol * GetParent(Symbol *symbol) const
Get the parent symbol for the given symbol.
Definition Symtab.cpp:1137
collection m_symbols
Definition Symtab.h:318
void CalculateHasSourceFiles() const
Definition Symtab.cpp:88
void SetWasSavedToCache()
Definition Symtab.h:266
bool Encode(DataEncoder &encoder) const
Encode this object into a data encoder object.
Definition Symtab.cpp:1256
collection::const_iterator const_iterator
Definition Symtab.h:285
uint32_t AppendSymbolIndexesWithNameAndType(ConstString symbol_name, lldb::SymbolType symbol_type, std::vector< uint32_t > &matches)
Definition Symtab.cpp:706
void SymbolIndicesToSymbolContextList(std::vector< uint32_t > &symbol_indexes, SymbolContextList &sc_list)
Definition Symtab.cpp:1061
bool LoadFromCache()
Load the symbol table from the index cache.
Definition Symtab.cpp:1379
void FindFunctionSymbols(ConstString name, uint32_t name_type_mask, SymbolContextList &sc_list)
Definition Symtab.cpp:1079
UniqueCStringMap< uint32_t > & GetNameToSymbolIndexMap(lldb::FunctionNameType type)
Definition Symtab.h:340
uint32_t AppendSymbolIndexesMatchingRegExAndType(const RegularExpression &regex, lldb::SymbolType symbol_type, std::vector< uint32_t > &indexes, Mangled::NamePreference name_preference=Mangled::ePreferDemangled)
Definition Symtab.cpp:736
void Append(ConstString unique_cstr, const T &value)
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
lldb::ByteOrder InlHostByteOrder()
Definition Endian.h:25
A class that represents a running process on the host machine.
uint64_t offset_t
Definition lldb-types.h:86
SymbolType
Symbol types.
@ eSymbolTypeReExported
@ eSymbolTypeResolver
@ eSymbolTypeSourceFile
@ eSymbolTypeAbsolute
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::Section > SectionSP
uint64_t addr_t
Definition lldb-types.h:80
const Symtab * symtab
Definition Symtab.cpp:878
addr_t match_offset
Definition Symtab.cpp:882
Symbol * match_symbol
Definition Symtab.cpp:880
const uint32_t * match_index_ptr
Definition Symtab.cpp:881
const addr_t file_addr
Definition Symtab.cpp:879
const bool sort_by_load_addr
Definition Symtab.cpp:557
const Symbol * symbols
Definition Symtab.cpp:558
A signature for a given file on disk.
bool Decode(const DataExtractor &data, lldb::offset_t *offset_ptr)
Decode a serialized version of this object from data.
bool Encode(DataEncoder &encoder) const
Encode this object into a data encoder object.
The parts of a mangled function name used in the symbol table's indices.
Definition Mangled.h:63
ConstString basename
If empty, the symbol is only indexed by its mangled name.
Definition Mangled.h:65
ConstString decl_context
The enclosing context.
Definition Mangled.h:70
BaseType GetRangeBase() const
Definition RangeMap.h:45
SizeType GetByteSize() const
Definition RangeMap.h:87
void SetRangeBase(BaseType b)
Set the start value for the range, and keep the same size.
Definition RangeMap.h:48
void SetByteSize(SizeType s)
Definition RangeMap.h:89