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