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 //===----------------------------------------------------------------------===//
10 #include "lldb/lldb-python.h"
12 #include "lldb/lldb-private-log.h"
13 #include "lldb/Breakpoint/BreakpointLocation.h"
14 #include "lldb/Core/Debugger.h"
15 #include "lldb/Core/Log.h"
16 #include "lldb/Core/State.h"
17 #include "lldb/Core/Stream.h"
18 #include "lldb/Core/StreamString.h"
19 #include "lldb/Core/RegularExpression.h"
20 #include "lldb/Host/Host.h"
21 #include "lldb/Interpreter/OptionValueFileSpecList.h"
22 #include "lldb/Symbol/Function.h"
23 #include "lldb/Target/DynamicLoader.h"
24 #include "lldb/Target/ExecutionContext.h"
25 #include "lldb/Target/ObjCLanguageRuntime.h"
26 #include "lldb/Target/Process.h"
27 #include "lldb/Target/RegisterContext.h"
28 #include "lldb/Target/StopInfo.h"
29 #include "lldb/Target/SystemRuntime.h"
30 #include "lldb/Target/Target.h"
31 #include "lldb/Target/Thread.h"
32 #include "lldb/Target/ThreadPlan.h"
33 #include "lldb/Target/ThreadPlanCallFunction.h"
34 #include "lldb/Target/ThreadPlanBase.h"
35 #include "lldb/Target/ThreadPlanStepInstruction.h"
36 #include "lldb/Target/ThreadPlanStepOut.h"
37 #include "lldb/Target/ThreadPlanStepOverBreakpoint.h"
38 #include "lldb/Target/ThreadPlanStepThrough.h"
39 #include "lldb/Target/ThreadPlanStepInRange.h"
40 #include "lldb/Target/ThreadPlanStepOverRange.h"
41 #include "lldb/Target/ThreadPlanRunToAddress.h"
42 #include "lldb/Target/ThreadPlanStepUntil.h"
43 #include "lldb/Target/ThreadSpec.h"
44 #include "lldb/Target/Unwind.h"
45 #include "Plugins/Process/Utility/UnwindLLDB.h"
46 #include "UnwindMacOSXFrameBackchain.h"
50 using namespace lldb_private;
53 const ThreadPropertiesSP &
54 Thread::GetGlobalProperties()
56 static ThreadPropertiesSP g_settings_sp;
58 g_settings_sp.reset (new ThreadProperties (true));
62 static PropertyDefinition
65 { "step-in-avoid-nodebug", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, step-in will not stop in functions with no debug information." },
66 { "step-out-avoid-nodebug", OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, when step-in/step-out/step-over leave the current frame, they will continue to step out till they come to a function with "
67 "debug information. Passing a frame argument to step-out will override this option." },
68 { "step-avoid-regexp", OptionValue::eTypeRegex , true , REG_EXTENDED, "^std::", NULL, "A regular expression defining functions step-in won't stop in." },
69 { "step-avoid-libraries", OptionValue::eTypeFileSpecList , true , REG_EXTENDED, NULL, NULL, "A list of libraries that source stepping won't stop in." },
70 { "trace-thread", OptionValue::eTypeBoolean, false, false, NULL, NULL, "If true, this thread will single-step and log execution." },
71 { NULL , OptionValue::eTypeInvalid, false, 0 , NULL, NULL, NULL }
75 ePropertyStepInAvoidsNoDebug,
76 ePropertyStepOutAvoidsNoDebug,
77 ePropertyStepAvoidRegex,
78 ePropertyStepAvoidLibraries,
79 ePropertyEnableThreadTrace
83 class ThreadOptionValueProperties : public OptionValueProperties
86 ThreadOptionValueProperties (const ConstString &name) :
87 OptionValueProperties (name)
91 // This constructor is used when creating ThreadOptionValueProperties when it
92 // is part of a new lldb_private::Thread instance. It will copy all current
93 // global property values as needed
94 ThreadOptionValueProperties (ThreadProperties *global_properties) :
95 OptionValueProperties(*global_properties->GetValueProperties())
99 virtual const Property *
100 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
102 // When getting the value for a key from the thread options, we will always
103 // try and grab the setting from the current thread if there is one. Else we just
104 // use the one from this instance.
107 Thread *thread = exe_ctx->GetThreadPtr();
110 ThreadOptionValueProperties *instance_properties = static_cast<ThreadOptionValueProperties *>(thread->GetValueProperties().get());
111 if (this != instance_properties)
112 return instance_properties->ProtectedGetPropertyAtIndex (idx);
115 return ProtectedGetPropertyAtIndex (idx);
121 ThreadProperties::ThreadProperties (bool is_global) :
126 m_collection_sp.reset (new ThreadOptionValueProperties(ConstString("thread")));
127 m_collection_sp->Initialize(g_properties);
130 m_collection_sp.reset (new ThreadOptionValueProperties(Thread::GetGlobalProperties().get()));
133 ThreadProperties::~ThreadProperties()
137 const RegularExpression *
138 ThreadProperties::GetSymbolsToAvoidRegexp()
140 const uint32_t idx = ePropertyStepAvoidRegex;
141 return m_collection_sp->GetPropertyAtIndexAsOptionValueRegex (NULL, idx);
145 ThreadProperties::GetLibrariesToAvoid() const
147 const uint32_t idx = ePropertyStepAvoidLibraries;
148 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
149 assert(option_value);
150 return option_value->GetCurrentValue();
154 ThreadProperties::GetTraceEnabledState() const
156 const uint32_t idx = ePropertyEnableThreadTrace;
157 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
161 ThreadProperties::GetStepInAvoidsNoDebug() const
163 const uint32_t idx = ePropertyStepInAvoidsNoDebug;
164 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
168 ThreadProperties::GetStepOutAvoidsNoDebug() const
170 const uint32_t idx = ePropertyStepOutAvoidsNoDebug;
171 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
175 //------------------------------------------------------------------
177 //------------------------------------------------------------------
181 Thread::ThreadEventData::GetFlavorString ()
183 static ConstString g_flavor ("Thread::ThreadEventData");
187 Thread::ThreadEventData::ThreadEventData (const lldb::ThreadSP thread_sp) :
188 m_thread_sp (thread_sp),
193 Thread::ThreadEventData::ThreadEventData (const lldb::ThreadSP thread_sp, const StackID &stack_id) :
194 m_thread_sp (thread_sp),
195 m_stack_id (stack_id)
199 Thread::ThreadEventData::ThreadEventData () :
205 Thread::ThreadEventData::~ThreadEventData ()
210 Thread::ThreadEventData::Dump (Stream *s) const
215 const Thread::ThreadEventData *
216 Thread::ThreadEventData::GetEventDataFromEvent (const Event *event_ptr)
220 const EventData *event_data = event_ptr->GetData();
221 if (event_data && event_data->GetFlavor() == ThreadEventData::GetFlavorString())
222 return static_cast <const ThreadEventData *> (event_ptr->GetData());
228 Thread::ThreadEventData::GetThreadFromEvent (const Event *event_ptr)
231 const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
233 thread_sp = event_data->GetThread();
238 Thread::ThreadEventData::GetStackIDFromEvent (const Event *event_ptr)
241 const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
243 stack_id = event_data->GetStackID();
248 Thread::ThreadEventData::GetStackFrameFromEvent (const Event *event_ptr)
250 const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr);
251 StackFrameSP frame_sp;
254 ThreadSP thread_sp = event_data->GetThread();
257 frame_sp = thread_sp->GetStackFrameList()->GetFrameWithStackID (event_data->GetStackID());
263 //------------------------------------------------------------------
265 //------------------------------------------------------------------
268 Thread::GetStaticBroadcasterClass ()
270 static ConstString class_name ("lldb.thread");
274 Thread::Thread (Process &process, lldb::tid_t tid, bool use_invalid_index_id) :
275 ThreadProperties (false),
277 Broadcaster(&process.GetTarget().GetDebugger(), Thread::GetStaticBroadcasterClass().AsCString()),
278 m_process_wp (process.shared_from_this()),
280 m_stop_info_stop_id (0),
281 m_index_id (use_invalid_index_id ? LLDB_INVALID_INDEX32 : process.GetNextThreadIndexID(tid)),
283 m_state (eStateUnloaded),
284 m_state_mutex (Mutex::eMutexTypeRecursive),
286 m_completed_plan_stack(),
287 m_frame_mutex (Mutex::eMutexTypeRecursive),
290 m_resume_signal (LLDB_INVALID_SIGNAL_NUMBER),
291 m_resume_state (eStateRunning),
292 m_temporary_resume_state (eStateRunning),
294 m_destroy_called (false),
295 m_override_should_notify (eLazyBoolCalculate),
296 m_extended_info_fetched (false),
299 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
301 log->Printf ("%p Thread::Thread(tid = 0x%4.4" PRIx64 ")",
302 static_cast<void*>(this), GetID());
304 CheckInWithManager();
305 QueueFundamentalPlan(true);
311 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
313 log->Printf ("%p Thread::~Thread(tid = 0x%4.4" PRIx64 ")",
314 static_cast<void*>(this), GetID());
315 /// If you hit this assert, it means your derived class forgot to call DoDestroy in its destructor.
316 assert (m_destroy_called);
320 Thread::DestroyThread ()
322 // Tell any plans on the plan stacks that the thread is being destroyed since
323 // any plans that have a thread go away in the middle of might need
324 // to do cleanup, or in some cases NOT do cleanup...
325 for (auto plan : m_plan_stack)
326 plan->ThreadDestroyed();
328 for (auto plan : m_discarded_plan_stack)
329 plan->ThreadDestroyed();
331 for (auto plan : m_completed_plan_stack)
332 plan->ThreadDestroyed();
334 m_destroy_called = true;
335 m_plan_stack.clear();
336 m_discarded_plan_stack.clear();
337 m_completed_plan_stack.clear();
339 // Push a ThreadPlanNull on the plan stack. That way we can continue assuming that the
340 // plan stack is never empty, but if somebody errantly asks questions of a destroyed thread
341 // without checking first whether it is destroyed, they won't crash.
342 ThreadPlanSP null_plan_sp(new ThreadPlanNull (*this));
343 m_plan_stack.push_back (null_plan_sp);
345 m_stop_info_sp.reset();
346 m_reg_context_sp.reset();
347 m_unwinder_ap.reset();
348 Mutex::Locker locker(m_frame_mutex);
349 m_curr_frames_sp.reset();
350 m_prev_frames_sp.reset();
354 Thread::BroadcastSelectedFrameChange(StackID &new_frame_id)
356 if (EventTypeHasListeners(eBroadcastBitSelectedFrameChanged))
357 BroadcastEvent(eBroadcastBitSelectedFrameChanged, new ThreadEventData (this->shared_from_this(), new_frame_id));
361 Thread::SetSelectedFrame (lldb_private::StackFrame *frame, bool broadcast)
363 uint32_t ret_value = GetStackFrameList()->SetSelectedFrame(frame);
365 BroadcastSelectedFrameChange(frame->GetStackID());
370 Thread::SetSelectedFrameByIndex (uint32_t frame_idx, bool broadcast)
372 StackFrameSP frame_sp(GetStackFrameList()->GetFrameAtIndex (frame_idx));
375 GetStackFrameList()->SetSelectedFrame(frame_sp.get());
377 BroadcastSelectedFrameChange(frame_sp->GetStackID());
385 Thread::SetSelectedFrameByIndexNoisily (uint32_t frame_idx, Stream &output_stream)
387 const bool broadcast = true;
388 bool success = SetSelectedFrameByIndex (frame_idx, broadcast);
391 StackFrameSP frame_sp = GetSelectedFrame();
394 bool already_shown = false;
395 SymbolContext frame_sc(frame_sp->GetSymbolContext(eSymbolContextLineEntry));
396 if (GetProcess()->GetTarget().GetDebugger().GetUseExternalEditor() && frame_sc.line_entry.file && frame_sc.line_entry.line != 0)
398 already_shown = Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line);
401 bool show_frame_info = true;
402 bool show_source = !already_shown;
403 return frame_sp->GetStatus (output_stream, show_frame_info, show_source);
413 Thread::GetStopInfo ()
415 if (m_destroy_called)
416 return m_stop_info_sp;
418 ThreadPlanSP plan_sp (GetCompletedPlan());
419 ProcessSP process_sp (GetProcess());
420 const uint32_t stop_id = process_sp ? process_sp->GetStopID() : UINT32_MAX;
421 if (plan_sp && plan_sp->PlanSucceeded())
423 return StopInfo::CreateStopReasonWithPlan (plan_sp, GetReturnValueObject(), GetExpressionVariable());
427 if ((m_stop_info_stop_id == stop_id) || // Stop info is valid, just return what we have (even if empty)
428 (m_stop_info_sp && m_stop_info_sp->IsValid())) // Stop info is valid, just return what we have
430 return m_stop_info_sp;
434 GetPrivateStopInfo ();
435 return m_stop_info_sp;
441 Thread::GetPrivateStopInfo ()
443 if (m_destroy_called)
444 return m_stop_info_sp;
446 ProcessSP process_sp (GetProcess());
449 const uint32_t process_stop_id = process_sp->GetStopID();
450 if (m_stop_info_stop_id != process_stop_id)
454 if (m_stop_info_sp->IsValid()
455 || IsStillAtLastBreakpointHit()
456 || GetCurrentPlan()->IsVirtualStep())
457 SetStopInfo (m_stop_info_sp);
459 m_stop_info_sp.reset();
464 if (CalculateStopInfo() == false)
465 SetStopInfo (StopInfoSP());
469 return m_stop_info_sp;
474 Thread::GetStopReason()
476 lldb::StopInfoSP stop_info_sp (GetStopInfo ());
478 return stop_info_sp->GetStopReason();
479 return eStopReasonNone;
485 Thread::SetStopInfo (const lldb::StopInfoSP &stop_info_sp)
487 m_stop_info_sp = stop_info_sp;
490 m_stop_info_sp->MakeStopInfoValid();
491 // If we are overriding the ShouldReportStop, do that here:
492 if (m_override_should_notify != eLazyBoolCalculate)
493 m_stop_info_sp->OverrideShouldNotify (m_override_should_notify == eLazyBoolYes);
496 ProcessSP process_sp (GetProcess());
498 m_stop_info_stop_id = process_sp->GetStopID();
500 m_stop_info_stop_id = UINT32_MAX;
501 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
503 log->Printf("%p: tid = 0x%" PRIx64 ": stop info = %s (stop_id = %u)",
504 static_cast<void*>(this), GetID(),
505 stop_info_sp ? stop_info_sp->GetDescription() : "<NULL>",
506 m_stop_info_stop_id);
510 Thread::SetShouldReportStop (Vote vote)
512 if (vote == eVoteNoOpinion)
516 m_override_should_notify = (vote == eVoteYes ? eLazyBoolYes : eLazyBoolNo);
518 m_stop_info_sp->OverrideShouldNotify (m_override_should_notify == eLazyBoolYes);
523 Thread::SetStopInfoToNothing()
525 // Note, we can't just NULL out the private reason, or the native thread implementation will try to
526 // go calculate it again. For now, just set it to a Unix Signal with an invalid signal number.
527 SetStopInfo (StopInfo::CreateStopReasonWithSignal (*this, LLDB_INVALID_SIGNAL_NUMBER));
531 Thread::ThreadStoppedForAReason (void)
533 return (bool) GetPrivateStopInfo ();
537 Thread::CheckpointThreadState (ThreadStateCheckpoint &saved_state)
539 saved_state.register_backup_sp.reset();
540 lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
543 lldb::RegisterCheckpointSP reg_checkpoint_sp(new RegisterCheckpoint(RegisterCheckpoint::Reason::eExpression));
544 if (reg_checkpoint_sp)
546 lldb::RegisterContextSP reg_ctx_sp (frame_sp->GetRegisterContext());
547 if (reg_ctx_sp && reg_ctx_sp->ReadAllRegisterValues (*reg_checkpoint_sp))
548 saved_state.register_backup_sp = reg_checkpoint_sp;
551 if (!saved_state.register_backup_sp)
554 saved_state.stop_info_sp = GetStopInfo();
555 ProcessSP process_sp (GetProcess());
557 saved_state.orig_stop_id = process_sp->GetStopID();
558 saved_state.current_inlined_depth = GetCurrentInlinedDepth();
564 Thread::RestoreRegisterStateFromCheckpoint (ThreadStateCheckpoint &saved_state)
566 if (saved_state.register_backup_sp)
568 lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
571 lldb::RegisterContextSP reg_ctx_sp (frame_sp->GetRegisterContext());
574 bool ret = reg_ctx_sp->WriteAllRegisterValues (*saved_state.register_backup_sp);
576 // Clear out all stack frames as our world just changed.
578 reg_ctx_sp->InvalidateIfNeeded(true);
579 if (m_unwinder_ap.get())
580 m_unwinder_ap->Clear();
589 Thread::RestoreThreadStateFromCheckpoint (ThreadStateCheckpoint &saved_state)
591 if (saved_state.stop_info_sp)
592 saved_state.stop_info_sp->MakeStopInfoValid();
593 SetStopInfo(saved_state.stop_info_sp);
594 GetStackFrameList()->SetCurrentInlinedDepth (saved_state.current_inlined_depth);
599 Thread::GetState() const
601 // If any other threads access this we will need a mutex for it
602 Mutex::Locker locker(m_state_mutex);
607 Thread::SetState(StateType state)
609 Mutex::Locker locker(m_state_mutex);
616 ThreadPlan *current_plan = GetCurrentPlan();
618 // FIXME: I may decide to disallow threads with no plans. In which
619 // case this should go to an assert.
624 current_plan->WillStop();
628 Thread::SetupForResume ()
630 if (GetResumeState() != eStateSuspended)
633 // If we're at a breakpoint push the step-over breakpoint plan. Do this before
634 // telling the current plan it will resume, since we might change what the current
637 // StopReason stop_reason = lldb::eStopReasonInvalid;
638 // StopInfoSP stop_info_sp = GetStopInfo();
639 // if (stop_info_sp.get())
640 // stop_reason = stop_info_sp->GetStopReason();
641 // if (stop_reason == lldb::eStopReasonBreakpoint)
642 lldb::RegisterContextSP reg_ctx_sp (GetRegisterContext());
645 BreakpointSiteSP bp_site_sp = GetProcess()->GetBreakpointSiteList().FindByAddress(reg_ctx_sp->GetPC());
648 // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the target may not require anything
649 // special to step over a breakpoint.
651 ThreadPlan *cur_plan = GetCurrentPlan();
653 if (cur_plan->GetKind() != ThreadPlan::eKindStepOverBreakpoint)
655 ThreadPlanStepOverBreakpoint *step_bp_plan = new ThreadPlanStepOverBreakpoint (*this);
658 ThreadPlanSP step_bp_plan_sp;
659 step_bp_plan->SetPrivate (true);
661 if (GetCurrentPlan()->RunState() != eStateStepping)
663 step_bp_plan->SetAutoContinue(true);
665 step_bp_plan_sp.reset (step_bp_plan);
666 QueueThreadPlan (step_bp_plan_sp, false);
675 Thread::ShouldResume (StateType resume_state)
677 // At this point clear the completed plan stack.
678 m_completed_plan_stack.clear();
679 m_discarded_plan_stack.clear();
680 m_override_should_notify = eLazyBoolCalculate;
682 m_temporary_resume_state = resume_state;
684 lldb::ThreadSP backing_thread_sp (GetBackingThread ());
685 if (backing_thread_sp)
686 backing_thread_sp->m_temporary_resume_state = resume_state;
688 // Make sure m_stop_info_sp is valid
689 GetPrivateStopInfo();
691 // This is a little dubious, but we are trying to limit how often we actually fetch stop info from
692 // the target, 'cause that slows down single stepping. So assume that if we got to the point where
693 // we're about to resume, and we haven't yet had to fetch the stop reason, then it doesn't need to know
694 // about the fact that we are resuming...
695 const uint32_t process_stop_id = GetProcess()->GetStopID();
696 if (m_stop_info_stop_id == process_stop_id &&
697 (m_stop_info_sp && m_stop_info_sp->IsValid()))
699 StopInfo *stop_info = GetPrivateStopInfo().get();
701 stop_info->WillResume (resume_state);
704 // Tell all the plans that we are about to resume in case they need to clear any state.
705 // We distinguish between the plan on the top of the stack and the lower
706 // plans in case a plan needs to do any special business before it runs.
708 bool need_to_resume = false;
709 ThreadPlan *plan_ptr = GetCurrentPlan();
712 need_to_resume = plan_ptr->WillResume(resume_state, true);
714 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != NULL)
716 plan_ptr->WillResume (resume_state, false);
719 // If the WillResume for the plan says we are faking a resume, then it will have set an appropriate stop info.
720 // In that case, don't reset it here.
722 if (need_to_resume && resume_state != eStateSuspended)
724 m_stop_info_sp.reset();
731 // Let Thread subclasses do any special work they need to prior to resuming
732 WillResume (resume_state);
735 return need_to_resume;
741 SetResumeSignal (LLDB_INVALID_SIGNAL_NUMBER);
747 SetState (eStateStopped);
751 Thread::ShouldStop (Event* event_ptr)
753 ThreadPlan *current_plan = GetCurrentPlan();
755 bool should_stop = true;
757 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
759 if (GetResumeState () == eStateSuspended)
762 log->Printf ("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", should_stop = 0 (ignore since thread was suspended)",
763 __FUNCTION__, GetID (), GetProtocolID());
767 if (GetTemporaryResumeState () == eStateSuspended)
770 log->Printf ("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", should_stop = 0 (ignore since thread was suspended)",
771 __FUNCTION__, GetID (), GetProtocolID());
775 // Based on the current thread plan and process stop info, check if this
776 // thread caused the process to stop. NOTE: this must take place before
777 // the plan is moved from the current plan stack to the completed plan
779 if (ThreadStoppedForAReason() == false)
782 log->Printf ("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", pc = 0x%16.16" PRIx64 ", should_stop = 0 (ignore since no stop reason)",
783 __FUNCTION__, GetID (), GetProtocolID(),
784 GetRegisterContext() ? GetRegisterContext()->GetPC() : LLDB_INVALID_ADDRESS);
790 log->Printf ("Thread::%s(%p) for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", pc = 0x%16.16" PRIx64,
791 __FUNCTION__, static_cast<void*>(this), GetID (),
794 ? GetRegisterContext()->GetPC()
795 : LLDB_INVALID_ADDRESS);
796 log->Printf ("^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^");
800 log->Printf ("Plan stack initial state:\n%s", s.GetData());
803 // The top most plan always gets to do the trace log...
804 current_plan->DoTraceLog ();
806 // First query the stop info's ShouldStopSynchronous. This handles "synchronous" stop reasons, for example the breakpoint
807 // command on internal breakpoints. If a synchronous stop reason says we should not stop, then we don't have to
808 // do any more work on this stop.
809 StopInfoSP private_stop_info (GetPrivateStopInfo());
810 if (private_stop_info && private_stop_info->ShouldStopSynchronous(event_ptr) == false)
813 log->Printf ("StopInfo::ShouldStop async callback says we should not stop, returning ShouldStop of false.");
817 // If we've already been restarted, don't query the plans since the state they would examine is not current.
818 if (Process::ProcessEventData::GetRestartedFromEvent(event_ptr))
821 // Before the plans see the state of the world, calculate the current inlined depth.
822 GetStackFrameList()->CalculateCurrentInlinedDepth();
824 // If the base plan doesn't understand why we stopped, then we have to find a plan that does.
825 // If that plan is still working, then we don't need to do any more work. If the plan that explains
826 // the stop is done, then we should pop all the plans below it, and pop it, and then let the plans above it decide
827 // whether they still need to do more work.
829 bool done_processing_current_plan = false;
831 if (!current_plan->PlanExplainsStop(event_ptr))
833 if (current_plan->TracerExplainsStop())
835 done_processing_current_plan = true;
840 // If the current plan doesn't explain the stop, then find one that
841 // does and let it handle the situation.
842 ThreadPlan *plan_ptr = current_plan;
843 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != NULL)
845 if (plan_ptr->PlanExplainsStop(event_ptr))
847 should_stop = plan_ptr->ShouldStop (event_ptr);
849 // plan_ptr explains the stop, next check whether plan_ptr is done, if so, then we should take it
850 // and all the plans below it off the stack.
852 if (plan_ptr->MischiefManaged())
854 // We're going to pop the plans up to and including the plan that explains the stop.
855 ThreadPlan *prev_plan_ptr = GetPreviousPlan (plan_ptr);
860 current_plan->WillStop();
863 while ((current_plan = GetCurrentPlan()) != prev_plan_ptr);
864 // Now, if the responsible plan was not "Okay to discard" then we're done,
865 // otherwise we forward this to the next plan in the stack below.
866 if (plan_ptr->IsMasterPlan() && !plan_ptr->OkayToDiscard())
867 done_processing_current_plan = true;
869 done_processing_current_plan = false;
872 done_processing_current_plan = true;
881 if (!done_processing_current_plan)
883 bool over_ride_stop = current_plan->ShouldAutoContinue(event_ptr);
886 log->Printf("Plan %s explains stop, auto-continue %i.",
887 current_plan->GetName(), over_ride_stop);
889 // We're starting from the base plan, so just let it decide;
890 if (PlanIsBasePlan(current_plan))
892 should_stop = current_plan->ShouldStop (event_ptr);
894 log->Printf("Base plan says should stop: %i.", should_stop);
898 // Otherwise, don't let the base plan override what the other plans say to do, since
899 // presumably if there were other plans they would know what to do...
902 if (PlanIsBasePlan(current_plan))
905 should_stop = current_plan->ShouldStop(event_ptr);
907 log->Printf("Plan %s should stop: %d.",
908 current_plan->GetName(), should_stop);
909 if (current_plan->MischiefManaged())
912 current_plan->WillStop();
914 // If a Master Plan wants to stop, and wants to stick on the stack, we let it.
915 // Otherwise, see if the plan's parent wants to stop.
917 if (should_stop && current_plan->IsMasterPlan() && !current_plan->OkayToDiscard())
927 current_plan = GetCurrentPlan();
928 if (current_plan == NULL)
944 // One other potential problem is that we set up a master plan, then stop in before it is complete - for instance
945 // by hitting a breakpoint during a step-over - then do some step/finish/etc operations that wind up
946 // past the end point condition of the initial plan. We don't want to strand the original plan on the stack,
947 // This code clears stale plans off the stack.
951 ThreadPlan *plan_ptr = GetCurrentPlan();
952 while (!PlanIsBasePlan(plan_ptr))
954 bool stale = plan_ptr->IsPlanStale ();
955 ThreadPlan *examined_plan = plan_ptr;
956 plan_ptr = GetPreviousPlan (examined_plan);
961 log->Printf("Plan %s being discarded in cleanup, it says it is already done.",
962 examined_plan->GetName());
963 DiscardThreadPlansUpToPlan(examined_plan);
975 log->Printf ("Plan stack final state:\n%s", s.GetData());
976 log->Printf ("vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv", should_stop);
982 Thread::ShouldReportStop (Event* event_ptr)
984 StateType thread_state = GetResumeState ();
985 StateType temp_thread_state = GetTemporaryResumeState();
987 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
989 if (thread_state == eStateSuspended || thread_state == eStateInvalid)
992 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (state was suspended or invalid)", GetID(), eVoteNoOpinion);
993 return eVoteNoOpinion;
996 if (temp_thread_state == eStateSuspended || temp_thread_state == eStateInvalid)
999 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (temporary state was suspended or invalid)", GetID(), eVoteNoOpinion);
1000 return eVoteNoOpinion;
1003 if (!ThreadStoppedForAReason())
1006 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (thread didn't stop for a reason.)", GetID(), eVoteNoOpinion);
1007 return eVoteNoOpinion;
1010 if (m_completed_plan_stack.size() > 0)
1012 // Don't use GetCompletedPlan here, since that suppresses private plans.
1014 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote for complete stack's back plan", GetID());
1015 return m_completed_plan_stack.back()->ShouldReportStop (event_ptr);
1019 Vote thread_vote = eVoteNoOpinion;
1020 ThreadPlan *plan_ptr = GetCurrentPlan();
1023 if (plan_ptr->PlanExplainsStop(event_ptr))
1025 thread_vote = plan_ptr->ShouldReportStop(event_ptr);
1028 if (PlanIsBasePlan(plan_ptr))
1031 plan_ptr = GetPreviousPlan(plan_ptr);
1034 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i for current plan", GetID(), thread_vote);
1041 Thread::ShouldReportRun (Event* event_ptr)
1043 StateType thread_state = GetResumeState ();
1045 if (thread_state == eStateSuspended
1046 || thread_state == eStateInvalid)
1048 return eVoteNoOpinion;
1051 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1052 if (m_completed_plan_stack.size() > 0)
1054 // Don't use GetCompletedPlan here, since that suppresses private plans.
1056 log->Printf ("Current Plan for thread %d(%p) (0x%4.4" PRIx64 ", %s): %s being asked whether we should report run.",
1057 GetIndexID(), static_cast<void*>(this), GetID(),
1058 StateAsCString(GetTemporaryResumeState()),
1059 m_completed_plan_stack.back()->GetName());
1061 return m_completed_plan_stack.back()->ShouldReportRun (event_ptr);
1066 log->Printf ("Current Plan for thread %d(%p) (0x%4.4" PRIx64 ", %s): %s being asked whether we should report run.",
1067 GetIndexID(), static_cast<void*>(this), GetID(),
1068 StateAsCString(GetTemporaryResumeState()),
1069 GetCurrentPlan()->GetName());
1071 return GetCurrentPlan()->ShouldReportRun (event_ptr);
1076 Thread::MatchesSpec (const ThreadSpec *spec)
1081 return spec->ThreadPassesBasicTests(*this);
1085 Thread::PushPlan (ThreadPlanSP &thread_plan_sp)
1089 // If the thread plan doesn't already have a tracer, give it its parent's tracer:
1090 if (!thread_plan_sp->GetThreadPlanTracer())
1091 thread_plan_sp->SetThreadPlanTracer(m_plan_stack.back()->GetThreadPlanTracer());
1092 m_plan_stack.push_back (thread_plan_sp);
1094 thread_plan_sp->DidPush();
1096 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1100 thread_plan_sp->GetDescription (&s, lldb::eDescriptionLevelFull);
1101 log->Printf("Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".",
1102 static_cast<void*>(this), s.GetData(),
1103 thread_plan_sp->GetThread().GetID());
1111 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1113 if (m_plan_stack.size() <= 1)
1117 ThreadPlanSP &plan = m_plan_stack.back();
1120 log->Printf("Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".", plan->GetName(), plan->GetThread().GetID());
1122 m_completed_plan_stack.push_back (plan);
1124 m_plan_stack.pop_back();
1129 Thread::DiscardPlan ()
1131 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1132 if (m_plan_stack.size() > 1)
1134 ThreadPlanSP &plan = m_plan_stack.back();
1136 log->Printf("Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".", plan->GetName(), plan->GetThread().GetID());
1138 m_discarded_plan_stack.push_back (plan);
1140 m_plan_stack.pop_back();
1145 Thread::GetCurrentPlan ()
1147 // There will always be at least the base plan. If somebody is mucking with a
1148 // thread with an empty plan stack, we should assert right away.
1149 if (m_plan_stack.empty())
1151 return m_plan_stack.back().get();
1155 Thread::GetCompletedPlan ()
1157 ThreadPlanSP empty_plan_sp;
1158 if (!m_completed_plan_stack.empty())
1160 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1162 ThreadPlanSP completed_plan_sp;
1163 completed_plan_sp = m_completed_plan_stack[i];
1164 if (!completed_plan_sp->GetPrivate ())
1165 return completed_plan_sp;
1168 return empty_plan_sp;
1172 Thread::GetReturnValueObject ()
1174 if (!m_completed_plan_stack.empty())
1176 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1178 ValueObjectSP return_valobj_sp;
1179 return_valobj_sp = m_completed_plan_stack[i]->GetReturnValueObject();
1180 if (return_valobj_sp)
1181 return return_valobj_sp;
1184 return ValueObjectSP();
1187 ClangExpressionVariableSP
1188 Thread::GetExpressionVariable ()
1190 if (!m_completed_plan_stack.empty())
1192 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1194 ClangExpressionVariableSP expression_variable_sp;
1195 expression_variable_sp = m_completed_plan_stack[i]->GetExpressionVariable();
1196 if (expression_variable_sp)
1197 return expression_variable_sp;
1200 return ClangExpressionVariableSP();
1204 Thread::IsThreadPlanDone (ThreadPlan *plan)
1206 if (!m_completed_plan_stack.empty())
1208 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
1210 if (m_completed_plan_stack[i].get() == plan)
1218 Thread::WasThreadPlanDiscarded (ThreadPlan *plan)
1220 if (!m_discarded_plan_stack.empty())
1222 for (int i = m_discarded_plan_stack.size() - 1; i >= 0; i--)
1224 if (m_discarded_plan_stack[i].get() == plan)
1232 Thread::GetPreviousPlan (ThreadPlan *current_plan)
1234 if (current_plan == NULL)
1237 int stack_size = m_completed_plan_stack.size();
1238 for (int i = stack_size - 1; i > 0; i--)
1240 if (current_plan == m_completed_plan_stack[i].get())
1241 return m_completed_plan_stack[i-1].get();
1244 if (stack_size > 0 && m_completed_plan_stack[0].get() == current_plan)
1246 if (m_plan_stack.size() > 0)
1247 return m_plan_stack.back().get();
1252 stack_size = m_plan_stack.size();
1253 for (int i = stack_size - 1; i > 0; i--)
1255 if (current_plan == m_plan_stack[i].get())
1256 return m_plan_stack[i-1].get();
1262 Thread::QueueThreadPlan (ThreadPlanSP &thread_plan_sp, bool abort_other_plans)
1264 if (abort_other_plans)
1265 DiscardThreadPlans(true);
1267 PushPlan (thread_plan_sp);
1272 Thread::EnableTracer (bool value, bool single_stepping)
1274 int stack_size = m_plan_stack.size();
1275 for (int i = 0; i < stack_size; i++)
1277 if (m_plan_stack[i]->GetThreadPlanTracer())
1279 m_plan_stack[i]->GetThreadPlanTracer()->EnableTracing(value);
1280 m_plan_stack[i]->GetThreadPlanTracer()->EnableSingleStep(single_stepping);
1286 Thread::SetTracer (lldb::ThreadPlanTracerSP &tracer_sp)
1288 int stack_size = m_plan_stack.size();
1289 for (int i = 0; i < stack_size; i++)
1290 m_plan_stack[i]->SetThreadPlanTracer(tracer_sp);
1294 Thread::DiscardThreadPlansUpToPlan (lldb::ThreadPlanSP &up_to_plan_sp)
1296 DiscardThreadPlansUpToPlan (up_to_plan_sp.get());
1300 Thread::DiscardThreadPlansUpToPlan (ThreadPlan *up_to_plan_ptr)
1302 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1304 log->Printf("Discarding thread plans for thread tid = 0x%4.4" PRIx64 ", up to %p",
1305 GetID(), static_cast<void*>(up_to_plan_ptr));
1307 int stack_size = m_plan_stack.size();
1309 // If the input plan is NULL, discard all plans. Otherwise make sure this plan is in the
1310 // stack, and if so discard up to and including it.
1312 if (up_to_plan_ptr == NULL)
1314 for (int i = stack_size - 1; i > 0; i--)
1319 bool found_it = false;
1320 for (int i = stack_size - 1; i > 0; i--)
1322 if (m_plan_stack[i].get() == up_to_plan_ptr)
1327 bool last_one = false;
1328 for (int i = stack_size - 1; i > 0 && !last_one ; i--)
1330 if (GetCurrentPlan() == up_to_plan_ptr)
1340 Thread::DiscardThreadPlans(bool force)
1342 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1345 log->Printf("Discarding thread plans for thread (tid = 0x%4.4" PRIx64 ", force %d)", GetID(), force);
1350 int stack_size = m_plan_stack.size();
1351 for (int i = stack_size - 1; i > 0; i--)
1361 int master_plan_idx;
1362 bool discard = true;
1364 // Find the first master plan, see if it wants discarding, and if yes discard up to it.
1365 for (master_plan_idx = m_plan_stack.size() - 1; master_plan_idx >= 0; master_plan_idx--)
1367 if (m_plan_stack[master_plan_idx]->IsMasterPlan())
1369 discard = m_plan_stack[master_plan_idx]->OkayToDiscard();
1376 // First pop all the dependent plans:
1377 for (int i = m_plan_stack.size() - 1; i > master_plan_idx; i--)
1380 // FIXME: Do we need a finalize here, or is the rule that "PrepareForStop"
1381 // for the plan leaves it in a state that it is safe to pop the plan
1382 // with no more notice?
1386 // Now discard the master plan itself.
1387 // The bottom-most plan never gets discarded. "OkayToDiscard" for it means
1388 // discard it's dependent plans, but not it...
1389 if (master_plan_idx > 0)
1396 // If the master plan doesn't want to get discarded, then we're done.
1404 Thread::PlanIsBasePlan (ThreadPlan *plan_ptr)
1406 if (plan_ptr->IsBasePlan())
1408 else if (m_plan_stack.size() == 0)
1411 return m_plan_stack[0].get() == plan_ptr;
1415 Thread::UnwindInnermostExpression()
1418 int stack_size = m_plan_stack.size();
1420 // If the input plan is NULL, discard all plans. Otherwise make sure this plan is in the
1421 // stack, and if so discard up to and including it.
1423 for (int i = stack_size - 1; i > 0; i--)
1425 if (m_plan_stack[i]->GetKind() == ThreadPlan::eKindCallFunction)
1427 DiscardThreadPlansUpToPlan(m_plan_stack[i].get());
1431 error.SetErrorString("No expressions currently active on this thread");
1437 Thread::QueueFundamentalPlan (bool abort_other_plans)
1439 ThreadPlanSP thread_plan_sp (new ThreadPlanBase(*this));
1440 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1441 return thread_plan_sp;
1445 Thread::QueueThreadPlanForStepSingleInstruction
1448 bool abort_other_plans,
1449 bool stop_other_threads
1452 ThreadPlanSP thread_plan_sp (new ThreadPlanStepInstruction (*this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
1453 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1454 return thread_plan_sp;
1458 Thread::QueueThreadPlanForStepOverRange
1460 bool abort_other_plans,
1461 const AddressRange &range,
1462 const SymbolContext &addr_context,
1463 lldb::RunMode stop_other_threads,
1464 LazyBool step_out_avoids_code_withoug_debug_info
1467 ThreadPlanSP thread_plan_sp;
1468 thread_plan_sp.reset (new ThreadPlanStepOverRange (*this, range, addr_context, stop_other_threads, step_out_avoids_code_withoug_debug_info));
1470 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1471 return thread_plan_sp;
1475 Thread::QueueThreadPlanForStepInRange
1477 bool abort_other_plans,
1478 const AddressRange &range,
1479 const SymbolContext &addr_context,
1480 const char *step_in_target,
1481 lldb::RunMode stop_other_threads,
1482 LazyBool step_in_avoids_code_without_debug_info,
1483 LazyBool step_out_avoids_code_without_debug_info
1486 ThreadPlanSP thread_plan_sp;
1487 ThreadPlanStepInRange *plan = new ThreadPlanStepInRange (*this,
1491 step_in_avoids_code_without_debug_info,
1492 step_out_avoids_code_without_debug_info);
1495 plan->SetStepInTarget(step_in_target);
1497 thread_plan_sp.reset (plan);
1499 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1500 return thread_plan_sp;
1505 Thread::QueueThreadPlanForStepOut
1507 bool abort_other_plans,
1508 SymbolContext *addr_context,
1510 bool stop_other_threads,
1514 LazyBool step_out_avoids_code_withoug_debug_info
1517 ThreadPlanSP thread_plan_sp (new ThreadPlanStepOut (*this,
1524 step_out_avoids_code_withoug_debug_info));
1526 if (thread_plan_sp->ValidatePlan(NULL))
1528 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1529 return thread_plan_sp;
1533 return ThreadPlanSP();
1538 Thread::QueueThreadPlanForStepOutNoShouldStop
1540 bool abort_other_plans,
1541 SymbolContext *addr_context,
1543 bool stop_other_threads,
1549 ThreadPlanStepOut *new_plan = new ThreadPlanStepOut (*this,
1557 new_plan->ClearShouldStopHereCallbacks();
1558 ThreadPlanSP thread_plan_sp(new_plan);
1560 if (thread_plan_sp->ValidatePlan(NULL))
1562 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1563 return thread_plan_sp;
1567 return ThreadPlanSP();
1572 Thread::QueueThreadPlanForStepThrough (StackID &return_stack_id, bool abort_other_plans, bool stop_other_threads)
1574 ThreadPlanSP thread_plan_sp(new ThreadPlanStepThrough (*this, return_stack_id, stop_other_threads));
1575 if (!thread_plan_sp || !thread_plan_sp->ValidatePlan (NULL))
1576 return ThreadPlanSP();
1578 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1579 return thread_plan_sp;
1583 Thread::QueueThreadPlanForRunToAddress (bool abort_other_plans,
1584 Address &target_addr,
1585 bool stop_other_threads)
1587 ThreadPlanSP thread_plan_sp (new ThreadPlanRunToAddress (*this, target_addr, stop_other_threads));
1588 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1589 return thread_plan_sp;
1593 Thread::QueueThreadPlanForStepUntil (bool abort_other_plans,
1594 lldb::addr_t *address_list,
1595 size_t num_addresses,
1596 bool stop_other_threads,
1599 ThreadPlanSP thread_plan_sp (new ThreadPlanStepUntil (*this, address_list, num_addresses, stop_other_threads, frame_idx));
1600 QueueThreadPlan (thread_plan_sp, abort_other_plans);
1601 return thread_plan_sp;
1606 Thread::GetIndexID () const
1612 Thread::DumpThreadPlans (lldb_private::Stream *s) const
1614 uint32_t stack_size = m_plan_stack.size();
1617 s->Printf ("Plan Stack for thread #%u: tid = 0x%4.4" PRIx64 ", stack_size = %d\n", GetIndexID(), GetID(), stack_size);
1618 for (i = stack_size - 1; i >= 0; i--)
1622 s->Printf ("Element %d: ", i);
1623 m_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
1628 stack_size = m_completed_plan_stack.size();
1632 s->Printf ("Completed Plan Stack: %d elements.\n", stack_size);
1633 for (i = stack_size - 1; i >= 0; i--)
1637 s->Printf ("Element %d: ", i);
1638 m_completed_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
1644 stack_size = m_discarded_plan_stack.size();
1648 s->Printf ("Discarded Plan Stack: %d elements.\n", stack_size);
1649 for (i = stack_size - 1; i >= 0; i--)
1653 s->Printf ("Element %d: ", i);
1654 m_discarded_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
1663 Thread::CalculateTarget ()
1666 ProcessSP process_sp(GetProcess());
1668 target_sp = process_sp->CalculateTarget();
1674 Thread::CalculateProcess ()
1676 return GetProcess();
1680 Thread::CalculateThread ()
1682 return shared_from_this();
1686 Thread::CalculateStackFrame ()
1688 return StackFrameSP();
1692 Thread::CalculateExecutionContext (ExecutionContext &exe_ctx)
1694 exe_ctx.SetContext (shared_from_this());
1699 Thread::GetStackFrameList ()
1701 StackFrameListSP frame_list_sp;
1702 Mutex::Locker locker(m_frame_mutex);
1703 if (m_curr_frames_sp)
1705 frame_list_sp = m_curr_frames_sp;
1709 frame_list_sp.reset(new StackFrameList (*this, m_prev_frames_sp, true));
1710 m_curr_frames_sp = frame_list_sp;
1712 return frame_list_sp;
1716 Thread::ClearStackFrames ()
1718 Mutex::Locker locker(m_frame_mutex);
1720 Unwind *unwinder = GetUnwinder ();
1724 // Only store away the old "reference" StackFrameList if we got all its frames:
1725 // FIXME: At some point we can try to splice in the frames we have fetched into
1726 // the new frame as we make it, but let's not try that now.
1727 if (m_curr_frames_sp && m_curr_frames_sp->GetAllFramesFetched())
1728 m_prev_frames_sp.swap (m_curr_frames_sp);
1729 m_curr_frames_sp.reset();
1731 m_extended_info.reset();
1732 m_extended_info_fetched = false;
1736 Thread::GetFrameWithConcreteFrameIndex (uint32_t unwind_idx)
1738 return GetStackFrameList()->GetFrameWithConcreteFrameIndex (unwind_idx);
1743 Thread::ReturnFromFrameWithIndex (uint32_t frame_idx, lldb::ValueObjectSP return_value_sp, bool broadcast)
1745 StackFrameSP frame_sp = GetStackFrameAtIndex (frame_idx);
1750 return_error.SetErrorStringWithFormat("Could not find frame with index %d in thread 0x%" PRIx64 ".", frame_idx, GetID());
1753 return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
1757 Thread::ReturnFromFrame (lldb::StackFrameSP frame_sp, lldb::ValueObjectSP return_value_sp, bool broadcast)
1763 return_error.SetErrorString("Can't return to a null frame.");
1764 return return_error;
1767 Thread *thread = frame_sp->GetThread().get();
1768 uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
1769 StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
1770 if (!older_frame_sp)
1772 return_error.SetErrorString("No older frame to return to.");
1773 return return_error;
1776 if (return_value_sp)
1778 lldb::ABISP abi = thread->GetProcess()->GetABI();
1781 return_error.SetErrorString("Could not find ABI to set return value.");
1782 return return_error;
1784 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
1786 // FIXME: ValueObject::Cast doesn't currently work correctly, at least not for scalars.
1787 // Turn that back on when that works.
1788 if (0 && sc.function != NULL)
1790 Type *function_type = sc.function->GetType();
1793 ClangASTType return_type = sc.function->GetClangType().GetFunctionReturnType();
1797 return_type.DumpTypeDescription(&s);
1798 ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type);
1801 cast_value_sp->SetFormat(eFormatHex);
1802 return_value_sp = cast_value_sp;
1808 return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
1809 if (!return_error.Success())
1810 return return_error;
1813 // Now write the return registers for the chosen frame:
1814 // Note, we can't use ReadAllRegisterValues->WriteAllRegisterValues, since the read & write
1817 StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);
1818 if (youngest_frame_sp)
1820 lldb::RegisterContextSP reg_ctx_sp (youngest_frame_sp->GetRegisterContext());
1823 bool copy_success = reg_ctx_sp->CopyFromRegisterContext(older_frame_sp->GetRegisterContext());
1826 thread->DiscardThreadPlans(true);
1827 thread->ClearStackFrames();
1828 if (broadcast && EventTypeHasListeners(eBroadcastBitStackChanged))
1829 BroadcastEvent(eBroadcastBitStackChanged, new ThreadEventData (this->shared_from_this()));
1833 return_error.SetErrorString("Could not reset register values.");
1838 return_error.SetErrorString("Frame has no register context.");
1843 return_error.SetErrorString("Returned past top frame.");
1845 return return_error;
1848 static void DumpAddressList (Stream &s, const std::vector<Address> &list, ExecutionContextScope *exe_scope)
1850 for (size_t n=0;n<list.size();n++)
1853 list[n].Dump (&s, exe_scope, Address::DumpStyleResolvedDescription, Address::DumpStyleSectionNameOffset);
1859 Thread::JumpToLine (const FileSpec &file, uint32_t line, bool can_leave_function, std::string *warnings)
1861 ExecutionContext exe_ctx (GetStackFrameAtIndex(0));
1862 Target *target = exe_ctx.GetTargetPtr();
1863 TargetSP target_sp = exe_ctx.GetTargetSP();
1864 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1865 StackFrame *frame = exe_ctx.GetFramePtr();
1866 const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction);
1868 // Find candidate locations.
1869 std::vector<Address> candidates, within_function, outside_function;
1870 target->GetImages().FindAddressesForLine (target_sp, file, line, sc.function, within_function, outside_function);
1872 // If possible, we try and stay within the current function.
1873 // Within a function, we accept multiple locations (optimized code may do this,
1874 // there's no solution here so we do the best we can).
1875 // However if we're trying to leave the function, we don't know how to pick the
1876 // right location, so if there's more than one then we bail.
1877 if (!within_function.empty())
1878 candidates = within_function;
1879 else if (outside_function.size() == 1 && can_leave_function)
1880 candidates = outside_function;
1882 // Check if we got anything.
1883 if (candidates.empty())
1885 if (outside_function.empty())
1887 return Error("Cannot locate an address for %s:%i.",
1888 file.GetFilename().AsCString(), line);
1890 else if (outside_function.size() == 1)
1892 return Error("%s:%i is outside the current function.",
1893 file.GetFilename().AsCString(), line);
1898 DumpAddressList(sstr, outside_function, target);
1899 return Error("%s:%i has multiple candidate locations:\n%s",
1900 file.GetFilename().AsCString(), line, sstr.GetString().c_str());
1904 // Accept the first location, warn about any others.
1905 Address dest = candidates[0];
1906 if (warnings && candidates.size() > 1)
1909 sstr.Printf("%s:%i appears multiple times in this function, selecting the first location:\n",
1910 file.GetFilename().AsCString(), line);
1911 DumpAddressList(sstr, candidates, target);
1912 *warnings = sstr.GetString();
1915 if (!reg_ctx->SetPC (dest))
1916 return Error("Cannot change PC to target address.");
1922 Thread::DumpUsingSettingsFormat (Stream &strm, uint32_t frame_idx)
1924 ExecutionContext exe_ctx (shared_from_this());
1925 Process *process = exe_ctx.GetProcessPtr();
1926 if (process == NULL)
1929 StackFrameSP frame_sp;
1930 SymbolContext frame_sc;
1931 if (frame_idx != LLDB_INVALID_INDEX32)
1933 frame_sp = GetStackFrameAtIndex (frame_idx);
1936 exe_ctx.SetFrameSP(frame_sp);
1937 frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
1941 const char *thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
1942 assert (thread_format);
1943 Debugger::FormatPrompt (thread_format,
1944 frame_sp ? &frame_sc : NULL,
1951 Thread::SettingsInitialize ()
1956 Thread::SettingsTerminate ()
1961 Thread::GetThreadPointer ()
1963 return LLDB_INVALID_ADDRESS;
1967 Thread::GetThreadLocalData (const ModuleSP module)
1969 // The default implementation is to ask the dynamic loader for it.
1970 // This can be overridden for specific platforms.
1971 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
1973 return loader->GetThreadLocalData (module, shared_from_this());
1975 return LLDB_INVALID_ADDRESS;
1979 Thread::SafeToCallFunctions ()
1981 Process *process = GetProcess().get();
1984 SystemRuntime *runtime = process->GetSystemRuntime ();
1987 return runtime->SafeToCallFunctionsOnThisThread (shared_from_this());
1994 Thread::GetStackFrameSPForStackFramePtr (StackFrame *stack_frame_ptr)
1996 return GetStackFrameList()->GetStackFrameSPForStackFramePtr (stack_frame_ptr);
2000 Thread::StopReasonAsCString (lldb::StopReason reason)
2004 case eStopReasonInvalid: return "invalid";
2005 case eStopReasonNone: return "none";
2006 case eStopReasonTrace: return "trace";
2007 case eStopReasonBreakpoint: return "breakpoint";
2008 case eStopReasonWatchpoint: return "watchpoint";
2009 case eStopReasonSignal: return "signal";
2010 case eStopReasonException: return "exception";
2011 case eStopReasonExec: return "exec";
2012 case eStopReasonPlanComplete: return "plan complete";
2013 case eStopReasonThreadExiting: return "thread exiting";
2017 static char unknown_state_string[64];
2018 snprintf(unknown_state_string, sizeof (unknown_state_string), "StopReason = %i", reason);
2019 return unknown_state_string;
2023 Thread::RunModeAsCString (lldb::RunMode mode)
2027 case eOnlyThisThread: return "only this thread";
2028 case eAllThreads: return "all threads";
2029 case eOnlyDuringStepping: return "only during stepping";
2032 static char unknown_state_string[64];
2033 snprintf(unknown_state_string, sizeof (unknown_state_string), "RunMode = %i", mode);
2034 return unknown_state_string;
2038 Thread::GetStatus (Stream &strm, uint32_t start_frame, uint32_t num_frames, uint32_t num_frames_with_source)
2040 ExecutionContext exe_ctx (shared_from_this());
2041 Target *target = exe_ctx.GetTargetPtr();
2042 Process *process = exe_ctx.GetProcessPtr();
2043 size_t num_frames_shown = 0;
2045 bool is_selected = false;
2048 if (process->GetThreadList().GetSelectedThread().get() == this)
2051 strm.Printf("%c ", is_selected ? '*' : ' ');
2052 if (target && target->GetDebugger().GetUseExternalEditor())
2054 StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
2057 SymbolContext frame_sc(frame_sp->GetSymbolContext (eSymbolContextLineEntry));
2058 if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file)
2060 Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line);
2065 DumpUsingSettingsFormat (strm, start_frame);
2071 const bool show_frame_info = true;
2073 const char *selected_frame_marker = NULL;
2074 if (num_frames == 1 || (GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID()))
2077 selected_frame_marker = "* ";
2079 num_frames_shown = GetStackFrameList ()->GetStatus (strm,
2083 num_frames_with_source,
2084 selected_frame_marker);
2085 if (num_frames == 1)
2089 return num_frames_shown;
2093 Thread::GetDescription (Stream &strm, lldb::DescriptionLevel level, bool print_json)
2095 DumpUsingSettingsFormat (strm, 0);
2098 StructuredData::ObjectSP thread_info = GetExtendedInfo();
2100 if (thread_info && print_json)
2102 thread_info->Dump (strm);
2109 StructuredData::ObjectSP activity = thread_info->GetObjectForDotSeparatedPath("activity");
2110 StructuredData::ObjectSP breadcrumb = thread_info->GetObjectForDotSeparatedPath("breadcrumb");
2111 StructuredData::ObjectSP messages = thread_info->GetObjectForDotSeparatedPath("trace_messages");
2113 bool printed_activity = false;
2114 if (activity && activity->GetType() == StructuredData::Type::eTypeDictionary)
2116 StructuredData::Dictionary *activity_dict = activity->GetAsDictionary();
2117 StructuredData::ObjectSP id = activity_dict->GetValueForKey("id");
2118 StructuredData::ObjectSP name = activity_dict->GetValueForKey("name");
2119 if (name && name->GetType() == StructuredData::Type::eTypeString
2120 && id && id->GetType() == StructuredData::Type::eTypeInteger)
2122 strm.Printf(" Activity '%s', 0x%" PRIx64 "\n", name->GetAsString()->GetValue().c_str(), id->GetAsInteger()->GetValue());
2124 printed_activity = true;
2126 bool printed_breadcrumb = false;
2127 if (breadcrumb && breadcrumb->GetType() == StructuredData::Type::eTypeDictionary)
2129 if (printed_activity)
2131 StructuredData::Dictionary *breadcrumb_dict = breadcrumb->GetAsDictionary();
2132 StructuredData::ObjectSP breadcrumb_text = breadcrumb_dict->GetValueForKey ("name");
2133 if (breadcrumb_text && breadcrumb_text->GetType() == StructuredData::Type::eTypeString)
2135 strm.Printf (" Current Breadcrumb: %s\n", breadcrumb_text->GetAsString()->GetValue().c_str());
2137 printed_breadcrumb = true;
2139 if (messages && messages->GetType() == StructuredData::Type::eTypeArray)
2141 if (printed_breadcrumb)
2143 StructuredData::Array *messages_array = messages->GetAsArray();
2144 const size_t msg_count = messages_array->GetSize();
2147 strm.Printf (" %zu trace messages:\n", msg_count);
2148 for (size_t i = 0; i < msg_count; i++)
2150 StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i);
2151 if (message && message->GetType() == StructuredData::Type::eTypeDictionary)
2153 StructuredData::Dictionary *message_dict = message->GetAsDictionary();
2154 StructuredData::ObjectSP message_text = message_dict->GetValueForKey ("message");
2155 if (message_text && message_text->GetType() == StructuredData::Type::eTypeString)
2157 strm.Printf (" %s\n", message_text->GetAsString()->GetValue().c_str());
2169 Thread::GetStackFrameStatus (Stream& strm,
2170 uint32_t first_frame,
2171 uint32_t num_frames,
2172 bool show_frame_info,
2173 uint32_t num_frames_with_source)
2175 return GetStackFrameList()->GetStatus (strm,
2179 num_frames_with_source);
2183 Thread::GetUnwinder ()
2185 if (m_unwinder_ap.get() == NULL)
2187 const ArchSpec target_arch (CalculateTarget()->GetArchitecture ());
2188 const llvm::Triple::ArchType machine = target_arch.GetMachine();
2191 case llvm::Triple::x86_64:
2192 case llvm::Triple::x86:
2193 case llvm::Triple::arm:
2194 case llvm::Triple::aarch64:
2195 case llvm::Triple::thumb:
2196 case llvm::Triple::mips64:
2197 case llvm::Triple::hexagon:
2198 m_unwinder_ap.reset (new UnwindLLDB (*this));
2202 if (target_arch.GetTriple().getVendor() == llvm::Triple::Apple)
2203 m_unwinder_ap.reset (new UnwindMacOSXFrameBackchain (*this));
2207 return m_unwinder_ap.get();
2214 ClearStackFrames ();
2215 m_reg_context_sp.reset();
2219 Thread::IsStillAtLastBreakpointHit ()
2221 // If we are currently stopped at a breakpoint, always return that stopinfo and don't reset it.
2222 // This allows threads to maintain their breakpoint stopinfo, such as when thread-stepping in
2223 // multithreaded programs.
2224 if (m_stop_info_sp) {
2225 StopReason stop_reason = m_stop_info_sp->GetStopReason();
2226 if (stop_reason == lldb::eStopReasonBreakpoint) {
2227 uint64_t value = m_stop_info_sp->GetValue();
2228 lldb::RegisterContextSP reg_ctx_sp (GetRegisterContext());
2231 lldb::addr_t pc = reg_ctx_sp->GetPC();
2232 BreakpointSiteSP bp_site_sp = GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2234 static_cast<break_id_t>(value) == bp_site_sp->GetID())
2244 Thread::StepIn (bool source_step,
2245 LazyBool step_in_avoids_code_without_debug_info,
2246 LazyBool step_out_avoids_code_without_debug_info)
2250 Process *process = GetProcess().get();
2251 if (StateIsStoppedState (process->GetState(), true))
2253 StackFrameSP frame_sp = GetStackFrameAtIndex (0);
2254 ThreadPlanSP new_plan_sp;
2255 const lldb::RunMode run_mode = eOnlyThisThread;
2256 const bool abort_other_plans = false;
2258 if (source_step && frame_sp && frame_sp->HasDebugInformation ())
2260 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2261 new_plan_sp = QueueThreadPlanForStepInRange (abort_other_plans,
2262 sc.line_entry.range,
2266 step_in_avoids_code_without_debug_info,
2267 step_out_avoids_code_without_debug_info);
2271 new_plan_sp = QueueThreadPlanForStepSingleInstruction (false,
2276 new_plan_sp->SetIsMasterPlan(true);
2277 new_plan_sp->SetOkayToDiscard(false);
2279 // Why do we need to set the current thread by ID here???
2280 process->GetThreadList().SetSelectedThreadByID (GetID());
2281 error = process->Resume();
2285 error.SetErrorString("process not stopped");
2291 Thread::StepOver (bool source_step,
2292 LazyBool step_out_avoids_code_without_debug_info)
2295 Process *process = GetProcess().get();
2296 if (StateIsStoppedState (process->GetState(), true))
2298 StackFrameSP frame_sp = GetStackFrameAtIndex (0);
2299 ThreadPlanSP new_plan_sp;
2301 const lldb::RunMode run_mode = eOnlyThisThread;
2302 const bool abort_other_plans = false;
2304 if (source_step && frame_sp && frame_sp->HasDebugInformation ())
2306 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2307 new_plan_sp = QueueThreadPlanForStepOverRange (abort_other_plans,
2308 sc.line_entry.range,
2311 step_out_avoids_code_without_debug_info);
2315 new_plan_sp = QueueThreadPlanForStepSingleInstruction (true,
2320 new_plan_sp->SetIsMasterPlan(true);
2321 new_plan_sp->SetOkayToDiscard(false);
2323 // Why do we need to set the current thread by ID here???
2324 process->GetThreadList().SetSelectedThreadByID (GetID());
2325 error = process->Resume();
2329 error.SetErrorString("process not stopped");
2338 Process *process = GetProcess().get();
2339 if (StateIsStoppedState (process->GetState(), true))
2341 const bool first_instruction = false;
2342 const bool stop_other_threads = false;
2343 const bool abort_other_plans = false;
2345 ThreadPlanSP new_plan_sp(QueueThreadPlanForStepOut (abort_other_plans,
2353 new_plan_sp->SetIsMasterPlan(true);
2354 new_plan_sp->SetOkayToDiscard(false);
2356 // Why do we need to set the current thread by ID here???
2357 process->GetThreadList().SetSelectedThreadByID (GetID());
2358 error = process->Resume();
2362 error.SetErrorString("process not stopped");