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