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