1 //===-- Thread.cpp ----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 // Other libraries and framework includes
14 #include "lldb/Breakpoint/BreakpointLocation.h"
15 #include "lldb/Core/Debugger.h"
16 #include "lldb/Core/Log.h"
17 #include "lldb/Core/FormatEntity.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/State.h"
20 #include "lldb/Core/Stream.h"
21 #include "lldb/Core/StreamString.h"
22 #include "lldb/Core/RegularExpression.h"
23 #include "lldb/Core/ValueObject.h"
24 #include "lldb/Host/Host.h"
25 #include "lldb/Interpreter/OptionValueFileSpecList.h"
26 #include "lldb/Interpreter/OptionValueProperties.h"
27 #include "lldb/Interpreter/Property.h"
28 #include "lldb/Symbol/Function.h"
29 #include "lldb/Target/ABI.h"
30 #include "lldb/Target/DynamicLoader.h"
31 #include "lldb/Target/ExecutionContext.h"
32 #include "lldb/Target/Process.h"
33 #include "lldb/Target/RegisterContext.h"
34 #include "lldb/Target/StopInfo.h"
35 #include "lldb/Target/SystemRuntime.h"
36 #include "lldb/Target/Target.h"
37 #include "lldb/Target/Thread.h"
38 #include "lldb/Target/ThreadPlan.h"
39 #include "lldb/Target/ThreadPlanCallFunction.h"
40 #include "lldb/Target/ThreadPlanBase.h"
41 #include "lldb/Target/ThreadPlanPython.h"
42 #include "lldb/Target/ThreadPlanStepInstruction.h"
43 #include "lldb/Target/ThreadPlanStepOut.h"
44 #include "lldb/Target/ThreadPlanStepOverBreakpoint.h"
45 #include "lldb/Target/ThreadPlanStepThrough.h"
46 #include "lldb/Target/ThreadPlanStepInRange.h"
47 #include "lldb/Target/ThreadPlanStepOverRange.h"
48 #include "lldb/Target/ThreadPlanRunToAddress.h"
49 #include "lldb/Target/ThreadPlanStepUntil.h"
50 #include "lldb/Target/ThreadSpec.h"
51 #include "lldb/Target/Unwind.h"
52 #include "Plugins/Process/Utility/UnwindLLDB.h"
53 #include "Plugins/Process/Utility/UnwindMacOSXFrameBackchain.h"
56 using namespace lldb_private;
58 const ThreadPropertiesSP &
59 Thread::GetGlobalProperties()
61 static ThreadPropertiesSP g_settings_sp;
63 g_settings_sp.reset (new ThreadProperties (true));
67 static PropertyDefinition
70 { "step-in-avoid-nodebug", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, step-in will not stop in functions with no debug information." },
71 { "step-out-avoid-nodebug", OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "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 "
72 "debug information. Passing a frame argument to step-out will override this option." },
73 { "step-avoid-regexp", OptionValue::eTypeRegex , true , 0, "^std::", nullptr, "A regular expression defining functions step-in won't stop in." },
74 { "step-avoid-libraries", OptionValue::eTypeFileSpecList , true , 0, nullptr, nullptr, "A list of libraries that source stepping won't stop in." },
75 { "trace-thread", OptionValue::eTypeBoolean, false, false, nullptr, nullptr, "If true, this thread will single-step and log execution." },
76 { nullptr , OptionValue::eTypeInvalid, false, 0 , nullptr, nullptr, nullptr }
80 ePropertyStepInAvoidsNoDebug,
81 ePropertyStepOutAvoidsNoDebug,
82 ePropertyStepAvoidRegex,
83 ePropertyStepAvoidLibraries,
84 ePropertyEnableThreadTrace
87 class ThreadOptionValueProperties : public OptionValueProperties
90 ThreadOptionValueProperties (const ConstString &name) :
91 OptionValueProperties (name)
95 // This constructor is used when creating ThreadOptionValueProperties when it
96 // is part of a new lldb_private::Thread instance. It will copy all current
97 // global property values as needed
98 ThreadOptionValueProperties (ThreadProperties *global_properties) :
99 OptionValueProperties(*global_properties->GetValueProperties())
104 GetPropertyAtIndex(const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const override
106 // When getting the value for a key from the thread options, we will always
107 // try and grab the setting from the current thread if there is one. Else we just
108 // use the one from this instance.
111 Thread *thread = exe_ctx->GetThreadPtr();
114 ThreadOptionValueProperties *instance_properties = static_cast<ThreadOptionValueProperties *>(thread->GetValueProperties().get());
115 if (this != instance_properties)
116 return instance_properties->ProtectedGetPropertyAtIndex (idx);
119 return ProtectedGetPropertyAtIndex (idx);
123 ThreadProperties::ThreadProperties (bool is_global) :
128 m_collection_sp.reset (new ThreadOptionValueProperties(ConstString("thread")));
129 m_collection_sp->Initialize(g_properties);
132 m_collection_sp.reset (new ThreadOptionValueProperties(Thread::GetGlobalProperties().get()));
135 ThreadProperties::~ThreadProperties() = default;
137 const RegularExpression *
138 ThreadProperties::GetSymbolsToAvoidRegexp()
140 const uint32_t idx = ePropertyStepAvoidRegex;
141 return m_collection_sp->GetPropertyAtIndexAsOptionValueRegex(nullptr, idx);
145 ThreadProperties::GetLibrariesToAvoid() const
147 const uint32_t idx = ePropertyStepAvoidLibraries;
148 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, false, idx);
149 assert(option_value);
150 return option_value->GetCurrentValue();
154 ThreadProperties::GetTraceEnabledState() const
156 const uint32_t idx = ePropertyEnableThreadTrace;
157 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
161 ThreadProperties::GetStepInAvoidsNoDebug() const
163 const uint32_t idx = ePropertyStepInAvoidsNoDebug;
164 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
168 ThreadProperties::GetStepOutAvoidsNoDebug() const
170 const uint32_t idx = ePropertyStepOutAvoidsNoDebug;
171 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
174 //------------------------------------------------------------------
176 //------------------------------------------------------------------
179 Thread::ThreadEventData::GetFlavorString ()
181 static ConstString g_flavor ("Thread::ThreadEventData");
185 Thread::ThreadEventData::ThreadEventData (const lldb::ThreadSP thread_sp) :
186 m_thread_sp (thread_sp),
191 Thread::ThreadEventData::ThreadEventData (const lldb::ThreadSP thread_sp, const StackID &stack_id) :
192 m_thread_sp (thread_sp),
193 m_stack_id (stack_id)
197 Thread::ThreadEventData::ThreadEventData () :
203 Thread::ThreadEventData::~ThreadEventData() = default;
206 Thread::ThreadEventData::Dump (Stream *s) const
210 const Thread::ThreadEventData *
211 Thread::ThreadEventData::GetEventDataFromEvent (const Event *event_ptr)
215 const EventData *event_data = event_ptr->GetData();
216 if (event_data && event_data->GetFlavor() == ThreadEventData::GetFlavorString())
217 return static_cast <const ThreadEventData *> (event_ptr->GetData());
223 Thread::ThreadEventData::GetThreadFromEvent (const Event *event_ptr)
226 const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
228 thread_sp = event_data->GetThread();
233 Thread::ThreadEventData::GetStackIDFromEvent (const Event *event_ptr)
236 const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
238 stack_id = event_data->GetStackID();
243 Thread::ThreadEventData::GetStackFrameFromEvent (const Event *event_ptr)
245 const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
246 StackFrameSP frame_sp;
249 ThreadSP thread_sp = event_data->GetThread();
252 frame_sp = thread_sp->GetStackFrameList()->GetFrameWithStackID (event_data->GetStackID());
258 //------------------------------------------------------------------
260 //------------------------------------------------------------------
263 Thread::GetStaticBroadcasterClass ()
265 static ConstString class_name ("lldb.thread");
269 Thread::Thread (Process &process, lldb::tid_t tid, bool use_invalid_index_id) :
270 ThreadProperties (false),
272 Broadcaster(&process.GetTarget().GetDebugger(), Thread::GetStaticBroadcasterClass().AsCString()),
273 m_process_wp (process.shared_from_this()),
275 m_stop_info_stop_id (0),
276 m_stop_info_override_stop_id (0),
277 m_index_id (use_invalid_index_id ? LLDB_INVALID_INDEX32 : process.GetNextThreadIndexID(tid)),
279 m_state (eStateUnloaded),
280 m_state_mutex (Mutex::eMutexTypeRecursive),
282 m_completed_plan_stack(),
283 m_frame_mutex (Mutex::eMutexTypeRecursive),
286 m_resume_signal (LLDB_INVALID_SIGNAL_NUMBER),
287 m_resume_state (eStateRunning),
288 m_temporary_resume_state (eStateRunning),
290 m_destroy_called (false),
291 m_override_should_notify (eLazyBoolCalculate),
292 m_extended_info_fetched (false),
295 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
297 log->Printf ("%p Thread::Thread(tid = 0x%4.4" PRIx64 ")",
298 static_cast<void*>(this), GetID());
300 CheckInWithManager();
301 QueueFundamentalPlan(true);
306 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
308 log->Printf ("%p Thread::~Thread(tid = 0x%4.4" PRIx64 ")",
309 static_cast<void*>(this), GetID());
310 /// If you hit this assert, it means your derived class forgot to call DoDestroy in its destructor.
311 assert (m_destroy_called);
315 Thread::DestroyThread ()
317 // Tell any plans on the plan stacks that the thread is being destroyed since
318 // any plans that have a thread go away in the middle of might need
319 // to do cleanup, or in some cases NOT do cleanup...
320 for (auto plan : m_plan_stack)
321 plan->ThreadDestroyed();
323 for (auto plan : m_discarded_plan_stack)
324 plan->ThreadDestroyed();
326 for (auto plan : m_completed_plan_stack)
327 plan->ThreadDestroyed();
329 m_destroy_called = true;
330 m_plan_stack.clear();
331 m_discarded_plan_stack.clear();
332 m_completed_plan_stack.clear();
334 // Push a ThreadPlanNull on the plan stack. That way we can continue assuming that the
335 // plan stack is never empty, but if somebody errantly asks questions of a destroyed thread
336 // without checking first whether it is destroyed, they won't crash.
337 ThreadPlanSP null_plan_sp(new ThreadPlanNull (*this));
338 m_plan_stack.push_back (null_plan_sp);
340 m_stop_info_sp.reset();
341 m_reg_context_sp.reset();
342 m_unwinder_ap.reset();
343 Mutex::Locker locker(m_frame_mutex);
344 m_curr_frames_sp.reset();
345 m_prev_frames_sp.reset();
349 Thread::BroadcastSelectedFrameChange(StackID &new_frame_id)
351 if (EventTypeHasListeners(eBroadcastBitSelectedFrameChanged))
352 BroadcastEvent(eBroadcastBitSelectedFrameChanged, new ThreadEventData (this->shared_from_this(), new_frame_id));
356 Thread::GetSelectedFrame()
358 StackFrameListSP stack_frame_list_sp(GetStackFrameList());
359 StackFrameSP frame_sp = stack_frame_list_sp->GetFrameAtIndex (stack_frame_list_sp->GetSelectedFrameIndex());
360 FunctionOptimizationWarning (frame_sp.get());
365 Thread::SetSelectedFrame (lldb_private::StackFrame *frame, bool broadcast)
367 uint32_t ret_value = GetStackFrameList()->SetSelectedFrame(frame);
369 BroadcastSelectedFrameChange(frame->GetStackID());
370 FunctionOptimizationWarning (frame);
375 Thread::SetSelectedFrameByIndex (uint32_t frame_idx, bool broadcast)
377 StackFrameSP frame_sp(GetStackFrameList()->GetFrameAtIndex (frame_idx));
380 GetStackFrameList()->SetSelectedFrame(frame_sp.get());
382 BroadcastSelectedFrameChange(frame_sp->GetStackID());
383 FunctionOptimizationWarning (frame_sp.get());
391 Thread::SetSelectedFrameByIndexNoisily (uint32_t frame_idx, Stream &output_stream)
393 const bool broadcast = true;
394 bool success = SetSelectedFrameByIndex (frame_idx, broadcast);
397 StackFrameSP frame_sp = GetSelectedFrame();
400 bool already_shown = false;
401 SymbolContext frame_sc(frame_sp->GetSymbolContext(eSymbolContextLineEntry));
402 if (GetProcess()->GetTarget().GetDebugger().GetUseExternalEditor() && frame_sc.line_entry.file && frame_sc.line_entry.line != 0)
404 already_shown = Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line);
407 bool show_frame_info = true;
408 bool show_source = !already_shown;
409 FunctionOptimizationWarning (frame_sp.get());
410 return frame_sp->GetStatus (output_stream, show_frame_info, show_source);
419 Thread::FunctionOptimizationWarning (StackFrame *frame)
421 if (frame && frame->HasDebugInformation() && GetProcess()->GetWarningsOptimization())
423 SymbolContext sc = frame->GetSymbolContext (eSymbolContextFunction | eSymbolContextModule);
424 GetProcess()->PrintWarningOptimization (sc);
429 Thread::GetStopInfo ()
431 if (m_destroy_called)
432 return m_stop_info_sp;
434 ThreadPlanSP plan_sp (GetCompletedPlan());
435 ProcessSP process_sp (GetProcess());
436 const uint32_t stop_id = process_sp ? process_sp->GetStopID() : UINT32_MAX;
437 if (plan_sp && plan_sp->PlanSucceeded())
439 return StopInfo::CreateStopReasonWithPlan (plan_sp, GetReturnValueObject(), GetExpressionVariable());
443 if ((m_stop_info_stop_id == stop_id) || // Stop info is valid, just return what we have (even if empty)
444 (m_stop_info_sp && m_stop_info_sp->IsValid())) // Stop info is valid, just return what we have
446 return m_stop_info_sp;
450 GetPrivateStopInfo ();
451 return m_stop_info_sp;
457 Thread::GetPrivateStopInfo ()
459 if (m_destroy_called)
460 return m_stop_info_sp;
462 ProcessSP process_sp (GetProcess());
465 const uint32_t process_stop_id = process_sp->GetStopID();
466 if (m_stop_info_stop_id != process_stop_id)
470 if (m_stop_info_sp->IsValid()
471 || IsStillAtLastBreakpointHit()
472 || GetCurrentPlan()->IsVirtualStep())
473 SetStopInfo (m_stop_info_sp);
475 m_stop_info_sp.reset();
480 if (!CalculateStopInfo())
481 SetStopInfo (StopInfoSP());
485 // The stop info can be manually set by calling Thread::SetStopInfo()
486 // prior to this function ever getting called, so we can't rely on
487 // "m_stop_info_stop_id != process_stop_id" as the condition for
488 // the if statement below, we must also check the stop info to see
489 // if we need to override it. See the header documentation in
490 // Process::GetStopInfoOverrideCallback() for more information on
491 // the stop info override callback.
492 if (m_stop_info_override_stop_id != process_stop_id)
494 m_stop_info_override_stop_id = process_stop_id;
497 ArchSpec::StopInfoOverrideCallbackType callback = GetProcess()->GetStopInfoOverrideCallback();
503 return m_stop_info_sp;
507 Thread::GetStopReason()
509 lldb::StopInfoSP stop_info_sp (GetStopInfo ());
511 return stop_info_sp->GetStopReason();
512 return eStopReasonNone;
516 Thread::StopInfoIsUpToDate() const
518 ProcessSP process_sp (GetProcess());
520 return m_stop_info_stop_id == process_sp->GetStopID();
522 return true; // Process is no longer around so stop info is always up to date...
526 Thread::SetStopInfo (const lldb::StopInfoSP &stop_info_sp)
528 m_stop_info_sp = stop_info_sp;
531 m_stop_info_sp->MakeStopInfoValid();
532 // If we are overriding the ShouldReportStop, do that here:
533 if (m_override_should_notify != eLazyBoolCalculate)
534 m_stop_info_sp->OverrideShouldNotify (m_override_should_notify == eLazyBoolYes);
537 ProcessSP process_sp (GetProcess());
539 m_stop_info_stop_id = process_sp->GetStopID();
541 m_stop_info_stop_id = UINT32_MAX;
542 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
544 log->Printf("%p: tid = 0x%" PRIx64 ": stop info = %s (stop_id = %u)",
545 static_cast<void*>(this), GetID(),
546 stop_info_sp ? stop_info_sp->GetDescription() : "<NULL>",
547 m_stop_info_stop_id);
551 Thread::SetShouldReportStop (Vote vote)
553 if (vote == eVoteNoOpinion)
557 m_override_should_notify = (vote == eVoteYes ? eLazyBoolYes : eLazyBoolNo);
559 m_stop_info_sp->OverrideShouldNotify (m_override_should_notify == eLazyBoolYes);
564 Thread::SetStopInfoToNothing()
566 // Note, we can't just NULL out the private reason, or the native thread implementation will try to
567 // go calculate it again. For now, just set it to a Unix Signal with an invalid signal number.
568 SetStopInfo (StopInfo::CreateStopReasonWithSignal (*this, LLDB_INVALID_SIGNAL_NUMBER));
572 Thread::ThreadStoppedForAReason (void)
574 return (bool) GetPrivateStopInfo ();
578 Thread::CheckpointThreadState (ThreadStateCheckpoint &saved_state)
580 saved_state.register_backup_sp.reset();
581 lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
584 lldb::RegisterCheckpointSP reg_checkpoint_sp(new RegisterCheckpoint(RegisterCheckpoint::Reason::eExpression));
585 if (reg_checkpoint_sp)
587 lldb::RegisterContextSP reg_ctx_sp (frame_sp->GetRegisterContext());
588 if (reg_ctx_sp && reg_ctx_sp->ReadAllRegisterValues (*reg_checkpoint_sp))
589 saved_state.register_backup_sp = reg_checkpoint_sp;
592 if (!saved_state.register_backup_sp)
595 saved_state.stop_info_sp = GetStopInfo();
596 ProcessSP process_sp (GetProcess());
598 saved_state.orig_stop_id = process_sp->GetStopID();
599 saved_state.current_inlined_depth = GetCurrentInlinedDepth();
605 Thread::RestoreRegisterStateFromCheckpoint (ThreadStateCheckpoint &saved_state)
607 if (saved_state.register_backup_sp)
609 lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
612 lldb::RegisterContextSP reg_ctx_sp (frame_sp->GetRegisterContext());
615 bool ret = reg_ctx_sp->WriteAllRegisterValues (*saved_state.register_backup_sp);
617 // Clear out all stack frames as our world just changed.
619 reg_ctx_sp->InvalidateIfNeeded(true);
620 if (m_unwinder_ap.get())
621 m_unwinder_ap->Clear();
630 Thread::RestoreThreadStateFromCheckpoint (ThreadStateCheckpoint &saved_state)
632 if (saved_state.stop_info_sp)
633 saved_state.stop_info_sp->MakeStopInfoValid();
634 SetStopInfo(saved_state.stop_info_sp);
635 GetStackFrameList()->SetCurrentInlinedDepth (saved_state.current_inlined_depth);
640 Thread::GetState() const
642 // If any other threads access this we will need a mutex for it
643 Mutex::Locker locker(m_state_mutex);
648 Thread::SetState(StateType state)
650 Mutex::Locker locker(m_state_mutex);
657 ThreadPlan *current_plan = GetCurrentPlan();
659 // FIXME: I may decide to disallow threads with no plans. In which
660 // case this should go to an assert.
665 current_plan->WillStop();
669 Thread::SetupForResume ()
671 if (GetResumeState() != eStateSuspended)
673 // If we're at a breakpoint push the step-over breakpoint plan. Do this before
674 // telling the current plan it will resume, since we might change what the current
677 lldb::RegisterContextSP reg_ctx_sp (GetRegisterContext());
680 const addr_t thread_pc = reg_ctx_sp->GetPC();
681 BreakpointSiteSP bp_site_sp = GetProcess()->GetBreakpointSiteList().FindByAddress(thread_pc);
684 // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the target may not require anything
685 // special to step over a breakpoint.
687 ThreadPlan *cur_plan = GetCurrentPlan();
689 bool push_step_over_bp_plan = false;
690 if (cur_plan->GetKind() == ThreadPlan::eKindStepOverBreakpoint)
692 ThreadPlanStepOverBreakpoint *bp_plan = (ThreadPlanStepOverBreakpoint *)cur_plan;
693 if (bp_plan->GetBreakpointLoadAddress() != thread_pc)
694 push_step_over_bp_plan = true;
697 push_step_over_bp_plan = true;
699 if (push_step_over_bp_plan)
701 ThreadPlanSP step_bp_plan_sp (new ThreadPlanStepOverBreakpoint (*this));
705 step_bp_plan_sp->SetPrivate (true);
707 if (GetCurrentPlan()->RunState() != eStateStepping)
709 ThreadPlanStepOverBreakpoint *step_bp_plan
710 = static_cast<ThreadPlanStepOverBreakpoint *>(step_bp_plan_sp.get());
711 step_bp_plan->SetAutoContinue(true);
713 QueueThreadPlan (step_bp_plan_sp, false);
722 Thread::ShouldResume (StateType resume_state)
724 // At this point clear the completed plan stack.
725 m_completed_plan_stack.clear();
726 m_discarded_plan_stack.clear();
727 m_override_should_notify = eLazyBoolCalculate;
729 StateType prev_resume_state = GetTemporaryResumeState();
731 SetTemporaryResumeState(resume_state);
733 lldb::ThreadSP backing_thread_sp (GetBackingThread ());
734 if (backing_thread_sp)
735 backing_thread_sp->SetTemporaryResumeState(resume_state);
737 // Make sure m_stop_info_sp is valid. Don't do this for threads we suspended in the previous run.
738 if (prev_resume_state != eStateSuspended)
739 GetPrivateStopInfo();
741 // This is a little dubious, but we are trying to limit how often we actually fetch stop info from
742 // the target, 'cause that slows down single stepping. So assume that if we got to the point where
743 // we're about to resume, and we haven't yet had to fetch the stop reason, then it doesn't need to know
744 // about the fact that we are resuming...
745 const uint32_t process_stop_id = GetProcess()->GetStopID();
746 if (m_stop_info_stop_id == process_stop_id &&
747 (m_stop_info_sp && m_stop_info_sp->IsValid()))
749 StopInfo *stop_info = GetPrivateStopInfo().get();
751 stop_info->WillResume (resume_state);
754 // Tell all the plans that we are about to resume in case they need to clear any state.
755 // We distinguish between the plan on the top of the stack and the lower
756 // plans in case a plan needs to do any special business before it runs.
758 bool need_to_resume = false;
759 ThreadPlan *plan_ptr = GetCurrentPlan();
762 need_to_resume = plan_ptr->WillResume(resume_state, true);
764 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr)
766 plan_ptr->WillResume (resume_state, false);
769 // If the WillResume for the plan says we are faking a resume, then it will have set an appropriate stop info.
770 // In that case, don't reset it here.
772 if (need_to_resume && resume_state != eStateSuspended)
774 m_stop_info_sp.reset();
781 // Let Thread subclasses do any special work they need to prior to resuming
782 WillResume (resume_state);
785 return need_to_resume;
791 SetResumeSignal (LLDB_INVALID_SIGNAL_NUMBER);
797 SetState (eStateStopped);
801 Thread::ShouldStop (Event* event_ptr)
803 ThreadPlan *current_plan = GetCurrentPlan();
805 bool should_stop = true;
807 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
809 if (GetResumeState () == eStateSuspended)
812 log->Printf ("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", should_stop = 0 (ignore since thread was suspended)",
813 __FUNCTION__, GetID (), GetProtocolID());
817 if (GetTemporaryResumeState () == eStateSuspended)
820 log->Printf ("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", should_stop = 0 (ignore since thread was suspended)",
821 __FUNCTION__, GetID (), GetProtocolID());
825 // Based on the current thread plan and process stop info, check if this
826 // thread caused the process to stop. NOTE: this must take place before
827 // the plan is moved from the current plan stack to the completed plan
829 if (!ThreadStoppedForAReason())
832 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)",
833 __FUNCTION__, GetID (), GetProtocolID(),
834 GetRegisterContext() ? GetRegisterContext()->GetPC() : LLDB_INVALID_ADDRESS);
840 log->Printf ("Thread::%s(%p) for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", pc = 0x%16.16" PRIx64,
841 __FUNCTION__, static_cast<void*>(this), GetID (),
844 ? GetRegisterContext()->GetPC()
845 : LLDB_INVALID_ADDRESS);
846 log->Printf ("^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^");
850 log->Printf ("Plan stack initial state:\n%s", s.GetData());
853 // The top most plan always gets to do the trace log...
854 current_plan->DoTraceLog ();
856 // First query the stop info's ShouldStopSynchronous. This handles "synchronous" stop reasons, for example the breakpoint
857 // command on internal breakpoints. If a synchronous stop reason says we should not stop, then we don't have to
858 // do any more work on this stop.
859 StopInfoSP private_stop_info (GetPrivateStopInfo());
860 if (private_stop_info && !private_stop_info->ShouldStopSynchronous(event_ptr))
863 log->Printf ("StopInfo::ShouldStop async callback says we should not stop, returning ShouldStop of false.");
867 // If we've already been restarted, don't query the plans since the state they would examine is not current.
868 if (Process::ProcessEventData::GetRestartedFromEvent(event_ptr))
871 // Before the plans see the state of the world, calculate the current inlined depth.
872 GetStackFrameList()->CalculateCurrentInlinedDepth();
874 // If the base plan doesn't understand why we stopped, then we have to find a plan that does.
875 // If that plan is still working, then we don't need to do any more work. If the plan that explains
876 // the stop is done, then we should pop all the plans below it, and pop it, and then let the plans above it decide
877 // whether they still need to do more work.
879 bool done_processing_current_plan = false;
881 if (!current_plan->PlanExplainsStop(event_ptr))
883 if (current_plan->TracerExplainsStop())
885 done_processing_current_plan = true;
890 // If the current plan doesn't explain the stop, then find one that
891 // does and let it handle the situation.
892 ThreadPlan *plan_ptr = current_plan;
893 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr)
895 if (plan_ptr->PlanExplainsStop(event_ptr))
897 should_stop = plan_ptr->ShouldStop (event_ptr);
899 // plan_ptr explains the stop, next check whether plan_ptr is done, if so, then we should take it
900 // and all the plans below it off the stack.
902 if (plan_ptr->MischiefManaged())
904 // We're going to pop the plans up to and including the plan that explains the stop.
905 ThreadPlan *prev_plan_ptr = GetPreviousPlan (plan_ptr);
910 current_plan->WillStop();
913 while ((current_plan = GetCurrentPlan()) != prev_plan_ptr);
914 // Now, if the responsible plan was not "Okay to discard" then we're done,
915 // otherwise we forward this to the next plan in the stack below.
916 done_processing_current_plan = (plan_ptr->IsMasterPlan() && !plan_ptr->OkayToDiscard());
919 done_processing_current_plan = true;
927 if (!done_processing_current_plan)
929 bool over_ride_stop = current_plan->ShouldAutoContinue(event_ptr);
932 log->Printf("Plan %s explains stop, auto-continue %i.",
933 current_plan->GetName(), over_ride_stop);
935 // We're starting from the base plan, so just let it decide;
936 if (PlanIsBasePlan(current_plan))
938 should_stop = current_plan->ShouldStop (event_ptr);
940 log->Printf("Base plan says should stop: %i.", should_stop);
944 // Otherwise, don't let the base plan override what the other plans say to do, since
945 // presumably if there were other plans they would know what to do...
948 if (PlanIsBasePlan(current_plan))
951 should_stop = current_plan->ShouldStop(event_ptr);
953 log->Printf("Plan %s should stop: %d.",
954 current_plan->GetName(), should_stop);
955 if (current_plan->MischiefManaged())
958 current_plan->WillStop();
960 // If a Master Plan wants to stop, and wants to stick on the stack, we let it.
961 // Otherwise, see if the plan's parent wants to stop.
963 if (should_stop && current_plan->IsMasterPlan() && !current_plan->OkayToDiscard())
972 current_plan = GetCurrentPlan();
973 if (current_plan == nullptr)
990 // One other potential problem is that we set up a master plan, then stop in before it is complete - for instance
991 // by hitting a breakpoint during a step-over - then do some step/finish/etc operations that wind up
992 // past the end point condition of the initial plan. We don't want to strand the original plan on the stack,
993 // This code clears stale plans off the stack.
997 ThreadPlan *plan_ptr = GetCurrentPlan();
998 while (!PlanIsBasePlan(plan_ptr))
1000 bool stale = plan_ptr->IsPlanStale ();
1001 ThreadPlan *examined_plan = plan_ptr;
1002 plan_ptr = GetPreviousPlan (examined_plan);
1007 log->Printf("Plan %s being discarded in cleanup, it says it is already done.",
1008 examined_plan->GetName());
1009 DiscardThreadPlansUpToPlan(examined_plan);
1018 DumpThreadPlans(&s);
1019 log->Printf ("Plan stack final state:\n%s", s.GetData());
1020 log->Printf ("vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv", should_stop);
1026 Thread::ShouldReportStop (Event* event_ptr)
1028 StateType thread_state = GetResumeState ();
1029 StateType temp_thread_state = GetTemporaryResumeState();
1031 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1033 if (thread_state == eStateSuspended || thread_state == eStateInvalid)
1036 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (state was suspended or invalid)", GetID(), eVoteNoOpinion);
1037 return eVoteNoOpinion;
1040 if (temp_thread_state == eStateSuspended || temp_thread_state == eStateInvalid)
1043 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (temporary state was suspended or invalid)", GetID(), eVoteNoOpinion);
1044 return eVoteNoOpinion;
1047 if (!ThreadStoppedForAReason())
1050 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (thread didn't stop for a reason.)", GetID(), eVoteNoOpinion);
1051 return eVoteNoOpinion;
1054 if (m_completed_plan_stack.size() > 0)
1056 // Don't use GetCompletedPlan here, since that suppresses private plans.
1058 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote for complete stack's back plan", GetID());
1059 return m_completed_plan_stack.back()->ShouldReportStop (event_ptr);
1063 Vote thread_vote = eVoteNoOpinion;
1064 ThreadPlan *plan_ptr = GetCurrentPlan();
1067 if (plan_ptr->PlanExplainsStop(event_ptr))
1069 thread_vote = plan_ptr->ShouldReportStop(event_ptr);
1072 if (PlanIsBasePlan(plan_ptr))
1075 plan_ptr = GetPreviousPlan(plan_ptr);
1078 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i for current plan", GetID(), thread_vote);
1085 Thread::ShouldReportRun (Event* event_ptr)
1087 StateType thread_state = GetResumeState ();
1089 if (thread_state == eStateSuspended
1090 || thread_state == eStateInvalid)
1092 return eVoteNoOpinion;
1095 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1096 if (m_completed_plan_stack.size() > 0)
1098 // Don't use GetCompletedPlan here, since that suppresses private plans.
1100 log->Printf ("Current Plan for thread %d(%p) (0x%4.4" PRIx64 ", %s): %s being asked whether we should report run.",
1101 GetIndexID(), static_cast<void*>(this), GetID(),
1102 StateAsCString(GetTemporaryResumeState()),
1103 m_completed_plan_stack.back()->GetName());
1105 return m_completed_plan_stack.back()->ShouldReportRun (event_ptr);
1110 log->Printf ("Current Plan for thread %d(%p) (0x%4.4" PRIx64 ", %s): %s being asked whether we should report run.",
1111 GetIndexID(), static_cast<void*>(this), GetID(),
1112 StateAsCString(GetTemporaryResumeState()),
1113 GetCurrentPlan()->GetName());
1115 return GetCurrentPlan()->ShouldReportRun (event_ptr);
1120 Thread::MatchesSpec (const ThreadSpec *spec)
1122 return (spec == nullptr) ? true : spec->ThreadPassesBasicTests(*this);
1126 Thread::PushPlan (ThreadPlanSP &thread_plan_sp)
1130 // If the thread plan doesn't already have a tracer, give it its parent's tracer:
1131 if (!thread_plan_sp->GetThreadPlanTracer())
1132 thread_plan_sp->SetThreadPlanTracer(m_plan_stack.back()->GetThreadPlanTracer());
1133 m_plan_stack.push_back (thread_plan_sp);
1135 thread_plan_sp->DidPush();
1137 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1141 thread_plan_sp->GetDescription (&s, lldb::eDescriptionLevelFull);
1142 log->Printf("Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".",
1143 static_cast<void*>(this), s.GetData(),
1144 thread_plan_sp->GetThread().GetID());
1152 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1154 if (m_plan_stack.size() <= 1)
1158 ThreadPlanSP &plan = m_plan_stack.back();
1161 log->Printf("Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".", plan->GetName(), plan->GetThread().GetID());
1163 m_completed_plan_stack.push_back (plan);
1165 m_plan_stack.pop_back();
1170 Thread::DiscardPlan ()
1172 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1173 if (m_plan_stack.size() > 1)
1175 ThreadPlanSP &plan = m_plan_stack.back();
1177 log->Printf("Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".", plan->GetName(), plan->GetThread().GetID());
1179 m_discarded_plan_stack.push_back (plan);
1181 m_plan_stack.pop_back();
1186 Thread::GetCurrentPlan ()
1188 // There will always be at least the base plan. If somebody is mucking with a
1189 // thread with an empty plan stack, we should assert right away.
1190 return m_plan_stack.empty() ? nullptr : m_plan_stack.back().get();
1194 Thread::GetCompletedPlan ()
1196 ThreadPlanSP empty_plan_sp;
1197 if (!m_completed_plan_stack.empty())
1199 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1201 ThreadPlanSP completed_plan_sp;
1202 completed_plan_sp = m_completed_plan_stack[i];
1203 if (!completed_plan_sp->GetPrivate ())
1204 return completed_plan_sp;
1207 return empty_plan_sp;
1211 Thread::GetReturnValueObject ()
1213 if (!m_completed_plan_stack.empty())
1215 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1217 ValueObjectSP return_valobj_sp;
1218 return_valobj_sp = m_completed_plan_stack[i]->GetReturnValueObject();
1219 if (return_valobj_sp)
1220 return return_valobj_sp;
1223 return ValueObjectSP();
1226 ExpressionVariableSP
1227 Thread::GetExpressionVariable ()
1229 if (!m_completed_plan_stack.empty())
1231 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1233 ExpressionVariableSP expression_variable_sp;
1234 expression_variable_sp = m_completed_plan_stack[i]->GetExpressionVariable();
1235 if (expression_variable_sp)
1236 return expression_variable_sp;
1239 return ExpressionVariableSP();
1243 Thread::IsThreadPlanDone (ThreadPlan *plan)
1245 if (!m_completed_plan_stack.empty())
1247 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1249 if (m_completed_plan_stack[i].get() == plan)
1257 Thread::WasThreadPlanDiscarded (ThreadPlan *plan)
1259 if (!m_discarded_plan_stack.empty())
1261 for (int i = m_discarded_plan_stack.size() - 1; i >= 0; i--)
1263 if (m_discarded_plan_stack[i].get() == plan)
1271 Thread::GetPreviousPlan (ThreadPlan *current_plan)
1273 if (current_plan == nullptr)
1276 int stack_size = m_completed_plan_stack.size();
1277 for (int i = stack_size - 1; i > 0; i--)
1279 if (current_plan == m_completed_plan_stack[i].get())
1280 return m_completed_plan_stack[i-1].get();
1283 if (stack_size > 0 && m_completed_plan_stack[0].get() == current_plan)
1285 return GetCurrentPlan();
1288 stack_size = m_plan_stack.size();
1289 for (int i = stack_size - 1; i > 0; i--)
1291 if (current_plan == m_plan_stack[i].get())
1292 return m_plan_stack[i-1].get();
1298 Thread::QueueThreadPlan (ThreadPlanSP &thread_plan_sp, bool abort_other_plans)
1300 if (abort_other_plans)
1301 DiscardThreadPlans(true);
1303 PushPlan (thread_plan_sp);
1307 Thread::EnableTracer (bool value, bool single_stepping)
1309 int stack_size = m_plan_stack.size();
1310 for (int i = 0; i < stack_size; i++)
1312 if (m_plan_stack[i]->GetThreadPlanTracer())
1314 m_plan_stack[i]->GetThreadPlanTracer()->EnableTracing(value);
1315 m_plan_stack[i]->GetThreadPlanTracer()->EnableSingleStep(single_stepping);
1321 Thread::SetTracer (lldb::ThreadPlanTracerSP &tracer_sp)
1323 int stack_size = m_plan_stack.size();
1324 for (int i = 0; i < stack_size; i++)
1325 m_plan_stack[i]->SetThreadPlanTracer(tracer_sp);
1329 Thread::DiscardUserThreadPlansUpToIndex (uint32_t thread_index)
1331 // Count the user thread plans from the back end to get the number of the one we want
1335 ThreadPlan *up_to_plan_ptr = nullptr;
1337 for (ThreadPlanSP plan_sp : m_plan_stack)
1339 if (plan_sp->GetPrivate())
1341 if (idx == thread_index)
1343 up_to_plan_ptr = plan_sp.get();
1350 if (up_to_plan_ptr == nullptr)
1353 DiscardThreadPlansUpToPlan(up_to_plan_ptr);
1358 Thread::DiscardThreadPlansUpToPlan (lldb::ThreadPlanSP &up_to_plan_sp)
1360 DiscardThreadPlansUpToPlan (up_to_plan_sp.get());
1364 Thread::DiscardThreadPlansUpToPlan (ThreadPlan *up_to_plan_ptr)
1366 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1368 log->Printf("Discarding thread plans for thread tid = 0x%4.4" PRIx64 ", up to %p",
1369 GetID(), static_cast<void*>(up_to_plan_ptr));
1371 int stack_size = m_plan_stack.size();
1373 // If the input plan is nullptr, discard all plans. Otherwise make sure this plan is in the
1374 // stack, and if so discard up to and including it.
1376 if (up_to_plan_ptr == nullptr)
1378 for (int i = stack_size - 1; i > 0; i--)
1383 bool found_it = false;
1384 for (int i = stack_size - 1; i > 0; i--)
1386 if (m_plan_stack[i].get() == up_to_plan_ptr)
1391 bool last_one = false;
1392 for (int i = stack_size - 1; i > 0 && !last_one ; i--)
1394 if (GetCurrentPlan() == up_to_plan_ptr)
1403 Thread::DiscardThreadPlans(bool force)
1405 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1408 log->Printf("Discarding thread plans for thread (tid = 0x%4.4" PRIx64 ", force %d)", GetID(), force);
1413 int stack_size = m_plan_stack.size();
1414 for (int i = stack_size - 1; i > 0; i--)
1423 int master_plan_idx;
1424 bool discard = true;
1426 // Find the first master plan, see if it wants discarding, and if yes discard up to it.
1427 for (master_plan_idx = m_plan_stack.size() - 1; master_plan_idx >= 0; master_plan_idx--)
1429 if (m_plan_stack[master_plan_idx]->IsMasterPlan())
1431 discard = m_plan_stack[master_plan_idx]->OkayToDiscard();
1438 // First pop all the dependent plans:
1439 for (int i = m_plan_stack.size() - 1; i > master_plan_idx; i--)
1441 // FIXME: Do we need a finalize here, or is the rule that "PrepareForStop"
1442 // for the plan leaves it in a state that it is safe to pop the plan
1443 // with no more notice?
1447 // Now discard the master plan itself.
1448 // The bottom-most plan never gets discarded. "OkayToDiscard" for it means
1449 // discard it's dependent plans, but not it...
1450 if (master_plan_idx > 0)
1457 // If the master plan doesn't want to get discarded, then we're done.
1464 Thread::PlanIsBasePlan (ThreadPlan *plan_ptr)
1466 if (plan_ptr->IsBasePlan())
1468 else if (m_plan_stack.size() == 0)
1471 return m_plan_stack[0].get() == plan_ptr;
1475 Thread::UnwindInnermostExpression()
1478 int stack_size = m_plan_stack.size();
1480 // If the input plan is nullptr, discard all plans. Otherwise make sure this plan is in the
1481 // stack, and if so discard up to and including it.
1483 for (int i = stack_size - 1; i > 0; i--)
1485 if (m_plan_stack[i]->GetKind() == ThreadPlan::eKindCallFunction)
1487 DiscardThreadPlansUpToPlan(m_plan_stack[i].get());
1491 error.SetErrorString("No expressions currently active on this thread");
1496 Thread::QueueFundamentalPlan (bool abort_other_plans)
1498 ThreadPlanSP thread_plan_sp (new ThreadPlanBase(*this));
1499 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1500 return thread_plan_sp;
1504 Thread::QueueThreadPlanForStepSingleInstruction(bool step_over,
1505 bool abort_other_plans,
1506 bool stop_other_threads)
1508 ThreadPlanSP thread_plan_sp (new ThreadPlanStepInstruction (*this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
1509 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1510 return thread_plan_sp;
1514 Thread::QueueThreadPlanForStepOverRange(bool abort_other_plans,
1515 const AddressRange &range,
1516 const SymbolContext &addr_context,
1517 lldb::RunMode stop_other_threads,
1518 LazyBool step_out_avoids_code_withoug_debug_info)
1520 ThreadPlanSP thread_plan_sp;
1521 thread_plan_sp.reset (new ThreadPlanStepOverRange (*this, range, addr_context, stop_other_threads, step_out_avoids_code_withoug_debug_info));
1523 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1524 return thread_plan_sp;
1527 // Call the QueueThreadPlanForStepOverRange method which takes an address range.
1529 Thread::QueueThreadPlanForStepOverRange(bool abort_other_plans,
1530 const LineEntry &line_entry,
1531 const SymbolContext &addr_context,
1532 lldb::RunMode stop_other_threads,
1533 LazyBool step_out_avoids_code_withoug_debug_info)
1535 return QueueThreadPlanForStepOverRange (abort_other_plans,
1536 line_entry.GetSameLineContiguousAddressRange(),
1539 step_out_avoids_code_withoug_debug_info);
1543 Thread::QueueThreadPlanForStepInRange(bool abort_other_plans,
1544 const AddressRange &range,
1545 const SymbolContext &addr_context,
1546 const char *step_in_target,
1547 lldb::RunMode stop_other_threads,
1548 LazyBool step_in_avoids_code_without_debug_info,
1549 LazyBool step_out_avoids_code_without_debug_info)
1551 ThreadPlanSP thread_plan_sp (new ThreadPlanStepInRange (*this,
1555 step_in_avoids_code_without_debug_info,
1556 step_out_avoids_code_without_debug_info));
1557 ThreadPlanStepInRange *plan = static_cast<ThreadPlanStepInRange *>(thread_plan_sp.get());
1560 plan->SetStepInTarget(step_in_target);
1562 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1563 return thread_plan_sp;
1566 // Call the QueueThreadPlanForStepInRange method which takes an address range.
1568 Thread::QueueThreadPlanForStepInRange(bool abort_other_plans,
1569 const LineEntry &line_entry,
1570 const SymbolContext &addr_context,
1571 const char *step_in_target,
1572 lldb::RunMode stop_other_threads,
1573 LazyBool step_in_avoids_code_without_debug_info,
1574 LazyBool step_out_avoids_code_without_debug_info)
1576 return QueueThreadPlanForStepInRange (abort_other_plans,
1577 line_entry.GetSameLineContiguousAddressRange(),
1581 step_in_avoids_code_without_debug_info,
1582 step_out_avoids_code_without_debug_info);
1587 Thread::QueueThreadPlanForStepOut(bool abort_other_plans,
1588 SymbolContext *addr_context,
1590 bool stop_other_threads,
1594 LazyBool step_out_avoids_code_without_debug_info)
1596 ThreadPlanSP thread_plan_sp (new ThreadPlanStepOut (*this,
1603 step_out_avoids_code_without_debug_info));
1605 if (thread_plan_sp->ValidatePlan(nullptr))
1607 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1608 return thread_plan_sp;
1612 return ThreadPlanSP();
1617 Thread::QueueThreadPlanForStepOutNoShouldStop(bool abort_other_plans,
1618 SymbolContext *addr_context,
1620 bool stop_other_threads,
1624 bool continue_to_next_branch)
1626 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut (*this,
1634 continue_to_next_branch));
1636 ThreadPlanStepOut *new_plan = static_cast<ThreadPlanStepOut *>(thread_plan_sp.get());
1637 new_plan->ClearShouldStopHereCallbacks();
1639 if (thread_plan_sp->ValidatePlan(nullptr))
1641 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1642 return thread_plan_sp;
1646 return ThreadPlanSP();
1651 Thread::QueueThreadPlanForStepThrough (StackID &return_stack_id, bool abort_other_plans, bool stop_other_threads)
1653 ThreadPlanSP thread_plan_sp(new ThreadPlanStepThrough (*this, return_stack_id, stop_other_threads));
1654 if (!thread_plan_sp || !thread_plan_sp->ValidatePlan(nullptr))
1655 return ThreadPlanSP();
1657 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1658 return thread_plan_sp;
1662 Thread::QueueThreadPlanForRunToAddress (bool abort_other_plans,
1663 Address &target_addr,
1664 bool stop_other_threads)
1666 ThreadPlanSP thread_plan_sp (new ThreadPlanRunToAddress (*this, target_addr, stop_other_threads));
1667 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1668 return thread_plan_sp;
1672 Thread::QueueThreadPlanForStepUntil (bool abort_other_plans,
1673 lldb::addr_t *address_list,
1674 size_t num_addresses,
1675 bool stop_other_threads,
1678 ThreadPlanSP thread_plan_sp (new ThreadPlanStepUntil (*this, address_list, num_addresses, stop_other_threads, frame_idx));
1679 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1680 return thread_plan_sp;
1685 Thread::QueueThreadPlanForStepScripted (bool abort_other_plans,
1686 const char *class_name,
1687 bool stop_other_threads)
1689 ThreadPlanSP thread_plan_sp (new ThreadPlanPython (*this, class_name));
1690 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1691 // This seems a little funny, but I don't want to have to split up the constructor and the
1692 // DidPush in the scripted plan, that seems annoying.
1693 // That means the constructor has to be in DidPush.
1694 // So I have to validate the plan AFTER pushing it, and then take it off again...
1695 if (!thread_plan_sp->ValidatePlan(nullptr))
1697 DiscardThreadPlansUpToPlan(thread_plan_sp);
1698 return ThreadPlanSP();
1701 return thread_plan_sp;
1705 Thread::GetIndexID () const
1711 PrintPlanElement (Stream *s, const ThreadPlanSP &plan, lldb::DescriptionLevel desc_level, int32_t elem_idx)
1715 s->Printf ("Element %d: ", elem_idx);
1716 plan->GetDescription (s, desc_level);
1722 PrintPlanStack (Stream *s, const std::vector<lldb::ThreadPlanSP> &plan_stack, lldb::DescriptionLevel desc_level, bool include_internal)
1724 int32_t print_idx = 0;
1725 for (ThreadPlanSP plan_sp : plan_stack)
1727 if (include_internal || !plan_sp->GetPrivate())
1729 PrintPlanElement (s, plan_sp, desc_level, print_idx++);
1735 Thread::DumpThreadPlans (Stream *s,
1736 lldb::DescriptionLevel desc_level,
1737 bool include_internal,
1738 bool ignore_boring_threads) const
1740 uint32_t stack_size;
1742 if (ignore_boring_threads)
1744 uint32_t stack_size = m_plan_stack.size();
1745 uint32_t completed_stack_size = m_completed_plan_stack.size();
1746 uint32_t discarded_stack_size = m_discarded_plan_stack.size();
1747 if (stack_size == 1 && completed_stack_size == 0 && discarded_stack_size == 0)
1749 s->Printf ("thread #%u: tid = 0x%4.4" PRIx64 "\n", GetIndexID(), GetID());
1752 s->Printf("No active thread plans\n");
1759 s->Printf ("thread #%u: tid = 0x%4.4" PRIx64 ":\n", GetIndexID(), GetID());
1762 s->Printf ("Active plan stack:\n");
1763 PrintPlanStack (s, m_plan_stack, desc_level, include_internal);
1765 stack_size = m_completed_plan_stack.size();
1769 s->Printf ("Completed Plan Stack:\n");
1770 PrintPlanStack (s, m_completed_plan_stack, desc_level, include_internal);
1773 stack_size = m_discarded_plan_stack.size();
1777 s->Printf ("Discarded Plan Stack:\n");
1778 PrintPlanStack (s, m_discarded_plan_stack, desc_level, include_internal);
1785 Thread::CalculateTarget ()
1788 ProcessSP process_sp(GetProcess());
1790 target_sp = process_sp->CalculateTarget();
1795 Thread::CalculateProcess ()
1797 return GetProcess();
1801 Thread::CalculateThread ()
1803 return shared_from_this();
1807 Thread::CalculateStackFrame ()
1809 return StackFrameSP();
1813 Thread::CalculateExecutionContext (ExecutionContext &exe_ctx)
1815 exe_ctx.SetContext (shared_from_this());
1819 Thread::GetStackFrameList ()
1821 StackFrameListSP frame_list_sp;
1822 Mutex::Locker locker(m_frame_mutex);
1823 if (m_curr_frames_sp)
1825 frame_list_sp = m_curr_frames_sp;
1829 frame_list_sp.reset(new StackFrameList (*this, m_prev_frames_sp, true));
1830 m_curr_frames_sp = frame_list_sp;
1832 return frame_list_sp;
1836 Thread::ClearStackFrames ()
1838 Mutex::Locker locker(m_frame_mutex);
1840 Unwind *unwinder = GetUnwinder ();
1844 // Only store away the old "reference" StackFrameList if we got all its frames:
1845 // FIXME: At some point we can try to splice in the frames we have fetched into
1846 // the new frame as we make it, but let's not try that now.
1847 if (m_curr_frames_sp && m_curr_frames_sp->GetAllFramesFetched())
1848 m_prev_frames_sp.swap (m_curr_frames_sp);
1849 m_curr_frames_sp.reset();
1851 m_extended_info.reset();
1852 m_extended_info_fetched = false;
1856 Thread::GetFrameWithConcreteFrameIndex (uint32_t unwind_idx)
1858 return GetStackFrameList()->GetFrameWithConcreteFrameIndex (unwind_idx);
1862 Thread::ReturnFromFrameWithIndex (uint32_t frame_idx, lldb::ValueObjectSP return_value_sp, bool broadcast)
1864 StackFrameSP frame_sp = GetStackFrameAtIndex (frame_idx);
1869 return_error.SetErrorStringWithFormat("Could not find frame with index %d in thread 0x%" PRIx64 ".", frame_idx, GetID());
1872 return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
1876 Thread::ReturnFromFrame (lldb::StackFrameSP frame_sp, lldb::ValueObjectSP return_value_sp, bool broadcast)
1882 return_error.SetErrorString("Can't return to a null frame.");
1883 return return_error;
1886 Thread *thread = frame_sp->GetThread().get();
1887 uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
1888 StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
1889 if (!older_frame_sp)
1891 return_error.SetErrorString("No older frame to return to.");
1892 return return_error;
1895 if (return_value_sp)
1897 lldb::ABISP abi = thread->GetProcess()->GetABI();
1900 return_error.SetErrorString("Could not find ABI to set return value.");
1901 return return_error;
1903 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
1905 // FIXME: ValueObject::Cast doesn't currently work correctly, at least not for scalars.
1906 // Turn that back on when that works.
1907 if (/* DISABLES CODE */ (0) && sc.function != nullptr)
1909 Type *function_type = sc.function->GetType();
1912 CompilerType return_type = sc.function->GetCompilerType().GetFunctionReturnType();
1916 return_type.DumpTypeDescription(&s);
1917 ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type);
1920 cast_value_sp->SetFormat(eFormatHex);
1921 return_value_sp = cast_value_sp;
1927 return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
1928 if (!return_error.Success())
1929 return return_error;
1932 // Now write the return registers for the chosen frame:
1933 // Note, we can't use ReadAllRegisterValues->WriteAllRegisterValues, since the read & write
1936 StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);
1937 if (youngest_frame_sp)
1939 lldb::RegisterContextSP reg_ctx_sp (youngest_frame_sp->GetRegisterContext());
1942 bool copy_success = reg_ctx_sp->CopyFromRegisterContext(older_frame_sp->GetRegisterContext());
1945 thread->DiscardThreadPlans(true);
1946 thread->ClearStackFrames();
1947 if (broadcast && EventTypeHasListeners(eBroadcastBitStackChanged))
1948 BroadcastEvent(eBroadcastBitStackChanged, new ThreadEventData (this->shared_from_this()));
1952 return_error.SetErrorString("Could not reset register values.");
1957 return_error.SetErrorString("Frame has no register context.");
1962 return_error.SetErrorString("Returned past top frame.");
1964 return return_error;
1967 static void DumpAddressList (Stream &s, const std::vector<Address> &list, ExecutionContextScope *exe_scope)
1969 for (size_t n=0;n<list.size();n++)
1972 list[n].Dump (&s, exe_scope, Address::DumpStyleResolvedDescription, Address::DumpStyleSectionNameOffset);
1978 Thread::JumpToLine (const FileSpec &file, uint32_t line, bool can_leave_function, std::string *warnings)
1980 ExecutionContext exe_ctx (GetStackFrameAtIndex(0));
1981 Target *target = exe_ctx.GetTargetPtr();
1982 TargetSP target_sp = exe_ctx.GetTargetSP();
1983 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1984 StackFrame *frame = exe_ctx.GetFramePtr();
1985 const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction);
1987 // Find candidate locations.
1988 std::vector<Address> candidates, within_function, outside_function;
1989 target->GetImages().FindAddressesForLine (target_sp, file, line, sc.function, within_function, outside_function);
1991 // If possible, we try and stay within the current function.
1992 // Within a function, we accept multiple locations (optimized code may do this,
1993 // there's no solution here so we do the best we can).
1994 // However if we're trying to leave the function, we don't know how to pick the
1995 // right location, so if there's more than one then we bail.
1996 if (!within_function.empty())
1997 candidates = within_function;
1998 else if (outside_function.size() == 1 && can_leave_function)
1999 candidates = outside_function;
2001 // Check if we got anything.
2002 if (candidates.empty())
2004 if (outside_function.empty())
2006 return Error("Cannot locate an address for %s:%i.",
2007 file.GetFilename().AsCString(), line);
2009 else if (outside_function.size() == 1)
2011 return Error("%s:%i is outside the current function.",
2012 file.GetFilename().AsCString(), line);
2017 DumpAddressList(sstr, outside_function, target);
2018 return Error("%s:%i has multiple candidate locations:\n%s",
2019 file.GetFilename().AsCString(), line, sstr.GetString().c_str());
2023 // Accept the first location, warn about any others.
2024 Address dest = candidates[0];
2025 if (warnings && candidates.size() > 1)
2028 sstr.Printf("%s:%i appears multiple times in this function, selecting the first location:\n",
2029 file.GetFilename().AsCString(), line);
2030 DumpAddressList(sstr, candidates, target);
2031 *warnings = sstr.GetString();
2034 if (!reg_ctx->SetPC (dest))
2035 return Error("Cannot change PC to target address.");
2041 Thread::DumpUsingSettingsFormat (Stream &strm, uint32_t frame_idx)
2043 ExecutionContext exe_ctx (shared_from_this());
2044 Process *process = exe_ctx.GetProcessPtr();
2045 if (process == nullptr)
2048 StackFrameSP frame_sp;
2049 SymbolContext frame_sc;
2050 if (frame_idx != LLDB_INVALID_FRAME_ID)
2052 frame_sp = GetStackFrameAtIndex (frame_idx);
2055 exe_ctx.SetFrameSP(frame_sp);
2056 frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
2060 const FormatEntity::Entry *thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
2061 assert (thread_format);
2063 FormatEntity::Format(*thread_format,
2065 frame_sp ? &frame_sc : nullptr,
2074 Thread::SettingsInitialize ()
2079 Thread::SettingsTerminate ()
2084 Thread::GetThreadPointer ()
2086 return LLDB_INVALID_ADDRESS;
2090 Thread::GetThreadLocalData (const ModuleSP module)
2092 // The default implementation is to ask the dynamic loader for it.
2093 // This can be overridden for specific platforms.
2094 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
2096 return loader->GetThreadLocalData (module, shared_from_this());
2098 return LLDB_INVALID_ADDRESS;
2102 Thread::SafeToCallFunctions ()
2104 Process *process = GetProcess().get();
2107 SystemRuntime *runtime = process->GetSystemRuntime ();
2110 return runtime->SafeToCallFunctionsOnThisThread (shared_from_this());
2117 Thread::GetStackFrameSPForStackFramePtr (StackFrame *stack_frame_ptr)
2119 return GetStackFrameList()->GetStackFrameSPForStackFramePtr (stack_frame_ptr);
2123 Thread::StopReasonAsCString (lldb::StopReason reason)
2127 case eStopReasonInvalid: return "invalid";
2128 case eStopReasonNone: return "none";
2129 case eStopReasonTrace: return "trace";
2130 case eStopReasonBreakpoint: return "breakpoint";
2131 case eStopReasonWatchpoint: return "watchpoint";
2132 case eStopReasonSignal: return "signal";
2133 case eStopReasonException: return "exception";
2134 case eStopReasonExec: return "exec";
2135 case eStopReasonPlanComplete: return "plan complete";
2136 case eStopReasonThreadExiting: return "thread exiting";
2137 case eStopReasonInstrumentation: return "instrumentation break";
2140 static char unknown_state_string[64];
2141 snprintf(unknown_state_string, sizeof (unknown_state_string), "StopReason = %i", reason);
2142 return unknown_state_string;
2146 Thread::RunModeAsCString (lldb::RunMode mode)
2150 case eOnlyThisThread: return "only this thread";
2151 case eAllThreads: return "all threads";
2152 case eOnlyDuringStepping: return "only during stepping";
2155 static char unknown_state_string[64];
2156 snprintf(unknown_state_string, sizeof (unknown_state_string), "RunMode = %i", mode);
2157 return unknown_state_string;
2161 Thread::GetStatus (Stream &strm, uint32_t start_frame, uint32_t num_frames, uint32_t num_frames_with_source)
2163 ExecutionContext exe_ctx (shared_from_this());
2164 Target *target = exe_ctx.GetTargetPtr();
2165 Process *process = exe_ctx.GetProcessPtr();
2166 size_t num_frames_shown = 0;
2168 bool is_selected = false;
2171 if (process->GetThreadList().GetSelectedThread().get() == this)
2174 strm.Printf("%c ", is_selected ? '*' : ' ');
2175 if (target && target->GetDebugger().GetUseExternalEditor())
2177 StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
2180 SymbolContext frame_sc(frame_sp->GetSymbolContext (eSymbolContextLineEntry));
2181 if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file)
2183 Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line);
2188 DumpUsingSettingsFormat (strm, start_frame);
2194 const bool show_frame_info = true;
2196 const char *selected_frame_marker = nullptr;
2197 if (num_frames == 1 || (GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID()))
2200 selected_frame_marker = "* ";
2202 num_frames_shown = GetStackFrameList ()->GetStatus (strm,
2206 num_frames_with_source,
2207 selected_frame_marker);
2208 if (num_frames == 1)
2212 return num_frames_shown;
2216 Thread::GetDescription (Stream &strm, lldb::DescriptionLevel level, bool print_json_thread, bool print_json_stopinfo)
2218 DumpUsingSettingsFormat (strm, 0);
2221 StructuredData::ObjectSP thread_info = GetExtendedInfo();
2223 if (print_json_thread || print_json_stopinfo)
2225 if (thread_info && print_json_thread)
2227 thread_info->Dump (strm);
2231 if (print_json_stopinfo && m_stop_info_sp)
2233 StructuredData::ObjectSP stop_info = m_stop_info_sp->GetExtendedInfo();
2236 stop_info->Dump (strm);
2246 StructuredData::ObjectSP activity = thread_info->GetObjectForDotSeparatedPath("activity");
2247 StructuredData::ObjectSP breadcrumb = thread_info->GetObjectForDotSeparatedPath("breadcrumb");
2248 StructuredData::ObjectSP messages = thread_info->GetObjectForDotSeparatedPath("trace_messages");
2250 bool printed_activity = false;
2251 if (activity && activity->GetType() == StructuredData::Type::eTypeDictionary)
2253 StructuredData::Dictionary *activity_dict = activity->GetAsDictionary();
2254 StructuredData::ObjectSP id = activity_dict->GetValueForKey("id");
2255 StructuredData::ObjectSP name = activity_dict->GetValueForKey("name");
2256 if (name && name->GetType() == StructuredData::Type::eTypeString
2257 && id && id->GetType() == StructuredData::Type::eTypeInteger)
2259 strm.Printf(" Activity '%s', 0x%" PRIx64 "\n", name->GetAsString()->GetValue().c_str(), id->GetAsInteger()->GetValue());
2261 printed_activity = true;
2263 bool printed_breadcrumb = false;
2264 if (breadcrumb && breadcrumb->GetType() == StructuredData::Type::eTypeDictionary)
2266 if (printed_activity)
2268 StructuredData::Dictionary *breadcrumb_dict = breadcrumb->GetAsDictionary();
2269 StructuredData::ObjectSP breadcrumb_text = breadcrumb_dict->GetValueForKey ("name");
2270 if (breadcrumb_text && breadcrumb_text->GetType() == StructuredData::Type::eTypeString)
2272 strm.Printf (" Current Breadcrumb: %s\n", breadcrumb_text->GetAsString()->GetValue().c_str());
2274 printed_breadcrumb = true;
2276 if (messages && messages->GetType() == StructuredData::Type::eTypeArray)
2278 if (printed_breadcrumb)
2280 StructuredData::Array *messages_array = messages->GetAsArray();
2281 const size_t msg_count = messages_array->GetSize();
2284 strm.Printf (" %zu trace messages:\n", msg_count);
2285 for (size_t i = 0; i < msg_count; i++)
2287 StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i);
2288 if (message && message->GetType() == StructuredData::Type::eTypeDictionary)
2290 StructuredData::Dictionary *message_dict = message->GetAsDictionary();
2291 StructuredData::ObjectSP message_text = message_dict->GetValueForKey ("message");
2292 if (message_text && message_text->GetType() == StructuredData::Type::eTypeString)
2294 strm.Printf (" %s\n", message_text->GetAsString()->GetValue().c_str());
2306 Thread::GetStackFrameStatus (Stream& strm,
2307 uint32_t first_frame,
2308 uint32_t num_frames,
2309 bool show_frame_info,
2310 uint32_t num_frames_with_source)
2312 return GetStackFrameList()->GetStatus (strm,
2316 num_frames_with_source);
2320 Thread::GetUnwinder ()
2324 const ArchSpec target_arch (CalculateTarget()->GetArchitecture ());
2325 const llvm::Triple::ArchType machine = target_arch.GetMachine();
2328 case llvm::Triple::x86_64:
2329 case llvm::Triple::x86:
2330 case llvm::Triple::arm:
2331 case llvm::Triple::aarch64:
2332 case llvm::Triple::thumb:
2333 case llvm::Triple::mips:
2334 case llvm::Triple::mipsel:
2335 case llvm::Triple::mips64:
2336 case llvm::Triple::mips64el:
2337 case llvm::Triple::ppc:
2338 case llvm::Triple::ppc64:
2339 case llvm::Triple::hexagon:
2340 m_unwinder_ap.reset (new UnwindLLDB (*this));
2344 if (target_arch.GetTriple().getVendor() == llvm::Triple::Apple)
2345 m_unwinder_ap.reset (new UnwindMacOSXFrameBackchain (*this));
2349 return m_unwinder_ap.get();
2355 ClearStackFrames ();
2356 m_reg_context_sp.reset();
2360 Thread::IsStillAtLastBreakpointHit ()
2362 // If we are currently stopped at a breakpoint, always return that stopinfo and don't reset it.
2363 // This allows threads to maintain their breakpoint stopinfo, such as when thread-stepping in
2364 // multithreaded programs.
2365 if (m_stop_info_sp) {
2366 StopReason stop_reason = m_stop_info_sp->GetStopReason();
2367 if (stop_reason == lldb::eStopReasonBreakpoint) {
2368 uint64_t value = m_stop_info_sp->GetValue();
2369 lldb::RegisterContextSP reg_ctx_sp (GetRegisterContext());
2372 lldb::addr_t pc = reg_ctx_sp->GetPC();
2373 BreakpointSiteSP bp_site_sp = GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2375 static_cast<break_id_t>(value) == bp_site_sp->GetID())
2384 Thread::StepIn (bool source_step,
2385 LazyBool step_in_avoids_code_without_debug_info,
2386 LazyBool step_out_avoids_code_without_debug_info)
2390 Process *process = GetProcess().get();
2391 if (StateIsStoppedState (process->GetState(), true))
2393 StackFrameSP frame_sp = GetStackFrameAtIndex (0);
2394 ThreadPlanSP new_plan_sp;
2395 const lldb::RunMode run_mode = eOnlyThisThread;
2396 const bool abort_other_plans = false;
2398 if (source_step && frame_sp && frame_sp->HasDebugInformation ())
2400 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2401 new_plan_sp = QueueThreadPlanForStepInRange(abort_other_plans,
2406 step_in_avoids_code_without_debug_info,
2407 step_out_avoids_code_without_debug_info);
2411 new_plan_sp = QueueThreadPlanForStepSingleInstruction (false,
2416 new_plan_sp->SetIsMasterPlan(true);
2417 new_plan_sp->SetOkayToDiscard(false);
2419 // Why do we need to set the current thread by ID here???
2420 process->GetThreadList().SetSelectedThreadByID (GetID());
2421 error = process->Resume();
2425 error.SetErrorString("process not stopped");
2431 Thread::StepOver (bool source_step,
2432 LazyBool step_out_avoids_code_without_debug_info)
2435 Process *process = GetProcess().get();
2436 if (StateIsStoppedState (process->GetState(), true))
2438 StackFrameSP frame_sp = GetStackFrameAtIndex (0);
2439 ThreadPlanSP new_plan_sp;
2441 const lldb::RunMode run_mode = eOnlyThisThread;
2442 const bool abort_other_plans = false;
2444 if (source_step && frame_sp && frame_sp->HasDebugInformation ())
2446 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2447 new_plan_sp = QueueThreadPlanForStepOverRange (abort_other_plans,
2451 step_out_avoids_code_without_debug_info);
2455 new_plan_sp = QueueThreadPlanForStepSingleInstruction (true,
2460 new_plan_sp->SetIsMasterPlan(true);
2461 new_plan_sp->SetOkayToDiscard(false);
2463 // Why do we need to set the current thread by ID here???
2464 process->GetThreadList().SetSelectedThreadByID (GetID());
2465 error = process->Resume();
2469 error.SetErrorString("process not stopped");
2478 Process *process = GetProcess().get();
2479 if (StateIsStoppedState (process->GetState(), true))
2481 const bool first_instruction = false;
2482 const bool stop_other_threads = false;
2483 const bool abort_other_plans = false;
2485 ThreadPlanSP new_plan_sp(QueueThreadPlanForStepOut(abort_other_plans,
2493 new_plan_sp->SetIsMasterPlan(true);
2494 new_plan_sp->SetOkayToDiscard(false);
2496 // Why do we need to set the current thread by ID here???
2497 process->GetThreadList().SetSelectedThreadByID (GetID());
2498 error = process->Resume();
2502 error.SetErrorString("process not stopped");