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