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