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