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