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