1 //===-- StackFrameList.cpp --------------------------------------*- C++ -*-===//
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 
9 #include "lldb/Target/StackFrameList.h"
10 #include "lldb/Breakpoint/Breakpoint.h"
11 #include "lldb/Breakpoint/BreakpointLocation.h"
12 #include "lldb/Core/SourceManager.h"
13 #include "lldb/Core/StreamFile.h"
14 #include "lldb/Symbol/Block.h"
15 #include "lldb/Symbol/Function.h"
16 #include "lldb/Symbol/Symbol.h"
17 #include "lldb/Target/Process.h"
18 #include "lldb/Target/RegisterContext.h"
19 #include "lldb/Target/StackFrame.h"
20 #include "lldb/Target/StopInfo.h"
21 #include "lldb/Target/Target.h"
22 #include "lldb/Target/Thread.h"
23 #include "lldb/Target/Unwind.h"
24 #include "lldb/Utility/Log.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 
27 #include <memory>
28 
29 //#define DEBUG_STACK_FRAMES 1
30 
31 using namespace lldb;
32 using namespace lldb_private;
33 
34 // StackFrameList constructor
35 StackFrameList::StackFrameList(Thread &thread,
36                                const lldb::StackFrameListSP &prev_frames_sp,
37                                bool show_inline_frames)
38     : m_thread(thread), m_prev_frames_sp(prev_frames_sp), m_mutex(), m_frames(),
39       m_selected_frame_idx(0), m_concrete_frames_fetched(0),
40       m_current_inlined_depth(UINT32_MAX),
41       m_current_inlined_pc(LLDB_INVALID_ADDRESS),
42       m_show_inlined_frames(show_inline_frames) {
43   if (prev_frames_sp) {
44     m_current_inlined_depth = prev_frames_sp->m_current_inlined_depth;
45     m_current_inlined_pc = prev_frames_sp->m_current_inlined_pc;
46   }
47 }
48 
49 StackFrameList::~StackFrameList() {
50   // Call clear since this takes a lock and clears the stack frame list in case
51   // another thread is currently using this stack frame list
52   Clear();
53 }
54 
55 void StackFrameList::CalculateCurrentInlinedDepth() {
56   uint32_t cur_inlined_depth = GetCurrentInlinedDepth();
57   if (cur_inlined_depth == UINT32_MAX) {
58     ResetCurrentInlinedDepth();
59   }
60 }
61 
62 uint32_t StackFrameList::GetCurrentInlinedDepth() {
63   if (m_show_inlined_frames && m_current_inlined_pc != LLDB_INVALID_ADDRESS) {
64     lldb::addr_t cur_pc = m_thread.GetRegisterContext()->GetPC();
65     if (cur_pc != m_current_inlined_pc) {
66       m_current_inlined_pc = LLDB_INVALID_ADDRESS;
67       m_current_inlined_depth = UINT32_MAX;
68       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
69       if (log && log->GetVerbose())
70         LLDB_LOGF(
71             log,
72             "GetCurrentInlinedDepth: invalidating current inlined depth.\n");
73     }
74     return m_current_inlined_depth;
75   } else {
76     return UINT32_MAX;
77   }
78 }
79 
80 void StackFrameList::ResetCurrentInlinedDepth() {
81   if (!m_show_inlined_frames)
82     return;
83 
84   std::lock_guard<std::recursive_mutex> guard(m_mutex);
85 
86   GetFramesUpTo(0);
87   if (m_frames.empty())
88     return;
89   if (!m_frames[0]->IsInlined()) {
90     m_current_inlined_depth = UINT32_MAX;
91     m_current_inlined_pc = LLDB_INVALID_ADDRESS;
92     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
93     if (log && log->GetVerbose())
94       LLDB_LOGF(
95           log,
96           "ResetCurrentInlinedDepth: Invalidating current inlined depth.\n");
97     return;
98   }
99 
100   // We only need to do something special about inlined blocks when we are
101   // at the beginning of an inlined function:
102   // FIXME: We probably also have to do something special if the PC is at
103   // the END of an inlined function, which coincides with the end of either
104   // its containing function or another inlined function.
105 
106   Block *block_ptr = m_frames[0]->GetFrameBlock();
107   if (!block_ptr)
108     return;
109 
110   Address pc_as_address;
111   lldb::addr_t curr_pc = m_thread.GetRegisterContext()->GetPC();
112   pc_as_address.SetLoadAddress(curr_pc, &(m_thread.GetProcess()->GetTarget()));
113   AddressRange containing_range;
114   if (!block_ptr->GetRangeContainingAddress(pc_as_address, containing_range) ||
115       pc_as_address != containing_range.GetBaseAddress())
116     return;
117 
118   // If we got here because of a breakpoint hit, then set the inlined depth
119   // depending on where the breakpoint was set. If we got here because of a
120   // crash, then set the inlined depth to the deepest most block.  Otherwise,
121   // we stopped here naturally as the result of a step, so set ourselves in the
122   // containing frame of the whole set of nested inlines, so the user can then
123   // "virtually" step into the frames one by one, or next over the whole mess.
124   // Note: We don't have to handle being somewhere in the middle of the stack
125   // here, since ResetCurrentInlinedDepth doesn't get called if there is a
126   // valid inlined depth set.
127   StopInfoSP stop_info_sp = m_thread.GetStopInfo();
128   if (!stop_info_sp)
129     return;
130   switch (stop_info_sp->GetStopReason()) {
131   case eStopReasonWatchpoint:
132   case eStopReasonException:
133   case eStopReasonExec:
134   case eStopReasonSignal:
135     // In all these cases we want to stop in the deepest frame.
136     m_current_inlined_pc = curr_pc;
137     m_current_inlined_depth = 0;
138     break;
139   case eStopReasonBreakpoint: {
140     // FIXME: Figure out what this break point is doing, and set the inline
141     // depth appropriately.  Be careful to take into account breakpoints that
142     // implement step over prologue, since that should do the default
143     // calculation. For now, if the breakpoints corresponding to this hit are
144     // all internal, I set the stop location to the top of the inlined stack,
145     // since that will make things like stepping over prologues work right.
146     // But if there are any non-internal breakpoints I do to the bottom of the
147     // stack, since that was the old behavior.
148     uint32_t bp_site_id = stop_info_sp->GetValue();
149     BreakpointSiteSP bp_site_sp(
150         m_thread.GetProcess()->GetBreakpointSiteList().FindByID(bp_site_id));
151     bool all_internal = true;
152     if (bp_site_sp) {
153       uint32_t num_owners = bp_site_sp->GetNumberOfOwners();
154       for (uint32_t i = 0; i < num_owners; i++) {
155         Breakpoint &bp_ref = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
156         if (!bp_ref.IsInternal()) {
157           all_internal = false;
158         }
159       }
160     }
161     if (!all_internal) {
162       m_current_inlined_pc = curr_pc;
163       m_current_inlined_depth = 0;
164       break;
165     }
166   }
167     LLVM_FALLTHROUGH;
168   default: {
169     // Otherwise, we should set ourselves at the container of the inlining, so
170     // that the user can descend into them. So first we check whether we have
171     // more than one inlined block sharing this PC:
172     int num_inlined_functions = 0;
173 
174     for (Block *container_ptr = block_ptr->GetInlinedParent();
175          container_ptr != nullptr;
176          container_ptr = container_ptr->GetInlinedParent()) {
177       if (!container_ptr->GetRangeContainingAddress(pc_as_address,
178                                                     containing_range))
179         break;
180       if (pc_as_address != containing_range.GetBaseAddress())
181         break;
182 
183       num_inlined_functions++;
184     }
185     m_current_inlined_pc = curr_pc;
186     m_current_inlined_depth = num_inlined_functions + 1;
187     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
188     if (log && log->GetVerbose())
189       LLDB_LOGF(log,
190                 "ResetCurrentInlinedDepth: setting inlined "
191                 "depth: %d 0x%" PRIx64 ".\n",
192                 m_current_inlined_depth, curr_pc);
193 
194     break;
195   }
196   }
197 }
198 
199 bool StackFrameList::DecrementCurrentInlinedDepth() {
200   if (m_show_inlined_frames) {
201     uint32_t current_inlined_depth = GetCurrentInlinedDepth();
202     if (current_inlined_depth != UINT32_MAX) {
203       if (current_inlined_depth > 0) {
204         m_current_inlined_depth--;
205         return true;
206       }
207     }
208   }
209   return false;
210 }
211 
212 void StackFrameList::SetCurrentInlinedDepth(uint32_t new_depth) {
213   m_current_inlined_depth = new_depth;
214   if (new_depth == UINT32_MAX)
215     m_current_inlined_pc = LLDB_INVALID_ADDRESS;
216   else
217     m_current_inlined_pc = m_thread.GetRegisterContext()->GetPC();
218 }
219 
220 void StackFrameList::GetOnlyConcreteFramesUpTo(uint32_t end_idx,
221                                                Unwind *unwinder) {
222   assert(m_thread.IsValid() && "Expected valid thread");
223   assert(m_frames.size() <= end_idx && "Expected there to be frames to fill");
224 
225   if (end_idx < m_concrete_frames_fetched)
226     return;
227 
228   if (!unwinder)
229     return;
230 
231   uint32_t num_frames = unwinder->GetFramesUpTo(end_idx);
232   if (num_frames <= end_idx + 1) {
233     // Done unwinding.
234     m_concrete_frames_fetched = UINT32_MAX;
235   }
236 
237   // Don't create the frames eagerly. Defer this work to GetFrameAtIndex,
238   // which can lazily query the unwinder to create frames.
239   m_frames.resize(num_frames);
240 }
241 
242 /// Find the unique path through the call graph from \p begin (with return PC
243 /// \p return_pc) to \p end. On success this path is stored into \p path, and
244 /// on failure \p path is unchanged.
245 static void FindInterveningFrames(Function &begin, Function &end,
246                                   Target &target, addr_t return_pc,
247                                   std::vector<Function *> &path,
248                                   ModuleList &images, Log *log) {
249   LLDB_LOG(log, "Finding frames between {0} and {1}, retn-pc={2:x}",
250            begin.GetDisplayName(), end.GetDisplayName(), return_pc);
251 
252   // Find a non-tail calling edge with the correct return PC.
253   if (log)
254     for (const CallEdge &edge : begin.GetCallEdges())
255       LLDB_LOG(log, "FindInterveningFrames: found call with retn-PC = {0:x}",
256                edge.GetReturnPCAddress(begin, target));
257   CallEdge *first_edge = begin.GetCallEdgeForReturnAddress(return_pc, target);
258   if (!first_edge) {
259     LLDB_LOG(log, "No call edge outgoing from {0} with retn-PC == {1:x}",
260              begin.GetDisplayName(), return_pc);
261     return;
262   }
263 
264   // The first callee may not be resolved, or there may be nothing to fill in.
265   Function *first_callee = first_edge->GetCallee(images);
266   if (!first_callee) {
267     LLDB_LOG(log, "Could not resolve callee");
268     return;
269   }
270   if (first_callee == &end) {
271     LLDB_LOG(log, "Not searching further, first callee is {0} (retn-PC: {1:x})",
272              end.GetDisplayName(), return_pc);
273     return;
274   }
275 
276   // Run DFS on the tail-calling edges out of the first callee to find \p end.
277   // Fully explore the set of functions reachable from the first edge via tail
278   // calls in order to detect ambiguous executions.
279   struct DFS {
280     std::vector<Function *> active_path = {};
281     std::vector<Function *> solution_path = {};
282     llvm::SmallPtrSet<Function *, 2> visited_nodes = {};
283     bool ambiguous = false;
284     Function *end;
285     ModuleList &images;
286 
287     DFS(Function *end, ModuleList &images) : end(end), images(images) {}
288 
289     void search(Function *first_callee, std::vector<Function *> &path) {
290       dfs(first_callee);
291       if (!ambiguous)
292         path = std::move(solution_path);
293     }
294 
295     void dfs(Function *callee) {
296       // Found a path to the target function.
297       if (callee == end) {
298         if (solution_path.empty())
299           solution_path = active_path;
300         else
301           ambiguous = true;
302         return;
303       }
304 
305       // Terminate the search if tail recursion is found, or more generally if
306       // there's more than one way to reach a target. This errs on the side of
307       // caution: it conservatively stops searching when some solutions are
308       // still possible to save time in the average case.
309       if (!visited_nodes.insert(callee).second) {
310         ambiguous = true;
311         return;
312       }
313 
314       // Search the calls made from this callee.
315       active_path.push_back(callee);
316       for (CallEdge &edge : callee->GetTailCallingEdges()) {
317         Function *next_callee = edge.GetCallee(images);
318         if (!next_callee)
319           continue;
320 
321         dfs(next_callee);
322         if (ambiguous)
323           return;
324       }
325       active_path.pop_back();
326     }
327   };
328 
329   DFS(&end, images).search(first_callee, path);
330 }
331 
332 /// Given that \p next_frame will be appended to the frame list, synthesize
333 /// tail call frames between the current end of the list and \p next_frame.
334 /// If any frames are added, adjust the frame index of \p next_frame.
335 ///
336 ///   --------------
337 ///   |    ...     | <- Completed frames.
338 ///   --------------
339 ///   | prev_frame |
340 ///   --------------
341 ///   |    ...     | <- Artificial frames inserted here.
342 ///   --------------
343 ///   | next_frame |
344 ///   --------------
345 ///   |    ...     | <- Not-yet-visited frames.
346 ///   --------------
347 void StackFrameList::SynthesizeTailCallFrames(StackFrame &next_frame) {
348   TargetSP target_sp = next_frame.CalculateTarget();
349   if (!target_sp)
350     return;
351 
352   lldb::RegisterContextSP next_reg_ctx_sp = next_frame.GetRegisterContext();
353   if (!next_reg_ctx_sp)
354     return;
355 
356   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
357 
358   assert(!m_frames.empty() && "Cannot synthesize frames in an empty stack");
359   StackFrame &prev_frame = *m_frames.back().get();
360 
361   // Find the functions prev_frame and next_frame are stopped in. The function
362   // objects are needed to search the lazy call graph for intervening frames.
363   Function *prev_func =
364       prev_frame.GetSymbolContext(eSymbolContextFunction).function;
365   if (!prev_func) {
366     LLDB_LOG(log, "SynthesizeTailCallFrames: can't find previous function");
367     return;
368   }
369   Function *next_func =
370       next_frame.GetSymbolContext(eSymbolContextFunction).function;
371   if (!next_func) {
372     LLDB_LOG(log, "SynthesizeTailCallFrames: can't find next function");
373     return;
374   }
375 
376   // Try to find the unique sequence of (tail) calls which led from next_frame
377   // to prev_frame.
378   std::vector<Function *> path;
379   addr_t return_pc = next_reg_ctx_sp->GetPC();
380   Target &target = *target_sp.get();
381   ModuleList &images = next_frame.CalculateTarget()->GetImages();
382   FindInterveningFrames(*next_func, *prev_func, target, return_pc, path, images,
383                         log);
384 
385   // Push synthetic tail call frames.
386   for (Function *callee : llvm::reverse(path)) {
387     uint32_t frame_idx = m_frames.size();
388     uint32_t concrete_frame_idx = next_frame.GetConcreteFrameIndex();
389     addr_t cfa = LLDB_INVALID_ADDRESS;
390     bool cfa_is_valid = false;
391     addr_t pc =
392         callee->GetAddressRange().GetBaseAddress().GetLoadAddress(&target);
393     constexpr bool behaves_like_zeroth_frame = false;
394     SymbolContext sc;
395     callee->CalculateSymbolContext(&sc);
396     auto synth_frame = std::make_shared<StackFrame>(
397         m_thread.shared_from_this(), frame_idx, concrete_frame_idx, cfa,
398         cfa_is_valid, pc, StackFrame::Kind::Artificial,
399         behaves_like_zeroth_frame, &sc);
400     m_frames.push_back(synth_frame);
401     LLDB_LOG(log, "Pushed frame {0}", callee->GetDisplayName());
402   }
403 
404   // If any frames were created, adjust next_frame's index.
405   if (!path.empty())
406     next_frame.SetFrameIndex(m_frames.size());
407 }
408 
409 void StackFrameList::GetFramesUpTo(uint32_t end_idx) {
410   // Do not fetch frames for an invalid thread.
411   if (!m_thread.IsValid())
412     return;
413 
414   // We've already gotten more frames than asked for, or we've already finished
415   // unwinding, return.
416   if (m_frames.size() > end_idx || GetAllFramesFetched())
417     return;
418 
419   Unwind *unwinder = m_thread.GetUnwinder();
420 
421   if (!m_show_inlined_frames) {
422     GetOnlyConcreteFramesUpTo(end_idx, unwinder);
423     return;
424   }
425 
426 #if defined(DEBUG_STACK_FRAMES)
427   StreamFile s(stdout, false);
428 #endif
429   // If we are hiding some frames from the outside world, we need to add
430   // those onto the total count of frames to fetch.  However, we don't need
431   // to do that if end_idx is 0 since in that case we always get the first
432   // concrete frame and all the inlined frames below it...  And of course, if
433   // end_idx is UINT32_MAX that means get all, so just do that...
434 
435   uint32_t inlined_depth = 0;
436   if (end_idx > 0 && end_idx != UINT32_MAX) {
437     inlined_depth = GetCurrentInlinedDepth();
438     if (inlined_depth != UINT32_MAX) {
439       if (end_idx > 0)
440         end_idx += inlined_depth;
441     }
442   }
443 
444   StackFrameSP unwind_frame_sp;
445   do {
446     uint32_t idx = m_concrete_frames_fetched++;
447     lldb::addr_t pc = LLDB_INVALID_ADDRESS;
448     lldb::addr_t cfa = LLDB_INVALID_ADDRESS;
449     bool behaves_like_zeroth_frame = (idx == 0);
450     if (idx == 0) {
451       // We might have already created frame zero, only create it if we need
452       // to.
453       if (m_frames.empty()) {
454         RegisterContextSP reg_ctx_sp(m_thread.GetRegisterContext());
455 
456         if (reg_ctx_sp) {
457           const bool success = unwinder &&
458                                unwinder->GetFrameInfoAtIndex(
459                                    idx, cfa, pc, behaves_like_zeroth_frame);
460           // There shouldn't be any way not to get the frame info for frame
461           // 0. But if the unwinder can't make one, lets make one by hand
462           // with the SP as the CFA and see if that gets any further.
463           if (!success) {
464             cfa = reg_ctx_sp->GetSP();
465             pc = reg_ctx_sp->GetPC();
466           }
467 
468           unwind_frame_sp = std::make_shared<StackFrame>(
469               m_thread.shared_from_this(), m_frames.size(), idx, reg_ctx_sp,
470               cfa, pc, behaves_like_zeroth_frame, nullptr);
471           m_frames.push_back(unwind_frame_sp);
472         }
473       } else {
474         unwind_frame_sp = m_frames.front();
475         cfa = unwind_frame_sp->m_id.GetCallFrameAddress();
476       }
477     } else {
478       const bool success = unwinder &&
479                            unwinder->GetFrameInfoAtIndex(
480                                idx, cfa, pc, behaves_like_zeroth_frame);
481       if (!success) {
482         // We've gotten to the end of the stack.
483         SetAllFramesFetched();
484         break;
485       }
486       const bool cfa_is_valid = true;
487       unwind_frame_sp = std::make_shared<StackFrame>(
488           m_thread.shared_from_this(), m_frames.size(), idx, cfa, cfa_is_valid,
489           pc, StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr);
490 
491       // Create synthetic tail call frames between the previous frame and the
492       // newly-found frame. The new frame's index may change after this call,
493       // although its concrete index will stay the same.
494       SynthesizeTailCallFrames(*unwind_frame_sp.get());
495 
496       m_frames.push_back(unwind_frame_sp);
497     }
498 
499     assert(unwind_frame_sp);
500     SymbolContext unwind_sc = unwind_frame_sp->GetSymbolContext(
501         eSymbolContextBlock | eSymbolContextFunction);
502     Block *unwind_block = unwind_sc.block;
503     if (unwind_block) {
504       Address curr_frame_address(unwind_frame_sp->GetFrameCodeAddress());
505       TargetSP target_sp = m_thread.CalculateTarget();
506       // Be sure to adjust the frame address to match the address that was
507       // used to lookup the symbol context above. If we are in the first
508       // concrete frame, then we lookup using the current address, else we
509       // decrement the address by one to get the correct location.
510       if (idx > 0) {
511         if (curr_frame_address.GetOffset() == 0) {
512           // If curr_frame_address points to the first address in a section
513           // then after adjustment it will point to an other section. In that
514           // case resolve the address again to the correct section plus
515           // offset form.
516           addr_t load_addr = curr_frame_address.GetOpcodeLoadAddress(
517               target_sp.get(), AddressClass::eCode);
518           curr_frame_address.SetOpcodeLoadAddress(
519               load_addr - 1, target_sp.get(), AddressClass::eCode);
520         } else {
521           curr_frame_address.Slide(-1);
522         }
523       }
524 
525       SymbolContext next_frame_sc;
526       Address next_frame_address;
527 
528       while (unwind_sc.GetParentOfInlinedScope(
529           curr_frame_address, next_frame_sc, next_frame_address)) {
530         next_frame_sc.line_entry.ApplyFileMappings(target_sp);
531         behaves_like_zeroth_frame = false;
532         StackFrameSP frame_sp(new StackFrame(
533             m_thread.shared_from_this(), m_frames.size(), idx,
534             unwind_frame_sp->GetRegisterContextSP(), cfa, next_frame_address,
535             behaves_like_zeroth_frame, &next_frame_sc));
536 
537         m_frames.push_back(frame_sp);
538         unwind_sc = next_frame_sc;
539         curr_frame_address = next_frame_address;
540       }
541     }
542   } while (m_frames.size() - 1 < end_idx);
543 
544   // Don't try to merge till you've calculated all the frames in this stack.
545   if (GetAllFramesFetched() && m_prev_frames_sp) {
546     StackFrameList *prev_frames = m_prev_frames_sp.get();
547     StackFrameList *curr_frames = this;
548 
549 #if defined(DEBUG_STACK_FRAMES)
550     s.PutCString("\nprev_frames:\n");
551     prev_frames->Dump(&s);
552     s.PutCString("\ncurr_frames:\n");
553     curr_frames->Dump(&s);
554     s.EOL();
555 #endif
556     size_t curr_frame_num, prev_frame_num;
557 
558     for (curr_frame_num = curr_frames->m_frames.size(),
559         prev_frame_num = prev_frames->m_frames.size();
560          curr_frame_num > 0 && prev_frame_num > 0;
561          --curr_frame_num, --prev_frame_num) {
562       const size_t curr_frame_idx = curr_frame_num - 1;
563       const size_t prev_frame_idx = prev_frame_num - 1;
564       StackFrameSP curr_frame_sp(curr_frames->m_frames[curr_frame_idx]);
565       StackFrameSP prev_frame_sp(prev_frames->m_frames[prev_frame_idx]);
566 
567 #if defined(DEBUG_STACK_FRAMES)
568       s.Printf("\n\nCurr frame #%u ", curr_frame_idx);
569       if (curr_frame_sp)
570         curr_frame_sp->Dump(&s, true, false);
571       else
572         s.PutCString("NULL");
573       s.Printf("\nPrev frame #%u ", prev_frame_idx);
574       if (prev_frame_sp)
575         prev_frame_sp->Dump(&s, true, false);
576       else
577         s.PutCString("NULL");
578 #endif
579 
580       StackFrame *curr_frame = curr_frame_sp.get();
581       StackFrame *prev_frame = prev_frame_sp.get();
582 
583       if (curr_frame == nullptr || prev_frame == nullptr)
584         break;
585 
586       // Check the stack ID to make sure they are equal.
587       if (curr_frame->GetStackID() != prev_frame->GetStackID())
588         break;
589 
590       prev_frame->UpdatePreviousFrameFromCurrentFrame(*curr_frame);
591       // Now copy the fixed up previous frame into the current frames so the
592       // pointer doesn't change.
593       m_frames[curr_frame_idx] = prev_frame_sp;
594 
595 #if defined(DEBUG_STACK_FRAMES)
596       s.Printf("\n    Copying previous frame to current frame");
597 #endif
598     }
599     // We are done with the old stack frame list, we can release it now.
600     m_prev_frames_sp.reset();
601   }
602 
603 #if defined(DEBUG_STACK_FRAMES)
604   s.PutCString("\n\nNew frames:\n");
605   Dump(&s);
606   s.EOL();
607 #endif
608 }
609 
610 uint32_t StackFrameList::GetNumFrames(bool can_create) {
611   std::lock_guard<std::recursive_mutex> guard(m_mutex);
612 
613   if (can_create)
614     GetFramesUpTo(UINT32_MAX);
615 
616   return GetVisibleStackFrameIndex(m_frames.size());
617 }
618 
619 void StackFrameList::Dump(Stream *s) {
620   if (s == nullptr)
621     return;
622 
623   std::lock_guard<std::recursive_mutex> guard(m_mutex);
624 
625   const_iterator pos, begin = m_frames.begin(), end = m_frames.end();
626   for (pos = begin; pos != end; ++pos) {
627     StackFrame *frame = (*pos).get();
628     s->Printf("%p: ", static_cast<void *>(frame));
629     if (frame) {
630       frame->GetStackID().Dump(s);
631       frame->DumpUsingSettingsFormat(s);
632     } else
633       s->Printf("frame #%u", (uint32_t)std::distance(begin, pos));
634     s->EOL();
635   }
636   s->EOL();
637 }
638 
639 StackFrameSP StackFrameList::GetFrameAtIndex(uint32_t idx) {
640   StackFrameSP frame_sp;
641   std::lock_guard<std::recursive_mutex> guard(m_mutex);
642   uint32_t original_idx = idx;
643 
644   uint32_t inlined_depth = GetCurrentInlinedDepth();
645   if (inlined_depth != UINT32_MAX)
646     idx += inlined_depth;
647 
648   if (idx < m_frames.size())
649     frame_sp = m_frames[idx];
650 
651   if (frame_sp)
652     return frame_sp;
653 
654   // GetFramesUpTo will fill m_frames with as many frames as you asked for, if
655   // there are that many.  If there weren't then you asked for too many frames.
656   GetFramesUpTo(idx);
657   if (idx < m_frames.size()) {
658     if (m_show_inlined_frames) {
659       // When inline frames are enabled we actually create all the frames in
660       // GetFramesUpTo.
661       frame_sp = m_frames[idx];
662     } else {
663       Unwind *unwinder = m_thread.GetUnwinder();
664       if (unwinder) {
665         addr_t pc, cfa;
666         bool behaves_like_zeroth_frame = (idx == 0);
667         if (unwinder->GetFrameInfoAtIndex(idx, cfa, pc,
668                                           behaves_like_zeroth_frame)) {
669           const bool cfa_is_valid = true;
670           frame_sp = std::make_shared<StackFrame>(
671               m_thread.shared_from_this(), idx, idx, cfa, cfa_is_valid, pc,
672               StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr);
673 
674           Function *function =
675               frame_sp->GetSymbolContext(eSymbolContextFunction).function;
676           if (function) {
677             // When we aren't showing inline functions we always use the top
678             // most function block as the scope.
679             frame_sp->SetSymbolContextScope(&function->GetBlock(false));
680           } else {
681             // Set the symbol scope from the symbol regardless if it is nullptr
682             // or valid.
683             frame_sp->SetSymbolContextScope(
684                 frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol);
685           }
686           SetFrameAtIndex(idx, frame_sp);
687         }
688       }
689     }
690   } else if (original_idx == 0) {
691     // There should ALWAYS be a frame at index 0.  If something went wrong with
692     // the CurrentInlinedDepth such that there weren't as many frames as we
693     // thought taking that into account, then reset the current inlined depth
694     // and return the real zeroth frame.
695     if (m_frames.empty()) {
696       // Why do we have a thread with zero frames, that should not ever
697       // happen...
698       assert(!m_thread.IsValid() && "A valid thread has no frames.");
699     } else {
700       ResetCurrentInlinedDepth();
701       frame_sp = m_frames[original_idx];
702     }
703   }
704 
705   return frame_sp;
706 }
707 
708 StackFrameSP
709 StackFrameList::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) {
710   // First try assuming the unwind index is the same as the frame index. The
711   // unwind index is always greater than or equal to the frame index, so it is
712   // a good place to start. If we have inlined frames we might have 5 concrete
713   // frames (frame unwind indexes go from 0-4), but we might have 15 frames
714   // after we make all the inlined frames. Most of the time the unwind frame
715   // index (or the concrete frame index) is the same as the frame index.
716   uint32_t frame_idx = unwind_idx;
717   StackFrameSP frame_sp(GetFrameAtIndex(frame_idx));
718   while (frame_sp) {
719     if (frame_sp->GetFrameIndex() == unwind_idx)
720       break;
721     frame_sp = GetFrameAtIndex(++frame_idx);
722   }
723   return frame_sp;
724 }
725 
726 static bool CompareStackID(const StackFrameSP &stack_sp,
727                            const StackID &stack_id) {
728   return stack_sp->GetStackID() < stack_id;
729 }
730 
731 StackFrameSP StackFrameList::GetFrameWithStackID(const StackID &stack_id) {
732   StackFrameSP frame_sp;
733 
734   if (stack_id.IsValid()) {
735     std::lock_guard<std::recursive_mutex> guard(m_mutex);
736     uint32_t frame_idx = 0;
737     // Do a binary search in case the stack frame is already in our cache
738     collection::const_iterator begin = m_frames.begin();
739     collection::const_iterator end = m_frames.end();
740     if (begin != end) {
741       collection::const_iterator pos =
742           std::lower_bound(begin, end, stack_id, CompareStackID);
743       if (pos != end) {
744         if ((*pos)->GetStackID() == stack_id)
745           return *pos;
746       }
747     }
748     do {
749       frame_sp = GetFrameAtIndex(frame_idx);
750       if (frame_sp && frame_sp->GetStackID() == stack_id)
751         break;
752       frame_idx++;
753     } while (frame_sp);
754   }
755   return frame_sp;
756 }
757 
758 bool StackFrameList::SetFrameAtIndex(uint32_t idx, StackFrameSP &frame_sp) {
759   if (idx >= m_frames.size())
760     m_frames.resize(idx + 1);
761   // Make sure allocation succeeded by checking bounds again
762   if (idx < m_frames.size()) {
763     m_frames[idx] = frame_sp;
764     return true;
765   }
766   return false; // resize failed, out of memory?
767 }
768 
769 uint32_t StackFrameList::GetSelectedFrameIndex() const {
770   std::lock_guard<std::recursive_mutex> guard(m_mutex);
771   return m_selected_frame_idx;
772 }
773 
774 uint32_t StackFrameList::SetSelectedFrame(lldb_private::StackFrame *frame) {
775   std::lock_guard<std::recursive_mutex> guard(m_mutex);
776   const_iterator pos;
777   const_iterator begin = m_frames.begin();
778   const_iterator end = m_frames.end();
779   m_selected_frame_idx = 0;
780   for (pos = begin; pos != end; ++pos) {
781     if (pos->get() == frame) {
782       m_selected_frame_idx = std::distance(begin, pos);
783       uint32_t inlined_depth = GetCurrentInlinedDepth();
784       if (inlined_depth != UINT32_MAX)
785         m_selected_frame_idx -= inlined_depth;
786       break;
787     }
788   }
789   SetDefaultFileAndLineToSelectedFrame();
790   return m_selected_frame_idx;
791 }
792 
793 bool StackFrameList::SetSelectedFrameByIndex(uint32_t idx) {
794   std::lock_guard<std::recursive_mutex> guard(m_mutex);
795   StackFrameSP frame_sp(GetFrameAtIndex(idx));
796   if (frame_sp) {
797     SetSelectedFrame(frame_sp.get());
798     return true;
799   } else
800     return false;
801 }
802 
803 void StackFrameList::SetDefaultFileAndLineToSelectedFrame() {
804   if (m_thread.GetID() ==
805       m_thread.GetProcess()->GetThreadList().GetSelectedThread()->GetID()) {
806     StackFrameSP frame_sp(GetFrameAtIndex(GetSelectedFrameIndex()));
807     if (frame_sp) {
808       SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextLineEntry);
809       if (sc.line_entry.file)
810         m_thread.CalculateTarget()->GetSourceManager().SetDefaultFileAndLine(
811             sc.line_entry.file, sc.line_entry.line);
812     }
813   }
814 }
815 
816 // The thread has been run, reset the number stack frames to zero so we can
817 // determine how many frames we have lazily.
818 void StackFrameList::Clear() {
819   std::lock_guard<std::recursive_mutex> guard(m_mutex);
820   m_frames.clear();
821   m_concrete_frames_fetched = 0;
822 }
823 
824 void StackFrameList::Merge(std::unique_ptr<StackFrameList> &curr_up,
825                            lldb::StackFrameListSP &prev_sp) {
826   std::unique_lock<std::recursive_mutex> current_lock, previous_lock;
827   if (curr_up)
828     current_lock = std::unique_lock<std::recursive_mutex>(curr_up->m_mutex);
829   if (prev_sp)
830     previous_lock = std::unique_lock<std::recursive_mutex>(prev_sp->m_mutex);
831 
832 #if defined(DEBUG_STACK_FRAMES)
833   StreamFile s(stdout, false);
834   s.PutCString("\n\nStackFrameList::Merge():\nPrev:\n");
835   if (prev_sp)
836     prev_sp->Dump(&s);
837   else
838     s.PutCString("NULL");
839   s.PutCString("\nCurr:\n");
840   if (curr_up)
841     curr_up->Dump(&s);
842   else
843     s.PutCString("NULL");
844   s.EOL();
845 #endif
846 
847   if (!curr_up || curr_up->GetNumFrames(false) == 0) {
848 #if defined(DEBUG_STACK_FRAMES)
849     s.PutCString("No current frames, leave previous frames alone...\n");
850 #endif
851     curr_up.release();
852     return;
853   }
854 
855   if (!prev_sp || prev_sp->GetNumFrames(false) == 0) {
856 #if defined(DEBUG_STACK_FRAMES)
857     s.PutCString("No previous frames, so use current frames...\n");
858 #endif
859     // We either don't have any previous frames, or since we have more than one
860     // current frames it means we have all the frames and can safely replace
861     // our previous frames.
862     prev_sp.reset(curr_up.release());
863     return;
864   }
865 
866   const uint32_t num_curr_frames = curr_up->GetNumFrames(false);
867 
868   if (num_curr_frames > 1) {
869 #if defined(DEBUG_STACK_FRAMES)
870     s.PutCString(
871         "We have more than one current frame, so use current frames...\n");
872 #endif
873     // We have more than one current frames it means we have all the frames and
874     // can safely replace our previous frames.
875     prev_sp.reset(curr_up.release());
876 
877 #if defined(DEBUG_STACK_FRAMES)
878     s.PutCString("\nMerged:\n");
879     prev_sp->Dump(&s);
880 #endif
881     return;
882   }
883 
884   StackFrameSP prev_frame_zero_sp(prev_sp->GetFrameAtIndex(0));
885   StackFrameSP curr_frame_zero_sp(curr_up->GetFrameAtIndex(0));
886   StackID curr_stack_id(curr_frame_zero_sp->GetStackID());
887   StackID prev_stack_id(prev_frame_zero_sp->GetStackID());
888 
889 #if defined(DEBUG_STACK_FRAMES)
890   const uint32_t num_prev_frames = prev_sp->GetNumFrames(false);
891   s.Printf("\n%u previous frames with one current frame\n", num_prev_frames);
892 #endif
893 
894   // We have only a single current frame
895   // Our previous stack frames only had a single frame as well...
896   if (curr_stack_id == prev_stack_id) {
897 #if defined(DEBUG_STACK_FRAMES)
898     s.Printf("\nPrevious frame #0 is same as current frame #0, merge the "
899              "cached data\n");
900 #endif
901 
902     curr_frame_zero_sp->UpdateCurrentFrameFromPreviousFrame(
903         *prev_frame_zero_sp);
904     //        prev_frame_zero_sp->UpdatePreviousFrameFromCurrentFrame
905     //        (*curr_frame_zero_sp);
906     //        prev_sp->SetFrameAtIndex (0, prev_frame_zero_sp);
907   } else if (curr_stack_id < prev_stack_id) {
908 #if defined(DEBUG_STACK_FRAMES)
909     s.Printf("\nCurrent frame #0 has a stack ID that is less than the previous "
910              "frame #0, insert current frame zero in front of previous\n");
911 #endif
912     prev_sp->m_frames.insert(prev_sp->m_frames.begin(), curr_frame_zero_sp);
913   }
914 
915   curr_up.release();
916 
917 #if defined(DEBUG_STACK_FRAMES)
918   s.PutCString("\nMerged:\n");
919   prev_sp->Dump(&s);
920 #endif
921 }
922 
923 lldb::StackFrameSP
924 StackFrameList::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) {
925   const_iterator pos;
926   const_iterator begin = m_frames.begin();
927   const_iterator end = m_frames.end();
928   lldb::StackFrameSP ret_sp;
929 
930   for (pos = begin; pos != end; ++pos) {
931     if (pos->get() == stack_frame_ptr) {
932       ret_sp = (*pos);
933       break;
934     }
935   }
936   return ret_sp;
937 }
938 
939 size_t StackFrameList::GetStatus(Stream &strm, uint32_t first_frame,
940                                  uint32_t num_frames, bool show_frame_info,
941                                  uint32_t num_frames_with_source,
942                                  bool show_unique,
943                                  const char *selected_frame_marker) {
944   size_t num_frames_displayed = 0;
945 
946   if (num_frames == 0)
947     return 0;
948 
949   StackFrameSP frame_sp;
950   uint32_t frame_idx = 0;
951   uint32_t last_frame;
952 
953   // Don't let the last frame wrap around...
954   if (num_frames == UINT32_MAX)
955     last_frame = UINT32_MAX;
956   else
957     last_frame = first_frame + num_frames;
958 
959   StackFrameSP selected_frame_sp = m_thread.GetSelectedFrame();
960   const char *unselected_marker = nullptr;
961   std::string buffer;
962   if (selected_frame_marker) {
963     size_t len = strlen(selected_frame_marker);
964     buffer.insert(buffer.begin(), len, ' ');
965     unselected_marker = buffer.c_str();
966   }
967   const char *marker = nullptr;
968 
969   for (frame_idx = first_frame; frame_idx < last_frame; ++frame_idx) {
970     frame_sp = GetFrameAtIndex(frame_idx);
971     if (!frame_sp)
972       break;
973 
974     if (selected_frame_marker != nullptr) {
975       if (frame_sp == selected_frame_sp)
976         marker = selected_frame_marker;
977       else
978         marker = unselected_marker;
979     }
980 
981     if (!frame_sp->GetStatus(strm, show_frame_info,
982                              num_frames_with_source > (first_frame - frame_idx),
983                              show_unique, marker))
984       break;
985     ++num_frames_displayed;
986   }
987 
988   strm.IndentLess();
989   return num_frames_displayed;
990 }
991