1 //===-- Thread.cpp ----------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/lldb-python.h"
11 
12 #include "lldb/lldb-private-log.h"
13 #include "lldb/Breakpoint/BreakpointLocation.h"
14 #include "lldb/Core/Debugger.h"
15 #include "lldb/Core/Log.h"
16 #include "lldb/Core/State.h"
17 #include "lldb/Core/Stream.h"
18 #include "lldb/Core/StreamString.h"
19 #include "lldb/Core/RegularExpression.h"
20 #include "lldb/Host/Host.h"
21 #include "lldb/Symbol/Function.h"
22 #include "lldb/Target/DynamicLoader.h"
23 #include "lldb/Target/ExecutionContext.h"
24 #include "lldb/Target/ObjCLanguageRuntime.h"
25 #include "lldb/Target/Process.h"
26 #include "lldb/Target/RegisterContext.h"
27 #include "lldb/Target/StopInfo.h"
28 #include "lldb/Target/Target.h"
29 #include "lldb/Target/Thread.h"
30 #include "lldb/Target/ThreadPlan.h"
31 #include "lldb/Target/ThreadPlanCallFunction.h"
32 #include "lldb/Target/ThreadPlanBase.h"
33 #include "lldb/Target/ThreadPlanStepInstruction.h"
34 #include "lldb/Target/ThreadPlanStepOut.h"
35 #include "lldb/Target/ThreadPlanStepOverBreakpoint.h"
36 #include "lldb/Target/ThreadPlanStepThrough.h"
37 #include "lldb/Target/ThreadPlanStepInRange.h"
38 #include "lldb/Target/ThreadPlanStepOverRange.h"
39 #include "lldb/Target/ThreadPlanRunToAddress.h"
40 #include "lldb/Target/ThreadPlanStepUntil.h"
41 #include "lldb/Target/ThreadSpec.h"
42 #include "lldb/Target/Unwind.h"
43 #include "Plugins/Process/Utility/UnwindLLDB.h"
44 #include "UnwindMacOSXFrameBackchain.h"
45 
46 
47 using namespace lldb;
48 using namespace lldb_private;
49 
50 
51 const ThreadPropertiesSP &
52 Thread::GetGlobalProperties()
53 {
54     static ThreadPropertiesSP g_settings_sp;
55     if (!g_settings_sp)
56         g_settings_sp.reset (new ThreadProperties (true));
57     return g_settings_sp;
58 }
59 
60 static PropertyDefinition
61 g_properties[] =
62 {
63     { "step-avoid-regexp",  OptionValue::eTypeRegex  , true , REG_EXTENDED, "^std::", NULL, "A regular expression defining functions step-in won't stop in." },
64     { "trace-thread",       OptionValue::eTypeBoolean, false, false, NULL, NULL, "If true, this thread will single-step and log execution." },
65     {  NULL               , OptionValue::eTypeInvalid, false, 0    , NULL, NULL, NULL  }
66 };
67 
68 enum {
69     ePropertyStepAvoidRegex,
70     ePropertyEnableThreadTrace
71 };
72 
73 
74 class ThreadOptionValueProperties : public OptionValueProperties
75 {
76 public:
77     ThreadOptionValueProperties (const ConstString &name) :
78         OptionValueProperties (name)
79     {
80     }
81 
82     // This constructor is used when creating ThreadOptionValueProperties when it
83     // is part of a new lldb_private::Thread instance. It will copy all current
84     // global property values as needed
85     ThreadOptionValueProperties (ThreadProperties *global_properties) :
86         OptionValueProperties(*global_properties->GetValueProperties())
87     {
88     }
89 
90     virtual const Property *
91     GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
92     {
93         // When gettings the value for a key from the thread options, we will always
94         // try and grab the setting from the current thread if there is one. Else we just
95         // use the one from this instance.
96         if (exe_ctx)
97         {
98             Thread *thread = exe_ctx->GetThreadPtr();
99             if (thread)
100             {
101                 ThreadOptionValueProperties *instance_properties = static_cast<ThreadOptionValueProperties *>(thread->GetValueProperties().get());
102                 if (this != instance_properties)
103                     return instance_properties->ProtectedGetPropertyAtIndex (idx);
104             }
105         }
106         return ProtectedGetPropertyAtIndex (idx);
107     }
108 };
109 
110 
111 
112 ThreadProperties::ThreadProperties (bool is_global) :
113     Properties ()
114 {
115     if (is_global)
116     {
117         m_collection_sp.reset (new ThreadOptionValueProperties(ConstString("thread")));
118         m_collection_sp->Initialize(g_properties);
119     }
120     else
121         m_collection_sp.reset (new ThreadOptionValueProperties(Thread::GetGlobalProperties().get()));
122 }
123 
124 ThreadProperties::~ThreadProperties()
125 {
126 }
127 
128 const RegularExpression *
129 ThreadProperties::GetSymbolsToAvoidRegexp()
130 {
131     const uint32_t idx = ePropertyStepAvoidRegex;
132     return m_collection_sp->GetPropertyAtIndexAsOptionValueRegex (NULL, idx);
133 }
134 
135 bool
136 ThreadProperties::GetTraceEnabledState() const
137 {
138     const uint32_t idx = ePropertyEnableThreadTrace;
139     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
140 }
141 
142 //------------------------------------------------------------------
143 // Thread Event Data
144 //------------------------------------------------------------------
145 
146 
147 const ConstString &
148 Thread::ThreadEventData::GetFlavorString ()
149 {
150     static ConstString g_flavor ("Thread::ThreadEventData");
151     return g_flavor;
152 }
153 
154 Thread::ThreadEventData::ThreadEventData (const lldb::ThreadSP thread_sp) :
155     m_thread_sp (thread_sp),
156     m_stack_id ()
157 {
158 }
159 
160 Thread::ThreadEventData::ThreadEventData (const lldb::ThreadSP thread_sp, const StackID &stack_id) :
161     m_thread_sp (thread_sp),
162     m_stack_id (stack_id)
163 {
164 }
165 
166 Thread::ThreadEventData::ThreadEventData () :
167     m_thread_sp (),
168     m_stack_id ()
169 {
170 }
171 
172 Thread::ThreadEventData::~ThreadEventData ()
173 {
174 }
175 
176 void
177 Thread::ThreadEventData::Dump (Stream *s) const
178 {
179 
180 }
181 
182 const Thread::ThreadEventData *
183 Thread::ThreadEventData::GetEventDataFromEvent (const Event *event_ptr)
184 {
185     if (event_ptr)
186     {
187         const EventData *event_data = event_ptr->GetData();
188         if (event_data && event_data->GetFlavor() == ThreadEventData::GetFlavorString())
189             return static_cast <const ThreadEventData *> (event_ptr->GetData());
190     }
191     return NULL;
192 }
193 
194 ThreadSP
195 Thread::ThreadEventData::GetThreadFromEvent (const Event *event_ptr)
196 {
197     ThreadSP thread_sp;
198     const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
199     if (event_data)
200         thread_sp = event_data->GetThread();
201     return thread_sp;
202 }
203 
204 StackID
205 Thread::ThreadEventData::GetStackIDFromEvent (const Event *event_ptr)
206 {
207     StackID stack_id;
208     const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
209     if (event_data)
210         stack_id = event_data->GetStackID();
211     return stack_id;
212 }
213 
214 StackFrameSP
215 Thread::ThreadEventData::GetStackFrameFromEvent (const Event *event_ptr)
216 {
217     const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
218     StackFrameSP frame_sp;
219     if (event_data)
220     {
221         ThreadSP thread_sp = event_data->GetThread();
222         if (thread_sp)
223         {
224             frame_sp = thread_sp->GetStackFrameList()->GetFrameWithStackID (event_data->GetStackID());
225         }
226     }
227     return frame_sp;
228 }
229 
230 //------------------------------------------------------------------
231 // Thread class
232 //------------------------------------------------------------------
233 
234 ConstString &
235 Thread::GetStaticBroadcasterClass ()
236 {
237     static ConstString class_name ("lldb.thread");
238     return class_name;
239 }
240 
241 Thread::Thread (Process &process, lldb::tid_t tid) :
242     ThreadProperties (false),
243     UserID (tid),
244     Broadcaster(&process.GetTarget().GetDebugger(), Thread::GetStaticBroadcasterClass().AsCString()),
245     m_process_wp (process.shared_from_this()),
246     m_stop_info_sp (),
247     m_stop_info_stop_id (0),
248     m_index_id (process.GetNextThreadIndexID(tid)),
249     m_reg_context_sp (),
250     m_state (eStateUnloaded),
251     m_state_mutex (Mutex::eMutexTypeRecursive),
252     m_plan_stack (),
253     m_completed_plan_stack(),
254     m_frame_mutex (Mutex::eMutexTypeRecursive),
255     m_curr_frames_sp (),
256     m_prev_frames_sp (),
257     m_resume_signal (LLDB_INVALID_SIGNAL_NUMBER),
258     m_resume_state (eStateRunning),
259     m_temporary_resume_state (eStateRunning),
260     m_unwinder_ap (),
261     m_destroy_called (false),
262     m_override_should_notify (eLazyBoolCalculate)
263 {
264     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
265     if (log)
266         log->Printf ("%p Thread::Thread(tid = 0x%4.4" PRIx64 ")", this, GetID());
267 
268     CheckInWithManager();
269     QueueFundamentalPlan(true);
270 }
271 
272 
273 Thread::~Thread()
274 {
275     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
276     if (log)
277         log->Printf ("%p Thread::~Thread(tid = 0x%4.4" PRIx64 ")", this, GetID());
278     /// If you hit this assert, it means your derived class forgot to call DoDestroy in its destructor.
279     assert (m_destroy_called);
280 }
281 
282 void
283 Thread::DestroyThread ()
284 {
285     // Tell any plans on the plan stack that the thread is being destroyed since
286     // any active plans that have a thread go away in the middle of might need
287     // to do cleanup.
288     for (auto plan : m_plan_stack)
289         plan->ThreadDestroyed();
290 
291     m_destroy_called = true;
292     m_plan_stack.clear();
293     m_discarded_plan_stack.clear();
294     m_completed_plan_stack.clear();
295     m_stop_info_sp.reset();
296     m_reg_context_sp.reset();
297     m_unwinder_ap.reset();
298     Mutex::Locker locker(m_frame_mutex);
299     m_curr_frames_sp.reset();
300     m_prev_frames_sp.reset();
301 }
302 
303 void
304 Thread::BroadcastSelectedFrameChange(StackID &new_frame_id)
305 {
306     if (EventTypeHasListeners(eBroadcastBitSelectedFrameChanged))
307         BroadcastEvent(eBroadcastBitSelectedFrameChanged, new ThreadEventData (this->shared_from_this(), new_frame_id));
308 }
309 
310 uint32_t
311 Thread::SetSelectedFrame (lldb_private::StackFrame *frame, bool broadcast)
312 {
313     uint32_t ret_value = GetStackFrameList()->SetSelectedFrame(frame);
314     if (broadcast)
315         BroadcastSelectedFrameChange(frame->GetStackID());
316     return ret_value;
317 }
318 
319 bool
320 Thread::SetSelectedFrameByIndex (uint32_t frame_idx, bool broadcast)
321 {
322     StackFrameSP frame_sp(GetStackFrameList()->GetFrameAtIndex (frame_idx));
323     if (frame_sp)
324     {
325         GetStackFrameList()->SetSelectedFrame(frame_sp.get());
326         if (broadcast)
327             BroadcastSelectedFrameChange(frame_sp->GetStackID());
328         return true;
329     }
330     else
331         return false;
332 }
333 
334 bool
335 Thread::SetSelectedFrameByIndexNoisily (uint32_t frame_idx, Stream &output_stream)
336 {
337     const bool broadcast = true;
338     bool success = SetSelectedFrameByIndex (frame_idx, broadcast);
339     if (success)
340     {
341         StackFrameSP frame_sp = GetSelectedFrame();
342         if (frame_sp)
343         {
344             bool already_shown = false;
345             SymbolContext frame_sc(frame_sp->GetSymbolContext(eSymbolContextLineEntry));
346             if (GetProcess()->GetTarget().GetDebugger().GetUseExternalEditor() && frame_sc.line_entry.file && frame_sc.line_entry.line != 0)
347             {
348                 already_shown = Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line);
349             }
350 
351             bool show_frame_info = true;
352             bool show_source = !already_shown;
353             return frame_sp->GetStatus (output_stream, show_frame_info, show_source);
354         }
355         return false;
356     }
357     else
358         return false;
359 }
360 
361 
362 lldb::StopInfoSP
363 Thread::GetStopInfo ()
364 {
365     ThreadPlanSP plan_sp (GetCompletedPlan());
366     ProcessSP process_sp (GetProcess());
367     const uint32_t stop_id = process_sp ? process_sp->GetStopID() : UINT32_MAX;
368     if (plan_sp && plan_sp->PlanSucceeded())
369     {
370         return StopInfo::CreateStopReasonWithPlan (plan_sp, GetReturnValueObject());
371     }
372     else
373     {
374         if ((m_stop_info_stop_id == stop_id) ||   // Stop info is valid, just return what we have (even if empty)
375             (m_stop_info_sp && m_stop_info_sp->IsValid()))  // Stop info is valid, just return what we have
376         {
377             return m_stop_info_sp;
378         }
379         else
380         {
381             GetPrivateStopInfo ();
382             return m_stop_info_sp;
383         }
384     }
385 }
386 
387 lldb::StopInfoSP
388 Thread::GetPrivateStopInfo ()
389 {
390     ProcessSP process_sp (GetProcess());
391     if (process_sp)
392     {
393         ProcessSP process_sp (GetProcess());
394         if (process_sp)
395         {
396             const uint32_t process_stop_id = process_sp->GetStopID();
397             if (m_stop_info_stop_id != process_stop_id)
398             {
399                 if (m_stop_info_sp)
400                 {
401                     if (m_stop_info_sp->IsValid())
402                     {
403                         SetStopInfo (m_stop_info_sp);
404                     }
405                     else
406                     {
407                         if (IsStillAtLastBreakpointHit())
408                             SetStopInfo(m_stop_info_sp);
409                         else
410                             m_stop_info_sp.reset();
411                     }
412                 }
413 
414                 if (!m_stop_info_sp)
415                 {
416                     if (CalculateStopInfo() == false)
417                         SetStopInfo (StopInfoSP());
418                 }
419             }
420         }
421     }
422     return m_stop_info_sp;
423 }
424 
425 
426 lldb::StopReason
427 Thread::GetStopReason()
428 {
429     lldb::StopInfoSP stop_info_sp (GetStopInfo ());
430     if (stop_info_sp)
431         return stop_info_sp->GetStopReason();
432     return eStopReasonNone;
433 }
434 
435 
436 
437 void
438 Thread::SetStopInfo (const lldb::StopInfoSP &stop_info_sp)
439 {
440     m_stop_info_sp = stop_info_sp;
441     if (m_stop_info_sp)
442     {
443         m_stop_info_sp->MakeStopInfoValid();
444         // If we are overriding the ShouldReportStop, do that here:
445         if (m_override_should_notify != eLazyBoolCalculate)
446             m_stop_info_sp->OverrideShouldNotify (m_override_should_notify == eLazyBoolYes);
447     }
448 
449     ProcessSP process_sp (GetProcess());
450     if (process_sp)
451         m_stop_info_stop_id = process_sp->GetStopID();
452     else
453         m_stop_info_stop_id = UINT32_MAX;
454 }
455 
456 void
457 Thread::SetShouldReportStop (Vote vote)
458 {
459     if (vote == eVoteNoOpinion)
460         return;
461     else
462     {
463         m_override_should_notify = (vote == eVoteYes ? eLazyBoolYes : eLazyBoolNo);
464         if (m_stop_info_sp)
465             m_stop_info_sp->OverrideShouldNotify (m_override_should_notify == eLazyBoolYes);
466     }
467 }
468 
469 void
470 Thread::SetStopInfoToNothing()
471 {
472     // Note, we can't just NULL out the private reason, or the native thread implementation will try to
473     // go calculate it again.  For now, just set it to a Unix Signal with an invalid signal number.
474     SetStopInfo (StopInfo::CreateStopReasonWithSignal (*this,  LLDB_INVALID_SIGNAL_NUMBER));
475 }
476 
477 bool
478 Thread::ThreadStoppedForAReason (void)
479 {
480     return (bool) GetPrivateStopInfo ();
481 }
482 
483 bool
484 Thread::CheckpointThreadState (ThreadStateCheckpoint &saved_state)
485 {
486     if (!SaveFrameZeroState(saved_state.register_backup))
487         return false;
488 
489     saved_state.stop_info_sp = GetStopInfo();
490     ProcessSP process_sp (GetProcess());
491     if (process_sp)
492         saved_state.orig_stop_id = process_sp->GetStopID();
493     saved_state.current_inlined_depth = GetCurrentInlinedDepth();
494 
495     return true;
496 }
497 
498 bool
499 Thread::RestoreRegisterStateFromCheckpoint (ThreadStateCheckpoint &saved_state)
500 {
501     RestoreSaveFrameZero(saved_state.register_backup);
502     return true;
503 }
504 
505 bool
506 Thread::RestoreThreadStateFromCheckpoint (ThreadStateCheckpoint &saved_state)
507 {
508     if (saved_state.stop_info_sp)
509         saved_state.stop_info_sp->MakeStopInfoValid();
510     SetStopInfo(saved_state.stop_info_sp);
511     GetStackFrameList()->SetCurrentInlinedDepth (saved_state.current_inlined_depth);
512     return true;
513 }
514 
515 StateType
516 Thread::GetState() const
517 {
518     // If any other threads access this we will need a mutex for it
519     Mutex::Locker locker(m_state_mutex);
520     return m_state;
521 }
522 
523 void
524 Thread::SetState(StateType state)
525 {
526     Mutex::Locker locker(m_state_mutex);
527     m_state = state;
528 }
529 
530 void
531 Thread::WillStop()
532 {
533     ThreadPlan *current_plan = GetCurrentPlan();
534 
535     // FIXME: I may decide to disallow threads with no plans.  In which
536     // case this should go to an assert.
537 
538     if (!current_plan)
539         return;
540 
541     current_plan->WillStop();
542 }
543 
544 void
545 Thread::SetupForResume ()
546 {
547     if (GetResumeState() != eStateSuspended)
548     {
549 
550         // If we're at a breakpoint push the step-over breakpoint plan.  Do this before
551         // telling the current plan it will resume, since we might change what the current
552         // plan is.
553 
554 //      StopReason stop_reason = lldb::eStopReasonInvalid;
555 //      StopInfoSP stop_info_sp = GetStopInfo();
556 //      if (stop_info_sp.get())
557 //          stop_reason = stop_info_sp->GetStopReason();
558 //      if (stop_reason == lldb::eStopReasonBreakpoint)
559         lldb::RegisterContextSP reg_ctx_sp (GetRegisterContext());
560         if (reg_ctx_sp)
561         {
562             BreakpointSiteSP bp_site_sp = GetProcess()->GetBreakpointSiteList().FindByAddress(reg_ctx_sp->GetPC());
563             if (bp_site_sp)
564             {
565                 // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the target may not require anything
566                 // special to step over a breakpoint.
567 
568                 ThreadPlan *cur_plan = GetCurrentPlan();
569 
570                 if (cur_plan->GetKind() != ThreadPlan::eKindStepOverBreakpoint)
571                 {
572                     ThreadPlanStepOverBreakpoint *step_bp_plan = new ThreadPlanStepOverBreakpoint (*this);
573                     if (step_bp_plan)
574                     {
575                         ThreadPlanSP step_bp_plan_sp;
576                         step_bp_plan->SetPrivate (true);
577 
578                         if (GetCurrentPlan()->RunState() != eStateStepping)
579                         {
580                             step_bp_plan->SetAutoContinue(true);
581                         }
582                         step_bp_plan_sp.reset (step_bp_plan);
583                         QueueThreadPlan (step_bp_plan_sp, false);
584                     }
585                 }
586             }
587         }
588     }
589 }
590 
591 bool
592 Thread::ShouldResume (StateType resume_state)
593 {
594     // At this point clear the completed plan stack.
595     m_completed_plan_stack.clear();
596     m_discarded_plan_stack.clear();
597     m_override_should_notify = eLazyBoolCalculate;
598 
599     m_temporary_resume_state = resume_state;
600 
601     lldb::ThreadSP backing_thread_sp (GetBackingThread ());
602     if (backing_thread_sp)
603         backing_thread_sp->m_temporary_resume_state = resume_state;
604 
605     // Make sure m_stop_info_sp is valid
606     GetPrivateStopInfo();
607 
608     // This is a little dubious, but we are trying to limit how often we actually fetch stop info from
609     // the target, 'cause that slows down single stepping.  So assume that if we got to the point where
610     // we're about to resume, and we haven't yet had to fetch the stop reason, then it doesn't need to know
611     // about the fact that we are resuming...
612         const uint32_t process_stop_id = GetProcess()->GetStopID();
613     if (m_stop_info_stop_id == process_stop_id &&
614         (m_stop_info_sp && m_stop_info_sp->IsValid()))
615     {
616         StopInfo *stop_info = GetPrivateStopInfo().get();
617         if (stop_info)
618             stop_info->WillResume (resume_state);
619     }
620 
621     // Tell all the plans that we are about to resume in case they need to clear any state.
622     // We distinguish between the plan on the top of the stack and the lower
623     // plans in case a plan needs to do any special business before it runs.
624 
625     bool need_to_resume = false;
626     ThreadPlan *plan_ptr = GetCurrentPlan();
627     if (plan_ptr)
628     {
629         need_to_resume = plan_ptr->WillResume(resume_state, true);
630 
631         while ((plan_ptr = GetPreviousPlan(plan_ptr)) != NULL)
632         {
633             plan_ptr->WillResume (resume_state, false);
634         }
635 
636         // If the WillResume for the plan says we are faking a resume, then it will have set an appropriate stop info.
637         // In that case, don't reset it here.
638 
639         if (need_to_resume && resume_state != eStateSuspended)
640         {
641             m_stop_info_sp.reset();
642         }
643     }
644 
645     if (need_to_resume)
646     {
647         ClearStackFrames();
648         // Let Thread subclasses do any special work they need to prior to resuming
649         WillResume (resume_state);
650     }
651 
652     return need_to_resume;
653 }
654 
655 void
656 Thread::DidResume ()
657 {
658     SetResumeSignal (LLDB_INVALID_SIGNAL_NUMBER);
659 }
660 
661 void
662 Thread::DidStop ()
663 {
664     SetState (eStateStopped);
665 }
666 
667 bool
668 Thread::ShouldStop (Event* event_ptr)
669 {
670     ThreadPlan *current_plan = GetCurrentPlan();
671 
672     bool should_stop = true;
673 
674     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
675 
676     if (GetResumeState () == eStateSuspended)
677     {
678         if (log)
679             log->Printf ("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", should_stop = 0 (ignore since thread was suspended)",
680                          __FUNCTION__,
681                          GetID (),
682                          GetProtocolID());
683         return false;
684     }
685 
686     if (GetTemporaryResumeState () == eStateSuspended)
687     {
688         if (log)
689             log->Printf ("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", should_stop = 0 (ignore since thread was suspended)",
690                          __FUNCTION__,
691                          GetID (),
692                          GetProtocolID());
693         return false;
694     }
695 
696     if (ThreadStoppedForAReason() == false)
697     {
698         if (log)
699             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)",
700                          __FUNCTION__,
701                          GetID (),
702                          GetProtocolID(),
703                          GetRegisterContext() ? GetRegisterContext()->GetPC() : LLDB_INVALID_ADDRESS);
704         return false;
705     }
706 
707     if (log)
708     {
709         log->Printf ("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", pc = 0x%16.16" PRIx64,
710                      __FUNCTION__,
711                      GetID (),
712                      GetProtocolID (),
713                      GetRegisterContext() ? GetRegisterContext()->GetPC() : LLDB_INVALID_ADDRESS);
714         log->Printf ("^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^");
715         StreamString s;
716         s.IndentMore();
717         DumpThreadPlans(&s);
718         log->Printf ("Plan stack initial state:\n%s", s.GetData());
719     }
720 
721     // The top most plan always gets to do the trace log...
722     current_plan->DoTraceLog ();
723 
724     // First query the stop info's ShouldStopSynchronous.  This handles "synchronous" stop reasons, for example the breakpoint
725     // command on internal breakpoints.  If a synchronous stop reason says we should not stop, then we don't have to
726     // do any more work on this stop.
727     StopInfoSP private_stop_info (GetPrivateStopInfo());
728     if (private_stop_info && private_stop_info->ShouldStopSynchronous(event_ptr) == false)
729     {
730         if (log)
731             log->Printf ("StopInfo::ShouldStop async callback says we should not stop, returning ShouldStop of false.");
732         return false;
733     }
734 
735     // If we've already been restarted, don't query the plans since the state they would examine is not current.
736     if (Process::ProcessEventData::GetRestartedFromEvent(event_ptr))
737         return false;
738 
739     // Before the plans see the state of the world, calculate the current inlined depth.
740     GetStackFrameList()->CalculateCurrentInlinedDepth();
741 
742     // If the base plan doesn't understand why we stopped, then we have to find a plan that does.
743     // If that plan is still working, then we don't need to do any more work.  If the plan that explains
744     // the stop is done, then we should pop all the plans below it, and pop it, and then let the plans above it decide
745     // whether they still need to do more work.
746 
747     bool done_processing_current_plan = false;
748 
749     if (!current_plan->PlanExplainsStop(event_ptr))
750     {
751         if (current_plan->TracerExplainsStop())
752         {
753             done_processing_current_plan = true;
754             should_stop = false;
755         }
756         else
757         {
758             // If the current plan doesn't explain the stop, then find one that
759             // does and let it handle the situation.
760             ThreadPlan *plan_ptr = current_plan;
761             while ((plan_ptr = GetPreviousPlan(plan_ptr)) != NULL)
762             {
763                 if (plan_ptr->PlanExplainsStop(event_ptr))
764                 {
765                     should_stop = plan_ptr->ShouldStop (event_ptr);
766 
767                     // plan_ptr explains the stop, next check whether plan_ptr is done, if so, then we should take it
768                     // and all the plans below it off the stack.
769 
770                     if (plan_ptr->MischiefManaged())
771                     {
772                         // We're going to pop the plans up to and including the plan that explains the stop.
773                         ThreadPlan *prev_plan_ptr = GetPreviousPlan (plan_ptr);
774 
775                         do
776                         {
777                             if (should_stop)
778                                 current_plan->WillStop();
779                             PopPlan();
780                         }
781                         while ((current_plan = GetCurrentPlan()) != prev_plan_ptr);
782                         // Now, if the responsible plan was not "Okay to discard" then we're done,
783                         // otherwise we forward this to the next plan in the stack below.
784                         if (plan_ptr->IsMasterPlan() && !plan_ptr->OkayToDiscard())
785                             done_processing_current_plan = true;
786                         else
787                             done_processing_current_plan = false;
788                     }
789                     else
790                         done_processing_current_plan = true;
791 
792                     break;
793                 }
794 
795             }
796         }
797     }
798 
799     if (!done_processing_current_plan)
800     {
801         bool over_ride_stop = current_plan->ShouldAutoContinue(event_ptr);
802 
803         if (log)
804             log->Printf("Plan %s explains stop, auto-continue %i.", current_plan->GetName(), over_ride_stop);
805 
806         // We're starting from the base plan, so just let it decide;
807         if (PlanIsBasePlan(current_plan))
808         {
809             should_stop = current_plan->ShouldStop (event_ptr);
810             if (log)
811                 log->Printf("Base plan says should stop: %i.", should_stop);
812         }
813         else
814         {
815             // Otherwise, don't let the base plan override what the other plans say to do, since
816             // presumably if there were other plans they would know what to do...
817             while (1)
818             {
819                 if (PlanIsBasePlan(current_plan))
820                     break;
821 
822                 should_stop = current_plan->ShouldStop(event_ptr);
823                 if (log)
824                     log->Printf("Plan %s should stop: %d.", current_plan->GetName(), should_stop);
825                 if (current_plan->MischiefManaged())
826                 {
827                     if (should_stop)
828                         current_plan->WillStop();
829 
830                     // If a Master Plan wants to stop, and wants to stick on the stack, we let it.
831                     // Otherwise, see if the plan's parent wants to stop.
832 
833                     if (should_stop && current_plan->IsMasterPlan() && !current_plan->OkayToDiscard())
834                     {
835                         PopPlan();
836                         break;
837                     }
838                     else
839                     {
840 
841                         PopPlan();
842 
843                         current_plan = GetCurrentPlan();
844                         if (current_plan == NULL)
845                         {
846                             break;
847                         }
848                     }
849                 }
850                 else
851                 {
852                     break;
853                 }
854             }
855         }
856 
857         if (over_ride_stop)
858             should_stop = false;
859 
860         // One other potential problem is that we set up a master plan, then stop in before it is complete - for instance
861         // by hitting a breakpoint during a step-over - then do some step/finish/etc operations that wind up
862         // past the end point condition of the initial plan.  We don't want to strand the original plan on the stack,
863         // This code clears stale plans off the stack.
864 
865         if (should_stop)
866         {
867             ThreadPlan *plan_ptr = GetCurrentPlan();
868             while (!PlanIsBasePlan(plan_ptr))
869             {
870                 bool stale = plan_ptr->IsPlanStale ();
871                 ThreadPlan *examined_plan = plan_ptr;
872                 plan_ptr = GetPreviousPlan (examined_plan);
873 
874                 if (stale)
875                 {
876                     if (log)
877                         log->Printf("Plan %s being discarded in cleanup, it says it is already done.", examined_plan->GetName());
878                     DiscardThreadPlansUpToPlan(examined_plan);
879                 }
880             }
881         }
882 
883     }
884 
885     if (log)
886     {
887         StreamString s;
888         s.IndentMore();
889         DumpThreadPlans(&s);
890         log->Printf ("Plan stack final state:\n%s", s.GetData());
891         log->Printf ("vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv", should_stop);
892     }
893     return should_stop;
894 }
895 
896 Vote
897 Thread::ShouldReportStop (Event* event_ptr)
898 {
899     StateType thread_state = GetResumeState ();
900     StateType temp_thread_state = GetTemporaryResumeState();
901 
902     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
903 
904     if (thread_state == eStateSuspended || thread_state == eStateInvalid)
905     {
906         if (log)
907             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (state was suspended or invalid)", GetID(), eVoteNoOpinion);
908         return eVoteNoOpinion;
909     }
910 
911     if (temp_thread_state == eStateSuspended || temp_thread_state == eStateInvalid)
912     {
913         if (log)
914             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (temporary state was suspended or invalid)", GetID(), eVoteNoOpinion);
915         return eVoteNoOpinion;
916     }
917 
918     if (!ThreadStoppedForAReason())
919     {
920         if (log)
921             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (thread didn't stop for a reason.)", GetID(), eVoteNoOpinion);
922         return eVoteNoOpinion;
923     }
924 
925     if (m_completed_plan_stack.size() > 0)
926     {
927         // Don't use GetCompletedPlan here, since that suppresses private plans.
928         if (log)
929             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote  for complete stack's back plan", GetID());
930         return m_completed_plan_stack.back()->ShouldReportStop (event_ptr);
931     }
932     else
933     {
934         Vote thread_vote = eVoteNoOpinion;
935         ThreadPlan *plan_ptr = GetCurrentPlan();
936         while (1)
937         {
938             if (plan_ptr->PlanExplainsStop(event_ptr))
939             {
940                 thread_vote = plan_ptr->ShouldReportStop(event_ptr);
941                 break;
942             }
943             if (PlanIsBasePlan(plan_ptr))
944                 break;
945             else
946                 plan_ptr = GetPreviousPlan(plan_ptr);
947         }
948         if (log)
949             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i for current plan", GetID(), thread_vote);
950 
951         return thread_vote;
952     }
953 }
954 
955 Vote
956 Thread::ShouldReportRun (Event* event_ptr)
957 {
958     StateType thread_state = GetResumeState ();
959 
960     if (thread_state == eStateSuspended
961             || thread_state == eStateInvalid)
962     {
963         return eVoteNoOpinion;
964     }
965 
966     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
967     if (m_completed_plan_stack.size() > 0)
968     {
969         // Don't use GetCompletedPlan here, since that suppresses private plans.
970         if (log)
971             log->Printf ("Current Plan for thread %d (0x%4.4" PRIx64 ", %s): %s being asked whether we should report run.",
972                          GetIndexID(),
973                          GetID(),
974                          StateAsCString(GetTemporaryResumeState()),
975                          m_completed_plan_stack.back()->GetName());
976 
977         return m_completed_plan_stack.back()->ShouldReportRun (event_ptr);
978     }
979     else
980     {
981         if (log)
982             log->Printf ("Current Plan for thread %d (0x%4.4" PRIx64 ", %s): %s being asked whether we should report run.",
983                          GetIndexID(),
984                          GetID(),
985                          StateAsCString(GetTemporaryResumeState()),
986                          GetCurrentPlan()->GetName());
987 
988         return GetCurrentPlan()->ShouldReportRun (event_ptr);
989      }
990 }
991 
992 bool
993 Thread::MatchesSpec (const ThreadSpec *spec)
994 {
995     if (spec == NULL)
996         return true;
997 
998     return spec->ThreadPassesBasicTests(*this);
999 }
1000 
1001 void
1002 Thread::PushPlan (ThreadPlanSP &thread_plan_sp)
1003 {
1004     if (thread_plan_sp)
1005     {
1006         // If the thread plan doesn't already have a tracer, give it its parent's tracer:
1007         if (!thread_plan_sp->GetThreadPlanTracer())
1008             thread_plan_sp->SetThreadPlanTracer(m_plan_stack.back()->GetThreadPlanTracer());
1009         m_plan_stack.push_back (thread_plan_sp);
1010 
1011         thread_plan_sp->DidPush();
1012 
1013         Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1014         if (log)
1015         {
1016             StreamString s;
1017             thread_plan_sp->GetDescription (&s, lldb::eDescriptionLevelFull);
1018             log->Printf("Pushing plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1019                         s.GetData(),
1020                         thread_plan_sp->GetThread().GetID());
1021         }
1022     }
1023 }
1024 
1025 void
1026 Thread::PopPlan ()
1027 {
1028     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1029 
1030     if (m_plan_stack.size() <= 1)
1031         return;
1032     else
1033     {
1034         ThreadPlanSP &plan = m_plan_stack.back();
1035         if (log)
1036         {
1037             log->Printf("Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".", plan->GetName(), plan->GetThread().GetID());
1038         }
1039         m_completed_plan_stack.push_back (plan);
1040         plan->WillPop();
1041         m_plan_stack.pop_back();
1042     }
1043 }
1044 
1045 void
1046 Thread::DiscardPlan ()
1047 {
1048     if (m_plan_stack.size() > 1)
1049     {
1050         ThreadPlanSP &plan = m_plan_stack.back();
1051         m_discarded_plan_stack.push_back (plan);
1052         plan->WillPop();
1053         m_plan_stack.pop_back();
1054     }
1055 }
1056 
1057 ThreadPlan *
1058 Thread::GetCurrentPlan ()
1059 {
1060     // There will always be at least the base plan.  If somebody is mucking with a
1061     // thread with an empty plan stack, we should assert right away.
1062     if (m_plan_stack.empty())
1063         return NULL;
1064     return m_plan_stack.back().get();
1065 }
1066 
1067 ThreadPlanSP
1068 Thread::GetCompletedPlan ()
1069 {
1070     ThreadPlanSP empty_plan_sp;
1071     if (!m_completed_plan_stack.empty())
1072     {
1073         for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1074         {
1075             ThreadPlanSP completed_plan_sp;
1076             completed_plan_sp = m_completed_plan_stack[i];
1077             if (!completed_plan_sp->GetPrivate ())
1078             return completed_plan_sp;
1079         }
1080     }
1081     return empty_plan_sp;
1082 }
1083 
1084 ValueObjectSP
1085 Thread::GetReturnValueObject ()
1086 {
1087     if (!m_completed_plan_stack.empty())
1088     {
1089         for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1090         {
1091             ValueObjectSP return_valobj_sp;
1092             return_valobj_sp = m_completed_plan_stack[i]->GetReturnValueObject();
1093             if (return_valobj_sp)
1094             return return_valobj_sp;
1095         }
1096     }
1097     return ValueObjectSP();
1098 }
1099 
1100 bool
1101 Thread::IsThreadPlanDone (ThreadPlan *plan)
1102 {
1103     if (!m_completed_plan_stack.empty())
1104     {
1105         for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1106         {
1107             if (m_completed_plan_stack[i].get() == plan)
1108                 return true;
1109         }
1110     }
1111     return false;
1112 }
1113 
1114 bool
1115 Thread::WasThreadPlanDiscarded (ThreadPlan *plan)
1116 {
1117     if (!m_discarded_plan_stack.empty())
1118     {
1119         for (int i = m_discarded_plan_stack.size() - 1; i >= 0; i--)
1120         {
1121             if (m_discarded_plan_stack[i].get() == plan)
1122                 return true;
1123         }
1124     }
1125     return false;
1126 }
1127 
1128 ThreadPlan *
1129 Thread::GetPreviousPlan (ThreadPlan *current_plan)
1130 {
1131     if (current_plan == NULL)
1132         return NULL;
1133 
1134     int stack_size = m_completed_plan_stack.size();
1135     for (int i = stack_size - 1; i > 0; i--)
1136     {
1137         if (current_plan == m_completed_plan_stack[i].get())
1138             return m_completed_plan_stack[i-1].get();
1139     }
1140 
1141     if (stack_size > 0 && m_completed_plan_stack[0].get() == current_plan)
1142     {
1143         if (m_plan_stack.size() > 0)
1144             return m_plan_stack.back().get();
1145         else
1146             return NULL;
1147     }
1148 
1149     stack_size = m_plan_stack.size();
1150     for (int i = stack_size - 1; i > 0; i--)
1151     {
1152         if (current_plan == m_plan_stack[i].get())
1153             return m_plan_stack[i-1].get();
1154     }
1155     return NULL;
1156 }
1157 
1158 void
1159 Thread::QueueThreadPlan (ThreadPlanSP &thread_plan_sp, bool abort_other_plans)
1160 {
1161     if (abort_other_plans)
1162        DiscardThreadPlans(true);
1163 
1164     PushPlan (thread_plan_sp);
1165 }
1166 
1167 
1168 void
1169 Thread::EnableTracer (bool value, bool single_stepping)
1170 {
1171     int stack_size = m_plan_stack.size();
1172     for (int i = 0; i < stack_size; i++)
1173     {
1174         if (m_plan_stack[i]->GetThreadPlanTracer())
1175         {
1176             m_plan_stack[i]->GetThreadPlanTracer()->EnableTracing(value);
1177             m_plan_stack[i]->GetThreadPlanTracer()->EnableSingleStep(single_stepping);
1178         }
1179     }
1180 }
1181 
1182 void
1183 Thread::SetTracer (lldb::ThreadPlanTracerSP &tracer_sp)
1184 {
1185     int stack_size = m_plan_stack.size();
1186     for (int i = 0; i < stack_size; i++)
1187         m_plan_stack[i]->SetThreadPlanTracer(tracer_sp);
1188 }
1189 
1190 void
1191 Thread::DiscardThreadPlansUpToPlan (lldb::ThreadPlanSP &up_to_plan_sp)
1192 {
1193     DiscardThreadPlansUpToPlan (up_to_plan_sp.get());
1194 }
1195 
1196 void
1197 Thread::DiscardThreadPlansUpToPlan (ThreadPlan *up_to_plan_ptr)
1198 {
1199     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1200     if (log)
1201     {
1202         log->Printf("Discarding thread plans for thread tid = 0x%4.4" PRIx64 ", up to %p", GetID(), up_to_plan_ptr);
1203     }
1204 
1205     int stack_size = m_plan_stack.size();
1206 
1207     // If the input plan is NULL, discard all plans.  Otherwise make sure this plan is in the
1208     // stack, and if so discard up to and including it.
1209 
1210     if (up_to_plan_ptr == NULL)
1211     {
1212         for (int i = stack_size - 1; i > 0; i--)
1213             DiscardPlan();
1214     }
1215     else
1216     {
1217         bool found_it = false;
1218         for (int i = stack_size - 1; i > 0; i--)
1219         {
1220             if (m_plan_stack[i].get() == up_to_plan_ptr)
1221                 found_it = true;
1222         }
1223         if (found_it)
1224         {
1225             bool last_one = false;
1226             for (int i = stack_size - 1; i > 0 && !last_one ; i--)
1227             {
1228                 if (GetCurrentPlan() == up_to_plan_ptr)
1229                     last_one = true;
1230                 DiscardPlan();
1231             }
1232         }
1233     }
1234     return;
1235 }
1236 
1237 void
1238 Thread::DiscardThreadPlans(bool force)
1239 {
1240     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1241     if (log)
1242     {
1243         log->Printf("Discarding thread plans for thread (tid = 0x%4.4" PRIx64 ", force %d)", GetID(), force);
1244     }
1245 
1246     if (force)
1247     {
1248         int stack_size = m_plan_stack.size();
1249         for (int i = stack_size - 1; i > 0; i--)
1250         {
1251             DiscardPlan();
1252         }
1253         return;
1254     }
1255 
1256     while (1)
1257     {
1258 
1259         int master_plan_idx;
1260         bool discard = true;
1261 
1262         // Find the first master plan, see if it wants discarding, and if yes discard up to it.
1263         for (master_plan_idx = m_plan_stack.size() - 1; master_plan_idx >= 0; master_plan_idx--)
1264         {
1265             if (m_plan_stack[master_plan_idx]->IsMasterPlan())
1266             {
1267                 discard = m_plan_stack[master_plan_idx]->OkayToDiscard();
1268                 break;
1269             }
1270         }
1271 
1272         if (discard)
1273         {
1274             // First pop all the dependent plans:
1275             for (int i = m_plan_stack.size() - 1; i > master_plan_idx; i--)
1276             {
1277 
1278                 // FIXME: Do we need a finalize here, or is the rule that "PrepareForStop"
1279                 // for the plan leaves it in a state that it is safe to pop the plan
1280                 // with no more notice?
1281                 DiscardPlan();
1282             }
1283 
1284             // Now discard the master plan itself.
1285             // The bottom-most plan never gets discarded.  "OkayToDiscard" for it means
1286             // discard it's dependent plans, but not it...
1287             if (master_plan_idx > 0)
1288             {
1289                 DiscardPlan();
1290             }
1291         }
1292         else
1293         {
1294             // If the master plan doesn't want to get discarded, then we're done.
1295             break;
1296         }
1297 
1298     }
1299 }
1300 
1301 bool
1302 Thread::PlanIsBasePlan (ThreadPlan *plan_ptr)
1303 {
1304     if (plan_ptr->IsBasePlan())
1305         return true;
1306     else if (m_plan_stack.size() == 0)
1307         return false;
1308     else
1309        return m_plan_stack[0].get() == plan_ptr;
1310 }
1311 
1312 Error
1313 Thread::UnwindInnermostExpression()
1314 {
1315     Error error;
1316     int stack_size = m_plan_stack.size();
1317 
1318     // If the input plan is NULL, discard all plans.  Otherwise make sure this plan is in the
1319     // stack, and if so discard up to and including it.
1320 
1321     for (int i = stack_size - 1; i > 0; i--)
1322     {
1323         if (m_plan_stack[i]->GetKind() == ThreadPlan::eKindCallFunction)
1324         {
1325             DiscardThreadPlansUpToPlan(m_plan_stack[i].get());
1326             return error;
1327         }
1328     }
1329     error.SetErrorString("No expressions currently active on this thread");
1330     return error;
1331 }
1332 
1333 
1334 ThreadPlan *
1335 Thread::QueueFundamentalPlan (bool abort_other_plans)
1336 {
1337     ThreadPlanSP thread_plan_sp (new ThreadPlanBase(*this));
1338     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1339     return thread_plan_sp.get();
1340 }
1341 
1342 ThreadPlan *
1343 Thread::QueueThreadPlanForStepSingleInstruction
1344 (
1345     bool step_over,
1346     bool abort_other_plans,
1347     bool stop_other_threads
1348 )
1349 {
1350     ThreadPlanSP thread_plan_sp (new ThreadPlanStepInstruction (*this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
1351     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1352     return thread_plan_sp.get();
1353 }
1354 
1355 ThreadPlan *
1356 Thread::QueueThreadPlanForStepOverRange
1357 (
1358     bool abort_other_plans,
1359     const AddressRange &range,
1360     const SymbolContext &addr_context,
1361     lldb::RunMode stop_other_threads
1362 )
1363 {
1364     ThreadPlanSP thread_plan_sp;
1365     thread_plan_sp.reset (new ThreadPlanStepOverRange (*this, range, addr_context, stop_other_threads));
1366 
1367     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1368     return thread_plan_sp.get();
1369 }
1370 
1371 ThreadPlan *
1372 Thread::QueueThreadPlanForStepInRange
1373 (
1374     bool abort_other_plans,
1375     const AddressRange &range,
1376     const SymbolContext &addr_context,
1377     const char *step_in_target,
1378     lldb::RunMode stop_other_threads,
1379     bool avoid_code_without_debug_info
1380 )
1381 {
1382     ThreadPlanSP thread_plan_sp;
1383     ThreadPlanStepInRange *plan = new ThreadPlanStepInRange (*this, range, addr_context, stop_other_threads);
1384     if (avoid_code_without_debug_info)
1385         plan->GetFlags().Set (ThreadPlanShouldStopHere::eAvoidNoDebug);
1386     else
1387         plan->GetFlags().Clear (ThreadPlanShouldStopHere::eAvoidNoDebug);
1388     if (step_in_target)
1389         plan->SetStepInTarget(step_in_target);
1390     thread_plan_sp.reset (plan);
1391 
1392     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1393     return thread_plan_sp.get();
1394 }
1395 
1396 
1397 ThreadPlan *
1398 Thread::QueueThreadPlanForStepOverBreakpointPlan (bool abort_other_plans)
1399 {
1400     ThreadPlanSP thread_plan_sp (new ThreadPlanStepOverBreakpoint (*this));
1401     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1402     return thread_plan_sp.get();
1403 }
1404 
1405 ThreadPlan *
1406 Thread::QueueThreadPlanForStepOut
1407 (
1408     bool abort_other_plans,
1409     SymbolContext *addr_context,
1410     bool first_insn,
1411     bool stop_other_threads,
1412     Vote stop_vote,
1413     Vote run_vote,
1414     uint32_t frame_idx
1415 )
1416 {
1417     ThreadPlanSP thread_plan_sp (new ThreadPlanStepOut (*this,
1418                                                         addr_context,
1419                                                         first_insn,
1420                                                         stop_other_threads,
1421                                                         stop_vote,
1422                                                         run_vote,
1423                                                         frame_idx));
1424 
1425     if (thread_plan_sp->ValidatePlan(NULL))
1426     {
1427         QueueThreadPlan (thread_plan_sp, abort_other_plans);
1428         return thread_plan_sp.get();
1429     }
1430     else
1431     {
1432         return NULL;
1433     }
1434 }
1435 
1436 ThreadPlan *
1437 Thread::QueueThreadPlanForStepThrough (StackID &return_stack_id, bool abort_other_plans, bool stop_other_threads)
1438 {
1439     ThreadPlanSP thread_plan_sp(new ThreadPlanStepThrough (*this, return_stack_id, stop_other_threads));
1440     if (!thread_plan_sp || !thread_plan_sp->ValidatePlan (NULL))
1441         return NULL;
1442 
1443     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1444     return thread_plan_sp.get();
1445 }
1446 
1447 ThreadPlan *
1448 Thread::QueueThreadPlanForCallFunction (bool abort_other_plans,
1449                                         Address& function,
1450                                         lldb::addr_t arg,
1451                                         bool stop_other_threads,
1452                                         bool unwind_on_error,
1453                                         bool ignore_breakpoints)
1454 {
1455     ThreadPlanSP thread_plan_sp (new ThreadPlanCallFunction (*this,
1456                                                              function,
1457                                                              ClangASTType(),
1458                                                              arg,
1459                                                              stop_other_threads,
1460                                                              unwind_on_error,
1461                                                              ignore_breakpoints));
1462     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1463     return thread_plan_sp.get();
1464 }
1465 
1466 ThreadPlan *
1467 Thread::QueueThreadPlanForRunToAddress (bool abort_other_plans,
1468                                         Address &target_addr,
1469                                         bool stop_other_threads)
1470 {
1471     ThreadPlanSP thread_plan_sp (new ThreadPlanRunToAddress (*this, target_addr, stop_other_threads));
1472     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1473     return thread_plan_sp.get();
1474 }
1475 
1476 ThreadPlan *
1477 Thread::QueueThreadPlanForStepUntil (bool abort_other_plans,
1478                                      lldb::addr_t *address_list,
1479                                      size_t num_addresses,
1480                                      bool stop_other_threads,
1481                                      uint32_t frame_idx)
1482 {
1483     ThreadPlanSP thread_plan_sp (new ThreadPlanStepUntil (*this, address_list, num_addresses, stop_other_threads, frame_idx));
1484     QueueThreadPlan (thread_plan_sp, abort_other_plans);
1485     return thread_plan_sp.get();
1486 
1487 }
1488 
1489 uint32_t
1490 Thread::GetIndexID () const
1491 {
1492     return m_index_id;
1493 }
1494 
1495 void
1496 Thread::DumpThreadPlans (lldb_private::Stream *s) const
1497 {
1498     uint32_t stack_size = m_plan_stack.size();
1499     int i;
1500     s->Indent();
1501     s->Printf ("Plan Stack for thread #%u: tid = 0x%4.4" PRIx64 ", stack_size = %d\n", GetIndexID(), GetID(), stack_size);
1502     for (i = stack_size - 1; i >= 0; i--)
1503     {
1504         s->IndentMore();
1505         s->Indent();
1506         s->Printf ("Element %d: ", i);
1507         m_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
1508         s->EOL();
1509         s->IndentLess();
1510     }
1511 
1512     stack_size = m_completed_plan_stack.size();
1513     if (stack_size > 0)
1514     {
1515         s->Indent();
1516         s->Printf ("Completed Plan Stack: %d elements.\n", stack_size);
1517         for (i = stack_size - 1; i >= 0; i--)
1518         {
1519             s->IndentMore();
1520             s->Indent();
1521             s->Printf ("Element %d: ", i);
1522             m_completed_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
1523             s->EOL();
1524             s->IndentLess();
1525         }
1526     }
1527 
1528     stack_size = m_discarded_plan_stack.size();
1529     if (stack_size > 0)
1530     {
1531         s->Indent();
1532         s->Printf ("Discarded Plan Stack: %d elements.\n", stack_size);
1533         for (i = stack_size - 1; i >= 0; i--)
1534         {
1535             s->IndentMore();
1536             s->Indent();
1537             s->Printf ("Element %d: ", i);
1538             m_discarded_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
1539             s->EOL();
1540             s->IndentLess();
1541         }
1542     }
1543 
1544 }
1545 
1546 TargetSP
1547 Thread::CalculateTarget ()
1548 {
1549     TargetSP target_sp;
1550     ProcessSP process_sp(GetProcess());
1551     if (process_sp)
1552         target_sp = process_sp->CalculateTarget();
1553     return target_sp;
1554 
1555 }
1556 
1557 ProcessSP
1558 Thread::CalculateProcess ()
1559 {
1560     return GetProcess();
1561 }
1562 
1563 ThreadSP
1564 Thread::CalculateThread ()
1565 {
1566     return shared_from_this();
1567 }
1568 
1569 StackFrameSP
1570 Thread::CalculateStackFrame ()
1571 {
1572     return StackFrameSP();
1573 }
1574 
1575 void
1576 Thread::CalculateExecutionContext (ExecutionContext &exe_ctx)
1577 {
1578     exe_ctx.SetContext (shared_from_this());
1579 }
1580 
1581 
1582 StackFrameListSP
1583 Thread::GetStackFrameList ()
1584 {
1585     StackFrameListSP frame_list_sp;
1586     Mutex::Locker locker(m_frame_mutex);
1587     if (m_curr_frames_sp)
1588     {
1589         frame_list_sp = m_curr_frames_sp;
1590     }
1591     else
1592     {
1593         frame_list_sp.reset(new StackFrameList (*this, m_prev_frames_sp, true));
1594         m_curr_frames_sp = frame_list_sp;
1595     }
1596     return frame_list_sp;
1597 }
1598 
1599 void
1600 Thread::ClearStackFrames ()
1601 {
1602     Mutex::Locker locker(m_frame_mutex);
1603 
1604     Unwind *unwinder = GetUnwinder ();
1605     if (unwinder)
1606         unwinder->Clear();
1607 
1608     // Only store away the old "reference" StackFrameList if we got all its frames:
1609     // FIXME: At some point we can try to splice in the frames we have fetched into
1610     // the new frame as we make it, but let's not try that now.
1611     if (m_curr_frames_sp && m_curr_frames_sp->GetAllFramesFetched())
1612         m_prev_frames_sp.swap (m_curr_frames_sp);
1613     m_curr_frames_sp.reset();
1614 }
1615 
1616 lldb::StackFrameSP
1617 Thread::GetFrameWithConcreteFrameIndex (uint32_t unwind_idx)
1618 {
1619     return GetStackFrameList()->GetFrameWithConcreteFrameIndex (unwind_idx);
1620 }
1621 
1622 
1623 Error
1624 Thread::ReturnFromFrameWithIndex (uint32_t frame_idx, lldb::ValueObjectSP return_value_sp, bool broadcast)
1625 {
1626     StackFrameSP frame_sp = GetStackFrameAtIndex (frame_idx);
1627     Error return_error;
1628 
1629     if (!frame_sp)
1630     {
1631         return_error.SetErrorStringWithFormat("Could not find frame with index %d in thread 0x%" PRIx64 ".", frame_idx, GetID());
1632     }
1633 
1634     return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
1635 }
1636 
1637 Error
1638 Thread::ReturnFromFrame (lldb::StackFrameSP frame_sp, lldb::ValueObjectSP return_value_sp, bool broadcast)
1639 {
1640     Error return_error;
1641 
1642     if (!frame_sp)
1643     {
1644         return_error.SetErrorString("Can't return to a null frame.");
1645         return return_error;
1646     }
1647 
1648     Thread *thread = frame_sp->GetThread().get();
1649     uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
1650     StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
1651     if (!older_frame_sp)
1652     {
1653         return_error.SetErrorString("No older frame to return to.");
1654         return return_error;
1655     }
1656 
1657     if (return_value_sp)
1658     {
1659         lldb::ABISP abi = thread->GetProcess()->GetABI();
1660         if (!abi)
1661         {
1662             return_error.SetErrorString("Could not find ABI to set return value.");
1663             return return_error;
1664         }
1665         SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
1666 
1667         // FIXME: ValueObject::Cast doesn't currently work correctly, at least not for scalars.
1668         // Turn that back on when that works.
1669         if (0 && sc.function != NULL)
1670         {
1671             Type *function_type = sc.function->GetType();
1672             if (function_type)
1673             {
1674                 clang_type_t return_type = sc.function->GetReturnClangType();
1675                 if (return_type)
1676                 {
1677                     ClangASTType ast_type (function_type->GetClangAST(), return_type);
1678                     StreamString s;
1679                     ast_type.DumpTypeDescription(&s);
1680                     ValueObjectSP cast_value_sp = return_value_sp->Cast(ast_type);
1681                     if (cast_value_sp)
1682                     {
1683                         cast_value_sp->SetFormat(eFormatHex);
1684                         return_value_sp = cast_value_sp;
1685                     }
1686                 }
1687             }
1688         }
1689 
1690         return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
1691         if (!return_error.Success())
1692             return return_error;
1693     }
1694 
1695     // Now write the return registers for the chosen frame:
1696     // Note, we can't use ReadAllRegisterValues->WriteAllRegisterValues, since the read & write
1697     // cook their data
1698 
1699     StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);
1700     if (youngest_frame_sp)
1701     {
1702         lldb::RegisterContextSP reg_ctx_sp (youngest_frame_sp->GetRegisterContext());
1703         if (reg_ctx_sp)
1704         {
1705             bool copy_success = reg_ctx_sp->CopyFromRegisterContext(older_frame_sp->GetRegisterContext());
1706             if (copy_success)
1707             {
1708                 thread->DiscardThreadPlans(true);
1709                 thread->ClearStackFrames();
1710                 if (broadcast && EventTypeHasListeners(eBroadcastBitStackChanged))
1711                     BroadcastEvent(eBroadcastBitStackChanged, new ThreadEventData (this->shared_from_this()));
1712             }
1713             else
1714             {
1715                 return_error.SetErrorString("Could not reset register values.");
1716             }
1717         }
1718         else
1719         {
1720             return_error.SetErrorString("Frame has no register context.");
1721         }
1722     }
1723     else
1724     {
1725         return_error.SetErrorString("Returned past top frame.");
1726     }
1727     return return_error;
1728 }
1729 
1730 void
1731 Thread::DumpUsingSettingsFormat (Stream &strm, uint32_t frame_idx)
1732 {
1733     ExecutionContext exe_ctx (shared_from_this());
1734     Process *process = exe_ctx.GetProcessPtr();
1735     if (process == NULL)
1736         return;
1737 
1738     StackFrameSP frame_sp;
1739     SymbolContext frame_sc;
1740     if (frame_idx != LLDB_INVALID_INDEX32)
1741     {
1742         frame_sp = GetStackFrameAtIndex (frame_idx);
1743         if (frame_sp)
1744         {
1745             exe_ctx.SetFrameSP(frame_sp);
1746             frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
1747         }
1748     }
1749 
1750     const char *thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
1751     assert (thread_format);
1752     const char *end = NULL;
1753     Debugger::FormatPrompt (thread_format,
1754                             frame_sp ? &frame_sc : NULL,
1755                             &exe_ctx,
1756                             NULL,
1757                             strm,
1758                             &end);
1759 }
1760 
1761 void
1762 Thread::SettingsInitialize ()
1763 {
1764 }
1765 
1766 void
1767 Thread::SettingsTerminate ()
1768 {
1769 }
1770 
1771 lldb::StackFrameSP
1772 Thread::GetStackFrameSPForStackFramePtr (StackFrame *stack_frame_ptr)
1773 {
1774     return GetStackFrameList()->GetStackFrameSPForStackFramePtr (stack_frame_ptr);
1775 }
1776 
1777 const char *
1778 Thread::StopReasonAsCString (lldb::StopReason reason)
1779 {
1780     switch (reason)
1781     {
1782     case eStopReasonInvalid:       return "invalid";
1783     case eStopReasonNone:          return "none";
1784     case eStopReasonTrace:         return "trace";
1785     case eStopReasonBreakpoint:    return "breakpoint";
1786     case eStopReasonWatchpoint:    return "watchpoint";
1787     case eStopReasonSignal:        return "signal";
1788     case eStopReasonException:     return "exception";
1789     case eStopReasonExec:          return "exec";
1790     case eStopReasonPlanComplete:  return "plan complete";
1791     case eStopReasonThreadExiting: return "thread exiting";
1792     }
1793 
1794 
1795     static char unknown_state_string[64];
1796     snprintf(unknown_state_string, sizeof (unknown_state_string), "StopReason = %i", reason);
1797     return unknown_state_string;
1798 }
1799 
1800 const char *
1801 Thread::RunModeAsCString (lldb::RunMode mode)
1802 {
1803     switch (mode)
1804     {
1805     case eOnlyThisThread:     return "only this thread";
1806     case eAllThreads:         return "all threads";
1807     case eOnlyDuringStepping: return "only during stepping";
1808     }
1809 
1810     static char unknown_state_string[64];
1811     snprintf(unknown_state_string, sizeof (unknown_state_string), "RunMode = %i", mode);
1812     return unknown_state_string;
1813 }
1814 
1815 size_t
1816 Thread::GetStatus (Stream &strm, uint32_t start_frame, uint32_t num_frames, uint32_t num_frames_with_source)
1817 {
1818     ExecutionContext exe_ctx (shared_from_this());
1819     Target *target = exe_ctx.GetTargetPtr();
1820     Process *process = exe_ctx.GetProcessPtr();
1821     size_t num_frames_shown = 0;
1822     strm.Indent();
1823     bool is_selected = false;
1824     if (process)
1825     {
1826         if (process->GetThreadList().GetSelectedThread().get() == this)
1827             is_selected = true;
1828     }
1829     strm.Printf("%c ", is_selected ? '*' : ' ');
1830     if (target && target->GetDebugger().GetUseExternalEditor())
1831     {
1832         StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
1833         if (frame_sp)
1834         {
1835             SymbolContext frame_sc(frame_sp->GetSymbolContext (eSymbolContextLineEntry));
1836             if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file)
1837             {
1838                 Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line);
1839             }
1840         }
1841     }
1842 
1843     DumpUsingSettingsFormat (strm, start_frame);
1844 
1845     if (num_frames > 0)
1846     {
1847         strm.IndentMore();
1848 
1849         const bool show_frame_info = true;
1850         strm.IndentMore ();
1851         num_frames_shown = GetStackFrameList ()->GetStatus (strm,
1852                                                             start_frame,
1853                                                             num_frames,
1854                                                             show_frame_info,
1855                                                             num_frames_with_source);
1856         strm.IndentLess();
1857         strm.IndentLess();
1858     }
1859     return num_frames_shown;
1860 }
1861 
1862 size_t
1863 Thread::GetStackFrameStatus (Stream& strm,
1864                              uint32_t first_frame,
1865                              uint32_t num_frames,
1866                              bool show_frame_info,
1867                              uint32_t num_frames_with_source)
1868 {
1869     return GetStackFrameList()->GetStatus (strm,
1870                                            first_frame,
1871                                            num_frames,
1872                                            show_frame_info,
1873                                            num_frames_with_source);
1874 }
1875 
1876 bool
1877 Thread::SaveFrameZeroState (RegisterCheckpoint &checkpoint)
1878 {
1879     lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
1880     if (frame_sp)
1881     {
1882         checkpoint.SetStackID(frame_sp->GetStackID());
1883         lldb::RegisterContextSP reg_ctx_sp (frame_sp->GetRegisterContext());
1884         if (reg_ctx_sp)
1885             return reg_ctx_sp->ReadAllRegisterValues (checkpoint.GetData());
1886     }
1887     return false;
1888 }
1889 
1890 bool
1891 Thread::RestoreSaveFrameZero (const RegisterCheckpoint &checkpoint)
1892 {
1893     return ResetFrameZeroRegisters (checkpoint.GetData());
1894 }
1895 
1896 bool
1897 Thread::ResetFrameZeroRegisters (lldb::DataBufferSP register_data_sp)
1898 {
1899     lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
1900     if (frame_sp)
1901     {
1902         lldb::RegisterContextSP reg_ctx_sp (frame_sp->GetRegisterContext());
1903         if (reg_ctx_sp)
1904         {
1905             bool ret = reg_ctx_sp->WriteAllRegisterValues (register_data_sp);
1906 
1907             // Clear out all stack frames as our world just changed.
1908             ClearStackFrames();
1909             reg_ctx_sp->InvalidateIfNeeded(true);
1910             if (m_unwinder_ap.get())
1911                 m_unwinder_ap->Clear();
1912             return ret;
1913         }
1914     }
1915     return false;
1916 }
1917 
1918 Unwind *
1919 Thread::GetUnwinder ()
1920 {
1921     if (m_unwinder_ap.get() == NULL)
1922     {
1923         const ArchSpec target_arch (CalculateTarget()->GetArchitecture ());
1924         const llvm::Triple::ArchType machine = target_arch.GetMachine();
1925         switch (machine)
1926         {
1927             case llvm::Triple::x86_64:
1928             case llvm::Triple::x86:
1929             case llvm::Triple::arm:
1930             case llvm::Triple::thumb:
1931                 m_unwinder_ap.reset (new UnwindLLDB (*this));
1932                 break;
1933 
1934             default:
1935                 if (target_arch.GetTriple().getVendor() == llvm::Triple::Apple)
1936                     m_unwinder_ap.reset (new UnwindMacOSXFrameBackchain (*this));
1937                 break;
1938         }
1939     }
1940     return m_unwinder_ap.get();
1941 }
1942 
1943 
1944 void
1945 Thread::Flush ()
1946 {
1947     ClearStackFrames ();
1948     m_reg_context_sp.reset();
1949 }
1950 
1951 bool
1952 Thread::IsStillAtLastBreakpointHit ()
1953 {
1954     // If we are currently stopped at a breakpoint, always return that stopinfo and don't reset it.
1955     // This allows threads to maintain their breakpoint stopinfo, such as when thread-stepping in
1956     // multithreaded programs.
1957     if (m_stop_info_sp) {
1958         StopReason stop_reason = m_stop_info_sp->GetStopReason();
1959         if (stop_reason == lldb::eStopReasonBreakpoint) {
1960             uint64_t value = m_stop_info_sp->GetValue();
1961             lldb::RegisterContextSP reg_ctx_sp (GetRegisterContext());
1962             if (reg_ctx_sp)
1963             {
1964                 lldb::addr_t pc = reg_ctx_sp->GetPC();
1965                 BreakpointSiteSP bp_site_sp = GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1966                 if (bp_site_sp && value == bp_site_sp->GetID())
1967                     return true;
1968             }
1969         }
1970     }
1971     return false;
1972 }
1973