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