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