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