1 //===-- StackFrame.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/Target/StackFrame.h"
10 #include "lldb/Core/Debugger.h"
11 #include "lldb/Core/Disassembler.h"
12 #include "lldb/Core/FormatEntity.h"
13 #include "lldb/Core/Mangled.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/Value.h"
16 #include "lldb/Core/ValueObjectConstResult.h"
17 #include "lldb/Core/ValueObjectMemory.h"
18 #include "lldb/Core/ValueObjectVariable.h"
19 #include "lldb/Symbol/CompileUnit.h"
20 #include "lldb/Symbol/Function.h"
21 #include "lldb/Symbol/Symbol.h"
22 #include "lldb/Symbol/SymbolContextScope.h"
23 #include "lldb/Symbol/Type.h"
24 #include "lldb/Symbol/VariableList.h"
25 #include "lldb/Target/ABI.h"
26 #include "lldb/Target/ExecutionContext.h"
27 #include "lldb/Target/Process.h"
28 #include "lldb/Target/RegisterContext.h"
29 #include "lldb/Target/StackFrameRecognizer.h"
30 #include "lldb/Target/Target.h"
31 #include "lldb/Target/Thread.h"
32 #include "lldb/Utility/RegisterValue.h"
33 
34 #include "lldb/lldb-enumerations.h"
35 
36 #include <memory>
37 
38 using namespace lldb;
39 using namespace lldb_private;
40 
41 // The first bits in the flags are reserved for the SymbolContext::Scope bits
42 // so we know if we have tried to look up information in our internal symbol
43 // context (m_sc) already.
44 #define RESOLVED_FRAME_CODE_ADDR (uint32_t(eSymbolContextEverything + 1))
45 #define RESOLVED_FRAME_ID_SYMBOL_SCOPE (RESOLVED_FRAME_CODE_ADDR << 1)
46 #define GOT_FRAME_BASE (RESOLVED_FRAME_ID_SYMBOL_SCOPE << 1)
47 #define RESOLVED_VARIABLES (GOT_FRAME_BASE << 1)
48 #define RESOLVED_GLOBAL_VARIABLES (RESOLVED_VARIABLES << 1)
49 
50 StackFrame::StackFrame(const ThreadSP &thread_sp, user_id_t frame_idx,
51                        user_id_t unwind_frame_index, addr_t cfa,
52                        bool cfa_is_valid, addr_t pc, StackFrame::Kind kind,
53                        const SymbolContext *sc_ptr)
54     : m_thread_wp(thread_sp), m_frame_index(frame_idx),
55       m_concrete_frame_index(unwind_frame_index), m_reg_context_sp(),
56       m_id(pc, cfa, nullptr), m_frame_code_addr(pc), m_sc(), m_flags(),
57       m_frame_base(), m_frame_base_error(), m_cfa_is_valid(cfa_is_valid),
58       m_stack_frame_kind(kind), m_variable_list_sp(),
59       m_variable_list_value_objects(), m_recognized_frame_sp(), m_disassembly(),
60       m_mutex() {
61   // If we don't have a CFA value, use the frame index for our StackID so that
62   // recursive functions properly aren't confused with one another on a history
63   // stack.
64   if (IsHistorical() && !m_cfa_is_valid) {
65     m_id.SetCFA(m_frame_index);
66   }
67 
68   if (sc_ptr != nullptr) {
69     m_sc = *sc_ptr;
70     m_flags.Set(m_sc.GetResolvedMask());
71   }
72 }
73 
74 StackFrame::StackFrame(const ThreadSP &thread_sp, user_id_t frame_idx,
75                        user_id_t unwind_frame_index,
76                        const RegisterContextSP &reg_context_sp, addr_t cfa,
77                        addr_t pc, const SymbolContext *sc_ptr)
78     : m_thread_wp(thread_sp), m_frame_index(frame_idx),
79       m_concrete_frame_index(unwind_frame_index),
80       m_reg_context_sp(reg_context_sp), m_id(pc, cfa, nullptr),
81       m_frame_code_addr(pc), m_sc(), m_flags(), m_frame_base(),
82       m_frame_base_error(), m_cfa_is_valid(true),
83       m_stack_frame_kind(StackFrame::Kind::Regular), m_variable_list_sp(),
84       m_variable_list_value_objects(), m_recognized_frame_sp(), m_disassembly(),
85       m_mutex() {
86   if (sc_ptr != nullptr) {
87     m_sc = *sc_ptr;
88     m_flags.Set(m_sc.GetResolvedMask());
89   }
90 
91   if (reg_context_sp && !m_sc.target_sp) {
92     m_sc.target_sp = reg_context_sp->CalculateTarget();
93     if (m_sc.target_sp)
94       m_flags.Set(eSymbolContextTarget);
95   }
96 }
97 
98 StackFrame::StackFrame(const ThreadSP &thread_sp, user_id_t frame_idx,
99                        user_id_t unwind_frame_index,
100                        const RegisterContextSP &reg_context_sp, addr_t cfa,
101                        const Address &pc_addr, const SymbolContext *sc_ptr)
102     : m_thread_wp(thread_sp), m_frame_index(frame_idx),
103       m_concrete_frame_index(unwind_frame_index),
104       m_reg_context_sp(reg_context_sp),
105       m_id(pc_addr.GetLoadAddress(thread_sp->CalculateTarget().get()), cfa,
106            nullptr),
107       m_frame_code_addr(pc_addr), m_sc(), m_flags(), m_frame_base(),
108       m_frame_base_error(), m_cfa_is_valid(true),
109       m_stack_frame_kind(StackFrame::Kind::Regular), m_variable_list_sp(),
110       m_variable_list_value_objects(), m_recognized_frame_sp(), m_disassembly(),
111       m_mutex() {
112   if (sc_ptr != nullptr) {
113     m_sc = *sc_ptr;
114     m_flags.Set(m_sc.GetResolvedMask());
115   }
116 
117   if (!m_sc.target_sp && reg_context_sp) {
118     m_sc.target_sp = reg_context_sp->CalculateTarget();
119     if (m_sc.target_sp)
120       m_flags.Set(eSymbolContextTarget);
121   }
122 
123   ModuleSP pc_module_sp(pc_addr.GetModule());
124   if (!m_sc.module_sp || m_sc.module_sp != pc_module_sp) {
125     if (pc_module_sp) {
126       m_sc.module_sp = pc_module_sp;
127       m_flags.Set(eSymbolContextModule);
128     } else {
129       m_sc.module_sp.reset();
130     }
131   }
132 }
133 
134 StackFrame::~StackFrame() = default;
135 
136 StackID &StackFrame::GetStackID() {
137   std::lock_guard<std::recursive_mutex> guard(m_mutex);
138   // Make sure we have resolved the StackID object's symbol context scope if we
139   // already haven't looked it up.
140 
141   if (m_flags.IsClear(RESOLVED_FRAME_ID_SYMBOL_SCOPE)) {
142     if (m_id.GetSymbolContextScope()) {
143       // We already have a symbol context scope, we just don't have our flag
144       // bit set.
145       m_flags.Set(RESOLVED_FRAME_ID_SYMBOL_SCOPE);
146     } else {
147       // Calculate the frame block and use this for the stack ID symbol context
148       // scope if we have one.
149       SymbolContextScope *scope = GetFrameBlock();
150       if (scope == nullptr) {
151         // We don't have a block, so use the symbol
152         if (m_flags.IsClear(eSymbolContextSymbol))
153           GetSymbolContext(eSymbolContextSymbol);
154 
155         // It is ok if m_sc.symbol is nullptr here
156         scope = m_sc.symbol;
157       }
158       // Set the symbol context scope (the accessor will set the
159       // RESOLVED_FRAME_ID_SYMBOL_SCOPE bit in m_flags).
160       SetSymbolContextScope(scope);
161     }
162   }
163   return m_id;
164 }
165 
166 uint32_t StackFrame::GetFrameIndex() const {
167   ThreadSP thread_sp = GetThread();
168   if (thread_sp)
169     return thread_sp->GetStackFrameList()->GetVisibleStackFrameIndex(
170         m_frame_index);
171   else
172     return m_frame_index;
173 }
174 
175 void StackFrame::SetSymbolContextScope(SymbolContextScope *symbol_scope) {
176   std::lock_guard<std::recursive_mutex> guard(m_mutex);
177   m_flags.Set(RESOLVED_FRAME_ID_SYMBOL_SCOPE);
178   m_id.SetSymbolContextScope(symbol_scope);
179 }
180 
181 const Address &StackFrame::GetFrameCodeAddress() {
182   std::lock_guard<std::recursive_mutex> guard(m_mutex);
183   if (m_flags.IsClear(RESOLVED_FRAME_CODE_ADDR) &&
184       !m_frame_code_addr.IsSectionOffset()) {
185     m_flags.Set(RESOLVED_FRAME_CODE_ADDR);
186 
187     // Resolve the PC into a temporary address because if ResolveLoadAddress
188     // fails to resolve the address, it will clear the address object...
189     ThreadSP thread_sp(GetThread());
190     if (thread_sp) {
191       TargetSP target_sp(thread_sp->CalculateTarget());
192       if (target_sp) {
193         const bool allow_section_end = true;
194         if (m_frame_code_addr.SetOpcodeLoadAddress(
195                 m_frame_code_addr.GetOffset(), target_sp.get(),
196                 AddressClass::eCode, allow_section_end)) {
197           ModuleSP module_sp(m_frame_code_addr.GetModule());
198           if (module_sp) {
199             m_sc.module_sp = module_sp;
200             m_flags.Set(eSymbolContextModule);
201           }
202         }
203       }
204     }
205   }
206   return m_frame_code_addr;
207 }
208 
209 bool StackFrame::ChangePC(addr_t pc) {
210   std::lock_guard<std::recursive_mutex> guard(m_mutex);
211   // We can't change the pc value of a history stack frame - it is immutable.
212   if (IsHistorical())
213     return false;
214   m_frame_code_addr.SetRawAddress(pc);
215   m_sc.Clear(false);
216   m_flags.Reset(0);
217   ThreadSP thread_sp(GetThread());
218   if (thread_sp)
219     thread_sp->ClearStackFrames();
220   return true;
221 }
222 
223 const char *StackFrame::Disassemble() {
224   std::lock_guard<std::recursive_mutex> guard(m_mutex);
225   if (m_disassembly.Empty()) {
226     ExecutionContext exe_ctx(shared_from_this());
227     Target *target = exe_ctx.GetTargetPtr();
228     if (target) {
229       const char *plugin_name = nullptr;
230       const char *flavor = nullptr;
231       Disassembler::Disassemble(target->GetDebugger(),
232                                 target->GetArchitecture(), plugin_name, flavor,
233                                 exe_ctx, 0, false, 0, 0, m_disassembly);
234     }
235     if (m_disassembly.Empty())
236       return nullptr;
237   }
238 
239   return m_disassembly.GetData();
240 }
241 
242 Block *StackFrame::GetFrameBlock() {
243   if (m_sc.block == nullptr && m_flags.IsClear(eSymbolContextBlock))
244     GetSymbolContext(eSymbolContextBlock);
245 
246   if (m_sc.block) {
247     Block *inline_block = m_sc.block->GetContainingInlinedBlock();
248     if (inline_block) {
249       // Use the block with the inlined function info as the frame block we
250       // want this frame to have only the variables for the inlined function
251       // and its non-inlined block child blocks.
252       return inline_block;
253     } else {
254       // This block is not contained within any inlined function blocks with so
255       // we want to use the top most function block.
256       return &m_sc.function->GetBlock(false);
257     }
258   }
259   return nullptr;
260 }
261 
262 //----------------------------------------------------------------------
263 // Get the symbol context if we already haven't done so by resolving the
264 // PC address as much as possible. This way when we pass around a
265 // StackFrame object, everyone will have as much information as possible and no
266 // one will ever have to look things up manually.
267 //----------------------------------------------------------------------
268 const SymbolContext &
269 StackFrame::GetSymbolContext(SymbolContextItem resolve_scope) {
270   std::lock_guard<std::recursive_mutex> guard(m_mutex);
271   // Copy our internal symbol context into "sc".
272   if ((m_flags.Get() & resolve_scope) != resolve_scope) {
273     uint32_t resolved = 0;
274 
275     // If the target was requested add that:
276     if (!m_sc.target_sp) {
277       m_sc.target_sp = CalculateTarget();
278       if (m_sc.target_sp)
279         resolved |= eSymbolContextTarget;
280     }
281 
282     // Resolve our PC to section offset if we haven't already done so and if we
283     // don't have a module. The resolved address section will contain the
284     // module to which it belongs
285     if (!m_sc.module_sp && m_flags.IsClear(RESOLVED_FRAME_CODE_ADDR))
286       GetFrameCodeAddress();
287 
288     // If this is not frame zero, then we need to subtract 1 from the PC value
289     // when doing address lookups since the PC will be on the instruction
290     // following the function call instruction...
291 
292     Address lookup_addr(GetFrameCodeAddress());
293     if (m_frame_index > 0 && lookup_addr.IsValid()) {
294       addr_t offset = lookup_addr.GetOffset();
295       if (offset > 0) {
296         lookup_addr.SetOffset(offset - 1);
297 
298       } else {
299         // lookup_addr is the start of a section.  We need do the math on the
300         // actual load address and re-compute the section.  We're working with
301         // a 'noreturn' function at the end of a section.
302         ThreadSP thread_sp(GetThread());
303         if (thread_sp) {
304           TargetSP target_sp(thread_sp->CalculateTarget());
305           if (target_sp) {
306             addr_t addr_minus_one =
307                 lookup_addr.GetLoadAddress(target_sp.get()) - 1;
308             lookup_addr.SetLoadAddress(addr_minus_one, target_sp.get());
309           } else {
310             lookup_addr.SetOffset(offset - 1);
311           }
312         }
313       }
314     }
315 
316     if (m_sc.module_sp) {
317       // We have something in our stack frame symbol context, lets check if we
318       // haven't already tried to lookup one of those things. If we haven't
319       // then we will do the query.
320 
321       SymbolContextItem actual_resolve_scope = SymbolContextItem(0);
322 
323       if (resolve_scope & eSymbolContextCompUnit) {
324         if (m_flags.IsClear(eSymbolContextCompUnit)) {
325           if (m_sc.comp_unit)
326             resolved |= eSymbolContextCompUnit;
327           else
328             actual_resolve_scope |= eSymbolContextCompUnit;
329         }
330       }
331 
332       if (resolve_scope & eSymbolContextFunction) {
333         if (m_flags.IsClear(eSymbolContextFunction)) {
334           if (m_sc.function)
335             resolved |= eSymbolContextFunction;
336           else
337             actual_resolve_scope |= eSymbolContextFunction;
338         }
339       }
340 
341       if (resolve_scope & eSymbolContextBlock) {
342         if (m_flags.IsClear(eSymbolContextBlock)) {
343           if (m_sc.block)
344             resolved |= eSymbolContextBlock;
345           else
346             actual_resolve_scope |= eSymbolContextBlock;
347         }
348       }
349 
350       if (resolve_scope & eSymbolContextSymbol) {
351         if (m_flags.IsClear(eSymbolContextSymbol)) {
352           if (m_sc.symbol)
353             resolved |= eSymbolContextSymbol;
354           else
355             actual_resolve_scope |= eSymbolContextSymbol;
356         }
357       }
358 
359       if (resolve_scope & eSymbolContextLineEntry) {
360         if (m_flags.IsClear(eSymbolContextLineEntry)) {
361           if (m_sc.line_entry.IsValid())
362             resolved |= eSymbolContextLineEntry;
363           else
364             actual_resolve_scope |= eSymbolContextLineEntry;
365         }
366       }
367 
368       if (actual_resolve_scope) {
369         // We might be resolving less information than what is already in our
370         // current symbol context so resolve into a temporary symbol context
371         // "sc" so we don't clear out data we have already found in "m_sc"
372         SymbolContext sc;
373         // Set flags that indicate what we have tried to resolve
374         resolved |= m_sc.module_sp->ResolveSymbolContextForAddress(
375             lookup_addr, actual_resolve_scope, sc);
376         // Only replace what we didn't already have as we may have information
377         // for an inlined function scope that won't match what a standard
378         // lookup by address would match
379         if ((resolved & eSymbolContextCompUnit) && m_sc.comp_unit == nullptr)
380           m_sc.comp_unit = sc.comp_unit;
381         if ((resolved & eSymbolContextFunction) && m_sc.function == nullptr)
382           m_sc.function = sc.function;
383         if ((resolved & eSymbolContextBlock) && m_sc.block == nullptr)
384           m_sc.block = sc.block;
385         if ((resolved & eSymbolContextSymbol) && m_sc.symbol == nullptr)
386           m_sc.symbol = sc.symbol;
387         if ((resolved & eSymbolContextLineEntry) &&
388             !m_sc.line_entry.IsValid()) {
389           m_sc.line_entry = sc.line_entry;
390           m_sc.line_entry.ApplyFileMappings(m_sc.target_sp);
391         }
392       }
393     } else {
394       // If we don't have a module, then we can't have the compile unit,
395       // function, block, line entry or symbol, so we can safely call
396       // ResolveSymbolContextForAddress with our symbol context member m_sc.
397       if (m_sc.target_sp) {
398         resolved |= m_sc.target_sp->GetImages().ResolveSymbolContextForAddress(
399             lookup_addr, resolve_scope, m_sc);
400       }
401     }
402 
403     // Update our internal flags so we remember what we have tried to locate so
404     // we don't have to keep trying when more calls to this function are made.
405     // We might have dug up more information that was requested (for example if
406     // we were asked to only get the block, we will have gotten the compile
407     // unit, and function) so set any additional bits that we resolved
408     m_flags.Set(resolve_scope | resolved);
409   }
410 
411   // Return the symbol context with everything that was possible to resolve
412   // resolved.
413   return m_sc;
414 }
415 
416 VariableList *StackFrame::GetVariableList(bool get_file_globals) {
417   std::lock_guard<std::recursive_mutex> guard(m_mutex);
418   if (m_flags.IsClear(RESOLVED_VARIABLES)) {
419     m_flags.Set(RESOLVED_VARIABLES);
420 
421     Block *frame_block = GetFrameBlock();
422 
423     if (frame_block) {
424       const bool get_child_variables = true;
425       const bool can_create = true;
426       const bool stop_if_child_block_is_inlined_function = true;
427       m_variable_list_sp = std::make_shared<VariableList>();
428       frame_block->AppendBlockVariables(can_create, get_child_variables,
429                                         stop_if_child_block_is_inlined_function,
430                                         [](Variable *v) { return true; },
431                                         m_variable_list_sp.get());
432     }
433   }
434 
435   if (m_flags.IsClear(RESOLVED_GLOBAL_VARIABLES) && get_file_globals) {
436     m_flags.Set(RESOLVED_GLOBAL_VARIABLES);
437 
438     if (m_flags.IsClear(eSymbolContextCompUnit))
439       GetSymbolContext(eSymbolContextCompUnit);
440 
441     if (m_sc.comp_unit) {
442       VariableListSP global_variable_list_sp(
443           m_sc.comp_unit->GetVariableList(true));
444       if (m_variable_list_sp)
445         m_variable_list_sp->AddVariables(global_variable_list_sp.get());
446       else
447         m_variable_list_sp = global_variable_list_sp;
448     }
449   }
450 
451   return m_variable_list_sp.get();
452 }
453 
454 VariableListSP
455 StackFrame::GetInScopeVariableList(bool get_file_globals,
456                                    bool must_have_valid_location) {
457   std::lock_guard<std::recursive_mutex> guard(m_mutex);
458   // We can't fetch variable information for a history stack frame.
459   if (IsHistorical())
460     return VariableListSP();
461 
462   VariableListSP var_list_sp(new VariableList);
463   GetSymbolContext(eSymbolContextCompUnit | eSymbolContextBlock);
464 
465   if (m_sc.block) {
466     const bool can_create = true;
467     const bool get_parent_variables = true;
468     const bool stop_if_block_is_inlined_function = true;
469     m_sc.block->AppendVariables(
470         can_create, get_parent_variables, stop_if_block_is_inlined_function,
471         [this, must_have_valid_location](Variable *v) {
472           return v->IsInScope(this) && (!must_have_valid_location ||
473                                         v->LocationIsValidForFrame(this));
474         },
475         var_list_sp.get());
476   }
477 
478   if (m_sc.comp_unit && get_file_globals) {
479     VariableListSP global_variable_list_sp(
480         m_sc.comp_unit->GetVariableList(true));
481     if (global_variable_list_sp)
482       var_list_sp->AddVariables(global_variable_list_sp.get());
483   }
484 
485   return var_list_sp;
486 }
487 
488 ValueObjectSP StackFrame::GetValueForVariableExpressionPath(
489     llvm::StringRef var_expr, DynamicValueType use_dynamic, uint32_t options,
490     VariableSP &var_sp, Status &error) {
491   llvm::StringRef original_var_expr = var_expr;
492   // We can't fetch variable information for a history stack frame.
493   if (IsHistorical())
494     return ValueObjectSP();
495 
496   if (var_expr.empty()) {
497     error.SetErrorStringWithFormat("invalid variable path '%s'",
498                                    var_expr.str().c_str());
499     return ValueObjectSP();
500   }
501 
502   const bool check_ptr_vs_member =
503       (options & eExpressionPathOptionCheckPtrVsMember) != 0;
504   const bool no_fragile_ivar =
505       (options & eExpressionPathOptionsNoFragileObjcIvar) != 0;
506   const bool no_synth_child =
507       (options & eExpressionPathOptionsNoSyntheticChildren) != 0;
508   // const bool no_synth_array = (options &
509   // eExpressionPathOptionsNoSyntheticArrayRange) != 0;
510   error.Clear();
511   bool deref = false;
512   bool address_of = false;
513   ValueObjectSP valobj_sp;
514   const bool get_file_globals = true;
515   // When looking up a variable for an expression, we need only consider the
516   // variables that are in scope.
517   VariableListSP var_list_sp(GetInScopeVariableList(get_file_globals));
518   VariableList *variable_list = var_list_sp.get();
519 
520   if (!variable_list)
521     return ValueObjectSP();
522 
523   // If first character is a '*', then show pointer contents
524   std::string var_expr_storage;
525   if (var_expr[0] == '*') {
526     deref = true;
527     var_expr = var_expr.drop_front(); // Skip the '*'
528   } else if (var_expr[0] == '&') {
529     address_of = true;
530     var_expr = var_expr.drop_front(); // Skip the '&'
531   }
532 
533   size_t separator_idx = var_expr.find_first_of(".-[=+~|&^%#@!/?,<>{}");
534   StreamString var_expr_path_strm;
535 
536   ConstString name_const_string(var_expr.substr(0, separator_idx));
537 
538   var_sp = variable_list->FindVariable(name_const_string, false);
539 
540   bool synthetically_added_instance_object = false;
541 
542   if (var_sp) {
543     var_expr = var_expr.drop_front(name_const_string.GetLength());
544   }
545 
546   if (!var_sp && (options & eExpressionPathOptionsAllowDirectIVarAccess)) {
547     // Check for direct ivars access which helps us with implicit access to
548     // ivars with the "this->" or "self->"
549     GetSymbolContext(eSymbolContextFunction | eSymbolContextBlock);
550     lldb::LanguageType method_language = eLanguageTypeUnknown;
551     bool is_instance_method = false;
552     ConstString method_object_name;
553     if (m_sc.GetFunctionMethodInfo(method_language, is_instance_method,
554                                    method_object_name)) {
555       if (is_instance_method && method_object_name) {
556         var_sp = variable_list->FindVariable(method_object_name);
557         if (var_sp) {
558           separator_idx = 0;
559           var_expr_storage = "->";
560           var_expr_storage += var_expr;
561           var_expr = var_expr_storage;
562           synthetically_added_instance_object = true;
563         }
564       }
565     }
566   }
567 
568   if (!var_sp && (options & eExpressionPathOptionsInspectAnonymousUnions)) {
569     // Check if any anonymous unions are there which contain a variable with
570     // the name we need
571     for (size_t i = 0; i < variable_list->GetSize(); i++) {
572       VariableSP variable_sp = variable_list->GetVariableAtIndex(i);
573       if (!variable_sp)
574         continue;
575       if (!variable_sp->GetName().IsEmpty())
576         continue;
577 
578       Type *var_type = variable_sp->GetType();
579       if (!var_type)
580         continue;
581 
582       if (!var_type->GetForwardCompilerType().IsAnonymousType())
583         continue;
584       valobj_sp = GetValueObjectForFrameVariable(variable_sp, use_dynamic);
585       if (!valobj_sp)
586         return valobj_sp;
587       valobj_sp = valobj_sp->GetChildMemberWithName(name_const_string, true);
588       if (valobj_sp)
589         break;
590     }
591   }
592 
593   if (var_sp && !valobj_sp) {
594     valobj_sp = GetValueObjectForFrameVariable(var_sp, use_dynamic);
595     if (!valobj_sp)
596       return valobj_sp;
597   }
598   if (!valobj_sp) {
599     error.SetErrorStringWithFormat("no variable named '%s' found in this frame",
600                                    name_const_string.GetCString());
601     return ValueObjectSP();
602   }
603 
604   // We are dumping at least one child
605   while (separator_idx != std::string::npos) {
606     // Calculate the next separator index ahead of time
607     ValueObjectSP child_valobj_sp;
608     const char separator_type = var_expr[0];
609     bool expr_is_ptr = false;
610     switch (separator_type) {
611     case '-':
612       expr_is_ptr = true;
613       if (var_expr.size() >= 2 && var_expr[1] != '>')
614         return ValueObjectSP();
615 
616       if (no_fragile_ivar) {
617         // Make sure we aren't trying to deref an objective
618         // C ivar if this is not allowed
619         const uint32_t pointer_type_flags =
620             valobj_sp->GetCompilerType().GetTypeInfo(nullptr);
621         if ((pointer_type_flags & eTypeIsObjC) &&
622             (pointer_type_flags & eTypeIsPointer)) {
623           // This was an objective C object pointer and it was requested we
624           // skip any fragile ivars so return nothing here
625           return ValueObjectSP();
626         }
627       }
628 
629       // If we have a non pointer type with a sythetic value then lets check if
630       // we have an sythetic dereference specified.
631       if (!valobj_sp->IsPointerType() && valobj_sp->HasSyntheticValue()) {
632         Status deref_error;
633         if (valobj_sp->GetCompilerType().IsReferenceType()) {
634           valobj_sp = valobj_sp->GetSyntheticValue()->Dereference(deref_error);
635           if (error.Fail()) {
636             error.SetErrorStringWithFormatv(
637                 "Failed to dereference reference type: %s", deref_error);
638             return ValueObjectSP();
639           }
640         }
641 
642         valobj_sp = valobj_sp->Dereference(deref_error);
643         if (error.Fail()) {
644           error.SetErrorStringWithFormatv(
645               "Failed to dereference sythetic value: {0}", deref_error);
646           return ValueObjectSP();
647         }
648         // Some synthetic plug-ins fail to set the error in Dereference
649         if (!valobj_sp) {
650           error.SetErrorString("Failed to dereference sythetic value");
651           return ValueObjectSP();
652         }
653         expr_is_ptr = false;
654       }
655 
656       var_expr = var_expr.drop_front(); // Remove the '-'
657       LLVM_FALLTHROUGH;
658     case '.': {
659       var_expr = var_expr.drop_front(); // Remove the '.' or '>'
660       separator_idx = var_expr.find_first_of(".-[");
661       ConstString child_name(var_expr.substr(0, var_expr.find_first_of(".-[")));
662 
663       if (check_ptr_vs_member) {
664         // We either have a pointer type and need to verify valobj_sp is a
665         // pointer, or we have a member of a class/union/struct being accessed
666         // with the . syntax and need to verify we don't have a pointer.
667         const bool actual_is_ptr = valobj_sp->IsPointerType();
668 
669         if (actual_is_ptr != expr_is_ptr) {
670           // Incorrect use of "." with a pointer, or "->" with a
671           // class/union/struct instance or reference.
672           valobj_sp->GetExpressionPath(var_expr_path_strm, false);
673           if (actual_is_ptr)
674             error.SetErrorStringWithFormat(
675                 "\"%s\" is a pointer and . was used to attempt to access "
676                 "\"%s\". Did you mean \"%s->%s\"?",
677                 var_expr_path_strm.GetData(), child_name.GetCString(),
678                 var_expr_path_strm.GetData(), var_expr.str().c_str());
679           else
680             error.SetErrorStringWithFormat(
681                 "\"%s\" is not a pointer and -> was used to attempt to "
682                 "access \"%s\". Did you mean \"%s.%s\"?",
683                 var_expr_path_strm.GetData(), child_name.GetCString(),
684                 var_expr_path_strm.GetData(), var_expr.str().c_str());
685           return ValueObjectSP();
686         }
687       }
688       child_valobj_sp = valobj_sp->GetChildMemberWithName(child_name, true);
689       if (!child_valobj_sp) {
690         if (!no_synth_child) {
691           child_valobj_sp = valobj_sp->GetSyntheticValue();
692           if (child_valobj_sp)
693             child_valobj_sp =
694                 child_valobj_sp->GetChildMemberWithName(child_name, true);
695         }
696 
697         if (no_synth_child || !child_valobj_sp) {
698           // No child member with name "child_name"
699           if (synthetically_added_instance_object) {
700             // We added a "this->" or "self->" to the beginning of the
701             // expression and this is the first pointer ivar access, so just
702             // return the normal error
703             error.SetErrorStringWithFormat(
704                 "no variable or instance variable named '%s' found in "
705                 "this frame",
706                 name_const_string.GetCString());
707           } else {
708             valobj_sp->GetExpressionPath(var_expr_path_strm, false);
709             if (child_name) {
710               error.SetErrorStringWithFormat(
711                   "\"%s\" is not a member of \"(%s) %s\"",
712                   child_name.GetCString(),
713                   valobj_sp->GetTypeName().AsCString("<invalid type>"),
714                   var_expr_path_strm.GetData());
715             } else {
716               error.SetErrorStringWithFormat(
717                   "incomplete expression path after \"%s\" in \"%s\"",
718                   var_expr_path_strm.GetData(),
719                   original_var_expr.str().c_str());
720             }
721           }
722           return ValueObjectSP();
723         }
724       }
725       synthetically_added_instance_object = false;
726       // Remove the child name from the path
727       var_expr = var_expr.drop_front(child_name.GetLength());
728       if (use_dynamic != eNoDynamicValues) {
729         ValueObjectSP dynamic_value_sp(
730             child_valobj_sp->GetDynamicValue(use_dynamic));
731         if (dynamic_value_sp)
732           child_valobj_sp = dynamic_value_sp;
733       }
734     } break;
735 
736     case '[': {
737       // Array member access, or treating pointer as an array Need at least two
738       // brackets and a number
739       if (var_expr.size() <= 2) {
740         error.SetErrorStringWithFormat(
741             "invalid square bracket encountered after \"%s\" in \"%s\"",
742             var_expr_path_strm.GetData(), var_expr.str().c_str());
743         return ValueObjectSP();
744       }
745 
746       // Drop the open brace.
747       var_expr = var_expr.drop_front();
748       long child_index = 0;
749 
750       // If there's no closing brace, this is an invalid expression.
751       size_t end_pos = var_expr.find_first_of(']');
752       if (end_pos == llvm::StringRef::npos) {
753         error.SetErrorStringWithFormat(
754             "missing closing square bracket in expression \"%s\"",
755             var_expr_path_strm.GetData());
756         return ValueObjectSP();
757       }
758       llvm::StringRef index_expr = var_expr.take_front(end_pos);
759       llvm::StringRef original_index_expr = index_expr;
760       // Drop all of "[index_expr]"
761       var_expr = var_expr.drop_front(end_pos + 1);
762 
763       if (index_expr.consumeInteger(0, child_index)) {
764         // If there was no integer anywhere in the index expression, this is
765         // erroneous expression.
766         error.SetErrorStringWithFormat("invalid index expression \"%s\"",
767                                        index_expr.str().c_str());
768         return ValueObjectSP();
769       }
770 
771       if (index_expr.empty()) {
772         // The entire index expression was a single integer.
773 
774         if (valobj_sp->GetCompilerType().IsPointerToScalarType() && deref) {
775           // what we have is *ptr[low]. the most similar C++ syntax is to deref
776           // ptr and extract bit low out of it. reading array item low would be
777           // done by saying ptr[low], without a deref * sign
778           Status error;
779           ValueObjectSP temp(valobj_sp->Dereference(error));
780           if (error.Fail()) {
781             valobj_sp->GetExpressionPath(var_expr_path_strm, false);
782             error.SetErrorStringWithFormat(
783                 "could not dereference \"(%s) %s\"",
784                 valobj_sp->GetTypeName().AsCString("<invalid type>"),
785                 var_expr_path_strm.GetData());
786             return ValueObjectSP();
787           }
788           valobj_sp = temp;
789           deref = false;
790         } else if (valobj_sp->GetCompilerType().IsArrayOfScalarType() &&
791                    deref) {
792           // what we have is *arr[low]. the most similar C++ syntax is to get
793           // arr[0] (an operation that is equivalent to deref-ing arr) and
794           // extract bit low out of it. reading array item low would be done by
795           // saying arr[low], without a deref * sign
796           Status error;
797           ValueObjectSP temp(valobj_sp->GetChildAtIndex(0, true));
798           if (error.Fail()) {
799             valobj_sp->GetExpressionPath(var_expr_path_strm, false);
800             error.SetErrorStringWithFormat(
801                 "could not get item 0 for \"(%s) %s\"",
802                 valobj_sp->GetTypeName().AsCString("<invalid type>"),
803                 var_expr_path_strm.GetData());
804             return ValueObjectSP();
805           }
806           valobj_sp = temp;
807           deref = false;
808         }
809 
810         bool is_incomplete_array = false;
811         if (valobj_sp->IsPointerType()) {
812           bool is_objc_pointer = true;
813 
814           if (valobj_sp->GetCompilerType().GetMinimumLanguage() !=
815               eLanguageTypeObjC)
816             is_objc_pointer = false;
817           else if (!valobj_sp->GetCompilerType().IsPointerType())
818             is_objc_pointer = false;
819 
820           if (no_synth_child && is_objc_pointer) {
821             error.SetErrorStringWithFormat(
822                 "\"(%s) %s\" is an Objective-C pointer, and cannot be "
823                 "subscripted",
824                 valobj_sp->GetTypeName().AsCString("<invalid type>"),
825                 var_expr_path_strm.GetData());
826 
827             return ValueObjectSP();
828           } else if (is_objc_pointer) {
829             // dereferencing ObjC variables is not valid.. so let's try and
830             // recur to synthetic children
831             ValueObjectSP synthetic = valobj_sp->GetSyntheticValue();
832             if (!synthetic                 /* no synthetic */
833                 || synthetic == valobj_sp) /* synthetic is the same as
834                                               the original object */
835             {
836               valobj_sp->GetExpressionPath(var_expr_path_strm, false);
837               error.SetErrorStringWithFormat(
838                   "\"(%s) %s\" is not an array type",
839                   valobj_sp->GetTypeName().AsCString("<invalid type>"),
840                   var_expr_path_strm.GetData());
841             } else if (
842                 static_cast<uint32_t>(child_index) >=
843                 synthetic
844                     ->GetNumChildren() /* synthetic does not have that many values */) {
845               valobj_sp->GetExpressionPath(var_expr_path_strm, false);
846               error.SetErrorStringWithFormat(
847                   "array index %ld is not valid for \"(%s) %s\"", child_index,
848                   valobj_sp->GetTypeName().AsCString("<invalid type>"),
849                   var_expr_path_strm.GetData());
850             } else {
851               child_valobj_sp = synthetic->GetChildAtIndex(child_index, true);
852               if (!child_valobj_sp) {
853                 valobj_sp->GetExpressionPath(var_expr_path_strm, false);
854                 error.SetErrorStringWithFormat(
855                     "array index %ld is not valid for \"(%s) %s\"", child_index,
856                     valobj_sp->GetTypeName().AsCString("<invalid type>"),
857                     var_expr_path_strm.GetData());
858               }
859             }
860           } else {
861             child_valobj_sp =
862                 valobj_sp->GetSyntheticArrayMember(child_index, true);
863             if (!child_valobj_sp) {
864               valobj_sp->GetExpressionPath(var_expr_path_strm, false);
865               error.SetErrorStringWithFormat(
866                   "failed to use pointer as array for index %ld for "
867                   "\"(%s) %s\"",
868                   child_index,
869                   valobj_sp->GetTypeName().AsCString("<invalid type>"),
870                   var_expr_path_strm.GetData());
871             }
872           }
873         } else if (valobj_sp->GetCompilerType().IsArrayType(
874                        nullptr, nullptr, &is_incomplete_array)) {
875           // Pass false to dynamic_value here so we can tell the difference
876           // between no dynamic value and no member of this type...
877           child_valobj_sp = valobj_sp->GetChildAtIndex(child_index, true);
878           if (!child_valobj_sp && (is_incomplete_array || !no_synth_child))
879             child_valobj_sp =
880                 valobj_sp->GetSyntheticArrayMember(child_index, true);
881 
882           if (!child_valobj_sp) {
883             valobj_sp->GetExpressionPath(var_expr_path_strm, false);
884             error.SetErrorStringWithFormat(
885                 "array index %ld is not valid for \"(%s) %s\"", child_index,
886                 valobj_sp->GetTypeName().AsCString("<invalid type>"),
887                 var_expr_path_strm.GetData());
888           }
889         } else if (valobj_sp->GetCompilerType().IsScalarType()) {
890           // this is a bitfield asking to display just one bit
891           child_valobj_sp = valobj_sp->GetSyntheticBitFieldChild(
892               child_index, child_index, true);
893           if (!child_valobj_sp) {
894             valobj_sp->GetExpressionPath(var_expr_path_strm, false);
895             error.SetErrorStringWithFormat(
896                 "bitfield range %ld-%ld is not valid for \"(%s) %s\"",
897                 child_index, child_index,
898                 valobj_sp->GetTypeName().AsCString("<invalid type>"),
899                 var_expr_path_strm.GetData());
900           }
901         } else {
902           ValueObjectSP synthetic = valobj_sp->GetSyntheticValue();
903           if (no_synth_child /* synthetic is forbidden */ ||
904               !synthetic                 /* no synthetic */
905               || synthetic == valobj_sp) /* synthetic is the same as the
906                                             original object */
907           {
908             valobj_sp->GetExpressionPath(var_expr_path_strm, false);
909             error.SetErrorStringWithFormat(
910                 "\"(%s) %s\" is not an array type",
911                 valobj_sp->GetTypeName().AsCString("<invalid type>"),
912                 var_expr_path_strm.GetData());
913           } else if (
914               static_cast<uint32_t>(child_index) >=
915               synthetic
916                   ->GetNumChildren() /* synthetic does not have that many values */) {
917             valobj_sp->GetExpressionPath(var_expr_path_strm, false);
918             error.SetErrorStringWithFormat(
919                 "array index %ld is not valid for \"(%s) %s\"", child_index,
920                 valobj_sp->GetTypeName().AsCString("<invalid type>"),
921                 var_expr_path_strm.GetData());
922           } else {
923             child_valobj_sp = synthetic->GetChildAtIndex(child_index, true);
924             if (!child_valobj_sp) {
925               valobj_sp->GetExpressionPath(var_expr_path_strm, false);
926               error.SetErrorStringWithFormat(
927                   "array index %ld is not valid for \"(%s) %s\"", child_index,
928                   valobj_sp->GetTypeName().AsCString("<invalid type>"),
929                   var_expr_path_strm.GetData());
930             }
931           }
932         }
933 
934         if (!child_valobj_sp) {
935           // Invalid array index...
936           return ValueObjectSP();
937         }
938 
939         separator_idx = var_expr.find_first_of(".-[");
940         if (use_dynamic != eNoDynamicValues) {
941           ValueObjectSP dynamic_value_sp(
942               child_valobj_sp->GetDynamicValue(use_dynamic));
943           if (dynamic_value_sp)
944             child_valobj_sp = dynamic_value_sp;
945         }
946         // Break out early from the switch since we were able to find the child
947         // member
948         break;
949       }
950 
951       // this is most probably a BitField, let's take a look
952       if (index_expr.front() != '-') {
953         error.SetErrorStringWithFormat("invalid range expression \"'%s'\"",
954                                        original_index_expr.str().c_str());
955         return ValueObjectSP();
956       }
957 
958       index_expr = index_expr.drop_front();
959       long final_index = 0;
960       if (index_expr.getAsInteger(0, final_index)) {
961         error.SetErrorStringWithFormat("invalid range expression \"'%s'\"",
962                                        original_index_expr.str().c_str());
963         return ValueObjectSP();
964       }
965 
966       // if the format given is [high-low], swap range
967       if (child_index > final_index) {
968         long temp = child_index;
969         child_index = final_index;
970         final_index = temp;
971       }
972 
973       if (valobj_sp->GetCompilerType().IsPointerToScalarType() && deref) {
974         // what we have is *ptr[low-high]. the most similar C++ syntax is to
975         // deref ptr and extract bits low thru high out of it. reading array
976         // items low thru high would be done by saying ptr[low-high], without a
977         // deref * sign
978         Status error;
979         ValueObjectSP temp(valobj_sp->Dereference(error));
980         if (error.Fail()) {
981           valobj_sp->GetExpressionPath(var_expr_path_strm, false);
982           error.SetErrorStringWithFormat(
983               "could not dereference \"(%s) %s\"",
984               valobj_sp->GetTypeName().AsCString("<invalid type>"),
985               var_expr_path_strm.GetData());
986           return ValueObjectSP();
987         }
988         valobj_sp = temp;
989         deref = false;
990       } else if (valobj_sp->GetCompilerType().IsArrayOfScalarType() && deref) {
991         // what we have is *arr[low-high]. the most similar C++ syntax is to
992         // get arr[0] (an operation that is equivalent to deref-ing arr) and
993         // extract bits low thru high out of it. reading array items low thru
994         // high would be done by saying arr[low-high], without a deref * sign
995         Status error;
996         ValueObjectSP temp(valobj_sp->GetChildAtIndex(0, true));
997         if (error.Fail()) {
998           valobj_sp->GetExpressionPath(var_expr_path_strm, false);
999           error.SetErrorStringWithFormat(
1000               "could not get item 0 for \"(%s) %s\"",
1001               valobj_sp->GetTypeName().AsCString("<invalid type>"),
1002               var_expr_path_strm.GetData());
1003           return ValueObjectSP();
1004         }
1005         valobj_sp = temp;
1006         deref = false;
1007       }
1008 
1009       child_valobj_sp =
1010           valobj_sp->GetSyntheticBitFieldChild(child_index, final_index, true);
1011       if (!child_valobj_sp) {
1012         valobj_sp->GetExpressionPath(var_expr_path_strm, false);
1013         error.SetErrorStringWithFormat(
1014             "bitfield range %ld-%ld is not valid for \"(%s) %s\"", child_index,
1015             final_index, valobj_sp->GetTypeName().AsCString("<invalid type>"),
1016             var_expr_path_strm.GetData());
1017       }
1018 
1019       if (!child_valobj_sp) {
1020         // Invalid bitfield range...
1021         return ValueObjectSP();
1022       }
1023 
1024       separator_idx = var_expr.find_first_of(".-[");
1025       if (use_dynamic != eNoDynamicValues) {
1026         ValueObjectSP dynamic_value_sp(
1027             child_valobj_sp->GetDynamicValue(use_dynamic));
1028         if (dynamic_value_sp)
1029           child_valobj_sp = dynamic_value_sp;
1030       }
1031       // Break out early from the switch since we were able to find the child
1032       // member
1033       break;
1034     }
1035     default:
1036       // Failure...
1037       {
1038         valobj_sp->GetExpressionPath(var_expr_path_strm, false);
1039         error.SetErrorStringWithFormat(
1040             "unexpected char '%c' encountered after \"%s\" in \"%s\"",
1041             separator_type, var_expr_path_strm.GetData(),
1042             var_expr.str().c_str());
1043 
1044         return ValueObjectSP();
1045       }
1046     }
1047 
1048     if (child_valobj_sp)
1049       valobj_sp = child_valobj_sp;
1050 
1051     if (var_expr.empty())
1052       break;
1053   }
1054   if (valobj_sp) {
1055     if (deref) {
1056       ValueObjectSP deref_valobj_sp(valobj_sp->Dereference(error));
1057       valobj_sp = deref_valobj_sp;
1058     } else if (address_of) {
1059       ValueObjectSP address_of_valobj_sp(valobj_sp->AddressOf(error));
1060       valobj_sp = address_of_valobj_sp;
1061     }
1062   }
1063   return valobj_sp;
1064 }
1065 
1066 bool StackFrame::GetFrameBaseValue(Scalar &frame_base, Status *error_ptr) {
1067   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1068   if (!m_cfa_is_valid) {
1069     m_frame_base_error.SetErrorString(
1070         "No frame base available for this historical stack frame.");
1071     return false;
1072   }
1073 
1074   if (m_flags.IsClear(GOT_FRAME_BASE)) {
1075     if (m_sc.function) {
1076       m_frame_base.Clear();
1077       m_frame_base_error.Clear();
1078 
1079       m_flags.Set(GOT_FRAME_BASE);
1080       ExecutionContext exe_ctx(shared_from_this());
1081       Value expr_value;
1082       addr_t loclist_base_addr = LLDB_INVALID_ADDRESS;
1083       if (m_sc.function->GetFrameBaseExpression().IsLocationList())
1084         loclist_base_addr =
1085             m_sc.function->GetAddressRange().GetBaseAddress().GetLoadAddress(
1086                 exe_ctx.GetTargetPtr());
1087 
1088       if (!m_sc.function->GetFrameBaseExpression().Evaluate(
1089               &exe_ctx, nullptr, loclist_base_addr, nullptr, nullptr,
1090               expr_value, &m_frame_base_error)) {
1091         // We should really have an error if evaluate returns, but in case we
1092         // don't, lets set the error to something at least.
1093         if (m_frame_base_error.Success())
1094           m_frame_base_error.SetErrorString(
1095               "Evaluation of the frame base expression failed.");
1096       } else {
1097         m_frame_base = expr_value.ResolveValue(&exe_ctx);
1098       }
1099     } else {
1100       m_frame_base_error.SetErrorString("No function in symbol context.");
1101     }
1102   }
1103 
1104   if (m_frame_base_error.Success())
1105     frame_base = m_frame_base;
1106 
1107   if (error_ptr)
1108     *error_ptr = m_frame_base_error;
1109   return m_frame_base_error.Success();
1110 }
1111 
1112 DWARFExpression *StackFrame::GetFrameBaseExpression(Status *error_ptr) {
1113   if (!m_sc.function) {
1114     if (error_ptr) {
1115       error_ptr->SetErrorString("No function in symbol context.");
1116     }
1117     return nullptr;
1118   }
1119 
1120   return &m_sc.function->GetFrameBaseExpression();
1121 }
1122 
1123 RegisterContextSP StackFrame::GetRegisterContext() {
1124   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1125   if (!m_reg_context_sp) {
1126     ThreadSP thread_sp(GetThread());
1127     if (thread_sp)
1128       m_reg_context_sp = thread_sp->CreateRegisterContextForFrame(this);
1129   }
1130   return m_reg_context_sp;
1131 }
1132 
1133 bool StackFrame::HasDebugInformation() {
1134   GetSymbolContext(eSymbolContextLineEntry);
1135   return m_sc.line_entry.IsValid();
1136 }
1137 
1138 ValueObjectSP
1139 StackFrame::GetValueObjectForFrameVariable(const VariableSP &variable_sp,
1140                                            DynamicValueType use_dynamic) {
1141   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1142   ValueObjectSP valobj_sp;
1143   if (IsHistorical()) {
1144     return valobj_sp;
1145   }
1146   VariableList *var_list = GetVariableList(true);
1147   if (var_list) {
1148     // Make sure the variable is a frame variable
1149     const uint32_t var_idx = var_list->FindIndexForVariable(variable_sp.get());
1150     const uint32_t num_variables = var_list->GetSize();
1151     if (var_idx < num_variables) {
1152       valobj_sp = m_variable_list_value_objects.GetValueObjectAtIndex(var_idx);
1153       if (!valobj_sp) {
1154         if (m_variable_list_value_objects.GetSize() < num_variables)
1155           m_variable_list_value_objects.Resize(num_variables);
1156         valobj_sp = ValueObjectVariable::Create(this, variable_sp);
1157         m_variable_list_value_objects.SetValueObjectAtIndex(var_idx, valobj_sp);
1158       }
1159     }
1160   }
1161   if (use_dynamic != eNoDynamicValues && valobj_sp) {
1162     ValueObjectSP dynamic_sp = valobj_sp->GetDynamicValue(use_dynamic);
1163     if (dynamic_sp)
1164       return dynamic_sp;
1165   }
1166   return valobj_sp;
1167 }
1168 
1169 ValueObjectSP StackFrame::TrackGlobalVariable(const VariableSP &variable_sp,
1170                                               DynamicValueType use_dynamic) {
1171   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1172   if (IsHistorical())
1173     return ValueObjectSP();
1174 
1175   // Check to make sure we aren't already tracking this variable?
1176   ValueObjectSP valobj_sp(
1177       GetValueObjectForFrameVariable(variable_sp, use_dynamic));
1178   if (!valobj_sp) {
1179     // We aren't already tracking this global
1180     VariableList *var_list = GetVariableList(true);
1181     // If this frame has no variables, create a new list
1182     if (var_list == nullptr)
1183       m_variable_list_sp = std::make_shared<VariableList>();
1184 
1185     // Add the global/static variable to this frame
1186     m_variable_list_sp->AddVariable(variable_sp);
1187 
1188     // Now make a value object for it so we can track its changes
1189     valobj_sp = GetValueObjectForFrameVariable(variable_sp, use_dynamic);
1190   }
1191   return valobj_sp;
1192 }
1193 
1194 bool StackFrame::IsInlined() {
1195   if (m_sc.block == nullptr)
1196     GetSymbolContext(eSymbolContextBlock);
1197   if (m_sc.block)
1198     return m_sc.block->GetContainingInlinedBlock() != nullptr;
1199   return false;
1200 }
1201 
1202 bool StackFrame::IsHistorical() const {
1203   return m_stack_frame_kind == StackFrame::Kind::History;
1204 }
1205 
1206 bool StackFrame::IsArtificial() const {
1207   return m_stack_frame_kind == StackFrame::Kind::Artificial;
1208 }
1209 
1210 lldb::LanguageType StackFrame::GetLanguage() {
1211   CompileUnit *cu = GetSymbolContext(eSymbolContextCompUnit).comp_unit;
1212   if (cu)
1213     return cu->GetLanguage();
1214   return lldb::eLanguageTypeUnknown;
1215 }
1216 
1217 lldb::LanguageType StackFrame::GuessLanguage() {
1218   LanguageType lang_type = GetLanguage();
1219 
1220   if (lang_type == eLanguageTypeUnknown) {
1221     SymbolContext sc = GetSymbolContext(eSymbolContextFunction
1222                                         | eSymbolContextSymbol);
1223     if (sc.function) {
1224       lang_type = sc.function->GetMangled().GuessLanguage();
1225     }
1226     else if (sc.symbol)
1227     {
1228       lang_type = sc.symbol->GetMangled().GuessLanguage();
1229     }
1230   }
1231 
1232   return lang_type;
1233 }
1234 
1235 namespace {
1236 std::pair<const Instruction::Operand *, int64_t>
1237 GetBaseExplainingValue(const Instruction::Operand &operand,
1238                        RegisterContext &register_context, lldb::addr_t value) {
1239   switch (operand.m_type) {
1240   case Instruction::Operand::Type::Dereference:
1241   case Instruction::Operand::Type::Immediate:
1242   case Instruction::Operand::Type::Invalid:
1243   case Instruction::Operand::Type::Product:
1244     // These are not currently interesting
1245     return std::make_pair(nullptr, 0);
1246   case Instruction::Operand::Type::Sum: {
1247     const Instruction::Operand *immediate_child = nullptr;
1248     const Instruction::Operand *variable_child = nullptr;
1249     if (operand.m_children[0].m_type == Instruction::Operand::Type::Immediate) {
1250       immediate_child = &operand.m_children[0];
1251       variable_child = &operand.m_children[1];
1252     } else if (operand.m_children[1].m_type ==
1253                Instruction::Operand::Type::Immediate) {
1254       immediate_child = &operand.m_children[1];
1255       variable_child = &operand.m_children[0];
1256     }
1257     if (!immediate_child) {
1258       return std::make_pair(nullptr, 0);
1259     }
1260     lldb::addr_t adjusted_value = value;
1261     if (immediate_child->m_negative) {
1262       adjusted_value += immediate_child->m_immediate;
1263     } else {
1264       adjusted_value -= immediate_child->m_immediate;
1265     }
1266     std::pair<const Instruction::Operand *, int64_t> base_and_offset =
1267         GetBaseExplainingValue(*variable_child, register_context,
1268                                adjusted_value);
1269     if (!base_and_offset.first) {
1270       return std::make_pair(nullptr, 0);
1271     }
1272     if (immediate_child->m_negative) {
1273       base_and_offset.second -= immediate_child->m_immediate;
1274     } else {
1275       base_and_offset.second += immediate_child->m_immediate;
1276     }
1277     return base_and_offset;
1278   }
1279   case Instruction::Operand::Type::Register: {
1280     const RegisterInfo *info =
1281         register_context.GetRegisterInfoByName(operand.m_register.AsCString());
1282     if (!info) {
1283       return std::make_pair(nullptr, 0);
1284     }
1285     RegisterValue reg_value;
1286     if (!register_context.ReadRegister(info, reg_value)) {
1287       return std::make_pair(nullptr, 0);
1288     }
1289     if (reg_value.GetAsUInt64() == value) {
1290       return std::make_pair(&operand, 0);
1291     } else {
1292       return std::make_pair(nullptr, 0);
1293     }
1294   }
1295   }
1296   return std::make_pair(nullptr, 0);
1297 }
1298 
1299 std::pair<const Instruction::Operand *, int64_t>
1300 GetBaseExplainingDereference(const Instruction::Operand &operand,
1301                              RegisterContext &register_context,
1302                              lldb::addr_t addr) {
1303   if (operand.m_type == Instruction::Operand::Type::Dereference) {
1304     return GetBaseExplainingValue(operand.m_children[0], register_context,
1305                                   addr);
1306   }
1307   return std::make_pair(nullptr, 0);
1308 }
1309 }
1310 
1311 lldb::ValueObjectSP StackFrame::GuessValueForAddress(lldb::addr_t addr) {
1312   TargetSP target_sp = CalculateTarget();
1313 
1314   const ArchSpec &target_arch = target_sp->GetArchitecture();
1315 
1316   AddressRange pc_range;
1317   pc_range.GetBaseAddress() = GetFrameCodeAddress();
1318   pc_range.SetByteSize(target_arch.GetMaximumOpcodeByteSize());
1319 
1320   ExecutionContext exe_ctx(shared_from_this());
1321 
1322   const char *plugin_name = nullptr;
1323   const char *flavor = nullptr;
1324   const bool prefer_file_cache = false;
1325 
1326   DisassemblerSP disassembler_sp = Disassembler::DisassembleRange(
1327       target_arch, plugin_name, flavor, exe_ctx, pc_range, prefer_file_cache);
1328 
1329   if (!disassembler_sp || !disassembler_sp->GetInstructionList().GetSize()) {
1330     return ValueObjectSP();
1331   }
1332 
1333   InstructionSP instruction_sp =
1334       disassembler_sp->GetInstructionList().GetInstructionAtIndex(0);
1335 
1336   llvm::SmallVector<Instruction::Operand, 3> operands;
1337 
1338   if (!instruction_sp->ParseOperands(operands)) {
1339     return ValueObjectSP();
1340   }
1341 
1342   RegisterContextSP register_context_sp = GetRegisterContext();
1343 
1344   if (!register_context_sp) {
1345     return ValueObjectSP();
1346   }
1347 
1348   for (const Instruction::Operand &operand : operands) {
1349     std::pair<const Instruction::Operand *, int64_t> base_and_offset =
1350         GetBaseExplainingDereference(operand, *register_context_sp, addr);
1351 
1352     if (!base_and_offset.first) {
1353       continue;
1354     }
1355 
1356     switch (base_and_offset.first->m_type) {
1357     case Instruction::Operand::Type::Immediate: {
1358       lldb_private::Address addr;
1359       if (target_sp->ResolveLoadAddress(base_and_offset.first->m_immediate +
1360                                             base_and_offset.second,
1361                                         addr)) {
1362         TypeSystem *c_type_system =
1363             target_sp->GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC);
1364         if (!c_type_system) {
1365           return ValueObjectSP();
1366         } else {
1367           CompilerType void_ptr_type =
1368               c_type_system
1369                   ->GetBasicTypeFromAST(lldb::BasicType::eBasicTypeChar)
1370                   .GetPointerType();
1371           return ValueObjectMemory::Create(this, "", addr, void_ptr_type);
1372         }
1373       } else {
1374         return ValueObjectSP();
1375       }
1376       break;
1377     }
1378     case Instruction::Operand::Type::Register: {
1379       return GuessValueForRegisterAndOffset(base_and_offset.first->m_register,
1380                                             base_and_offset.second);
1381     }
1382     default:
1383       return ValueObjectSP();
1384     }
1385   }
1386 
1387   return ValueObjectSP();
1388 }
1389 
1390 namespace {
1391 ValueObjectSP GetValueForOffset(StackFrame &frame, ValueObjectSP &parent,
1392                                 int64_t offset) {
1393   if (offset < 0 || uint64_t(offset) >= parent->GetByteSize()) {
1394     return ValueObjectSP();
1395   }
1396 
1397   if (parent->IsPointerOrReferenceType()) {
1398     return parent;
1399   }
1400 
1401   for (int ci = 0, ce = parent->GetNumChildren(); ci != ce; ++ci) {
1402     const bool can_create = true;
1403     ValueObjectSP child_sp = parent->GetChildAtIndex(ci, can_create);
1404 
1405     if (!child_sp) {
1406       return ValueObjectSP();
1407     }
1408 
1409     int64_t child_offset = child_sp->GetByteOffset();
1410     int64_t child_size = child_sp->GetByteSize();
1411 
1412     if (offset >= child_offset && offset < (child_offset + child_size)) {
1413       return GetValueForOffset(frame, child_sp, offset - child_offset);
1414     }
1415   }
1416 
1417   if (offset == 0) {
1418     return parent;
1419   } else {
1420     return ValueObjectSP();
1421   }
1422 }
1423 
1424 ValueObjectSP GetValueForDereferincingOffset(StackFrame &frame,
1425                                              ValueObjectSP &base,
1426                                              int64_t offset) {
1427   // base is a pointer to something
1428   // offset is the thing to add to the pointer We return the most sensible
1429   // ValueObject for the result of *(base+offset)
1430 
1431   if (!base->IsPointerOrReferenceType()) {
1432     return ValueObjectSP();
1433   }
1434 
1435   Status error;
1436   ValueObjectSP pointee = base->Dereference(error);
1437 
1438   if (!pointee) {
1439     return ValueObjectSP();
1440   }
1441 
1442   if (offset >= 0 && uint64_t(offset) >= pointee->GetByteSize()) {
1443     int64_t index = offset / pointee->GetByteSize();
1444     offset = offset % pointee->GetByteSize();
1445     const bool can_create = true;
1446     pointee = base->GetSyntheticArrayMember(index, can_create);
1447   }
1448 
1449   if (!pointee || error.Fail()) {
1450     return ValueObjectSP();
1451   }
1452 
1453   return GetValueForOffset(frame, pointee, offset);
1454 }
1455 
1456 //------------------------------------------------------------------
1457 /// Attempt to reconstruct the ValueObject for the address contained in a
1458 /// given register plus an offset.
1459 ///
1460 /// \params [in] frame
1461 ///   The current stack frame.
1462 ///
1463 /// \params [in] reg
1464 ///   The register.
1465 ///
1466 /// \params [in] offset
1467 ///   The offset from the register.
1468 ///
1469 /// \param [in] disassembler
1470 ///   A disassembler containing instructions valid up to the current PC.
1471 ///
1472 /// \param [in] variables
1473 ///   The variable list from the current frame,
1474 ///
1475 /// \param [in] pc
1476 ///   The program counter for the instruction considered the 'user'.
1477 ///
1478 /// \return
1479 ///   A string describing the base for the ExpressionPath.  This could be a
1480 ///     variable, a register value, an argument, or a function return value.
1481 ///   The ValueObject if found.  If valid, it has a valid ExpressionPath.
1482 //------------------------------------------------------------------
1483 lldb::ValueObjectSP DoGuessValueAt(StackFrame &frame, ConstString reg,
1484                                    int64_t offset, Disassembler &disassembler,
1485                                    VariableList &variables, const Address &pc) {
1486   // Example of operation for Intel:
1487   //
1488   // +14: movq   -0x8(%rbp), %rdi
1489   // +18: movq   0x8(%rdi), %rdi
1490   // +22: addl   0x4(%rdi), %eax
1491   //
1492   // f, a pointer to a struct, is known to be at -0x8(%rbp).
1493   //
1494   // DoGuessValueAt(frame, rdi, 4, dis, vars, 0x22) finds the instruction at
1495   // +18 that assigns to rdi, and calls itself recursively for that dereference
1496   //   DoGuessValueAt(frame, rdi, 8, dis, vars, 0x18) finds the instruction at
1497   //   +14 that assigns to rdi, and calls itself recursively for that
1498   //   derefernece
1499   //     DoGuessValueAt(frame, rbp, -8, dis, vars, 0x14) finds "f" in the
1500   //     variable list.
1501   //     Returns a ValueObject for f.  (That's what was stored at rbp-8 at +14)
1502   //   Returns a ValueObject for *(f+8) or f->b (That's what was stored at rdi+8
1503   //   at +18)
1504   // Returns a ValueObject for *(f->b+4) or f->b->a (That's what was stored at
1505   // rdi+4 at +22)
1506 
1507   // First, check the variable list to see if anything is at the specified
1508   // location.
1509 
1510   using namespace OperandMatchers;
1511 
1512   const RegisterInfo *reg_info =
1513       frame.GetRegisterContext()->GetRegisterInfoByName(reg.AsCString());
1514   if (!reg_info) {
1515     return ValueObjectSP();
1516   }
1517 
1518   Instruction::Operand op =
1519       offset ? Instruction::Operand::BuildDereference(
1520                    Instruction::Operand::BuildSum(
1521                        Instruction::Operand::BuildRegister(reg),
1522                        Instruction::Operand::BuildImmediate(offset)))
1523              : Instruction::Operand::BuildDereference(
1524                    Instruction::Operand::BuildRegister(reg));
1525 
1526   for (size_t vi = 0, ve = variables.GetSize(); vi != ve; ++vi) {
1527     VariableSP var_sp = variables.GetVariableAtIndex(vi);
1528     if (var_sp->LocationExpression().MatchesOperand(frame, op)) {
1529       return frame.GetValueObjectForFrameVariable(var_sp, eNoDynamicValues);
1530     }
1531   }
1532 
1533   const uint32_t current_inst =
1534       disassembler.GetInstructionList().GetIndexOfInstructionAtAddress(pc);
1535   if (current_inst == UINT32_MAX) {
1536     return ValueObjectSP();
1537   }
1538 
1539   for (uint32_t ii = current_inst - 1; ii != (uint32_t)-1; --ii) {
1540     // This is not an exact algorithm, and it sacrifices accuracy for
1541     // generality.  Recognizing "mov" and "ld" instructions –– and which
1542     // are their source and destination operands -- is something the
1543     // disassembler should do for us.
1544     InstructionSP instruction_sp =
1545         disassembler.GetInstructionList().GetInstructionAtIndex(ii);
1546 
1547     if (instruction_sp->IsCall()) {
1548       ABISP abi_sp = frame.CalculateProcess()->GetABI();
1549       if (!abi_sp) {
1550         continue;
1551       }
1552 
1553       const char *return_register_name;
1554       if (!abi_sp->GetPointerReturnRegister(return_register_name)) {
1555         continue;
1556       }
1557 
1558       const RegisterInfo *return_register_info =
1559           frame.GetRegisterContext()->GetRegisterInfoByName(
1560               return_register_name);
1561       if (!return_register_info) {
1562         continue;
1563       }
1564 
1565       int64_t offset = 0;
1566 
1567       if (!MatchUnaryOp(MatchOpType(Instruction::Operand::Type::Dereference),
1568                         MatchRegOp(*return_register_info))(op) &&
1569           !MatchUnaryOp(
1570               MatchOpType(Instruction::Operand::Type::Dereference),
1571               MatchBinaryOp(MatchOpType(Instruction::Operand::Type::Sum),
1572                             MatchRegOp(*return_register_info),
1573                             FetchImmOp(offset)))(op)) {
1574         continue;
1575       }
1576 
1577       llvm::SmallVector<Instruction::Operand, 1> operands;
1578       if (!instruction_sp->ParseOperands(operands) || operands.size() != 1) {
1579         continue;
1580       }
1581 
1582       switch (operands[0].m_type) {
1583       default:
1584         break;
1585       case Instruction::Operand::Type::Immediate: {
1586         SymbolContext sc;
1587         Address load_address;
1588         if (!frame.CalculateTarget()->ResolveLoadAddress(
1589                 operands[0].m_immediate, load_address)) {
1590           break;
1591         }
1592         frame.CalculateTarget()->GetImages().ResolveSymbolContextForAddress(
1593             load_address, eSymbolContextFunction, sc);
1594         if (!sc.function) {
1595           break;
1596         }
1597         CompilerType function_type = sc.function->GetCompilerType();
1598         if (!function_type.IsFunctionType()) {
1599           break;
1600         }
1601         CompilerType return_type = function_type.GetFunctionReturnType();
1602         RegisterValue return_value;
1603         if (!frame.GetRegisterContext()->ReadRegister(return_register_info,
1604                                                       return_value)) {
1605           break;
1606         }
1607         std::string name_str(
1608             sc.function->GetName().AsCString("<unknown function>"));
1609         name_str.append("()");
1610         Address return_value_address(return_value.GetAsUInt64());
1611         ValueObjectSP return_value_sp = ValueObjectMemory::Create(
1612             &frame, name_str, return_value_address, return_type);
1613         return GetValueForDereferincingOffset(frame, return_value_sp, offset);
1614       }
1615       }
1616 
1617       continue;
1618     }
1619 
1620     llvm::SmallVector<Instruction::Operand, 2> operands;
1621     if (!instruction_sp->ParseOperands(operands) || operands.size() != 2) {
1622       continue;
1623     }
1624 
1625     Instruction::Operand *origin_operand = nullptr;
1626     auto clobbered_reg_matcher = [reg_info](const Instruction::Operand &op) {
1627       return MatchRegOp(*reg_info)(op) && op.m_clobbered;
1628     };
1629 
1630     if (clobbered_reg_matcher(operands[0])) {
1631       origin_operand = &operands[1];
1632     }
1633     else if (clobbered_reg_matcher(operands[1])) {
1634       origin_operand = &operands[0];
1635     }
1636     else {
1637       continue;
1638     }
1639 
1640     // We have an origin operand.  Can we track its value down?
1641     ValueObjectSP source_path;
1642     ConstString origin_register;
1643     int64_t origin_offset = 0;
1644 
1645     if (FetchRegOp(origin_register)(*origin_operand)) {
1646       source_path = DoGuessValueAt(frame, origin_register, 0, disassembler,
1647                                    variables, instruction_sp->GetAddress());
1648     } else if (MatchUnaryOp(
1649                    MatchOpType(Instruction::Operand::Type::Dereference),
1650                    FetchRegOp(origin_register))(*origin_operand) ||
1651                MatchUnaryOp(
1652                    MatchOpType(Instruction::Operand::Type::Dereference),
1653                    MatchBinaryOp(MatchOpType(Instruction::Operand::Type::Sum),
1654                                  FetchRegOp(origin_register),
1655                                  FetchImmOp(origin_offset)))(*origin_operand)) {
1656       source_path =
1657           DoGuessValueAt(frame, origin_register, origin_offset, disassembler,
1658                          variables, instruction_sp->GetAddress());
1659       if (!source_path) {
1660         continue;
1661       }
1662       source_path =
1663           GetValueForDereferincingOffset(frame, source_path, offset);
1664     }
1665 
1666     if (source_path) {
1667       return source_path;
1668     }
1669   }
1670 
1671   return ValueObjectSP();
1672 }
1673 }
1674 
1675 lldb::ValueObjectSP StackFrame::GuessValueForRegisterAndOffset(ConstString reg,
1676                                                                int64_t offset) {
1677   TargetSP target_sp = CalculateTarget();
1678 
1679   const ArchSpec &target_arch = target_sp->GetArchitecture();
1680 
1681   Block *frame_block = GetFrameBlock();
1682 
1683   if (!frame_block) {
1684     return ValueObjectSP();
1685   }
1686 
1687   Function *function = frame_block->CalculateSymbolContextFunction();
1688   if (!function) {
1689     return ValueObjectSP();
1690   }
1691 
1692   AddressRange pc_range = function->GetAddressRange();
1693 
1694   if (GetFrameCodeAddress().GetFileAddress() <
1695           pc_range.GetBaseAddress().GetFileAddress() ||
1696       GetFrameCodeAddress().GetFileAddress() -
1697               pc_range.GetBaseAddress().GetFileAddress() >=
1698           pc_range.GetByteSize()) {
1699     return ValueObjectSP();
1700   }
1701 
1702   ExecutionContext exe_ctx(shared_from_this());
1703 
1704   const char *plugin_name = nullptr;
1705   const char *flavor = nullptr;
1706   const bool prefer_file_cache = false;
1707   DisassemblerSP disassembler_sp = Disassembler::DisassembleRange(
1708       target_arch, plugin_name, flavor, exe_ctx, pc_range, prefer_file_cache);
1709 
1710   if (!disassembler_sp || !disassembler_sp->GetInstructionList().GetSize()) {
1711     return ValueObjectSP();
1712   }
1713 
1714   const bool get_file_globals = false;
1715   VariableList *variables = GetVariableList(get_file_globals);
1716 
1717   if (!variables) {
1718     return ValueObjectSP();
1719   }
1720 
1721   return DoGuessValueAt(*this, reg, offset, *disassembler_sp, *variables,
1722                         GetFrameCodeAddress());
1723 }
1724 
1725 lldb::ValueObjectSP StackFrame::FindVariable(ConstString name) {
1726   ValueObjectSP value_sp;
1727 
1728   if (!name)
1729     return value_sp;
1730 
1731   TargetSP target_sp = CalculateTarget();
1732   ProcessSP process_sp = CalculateProcess();
1733 
1734   if (!target_sp && !process_sp)
1735     return value_sp;
1736 
1737   VariableList variable_list;
1738   VariableSP var_sp;
1739   SymbolContext sc(GetSymbolContext(eSymbolContextBlock));
1740 
1741   if (sc.block) {
1742     const bool can_create = true;
1743     const bool get_parent_variables = true;
1744     const bool stop_if_block_is_inlined_function = true;
1745 
1746     if (sc.block->AppendVariables(
1747             can_create, get_parent_variables, stop_if_block_is_inlined_function,
1748             [this](Variable *v) { return v->IsInScope(this); },
1749             &variable_list)) {
1750       var_sp = variable_list.FindVariable(name);
1751     }
1752 
1753     if (var_sp)
1754       value_sp = GetValueObjectForFrameVariable(var_sp, eNoDynamicValues);
1755   }
1756 
1757   return value_sp;
1758 }
1759 
1760 TargetSP StackFrame::CalculateTarget() {
1761   TargetSP target_sp;
1762   ThreadSP thread_sp(GetThread());
1763   if (thread_sp) {
1764     ProcessSP process_sp(thread_sp->CalculateProcess());
1765     if (process_sp)
1766       target_sp = process_sp->CalculateTarget();
1767   }
1768   return target_sp;
1769 }
1770 
1771 ProcessSP StackFrame::CalculateProcess() {
1772   ProcessSP process_sp;
1773   ThreadSP thread_sp(GetThread());
1774   if (thread_sp)
1775     process_sp = thread_sp->CalculateProcess();
1776   return process_sp;
1777 }
1778 
1779 ThreadSP StackFrame::CalculateThread() { return GetThread(); }
1780 
1781 StackFrameSP StackFrame::CalculateStackFrame() { return shared_from_this(); }
1782 
1783 void StackFrame::CalculateExecutionContext(ExecutionContext &exe_ctx) {
1784   exe_ctx.SetContext(shared_from_this());
1785 }
1786 
1787 void StackFrame::DumpUsingSettingsFormat(Stream *strm, bool show_unique,
1788                                          const char *frame_marker) {
1789   if (strm == nullptr)
1790     return;
1791 
1792   GetSymbolContext(eSymbolContextEverything);
1793   ExecutionContext exe_ctx(shared_from_this());
1794   StreamString s;
1795 
1796   if (frame_marker)
1797     s.PutCString(frame_marker);
1798 
1799   const FormatEntity::Entry *frame_format = nullptr;
1800   Target *target = exe_ctx.GetTargetPtr();
1801   if (target) {
1802     if (show_unique) {
1803       frame_format = target->GetDebugger().GetFrameFormatUnique();
1804     } else {
1805       frame_format = target->GetDebugger().GetFrameFormat();
1806     }
1807   }
1808   if (frame_format && FormatEntity::Format(*frame_format, s, &m_sc, &exe_ctx,
1809                                            nullptr, nullptr, false, false)) {
1810     strm->PutCString(s.GetString());
1811   } else {
1812     Dump(strm, true, false);
1813     strm->EOL();
1814   }
1815 }
1816 
1817 void StackFrame::Dump(Stream *strm, bool show_frame_index,
1818                       bool show_fullpaths) {
1819   if (strm == nullptr)
1820     return;
1821 
1822   if (show_frame_index)
1823     strm->Printf("frame #%u: ", m_frame_index);
1824   ExecutionContext exe_ctx(shared_from_this());
1825   Target *target = exe_ctx.GetTargetPtr();
1826   strm->Printf("0x%0*" PRIx64 " ",
1827                target ? (target->GetArchitecture().GetAddressByteSize() * 2)
1828                       : 16,
1829                GetFrameCodeAddress().GetLoadAddress(target));
1830   GetSymbolContext(eSymbolContextEverything);
1831   const bool show_module = true;
1832   const bool show_inline = true;
1833   const bool show_function_arguments = true;
1834   const bool show_function_name = true;
1835   m_sc.DumpStopContext(strm, exe_ctx.GetBestExecutionContextScope(),
1836                        GetFrameCodeAddress(), show_fullpaths, show_module,
1837                        show_inline, show_function_arguments,
1838                        show_function_name);
1839 }
1840 
1841 void StackFrame::UpdateCurrentFrameFromPreviousFrame(StackFrame &prev_frame) {
1842   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1843   assert(GetStackID() ==
1844          prev_frame.GetStackID()); // TODO: remove this after some testing
1845   m_variable_list_sp = prev_frame.m_variable_list_sp;
1846   m_variable_list_value_objects.Swap(prev_frame.m_variable_list_value_objects);
1847   if (!m_disassembly.GetString().empty()) {
1848     m_disassembly.Clear();
1849     m_disassembly.PutCString(prev_frame.m_disassembly.GetString());
1850   }
1851 }
1852 
1853 void StackFrame::UpdatePreviousFrameFromCurrentFrame(StackFrame &curr_frame) {
1854   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1855   assert(GetStackID() ==
1856          curr_frame.GetStackID());     // TODO: remove this after some testing
1857   m_id.SetPC(curr_frame.m_id.GetPC()); // Update the Stack ID PC value
1858   assert(GetThread() == curr_frame.GetThread());
1859   m_frame_index = curr_frame.m_frame_index;
1860   m_concrete_frame_index = curr_frame.m_concrete_frame_index;
1861   m_reg_context_sp = curr_frame.m_reg_context_sp;
1862   m_frame_code_addr = curr_frame.m_frame_code_addr;
1863   assert(!m_sc.target_sp || !curr_frame.m_sc.target_sp ||
1864          m_sc.target_sp.get() == curr_frame.m_sc.target_sp.get());
1865   assert(!m_sc.module_sp || !curr_frame.m_sc.module_sp ||
1866          m_sc.module_sp.get() == curr_frame.m_sc.module_sp.get());
1867   assert(m_sc.comp_unit == nullptr || curr_frame.m_sc.comp_unit == nullptr ||
1868          m_sc.comp_unit == curr_frame.m_sc.comp_unit);
1869   assert(m_sc.function == nullptr || curr_frame.m_sc.function == nullptr ||
1870          m_sc.function == curr_frame.m_sc.function);
1871   m_sc = curr_frame.m_sc;
1872   m_flags.Clear(GOT_FRAME_BASE | eSymbolContextEverything);
1873   m_flags.Set(m_sc.GetResolvedMask());
1874   m_frame_base.Clear();
1875   m_frame_base_error.Clear();
1876 }
1877 
1878 bool StackFrame::HasCachedData() const {
1879   if (m_variable_list_sp)
1880     return true;
1881   if (m_variable_list_value_objects.GetSize() > 0)
1882     return true;
1883   if (!m_disassembly.GetString().empty())
1884     return true;
1885   return false;
1886 }
1887 
1888 bool StackFrame::GetStatus(Stream &strm, bool show_frame_info, bool show_source,
1889                            bool show_unique, const char *frame_marker) {
1890   if (show_frame_info) {
1891     strm.Indent();
1892     DumpUsingSettingsFormat(&strm, show_unique, frame_marker);
1893   }
1894 
1895   if (show_source) {
1896     ExecutionContext exe_ctx(shared_from_this());
1897     bool have_source = false, have_debuginfo = false;
1898     Debugger::StopDisassemblyType disasm_display =
1899         Debugger::eStopDisassemblyTypeNever;
1900     Target *target = exe_ctx.GetTargetPtr();
1901     if (target) {
1902       Debugger &debugger = target->GetDebugger();
1903       const uint32_t source_lines_before =
1904           debugger.GetStopSourceLineCount(true);
1905       const uint32_t source_lines_after =
1906           debugger.GetStopSourceLineCount(false);
1907       disasm_display = debugger.GetStopDisassemblyDisplay();
1908 
1909       GetSymbolContext(eSymbolContextCompUnit | eSymbolContextLineEntry);
1910       if (m_sc.comp_unit && m_sc.line_entry.IsValid()) {
1911         have_debuginfo = true;
1912         if (source_lines_before > 0 || source_lines_after > 0) {
1913           size_t num_lines =
1914               target->GetSourceManager().DisplaySourceLinesWithLineNumbers(
1915                   m_sc.line_entry.file, m_sc.line_entry.line,
1916                   m_sc.line_entry.column, source_lines_before,
1917                   source_lines_after, "->", &strm);
1918           if (num_lines != 0)
1919             have_source = true;
1920           // TODO: Give here a one time warning if source file is missing.
1921         }
1922       }
1923       switch (disasm_display) {
1924       case Debugger::eStopDisassemblyTypeNever:
1925         break;
1926 
1927       case Debugger::eStopDisassemblyTypeNoDebugInfo:
1928         if (have_debuginfo)
1929           break;
1930         LLVM_FALLTHROUGH;
1931 
1932       case Debugger::eStopDisassemblyTypeNoSource:
1933         if (have_source)
1934           break;
1935         LLVM_FALLTHROUGH;
1936 
1937       case Debugger::eStopDisassemblyTypeAlways:
1938         if (target) {
1939           const uint32_t disasm_lines = debugger.GetDisassemblyLineCount();
1940           if (disasm_lines > 0) {
1941             const ArchSpec &target_arch = target->GetArchitecture();
1942             AddressRange pc_range;
1943             pc_range.GetBaseAddress() = GetFrameCodeAddress();
1944             pc_range.SetByteSize(disasm_lines *
1945                                  target_arch.GetMaximumOpcodeByteSize());
1946             const char *plugin_name = nullptr;
1947             const char *flavor = nullptr;
1948             const bool mixed_source_and_assembly = false;
1949             Disassembler::Disassemble(
1950                 target->GetDebugger(), target_arch, plugin_name, flavor,
1951                 exe_ctx, pc_range, disasm_lines, mixed_source_and_assembly, 0,
1952                 Disassembler::eOptionMarkPCAddress, strm);
1953           }
1954         }
1955         break;
1956       }
1957     }
1958   }
1959   return true;
1960 }
1961 
1962 RecognizedStackFrameSP StackFrame::GetRecognizedFrame() {
1963   if (!m_recognized_frame_sp) {
1964     m_recognized_frame_sp =
1965         StackFrameRecognizerManager::RecognizeFrame(CalculateStackFrame());
1966   }
1967   return m_recognized_frame_sp;
1968 }
1969