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