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