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