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