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