1 //===-- Thread.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 #include "lldb/lldb-private-log.h"
11 #include "lldb/Breakpoint/BreakpointLocation.h"
12 #include "lldb/Core/Debugger.h"
13 #include "lldb/Core/Log.h"
14 #include "lldb/Core/Stream.h"
15 #include "lldb/Core/StreamString.h"
16 #include "lldb/Core/RegularExpression.h"
17 #include "lldb/Host/Host.h"
18 #include "lldb/Symbol/Function.h"
19 #include "lldb/Target/DynamicLoader.h"
20 #include "lldb/Target/ExecutionContext.h"
21 #include "lldb/Target/ObjCLanguageRuntime.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Target/RegisterContext.h"
24 #include "lldb/Target/StopInfo.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Target/Thread.h"
27 #include "lldb/Target/ThreadPlan.h"
28 #include "lldb/Target/ThreadPlanCallFunction.h"
29 #include "lldb/Target/ThreadPlanBase.h"
30 #include "lldb/Target/ThreadPlanStepInstruction.h"
31 #include "lldb/Target/ThreadPlanStepOut.h"
32 #include "lldb/Target/ThreadPlanStepOverBreakpoint.h"
33 #include "lldb/Target/ThreadPlanStepThrough.h"
34 #include "lldb/Target/ThreadPlanStepInRange.h"
35 #include "lldb/Target/ThreadPlanStepOverRange.h"
36 #include "lldb/Target/ThreadPlanRunToAddress.h"
37 #include "lldb/Target/ThreadPlanStepUntil.h"
38 #include "lldb/Target/ThreadSpec.h"
39 #include "lldb/Target/Unwind.h"
40 #include "Plugins/Process/Utility/UnwindLLDB.h"
41 #include "UnwindMacOSXFrameBackchain.h"
42 
43 
44 using namespace lldb;
45 using namespace lldb_private;
46 
47 
48 const ThreadPropertiesSP &
49 Thread::GetGlobalProperties()
50 {
51     static ThreadPropertiesSP g_settings_sp;
52     if (!g_settings_sp)
53         g_settings_sp.reset (new ThreadProperties (true));
54     return g_settings_sp;
55 }
56 
57 static PropertyDefinition
58 g_properties[] =
59 {
60     { "step-avoid-regexp",  OptionValue::eTypeRegex  , true , REG_EXTENDED, "^std::", NULL, "A regular expression defining functions step-in won't stop in." },
61     { "trace-thread",       OptionValue::eTypeBoolean, false, false, NULL, NULL, "If true, this thread will single-step and log execution." },
62     {  NULL               , OptionValue::eTypeInvalid, false, 0    , NULL, NULL, NULL  }
63 };
64 
65 enum {
66     ePropertyStepAvoidRegex,
67     ePropertyEnableThreadTrace
68 };
69 
70 
71 class ThreadOptionValueProperties : public OptionValueProperties
72 {
73 public:
74     ThreadOptionValueProperties (const ConstString &name) :
75         OptionValueProperties (name)
76     {
77     }
78 
79     // This constructor is used when creating ThreadOptionValueProperties when it
80     // is part of a new lldb_private::Thread instance. It will copy all current
81     // global property values as needed
82     ThreadOptionValueProperties (ThreadProperties *global_properties) :
83         OptionValueProperties(*global_properties->GetValueProperties())
84     {
85     }
86 
87     virtual const Property *
88     GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
89     {
90         // When gettings the value for a key from the thread options, we will always
91         // try and grab the setting from the current thread if there is one. Else we just
92         // use the one from this instance.
93         if (exe_ctx)
94         {
95             Thread *thread = exe_ctx->GetThreadPtr();
96             if (thread)
97             {
98                 ThreadOptionValueProperties *instance_properties = static_cast<ThreadOptionValueProperties *>(thread->GetValueProperties().get());
99                 if (this != instance_properties)
100                     return instance_properties->ProtectedGetPropertyAtIndex (idx);
101             }
102         }
103         return ProtectedGetPropertyAtIndex (idx);
104     }
105 };
106 
107 
108 
109 ThreadProperties::ThreadProperties (bool is_global) :
110     Properties ()
111 {
112     if (is_global)
113     {
114         m_collection_sp.reset (new ThreadOptionValueProperties(ConstString("thread")));
115         m_collection_sp->Initialize(g_properties);
116     }
117     else
118         m_collection_sp.reset (new ThreadOptionValueProperties(Thread::GetGlobalProperties().get()));
119 }
120 
121 ThreadProperties::~ThreadProperties()
122 {
123 }
124 
125 const RegularExpression *
126 ThreadProperties::GetSymbolsToAvoidRegexp()
127 {
128     const uint32_t idx = ePropertyStepAvoidRegex;
129     return m_collection_sp->GetPropertyAtIndexAsOptionValueRegex (NULL, idx);
130 }
131 
132 bool
133 ThreadProperties::GetTraceEnabledState() const
134 {
135     const uint32_t idx = ePropertyEnableThreadTrace;
136     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
137 }
138 
139 //------------------------------------------------------------------
140 // Thread Event Data
141 //------------------------------------------------------------------
142 
143 
144 const ConstString &
145 Thread::ThreadEventData::GetFlavorString ()
146 {
147     static ConstString g_flavor ("Thread::ThreadEventData");
148     return g_flavor;
149 }
150 
151 Thread::ThreadEventData::ThreadEventData (const lldb::ThreadSP thread_sp) :
152     m_thread_sp (thread_sp),
153     m_stack_id ()
154 {
155 }
156 
157 Thread::ThreadEventData::ThreadEventData (const lldb::ThreadSP thread_sp, const StackID &stack_id) :
158     m_thread_sp (thread_sp),
159     m_stack_id (stack_id)
160 {
161 }
162 
163 Thread::ThreadEventData::ThreadEventData () :
164     m_thread_sp (),
165     m_stack_id ()
166 {
167 }
168 
169 Thread::ThreadEventData::~ThreadEventData ()
170 {
171 }
172 
173 void
174 Thread::ThreadEventData::Dump (Stream *s) const
175 {
176 
177 }
178 
179 const Thread::ThreadEventData *
180 Thread::ThreadEventData::GetEventDataFromEvent (const Event *event_ptr)
181 {
182     if (event_ptr)
183     {
184         const EventData *event_data = event_ptr->GetData();
185         if (event_data && event_data->GetFlavor() == ThreadEventData::GetFlavorString())
186             return static_cast <const ThreadEventData *> (event_ptr->GetData());
187     }
188     return NULL;
189 }
190 
191 ThreadSP
192 Thread::ThreadEventData::GetThreadFromEvent (const Event *event_ptr)
193 {
194     ThreadSP thread_sp;
195     const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
196     if (event_data)
197         thread_sp = event_data->GetThread();
198     return thread_sp;
199 }
200 
201 StackID
202 Thread::ThreadEventData::GetStackIDFromEvent (const Event *event_ptr)
203 {
204     StackID stack_id;
205     const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
206     if (event_data)
207         stack_id = event_data->GetStackID();
208     return stack_id;
209 }
210 
211 StackFrameSP
212 Thread::ThreadEventData::GetStackFrameFromEvent (const Event *event_ptr)
213 {
214     const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
215     StackFrameSP frame_sp;
216     if (event_data)
217     {
218         ThreadSP thread_sp = event_data->GetThread();
219         if (thread_sp)
220         {
221             frame_sp = thread_sp->GetStackFrameList()->GetFrameWithStackID (event_data->GetStackID());
222         }
223     }
224     return frame_sp;
225 }
226 
227 //------------------------------------------------------------------
228 // Thread class
229 //------------------------------------------------------------------
230 
231 ConstString &
232 Thread::GetStaticBroadcasterClass ()
233 {
234     static ConstString class_name ("lldb.thread");
235     return class_name;
236 }
237 
238 Thread::Thread (Process &process, lldb::tid_t tid) :
239     ThreadProperties (false),
240     UserID (tid),
241     Broadcaster(&process.GetTarget().GetDebugger(), Thread::GetStaticBroadcasterClass().AsCString()),
242     m_process_wp (process.shared_from_this()),
243     m_actual_stop_info_sp (),
244     m_index_id (process.GetNextThreadIndexID ()),
245     m_reg_context_sp (),
246     m_state (eStateUnloaded),
247     m_state_mutex (Mutex::eMutexTypeRecursive),
248     m_plan_stack (),
249     m_completed_plan_stack(),
250     m_frame_mutex (Mutex::eMutexTypeRecursive),
251     m_curr_frames_sp (),
252     m_prev_frames_sp (),
253     m_resume_signal (LLDB_INVALID_SIGNAL_NUMBER),
254     m_resume_state (eStateRunning),
255     m_temporary_resume_state (eStateRunning),
256     m_unwinder_ap (),
257     m_destroy_called (false),
258     m_thread_stop_reason_stop_id (0)
259 
260 {
261     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
262     if (log)
263         log->Printf ("%p Thread::Thread(tid = 0x%4.4llx)", this, GetID());
264 
265     CheckInWithManager();
266     QueueFundamentalPlan(true);
267 }
268 
269 
270 Thread::~Thread()
271 {
272     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
273     if (log)
274         log->Printf ("%p Thread::~Thread(tid = 0x%4.4llx)", this, GetID());
275     /// If you hit this assert, it means your derived class forgot to call DoDestroy in its destructor.
276     assert (m_destroy_called);
277 }
278 
279 void
280 Thread::DestroyThread ()
281 {
282     m_destroy_called = true;
283     m_plan_stack.clear();
284     m_discarded_plan_stack.clear();
285     m_completed_plan_stack.clear();
286     m_actual_stop_info_sp.reset();
287     m_reg_context_sp.reset();
288     m_unwinder_ap.reset();
289     Mutex::Locker locker(m_frame_mutex);
290     m_curr_frames_sp.reset();
291     m_prev_frames_sp.reset();
292 }
293 
294 void
295 Thread::BroadcastSelectedFrameChange(StackID &new_frame_id)
296 {
297     if (EventTypeHasListeners(eBroadcastBitSelectedFrameChanged))
298         BroadcastEvent(eBroadcastBitSelectedFrameChanged, new ThreadEventData (this->shared_from_this(), new_frame_id));
299 }
300 
301 uint32_t
302 Thread::SetSelectedFrame (lldb_private::StackFrame *frame, bool broadcast)
303 {
304     uint32_t ret_value = GetStackFrameList()->SetSelectedFrame(frame);
305     if (broadcast)
306         BroadcastSelectedFrameChange(frame->GetStackID());
307     return ret_value;
308 }
309 
310 bool
311 Thread::SetSelectedFrameByIndex (uint32_t frame_idx, bool broadcast)
312 {
313     StackFrameSP frame_sp(GetStackFrameList()->GetFrameAtIndex (frame_idx));
314     if (frame_sp)
315     {
316         GetStackFrameList()->SetSelectedFrame(frame_sp.get());
317         if (broadcast)
318             BroadcastSelectedFrameChange(frame_sp->GetStackID());
319         return true;
320     }
321     else
322         return false;
323 }
324 
325 
326 lldb::StopInfoSP
327 Thread::GetStopInfo ()
328 {
329     ThreadPlanSP plan_sp (GetCompletedPlan());
330     if (plan_sp && plan_sp->PlanSucceeded())
331         return StopInfo::CreateStopReasonWithPlan (plan_sp, GetReturnValueObject());
332     else
333     {
334         ProcessSP process_sp (GetProcess());
335         if (process_sp
336             && m_actual_stop_info_sp
337             && m_actual_stop_info_sp->IsValid()
338             && m_thread_stop_reason_stop_id == process_sp->GetStopID())
339             return m_actual_stop_info_sp;
340         else
341             return GetPrivateStopReason ();
342     }
343 }
344 
345 lldb::StopReason
346 Thread::GetStopReason()
347 {
348     lldb::StopInfoSP stop_info_sp (GetStopInfo ());
349     if (stop_info_sp)
350         return stop_info_sp->GetStopReason();
351     return eStopReasonNone;
352 }
353 
354 
355 
356 void
357 Thread::SetStopInfo (const lldb::StopInfoSP &stop_info_sp)
358 {
359     m_actual_stop_info_sp = stop_info_sp;
360     if (m_actual_stop_info_sp)
361         m_actual_stop_info_sp->MakeStopInfoValid();
362     ProcessSP process_sp (GetProcess());
363     if (process_sp)
364         m_thread_stop_reason_stop_id = process_sp->GetStopID();
365     else
366         m_thread_stop_reason_stop_id = UINT32_MAX;
367 }
368 
369 void
370 Thread::SetStopInfoToNothing()
371 {
372     // Note, we can't just NULL out the private reason, or the native thread implementation will try to
373     // go calculate it again.  For now, just set it to a Unix Signal with an invalid signal number.
374     SetStopInfo (StopInfo::CreateStopReasonWithSignal (*this,  LLDB_INVALID_SIGNAL_NUMBER));
375 }
376 
377 bool
378 Thread::ThreadStoppedForAReason (void)
379 {
380     return (bool) GetPrivateStopReason ();
381 }
382 
383 bool
384 Thread::CheckpointThreadState (ThreadStateCheckpoint &saved_state)
385 {
386     if (!SaveFrameZeroState(saved_state.register_backup))
387         return false;
388 
389     saved_state.stop_info_sp = GetStopInfo();
390     ProcessSP process_sp (GetProcess());
391     if (process_sp)
392         saved_state.orig_stop_id = process_sp->GetStopID();
393     saved_state.current_inlined_depth = GetCurrentInlinedDepth();
394 
395     return true;
396 }
397 
398 bool
399 Thread::RestoreRegisterStateFromCheckpoint (ThreadStateCheckpoint &saved_state)
400 {
401     RestoreSaveFrameZero(saved_state.register_backup);
402     return true;
403 }
404 
405 bool
406 Thread::RestoreThreadStateFromCheckpoint (ThreadStateCheckpoint &saved_state)
407 {
408     if (saved_state.stop_info_sp)
409         saved_state.stop_info_sp->MakeStopInfoValid();
410     SetStopInfo(saved_state.stop_info_sp);
411     GetStackFrameList()->SetCurrentInlinedDepth (saved_state.current_inlined_depth);
412     return true;
413 }
414 
415 StateType
416 Thread::GetState() const
417 {
418     // If any other threads access this we will need a mutex for it
419     Mutex::Locker locker(m_state_mutex);
420     return m_state;
421 }
422 
423 void
424 Thread::SetState(StateType state)
425 {
426     Mutex::Locker locker(m_state_mutex);
427     m_state = state;
428 }
429 
430 void
431 Thread::WillStop()
432 {
433     ThreadPlan *current_plan = GetCurrentPlan();
434 
435     // FIXME: I may decide to disallow threads with no plans.  In which
436     // case this should go to an assert.
437 
438     if (!current_plan)
439         return;
440 
441     current_plan->WillStop();
442 }
443 
444 void
445 Thread::SetupForResume ()
446 {
447     if (GetResumeState() != eStateSuspended)
448     {
449 
450         // If we're at a breakpoint push the step-over breakpoint plan.  Do this before
451         // telling the current plan it will resume, since we might change what the current
452         // plan is.
453 
454         StopReason stop_reason = lldb::eStopReasonInvalid;
455         StopInfoSP stop_info_sp = GetStopInfo();
456         if (stop_info_sp.get())
457             stop_reason = stop_info_sp->GetStopReason();
458         if (stop_reason == lldb::eStopReasonBreakpoint)
459         {
460             // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the target may not require anything
461             // special to step over a breakpoint.
462 
463             ThreadPlan *cur_plan = GetCurrentPlan();
464 
465             if (cur_plan->GetKind() != ThreadPlan::eKindStepOverBreakpoint)
466             {
467                 ThreadPlanStepOverBreakpoint *step_bp_plan = new ThreadPlanStepOverBreakpoint (*this);
468                 if (step_bp_plan)
469                 {
470                     ThreadPlanSP step_bp_plan_sp;
471                     step_bp_plan->SetPrivate (true);
472 
473                     if (GetCurrentPlan()->RunState() != eStateStepping)
474                     {
475                         step_bp_plan->SetAutoContinue(true);
476                     }
477                     step_bp_plan_sp.reset (step_bp_plan);
478                     QueueThreadPlan (step_bp_plan_sp, false);
479                 }
480             }
481         }
482     }
483 }
484 
485 bool
486 Thread::WillResume (StateType resume_state)
487 {
488     // At this point clear the completed plan stack.
489     m_completed_plan_stack.clear();
490     m_discarded_plan_stack.clear();
491 
492     m_temporary_resume_state = resume_state;
493 
494     // This is a little dubious, but we are trying to limit how often we actually fetch stop info from
495     // the target, 'cause that slows down single stepping.  So assume that if we got to the point where
496     // we're about to resume, and we haven't yet had to fetch the stop reason, then it doesn't need to know
497     // about the fact that we are resuming...
498         const uint32_t process_stop_id = GetProcess()->GetStopID();
499     if (m_thread_stop_reason_stop_id == process_stop_id &&
500         (m_actual_stop_info_sp && m_actual_stop_info_sp->IsValid()))
501     {
502         StopInfo *stop_info = GetPrivateStopReason().get();
503         if (stop_info)
504             stop_info->WillResume (resume_state);
505     }
506 
507     // Tell all the plans that we are about to resume in case they need to clear any state.
508     // We distinguish between the plan on the top of the stack and the lower
509     // plans in case a plan needs to do any special business before it runs.
510 
511     ThreadPlan *plan_ptr = GetCurrentPlan();
512     bool need_to_resume = plan_ptr->WillResume(resume_state, true);
513 
514     while ((plan_ptr = GetPreviousPlan(plan_ptr)) != NULL)
515     {
516         plan_ptr->WillResume (resume_state, false);
517     }
518 
519     // If the WillResume for the plan says we are faking a resume, then it will have set an appropriate stop info.
520     // In that case, don't reset it here.
521 
522     if (need_to_resume && resume_state != eStateSuspended)
523     {
524         m_actual_stop_info_sp.reset();
525     }
526 
527     return need_to_resume;
528 }
529 
530 void
531 Thread::DidResume ()
532 {
533     SetResumeSignal (LLDB_INVALID_SIGNAL_NUMBER);
534 }
535 
536 bool
537 Thread::ShouldStop (Event* event_ptr)
538 {
539     ThreadPlan *current_plan = GetCurrentPlan();
540     bool should_stop = true;
541 
542     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
543 
544     if (GetResumeState () == eStateSuspended)
545     {
546         if (log)
547             log->Printf ("Thread::%s for tid = 0x%4.4llx, should_stop = 0 (ignore since thread was suspended)",
548                          __FUNCTION__,
549                          GetID ());
550 //            log->Printf ("Thread::%s for tid = 0x%4.4llx, pc = 0x%16.16llx, should_stop = 0 (ignore since thread was suspended)",
551 //                         __FUNCTION__,
552 //                         GetID (),
553 //                         GetRegisterContext()->GetPC());
554         return false;
555     }
556 
557     if (GetTemporaryResumeState () == eStateSuspended)
558     {
559         if (log)
560             log->Printf ("Thread::%s for tid = 0x%4.4llx, should_stop = 0 (ignore since thread was suspended)",
561                          __FUNCTION__,
562                          GetID ());
563 //            log->Printf ("Thread::%s for tid = 0x%4.4llx, pc = 0x%16.16llx, should_stop = 0 (ignore since thread was suspended)",
564 //                         __FUNCTION__,
565 //                         GetID (),
566 //                         GetRegisterContext()->GetPC());
567         return false;
568     }
569 
570     if (ThreadStoppedForAReason() == false)
571     {
572         if (log)
573             log->Printf ("Thread::%s for tid = 0x%4.4llx, pc = 0x%16.16llx, should_stop = 0 (ignore since no stop reason)",
574                          __FUNCTION__,
575                          GetID (),
576                          GetRegisterContext()->GetPC());
577         return false;
578     }
579 
580     if (log)
581     {
582         log->Printf ("Thread::%s for tid = 0x%4.4llx, pc = 0x%16.16llx",
583                      __FUNCTION__,
584                      GetID (),
585                      GetRegisterContext()->GetPC());
586         log->Printf ("^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^");
587         StreamString s;
588         s.IndentMore();
589         DumpThreadPlans(&s);
590         log->Printf ("Plan stack initial state:\n%s", s.GetData());
591     }
592 
593     // The top most plan always gets to do the trace log...
594     current_plan->DoTraceLog ();
595 
596     // First query the stop info's ShouldStopSynchronous.  This handles "synchronous" stop reasons, for example the breakpoint
597     // command on internal breakpoints.  If a synchronous stop reason says we should not stop, then we don't have to
598     // do any more work on this stop.
599     StopInfoSP private_stop_info (GetPrivateStopReason());
600     if (private_stop_info && private_stop_info->ShouldStopSynchronous(event_ptr) == false)
601     {
602         if (log)
603             log->Printf ("StopInfo::ShouldStop async callback says we should not stop, returning ShouldStop of false.");
604         return false;
605     }
606 
607     // If we've already been restarted, don't query the plans since the state they would examine is not current.
608     if (Process::ProcessEventData::GetRestartedFromEvent(event_ptr))
609         return false;
610 
611     // Before the plans see the state of the world, calculate the current inlined depth.
612     GetStackFrameList()->CalculateCurrentInlinedDepth();
613 
614     // If the base plan doesn't understand why we stopped, then we have to find a plan that does.
615     // If that plan is still working, then we don't need to do any more work.  If the plan that explains
616     // the stop is done, then we should pop all the plans below it, and pop it, and then let the plans above it decide
617     // whether they still need to do more work.
618 
619     bool done_processing_current_plan = false;
620 
621     if (!current_plan->PlanExplainsStop())
622     {
623         if (current_plan->TracerExplainsStop())
624         {
625             done_processing_current_plan = true;
626             should_stop = false;
627         }
628         else
629         {
630             // If the current plan doesn't explain the stop, then find one that
631             // does and let it handle the situation.
632             ThreadPlan *plan_ptr = current_plan;
633             while ((plan_ptr = GetPreviousPlan(plan_ptr)) != NULL)
634             {
635                 if (plan_ptr->PlanExplainsStop())
636                 {
637                     should_stop = plan_ptr->ShouldStop (event_ptr);
638 
639                     // plan_ptr explains the stop, next check whether plan_ptr is done, if so, then we should take it
640                     // and all the plans below it off the stack.
641 
642                     if (plan_ptr->MischiefManaged())
643                     {
644                         // We're going to pop the plans up to and including the plan that explains the stop.
645                         ThreadPlan *prev_plan_ptr = GetPreviousPlan (plan_ptr);
646 
647                         do
648                         {
649                             if (should_stop)
650                                 current_plan->WillStop();
651                             PopPlan();
652                         }
653                         while ((current_plan = GetCurrentPlan()) != prev_plan_ptr);
654                         // Now, if the responsible plan was not "Okay to discard" then we're done,
655                         // otherwise we forward this to the next plan in the stack below.
656                         if (plan_ptr->IsMasterPlan() && !plan_ptr->OkayToDiscard())
657                             done_processing_current_plan = true;
658                         else
659                             done_processing_current_plan = false;
660                     }
661                     else
662                         done_processing_current_plan = true;
663 
664                     break;
665                 }
666 
667             }
668         }
669     }
670 
671     if (!done_processing_current_plan)
672     {
673         bool over_ride_stop = current_plan->ShouldAutoContinue(event_ptr);
674 
675         if (log)
676             log->Printf("Plan %s explains stop, auto-continue %i.", current_plan->GetName(), over_ride_stop);
677 
678         // We're starting from the base plan, so just let it decide;
679         if (PlanIsBasePlan(current_plan))
680         {
681             should_stop = current_plan->ShouldStop (event_ptr);
682             if (log)
683                 log->Printf("Base plan says should stop: %i.", should_stop);
684         }
685         else
686         {
687             // Otherwise, don't let the base plan override what the other plans say to do, since
688             // presumably if there were other plans they would know what to do...
689             while (1)
690             {
691                 if (PlanIsBasePlan(current_plan))
692                     break;
693 
694                 should_stop = current_plan->ShouldStop(event_ptr);
695                 if (log)
696                     log->Printf("Plan %s should stop: %d.", current_plan->GetName(), should_stop);
697                 if (current_plan->MischiefManaged())
698                 {
699                     if (should_stop)
700                         current_plan->WillStop();
701 
702                     // If a Master Plan wants to stop, and wants to stick on the stack, we let it.
703                     // Otherwise, see if the plan's parent wants to stop.
704 
705                     if (should_stop && current_plan->IsMasterPlan() && !current_plan->OkayToDiscard())
706                     {
707                         PopPlan();
708                         break;
709                     }
710                     else
711                     {
712 
713                         PopPlan();
714 
715                         current_plan = GetCurrentPlan();
716                         if (current_plan == NULL)
717                         {
718                             break;
719                         }
720                     }
721                 }
722                 else
723                 {
724                     break;
725                 }
726             }
727         }
728 
729         if (over_ride_stop)
730             should_stop = false;
731 
732         // One other potential problem is that we set up a master plan, then stop in before it is complete - for instance
733         // by hitting a breakpoint during a step-over - then do some step/finish/etc operations that wind up
734         // past the end point condition of the initial plan.  We don't want to strand the original plan on the stack,
735         // This code clears stale plans off the stack.
736 
737         if (should_stop)
738         {
739             ThreadPlan *plan_ptr = GetCurrentPlan();
740             while (!PlanIsBasePlan(plan_ptr))
741             {
742                 bool stale = plan_ptr->IsPlanStale ();
743                 ThreadPlan *examined_plan = plan_ptr;
744                 plan_ptr = GetPreviousPlan (examined_plan);
745 
746                 if (stale)
747                 {
748                     if (log)
749                         log->Printf("Plan %s being discarded in cleanup, it says it is already done.", examined_plan->GetName());
750                     DiscardThreadPlansUpToPlan(examined_plan);
751                 }
752             }
753         }
754 
755     }
756 
757     if (log)
758     {
759         StreamString s;
760         s.IndentMore();
761         DumpThreadPlans(&s);
762         log->Printf ("Plan stack final state:\n%s", s.GetData());
763         log->Printf ("vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv", should_stop);
764     }
765     return should_stop;
766 }
767 
768 Vote
769 Thread::ShouldReportStop (Event* event_ptr)
770 {
771     StateType thread_state = GetResumeState ();
772     StateType temp_thread_state = GetTemporaryResumeState();
773 
774     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
775 
776     if (thread_state == eStateSuspended || thread_state == eStateInvalid)
777     {
778         if (log)
779             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4llx: returning vote %i (state was suspended or invalid)\n", GetID(), eVoteNoOpinion);
780         return eVoteNoOpinion;
781     }
782 
783     if (temp_thread_state == eStateSuspended || temp_thread_state == eStateInvalid)
784     {
785         if (log)
786             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4llx: returning vote %i (temporary state was suspended or invalid)\n", GetID(), eVoteNoOpinion);
787         return eVoteNoOpinion;
788     }
789 
790     if (!ThreadStoppedForAReason())
791     {
792         if (log)
793             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4llx: returning vote %i (thread didn't stop for a reason.)\n", GetID(), eVoteNoOpinion);
794         return eVoteNoOpinion;
795     }
796 
797     if (m_completed_plan_stack.size() > 0)
798     {
799         // Don't use GetCompletedPlan here, since that suppresses private plans.
800         if (log)
801             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4llx: returning vote  for complete stack's back plan\n", GetID());
802         return m_completed_plan_stack.back()->ShouldReportStop (event_ptr);
803     }
804     else
805     {
806         if (log)
807             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4llx: returning vote  for current plan\n", GetID());
808         return GetCurrentPlan()->ShouldReportStop (event_ptr);
809     }
810 }
811 
812 Vote
813 Thread::ShouldReportRun (Event* event_ptr)
814 {
815     StateType thread_state = GetResumeState ();
816 
817     if (thread_state == eStateSuspended
818             || thread_state == eStateInvalid)
819     {
820         return eVoteNoOpinion;
821     }
822 
823     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
824     if (m_completed_plan_stack.size() > 0)
825     {
826         // Don't use GetCompletedPlan here, since that suppresses private plans.
827         if (log)
828             log->Printf ("Current Plan for thread %d (0x%4.4llx): %s being asked whether we should report run.",
829                          GetIndexID(),
830                          GetID(),
831                          m_completed_plan_stack.back()->GetName());
832 
833         return m_completed_plan_stack.back()->ShouldReportRun (event_ptr);
834     }
835     else
836     {
837         if (log)
838             log->Printf ("Current Plan for thread %d (0x%4.4llx): %s being asked whether we should report run.",
839                          GetIndexID(),
840                          GetID(),
841                          GetCurrentPlan()->GetName());
842 
843         return GetCurrentPlan()->ShouldReportRun (event_ptr);
844      }
845 }
846 
847 bool
848 Thread::MatchesSpec (const ThreadSpec *spec)
849 {
850     if (spec == NULL)
851         return true;
852 
853     return spec->ThreadPassesBasicTests(*this);
854 }
855 
856 void
857 Thread::PushPlan (ThreadPlanSP &thread_plan_sp)
858 {
859     if (thread_plan_sp)
860     {
861         // If the thread plan doesn't already have a tracer, give it its parent's tracer:
862         if (!thread_plan_sp->GetThreadPlanTracer())
863             thread_plan_sp->SetThreadPlanTracer(m_plan_stack.back()->GetThreadPlanTracer());
864         m_plan_stack.push_back (thread_plan_sp);
865 
866         thread_plan_sp->DidPush();
867 
868         LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
869         if (log)
870         {
871             StreamString s;
872             thread_plan_sp->GetDescription (&s, lldb::eDescriptionLevelFull);
873             log->Printf("Pushing plan: \"%s\", tid = 0x%4.4llx.",
874                         s.GetData(),
875                         thread_plan_sp->GetThread().GetID());
876         }
877     }
878 }
879 
880 void
881 Thread::PopPlan ()
882 {
883     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
884 
885     if (m_plan_stack.size() <= 1)
886         return;
887     else
888     {
889         ThreadPlanSP &plan = m_plan_stack.back();
890         if (log)
891         {
892             log->Printf("Popping plan: \"%s\", tid = 0x%4.4llx.", plan->GetName(), plan->GetThread().GetID());
893         }
894         m_completed_plan_stack.push_back (plan);
895         plan->WillPop();
896         m_plan_stack.pop_back();
897     }
898 }
899 
900 void
901 Thread::DiscardPlan ()
902 {
903     if (m_plan_stack.size() > 1)
904     {
905         ThreadPlanSP &plan = m_plan_stack.back();
906         m_discarded_plan_stack.push_back (plan);
907         plan->WillPop();
908         m_plan_stack.pop_back();
909     }
910 }
911 
912 ThreadPlan *
913 Thread::GetCurrentPlan ()
914 {
915     // There will always be at least the base plan.  If somebody is mucking with a
916     // thread with an empty plan stack, we should assert right away.
917     assert (!m_plan_stack.empty());
918 
919     return m_plan_stack.back().get();
920 }
921 
922 ThreadPlanSP
923 Thread::GetCompletedPlan ()
924 {
925     ThreadPlanSP empty_plan_sp;
926     if (!m_completed_plan_stack.empty())
927     {
928         for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
929         {
930             ThreadPlanSP completed_plan_sp;
931             completed_plan_sp = m_completed_plan_stack[i];
932             if (!completed_plan_sp->GetPrivate ())
933             return completed_plan_sp;
934         }
935     }
936     return empty_plan_sp;
937 }
938 
939 ValueObjectSP
940 Thread::GetReturnValueObject ()
941 {
942     if (!m_completed_plan_stack.empty())
943     {
944         for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
945         {
946             ValueObjectSP return_valobj_sp;
947             return_valobj_sp = m_completed_plan_stack[i]->GetReturnValueObject();
948             if (return_valobj_sp)
949             return return_valobj_sp;
950         }
951     }
952     return ValueObjectSP();
953 }
954 
955 bool
956 Thread::IsThreadPlanDone (ThreadPlan *plan)
957 {
958     if (!m_completed_plan_stack.empty())
959     {
960         for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
961         {
962             if (m_completed_plan_stack[i].get() == plan)
963                 return true;
964         }
965     }
966     return false;
967 }
968 
969 bool
970 Thread::WasThreadPlanDiscarded (ThreadPlan *plan)
971 {
972     if (!m_discarded_plan_stack.empty())
973     {
974         for (int i = m_discarded_plan_stack.size() - 1; i >= 0; i--)
975         {
976             if (m_discarded_plan_stack[i].get() == plan)
977                 return true;
978         }
979     }
980     return false;
981 }
982 
983 ThreadPlan *
984 Thread::GetPreviousPlan (ThreadPlan *current_plan)
985 {
986     if (current_plan == NULL)
987         return NULL;
988 
989     int stack_size = m_completed_plan_stack.size();
990     for (int i = stack_size - 1; i > 0; i--)
991     {
992         if (current_plan == m_completed_plan_stack[i].get())
993             return m_completed_plan_stack[i-1].get();
994     }
995 
996     if (stack_size > 0 && m_completed_plan_stack[0].get() == current_plan)
997     {
998         if (m_plan_stack.size() > 0)
999             return m_plan_stack.back().get();
1000         else
1001             return NULL;
1002     }
1003 
1004     stack_size = m_plan_stack.size();
1005     for (int i = stack_size - 1; i > 0; i--)
1006     {
1007         if (current_plan == m_plan_stack[i].get())
1008             return m_plan_stack[i-1].get();
1009     }
1010     return NULL;
1011 }
1012 
1013 void
1014 Thread::QueueThreadPlan (ThreadPlanSP &thread_plan_sp, bool abort_other_plans)
1015 {
1016     if (abort_other_plans)
1017        DiscardThreadPlans(true);
1018 
1019     PushPlan (thread_plan_sp);
1020 }
1021 
1022 
1023 void
1024 Thread::EnableTracer (bool value, bool single_stepping)
1025 {
1026     int stack_size = m_plan_stack.size();
1027     for (int i = 0; i < stack_size; i++)
1028     {
1029         if (m_plan_stack[i]->GetThreadPlanTracer())
1030         {
1031             m_plan_stack[i]->GetThreadPlanTracer()->EnableTracing(value);
1032             m_plan_stack[i]->GetThreadPlanTracer()->EnableSingleStep(single_stepping);
1033         }
1034     }
1035 }
1036 
1037 void
1038 Thread::SetTracer (lldb::ThreadPlanTracerSP &tracer_sp)
1039 {
1040     int stack_size = m_plan_stack.size();
1041     for (int i = 0; i < stack_size; i++)
1042         m_plan_stack[i]->SetThreadPlanTracer(tracer_sp);
1043 }
1044 
1045 void
1046 Thread::DiscardThreadPlansUpToPlan (lldb::ThreadPlanSP &up_to_plan_sp)
1047 {
1048     DiscardThreadPlansUpToPlan (up_to_plan_sp.get());
1049 }
1050 
1051 void
1052 Thread::DiscardThreadPlansUpToPlan (ThreadPlan *up_to_plan_ptr)
1053 {
1054     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1055     if (log)
1056     {
1057         log->Printf("Discarding thread plans for thread tid = 0x%4.4llx, up to %p", GetID(), up_to_plan_ptr);
1058     }
1059 
1060     int stack_size = m_plan_stack.size();
1061 
1062     // If the input plan is NULL, discard all plans.  Otherwise make sure this plan is in the
1063     // stack, and if so discard up to and including it.
1064 
1065     if (up_to_plan_ptr == NULL)
1066     {
1067         for (int i = stack_size - 1; i > 0; i--)
1068             DiscardPlan();
1069     }
1070     else
1071     {
1072         bool found_it = false;
1073         for (int i = stack_size - 1; i > 0; i--)
1074         {
1075             if (m_plan_stack[i].get() == up_to_plan_ptr)
1076                 found_it = true;
1077         }
1078         if (found_it)
1079         {
1080             bool last_one = false;
1081             for (int i = stack_size - 1; i > 0 && !last_one ; i--)
1082             {
1083                 if (GetCurrentPlan() == up_to_plan_ptr)
1084                     last_one = true;
1085                 DiscardPlan();
1086             }
1087         }
1088     }
1089     return;
1090 }
1091 
1092 void
1093 Thread::DiscardThreadPlans(bool force)
1094 {
1095     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1096     if (log)
1097     {
1098         log->Printf("Discarding thread plans for thread (tid = 0x%4.4llx, force %d)", GetID(), force);
1099     }
1100 
1101     if (force)
1102     {
1103         int stack_size = m_plan_stack.size();
1104         for (int i = stack_size - 1; i > 0; i--)
1105         {
1106             DiscardPlan();
1107         }
1108         return;
1109     }
1110 
1111     while (1)
1112     {
1113 
1114         int master_plan_idx;
1115         bool discard = true;
1116 
1117         // Find the first master plan, see if it wants discarding, and if yes discard up to it.
1118         for (master_plan_idx = m_plan_stack.size() - 1; master_plan_idx >= 0; master_plan_idx--)
1119         {
1120             if (m_plan_stack[master_plan_idx]->IsMasterPlan())
1121             {
1122                 discard = m_plan_stack[master_plan_idx]->OkayToDiscard();
1123                 break;
1124             }
1125         }
1126 
1127         if (discard)
1128         {
1129             // First pop all the dependent plans:
1130             for (int i = m_plan_stack.size() - 1; i > master_plan_idx; i--)
1131             {
1132 
1133                 // FIXME: Do we need a finalize here, or is the rule that "PrepareForStop"
1134                 // for the plan leaves it in a state that it is safe to pop the plan
1135                 // with no more notice?
1136                 DiscardPlan();
1137             }
1138 
1139             // Now discard the master plan itself.
1140             // The bottom-most plan never gets discarded.  "OkayToDiscard" for it means
1141             // discard it's dependent plans, but not it...
1142             if (master_plan_idx > 0)
1143             {
1144                 DiscardPlan();
1145             }
1146         }
1147         else
1148         {
1149             // If the master plan doesn't want to get discarded, then we're done.
1150             break;
1151         }
1152 
1153     }
1154 }
1155 
1156 bool
1157 Thread::PlanIsBasePlan (ThreadPlan *plan_ptr)
1158 {
1159     if (plan_ptr->IsBasePlan())
1160         return true;
1161     else if (m_plan_stack.size() == 0)
1162         return false;
1163     else
1164        return m_plan_stack[0].get() == plan_ptr;
1165 }
1166 
1167 ThreadPlan *
1168 Thread::QueueFundamentalPlan (bool abort_other_plans)
1169 {
1170     ThreadPlanSP thread_plan_sp (new ThreadPlanBase(*this));
1171     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1172     return thread_plan_sp.get();
1173 }
1174 
1175 ThreadPlan *
1176 Thread::QueueThreadPlanForStepSingleInstruction
1177 (
1178     bool step_over,
1179     bool abort_other_plans,
1180     bool stop_other_threads
1181 )
1182 {
1183     ThreadPlanSP thread_plan_sp (new ThreadPlanStepInstruction (*this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
1184     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1185     return thread_plan_sp.get();
1186 }
1187 
1188 ThreadPlan *
1189 Thread::QueueThreadPlanForStepRange
1190 (
1191     bool abort_other_plans,
1192     StepType type,
1193     const AddressRange &range,
1194     const SymbolContext &addr_context,
1195     lldb::RunMode stop_other_threads,
1196     bool avoid_code_without_debug_info
1197 )
1198 {
1199     ThreadPlanSP thread_plan_sp;
1200     if (type == eStepTypeInto)
1201     {
1202         ThreadPlanStepInRange *plan = new ThreadPlanStepInRange (*this, range, addr_context, stop_other_threads);
1203         if (avoid_code_without_debug_info)
1204             plan->GetFlags().Set (ThreadPlanShouldStopHere::eAvoidNoDebug);
1205         else
1206             plan->GetFlags().Clear (ThreadPlanShouldStopHere::eAvoidNoDebug);
1207         thread_plan_sp.reset (plan);
1208     }
1209     else
1210         thread_plan_sp.reset (new ThreadPlanStepOverRange (*this, range, addr_context, stop_other_threads));
1211 
1212     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1213     return thread_plan_sp.get();
1214 }
1215 
1216 
1217 ThreadPlan *
1218 Thread::QueueThreadPlanForStepOverBreakpointPlan (bool abort_other_plans)
1219 {
1220     ThreadPlanSP thread_plan_sp (new ThreadPlanStepOverBreakpoint (*this));
1221     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1222     return thread_plan_sp.get();
1223 }
1224 
1225 ThreadPlan *
1226 Thread::QueueThreadPlanForStepOut
1227 (
1228     bool abort_other_plans,
1229     SymbolContext *addr_context,
1230     bool first_insn,
1231     bool stop_other_threads,
1232     Vote stop_vote,
1233     Vote run_vote,
1234     uint32_t frame_idx
1235 )
1236 {
1237     ThreadPlanSP thread_plan_sp (new ThreadPlanStepOut (*this,
1238                                                         addr_context,
1239                                                         first_insn,
1240                                                         stop_other_threads,
1241                                                         stop_vote,
1242                                                         run_vote,
1243                                                         frame_idx));
1244 
1245     if (thread_plan_sp->ValidatePlan(NULL))
1246     {
1247         QueueThreadPlan (thread_plan_sp, abort_other_plans);
1248         return thread_plan_sp.get();
1249     }
1250     else
1251     {
1252         return NULL;
1253     }
1254 }
1255 
1256 ThreadPlan *
1257 Thread::QueueThreadPlanForStepThrough (StackID &return_stack_id, bool abort_other_plans, bool stop_other_threads)
1258 {
1259     ThreadPlanSP thread_plan_sp(new ThreadPlanStepThrough (*this, return_stack_id, stop_other_threads));
1260     if (!thread_plan_sp || !thread_plan_sp->ValidatePlan (NULL))
1261         return NULL;
1262 
1263     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1264     return thread_plan_sp.get();
1265 }
1266 
1267 ThreadPlan *
1268 Thread::QueueThreadPlanForCallFunction (bool abort_other_plans,
1269                                         Address& function,
1270                                         lldb::addr_t arg,
1271                                         bool stop_other_threads,
1272                                         bool discard_on_error)
1273 {
1274     ThreadPlanSP thread_plan_sp (new ThreadPlanCallFunction (*this, function, ClangASTType(), arg, stop_other_threads, discard_on_error));
1275     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1276     return thread_plan_sp.get();
1277 }
1278 
1279 ThreadPlan *
1280 Thread::QueueThreadPlanForRunToAddress (bool abort_other_plans,
1281                                         Address &target_addr,
1282                                         bool stop_other_threads)
1283 {
1284     ThreadPlanSP thread_plan_sp (new ThreadPlanRunToAddress (*this, target_addr, stop_other_threads));
1285     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1286     return thread_plan_sp.get();
1287 }
1288 
1289 ThreadPlan *
1290 Thread::QueueThreadPlanForStepUntil (bool abort_other_plans,
1291                                      lldb::addr_t *address_list,
1292                                      size_t num_addresses,
1293                                      bool stop_other_threads,
1294                                      uint32_t frame_idx)
1295 {
1296     ThreadPlanSP thread_plan_sp (new ThreadPlanStepUntil (*this, address_list, num_addresses, stop_other_threads, frame_idx));
1297     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1298     return thread_plan_sp.get();
1299 
1300 }
1301 
1302 uint32_t
1303 Thread::GetIndexID () const
1304 {
1305     return m_index_id;
1306 }
1307 
1308 void
1309 Thread::DumpThreadPlans (lldb_private::Stream *s) const
1310 {
1311     uint32_t stack_size = m_plan_stack.size();
1312     int i;
1313     s->Indent();
1314     s->Printf ("Plan Stack for thread #%u: tid = 0x%4.4llx, stack_size = %d\n", GetIndexID(), GetID(), stack_size);
1315     for (i = stack_size - 1; i >= 0; i--)
1316     {
1317         s->IndentMore();
1318         s->Indent();
1319         s->Printf ("Element %d: ", i);
1320         m_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
1321         s->EOL();
1322         s->IndentLess();
1323     }
1324 
1325     stack_size = m_completed_plan_stack.size();
1326     if (stack_size > 0)
1327     {
1328         s->Indent();
1329         s->Printf ("Completed Plan Stack: %d elements.\n", stack_size);
1330         for (i = stack_size - 1; i >= 0; i--)
1331         {
1332             s->IndentMore();
1333             s->Indent();
1334             s->Printf ("Element %d: ", i);
1335             m_completed_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
1336             s->EOL();
1337             s->IndentLess();
1338         }
1339     }
1340 
1341     stack_size = m_discarded_plan_stack.size();
1342     if (stack_size > 0)
1343     {
1344         s->Indent();
1345         s->Printf ("Discarded Plan Stack: %d elements.\n", stack_size);
1346         for (i = stack_size - 1; i >= 0; i--)
1347         {
1348             s->IndentMore();
1349             s->Indent();
1350             s->Printf ("Element %d: ", i);
1351             m_discarded_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
1352             s->EOL();
1353             s->IndentLess();
1354         }
1355     }
1356 
1357 }
1358 
1359 TargetSP
1360 Thread::CalculateTarget ()
1361 {
1362     TargetSP target_sp;
1363     ProcessSP process_sp(GetProcess());
1364     if (process_sp)
1365         target_sp = process_sp->CalculateTarget();
1366     return target_sp;
1367 
1368 }
1369 
1370 ProcessSP
1371 Thread::CalculateProcess ()
1372 {
1373     return GetProcess();
1374 }
1375 
1376 ThreadSP
1377 Thread::CalculateThread ()
1378 {
1379     return shared_from_this();
1380 }
1381 
1382 StackFrameSP
1383 Thread::CalculateStackFrame ()
1384 {
1385     return StackFrameSP();
1386 }
1387 
1388 void
1389 Thread::CalculateExecutionContext (ExecutionContext &exe_ctx)
1390 {
1391     exe_ctx.SetContext (shared_from_this());
1392 }
1393 
1394 
1395 StackFrameListSP
1396 Thread::GetStackFrameList ()
1397 {
1398     StackFrameListSP frame_list_sp;
1399     Mutex::Locker locker(m_frame_mutex);
1400     if (m_curr_frames_sp)
1401     {
1402         frame_list_sp = m_curr_frames_sp;
1403     }
1404     else
1405     {
1406         frame_list_sp.reset(new StackFrameList (*this, m_prev_frames_sp, true));
1407         m_curr_frames_sp = frame_list_sp;
1408     }
1409     return frame_list_sp;
1410 }
1411 
1412 void
1413 Thread::ClearStackFrames ()
1414 {
1415     Mutex::Locker locker(m_frame_mutex);
1416 
1417     // Only store away the old "reference" StackFrameList if we got all its frames:
1418     // FIXME: At some point we can try to splice in the frames we have fetched into
1419     // the new frame as we make it, but let's not try that now.
1420     if (m_curr_frames_sp && m_curr_frames_sp->GetAllFramesFetched())
1421         m_prev_frames_sp.swap (m_curr_frames_sp);
1422     m_curr_frames_sp.reset();
1423 }
1424 
1425 lldb::StackFrameSP
1426 Thread::GetFrameWithConcreteFrameIndex (uint32_t unwind_idx)
1427 {
1428     return GetStackFrameList()->GetFrameWithConcreteFrameIndex (unwind_idx);
1429 }
1430 
1431 
1432 Error
1433 Thread::ReturnFromFrameWithIndex (uint32_t frame_idx, lldb::ValueObjectSP return_value_sp, bool broadcast)
1434 {
1435     StackFrameSP frame_sp = GetStackFrameAtIndex (frame_idx);
1436     Error return_error;
1437 
1438     if (!frame_sp)
1439     {
1440         return_error.SetErrorStringWithFormat("Could not find frame with index %d in thread 0x%llx.", frame_idx, GetID());
1441     }
1442 
1443     return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
1444 }
1445 
1446 Error
1447 Thread::ReturnFromFrame (lldb::StackFrameSP frame_sp, lldb::ValueObjectSP return_value_sp, bool broadcast)
1448 {
1449     Error return_error;
1450 
1451     if (!frame_sp)
1452     {
1453         return_error.SetErrorString("Can't return to a null frame.");
1454         return return_error;
1455     }
1456 
1457     Thread *thread = frame_sp->GetThread().get();
1458     uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
1459     StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
1460 
1461     if (return_value_sp)
1462     {
1463         lldb::ABISP abi = thread->GetProcess()->GetABI();
1464         if (!abi)
1465         {
1466             return_error.SetErrorString("Could not find ABI to set return value.");
1467             return return_error;
1468         }
1469         SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
1470 
1471         // FIXME: ValueObject::Cast doesn't currently work correctly, at least not for scalars.
1472         // Turn that back on when that works.
1473         if (0 && sc.function != NULL)
1474         {
1475             Type *function_type = sc.function->GetType();
1476             if (function_type)
1477             {
1478                 clang_type_t return_type = sc.function->GetReturnClangType();
1479                 if (return_type)
1480                 {
1481                     ClangASTType ast_type (function_type->GetClangAST(), return_type);
1482                     StreamString s;
1483                     ast_type.DumpTypeDescription(&s);
1484                     ValueObjectSP cast_value_sp = return_value_sp->Cast(ast_type);
1485                     if (cast_value_sp)
1486                     {
1487                         cast_value_sp->SetFormat(eFormatHex);
1488                         return_value_sp = cast_value_sp;
1489                     }
1490                 }
1491             }
1492         }
1493 
1494         return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
1495         if (!return_error.Success())
1496             return return_error;
1497     }
1498 
1499     // Now write the return registers for the chosen frame:
1500     // Note, we can't use ReadAllRegisterValues->WriteAllRegisterValues, since the read & write
1501     // cook their data
1502     bool copy_success = thread->GetStackFrameAtIndex(0)->GetRegisterContext()->CopyFromRegisterContext(older_frame_sp->GetRegisterContext());
1503     if (copy_success)
1504     {
1505         thread->DiscardThreadPlans(true);
1506         thread->ClearStackFrames();
1507         if (broadcast && EventTypeHasListeners(eBroadcastBitStackChanged))
1508             BroadcastEvent(eBroadcastBitStackChanged, new ThreadEventData (this->shared_from_this()));
1509         return return_error;
1510     }
1511     else
1512     {
1513         return_error.SetErrorString("Could not reset register values.");
1514         return return_error;
1515     }
1516 }
1517 
1518 void
1519 Thread::DumpUsingSettingsFormat (Stream &strm, uint32_t frame_idx)
1520 {
1521     ExecutionContext exe_ctx (shared_from_this());
1522     Process *process = exe_ctx.GetProcessPtr();
1523     if (process == NULL)
1524         return;
1525 
1526     StackFrameSP frame_sp;
1527     SymbolContext frame_sc;
1528     if (frame_idx != LLDB_INVALID_INDEX32)
1529     {
1530         frame_sp = GetStackFrameAtIndex (frame_idx);
1531         if (frame_sp)
1532         {
1533             exe_ctx.SetFrameSP(frame_sp);
1534             frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
1535         }
1536     }
1537 
1538     const char *thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
1539     assert (thread_format);
1540     const char *end = NULL;
1541     Debugger::FormatPrompt (thread_format,
1542                             frame_sp ? &frame_sc : NULL,
1543                             &exe_ctx,
1544                             NULL,
1545                             strm,
1546                             &end);
1547 }
1548 
1549 void
1550 Thread::SettingsInitialize ()
1551 {
1552 }
1553 
1554 void
1555 Thread::SettingsTerminate ()
1556 {
1557 }
1558 
1559 lldb::StackFrameSP
1560 Thread::GetStackFrameSPForStackFramePtr (StackFrame *stack_frame_ptr)
1561 {
1562     return GetStackFrameList()->GetStackFrameSPForStackFramePtr (stack_frame_ptr);
1563 }
1564 
1565 const char *
1566 Thread::StopReasonAsCString (lldb::StopReason reason)
1567 {
1568     switch (reason)
1569     {
1570     case eStopReasonInvalid:      return "invalid";
1571     case eStopReasonNone:         return "none";
1572     case eStopReasonTrace:        return "trace";
1573     case eStopReasonBreakpoint:   return "breakpoint";
1574     case eStopReasonWatchpoint:   return "watchpoint";
1575     case eStopReasonSignal:       return "signal";
1576     case eStopReasonException:    return "exception";
1577     case eStopReasonPlanComplete: return "plan complete";
1578     }
1579 
1580 
1581     static char unknown_state_string[64];
1582     snprintf(unknown_state_string, sizeof (unknown_state_string), "StopReason = %i", reason);
1583     return unknown_state_string;
1584 }
1585 
1586 const char *
1587 Thread::RunModeAsCString (lldb::RunMode mode)
1588 {
1589     switch (mode)
1590     {
1591     case eOnlyThisThread:     return "only this thread";
1592     case eAllThreads:         return "all threads";
1593     case eOnlyDuringStepping: return "only during stepping";
1594     }
1595 
1596     static char unknown_state_string[64];
1597     snprintf(unknown_state_string, sizeof (unknown_state_string), "RunMode = %i", mode);
1598     return unknown_state_string;
1599 }
1600 
1601 size_t
1602 Thread::GetStatus (Stream &strm, uint32_t start_frame, uint32_t num_frames, uint32_t num_frames_with_source)
1603 {
1604     ExecutionContext exe_ctx (shared_from_this());
1605     Target *target = exe_ctx.GetTargetPtr();
1606     Process *process = exe_ctx.GetProcessPtr();
1607     size_t num_frames_shown = 0;
1608     strm.Indent();
1609     bool is_selected = false;
1610     if (process)
1611     {
1612         if (process->GetThreadList().GetSelectedThread().get() == this)
1613             is_selected = true;
1614     }
1615     strm.Printf("%c ", is_selected ? '*' : ' ');
1616     if (target && target->GetDebugger().GetUseExternalEditor())
1617     {
1618         StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
1619         if (frame_sp)
1620         {
1621             SymbolContext frame_sc(frame_sp->GetSymbolContext (eSymbolContextLineEntry));
1622             if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file)
1623             {
1624                 Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line);
1625             }
1626         }
1627     }
1628 
1629     DumpUsingSettingsFormat (strm, start_frame);
1630 
1631     if (num_frames > 0)
1632     {
1633         strm.IndentMore();
1634 
1635         const bool show_frame_info = true;
1636         strm.IndentMore ();
1637         num_frames_shown = GetStackFrameList ()->GetStatus (strm,
1638                                                             start_frame,
1639                                                             num_frames,
1640                                                             show_frame_info,
1641                                                             num_frames_with_source);
1642         strm.IndentLess();
1643         strm.IndentLess();
1644     }
1645     return num_frames_shown;
1646 }
1647 
1648 size_t
1649 Thread::GetStackFrameStatus (Stream& strm,
1650                              uint32_t first_frame,
1651                              uint32_t num_frames,
1652                              bool show_frame_info,
1653                              uint32_t num_frames_with_source)
1654 {
1655     return GetStackFrameList()->GetStatus (strm,
1656                                            first_frame,
1657                                            num_frames,
1658                                            show_frame_info,
1659                                            num_frames_with_source);
1660 }
1661 
1662 bool
1663 Thread::SaveFrameZeroState (RegisterCheckpoint &checkpoint)
1664 {
1665     lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
1666     if (frame_sp)
1667     {
1668         checkpoint.SetStackID(frame_sp->GetStackID());
1669         return frame_sp->GetRegisterContext()->ReadAllRegisterValues (checkpoint.GetData());
1670     }
1671     return false;
1672 }
1673 
1674 bool
1675 Thread::RestoreSaveFrameZero (const RegisterCheckpoint &checkpoint)
1676 {
1677     return ResetFrameZeroRegisters (checkpoint.GetData());
1678 }
1679 
1680 bool
1681 Thread::ResetFrameZeroRegisters (lldb::DataBufferSP register_data_sp)
1682 {
1683     lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
1684     if (frame_sp)
1685     {
1686         bool ret = frame_sp->GetRegisterContext()->WriteAllRegisterValues (register_data_sp);
1687 
1688         // Clear out all stack frames as our world just changed.
1689         ClearStackFrames();
1690         frame_sp->GetRegisterContext()->InvalidateIfNeeded(true);
1691         if (m_unwinder_ap.get())
1692             m_unwinder_ap->Clear();
1693 
1694         return ret;
1695     }
1696     return false;
1697 }
1698 
1699 Unwind *
1700 Thread::GetUnwinder ()
1701 {
1702     if (m_unwinder_ap.get() == NULL)
1703     {
1704         const ArchSpec target_arch (CalculateTarget()->GetArchitecture ());
1705         const llvm::Triple::ArchType machine = target_arch.GetMachine();
1706         switch (machine)
1707         {
1708             case llvm::Triple::x86_64:
1709             case llvm::Triple::x86:
1710             case llvm::Triple::arm:
1711             case llvm::Triple::thumb:
1712                 m_unwinder_ap.reset (new UnwindLLDB (*this));
1713                 break;
1714 
1715             default:
1716                 if (target_arch.GetTriple().getVendor() == llvm::Triple::Apple)
1717                     m_unwinder_ap.reset (new UnwindMacOSXFrameBackchain (*this));
1718                 break;
1719         }
1720     }
1721     return m_unwinder_ap.get();
1722 }
1723 
1724 
1725 void
1726 Thread::Flush ()
1727 {
1728     ClearStackFrames ();
1729     m_reg_context_sp.reset();
1730 }
1731 
1732 bool
1733 Thread::IsStillAtLastBreakpointHit ()
1734 {
1735     // If we are currently stopped at a breakpoint, always return that stopinfo and don't reset it.
1736     // This allows threads to maintain their breakpoint stopinfo, such as when thread-stepping in
1737     // multithreaded programs.
1738     if (m_actual_stop_info_sp) {
1739         StopReason stop_reason = m_actual_stop_info_sp->GetStopReason();
1740         if (stop_reason == lldb::eStopReasonBreakpoint) {
1741             uint64_t value = m_actual_stop_info_sp->GetValue();
1742             lldb::addr_t pc = GetRegisterContext()->GetPC();
1743             BreakpointSiteSP bp_site_sp = GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1744             if (bp_site_sp && value == bp_site_sp->GetID())
1745                 return true;
1746         }
1747     }
1748     return false;
1749 }
1750