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