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