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