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