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