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/Interpreter/OptionValueFileSpecList.h"
22 #include "lldb/Symbol/Function.h"
23 #include "lldb/Target/DynamicLoader.h"
24 #include "lldb/Target/ExecutionContext.h"
25 #include "lldb/Target/ObjCLanguageRuntime.h"
26 #include "lldb/Target/Process.h"
27 #include "lldb/Target/RegisterContext.h"
28 #include "lldb/Target/StopInfo.h"
29 #include "lldb/Target/SystemRuntime.h"
30 #include "lldb/Target/Target.h"
31 #include "lldb/Target/Thread.h"
32 #include "lldb/Target/ThreadPlan.h"
33 #include "lldb/Target/ThreadPlanCallFunction.h"
34 #include "lldb/Target/ThreadPlanBase.h"
35 #include "lldb/Target/ThreadPlanStepInstruction.h"
36 #include "lldb/Target/ThreadPlanStepOut.h"
37 #include "lldb/Target/ThreadPlanStepOverBreakpoint.h"
38 #include "lldb/Target/ThreadPlanStepThrough.h"
39 #include "lldb/Target/ThreadPlanStepInRange.h"
40 #include "lldb/Target/ThreadPlanStepOverRange.h"
41 #include "lldb/Target/ThreadPlanRunToAddress.h"
42 #include "lldb/Target/ThreadPlanStepUntil.h"
43 #include "lldb/Target/ThreadSpec.h"
44 #include "lldb/Target/Unwind.h"
45 #include "Plugins/Process/Utility/UnwindLLDB.h"
46 #include "UnwindMacOSXFrameBackchain.h"
47 
48 
49 using namespace lldb;
50 using namespace lldb_private;
51 
52 
53 const ThreadPropertiesSP &
54 Thread::GetGlobalProperties()
55 {
56     static ThreadPropertiesSP g_settings_sp;
57     if (!g_settings_sp)
58         g_settings_sp.reset (new ThreadProperties (true));
59     return g_settings_sp;
60 }
61 
62 static PropertyDefinition
63 g_properties[] =
64 {
65     { "step-in-avoid-nodebug", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, step-in will not stop in functions with no debug information." },
66     { "step-out-avoid-nodebug", OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, when step-in/step-out/step-over leave the current frame, they will continue to step out till they come to a function with "
67                                                                                     "debug information.  Passing a frame argument to step-out will override this option." },
68     { "step-avoid-regexp",  OptionValue::eTypeRegex  , true , REG_EXTENDED, "^std::", NULL, "A regular expression defining functions step-in won't stop in." },
69     { "step-avoid-libraries",  OptionValue::eTypeFileSpecList  , true , REG_EXTENDED, NULL, NULL, "A list of libraries that source stepping won't stop in." },
70     { "trace-thread",       OptionValue::eTypeBoolean, false, false, NULL, NULL, "If true, this thread will single-step and log execution." },
71     {  NULL               , OptionValue::eTypeInvalid, false, 0    , NULL, NULL, NULL  }
72 };
73 
74 enum {
75     ePropertyStepInAvoidsNoDebug,
76     ePropertyStepOutAvoidsNoDebug,
77     ePropertyStepAvoidRegex,
78     ePropertyStepAvoidLibraries,
79     ePropertyEnableThreadTrace
80 };
81 
82 
83 class ThreadOptionValueProperties : public OptionValueProperties
84 {
85 public:
86     ThreadOptionValueProperties (const ConstString &name) :
87         OptionValueProperties (name)
88     {
89     }
90 
91     // This constructor is used when creating ThreadOptionValueProperties when it
92     // is part of a new lldb_private::Thread instance. It will copy all current
93     // global property values as needed
94     ThreadOptionValueProperties (ThreadProperties *global_properties) :
95         OptionValueProperties(*global_properties->GetValueProperties())
96     {
97     }
98 
99     virtual const Property *
100     GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
101     {
102         // When gettings the value for a key from the thread options, we will always
103         // try and grab the setting from the current thread if there is one. Else we just
104         // use the one from this instance.
105         if (exe_ctx)
106         {
107             Thread *thread = exe_ctx->GetThreadPtr();
108             if (thread)
109             {
110                 ThreadOptionValueProperties *instance_properties = static_cast<ThreadOptionValueProperties *>(thread->GetValueProperties().get());
111                 if (this != instance_properties)
112                     return instance_properties->ProtectedGetPropertyAtIndex (idx);
113             }
114         }
115         return ProtectedGetPropertyAtIndex (idx);
116     }
117 };
118 
119 
120 
121 ThreadProperties::ThreadProperties (bool is_global) :
122     Properties ()
123 {
124     if (is_global)
125     {
126         m_collection_sp.reset (new ThreadOptionValueProperties(ConstString("thread")));
127         m_collection_sp->Initialize(g_properties);
128     }
129     else
130         m_collection_sp.reset (new ThreadOptionValueProperties(Thread::GetGlobalProperties().get()));
131 }
132 
133 ThreadProperties::~ThreadProperties()
134 {
135 }
136 
137 const RegularExpression *
138 ThreadProperties::GetSymbolsToAvoidRegexp()
139 {
140     const uint32_t idx = ePropertyStepAvoidRegex;
141     return m_collection_sp->GetPropertyAtIndexAsOptionValueRegex (NULL, idx);
142 }
143 
144 FileSpecList &
145 ThreadProperties::GetLibrariesToAvoid() const
146 {
147     const uint32_t idx = ePropertyStepAvoidLibraries;
148     OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
149     assert(option_value);
150     return option_value->GetCurrentValue();
151 }
152 
153 bool
154 ThreadProperties::GetTraceEnabledState() const
155 {
156     const uint32_t idx = ePropertyEnableThreadTrace;
157     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
158 }
159 
160 bool
161 ThreadProperties::GetStepInAvoidsNoDebug() const
162 {
163     const uint32_t idx = ePropertyStepInAvoidsNoDebug;
164     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
165 }
166 
167 bool
168 ThreadProperties::GetStepOutAvoidsNoDebug() const
169 {
170     const uint32_t idx = ePropertyStepOutAvoidsNoDebug;
171     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
172 }
173 
174 
175 //------------------------------------------------------------------
176 // Thread Event Data
177 //------------------------------------------------------------------
178 
179 
180 const ConstString &
181 Thread::ThreadEventData::GetFlavorString ()
182 {
183     static ConstString g_flavor ("Thread::ThreadEventData");
184     return g_flavor;
185 }
186 
187 Thread::ThreadEventData::ThreadEventData (const lldb::ThreadSP thread_sp) :
188     m_thread_sp (thread_sp),
189     m_stack_id ()
190 {
191 }
192 
193 Thread::ThreadEventData::ThreadEventData (const lldb::ThreadSP thread_sp, const StackID &stack_id) :
194     m_thread_sp (thread_sp),
195     m_stack_id (stack_id)
196 {
197 }
198 
199 Thread::ThreadEventData::ThreadEventData () :
200     m_thread_sp (),
201     m_stack_id ()
202 {
203 }
204 
205 Thread::ThreadEventData::~ThreadEventData ()
206 {
207 }
208 
209 void
210 Thread::ThreadEventData::Dump (Stream *s) const
211 {
212 
213 }
214 
215 const Thread::ThreadEventData *
216 Thread::ThreadEventData::GetEventDataFromEvent (const Event *event_ptr)
217 {
218     if (event_ptr)
219     {
220         const EventData *event_data = event_ptr->GetData();
221         if (event_data && event_data->GetFlavor() == ThreadEventData::GetFlavorString())
222             return static_cast <const ThreadEventData *> (event_ptr->GetData());
223     }
224     return NULL;
225 }
226 
227 ThreadSP
228 Thread::ThreadEventData::GetThreadFromEvent (const Event *event_ptr)
229 {
230     ThreadSP thread_sp;
231     const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
232     if (event_data)
233         thread_sp = event_data->GetThread();
234     return thread_sp;
235 }
236 
237 StackID
238 Thread::ThreadEventData::GetStackIDFromEvent (const Event *event_ptr)
239 {
240     StackID stack_id;
241     const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
242     if (event_data)
243         stack_id = event_data->GetStackID();
244     return stack_id;
245 }
246 
247 StackFrameSP
248 Thread::ThreadEventData::GetStackFrameFromEvent (const Event *event_ptr)
249 {
250     const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
251     StackFrameSP frame_sp;
252     if (event_data)
253     {
254         ThreadSP thread_sp = event_data->GetThread();
255         if (thread_sp)
256         {
257             frame_sp = thread_sp->GetStackFrameList()->GetFrameWithStackID (event_data->GetStackID());
258         }
259     }
260     return frame_sp;
261 }
262 
263 //------------------------------------------------------------------
264 // Thread class
265 //------------------------------------------------------------------
266 
267 ConstString &
268 Thread::GetStaticBroadcasterClass ()
269 {
270     static ConstString class_name ("lldb.thread");
271     return class_name;
272 }
273 
274 Thread::Thread (Process &process, lldb::tid_t tid, bool use_invalid_index_id) :
275     ThreadProperties (false),
276     UserID (tid),
277     Broadcaster(&process.GetTarget().GetDebugger(), Thread::GetStaticBroadcasterClass().AsCString()),
278     m_process_wp (process.shared_from_this()),
279     m_stop_info_sp (),
280     m_stop_info_stop_id (0),
281     m_index_id (use_invalid_index_id ? LLDB_INVALID_INDEX32 : process.GetNextThreadIndexID(tid)),
282     m_reg_context_sp (),
283     m_state (eStateUnloaded),
284     m_state_mutex (Mutex::eMutexTypeRecursive),
285     m_plan_stack (),
286     m_completed_plan_stack(),
287     m_frame_mutex (Mutex::eMutexTypeRecursive),
288     m_curr_frames_sp (),
289     m_prev_frames_sp (),
290     m_resume_signal (LLDB_INVALID_SIGNAL_NUMBER),
291     m_resume_state (eStateRunning),
292     m_temporary_resume_state (eStateRunning),
293     m_unwinder_ap (),
294     m_destroy_called (false),
295     m_override_should_notify (eLazyBoolCalculate),
296     m_extended_info_fetched (false),
297     m_extended_info ()
298 {
299     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
300     if (log)
301         log->Printf ("%p Thread::Thread(tid = 0x%4.4" PRIx64 ")",
302                      static_cast<void*>(this), GetID());
303 
304     CheckInWithManager();
305     QueueFundamentalPlan(true);
306 }
307 
308 
309 Thread::~Thread()
310 {
311     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
312     if (log)
313         log->Printf ("%p Thread::~Thread(tid = 0x%4.4" PRIx64 ")",
314                      static_cast<void*>(this), GetID());
315     /// If you hit this assert, it means your derived class forgot to call DoDestroy in its destructor.
316     assert (m_destroy_called);
317 }
318 
319 void
320 Thread::DestroyThread ()
321 {
322     // Tell any plans on the plan stacks that the thread is being destroyed since
323     // any plans that have a thread go away in the middle of might need
324     // to do cleanup, or in some cases NOT do cleanup...
325     for (auto plan : m_plan_stack)
326         plan->ThreadDestroyed();
327 
328     for (auto plan : m_discarded_plan_stack)
329         plan->ThreadDestroyed();
330 
331     for (auto plan : m_completed_plan_stack)
332         plan->ThreadDestroyed();
333 
334     m_destroy_called = true;
335     m_plan_stack.clear();
336     m_discarded_plan_stack.clear();
337     m_completed_plan_stack.clear();
338 
339     // Push a ThreadPlanNull on the plan stack.  That way we can continue assuming that the
340     // plan stack is never empty, but if somebody errantly asks questions of a destroyed thread
341     // without checking first whether it is destroyed, they won't crash.
342     ThreadPlanSP null_plan_sp(new ThreadPlanNull (*this));
343     m_plan_stack.push_back (null_plan_sp);
344 
345     m_stop_info_sp.reset();
346     m_reg_context_sp.reset();
347     m_unwinder_ap.reset();
348     Mutex::Locker locker(m_frame_mutex);
349     m_curr_frames_sp.reset();
350     m_prev_frames_sp.reset();
351 }
352 
353 void
354 Thread::BroadcastSelectedFrameChange(StackID &new_frame_id)
355 {
356     if (EventTypeHasListeners(eBroadcastBitSelectedFrameChanged))
357         BroadcastEvent(eBroadcastBitSelectedFrameChanged, new ThreadEventData (this->shared_from_this(), new_frame_id));
358 }
359 
360 uint32_t
361 Thread::SetSelectedFrame (lldb_private::StackFrame *frame, bool broadcast)
362 {
363     uint32_t ret_value = GetStackFrameList()->SetSelectedFrame(frame);
364     if (broadcast)
365         BroadcastSelectedFrameChange(frame->GetStackID());
366     return ret_value;
367 }
368 
369 bool
370 Thread::SetSelectedFrameByIndex (uint32_t frame_idx, bool broadcast)
371 {
372     StackFrameSP frame_sp(GetStackFrameList()->GetFrameAtIndex (frame_idx));
373     if (frame_sp)
374     {
375         GetStackFrameList()->SetSelectedFrame(frame_sp.get());
376         if (broadcast)
377             BroadcastSelectedFrameChange(frame_sp->GetStackID());
378         return true;
379     }
380     else
381         return false;
382 }
383 
384 bool
385 Thread::SetSelectedFrameByIndexNoisily (uint32_t frame_idx, Stream &output_stream)
386 {
387     const bool broadcast = true;
388     bool success = SetSelectedFrameByIndex (frame_idx, broadcast);
389     if (success)
390     {
391         StackFrameSP frame_sp = GetSelectedFrame();
392         if (frame_sp)
393         {
394             bool already_shown = false;
395             SymbolContext frame_sc(frame_sp->GetSymbolContext(eSymbolContextLineEntry));
396             if (GetProcess()->GetTarget().GetDebugger().GetUseExternalEditor() && frame_sc.line_entry.file && frame_sc.line_entry.line != 0)
397             {
398                 already_shown = Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line);
399             }
400 
401             bool show_frame_info = true;
402             bool show_source = !already_shown;
403             return frame_sp->GetStatus (output_stream, show_frame_info, show_source);
404         }
405         return false;
406     }
407     else
408         return false;
409 }
410 
411 
412 lldb::StopInfoSP
413 Thread::GetStopInfo ()
414 {
415     if (m_destroy_called)
416         return m_stop_info_sp;
417 
418     ThreadPlanSP plan_sp (GetCompletedPlan());
419     ProcessSP process_sp (GetProcess());
420     const uint32_t stop_id = process_sp ? process_sp->GetStopID() : UINT32_MAX;
421     if (plan_sp && plan_sp->PlanSucceeded())
422     {
423         return StopInfo::CreateStopReasonWithPlan (plan_sp, GetReturnValueObject());
424     }
425     else
426     {
427         if ((m_stop_info_stop_id == stop_id) ||   // Stop info is valid, just return what we have (even if empty)
428             (m_stop_info_sp && m_stop_info_sp->IsValid()))  // Stop info is valid, just return what we have
429         {
430             return m_stop_info_sp;
431         }
432         else
433         {
434             GetPrivateStopInfo ();
435             return m_stop_info_sp;
436         }
437     }
438 }
439 
440 lldb::StopInfoSP
441 Thread::GetPrivateStopInfo ()
442 {
443     if (m_destroy_called)
444         return m_stop_info_sp;
445 
446     ProcessSP process_sp (GetProcess());
447     if (process_sp)
448     {
449         const uint32_t process_stop_id = process_sp->GetStopID();
450         if (m_stop_info_stop_id != process_stop_id)
451         {
452             if (m_stop_info_sp)
453             {
454                 if (m_stop_info_sp->IsValid()
455                     || IsStillAtLastBreakpointHit()
456                     || GetCurrentPlan()->IsVirtualStep())
457                     SetStopInfo (m_stop_info_sp);
458                 else
459                     m_stop_info_sp.reset();
460             }
461 
462             if (!m_stop_info_sp)
463             {
464                 if (CalculateStopInfo() == false)
465                     SetStopInfo (StopInfoSP());
466             }
467         }
468     }
469     return m_stop_info_sp;
470 }
471 
472 
473 lldb::StopReason
474 Thread::GetStopReason()
475 {
476     lldb::StopInfoSP stop_info_sp (GetStopInfo ());
477     if (stop_info_sp)
478         return stop_info_sp->GetStopReason();
479     return eStopReasonNone;
480 }
481 
482 
483 
484 void
485 Thread::SetStopInfo (const lldb::StopInfoSP &stop_info_sp)
486 {
487     m_stop_info_sp = stop_info_sp;
488     if (m_stop_info_sp)
489     {
490         m_stop_info_sp->MakeStopInfoValid();
491         // If we are overriding the ShouldReportStop, do that here:
492         if (m_override_should_notify != eLazyBoolCalculate)
493             m_stop_info_sp->OverrideShouldNotify (m_override_should_notify == eLazyBoolYes);
494     }
495 
496     ProcessSP process_sp (GetProcess());
497     if (process_sp)
498         m_stop_info_stop_id = process_sp->GetStopID();
499     else
500         m_stop_info_stop_id = UINT32_MAX;
501     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
502     if (log)
503         log->Printf("%p: tid = 0x%" PRIx64 ": stop info = %s (stop_id = %u)\n",
504                     static_cast<void*>(this), GetID(),
505                     stop_info_sp ? stop_info_sp->GetDescription() : "<NULL>",
506                     m_stop_info_stop_id);
507 }
508 
509 void
510 Thread::SetShouldReportStop (Vote vote)
511 {
512     if (vote == eVoteNoOpinion)
513         return;
514     else
515     {
516         m_override_should_notify = (vote == eVoteYes ? eLazyBoolYes : eLazyBoolNo);
517         if (m_stop_info_sp)
518             m_stop_info_sp->OverrideShouldNotify (m_override_should_notify == eLazyBoolYes);
519     }
520 }
521 
522 void
523 Thread::SetStopInfoToNothing()
524 {
525     // Note, we can't just NULL out the private reason, or the native thread implementation will try to
526     // go calculate it again.  For now, just set it to a Unix Signal with an invalid signal number.
527     SetStopInfo (StopInfo::CreateStopReasonWithSignal (*this,  LLDB_INVALID_SIGNAL_NUMBER));
528 }
529 
530 bool
531 Thread::ThreadStoppedForAReason (void)
532 {
533     return (bool) GetPrivateStopInfo ();
534 }
535 
536 bool
537 Thread::CheckpointThreadState (ThreadStateCheckpoint &saved_state)
538 {
539     saved_state.register_backup_sp.reset();
540     lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
541     if (frame_sp)
542     {
543         lldb::RegisterCheckpointSP reg_checkpoint_sp(new RegisterCheckpoint(RegisterCheckpoint::Reason::eExpression));
544         if (reg_checkpoint_sp)
545         {
546             lldb::RegisterContextSP reg_ctx_sp (frame_sp->GetRegisterContext());
547             if (reg_ctx_sp && reg_ctx_sp->ReadAllRegisterValues (*reg_checkpoint_sp))
548                 saved_state.register_backup_sp = reg_checkpoint_sp;
549         }
550     }
551     if (!saved_state.register_backup_sp)
552         return false;
553 
554     saved_state.stop_info_sp = GetStopInfo();
555     ProcessSP process_sp (GetProcess());
556     if (process_sp)
557         saved_state.orig_stop_id = process_sp->GetStopID();
558     saved_state.current_inlined_depth = GetCurrentInlinedDepth();
559 
560     return true;
561 }
562 
563 bool
564 Thread::RestoreRegisterStateFromCheckpoint (ThreadStateCheckpoint &saved_state)
565 {
566     if (saved_state.register_backup_sp)
567     {
568         lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
569         if (frame_sp)
570         {
571             lldb::RegisterContextSP reg_ctx_sp (frame_sp->GetRegisterContext());
572             if (reg_ctx_sp)
573             {
574                 bool ret = reg_ctx_sp->WriteAllRegisterValues (*saved_state.register_backup_sp);
575 
576                 // Clear out all stack frames as our world just changed.
577                 ClearStackFrames();
578                 reg_ctx_sp->InvalidateIfNeeded(true);
579                 if (m_unwinder_ap.get())
580                     m_unwinder_ap->Clear();
581                 return ret;
582             }
583         }
584     }
585     return false;
586 }
587 
588 bool
589 Thread::RestoreThreadStateFromCheckpoint (ThreadStateCheckpoint &saved_state)
590 {
591     if (saved_state.stop_info_sp)
592         saved_state.stop_info_sp->MakeStopInfoValid();
593     SetStopInfo(saved_state.stop_info_sp);
594     GetStackFrameList()->SetCurrentInlinedDepth (saved_state.current_inlined_depth);
595     return true;
596 }
597 
598 StateType
599 Thread::GetState() const
600 {
601     // If any other threads access this we will need a mutex for it
602     Mutex::Locker locker(m_state_mutex);
603     return m_state;
604 }
605 
606 void
607 Thread::SetState(StateType state)
608 {
609     Mutex::Locker locker(m_state_mutex);
610     m_state = state;
611 }
612 
613 void
614 Thread::WillStop()
615 {
616     ThreadPlan *current_plan = GetCurrentPlan();
617 
618     // FIXME: I may decide to disallow threads with no plans.  In which
619     // case this should go to an assert.
620 
621     if (!current_plan)
622         return;
623 
624     current_plan->WillStop();
625 }
626 
627 void
628 Thread::SetupForResume ()
629 {
630     if (GetResumeState() != eStateSuspended)
631     {
632 
633         // If we're at a breakpoint push the step-over breakpoint plan.  Do this before
634         // telling the current plan it will resume, since we might change what the current
635         // plan is.
636 
637 //      StopReason stop_reason = lldb::eStopReasonInvalid;
638 //      StopInfoSP stop_info_sp = GetStopInfo();
639 //      if (stop_info_sp.get())
640 //          stop_reason = stop_info_sp->GetStopReason();
641 //      if (stop_reason == lldb::eStopReasonBreakpoint)
642         lldb::RegisterContextSP reg_ctx_sp (GetRegisterContext());
643         if (reg_ctx_sp)
644         {
645             BreakpointSiteSP bp_site_sp = GetProcess()->GetBreakpointSiteList().FindByAddress(reg_ctx_sp->GetPC());
646             if (bp_site_sp)
647             {
648                 // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the target may not require anything
649                 // special to step over a breakpoint.
650 
651                 ThreadPlan *cur_plan = GetCurrentPlan();
652 
653                 if (cur_plan->GetKind() != ThreadPlan::eKindStepOverBreakpoint)
654                 {
655                     ThreadPlanStepOverBreakpoint *step_bp_plan = new ThreadPlanStepOverBreakpoint (*this);
656                     if (step_bp_plan)
657                     {
658                         ThreadPlanSP step_bp_plan_sp;
659                         step_bp_plan->SetPrivate (true);
660 
661                         if (GetCurrentPlan()->RunState() != eStateStepping)
662                         {
663                             step_bp_plan->SetAutoContinue(true);
664                         }
665                         step_bp_plan_sp.reset (step_bp_plan);
666                         QueueThreadPlan (step_bp_plan_sp, false);
667                     }
668                 }
669             }
670         }
671     }
672 }
673 
674 bool
675 Thread::ShouldResume (StateType resume_state)
676 {
677     // At this point clear the completed plan stack.
678     m_completed_plan_stack.clear();
679     m_discarded_plan_stack.clear();
680     m_override_should_notify = eLazyBoolCalculate;
681 
682     m_temporary_resume_state = resume_state;
683 
684     lldb::ThreadSP backing_thread_sp (GetBackingThread ());
685     if (backing_thread_sp)
686         backing_thread_sp->m_temporary_resume_state = resume_state;
687 
688     // Make sure m_stop_info_sp is valid
689     GetPrivateStopInfo();
690 
691     // This is a little dubious, but we are trying to limit how often we actually fetch stop info from
692     // the target, 'cause that slows down single stepping.  So assume that if we got to the point where
693     // we're about to resume, and we haven't yet had to fetch the stop reason, then it doesn't need to know
694     // about the fact that we are resuming...
695         const uint32_t process_stop_id = GetProcess()->GetStopID();
696     if (m_stop_info_stop_id == process_stop_id &&
697         (m_stop_info_sp && m_stop_info_sp->IsValid()))
698     {
699         StopInfo *stop_info = GetPrivateStopInfo().get();
700         if (stop_info)
701             stop_info->WillResume (resume_state);
702     }
703 
704     // Tell all the plans that we are about to resume in case they need to clear any state.
705     // We distinguish between the plan on the top of the stack and the lower
706     // plans in case a plan needs to do any special business before it runs.
707 
708     bool need_to_resume = false;
709     ThreadPlan *plan_ptr = GetCurrentPlan();
710     if (plan_ptr)
711     {
712         need_to_resume = plan_ptr->WillResume(resume_state, true);
713 
714         while ((plan_ptr = GetPreviousPlan(plan_ptr)) != NULL)
715         {
716             plan_ptr->WillResume (resume_state, false);
717         }
718 
719         // If the WillResume for the plan says we are faking a resume, then it will have set an appropriate stop info.
720         // In that case, don't reset it here.
721 
722         if (need_to_resume && resume_state != eStateSuspended)
723         {
724             m_stop_info_sp.reset();
725         }
726     }
727 
728     if (need_to_resume)
729     {
730         ClearStackFrames();
731         // Let Thread subclasses do any special work they need to prior to resuming
732         WillResume (resume_state);
733     }
734 
735     return need_to_resume;
736 }
737 
738 void
739 Thread::DidResume ()
740 {
741     SetResumeSignal (LLDB_INVALID_SIGNAL_NUMBER);
742 }
743 
744 void
745 Thread::DidStop ()
746 {
747     SetState (eStateStopped);
748 }
749 
750 bool
751 Thread::ShouldStop (Event* event_ptr)
752 {
753     ThreadPlan *current_plan = GetCurrentPlan();
754 
755     bool should_stop = true;
756 
757     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
758 
759     if (GetResumeState () == eStateSuspended)
760     {
761         if (log)
762             log->Printf ("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", should_stop = 0 (ignore since thread was suspended)",
763                          __FUNCTION__, GetID (), GetProtocolID());
764         return false;
765     }
766 
767     if (GetTemporaryResumeState () == eStateSuspended)
768     {
769         if (log)
770             log->Printf ("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", should_stop = 0 (ignore since thread was suspended)",
771                          __FUNCTION__, GetID (), GetProtocolID());
772         return false;
773     }
774 
775     // Based on the current thread plan and process stop info, check if this
776     // thread caused the process to stop. NOTE: this must take place before
777     // the plan is moved from the current plan stack to the completed plan
778     // stack.
779     if (ThreadStoppedForAReason() == false)
780     {
781         if (log)
782             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)",
783                          __FUNCTION__, GetID (), GetProtocolID(),
784                          GetRegisterContext() ? GetRegisterContext()->GetPC() : LLDB_INVALID_ADDRESS);
785         return false;
786     }
787 
788     if (log)
789     {
790         log->Printf ("Thread::%s(%p) for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", pc = 0x%16.16" PRIx64,
791                      __FUNCTION__, static_cast<void*>(this), GetID (),
792                      GetProtocolID (),
793                      GetRegisterContext()
794                         ? GetRegisterContext()->GetPC()
795                         : LLDB_INVALID_ADDRESS);
796         log->Printf ("^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^");
797         StreamString s;
798         s.IndentMore();
799         DumpThreadPlans(&s);
800         log->Printf ("Plan stack initial state:\n%s", s.GetData());
801     }
802 
803     // The top most plan always gets to do the trace log...
804     current_plan->DoTraceLog ();
805 
806     // First query the stop info's ShouldStopSynchronous.  This handles "synchronous" stop reasons, for example the breakpoint
807     // command on internal breakpoints.  If a synchronous stop reason says we should not stop, then we don't have to
808     // do any more work on this stop.
809     StopInfoSP private_stop_info (GetPrivateStopInfo());
810     if (private_stop_info && private_stop_info->ShouldStopSynchronous(event_ptr) == false)
811     {
812         if (log)
813             log->Printf ("StopInfo::ShouldStop async callback says we should not stop, returning ShouldStop of false.");
814         return false;
815     }
816 
817     // If we've already been restarted, don't query the plans since the state they would examine is not current.
818     if (Process::ProcessEventData::GetRestartedFromEvent(event_ptr))
819         return false;
820 
821     // Before the plans see the state of the world, calculate the current inlined depth.
822     GetStackFrameList()->CalculateCurrentInlinedDepth();
823 
824     // If the base plan doesn't understand why we stopped, then we have to find a plan that does.
825     // If that plan is still working, then we don't need to do any more work.  If the plan that explains
826     // the stop is done, then we should pop all the plans below it, and pop it, and then let the plans above it decide
827     // whether they still need to do more work.
828 
829     bool done_processing_current_plan = false;
830 
831     if (!current_plan->PlanExplainsStop(event_ptr))
832     {
833         if (current_plan->TracerExplainsStop())
834         {
835             done_processing_current_plan = true;
836             should_stop = false;
837         }
838         else
839         {
840             // If the current plan doesn't explain the stop, then find one that
841             // does and let it handle the situation.
842             ThreadPlan *plan_ptr = current_plan;
843             while ((plan_ptr = GetPreviousPlan(plan_ptr)) != NULL)
844             {
845                 if (plan_ptr->PlanExplainsStop(event_ptr))
846                 {
847                     should_stop = plan_ptr->ShouldStop (event_ptr);
848 
849                     // plan_ptr explains the stop, next check whether plan_ptr is done, if so, then we should take it
850                     // and all the plans below it off the stack.
851 
852                     if (plan_ptr->MischiefManaged())
853                     {
854                         // We're going to pop the plans up to and including the plan that explains the stop.
855                         ThreadPlan *prev_plan_ptr = GetPreviousPlan (plan_ptr);
856 
857                         do
858                         {
859                             if (should_stop)
860                                 current_plan->WillStop();
861                             PopPlan();
862                         }
863                         while ((current_plan = GetCurrentPlan()) != prev_plan_ptr);
864                         // Now, if the responsible plan was not "Okay to discard" then we're done,
865                         // otherwise we forward this to the next plan in the stack below.
866                         if (plan_ptr->IsMasterPlan() && !plan_ptr->OkayToDiscard())
867                             done_processing_current_plan = true;
868                         else
869                             done_processing_current_plan = false;
870                     }
871                     else
872                         done_processing_current_plan = true;
873 
874                     break;
875                 }
876 
877             }
878         }
879     }
880 
881     if (!done_processing_current_plan)
882     {
883         bool over_ride_stop = current_plan->ShouldAutoContinue(event_ptr);
884 
885         if (log)
886             log->Printf("Plan %s explains stop, auto-continue %i.",
887                         current_plan->GetName(), over_ride_stop);
888 
889         // We're starting from the base plan, so just let it decide;
890         if (PlanIsBasePlan(current_plan))
891         {
892             should_stop = current_plan->ShouldStop (event_ptr);
893             if (log)
894                 log->Printf("Base plan says should stop: %i.", should_stop);
895         }
896         else
897         {
898             // Otherwise, don't let the base plan override what the other plans say to do, since
899             // presumably if there were other plans they would know what to do...
900             while (1)
901             {
902                 if (PlanIsBasePlan(current_plan))
903                     break;
904 
905                 should_stop = current_plan->ShouldStop(event_ptr);
906                 if (log)
907                     log->Printf("Plan %s should stop: %d.",
908                                 current_plan->GetName(), should_stop);
909                 if (current_plan->MischiefManaged())
910                 {
911                     if (should_stop)
912                         current_plan->WillStop();
913 
914                     // If a Master Plan wants to stop, and wants to stick on the stack, we let it.
915                     // Otherwise, see if the plan's parent wants to stop.
916 
917                     if (should_stop && current_plan->IsMasterPlan() && !current_plan->OkayToDiscard())
918                     {
919                         PopPlan();
920                         break;
921                     }
922                     else
923                     {
924 
925                         PopPlan();
926 
927                         current_plan = GetCurrentPlan();
928                         if (current_plan == NULL)
929                         {
930                             break;
931                         }
932                     }
933                 }
934                 else
935                 {
936                     break;
937                 }
938             }
939         }
940 
941         if (over_ride_stop)
942             should_stop = false;
943 
944         // One other potential problem is that we set up a master plan, then stop in before it is complete - for instance
945         // by hitting a breakpoint during a step-over - then do some step/finish/etc operations that wind up
946         // past the end point condition of the initial plan.  We don't want to strand the original plan on the stack,
947         // This code clears stale plans off the stack.
948 
949         if (should_stop)
950         {
951             ThreadPlan *plan_ptr = GetCurrentPlan();
952             while (!PlanIsBasePlan(plan_ptr))
953             {
954                 bool stale = plan_ptr->IsPlanStale ();
955                 ThreadPlan *examined_plan = plan_ptr;
956                 plan_ptr = GetPreviousPlan (examined_plan);
957 
958                 if (stale)
959                 {
960                     if (log)
961                         log->Printf("Plan %s being discarded in cleanup, it says it is already done.",
962                                     examined_plan->GetName());
963                     DiscardThreadPlansUpToPlan(examined_plan);
964                 }
965             }
966         }
967 
968     }
969 
970     if (log)
971     {
972         StreamString s;
973         s.IndentMore();
974         DumpThreadPlans(&s);
975         log->Printf ("Plan stack final state:\n%s", s.GetData());
976         log->Printf ("vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv", should_stop);
977     }
978     return should_stop;
979 }
980 
981 Vote
982 Thread::ShouldReportStop (Event* event_ptr)
983 {
984     StateType thread_state = GetResumeState ();
985     StateType temp_thread_state = GetTemporaryResumeState();
986 
987     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
988 
989     if (thread_state == eStateSuspended || thread_state == eStateInvalid)
990     {
991         if (log)
992             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (state was suspended or invalid)", GetID(), eVoteNoOpinion);
993         return eVoteNoOpinion;
994     }
995 
996     if (temp_thread_state == eStateSuspended || temp_thread_state == eStateInvalid)
997     {
998         if (log)
999             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (temporary state was suspended or invalid)", GetID(), eVoteNoOpinion);
1000         return eVoteNoOpinion;
1001     }
1002 
1003     if (!ThreadStoppedForAReason())
1004     {
1005         if (log)
1006             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (thread didn't stop for a reason.)", GetID(), eVoteNoOpinion);
1007         return eVoteNoOpinion;
1008     }
1009 
1010     if (m_completed_plan_stack.size() > 0)
1011     {
1012         // Don't use GetCompletedPlan here, since that suppresses private plans.
1013         if (log)
1014             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote  for complete stack's back plan", GetID());
1015         return m_completed_plan_stack.back()->ShouldReportStop (event_ptr);
1016     }
1017     else
1018     {
1019         Vote thread_vote = eVoteNoOpinion;
1020         ThreadPlan *plan_ptr = GetCurrentPlan();
1021         while (1)
1022         {
1023             if (plan_ptr->PlanExplainsStop(event_ptr))
1024             {
1025                 thread_vote = plan_ptr->ShouldReportStop(event_ptr);
1026                 break;
1027             }
1028             if (PlanIsBasePlan(plan_ptr))
1029                 break;
1030             else
1031                 plan_ptr = GetPreviousPlan(plan_ptr);
1032         }
1033         if (log)
1034             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i for current plan", GetID(), thread_vote);
1035 
1036         return thread_vote;
1037     }
1038 }
1039 
1040 Vote
1041 Thread::ShouldReportRun (Event* event_ptr)
1042 {
1043     StateType thread_state = GetResumeState ();
1044 
1045     if (thread_state == eStateSuspended
1046             || thread_state == eStateInvalid)
1047     {
1048         return eVoteNoOpinion;
1049     }
1050 
1051     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1052     if (m_completed_plan_stack.size() > 0)
1053     {
1054         // Don't use GetCompletedPlan here, since that suppresses private plans.
1055         if (log)
1056             log->Printf ("Current Plan for thread %d(%p) (0x%4.4" PRIx64 ", %s): %s being asked whether we should report run.",
1057                          GetIndexID(), static_cast<void*>(this), GetID(),
1058                          StateAsCString(GetTemporaryResumeState()),
1059                          m_completed_plan_stack.back()->GetName());
1060 
1061         return m_completed_plan_stack.back()->ShouldReportRun (event_ptr);
1062     }
1063     else
1064     {
1065         if (log)
1066             log->Printf ("Current Plan for thread %d(%p) (0x%4.4" PRIx64 ", %s): %s being asked whether we should report run.",
1067                          GetIndexID(), static_cast<void*>(this), GetID(),
1068                          StateAsCString(GetTemporaryResumeState()),
1069                          GetCurrentPlan()->GetName());
1070 
1071         return GetCurrentPlan()->ShouldReportRun (event_ptr);
1072      }
1073 }
1074 
1075 bool
1076 Thread::MatchesSpec (const ThreadSpec *spec)
1077 {
1078     if (spec == NULL)
1079         return true;
1080 
1081     return spec->ThreadPassesBasicTests(*this);
1082 }
1083 
1084 void
1085 Thread::PushPlan (ThreadPlanSP &thread_plan_sp)
1086 {
1087     if (thread_plan_sp)
1088     {
1089         // If the thread plan doesn't already have a tracer, give it its parent's tracer:
1090         if (!thread_plan_sp->GetThreadPlanTracer())
1091             thread_plan_sp->SetThreadPlanTracer(m_plan_stack.back()->GetThreadPlanTracer());
1092         m_plan_stack.push_back (thread_plan_sp);
1093 
1094         thread_plan_sp->DidPush();
1095 
1096         Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1097         if (log)
1098         {
1099             StreamString s;
1100             thread_plan_sp->GetDescription (&s, lldb::eDescriptionLevelFull);
1101             log->Printf("Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".",
1102                         static_cast<void*>(this), s.GetData(),
1103                         thread_plan_sp->GetThread().GetID());
1104         }
1105     }
1106 }
1107 
1108 void
1109 Thread::PopPlan ()
1110 {
1111     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1112 
1113     if (m_plan_stack.size() <= 1)
1114         return;
1115     else
1116     {
1117         ThreadPlanSP &plan = m_plan_stack.back();
1118         if (log)
1119         {
1120             log->Printf("Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".", plan->GetName(), plan->GetThread().GetID());
1121         }
1122         m_completed_plan_stack.push_back (plan);
1123         plan->WillPop();
1124         m_plan_stack.pop_back();
1125     }
1126 }
1127 
1128 void
1129 Thread::DiscardPlan ()
1130 {
1131     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1132     if (m_plan_stack.size() > 1)
1133     {
1134         ThreadPlanSP &plan = m_plan_stack.back();
1135         if (log)
1136             log->Printf("Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".", plan->GetName(), plan->GetThread().GetID());
1137 
1138         m_discarded_plan_stack.push_back (plan);
1139         plan->WillPop();
1140         m_plan_stack.pop_back();
1141     }
1142 }
1143 
1144 ThreadPlan *
1145 Thread::GetCurrentPlan ()
1146 {
1147     // There will always be at least the base plan.  If somebody is mucking with a
1148     // thread with an empty plan stack, we should assert right away.
1149     if (m_plan_stack.empty())
1150         return NULL;
1151     return m_plan_stack.back().get();
1152 }
1153 
1154 ThreadPlanSP
1155 Thread::GetCompletedPlan ()
1156 {
1157     ThreadPlanSP empty_plan_sp;
1158     if (!m_completed_plan_stack.empty())
1159     {
1160         for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1161         {
1162             ThreadPlanSP completed_plan_sp;
1163             completed_plan_sp = m_completed_plan_stack[i];
1164             if (!completed_plan_sp->GetPrivate ())
1165             return completed_plan_sp;
1166         }
1167     }
1168     return empty_plan_sp;
1169 }
1170 
1171 ValueObjectSP
1172 Thread::GetReturnValueObject ()
1173 {
1174     if (!m_completed_plan_stack.empty())
1175     {
1176         for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1177         {
1178             ValueObjectSP return_valobj_sp;
1179             return_valobj_sp = m_completed_plan_stack[i]->GetReturnValueObject();
1180             if (return_valobj_sp)
1181             return return_valobj_sp;
1182         }
1183     }
1184     return ValueObjectSP();
1185 }
1186 
1187 bool
1188 Thread::IsThreadPlanDone (ThreadPlan *plan)
1189 {
1190     if (!m_completed_plan_stack.empty())
1191     {
1192         for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1193         {
1194             if (m_completed_plan_stack[i].get() == plan)
1195                 return true;
1196         }
1197     }
1198     return false;
1199 }
1200 
1201 bool
1202 Thread::WasThreadPlanDiscarded (ThreadPlan *plan)
1203 {
1204     if (!m_discarded_plan_stack.empty())
1205     {
1206         for (int i = m_discarded_plan_stack.size() - 1; i >= 0; i--)
1207         {
1208             if (m_discarded_plan_stack[i].get() == plan)
1209                 return true;
1210         }
1211     }
1212     return false;
1213 }
1214 
1215 ThreadPlan *
1216 Thread::GetPreviousPlan (ThreadPlan *current_plan)
1217 {
1218     if (current_plan == NULL)
1219         return NULL;
1220 
1221     int stack_size = m_completed_plan_stack.size();
1222     for (int i = stack_size - 1; i > 0; i--)
1223     {
1224         if (current_plan == m_completed_plan_stack[i].get())
1225             return m_completed_plan_stack[i-1].get();
1226     }
1227 
1228     if (stack_size > 0 && m_completed_plan_stack[0].get() == current_plan)
1229     {
1230         if (m_plan_stack.size() > 0)
1231             return m_plan_stack.back().get();
1232         else
1233             return NULL;
1234     }
1235 
1236     stack_size = m_plan_stack.size();
1237     for (int i = stack_size - 1; i > 0; i--)
1238     {
1239         if (current_plan == m_plan_stack[i].get())
1240             return m_plan_stack[i-1].get();
1241     }
1242     return NULL;
1243 }
1244 
1245 void
1246 Thread::QueueThreadPlan (ThreadPlanSP &thread_plan_sp, bool abort_other_plans)
1247 {
1248     if (abort_other_plans)
1249        DiscardThreadPlans(true);
1250 
1251     PushPlan (thread_plan_sp);
1252 }
1253 
1254 
1255 void
1256 Thread::EnableTracer (bool value, bool single_stepping)
1257 {
1258     int stack_size = m_plan_stack.size();
1259     for (int i = 0; i < stack_size; i++)
1260     {
1261         if (m_plan_stack[i]->GetThreadPlanTracer())
1262         {
1263             m_plan_stack[i]->GetThreadPlanTracer()->EnableTracing(value);
1264             m_plan_stack[i]->GetThreadPlanTracer()->EnableSingleStep(single_stepping);
1265         }
1266     }
1267 }
1268 
1269 void
1270 Thread::SetTracer (lldb::ThreadPlanTracerSP &tracer_sp)
1271 {
1272     int stack_size = m_plan_stack.size();
1273     for (int i = 0; i < stack_size; i++)
1274         m_plan_stack[i]->SetThreadPlanTracer(tracer_sp);
1275 }
1276 
1277 void
1278 Thread::DiscardThreadPlansUpToPlan (lldb::ThreadPlanSP &up_to_plan_sp)
1279 {
1280     DiscardThreadPlansUpToPlan (up_to_plan_sp.get());
1281 }
1282 
1283 void
1284 Thread::DiscardThreadPlansUpToPlan (ThreadPlan *up_to_plan_ptr)
1285 {
1286     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1287     if (log)
1288         log->Printf("Discarding thread plans for thread tid = 0x%4.4" PRIx64 ", up to %p",
1289                     GetID(), static_cast<void*>(up_to_plan_ptr));
1290 
1291     int stack_size = m_plan_stack.size();
1292 
1293     // If the input plan is NULL, discard all plans.  Otherwise make sure this plan is in the
1294     // stack, and if so discard up to and including it.
1295 
1296     if (up_to_plan_ptr == NULL)
1297     {
1298         for (int i = stack_size - 1; i > 0; i--)
1299             DiscardPlan();
1300     }
1301     else
1302     {
1303         bool found_it = false;
1304         for (int i = stack_size - 1; i > 0; i--)
1305         {
1306             if (m_plan_stack[i].get() == up_to_plan_ptr)
1307                 found_it = true;
1308         }
1309         if (found_it)
1310         {
1311             bool last_one = false;
1312             for (int i = stack_size - 1; i > 0 && !last_one ; i--)
1313             {
1314                 if (GetCurrentPlan() == up_to_plan_ptr)
1315                     last_one = true;
1316                 DiscardPlan();
1317             }
1318         }
1319     }
1320     return;
1321 }
1322 
1323 void
1324 Thread::DiscardThreadPlans(bool force)
1325 {
1326     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1327     if (log)
1328     {
1329         log->Printf("Discarding thread plans for thread (tid = 0x%4.4" PRIx64 ", force %d)", GetID(), force);
1330     }
1331 
1332     if (force)
1333     {
1334         int stack_size = m_plan_stack.size();
1335         for (int i = stack_size - 1; i > 0; i--)
1336         {
1337             DiscardPlan();
1338         }
1339         return;
1340     }
1341 
1342     while (1)
1343     {
1344 
1345         int master_plan_idx;
1346         bool discard = true;
1347 
1348         // Find the first master plan, see if it wants discarding, and if yes discard up to it.
1349         for (master_plan_idx = m_plan_stack.size() - 1; master_plan_idx >= 0; master_plan_idx--)
1350         {
1351             if (m_plan_stack[master_plan_idx]->IsMasterPlan())
1352             {
1353                 discard = m_plan_stack[master_plan_idx]->OkayToDiscard();
1354                 break;
1355             }
1356         }
1357 
1358         if (discard)
1359         {
1360             // First pop all the dependent plans:
1361             for (int i = m_plan_stack.size() - 1; i > master_plan_idx; i--)
1362             {
1363 
1364                 // FIXME: Do we need a finalize here, or is the rule that "PrepareForStop"
1365                 // for the plan leaves it in a state that it is safe to pop the plan
1366                 // with no more notice?
1367                 DiscardPlan();
1368             }
1369 
1370             // Now discard the master plan itself.
1371             // The bottom-most plan never gets discarded.  "OkayToDiscard" for it means
1372             // discard it's dependent plans, but not it...
1373             if (master_plan_idx > 0)
1374             {
1375                 DiscardPlan();
1376             }
1377         }
1378         else
1379         {
1380             // If the master plan doesn't want to get discarded, then we're done.
1381             break;
1382         }
1383 
1384     }
1385 }
1386 
1387 bool
1388 Thread::PlanIsBasePlan (ThreadPlan *plan_ptr)
1389 {
1390     if (plan_ptr->IsBasePlan())
1391         return true;
1392     else if (m_plan_stack.size() == 0)
1393         return false;
1394     else
1395        return m_plan_stack[0].get() == plan_ptr;
1396 }
1397 
1398 Error
1399 Thread::UnwindInnermostExpression()
1400 {
1401     Error error;
1402     int stack_size = m_plan_stack.size();
1403 
1404     // If the input plan is NULL, discard all plans.  Otherwise make sure this plan is in the
1405     // stack, and if so discard up to and including it.
1406 
1407     for (int i = stack_size - 1; i > 0; i--)
1408     {
1409         if (m_plan_stack[i]->GetKind() == ThreadPlan::eKindCallFunction)
1410         {
1411             DiscardThreadPlansUpToPlan(m_plan_stack[i].get());
1412             return error;
1413         }
1414     }
1415     error.SetErrorString("No expressions currently active on this thread");
1416     return error;
1417 }
1418 
1419 
1420 ThreadPlanSP
1421 Thread::QueueFundamentalPlan (bool abort_other_plans)
1422 {
1423     ThreadPlanSP thread_plan_sp (new ThreadPlanBase(*this));
1424     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1425     return thread_plan_sp;
1426 }
1427 
1428 ThreadPlanSP
1429 Thread::QueueThreadPlanForStepSingleInstruction
1430 (
1431     bool step_over,
1432     bool abort_other_plans,
1433     bool stop_other_threads
1434 )
1435 {
1436     ThreadPlanSP thread_plan_sp (new ThreadPlanStepInstruction (*this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
1437     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1438     return thread_plan_sp;
1439 }
1440 
1441 ThreadPlanSP
1442 Thread::QueueThreadPlanForStepOverRange
1443 (
1444     bool abort_other_plans,
1445     const AddressRange &range,
1446     const SymbolContext &addr_context,
1447     lldb::RunMode stop_other_threads,
1448     LazyBool step_out_avoids_code_withoug_debug_info
1449 )
1450 {
1451     ThreadPlanSP thread_plan_sp;
1452     thread_plan_sp.reset (new ThreadPlanStepOverRange (*this, range, addr_context, stop_other_threads, step_out_avoids_code_withoug_debug_info));
1453 
1454     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1455     return thread_plan_sp;
1456 }
1457 
1458 ThreadPlanSP
1459 Thread::QueueThreadPlanForStepInRange
1460 (
1461     bool abort_other_plans,
1462     const AddressRange &range,
1463     const SymbolContext &addr_context,
1464     const char *step_in_target,
1465     lldb::RunMode stop_other_threads,
1466     LazyBool step_in_avoids_code_without_debug_info,
1467     LazyBool step_out_avoids_code_without_debug_info
1468 )
1469 {
1470     ThreadPlanSP thread_plan_sp;
1471     ThreadPlanStepInRange *plan = new ThreadPlanStepInRange (*this,
1472                                                              range,
1473                                                              addr_context,
1474                                                              stop_other_threads,
1475                                                              step_in_avoids_code_without_debug_info,
1476                                                              step_out_avoids_code_without_debug_info);
1477 
1478     if (step_in_target)
1479         plan->SetStepInTarget(step_in_target);
1480 
1481     thread_plan_sp.reset (plan);
1482 
1483     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1484     return thread_plan_sp;
1485 }
1486 
1487 
1488 ThreadPlanSP
1489 Thread::QueueThreadPlanForStepOut
1490 (
1491     bool abort_other_plans,
1492     SymbolContext *addr_context,
1493     bool first_insn,
1494     bool stop_other_threads,
1495     Vote stop_vote,
1496     Vote run_vote,
1497     uint32_t frame_idx,
1498     LazyBool step_out_avoids_code_withoug_debug_info
1499 )
1500 {
1501     ThreadPlanSP thread_plan_sp (new ThreadPlanStepOut (*this,
1502                                                         addr_context,
1503                                                         first_insn,
1504                                                         stop_other_threads,
1505                                                         stop_vote,
1506                                                         run_vote,
1507                                                         frame_idx,
1508                                                         step_out_avoids_code_withoug_debug_info));
1509 
1510     if (thread_plan_sp->ValidatePlan(NULL))
1511     {
1512         QueueThreadPlan (thread_plan_sp, abort_other_plans);
1513         return thread_plan_sp;
1514     }
1515     else
1516     {
1517         return ThreadPlanSP();
1518     }
1519 }
1520 
1521 ThreadPlanSP
1522 Thread::QueueThreadPlanForStepOutNoShouldStop
1523 (
1524     bool abort_other_plans,
1525     SymbolContext *addr_context,
1526     bool first_insn,
1527     bool stop_other_threads,
1528     Vote stop_vote,
1529     Vote run_vote,
1530     uint32_t frame_idx
1531 )
1532 {
1533     ThreadPlanStepOut *new_plan = new ThreadPlanStepOut (*this,
1534                                                         addr_context,
1535                                                         first_insn,
1536                                                         stop_other_threads,
1537                                                         stop_vote,
1538                                                         run_vote,
1539                                                         frame_idx,
1540                                                         eLazyBoolNo);
1541     new_plan->ClearShouldStopHereCallbacks();
1542     ThreadPlanSP thread_plan_sp(new_plan);
1543 
1544     if (thread_plan_sp->ValidatePlan(NULL))
1545     {
1546         QueueThreadPlan (thread_plan_sp, abort_other_plans);
1547         return thread_plan_sp;
1548     }
1549     else
1550     {
1551         return ThreadPlanSP();
1552     }
1553 }
1554 
1555 ThreadPlanSP
1556 Thread::QueueThreadPlanForStepThrough (StackID &return_stack_id, bool abort_other_plans, bool stop_other_threads)
1557 {
1558     ThreadPlanSP thread_plan_sp(new ThreadPlanStepThrough (*this, return_stack_id, stop_other_threads));
1559     if (!thread_plan_sp || !thread_plan_sp->ValidatePlan (NULL))
1560         return ThreadPlanSP();
1561 
1562     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1563     return thread_plan_sp;
1564 }
1565 
1566 ThreadPlanSP
1567 Thread::QueueThreadPlanForRunToAddress (bool abort_other_plans,
1568                                         Address &target_addr,
1569                                         bool stop_other_threads)
1570 {
1571     ThreadPlanSP thread_plan_sp (new ThreadPlanRunToAddress (*this, target_addr, stop_other_threads));
1572     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1573     return thread_plan_sp;
1574 }
1575 
1576 ThreadPlanSP
1577 Thread::QueueThreadPlanForStepUntil (bool abort_other_plans,
1578                                      lldb::addr_t *address_list,
1579                                      size_t num_addresses,
1580                                      bool stop_other_threads,
1581                                      uint32_t frame_idx)
1582 {
1583     ThreadPlanSP thread_plan_sp (new ThreadPlanStepUntil (*this, address_list, num_addresses, stop_other_threads, frame_idx));
1584     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1585     return thread_plan_sp;
1586 
1587 }
1588 
1589 uint32_t
1590 Thread::GetIndexID () const
1591 {
1592     return m_index_id;
1593 }
1594 
1595 void
1596 Thread::DumpThreadPlans (lldb_private::Stream *s) const
1597 {
1598     uint32_t stack_size = m_plan_stack.size();
1599     int i;
1600     s->Indent();
1601     s->Printf ("Plan Stack for thread #%u: tid = 0x%4.4" PRIx64 ", stack_size = %d\n", GetIndexID(), GetID(), stack_size);
1602     for (i = stack_size - 1; i >= 0; i--)
1603     {
1604         s->IndentMore();
1605         s->Indent();
1606         s->Printf ("Element %d: ", i);
1607         m_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
1608         s->EOL();
1609         s->IndentLess();
1610     }
1611 
1612     stack_size = m_completed_plan_stack.size();
1613     if (stack_size > 0)
1614     {
1615         s->Indent();
1616         s->Printf ("Completed Plan Stack: %d elements.\n", stack_size);
1617         for (i = stack_size - 1; i >= 0; i--)
1618         {
1619             s->IndentMore();
1620             s->Indent();
1621             s->Printf ("Element %d: ", i);
1622             m_completed_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
1623             s->EOL();
1624             s->IndentLess();
1625         }
1626     }
1627 
1628     stack_size = m_discarded_plan_stack.size();
1629     if (stack_size > 0)
1630     {
1631         s->Indent();
1632         s->Printf ("Discarded Plan Stack: %d elements.\n", stack_size);
1633         for (i = stack_size - 1; i >= 0; i--)
1634         {
1635             s->IndentMore();
1636             s->Indent();
1637             s->Printf ("Element %d: ", i);
1638             m_discarded_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
1639             s->EOL();
1640             s->IndentLess();
1641         }
1642     }
1643 
1644 }
1645 
1646 TargetSP
1647 Thread::CalculateTarget ()
1648 {
1649     TargetSP target_sp;
1650     ProcessSP process_sp(GetProcess());
1651     if (process_sp)
1652         target_sp = process_sp->CalculateTarget();
1653     return target_sp;
1654 
1655 }
1656 
1657 ProcessSP
1658 Thread::CalculateProcess ()
1659 {
1660     return GetProcess();
1661 }
1662 
1663 ThreadSP
1664 Thread::CalculateThread ()
1665 {
1666     return shared_from_this();
1667 }
1668 
1669 StackFrameSP
1670 Thread::CalculateStackFrame ()
1671 {
1672     return StackFrameSP();
1673 }
1674 
1675 void
1676 Thread::CalculateExecutionContext (ExecutionContext &exe_ctx)
1677 {
1678     exe_ctx.SetContext (shared_from_this());
1679 }
1680 
1681 
1682 StackFrameListSP
1683 Thread::GetStackFrameList ()
1684 {
1685     StackFrameListSP frame_list_sp;
1686     Mutex::Locker locker(m_frame_mutex);
1687     if (m_curr_frames_sp)
1688     {
1689         frame_list_sp = m_curr_frames_sp;
1690     }
1691     else
1692     {
1693         frame_list_sp.reset(new StackFrameList (*this, m_prev_frames_sp, true));
1694         m_curr_frames_sp = frame_list_sp;
1695     }
1696     return frame_list_sp;
1697 }
1698 
1699 void
1700 Thread::ClearStackFrames ()
1701 {
1702     Mutex::Locker locker(m_frame_mutex);
1703 
1704     Unwind *unwinder = GetUnwinder ();
1705     if (unwinder)
1706         unwinder->Clear();
1707 
1708     // Only store away the old "reference" StackFrameList if we got all its frames:
1709     // FIXME: At some point we can try to splice in the frames we have fetched into
1710     // the new frame as we make it, but let's not try that now.
1711     if (m_curr_frames_sp && m_curr_frames_sp->GetAllFramesFetched())
1712         m_prev_frames_sp.swap (m_curr_frames_sp);
1713     m_curr_frames_sp.reset();
1714 
1715     m_extended_info.reset();
1716     m_extended_info_fetched = false;
1717 }
1718 
1719 lldb::StackFrameSP
1720 Thread::GetFrameWithConcreteFrameIndex (uint32_t unwind_idx)
1721 {
1722     return GetStackFrameList()->GetFrameWithConcreteFrameIndex (unwind_idx);
1723 }
1724 
1725 
1726 Error
1727 Thread::ReturnFromFrameWithIndex (uint32_t frame_idx, lldb::ValueObjectSP return_value_sp, bool broadcast)
1728 {
1729     StackFrameSP frame_sp = GetStackFrameAtIndex (frame_idx);
1730     Error return_error;
1731 
1732     if (!frame_sp)
1733     {
1734         return_error.SetErrorStringWithFormat("Could not find frame with index %d in thread 0x%" PRIx64 ".", frame_idx, GetID());
1735     }
1736 
1737     return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
1738 }
1739 
1740 Error
1741 Thread::ReturnFromFrame (lldb::StackFrameSP frame_sp, lldb::ValueObjectSP return_value_sp, bool broadcast)
1742 {
1743     Error return_error;
1744 
1745     if (!frame_sp)
1746     {
1747         return_error.SetErrorString("Can't return to a null frame.");
1748         return return_error;
1749     }
1750 
1751     Thread *thread = frame_sp->GetThread().get();
1752     uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
1753     StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
1754     if (!older_frame_sp)
1755     {
1756         return_error.SetErrorString("No older frame to return to.");
1757         return return_error;
1758     }
1759 
1760     if (return_value_sp)
1761     {
1762         lldb::ABISP abi = thread->GetProcess()->GetABI();
1763         if (!abi)
1764         {
1765             return_error.SetErrorString("Could not find ABI to set return value.");
1766             return return_error;
1767         }
1768         SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
1769 
1770         // FIXME: ValueObject::Cast doesn't currently work correctly, at least not for scalars.
1771         // Turn that back on when that works.
1772         if (0 && sc.function != NULL)
1773         {
1774             Type *function_type = sc.function->GetType();
1775             if (function_type)
1776             {
1777                 ClangASTType return_type = sc.function->GetClangType().GetFunctionReturnType();
1778                 if (return_type)
1779                 {
1780                     StreamString s;
1781                     return_type.DumpTypeDescription(&s);
1782                     ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type);
1783                     if (cast_value_sp)
1784                     {
1785                         cast_value_sp->SetFormat(eFormatHex);
1786                         return_value_sp = cast_value_sp;
1787                     }
1788                 }
1789             }
1790         }
1791 
1792         return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
1793         if (!return_error.Success())
1794             return return_error;
1795     }
1796 
1797     // Now write the return registers for the chosen frame:
1798     // Note, we can't use ReadAllRegisterValues->WriteAllRegisterValues, since the read & write
1799     // cook their data
1800 
1801     StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);
1802     if (youngest_frame_sp)
1803     {
1804         lldb::RegisterContextSP reg_ctx_sp (youngest_frame_sp->GetRegisterContext());
1805         if (reg_ctx_sp)
1806         {
1807             bool copy_success = reg_ctx_sp->CopyFromRegisterContext(older_frame_sp->GetRegisterContext());
1808             if (copy_success)
1809             {
1810                 thread->DiscardThreadPlans(true);
1811                 thread->ClearStackFrames();
1812                 if (broadcast && EventTypeHasListeners(eBroadcastBitStackChanged))
1813                     BroadcastEvent(eBroadcastBitStackChanged, new ThreadEventData (this->shared_from_this()));
1814             }
1815             else
1816             {
1817                 return_error.SetErrorString("Could not reset register values.");
1818             }
1819         }
1820         else
1821         {
1822             return_error.SetErrorString("Frame has no register context.");
1823         }
1824     }
1825     else
1826     {
1827         return_error.SetErrorString("Returned past top frame.");
1828     }
1829     return return_error;
1830 }
1831 
1832 static void DumpAddressList (Stream &s, const std::vector<Address> &list, ExecutionContextScope *exe_scope)
1833 {
1834     for (size_t n=0;n<list.size();n++)
1835     {
1836         s << "\t";
1837         list[n].Dump (&s, exe_scope, Address::DumpStyleResolvedDescription, Address::DumpStyleSectionNameOffset);
1838         s << "\n";
1839     }
1840 }
1841 
1842 Error
1843 Thread::JumpToLine (const FileSpec &file, uint32_t line, bool can_leave_function, std::string *warnings)
1844 {
1845     ExecutionContext exe_ctx (GetStackFrameAtIndex(0));
1846     Target *target = exe_ctx.GetTargetPtr();
1847     TargetSP target_sp = exe_ctx.GetTargetSP();
1848     RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1849     StackFrame *frame = exe_ctx.GetFramePtr();
1850     const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction);
1851 
1852     // Find candidate locations.
1853     std::vector<Address> candidates, within_function, outside_function;
1854     target->GetImages().FindAddressesForLine (target_sp, file, line, sc.function, within_function, outside_function);
1855 
1856     // If possible, we try and stay within the current function.
1857     // Within a function, we accept multiple locations (optimized code may do this,
1858     // there's no solution here so we do the best we can).
1859     // However if we're trying to leave the function, we don't know how to pick the
1860     // right location, so if there's more than one then we bail.
1861     if (!within_function.empty())
1862         candidates = within_function;
1863     else if (outside_function.size() == 1 && can_leave_function)
1864         candidates = outside_function;
1865 
1866     // Check if we got anything.
1867     if (candidates.empty())
1868     {
1869         if (outside_function.empty())
1870         {
1871             return Error("Cannot locate an address for %s:%i.",
1872                          file.GetFilename().AsCString(), line);
1873         }
1874         else if (outside_function.size() == 1)
1875         {
1876             return Error("%s:%i is outside the current function.",
1877                          file.GetFilename().AsCString(), line);
1878         }
1879         else
1880         {
1881             StreamString sstr;
1882             DumpAddressList(sstr, outside_function, target);
1883             return Error("%s:%i has multiple candidate locations:\n%s",
1884                          file.GetFilename().AsCString(), line, sstr.GetString().c_str());
1885         }
1886     }
1887 
1888     // Accept the first location, warn about any others.
1889     Address dest = candidates[0];
1890     if (warnings && candidates.size() > 1)
1891     {
1892         StreamString sstr;
1893         sstr.Printf("%s:%i appears multiple times in this function, selecting the first location:\n",
1894                      file.GetFilename().AsCString(), line);
1895         DumpAddressList(sstr, candidates, target);
1896         *warnings = sstr.GetString();
1897     }
1898 
1899     if (!reg_ctx->SetPC (dest))
1900         return Error("Cannot change PC to target address.");
1901 
1902     return Error();
1903 }
1904 
1905 void
1906 Thread::DumpUsingSettingsFormat (Stream &strm, uint32_t frame_idx)
1907 {
1908     ExecutionContext exe_ctx (shared_from_this());
1909     Process *process = exe_ctx.GetProcessPtr();
1910     if (process == NULL)
1911         return;
1912 
1913     StackFrameSP frame_sp;
1914     SymbolContext frame_sc;
1915     if (frame_idx != LLDB_INVALID_INDEX32)
1916     {
1917         frame_sp = GetStackFrameAtIndex (frame_idx);
1918         if (frame_sp)
1919         {
1920             exe_ctx.SetFrameSP(frame_sp);
1921             frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
1922         }
1923     }
1924 
1925     const char *thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
1926     assert (thread_format);
1927     Debugger::FormatPrompt (thread_format,
1928                             frame_sp ? &frame_sc : NULL,
1929                             &exe_ctx,
1930                             NULL,
1931                             strm);
1932 }
1933 
1934 void
1935 Thread::SettingsInitialize ()
1936 {
1937 }
1938 
1939 void
1940 Thread::SettingsTerminate ()
1941 {
1942 }
1943 
1944 lldb::addr_t
1945 Thread::GetThreadPointer ()
1946 {
1947     return LLDB_INVALID_ADDRESS;
1948 }
1949 
1950 addr_t
1951 Thread::GetThreadLocalData (const ModuleSP module)
1952 {
1953     // The default implementation is to ask the dynamic loader for it.
1954     // This can be overridden for specific platforms.
1955     DynamicLoader *loader = GetProcess()->GetDynamicLoader();
1956     if (loader)
1957         return loader->GetThreadLocalData (module, shared_from_this());
1958     else
1959         return LLDB_INVALID_ADDRESS;
1960 }
1961 
1962 bool
1963 Thread::SafeToCallFunctions ()
1964 {
1965     Process *process = GetProcess().get();
1966     if (process)
1967     {
1968         SystemRuntime *runtime = process->GetSystemRuntime ();
1969         if (runtime)
1970         {
1971             return runtime->SafeToCallFunctionsOnThisThread (shared_from_this());
1972         }
1973     }
1974     return true;
1975 }
1976 
1977 lldb::StackFrameSP
1978 Thread::GetStackFrameSPForStackFramePtr (StackFrame *stack_frame_ptr)
1979 {
1980     return GetStackFrameList()->GetStackFrameSPForStackFramePtr (stack_frame_ptr);
1981 }
1982 
1983 const char *
1984 Thread::StopReasonAsCString (lldb::StopReason reason)
1985 {
1986     switch (reason)
1987     {
1988     case eStopReasonInvalid:       return "invalid";
1989     case eStopReasonNone:          return "none";
1990     case eStopReasonTrace:         return "trace";
1991     case eStopReasonBreakpoint:    return "breakpoint";
1992     case eStopReasonWatchpoint:    return "watchpoint";
1993     case eStopReasonSignal:        return "signal";
1994     case eStopReasonException:     return "exception";
1995     case eStopReasonExec:          return "exec";
1996     case eStopReasonPlanComplete:  return "plan complete";
1997     case eStopReasonThreadExiting: return "thread exiting";
1998     }
1999 
2000 
2001     static char unknown_state_string[64];
2002     snprintf(unknown_state_string, sizeof (unknown_state_string), "StopReason = %i", reason);
2003     return unknown_state_string;
2004 }
2005 
2006 const char *
2007 Thread::RunModeAsCString (lldb::RunMode mode)
2008 {
2009     switch (mode)
2010     {
2011     case eOnlyThisThread:     return "only this thread";
2012     case eAllThreads:         return "all threads";
2013     case eOnlyDuringStepping: return "only during stepping";
2014     }
2015 
2016     static char unknown_state_string[64];
2017     snprintf(unknown_state_string, sizeof (unknown_state_string), "RunMode = %i", mode);
2018     return unknown_state_string;
2019 }
2020 
2021 size_t
2022 Thread::GetStatus (Stream &strm, uint32_t start_frame, uint32_t num_frames, uint32_t num_frames_with_source)
2023 {
2024     ExecutionContext exe_ctx (shared_from_this());
2025     Target *target = exe_ctx.GetTargetPtr();
2026     Process *process = exe_ctx.GetProcessPtr();
2027     size_t num_frames_shown = 0;
2028     strm.Indent();
2029     bool is_selected = false;
2030     if (process)
2031     {
2032         if (process->GetThreadList().GetSelectedThread().get() == this)
2033             is_selected = true;
2034     }
2035     strm.Printf("%c ", is_selected ? '*' : ' ');
2036     if (target && target->GetDebugger().GetUseExternalEditor())
2037     {
2038         StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
2039         if (frame_sp)
2040         {
2041             SymbolContext frame_sc(frame_sp->GetSymbolContext (eSymbolContextLineEntry));
2042             if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file)
2043             {
2044                 Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line);
2045             }
2046         }
2047     }
2048 
2049     DumpUsingSettingsFormat (strm, start_frame);
2050 
2051     if (num_frames > 0)
2052     {
2053         strm.IndentMore();
2054 
2055         const bool show_frame_info = true;
2056 
2057         const char *selected_frame_marker = NULL;
2058         if (num_frames == 1 || (GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID()))
2059             strm.IndentMore ();
2060         else
2061             selected_frame_marker = "* ";
2062 
2063         num_frames_shown = GetStackFrameList ()->GetStatus (strm,
2064                                                             start_frame,
2065                                                             num_frames,
2066                                                             show_frame_info,
2067                                                             num_frames_with_source,
2068                                                             selected_frame_marker);
2069         if (num_frames == 1)
2070             strm.IndentLess();
2071         strm.IndentLess();
2072     }
2073     return num_frames_shown;
2074 }
2075 
2076 bool
2077 Thread::GetDescription (Stream &strm, lldb::DescriptionLevel level, bool print_json)
2078 {
2079     DumpUsingSettingsFormat (strm, 0);
2080     strm.Printf("\n");
2081 
2082     StructuredData::ObjectSP thread_info = GetExtendedInfo();
2083 
2084     if (thread_info && print_json)
2085     {
2086         thread_info->Dump (strm);
2087         strm.Printf("\n");
2088         return true;
2089     }
2090 
2091     if (thread_info)
2092     {
2093         StructuredData::ObjectSP activity = thread_info->GetObjectForDotSeparatedPath("activity");
2094         StructuredData::ObjectSP breadcrumb = thread_info->GetObjectForDotSeparatedPath("breadcrumb");
2095         StructuredData::ObjectSP messages = thread_info->GetObjectForDotSeparatedPath("trace_messages");
2096 
2097         bool printed_activity = false;
2098         if (activity && activity->GetType() == StructuredData::Type::eTypeDictionary)
2099         {
2100             StructuredData::Dictionary *activity_dict = activity->GetAsDictionary();
2101             StructuredData::ObjectSP id = activity_dict->GetValueForKey("id");
2102             StructuredData::ObjectSP name = activity_dict->GetValueForKey("name");
2103             if (name && name->GetType() == StructuredData::Type::eTypeString
2104                 && id && id->GetType() == StructuredData::Type::eTypeInteger)
2105             {
2106                 strm.Printf("  Activity '%s', 0x%" PRIx64 "\n", name->GetAsString()->GetValue().c_str(), id->GetAsInteger()->GetValue());
2107             }
2108             printed_activity = true;
2109         }
2110         bool printed_breadcrumb = false;
2111         if (breadcrumb && breadcrumb->GetType() == StructuredData::Type::eTypeDictionary)
2112         {
2113             if (printed_activity)
2114                 strm.Printf ("\n");
2115             StructuredData::Dictionary *breadcrumb_dict = breadcrumb->GetAsDictionary();
2116             StructuredData::ObjectSP breadcrumb_text = breadcrumb_dict->GetValueForKey ("name");
2117             if (breadcrumb_text && breadcrumb_text->GetType() == StructuredData::Type::eTypeString)
2118             {
2119                 strm.Printf ("  Current Breadcrumb: %s\n", breadcrumb_text->GetAsString()->GetValue().c_str());
2120             }
2121             printed_breadcrumb = true;
2122         }
2123         if (messages && messages->GetType() == StructuredData::Type::eTypeArray)
2124         {
2125             if (printed_breadcrumb)
2126                 strm.Printf("\n");
2127             StructuredData::Array *messages_array = messages->GetAsArray();
2128             const size_t msg_count = messages_array->GetSize();
2129             if (msg_count > 0)
2130             {
2131                 strm.Printf ("  %zu trace messages:\n", msg_count);
2132                 for (size_t i = 0; i < msg_count; i++)
2133                 {
2134                     StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i);
2135                     if (message && message->GetType() == StructuredData::Type::eTypeDictionary)
2136                     {
2137                         StructuredData::Dictionary *message_dict = message->GetAsDictionary();
2138                         StructuredData::ObjectSP message_text = message_dict->GetValueForKey ("message");
2139                         if (message_text && message_text->GetType() == StructuredData::Type::eTypeString)
2140                         {
2141                             strm.Printf ("    %s\n", message_text->GetAsString()->GetValue().c_str());
2142                         }
2143                     }
2144                 }
2145             }
2146         }
2147     }
2148 
2149     return true;
2150 }
2151 
2152 size_t
2153 Thread::GetStackFrameStatus (Stream& strm,
2154                              uint32_t first_frame,
2155                              uint32_t num_frames,
2156                              bool show_frame_info,
2157                              uint32_t num_frames_with_source)
2158 {
2159     return GetStackFrameList()->GetStatus (strm,
2160                                            first_frame,
2161                                            num_frames,
2162                                            show_frame_info,
2163                                            num_frames_with_source);
2164 }
2165 
2166 Unwind *
2167 Thread::GetUnwinder ()
2168 {
2169     if (m_unwinder_ap.get() == NULL)
2170     {
2171         const ArchSpec target_arch (CalculateTarget()->GetArchitecture ());
2172         const llvm::Triple::ArchType machine = target_arch.GetMachine();
2173         switch (machine)
2174         {
2175             case llvm::Triple::x86_64:
2176             case llvm::Triple::x86:
2177             case llvm::Triple::arm:
2178             case llvm::Triple::arm64:
2179             case llvm::Triple::thumb:
2180             case llvm::Triple::mips64:
2181             case llvm::Triple::hexagon:
2182                 m_unwinder_ap.reset (new UnwindLLDB (*this));
2183                 break;
2184 
2185             default:
2186                 if (target_arch.GetTriple().getVendor() == llvm::Triple::Apple)
2187                     m_unwinder_ap.reset (new UnwindMacOSXFrameBackchain (*this));
2188                 break;
2189         }
2190     }
2191     return m_unwinder_ap.get();
2192 }
2193 
2194 
2195 void
2196 Thread::Flush ()
2197 {
2198     ClearStackFrames ();
2199     m_reg_context_sp.reset();
2200 }
2201 
2202 bool
2203 Thread::IsStillAtLastBreakpointHit ()
2204 {
2205     // If we are currently stopped at a breakpoint, always return that stopinfo and don't reset it.
2206     // This allows threads to maintain their breakpoint stopinfo, such as when thread-stepping in
2207     // multithreaded programs.
2208     if (m_stop_info_sp) {
2209         StopReason stop_reason = m_stop_info_sp->GetStopReason();
2210         if (stop_reason == lldb::eStopReasonBreakpoint) {
2211             uint64_t value = m_stop_info_sp->GetValue();
2212             lldb::RegisterContextSP reg_ctx_sp (GetRegisterContext());
2213             if (reg_ctx_sp)
2214             {
2215                 lldb::addr_t pc = reg_ctx_sp->GetPC();
2216                 BreakpointSiteSP bp_site_sp = GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2217                 if (bp_site_sp &&
2218                     static_cast<break_id_t>(value) == bp_site_sp->GetID())
2219                     return true;
2220             }
2221         }
2222     }
2223     return false;
2224 }
2225 
2226 
2227 Error
2228 Thread::StepIn (bool source_step,
2229                 LazyBool step_in_avoids_code_without_debug_info,
2230                 LazyBool step_out_avoids_code_without_debug_info)
2231 
2232 {
2233     Error error;
2234     Process *process = GetProcess().get();
2235     if (StateIsStoppedState (process->GetState(), true))
2236     {
2237         StackFrameSP frame_sp = GetStackFrameAtIndex (0);
2238         ThreadPlanSP new_plan_sp;
2239         const lldb::RunMode run_mode = eOnlyThisThread;
2240         const bool abort_other_plans = false;
2241 
2242         if (source_step && frame_sp && frame_sp->HasDebugInformation ())
2243         {
2244             SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2245             new_plan_sp = QueueThreadPlanForStepInRange (abort_other_plans,
2246                                                          sc.line_entry.range,
2247                                                          sc,
2248                                                          NULL,
2249                                                          run_mode,
2250                                                          step_in_avoids_code_without_debug_info,
2251                                                          step_out_avoids_code_without_debug_info);
2252         }
2253         else
2254         {
2255             new_plan_sp = QueueThreadPlanForStepSingleInstruction (false,
2256                                                                    abort_other_plans,
2257                                                                    run_mode);
2258         }
2259 
2260         new_plan_sp->SetIsMasterPlan(true);
2261         new_plan_sp->SetOkayToDiscard(false);
2262 
2263         // Why do we need to set the current thread by ID here???
2264         process->GetThreadList().SetSelectedThreadByID (GetID());
2265         error = process->Resume();
2266     }
2267     else
2268     {
2269         error.SetErrorString("process not stopped");
2270     }
2271     return error;
2272 }
2273 
2274 Error
2275 Thread::StepOver (bool source_step,
2276                 LazyBool step_out_avoids_code_without_debug_info)
2277 {
2278     Error error;
2279     Process *process = GetProcess().get();
2280     if (StateIsStoppedState (process->GetState(), true))
2281     {
2282         StackFrameSP frame_sp = GetStackFrameAtIndex (0);
2283         ThreadPlanSP new_plan_sp;
2284 
2285         const lldb::RunMode run_mode = eOnlyThisThread;
2286         const bool abort_other_plans = false;
2287 
2288         if (source_step && frame_sp && frame_sp->HasDebugInformation ())
2289         {
2290             SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2291             new_plan_sp = QueueThreadPlanForStepOverRange (abort_other_plans,
2292                                                            sc.line_entry.range,
2293                                                            sc,
2294                                                            run_mode,
2295                                                            step_out_avoids_code_without_debug_info);
2296         }
2297         else
2298         {
2299             new_plan_sp = QueueThreadPlanForStepSingleInstruction (true,
2300                                                                    abort_other_plans,
2301                                                                    run_mode);
2302         }
2303 
2304         new_plan_sp->SetIsMasterPlan(true);
2305         new_plan_sp->SetOkayToDiscard(false);
2306 
2307         // Why do we need to set the current thread by ID here???
2308         process->GetThreadList().SetSelectedThreadByID (GetID());
2309         error = process->Resume();
2310     }
2311     else
2312     {
2313         error.SetErrorString("process not stopped");
2314     }
2315     return error;
2316 }
2317 
2318 Error
2319 Thread::StepOut ()
2320 {
2321     Error error;
2322     Process *process = GetProcess().get();
2323     if (StateIsStoppedState (process->GetState(), true))
2324     {
2325         const bool first_instruction = false;
2326         const bool stop_other_threads = false;
2327         const bool abort_other_plans = false;
2328 
2329         ThreadPlanSP new_plan_sp(QueueThreadPlanForStepOut (abort_other_plans,
2330                                                             NULL,
2331                                                             first_instruction,
2332                                                             stop_other_threads,
2333                                                             eVoteYes,
2334                                                             eVoteNoOpinion,
2335                                                             0));
2336 
2337         new_plan_sp->SetIsMasterPlan(true);
2338         new_plan_sp->SetOkayToDiscard(false);
2339 
2340         // Why do we need to set the current thread by ID here???
2341         process->GetThreadList().SetSelectedThreadByID (GetID());
2342         error = process->Resume();
2343     }
2344     else
2345     {
2346         error.SetErrorString("process not stopped");
2347     }
2348     return error;
2349 }
2350