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