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