180814287SRaphael Isemann //===-- StackFrameList.cpp ------------------------------------------------===//
230fdc8d8SChris Lattner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
630fdc8d8SChris Lattner //
730fdc8d8SChris Lattner //===----------------------------------------------------------------------===//
830fdc8d8SChris Lattner 
9d70a6e71SEugene Zelenko #include "lldb/Target/StackFrameList.h"
10c635500dSJim Ingham #include "lldb/Breakpoint/Breakpoint.h"
11b9c1b51eSKate Stone #include "lldb/Breakpoint/BreakpointLocation.h"
12b7f6b2faSJim Ingham #include "lldb/Core/SourceManager.h"
13b9c1b51eSKate Stone #include "lldb/Core/StreamFile.h"
1412daf946SGreg Clayton #include "lldb/Symbol/Block.h"
1512daf946SGreg Clayton #include "lldb/Symbol/Function.h"
1659e8fc1cSGreg Clayton #include "lldb/Symbol/Symbol.h"
17b7f6b2faSJim Ingham #include "lldb/Target/Process.h"
1812daf946SGreg Clayton #include "lldb/Target/RegisterContext.h"
1930fdc8d8SChris Lattner #include "lldb/Target/StackFrame.h"
20513c6bb8SJim Ingham #include "lldb/Target/StopInfo.h"
21b7f6b2faSJim Ingham #include "lldb/Target/Target.h"
2212daf946SGreg Clayton #include "lldb/Target/Thread.h"
2312daf946SGreg Clayton #include "lldb/Target/Unwind.h"
246f9e6901SZachary Turner #include "lldb/Utility/Log.h"
254b36f791SVedant Kumar #include "llvm/ADT/SmallPtrSet.h"
2630fdc8d8SChris Lattner 
27796ac80bSJonas Devlieghere #include <memory>
28796ac80bSJonas Devlieghere 
295082c5fdSGreg Clayton //#define DEBUG_STACK_FRAMES 1
305082c5fdSGreg Clayton 
3130fdc8d8SChris Lattner using namespace lldb;
3230fdc8d8SChris Lattner using namespace lldb_private;
3330fdc8d8SChris Lattner 
3430fdc8d8SChris Lattner // StackFrameList constructor
35b9c1b51eSKate Stone StackFrameList::StackFrameList(Thread &thread,
36b9c1b51eSKate Stone                                const lldb::StackFrameListSP &prev_frames_sp,
37b9c1b51eSKate Stone                                bool show_inline_frames)
38b9c1b51eSKate Stone     : m_thread(thread), m_prev_frames_sp(prev_frames_sp), m_mutex(), m_frames(),
39b9c1b51eSKate Stone       m_selected_frame_idx(0), m_concrete_frames_fetched(0),
40513c6bb8SJim Ingham       m_current_inlined_depth(UINT32_MAX),
41513c6bb8SJim Ingham       m_current_inlined_pc(LLDB_INVALID_ADDRESS),
42b9c1b51eSKate Stone       m_show_inlined_frames(show_inline_frames) {
43b9c1b51eSKate Stone   if (prev_frames_sp) {
44513c6bb8SJim Ingham     m_current_inlined_depth = prev_frames_sp->m_current_inlined_depth;
45513c6bb8SJim Ingham     m_current_inlined_pc = prev_frames_sp->m_current_inlined_pc;
46513c6bb8SJim Ingham   }
4730fdc8d8SChris Lattner }
4830fdc8d8SChris Lattner 
49b9c1b51eSKate Stone StackFrameList::~StackFrameList() {
5005097246SAdrian Prantl   // Call clear since this takes a lock and clears the stack frame list in case
5105097246SAdrian Prantl   // another thread is currently using this stack frame list
52ca5ce187SGreg Clayton   Clear();
5330fdc8d8SChris Lattner }
5430fdc8d8SChris Lattner 
55b9c1b51eSKate Stone void StackFrameList::CalculateCurrentInlinedDepth() {
56513c6bb8SJim Ingham   uint32_t cur_inlined_depth = GetCurrentInlinedDepth();
57b9c1b51eSKate Stone   if (cur_inlined_depth == UINT32_MAX) {
58513c6bb8SJim Ingham     ResetCurrentInlinedDepth();
59513c6bb8SJim Ingham   }
60513c6bb8SJim Ingham }
61513c6bb8SJim Ingham 
62b9c1b51eSKate Stone uint32_t StackFrameList::GetCurrentInlinedDepth() {
63b9c1b51eSKate Stone   if (m_show_inlined_frames && m_current_inlined_pc != LLDB_INVALID_ADDRESS) {
64513c6bb8SJim Ingham     lldb::addr_t cur_pc = m_thread.GetRegisterContext()->GetPC();
65b9c1b51eSKate Stone     if (cur_pc != m_current_inlined_pc) {
66513c6bb8SJim Ingham       m_current_inlined_pc = LLDB_INVALID_ADDRESS;
67513c6bb8SJim Ingham       m_current_inlined_depth = UINT32_MAX;
685160ce5cSGreg Clayton       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
696cd41da7SJim Ingham       if (log && log->GetVerbose())
7063e5fb76SJonas Devlieghere         LLDB_LOGF(
7163e5fb76SJonas Devlieghere             log,
72b9c1b51eSKate Stone             "GetCurrentInlinedDepth: invalidating current inlined depth.\n");
73513c6bb8SJim Ingham     }
74513c6bb8SJim Ingham     return m_current_inlined_depth;
75b9c1b51eSKate Stone   } else {
76513c6bb8SJim Ingham     return UINT32_MAX;
77513c6bb8SJim Ingham   }
78513c6bb8SJim Ingham }
79513c6bb8SJim Ingham 
80b9c1b51eSKate Stone void StackFrameList::ResetCurrentInlinedDepth() {
81e7167e03SVedant Kumar   if (!m_show_inlined_frames)
82e7167e03SVedant Kumar     return;
83e7167e03SVedant Kumar 
84bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_mutex);
8547db4a2cSKeno Fischer 
86513c6bb8SJim Ingham   GetFramesUpTo(0);
87d70a6e71SEugene Zelenko   if (m_frames.empty())
8865d4d5c3SRyan Brown     return;
89b9c1b51eSKate Stone   if (!m_frames[0]->IsInlined()) {
90513c6bb8SJim Ingham     m_current_inlined_depth = UINT32_MAX;
91513c6bb8SJim Ingham     m_current_inlined_pc = LLDB_INVALID_ADDRESS;
925160ce5cSGreg Clayton     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
936cd41da7SJim Ingham     if (log && log->GetVerbose())
9463e5fb76SJonas Devlieghere       LLDB_LOGF(
9563e5fb76SJonas Devlieghere           log,
96b9c1b51eSKate Stone           "ResetCurrentInlinedDepth: Invalidating current inlined depth.\n");
97e7167e03SVedant Kumar     return;
98e7167e03SVedant Kumar   }
99e7167e03SVedant Kumar 
10005097246SAdrian Prantl   // We only need to do something special about inlined blocks when we are
10105097246SAdrian Prantl   // at the beginning of an inlined function:
102b9c1b51eSKate Stone   // FIXME: We probably also have to do something special if the PC is at
103e7167e03SVedant Kumar   // the END of an inlined function, which coincides with the end of either
104e7167e03SVedant Kumar   // its containing function or another inlined function.
105513c6bb8SJim Ingham 
106513c6bb8SJim Ingham   Block *block_ptr = m_frames[0]->GetFrameBlock();
107e7167e03SVedant Kumar   if (!block_ptr)
108e7167e03SVedant Kumar     return;
109e7167e03SVedant Kumar 
110513c6bb8SJim Ingham   Address pc_as_address;
111e7167e03SVedant Kumar   lldb::addr_t curr_pc = m_thread.GetRegisterContext()->GetPC();
112e7167e03SVedant Kumar   pc_as_address.SetLoadAddress(curr_pc, &(m_thread.GetProcess()->GetTarget()));
113513c6bb8SJim Ingham   AddressRange containing_range;
114e7167e03SVedant Kumar   if (!block_ptr->GetRangeContainingAddress(pc_as_address, containing_range) ||
115e7167e03SVedant Kumar       pc_as_address != containing_range.GetBaseAddress())
116e7167e03SVedant Kumar     return;
117e7167e03SVedant Kumar 
118e7167e03SVedant Kumar   // If we got here because of a breakpoint hit, then set the inlined depth
119e7167e03SVedant Kumar   // depending on where the breakpoint was set. If we got here because of a
120e7167e03SVedant Kumar   // crash, then set the inlined depth to the deepest most block.  Otherwise,
121e7167e03SVedant Kumar   // we stopped here naturally as the result of a step, so set ourselves in the
122e7167e03SVedant Kumar   // containing frame of the whole set of nested inlines, so the user can then
123e7167e03SVedant Kumar   // "virtually" step into the frames one by one, or next over the whole mess.
124e7167e03SVedant Kumar   // Note: We don't have to handle being somewhere in the middle of the stack
125e7167e03SVedant Kumar   // here, since ResetCurrentInlinedDepth doesn't get called if there is a
126e7167e03SVedant Kumar   // valid inlined depth set.
127513c6bb8SJim Ingham   StopInfoSP stop_info_sp = m_thread.GetStopInfo();
128e7167e03SVedant Kumar   if (!stop_info_sp)
129e7167e03SVedant Kumar     return;
130b9c1b51eSKate Stone   switch (stop_info_sp->GetStopReason()) {
131513c6bb8SJim Ingham   case eStopReasonWatchpoint:
132513c6bb8SJim Ingham   case eStopReasonException:
13390ba8115SGreg Clayton   case eStopReasonExec:
134513c6bb8SJim Ingham   case eStopReasonSignal:
135e7167e03SVedant Kumar     // In all these cases we want to stop in the deepest frame.
136513c6bb8SJim Ingham     m_current_inlined_pc = curr_pc;
137513c6bb8SJim Ingham     m_current_inlined_depth = 0;
138513c6bb8SJim Ingham     break;
139b9c1b51eSKate Stone   case eStopReasonBreakpoint: {
140e7167e03SVedant Kumar     // FIXME: Figure out what this break point is doing, and set the inline
141e7167e03SVedant Kumar     // depth appropriately.  Be careful to take into account breakpoints that
142e7167e03SVedant Kumar     // implement step over prologue, since that should do the default
143e7167e03SVedant Kumar     // calculation. For now, if the breakpoints corresponding to this hit are
144e7167e03SVedant Kumar     // all internal, I set the stop location to the top of the inlined stack,
145e7167e03SVedant Kumar     // since that will make things like stepping over prologues work right.
146e7167e03SVedant Kumar     // But if there are any non-internal breakpoints I do to the bottom of the
147e7167e03SVedant Kumar     // stack, since that was the old behavior.
148c635500dSJim Ingham     uint32_t bp_site_id = stop_info_sp->GetValue();
149b9c1b51eSKate Stone     BreakpointSiteSP bp_site_sp(
150e7167e03SVedant Kumar         m_thread.GetProcess()->GetBreakpointSiteList().FindByID(bp_site_id));
151c635500dSJim Ingham     bool all_internal = true;
152b9c1b51eSKate Stone     if (bp_site_sp) {
153c635500dSJim Ingham       uint32_t num_owners = bp_site_sp->GetNumberOfOwners();
154b9c1b51eSKate Stone       for (uint32_t i = 0; i < num_owners; i++) {
155e7167e03SVedant Kumar         Breakpoint &bp_ref = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
156b9c1b51eSKate Stone         if (!bp_ref.IsInternal()) {
157c635500dSJim Ingham           all_internal = false;
158c635500dSJim Ingham         }
159c635500dSJim Ingham       }
160c635500dSJim Ingham     }
161b9c1b51eSKate Stone     if (!all_internal) {
162c635500dSJim Ingham       m_current_inlined_pc = curr_pc;
163c635500dSJim Ingham       m_current_inlined_depth = 0;
164c635500dSJim Ingham       break;
165c635500dSJim Ingham     }
1667da851a3SJim Ingham   }
167cec91ef9SGreg Clayton     LLVM_FALLTHROUGH;
168b9c1b51eSKate Stone   default: {
169e7167e03SVedant Kumar     // Otherwise, we should set ourselves at the container of the inlining, so
170e7167e03SVedant Kumar     // that the user can descend into them. So first we check whether we have
171e7167e03SVedant Kumar     // more than one inlined block sharing this PC:
172513c6bb8SJim Ingham     int num_inlined_functions = 0;
173513c6bb8SJim Ingham 
174513c6bb8SJim Ingham     for (Block *container_ptr = block_ptr->GetInlinedParent();
175d70a6e71SEugene Zelenko          container_ptr != nullptr;
176b9c1b51eSKate Stone          container_ptr = container_ptr->GetInlinedParent()) {
177e7167e03SVedant Kumar       if (!container_ptr->GetRangeContainingAddress(pc_as_address,
178e7167e03SVedant Kumar                                                     containing_range))
179513c6bb8SJim Ingham         break;
180513c6bb8SJim Ingham       if (pc_as_address != containing_range.GetBaseAddress())
181513c6bb8SJim Ingham         break;
182513c6bb8SJim Ingham 
183513c6bb8SJim Ingham       num_inlined_functions++;
184513c6bb8SJim Ingham     }
185513c6bb8SJim Ingham     m_current_inlined_pc = curr_pc;
186513c6bb8SJim Ingham     m_current_inlined_depth = num_inlined_functions + 1;
187e7167e03SVedant Kumar     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1886cd41da7SJim Ingham     if (log && log->GetVerbose())
18963e5fb76SJonas Devlieghere       LLDB_LOGF(log,
19063e5fb76SJonas Devlieghere                 "ResetCurrentInlinedDepth: setting inlined "
191b9c1b51eSKate Stone                 "depth: %d 0x%" PRIx64 ".\n",
192b9c1b51eSKate Stone                 m_current_inlined_depth, curr_pc);
193513c6bb8SJim Ingham 
194e7167e03SVedant Kumar     break;
195513c6bb8SJim Ingham   }
196513c6bb8SJim Ingham   }
197513c6bb8SJim Ingham }
198513c6bb8SJim Ingham 
199b9c1b51eSKate Stone bool StackFrameList::DecrementCurrentInlinedDepth() {
200b9c1b51eSKate Stone   if (m_show_inlined_frames) {
201513c6bb8SJim Ingham     uint32_t current_inlined_depth = GetCurrentInlinedDepth();
202b9c1b51eSKate Stone     if (current_inlined_depth != UINT32_MAX) {
203b9c1b51eSKate Stone       if (current_inlined_depth > 0) {
204513c6bb8SJim Ingham         m_current_inlined_depth--;
205513c6bb8SJim Ingham         return true;
206513c6bb8SJim Ingham       }
207513c6bb8SJim Ingham     }
2089786eeebSJim Ingham   }
209513c6bb8SJim Ingham   return false;
210513c6bb8SJim Ingham }
211513c6bb8SJim Ingham 
212b9c1b51eSKate Stone void StackFrameList::SetCurrentInlinedDepth(uint32_t new_depth) {
2136cd41da7SJim Ingham   m_current_inlined_depth = new_depth;
2146cd41da7SJim Ingham   if (new_depth == UINT32_MAX)
2156cd41da7SJim Ingham     m_current_inlined_pc = LLDB_INVALID_ADDRESS;
2166cd41da7SJim Ingham   else
2176cd41da7SJim Ingham     m_current_inlined_pc = m_thread.GetRegisterContext()->GetPC();
2186cd41da7SJim Ingham }
2196cd41da7SJim Ingham 
220eb8fa58eSVedant Kumar void StackFrameList::GetOnlyConcreteFramesUpTo(uint32_t end_idx,
221c0b1af68SPavel Labath                                                Unwind &unwinder) {
222eb8fa58eSVedant Kumar   assert(m_thread.IsValid() && "Expected valid thread");
223eb8fa58eSVedant Kumar   assert(m_frames.size() <= end_idx && "Expected there to be frames to fill");
224eb8fa58eSVedant Kumar 
225eb8fa58eSVedant Kumar   if (end_idx < m_concrete_frames_fetched)
226eb8fa58eSVedant Kumar     return;
227eb8fa58eSVedant Kumar 
228c0b1af68SPavel Labath   uint32_t num_frames = unwinder.GetFramesUpTo(end_idx);
229eb8fa58eSVedant Kumar   if (num_frames <= end_idx + 1) {
230eb8fa58eSVedant Kumar     // Done unwinding.
231eb8fa58eSVedant Kumar     m_concrete_frames_fetched = UINT32_MAX;
232eb8fa58eSVedant Kumar   }
23333e51b14SVedant Kumar 
23433e51b14SVedant Kumar   // Don't create the frames eagerly. Defer this work to GetFrameAtIndex,
23533e51b14SVedant Kumar   // which can lazily query the unwinder to create frames.
236eb8fa58eSVedant Kumar   m_frames.resize(num_frames);
237eb8fa58eSVedant Kumar }
238eb8fa58eSVedant Kumar 
23903e29e2cSVedant Kumar /// A sequence of calls that comprise some portion of a backtrace. Each frame
24003e29e2cSVedant Kumar /// is represented as a pair of a callee (Function *) and an address within the
24103e29e2cSVedant Kumar /// callee.
242*0081149fSPavel Labath struct CallDescriptor {
243*0081149fSPavel Labath   Function *func;
244*0081149fSPavel Labath   CallEdge::AddrType address_type;
245*0081149fSPavel Labath   addr_t address;
246*0081149fSPavel Labath };
247*0081149fSPavel Labath using CallSequence = std::vector<CallDescriptor>;
24803e29e2cSVedant Kumar 
2494b36f791SVedant Kumar /// Find the unique path through the call graph from \p begin (with return PC
2504b36f791SVedant Kumar /// \p return_pc) to \p end. On success this path is stored into \p path, and
2514b36f791SVedant Kumar /// on failure \p path is unchanged.
2524b36f791SVedant Kumar static void FindInterveningFrames(Function &begin, Function &end,
2534fdbc072SVedant Kumar                                   ExecutionContext &exe_ctx, Target &target,
25403e29e2cSVedant Kumar                                   addr_t return_pc, CallSequence &path,
2554b36f791SVedant Kumar                                   ModuleList &images, Log *log) {
2564b36f791SVedant Kumar   LLDB_LOG(log, "Finding frames between {0} and {1}, retn-pc={2:x}",
2574b36f791SVedant Kumar            begin.GetDisplayName(), end.GetDisplayName(), return_pc);
2584b36f791SVedant Kumar 
2594b36f791SVedant Kumar   // Find a non-tail calling edge with the correct return PC.
2604b36f791SVedant Kumar   if (log)
2614fdbc072SVedant Kumar     for (const auto &edge : begin.GetCallEdges())
2624b36f791SVedant Kumar       LLDB_LOG(log, "FindInterveningFrames: found call with retn-PC = {0:x}",
2634fdbc072SVedant Kumar                edge->GetReturnPCAddress(begin, target));
264ff02109aSVedant Kumar   CallEdge *first_edge = begin.GetCallEdgeForReturnAddress(return_pc, target);
265ff02109aSVedant Kumar   if (!first_edge) {
2664b36f791SVedant Kumar     LLDB_LOG(log, "No call edge outgoing from {0} with retn-PC == {1:x}",
2674b36f791SVedant Kumar              begin.GetDisplayName(), return_pc);
2684b36f791SVedant Kumar     return;
2694b36f791SVedant Kumar   }
2704b36f791SVedant Kumar 
2714b36f791SVedant Kumar   // The first callee may not be resolved, or there may be nothing to fill in.
2724fdbc072SVedant Kumar   Function *first_callee = first_edge->GetCallee(images, exe_ctx);
2734b36f791SVedant Kumar   if (!first_callee) {
2744b36f791SVedant Kumar     LLDB_LOG(log, "Could not resolve callee");
2754b36f791SVedant Kumar     return;
2764b36f791SVedant Kumar   }
2774b36f791SVedant Kumar   if (first_callee == &end) {
2784b36f791SVedant Kumar     LLDB_LOG(log, "Not searching further, first callee is {0} (retn-PC: {1:x})",
2794b36f791SVedant Kumar              end.GetDisplayName(), return_pc);
2804b36f791SVedant Kumar     return;
2814b36f791SVedant Kumar   }
2824b36f791SVedant Kumar 
2834b36f791SVedant Kumar   // Run DFS on the tail-calling edges out of the first callee to find \p end.
2844b36f791SVedant Kumar   // Fully explore the set of functions reachable from the first edge via tail
2854b36f791SVedant Kumar   // calls in order to detect ambiguous executions.
2864b36f791SVedant Kumar   struct DFS {
28703e29e2cSVedant Kumar     CallSequence active_path = {};
28803e29e2cSVedant Kumar     CallSequence solution_path = {};
2894b36f791SVedant Kumar     llvm::SmallPtrSet<Function *, 2> visited_nodes = {};
2904b36f791SVedant Kumar     bool ambiguous = false;
2914b36f791SVedant Kumar     Function *end;
2924b36f791SVedant Kumar     ModuleList &images;
29303e29e2cSVedant Kumar     Target &target;
2944fdbc072SVedant Kumar     ExecutionContext &context;
2954b36f791SVedant Kumar 
29603e29e2cSVedant Kumar     DFS(Function *end, ModuleList &images, Target &target,
29703e29e2cSVedant Kumar         ExecutionContext &context)
29803e29e2cSVedant Kumar         : end(end), images(images), target(target), context(context) {}
2994b36f791SVedant Kumar 
30003e29e2cSVedant Kumar     void search(CallEdge &first_edge, Function &first_callee,
30103e29e2cSVedant Kumar                 CallSequence &path) {
30203e29e2cSVedant Kumar       dfs(first_edge, first_callee);
3034b36f791SVedant Kumar       if (!ambiguous)
3044b36f791SVedant Kumar         path = std::move(solution_path);
3054b36f791SVedant Kumar     }
3064b36f791SVedant Kumar 
30703e29e2cSVedant Kumar     void dfs(CallEdge &current_edge, Function &callee) {
3084b36f791SVedant Kumar       // Found a path to the target function.
309c03c2e88SVedant Kumar       if (&callee == end) {
3104b36f791SVedant Kumar         if (solution_path.empty())
3114b36f791SVedant Kumar           solution_path = active_path;
3124b36f791SVedant Kumar         else
3134b36f791SVedant Kumar           ambiguous = true;
3144b36f791SVedant Kumar         return;
3154b36f791SVedant Kumar       }
3164b36f791SVedant Kumar 
3174b36f791SVedant Kumar       // Terminate the search if tail recursion is found, or more generally if
3184b36f791SVedant Kumar       // there's more than one way to reach a target. This errs on the side of
3194b36f791SVedant Kumar       // caution: it conservatively stops searching when some solutions are
3204b36f791SVedant Kumar       // still possible to save time in the average case.
321c03c2e88SVedant Kumar       if (!visited_nodes.insert(&callee).second) {
3224b36f791SVedant Kumar         ambiguous = true;
3234b36f791SVedant Kumar         return;
3244b36f791SVedant Kumar       }
3254b36f791SVedant Kumar 
3264b36f791SVedant Kumar       // Search the calls made from this callee.
327*0081149fSPavel Labath       active_path.push_back(CallDescriptor{&callee});
3284fdbc072SVedant Kumar       for (const auto &edge : callee.GetTailCallingEdges()) {
3294fdbc072SVedant Kumar         Function *next_callee = edge->GetCallee(images, context);
3304b36f791SVedant Kumar         if (!next_callee)
3314b36f791SVedant Kumar           continue;
3324b36f791SVedant Kumar 
333*0081149fSPavel Labath         std::tie(active_path.back().address_type, active_path.back().address) =
334*0081149fSPavel Labath             edge->GetCallerAddress(callee, target);
33503e29e2cSVedant Kumar 
33603e29e2cSVedant Kumar         dfs(*edge, *next_callee);
3374b36f791SVedant Kumar         if (ambiguous)
3384b36f791SVedant Kumar           return;
3394b36f791SVedant Kumar       }
3404b36f791SVedant Kumar       active_path.pop_back();
3414b36f791SVedant Kumar     }
3424b36f791SVedant Kumar   };
3434b36f791SVedant Kumar 
34403e29e2cSVedant Kumar   DFS(&end, images, target, exe_ctx).search(*first_edge, *first_callee, path);
3454b36f791SVedant Kumar }
3464b36f791SVedant Kumar 
3474b36f791SVedant Kumar /// Given that \p next_frame will be appended to the frame list, synthesize
3484b36f791SVedant Kumar /// tail call frames between the current end of the list and \p next_frame.
3494b36f791SVedant Kumar /// If any frames are added, adjust the frame index of \p next_frame.
3504b36f791SVedant Kumar ///
3514b36f791SVedant Kumar ///   --------------
3524b36f791SVedant Kumar ///   |    ...     | <- Completed frames.
3534b36f791SVedant Kumar ///   --------------
3544b36f791SVedant Kumar ///   | prev_frame |
3554b36f791SVedant Kumar ///   --------------
3564b36f791SVedant Kumar ///   |    ...     | <- Artificial frames inserted here.
3574b36f791SVedant Kumar ///   --------------
3584b36f791SVedant Kumar ///   | next_frame |
3594b36f791SVedant Kumar ///   --------------
3604b36f791SVedant Kumar ///   |    ...     | <- Not-yet-visited frames.
3614b36f791SVedant Kumar ///   --------------
3624b36f791SVedant Kumar void StackFrameList::SynthesizeTailCallFrames(StackFrame &next_frame) {
363e05af081SVedant Kumar   // Cannot synthesize tail call frames when the stack is empty (there is no
364e05af081SVedant Kumar   // "previous" frame).
365e05af081SVedant Kumar   if (m_frames.empty())
366e05af081SVedant Kumar     return;
367e05af081SVedant Kumar 
3684b36f791SVedant Kumar   TargetSP target_sp = next_frame.CalculateTarget();
3694b36f791SVedant Kumar   if (!target_sp)
3704b36f791SVedant Kumar     return;
3714b36f791SVedant Kumar 
3724b36f791SVedant Kumar   lldb::RegisterContextSP next_reg_ctx_sp = next_frame.GetRegisterContext();
3734b36f791SVedant Kumar   if (!next_reg_ctx_sp)
3744b36f791SVedant Kumar     return;
3754b36f791SVedant Kumar 
3764b36f791SVedant Kumar   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3774b36f791SVedant Kumar 
3784b36f791SVedant Kumar   StackFrame &prev_frame = *m_frames.back().get();
3794b36f791SVedant Kumar 
3804b36f791SVedant Kumar   // Find the functions prev_frame and next_frame are stopped in. The function
3814b36f791SVedant Kumar   // objects are needed to search the lazy call graph for intervening frames.
3824b36f791SVedant Kumar   Function *prev_func =
3834b36f791SVedant Kumar       prev_frame.GetSymbolContext(eSymbolContextFunction).function;
3844b36f791SVedant Kumar   if (!prev_func) {
3854b36f791SVedant Kumar     LLDB_LOG(log, "SynthesizeTailCallFrames: can't find previous function");
3864b36f791SVedant Kumar     return;
3874b36f791SVedant Kumar   }
3884b36f791SVedant Kumar   Function *next_func =
3894b36f791SVedant Kumar       next_frame.GetSymbolContext(eSymbolContextFunction).function;
3904b36f791SVedant Kumar   if (!next_func) {
3914b36f791SVedant Kumar     LLDB_LOG(log, "SynthesizeTailCallFrames: can't find next function");
3924b36f791SVedant Kumar     return;
3934b36f791SVedant Kumar   }
3944b36f791SVedant Kumar 
3954b36f791SVedant Kumar   // Try to find the unique sequence of (tail) calls which led from next_frame
3964b36f791SVedant Kumar   // to prev_frame.
39703e29e2cSVedant Kumar   CallSequence path;
3984b36f791SVedant Kumar   addr_t return_pc = next_reg_ctx_sp->GetPC();
3994b36f791SVedant Kumar   Target &target = *target_sp.get();
4004b36f791SVedant Kumar   ModuleList &images = next_frame.CalculateTarget()->GetImages();
4014fdbc072SVedant Kumar   ExecutionContext exe_ctx(target_sp, /*get_process=*/true);
4024fdbc072SVedant Kumar   exe_ctx.SetFramePtr(&next_frame);
4034fdbc072SVedant Kumar   FindInterveningFrames(*next_func, *prev_func, exe_ctx, target, return_pc,
4044fdbc072SVedant Kumar                         path, images, log);
4054b36f791SVedant Kumar 
4064b36f791SVedant Kumar   // Push synthetic tail call frames.
40703e29e2cSVedant Kumar   for (auto calleeInfo : llvm::reverse(path)) {
408*0081149fSPavel Labath     Function *callee = calleeInfo.func;
4094b36f791SVedant Kumar     uint32_t frame_idx = m_frames.size();
4104b36f791SVedant Kumar     uint32_t concrete_frame_idx = next_frame.GetConcreteFrameIndex();
4114b36f791SVedant Kumar     addr_t cfa = LLDB_INVALID_ADDRESS;
4124b36f791SVedant Kumar     bool cfa_is_valid = false;
413*0081149fSPavel Labath     addr_t pc = calleeInfo.address;
414*0081149fSPavel Labath     // If the callee address refers to the call instruction, we do not want to
415*0081149fSPavel Labath     // subtract 1 from this value.
416*0081149fSPavel Labath     const bool behaves_like_zeroth_frame =
417*0081149fSPavel Labath         calleeInfo.address_type == CallEdge::AddrType::Call;
4184b36f791SVedant Kumar     SymbolContext sc;
4194b36f791SVedant Kumar     callee->CalculateSymbolContext(&sc);
4204b36f791SVedant Kumar     auto synth_frame = std::make_shared<StackFrame>(
4214b36f791SVedant Kumar         m_thread.shared_from_this(), frame_idx, concrete_frame_idx, cfa,
42231e6dbe1SJoseph Tremoulet         cfa_is_valid, pc, StackFrame::Kind::Artificial,
42331e6dbe1SJoseph Tremoulet         behaves_like_zeroth_frame, &sc);
4244b36f791SVedant Kumar     m_frames.push_back(synth_frame);
42503e29e2cSVedant Kumar     LLDB_LOG(log, "Pushed frame {0} at {1:x}", callee->GetDisplayName(), pc);
4264b36f791SVedant Kumar   }
4274b36f791SVedant Kumar 
4284b36f791SVedant Kumar   // If any frames were created, adjust next_frame's index.
4294b36f791SVedant Kumar   if (!path.empty())
4304b36f791SVedant Kumar     next_frame.SetFrameIndex(m_frames.size());
4314b36f791SVedant Kumar }
4324b36f791SVedant Kumar 
433b9c1b51eSKate Stone void StackFrameList::GetFramesUpTo(uint32_t end_idx) {
434eb8fa58eSVedant Kumar   // Do not fetch frames for an invalid thread.
435d70a6e71SEugene Zelenko   if (!m_thread.IsValid())
436ebafd2f1SEnrico Granata     return;
437ebafd2f1SEnrico Granata 
438b9c1b51eSKate Stone   // We've already gotten more frames than asked for, or we've already finished
439b9c1b51eSKate Stone   // unwinding, return.
440b0c72a5fSJim Ingham   if (m_frames.size() > end_idx || GetAllFramesFetched())
441b0c72a5fSJim Ingham     return;
44212daf946SGreg Clayton 
443c0b1af68SPavel Labath   Unwind &unwinder = m_thread.GetUnwinder();
444b0c72a5fSJim Ingham 
445eb8fa58eSVedant Kumar   if (!m_show_inlined_frames) {
446eb8fa58eSVedant Kumar     GetOnlyConcreteFramesUpTo(end_idx, unwinder);
447eb8fa58eSVedant Kumar     return;
448eb8fa58eSVedant Kumar   }
449eb8fa58eSVedant Kumar 
4505082c5fdSGreg Clayton #if defined(DEBUG_STACK_FRAMES)
4512c595273SJohnny Chen   StreamFile s(stdout, false);
4525082c5fdSGreg Clayton #endif
45305097246SAdrian Prantl   // If we are hiding some frames from the outside world, we need to add
45405097246SAdrian Prantl   // those onto the total count of frames to fetch.  However, we don't need
45505097246SAdrian Prantl   // to do that if end_idx is 0 since in that case we always get the first
45605097246SAdrian Prantl   // concrete frame and all the inlined frames below it...  And of course, if
45705097246SAdrian Prantl   // end_idx is UINT32_MAX that means get all, so just do that...
458513c6bb8SJim Ingham 
459513c6bb8SJim Ingham   uint32_t inlined_depth = 0;
460b9c1b51eSKate Stone   if (end_idx > 0 && end_idx != UINT32_MAX) {
461513c6bb8SJim Ingham     inlined_depth = GetCurrentInlinedDepth();
462b9c1b51eSKate Stone     if (inlined_depth != UINT32_MAX) {
463513c6bb8SJim Ingham       if (end_idx > 0)
464513c6bb8SJim Ingham         end_idx += inlined_depth;
465513c6bb8SJim Ingham     }
466513c6bb8SJim Ingham   }
46712daf946SGreg Clayton 
468b57e4a1bSJason Molenda   StackFrameSP unwind_frame_sp;
469b9c1b51eSKate Stone   do {
470b0c72a5fSJim Ingham     uint32_t idx = m_concrete_frames_fetched++;
4718012cadbSGreg Clayton     lldb::addr_t pc = LLDB_INVALID_ADDRESS;
4728012cadbSGreg Clayton     lldb::addr_t cfa = LLDB_INVALID_ADDRESS;
47331e6dbe1SJoseph Tremoulet     bool behaves_like_zeroth_frame = (idx == 0);
474b9c1b51eSKate Stone     if (idx == 0) {
47505097246SAdrian Prantl       // We might have already created frame zero, only create it if we need
476eb8fa58eSVedant Kumar       // to.
477b9c1b51eSKate Stone       if (m_frames.empty()) {
478b3ae8761SGreg Clayton         RegisterContextSP reg_ctx_sp(m_thread.GetRegisterContext());
479b3ae8761SGreg Clayton 
480b9c1b51eSKate Stone         if (reg_ctx_sp) {
481c0b1af68SPavel Labath           const bool success = unwinder.GetFrameInfoAtIndex(
48231e6dbe1SJoseph Tremoulet               idx, cfa, pc, behaves_like_zeroth_frame);
48305097246SAdrian Prantl           // There shouldn't be any way not to get the frame info for frame
48405097246SAdrian Prantl           // 0. But if the unwinder can't make one, lets make one by hand
485eb8fa58eSVedant Kumar           // with the SP as the CFA and see if that gets any further.
486b9c1b51eSKate Stone           if (!success) {
487b3ae8761SGreg Clayton             cfa = reg_ctx_sp->GetSP();
488b3ae8761SGreg Clayton             pc = reg_ctx_sp->GetPC();
489376c4854SJim Ingham           }
490376c4854SJim Ingham 
491796ac80bSJonas Devlieghere           unwind_frame_sp = std::make_shared<StackFrame>(
492796ac80bSJonas Devlieghere               m_thread.shared_from_this(), m_frames.size(), idx, reg_ctx_sp,
49331e6dbe1SJoseph Tremoulet               cfa, pc, behaves_like_zeroth_frame, nullptr);
4945082c5fdSGreg Clayton           m_frames.push_back(unwind_frame_sp);
4955082c5fdSGreg Clayton         }
496b9c1b51eSKate Stone       } else {
4975082c5fdSGreg Clayton         unwind_frame_sp = m_frames.front();
498b57e4a1bSJason Molenda         cfa = unwind_frame_sp->m_id.GetCallFrameAddress();
4995082c5fdSGreg Clayton       }
500b9c1b51eSKate Stone     } else {
501c0b1af68SPavel Labath       const bool success =
502c0b1af68SPavel Labath           unwinder.GetFrameInfoAtIndex(idx, cfa, pc, behaves_like_zeroth_frame);
503b9c1b51eSKate Stone       if (!success) {
504b0c72a5fSJim Ingham         // We've gotten to the end of the stack.
505b0c72a5fSJim Ingham         SetAllFramesFetched();
506b0c72a5fSJim Ingham         break;
507b0c72a5fSJim Ingham       }
50899618476SJason Molenda       const bool cfa_is_valid = true;
509796ac80bSJonas Devlieghere       unwind_frame_sp = std::make_shared<StackFrame>(
510796ac80bSJonas Devlieghere           m_thread.shared_from_this(), m_frames.size(), idx, cfa, cfa_is_valid,
51131e6dbe1SJoseph Tremoulet           pc, StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr);
5124b36f791SVedant Kumar 
5134b36f791SVedant Kumar       // Create synthetic tail call frames between the previous frame and the
5144b36f791SVedant Kumar       // newly-found frame. The new frame's index may change after this call,
5154b36f791SVedant Kumar       // although its concrete index will stay the same.
5164b36f791SVedant Kumar       SynthesizeTailCallFrames(*unwind_frame_sp.get());
5174b36f791SVedant Kumar 
5185082c5fdSGreg Clayton       m_frames.push_back(unwind_frame_sp);
51912daf946SGreg Clayton     }
52012daf946SGreg Clayton 
521ff1b5c42SEd Maste     assert(unwind_frame_sp);
522b9c1b51eSKate Stone     SymbolContext unwind_sc = unwind_frame_sp->GetSymbolContext(
523b9c1b51eSKate Stone         eSymbolContextBlock | eSymbolContextFunction);
5241ed54f50SGreg Clayton     Block *unwind_block = unwind_sc.block;
525b9c1b51eSKate Stone     if (unwind_block) {
5265f4c61e2SGreg Clayton       Address curr_frame_address(unwind_frame_sp->GetFrameCodeAddress());
527911d5784STed Woodward       TargetSP target_sp = m_thread.CalculateTarget();
52805097246SAdrian Prantl       // Be sure to adjust the frame address to match the address that was
52905097246SAdrian Prantl       // used to lookup the symbol context above. If we are in the first
53005097246SAdrian Prantl       // concrete frame, then we lookup using the current address, else we
53105097246SAdrian Prantl       // decrement the address by one to get the correct location.
532b9c1b51eSKate Stone       if (idx > 0) {
533b9c1b51eSKate Stone         if (curr_frame_address.GetOffset() == 0) {
534b9c1b51eSKate Stone           // If curr_frame_address points to the first address in a section
53505097246SAdrian Prantl           // then after adjustment it will point to an other section. In that
53605097246SAdrian Prantl           // case resolve the address again to the correct section plus
53705097246SAdrian Prantl           // offset form.
538b9c1b51eSKate Stone           addr_t load_addr = curr_frame_address.GetOpcodeLoadAddress(
53904803b3eSTatyana Krasnukha               target_sp.get(), AddressClass::eCode);
540b9c1b51eSKate Stone           curr_frame_address.SetOpcodeLoadAddress(
54104803b3eSTatyana Krasnukha               load_addr - 1, target_sp.get(), AddressClass::eCode);
542b9c1b51eSKate Stone         } else {
5435f4c61e2SGreg Clayton           curr_frame_address.Slide(-1);
5440f8452baSTamas Berghammer         }
5450f8452baSTamas Berghammer       }
5465f4c61e2SGreg Clayton 
5471ed54f50SGreg Clayton       SymbolContext next_frame_sc;
5481ed54f50SGreg Clayton       Address next_frame_address;
5491ed54f50SGreg Clayton 
550b9c1b51eSKate Stone       while (unwind_sc.GetParentOfInlinedScope(
551b9c1b51eSKate Stone           curr_frame_address, next_frame_sc, next_frame_address)) {
552911d5784STed Woodward         next_frame_sc.line_entry.ApplyFileMappings(target_sp);
55331e6dbe1SJoseph Tremoulet         behaves_like_zeroth_frame = false;
55431e6dbe1SJoseph Tremoulet         StackFrameSP frame_sp(new StackFrame(
55531e6dbe1SJoseph Tremoulet             m_thread.shared_from_this(), m_frames.size(), idx,
55631e6dbe1SJoseph Tremoulet             unwind_frame_sp->GetRegisterContextSP(), cfa, next_frame_address,
55731e6dbe1SJoseph Tremoulet             behaves_like_zeroth_frame, &next_frame_sc));
5585082c5fdSGreg Clayton 
5595082c5fdSGreg Clayton         m_frames.push_back(frame_sp);
5601ed54f50SGreg Clayton         unwind_sc = next_frame_sc;
5611ed54f50SGreg Clayton         curr_frame_address = next_frame_address;
562b0c72a5fSJim Ingham       }
563b0c72a5fSJim Ingham     }
564b0c72a5fSJim Ingham   } while (m_frames.size() - 1 < end_idx);
5651ed54f50SGreg Clayton 
566b0c72a5fSJim Ingham   // Don't try to merge till you've calculated all the frames in this stack.
567b9c1b51eSKate Stone   if (GetAllFramesFetched() && m_prev_frames_sp) {
5682cad65a5SGreg Clayton     StackFrameList *prev_frames = m_prev_frames_sp.get();
5695082c5fdSGreg Clayton     StackFrameList *curr_frames = this;
5705082c5fdSGreg Clayton 
5715082c5fdSGreg Clayton #if defined(DEBUG_STACK_FRAMES)
57268275d5eSGreg Clayton     s.PutCString("\nprev_frames:\n");
5735082c5fdSGreg Clayton     prev_frames->Dump(&s);
57468275d5eSGreg Clayton     s.PutCString("\ncurr_frames:\n");
5755082c5fdSGreg Clayton     curr_frames->Dump(&s);
5765082c5fdSGreg Clayton     s.EOL();
5775082c5fdSGreg Clayton #endif
5785082c5fdSGreg Clayton     size_t curr_frame_num, prev_frame_num;
5795082c5fdSGreg Clayton 
580b9c1b51eSKate Stone     for (curr_frame_num = curr_frames->m_frames.size(),
581b9c1b51eSKate Stone         prev_frame_num = prev_frames->m_frames.size();
5825082c5fdSGreg Clayton          curr_frame_num > 0 && prev_frame_num > 0;
583b9c1b51eSKate Stone          --curr_frame_num, --prev_frame_num) {
5845082c5fdSGreg Clayton       const size_t curr_frame_idx = curr_frame_num - 1;
5855082c5fdSGreg Clayton       const size_t prev_frame_idx = prev_frame_num - 1;
586b57e4a1bSJason Molenda       StackFrameSP curr_frame_sp(curr_frames->m_frames[curr_frame_idx]);
587b57e4a1bSJason Molenda       StackFrameSP prev_frame_sp(prev_frames->m_frames[prev_frame_idx]);
5885082c5fdSGreg Clayton 
5895082c5fdSGreg Clayton #if defined(DEBUG_STACK_FRAMES)
5902cad65a5SGreg Clayton       s.Printf("\n\nCurr frame #%u ", curr_frame_idx);
5915082c5fdSGreg Clayton       if (curr_frame_sp)
5922cad65a5SGreg Clayton         curr_frame_sp->Dump(&s, true, false);
5935082c5fdSGreg Clayton       else
5945082c5fdSGreg Clayton         s.PutCString("NULL");
5952cad65a5SGreg Clayton       s.Printf("\nPrev frame #%u ", prev_frame_idx);
5965082c5fdSGreg Clayton       if (prev_frame_sp)
5972cad65a5SGreg Clayton         prev_frame_sp->Dump(&s, true, false);
5985082c5fdSGreg Clayton       else
5995082c5fdSGreg Clayton         s.PutCString("NULL");
6005082c5fdSGreg Clayton #endif
6015082c5fdSGreg Clayton 
602b57e4a1bSJason Molenda       StackFrame *curr_frame = curr_frame_sp.get();
603b57e4a1bSJason Molenda       StackFrame *prev_frame = prev_frame_sp.get();
6045082c5fdSGreg Clayton 
605d70a6e71SEugene Zelenko       if (curr_frame == nullptr || prev_frame == nullptr)
6065082c5fdSGreg Clayton         break;
6075082c5fdSGreg Clayton 
608eb8fa58eSVedant Kumar       // Check the stack ID to make sure they are equal.
60959e8fc1cSGreg Clayton       if (curr_frame->GetStackID() != prev_frame->GetStackID())
6105082c5fdSGreg Clayton         break;
6115082c5fdSGreg Clayton 
61259e8fc1cSGreg Clayton       prev_frame->UpdatePreviousFrameFromCurrentFrame(*curr_frame);
61305097246SAdrian Prantl       // Now copy the fixed up previous frame into the current frames so the
614eb8fa58eSVedant Kumar       // pointer doesn't change.
61559e8fc1cSGreg Clayton       m_frames[curr_frame_idx] = prev_frame_sp;
6165082c5fdSGreg Clayton 
6175082c5fdSGreg Clayton #if defined(DEBUG_STACK_FRAMES)
61868275d5eSGreg Clayton       s.Printf("\n    Copying previous frame to current frame");
6195082c5fdSGreg Clayton #endif
6205082c5fdSGreg Clayton     }
621eb8fa58eSVedant Kumar     // We are done with the old stack frame list, we can release it now.
6222cad65a5SGreg Clayton     m_prev_frames_sp.reset();
6235082c5fdSGreg Clayton   }
62468275d5eSGreg Clayton 
62568275d5eSGreg Clayton #if defined(DEBUG_STACK_FRAMES)
62668275d5eSGreg Clayton   s.PutCString("\n\nNew frames:\n");
62768275d5eSGreg Clayton   Dump(&s);
62868275d5eSGreg Clayton   s.EOL();
62968275d5eSGreg Clayton #endif
630ec6829eaSGreg Clayton }
631b0c72a5fSJim Ingham 
632b9c1b51eSKate Stone uint32_t StackFrameList::GetNumFrames(bool can_create) {
633bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_mutex);
634b0c72a5fSJim Ingham 
635b0c72a5fSJim Ingham   if (can_create)
636b0c72a5fSJim Ingham     GetFramesUpTo(UINT32_MAX);
637513c6bb8SJim Ingham 
638b3b7b1bfSVedant Kumar   return GetVisibleStackFrameIndex(m_frames.size());
63930fdc8d8SChris Lattner }
64030fdc8d8SChris Lattner 
641b9c1b51eSKate Stone void StackFrameList::Dump(Stream *s) {
642d70a6e71SEugene Zelenko   if (s == nullptr)
6435082c5fdSGreg Clayton     return;
644bb19a13cSSaleem Abdulrasool 
645bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_mutex);
64630fdc8d8SChris Lattner 
6475082c5fdSGreg Clayton   const_iterator pos, begin = m_frames.begin(), end = m_frames.end();
648b9c1b51eSKate Stone   for (pos = begin; pos != end; ++pos) {
649b57e4a1bSJason Molenda     StackFrame *frame = (*pos).get();
650324a1036SSaleem Abdulrasool     s->Printf("%p: ", static_cast<void *>(frame));
651b9c1b51eSKate Stone     if (frame) {
65259e8fc1cSGreg Clayton       frame->GetStackID().Dump(s);
6530603aa9dSGreg Clayton       frame->DumpUsingSettingsFormat(s);
654b9c1b51eSKate Stone     } else
655dce502edSGreg Clayton       s->Printf("frame #%u", (uint32_t)std::distance(begin, pos));
6565082c5fdSGreg Clayton     s->EOL();
65712daf946SGreg Clayton   }
6585082c5fdSGreg Clayton   s->EOL();
6595082c5fdSGreg Clayton }
66012daf946SGreg Clayton 
661b9c1b51eSKate Stone StackFrameSP StackFrameList::GetFrameAtIndex(uint32_t idx) {
662b57e4a1bSJason Molenda   StackFrameSP frame_sp;
663bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_mutex);
6645cb9a184SJim Ingham   uint32_t original_idx = idx;
6655cb9a184SJim Ingham 
666513c6bb8SJim Ingham   uint32_t inlined_depth = GetCurrentInlinedDepth();
667513c6bb8SJim Ingham   if (inlined_depth != UINT32_MAX)
668513c6bb8SJim Ingham     idx += inlined_depth;
669513c6bb8SJim Ingham 
6705082c5fdSGreg Clayton   if (idx < m_frames.size())
6715082c5fdSGreg Clayton     frame_sp = m_frames[idx];
67212daf946SGreg Clayton 
6735082c5fdSGreg Clayton   if (frame_sp)
67412daf946SGreg Clayton     return frame_sp;
67512daf946SGreg Clayton 
67605097246SAdrian Prantl   // GetFramesUpTo will fill m_frames with as many frames as you asked for, if
67705097246SAdrian Prantl   // there are that many.  If there weren't then you asked for too many frames.
678b0c72a5fSJim Ingham   GetFramesUpTo(idx);
679b9c1b51eSKate Stone   if (idx < m_frames.size()) {
680b9c1b51eSKate Stone     if (m_show_inlined_frames) {
681b9c1b51eSKate Stone       // When inline frames are enabled we actually create all the frames in
682b9c1b51eSKate Stone       // GetFramesUpTo.
6835082c5fdSGreg Clayton       frame_sp = m_frames[idx];
684b9c1b51eSKate Stone     } else {
68512daf946SGreg Clayton       addr_t pc, cfa;
68631e6dbe1SJoseph Tremoulet       bool behaves_like_zeroth_frame = (idx == 0);
687c0b1af68SPavel Labath       if (m_thread.GetUnwinder().GetFrameInfoAtIndex(
688c0b1af68SPavel Labath               idx, cfa, pc, behaves_like_zeroth_frame)) {
68999618476SJason Molenda         const bool cfa_is_valid = true;
690796ac80bSJonas Devlieghere         frame_sp = std::make_shared<StackFrame>(
691796ac80bSJonas Devlieghere             m_thread.shared_from_this(), idx, idx, cfa, cfa_is_valid, pc,
69231e6dbe1SJoseph Tremoulet             StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr);
69359e8fc1cSGreg Clayton 
694b9c1b51eSKate Stone         Function *function =
695b9c1b51eSKate Stone             frame_sp->GetSymbolContext(eSymbolContextFunction).function;
696b9c1b51eSKate Stone         if (function) {
69705097246SAdrian Prantl           // When we aren't showing inline functions we always use the top
69805097246SAdrian Prantl           // most function block as the scope.
69959e8fc1cSGreg Clayton           frame_sp->SetSymbolContextScope(&function->GetBlock(false));
700b9c1b51eSKate Stone         } else {
701b9c1b51eSKate Stone           // Set the symbol scope from the symbol regardless if it is nullptr
702b9c1b51eSKate Stone           // or valid.
703b9c1b51eSKate Stone           frame_sp->SetSymbolContextScope(
704b9c1b51eSKate Stone               frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol);
70559e8fc1cSGreg Clayton         }
7065082c5fdSGreg Clayton         SetFrameAtIndex(idx, frame_sp);
70712daf946SGreg Clayton       }
70812daf946SGreg Clayton     }
709b9c1b51eSKate Stone   } else if (original_idx == 0) {
710b9c1b51eSKate Stone     // There should ALWAYS be a frame at index 0.  If something went wrong with
71105097246SAdrian Prantl     // the CurrentInlinedDepth such that there weren't as many frames as we
71205097246SAdrian Prantl     // thought taking that into account, then reset the current inlined depth
7135cb9a184SJim Ingham     // and return the real zeroth frame.
714b9c1b51eSKate Stone     if (m_frames.empty()) {
715b9c1b51eSKate Stone       // Why do we have a thread with zero frames, that should not ever
716b9c1b51eSKate Stone       // happen...
717a322f36cSDavid Blaikie       assert(!m_thread.IsValid() && "A valid thread has no frames.");
718b9c1b51eSKate Stone     } else {
719d70a6e71SEugene Zelenko       ResetCurrentInlinedDepth();
720d70a6e71SEugene Zelenko       frame_sp = m_frames[original_idx];
7215cb9a184SJim Ingham     }
7225cb9a184SJim Ingham   }
7235cb9a184SJim Ingham 
72430fdc8d8SChris Lattner   return frame_sp;
72530fdc8d8SChris Lattner }
72630fdc8d8SChris Lattner 
727b57e4a1bSJason Molenda StackFrameSP
728b9c1b51eSKate Stone StackFrameList::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) {
7295ccbd294SGreg Clayton   // First try assuming the unwind index is the same as the frame index. The
73005097246SAdrian Prantl   // unwind index is always greater than or equal to the frame index, so it is
73105097246SAdrian Prantl   // a good place to start. If we have inlined frames we might have 5 concrete
73205097246SAdrian Prantl   // frames (frame unwind indexes go from 0-4), but we might have 15 frames
73305097246SAdrian Prantl   // after we make all the inlined frames. Most of the time the unwind frame
73405097246SAdrian Prantl   // index (or the concrete frame index) is the same as the frame index.
7355ccbd294SGreg Clayton   uint32_t frame_idx = unwind_idx;
736b57e4a1bSJason Molenda   StackFrameSP frame_sp(GetFrameAtIndex(frame_idx));
737b9c1b51eSKate Stone   while (frame_sp) {
7385ccbd294SGreg Clayton     if (frame_sp->GetFrameIndex() == unwind_idx)
7395ccbd294SGreg Clayton       break;
7405ccbd294SGreg Clayton     frame_sp = GetFrameAtIndex(++frame_idx);
7415ccbd294SGreg Clayton   }
7425ccbd294SGreg Clayton   return frame_sp;
7435ccbd294SGreg Clayton }
7445ccbd294SGreg Clayton 
745b9c1b51eSKate Stone static bool CompareStackID(const StackFrameSP &stack_sp,
746b9c1b51eSKate Stone                            const StackID &stack_id) {
7477bcb93d5SGreg Clayton   return stack_sp->GetStackID() < stack_id;
7487bcb93d5SGreg Clayton }
7497bcb93d5SGreg Clayton 
750b9c1b51eSKate Stone StackFrameSP StackFrameList::GetFrameWithStackID(const StackID &stack_id) {
751b57e4a1bSJason Molenda   StackFrameSP frame_sp;
7527bcb93d5SGreg Clayton 
753b9c1b51eSKate Stone   if (stack_id.IsValid()) {
754bb19a13cSSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(m_mutex);
7557bcb93d5SGreg Clayton     uint32_t frame_idx = 0;
7567bcb93d5SGreg Clayton     // Do a binary search in case the stack frame is already in our cache
7577bcb93d5SGreg Clayton     collection::const_iterator begin = m_frames.begin();
7587bcb93d5SGreg Clayton     collection::const_iterator end = m_frames.end();
759b9c1b51eSKate Stone     if (begin != end) {
760b9c1b51eSKate Stone       collection::const_iterator pos =
761b9c1b51eSKate Stone           std::lower_bound(begin, end, stack_id, CompareStackID);
762b9c1b51eSKate Stone       if (pos != end) {
7638012cadbSGreg Clayton         if ((*pos)->GetStackID() == stack_id)
7647bcb93d5SGreg Clayton           return *pos;
7658012cadbSGreg Clayton       }
7667bcb93d5SGreg Clayton     }
767b9c1b51eSKate Stone     do {
7683a195b7eSJim Ingham       frame_sp = GetFrameAtIndex(frame_idx);
7693a195b7eSJim Ingham       if (frame_sp && frame_sp->GetStackID() == stack_id)
7703a195b7eSJim Ingham         break;
7713a195b7eSJim Ingham       frame_idx++;
772b9c1b51eSKate Stone     } while (frame_sp);
7737bcb93d5SGreg Clayton   }
7743a195b7eSJim Ingham   return frame_sp;
7753a195b7eSJim Ingham }
7765ccbd294SGreg Clayton 
777b9c1b51eSKate Stone bool StackFrameList::SetFrameAtIndex(uint32_t idx, StackFrameSP &frame_sp) {
7785082c5fdSGreg Clayton   if (idx >= m_frames.size())
7795082c5fdSGreg Clayton     m_frames.resize(idx + 1);
78012daf946SGreg Clayton   // Make sure allocation succeeded by checking bounds again
781b9c1b51eSKate Stone   if (idx < m_frames.size()) {
7825082c5fdSGreg Clayton     m_frames[idx] = frame_sp;
78330fdc8d8SChris Lattner     return true;
78430fdc8d8SChris Lattner   }
78530fdc8d8SChris Lattner   return false; // resize failed, out of memory?
78630fdc8d8SChris Lattner }
78730fdc8d8SChris Lattner 
788b9c1b51eSKate Stone uint32_t StackFrameList::GetSelectedFrameIndex() const {
789bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_mutex);
7902976d00aSJim Ingham   return m_selected_frame_idx;
79130fdc8d8SChris Lattner }
79230fdc8d8SChris Lattner 
793b9c1b51eSKate Stone uint32_t StackFrameList::SetSelectedFrame(lldb_private::StackFrame *frame) {
794bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_mutex);
79512daf946SGreg Clayton   const_iterator pos;
7965082c5fdSGreg Clayton   const_iterator begin = m_frames.begin();
7975082c5fdSGreg Clayton   const_iterator end = m_frames.end();
798b7f6b2faSJim Ingham   m_selected_frame_idx = 0;
799b9c1b51eSKate Stone   for (pos = begin; pos != end; ++pos) {
800b9c1b51eSKate Stone     if (pos->get() == frame) {
8012976d00aSJim Ingham       m_selected_frame_idx = std::distance(begin, pos);
802513c6bb8SJim Ingham       uint32_t inlined_depth = GetCurrentInlinedDepth();
803513c6bb8SJim Ingham       if (inlined_depth != UINT32_MAX)
804513c6bb8SJim Ingham         m_selected_frame_idx -= inlined_depth;
805b7f6b2faSJim Ingham       break;
80630fdc8d8SChris Lattner     }
80730fdc8d8SChris Lattner   }
808b7f6b2faSJim Ingham   SetDefaultFileAndLineToSelectedFrame();
8092976d00aSJim Ingham   return m_selected_frame_idx;
81030fdc8d8SChris Lattner }
81130fdc8d8SChris Lattner 
812b9c1b51eSKate Stone bool StackFrameList::SetSelectedFrameByIndex(uint32_t idx) {
813bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_mutex);
814b57e4a1bSJason Molenda   StackFrameSP frame_sp(GetFrameAtIndex(idx));
815b9c1b51eSKate Stone   if (frame_sp) {
816b0c72a5fSJim Ingham     SetSelectedFrame(frame_sp.get());
817b0c72a5fSJim Ingham     return true;
818b9c1b51eSKate Stone   } else
819b0c72a5fSJim Ingham     return false;
820b7f6b2faSJim Ingham }
821b7f6b2faSJim Ingham 
822b9c1b51eSKate Stone void StackFrameList::SetDefaultFileAndLineToSelectedFrame() {
823b9c1b51eSKate Stone   if (m_thread.GetID() ==
824b9c1b51eSKate Stone       m_thread.GetProcess()->GetThreadList().GetSelectedThread()->GetID()) {
825b57e4a1bSJason Molenda     StackFrameSP frame_sp(GetFrameAtIndex(GetSelectedFrameIndex()));
826b9c1b51eSKate Stone     if (frame_sp) {
827252d0edeSGreg Clayton       SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextLineEntry);
828b7f6b2faSJim Ingham       if (sc.line_entry.file)
829b9c1b51eSKate Stone         m_thread.CalculateTarget()->GetSourceManager().SetDefaultFileAndLine(
830b9c1b51eSKate Stone             sc.line_entry.file, sc.line_entry.line);
831b7f6b2faSJim Ingham     }
832b7f6b2faSJim Ingham   }
83330fdc8d8SChris Lattner }
83430fdc8d8SChris Lattner 
83530fdc8d8SChris Lattner // The thread has been run, reset the number stack frames to zero so we can
83630fdc8d8SChris Lattner // determine how many frames we have lazily.
837b9c1b51eSKate Stone void StackFrameList::Clear() {
838bb19a13cSSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_mutex);
8395082c5fdSGreg Clayton   m_frames.clear();
840b0c72a5fSJim Ingham   m_concrete_frames_fetched = 0;
84130fdc8d8SChris Lattner }
84230fdc8d8SChris Lattner 
843d5b44036SJonas Devlieghere void StackFrameList::Merge(std::unique_ptr<StackFrameList> &curr_up,
844b9c1b51eSKate Stone                            lldb::StackFrameListSP &prev_sp) {
845bb19a13cSSaleem Abdulrasool   std::unique_lock<std::recursive_mutex> current_lock, previous_lock;
846d5b44036SJonas Devlieghere   if (curr_up)
847d5b44036SJonas Devlieghere     current_lock = std::unique_lock<std::recursive_mutex>(curr_up->m_mutex);
848bb19a13cSSaleem Abdulrasool   if (prev_sp)
849bb19a13cSSaleem Abdulrasool     previous_lock = std::unique_lock<std::recursive_mutex>(prev_sp->m_mutex);
8502cad65a5SGreg Clayton 
8512cad65a5SGreg Clayton #if defined(DEBUG_STACK_FRAMES)
8522c595273SJohnny Chen   StreamFile s(stdout, false);
8532cad65a5SGreg Clayton   s.PutCString("\n\nStackFrameList::Merge():\nPrev:\n");
854d70a6e71SEugene Zelenko   if (prev_sp)
8552cad65a5SGreg Clayton     prev_sp->Dump(&s);
8562cad65a5SGreg Clayton   else
8572cad65a5SGreg Clayton     s.PutCString("NULL");
8582cad65a5SGreg Clayton   s.PutCString("\nCurr:\n");
859d5b44036SJonas Devlieghere   if (curr_up)
860d5b44036SJonas Devlieghere     curr_up->Dump(&s);
8612cad65a5SGreg Clayton   else
8622cad65a5SGreg Clayton     s.PutCString("NULL");
8632cad65a5SGreg Clayton   s.EOL();
8642cad65a5SGreg Clayton #endif
8652cad65a5SGreg Clayton 
866d5b44036SJonas Devlieghere   if (!curr_up || curr_up->GetNumFrames(false) == 0) {
8672cad65a5SGreg Clayton #if defined(DEBUG_STACK_FRAMES)
8682cad65a5SGreg Clayton     s.PutCString("No current frames, leave previous frames alone...\n");
8692cad65a5SGreg Clayton #endif
870d5b44036SJonas Devlieghere     curr_up.release();
8712cad65a5SGreg Clayton     return;
8722cad65a5SGreg Clayton   }
8732cad65a5SGreg Clayton 
874b9c1b51eSKate Stone   if (!prev_sp || prev_sp->GetNumFrames(false) == 0) {
8752cad65a5SGreg Clayton #if defined(DEBUG_STACK_FRAMES)
8762cad65a5SGreg Clayton     s.PutCString("No previous frames, so use current frames...\n");
8772cad65a5SGreg Clayton #endif
87805097246SAdrian Prantl     // We either don't have any previous frames, or since we have more than one
87905097246SAdrian Prantl     // current frames it means we have all the frames and can safely replace
88005097246SAdrian Prantl     // our previous frames.
881d5b44036SJonas Devlieghere     prev_sp.reset(curr_up.release());
8822cad65a5SGreg Clayton     return;
8832cad65a5SGreg Clayton   }
8842cad65a5SGreg Clayton 
885d5b44036SJonas Devlieghere   const uint32_t num_curr_frames = curr_up->GetNumFrames(false);
8862cad65a5SGreg Clayton 
887b9c1b51eSKate Stone   if (num_curr_frames > 1) {
8882cad65a5SGreg Clayton #if defined(DEBUG_STACK_FRAMES)
889b9c1b51eSKate Stone     s.PutCString(
890b9c1b51eSKate Stone         "We have more than one current frame, so use current frames...\n");
8912cad65a5SGreg Clayton #endif
89205097246SAdrian Prantl     // We have more than one current frames it means we have all the frames and
89305097246SAdrian Prantl     // can safely replace our previous frames.
894d5b44036SJonas Devlieghere     prev_sp.reset(curr_up.release());
8952cad65a5SGreg Clayton 
8962cad65a5SGreg Clayton #if defined(DEBUG_STACK_FRAMES)
8972cad65a5SGreg Clayton     s.PutCString("\nMerged:\n");
8982cad65a5SGreg Clayton     prev_sp->Dump(&s);
8992cad65a5SGreg Clayton #endif
9002cad65a5SGreg Clayton     return;
9012cad65a5SGreg Clayton   }
9022cad65a5SGreg Clayton 
903b57e4a1bSJason Molenda   StackFrameSP prev_frame_zero_sp(prev_sp->GetFrameAtIndex(0));
904d5b44036SJonas Devlieghere   StackFrameSP curr_frame_zero_sp(curr_up->GetFrameAtIndex(0));
9052cad65a5SGreg Clayton   StackID curr_stack_id(curr_frame_zero_sp->GetStackID());
9062cad65a5SGreg Clayton   StackID prev_stack_id(prev_frame_zero_sp->GetStackID());
9072cad65a5SGreg Clayton 
9082cad65a5SGreg Clayton #if defined(DEBUG_STACK_FRAMES)
9092c595273SJohnny Chen   const uint32_t num_prev_frames = prev_sp->GetNumFrames(false);
9102cad65a5SGreg Clayton   s.Printf("\n%u previous frames with one current frame\n", num_prev_frames);
9112cad65a5SGreg Clayton #endif
9122cad65a5SGreg Clayton 
9132cad65a5SGreg Clayton   // We have only a single current frame
9142cad65a5SGreg Clayton   // Our previous stack frames only had a single frame as well...
915b9c1b51eSKate Stone   if (curr_stack_id == prev_stack_id) {
9162cad65a5SGreg Clayton #if defined(DEBUG_STACK_FRAMES)
917b9c1b51eSKate Stone     s.Printf("\nPrevious frame #0 is same as current frame #0, merge the "
918b9c1b51eSKate Stone              "cached data\n");
9192cad65a5SGreg Clayton #endif
9202cad65a5SGreg Clayton 
921b9c1b51eSKate Stone     curr_frame_zero_sp->UpdateCurrentFrameFromPreviousFrame(
922b9c1b51eSKate Stone         *prev_frame_zero_sp);
923b9c1b51eSKate Stone     //        prev_frame_zero_sp->UpdatePreviousFrameFromCurrentFrame
924b9c1b51eSKate Stone     //        (*curr_frame_zero_sp);
9252cad65a5SGreg Clayton     //        prev_sp->SetFrameAtIndex (0, prev_frame_zero_sp);
926b9c1b51eSKate Stone   } else if (curr_stack_id < prev_stack_id) {
9272cad65a5SGreg Clayton #if defined(DEBUG_STACK_FRAMES)
928b9c1b51eSKate Stone     s.Printf("\nCurrent frame #0 has a stack ID that is less than the previous "
929b9c1b51eSKate Stone              "frame #0, insert current frame zero in front of previous\n");
9302cad65a5SGreg Clayton #endif
9312cad65a5SGreg Clayton     prev_sp->m_frames.insert(prev_sp->m_frames.begin(), curr_frame_zero_sp);
9322cad65a5SGreg Clayton   }
9332cad65a5SGreg Clayton 
934d5b44036SJonas Devlieghere   curr_up.release();
9352cad65a5SGreg Clayton 
9362cad65a5SGreg Clayton #if defined(DEBUG_STACK_FRAMES)
9372cad65a5SGreg Clayton   s.PutCString("\nMerged:\n");
9382cad65a5SGreg Clayton   prev_sp->Dump(&s);
9392cad65a5SGreg Clayton #endif
9402cad65a5SGreg Clayton }
941e4284b71SJim Ingham 
942b57e4a1bSJason Molenda lldb::StackFrameSP
943b9c1b51eSKate Stone StackFrameList::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) {
944e4284b71SJim Ingham   const_iterator pos;
945e4284b71SJim Ingham   const_iterator begin = m_frames.begin();
946e4284b71SJim Ingham   const_iterator end = m_frames.end();
947b57e4a1bSJason Molenda   lldb::StackFrameSP ret_sp;
948e4284b71SJim Ingham 
949b9c1b51eSKate Stone   for (pos = begin; pos != end; ++pos) {
950b9c1b51eSKate Stone     if (pos->get() == stack_frame_ptr) {
951e4284b71SJim Ingham       ret_sp = (*pos);
952e4284b71SJim Ingham       break;
953e4284b71SJim Ingham     }
954e4284b71SJim Ingham   }
955e4284b71SJim Ingham   return ret_sp;
956e4284b71SJim Ingham }
957e4284b71SJim Ingham 
958b9c1b51eSKate Stone size_t StackFrameList::GetStatus(Stream &strm, uint32_t first_frame,
959b9c1b51eSKate Stone                                  uint32_t num_frames, bool show_frame_info,
9608ec10efcSJim Ingham                                  uint32_t num_frames_with_source,
9617f1c1211SPavel Labath                                  bool show_unique,
962b9c1b51eSKate Stone                                  const char *selected_frame_marker) {
9637260f620SGreg Clayton   size_t num_frames_displayed = 0;
9647260f620SGreg Clayton 
9657260f620SGreg Clayton   if (num_frames == 0)
9667260f620SGreg Clayton     return 0;
9677260f620SGreg Clayton 
968b57e4a1bSJason Molenda   StackFrameSP frame_sp;
9697260f620SGreg Clayton   uint32_t frame_idx = 0;
9707260f620SGreg Clayton   uint32_t last_frame;
9717260f620SGreg Clayton 
9727260f620SGreg Clayton   // Don't let the last frame wrap around...
9737260f620SGreg Clayton   if (num_frames == UINT32_MAX)
9747260f620SGreg Clayton     last_frame = UINT32_MAX;
9757260f620SGreg Clayton   else
9767260f620SGreg Clayton     last_frame = first_frame + num_frames;
9777260f620SGreg Clayton 
978b57e4a1bSJason Molenda   StackFrameSP selected_frame_sp = m_thread.GetSelectedFrame();
979d70a6e71SEugene Zelenko   const char *unselected_marker = nullptr;
9808ec10efcSJim Ingham   std::string buffer;
981b9c1b51eSKate Stone   if (selected_frame_marker) {
9828ec10efcSJim Ingham     size_t len = strlen(selected_frame_marker);
9838ec10efcSJim Ingham     buffer.insert(buffer.begin(), len, ' ');
9848ec10efcSJim Ingham     unselected_marker = buffer.c_str();
9858ec10efcSJim Ingham   }
986d70a6e71SEugene Zelenko   const char *marker = nullptr;
9878ec10efcSJim Ingham 
988b9c1b51eSKate Stone   for (frame_idx = first_frame; frame_idx < last_frame; ++frame_idx) {
9897260f620SGreg Clayton     frame_sp = GetFrameAtIndex(frame_idx);
990d70a6e71SEugene Zelenko     if (!frame_sp)
9917260f620SGreg Clayton       break;
9927260f620SGreg Clayton 
993b9c1b51eSKate Stone     if (selected_frame_marker != nullptr) {
9948ec10efcSJim Ingham       if (frame_sp == selected_frame_sp)
9958ec10efcSJim Ingham         marker = selected_frame_marker;
9968ec10efcSJim Ingham       else
9978ec10efcSJim Ingham         marker = unselected_marker;
9988ec10efcSJim Ingham     }
9998ec10efcSJim Ingham 
1000b9c1b51eSKate Stone     if (!frame_sp->GetStatus(strm, show_frame_info,
1001b9c1b51eSKate Stone                              num_frames_with_source > (first_frame - frame_idx),
10027f1c1211SPavel Labath                              show_unique, marker))
10037260f620SGreg Clayton       break;
10047260f620SGreg Clayton     ++num_frames_displayed;
10057260f620SGreg Clayton   }
10067260f620SGreg Clayton 
10077260f620SGreg Clayton   strm.IndentLess();
10087260f620SGreg Clayton   return num_frames_displayed;
10097260f620SGreg Clayton }
1010