1 //===-- SymbolContext.cpp ---------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Symbol/SymbolContext.h"
10 
11 #include "lldb/Core/Module.h"
12 #include "lldb/Core/ModuleSpec.h"
13 #include "lldb/Host/Host.h"
14 #include "lldb/Host/StringConvert.h"
15 #include "lldb/Symbol/Block.h"
16 #include "lldb/Symbol/CompileUnit.h"
17 #include "lldb/Symbol/ObjectFile.h"
18 #include "lldb/Symbol/Symbol.h"
19 #include "lldb/Symbol/SymbolFile.h"
20 #include "lldb/Symbol/SymbolVendor.h"
21 #include "lldb/Symbol/Variable.h"
22 #include "lldb/Target/Target.h"
23 #include "lldb/Utility/Log.h"
24 #include "lldb/Utility/StreamString.h"
25 
26 using namespace lldb;
27 using namespace lldb_private;
28 
29 SymbolContext::SymbolContext()
30     : target_sp(), module_sp(), comp_unit(nullptr), function(nullptr),
31       block(nullptr), line_entry(), symbol(nullptr), variable(nullptr) {}
32 
33 SymbolContext::SymbolContext(const ModuleSP &m, CompileUnit *cu, Function *f,
34                              Block *b, LineEntry *le, Symbol *s)
35     : target_sp(), module_sp(m), comp_unit(cu), function(f), block(b),
36       line_entry(), symbol(s), variable(nullptr) {
37   if (le)
38     line_entry = *le;
39 }
40 
41 SymbolContext::SymbolContext(const TargetSP &t, const ModuleSP &m,
42                              CompileUnit *cu, Function *f, Block *b,
43                              LineEntry *le, Symbol *s)
44     : target_sp(t), module_sp(m), comp_unit(cu), function(f), block(b),
45       line_entry(), symbol(s), variable(nullptr) {
46   if (le)
47     line_entry = *le;
48 }
49 
50 SymbolContext::SymbolContext(SymbolContextScope *sc_scope)
51     : target_sp(), module_sp(), comp_unit(nullptr), function(nullptr),
52       block(nullptr), line_entry(), symbol(nullptr), variable(nullptr) {
53   sc_scope->CalculateSymbolContext(this);
54 }
55 
56 SymbolContext::~SymbolContext() {}
57 
58 const SymbolContext &SymbolContext::operator=(const SymbolContext &rhs) {
59   if (this != &rhs) {
60     target_sp = rhs.target_sp;
61     module_sp = rhs.module_sp;
62     comp_unit = rhs.comp_unit;
63     function = rhs.function;
64     block = rhs.block;
65     line_entry = rhs.line_entry;
66     symbol = rhs.symbol;
67     variable = rhs.variable;
68   }
69   return *this;
70 }
71 
72 void SymbolContext::Clear(bool clear_target) {
73   if (clear_target)
74     target_sp.reset();
75   module_sp.reset();
76   comp_unit = nullptr;
77   function = nullptr;
78   block = nullptr;
79   line_entry.Clear();
80   symbol = nullptr;
81   variable = nullptr;
82 }
83 
84 bool SymbolContext::DumpStopContext(Stream *s, ExecutionContextScope *exe_scope,
85                                     const Address &addr, bool show_fullpaths,
86                                     bool show_module, bool show_inlined_frames,
87                                     bool show_function_arguments,
88                                     bool show_function_name) const {
89   bool dumped_something = false;
90   if (show_module && module_sp) {
91     if (show_fullpaths)
92       *s << module_sp->GetFileSpec();
93     else
94       *s << module_sp->GetFileSpec().GetFilename();
95     s->PutChar('`');
96     dumped_something = true;
97   }
98 
99   if (function != nullptr) {
100     SymbolContext inline_parent_sc;
101     Address inline_parent_addr;
102     if (!show_function_name) {
103       s->Printf("<");
104       dumped_something = true;
105     } else {
106       ConstString name;
107       if (!show_function_arguments)
108         name = function->GetNameNoArguments();
109       if (!name)
110         name = function->GetName();
111       if (name)
112         name.Dump(s);
113     }
114 
115     if (addr.IsValid()) {
116       const addr_t function_offset =
117           addr.GetOffset() -
118           function->GetAddressRange().GetBaseAddress().GetOffset();
119       if (!show_function_name) {
120         // Print +offset even if offset is 0
121         dumped_something = true;
122         s->Printf("+%" PRIu64 ">", function_offset);
123       } else if (function_offset) {
124         dumped_something = true;
125         s->Printf(" + %" PRIu64, function_offset);
126       }
127     }
128 
129     if (GetParentOfInlinedScope(addr, inline_parent_sc, inline_parent_addr)) {
130       dumped_something = true;
131       Block *inlined_block = block->GetContainingInlinedBlock();
132       const InlineFunctionInfo *inlined_block_info =
133           inlined_block->GetInlinedFunctionInfo();
134       s->Printf(
135           " [inlined] %s",
136           inlined_block_info->GetName(function->GetLanguage()).GetCString());
137 
138       lldb_private::AddressRange block_range;
139       if (inlined_block->GetRangeContainingAddress(addr, block_range)) {
140         const addr_t inlined_function_offset =
141             addr.GetOffset() - block_range.GetBaseAddress().GetOffset();
142         if (inlined_function_offset) {
143           s->Printf(" + %" PRIu64, inlined_function_offset);
144         }
145       }
146       const Declaration &call_site = inlined_block_info->GetCallSite();
147       if (call_site.IsValid()) {
148         s->PutCString(" at ");
149         call_site.DumpStopContext(s, show_fullpaths);
150       }
151       if (show_inlined_frames) {
152         s->EOL();
153         s->Indent();
154         const bool show_function_name = true;
155         return inline_parent_sc.DumpStopContext(
156             s, exe_scope, inline_parent_addr, show_fullpaths, show_module,
157             show_inlined_frames, show_function_arguments, show_function_name);
158       }
159     } else {
160       if (line_entry.IsValid()) {
161         dumped_something = true;
162         s->PutCString(" at ");
163         if (line_entry.DumpStopContext(s, show_fullpaths))
164           dumped_something = true;
165       }
166     }
167   } else if (symbol != nullptr) {
168     if (!show_function_name) {
169       s->Printf("<");
170       dumped_something = true;
171     } else if (symbol->GetName()) {
172       dumped_something = true;
173       if (symbol->GetType() == eSymbolTypeTrampoline)
174         s->PutCString("symbol stub for: ");
175       symbol->GetName().Dump(s);
176     }
177 
178     if (addr.IsValid() && symbol->ValueIsAddress()) {
179       const addr_t symbol_offset =
180           addr.GetOffset() - symbol->GetAddressRef().GetOffset();
181       if (!show_function_name) {
182         // Print +offset even if offset is 0
183         dumped_something = true;
184         s->Printf("+%" PRIu64 ">", symbol_offset);
185       } else if (symbol_offset) {
186         dumped_something = true;
187         s->Printf(" + %" PRIu64, symbol_offset);
188       }
189     }
190   } else if (addr.IsValid()) {
191     addr.Dump(s, exe_scope, Address::DumpStyleModuleWithFileAddress);
192     dumped_something = true;
193   }
194   return dumped_something;
195 }
196 
197 void SymbolContext::GetDescription(Stream *s, lldb::DescriptionLevel level,
198                                    Target *target) const {
199   if (module_sp) {
200     s->Indent("     Module: file = \"");
201     module_sp->GetFileSpec().Dump(s);
202     *s << '"';
203     if (module_sp->GetArchitecture().IsValid())
204       s->Printf(", arch = \"%s\"",
205                 module_sp->GetArchitecture().GetArchitectureName());
206     s->EOL();
207   }
208 
209   if (comp_unit != nullptr) {
210     s->Indent("CompileUnit: ");
211     comp_unit->GetDescription(s, level);
212     s->EOL();
213   }
214 
215   if (function != nullptr) {
216     s->Indent("   Function: ");
217     function->GetDescription(s, level, target);
218     s->EOL();
219 
220     Type *func_type = function->GetType();
221     if (func_type) {
222       s->Indent("   FuncType: ");
223       func_type->GetDescription(s, level, false);
224       s->EOL();
225     }
226   }
227 
228   if (block != nullptr) {
229     std::vector<Block *> blocks;
230     blocks.push_back(block);
231     Block *parent_block = block->GetParent();
232 
233     while (parent_block) {
234       blocks.push_back(parent_block);
235       parent_block = parent_block->GetParent();
236     }
237     std::vector<Block *>::reverse_iterator pos;
238     std::vector<Block *>::reverse_iterator begin = blocks.rbegin();
239     std::vector<Block *>::reverse_iterator end = blocks.rend();
240     for (pos = begin; pos != end; ++pos) {
241       if (pos == begin)
242         s->Indent("     Blocks: ");
243       else
244         s->Indent("             ");
245       (*pos)->GetDescription(s, function, level, target);
246       s->EOL();
247     }
248   }
249 
250   if (line_entry.IsValid()) {
251     s->Indent("  LineEntry: ");
252     line_entry.GetDescription(s, level, comp_unit, target, false);
253     s->EOL();
254   }
255 
256   if (symbol != nullptr) {
257     s->Indent("     Symbol: ");
258     symbol->GetDescription(s, level, target);
259     s->EOL();
260   }
261 
262   if (variable != nullptr) {
263     s->Indent("   Variable: ");
264 
265     s->Printf("id = {0x%8.8" PRIx64 "}, ", variable->GetID());
266 
267     switch (variable->GetScope()) {
268     case eValueTypeVariableGlobal:
269       s->PutCString("kind = global, ");
270       break;
271 
272     case eValueTypeVariableStatic:
273       s->PutCString("kind = static, ");
274       break;
275 
276     case eValueTypeVariableArgument:
277       s->PutCString("kind = argument, ");
278       break;
279 
280     case eValueTypeVariableLocal:
281       s->PutCString("kind = local, ");
282       break;
283 
284     case eValueTypeVariableThreadLocal:
285       s->PutCString("kind = thread local, ");
286       break;
287 
288     default:
289       break;
290     }
291 
292     s->Printf("name = \"%s\"\n", variable->GetName().GetCString());
293   }
294 }
295 
296 uint32_t SymbolContext::GetResolvedMask() const {
297   uint32_t resolved_mask = 0;
298   if (target_sp)
299     resolved_mask |= eSymbolContextTarget;
300   if (module_sp)
301     resolved_mask |= eSymbolContextModule;
302   if (comp_unit)
303     resolved_mask |= eSymbolContextCompUnit;
304   if (function)
305     resolved_mask |= eSymbolContextFunction;
306   if (block)
307     resolved_mask |= eSymbolContextBlock;
308   if (line_entry.IsValid())
309     resolved_mask |= eSymbolContextLineEntry;
310   if (symbol)
311     resolved_mask |= eSymbolContextSymbol;
312   if (variable)
313     resolved_mask |= eSymbolContextVariable;
314   return resolved_mask;
315 }
316 
317 void SymbolContext::Dump(Stream *s, Target *target) const {
318   *s << this << ": ";
319   s->Indent();
320   s->PutCString("SymbolContext");
321   s->IndentMore();
322   s->EOL();
323   s->IndentMore();
324   s->Indent();
325   *s << "Module       = " << module_sp.get() << ' ';
326   if (module_sp)
327     module_sp->GetFileSpec().Dump(s);
328   s->EOL();
329   s->Indent();
330   *s << "CompileUnit  = " << comp_unit;
331   if (comp_unit != nullptr)
332     *s << " {0x" << comp_unit->GetID() << "} "
333        << *(static_cast<FileSpec *>(comp_unit));
334   s->EOL();
335   s->Indent();
336   *s << "Function     = " << function;
337   if (function != nullptr) {
338     *s << " {0x" << function->GetID() << "} " << function->GetType()->GetName()
339        << ", address-range = ";
340     function->GetAddressRange().Dump(s, target, Address::DumpStyleLoadAddress,
341                                      Address::DumpStyleModuleWithFileAddress);
342     s->EOL();
343     s->Indent();
344     Type *func_type = function->GetType();
345     if (func_type) {
346       *s << "        Type = ";
347       func_type->Dump(s, false);
348     }
349   }
350   s->EOL();
351   s->Indent();
352   *s << "Block        = " << block;
353   if (block != nullptr)
354     *s << " {0x" << block->GetID() << '}';
355   // Dump the block and pass it a negative depth to we print all the parent
356   // blocks if (block != NULL)
357   //  block->Dump(s, function->GetFileAddress(), INT_MIN);
358   s->EOL();
359   s->Indent();
360   *s << "LineEntry    = ";
361   line_entry.Dump(s, target, true, Address::DumpStyleLoadAddress,
362                   Address::DumpStyleModuleWithFileAddress, true);
363   s->EOL();
364   s->Indent();
365   *s << "Symbol       = " << symbol;
366   if (symbol != nullptr && symbol->GetMangled())
367     *s << ' ' << symbol->GetName().AsCString();
368   s->EOL();
369   *s << "Variable     = " << variable;
370   if (variable != nullptr) {
371     *s << " {0x" << variable->GetID() << "} " << variable->GetType()->GetName();
372     s->EOL();
373   }
374   s->IndentLess();
375   s->IndentLess();
376 }
377 
378 bool lldb_private::operator==(const SymbolContext &lhs,
379                               const SymbolContext &rhs) {
380   return lhs.function == rhs.function && lhs.symbol == rhs.symbol &&
381          lhs.module_sp.get() == rhs.module_sp.get() &&
382          lhs.comp_unit == rhs.comp_unit &&
383          lhs.target_sp.get() == rhs.target_sp.get() &&
384          LineEntry::Compare(lhs.line_entry, rhs.line_entry) == 0 &&
385          lhs.variable == rhs.variable;
386 }
387 
388 bool lldb_private::operator!=(const SymbolContext &lhs,
389                               const SymbolContext &rhs) {
390   return !(lhs == rhs);
391 }
392 
393 bool SymbolContext::GetAddressRange(uint32_t scope, uint32_t range_idx,
394                                     bool use_inline_block_range,
395                                     AddressRange &range) const {
396   if ((scope & eSymbolContextLineEntry) && line_entry.IsValid()) {
397     range = line_entry.range;
398     return true;
399   }
400 
401   if ((scope & eSymbolContextBlock) && (block != nullptr)) {
402     if (use_inline_block_range) {
403       Block *inline_block = block->GetContainingInlinedBlock();
404       if (inline_block)
405         return inline_block->GetRangeAtIndex(range_idx, range);
406     } else {
407       return block->GetRangeAtIndex(range_idx, range);
408     }
409   }
410 
411   if ((scope & eSymbolContextFunction) && (function != nullptr)) {
412     if (range_idx == 0) {
413       range = function->GetAddressRange();
414       return true;
415     }
416   }
417 
418   if ((scope & eSymbolContextSymbol) && (symbol != nullptr)) {
419     if (range_idx == 0) {
420       if (symbol->ValueIsAddress()) {
421         range.GetBaseAddress() = symbol->GetAddressRef();
422         range.SetByteSize(symbol->GetByteSize());
423         return true;
424       }
425     }
426   }
427   range.Clear();
428   return false;
429 }
430 
431 LanguageType SymbolContext::GetLanguage() const {
432   LanguageType lang;
433   if (function && (lang = function->GetLanguage()) != eLanguageTypeUnknown) {
434     return lang;
435   } else if (variable &&
436              (lang = variable->GetLanguage()) != eLanguageTypeUnknown) {
437     return lang;
438   } else if (symbol && (lang = symbol->GetLanguage()) != eLanguageTypeUnknown) {
439     return lang;
440   } else if (comp_unit &&
441              (lang = comp_unit->GetLanguage()) != eLanguageTypeUnknown) {
442     return lang;
443   } else if (symbol) {
444     // If all else fails, try to guess the language from the name.
445     return symbol->GetMangled().GuessLanguage();
446   }
447   return eLanguageTypeUnknown;
448 }
449 
450 bool SymbolContext::GetParentOfInlinedScope(const Address &curr_frame_pc,
451                                             SymbolContext &next_frame_sc,
452                                             Address &next_frame_pc) const {
453   next_frame_sc.Clear(false);
454   next_frame_pc.Clear();
455 
456   if (block) {
457     // const addr_t curr_frame_file_addr = curr_frame_pc.GetFileAddress();
458 
459     // In order to get the parent of an inlined function we first need to see
460     // if we are in an inlined block as "this->block" could be an inlined
461     // block, or a parent of "block" could be. So lets check if this block or
462     // one of this blocks parents is an inlined function.
463     Block *curr_inlined_block = block->GetContainingInlinedBlock();
464     if (curr_inlined_block) {
465       // "this->block" is contained in an inline function block, so to get the
466       // scope above the inlined block, we get the parent of the inlined block
467       // itself
468       Block *next_frame_block = curr_inlined_block->GetParent();
469       // Now calculate the symbol context of the containing block
470       next_frame_block->CalculateSymbolContext(&next_frame_sc);
471 
472       // If we get here we weren't able to find the return line entry using the
473       // nesting of the blocks and the line table.  So just use the call site
474       // info from our inlined block.
475 
476       AddressRange range;
477       if (curr_inlined_block->GetRangeContainingAddress(curr_frame_pc, range)) {
478         // To see there this new frame block it, we need to look at the call
479         // site information from
480         const InlineFunctionInfo *curr_inlined_block_inlined_info =
481             curr_inlined_block->GetInlinedFunctionInfo();
482         next_frame_pc = range.GetBaseAddress();
483         next_frame_sc.line_entry.range.GetBaseAddress() = next_frame_pc;
484         next_frame_sc.line_entry.file =
485             curr_inlined_block_inlined_info->GetCallSite().GetFile();
486         next_frame_sc.line_entry.original_file =
487             curr_inlined_block_inlined_info->GetCallSite().GetFile();
488         next_frame_sc.line_entry.line =
489             curr_inlined_block_inlined_info->GetCallSite().GetLine();
490         next_frame_sc.line_entry.column =
491             curr_inlined_block_inlined_info->GetCallSite().GetColumn();
492         return true;
493       } else {
494         Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
495 
496         if (log) {
497           LLDB_LOGF(
498               log,
499               "warning: inlined block 0x%8.8" PRIx64
500               " doesn't have a range that contains file address 0x%" PRIx64,
501               curr_inlined_block->GetID(), curr_frame_pc.GetFileAddress());
502         }
503 #ifdef LLDB_CONFIGURATION_DEBUG
504         else {
505           ObjectFile *objfile = nullptr;
506           if (module_sp) {
507             if (SymbolFile *symbol_file = module_sp->GetSymbolFile())
508               objfile = symbol_file->GetObjectFile();
509           }
510           if (objfile) {
511             Host::SystemLog(
512                 Host::eSystemLogWarning,
513                 "warning: inlined block 0x%8.8" PRIx64
514                 " doesn't have a range that contains file address 0x%" PRIx64
515                 " in %s\n",
516                 curr_inlined_block->GetID(), curr_frame_pc.GetFileAddress(),
517                 objfile->GetFileSpec().GetPath().c_str());
518           } else {
519             Host::SystemLog(
520                 Host::eSystemLogWarning,
521                 "warning: inlined block 0x%8.8" PRIx64
522                 " doesn't have a range that contains file address 0x%" PRIx64
523                 "\n",
524                 curr_inlined_block->GetID(), curr_frame_pc.GetFileAddress());
525           }
526         }
527 #endif
528       }
529     }
530   }
531 
532   return false;
533 }
534 
535 Block *SymbolContext::GetFunctionBlock() {
536   if (function) {
537     if (block) {
538       // If this symbol context has a block, check to see if this block is
539       // itself, or is contained within a block with inlined function
540       // information. If so, then the inlined block is the block that defines
541       // the function.
542       Block *inlined_block = block->GetContainingInlinedBlock();
543       if (inlined_block)
544         return inlined_block;
545 
546       // The block in this symbol context is not inside an inlined block, so
547       // the block that defines the function is the function's top level block,
548       // which is returned below.
549     }
550 
551     // There is no block information in this symbol context, so we must assume
552     // that the block that is desired is the top level block of the function
553     // itself.
554     return &function->GetBlock(true);
555   }
556   return nullptr;
557 }
558 
559 bool SymbolContext::GetFunctionMethodInfo(lldb::LanguageType &language,
560                                           bool &is_instance_method,
561                                           ConstString &language_object_name)
562 
563 {
564   Block *function_block = GetFunctionBlock();
565   if (function_block) {
566     CompilerDeclContext decl_ctx = function_block->GetDeclContext();
567     if (decl_ctx)
568       return decl_ctx.IsClassMethod(&language, &is_instance_method,
569                                     &language_object_name);
570   }
571   return false;
572 }
573 
574 void SymbolContext::SortTypeList(TypeMap &type_map, TypeList &type_list) const {
575   Block *curr_block = block;
576   bool isInlinedblock = false;
577   if (curr_block != nullptr &&
578       curr_block->GetContainingInlinedBlock() != nullptr)
579     isInlinedblock = true;
580 
581   // Find all types that match the current block if we have one and put them
582   // first in the list. Keep iterating up through all blocks.
583   while (curr_block != nullptr && !isInlinedblock) {
584     type_map.ForEach(
585         [curr_block, &type_list](const lldb::TypeSP &type_sp) -> bool {
586           SymbolContextScope *scs = type_sp->GetSymbolContextScope();
587           if (scs && curr_block == scs->CalculateSymbolContextBlock())
588             type_list.Insert(type_sp);
589           return true; // Keep iterating
590         });
591 
592     // Remove any entries that are now in "type_list" from "type_map" since we
593     // can't remove from type_map while iterating
594     type_list.ForEach([&type_map](const lldb::TypeSP &type_sp) -> bool {
595       type_map.Remove(type_sp);
596       return true; // Keep iterating
597     });
598     curr_block = curr_block->GetParent();
599   }
600   // Find all types that match the current function, if we have onem, and put
601   // them next in the list.
602   if (function != nullptr && !type_map.Empty()) {
603     const size_t old_type_list_size = type_list.GetSize();
604     type_map.ForEach([this, &type_list](const lldb::TypeSP &type_sp) -> bool {
605       SymbolContextScope *scs = type_sp->GetSymbolContextScope();
606       if (scs && function == scs->CalculateSymbolContextFunction())
607         type_list.Insert(type_sp);
608       return true; // Keep iterating
609     });
610 
611     // Remove any entries that are now in "type_list" from "type_map" since we
612     // can't remove from type_map while iterating
613     const size_t new_type_list_size = type_list.GetSize();
614     if (new_type_list_size > old_type_list_size) {
615       for (size_t i = old_type_list_size; i < new_type_list_size; ++i)
616         type_map.Remove(type_list.GetTypeAtIndex(i));
617     }
618   }
619   // Find all types that match the current compile unit, if we have one, and
620   // put them next in the list.
621   if (comp_unit != nullptr && !type_map.Empty()) {
622     const size_t old_type_list_size = type_list.GetSize();
623 
624     type_map.ForEach([this, &type_list](const lldb::TypeSP &type_sp) -> bool {
625       SymbolContextScope *scs = type_sp->GetSymbolContextScope();
626       if (scs && comp_unit == scs->CalculateSymbolContextCompileUnit())
627         type_list.Insert(type_sp);
628       return true; // Keep iterating
629     });
630 
631     // Remove any entries that are now in "type_list" from "type_map" since we
632     // can't remove from type_map while iterating
633     const size_t new_type_list_size = type_list.GetSize();
634     if (new_type_list_size > old_type_list_size) {
635       for (size_t i = old_type_list_size; i < new_type_list_size; ++i)
636         type_map.Remove(type_list.GetTypeAtIndex(i));
637     }
638   }
639   // Find all types that match the current module, if we have one, and put them
640   // next in the list.
641   if (module_sp && !type_map.Empty()) {
642     const size_t old_type_list_size = type_list.GetSize();
643     type_map.ForEach([this, &type_list](const lldb::TypeSP &type_sp) -> bool {
644       SymbolContextScope *scs = type_sp->GetSymbolContextScope();
645       if (scs && module_sp == scs->CalculateSymbolContextModule())
646         type_list.Insert(type_sp);
647       return true; // Keep iterating
648     });
649     // Remove any entries that are now in "type_list" from "type_map" since we
650     // can't remove from type_map while iterating
651     const size_t new_type_list_size = type_list.GetSize();
652     if (new_type_list_size > old_type_list_size) {
653       for (size_t i = old_type_list_size; i < new_type_list_size; ++i)
654         type_map.Remove(type_list.GetTypeAtIndex(i));
655     }
656   }
657   // Any types that are left get copied into the list an any order.
658   if (!type_map.Empty()) {
659     type_map.ForEach([&type_list](const lldb::TypeSP &type_sp) -> bool {
660       type_list.Insert(type_sp);
661       return true; // Keep iterating
662     });
663   }
664 }
665 
666 ConstString
667 SymbolContext::GetFunctionName(Mangled::NamePreference preference) const {
668   if (function) {
669     if (block) {
670       Block *inlined_block = block->GetContainingInlinedBlock();
671 
672       if (inlined_block) {
673         const InlineFunctionInfo *inline_info =
674             inlined_block->GetInlinedFunctionInfo();
675         if (inline_info)
676           return inline_info->GetName(function->GetLanguage());
677       }
678     }
679     return function->GetMangled().GetName(function->GetLanguage(), preference);
680   } else if (symbol && symbol->ValueIsAddress()) {
681     return symbol->GetMangled().GetName(symbol->GetLanguage(), preference);
682   } else {
683     // No function, return an empty string.
684     return ConstString();
685   }
686 }
687 
688 LineEntry SymbolContext::GetFunctionStartLineEntry() const {
689   LineEntry line_entry;
690   Address start_addr;
691   if (block) {
692     Block *inlined_block = block->GetContainingInlinedBlock();
693     if (inlined_block) {
694       if (inlined_block->GetStartAddress(start_addr)) {
695         if (start_addr.CalculateSymbolContextLineEntry(line_entry))
696           return line_entry;
697       }
698       return LineEntry();
699     }
700   }
701 
702   if (function) {
703     if (function->GetAddressRange()
704             .GetBaseAddress()
705             .CalculateSymbolContextLineEntry(line_entry))
706       return line_entry;
707   }
708   return LineEntry();
709 }
710 
711 bool SymbolContext::GetAddressRangeFromHereToEndLine(uint32_t end_line,
712                                                      AddressRange &range,
713                                                      Status &error) {
714   if (!line_entry.IsValid()) {
715     error.SetErrorString("Symbol context has no line table.");
716     return false;
717   }
718 
719   range = line_entry.range;
720   if (line_entry.line > end_line) {
721     error.SetErrorStringWithFormat(
722         "end line option %d must be after the current line: %d", end_line,
723         line_entry.line);
724     return false;
725   }
726 
727   uint32_t line_index = 0;
728   bool found = false;
729   while (true) {
730     LineEntry this_line;
731     line_index = comp_unit->FindLineEntry(line_index, line_entry.line, nullptr,
732                                           false, &this_line);
733     if (line_index == UINT32_MAX)
734       break;
735     if (LineEntry::Compare(this_line, line_entry) == 0) {
736       found = true;
737       break;
738     }
739   }
740 
741   LineEntry end_entry;
742   if (!found) {
743     // Can't find the index of the SymbolContext's line entry in the
744     // SymbolContext's CompUnit.
745     error.SetErrorString(
746         "Can't find the current line entry in the CompUnit - can't process "
747         "the end-line option");
748     return false;
749   }
750 
751   line_index = comp_unit->FindLineEntry(line_index, end_line, nullptr, false,
752                                         &end_entry);
753   if (line_index == UINT32_MAX) {
754     error.SetErrorStringWithFormat(
755         "could not find a line table entry corresponding "
756         "to end line number %d",
757         end_line);
758     return false;
759   }
760 
761   Block *func_block = GetFunctionBlock();
762   if (func_block &&
763       func_block->GetRangeIndexContainingAddress(
764           end_entry.range.GetBaseAddress()) == UINT32_MAX) {
765     error.SetErrorStringWithFormat(
766         "end line number %d is not contained within the current function.",
767         end_line);
768     return false;
769   }
770 
771   lldb::addr_t range_size = end_entry.range.GetBaseAddress().GetFileAddress() -
772                             range.GetBaseAddress().GetFileAddress();
773   range.SetByteSize(range_size);
774   return true;
775 }
776 
777 const Symbol *
778 SymbolContext::FindBestGlobalDataSymbol(ConstString name, Status &error) {
779   error.Clear();
780 
781   if (!target_sp) {
782     return nullptr;
783   }
784 
785   Target &target = *target_sp;
786   Module *module = module_sp.get();
787 
788   auto ProcessMatches = [this, &name, &target, module]
789   (SymbolContextList &sc_list, Status &error) -> const Symbol* {
790     llvm::SmallVector<const Symbol *, 1> external_symbols;
791     llvm::SmallVector<const Symbol *, 1> internal_symbols;
792     const uint32_t matches = sc_list.GetSize();
793     for (uint32_t i = 0; i < matches; ++i) {
794       SymbolContext sym_ctx;
795       sc_list.GetContextAtIndex(i, sym_ctx);
796       if (sym_ctx.symbol) {
797         const Symbol *symbol = sym_ctx.symbol;
798         const Address sym_address = symbol->GetAddress();
799 
800         if (sym_address.IsValid()) {
801           switch (symbol->GetType()) {
802             case eSymbolTypeData:
803             case eSymbolTypeRuntime:
804             case eSymbolTypeAbsolute:
805             case eSymbolTypeObjCClass:
806             case eSymbolTypeObjCMetaClass:
807             case eSymbolTypeObjCIVar:
808               if (symbol->GetDemangledNameIsSynthesized()) {
809                 // If the demangled name was synthesized, then don't use it for
810                 // expressions. Only let the symbol match if the mangled named
811                 // matches for these symbols.
812                 if (symbol->GetMangled().GetMangledName() != name)
813                   break;
814               }
815               if (symbol->IsExternal()) {
816                 external_symbols.push_back(symbol);
817               } else {
818                 internal_symbols.push_back(symbol);
819               }
820               break;
821             case eSymbolTypeReExported: {
822               ConstString reexport_name = symbol->GetReExportedSymbolName();
823               if (reexport_name) {
824                 ModuleSP reexport_module_sp;
825                 ModuleSpec reexport_module_spec;
826                 reexport_module_spec.GetPlatformFileSpec() =
827                 symbol->GetReExportedSymbolSharedLibrary();
828                 if (reexport_module_spec.GetPlatformFileSpec()) {
829                   reexport_module_sp =
830                   target.GetImages().FindFirstModule(reexport_module_spec);
831                   if (!reexport_module_sp) {
832                     reexport_module_spec.GetPlatformFileSpec()
833                     .GetDirectory()
834                     .Clear();
835                     reexport_module_sp =
836                     target.GetImages().FindFirstModule(reexport_module_spec);
837                   }
838                 }
839                 // Don't allow us to try and resolve a re-exported symbol if it
840                 // is the same as the current symbol
841                 if (name == symbol->GetReExportedSymbolName() &&
842                     module == reexport_module_sp.get())
843                   return nullptr;
844 
845                 return FindBestGlobalDataSymbol(
846                     symbol->GetReExportedSymbolName(), error);
847               }
848             } break;
849 
850             case eSymbolTypeCode: // We already lookup functions elsewhere
851             case eSymbolTypeVariable:
852             case eSymbolTypeLocal:
853             case eSymbolTypeParam:
854             case eSymbolTypeTrampoline:
855             case eSymbolTypeInvalid:
856             case eSymbolTypeException:
857             case eSymbolTypeSourceFile:
858             case eSymbolTypeHeaderFile:
859             case eSymbolTypeObjectFile:
860             case eSymbolTypeCommonBlock:
861             case eSymbolTypeBlock:
862             case eSymbolTypeVariableType:
863             case eSymbolTypeLineEntry:
864             case eSymbolTypeLineHeader:
865             case eSymbolTypeScopeBegin:
866             case eSymbolTypeScopeEnd:
867             case eSymbolTypeAdditional:
868             case eSymbolTypeCompiler:
869             case eSymbolTypeInstrumentation:
870             case eSymbolTypeUndefined:
871             case eSymbolTypeResolver:
872               break;
873           }
874         }
875       }
876     }
877 
878     if (external_symbols.size() > 1) {
879       StreamString ss;
880       ss.Printf("Multiple external symbols found for '%s'\n", name.AsCString());
881       for (const Symbol *symbol : external_symbols) {
882         symbol->GetDescription(&ss, eDescriptionLevelFull, &target);
883       }
884       ss.PutChar('\n');
885       error.SetErrorString(ss.GetData());
886       return nullptr;
887     } else if (external_symbols.size()) {
888       return external_symbols[0];
889     } else if (internal_symbols.size() > 1) {
890       StreamString ss;
891       ss.Printf("Multiple internal symbols found for '%s'\n", name.AsCString());
892       for (const Symbol *symbol : internal_symbols) {
893         symbol->GetDescription(&ss, eDescriptionLevelVerbose, &target);
894         ss.PutChar('\n');
895       }
896       error.SetErrorString(ss.GetData());
897       return nullptr;
898     } else if (internal_symbols.size()) {
899       return internal_symbols[0];
900     } else {
901       return nullptr;
902     }
903   };
904 
905   if (module) {
906     SymbolContextList sc_list;
907     module->FindSymbolsWithNameAndType(name, eSymbolTypeAny, sc_list);
908     const Symbol *const module_symbol = ProcessMatches(sc_list, error);
909 
910     if (!error.Success()) {
911       return nullptr;
912     } else if (module_symbol) {
913       return module_symbol;
914     }
915   }
916 
917   {
918     SymbolContextList sc_list;
919     target.GetImages().FindSymbolsWithNameAndType(name, eSymbolTypeAny,
920                                                   sc_list);
921     const Symbol *const target_symbol = ProcessMatches(sc_list, error);
922 
923     if (!error.Success()) {
924       return nullptr;
925     } else if (target_symbol) {
926       return target_symbol;
927     }
928   }
929 
930   return nullptr; // no error; we just didn't find anything
931 }
932 
933 
934 //
935 //  SymbolContextSpecifier
936 //
937 
938 SymbolContextSpecifier::SymbolContextSpecifier(const TargetSP &target_sp)
939     : m_target_sp(target_sp), m_module_spec(), m_module_sp(), m_file_spec_up(),
940       m_start_line(0), m_end_line(0), m_function_spec(), m_class_name(),
941       m_address_range_up(), m_type(eNothingSpecified) {}
942 
943 SymbolContextSpecifier::~SymbolContextSpecifier() {}
944 
945 bool SymbolContextSpecifier::AddLineSpecification(uint32_t line_no,
946                                                   SpecificationType type) {
947   bool return_value = true;
948   switch (type) {
949   case eNothingSpecified:
950     Clear();
951     break;
952   case eLineStartSpecified:
953     m_start_line = line_no;
954     m_type |= eLineStartSpecified;
955     break;
956   case eLineEndSpecified:
957     m_end_line = line_no;
958     m_type |= eLineEndSpecified;
959     break;
960   default:
961     return_value = false;
962     break;
963   }
964   return return_value;
965 }
966 
967 bool SymbolContextSpecifier::AddSpecification(const char *spec_string,
968                                               SpecificationType type) {
969   bool return_value = true;
970   switch (type) {
971   case eNothingSpecified:
972     Clear();
973     break;
974   case eModuleSpecified: {
975     // See if we can find the Module, if so stick it in the SymbolContext.
976     FileSpec module_file_spec(spec_string);
977     ModuleSpec module_spec(module_file_spec);
978     lldb::ModuleSP module_sp(
979         m_target_sp->GetImages().FindFirstModule(module_spec));
980     m_type |= eModuleSpecified;
981     if (module_sp)
982       m_module_sp = module_sp;
983     else
984       m_module_spec.assign(spec_string);
985   } break;
986   case eFileSpecified:
987     // CompUnits can't necessarily be resolved here, since an inlined function
988     // might show up in a number of CompUnits.  Instead we just convert to a
989     // FileSpec and store it away.
990     m_file_spec_up.reset(new FileSpec(spec_string));
991     m_type |= eFileSpecified;
992     break;
993   case eLineStartSpecified:
994     m_start_line = StringConvert::ToSInt32(spec_string, 0, 0, &return_value);
995     if (return_value)
996       m_type |= eLineStartSpecified;
997     break;
998   case eLineEndSpecified:
999     m_end_line = StringConvert::ToSInt32(spec_string, 0, 0, &return_value);
1000     if (return_value)
1001       m_type |= eLineEndSpecified;
1002     break;
1003   case eFunctionSpecified:
1004     m_function_spec.assign(spec_string);
1005     m_type |= eFunctionSpecified;
1006     break;
1007   case eClassOrNamespaceSpecified:
1008     Clear();
1009     m_class_name.assign(spec_string);
1010     m_type = eClassOrNamespaceSpecified;
1011     break;
1012   case eAddressRangeSpecified:
1013     // Not specified yet...
1014     break;
1015   }
1016 
1017   return return_value;
1018 }
1019 
1020 void SymbolContextSpecifier::Clear() {
1021   m_module_spec.clear();
1022   m_file_spec_up.reset();
1023   m_function_spec.clear();
1024   m_class_name.clear();
1025   m_start_line = 0;
1026   m_end_line = 0;
1027   m_address_range_up.reset();
1028 
1029   m_type = eNothingSpecified;
1030 }
1031 
1032 bool SymbolContextSpecifier::SymbolContextMatches(SymbolContext &sc) {
1033   if (m_type == eNothingSpecified)
1034     return true;
1035 
1036   if (m_target_sp.get() != sc.target_sp.get())
1037     return false;
1038 
1039   if (m_type & eModuleSpecified) {
1040     if (sc.module_sp) {
1041       if (m_module_sp.get() != nullptr) {
1042         if (m_module_sp.get() != sc.module_sp.get())
1043           return false;
1044       } else {
1045         FileSpec module_file_spec(m_module_spec);
1046         if (!FileSpec::Equal(module_file_spec, sc.module_sp->GetFileSpec(),
1047                              false))
1048           return false;
1049       }
1050     }
1051   }
1052   if (m_type & eFileSpecified) {
1053     if (m_file_spec_up) {
1054       // If we don't have a block or a comp_unit, then we aren't going to match
1055       // a source file.
1056       if (sc.block == nullptr && sc.comp_unit == nullptr)
1057         return false;
1058 
1059       // Check if the block is present, and if so is it inlined:
1060       bool was_inlined = false;
1061       if (sc.block != nullptr) {
1062         const InlineFunctionInfo *inline_info =
1063             sc.block->GetInlinedFunctionInfo();
1064         if (inline_info != nullptr) {
1065           was_inlined = true;
1066           if (!FileSpec::Equal(inline_info->GetDeclaration().GetFile(),
1067                                *(m_file_spec_up.get()), false))
1068             return false;
1069         }
1070       }
1071 
1072       // Next check the comp unit, but only if the SymbolContext was not
1073       // inlined.
1074       if (!was_inlined && sc.comp_unit != nullptr) {
1075         if (!FileSpec::Equal(*(sc.comp_unit), *(m_file_spec_up.get()), false))
1076           return false;
1077       }
1078     }
1079   }
1080   if (m_type & eLineStartSpecified || m_type & eLineEndSpecified) {
1081     if (sc.line_entry.line < m_start_line || sc.line_entry.line > m_end_line)
1082       return false;
1083   }
1084 
1085   if (m_type & eFunctionSpecified) {
1086     // First check the current block, and if it is inlined, get the inlined
1087     // function name:
1088     bool was_inlined = false;
1089     ConstString func_name(m_function_spec.c_str());
1090 
1091     if (sc.block != nullptr) {
1092       const InlineFunctionInfo *inline_info =
1093           sc.block->GetInlinedFunctionInfo();
1094       if (inline_info != nullptr) {
1095         was_inlined = true;
1096         const Mangled &name = inline_info->GetMangled();
1097         if (!name.NameMatches(func_name, sc.function->GetLanguage()))
1098           return false;
1099       }
1100     }
1101     //  If it wasn't inlined, check the name in the function or symbol:
1102     if (!was_inlined) {
1103       if (sc.function != nullptr) {
1104         if (!sc.function->GetMangled().NameMatches(func_name,
1105                                                    sc.function->GetLanguage()))
1106           return false;
1107       } else if (sc.symbol != nullptr) {
1108         if (!sc.symbol->GetMangled().NameMatches(func_name,
1109                                                  sc.symbol->GetLanguage()))
1110           return false;
1111       }
1112     }
1113   }
1114 
1115   return true;
1116 }
1117 
1118 bool SymbolContextSpecifier::AddressMatches(lldb::addr_t addr) {
1119   if (m_type & eAddressRangeSpecified) {
1120 
1121   } else {
1122     Address match_address(addr, nullptr);
1123     SymbolContext sc;
1124     m_target_sp->GetImages().ResolveSymbolContextForAddress(
1125         match_address, eSymbolContextEverything, sc);
1126     return SymbolContextMatches(sc);
1127   }
1128   return true;
1129 }
1130 
1131 void SymbolContextSpecifier::GetDescription(
1132     Stream *s, lldb::DescriptionLevel level) const {
1133   char path_str[PATH_MAX + 1];
1134 
1135   if (m_type == eNothingSpecified) {
1136     s->Printf("Nothing specified.\n");
1137   }
1138 
1139   if (m_type == eModuleSpecified) {
1140     s->Indent();
1141     if (m_module_sp) {
1142       m_module_sp->GetFileSpec().GetPath(path_str, PATH_MAX);
1143       s->Printf("Module: %s\n", path_str);
1144     } else
1145       s->Printf("Module: %s\n", m_module_spec.c_str());
1146   }
1147 
1148   if (m_type == eFileSpecified && m_file_spec_up != nullptr) {
1149     m_file_spec_up->GetPath(path_str, PATH_MAX);
1150     s->Indent();
1151     s->Printf("File: %s", path_str);
1152     if (m_type == eLineStartSpecified) {
1153       s->Printf(" from line %" PRIu64 "", (uint64_t)m_start_line);
1154       if (m_type == eLineEndSpecified)
1155         s->Printf("to line %" PRIu64 "", (uint64_t)m_end_line);
1156       else
1157         s->Printf("to end");
1158     } else if (m_type == eLineEndSpecified) {
1159       s->Printf(" from start to line %" PRIu64 "", (uint64_t)m_end_line);
1160     }
1161     s->Printf(".\n");
1162   }
1163 
1164   if (m_type == eLineStartSpecified) {
1165     s->Indent();
1166     s->Printf("From line %" PRIu64 "", (uint64_t)m_start_line);
1167     if (m_type == eLineEndSpecified)
1168       s->Printf("to line %" PRIu64 "", (uint64_t)m_end_line);
1169     else
1170       s->Printf("to end");
1171     s->Printf(".\n");
1172   } else if (m_type == eLineEndSpecified) {
1173     s->Printf("From start to line %" PRIu64 ".\n", (uint64_t)m_end_line);
1174   }
1175 
1176   if (m_type == eFunctionSpecified) {
1177     s->Indent();
1178     s->Printf("Function: %s.\n", m_function_spec.c_str());
1179   }
1180 
1181   if (m_type == eClassOrNamespaceSpecified) {
1182     s->Indent();
1183     s->Printf("Class name: %s.\n", m_class_name.c_str());
1184   }
1185 
1186   if (m_type == eAddressRangeSpecified && m_address_range_up != nullptr) {
1187     s->Indent();
1188     s->PutCString("Address range: ");
1189     m_address_range_up->Dump(s, m_target_sp.get(),
1190                              Address::DumpStyleLoadAddress,
1191                              Address::DumpStyleFileAddress);
1192     s->PutCString("\n");
1193   }
1194 }
1195 
1196 //
1197 //  SymbolContextList
1198 //
1199 
1200 SymbolContextList::SymbolContextList() : m_symbol_contexts() {}
1201 
1202 SymbolContextList::~SymbolContextList() {}
1203 
1204 void SymbolContextList::Append(const SymbolContext &sc) {
1205   m_symbol_contexts.push_back(sc);
1206 }
1207 
1208 void SymbolContextList::Append(const SymbolContextList &sc_list) {
1209   collection::const_iterator pos, end = sc_list.m_symbol_contexts.end();
1210   for (pos = sc_list.m_symbol_contexts.begin(); pos != end; ++pos)
1211     m_symbol_contexts.push_back(*pos);
1212 }
1213 
1214 uint32_t SymbolContextList::AppendIfUnique(const SymbolContextList &sc_list,
1215                                            bool merge_symbol_into_function) {
1216   uint32_t unique_sc_add_count = 0;
1217   collection::const_iterator pos, end = sc_list.m_symbol_contexts.end();
1218   for (pos = sc_list.m_symbol_contexts.begin(); pos != end; ++pos) {
1219     if (AppendIfUnique(*pos, merge_symbol_into_function))
1220       ++unique_sc_add_count;
1221   }
1222   return unique_sc_add_count;
1223 }
1224 
1225 bool SymbolContextList::AppendIfUnique(const SymbolContext &sc,
1226                                        bool merge_symbol_into_function) {
1227   collection::iterator pos, end = m_symbol_contexts.end();
1228   for (pos = m_symbol_contexts.begin(); pos != end; ++pos) {
1229     if (*pos == sc)
1230       return false;
1231   }
1232   if (merge_symbol_into_function && sc.symbol != nullptr &&
1233       sc.comp_unit == nullptr && sc.function == nullptr &&
1234       sc.block == nullptr && !sc.line_entry.IsValid()) {
1235     if (sc.symbol->ValueIsAddress()) {
1236       for (pos = m_symbol_contexts.begin(); pos != end; ++pos) {
1237         // Don't merge symbols into inlined function symbol contexts
1238         if (pos->block && pos->block->GetContainingInlinedBlock())
1239           continue;
1240 
1241         if (pos->function) {
1242           if (pos->function->GetAddressRange().GetBaseAddress() ==
1243               sc.symbol->GetAddressRef()) {
1244             // Do we already have a function with this symbol?
1245             if (pos->symbol == sc.symbol)
1246               return false;
1247             if (pos->symbol == nullptr) {
1248               pos->symbol = sc.symbol;
1249               return false;
1250             }
1251           }
1252         }
1253       }
1254     }
1255   }
1256   m_symbol_contexts.push_back(sc);
1257   return true;
1258 }
1259 
1260 void SymbolContextList::Clear() { m_symbol_contexts.clear(); }
1261 
1262 void SymbolContextList::Dump(Stream *s, Target *target) const {
1263 
1264   *s << this << ": ";
1265   s->Indent();
1266   s->PutCString("SymbolContextList");
1267   s->EOL();
1268   s->IndentMore();
1269 
1270   collection::const_iterator pos, end = m_symbol_contexts.end();
1271   for (pos = m_symbol_contexts.begin(); pos != end; ++pos) {
1272     // pos->Dump(s, target);
1273     pos->GetDescription(s, eDescriptionLevelVerbose, target);
1274   }
1275   s->IndentLess();
1276 }
1277 
1278 bool SymbolContextList::GetContextAtIndex(size_t idx, SymbolContext &sc) const {
1279   if (idx < m_symbol_contexts.size()) {
1280     sc = m_symbol_contexts[idx];
1281     return true;
1282   }
1283   return false;
1284 }
1285 
1286 bool SymbolContextList::RemoveContextAtIndex(size_t idx) {
1287   if (idx < m_symbol_contexts.size()) {
1288     m_symbol_contexts.erase(m_symbol_contexts.begin() + idx);
1289     return true;
1290   }
1291   return false;
1292 }
1293 
1294 uint32_t SymbolContextList::GetSize() const { return m_symbol_contexts.size(); }
1295 
1296 uint32_t SymbolContextList::NumLineEntriesWithLine(uint32_t line) const {
1297   uint32_t match_count = 0;
1298   const size_t size = m_symbol_contexts.size();
1299   for (size_t idx = 0; idx < size; ++idx) {
1300     if (m_symbol_contexts[idx].line_entry.line == line)
1301       ++match_count;
1302   }
1303   return match_count;
1304 }
1305 
1306 void SymbolContextList::GetDescription(Stream *s, lldb::DescriptionLevel level,
1307                                        Target *target) const {
1308   const size_t size = m_symbol_contexts.size();
1309   for (size_t idx = 0; idx < size; ++idx)
1310     m_symbol_contexts[idx].GetDescription(s, level, target);
1311 }
1312 
1313 bool lldb_private::operator==(const SymbolContextList &lhs,
1314                               const SymbolContextList &rhs) {
1315   const uint32_t size = lhs.GetSize();
1316   if (size != rhs.GetSize())
1317     return false;
1318 
1319   SymbolContext lhs_sc;
1320   SymbolContext rhs_sc;
1321   for (uint32_t i = 0; i < size; ++i) {
1322     lhs.GetContextAtIndex(i, lhs_sc);
1323     rhs.GetContextAtIndex(i, rhs_sc);
1324     if (lhs_sc != rhs_sc)
1325       return false;
1326   }
1327   return true;
1328 }
1329 
1330 bool lldb_private::operator!=(const SymbolContextList &lhs,
1331                               const SymbolContextList &rhs) {
1332   return !(lhs == rhs);
1333 }
1334