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