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