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