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