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