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