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