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