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