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