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