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