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