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