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   auto first_level_edges = begin.GetCallEdges();
254   if (log)
255     for (const CallEdge &edge : first_level_edges)
256       LLDB_LOG(log, "FindInterveningFrames: found call with retn-PC = {0:x}",
257                edge.GetReturnPCAddress(begin, target));
258   auto first_edge_it = std::lower_bound(
259       first_level_edges.begin(), first_level_edges.end(), return_pc,
260       [&](const CallEdge &edge, addr_t target_pc) {
261         return edge.GetReturnPCAddress(begin, target) < target_pc;
262       });
263   if (first_edge_it == first_level_edges.end() ||
264       first_edge_it->GetReturnPCAddress(begin, target) != return_pc) {
265     LLDB_LOG(log, "No call edge outgoing from {0} with retn-PC == {1:x}",
266              begin.GetDisplayName(), return_pc);
267     return;
268   }
269   CallEdge &first_edge = const_cast<CallEdge &>(*first_edge_it);
270 
271   // The first callee may not be resolved, or there may be nothing to fill in.
272   Function *first_callee = first_edge.GetCallee(images);
273   if (!first_callee) {
274     LLDB_LOG(log, "Could not resolve callee");
275     return;
276   }
277   if (first_callee == &end) {
278     LLDB_LOG(log, "Not searching further, first callee is {0} (retn-PC: {1:x})",
279              end.GetDisplayName(), return_pc);
280     return;
281   }
282 
283   // Run DFS on the tail-calling edges out of the first callee to find \p end.
284   // Fully explore the set of functions reachable from the first edge via tail
285   // calls in order to detect ambiguous executions.
286   struct DFS {
287     std::vector<Function *> active_path = {};
288     std::vector<Function *> solution_path = {};
289     llvm::SmallPtrSet<Function *, 2> visited_nodes = {};
290     bool ambiguous = false;
291     Function *end;
292     ModuleList &images;
293 
294     DFS(Function *end, ModuleList &images) : end(end), images(images) {}
295 
296     void search(Function *first_callee, std::vector<Function *> &path) {
297       dfs(first_callee);
298       if (!ambiguous)
299         path = std::move(solution_path);
300     }
301 
302     void dfs(Function *callee) {
303       // Found a path to the target function.
304       if (callee == end) {
305         if (solution_path.empty())
306           solution_path = active_path;
307         else
308           ambiguous = true;
309         return;
310       }
311 
312       // Terminate the search if tail recursion is found, or more generally if
313       // there's more than one way to reach a target. This errs on the side of
314       // caution: it conservatively stops searching when some solutions are
315       // still possible to save time in the average case.
316       if (!visited_nodes.insert(callee).second) {
317         ambiguous = true;
318         return;
319       }
320 
321       // Search the calls made from this callee.
322       active_path.push_back(callee);
323       for (CallEdge &edge : callee->GetTailCallingEdges()) {
324         Function *next_callee = edge.GetCallee(images);
325         if (!next_callee)
326           continue;
327 
328         dfs(next_callee);
329         if (ambiguous)
330           return;
331       }
332       active_path.pop_back();
333     }
334   };
335 
336   DFS(&end, images).search(first_callee, path);
337 }
338 
339 /// Given that \p next_frame will be appended to the frame list, synthesize
340 /// tail call frames between the current end of the list and \p next_frame.
341 /// If any frames are added, adjust the frame index of \p next_frame.
342 ///
343 ///   --------------
344 ///   |    ...     | <- Completed frames.
345 ///   --------------
346 ///   | prev_frame |
347 ///   --------------
348 ///   |    ...     | <- Artificial frames inserted here.
349 ///   --------------
350 ///   | next_frame |
351 ///   --------------
352 ///   |    ...     | <- Not-yet-visited frames.
353 ///   --------------
354 void StackFrameList::SynthesizeTailCallFrames(StackFrame &next_frame) {
355   TargetSP target_sp = next_frame.CalculateTarget();
356   if (!target_sp)
357     return;
358 
359   lldb::RegisterContextSP next_reg_ctx_sp = next_frame.GetRegisterContext();
360   if (!next_reg_ctx_sp)
361     return;
362 
363   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
364 
365   assert(!m_frames.empty() && "Cannot synthesize frames in an empty stack");
366   StackFrame &prev_frame = *m_frames.back().get();
367 
368   // Find the functions prev_frame and next_frame are stopped in. The function
369   // objects are needed to search the lazy call graph for intervening frames.
370   Function *prev_func =
371       prev_frame.GetSymbolContext(eSymbolContextFunction).function;
372   if (!prev_func) {
373     LLDB_LOG(log, "SynthesizeTailCallFrames: can't find previous function");
374     return;
375   }
376   Function *next_func =
377       next_frame.GetSymbolContext(eSymbolContextFunction).function;
378   if (!next_func) {
379     LLDB_LOG(log, "SynthesizeTailCallFrames: can't find next function");
380     return;
381   }
382 
383   // Try to find the unique sequence of (tail) calls which led from next_frame
384   // to prev_frame.
385   std::vector<Function *> path;
386   addr_t return_pc = next_reg_ctx_sp->GetPC();
387   Target &target = *target_sp.get();
388   ModuleList &images = next_frame.CalculateTarget()->GetImages();
389   FindInterveningFrames(*next_func, *prev_func, target, return_pc, path, images,
390                         log);
391 
392   // Push synthetic tail call frames.
393   for (Function *callee : llvm::reverse(path)) {
394     uint32_t frame_idx = m_frames.size();
395     uint32_t concrete_frame_idx = next_frame.GetConcreteFrameIndex();
396     addr_t cfa = LLDB_INVALID_ADDRESS;
397     bool cfa_is_valid = false;
398     addr_t pc =
399         callee->GetAddressRange().GetBaseAddress().GetLoadAddress(&target);
400     SymbolContext sc;
401     callee->CalculateSymbolContext(&sc);
402     auto synth_frame = std::make_shared<StackFrame>(
403         m_thread.shared_from_this(), frame_idx, concrete_frame_idx, cfa,
404         cfa_is_valid, pc, StackFrame::Kind::Artificial, &sc);
405     m_frames.push_back(synth_frame);
406     LLDB_LOG(log, "Pushed frame {0}", callee->GetDisplayName());
407   }
408 
409   // If any frames were created, adjust next_frame's index.
410   if (!path.empty())
411     next_frame.SetFrameIndex(m_frames.size());
412 }
413 
414 void StackFrameList::GetFramesUpTo(uint32_t end_idx) {
415   // Do not fetch frames for an invalid thread.
416   if (!m_thread.IsValid())
417     return;
418 
419   // We've already gotten more frames than asked for, or we've already finished
420   // unwinding, return.
421   if (m_frames.size() > end_idx || GetAllFramesFetched())
422     return;
423 
424   Unwind *unwinder = m_thread.GetUnwinder();
425 
426   if (!m_show_inlined_frames) {
427     GetOnlyConcreteFramesUpTo(end_idx, unwinder);
428     return;
429   }
430 
431 #if defined(DEBUG_STACK_FRAMES)
432   StreamFile s(stdout, false);
433 #endif
434   // If we are hiding some frames from the outside world, we need to add
435   // those onto the total count of frames to fetch.  However, we don't need
436   // to do that if end_idx is 0 since in that case we always get the first
437   // concrete frame and all the inlined frames below it...  And of course, if
438   // end_idx is UINT32_MAX that means get all, so just do that...
439 
440   uint32_t inlined_depth = 0;
441   if (end_idx > 0 && end_idx != UINT32_MAX) {
442     inlined_depth = GetCurrentInlinedDepth();
443     if (inlined_depth != UINT32_MAX) {
444       if (end_idx > 0)
445         end_idx += inlined_depth;
446     }
447   }
448 
449   StackFrameSP unwind_frame_sp;
450   do {
451     uint32_t idx = m_concrete_frames_fetched++;
452     lldb::addr_t pc = LLDB_INVALID_ADDRESS;
453     lldb::addr_t cfa = LLDB_INVALID_ADDRESS;
454     if (idx == 0) {
455       // We might have already created frame zero, only create it if we need
456       // to.
457       if (m_frames.empty()) {
458         RegisterContextSP reg_ctx_sp(m_thread.GetRegisterContext());
459 
460         if (reg_ctx_sp) {
461           const bool success =
462               unwinder && unwinder->GetFrameInfoAtIndex(idx, cfa, pc);
463           // There shouldn't be any way not to get the frame info for frame
464           // 0. But if the unwinder can't make one, lets make one by hand
465           // with the SP as the CFA and see if that gets any further.
466           if (!success) {
467             cfa = reg_ctx_sp->GetSP();
468             pc = reg_ctx_sp->GetPC();
469           }
470 
471           unwind_frame_sp = std::make_shared<StackFrame>(
472               m_thread.shared_from_this(), m_frames.size(), idx, reg_ctx_sp,
473               cfa, pc, nullptr);
474           m_frames.push_back(unwind_frame_sp);
475         }
476       } else {
477         unwind_frame_sp = m_frames.front();
478         cfa = unwind_frame_sp->m_id.GetCallFrameAddress();
479       }
480     } else {
481       const bool success =
482           unwinder && unwinder->GetFrameInfoAtIndex(idx, cfa, pc);
483       if (!success) {
484         // We've gotten to the end of the stack.
485         SetAllFramesFetched();
486         break;
487       }
488       const bool cfa_is_valid = true;
489       unwind_frame_sp = std::make_shared<StackFrame>(
490           m_thread.shared_from_this(), m_frames.size(), idx, cfa, cfa_is_valid,
491           pc, StackFrame::Kind::Regular, nullptr);
492 
493       // Create synthetic tail call frames between the previous frame and the
494       // newly-found frame. The new frame's index may change after this call,
495       // although its concrete index will stay the same.
496       SynthesizeTailCallFrames(*unwind_frame_sp.get());
497 
498       m_frames.push_back(unwind_frame_sp);
499     }
500 
501     assert(unwind_frame_sp);
502     SymbolContext unwind_sc = unwind_frame_sp->GetSymbolContext(
503         eSymbolContextBlock | eSymbolContextFunction);
504     Block *unwind_block = unwind_sc.block;
505     if (unwind_block) {
506       Address curr_frame_address(unwind_frame_sp->GetFrameCodeAddress());
507       TargetSP target_sp = m_thread.CalculateTarget();
508       // Be sure to adjust the frame address to match the address that was
509       // used to lookup the symbol context above. If we are in the first
510       // concrete frame, then we lookup using the current address, else we
511       // decrement the address by one to get the correct location.
512       if (idx > 0) {
513         if (curr_frame_address.GetOffset() == 0) {
514           // If curr_frame_address points to the first address in a section
515           // then after adjustment it will point to an other section. In that
516           // case resolve the address again to the correct section plus
517           // offset form.
518           addr_t load_addr = curr_frame_address.GetOpcodeLoadAddress(
519               target_sp.get(), AddressClass::eCode);
520           curr_frame_address.SetOpcodeLoadAddress(
521               load_addr - 1, target_sp.get(), AddressClass::eCode);
522         } else {
523           curr_frame_address.Slide(-1);
524         }
525       }
526 
527       SymbolContext next_frame_sc;
528       Address next_frame_address;
529 
530       while (unwind_sc.GetParentOfInlinedScope(
531           curr_frame_address, next_frame_sc, next_frame_address)) {
532         next_frame_sc.line_entry.ApplyFileMappings(target_sp);
533         StackFrameSP frame_sp(
534             new StackFrame(m_thread.shared_from_this(), m_frames.size(), idx,
535                            unwind_frame_sp->GetRegisterContextSP(), cfa,
536                            next_frame_address, &next_frame_sc));
537 
538         m_frames.push_back(frame_sp);
539         unwind_sc = next_frame_sc;
540         curr_frame_address = next_frame_address;
541       }
542     }
543   } while (m_frames.size() - 1 < end_idx);
544 
545   // Don't try to merge till you've calculated all the frames in this stack.
546   if (GetAllFramesFetched() && m_prev_frames_sp) {
547     StackFrameList *prev_frames = m_prev_frames_sp.get();
548     StackFrameList *curr_frames = this;
549 
550 #if defined(DEBUG_STACK_FRAMES)
551     s.PutCString("\nprev_frames:\n");
552     prev_frames->Dump(&s);
553     s.PutCString("\ncurr_frames:\n");
554     curr_frames->Dump(&s);
555     s.EOL();
556 #endif
557     size_t curr_frame_num, prev_frame_num;
558 
559     for (curr_frame_num = curr_frames->m_frames.size(),
560         prev_frame_num = prev_frames->m_frames.size();
561          curr_frame_num > 0 && prev_frame_num > 0;
562          --curr_frame_num, --prev_frame_num) {
563       const size_t curr_frame_idx = curr_frame_num - 1;
564       const size_t prev_frame_idx = prev_frame_num - 1;
565       StackFrameSP curr_frame_sp(curr_frames->m_frames[curr_frame_idx]);
566       StackFrameSP prev_frame_sp(prev_frames->m_frames[prev_frame_idx]);
567 
568 #if defined(DEBUG_STACK_FRAMES)
569       s.Printf("\n\nCurr frame #%u ", curr_frame_idx);
570       if (curr_frame_sp)
571         curr_frame_sp->Dump(&s, true, false);
572       else
573         s.PutCString("NULL");
574       s.Printf("\nPrev frame #%u ", prev_frame_idx);
575       if (prev_frame_sp)
576         prev_frame_sp->Dump(&s, true, false);
577       else
578         s.PutCString("NULL");
579 #endif
580 
581       StackFrame *curr_frame = curr_frame_sp.get();
582       StackFrame *prev_frame = prev_frame_sp.get();
583 
584       if (curr_frame == nullptr || prev_frame == nullptr)
585         break;
586 
587       // Check the stack ID to make sure they are equal.
588       if (curr_frame->GetStackID() != prev_frame->GetStackID())
589         break;
590 
591       prev_frame->UpdatePreviousFrameFromCurrentFrame(*curr_frame);
592       // Now copy the fixed up previous frame into the current frames so the
593       // pointer doesn't change.
594       m_frames[curr_frame_idx] = prev_frame_sp;
595 
596 #if defined(DEBUG_STACK_FRAMES)
597       s.Printf("\n    Copying previous frame to current frame");
598 #endif
599     }
600     // We are done with the old stack frame list, we can release it now.
601     m_prev_frames_sp.reset();
602   }
603 
604 #if defined(DEBUG_STACK_FRAMES)
605   s.PutCString("\n\nNew frames:\n");
606   Dump(&s);
607   s.EOL();
608 #endif
609 }
610 
611 uint32_t StackFrameList::GetNumFrames(bool can_create) {
612   std::lock_guard<std::recursive_mutex> guard(m_mutex);
613 
614   if (can_create)
615     GetFramesUpTo(UINT32_MAX);
616 
617   return GetVisibleStackFrameIndex(m_frames.size());
618 }
619 
620 void StackFrameList::Dump(Stream *s) {
621   if (s == nullptr)
622     return;
623 
624   std::lock_guard<std::recursive_mutex> guard(m_mutex);
625 
626   const_iterator pos, begin = m_frames.begin(), end = m_frames.end();
627   for (pos = begin; pos != end; ++pos) {
628     StackFrame *frame = (*pos).get();
629     s->Printf("%p: ", static_cast<void *>(frame));
630     if (frame) {
631       frame->GetStackID().Dump(s);
632       frame->DumpUsingSettingsFormat(s);
633     } else
634       s->Printf("frame #%u", (uint32_t)std::distance(begin, pos));
635     s->EOL();
636   }
637   s->EOL();
638 }
639 
640 StackFrameSP StackFrameList::GetFrameAtIndex(uint32_t idx) {
641   StackFrameSP frame_sp;
642   std::lock_guard<std::recursive_mutex> guard(m_mutex);
643   uint32_t original_idx = idx;
644 
645   uint32_t inlined_depth = GetCurrentInlinedDepth();
646   if (inlined_depth != UINT32_MAX)
647     idx += inlined_depth;
648 
649   if (idx < m_frames.size())
650     frame_sp = m_frames[idx];
651 
652   if (frame_sp)
653     return frame_sp;
654 
655   // GetFramesUpTo will fill m_frames with as many frames as you asked for, if
656   // there are that many.  If there weren't then you asked for too many frames.
657   GetFramesUpTo(idx);
658   if (idx < m_frames.size()) {
659     if (m_show_inlined_frames) {
660       // When inline frames are enabled we actually create all the frames in
661       // GetFramesUpTo.
662       frame_sp = m_frames[idx];
663     } else {
664       Unwind *unwinder = m_thread.GetUnwinder();
665       if (unwinder) {
666         addr_t pc, cfa;
667         if (unwinder->GetFrameInfoAtIndex(idx, cfa, pc)) {
668           const bool cfa_is_valid = true;
669           frame_sp = std::make_shared<StackFrame>(
670               m_thread.shared_from_this(), idx, idx, cfa, cfa_is_valid, pc,
671               StackFrame::Kind::Regular, nullptr);
672 
673           Function *function =
674               frame_sp->GetSymbolContext(eSymbolContextFunction).function;
675           if (function) {
676             // When we aren't showing inline functions we always use the top
677             // most function block as the scope.
678             frame_sp->SetSymbolContextScope(&function->GetBlock(false));
679           } else {
680             // Set the symbol scope from the symbol regardless if it is nullptr
681             // or valid.
682             frame_sp->SetSymbolContextScope(
683                 frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol);
684           }
685           SetFrameAtIndex(idx, frame_sp);
686         }
687       }
688     }
689   } else if (original_idx == 0) {
690     // There should ALWAYS be a frame at index 0.  If something went wrong with
691     // the CurrentInlinedDepth such that there weren't as many frames as we
692     // thought taking that into account, then reset the current inlined depth
693     // and return the real zeroth frame.
694     if (m_frames.empty()) {
695       // Why do we have a thread with zero frames, that should not ever
696       // happen...
697       assert(!m_thread.IsValid() && "A valid thread has no frames.");
698     } else {
699       ResetCurrentInlinedDepth();
700       frame_sp = m_frames[original_idx];
701     }
702   }
703 
704   return frame_sp;
705 }
706 
707 StackFrameSP
708 StackFrameList::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) {
709   // First try assuming the unwind index is the same as the frame index. The
710   // unwind index is always greater than or equal to the frame index, so it is
711   // a good place to start. If we have inlined frames we might have 5 concrete
712   // frames (frame unwind indexes go from 0-4), but we might have 15 frames
713   // after we make all the inlined frames. Most of the time the unwind frame
714   // index (or the concrete frame index) is the same as the frame index.
715   uint32_t frame_idx = unwind_idx;
716   StackFrameSP frame_sp(GetFrameAtIndex(frame_idx));
717   while (frame_sp) {
718     if (frame_sp->GetFrameIndex() == unwind_idx)
719       break;
720     frame_sp = GetFrameAtIndex(++frame_idx);
721   }
722   return frame_sp;
723 }
724 
725 static bool CompareStackID(const StackFrameSP &stack_sp,
726                            const StackID &stack_id) {
727   return stack_sp->GetStackID() < stack_id;
728 }
729 
730 StackFrameSP StackFrameList::GetFrameWithStackID(const StackID &stack_id) {
731   StackFrameSP frame_sp;
732 
733   if (stack_id.IsValid()) {
734     std::lock_guard<std::recursive_mutex> guard(m_mutex);
735     uint32_t frame_idx = 0;
736     // Do a binary search in case the stack frame is already in our cache
737     collection::const_iterator begin = m_frames.begin();
738     collection::const_iterator end = m_frames.end();
739     if (begin != end) {
740       collection::const_iterator pos =
741           std::lower_bound(begin, end, stack_id, CompareStackID);
742       if (pos != end) {
743         if ((*pos)->GetStackID() == stack_id)
744           return *pos;
745       }
746     }
747     do {
748       frame_sp = GetFrameAtIndex(frame_idx);
749       if (frame_sp && frame_sp->GetStackID() == stack_id)
750         break;
751       frame_idx++;
752     } while (frame_sp);
753   }
754   return frame_sp;
755 }
756 
757 bool StackFrameList::SetFrameAtIndex(uint32_t idx, StackFrameSP &frame_sp) {
758   if (idx >= m_frames.size())
759     m_frames.resize(idx + 1);
760   // Make sure allocation succeeded by checking bounds again
761   if (idx < m_frames.size()) {
762     m_frames[idx] = frame_sp;
763     return true;
764   }
765   return false; // resize failed, out of memory?
766 }
767 
768 uint32_t StackFrameList::GetSelectedFrameIndex() const {
769   std::lock_guard<std::recursive_mutex> guard(m_mutex);
770   return m_selected_frame_idx;
771 }
772 
773 uint32_t StackFrameList::SetSelectedFrame(lldb_private::StackFrame *frame) {
774   std::lock_guard<std::recursive_mutex> guard(m_mutex);
775   const_iterator pos;
776   const_iterator begin = m_frames.begin();
777   const_iterator end = m_frames.end();
778   m_selected_frame_idx = 0;
779   for (pos = begin; pos != end; ++pos) {
780     if (pos->get() == frame) {
781       m_selected_frame_idx = std::distance(begin, pos);
782       uint32_t inlined_depth = GetCurrentInlinedDepth();
783       if (inlined_depth != UINT32_MAX)
784         m_selected_frame_idx -= inlined_depth;
785       break;
786     }
787   }
788   SetDefaultFileAndLineToSelectedFrame();
789   return m_selected_frame_idx;
790 }
791 
792 bool StackFrameList::SetSelectedFrameByIndex(uint32_t idx) {
793   std::lock_guard<std::recursive_mutex> guard(m_mutex);
794   StackFrameSP frame_sp(GetFrameAtIndex(idx));
795   if (frame_sp) {
796     SetSelectedFrame(frame_sp.get());
797     return true;
798   } else
799     return false;
800 }
801 
802 void StackFrameList::SetDefaultFileAndLineToSelectedFrame() {
803   if (m_thread.GetID() ==
804       m_thread.GetProcess()->GetThreadList().GetSelectedThread()->GetID()) {
805     StackFrameSP frame_sp(GetFrameAtIndex(GetSelectedFrameIndex()));
806     if (frame_sp) {
807       SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextLineEntry);
808       if (sc.line_entry.file)
809         m_thread.CalculateTarget()->GetSourceManager().SetDefaultFileAndLine(
810             sc.line_entry.file, sc.line_entry.line);
811     }
812   }
813 }
814 
815 // The thread has been run, reset the number stack frames to zero so we can
816 // determine how many frames we have lazily.
817 void StackFrameList::Clear() {
818   std::lock_guard<std::recursive_mutex> guard(m_mutex);
819   m_frames.clear();
820   m_concrete_frames_fetched = 0;
821 }
822 
823 void StackFrameList::Merge(std::unique_ptr<StackFrameList> &curr_up,
824                            lldb::StackFrameListSP &prev_sp) {
825   std::unique_lock<std::recursive_mutex> current_lock, previous_lock;
826   if (curr_up)
827     current_lock = std::unique_lock<std::recursive_mutex>(curr_up->m_mutex);
828   if (prev_sp)
829     previous_lock = std::unique_lock<std::recursive_mutex>(prev_sp->m_mutex);
830 
831 #if defined(DEBUG_STACK_FRAMES)
832   StreamFile s(stdout, false);
833   s.PutCString("\n\nStackFrameList::Merge():\nPrev:\n");
834   if (prev_sp)
835     prev_sp->Dump(&s);
836   else
837     s.PutCString("NULL");
838   s.PutCString("\nCurr:\n");
839   if (curr_up)
840     curr_up->Dump(&s);
841   else
842     s.PutCString("NULL");
843   s.EOL();
844 #endif
845 
846   if (!curr_up || curr_up->GetNumFrames(false) == 0) {
847 #if defined(DEBUG_STACK_FRAMES)
848     s.PutCString("No current frames, leave previous frames alone...\n");
849 #endif
850     curr_up.release();
851     return;
852   }
853 
854   if (!prev_sp || prev_sp->GetNumFrames(false) == 0) {
855 #if defined(DEBUG_STACK_FRAMES)
856     s.PutCString("No previous frames, so use current frames...\n");
857 #endif
858     // We either don't have any previous frames, or since we have more than one
859     // current frames it means we have all the frames and can safely replace
860     // our previous frames.
861     prev_sp.reset(curr_up.release());
862     return;
863   }
864 
865   const uint32_t num_curr_frames = curr_up->GetNumFrames(false);
866 
867   if (num_curr_frames > 1) {
868 #if defined(DEBUG_STACK_FRAMES)
869     s.PutCString(
870         "We have more than one current frame, so use current frames...\n");
871 #endif
872     // We have more than one current frames it means we have all the frames and
873     // can safely replace our previous frames.
874     prev_sp.reset(curr_up.release());
875 
876 #if defined(DEBUG_STACK_FRAMES)
877     s.PutCString("\nMerged:\n");
878     prev_sp->Dump(&s);
879 #endif
880     return;
881   }
882 
883   StackFrameSP prev_frame_zero_sp(prev_sp->GetFrameAtIndex(0));
884   StackFrameSP curr_frame_zero_sp(curr_up->GetFrameAtIndex(0));
885   StackID curr_stack_id(curr_frame_zero_sp->GetStackID());
886   StackID prev_stack_id(prev_frame_zero_sp->GetStackID());
887 
888 #if defined(DEBUG_STACK_FRAMES)
889   const uint32_t num_prev_frames = prev_sp->GetNumFrames(false);
890   s.Printf("\n%u previous frames with one current frame\n", num_prev_frames);
891 #endif
892 
893   // We have only a single current frame
894   // Our previous stack frames only had a single frame as well...
895   if (curr_stack_id == prev_stack_id) {
896 #if defined(DEBUG_STACK_FRAMES)
897     s.Printf("\nPrevious frame #0 is same as current frame #0, merge the "
898              "cached data\n");
899 #endif
900 
901     curr_frame_zero_sp->UpdateCurrentFrameFromPreviousFrame(
902         *prev_frame_zero_sp);
903     //        prev_frame_zero_sp->UpdatePreviousFrameFromCurrentFrame
904     //        (*curr_frame_zero_sp);
905     //        prev_sp->SetFrameAtIndex (0, prev_frame_zero_sp);
906   } else if (curr_stack_id < prev_stack_id) {
907 #if defined(DEBUG_STACK_FRAMES)
908     s.Printf("\nCurrent frame #0 has a stack ID that is less than the previous "
909              "frame #0, insert current frame zero in front of previous\n");
910 #endif
911     prev_sp->m_frames.insert(prev_sp->m_frames.begin(), curr_frame_zero_sp);
912   }
913 
914   curr_up.release();
915 
916 #if defined(DEBUG_STACK_FRAMES)
917   s.PutCString("\nMerged:\n");
918   prev_sp->Dump(&s);
919 #endif
920 }
921 
922 lldb::StackFrameSP
923 StackFrameList::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) {
924   const_iterator pos;
925   const_iterator begin = m_frames.begin();
926   const_iterator end = m_frames.end();
927   lldb::StackFrameSP ret_sp;
928 
929   for (pos = begin; pos != end; ++pos) {
930     if (pos->get() == stack_frame_ptr) {
931       ret_sp = (*pos);
932       break;
933     }
934   }
935   return ret_sp;
936 }
937 
938 size_t StackFrameList::GetStatus(Stream &strm, uint32_t first_frame,
939                                  uint32_t num_frames, bool show_frame_info,
940                                  uint32_t num_frames_with_source,
941                                  bool show_unique,
942                                  const char *selected_frame_marker) {
943   size_t num_frames_displayed = 0;
944 
945   if (num_frames == 0)
946     return 0;
947 
948   StackFrameSP frame_sp;
949   uint32_t frame_idx = 0;
950   uint32_t last_frame;
951 
952   // Don't let the last frame wrap around...
953   if (num_frames == UINT32_MAX)
954     last_frame = UINT32_MAX;
955   else
956     last_frame = first_frame + num_frames;
957 
958   StackFrameSP selected_frame_sp = m_thread.GetSelectedFrame();
959   const char *unselected_marker = nullptr;
960   std::string buffer;
961   if (selected_frame_marker) {
962     size_t len = strlen(selected_frame_marker);
963     buffer.insert(buffer.begin(), len, ' ');
964     unselected_marker = buffer.c_str();
965   }
966   const char *marker = nullptr;
967 
968   for (frame_idx = first_frame; frame_idx < last_frame; ++frame_idx) {
969     frame_sp = GetFrameAtIndex(frame_idx);
970     if (!frame_sp)
971       break;
972 
973     if (selected_frame_marker != nullptr) {
974       if (frame_sp == selected_frame_sp)
975         marker = selected_frame_marker;
976       else
977         marker = unselected_marker;
978     }
979 
980     if (!frame_sp->GetStatus(strm, show_frame_info,
981                              num_frames_with_source > (first_frame - frame_idx),
982                              show_unique, marker))
983       break;
984     ++num_frames_displayed;
985   }
986 
987   strm.IndentLess();
988   return num_frames_displayed;
989 }
990