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"
22#include "lldb/Target/Target.h"
23#include "lldb/Target/Thread.h"
24#include "lldb/Target/Unwind.h"
26#include "lldb/Utility/Log.h"
27#include "llvm/ADT/SmallPtrSet.h"
28
29#include <memory>
30
31//#define DEBUG_STACK_FRAMES 1
32
33using namespace lldb;
34using namespace lldb_private;
35
36// StackFrameList constructor
38 const lldb::StackFrameListSP &prev_frames_sp,
39 bool show_inline_frames)
40 : m_thread(thread), m_prev_frames_sp(prev_frames_sp), m_mutex(), m_frames(),
41 m_selected_frame_idx(0), m_concrete_frames_fetched(0),
42 m_current_inlined_depth(UINT32_MAX),
43 m_current_inlined_pc(LLDB_INVALID_ADDRESS),
44 m_show_inlined_frames(show_inline_frames) {
45 if (prev_frames_sp) {
46 m_current_inlined_depth = prev_frames_sp->m_current_inlined_depth;
47 m_current_inlined_pc = prev_frames_sp->m_current_inlined_pc;
48 }
49}
50
52 // Call clear since this takes a lock and clears the stack frame list in case
53 // another thread is currently using this stack frame list
54 Clear();
55}
56
58 uint32_t cur_inlined_depth = GetCurrentInlinedDepth();
59 if (cur_inlined_depth == UINT32_MAX) {
61 }
62}
63
66 lldb::addr_t cur_pc = m_thread.GetRegisterContext()->GetPC();
67 if (cur_pc != m_current_inlined_pc) {
70 Log *log = GetLog(LLDBLog::Step);
71 if (log && log->GetVerbose())
73 log,
74 "GetCurrentInlinedDepth: invalidating current inlined depth.\n");
75 }
77 } else {
78 return UINT32_MAX;
79 }
80}
81
84 return;
85
86 std::lock_guard<std::recursive_mutex> guard(m_mutex);
87
89 if (m_frames.empty())
90 return;
91 if (!m_frames[0]->IsInlined()) {
94 Log *log = GetLog(LLDBLog::Step);
95 if (log && log->GetVerbose())
97 log,
98 "ResetCurrentInlinedDepth: Invalidating current inlined depth.\n");
99 return;
100 }
101
102 // We only need to do something special about inlined blocks when we are
103 // at the beginning of an inlined function:
104 // FIXME: We probably also have to do something special if the PC is at
105 // the END of an inlined function, which coincides with the end of either
106 // its containing function or another inlined function.
107
108 Block *block_ptr = m_frames[0]->GetFrameBlock();
109 if (!block_ptr)
110 return;
111
112 Address pc_as_address;
113 lldb::addr_t curr_pc = m_thread.GetRegisterContext()->GetPC();
114 pc_as_address.SetLoadAddress(curr_pc, &(m_thread.GetProcess()->GetTarget()));
115 AddressRange containing_range;
116 if (!block_ptr->GetRangeContainingAddress(pc_as_address, containing_range) ||
117 pc_as_address != containing_range.GetBaseAddress())
118 return;
119
120 // If we got here because of a breakpoint hit, then set the inlined depth
121 // depending on where the breakpoint was set. If we got here because of a
122 // crash, then set the inlined depth to the deepest most block. Otherwise,
123 // we stopped here naturally as the result of a step, so set ourselves in the
124 // containing frame of the whole set of nested inlines, so the user can then
125 // "virtually" step into the frames one by one, or next over the whole mess.
126 // Note: We don't have to handle being somewhere in the middle of the stack
127 // here, since ResetCurrentInlinedDepth doesn't get called if there is a
128 // valid inlined depth set.
129 StopInfoSP stop_info_sp = m_thread.GetStopInfo();
130 if (!stop_info_sp)
131 return;
132 switch (stop_info_sp->GetStopReason()) {
135 case eStopReasonExec:
136 case eStopReasonFork:
137 case eStopReasonVFork:
140 // In all these cases we want to stop in the deepest frame.
141 m_current_inlined_pc = curr_pc;
143 break;
145 // FIXME: Figure out what this break point is doing, and set the inline
146 // depth appropriately. Be careful to take into account breakpoints that
147 // implement step over prologue, since that should do the default
148 // calculation. For now, if the breakpoints corresponding to this hit are
149 // all internal, I set the stop location to the top of the inlined stack,
150 // since that will make things like stepping over prologues work right.
151 // But if there are any non-internal breakpoints I do to the bottom of the
152 // stack, since that was the old behavior.
153 uint32_t bp_site_id = stop_info_sp->GetValue();
154 BreakpointSiteSP bp_site_sp(
155 m_thread.GetProcess()->GetBreakpointSiteList().FindByID(bp_site_id));
156 bool all_internal = true;
157 if (bp_site_sp) {
158 uint32_t num_owners = bp_site_sp->GetNumberOfOwners();
159 for (uint32_t i = 0; i < num_owners; i++) {
160 Breakpoint &bp_ref = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
161 if (!bp_ref.IsInternal()) {
162 all_internal = false;
163 }
164 }
165 }
166 if (!all_internal) {
167 m_current_inlined_pc = curr_pc;
169 break;
170 }
171 }
172 [[fallthrough]];
173 default: {
174 // Otherwise, we should set ourselves at the container of the inlining, so
175 // that the user can descend into them. So first we check whether we have
176 // more than one inlined block sharing this PC:
177 int num_inlined_functions = 0;
178
179 for (Block *container_ptr = block_ptr->GetInlinedParent();
180 container_ptr != nullptr;
181 container_ptr = container_ptr->GetInlinedParent()) {
182 if (!container_ptr->GetRangeContainingAddress(pc_as_address,
183 containing_range))
184 break;
185 if (pc_as_address != containing_range.GetBaseAddress())
186 break;
187
188 num_inlined_functions++;
189 }
190 m_current_inlined_pc = curr_pc;
191 m_current_inlined_depth = num_inlined_functions + 1;
192 Log *log = GetLog(LLDBLog::Step);
193 if (log && log->GetVerbose())
194 LLDB_LOGF(log,
195 "ResetCurrentInlinedDepth: setting inlined "
196 "depth: %d 0x%" PRIx64 ".\n",
197 m_current_inlined_depth, curr_pc);
198
199 break;
200 }
201 }
202}
203
206 uint32_t current_inlined_depth = GetCurrentInlinedDepth();
207 if (current_inlined_depth != UINT32_MAX) {
208 if (current_inlined_depth > 0) {
210 return true;
211 }
212 }
213 }
214 return false;
215}
216
218 m_current_inlined_depth = new_depth;
219 if (new_depth == UINT32_MAX)
221 else
223}
224
226 Unwind &unwinder) {
227 assert(m_thread.IsValid() && "Expected valid thread");
228 assert(m_frames.size() <= end_idx && "Expected there to be frames to fill");
229
230 if (end_idx < m_concrete_frames_fetched)
231 return;
232
233 uint32_t num_frames = unwinder.GetFramesUpTo(end_idx);
234 if (num_frames <= end_idx + 1) {
235 // Done unwinding.
237 }
238
239 // Don't create the frames eagerly. Defer this work to GetFrameAtIndex,
240 // which can lazily query the unwinder to create frames.
241 m_frames.resize(num_frames);
242}
243
244/// A sequence of calls that comprise some portion of a backtrace. Each frame
245/// is represented as a pair of a callee (Function *) and an address within the
246/// callee.
249 CallEdge::AddrType address_type = CallEdge::AddrType::Call;
251};
252using CallSequence = std::vector<CallDescriptor>;
253
254/// Find the unique path through the call graph from \p begin (with return PC
255/// \p return_pc) to \p end. On success this path is stored into \p path, and
256/// on failure \p path is unchanged.
257static void FindInterveningFrames(Function &begin, Function &end,
258 ExecutionContext &exe_ctx, Target &target,
259 addr_t return_pc, CallSequence &path,
260 ModuleList &images, Log *log) {
261 LLDB_LOG(log, "Finding frames between {0} and {1}, retn-pc={2:x}",
262 begin.GetDisplayName(), end.GetDisplayName(), return_pc);
263
264 // Find a non-tail calling edge with the correct return PC.
265 if (log)
266 for (const auto &edge : begin.GetCallEdges())
267 LLDB_LOG(log, "FindInterveningFrames: found call with retn-PC = {0:x}",
268 edge->GetReturnPCAddress(begin, target));
269 CallEdge *first_edge = begin.GetCallEdgeForReturnAddress(return_pc, target);
270 if (!first_edge) {
271 LLDB_LOG(log, "No call edge outgoing from {0} with retn-PC == {1:x}",
272 begin.GetDisplayName(), return_pc);
273 return;
274 }
275
276 // The first callee may not be resolved, or there may be nothing to fill in.
277 Function *first_callee = first_edge->GetCallee(images, exe_ctx);
278 if (!first_callee) {
279 LLDB_LOG(log, "Could not resolve callee");
280 return;
281 }
282 if (first_callee == &end) {
283 LLDB_LOG(log, "Not searching further, first callee is {0} (retn-PC: {1:x})",
284 end.GetDisplayName(), return_pc);
285 return;
286 }
287
288 // Run DFS on the tail-calling edges out of the first callee to find \p end.
289 // Fully explore the set of functions reachable from the first edge via tail
290 // calls in order to detect ambiguous executions.
291 struct DFS {
292 CallSequence active_path = {};
293 CallSequence solution_path = {};
294 llvm::SmallPtrSet<Function *, 2> visited_nodes = {};
295 bool ambiguous = false;
296 Function *end;
297 ModuleList &images;
298 Target &target;
299 ExecutionContext &context;
300
301 DFS(Function *end, ModuleList &images, Target &target,
302 ExecutionContext &context)
303 : end(end), images(images), target(target), context(context) {}
304
305 void search(CallEdge &first_edge, Function &first_callee,
306 CallSequence &path) {
307 dfs(first_edge, first_callee);
308 if (!ambiguous)
309 path = std::move(solution_path);
310 }
311
312 void dfs(CallEdge &current_edge, Function &callee) {
313 // Found a path to the target function.
314 if (&callee == end) {
315 if (solution_path.empty())
316 solution_path = active_path;
317 else
318 ambiguous = true;
319 return;
320 }
321
322 // Terminate the search if tail recursion is found, or more generally if
323 // there's more than one way to reach a target. This errs on the side of
324 // caution: it conservatively stops searching when some solutions are
325 // still possible to save time in the average case.
326 if (!visited_nodes.insert(&callee).second) {
327 ambiguous = true;
328 return;
329 }
330
331 // Search the calls made from this callee.
332 active_path.push_back(CallDescriptor{&callee});
333 for (const auto &edge : callee.GetTailCallingEdges()) {
334 Function *next_callee = edge->GetCallee(images, context);
335 if (!next_callee)
336 continue;
337
338 std::tie(active_path.back().address_type, active_path.back().address) =
339 edge->GetCallerAddress(callee, target);
340
341 dfs(*edge, *next_callee);
342 if (ambiguous)
343 return;
344 }
345 active_path.pop_back();
346 }
347 };
348
349 DFS(&end, images, target, exe_ctx).search(*first_edge, *first_callee, path);
350}
351
352/// Given that \p next_frame will be appended to the frame list, synthesize
353/// tail call frames between the current end of the list and \p next_frame.
354/// If any frames are added, adjust the frame index of \p next_frame.
355///
356/// --------------
357/// | ... | <- Completed frames.
358/// --------------
359/// | prev_frame |
360/// --------------
361/// | ... | <- Artificial frames inserted here.
362/// --------------
363/// | next_frame |
364/// --------------
365/// | ... | <- Not-yet-visited frames.
366/// --------------
368 // Cannot synthesize tail call frames when the stack is empty (there is no
369 // "previous" frame).
370 if (m_frames.empty())
371 return;
372
373 TargetSP target_sp = next_frame.CalculateTarget();
374 if (!target_sp)
375 return;
376
377 lldb::RegisterContextSP next_reg_ctx_sp = next_frame.GetRegisterContext();
378 if (!next_reg_ctx_sp)
379 return;
380
381 Log *log = GetLog(LLDBLog::Step);
382
383 StackFrame &prev_frame = *m_frames.back().get();
384
385 // Find the functions prev_frame and next_frame are stopped in. The function
386 // objects are needed to search the lazy call graph for intervening frames.
387 Function *prev_func =
388 prev_frame.GetSymbolContext(eSymbolContextFunction).function;
389 if (!prev_func) {
390 LLDB_LOG(log, "SynthesizeTailCallFrames: can't find previous function");
391 return;
392 }
393 Function *next_func =
394 next_frame.GetSymbolContext(eSymbolContextFunction).function;
395 if (!next_func) {
396 LLDB_LOG(log, "SynthesizeTailCallFrames: can't find next function");
397 return;
398 }
399
400 // Try to find the unique sequence of (tail) calls which led from next_frame
401 // to prev_frame.
402 CallSequence path;
403 addr_t return_pc = next_reg_ctx_sp->GetPC();
404 Target &target = *target_sp.get();
405 ModuleList &images = next_frame.CalculateTarget()->GetImages();
406 ExecutionContext exe_ctx(target_sp, /*get_process=*/true);
407 exe_ctx.SetFramePtr(&next_frame);
408 FindInterveningFrames(*next_func, *prev_func, exe_ctx, target, return_pc,
409 path, images, log);
410
411 // Push synthetic tail call frames.
412 for (auto calleeInfo : llvm::reverse(path)) {
413 Function *callee = calleeInfo.func;
414 uint32_t frame_idx = m_frames.size();
415 uint32_t concrete_frame_idx = next_frame.GetConcreteFrameIndex();
417 bool cfa_is_valid = false;
418 addr_t pc = calleeInfo.address;
419 // If the callee address refers to the call instruction, we do not want to
420 // subtract 1 from this value.
421 const bool behaves_like_zeroth_frame =
422 calleeInfo.address_type == CallEdge::AddrType::Call;
423 SymbolContext sc;
424 callee->CalculateSymbolContext(&sc);
425 auto synth_frame = std::make_shared<StackFrame>(
426 m_thread.shared_from_this(), frame_idx, concrete_frame_idx, cfa,
427 cfa_is_valid, pc, StackFrame::Kind::Artificial,
428 behaves_like_zeroth_frame, &sc);
429 m_frames.push_back(synth_frame);
430 LLDB_LOG(log, "Pushed frame {0} at {1:x}", callee->GetDisplayName(), pc);
431 }
432
433 // If any frames were created, adjust next_frame's index.
434 if (!path.empty())
435 next_frame.SetFrameIndex(m_frames.size());
436}
437
439 // Do not fetch frames for an invalid thread.
440 if (!m_thread.IsValid())
441 return;
442
443 // We've already gotten more frames than asked for, or we've already finished
444 // unwinding, return.
445 if (m_frames.size() > end_idx || GetAllFramesFetched())
446 return;
447
448 Unwind &unwinder = m_thread.GetUnwinder();
449
451 GetOnlyConcreteFramesUpTo(end_idx, unwinder);
452 return;
453 }
454
455#if defined(DEBUG_STACK_FRAMES)
456 StreamFile s(stdout, false);
457#endif
458 // If we are hiding some frames from the outside world, we need to add
459 // those onto the total count of frames to fetch. However, we don't need
460 // to do that if end_idx is 0 since in that case we always get the first
461 // concrete frame and all the inlined frames below it... And of course, if
462 // end_idx is UINT32_MAX that means get all, so just do that...
463
464 uint32_t inlined_depth = 0;
465 if (end_idx > 0 && end_idx != UINT32_MAX) {
466 inlined_depth = GetCurrentInlinedDepth();
467 if (inlined_depth != UINT32_MAX) {
468 if (end_idx > 0)
469 end_idx += inlined_depth;
470 }
471 }
472
473 StackFrameSP unwind_frame_sp;
474 Debugger &dbg = m_thread.GetProcess()->GetTarget().GetDebugger();
475 do {
476 // Check for interruption here when building the frames - this is the
477 // expensive part, Dump later on is cheap.
478 if (dbg.InterruptRequested()) {
479 Log *log = GetLog(LLDBLog::Host);
480 LLDB_LOG(log, "Interrupted %s", __FUNCTION__);
481 break;
482 }
486 bool behaves_like_zeroth_frame = (idx == 0);
487 if (idx == 0) {
488 // We might have already created frame zero, only create it if we need
489 // to.
490 if (m_frames.empty()) {
491 RegisterContextSP reg_ctx_sp(m_thread.GetRegisterContext());
492
493 if (reg_ctx_sp) {
494 const bool success = unwinder.GetFrameInfoAtIndex(
495 idx, cfa, pc, behaves_like_zeroth_frame);
496 // There shouldn't be any way not to get the frame info for frame
497 // 0. But if the unwinder can't make one, lets make one by hand
498 // with the SP as the CFA and see if that gets any further.
499 if (!success) {
500 cfa = reg_ctx_sp->GetSP();
501 pc = reg_ctx_sp->GetPC();
502 }
503
504 unwind_frame_sp = std::make_shared<StackFrame>(
505 m_thread.shared_from_this(), m_frames.size(), idx, reg_ctx_sp,
506 cfa, pc, behaves_like_zeroth_frame, nullptr);
507 m_frames.push_back(unwind_frame_sp);
508 }
509 } else {
510 unwind_frame_sp = m_frames.front();
511 cfa = unwind_frame_sp->m_id.GetCallFrameAddress();
512 }
513 } else {
514 const bool success =
515 unwinder.GetFrameInfoAtIndex(idx, cfa, pc, behaves_like_zeroth_frame);
516 if (!success) {
517 // We've gotten to the end of the stack.
519 break;
520 }
521 const bool cfa_is_valid = true;
522 unwind_frame_sp = std::make_shared<StackFrame>(
523 m_thread.shared_from_this(), m_frames.size(), idx, cfa, cfa_is_valid,
524 pc, StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr);
525
526 // Create synthetic tail call frames between the previous frame and the
527 // newly-found frame. The new frame's index may change after this call,
528 // although its concrete index will stay the same.
529 SynthesizeTailCallFrames(*unwind_frame_sp.get());
530
531 m_frames.push_back(unwind_frame_sp);
532 }
533
534 assert(unwind_frame_sp);
535 SymbolContext unwind_sc = unwind_frame_sp->GetSymbolContext(
536 eSymbolContextBlock | eSymbolContextFunction);
537 Block *unwind_block = unwind_sc.block;
538 TargetSP target_sp = m_thread.CalculateTarget();
539 if (unwind_block) {
540 Address curr_frame_address(
541 unwind_frame_sp->GetFrameCodeAddressForSymbolication());
542
543 SymbolContext next_frame_sc;
544 Address next_frame_address;
545
546 while (unwind_sc.GetParentOfInlinedScope(
547 curr_frame_address, next_frame_sc, next_frame_address)) {
548 next_frame_sc.line_entry.ApplyFileMappings(target_sp);
549 behaves_like_zeroth_frame = false;
550 StackFrameSP frame_sp(new StackFrame(
551 m_thread.shared_from_this(), m_frames.size(), idx,
552 unwind_frame_sp->GetRegisterContextSP(), cfa, next_frame_address,
553 behaves_like_zeroth_frame, &next_frame_sc));
554
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 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
621#if defined(DEBUG_STACK_FRAMES)
622 s.PutCString("\n\nNew frames:\n");
623 Dump(&s);
624 s.EOL();
625#endif
626}
627
629 std::lock_guard<std::recursive_mutex> guard(m_mutex);
630
631 if (can_create)
633
634 return GetVisibleStackFrameIndex(m_frames.size());
635}
636
638 if (s == nullptr)
639 return;
640
641 std::lock_guard<std::recursive_mutex> guard(m_mutex);
642
643 const_iterator pos, begin = m_frames.begin(), end = m_frames.end();
644 for (pos = begin; pos != end; ++pos) {
645 StackFrame *frame = (*pos).get();
646 s->Printf("%p: ", static_cast<void *>(frame));
647 if (frame) {
648 frame->GetStackID().Dump(s);
649 frame->DumpUsingSettingsFormat(s);
650 } else
651 s->Printf("frame #%u", (uint32_t)std::distance(begin, pos));
652 s->EOL();
653 }
654 s->EOL();
655}
656
658 StackFrameSP frame_sp;
659 std::lock_guard<std::recursive_mutex> guard(m_mutex);
660 uint32_t original_idx = idx;
661
662 uint32_t inlined_depth = GetCurrentInlinedDepth();
663 if (inlined_depth != UINT32_MAX)
664 idx += inlined_depth;
665
666 if (idx < m_frames.size())
667 frame_sp = m_frames[idx];
668
669 if (frame_sp)
670 return frame_sp;
671
672 // GetFramesUpTo will fill m_frames with as many frames as you asked for, if
673 // there are that many. If there weren't then you asked for too many frames.
674 GetFramesUpTo(idx);
675 if (idx < m_frames.size()) {
677 // When inline frames are enabled we actually create all the frames in
678 // GetFramesUpTo.
679 frame_sp = m_frames[idx];
680 } else {
681 addr_t pc, cfa;
682 bool behaves_like_zeroth_frame = (idx == 0);
684 idx, cfa, pc, behaves_like_zeroth_frame)) {
685 const bool cfa_is_valid = true;
686 frame_sp = std::make_shared<StackFrame>(
687 m_thread.shared_from_this(), idx, idx, cfa, cfa_is_valid, pc,
688 StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr);
689
690 Function *function =
691 frame_sp->GetSymbolContext(eSymbolContextFunction).function;
692 if (function) {
693 // When we aren't showing inline functions we always use the top
694 // most function block as the scope.
695 frame_sp->SetSymbolContextScope(&function->GetBlock(false));
696 } else {
697 // Set the symbol scope from the symbol regardless if it is nullptr
698 // or valid.
699 frame_sp->SetSymbolContextScope(
700 frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol);
701 }
702 SetFrameAtIndex(idx, frame_sp);
703 }
704 }
705 } else if (original_idx == 0) {
706 // There should ALWAYS be a frame at index 0. If something went wrong with
707 // the CurrentInlinedDepth such that there weren't as many frames as we
708 // thought taking that into account, then reset the current inlined depth
709 // and return the real zeroth frame.
710 if (m_frames.empty()) {
711 // Why do we have a thread with zero frames, that should not ever
712 // happen...
713 assert(!m_thread.IsValid() && "A valid thread has no frames.");
714 } else {
716 frame_sp = m_frames[original_idx];
717 }
718 }
719
720 return frame_sp;
721}
722
723StackFrameSP
725 // First try assuming the unwind index is the same as the frame index. The
726 // unwind index is always greater than or equal to the frame index, so it is
727 // a good place to start. If we have inlined frames we might have 5 concrete
728 // frames (frame unwind indexes go from 0-4), but we might have 15 frames
729 // after we make all the inlined frames. Most of the time the unwind frame
730 // index (or the concrete frame index) is the same as the frame index.
731 uint32_t frame_idx = unwind_idx;
732 StackFrameSP frame_sp(GetFrameAtIndex(frame_idx));
733 while (frame_sp) {
734 if (frame_sp->GetFrameIndex() == unwind_idx)
735 break;
736 frame_sp = GetFrameAtIndex(++frame_idx);
737 }
738 return frame_sp;
739}
740
741static bool CompareStackID(const StackFrameSP &stack_sp,
742 const StackID &stack_id) {
743 return stack_sp->GetStackID() < stack_id;
744}
745
746StackFrameSP StackFrameList::GetFrameWithStackID(const StackID &stack_id) {
747 StackFrameSP frame_sp;
748
749 if (stack_id.IsValid()) {
750 std::lock_guard<std::recursive_mutex> guard(m_mutex);
751 uint32_t frame_idx = 0;
752 // Do a binary search in case the stack frame is already in our cache
753 collection::const_iterator begin = m_frames.begin();
754 collection::const_iterator end = m_frames.end();
755 if (begin != end) {
756 collection::const_iterator pos =
757 std::lower_bound(begin, end, stack_id, CompareStackID);
758 if (pos != end) {
759 if ((*pos)->GetStackID() == stack_id)
760 return *pos;
761 }
762 }
763 do {
764 frame_sp = GetFrameAtIndex(frame_idx);
765 if (frame_sp && frame_sp->GetStackID() == stack_id)
766 break;
767 frame_idx++;
768 } while (frame_sp);
769 }
770 return frame_sp;
771}
772
773bool StackFrameList::SetFrameAtIndex(uint32_t idx, StackFrameSP &frame_sp) {
774 if (idx >= m_frames.size())
775 m_frames.resize(idx + 1);
776 // Make sure allocation succeeded by checking bounds again
777 if (idx < m_frames.size()) {
778 m_frames[idx] = frame_sp;
779 return true;
780 }
781 return false; // resize failed, out of memory?
782}
783
785 std::lock_guard<std::recursive_mutex> guard(m_mutex);
787}
788
790 std::lock_guard<std::recursive_mutex> guard(m_mutex);
791 const_iterator pos;
792 const_iterator begin = m_frames.begin();
793 const_iterator end = m_frames.end();
795 for (pos = begin; pos != end; ++pos) {
796 if (pos->get() == frame) {
797 m_selected_frame_idx = std::distance(begin, pos);
798 uint32_t inlined_depth = GetCurrentInlinedDepth();
799 if (inlined_depth != UINT32_MAX)
800 m_selected_frame_idx -= inlined_depth;
801 break;
802 }
803 }
806}
807
809 std::lock_guard<std::recursive_mutex> guard(m_mutex);
810 StackFrameSP frame_sp(GetFrameAtIndex(idx));
811 if (frame_sp) {
812 SetSelectedFrame(frame_sp.get());
813 return true;
814 } else
815 return false;
816}
817
819 if (m_thread.GetID() ==
820 m_thread.GetProcess()->GetThreadList().GetSelectedThread()->GetID()) {
821 StackFrameSP frame_sp(GetFrameAtIndex(GetSelectedFrameIndex()));
822 if (frame_sp) {
823 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextLineEntry);
824 if (sc.line_entry.file)
825 m_thread.CalculateTarget()->GetSourceManager().SetDefaultFileAndLine(
827 }
828 }
829}
830
831// The thread has been run, reset the number stack frames to zero so we can
832// determine how many frames we have lazily.
834 std::lock_guard<std::recursive_mutex> guard(m_mutex);
835 m_frames.clear();
837}
838
839lldb::StackFrameSP
841 const_iterator pos;
842 const_iterator begin = m_frames.begin();
843 const_iterator end = m_frames.end();
844 lldb::StackFrameSP ret_sp;
845
846 for (pos = begin; pos != end; ++pos) {
847 if (pos->get() == stack_frame_ptr) {
848 ret_sp = (*pos);
849 break;
850 }
851 }
852 return ret_sp;
853}
854
855size_t StackFrameList::GetStatus(Stream &strm, uint32_t first_frame,
856 uint32_t num_frames, bool show_frame_info,
857 uint32_t num_frames_with_source,
858 bool show_unique,
859 const char *selected_frame_marker) {
860 size_t num_frames_displayed = 0;
861
862 if (num_frames == 0)
863 return 0;
864
865 StackFrameSP frame_sp;
866 uint32_t frame_idx = 0;
867 uint32_t last_frame;
868
869 // Don't let the last frame wrap around...
870 if (num_frames == UINT32_MAX)
871 last_frame = UINT32_MAX;
872 else
873 last_frame = first_frame + num_frames;
874
875 StackFrameSP selected_frame_sp = m_thread.GetSelectedFrame();
876 const char *unselected_marker = nullptr;
877 std::string buffer;
878 if (selected_frame_marker) {
879 size_t len = strlen(selected_frame_marker);
880 buffer.insert(buffer.begin(), len, ' ');
881 unselected_marker = buffer.c_str();
882 }
883 const char *marker = nullptr;
884
885 for (frame_idx = first_frame; frame_idx < last_frame; ++frame_idx) {
886 frame_sp = GetFrameAtIndex(frame_idx);
887 if (!frame_sp)
888 break;
889
890 if (selected_frame_marker != nullptr) {
891 if (frame_sp == selected_frame_sp)
892 marker = selected_frame_marker;
893 else
894 marker = unselected_marker;
895 }
896
897 if (!frame_sp->GetStatus(strm, show_frame_info,
898 num_frames_with_source > (first_frame - frame_idx),
899 show_unique, marker))
900 break;
901 ++num_frames_displayed;
902 }
903
904 strm.IndentLess();
905 return num_frames_displayed;
906}
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition: Log.h:337
#define LLDB_LOGF(log,...)
Definition: Log.h:344
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 range class.
Definition: AddressRange.h:25
Address & GetBaseAddress()
Get accessor for the base address of the range.
Definition: AddressRange.h:209
A section + offset based address class.
Definition: Address.h:59
bool SetLoadAddress(lldb::addr_t load_addr, Target *target, bool allow_section_end=false)
Set the address to represent load_addr.
Definition: Address.cpp:1040
A class that describes a single lexical block.
Definition: Block.h:41
bool GetRangeContainingAddress(const Address &addr, AddressRange &range)
Definition: Block.cpp:250
Block * GetInlinedParent()
Get the inlined parent block for this block.
Definition: Block.cpp:214
General Outline: A breakpoint has four main parts, a filter, a resolver, the list of breakpoint locat...
Definition: Breakpoint.h:81
bool IsInternal() const
Tell whether this breakpoint is an "internal" breakpoint.
Definition: Breakpoint.cpp:259
Represent a call made within a Function.
Definition: Function.h:267
virtual Function * GetCallee(ModuleList &images, ExecutionContext &exe_ctx)=0
Get the callee's definition.
A class to manage flag bits.
Definition: Debugger.h:78
bool InterruptRequested()
This is the correct way to query the state of Interruption.
Definition: Debugger.cpp:1244
"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:409
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:330
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:293
void CalculateSymbolContext(SymbolContext *sc) override
Reconstruct the object's symbol context into sc.
Definition: Function.cpp:403
llvm::ArrayRef< std::unique_ptr< CallEdge > > GetTailCallingEdges()
Get the outgoing tail-calling edges from this function.
Definition: Function.cpp:323
ConstString GetDisplayName() const
Definition: Function.cpp:486
Block & GetBlock(bool can_create)
Get accessor for the block list.
Definition: Function.cpp:345
bool GetVerbose() const
Definition: Log.cpp:301
A collection class for Module objects.
Definition: ModuleList.h:82
lldb::addr_t m_current_inlined_pc
The program counter value at the currently selected synthetic activation.
collection m_frames
A cache of frames.
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, const char *frame_marker=nullptr)
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.
void Clear()
Clear the cache of frames.
lldb::StackFrameSP GetFrameAtIndex(uint32_t idx)
Get the frame at index idx. Invisible frames cannot be indexed.
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.
std::recursive_mutex m_mutex
A mutex for this frame list.
Thread & m_thread
The thread this frame list describes.
const bool m_show_inlined_frames
Whether or not to show synthetic (inline) frames. Immutable.
uint32_t m_selected_frame_idx
The currently selected frame.
bool SetFrameAtIndex(uint32_t idx, lldb::StackFrameSP &frame_sp)
void GetOnlyConcreteFramesUpTo(uint32_t end_idx, Unwind &unwinder)
void GetFramesUpTo(uint32_t end_idx)
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.
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...
uint32_t GetSelectedFrameIndex() const
Get the currently selected frame index.
StackFrameList(Thread &thread, const lldb::StackFrameListSP &prev_frames_sp, bool show_inline_frames)
void SetCurrentInlinedDepth(uint32_t new_depth)
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 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:41
void UpdatePreviousFrameFromCurrentFrame(StackFrame &curr_frame)
uint32_t GetConcreteFrameIndex() const
Query this frame to find what frame it is in this Thread's StackFrameList, not counting inlined frame...
Definition: StackFrame.h:412
void SetFrameIndex(uint32_t index)
Set this frame's synthetic frame index.
Definition: StackFrame.h:402
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.
lldb::RegisterContextSP GetRegisterContext()
Get the RegisterContext for this frame, if possible.
@ Artificial
An artificial stack frame (e.g.
@ Regular
A regular stack frame with access to registers and local variables.
const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
Definition: StackFrame.cpp:300
lldb::TargetSP CalculateTarget() override
void Dump(Stream *s)
Definition: StackID.cpp:17
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:107
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition: Stream.cpp:63
size_t EOL()
Output and End of Line character to the stream.
Definition: Stream.cpp:128
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition: Stream.cpp:171
Defines a symbol context baton that can be handed other debug core functions.
Definition: SymbolContext.h:33
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.
virtual lldb::RegisterContextSP GetRegisterContext()=0
lldb::StackFrameSP GetSelectedFrame()
Definition: Thread.cpp:267
virtual Unwind & GetUnwinder()
Definition: Thread.cpp:1882
lldb::TargetSP CalculateTarget() override
Definition: Thread.cpp:1406
lldb::ProcessSP GetProcess() const
Definition: Thread.h:153
bool IsValid() const
Definition: Thread.h:1110
lldb::StopInfoSP GetStopInfo()
Definition: Thread.cpp:336
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
Definition: lldb-defines.h:74
#define UINT32_MAX
Definition: lldb-defines.h:19
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:309
Definition: SBAddress.h:15
uint64_t addr_t
Definition: lldb-types.h:83
@ eStopReasonBreakpoint
@ eStopReasonExec
Program was re-exec'ed.
@ eStopReasonVForkDone
@ eStopReasonException
@ eStopReasonWatchpoint
@ eStopReasonVFork
@ eStopReasonSignal
A sequence of calls that comprise some portion of a backtrace.
FileSpec file
The source file, possibly mapped by the target.source-map setting.
Definition: LineEntry.h:140
uint32_t line
The source line number, or zero if there is no line number information.
Definition: LineEntry.h:143
void ApplyFileMappings(lldb::TargetSP target_sp)
Apply file mappings from target.source-map to the LineEntry's file.
Definition: LineEntry.cpp:253
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition: UserID.h:47