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