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