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