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