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