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