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