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