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