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   return raw_stop_description;
602 }
603 
604 void Thread::SelectMostRelevantFrame() {
605   Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
606 
607   auto frames_list_sp = GetStackFrameList();
608 
609   // Only the top frame should be recognized.
610   auto frame_sp = frames_list_sp->GetFrameAtIndex(0);
611 
612   auto recognized_frame_sp = frame_sp->GetRecognizedFrame();
613 
614   if (!recognized_frame_sp) {
615     LLDB_LOG(log, "Frame #0 not recognized");
616     return;
617   }
618 
619   if (StackFrameSP most_relevant_frame_sp =
620           recognized_frame_sp->GetMostRelevantFrame()) {
621     LLDB_LOG(log, "Found most relevant frame at index {0}",
622              most_relevant_frame_sp->GetFrameIndex());
623     SetSelectedFrame(most_relevant_frame_sp.get());
624   } else {
625     LLDB_LOG(log, "No relevant frame!");
626   }
627 }
628 
629 void Thread::WillStop() {
630   ThreadPlan *current_plan = GetCurrentPlan();
631 
632   SelectMostRelevantFrame();
633 
634   // FIXME: I may decide to disallow threads with no plans.  In which
635   // case this should go to an assert.
636 
637   if (!current_plan)
638     return;
639 
640   current_plan->WillStop();
641 }
642 
643 void Thread::SetupForResume() {
644   if (GetResumeState() != eStateSuspended) {
645     // If we're at a breakpoint push the step-over breakpoint plan.  Do this
646     // before telling the current plan it will resume, since we might change
647     // what the current plan is.
648 
649     lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext());
650     if (reg_ctx_sp) {
651       const addr_t thread_pc = reg_ctx_sp->GetPC();
652       BreakpointSiteSP bp_site_sp =
653           GetProcess()->GetBreakpointSiteList().FindByAddress(thread_pc);
654       if (bp_site_sp) {
655         // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the
656         // target may not require anything special to step over a breakpoint.
657 
658         ThreadPlan *cur_plan = GetCurrentPlan();
659 
660         bool push_step_over_bp_plan = false;
661         if (cur_plan->GetKind() == ThreadPlan::eKindStepOverBreakpoint) {
662           ThreadPlanStepOverBreakpoint *bp_plan =
663               (ThreadPlanStepOverBreakpoint *)cur_plan;
664           if (bp_plan->GetBreakpointLoadAddress() != thread_pc)
665             push_step_over_bp_plan = true;
666         } else
667           push_step_over_bp_plan = true;
668 
669         if (push_step_over_bp_plan) {
670           ThreadPlanSP step_bp_plan_sp(new ThreadPlanStepOverBreakpoint(*this));
671           if (step_bp_plan_sp) {
672             step_bp_plan_sp->SetPrivate(true);
673 
674             if (GetCurrentPlan()->RunState() != eStateStepping) {
675               ThreadPlanStepOverBreakpoint *step_bp_plan =
676                   static_cast<ThreadPlanStepOverBreakpoint *>(
677                       step_bp_plan_sp.get());
678               step_bp_plan->SetAutoContinue(true);
679             }
680             QueueThreadPlan(step_bp_plan_sp, false);
681           }
682         }
683       }
684     }
685   }
686 }
687 
688 bool Thread::ShouldResume(StateType resume_state) {
689   // At this point clear the completed plan stack.
690   m_completed_plan_stack.clear();
691   m_discarded_plan_stack.clear();
692   m_override_should_notify = eLazyBoolCalculate;
693 
694   StateType prev_resume_state = GetTemporaryResumeState();
695 
696   SetTemporaryResumeState(resume_state);
697 
698   lldb::ThreadSP backing_thread_sp(GetBackingThread());
699   if (backing_thread_sp)
700     backing_thread_sp->SetTemporaryResumeState(resume_state);
701 
702   // Make sure m_stop_info_sp is valid.  Don't do this for threads we suspended
703   // in the previous run.
704   if (prev_resume_state != eStateSuspended)
705     GetPrivateStopInfo();
706 
707   // This is a little dubious, but we are trying to limit how often we actually
708   // fetch stop info from the target, 'cause that slows down single stepping.
709   // So assume that if we got to the point where we're about to resume, and we
710   // haven't yet had to fetch the stop reason, then it doesn't need to know
711   // about the fact that we are resuming...
712   const uint32_t process_stop_id = GetProcess()->GetStopID();
713   if (m_stop_info_stop_id == process_stop_id &&
714       (m_stop_info_sp && m_stop_info_sp->IsValid())) {
715     StopInfo *stop_info = GetPrivateStopInfo().get();
716     if (stop_info)
717       stop_info->WillResume(resume_state);
718   }
719 
720   // Tell all the plans that we are about to resume in case they need to clear
721   // any state. We distinguish between the plan on the top of the stack and the
722   // lower plans in case a plan needs to do any special business before it
723   // runs.
724 
725   bool need_to_resume = false;
726   ThreadPlan *plan_ptr = GetCurrentPlan();
727   if (plan_ptr) {
728     need_to_resume = plan_ptr->WillResume(resume_state, true);
729 
730     while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
731       plan_ptr->WillResume(resume_state, false);
732     }
733 
734     // If the WillResume for the plan says we are faking a resume, then it will
735     // have set an appropriate stop info. In that case, don't reset it here.
736 
737     if (need_to_resume && resume_state != eStateSuspended) {
738       m_stop_info_sp.reset();
739     }
740   }
741 
742   if (need_to_resume) {
743     ClearStackFrames();
744     // Let Thread subclasses do any special work they need to prior to resuming
745     WillResume(resume_state);
746   }
747 
748   return need_to_resume;
749 }
750 
751 void Thread::DidResume() { SetResumeSignal(LLDB_INVALID_SIGNAL_NUMBER); }
752 
753 void Thread::DidStop() { SetState(eStateStopped); }
754 
755 bool Thread::ShouldStop(Event *event_ptr) {
756   ThreadPlan *current_plan = GetCurrentPlan();
757 
758   bool should_stop = true;
759 
760   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
761 
762   if (GetResumeState() == eStateSuspended) {
763     LLDB_LOGF(log,
764               "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
765               ", should_stop = 0 (ignore since thread was suspended)",
766               __FUNCTION__, GetID(), GetProtocolID());
767     return false;
768   }
769 
770   if (GetTemporaryResumeState() == eStateSuspended) {
771     LLDB_LOGF(log,
772               "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
773               ", should_stop = 0 (ignore since thread was suspended)",
774               __FUNCTION__, GetID(), GetProtocolID());
775     return false;
776   }
777 
778   // Based on the current thread plan and process stop info, check if this
779   // thread caused the process to stop. NOTE: this must take place before the
780   // plan is moved from the current plan stack to the completed plan stack.
781   if (!ThreadStoppedForAReason()) {
782     LLDB_LOGF(log,
783               "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
784               ", pc = 0x%16.16" PRIx64
785               ", should_stop = 0 (ignore since no stop reason)",
786               __FUNCTION__, GetID(), GetProtocolID(),
787               GetRegisterContext() ? GetRegisterContext()->GetPC()
788                                    : LLDB_INVALID_ADDRESS);
789     return false;
790   }
791 
792   if (log) {
793     LLDB_LOGF(log,
794               "Thread::%s(%p) for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
795               ", pc = 0x%16.16" PRIx64,
796               __FUNCTION__, static_cast<void *>(this), GetID(), GetProtocolID(),
797               GetRegisterContext() ? GetRegisterContext()->GetPC()
798                                    : LLDB_INVALID_ADDRESS);
799     LLDB_LOGF(log, "^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^");
800     StreamString s;
801     s.IndentMore();
802     DumpThreadPlans(&s);
803     LLDB_LOGF(log, "Plan stack initial state:\n%s", s.GetData());
804   }
805 
806   // The top most plan always gets to do the trace log...
807   current_plan->DoTraceLog();
808 
809   // First query the stop info's ShouldStopSynchronous.  This handles
810   // "synchronous" stop reasons, for example the breakpoint command on internal
811   // breakpoints.  If a synchronous stop reason says we should not stop, then
812   // we don't have to do any more work on this stop.
813   StopInfoSP private_stop_info(GetPrivateStopInfo());
814   if (private_stop_info &&
815       !private_stop_info->ShouldStopSynchronous(event_ptr)) {
816     LLDB_LOGF(log, "StopInfo::ShouldStop async callback says we should not "
817                    "stop, returning ShouldStop of false.");
818     return false;
819   }
820 
821   // If we've already been restarted, don't query the plans since the state
822   // they would examine is not current.
823   if (Process::ProcessEventData::GetRestartedFromEvent(event_ptr))
824     return false;
825 
826   // Before the plans see the state of the world, calculate the current inlined
827   // depth.
828   GetStackFrameList()->CalculateCurrentInlinedDepth();
829 
830   // If the base plan doesn't understand why we stopped, then we have to find a
831   // plan that does. If that plan is still working, then we don't need to do
832   // any more work.  If the plan that explains the stop is done, then we should
833   // pop all the plans below it, and pop it, and then let the plans above it
834   // decide whether they still need to do more work.
835 
836   bool done_processing_current_plan = false;
837 
838   if (!current_plan->PlanExplainsStop(event_ptr)) {
839     if (current_plan->TracerExplainsStop()) {
840       done_processing_current_plan = true;
841       should_stop = false;
842     } else {
843       // If the current plan doesn't explain the stop, then find one that does
844       // and let it handle the situation.
845       ThreadPlan *plan_ptr = current_plan;
846       while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
847         if (plan_ptr->PlanExplainsStop(event_ptr)) {
848           should_stop = plan_ptr->ShouldStop(event_ptr);
849 
850           // plan_ptr explains the stop, next check whether plan_ptr is done,
851           // if so, then we should take it and all the plans below it off the
852           // stack.
853 
854           if (plan_ptr->MischiefManaged()) {
855             // We're going to pop the plans up to and including the plan that
856             // explains the stop.
857             ThreadPlan *prev_plan_ptr = GetPreviousPlan(plan_ptr);
858 
859             do {
860               if (should_stop)
861                 current_plan->WillStop();
862               PopPlan();
863             } while ((current_plan = GetCurrentPlan()) != prev_plan_ptr);
864             // Now, if the responsible plan was not "Okay to discard" then
865             // we're done, otherwise we forward this to the next plan in the
866             // stack below.
867             done_processing_current_plan =
868                 (plan_ptr->IsMasterPlan() && !plan_ptr->OkayToDiscard());
869           } else
870             done_processing_current_plan = true;
871 
872           break;
873         }
874       }
875     }
876   }
877 
878   if (!done_processing_current_plan) {
879     bool over_ride_stop = current_plan->ShouldAutoContinue(event_ptr);
880 
881     LLDB_LOGF(log, "Plan %s explains stop, auto-continue %i.",
882               current_plan->GetName(), over_ride_stop);
883 
884     // We're starting from the base plan, so just let it decide;
885     if (PlanIsBasePlan(current_plan)) {
886       should_stop = current_plan->ShouldStop(event_ptr);
887       LLDB_LOGF(log, "Base plan says should stop: %i.", should_stop);
888     } else {
889       // Otherwise, don't let the base plan override what the other plans say
890       // to do, since presumably if there were other plans they would know what
891       // to do...
892       while (true) {
893         if (PlanIsBasePlan(current_plan))
894           break;
895 
896         should_stop = current_plan->ShouldStop(event_ptr);
897         LLDB_LOGF(log, "Plan %s should stop: %d.", current_plan->GetName(),
898                   should_stop);
899         if (current_plan->MischiefManaged()) {
900           if (should_stop)
901             current_plan->WillStop();
902 
903           // If a Master Plan wants to stop, and wants to stick on the stack,
904           // we let it. Otherwise, see if the plan's parent wants to stop.
905 
906           if (should_stop && current_plan->IsMasterPlan() &&
907               !current_plan->OkayToDiscard()) {
908             PopPlan();
909             break;
910           } else {
911             PopPlan();
912 
913             current_plan = GetCurrentPlan();
914             if (current_plan == nullptr) {
915               break;
916             }
917           }
918         } else {
919           break;
920         }
921       }
922     }
923 
924     if (over_ride_stop)
925       should_stop = false;
926   }
927 
928   // One other potential problem is that we set up a master plan, then stop in
929   // before it is complete - for instance by hitting a breakpoint during a
930   // step-over - then do some step/finish/etc operations that wind up past the
931   // end point condition of the initial plan.  We don't want to strand the
932   // original plan on the stack, This code clears stale plans off the stack.
933 
934   if (should_stop) {
935     ThreadPlan *plan_ptr = GetCurrentPlan();
936 
937     // Discard the stale plans and all plans below them in the stack, plus move
938     // the completed plans to the completed plan stack
939     while (!PlanIsBasePlan(plan_ptr)) {
940       bool stale = plan_ptr->IsPlanStale();
941       ThreadPlan *examined_plan = plan_ptr;
942       plan_ptr = GetPreviousPlan(examined_plan);
943 
944       if (stale) {
945         LLDB_LOGF(
946             log,
947             "Plan %s being discarded in cleanup, it says it is already done.",
948             examined_plan->GetName());
949         while (GetCurrentPlan() != examined_plan) {
950           DiscardPlan();
951         }
952         if (examined_plan->IsPlanComplete()) {
953           // plan is complete but does not explain the stop (example: step to a
954           // line with breakpoint), let us move the plan to
955           // completed_plan_stack anyway
956           PopPlan();
957         } else
958           DiscardPlan();
959       }
960     }
961   }
962 
963   if (log) {
964     StreamString s;
965     s.IndentMore();
966     DumpThreadPlans(&s);
967     LLDB_LOGF(log, "Plan stack final state:\n%s", s.GetData());
968     LLDB_LOGF(log, "vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv",
969               should_stop);
970   }
971   return should_stop;
972 }
973 
974 Vote Thread::ShouldReportStop(Event *event_ptr) {
975   StateType thread_state = GetResumeState();
976   StateType temp_thread_state = GetTemporaryResumeState();
977 
978   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
979 
980   if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
981     LLDB_LOGF(log,
982               "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
983               ": returning vote %i (state was suspended or invalid)",
984               GetID(), eVoteNoOpinion);
985     return eVoteNoOpinion;
986   }
987 
988   if (temp_thread_state == eStateSuspended ||
989       temp_thread_state == eStateInvalid) {
990     LLDB_LOGF(log,
991               "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
992               ": returning vote %i (temporary state was suspended or invalid)",
993               GetID(), eVoteNoOpinion);
994     return eVoteNoOpinion;
995   }
996 
997   if (!ThreadStoppedForAReason()) {
998     LLDB_LOGF(log,
999               "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1000               ": returning vote %i (thread didn't stop for a reason.)",
1001               GetID(), eVoteNoOpinion);
1002     return eVoteNoOpinion;
1003   }
1004 
1005   if (m_completed_plan_stack.size() > 0) {
1006     // Don't use GetCompletedPlan here, since that suppresses private plans.
1007     LLDB_LOGF(log,
1008               "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1009               ": returning vote  for complete stack's back plan",
1010               GetID());
1011     return m_completed_plan_stack.back()->ShouldReportStop(event_ptr);
1012   } else {
1013     Vote thread_vote = eVoteNoOpinion;
1014     ThreadPlan *plan_ptr = GetCurrentPlan();
1015     while (true) {
1016       if (plan_ptr->PlanExplainsStop(event_ptr)) {
1017         thread_vote = plan_ptr->ShouldReportStop(event_ptr);
1018         break;
1019       }
1020       if (PlanIsBasePlan(plan_ptr))
1021         break;
1022       else
1023         plan_ptr = GetPreviousPlan(plan_ptr);
1024     }
1025     LLDB_LOGF(log,
1026               "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1027               ": returning vote %i for current plan",
1028               GetID(), thread_vote);
1029 
1030     return thread_vote;
1031   }
1032 }
1033 
1034 Vote Thread::ShouldReportRun(Event *event_ptr) {
1035   StateType thread_state = GetResumeState();
1036 
1037   if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
1038     return eVoteNoOpinion;
1039   }
1040 
1041   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1042   if (m_completed_plan_stack.size() > 0) {
1043     // Don't use GetCompletedPlan here, since that suppresses private plans.
1044     LLDB_LOGF(log,
1045               "Current Plan for thread %d(%p) (0x%4.4" PRIx64
1046               ", %s): %s being asked whether we should report run.",
1047               GetIndexID(), static_cast<void *>(this), GetID(),
1048               StateAsCString(GetTemporaryResumeState()),
1049               m_completed_plan_stack.back()->GetName());
1050 
1051     return m_completed_plan_stack.back()->ShouldReportRun(event_ptr);
1052   } else {
1053     LLDB_LOGF(log,
1054               "Current Plan for thread %d(%p) (0x%4.4" PRIx64
1055               ", %s): %s being asked whether we should report run.",
1056               GetIndexID(), static_cast<void *>(this), GetID(),
1057               StateAsCString(GetTemporaryResumeState()),
1058               GetCurrentPlan()->GetName());
1059 
1060     return GetCurrentPlan()->ShouldReportRun(event_ptr);
1061   }
1062 }
1063 
1064 bool Thread::MatchesSpec(const ThreadSpec *spec) {
1065   return (spec == nullptr) ? true : spec->ThreadPassesBasicTests(*this);
1066 }
1067 
1068 void Thread::PushPlan(ThreadPlanSP &thread_plan_sp) {
1069   if (thread_plan_sp) {
1070     // If the thread plan doesn't already have a tracer, give it its parent's
1071     // tracer:
1072     if (!thread_plan_sp->GetThreadPlanTracer()) {
1073       assert(!m_plan_stack.empty());
1074       thread_plan_sp->SetThreadPlanTracer(
1075           m_plan_stack.back()->GetThreadPlanTracer());
1076     }
1077     m_plan_stack.push_back(thread_plan_sp);
1078 
1079     thread_plan_sp->DidPush();
1080 
1081     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1082     if (log) {
1083       StreamString s;
1084       thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelFull);
1085       LLDB_LOGF(log, "Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".",
1086                 static_cast<void *>(this), s.GetData(),
1087                 thread_plan_sp->GetThread().GetID());
1088     }
1089   }
1090 }
1091 
1092 void Thread::PopPlan() {
1093   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1094 
1095   if (m_plan_stack.size() <= 1)
1096     return;
1097   else {
1098     ThreadPlanSP &plan = m_plan_stack.back();
1099     if (log) {
1100       LLDB_LOGF(log, "Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1101                 plan->GetName(), plan->GetThread().GetID());
1102     }
1103     m_completed_plan_stack.push_back(plan);
1104     plan->WillPop();
1105     m_plan_stack.pop_back();
1106   }
1107 }
1108 
1109 void Thread::DiscardPlan() {
1110   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1111   if (m_plan_stack.size() > 1) {
1112     ThreadPlanSP &plan = m_plan_stack.back();
1113     LLDB_LOGF(log, "Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1114               plan->GetName(), plan->GetThread().GetID());
1115 
1116     m_discarded_plan_stack.push_back(plan);
1117     plan->WillPop();
1118     m_plan_stack.pop_back();
1119   }
1120 }
1121 
1122 ThreadPlan *Thread::GetCurrentPlan() {
1123   // There will always be at least the base plan.  If somebody is mucking with
1124   // a thread with an empty plan stack, we should assert right away.
1125   return m_plan_stack.empty() ? nullptr : m_plan_stack.back().get();
1126 }
1127 
1128 ThreadPlanSP Thread::GetCompletedPlan() {
1129   ThreadPlanSP empty_plan_sp;
1130   if (!m_completed_plan_stack.empty()) {
1131     for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) {
1132       ThreadPlanSP completed_plan_sp;
1133       completed_plan_sp = m_completed_plan_stack[i];
1134       if (!completed_plan_sp->GetPrivate())
1135         return completed_plan_sp;
1136     }
1137   }
1138   return empty_plan_sp;
1139 }
1140 
1141 ValueObjectSP Thread::GetReturnValueObject() {
1142   if (!m_completed_plan_stack.empty()) {
1143     for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) {
1144       ValueObjectSP return_valobj_sp;
1145       return_valobj_sp = m_completed_plan_stack[i]->GetReturnValueObject();
1146       if (return_valobj_sp)
1147         return return_valobj_sp;
1148     }
1149   }
1150   return ValueObjectSP();
1151 }
1152 
1153 ExpressionVariableSP Thread::GetExpressionVariable() {
1154   if (!m_completed_plan_stack.empty()) {
1155     for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) {
1156       ExpressionVariableSP expression_variable_sp;
1157       expression_variable_sp =
1158           m_completed_plan_stack[i]->GetExpressionVariable();
1159       if (expression_variable_sp)
1160         return expression_variable_sp;
1161     }
1162   }
1163   return ExpressionVariableSP();
1164 }
1165 
1166 bool Thread::IsThreadPlanDone(ThreadPlan *plan) {
1167   if (!m_completed_plan_stack.empty()) {
1168     for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) {
1169       if (m_completed_plan_stack[i].get() == plan)
1170         return true;
1171     }
1172   }
1173   return false;
1174 }
1175 
1176 bool Thread::WasThreadPlanDiscarded(ThreadPlan *plan) {
1177   if (!m_discarded_plan_stack.empty()) {
1178     for (int i = m_discarded_plan_stack.size() - 1; i >= 0; i--) {
1179       if (m_discarded_plan_stack[i].get() == plan)
1180         return true;
1181     }
1182   }
1183   return false;
1184 }
1185 
1186 bool Thread::CompletedPlanOverridesBreakpoint() {
1187   return (!m_completed_plan_stack.empty()) ;
1188 }
1189 
1190 ThreadPlan *Thread::GetPreviousPlan(ThreadPlan *current_plan) {
1191   if (current_plan == nullptr)
1192     return nullptr;
1193 
1194   int stack_size = m_completed_plan_stack.size();
1195   for (int i = stack_size - 1; i > 0; i--) {
1196     if (current_plan == m_completed_plan_stack[i].get())
1197       return m_completed_plan_stack[i - 1].get();
1198   }
1199 
1200   if (stack_size > 0 && m_completed_plan_stack[0].get() == current_plan) {
1201     return GetCurrentPlan();
1202   }
1203 
1204   stack_size = m_plan_stack.size();
1205   for (int i = stack_size - 1; i > 0; i--) {
1206     if (current_plan == m_plan_stack[i].get())
1207       return m_plan_stack[i - 1].get();
1208   }
1209   return nullptr;
1210 }
1211 
1212 Status Thread::QueueThreadPlan(ThreadPlanSP &thread_plan_sp,
1213                                bool abort_other_plans) {
1214   Status status;
1215   StreamString s;
1216   if (!thread_plan_sp->ValidatePlan(&s)) {
1217     DiscardThreadPlansUpToPlan(thread_plan_sp);
1218     thread_plan_sp.reset();
1219     status.SetErrorString(s.GetString());
1220     return status;
1221   }
1222 
1223   if (abort_other_plans)
1224     DiscardThreadPlans(true);
1225 
1226   PushPlan(thread_plan_sp);
1227 
1228   // This seems a little funny, but I don't want to have to split up the
1229   // constructor and the DidPush in the scripted plan, that seems annoying.
1230   // That means the constructor has to be in DidPush. So I have to validate the
1231   // plan AFTER pushing it, and then take it off again...
1232   if (!thread_plan_sp->ValidatePlan(&s)) {
1233     DiscardThreadPlansUpToPlan(thread_plan_sp);
1234     thread_plan_sp.reset();
1235     status.SetErrorString(s.GetString());
1236     return status;
1237   }
1238 
1239   return status;
1240 }
1241 
1242 void Thread::EnableTracer(bool value, bool single_stepping) {
1243   int stack_size = m_plan_stack.size();
1244   for (int i = 0; i < stack_size; i++) {
1245     if (m_plan_stack[i]->GetThreadPlanTracer()) {
1246       m_plan_stack[i]->GetThreadPlanTracer()->EnableTracing(value);
1247       m_plan_stack[i]->GetThreadPlanTracer()->EnableSingleStep(single_stepping);
1248     }
1249   }
1250 }
1251 
1252 void Thread::SetTracer(lldb::ThreadPlanTracerSP &tracer_sp) {
1253   int stack_size = m_plan_stack.size();
1254   for (int i = 0; i < stack_size; i++)
1255     m_plan_stack[i]->SetThreadPlanTracer(tracer_sp);
1256 }
1257 
1258 bool Thread::DiscardUserThreadPlansUpToIndex(uint32_t thread_index) {
1259   // Count the user thread plans from the back end to get the number of the one
1260   // we want to discard:
1261 
1262   uint32_t idx = 0;
1263   ThreadPlan *up_to_plan_ptr = nullptr;
1264 
1265   for (ThreadPlanSP plan_sp : m_plan_stack) {
1266     if (plan_sp->GetPrivate())
1267       continue;
1268     if (idx == thread_index) {
1269       up_to_plan_ptr = plan_sp.get();
1270       break;
1271     } else
1272       idx++;
1273   }
1274 
1275   if (up_to_plan_ptr == nullptr)
1276     return false;
1277 
1278   DiscardThreadPlansUpToPlan(up_to_plan_ptr);
1279   return true;
1280 }
1281 
1282 void Thread::DiscardThreadPlansUpToPlan(lldb::ThreadPlanSP &up_to_plan_sp) {
1283   DiscardThreadPlansUpToPlan(up_to_plan_sp.get());
1284 }
1285 
1286 void Thread::DiscardThreadPlansUpToPlan(ThreadPlan *up_to_plan_ptr) {
1287   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1288   LLDB_LOGF(log,
1289             "Discarding thread plans for thread tid = 0x%4.4" PRIx64
1290             ", up to %p",
1291             GetID(), static_cast<void *>(up_to_plan_ptr));
1292 
1293   int stack_size = m_plan_stack.size();
1294 
1295   // If the input plan is nullptr, discard all plans.  Otherwise make sure this
1296   // plan is in the stack, and if so discard up to and including it.
1297 
1298   if (up_to_plan_ptr == nullptr) {
1299     for (int i = stack_size - 1; i > 0; i--)
1300       DiscardPlan();
1301   } else {
1302     bool found_it = false;
1303     for (int i = stack_size - 1; i > 0; i--) {
1304       if (m_plan_stack[i].get() == up_to_plan_ptr)
1305         found_it = true;
1306     }
1307     if (found_it) {
1308       bool last_one = false;
1309       for (int i = stack_size - 1; i > 0 && !last_one; i--) {
1310         if (GetCurrentPlan() == up_to_plan_ptr)
1311           last_one = true;
1312         DiscardPlan();
1313       }
1314     }
1315   }
1316 }
1317 
1318 void Thread::DiscardThreadPlans(bool force) {
1319   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1320   if (log) {
1321     LLDB_LOGF(log,
1322               "Discarding thread plans for thread (tid = 0x%4.4" PRIx64
1323               ", force %d)",
1324               GetID(), force);
1325   }
1326 
1327   if (force) {
1328     int stack_size = m_plan_stack.size();
1329     for (int i = stack_size - 1; i > 0; i--) {
1330       DiscardPlan();
1331     }
1332     return;
1333   }
1334 
1335   while (true) {
1336     int master_plan_idx;
1337     bool discard = true;
1338 
1339     // Find the first master plan, see if it wants discarding, and if yes
1340     // discard up to it.
1341     for (master_plan_idx = m_plan_stack.size() - 1; master_plan_idx >= 0;
1342          master_plan_idx--) {
1343       if (m_plan_stack[master_plan_idx]->IsMasterPlan()) {
1344         discard = m_plan_stack[master_plan_idx]->OkayToDiscard();
1345         break;
1346       }
1347     }
1348 
1349     if (discard) {
1350       // First pop all the dependent plans:
1351       for (int i = m_plan_stack.size() - 1; i > master_plan_idx; i--) {
1352         // FIXME: Do we need a finalize here, or is the rule that
1353         // "PrepareForStop"
1354         // for the plan leaves it in a state that it is safe to pop the plan
1355         // with no more notice?
1356         DiscardPlan();
1357       }
1358 
1359       // Now discard the master plan itself.
1360       // The bottom-most plan never gets discarded.  "OkayToDiscard" for it
1361       // means discard it's dependent plans, but not it...
1362       if (master_plan_idx > 0) {
1363         DiscardPlan();
1364       }
1365     } else {
1366       // If the master plan doesn't want to get discarded, then we're done.
1367       break;
1368     }
1369   }
1370 }
1371 
1372 bool Thread::PlanIsBasePlan(ThreadPlan *plan_ptr) {
1373   if (plan_ptr->IsBasePlan())
1374     return true;
1375   else if (m_plan_stack.size() == 0)
1376     return false;
1377   else
1378     return m_plan_stack[0].get() == plan_ptr;
1379 }
1380 
1381 Status Thread::UnwindInnermostExpression() {
1382   Status error;
1383   int stack_size = m_plan_stack.size();
1384 
1385   // If the input plan is nullptr, discard all plans.  Otherwise make sure this
1386   // plan is in the stack, and if so discard up to and including it.
1387 
1388   for (int i = stack_size - 1; i > 0; i--) {
1389     if (m_plan_stack[i]->GetKind() == ThreadPlan::eKindCallFunction) {
1390       DiscardThreadPlansUpToPlan(m_plan_stack[i].get());
1391       return error;
1392     }
1393   }
1394   error.SetErrorString("No expressions currently active on this thread");
1395   return error;
1396 }
1397 
1398 ThreadPlanSP Thread::QueueFundamentalPlan(bool abort_other_plans) {
1399   ThreadPlanSP thread_plan_sp(new ThreadPlanBase(*this));
1400   QueueThreadPlan(thread_plan_sp, abort_other_plans);
1401   return thread_plan_sp;
1402 }
1403 
1404 ThreadPlanSP Thread::QueueThreadPlanForStepSingleInstruction(
1405     bool step_over, bool abort_other_plans, bool stop_other_threads,
1406     Status &status) {
1407   ThreadPlanSP thread_plan_sp(new ThreadPlanStepInstruction(
1408       *this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
1409   status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1410   return thread_plan_sp;
1411 }
1412 
1413 ThreadPlanSP Thread::QueueThreadPlanForStepOverRange(
1414     bool abort_other_plans, const AddressRange &range,
1415     const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1416     Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
1417   ThreadPlanSP thread_plan_sp;
1418   thread_plan_sp = std::make_shared<ThreadPlanStepOverRange>(
1419       *this, range, addr_context, stop_other_threads,
1420       step_out_avoids_code_withoug_debug_info);
1421 
1422   status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1423   return thread_plan_sp;
1424 }
1425 
1426 // Call the QueueThreadPlanForStepOverRange method which takes an address
1427 // range.
1428 ThreadPlanSP Thread::QueueThreadPlanForStepOverRange(
1429     bool abort_other_plans, const LineEntry &line_entry,
1430     const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1431     Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
1432   const bool include_inlined_functions = true;
1433   auto address_range =
1434       line_entry.GetSameLineContiguousAddressRange(include_inlined_functions);
1435   return QueueThreadPlanForStepOverRange(
1436       abort_other_plans, address_range, addr_context, stop_other_threads,
1437       status, step_out_avoids_code_withoug_debug_info);
1438 }
1439 
1440 ThreadPlanSP Thread::QueueThreadPlanForStepInRange(
1441     bool abort_other_plans, const AddressRange &range,
1442     const SymbolContext &addr_context, const char *step_in_target,
1443     lldb::RunMode stop_other_threads, Status &status,
1444     LazyBool step_in_avoids_code_without_debug_info,
1445     LazyBool step_out_avoids_code_without_debug_info) {
1446   ThreadPlanSP thread_plan_sp(
1447       new ThreadPlanStepInRange(*this, range, addr_context, stop_other_threads,
1448                                 step_in_avoids_code_without_debug_info,
1449                                 step_out_avoids_code_without_debug_info));
1450   ThreadPlanStepInRange *plan =
1451       static_cast<ThreadPlanStepInRange *>(thread_plan_sp.get());
1452 
1453   if (step_in_target)
1454     plan->SetStepInTarget(step_in_target);
1455 
1456   status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1457   return thread_plan_sp;
1458 }
1459 
1460 // Call the QueueThreadPlanForStepInRange method which takes an address range.
1461 ThreadPlanSP Thread::QueueThreadPlanForStepInRange(
1462     bool abort_other_plans, const LineEntry &line_entry,
1463     const SymbolContext &addr_context, const char *step_in_target,
1464     lldb::RunMode stop_other_threads, Status &status,
1465     LazyBool step_in_avoids_code_without_debug_info,
1466     LazyBool step_out_avoids_code_without_debug_info) {
1467   const bool include_inlined_functions = false;
1468   return QueueThreadPlanForStepInRange(
1469       abort_other_plans,
1470       line_entry.GetSameLineContiguousAddressRange(include_inlined_functions),
1471       addr_context, step_in_target, stop_other_threads, status,
1472       step_in_avoids_code_without_debug_info,
1473       step_out_avoids_code_without_debug_info);
1474 }
1475 
1476 ThreadPlanSP Thread::QueueThreadPlanForStepOut(
1477     bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1478     bool stop_other_threads, Vote stop_vote, Vote run_vote, uint32_t frame_idx,
1479     Status &status, LazyBool step_out_avoids_code_without_debug_info) {
1480   ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1481       *this, addr_context, first_insn, stop_other_threads, stop_vote, run_vote,
1482       frame_idx, step_out_avoids_code_without_debug_info));
1483 
1484   status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1485   return thread_plan_sp;
1486 }
1487 
1488 ThreadPlanSP Thread::QueueThreadPlanForStepOutNoShouldStop(
1489     bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1490     bool stop_other_threads, Vote stop_vote, Vote run_vote, uint32_t frame_idx,
1491     Status &status, bool continue_to_next_branch) {
1492   const bool calculate_return_value =
1493       false; // No need to calculate the return value here.
1494   ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1495       *this, addr_context, first_insn, stop_other_threads, stop_vote, run_vote,
1496       frame_idx, eLazyBoolNo, continue_to_next_branch, calculate_return_value));
1497 
1498   ThreadPlanStepOut *new_plan =
1499       static_cast<ThreadPlanStepOut *>(thread_plan_sp.get());
1500   new_plan->ClearShouldStopHereCallbacks();
1501 
1502   status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1503   return thread_plan_sp;
1504 }
1505 
1506 ThreadPlanSP Thread::QueueThreadPlanForStepThrough(StackID &return_stack_id,
1507                                                    bool abort_other_plans,
1508                                                    bool stop_other_threads,
1509                                                    Status &status) {
1510   ThreadPlanSP thread_plan_sp(
1511       new ThreadPlanStepThrough(*this, return_stack_id, stop_other_threads));
1512   if (!thread_plan_sp || !thread_plan_sp->ValidatePlan(nullptr))
1513     return ThreadPlanSP();
1514 
1515   status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1516   return thread_plan_sp;
1517 }
1518 
1519 ThreadPlanSP Thread::QueueThreadPlanForRunToAddress(bool abort_other_plans,
1520                                                     Address &target_addr,
1521                                                     bool stop_other_threads,
1522                                                     Status &status) {
1523   ThreadPlanSP thread_plan_sp(
1524       new ThreadPlanRunToAddress(*this, target_addr, stop_other_threads));
1525 
1526   status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1527   return thread_plan_sp;
1528 }
1529 
1530 ThreadPlanSP Thread::QueueThreadPlanForStepUntil(
1531     bool abort_other_plans, lldb::addr_t *address_list, size_t num_addresses,
1532     bool stop_other_threads, uint32_t frame_idx, Status &status) {
1533   ThreadPlanSP thread_plan_sp(new ThreadPlanStepUntil(
1534       *this, address_list, num_addresses, stop_other_threads, frame_idx));
1535 
1536   status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1537   return thread_plan_sp;
1538 }
1539 
1540 lldb::ThreadPlanSP Thread::QueueThreadPlanForStepScripted(
1541     bool abort_other_plans, const char *class_name,
1542     StructuredData::ObjectSP extra_args_sp,  bool stop_other_threads,
1543     Status &status) {
1544 
1545   StructuredDataImpl *extra_args_impl = nullptr;
1546   if (extra_args_sp) {
1547     extra_args_impl = new StructuredDataImpl();
1548     extra_args_impl->SetObjectSP(extra_args_sp);
1549   }
1550 
1551   ThreadPlanSP thread_plan_sp(new ThreadPlanPython(*this, class_name,
1552                                                    extra_args_impl));
1553 
1554   status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1555   return thread_plan_sp;
1556 }
1557 
1558 uint32_t Thread::GetIndexID() const { return m_index_id; }
1559 
1560 static void PrintPlanElement(Stream *s, const ThreadPlanSP &plan,
1561                              lldb::DescriptionLevel desc_level,
1562                              int32_t elem_idx) {
1563   s->IndentMore();
1564   s->Indent();
1565   s->Printf("Element %d: ", elem_idx);
1566   plan->GetDescription(s, desc_level);
1567   s->EOL();
1568   s->IndentLess();
1569 }
1570 
1571 static void PrintPlanStack(Stream *s,
1572                            const std::vector<lldb::ThreadPlanSP> &plan_stack,
1573                            lldb::DescriptionLevel desc_level,
1574                            bool include_internal) {
1575   int32_t print_idx = 0;
1576   for (ThreadPlanSP plan_sp : plan_stack) {
1577     if (include_internal || !plan_sp->GetPrivate()) {
1578       PrintPlanElement(s, plan_sp, desc_level, print_idx++);
1579     }
1580   }
1581 }
1582 
1583 void Thread::DumpThreadPlans(Stream *s, lldb::DescriptionLevel desc_level,
1584                              bool include_internal,
1585                              bool ignore_boring_threads) const {
1586   uint32_t stack_size;
1587 
1588   if (ignore_boring_threads) {
1589     uint32_t stack_size = m_plan_stack.size();
1590     uint32_t completed_stack_size = m_completed_plan_stack.size();
1591     uint32_t discarded_stack_size = m_discarded_plan_stack.size();
1592     if (stack_size == 1 && completed_stack_size == 0 &&
1593         discarded_stack_size == 0) {
1594       s->Printf("thread #%u: tid = 0x%4.4" PRIx64 "\n", GetIndexID(), GetID());
1595       s->IndentMore();
1596       s->Indent();
1597       s->Printf("No active thread plans\n");
1598       s->IndentLess();
1599       return;
1600     }
1601   }
1602 
1603   s->Indent();
1604   s->Printf("thread #%u: tid = 0x%4.4" PRIx64 ":\n", GetIndexID(), GetID());
1605   s->IndentMore();
1606   s->Indent();
1607   s->Printf("Active plan stack:\n");
1608   PrintPlanStack(s, m_plan_stack, desc_level, include_internal);
1609 
1610   stack_size = m_completed_plan_stack.size();
1611   if (stack_size > 0) {
1612     s->Indent();
1613     s->Printf("Completed Plan Stack:\n");
1614     PrintPlanStack(s, m_completed_plan_stack, desc_level, include_internal);
1615   }
1616 
1617   stack_size = m_discarded_plan_stack.size();
1618   if (stack_size > 0) {
1619     s->Indent();
1620     s->Printf("Discarded Plan Stack:\n");
1621     PrintPlanStack(s, m_discarded_plan_stack, desc_level, include_internal);
1622   }
1623 
1624   s->IndentLess();
1625 }
1626 
1627 TargetSP Thread::CalculateTarget() {
1628   TargetSP target_sp;
1629   ProcessSP process_sp(GetProcess());
1630   if (process_sp)
1631     target_sp = process_sp->CalculateTarget();
1632   return target_sp;
1633 }
1634 
1635 ProcessSP Thread::CalculateProcess() { return GetProcess(); }
1636 
1637 ThreadSP Thread::CalculateThread() { return shared_from_this(); }
1638 
1639 StackFrameSP Thread::CalculateStackFrame() { return StackFrameSP(); }
1640 
1641 void Thread::CalculateExecutionContext(ExecutionContext &exe_ctx) {
1642   exe_ctx.SetContext(shared_from_this());
1643 }
1644 
1645 StackFrameListSP Thread::GetStackFrameList() {
1646   std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1647 
1648   if (!m_curr_frames_sp)
1649     m_curr_frames_sp =
1650         std::make_shared<StackFrameList>(*this, m_prev_frames_sp, true);
1651 
1652   return m_curr_frames_sp;
1653 }
1654 
1655 void Thread::ClearStackFrames() {
1656   std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1657 
1658   Unwind *unwinder = GetUnwinder();
1659   if (unwinder)
1660     unwinder->Clear();
1661 
1662   // Only store away the old "reference" StackFrameList if we got all its
1663   // frames:
1664   // FIXME: At some point we can try to splice in the frames we have fetched
1665   // into
1666   // the new frame as we make it, but let's not try that now.
1667   if (m_curr_frames_sp && m_curr_frames_sp->GetAllFramesFetched())
1668     m_prev_frames_sp.swap(m_curr_frames_sp);
1669   m_curr_frames_sp.reset();
1670 
1671   m_extended_info.reset();
1672   m_extended_info_fetched = false;
1673 }
1674 
1675 lldb::StackFrameSP Thread::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) {
1676   return GetStackFrameList()->GetFrameWithConcreteFrameIndex(unwind_idx);
1677 }
1678 
1679 Status Thread::ReturnFromFrameWithIndex(uint32_t frame_idx,
1680                                         lldb::ValueObjectSP return_value_sp,
1681                                         bool broadcast) {
1682   StackFrameSP frame_sp = GetStackFrameAtIndex(frame_idx);
1683   Status return_error;
1684 
1685   if (!frame_sp) {
1686     return_error.SetErrorStringWithFormat(
1687         "Could not find frame with index %d in thread 0x%" PRIx64 ".",
1688         frame_idx, GetID());
1689   }
1690 
1691   return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
1692 }
1693 
1694 Status Thread::ReturnFromFrame(lldb::StackFrameSP frame_sp,
1695                                lldb::ValueObjectSP return_value_sp,
1696                                bool broadcast) {
1697   Status return_error;
1698 
1699   if (!frame_sp) {
1700     return_error.SetErrorString("Can't return to a null frame.");
1701     return return_error;
1702   }
1703 
1704   Thread *thread = frame_sp->GetThread().get();
1705   uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
1706   StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
1707   if (!older_frame_sp) {
1708     return_error.SetErrorString("No older frame to return to.");
1709     return return_error;
1710   }
1711 
1712   if (return_value_sp) {
1713     lldb::ABISP abi = thread->GetProcess()->GetABI();
1714     if (!abi) {
1715       return_error.SetErrorString("Could not find ABI to set return value.");
1716       return return_error;
1717     }
1718     SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
1719 
1720     // FIXME: ValueObject::Cast doesn't currently work correctly, at least not
1721     // for scalars.
1722     // Turn that back on when that works.
1723     if (/* DISABLES CODE */ (false) && sc.function != nullptr) {
1724       Type *function_type = sc.function->GetType();
1725       if (function_type) {
1726         CompilerType return_type =
1727             sc.function->GetCompilerType().GetFunctionReturnType();
1728         if (return_type) {
1729           StreamString s;
1730           return_type.DumpTypeDescription(&s);
1731           ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type);
1732           if (cast_value_sp) {
1733             cast_value_sp->SetFormat(eFormatHex);
1734             return_value_sp = cast_value_sp;
1735           }
1736         }
1737       }
1738     }
1739 
1740     return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
1741     if (!return_error.Success())
1742       return return_error;
1743   }
1744 
1745   // Now write the return registers for the chosen frame: Note, we can't use
1746   // ReadAllRegisterValues->WriteAllRegisterValues, since the read & write cook
1747   // their data
1748 
1749   StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);
1750   if (youngest_frame_sp) {
1751     lldb::RegisterContextSP reg_ctx_sp(youngest_frame_sp->GetRegisterContext());
1752     if (reg_ctx_sp) {
1753       bool copy_success = reg_ctx_sp->CopyFromRegisterContext(
1754           older_frame_sp->GetRegisterContext());
1755       if (copy_success) {
1756         thread->DiscardThreadPlans(true);
1757         thread->ClearStackFrames();
1758         if (broadcast && EventTypeHasListeners(eBroadcastBitStackChanged))
1759           BroadcastEvent(eBroadcastBitStackChanged,
1760                          new ThreadEventData(this->shared_from_this()));
1761       } else {
1762         return_error.SetErrorString("Could not reset register values.");
1763       }
1764     } else {
1765       return_error.SetErrorString("Frame has no register context.");
1766     }
1767   } else {
1768     return_error.SetErrorString("Returned past top frame.");
1769   }
1770   return return_error;
1771 }
1772 
1773 static void DumpAddressList(Stream &s, const std::vector<Address> &list,
1774                             ExecutionContextScope *exe_scope) {
1775   for (size_t n = 0; n < list.size(); n++) {
1776     s << "\t";
1777     list[n].Dump(&s, exe_scope, Address::DumpStyleResolvedDescription,
1778                  Address::DumpStyleSectionNameOffset);
1779     s << "\n";
1780   }
1781 }
1782 
1783 Status Thread::JumpToLine(const FileSpec &file, uint32_t line,
1784                           bool can_leave_function, std::string *warnings) {
1785   ExecutionContext exe_ctx(GetStackFrameAtIndex(0));
1786   Target *target = exe_ctx.GetTargetPtr();
1787   TargetSP target_sp = exe_ctx.GetTargetSP();
1788   RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1789   StackFrame *frame = exe_ctx.GetFramePtr();
1790   const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction);
1791 
1792   // Find candidate locations.
1793   std::vector<Address> candidates, within_function, outside_function;
1794   target->GetImages().FindAddressesForLine(target_sp, file, line, sc.function,
1795                                            within_function, outside_function);
1796 
1797   // If possible, we try and stay within the current function. Within a
1798   // function, we accept multiple locations (optimized code may do this,
1799   // there's no solution here so we do the best we can). However if we're
1800   // trying to leave the function, we don't know how to pick the right
1801   // location, so if there's more than one then we bail.
1802   if (!within_function.empty())
1803     candidates = within_function;
1804   else if (outside_function.size() == 1 && can_leave_function)
1805     candidates = outside_function;
1806 
1807   // Check if we got anything.
1808   if (candidates.empty()) {
1809     if (outside_function.empty()) {
1810       return Status("Cannot locate an address for %s:%i.",
1811                     file.GetFilename().AsCString(), line);
1812     } else if (outside_function.size() == 1) {
1813       return Status("%s:%i is outside the current function.",
1814                     file.GetFilename().AsCString(), line);
1815     } else {
1816       StreamString sstr;
1817       DumpAddressList(sstr, outside_function, target);
1818       return Status("%s:%i has multiple candidate locations:\n%s",
1819                     file.GetFilename().AsCString(), line, sstr.GetData());
1820     }
1821   }
1822 
1823   // Accept the first location, warn about any others.
1824   Address dest = candidates[0];
1825   if (warnings && candidates.size() > 1) {
1826     StreamString sstr;
1827     sstr.Printf("%s:%i appears multiple times in this function, selecting the "
1828                 "first location:\n",
1829                 file.GetFilename().AsCString(), line);
1830     DumpAddressList(sstr, candidates, target);
1831     *warnings = std::string(sstr.GetString());
1832   }
1833 
1834   if (!reg_ctx->SetPC(dest))
1835     return Status("Cannot change PC to target address.");
1836 
1837   return Status();
1838 }
1839 
1840 void Thread::DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx,
1841                                      bool stop_format) {
1842   ExecutionContext exe_ctx(shared_from_this());
1843   Process *process = exe_ctx.GetProcessPtr();
1844   if (process == nullptr)
1845     return;
1846 
1847   StackFrameSP frame_sp;
1848   SymbolContext frame_sc;
1849   if (frame_idx != LLDB_INVALID_FRAME_ID) {
1850     frame_sp = GetStackFrameAtIndex(frame_idx);
1851     if (frame_sp) {
1852       exe_ctx.SetFrameSP(frame_sp);
1853       frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
1854     }
1855   }
1856 
1857   const FormatEntity::Entry *thread_format;
1858   if (stop_format)
1859     thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadStopFormat();
1860   else
1861     thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
1862 
1863   assert(thread_format);
1864 
1865   FormatEntity::Format(*thread_format, strm, frame_sp ? &frame_sc : nullptr,
1866                        &exe_ctx, nullptr, nullptr, false, false);
1867 }
1868 
1869 void Thread::SettingsInitialize() {}
1870 
1871 void Thread::SettingsTerminate() {}
1872 
1873 lldb::addr_t Thread::GetThreadPointer() { return LLDB_INVALID_ADDRESS; }
1874 
1875 addr_t Thread::GetThreadLocalData(const ModuleSP module,
1876                                   lldb::addr_t tls_file_addr) {
1877   // The default implementation is to ask the dynamic loader for it. This can
1878   // be overridden for specific platforms.
1879   DynamicLoader *loader = GetProcess()->GetDynamicLoader();
1880   if (loader)
1881     return loader->GetThreadLocalData(module, shared_from_this(),
1882                                       tls_file_addr);
1883   else
1884     return LLDB_INVALID_ADDRESS;
1885 }
1886 
1887 bool Thread::SafeToCallFunctions() {
1888   Process *process = GetProcess().get();
1889   if (process) {
1890     SystemRuntime *runtime = process->GetSystemRuntime();
1891     if (runtime) {
1892       return runtime->SafeToCallFunctionsOnThisThread(shared_from_this());
1893     }
1894   }
1895   return true;
1896 }
1897 
1898 lldb::StackFrameSP
1899 Thread::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) {
1900   return GetStackFrameList()->GetStackFrameSPForStackFramePtr(stack_frame_ptr);
1901 }
1902 
1903 const char *Thread::StopReasonAsCString(lldb::StopReason reason) {
1904   switch (reason) {
1905   case eStopReasonInvalid:
1906     return "invalid";
1907   case eStopReasonNone:
1908     return "none";
1909   case eStopReasonTrace:
1910     return "trace";
1911   case eStopReasonBreakpoint:
1912     return "breakpoint";
1913   case eStopReasonWatchpoint:
1914     return "watchpoint";
1915   case eStopReasonSignal:
1916     return "signal";
1917   case eStopReasonException:
1918     return "exception";
1919   case eStopReasonExec:
1920     return "exec";
1921   case eStopReasonPlanComplete:
1922     return "plan complete";
1923   case eStopReasonThreadExiting:
1924     return "thread exiting";
1925   case eStopReasonInstrumentation:
1926     return "instrumentation break";
1927   }
1928 
1929   static char unknown_state_string[64];
1930   snprintf(unknown_state_string, sizeof(unknown_state_string),
1931            "StopReason = %i", reason);
1932   return unknown_state_string;
1933 }
1934 
1935 const char *Thread::RunModeAsCString(lldb::RunMode mode) {
1936   switch (mode) {
1937   case eOnlyThisThread:
1938     return "only this thread";
1939   case eAllThreads:
1940     return "all threads";
1941   case eOnlyDuringStepping:
1942     return "only during stepping";
1943   }
1944 
1945   static char unknown_state_string[64];
1946   snprintf(unknown_state_string, sizeof(unknown_state_string), "RunMode = %i",
1947            mode);
1948   return unknown_state_string;
1949 }
1950 
1951 size_t Thread::GetStatus(Stream &strm, uint32_t start_frame,
1952                          uint32_t num_frames, uint32_t num_frames_with_source,
1953                          bool stop_format, bool only_stacks) {
1954 
1955   if (!only_stacks) {
1956     ExecutionContext exe_ctx(shared_from_this());
1957     Target *target = exe_ctx.GetTargetPtr();
1958     Process *process = exe_ctx.GetProcessPtr();
1959     strm.Indent();
1960     bool is_selected = false;
1961     if (process) {
1962       if (process->GetThreadList().GetSelectedThread().get() == this)
1963         is_selected = true;
1964     }
1965     strm.Printf("%c ", is_selected ? '*' : ' ');
1966     if (target && target->GetDebugger().GetUseExternalEditor()) {
1967       StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
1968       if (frame_sp) {
1969         SymbolContext frame_sc(
1970             frame_sp->GetSymbolContext(eSymbolContextLineEntry));
1971         if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file) {
1972           Host::OpenFileInExternalEditor(frame_sc.line_entry.file,
1973                                          frame_sc.line_entry.line);
1974         }
1975       }
1976     }
1977 
1978     DumpUsingSettingsFormat(strm, start_frame, stop_format);
1979   }
1980 
1981   size_t num_frames_shown = 0;
1982   if (num_frames > 0) {
1983     strm.IndentMore();
1984 
1985     const bool show_frame_info = true;
1986     const bool show_frame_unique = only_stacks;
1987     const char *selected_frame_marker = nullptr;
1988     if (num_frames == 1 || only_stacks ||
1989         (GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID()))
1990       strm.IndentMore();
1991     else
1992       selected_frame_marker = "* ";
1993 
1994     num_frames_shown = GetStackFrameList()->GetStatus(
1995         strm, start_frame, num_frames, show_frame_info, num_frames_with_source,
1996         show_frame_unique, selected_frame_marker);
1997     if (num_frames == 1)
1998       strm.IndentLess();
1999     strm.IndentLess();
2000   }
2001   return num_frames_shown;
2002 }
2003 
2004 bool Thread::GetDescription(Stream &strm, lldb::DescriptionLevel level,
2005                             bool print_json_thread, bool print_json_stopinfo) {
2006   const bool stop_format = false;
2007   DumpUsingSettingsFormat(strm, 0, stop_format);
2008   strm.Printf("\n");
2009 
2010   StructuredData::ObjectSP thread_info = GetExtendedInfo();
2011 
2012   if (print_json_thread || print_json_stopinfo) {
2013     if (thread_info && print_json_thread) {
2014       thread_info->Dump(strm);
2015       strm.Printf("\n");
2016     }
2017 
2018     if (print_json_stopinfo && m_stop_info_sp) {
2019       StructuredData::ObjectSP stop_info = m_stop_info_sp->GetExtendedInfo();
2020       if (stop_info) {
2021         stop_info->Dump(strm);
2022         strm.Printf("\n");
2023       }
2024     }
2025 
2026     return true;
2027   }
2028 
2029   if (thread_info) {
2030     StructuredData::ObjectSP activity =
2031         thread_info->GetObjectForDotSeparatedPath("activity");
2032     StructuredData::ObjectSP breadcrumb =
2033         thread_info->GetObjectForDotSeparatedPath("breadcrumb");
2034     StructuredData::ObjectSP messages =
2035         thread_info->GetObjectForDotSeparatedPath("trace_messages");
2036 
2037     bool printed_activity = false;
2038     if (activity && activity->GetType() == eStructuredDataTypeDictionary) {
2039       StructuredData::Dictionary *activity_dict = activity->GetAsDictionary();
2040       StructuredData::ObjectSP id = activity_dict->GetValueForKey("id");
2041       StructuredData::ObjectSP name = activity_dict->GetValueForKey("name");
2042       if (name && name->GetType() == eStructuredDataTypeString && id &&
2043           id->GetType() == eStructuredDataTypeInteger) {
2044         strm.Format("  Activity '{0}', {1:x}\n",
2045                     name->GetAsString()->GetValue(),
2046                     id->GetAsInteger()->GetValue());
2047       }
2048       printed_activity = true;
2049     }
2050     bool printed_breadcrumb = false;
2051     if (breadcrumb && breadcrumb->GetType() == eStructuredDataTypeDictionary) {
2052       if (printed_activity)
2053         strm.Printf("\n");
2054       StructuredData::Dictionary *breadcrumb_dict =
2055           breadcrumb->GetAsDictionary();
2056       StructuredData::ObjectSP breadcrumb_text =
2057           breadcrumb_dict->GetValueForKey("name");
2058       if (breadcrumb_text &&
2059           breadcrumb_text->GetType() == eStructuredDataTypeString) {
2060         strm.Format("  Current Breadcrumb: {0}\n",
2061                     breadcrumb_text->GetAsString()->GetValue());
2062       }
2063       printed_breadcrumb = true;
2064     }
2065     if (messages && messages->GetType() == eStructuredDataTypeArray) {
2066       if (printed_breadcrumb)
2067         strm.Printf("\n");
2068       StructuredData::Array *messages_array = messages->GetAsArray();
2069       const size_t msg_count = messages_array->GetSize();
2070       if (msg_count > 0) {
2071         strm.Printf("  %zu trace messages:\n", msg_count);
2072         for (size_t i = 0; i < msg_count; i++) {
2073           StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i);
2074           if (message && message->GetType() == eStructuredDataTypeDictionary) {
2075             StructuredData::Dictionary *message_dict =
2076                 message->GetAsDictionary();
2077             StructuredData::ObjectSP message_text =
2078                 message_dict->GetValueForKey("message");
2079             if (message_text &&
2080                 message_text->GetType() == eStructuredDataTypeString) {
2081               strm.Format("    {0}\n", message_text->GetAsString()->GetValue());
2082             }
2083           }
2084         }
2085       }
2086     }
2087   }
2088 
2089   return true;
2090 }
2091 
2092 size_t Thread::GetStackFrameStatus(Stream &strm, uint32_t first_frame,
2093                                    uint32_t num_frames, bool show_frame_info,
2094                                    uint32_t num_frames_with_source) {
2095   return GetStackFrameList()->GetStatus(
2096       strm, first_frame, num_frames, show_frame_info, num_frames_with_source);
2097 }
2098 
2099 Unwind *Thread::GetUnwinder() {
2100   if (!m_unwinder_up) {
2101     const ArchSpec target_arch(CalculateTarget()->GetArchitecture());
2102     const llvm::Triple::ArchType machine = target_arch.GetMachine();
2103     switch (machine) {
2104     case llvm::Triple::x86_64:
2105     case llvm::Triple::x86:
2106     case llvm::Triple::arm:
2107     case llvm::Triple::aarch64:
2108     case llvm::Triple::aarch64_32:
2109     case llvm::Triple::thumb:
2110     case llvm::Triple::mips:
2111     case llvm::Triple::mipsel:
2112     case llvm::Triple::mips64:
2113     case llvm::Triple::mips64el:
2114     case llvm::Triple::ppc:
2115     case llvm::Triple::ppc64:
2116     case llvm::Triple::ppc64le:
2117     case llvm::Triple::systemz:
2118     case llvm::Triple::hexagon:
2119     case llvm::Triple::arc:
2120       m_unwinder_up.reset(new UnwindLLDB(*this));
2121       break;
2122 
2123     default:
2124       if (target_arch.GetTriple().getVendor() == llvm::Triple::Apple)
2125         m_unwinder_up.reset(new UnwindMacOSXFrameBackchain(*this));
2126       break;
2127     }
2128   }
2129   return m_unwinder_up.get();
2130 }
2131 
2132 void Thread::Flush() {
2133   ClearStackFrames();
2134   m_reg_context_sp.reset();
2135 }
2136 
2137 bool Thread::IsStillAtLastBreakpointHit() {
2138   // If we are currently stopped at a breakpoint, always return that stopinfo
2139   // and don't reset it. This allows threads to maintain their breakpoint
2140   // stopinfo, such as when thread-stepping in multithreaded programs.
2141   if (m_stop_info_sp) {
2142     StopReason stop_reason = m_stop_info_sp->GetStopReason();
2143     if (stop_reason == lldb::eStopReasonBreakpoint) {
2144       uint64_t value = m_stop_info_sp->GetValue();
2145       lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext());
2146       if (reg_ctx_sp) {
2147         lldb::addr_t pc = reg_ctx_sp->GetPC();
2148         BreakpointSiteSP bp_site_sp =
2149             GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2150         if (bp_site_sp && static_cast<break_id_t>(value) == bp_site_sp->GetID())
2151           return true;
2152       }
2153     }
2154   }
2155   return false;
2156 }
2157 
2158 Status Thread::StepIn(bool source_step,
2159                       LazyBool step_in_avoids_code_without_debug_info,
2160                       LazyBool step_out_avoids_code_without_debug_info)
2161 
2162 {
2163   Status error;
2164   Process *process = GetProcess().get();
2165   if (StateIsStoppedState(process->GetState(), true)) {
2166     StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2167     ThreadPlanSP new_plan_sp;
2168     const lldb::RunMode run_mode = eOnlyThisThread;
2169     const bool abort_other_plans = false;
2170 
2171     if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2172       SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2173       new_plan_sp = QueueThreadPlanForStepInRange(
2174           abort_other_plans, sc.line_entry, sc, nullptr, run_mode, error,
2175           step_in_avoids_code_without_debug_info,
2176           step_out_avoids_code_without_debug_info);
2177     } else {
2178       new_plan_sp = QueueThreadPlanForStepSingleInstruction(
2179           false, abort_other_plans, run_mode, error);
2180     }
2181 
2182     new_plan_sp->SetIsMasterPlan(true);
2183     new_plan_sp->SetOkayToDiscard(false);
2184 
2185     // Why do we need to set the current thread by ID here???
2186     process->GetThreadList().SetSelectedThreadByID(GetID());
2187     error = process->Resume();
2188   } else {
2189     error.SetErrorString("process not stopped");
2190   }
2191   return error;
2192 }
2193 
2194 Status Thread::StepOver(bool source_step,
2195                         LazyBool step_out_avoids_code_without_debug_info) {
2196   Status error;
2197   Process *process = GetProcess().get();
2198   if (StateIsStoppedState(process->GetState(), true)) {
2199     StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2200     ThreadPlanSP new_plan_sp;
2201 
2202     const lldb::RunMode run_mode = eOnlyThisThread;
2203     const bool abort_other_plans = false;
2204 
2205     if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2206       SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2207       new_plan_sp = QueueThreadPlanForStepOverRange(
2208           abort_other_plans, sc.line_entry, sc, run_mode, error,
2209           step_out_avoids_code_without_debug_info);
2210     } else {
2211       new_plan_sp = QueueThreadPlanForStepSingleInstruction(
2212           true, abort_other_plans, run_mode, error);
2213     }
2214 
2215     new_plan_sp->SetIsMasterPlan(true);
2216     new_plan_sp->SetOkayToDiscard(false);
2217 
2218     // Why do we need to set the current thread by ID here???
2219     process->GetThreadList().SetSelectedThreadByID(GetID());
2220     error = process->Resume();
2221   } else {
2222     error.SetErrorString("process not stopped");
2223   }
2224   return error;
2225 }
2226 
2227 Status Thread::StepOut() {
2228   Status error;
2229   Process *process = GetProcess().get();
2230   if (StateIsStoppedState(process->GetState(), true)) {
2231     const bool first_instruction = false;
2232     const bool stop_other_threads = false;
2233     const bool abort_other_plans = false;
2234 
2235     ThreadPlanSP new_plan_sp(QueueThreadPlanForStepOut(
2236         abort_other_plans, nullptr, first_instruction, stop_other_threads,
2237         eVoteYes, eVoteNoOpinion, 0, error));
2238 
2239     new_plan_sp->SetIsMasterPlan(true);
2240     new_plan_sp->SetOkayToDiscard(false);
2241 
2242     // Why do we need to set the current thread by ID here???
2243     process->GetThreadList().SetSelectedThreadByID(GetID());
2244     error = process->Resume();
2245   } else {
2246     error.SetErrorString("process not stopped");
2247   }
2248   return error;
2249 }
2250 
2251 ValueObjectSP Thread::GetCurrentException() {
2252   if (auto frame_sp = GetStackFrameAtIndex(0))
2253     if (auto recognized_frame = frame_sp->GetRecognizedFrame())
2254       if (auto e = recognized_frame->GetExceptionObject())
2255         return e;
2256 
2257   // NOTE: Even though this behavior is generalized, only ObjC is actually
2258   // supported at the moment.
2259   for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
2260     if (auto e = runtime->GetExceptionObjectForThread(shared_from_this()))
2261       return e;
2262   }
2263 
2264   return ValueObjectSP();
2265 }
2266 
2267 ThreadSP Thread::GetCurrentExceptionBacktrace() {
2268   ValueObjectSP exception = GetCurrentException();
2269   if (!exception)
2270     return ThreadSP();
2271 
2272   // NOTE: Even though this behavior is generalized, only ObjC is actually
2273   // supported at the moment.
2274   for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
2275     if (auto bt = runtime->GetBacktraceThreadFromException(exception))
2276       return bt;
2277   }
2278 
2279   return ThreadSP();
2280 }
2281