LLDB mainline
StackFrameList.cpp
Go to the documentation of this file.
1//===-- StackFrameList.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
12#include "lldb/Core/Debugger.h"
15#include "lldb/Symbol/Block.h"
17#include "lldb/Symbol/Symbol.h"
18#include "lldb/Target/Process.h"
24#include "lldb/Target/Target.h"
25#include "lldb/Target/Thread.h"
26#include "lldb/Target/Unwind.h"
28#include "lldb/Utility/Log.h"
29#include "llvm/ADT/ScopeExit.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/Support/ConvertUTF.h"
32
33#include <memory>
34
35//#define DEBUG_STACK_FRAMES 1
36
37using namespace lldb;
38using namespace lldb_private;
39
40// StackFrameList constructor
42 const lldb::StackFrameListSP &prev_frames_sp,
43 bool show_inline_frames,
44 lldb::frame_list_id_t provider_id)
45 : m_thread(thread), m_prev_frames_sp(prev_frames_sp), m_frames(),
49 m_show_inlined_frames(show_inline_frames), m_identifier(provider_id) {
50 if (prev_frames_sp) {
51 m_current_inlined_depth = prev_frames_sp->m_current_inlined_depth;
52 m_current_inlined_pc = prev_frames_sp->m_current_inlined_pc;
53 }
54}
55
57 // Call clear since this takes a lock and clears the stack frame list in case
58 // another thread is currently using this stack frame list
59 Clear();
60}
61
63 Thread &thread, lldb::StackFrameListSP input_frames,
64 const lldb::StackFrameListSP &prev_frames_sp, bool show_inline_frames,
65 lldb::SyntheticFrameProviderSP provider_sp, uint64_t provider_id)
66 : StackFrameList(thread, prev_frames_sp, show_inline_frames, provider_id),
67 m_input_frames(std::move(input_frames)),
68 m_provider(std::move(provider_sp)) {}
69
71 uint32_t end_idx, InterruptionControl allow_interrupt) {
72
73 // Use the provider to generate frames lazily.
74 if (m_provider) {
75 // Count how many synthetic frames already exist so we assign unique CFAs
76 // to new ones. This must not be a local initialized to zero — when
77 // FetchFramesUpTo is called incrementally (first for a small range, then
78 // for the full stack), a zero-initialized counter would hand out duplicate
79 // CFA values, creating StackID collisions for PC-less synthetic frames.
80 size_t num_synthetic_frames = 0;
81 for (const auto &f : m_frames) {
82 if (f && f->IsSynthetic())
83 num_synthetic_frames++;
84 }
85
86 // Keep fetching until we reach end_idx or the provider returns an error.
87 for (uint32_t idx = m_frames.size(); idx <= end_idx; idx++) {
88 if (allow_interrupt &&
89 m_thread.GetProcess()->GetTarget().GetDebugger().InterruptRequested())
90 return true;
91
92 // Ensure the provider sees its parent StackFrameList, not the
93 // synthetic list being constructed. In a chain A->B->C, provider C
94 // must consult B's output - using its own list would be nonsensical.
95 // This also applies when the provider runs commands or expressions:
96 // any path that fetches a StackFrameList should transparently get the
97 // parent list. As a side benefit, this avoids circular re-entrancy and
98 // deadlocks on the private state thread.
99 m_thread.PushProviderFrameList(m_input_frames);
100 auto clear_active_frames =
101 llvm::scope_exit([&]() { m_thread.PopProviderFrameList(); });
102 auto frame_or_err = m_provider->GetFrameAtIndex(idx);
103
104 if (!frame_or_err) {
105 // Provider returned error - we've reached the end.
106 LLDB_LOG_ERROR(GetLog(LLDBLog::Thread), frame_or_err.takeError(),
107 "Frame provider reached end at index {0}: {1}", idx);
109 break;
110 }
111 StackFrameSP frame_sp = *frame_or_err;
112 if (frame_sp->IsSynthetic())
113 frame_sp->GetStackID().SetCFA(num_synthetic_frames++,
114 GetThread().GetProcess().get());
115 // Set the frame list weak pointer so ExecutionContextRef can resolve
116 // the frame without calling Thread::GetStackFrameList().
117 frame_sp->m_frame_list_id = GetIdentifier();
118 m_frames.push_back(frame_sp);
119 }
120
121 return false; // Not interrupted.
122 }
123
124 // If no provider, fall back to the base implementation.
125 return StackFrameList::FetchFramesUpTo(end_idx, allow_interrupt);
126}
127
129 uint32_t cur_inlined_depth = GetCurrentInlinedDepth();
130 if (cur_inlined_depth == UINT32_MAX) {
132 }
133}
134
136 std::lock_guard<std::mutex> guard(m_inlined_depth_mutex);
138 lldb::addr_t cur_pc = m_thread.GetRegisterContext()->GetPC();
139 if (cur_pc != m_current_inlined_pc) {
144 "GetCurrentInlinedDepth: invalidating current inlined depth.\n");
145 }
147 } else {
148 return UINT32_MAX;
149 }
150}
151
154 return;
155
156 StopInfoSP stop_info_sp = m_thread.GetStopInfo();
157 if (!stop_info_sp)
158 return;
159
160 bool inlined = true;
161 auto inline_depth = stop_info_sp->GetSuggestedStackFrameIndex(inlined);
162 // We're only adjusting the inlined stack here.
163 Log *log = GetLog(LLDBLog::Step);
164 if (inline_depth) {
165 std::lock_guard<std::mutex> guard(m_inlined_depth_mutex);
166 m_current_inlined_depth = *inline_depth;
167 m_current_inlined_pc = m_thread.GetRegisterContext()->GetPC();
168
170 "ResetCurrentInlinedDepth: setting inlined "
171 "depth: %d 0x%" PRIx64 ".\n",
173 } else {
174 std::lock_guard<std::mutex> guard(m_inlined_depth_mutex);
178 log, "ResetCurrentInlinedDepth: Invalidating current inlined depth.\n");
179 }
180}
181
184 uint32_t current_inlined_depth = GetCurrentInlinedDepth();
185 if (current_inlined_depth != UINT32_MAX) {
186 if (current_inlined_depth > 0) {
187 std::lock_guard<std::mutex> guard(m_inlined_depth_mutex);
189 return true;
190 }
191 }
192 }
193 return false;
194}
195
197 std::lock_guard<std::mutex> guard(m_inlined_depth_mutex);
198 m_current_inlined_depth = new_depth;
199 if (new_depth == UINT32_MAX)
201 else
202 m_current_inlined_pc = m_thread.GetRegisterContext()->GetPC();
203}
204
206 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
207 return GetAllFramesFetched();
208}
209
210/// A sequence of calls that comprise some portion of a backtrace. Each frame
211/// is represented as a pair of a callee (Function *) and an address within the
212/// callee.
218using CallSequence = std::vector<CallDescriptor>;
219
220/// Find the unique path through the call graph from \p begin (with return PC
221/// \p return_pc) to \p end. On success this path is stored into \p path, and
222/// on failure \p path is unchanged.
223/// This function doesn't currently access StackFrameLists at all, it only looks
224/// at the frame set in the ExecutionContext it passes around.
225static void FindInterveningFrames(Function &begin, Function &end,
226 ExecutionContext &exe_ctx, Target &target,
227 addr_t return_pc, CallSequence &path,
228 ModuleList &images, Log *log) {
229 LLDB_LOG_VERBOSE(log, "Finding frames between {0} and {1}, retn-pc={2:x}",
230 begin.GetDisplayName(), end.GetDisplayName(), return_pc);
231
232 // Find a non-tail calling edge with the correct return PC.
233 if (log)
234 for (const auto &edge : begin.GetCallEdges())
236 "FindInterveningFrames: found call with retn-PC = {0:x}",
237 edge->GetReturnPCAddress(begin, target));
238 CallEdge *first_edge = begin.GetCallEdgeForReturnAddress(return_pc, target);
239 if (!first_edge) {
241 "No call edge outgoing from {0} with retn-PC == {1:x}",
242 begin.GetDisplayName(), return_pc);
243 return;
244 }
245
246 // The first callee may not be resolved, or there may be nothing to fill in.
247 Function *first_callee = first_edge->GetCallee(images, exe_ctx);
248 if (!first_callee) {
249 LLDB_LOG_VERBOSE(log, "Could not resolve callee");
250 return;
251 }
252 if (first_callee == &end) {
254 log, "Not searching further, first callee is {0} (retn-PC: {1:x})",
255 end.GetDisplayName(), return_pc);
256 return;
257 }
258
259 // Run DFS on the tail-calling edges out of the first callee to find \p end.
260 // Fully explore the set of functions reachable from the first edge via tail
261 // calls in order to detect ambiguous executions.
262 struct DFS {
263 CallSequence active_path = {};
264 CallSequence solution_path = {};
265 llvm::SmallPtrSet<Function *, 2> visited_nodes = {};
266 bool ambiguous = false;
267 Function *end;
268 ModuleList &images;
269 Target &target;
270 ExecutionContext &context;
271
272 DFS(Function *end, ModuleList &images, Target &target,
273 ExecutionContext &context)
274 : end(end), images(images), target(target), context(context) {}
275
276 void search(CallEdge &first_edge, Function &first_callee,
277 CallSequence &path) {
278 dfs(first_edge, first_callee);
279 if (!ambiguous)
280 path = std::move(solution_path);
281 }
282
283 void dfs(CallEdge &current_edge, Function &callee) {
284 // Found a path to the target function.
285 if (&callee == end) {
286 if (solution_path.empty())
287 solution_path = active_path;
288 else
289 ambiguous = true;
290 return;
291 }
292
293 // Terminate the search if tail recursion is found, or more generally if
294 // there's more than one way to reach a target. This errs on the side of
295 // caution: it conservatively stops searching when some solutions are
296 // still possible to save time in the average case.
297 if (!visited_nodes.insert(&callee).second) {
298 ambiguous = true;
299 return;
300 }
301
302 // Search the calls made from this callee.
303 active_path.push_back(CallDescriptor{&callee});
304 for (const auto &edge : callee.GetTailCallingEdges()) {
305 Function *next_callee = edge->GetCallee(images, context);
306 if (!next_callee)
307 continue;
308
309 std::tie(active_path.back().address_type, active_path.back().address) =
310 edge->GetCallerAddress(callee, target);
311
312 dfs(*edge, *next_callee);
313 if (ambiguous)
314 return;
315 }
316 active_path.pop_back();
317 }
318 };
319
320 DFS(&end, images, target, exe_ctx).search(*first_edge, *first_callee, path);
321}
322
323/// Given that \p next_frame will be appended to the frame list, synthesize
324/// tail call frames between the current end of the list and \p next_frame.
325/// If any frames are added, adjust the frame index of \p next_frame.
326///
327/// --------------
328/// | ... | <- Completed frames.
329/// --------------
330/// | prev_frame |
331/// --------------
332/// | ... | <- Artificial frames inserted here.
333/// --------------
334/// | next_frame |
335/// --------------
336/// | ... | <- Not-yet-visited frames.
337/// --------------
339 // Cannot synthesize tail call frames when the stack is empty (there is no
340 // "previous" frame).
341 if (m_frames.empty())
342 return;
343
344 TargetSP target_sp = next_frame.CalculateTarget();
345 if (!target_sp)
346 return;
347
348 lldb::RegisterContextSP next_reg_ctx_sp = next_frame.GetRegisterContext();
349 if (!next_reg_ctx_sp)
350 return;
351
352 Log *log = GetLog(LLDBLog::Step);
353
354 StackFrame &prev_frame = *m_frames.back().get();
355
356 // Find the functions prev_frame and next_frame are stopped in. The function
357 // objects are needed to search the lazy call graph for intervening frames.
358 Function *prev_func =
359 prev_frame.GetSymbolContext(eSymbolContextFunction).function;
360 if (!prev_func) {
361 LLDB_LOG(log, "SynthesizeTailCallFrames: can't find previous function");
362 return;
363 }
364 Function *next_func =
365 next_frame.GetSymbolContext(eSymbolContextFunction).function;
366 if (!next_func) {
367 LLDB_LOG(log, "SynthesizeTailCallFrames: can't find next function");
368 return;
369 }
370
371 // Try to find the unique sequence of (tail) calls which led from next_frame
372 // to prev_frame.
373 CallSequence path;
374 addr_t return_pc = next_reg_ctx_sp->GetPC();
375 Target &target = *target_sp.get();
376 ModuleList &images = next_frame.CalculateTarget()->GetImages();
377 ExecutionContext exe_ctx(target_sp, /*get_process=*/true);
378 exe_ctx.SetFramePtr(&next_frame);
379 FindInterveningFrames(*next_func, *prev_func, exe_ctx, target, return_pc,
380 path, images, log);
381
382 // Push synthetic tail call frames.
383 for (auto calleeInfo : llvm::reverse(path)) {
384 Function *callee = calleeInfo.func;
385 uint32_t frame_idx = m_frames.size();
386 uint32_t concrete_frame_idx = next_frame.GetConcreteFrameIndex();
388 bool cfa_is_valid = false;
389 addr_t pc = calleeInfo.address;
390 // If the callee address refers to the call instruction, we do not want to
391 // subtract 1 from this value.
392 const bool artificial = true;
393 const bool behaves_like_zeroth_frame =
394 calleeInfo.address_type == CallEdge::AddrType::Call;
395 SymbolContext sc;
396 callee->CalculateSymbolContext(&sc);
397 auto synth_frame = std::make_shared<StackFrame>(
398 m_thread.shared_from_this(), frame_idx, concrete_frame_idx, cfa,
399 cfa_is_valid, pc, StackFrame::Kind::Regular, artificial,
400 behaves_like_zeroth_frame, &sc);
401 synth_frame->m_frame_list_id = GetIdentifier();
402 m_frames.push_back(synth_frame);
403 LLDB_LOG(log, "Pushed frame {0} at {1:x}", callee->GetDisplayName(), pc);
404 }
405
406 // If any frames were created, adjust next_frame's index.
407 if (!path.empty())
408 next_frame.SetFrameIndex(m_frames.size());
409}
410
412 addr_t cfa) {
413 SymbolContext unwind_sc =
414 frame_sp->GetSymbolContext(eSymbolContextBlock | eSymbolContextFunction);
415 if (!unwind_sc.block)
416 return 0;
417
418 TargetSP target_sp = m_thread.CalculateTarget();
419 uint32_t concrete_frame_idx = frame_sp->GetConcreteFrameIndex();
420 Address curr_frame_address(frame_sp->GetFrameCodeAddressForSymbolication());
421
422 SymbolContext next_frame_sc;
423 Address next_frame_address;
424 uint32_t num_inlined_frames = 0;
425
426 while (unwind_sc.GetParentOfInlinedScope(curr_frame_address, next_frame_sc,
427 next_frame_address)) {
428 next_frame_sc.line_entry.ApplyFileMappings(target_sp);
429 StackFrameSP inline_frame_sp = std::make_shared<StackFrame>(
430 m_thread.shared_from_this(), m_frames.size(), concrete_frame_idx,
431 frame_sp->GetRegisterContextSP(), cfa, next_frame_address,
432 /*behaves_like_zeroth_frame=*/false, &next_frame_sc);
433
434 inline_frame_sp->m_frame_list_id = GetIdentifier();
435 m_frames.push_back(inline_frame_sp);
436 unwind_sc = next_frame_sc;
437 curr_frame_address = next_frame_address;
438 ++num_inlined_frames;
439 }
440
441 return num_inlined_frames;
442}
443
444bool StackFrameList::GetFramesUpTo(uint32_t end_idx,
445 InterruptionControl allow_interrupt) {
446 // GetFramesUpTo is always called with the intent to add frames, so get the
447 // writer lock:
448 std::unique_lock<std::shared_mutex> guard(m_list_mutex);
449 // Now that we have the lock, check to make sure someone didn't get there
450 // ahead of us:
451 if (m_frames.size() > end_idx || GetAllFramesFetched())
452 return false;
453
454 // Do not fetch frames for an invalid thread.
455 bool was_interrupted = false;
456 if (!m_thread.IsValid())
457 return false;
458
459 // lock the writer side of m_list_mutex as we're going to add frames here:
461 if (end_idx < m_concrete_frames_fetched)
462 return false;
463 // We're adding concrete frames now:
464 // FIXME: This should also be interruptible:
466 return false;
467 }
468
469 // We're adding concrete and inlined frames now:
470 was_interrupted = FetchFramesUpTo(end_idx, allow_interrupt);
471
472#if defined(DEBUG_STACK_FRAMES)
473 s.PutCString("\n\nNew frames:\n");
474 Dump(&s);
475 s.EOL();
476#endif
477 return was_interrupted;
478}
479
481 assert(m_thread.IsValid() && "Expected valid thread");
482 assert(m_frames.size() <= end_idx && "Expected there to be frames to fill");
483
484 Unwind &unwinder = m_thread.GetUnwinder();
485
486 if (end_idx < m_concrete_frames_fetched)
487 return;
488
489 uint32_t num_frames = unwinder.GetFramesUpTo(end_idx);
490 if (num_frames <= end_idx + 1) {
491 // Done unwinding.
493 }
494
495 // Don't create the frames eagerly. Defer this work to GetFrameAtIndex,
496 // which can lazily query the unwinder to create frames.
497 m_frames.resize(num_frames);
498}
499
501 InterruptionControl allow_interrupt) {
502 Unwind &unwinder = m_thread.GetUnwinder();
503 bool was_interrupted = false;
504
505#if defined(DEBUG_STACK_FRAMES)
506 StreamFile s(stdout, false);
507#endif
508 // If we are hiding some frames from the outside world, we need to add
509 // those onto the total count of frames to fetch. However, we don't need
510 // to do that if end_idx is 0 since in that case we always get the first
511 // concrete frame and all the inlined frames below it... And of course, if
512 // end_idx is UINT32_MAX that means get all, so just do that...
513
514 uint32_t inlined_depth = 0;
515 if (end_idx > 0 && end_idx != UINT32_MAX) {
516 inlined_depth = GetCurrentInlinedDepth();
517 if (inlined_depth != UINT32_MAX) {
518 if (end_idx > 0)
519 end_idx += inlined_depth;
520 }
521 }
522
523 StackFrameSP unwind_frame_sp;
524 Debugger &dbg = m_thread.GetProcess()->GetTarget().GetDebugger();
525 do {
526 uint32_t idx = m_concrete_frames_fetched++;
529 bool behaves_like_zeroth_frame = (idx == 0);
530 if (idx == 0) {
531 // We might have already created frame zero, only create it if we need
532 // to.
533 if (m_frames.empty()) {
534 RegisterContextSP reg_ctx_sp(m_thread.GetRegisterContext());
535
536 if (reg_ctx_sp) {
537 const bool success = unwinder.GetFrameInfoAtIndex(
538 idx, cfa, pc, behaves_like_zeroth_frame);
539 // There shouldn't be any way not to get the frame info for frame
540 // 0. But if the unwinder can't make one, lets make one by hand
541 // with the SP as the CFA and see if that gets any further.
542 if (!success) {
543 cfa = reg_ctx_sp->GetSP();
544 pc = reg_ctx_sp->GetPC();
545 }
546
547 unwind_frame_sp = std::make_shared<StackFrame>(
548 m_thread.shared_from_this(), m_frames.size(), idx, reg_ctx_sp,
549 cfa, pc, behaves_like_zeroth_frame, nullptr);
550 unwind_frame_sp->m_frame_list_id = GetIdentifier();
551 m_frames.push_back(unwind_frame_sp);
552 }
553 } else {
554 unwind_frame_sp = m_frames.front();
555 cfa = unwind_frame_sp->m_id.GetCallFrameAddressWithoutMetadata();
556 }
557 } else {
558 // Check for interruption when building the frames.
559 // Do the check in idx > 0 so that we'll always create a 0th frame.
560 if (allow_interrupt &&
561 INTERRUPT_REQUESTED(dbg, "Interrupted having fetched {0} frames",
562 m_frames.size())) {
563 was_interrupted = true;
564 break;
565 }
566
567 const bool success =
568 unwinder.GetFrameInfoAtIndex(idx, cfa, pc, behaves_like_zeroth_frame);
569 if (!success) {
570 // We've gotten to the end of the stack.
572 break;
573 }
574 const bool cfa_is_valid = true;
575 unwind_frame_sp = std::make_shared<StackFrame>(
576 m_thread.shared_from_this(), m_frames.size(), idx, cfa, cfa_is_valid,
577 pc, StackFrame::Kind::Regular, false, behaves_like_zeroth_frame,
578 nullptr);
579
580 // Create synthetic tail call frames between the previous frame and the
581 // newly-found frame. The new frame's index may change after this call,
582 // although its concrete index will stay the same.
583 SynthesizeTailCallFrames(*unwind_frame_sp.get());
584
585 unwind_frame_sp->m_frame_list_id = GetIdentifier();
586 m_frames.push_back(unwind_frame_sp);
587 }
588
589 assert(unwind_frame_sp);
590 SynthesizeInlineFrames(unwind_frame_sp, cfa);
591 } while (m_frames.size() - 1 < end_idx);
592
593 // Don't try to merge till you've calculated all the frames in this stack.
595 StackFrameList *prev_frames = m_prev_frames_sp.get();
596 StackFrameList *curr_frames = this;
597
598#if defined(DEBUG_STACK_FRAMES)
599 s.PutCString("\nprev_frames:\n");
600 prev_frames->Dump(&s);
601 s.PutCString("\ncurr_frames:\n");
602 curr_frames->Dump(&s);
603 s.EOL();
604#endif
605 size_t curr_frame_num, prev_frame_num;
606
607 for (curr_frame_num = curr_frames->m_frames.size(),
608 prev_frame_num = prev_frames->m_frames.size();
609 curr_frame_num > 0 && prev_frame_num > 0;
610 --curr_frame_num, --prev_frame_num) {
611 const size_t curr_frame_idx = curr_frame_num - 1;
612 const size_t prev_frame_idx = prev_frame_num - 1;
613 StackFrameSP curr_frame_sp(curr_frames->m_frames[curr_frame_idx]);
614 StackFrameSP prev_frame_sp(prev_frames->m_frames[prev_frame_idx]);
615
616#if defined(DEBUG_STACK_FRAMES)
617 s.Printf("\n\nCurr frame #%u ", curr_frame_idx);
618 if (curr_frame_sp)
619 curr_frame_sp->Dump(&s, true, false);
620 else
621 s.PutCString("NULL");
622 s.Printf("\nPrev frame #%u ", prev_frame_idx);
623 if (prev_frame_sp)
624 prev_frame_sp->Dump(&s, true, false);
625 else
626 s.PutCString("NULL");
627#endif
628
629 StackFrame *curr_frame = curr_frame_sp.get();
630 StackFrame *prev_frame = prev_frame_sp.get();
631
632 if (curr_frame == nullptr || prev_frame == nullptr)
633 break;
634
635 // Check the stack ID to make sure they are equal.
636 if (curr_frame->GetStackID() != prev_frame->GetStackID())
637 break;
638
639 prev_frame->UpdatePreviousFrameFromCurrentFrame(*curr_frame);
640 // Now copy the fixed up previous frame into the current frames so the
641 // pointer doesn't change.
642 prev_frame_sp->m_frame_list_id = GetIdentifier();
643 m_frames[curr_frame_idx] = prev_frame_sp;
644
645#if defined(DEBUG_STACK_FRAMES)
646 s.Printf("\n Copying previous frame to current frame");
647#endif
648 }
649 // We are done with the old stack frame list, we can release it now.
650 m_prev_frames_sp.reset();
651 }
652 // Don't report interrupted if we happen to have gotten all the frames:
653 if (!GetAllFramesFetched())
654 return was_interrupted;
655 return false;
656}
657
658uint32_t StackFrameList::GetNumFrames(bool can_create) {
659 if (!WereAllFramesFetched() && can_create) {
660 // Don't allow interrupt or we might not return the correct count
662 }
663 uint32_t frame_idx;
664 {
665 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
666 frame_idx = GetVisibleStackFrameIndex(m_frames.size());
667 }
668 return frame_idx;
669}
670
672 if (s == nullptr)
673 return;
674
675 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
676
677 const_iterator pos, begin = m_frames.begin(), end = m_frames.end();
678 for (pos = begin; pos != end; ++pos) {
679 StackFrame *frame = (*pos).get();
680 s->Printf("%p: ", static_cast<void *>(frame));
681 if (frame) {
682 frame->GetStackID().Dump(s);
683 frame->DumpUsingSettingsFormat(s);
684 } else
685 s->Printf("frame #%u", (uint32_t)std::distance(begin, pos));
686 s->EOL();
687 }
688 s->EOL();
689}
690
692 StackFrameSP frame_sp;
693 uint32_t original_idx = idx;
694
695 // We're going to consult the m_frames.size, but if there are already
696 // enough frames for our request we don't want to block other readers, so
697 // first acquire the shared lock:
698 { // Scope for shared lock:
699 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
700
701 uint32_t inlined_depth = GetCurrentInlinedDepth();
702 if (inlined_depth != UINT32_MAX)
703 idx += inlined_depth;
704
705 if (idx < m_frames.size())
706 frame_sp = m_frames[idx];
707
708 if (frame_sp)
709 return frame_sp;
710 } // End of reader lock scope
711
712 // GetFramesUpTo will fill m_frames with as many frames as you asked for, if
713 // there are that many. If there weren't then you asked for too many frames.
714 // GetFramesUpTo returns true if interrupted:
716 Log *log = GetLog(LLDBLog::Thread);
717 LLDB_LOG(log, "GetFrameAtIndex was interrupted");
718 return {};
719 }
720
721 { // Now we're accessing m_frames as a reader, so acquire the reader lock.
722 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
723 if (idx < m_frames.size()) {
724 frame_sp = m_frames[idx];
725 } else if (original_idx == 0) {
726 // There should ALWAYS be a frame at index 0. If something went wrong
727 // with the CurrentInlinedDepth such that there weren't as many frames as
728 // we thought taking that into account, then reset the current inlined
729 // depth and return the real zeroth frame.
730 if (m_frames.empty()) {
731 // Why do we have a thread with zero frames, that should not ever
732 // happen...
733 assert(!m_thread.IsValid() && "A valid thread has no frames.");
734 } else {
736 frame_sp = m_frames[original_idx];
737 }
738 }
739 } // End of reader lock scope
740
741 return frame_sp;
742}
743
746 // First try assuming the unwind index is the same as the frame index. The
747 // unwind index is always greater than or equal to the frame index, so it is
748 // a good place to start. If we have inlined frames we might have 5 concrete
749 // frames (frame unwind indexes go from 0-4), but we might have 15 frames
750 // after we make all the inlined frames. Most of the time the unwind frame
751 // index (or the concrete frame index) is the same as the frame index.
752 uint32_t frame_idx = unwind_idx;
753 StackFrameSP frame_sp(GetFrameAtIndex(frame_idx));
754 while (frame_sp) {
755 if (frame_sp->GetFrameIndex() == unwind_idx)
756 break;
757 frame_sp = GetFrameAtIndex(++frame_idx);
758 }
759 return frame_sp;
760}
761
762static bool CompareStackID(const StackFrameSP &stack_sp,
763 const StackID &stack_id) {
764 return stack_sp->GetStackID() < stack_id;
765}
766
768 StackFrameSP frame_sp;
769
770 if (stack_id.IsValid()) {
771 uint32_t frame_idx = 0;
772 {
773 // First see if the frame is already realized. This is the scope for
774 // the shared mutex:
775 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
776 // Do a binary search in case the stack frame is already in our cache
777 collection::const_iterator pos =
778 llvm::lower_bound(m_frames, stack_id, CompareStackID);
779 if (pos != m_frames.end() && (*pos)->GetStackID() == stack_id)
780 return *pos;
781 }
782 // If we needed to add more frames, we would get to here.
783 do {
784 frame_sp = GetFrameAtIndex(frame_idx);
785 if (frame_sp && frame_sp->GetStackID() == stack_id)
786 break;
787 frame_idx++;
788 } while (frame_sp);
789 }
790 return frame_sp;
791}
792
793bool StackFrameList::SetFrameAtIndex(uint32_t idx, StackFrameSP &frame_sp) {
794 std::unique_lock<std::shared_mutex> guard(m_list_mutex);
795 if (idx >= m_frames.size())
796 m_frames.resize(idx + 1);
797 // Make sure allocation succeeded by checking bounds again
798 if (idx < m_frames.size()) {
799 m_frames[idx] = frame_sp;
800 return true;
801 }
802 return false; // resize failed, out of memory?
803}
804
806 // Don't call into the frame recognizers on the private state thread as
807 // they can cause code to run in the target, and that can cause deadlocks
808 // when fetching stop events for the expression.
809 if (m_thread.GetProcess()->CurrentThreadPosesAsPrivateStateThread())
810 return;
811
812 Log *log = GetLog(LLDBLog::Thread);
813
814 // Only the top frame should be recognized.
815 StackFrameSP frame_sp = GetFrameAtIndex(0);
816 if (!frame_sp) {
817 LLDB_LOG(log, "Failed to construct Frame #0");
818 return;
819 }
820
821 RecognizedStackFrameSP recognized_frame_sp = frame_sp->GetRecognizedFrame();
822
823 if (recognized_frame_sp) {
824 if (StackFrameSP most_relevant_frame_sp =
825 recognized_frame_sp->GetMostRelevantFrame()) {
826 LLDB_LOG(log, "Found most relevant frame at index {0}",
827 most_relevant_frame_sp->GetFrameIndex());
828 SetSelectedFrame(most_relevant_frame_sp.get());
829 return;
830 }
831 }
832 LLDB_LOG(log, "Frame #0 not recognized");
833
834 // If this thread has a non-trivial StopInfo, then let it suggest
835 // a most relevant frame:
836 StopInfoSP stop_info_sp = m_thread.GetStopInfo();
837 uint32_t stack_idx = 0;
838 bool found_relevant = false;
839 if (stop_info_sp) {
840 // Here we're only asking the stop info if it wants to adjust the real stack
841 // index. We have to ask about the m_inlined_stack_depth in
842 // Thread::ShouldStop since the plans need to reason with that info.
843 bool inlined = false;
844 std::optional<uint32_t> stack_opt =
845 stop_info_sp->GetSuggestedStackFrameIndex(inlined);
846 if (stack_opt) {
847 stack_idx = *stack_opt;
848 found_relevant = true;
849 }
850 }
851
852 frame_sp = GetFrameAtIndex(stack_idx);
853 if (!frame_sp)
854 LLDB_LOG(log, "Stop info suggested relevant frame {0} but it didn't exist",
855 stack_idx);
856 else if (found_relevant)
857 LLDB_LOG(log, "Setting selected frame from stop info to {0}", stack_idx);
858 // Note, we don't have to worry about "inlined" frames here, because we've
859 // already calculated the inlined frame in Thread::ShouldStop, and
860 // SetSelectedFrame will take care of that adjustment for us.
861 SetSelectedFrame(frame_sp.get());
862
863 if (!found_relevant)
864 LLDB_LOG(log, "No relevant frame!");
865}
866
867uint32_t
869 std::lock_guard<std::recursive_mutex> guard(m_selected_frame_mutex);
870
871 if (!m_selected_frame_idx && select_most_relevant)
874 // If we aren't selecting the most relevant frame, and the selected frame
875 // isn't set, then don't force a selection here, just return 0.
876 if (!select_most_relevant)
877 return 0;
878 // If the inlined stack frame is set, then use that:
880 }
881 return *m_selected_frame_idx;
882}
883
885 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
886 std::lock_guard<std::recursive_mutex> selected_frame_guard(
888
889 const_iterator pos;
890 const_iterator begin = m_frames.begin();
891 const_iterator end = m_frames.end();
893
894 for (pos = begin; pos != end; ++pos) {
895 if (pos->get() == frame) {
896 m_selected_frame_idx = std::distance(begin, pos);
897 uint32_t inlined_depth = GetCurrentInlinedDepth();
898 if (inlined_depth != UINT32_MAX)
900 break;
901 }
902 }
904 return *m_selected_frame_idx;
905}
906
908 StackFrameSP frame_sp(GetFrameAtIndex(idx));
909 if (frame_sp) {
910 SetSelectedFrame(frame_sp.get());
911 return true;
912 } else
913 return false;
914}
915
917 if (m_thread.GetID() ==
918 m_thread.GetProcess()->GetThreadList().GetSelectedThread()->GetID()) {
919 StackFrameSP frame_sp(
921 if (frame_sp) {
922 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextLineEntry);
923 if (sc.line_entry.GetFile())
924 m_thread.CalculateTarget()->GetSourceManager().SetDefaultFileAndLine(
926 }
927 }
928}
929
930// The thread has been run, reset the number stack frames to zero so we can
931// determine how many frames we have lazily.
932// Note, we don't actually re-use StackFrameLists, we always make a new
933// StackFrameList every time we stop, and then copy frame information frame
934// by frame from the old to the new StackFrameList. So the comment above,
935// does not describe how StackFrameLists are currently used.
936// Clear is currently only used to clear the list in the destructor.
938 std::unique_lock<std::shared_mutex> guard(m_list_mutex);
939 m_frames.clear();
941 std::lock_guard<std::recursive_mutex> selected_frame_guard(
943 m_selected_frame_idx.reset();
944}
945
948 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
949 const_iterator pos;
950 const_iterator begin = m_frames.begin();
951 const_iterator end = m_frames.end();
952 lldb::StackFrameSP ret_sp;
953
954 for (pos = begin; pos != end; ++pos) {
955 if (pos->get() == stack_frame_ptr) {
956 ret_sp = (*pos);
957 break;
958 }
959 }
960 return ret_sp;
961}
962
964 uint32_t frame_idx = frame.GetFrameIndex();
965 StackFrameSP frame_sp = GetFrameAtIndex(frame_idx + 1);
966 if (!frame_sp)
967 return false;
968 return frame_sp->IsHidden();
969}
970
972 uint32_t frame_idx = frame.GetFrameIndex();
973 if (frame_idx == 0)
974 return false;
975 StackFrameSP frame_sp = GetFrameAtIndex(frame_idx - 1);
976 if (!frame_sp)
977 return false;
978 return frame_sp->IsHidden();
979}
980
982 lldb::StackFrameSP selected_frame_sp,
983 bool show_hidden_marker) {
984 bool show_unicode_marker = Terminal::SupportsUnicode() && show_hidden_marker;
985 if (frame_sp == selected_frame_sp)
986 return show_unicode_marker ? " * " : "* ";
987 if (!show_unicode_marker)
988 return " ";
989 if (IsPreviousFrameHidden(*frame_sp))
990 return reinterpret_cast<const char *>(u8"﹉ ");
991 if (IsNextFrameHidden(*frame_sp))
992 return reinterpret_cast<const char *>(u8"﹍ ");
993 return " ";
994}
995
996size_t StackFrameList::GetStatus(Stream &strm, uint32_t first_frame,
997 uint32_t num_frames, bool show_frame_info,
998 uint32_t num_frames_with_source,
999 bool show_unique, bool show_hidden,
1000 bool show_hidden_marker,
1001 bool show_selected_frame) {
1002 size_t num_frames_displayed = 0;
1003
1004 if (num_frames == 0)
1005 return 0;
1006
1007 StackFrameSP frame_sp;
1008 uint32_t frame_idx = 0;
1009 uint32_t last_frame;
1010
1011 // Don't let the last frame wrap around...
1012 if (num_frames == UINT32_MAX)
1013 last_frame = UINT32_MAX;
1014 else
1015 last_frame = first_frame + num_frames;
1016
1017 StackFrameSP selected_frame_sp =
1018 m_thread.GetSelectedFrame(DoNoSelectMostRelevantFrame);
1019 std::string buffer;
1020 std::string marker;
1021 for (frame_idx = first_frame; frame_idx < last_frame; ++frame_idx) {
1022 frame_sp = GetFrameAtIndex(frame_idx);
1023 if (!frame_sp)
1024 break;
1025
1026 if (show_selected_frame)
1027 marker = GetFrameMarker(frame_sp, selected_frame_sp, show_hidden_marker);
1028 else
1029 marker = GetFrameMarker(frame_sp, /*selected_frame_sp=*/nullptr,
1030 show_hidden_marker);
1031
1032 // Hide uninteresting frames unless it's the selected frame.
1033 if (!show_hidden && frame_sp != selected_frame_sp && frame_sp->IsHidden())
1034 continue;
1035
1036 // Check for interruption here. If we're fetching arguments, this loop
1037 // can go slowly:
1038 Debugger &dbg = m_thread.GetProcess()->GetTarget().GetDebugger();
1040 dbg, "Interrupted dumping stack for thread {0:x} with {1} shown.",
1041 m_thread.GetID(), num_frames_displayed))
1042 break;
1043
1044 if (!frame_sp->GetStatus(strm, show_frame_info,
1045 num_frames_with_source > (first_frame - frame_idx),
1046 show_unique, marker))
1047 break;
1048 ++num_frames_displayed;
1049 }
1050
1051 strm.IndentLess();
1052 return num_frames_displayed;
1053}
1054
#define INTERRUPT_REQUESTED(debugger,...)
This handy define will keep you from having to generate a report for the interruption by hand.
Definition Debugger.h:494
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:364
#define LLDB_LOGF_VERBOSE(log,...)
Definition Log.h:385
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:394
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:371
static void FindInterveningFrames(Function &begin, Function &end, ExecutionContext &exe_ctx, Target &target, addr_t return_pc, CallSequence &path, ModuleList &images, Log *log)
Find the unique path through the call graph from begin (with return PC return_pc) to end.
static bool CompareStackID(const StackFrameSP &stack_sp, const StackID &stack_id)
std::vector< CallDescriptor > CallSequence
A section + offset based address class.
Definition Address.h:62
Represent a call made within a Function.
Definition Function.h:268
virtual Function * GetCallee(ModuleList &images, ExecutionContext &exe_ctx)=0
Get the callee's definition.
A class to manage flag bits.
Definition Debugger.h:100
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
void SetFramePtr(StackFrame *frame)
Set accessor to set only the frame shared pointer from a frame pointer.
A class that describes a function.
Definition Function.h:400
CallEdge * GetCallEdgeForReturnAddress(lldb::addr_t return_pc, Target &target)
Get the outgoing call edge from this function which has the given return address return_pc,...
Definition Function.cpp:368
llvm::ArrayRef< std::unique_ptr< CallEdge > > GetCallEdges()
Get the outgoing call edges from this function, sorted by their return PC addresses (in increasing or...
Definition Function.cpp:331
void CalculateSymbolContext(SymbolContext *sc) override
Reconstruct the object's symbol context into sc.
Definition Function.cpp:451
llvm::ArrayRef< std::unique_ptr< CallEdge > > GetTailCallingEdges()
Get the outgoing tail-calling edges from this function.
Definition Function.cpp:361
ConstString GetDisplayName() const
Definition Function.cpp:533
A collection class for Module objects.
Definition ModuleList.h:125
lldb::frame_list_id_t m_identifier
Unique identifier for this frame list instance.
lldb::frame_list_id_t GetIdentifier() const
Get the unique identifier for this frame list.
StackFrameList(Thread &thread, const lldb::StackFrameListSP &prev_frames_sp, bool show_inline_frames, lldb::frame_list_id_t provider_id=0)
lldb::addr_t m_current_inlined_pc
The program counter value at the currently selected synthetic activation.
collection m_frames
A cache of frames.
lldb::StackFrameSP GetFrameWithStackID(const StackID &stack_id)
Retrieve the stack frame with the given ID stack_id.
lldb::StackFrameSP GetFrameWithConcreteFrameIndex(uint32_t unwind_idx)
Get the first concrete frame with index greater than or equal to idx.
bool GetFramesUpTo(uint32_t end_idx, InterruptionControl allow_interrupt)
Ensures that frames up to (and including) end_idx are realized in the StackFrameList.
void ClearSelectedFrameIndex()
Resets the selected frame index of this object.
uint32_t SynthesizeInlineFrames(lldb::StackFrameSP frame_sp, lldb::addr_t cfa)
Synthesize inline frames for frame_sp by walking the inlined scope chain via GetParentOfInlinedScope ...
std::recursive_mutex m_selected_frame_mutex
Protect access to m_selected_frame_idx.
void Clear()
Clear the cache of frames.
lldb::StackFrameSP GetFrameAtIndex(uint32_t idx)
Get the frame at index idx. Invisible frames cannot be indexed.
std::optional< uint32_t > m_selected_frame_idx
The currently selected frame.
lldb::StackFrameListSP m_prev_frames_sp
The old stack frame list.
uint32_t m_concrete_frames_fetched
The number of concrete frames fetched while filling the frame list.
void FetchOnlyConcreteFramesUpTo(uint32_t end_idx)
Thread & m_thread
The thread this frame list describes.
void SelectMostRelevantFrame()
Calls into the stack frame recognizers and stop info to set the most relevant frame.
const bool m_show_inlined_frames
Whether or not to show synthetic (inline) frames. Immutable.
bool SetFrameAtIndex(uint32_t idx, lldb::StackFrameSP &frame_sp)
Use this API to build a stack frame list (used for scripted threads, for instance....
uint32_t m_current_inlined_depth
The number of synthetic function activations (invisible frames) expanded from the concrete frame #0 a...
void SetDefaultFileAndLineToSelectedFrame()
If the currently selected frame comes from the currently selected thread, point the default file and ...
uint32_t GetVisibleStackFrameIndex(uint32_t idx)
If the current inline depth (i.e the number of invisible frames) is valid, subtract it from idx.
bool IsNextFrameHidden(lldb_private::StackFrame &frame)
Returns true if the next frame is hidden.
uint32_t GetNumFrames(bool can_create=true)
Get the number of visible frames.
virtual bool FetchFramesUpTo(uint32_t end_idx, InterruptionControl allow_interrupt)
Returns true if fetching frames was interrupted, false otherwise.
collection::const_iterator const_iterator
void SynthesizeTailCallFrames(StackFrame &next_frame)
Given that next_frame will be appended to the frame list, synthesize tail call frames between the cur...
std::string GetFrameMarker(lldb::StackFrameSP frame_sp, lldb::StackFrameSP selected_frame_sp, bool show_hidden_marker)
Returns the stack frame marker depending on if frame_sp:
void SetCurrentInlinedDepth(uint32_t new_depth)
Thread & GetThread() const
Get the thread associated with this frame list.
uint32_t GetSelectedFrameIndex(SelectMostRelevant select_most_relevant_frame)
Get the currently selected frame index.
std::shared_mutex m_list_mutex
A mutex for this frame list.
uint32_t SetSelectedFrame(lldb_private::StackFrame *frame)
Mark a stack frame as the currently selected frame and return its index.
size_t GetStatus(Stream &strm, uint32_t first_frame, uint32_t num_frames, bool show_frame_info, uint32_t num_frames_with_source, bool show_unique=false, bool show_hidden=false, bool show_hidden_marker=true, bool show_selected_frame=false)
void CalculateCurrentInlinedDepth()
Calculate and set the current inline depth.
lldb::StackFrameSP GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr)
If stack_frame_ptr is contained in this StackFrameList, return its wrapping shared pointer.
bool WereAllFramesFetched() const
Returns whether we have currently fetched all the frames of a stack.
bool IsPreviousFrameHidden(lldb_private::StackFrame &frame)
Returns true if the previous frame is hidden.
bool SetSelectedFrameByIndex(uint32_t idx)
Mark a stack frame as the currently selected frame using the frame index idx.
This base class provides an interface to stack frames.
Definition StackFrame.h:44
void UpdatePreviousFrameFromCurrentFrame(StackFrame &curr_frame)
void SetFrameIndex(uint32_t index)
Set this frame's frame index.
Definition StackFrame.h:478
virtual uint32_t GetConcreteFrameIndex()
Query this frame to find what frame it is in this Thread's StackFrameList, not counting inlined frame...
Definition StackFrame.h:488
virtual lldb::RegisterContextSP GetRegisterContext()
Get the RegisterContext for this frame, if possible.
@ Regular
A regular stack frame with access to registers and local variables.
Definition StackFrame.h:66
virtual StackID & GetStackID()
virtual const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
virtual uint32_t GetFrameIndex() const
Query this frame to find what frame it is in this Thread's StackFrameList.
virtual void DumpUsingSettingsFormat(Stream *strm, bool show_unique=false, const llvm::StringRef frame_marker="")
Print a description for this frame using the frame-format formatter settings.
lldb::TargetSP CalculateTarget() override
void Dump(Stream *s)
Definition StackID.cpp:37
bool IsValid() const
Definition StackID.h:47
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:132
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:153
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:202
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
bool GetParentOfInlinedScope(const Address &curr_frame_pc, SymbolContext &next_frame_sc, Address &inlined_frame_addr) const
Find the block containing the inlined block that contains this block.
Block * block
The Block for a given query.
LineEntry line_entry
The LineEntry for a given query.
lldb::SyntheticFrameProviderSP m_provider
The provider that transforms the input frames.
bool FetchFramesUpTo(uint32_t end_idx, InterruptionControl allow_interrupt) override
Override FetchFramesUpTo to lazily return frames from the provider or from the actual stack frame lis...
lldb::StackFrameListSP m_input_frames
The input stack frame list that the provider transforms.
SyntheticStackFrameList(Thread &thread, lldb::StackFrameListSP input_frames, const lldb::StackFrameListSP &prev_frames_sp, bool show_inline_frames, lldb::SyntheticFrameProviderSP provider_sp, uint64_t provider_id)
static bool SupportsUnicode()
Returns whether or not the current terminal supports Unicode rendering.
Definition Terminal.cpp:407
bool GetFrameInfoAtIndex(uint32_t frame_idx, lldb::addr_t &cfa, lldb::addr_t &pc, bool &behaves_like_zeroth_frame)
Definition Unwind.h:50
uint32_t GetFramesUpTo(uint32_t end_idx)
Definition Unwind.h:36
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
@ DoNoSelectMostRelevantFrame
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:327
std::shared_ptr< lldb_private::SyntheticFrameProvider > SyntheticFrameProviderSP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::RecognizedStackFrame > RecognizedStackFrameSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
std::shared_ptr< lldb_private::StackFrameList > StackFrameListSP
uint32_t frame_list_id_t
Definition lldb-types.h:86
A sequence of calls that comprise some portion of a backtrace.
CallEdge::AddrType address_type
uint32_t line
The source line number, or LLDB_INVALID_LINE_NUMBER if there is no line number information.
Definition LineEntry.h:151
const FileSpec & GetFile() const
Helper to access the file.
Definition LineEntry.h:134
SupportFileNSP file_sp
The source file, possibly mapped by the target.source-map setting.
Definition LineEntry.h:144
void ApplyFileMappings(lldb::TargetSP target_sp)
Apply file mappings from target.source-map to the LineEntry's file.