Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/lldb/source/Target/StackFrame.cpp
Warning:line 565, column 11
Value stored to 'separator_idx' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

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