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