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