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/SmallPtrSet.h"
30
31#include <memory>
32
33//#define DEBUG_STACK_FRAMES 1
34
35using namespace lldb;
36using namespace lldb_private;
37
38// StackFrameList constructor
40 const lldb::StackFrameListSP &prev_frames_sp,
41 bool show_inline_frames)
42 : m_thread(thread), m_prev_frames_sp(prev_frames_sp), m_frames(),
46 m_show_inlined_frames(show_inline_frames) {
47 if (prev_frames_sp) {
48 m_current_inlined_depth = prev_frames_sp->m_current_inlined_depth;
49 m_current_inlined_pc = prev_frames_sp->m_current_inlined_pc;
50 }
51}
52
54 // Call clear since this takes a lock and clears the stack frame list in case
55 // another thread is currently using this stack frame list
56 Clear();
57}
58
60 Thread &thread, lldb::StackFrameListSP input_frames,
61 const lldb::StackFrameListSP &prev_frames_sp, bool show_inline_frames,
63 : StackFrameList(thread, prev_frames_sp, show_inline_frames),
64 m_input_frames(std::move(input_frames)),
65 m_provider(std::move(provider_sp)) {}
66
68 uint32_t end_idx, InterruptionControl allow_interrupt) {
69
70 size_t num_synthetic_frames = 0;
71 // Use the provider to generate frames lazily.
72 if (m_provider) {
73 // Keep fetching until we reach end_idx or the provider returns an error.
74 for (uint32_t idx = m_frames.size(); idx <= end_idx; idx++) {
75 if (allow_interrupt &&
76 m_thread.GetProcess()->GetTarget().GetDebugger().InterruptRequested())
77 return true;
78 auto frame_or_err = m_provider->GetFrameAtIndex(idx);
79 if (!frame_or_err) {
80 // Provider returned error - we've reached the end.
81 LLDB_LOG_ERROR(GetLog(LLDBLog::Thread), frame_or_err.takeError(),
82 "Frame provider reached end at index {0}: {1}", idx);
84 break;
85 }
86 StackFrameSP frame_sp = *frame_or_err;
87 if (frame_sp->IsSynthetic())
88 frame_sp->GetStackID().SetCFA(num_synthetic_frames++,
89 GetThread().GetProcess().get());
90 // Set the frame list weak pointer so ExecutionContextRef can resolve
91 // the frame without calling Thread::GetStackFrameList().
92 frame_sp->m_frame_list_wp = shared_from_this();
93 m_frames.push_back(frame_sp);
94 }
95
96 return false; // Not interrupted.
97 }
98
99 // If no provider, fall back to the base implementation.
100 return StackFrameList::FetchFramesUpTo(end_idx, allow_interrupt);
101}
102
104 uint32_t cur_inlined_depth = GetCurrentInlinedDepth();
105 if (cur_inlined_depth == UINT32_MAX) {
107 }
108}
109
111 std::lock_guard<std::mutex> guard(m_inlined_depth_mutex);
113 lldb::addr_t cur_pc = m_thread.GetRegisterContext()->GetPC();
114 if (cur_pc != m_current_inlined_pc) {
117 Log *log = GetLog(LLDBLog::Step);
118 if (log && log->GetVerbose())
119 LLDB_LOGF(
120 log,
121 "GetCurrentInlinedDepth: invalidating current inlined depth.\n");
122 }
124 } else {
125 return UINT32_MAX;
126 }
127}
128
131 return;
132
133 StopInfoSP stop_info_sp = m_thread.GetStopInfo();
134 if (!stop_info_sp)
135 return;
136
137 bool inlined = true;
138 auto inline_depth = stop_info_sp->GetSuggestedStackFrameIndex(inlined);
139 // We're only adjusting the inlined stack here.
140 Log *log = GetLog(LLDBLog::Step);
141 if (inline_depth) {
142 std::lock_guard<std::mutex> guard(m_inlined_depth_mutex);
143 m_current_inlined_depth = *inline_depth;
144 m_current_inlined_pc = m_thread.GetRegisterContext()->GetPC();
145
146 if (log && log->GetVerbose())
147 LLDB_LOGF(log,
148 "ResetCurrentInlinedDepth: setting inlined "
149 "depth: %d 0x%" PRIx64 ".\n",
151 } else {
152 std::lock_guard<std::mutex> guard(m_inlined_depth_mutex);
155 if (log && log->GetVerbose())
156 LLDB_LOGF(
157 log,
158 "ResetCurrentInlinedDepth: Invalidating current inlined depth.\n");
159 }
160}
161
164 uint32_t current_inlined_depth = GetCurrentInlinedDepth();
165 if (current_inlined_depth != UINT32_MAX) {
166 if (current_inlined_depth > 0) {
167 std::lock_guard<std::mutex> guard(m_inlined_depth_mutex);
169 return true;
170 }
171 }
172 }
173 return false;
174}
175
177 std::lock_guard<std::mutex> guard(m_inlined_depth_mutex);
178 m_current_inlined_depth = new_depth;
179 if (new_depth == UINT32_MAX)
181 else
182 m_current_inlined_pc = m_thread.GetRegisterContext()->GetPC();
183}
184
186 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
187 return GetAllFramesFetched();
188}
189
190/// A sequence of calls that comprise some portion of a backtrace. Each frame
191/// is represented as a pair of a callee (Function *) and an address within the
192/// callee.
198using CallSequence = std::vector<CallDescriptor>;
199
200/// Find the unique path through the call graph from \p begin (with return PC
201/// \p return_pc) to \p end. On success this path is stored into \p path, and
202/// on failure \p path is unchanged.
203/// This function doesn't currently access StackFrameLists at all, it only looks
204/// at the frame set in the ExecutionContext it passes around.
205static void FindInterveningFrames(Function &begin, Function &end,
206 ExecutionContext &exe_ctx, Target &target,
207 addr_t return_pc, CallSequence &path,
208 ModuleList &images, Log *log) {
209 LLDB_LOG(log, "Finding frames between {0} and {1}, retn-pc={2:x}",
210 begin.GetDisplayName(), end.GetDisplayName(), return_pc);
211
212 // Find a non-tail calling edge with the correct return PC.
213 if (log)
214 for (const auto &edge : begin.GetCallEdges())
215 LLDB_LOG(log, "FindInterveningFrames: found call with retn-PC = {0:x}",
216 edge->GetReturnPCAddress(begin, target));
217 CallEdge *first_edge = begin.GetCallEdgeForReturnAddress(return_pc, target);
218 if (!first_edge) {
219 LLDB_LOG(log, "No call edge outgoing from {0} with retn-PC == {1:x}",
220 begin.GetDisplayName(), return_pc);
221 return;
222 }
223
224 // The first callee may not be resolved, or there may be nothing to fill in.
225 Function *first_callee = first_edge->GetCallee(images, exe_ctx);
226 if (!first_callee) {
227 LLDB_LOG(log, "Could not resolve callee");
228 return;
229 }
230 if (first_callee == &end) {
231 LLDB_LOG(log, "Not searching further, first callee is {0} (retn-PC: {1:x})",
232 end.GetDisplayName(), return_pc);
233 return;
234 }
235
236 // Run DFS on the tail-calling edges out of the first callee to find \p end.
237 // Fully explore the set of functions reachable from the first edge via tail
238 // calls in order to detect ambiguous executions.
239 struct DFS {
240 CallSequence active_path = {};
241 CallSequence solution_path = {};
242 llvm::SmallPtrSet<Function *, 2> visited_nodes = {};
243 bool ambiguous = false;
244 Function *end;
245 ModuleList &images;
246 Target &target;
247 ExecutionContext &context;
248
249 DFS(Function *end, ModuleList &images, Target &target,
250 ExecutionContext &context)
251 : end(end), images(images), target(target), context(context) {}
252
253 void search(CallEdge &first_edge, Function &first_callee,
254 CallSequence &path) {
255 dfs(first_edge, first_callee);
256 if (!ambiguous)
257 path = std::move(solution_path);
258 }
259
260 void dfs(CallEdge &current_edge, Function &callee) {
261 // Found a path to the target function.
262 if (&callee == end) {
263 if (solution_path.empty())
264 solution_path = active_path;
265 else
266 ambiguous = true;
267 return;
268 }
269
270 // Terminate the search if tail recursion is found, or more generally if
271 // there's more than one way to reach a target. This errs on the side of
272 // caution: it conservatively stops searching when some solutions are
273 // still possible to save time in the average case.
274 if (!visited_nodes.insert(&callee).second) {
275 ambiguous = true;
276 return;
277 }
278
279 // Search the calls made from this callee.
280 active_path.push_back(CallDescriptor{&callee});
281 for (const auto &edge : callee.GetTailCallingEdges()) {
282 Function *next_callee = edge->GetCallee(images, context);
283 if (!next_callee)
284 continue;
285
286 std::tie(active_path.back().address_type, active_path.back().address) =
287 edge->GetCallerAddress(callee, target);
288
289 dfs(*edge, *next_callee);
290 if (ambiguous)
291 return;
292 }
293 active_path.pop_back();
294 }
295 };
296
297 DFS(&end, images, target, exe_ctx).search(*first_edge, *first_callee, path);
298}
299
300/// Given that \p next_frame will be appended to the frame list, synthesize
301/// tail call frames between the current end of the list and \p next_frame.
302/// If any frames are added, adjust the frame index of \p next_frame.
303///
304/// --------------
305/// | ... | <- Completed frames.
306/// --------------
307/// | prev_frame |
308/// --------------
309/// | ... | <- Artificial frames inserted here.
310/// --------------
311/// | next_frame |
312/// --------------
313/// | ... | <- Not-yet-visited frames.
314/// --------------
316 // Cannot synthesize tail call frames when the stack is empty (there is no
317 // "previous" frame).
318 if (m_frames.empty())
319 return;
320
321 TargetSP target_sp = next_frame.CalculateTarget();
322 if (!target_sp)
323 return;
324
325 lldb::RegisterContextSP next_reg_ctx_sp = next_frame.GetRegisterContext();
326 if (!next_reg_ctx_sp)
327 return;
328
329 Log *log = GetLog(LLDBLog::Step);
330
331 StackFrame &prev_frame = *m_frames.back().get();
332
333 // Find the functions prev_frame and next_frame are stopped in. The function
334 // objects are needed to search the lazy call graph for intervening frames.
335 Function *prev_func =
336 prev_frame.GetSymbolContext(eSymbolContextFunction).function;
337 if (!prev_func) {
338 LLDB_LOG(log, "SynthesizeTailCallFrames: can't find previous function");
339 return;
340 }
341 Function *next_func =
342 next_frame.GetSymbolContext(eSymbolContextFunction).function;
343 if (!next_func) {
344 LLDB_LOG(log, "SynthesizeTailCallFrames: can't find next function");
345 return;
346 }
347
348 // Try to find the unique sequence of (tail) calls which led from next_frame
349 // to prev_frame.
350 CallSequence path;
351 addr_t return_pc = next_reg_ctx_sp->GetPC();
352 Target &target = *target_sp.get();
353 ModuleList &images = next_frame.CalculateTarget()->GetImages();
354 ExecutionContext exe_ctx(target_sp, /*get_process=*/true);
355 exe_ctx.SetFramePtr(&next_frame);
356 FindInterveningFrames(*next_func, *prev_func, exe_ctx, target, return_pc,
357 path, images, log);
358
359 // Push synthetic tail call frames.
360 for (auto calleeInfo : llvm::reverse(path)) {
361 Function *callee = calleeInfo.func;
362 uint32_t frame_idx = m_frames.size();
363 uint32_t concrete_frame_idx = next_frame.GetConcreteFrameIndex();
365 bool cfa_is_valid = false;
366 addr_t pc = calleeInfo.address;
367 // If the callee address refers to the call instruction, we do not want to
368 // subtract 1 from this value.
369 const bool artificial = true;
370 const bool behaves_like_zeroth_frame =
371 calleeInfo.address_type == CallEdge::AddrType::Call;
372 SymbolContext sc;
373 callee->CalculateSymbolContext(&sc);
374 auto synth_frame = std::make_shared<StackFrame>(
375 m_thread.shared_from_this(), frame_idx, concrete_frame_idx, cfa,
376 cfa_is_valid, pc, StackFrame::Kind::Regular, artificial,
377 behaves_like_zeroth_frame, &sc);
378 synth_frame->m_frame_list_wp = shared_from_this();
379 m_frames.push_back(synth_frame);
380 LLDB_LOG(log, "Pushed frame {0} at {1:x}", callee->GetDisplayName(), pc);
381 }
382
383 // If any frames were created, adjust next_frame's index.
384 if (!path.empty())
385 next_frame.SetFrameIndex(m_frames.size());
386}
387
388bool StackFrameList::GetFramesUpTo(uint32_t end_idx,
389 InterruptionControl allow_interrupt) {
390 // GetFramesUpTo is always called with the intent to add frames, so get the
391 // writer lock:
392 std::unique_lock<std::shared_mutex> guard(m_list_mutex);
393 // Now that we have the lock, check to make sure someone didn't get there
394 // ahead of us:
395 if (m_frames.size() > end_idx || GetAllFramesFetched())
396 return false;
397
398 // Do not fetch frames for an invalid thread.
399 bool was_interrupted = false;
400 if (!m_thread.IsValid())
401 return false;
402
403 // lock the writer side of m_list_mutex as we're going to add frames here:
405 if (end_idx < m_concrete_frames_fetched)
406 return false;
407 // We're adding concrete frames now:
408 // FIXME: This should also be interruptible:
410 return false;
411 }
412
413 // We're adding concrete and inlined frames now:
414 was_interrupted = FetchFramesUpTo(end_idx, allow_interrupt);
415
416#if defined(DEBUG_STACK_FRAMES)
417 s.PutCString("\n\nNew frames:\n");
418 Dump(&s);
419 s.EOL();
420#endif
421 return was_interrupted;
422}
423
425 assert(m_thread.IsValid() && "Expected valid thread");
426 assert(m_frames.size() <= end_idx && "Expected there to be frames to fill");
427
428 Unwind &unwinder = m_thread.GetUnwinder();
429
430 if (end_idx < m_concrete_frames_fetched)
431 return;
432
433 uint32_t num_frames = unwinder.GetFramesUpTo(end_idx);
434 if (num_frames <= end_idx + 1) {
435 // Done unwinding.
437 }
438
439 // Don't create the frames eagerly. Defer this work to GetFrameAtIndex,
440 // which can lazily query the unwinder to create frames.
441 m_frames.resize(num_frames);
442}
443
445 InterruptionControl allow_interrupt) {
446 Unwind &unwinder = m_thread.GetUnwinder();
447 bool was_interrupted = false;
448
449#if defined(DEBUG_STACK_FRAMES)
450 StreamFile s(stdout, false);
451#endif
452 // If we are hiding some frames from the outside world, we need to add
453 // those onto the total count of frames to fetch. However, we don't need
454 // to do that if end_idx is 0 since in that case we always get the first
455 // concrete frame and all the inlined frames below it... And of course, if
456 // end_idx is UINT32_MAX that means get all, so just do that...
457
458 uint32_t inlined_depth = 0;
459 if (end_idx > 0 && end_idx != UINT32_MAX) {
460 inlined_depth = GetCurrentInlinedDepth();
461 if (inlined_depth != UINT32_MAX) {
462 if (end_idx > 0)
463 end_idx += inlined_depth;
464 }
465 }
466
467 StackFrameSP unwind_frame_sp;
468 Debugger &dbg = m_thread.GetProcess()->GetTarget().GetDebugger();
469 do {
470 uint32_t idx = m_concrete_frames_fetched++;
473 bool behaves_like_zeroth_frame = (idx == 0);
474 if (idx == 0) {
475 // We might have already created frame zero, only create it if we need
476 // to.
477 if (m_frames.empty()) {
478 RegisterContextSP reg_ctx_sp(m_thread.GetRegisterContext());
479
480 if (reg_ctx_sp) {
481 const bool success = unwinder.GetFrameInfoAtIndex(
482 idx, cfa, pc, behaves_like_zeroth_frame);
483 // There shouldn't be any way not to get the frame info for frame
484 // 0. But if the unwinder can't make one, lets make one by hand
485 // with the SP as the CFA and see if that gets any further.
486 if (!success) {
487 cfa = reg_ctx_sp->GetSP();
488 pc = reg_ctx_sp->GetPC();
489 }
490
491 unwind_frame_sp = std::make_shared<StackFrame>(
492 m_thread.shared_from_this(), m_frames.size(), idx, reg_ctx_sp,
493 cfa, pc, behaves_like_zeroth_frame, nullptr);
494 unwind_frame_sp->m_frame_list_wp = shared_from_this();
495 m_frames.push_back(unwind_frame_sp);
496 }
497 } else {
498 unwind_frame_sp = m_frames.front();
499 cfa = unwind_frame_sp->m_id.GetCallFrameAddressWithoutMetadata();
500 }
501 } else {
502 // Check for interruption when building the frames.
503 // Do the check in idx > 0 so that we'll always create a 0th frame.
504 if (allow_interrupt &&
505 INTERRUPT_REQUESTED(dbg, "Interrupted having fetched {0} frames",
506 m_frames.size())) {
507 was_interrupted = true;
508 break;
509 }
510
511 const bool success =
512 unwinder.GetFrameInfoAtIndex(idx, cfa, pc, behaves_like_zeroth_frame);
513 if (!success) {
514 // We've gotten to the end of the stack.
516 break;
517 }
518 const bool cfa_is_valid = true;
519 unwind_frame_sp = std::make_shared<StackFrame>(
520 m_thread.shared_from_this(), m_frames.size(), idx, cfa, cfa_is_valid,
521 pc, StackFrame::Kind::Regular, false, behaves_like_zeroth_frame,
522 nullptr);
523
524 // Create synthetic tail call frames between the previous frame and the
525 // newly-found frame. The new frame's index may change after this call,
526 // although its concrete index will stay the same.
527 SynthesizeTailCallFrames(*unwind_frame_sp.get());
528
529 unwind_frame_sp->m_frame_list_wp = shared_from_this();
530 m_frames.push_back(unwind_frame_sp);
531 }
532
533 assert(unwind_frame_sp);
534 SymbolContext unwind_sc = unwind_frame_sp->GetSymbolContext(
535 eSymbolContextBlock | eSymbolContextFunction);
536 Block *unwind_block = unwind_sc.block;
537 TargetSP target_sp = m_thread.CalculateTarget();
538 if (unwind_block) {
539 Address curr_frame_address(
540 unwind_frame_sp->GetFrameCodeAddressForSymbolication());
541
542 SymbolContext next_frame_sc;
543 Address next_frame_address;
544
545 while (unwind_sc.GetParentOfInlinedScope(
546 curr_frame_address, next_frame_sc, next_frame_address)) {
547 next_frame_sc.line_entry.ApplyFileMappings(target_sp);
548 behaves_like_zeroth_frame = false;
549 StackFrameSP frame_sp(new StackFrame(
550 m_thread.shared_from_this(), m_frames.size(), idx,
551 unwind_frame_sp->GetRegisterContextSP(), cfa, next_frame_address,
552 behaves_like_zeroth_frame, &next_frame_sc));
553
554 frame_sp->m_frame_list_wp = shared_from_this();
555 m_frames.push_back(frame_sp);
556 unwind_sc = next_frame_sc;
557 curr_frame_address = next_frame_address;
558 }
559 }
560 } while (m_frames.size() - 1 < end_idx);
561
562 // Don't try to merge till you've calculated all the frames in this stack.
564 StackFrameList *prev_frames = m_prev_frames_sp.get();
565 StackFrameList *curr_frames = this;
566
567#if defined(DEBUG_STACK_FRAMES)
568 s.PutCString("\nprev_frames:\n");
569 prev_frames->Dump(&s);
570 s.PutCString("\ncurr_frames:\n");
571 curr_frames->Dump(&s);
572 s.EOL();
573#endif
574 size_t curr_frame_num, prev_frame_num;
575
576 for (curr_frame_num = curr_frames->m_frames.size(),
577 prev_frame_num = prev_frames->m_frames.size();
578 curr_frame_num > 0 && prev_frame_num > 0;
579 --curr_frame_num, --prev_frame_num) {
580 const size_t curr_frame_idx = curr_frame_num - 1;
581 const size_t prev_frame_idx = prev_frame_num - 1;
582 StackFrameSP curr_frame_sp(curr_frames->m_frames[curr_frame_idx]);
583 StackFrameSP prev_frame_sp(prev_frames->m_frames[prev_frame_idx]);
584
585#if defined(DEBUG_STACK_FRAMES)
586 s.Printf("\n\nCurr frame #%u ", curr_frame_idx);
587 if (curr_frame_sp)
588 curr_frame_sp->Dump(&s, true, false);
589 else
590 s.PutCString("NULL");
591 s.Printf("\nPrev frame #%u ", prev_frame_idx);
592 if (prev_frame_sp)
593 prev_frame_sp->Dump(&s, true, false);
594 else
595 s.PutCString("NULL");
596#endif
597
598 StackFrame *curr_frame = curr_frame_sp.get();
599 StackFrame *prev_frame = prev_frame_sp.get();
600
601 if (curr_frame == nullptr || prev_frame == nullptr)
602 break;
603
604 // Check the stack ID to make sure they are equal.
605 if (curr_frame->GetStackID() != prev_frame->GetStackID())
606 break;
607
608 prev_frame->UpdatePreviousFrameFromCurrentFrame(*curr_frame);
609 // Now copy the fixed up previous frame into the current frames so the
610 // pointer doesn't change.
611 prev_frame_sp->m_frame_list_wp = shared_from_this();
612 m_frames[curr_frame_idx] = prev_frame_sp;
613
614#if defined(DEBUG_STACK_FRAMES)
615 s.Printf("\n Copying previous frame to current frame");
616#endif
617 }
618 // We are done with the old stack frame list, we can release it now.
619 m_prev_frames_sp.reset();
620 }
621 // Don't report interrupted if we happen to have gotten all the frames:
622 if (!GetAllFramesFetched())
623 return was_interrupted;
624 return false;
625}
626
627uint32_t StackFrameList::GetNumFrames(bool can_create) {
628 if (!WereAllFramesFetched() && can_create) {
629 // Don't allow interrupt or we might not return the correct count
631 }
632 uint32_t frame_idx;
633 {
634 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
635 frame_idx = GetVisibleStackFrameIndex(m_frames.size());
636 }
637 return frame_idx;
638}
639
641 if (s == nullptr)
642 return;
643
644 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
645
646 const_iterator pos, begin = m_frames.begin(), end = m_frames.end();
647 for (pos = begin; pos != end; ++pos) {
648 StackFrame *frame = (*pos).get();
649 s->Printf("%p: ", static_cast<void *>(frame));
650 if (frame) {
651 frame->GetStackID().Dump(s);
652 frame->DumpUsingSettingsFormat(s);
653 } else
654 s->Printf("frame #%u", (uint32_t)std::distance(begin, pos));
655 s->EOL();
656 }
657 s->EOL();
658}
659
661 StackFrameSP frame_sp;
662 uint32_t original_idx = idx;
663
664 // We're going to consult the m_frames.size, but if there are already
665 // enough frames for our request we don't want to block other readers, so
666 // first acquire the shared lock:
667 { // Scope for shared lock:
668 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
669
670 uint32_t inlined_depth = GetCurrentInlinedDepth();
671 if (inlined_depth != UINT32_MAX)
672 idx += inlined_depth;
673
674 if (idx < m_frames.size())
675 frame_sp = m_frames[idx];
676
677 if (frame_sp)
678 return frame_sp;
679 } // End of reader lock scope
680
681 // GetFramesUpTo will fill m_frames with as many frames as you asked for, if
682 // there are that many. If there weren't then you asked for too many frames.
683 // GetFramesUpTo returns true if interrupted:
685 Log *log = GetLog(LLDBLog::Thread);
686 LLDB_LOG(log, "GetFrameAtIndex was interrupted");
687 return {};
688 }
689
690 { // Now we're accessing m_frames as a reader, so acquire the reader lock.
691 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
692 if (idx < m_frames.size()) {
693 frame_sp = m_frames[idx];
694 } else if (original_idx == 0) {
695 // There should ALWAYS be a frame at index 0. If something went wrong
696 // with the CurrentInlinedDepth such that there weren't as many frames as
697 // we thought taking that into account, then reset the current inlined
698 // depth and return the real zeroth frame.
699 if (m_frames.empty()) {
700 // Why do we have a thread with zero frames, that should not ever
701 // happen...
702 assert(!m_thread.IsValid() && "A valid thread has no frames.");
703 } else {
705 frame_sp = m_frames[original_idx];
706 }
707 }
708 } // End of reader lock scope
709
710 return frame_sp;
711}
712
715 // First try assuming the unwind index is the same as the frame index. The
716 // unwind index is always greater than or equal to the frame index, so it is
717 // a good place to start. If we have inlined frames we might have 5 concrete
718 // frames (frame unwind indexes go from 0-4), but we might have 15 frames
719 // after we make all the inlined frames. Most of the time the unwind frame
720 // index (or the concrete frame index) is the same as the frame index.
721 uint32_t frame_idx = unwind_idx;
722 StackFrameSP frame_sp(GetFrameAtIndex(frame_idx));
723 while (frame_sp) {
724 if (frame_sp->GetFrameIndex() == unwind_idx)
725 break;
726 frame_sp = GetFrameAtIndex(++frame_idx);
727 }
728 return frame_sp;
729}
730
731static bool CompareStackID(const StackFrameSP &stack_sp,
732 const StackID &stack_id) {
733 return stack_sp->GetStackID() < stack_id;
734}
735
737 StackFrameSP frame_sp;
738
739 if (stack_id.IsValid()) {
740 uint32_t frame_idx = 0;
741 {
742 // First see if the frame is already realized. This is the scope for
743 // the shared mutex:
744 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
745 // Do a binary search in case the stack frame is already in our cache
746 collection::const_iterator pos =
747 llvm::lower_bound(m_frames, stack_id, CompareStackID);
748 if (pos != m_frames.end() && (*pos)->GetStackID() == stack_id)
749 return *pos;
750 }
751 // If we needed to add more frames, we would get to here.
752 do {
753 frame_sp = GetFrameAtIndex(frame_idx);
754 if (frame_sp && frame_sp->GetStackID() == stack_id)
755 break;
756 frame_idx++;
757 } while (frame_sp);
758 }
759 return frame_sp;
760}
761
762bool StackFrameList::SetFrameAtIndex(uint32_t idx, StackFrameSP &frame_sp) {
763 std::unique_lock<std::shared_mutex> guard(m_list_mutex);
764 if (idx >= m_frames.size())
765 m_frames.resize(idx + 1);
766 // Make sure allocation succeeded by checking bounds again
767 if (idx < m_frames.size()) {
768 m_frames[idx] = frame_sp;
769 return true;
770 }
771 return false; // resize failed, out of memory?
772}
773
775 // Don't call into the frame recognizers on the private state thread as
776 // they can cause code to run in the target, and that can cause deadlocks
777 // when fetching stop events for the expression.
778 if (m_thread.GetProcess()->CurrentThreadPosesAsPrivateStateThread())
779 return;
780
781 Log *log = GetLog(LLDBLog::Thread);
782
783 // Only the top frame should be recognized.
784 StackFrameSP frame_sp = GetFrameAtIndex(0);
785 if (!frame_sp) {
786 LLDB_LOG(log, "Failed to construct Frame #0");
787 return;
788 }
789
790 RecognizedStackFrameSP recognized_frame_sp = frame_sp->GetRecognizedFrame();
791
792 if (recognized_frame_sp) {
793 if (StackFrameSP most_relevant_frame_sp =
794 recognized_frame_sp->GetMostRelevantFrame()) {
795 LLDB_LOG(log, "Found most relevant frame at index {0}",
796 most_relevant_frame_sp->GetFrameIndex());
797 SetSelectedFrame(most_relevant_frame_sp.get());
798 return;
799 }
800 }
801 LLDB_LOG(log, "Frame #0 not recognized");
802
803 // If this thread has a non-trivial StopInfo, then let it suggest
804 // a most relevant frame:
805 StopInfoSP stop_info_sp = m_thread.GetStopInfo();
806 uint32_t stack_idx = 0;
807 bool found_relevant = false;
808 if (stop_info_sp) {
809 // Here we're only asking the stop info if it wants to adjust the real stack
810 // index. We have to ask about the m_inlined_stack_depth in
811 // Thread::ShouldStop since the plans need to reason with that info.
812 bool inlined = false;
813 std::optional<uint32_t> stack_opt =
814 stop_info_sp->GetSuggestedStackFrameIndex(inlined);
815 if (stack_opt) {
816 stack_idx = *stack_opt;
817 found_relevant = true;
818 }
819 }
820
821 frame_sp = GetFrameAtIndex(stack_idx);
822 if (!frame_sp)
823 LLDB_LOG(log, "Stop info suggested relevant frame {0} but it didn't exist",
824 stack_idx);
825 else if (found_relevant)
826 LLDB_LOG(log, "Setting selected frame from stop info to {0}", stack_idx);
827 // Note, we don't have to worry about "inlined" frames here, because we've
828 // already calculated the inlined frame in Thread::ShouldStop, and
829 // SetSelectedFrame will take care of that adjustment for us.
830 SetSelectedFrame(frame_sp.get());
831
832 if (!found_relevant)
833 LLDB_LOG(log, "No relevant frame!");
834}
835
836uint32_t
838 std::lock_guard<std::recursive_mutex> guard(m_selected_frame_mutex);
839
840 if (!m_selected_frame_idx && select_most_relevant)
843 // If we aren't selecting the most relevant frame, and the selected frame
844 // isn't set, then don't force a selection here, just return 0.
845 if (!select_most_relevant)
846 return 0;
847 // If the inlined stack frame is set, then use that:
849 }
850 return *m_selected_frame_idx;
851}
852
854 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
855 std::lock_guard<std::recursive_mutex> selected_frame_guard(
857
858 const_iterator pos;
859 const_iterator begin = m_frames.begin();
860 const_iterator end = m_frames.end();
862
863 for (pos = begin; pos != end; ++pos) {
864 if (pos->get() == frame) {
865 m_selected_frame_idx = std::distance(begin, pos);
866 uint32_t inlined_depth = GetCurrentInlinedDepth();
867 if (inlined_depth != UINT32_MAX)
869 break;
870 }
871 }
873 return *m_selected_frame_idx;
874}
875
877 StackFrameSP frame_sp(GetFrameAtIndex(idx));
878 if (frame_sp) {
879 SetSelectedFrame(frame_sp.get());
880 return true;
881 } else
882 return false;
883}
884
886 if (m_thread.GetID() ==
887 m_thread.GetProcess()->GetThreadList().GetSelectedThread()->GetID()) {
888 StackFrameSP frame_sp(
890 if (frame_sp) {
891 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextLineEntry);
892 if (sc.line_entry.GetFile())
893 m_thread.CalculateTarget()->GetSourceManager().SetDefaultFileAndLine(
895 }
896 }
897}
898
899// The thread has been run, reset the number stack frames to zero so we can
900// determine how many frames we have lazily.
901// Note, we don't actually re-use StackFrameLists, we always make a new
902// StackFrameList every time we stop, and then copy frame information frame
903// by frame from the old to the new StackFrameList. So the comment above,
904// does not describe how StackFrameLists are currently used.
905// Clear is currently only used to clear the list in the destructor.
907 std::unique_lock<std::shared_mutex> guard(m_list_mutex);
908 m_frames.clear();
910 std::lock_guard<std::recursive_mutex> selected_frame_guard(
912 m_selected_frame_idx.reset();
913}
914
917 std::shared_lock<std::shared_mutex> guard(m_list_mutex);
918 const_iterator pos;
919 const_iterator begin = m_frames.begin();
920 const_iterator end = m_frames.end();
921 lldb::StackFrameSP ret_sp;
922
923 for (pos = begin; pos != end; ++pos) {
924 if (pos->get() == stack_frame_ptr) {
925 ret_sp = (*pos);
926 break;
927 }
928 }
929 return ret_sp;
930}
931
932size_t StackFrameList::GetStatus(Stream &strm, uint32_t first_frame,
933 uint32_t num_frames, bool show_frame_info,
934 uint32_t num_frames_with_source,
935 bool show_unique, bool show_hidden,
936 const char *selected_frame_marker) {
937 size_t num_frames_displayed = 0;
938
939 if (num_frames == 0)
940 return 0;
941
942 StackFrameSP frame_sp;
943 uint32_t frame_idx = 0;
944 uint32_t last_frame;
945
946 // Don't let the last frame wrap around...
947 if (num_frames == UINT32_MAX)
948 last_frame = UINT32_MAX;
949 else
950 last_frame = first_frame + num_frames;
951
952 StackFrameSP selected_frame_sp =
953 m_thread.GetSelectedFrame(DoNoSelectMostRelevantFrame);
954 const char *unselected_marker = nullptr;
955 std::string buffer;
956 if (selected_frame_marker) {
957 size_t len = strlen(selected_frame_marker);
958 buffer.insert(buffer.begin(), len, ' ');
959 unselected_marker = buffer.c_str();
960 }
961 const char *marker = nullptr;
962 for (frame_idx = first_frame; frame_idx < last_frame; ++frame_idx) {
963 frame_sp = GetFrameAtIndex(frame_idx);
964 if (!frame_sp)
965 break;
966
967 if (selected_frame_marker != nullptr) {
968 if (frame_sp == selected_frame_sp)
969 marker = selected_frame_marker;
970 else
971 marker = unselected_marker;
972 }
973
974 // Hide uninteresting frames unless it's the selected frame.
975 if (!show_hidden && frame_sp != selected_frame_sp && frame_sp->IsHidden())
976 continue;
977
978 // Check for interruption here. If we're fetching arguments, this loop
979 // can go slowly:
980 Debugger &dbg = m_thread.GetProcess()->GetTarget().GetDebugger();
982 dbg, "Interrupted dumping stack for thread {0:x} with {1} shown.",
983 m_thread.GetID(), num_frames_displayed))
984 break;
985
986 if (!frame_sp->GetStatus(strm, show_frame_info,
987 num_frames_with_source > (first_frame - frame_idx),
988 show_unique, marker))
989 break;
990 ++num_frames_displayed;
991 }
992
993 strm.IndentLess();
994 return num_frames_displayed;
995}
996
#define INTERRUPT_REQUESTED(debugger,...)
This handy define will keep you from having to generate a report for the interruption by hand.
Definition Debugger.h:476
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:369
#define LLDB_LOGF(log,...)
Definition Log.h:376
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:392
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
A class that describes a single lexical block.
Definition Block.h:41
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:87
"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
bool GetVerbose() const
Definition Log.cpp:326
A collection class for Module objects.
Definition ModuleList.h:101
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.
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.
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, const char *frame_marker=nullptr)
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.
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...
StackFrameList(Thread &thread, const lldb::StackFrameListSP &prev_frames_sp, bool show_inline_frames)
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.
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 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:455
virtual void DumpUsingSettingsFormat(Stream *strm, bool show_unique=false, const char *frame_marker=nullptr)
Print a description for this frame using the frame-format formatter settings.
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:465
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:64
virtual StackID & GetStackID()
virtual const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
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:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:65
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:155
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:198
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)
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:332
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
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.