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