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