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