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/Target/Thread.h"
11 #include "Plugins/Process/Utility/UnwindLLDB.h"
12 #include "Plugins/Process/Utility/UnwindMacOSXFrameBackchain.h"
13 #include "lldb/Breakpoint/BreakpointLocation.h"
14 #include "lldb/Core/Debugger.h"
15 #include "lldb/Core/FormatEntity.h"
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ValueObject.h"
18 #include "lldb/Host/Host.h"
19 #include "lldb/Interpreter/OptionValueFileSpecList.h"
20 #include "lldb/Interpreter/OptionValueProperties.h"
21 #include "lldb/Interpreter/Property.h"
22 #include "lldb/Symbol/Function.h"
23 #include "lldb/Target/ABI.h"
24 #include "lldb/Target/DynamicLoader.h"
25 #include "lldb/Target/ExecutionContext.h"
26 #include "lldb/Target/ObjCLanguageRuntime.h"
27 #include "lldb/Target/Process.h"
28 #include "lldb/Target/RegisterContext.h"
29 #include "lldb/Target/StackFrameRecognizer.h"
30 #include "lldb/Target/StopInfo.h"
31 #include "lldb/Target/SystemRuntime.h"
32 #include "lldb/Target/Target.h"
33 #include "lldb/Target/ThreadPlan.h"
34 #include "lldb/Target/ThreadPlanBase.h"
35 #include "lldb/Target/ThreadPlanCallFunction.h"
36 #include "lldb/Target/ThreadPlanPython.h"
37 #include "lldb/Target/ThreadPlanRunToAddress.h"
38 #include "lldb/Target/ThreadPlanStepInRange.h"
39 #include "lldb/Target/ThreadPlanStepInstruction.h"
40 #include "lldb/Target/ThreadPlanStepOut.h"
41 #include "lldb/Target/ThreadPlanStepOverBreakpoint.h"
42 #include "lldb/Target/ThreadPlanStepOverRange.h"
43 #include "lldb/Target/ThreadPlanStepThrough.h"
44 #include "lldb/Target/ThreadPlanStepUntil.h"
45 #include "lldb/Target/ThreadSpec.h"
46 #include "lldb/Target/Unwind.h"
47 #include "lldb/Utility/Log.h"
48 #include "lldb/Utility/RegularExpression.h"
49 #include "lldb/Utility/State.h"
50 #include "lldb/Utility/Stream.h"
51 #include "lldb/Utility/StreamString.h"
52 #include "lldb/lldb-enumerations.h"
55 using namespace lldb_private;
57 const ThreadPropertiesSP &Thread::GetGlobalProperties() {
58 // NOTE: intentional leak so we don't crash if global destructor chain gets
59 // called as other threads still use the result of this function
60 static ThreadPropertiesSP *g_settings_sp_ptr =
61 new ThreadPropertiesSP(new ThreadProperties(true));
62 return *g_settings_sp_ptr;
65 static constexpr PropertyDefinition g_properties[] = {
66 {"step-in-avoid-nodebug", OptionValue::eTypeBoolean, true, true, nullptr,
68 "If true, step-in will not stop in functions with no debug information."},
69 {"step-out-avoid-nodebug", OptionValue::eTypeBoolean, true, false, nullptr,
70 {}, "If true, when step-in/step-out/step-over leave the current frame, "
71 "they will continue to step out till they come to a function with "
72 "debug information. Passing a frame argument to step-out will "
73 "override this option."},
74 {"step-avoid-regexp", OptionValue::eTypeRegex, true, 0, "^std::", {},
75 "A regular expression defining functions step-in won't stop in."},
76 {"step-avoid-libraries", OptionValue::eTypeFileSpecList, true, 0, nullptr,
77 {}, "A list of libraries that source stepping won't stop in."},
78 {"trace-thread", OptionValue::eTypeBoolean, false, false, nullptr, {},
79 "If true, this thread will single-step and log execution."},
80 {"max-backtrace-depth", OptionValue::eTypeUInt64, false, 300000, nullptr,
81 {}, "Maximum number of frames to backtrace."}};
84 ePropertyStepInAvoidsNoDebug,
85 ePropertyStepOutAvoidsNoDebug,
86 ePropertyStepAvoidRegex,
87 ePropertyStepAvoidLibraries,
88 ePropertyEnableThreadTrace,
89 ePropertyMaxBacktraceDepth
92 class ThreadOptionValueProperties : public OptionValueProperties {
94 ThreadOptionValueProperties(const ConstString &name)
95 : OptionValueProperties(name) {}
97 // This constructor is used when creating ThreadOptionValueProperties when it
98 // is part of a new lldb_private::Thread instance. It will copy all current
99 // global property values as needed
100 ThreadOptionValueProperties(ThreadProperties *global_properties)
101 : OptionValueProperties(*global_properties->GetValueProperties()) {}
103 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
105 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
108 // we just use the one from this instance.
110 Thread *thread = exe_ctx->GetThreadPtr();
112 ThreadOptionValueProperties *instance_properties =
113 static_cast<ThreadOptionValueProperties *>(
114 thread->GetValueProperties().get());
115 if (this != instance_properties)
116 return instance_properties->ProtectedGetPropertyAtIndex(idx);
119 return ProtectedGetPropertyAtIndex(idx);
123 ThreadProperties::ThreadProperties(bool is_global) : Properties() {
125 m_collection_sp.reset(
126 new ThreadOptionValueProperties(ConstString("thread")));
127 m_collection_sp->Initialize(g_properties);
129 m_collection_sp.reset(
130 new ThreadOptionValueProperties(Thread::GetGlobalProperties().get()));
133 ThreadProperties::~ThreadProperties() = default;
135 const RegularExpression *ThreadProperties::GetSymbolsToAvoidRegexp() {
136 const uint32_t idx = ePropertyStepAvoidRegex;
137 return m_collection_sp->GetPropertyAtIndexAsOptionValueRegex(nullptr, idx);
140 FileSpecList &ThreadProperties::GetLibrariesToAvoid() const {
141 const uint32_t idx = ePropertyStepAvoidLibraries;
142 OptionValueFileSpecList *option_value =
143 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
145 assert(option_value);
146 return option_value->GetCurrentValue();
149 bool ThreadProperties::GetTraceEnabledState() const {
150 const uint32_t idx = ePropertyEnableThreadTrace;
151 return m_collection_sp->GetPropertyAtIndexAsBoolean(
152 nullptr, idx, g_properties[idx].default_uint_value != 0);
155 bool ThreadProperties::GetStepInAvoidsNoDebug() const {
156 const uint32_t idx = ePropertyStepInAvoidsNoDebug;
157 return m_collection_sp->GetPropertyAtIndexAsBoolean(
158 nullptr, idx, g_properties[idx].default_uint_value != 0);
161 bool ThreadProperties::GetStepOutAvoidsNoDebug() const {
162 const uint32_t idx = ePropertyStepOutAvoidsNoDebug;
163 return m_collection_sp->GetPropertyAtIndexAsBoolean(
164 nullptr, idx, g_properties[idx].default_uint_value != 0);
167 uint64_t ThreadProperties::GetMaxBacktraceDepth() const {
168 const uint32_t idx = ePropertyMaxBacktraceDepth;
169 return m_collection_sp->GetPropertyAtIndexAsUInt64(
170 nullptr, idx, g_properties[idx].default_uint_value != 0);
173 //------------------------------------------------------------------
175 //------------------------------------------------------------------
177 const ConstString &Thread::ThreadEventData::GetFlavorString() {
178 static ConstString g_flavor("Thread::ThreadEventData");
182 Thread::ThreadEventData::ThreadEventData(const lldb::ThreadSP thread_sp)
183 : m_thread_sp(thread_sp), m_stack_id() {}
185 Thread::ThreadEventData::ThreadEventData(const lldb::ThreadSP thread_sp,
186 const StackID &stack_id)
187 : m_thread_sp(thread_sp), m_stack_id(stack_id) {}
189 Thread::ThreadEventData::ThreadEventData() : m_thread_sp(), m_stack_id() {}
191 Thread::ThreadEventData::~ThreadEventData() = default;
193 void Thread::ThreadEventData::Dump(Stream *s) const {}
195 const Thread::ThreadEventData *
196 Thread::ThreadEventData::GetEventDataFromEvent(const Event *event_ptr) {
198 const EventData *event_data = event_ptr->GetData();
200 event_data->GetFlavor() == ThreadEventData::GetFlavorString())
201 return static_cast<const ThreadEventData *>(event_ptr->GetData());
206 ThreadSP Thread::ThreadEventData::GetThreadFromEvent(const Event *event_ptr) {
208 const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
210 thread_sp = event_data->GetThread();
214 StackID Thread::ThreadEventData::GetStackIDFromEvent(const Event *event_ptr) {
216 const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
218 stack_id = event_data->GetStackID();
223 Thread::ThreadEventData::GetStackFrameFromEvent(const Event *event_ptr) {
224 const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
225 StackFrameSP frame_sp;
227 ThreadSP thread_sp = event_data->GetThread();
229 frame_sp = thread_sp->GetStackFrameList()->GetFrameWithStackID(
230 event_data->GetStackID());
236 //------------------------------------------------------------------
238 //------------------------------------------------------------------
240 ConstString &Thread::GetStaticBroadcasterClass() {
241 static ConstString class_name("lldb.thread");
245 Thread::Thread(Process &process, lldb::tid_t tid, bool use_invalid_index_id)
246 : ThreadProperties(false), UserID(tid),
247 Broadcaster(process.GetTarget().GetDebugger().GetBroadcasterManager(),
248 Thread::GetStaticBroadcasterClass().AsCString()),
249 m_process_wp(process.shared_from_this()), m_stop_info_sp(),
250 m_stop_info_stop_id(0), m_stop_info_override_stop_id(0),
251 m_index_id(use_invalid_index_id ? LLDB_INVALID_INDEX32
252 : process.GetNextThreadIndexID(tid)),
253 m_reg_context_sp(), m_state(eStateUnloaded), m_state_mutex(),
254 m_plan_stack(), m_completed_plan_stack(), m_frame_mutex(),
255 m_curr_frames_sp(), m_prev_frames_sp(),
256 m_resume_signal(LLDB_INVALID_SIGNAL_NUMBER),
257 m_resume_state(eStateRunning), m_temporary_resume_state(eStateRunning),
258 m_unwinder_ap(), m_destroy_called(false),
259 m_override_should_notify(eLazyBoolCalculate),
260 m_extended_info_fetched(false), m_extended_info() {
261 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
263 log->Printf("%p Thread::Thread(tid = 0x%4.4" PRIx64 ")",
264 static_cast<void *>(this), GetID());
266 CheckInWithManager();
268 QueueFundamentalPlan(true);
272 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
274 log->Printf("%p Thread::~Thread(tid = 0x%4.4" PRIx64 ")",
275 static_cast<void *>(this), GetID());
276 /// If you hit this assert, it means your derived class forgot to call
277 /// DoDestroy in its destructor.
278 assert(m_destroy_called);
281 void Thread::DestroyThread() {
282 // Tell any plans on the plan stacks that the thread is being destroyed since
283 // any plans that have a thread go away in the middle of might need to do
284 // cleanup, or in some cases NOT do cleanup...
285 for (auto plan : m_plan_stack)
286 plan->ThreadDestroyed();
288 for (auto plan : m_discarded_plan_stack)
289 plan->ThreadDestroyed();
291 for (auto plan : m_completed_plan_stack)
292 plan->ThreadDestroyed();
294 m_destroy_called = true;
295 m_plan_stack.clear();
296 m_discarded_plan_stack.clear();
297 m_completed_plan_stack.clear();
299 // Push a ThreadPlanNull on the plan stack. That way we can continue
300 // assuming that the plan stack is never empty, but if somebody errantly asks
301 // questions of a destroyed thread without checking first whether it is
302 // destroyed, they won't crash.
303 ThreadPlanSP null_plan_sp(new ThreadPlanNull(*this));
304 m_plan_stack.push_back(null_plan_sp);
306 m_stop_info_sp.reset();
307 m_reg_context_sp.reset();
308 m_unwinder_ap.reset();
309 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
310 m_curr_frames_sp.reset();
311 m_prev_frames_sp.reset();
314 void Thread::BroadcastSelectedFrameChange(StackID &new_frame_id) {
315 if (EventTypeHasListeners(eBroadcastBitSelectedFrameChanged))
316 BroadcastEvent(eBroadcastBitSelectedFrameChanged,
317 new ThreadEventData(this->shared_from_this(), new_frame_id));
320 lldb::StackFrameSP Thread::GetSelectedFrame() {
321 StackFrameListSP stack_frame_list_sp(GetStackFrameList());
322 StackFrameSP frame_sp = stack_frame_list_sp->GetFrameAtIndex(
323 stack_frame_list_sp->GetSelectedFrameIndex());
324 FunctionOptimizationWarning(frame_sp.get());
328 uint32_t Thread::SetSelectedFrame(lldb_private::StackFrame *frame,
330 uint32_t ret_value = GetStackFrameList()->SetSelectedFrame(frame);
332 BroadcastSelectedFrameChange(frame->GetStackID());
333 FunctionOptimizationWarning(frame);
337 bool Thread::SetSelectedFrameByIndex(uint32_t frame_idx, bool broadcast) {
338 StackFrameSP frame_sp(GetStackFrameList()->GetFrameAtIndex(frame_idx));
340 GetStackFrameList()->SetSelectedFrame(frame_sp.get());
342 BroadcastSelectedFrameChange(frame_sp->GetStackID());
343 FunctionOptimizationWarning(frame_sp.get());
349 bool Thread::SetSelectedFrameByIndexNoisily(uint32_t frame_idx,
350 Stream &output_stream) {
351 const bool broadcast = true;
352 bool success = SetSelectedFrameByIndex(frame_idx, broadcast);
354 StackFrameSP frame_sp = GetSelectedFrame();
356 bool already_shown = false;
357 SymbolContext frame_sc(
358 frame_sp->GetSymbolContext(eSymbolContextLineEntry));
359 if (GetProcess()->GetTarget().GetDebugger().GetUseExternalEditor() &&
360 frame_sc.line_entry.file && frame_sc.line_entry.line != 0) {
361 already_shown = Host::OpenFileInExternalEditor(
362 frame_sc.line_entry.file, frame_sc.line_entry.line);
365 bool show_frame_info = true;
366 bool show_source = !already_shown;
367 FunctionOptimizationWarning(frame_sp.get());
368 return frame_sp->GetStatus(output_stream, show_frame_info, show_source);
375 void Thread::FunctionOptimizationWarning(StackFrame *frame) {
376 if (frame && frame->HasDebugInformation() &&
377 GetProcess()->GetWarningsOptimization()) {
379 frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextModule);
380 GetProcess()->PrintWarningOptimization(sc);
384 lldb::StopInfoSP Thread::GetStopInfo() {
385 if (m_destroy_called)
386 return m_stop_info_sp;
388 ThreadPlanSP completed_plan_sp(GetCompletedPlan());
389 ProcessSP process_sp(GetProcess());
390 const uint32_t stop_id = process_sp ? process_sp->GetStopID() : UINT32_MAX;
392 // Here we select the stop info according to priorirty: - m_stop_info_sp (if
393 // not trace) - preset value - completed plan stop info - new value with plan
394 // from completed plan stack - m_stop_info_sp (trace stop reason is OK now) -
395 // ask GetPrivateStopInfo to set stop info
397 bool have_valid_stop_info = m_stop_info_sp &&
398 m_stop_info_sp ->IsValid() &&
399 m_stop_info_stop_id == stop_id;
400 bool have_valid_completed_plan = completed_plan_sp && completed_plan_sp->PlanSucceeded();
401 bool plan_failed = completed_plan_sp && !completed_plan_sp->PlanSucceeded();
402 bool plan_overrides_trace =
403 have_valid_stop_info && have_valid_completed_plan
404 && (m_stop_info_sp->GetStopReason() == eStopReasonTrace);
406 if (have_valid_stop_info && !plan_overrides_trace && !plan_failed) {
407 return m_stop_info_sp;
408 } else if (completed_plan_sp) {
409 return StopInfo::CreateStopReasonWithPlan(
410 completed_plan_sp, GetReturnValueObject(), GetExpressionVariable());
412 GetPrivateStopInfo();
413 return m_stop_info_sp;
417 lldb::StopInfoSP Thread::GetPrivateStopInfo() {
418 if (m_destroy_called)
419 return m_stop_info_sp;
421 ProcessSP process_sp(GetProcess());
423 const uint32_t process_stop_id = process_sp->GetStopID();
424 if (m_stop_info_stop_id != process_stop_id) {
425 if (m_stop_info_sp) {
426 if (m_stop_info_sp->IsValid() || IsStillAtLastBreakpointHit() ||
427 GetCurrentPlan()->IsVirtualStep())
428 SetStopInfo(m_stop_info_sp);
430 m_stop_info_sp.reset();
433 if (!m_stop_info_sp) {
434 if (!CalculateStopInfo())
435 SetStopInfo(StopInfoSP());
439 // The stop info can be manually set by calling Thread::SetStopInfo() prior
440 // to this function ever getting called, so we can't rely on
441 // "m_stop_info_stop_id != process_stop_id" as the condition for the if
442 // statement below, we must also check the stop info to see if we need to
443 // override it. See the header documentation in
444 // Process::GetStopInfoOverrideCallback() for more information on the stop
445 // info override callback.
446 if (m_stop_info_override_stop_id != process_stop_id) {
447 m_stop_info_override_stop_id = process_stop_id;
448 if (m_stop_info_sp) {
449 if (const Architecture *arch =
450 process_sp->GetTarget().GetArchitecturePlugin())
451 arch->OverrideStopInfo(*this);
455 return m_stop_info_sp;
458 lldb::StopReason Thread::GetStopReason() {
459 lldb::StopInfoSP stop_info_sp(GetStopInfo());
461 return stop_info_sp->GetStopReason();
462 return eStopReasonNone;
465 bool Thread::StopInfoIsUpToDate() const {
466 ProcessSP process_sp(GetProcess());
468 return m_stop_info_stop_id == process_sp->GetStopID();
470 return true; // Process is no longer around so stop info is always up to
474 void Thread::ResetStopInfo() {
475 if (m_stop_info_sp) {
476 m_stop_info_sp.reset();
480 void Thread::SetStopInfo(const lldb::StopInfoSP &stop_info_sp) {
481 m_stop_info_sp = stop_info_sp;
482 if (m_stop_info_sp) {
483 m_stop_info_sp->MakeStopInfoValid();
484 // If we are overriding the ShouldReportStop, do that here:
485 if (m_override_should_notify != eLazyBoolCalculate)
486 m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==
490 ProcessSP process_sp(GetProcess());
492 m_stop_info_stop_id = process_sp->GetStopID();
494 m_stop_info_stop_id = UINT32_MAX;
495 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
497 log->Printf("%p: tid = 0x%" PRIx64 ": stop info = %s (stop_id = %u)",
498 static_cast<void *>(this), GetID(),
499 stop_info_sp ? stop_info_sp->GetDescription() : "<NULL>",
500 m_stop_info_stop_id);
503 void Thread::SetShouldReportStop(Vote vote) {
504 if (vote == eVoteNoOpinion)
507 m_override_should_notify = (vote == eVoteYes ? eLazyBoolYes : eLazyBoolNo);
509 m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==
514 void Thread::SetStopInfoToNothing() {
515 // Note, we can't just NULL out the private reason, or the native thread
516 // implementation will try to go calculate it again. For now, just set it to
517 // a Unix Signal with an invalid signal number.
519 StopInfo::CreateStopReasonWithSignal(*this, LLDB_INVALID_SIGNAL_NUMBER));
522 bool Thread::ThreadStoppedForAReason(void) {
523 return (bool)GetPrivateStopInfo();
526 bool Thread::CheckpointThreadState(ThreadStateCheckpoint &saved_state) {
527 saved_state.register_backup_sp.reset();
528 lldb::StackFrameSP frame_sp(GetStackFrameAtIndex(0));
530 lldb::RegisterCheckpointSP reg_checkpoint_sp(
531 new RegisterCheckpoint(RegisterCheckpoint::Reason::eExpression));
532 if (reg_checkpoint_sp) {
533 lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());
534 if (reg_ctx_sp && reg_ctx_sp->ReadAllRegisterValues(*reg_checkpoint_sp))
535 saved_state.register_backup_sp = reg_checkpoint_sp;
538 if (!saved_state.register_backup_sp)
541 saved_state.stop_info_sp = GetStopInfo();
542 ProcessSP process_sp(GetProcess());
544 saved_state.orig_stop_id = process_sp->GetStopID();
545 saved_state.current_inlined_depth = GetCurrentInlinedDepth();
546 saved_state.m_completed_plan_stack = m_completed_plan_stack;
551 bool Thread::RestoreRegisterStateFromCheckpoint(
552 ThreadStateCheckpoint &saved_state) {
553 if (saved_state.register_backup_sp) {
554 lldb::StackFrameSP frame_sp(GetStackFrameAtIndex(0));
556 lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());
559 reg_ctx_sp->WriteAllRegisterValues(*saved_state.register_backup_sp);
561 // Clear out all stack frames as our world just changed.
563 reg_ctx_sp->InvalidateIfNeeded(true);
564 if (m_unwinder_ap.get())
565 m_unwinder_ap->Clear();
573 bool Thread::RestoreThreadStateFromCheckpoint(
574 ThreadStateCheckpoint &saved_state) {
575 if (saved_state.stop_info_sp)
576 saved_state.stop_info_sp->MakeStopInfoValid();
577 SetStopInfo(saved_state.stop_info_sp);
578 GetStackFrameList()->SetCurrentInlinedDepth(
579 saved_state.current_inlined_depth);
580 m_completed_plan_stack = saved_state.m_completed_plan_stack;
584 StateType Thread::GetState() const {
585 // If any other threads access this we will need a mutex for it
586 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
590 void Thread::SetState(StateType state) {
591 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
595 void Thread::WillStop() {
596 ThreadPlan *current_plan = GetCurrentPlan();
598 // FIXME: I may decide to disallow threads with no plans. In which
599 // case this should go to an assert.
604 current_plan->WillStop();
607 void Thread::SetupForResume() {
608 if (GetResumeState() != eStateSuspended) {
609 // If we're at a breakpoint push the step-over breakpoint plan. Do this
610 // before telling the current plan it will resume, since we might change
611 // what the current plan is.
613 lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext());
615 const addr_t thread_pc = reg_ctx_sp->GetPC();
616 BreakpointSiteSP bp_site_sp =
617 GetProcess()->GetBreakpointSiteList().FindByAddress(thread_pc);
619 // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the
620 // target may not require anything special to step over a breakpoint.
622 ThreadPlan *cur_plan = GetCurrentPlan();
624 bool push_step_over_bp_plan = false;
625 if (cur_plan->GetKind() == ThreadPlan::eKindStepOverBreakpoint) {
626 ThreadPlanStepOverBreakpoint *bp_plan =
627 (ThreadPlanStepOverBreakpoint *)cur_plan;
628 if (bp_plan->GetBreakpointLoadAddress() != thread_pc)
629 push_step_over_bp_plan = true;
631 push_step_over_bp_plan = true;
633 if (push_step_over_bp_plan) {
634 ThreadPlanSP step_bp_plan_sp(new ThreadPlanStepOverBreakpoint(*this));
635 if (step_bp_plan_sp) {
636 step_bp_plan_sp->SetPrivate(true);
638 if (GetCurrentPlan()->RunState() != eStateStepping) {
639 ThreadPlanStepOverBreakpoint *step_bp_plan =
640 static_cast<ThreadPlanStepOverBreakpoint *>(
641 step_bp_plan_sp.get());
642 step_bp_plan->SetAutoContinue(true);
644 QueueThreadPlan(step_bp_plan_sp, false);
652 bool Thread::ShouldResume(StateType resume_state) {
653 // At this point clear the completed plan stack.
654 m_completed_plan_stack.clear();
655 m_discarded_plan_stack.clear();
656 m_override_should_notify = eLazyBoolCalculate;
658 StateType prev_resume_state = GetTemporaryResumeState();
660 SetTemporaryResumeState(resume_state);
662 lldb::ThreadSP backing_thread_sp(GetBackingThread());
663 if (backing_thread_sp)
664 backing_thread_sp->SetTemporaryResumeState(resume_state);
666 // Make sure m_stop_info_sp is valid. Don't do this for threads we suspended
667 // in the previous run.
668 if (prev_resume_state != eStateSuspended)
669 GetPrivateStopInfo();
671 // This is a little dubious, but we are trying to limit how often we actually
672 // fetch stop info from the target, 'cause that slows down single stepping.
673 // So assume that if we got to the point where we're about to resume, and we
674 // haven't yet had to fetch the stop reason, then it doesn't need to know
675 // about the fact that we are resuming...
676 const uint32_t process_stop_id = GetProcess()->GetStopID();
677 if (m_stop_info_stop_id == process_stop_id &&
678 (m_stop_info_sp && m_stop_info_sp->IsValid())) {
679 StopInfo *stop_info = GetPrivateStopInfo().get();
681 stop_info->WillResume(resume_state);
684 // Tell all the plans that we are about to resume in case they need to clear
685 // any state. We distinguish between the plan on the top of the stack and the
686 // lower plans in case a plan needs to do any special business before it
689 bool need_to_resume = false;
690 ThreadPlan *plan_ptr = GetCurrentPlan();
692 need_to_resume = plan_ptr->WillResume(resume_state, true);
694 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
695 plan_ptr->WillResume(resume_state, false);
698 // If the WillResume for the plan says we are faking a resume, then it will
699 // have set an appropriate stop info. In that case, don't reset it here.
701 if (need_to_resume && resume_state != eStateSuspended) {
702 m_stop_info_sp.reset();
706 if (need_to_resume) {
708 // Let Thread subclasses do any special work they need to prior to resuming
709 WillResume(resume_state);
712 return need_to_resume;
715 void Thread::DidResume() { SetResumeSignal(LLDB_INVALID_SIGNAL_NUMBER); }
717 void Thread::DidStop() { SetState(eStateStopped); }
719 bool Thread::ShouldStop(Event *event_ptr) {
720 ThreadPlan *current_plan = GetCurrentPlan();
722 bool should_stop = true;
724 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
726 if (GetResumeState() == eStateSuspended) {
728 log->Printf("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
729 ", should_stop = 0 (ignore since thread was suspended)",
730 __FUNCTION__, GetID(), GetProtocolID());
734 if (GetTemporaryResumeState() == eStateSuspended) {
736 log->Printf("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
737 ", should_stop = 0 (ignore since thread was suspended)",
738 __FUNCTION__, GetID(), GetProtocolID());
742 // Based on the current thread plan and process stop info, check if this
743 // thread caused the process to stop. NOTE: this must take place before the
744 // plan is moved from the current plan stack to the completed plan stack.
745 if (!ThreadStoppedForAReason()) {
747 log->Printf("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
748 ", pc = 0x%16.16" PRIx64
749 ", should_stop = 0 (ignore since no stop reason)",
750 __FUNCTION__, GetID(), GetProtocolID(),
751 GetRegisterContext() ? GetRegisterContext()->GetPC()
752 : LLDB_INVALID_ADDRESS);
757 log->Printf("Thread::%s(%p) for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
758 ", pc = 0x%16.16" PRIx64,
759 __FUNCTION__, static_cast<void *>(this), GetID(),
761 GetRegisterContext() ? GetRegisterContext()->GetPC()
762 : LLDB_INVALID_ADDRESS);
763 log->Printf("^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^");
767 log->Printf("Plan stack initial state:\n%s", s.GetData());
770 // The top most plan always gets to do the trace log...
771 current_plan->DoTraceLog();
773 // First query the stop info's ShouldStopSynchronous. This handles
774 // "synchronous" stop reasons, for example the breakpoint command on internal
775 // breakpoints. If a synchronous stop reason says we should not stop, then
776 // we don't have to do any more work on this stop.
777 StopInfoSP private_stop_info(GetPrivateStopInfo());
778 if (private_stop_info &&
779 !private_stop_info->ShouldStopSynchronous(event_ptr)) {
781 log->Printf("StopInfo::ShouldStop async callback says we should not "
782 "stop, returning ShouldStop of false.");
786 // If we've already been restarted, don't query the plans since the state
787 // they would examine is not current.
788 if (Process::ProcessEventData::GetRestartedFromEvent(event_ptr))
791 // Before the plans see the state of the world, calculate the current inlined
793 GetStackFrameList()->CalculateCurrentInlinedDepth();
795 // If the base plan doesn't understand why we stopped, then we have to find a
796 // plan that does. If that plan is still working, then we don't need to do
797 // any more work. If the plan that explains the stop is done, then we should
798 // pop all the plans below it, and pop it, and then let the plans above it
799 // decide whether they still need to do more work.
801 bool done_processing_current_plan = false;
803 if (!current_plan->PlanExplainsStop(event_ptr)) {
804 if (current_plan->TracerExplainsStop()) {
805 done_processing_current_plan = true;
808 // If the current plan doesn't explain the stop, then find one that does
809 // and let it handle the situation.
810 ThreadPlan *plan_ptr = current_plan;
811 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
812 if (plan_ptr->PlanExplainsStop(event_ptr)) {
813 should_stop = plan_ptr->ShouldStop(event_ptr);
815 // plan_ptr explains the stop, next check whether plan_ptr is done,
816 // if so, then we should take it and all the plans below it off the
819 if (plan_ptr->MischiefManaged()) {
820 // We're going to pop the plans up to and including the plan that
821 // explains the stop.
822 ThreadPlan *prev_plan_ptr = GetPreviousPlan(plan_ptr);
826 current_plan->WillStop();
828 } while ((current_plan = GetCurrentPlan()) != prev_plan_ptr);
829 // Now, if the responsible plan was not "Okay to discard" then
830 // we're done, otherwise we forward this to the next plan in the
832 done_processing_current_plan =
833 (plan_ptr->IsMasterPlan() && !plan_ptr->OkayToDiscard());
835 done_processing_current_plan = true;
843 if (!done_processing_current_plan) {
844 bool over_ride_stop = current_plan->ShouldAutoContinue(event_ptr);
847 log->Printf("Plan %s explains stop, auto-continue %i.",
848 current_plan->GetName(), over_ride_stop);
850 // We're starting from the base plan, so just let it decide;
851 if (PlanIsBasePlan(current_plan)) {
852 should_stop = current_plan->ShouldStop(event_ptr);
854 log->Printf("Base plan says should stop: %i.", should_stop);
856 // Otherwise, don't let the base plan override what the other plans say
857 // to do, since presumably if there were other plans they would know what
860 if (PlanIsBasePlan(current_plan))
863 should_stop = current_plan->ShouldStop(event_ptr);
865 log->Printf("Plan %s should stop: %d.", current_plan->GetName(),
867 if (current_plan->MischiefManaged()) {
869 current_plan->WillStop();
871 // If a Master Plan wants to stop, and wants to stick on the stack,
872 // we let it. Otherwise, see if the plan's parent wants to stop.
874 if (should_stop && current_plan->IsMasterPlan() &&
875 !current_plan->OkayToDiscard()) {
881 current_plan = GetCurrentPlan();
882 if (current_plan == nullptr) {
896 // One other potential problem is that we set up a master plan, then stop in
897 // before it is complete - for instance by hitting a breakpoint during a
898 // step-over - then do some step/finish/etc operations that wind up past the
899 // end point condition of the initial plan. We don't want to strand the
900 // original plan on the stack, This code clears stale plans off the stack.
903 ThreadPlan *plan_ptr = GetCurrentPlan();
905 // Discard the stale plans and all plans below them in the stack, plus move
906 // the completed plans to the completed plan stack
907 while (!PlanIsBasePlan(plan_ptr)) {
908 bool stale = plan_ptr->IsPlanStale();
909 ThreadPlan *examined_plan = plan_ptr;
910 plan_ptr = GetPreviousPlan(examined_plan);
915 "Plan %s being discarded in cleanup, it says it is already done.",
916 examined_plan->GetName());
917 while (GetCurrentPlan() != examined_plan) {
920 if (examined_plan->IsPlanComplete()) {
921 // plan is complete but does not explain the stop (example: step to a
922 // line with breakpoint), let us move the plan to
923 // completed_plan_stack anyway
935 log->Printf("Plan stack final state:\n%s", s.GetData());
936 log->Printf("vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv",
942 Vote Thread::ShouldReportStop(Event *event_ptr) {
943 StateType thread_state = GetResumeState();
944 StateType temp_thread_state = GetTemporaryResumeState();
946 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
948 if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
950 log->Printf("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
951 ": returning vote %i (state was suspended or invalid)",
952 GetID(), eVoteNoOpinion);
953 return eVoteNoOpinion;
956 if (temp_thread_state == eStateSuspended ||
957 temp_thread_state == eStateInvalid) {
960 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
961 ": returning vote %i (temporary state was suspended or invalid)",
962 GetID(), eVoteNoOpinion);
963 return eVoteNoOpinion;
966 if (!ThreadStoppedForAReason()) {
968 log->Printf("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
969 ": returning vote %i (thread didn't stop for a reason.)",
970 GetID(), eVoteNoOpinion);
971 return eVoteNoOpinion;
974 if (m_completed_plan_stack.size() > 0) {
975 // Don't use GetCompletedPlan here, since that suppresses private plans.
977 log->Printf("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
978 ": returning vote for complete stack's back plan",
980 return m_completed_plan_stack.back()->ShouldReportStop(event_ptr);
982 Vote thread_vote = eVoteNoOpinion;
983 ThreadPlan *plan_ptr = GetCurrentPlan();
985 if (plan_ptr->PlanExplainsStop(event_ptr)) {
986 thread_vote = plan_ptr->ShouldReportStop(event_ptr);
989 if (PlanIsBasePlan(plan_ptr))
992 plan_ptr = GetPreviousPlan(plan_ptr);
995 log->Printf("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
996 ": returning vote %i for current plan",
997 GetID(), thread_vote);
1003 Vote Thread::ShouldReportRun(Event *event_ptr) {
1004 StateType thread_state = GetResumeState();
1006 if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
1007 return eVoteNoOpinion;
1010 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1011 if (m_completed_plan_stack.size() > 0) {
1012 // Don't use GetCompletedPlan here, since that suppresses private plans.
1014 log->Printf("Current Plan for thread %d(%p) (0x%4.4" PRIx64
1015 ", %s): %s being asked whether we should report run.",
1016 GetIndexID(), static_cast<void *>(this), GetID(),
1017 StateAsCString(GetTemporaryResumeState()),
1018 m_completed_plan_stack.back()->GetName());
1020 return m_completed_plan_stack.back()->ShouldReportRun(event_ptr);
1023 log->Printf("Current Plan for thread %d(%p) (0x%4.4" PRIx64
1024 ", %s): %s being asked whether we should report run.",
1025 GetIndexID(), static_cast<void *>(this), GetID(),
1026 StateAsCString(GetTemporaryResumeState()),
1027 GetCurrentPlan()->GetName());
1029 return GetCurrentPlan()->ShouldReportRun(event_ptr);
1033 bool Thread::MatchesSpec(const ThreadSpec *spec) {
1034 return (spec == nullptr) ? true : spec->ThreadPassesBasicTests(*this);
1037 void Thread::PushPlan(ThreadPlanSP &thread_plan_sp) {
1038 if (thread_plan_sp) {
1039 // If the thread plan doesn't already have a tracer, give it its parent's
1041 if (!thread_plan_sp->GetThreadPlanTracer()) {
1042 assert(!m_plan_stack.empty());
1043 thread_plan_sp->SetThreadPlanTracer(
1044 m_plan_stack.back()->GetThreadPlanTracer());
1046 m_plan_stack.push_back(thread_plan_sp);
1048 thread_plan_sp->DidPush();
1050 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1053 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelFull);
1054 log->Printf("Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".",
1055 static_cast<void *>(this), s.GetData(),
1056 thread_plan_sp->GetThread().GetID());
1061 void Thread::PopPlan() {
1062 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1064 if (m_plan_stack.size() <= 1)
1067 ThreadPlanSP &plan = m_plan_stack.back();
1069 log->Printf("Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1070 plan->GetName(), plan->GetThread().GetID());
1072 m_completed_plan_stack.push_back(plan);
1074 m_plan_stack.pop_back();
1078 void Thread::DiscardPlan() {
1079 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1080 if (m_plan_stack.size() > 1) {
1081 ThreadPlanSP &plan = m_plan_stack.back();
1083 log->Printf("Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1084 plan->GetName(), plan->GetThread().GetID());
1086 m_discarded_plan_stack.push_back(plan);
1088 m_plan_stack.pop_back();
1092 ThreadPlan *Thread::GetCurrentPlan() {
1093 // There will always be at least the base plan. If somebody is mucking with
1094 // a thread with an empty plan stack, we should assert right away.
1095 return m_plan_stack.empty() ? nullptr : m_plan_stack.back().get();
1098 ThreadPlanSP Thread::GetCompletedPlan() {
1099 ThreadPlanSP empty_plan_sp;
1100 if (!m_completed_plan_stack.empty()) {
1101 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) {
1102 ThreadPlanSP completed_plan_sp;
1103 completed_plan_sp = m_completed_plan_stack[i];
1104 if (!completed_plan_sp->GetPrivate())
1105 return completed_plan_sp;
1108 return empty_plan_sp;
1111 ValueObjectSP Thread::GetReturnValueObject() {
1112 if (!m_completed_plan_stack.empty()) {
1113 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) {
1114 ValueObjectSP return_valobj_sp;
1115 return_valobj_sp = m_completed_plan_stack[i]->GetReturnValueObject();
1116 if (return_valobj_sp)
1117 return return_valobj_sp;
1120 return ValueObjectSP();
1123 ExpressionVariableSP Thread::GetExpressionVariable() {
1124 if (!m_completed_plan_stack.empty()) {
1125 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) {
1126 ExpressionVariableSP expression_variable_sp;
1127 expression_variable_sp =
1128 m_completed_plan_stack[i]->GetExpressionVariable();
1129 if (expression_variable_sp)
1130 return expression_variable_sp;
1133 return ExpressionVariableSP();
1136 bool Thread::IsThreadPlanDone(ThreadPlan *plan) {
1137 if (!m_completed_plan_stack.empty()) {
1138 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) {
1139 if (m_completed_plan_stack[i].get() == plan)
1146 bool Thread::WasThreadPlanDiscarded(ThreadPlan *plan) {
1147 if (!m_discarded_plan_stack.empty()) {
1148 for (int i = m_discarded_plan_stack.size() - 1; i >= 0; i--) {
1149 if (m_discarded_plan_stack[i].get() == plan)
1156 bool Thread::CompletedPlanOverridesBreakpoint() {
1157 return (!m_completed_plan_stack.empty()) ;
1160 ThreadPlan *Thread::GetPreviousPlan(ThreadPlan *current_plan) {
1161 if (current_plan == nullptr)
1164 int stack_size = m_completed_plan_stack.size();
1165 for (int i = stack_size - 1; i > 0; i--) {
1166 if (current_plan == m_completed_plan_stack[i].get())
1167 return m_completed_plan_stack[i - 1].get();
1170 if (stack_size > 0 && m_completed_plan_stack[0].get() == current_plan) {
1171 return GetCurrentPlan();
1174 stack_size = m_plan_stack.size();
1175 for (int i = stack_size - 1; i > 0; i--) {
1176 if (current_plan == m_plan_stack[i].get())
1177 return m_plan_stack[i - 1].get();
1182 Status Thread::QueueThreadPlan(ThreadPlanSP &thread_plan_sp,
1183 bool abort_other_plans) {
1186 if (!thread_plan_sp->ValidatePlan(&s)) {
1187 DiscardThreadPlansUpToPlan(thread_plan_sp);
1188 thread_plan_sp.reset();
1189 status.SetErrorString(s.GetString());
1193 if (abort_other_plans)
1194 DiscardThreadPlans(true);
1196 PushPlan(thread_plan_sp);
1198 // This seems a little funny, but I don't want to have to split up the
1199 // constructor and the DidPush in the scripted plan, that seems annoying.
1200 // That means the constructor has to be in DidPush. So I have to validate the
1201 // plan AFTER pushing it, and then take it off again...
1202 if (!thread_plan_sp->ValidatePlan(&s)) {
1203 DiscardThreadPlansUpToPlan(thread_plan_sp);
1204 thread_plan_sp.reset();
1205 status.SetErrorString(s.GetString());
1212 void Thread::EnableTracer(bool value, bool single_stepping) {
1213 int stack_size = m_plan_stack.size();
1214 for (int i = 0; i < stack_size; i++) {
1215 if (m_plan_stack[i]->GetThreadPlanTracer()) {
1216 m_plan_stack[i]->GetThreadPlanTracer()->EnableTracing(value);
1217 m_plan_stack[i]->GetThreadPlanTracer()->EnableSingleStep(single_stepping);
1222 void Thread::SetTracer(lldb::ThreadPlanTracerSP &tracer_sp) {
1223 int stack_size = m_plan_stack.size();
1224 for (int i = 0; i < stack_size; i++)
1225 m_plan_stack[i]->SetThreadPlanTracer(tracer_sp);
1228 bool Thread::DiscardUserThreadPlansUpToIndex(uint32_t thread_index) {
1229 // Count the user thread plans from the back end to get the number of the one
1230 // we want to discard:
1233 ThreadPlan *up_to_plan_ptr = nullptr;
1235 for (ThreadPlanSP plan_sp : m_plan_stack) {
1236 if (plan_sp->GetPrivate())
1238 if (idx == thread_index) {
1239 up_to_plan_ptr = plan_sp.get();
1245 if (up_to_plan_ptr == nullptr)
1248 DiscardThreadPlansUpToPlan(up_to_plan_ptr);
1252 void Thread::DiscardThreadPlansUpToPlan(lldb::ThreadPlanSP &up_to_plan_sp) {
1253 DiscardThreadPlansUpToPlan(up_to_plan_sp.get());
1256 void Thread::DiscardThreadPlansUpToPlan(ThreadPlan *up_to_plan_ptr) {
1257 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1259 log->Printf("Discarding thread plans for thread tid = 0x%4.4" PRIx64
1261 GetID(), static_cast<void *>(up_to_plan_ptr));
1263 int stack_size = m_plan_stack.size();
1265 // If the input plan is nullptr, discard all plans. Otherwise make sure this
1266 // plan is in the stack, and if so discard up to and including it.
1268 if (up_to_plan_ptr == nullptr) {
1269 for (int i = stack_size - 1; i > 0; i--)
1272 bool found_it = false;
1273 for (int i = stack_size - 1; i > 0; i--) {
1274 if (m_plan_stack[i].get() == up_to_plan_ptr)
1278 bool last_one = false;
1279 for (int i = stack_size - 1; i > 0 && !last_one; i--) {
1280 if (GetCurrentPlan() == up_to_plan_ptr)
1288 void Thread::DiscardThreadPlans(bool force) {
1289 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1291 log->Printf("Discarding thread plans for thread (tid = 0x%4.4" PRIx64
1297 int stack_size = m_plan_stack.size();
1298 for (int i = stack_size - 1; i > 0; i--) {
1305 int master_plan_idx;
1306 bool discard = true;
1308 // Find the first master plan, see if it wants discarding, and if yes
1309 // discard up to it.
1310 for (master_plan_idx = m_plan_stack.size() - 1; master_plan_idx >= 0;
1311 master_plan_idx--) {
1312 if (m_plan_stack[master_plan_idx]->IsMasterPlan()) {
1313 discard = m_plan_stack[master_plan_idx]->OkayToDiscard();
1319 // First pop all the dependent plans:
1320 for (int i = m_plan_stack.size() - 1; i > master_plan_idx; i--) {
1321 // FIXME: Do we need a finalize here, or is the rule that
1323 // for the plan leaves it in a state that it is safe to pop the plan
1324 // with no more notice?
1328 // Now discard the master plan itself.
1329 // The bottom-most plan never gets discarded. "OkayToDiscard" for it
1330 // means discard it's dependent plans, but not it...
1331 if (master_plan_idx > 0) {
1335 // If the master plan doesn't want to get discarded, then we're done.
1341 bool Thread::PlanIsBasePlan(ThreadPlan *plan_ptr) {
1342 if (plan_ptr->IsBasePlan())
1344 else if (m_plan_stack.size() == 0)
1347 return m_plan_stack[0].get() == plan_ptr;
1350 Status Thread::UnwindInnermostExpression() {
1352 int stack_size = m_plan_stack.size();
1354 // If the input plan is nullptr, discard all plans. Otherwise make sure this
1355 // plan is in the stack, and if so discard up to and including it.
1357 for (int i = stack_size - 1; i > 0; i--) {
1358 if (m_plan_stack[i]->GetKind() == ThreadPlan::eKindCallFunction) {
1359 DiscardThreadPlansUpToPlan(m_plan_stack[i].get());
1363 error.SetErrorString("No expressions currently active on this thread");
1367 ThreadPlanSP Thread::QueueFundamentalPlan(bool abort_other_plans) {
1368 ThreadPlanSP thread_plan_sp(new ThreadPlanBase(*this));
1369 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1370 return thread_plan_sp;
1373 ThreadPlanSP Thread::QueueThreadPlanForStepSingleInstruction(
1374 bool step_over, bool abort_other_plans, bool stop_other_threads,
1376 ThreadPlanSP thread_plan_sp(new ThreadPlanStepInstruction(
1377 *this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
1378 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1379 return thread_plan_sp;
1382 ThreadPlanSP Thread::QueueThreadPlanForStepOverRange(
1383 bool abort_other_plans, const AddressRange &range,
1384 const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1385 Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
1386 ThreadPlanSP thread_plan_sp;
1387 thread_plan_sp.reset(new ThreadPlanStepOverRange(
1388 *this, range, addr_context, stop_other_threads,
1389 step_out_avoids_code_withoug_debug_info));
1391 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1392 return thread_plan_sp;
1395 // Call the QueueThreadPlanForStepOverRange method which takes an address
1397 ThreadPlanSP Thread::QueueThreadPlanForStepOverRange(
1398 bool abort_other_plans, const LineEntry &line_entry,
1399 const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1400 Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
1401 return QueueThreadPlanForStepOverRange(
1402 abort_other_plans, line_entry.GetSameLineContiguousAddressRange(),
1403 addr_context, stop_other_threads, status,
1404 step_out_avoids_code_withoug_debug_info);
1407 ThreadPlanSP Thread::QueueThreadPlanForStepInRange(
1408 bool abort_other_plans, const AddressRange &range,
1409 const SymbolContext &addr_context, const char *step_in_target,
1410 lldb::RunMode stop_other_threads, Status &status,
1411 LazyBool step_in_avoids_code_without_debug_info,
1412 LazyBool step_out_avoids_code_without_debug_info) {
1413 ThreadPlanSP thread_plan_sp(
1414 new ThreadPlanStepInRange(*this, range, addr_context, stop_other_threads,
1415 step_in_avoids_code_without_debug_info,
1416 step_out_avoids_code_without_debug_info));
1417 ThreadPlanStepInRange *plan =
1418 static_cast<ThreadPlanStepInRange *>(thread_plan_sp.get());
1421 plan->SetStepInTarget(step_in_target);
1423 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1424 return thread_plan_sp;
1427 // Call the QueueThreadPlanForStepInRange method which takes an address range.
1428 ThreadPlanSP Thread::QueueThreadPlanForStepInRange(
1429 bool abort_other_plans, const LineEntry &line_entry,
1430 const SymbolContext &addr_context, const char *step_in_target,
1431 lldb::RunMode stop_other_threads, Status &status,
1432 LazyBool step_in_avoids_code_without_debug_info,
1433 LazyBool step_out_avoids_code_without_debug_info) {
1434 return QueueThreadPlanForStepInRange(
1435 abort_other_plans, line_entry.GetSameLineContiguousAddressRange(),
1436 addr_context, step_in_target, stop_other_threads, status,
1437 step_in_avoids_code_without_debug_info,
1438 step_out_avoids_code_without_debug_info);
1441 ThreadPlanSP Thread::QueueThreadPlanForStepOut(
1442 bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1443 bool stop_other_threads, Vote stop_vote, Vote run_vote, uint32_t frame_idx,
1444 Status &status, LazyBool step_out_avoids_code_without_debug_info) {
1445 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1446 *this, addr_context, first_insn, stop_other_threads, stop_vote, run_vote,
1447 frame_idx, step_out_avoids_code_without_debug_info));
1449 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1450 return thread_plan_sp;
1453 ThreadPlanSP Thread::QueueThreadPlanForStepOutNoShouldStop(
1454 bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1455 bool stop_other_threads, Vote stop_vote, Vote run_vote, uint32_t frame_idx,
1456 Status &status, bool continue_to_next_branch) {
1457 const bool calculate_return_value =
1458 false; // No need to calculate the return value here.
1459 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1460 *this, addr_context, first_insn, stop_other_threads, stop_vote, run_vote,
1461 frame_idx, eLazyBoolNo, continue_to_next_branch, calculate_return_value));
1463 ThreadPlanStepOut *new_plan =
1464 static_cast<ThreadPlanStepOut *>(thread_plan_sp.get());
1465 new_plan->ClearShouldStopHereCallbacks();
1467 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1468 return thread_plan_sp;
1471 ThreadPlanSP Thread::QueueThreadPlanForStepThrough(StackID &return_stack_id,
1472 bool abort_other_plans,
1473 bool stop_other_threads,
1475 ThreadPlanSP thread_plan_sp(
1476 new ThreadPlanStepThrough(*this, return_stack_id, stop_other_threads));
1477 if (!thread_plan_sp || !thread_plan_sp->ValidatePlan(nullptr))
1478 return ThreadPlanSP();
1480 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1481 return thread_plan_sp;
1484 ThreadPlanSP Thread::QueueThreadPlanForRunToAddress(bool abort_other_plans,
1485 Address &target_addr,
1486 bool stop_other_threads,
1488 ThreadPlanSP thread_plan_sp(
1489 new ThreadPlanRunToAddress(*this, target_addr, stop_other_threads));
1491 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1492 return thread_plan_sp;
1495 ThreadPlanSP Thread::QueueThreadPlanForStepUntil(
1496 bool abort_other_plans, lldb::addr_t *address_list, size_t num_addresses,
1497 bool stop_other_threads, uint32_t frame_idx, Status &status) {
1498 ThreadPlanSP thread_plan_sp(new ThreadPlanStepUntil(
1499 *this, address_list, num_addresses, stop_other_threads, frame_idx));
1501 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1502 return thread_plan_sp;
1505 lldb::ThreadPlanSP Thread::QueueThreadPlanForStepScripted(
1506 bool abort_other_plans, const char *class_name, bool stop_other_threads,
1508 ThreadPlanSP thread_plan_sp(new ThreadPlanPython(*this, class_name));
1510 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1511 return thread_plan_sp;
1514 uint32_t Thread::GetIndexID() const { return m_index_id; }
1516 static void PrintPlanElement(Stream *s, const ThreadPlanSP &plan,
1517 lldb::DescriptionLevel desc_level,
1521 s->Printf("Element %d: ", elem_idx);
1522 plan->GetDescription(s, desc_level);
1527 static void PrintPlanStack(Stream *s,
1528 const std::vector<lldb::ThreadPlanSP> &plan_stack,
1529 lldb::DescriptionLevel desc_level,
1530 bool include_internal) {
1531 int32_t print_idx = 0;
1532 for (ThreadPlanSP plan_sp : plan_stack) {
1533 if (include_internal || !plan_sp->GetPrivate()) {
1534 PrintPlanElement(s, plan_sp, desc_level, print_idx++);
1539 void Thread::DumpThreadPlans(Stream *s, lldb::DescriptionLevel desc_level,
1540 bool include_internal,
1541 bool ignore_boring_threads) const {
1542 uint32_t stack_size;
1544 if (ignore_boring_threads) {
1545 uint32_t stack_size = m_plan_stack.size();
1546 uint32_t completed_stack_size = m_completed_plan_stack.size();
1547 uint32_t discarded_stack_size = m_discarded_plan_stack.size();
1548 if (stack_size == 1 && completed_stack_size == 0 &&
1549 discarded_stack_size == 0) {
1550 s->Printf("thread #%u: tid = 0x%4.4" PRIx64 "\n", GetIndexID(), GetID());
1553 s->Printf("No active thread plans\n");
1560 s->Printf("thread #%u: tid = 0x%4.4" PRIx64 ":\n", GetIndexID(), GetID());
1563 s->Printf("Active plan stack:\n");
1564 PrintPlanStack(s, m_plan_stack, desc_level, include_internal);
1566 stack_size = m_completed_plan_stack.size();
1567 if (stack_size > 0) {
1569 s->Printf("Completed Plan Stack:\n");
1570 PrintPlanStack(s, m_completed_plan_stack, desc_level, include_internal);
1573 stack_size = m_discarded_plan_stack.size();
1574 if (stack_size > 0) {
1576 s->Printf("Discarded Plan Stack:\n");
1577 PrintPlanStack(s, m_discarded_plan_stack, desc_level, include_internal);
1583 TargetSP Thread::CalculateTarget() {
1585 ProcessSP process_sp(GetProcess());
1587 target_sp = process_sp->CalculateTarget();
1591 ProcessSP Thread::CalculateProcess() { return GetProcess(); }
1593 ThreadSP Thread::CalculateThread() { return shared_from_this(); }
1595 StackFrameSP Thread::CalculateStackFrame() { return StackFrameSP(); }
1597 void Thread::CalculateExecutionContext(ExecutionContext &exe_ctx) {
1598 exe_ctx.SetContext(shared_from_this());
1601 StackFrameListSP Thread::GetStackFrameList() {
1602 StackFrameListSP frame_list_sp;
1603 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1604 if (m_curr_frames_sp) {
1605 frame_list_sp = m_curr_frames_sp;
1607 frame_list_sp.reset(new StackFrameList(*this, m_prev_frames_sp, true));
1608 m_curr_frames_sp = frame_list_sp;
1610 return frame_list_sp;
1613 void Thread::ClearStackFrames() {
1614 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1616 Unwind *unwinder = GetUnwinder();
1620 // Only store away the old "reference" StackFrameList if we got all its
1622 // FIXME: At some point we can try to splice in the frames we have fetched
1624 // the new frame as we make it, but let's not try that now.
1625 if (m_curr_frames_sp && m_curr_frames_sp->GetAllFramesFetched())
1626 m_prev_frames_sp.swap(m_curr_frames_sp);
1627 m_curr_frames_sp.reset();
1629 m_extended_info.reset();
1630 m_extended_info_fetched = false;
1633 lldb::StackFrameSP Thread::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) {
1634 return GetStackFrameList()->GetFrameWithConcreteFrameIndex(unwind_idx);
1637 Status Thread::ReturnFromFrameWithIndex(uint32_t frame_idx,
1638 lldb::ValueObjectSP return_value_sp,
1640 StackFrameSP frame_sp = GetStackFrameAtIndex(frame_idx);
1641 Status return_error;
1644 return_error.SetErrorStringWithFormat(
1645 "Could not find frame with index %d in thread 0x%" PRIx64 ".",
1646 frame_idx, GetID());
1649 return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
1652 Status Thread::ReturnFromFrame(lldb::StackFrameSP frame_sp,
1653 lldb::ValueObjectSP return_value_sp,
1655 Status return_error;
1658 return_error.SetErrorString("Can't return to a null frame.");
1659 return return_error;
1662 Thread *thread = frame_sp->GetThread().get();
1663 uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
1664 StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
1665 if (!older_frame_sp) {
1666 return_error.SetErrorString("No older frame to return to.");
1667 return return_error;
1670 if (return_value_sp) {
1671 lldb::ABISP abi = thread->GetProcess()->GetABI();
1673 return_error.SetErrorString("Could not find ABI to set return value.");
1674 return return_error;
1676 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
1678 // FIXME: ValueObject::Cast doesn't currently work correctly, at least not
1680 // Turn that back on when that works.
1681 if (/* DISABLES CODE */ (0) && sc.function != nullptr) {
1682 Type *function_type = sc.function->GetType();
1683 if (function_type) {
1684 CompilerType return_type =
1685 sc.function->GetCompilerType().GetFunctionReturnType();
1688 return_type.DumpTypeDescription(&s);
1689 ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type);
1690 if (cast_value_sp) {
1691 cast_value_sp->SetFormat(eFormatHex);
1692 return_value_sp = cast_value_sp;
1698 return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
1699 if (!return_error.Success())
1700 return return_error;
1703 // Now write the return registers for the chosen frame: Note, we can't use
1704 // ReadAllRegisterValues->WriteAllRegisterValues, since the read & write cook
1707 StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);
1708 if (youngest_frame_sp) {
1709 lldb::RegisterContextSP reg_ctx_sp(youngest_frame_sp->GetRegisterContext());
1711 bool copy_success = reg_ctx_sp->CopyFromRegisterContext(
1712 older_frame_sp->GetRegisterContext());
1714 thread->DiscardThreadPlans(true);
1715 thread->ClearStackFrames();
1716 if (broadcast && EventTypeHasListeners(eBroadcastBitStackChanged))
1717 BroadcastEvent(eBroadcastBitStackChanged,
1718 new ThreadEventData(this->shared_from_this()));
1720 return_error.SetErrorString("Could not reset register values.");
1723 return_error.SetErrorString("Frame has no register context.");
1726 return_error.SetErrorString("Returned past top frame.");
1728 return return_error;
1731 static void DumpAddressList(Stream &s, const std::vector<Address> &list,
1732 ExecutionContextScope *exe_scope) {
1733 for (size_t n = 0; n < list.size(); n++) {
1735 list[n].Dump(&s, exe_scope, Address::DumpStyleResolvedDescription,
1736 Address::DumpStyleSectionNameOffset);
1741 Status Thread::JumpToLine(const FileSpec &file, uint32_t line,
1742 bool can_leave_function, std::string *warnings) {
1743 ExecutionContext exe_ctx(GetStackFrameAtIndex(0));
1744 Target *target = exe_ctx.GetTargetPtr();
1745 TargetSP target_sp = exe_ctx.GetTargetSP();
1746 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1747 StackFrame *frame = exe_ctx.GetFramePtr();
1748 const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction);
1750 // Find candidate locations.
1751 std::vector<Address> candidates, within_function, outside_function;
1752 target->GetImages().FindAddressesForLine(target_sp, file, line, sc.function,
1753 within_function, outside_function);
1755 // If possible, we try and stay within the current function. Within a
1756 // function, we accept multiple locations (optimized code may do this,
1757 // there's no solution here so we do the best we can). However if we're
1758 // trying to leave the function, we don't know how to pick the right
1759 // location, so if there's more than one then we bail.
1760 if (!within_function.empty())
1761 candidates = within_function;
1762 else if (outside_function.size() == 1 && can_leave_function)
1763 candidates = outside_function;
1765 // Check if we got anything.
1766 if (candidates.empty()) {
1767 if (outside_function.empty()) {
1768 return Status("Cannot locate an address for %s:%i.",
1769 file.GetFilename().AsCString(), line);
1770 } else if (outside_function.size() == 1) {
1771 return Status("%s:%i is outside the current function.",
1772 file.GetFilename().AsCString(), line);
1775 DumpAddressList(sstr, outside_function, target);
1776 return Status("%s:%i has multiple candidate locations:\n%s",
1777 file.GetFilename().AsCString(), line, sstr.GetData());
1781 // Accept the first location, warn about any others.
1782 Address dest = candidates[0];
1783 if (warnings && candidates.size() > 1) {
1785 sstr.Printf("%s:%i appears multiple times in this function, selecting the "
1786 "first location:\n",
1787 file.GetFilename().AsCString(), line);
1788 DumpAddressList(sstr, candidates, target);
1789 *warnings = sstr.GetString();
1792 if (!reg_ctx->SetPC(dest))
1793 return Status("Cannot change PC to target address.");
1798 void Thread::DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx,
1800 ExecutionContext exe_ctx(shared_from_this());
1801 Process *process = exe_ctx.GetProcessPtr();
1802 if (process == nullptr)
1805 StackFrameSP frame_sp;
1806 SymbolContext frame_sc;
1807 if (frame_idx != LLDB_INVALID_FRAME_ID) {
1808 frame_sp = GetStackFrameAtIndex(frame_idx);
1810 exe_ctx.SetFrameSP(frame_sp);
1811 frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
1815 const FormatEntity::Entry *thread_format;
1817 thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadStopFormat();
1819 thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
1821 assert(thread_format);
1823 FormatEntity::Format(*thread_format, strm, frame_sp ? &frame_sc : nullptr,
1824 &exe_ctx, nullptr, nullptr, false, false);
1827 void Thread::SettingsInitialize() {}
1829 void Thread::SettingsTerminate() {}
1831 lldb::addr_t Thread::GetThreadPointer() { return LLDB_INVALID_ADDRESS; }
1833 addr_t Thread::GetThreadLocalData(const ModuleSP module,
1834 lldb::addr_t tls_file_addr) {
1835 // The default implementation is to ask the dynamic loader for it. This can
1836 // be overridden for specific platforms.
1837 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
1839 return loader->GetThreadLocalData(module, shared_from_this(),
1842 return LLDB_INVALID_ADDRESS;
1845 bool Thread::SafeToCallFunctions() {
1846 Process *process = GetProcess().get();
1848 SystemRuntime *runtime = process->GetSystemRuntime();
1850 return runtime->SafeToCallFunctionsOnThisThread(shared_from_this());
1857 Thread::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) {
1858 return GetStackFrameList()->GetStackFrameSPForStackFramePtr(stack_frame_ptr);
1861 const char *Thread::StopReasonAsCString(lldb::StopReason reason) {
1863 case eStopReasonInvalid:
1865 case eStopReasonNone:
1867 case eStopReasonTrace:
1869 case eStopReasonBreakpoint:
1870 return "breakpoint";
1871 case eStopReasonWatchpoint:
1872 return "watchpoint";
1873 case eStopReasonSignal:
1875 case eStopReasonException:
1877 case eStopReasonExec:
1879 case eStopReasonPlanComplete:
1880 return "plan complete";
1881 case eStopReasonThreadExiting:
1882 return "thread exiting";
1883 case eStopReasonInstrumentation:
1884 return "instrumentation break";
1887 static char unknown_state_string[64];
1888 snprintf(unknown_state_string, sizeof(unknown_state_string),
1889 "StopReason = %i", reason);
1890 return unknown_state_string;
1893 const char *Thread::RunModeAsCString(lldb::RunMode mode) {
1895 case eOnlyThisThread:
1896 return "only this thread";
1898 return "all threads";
1899 case eOnlyDuringStepping:
1900 return "only during stepping";
1903 static char unknown_state_string[64];
1904 snprintf(unknown_state_string, sizeof(unknown_state_string), "RunMode = %i",
1906 return unknown_state_string;
1909 size_t Thread::GetStatus(Stream &strm, uint32_t start_frame,
1910 uint32_t num_frames, uint32_t num_frames_with_source,
1911 bool stop_format, bool only_stacks) {
1914 ExecutionContext exe_ctx(shared_from_this());
1915 Target *target = exe_ctx.GetTargetPtr();
1916 Process *process = exe_ctx.GetProcessPtr();
1918 bool is_selected = false;
1920 if (process->GetThreadList().GetSelectedThread().get() == this)
1923 strm.Printf("%c ", is_selected ? '*' : ' ');
1924 if (target && target->GetDebugger().GetUseExternalEditor()) {
1925 StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
1927 SymbolContext frame_sc(
1928 frame_sp->GetSymbolContext(eSymbolContextLineEntry));
1929 if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file) {
1930 Host::OpenFileInExternalEditor(frame_sc.line_entry.file,
1931 frame_sc.line_entry.line);
1936 DumpUsingSettingsFormat(strm, start_frame, stop_format);
1939 size_t num_frames_shown = 0;
1940 if (num_frames > 0) {
1943 const bool show_frame_info = true;
1944 const bool show_frame_unique = only_stacks;
1945 const char *selected_frame_marker = nullptr;
1946 if (num_frames == 1 || only_stacks ||
1947 (GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID()))
1950 selected_frame_marker = "* ";
1952 num_frames_shown = GetStackFrameList()->GetStatus(
1953 strm, start_frame, num_frames, show_frame_info, num_frames_with_source,
1954 show_frame_unique, selected_frame_marker);
1955 if (num_frames == 1)
1959 return num_frames_shown;
1962 bool Thread::GetDescription(Stream &strm, lldb::DescriptionLevel level,
1963 bool print_json_thread, bool print_json_stopinfo) {
1964 const bool stop_format = false;
1965 DumpUsingSettingsFormat(strm, 0, stop_format);
1968 StructuredData::ObjectSP thread_info = GetExtendedInfo();
1970 if (print_json_thread || print_json_stopinfo) {
1971 if (thread_info && print_json_thread) {
1972 thread_info->Dump(strm);
1976 if (print_json_stopinfo && m_stop_info_sp) {
1977 StructuredData::ObjectSP stop_info = m_stop_info_sp->GetExtendedInfo();
1979 stop_info->Dump(strm);
1988 StructuredData::ObjectSP activity =
1989 thread_info->GetObjectForDotSeparatedPath("activity");
1990 StructuredData::ObjectSP breadcrumb =
1991 thread_info->GetObjectForDotSeparatedPath("breadcrumb");
1992 StructuredData::ObjectSP messages =
1993 thread_info->GetObjectForDotSeparatedPath("trace_messages");
1995 bool printed_activity = false;
1996 if (activity && activity->GetType() == eStructuredDataTypeDictionary) {
1997 StructuredData::Dictionary *activity_dict = activity->GetAsDictionary();
1998 StructuredData::ObjectSP id = activity_dict->GetValueForKey("id");
1999 StructuredData::ObjectSP name = activity_dict->GetValueForKey("name");
2000 if (name && name->GetType() == eStructuredDataTypeString && id &&
2001 id->GetType() == eStructuredDataTypeInteger) {
2002 strm.Format(" Activity '{0}', {1:x}\n",
2003 name->GetAsString()->GetValue(),
2004 id->GetAsInteger()->GetValue());
2006 printed_activity = true;
2008 bool printed_breadcrumb = false;
2009 if (breadcrumb && breadcrumb->GetType() == eStructuredDataTypeDictionary) {
2010 if (printed_activity)
2012 StructuredData::Dictionary *breadcrumb_dict =
2013 breadcrumb->GetAsDictionary();
2014 StructuredData::ObjectSP breadcrumb_text =
2015 breadcrumb_dict->GetValueForKey("name");
2016 if (breadcrumb_text &&
2017 breadcrumb_text->GetType() == eStructuredDataTypeString) {
2018 strm.Format(" Current Breadcrumb: {0}\n",
2019 breadcrumb_text->GetAsString()->GetValue());
2021 printed_breadcrumb = true;
2023 if (messages && messages->GetType() == eStructuredDataTypeArray) {
2024 if (printed_breadcrumb)
2026 StructuredData::Array *messages_array = messages->GetAsArray();
2027 const size_t msg_count = messages_array->GetSize();
2028 if (msg_count > 0) {
2029 strm.Printf(" %zu trace messages:\n", msg_count);
2030 for (size_t i = 0; i < msg_count; i++) {
2031 StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i);
2032 if (message && message->GetType() == eStructuredDataTypeDictionary) {
2033 StructuredData::Dictionary *message_dict =
2034 message->GetAsDictionary();
2035 StructuredData::ObjectSP message_text =
2036 message_dict->GetValueForKey("message");
2038 message_text->GetType() == eStructuredDataTypeString) {
2039 strm.Format(" {0}\n", message_text->GetAsString()->GetValue());
2050 size_t Thread::GetStackFrameStatus(Stream &strm, uint32_t first_frame,
2051 uint32_t num_frames, bool show_frame_info,
2052 uint32_t num_frames_with_source) {
2053 return GetStackFrameList()->GetStatus(
2054 strm, first_frame, num_frames, show_frame_info, num_frames_with_source);
2057 Unwind *Thread::GetUnwinder() {
2058 if (!m_unwinder_ap) {
2059 const ArchSpec target_arch(CalculateTarget()->GetArchitecture());
2060 const llvm::Triple::ArchType machine = target_arch.GetMachine();
2062 case llvm::Triple::x86_64:
2063 case llvm::Triple::x86:
2064 case llvm::Triple::arm:
2065 case llvm::Triple::aarch64:
2066 case llvm::Triple::thumb:
2067 case llvm::Triple::mips:
2068 case llvm::Triple::mipsel:
2069 case llvm::Triple::mips64:
2070 case llvm::Triple::mips64el:
2071 case llvm::Triple::ppc:
2072 case llvm::Triple::ppc64:
2073 case llvm::Triple::ppc64le:
2074 case llvm::Triple::systemz:
2075 case llvm::Triple::hexagon:
2076 m_unwinder_ap.reset(new UnwindLLDB(*this));
2080 if (target_arch.GetTriple().getVendor() == llvm::Triple::Apple)
2081 m_unwinder_ap.reset(new UnwindMacOSXFrameBackchain(*this));
2085 return m_unwinder_ap.get();
2088 void Thread::Flush() {
2090 m_reg_context_sp.reset();
2093 bool Thread::IsStillAtLastBreakpointHit() {
2094 // If we are currently stopped at a breakpoint, always return that stopinfo
2095 // and don't reset it. This allows threads to maintain their breakpoint
2096 // stopinfo, such as when thread-stepping in multithreaded programs.
2097 if (m_stop_info_sp) {
2098 StopReason stop_reason = m_stop_info_sp->GetStopReason();
2099 if (stop_reason == lldb::eStopReasonBreakpoint) {
2100 uint64_t value = m_stop_info_sp->GetValue();
2101 lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext());
2103 lldb::addr_t pc = reg_ctx_sp->GetPC();
2104 BreakpointSiteSP bp_site_sp =
2105 GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2106 if (bp_site_sp && static_cast<break_id_t>(value) == bp_site_sp->GetID())
2114 Status Thread::StepIn(bool source_step,
2115 LazyBool step_in_avoids_code_without_debug_info,
2116 LazyBool step_out_avoids_code_without_debug_info)
2120 Process *process = GetProcess().get();
2121 if (StateIsStoppedState(process->GetState(), true)) {
2122 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2123 ThreadPlanSP new_plan_sp;
2124 const lldb::RunMode run_mode = eOnlyThisThread;
2125 const bool abort_other_plans = false;
2127 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2128 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2129 new_plan_sp = QueueThreadPlanForStepInRange(
2130 abort_other_plans, sc.line_entry, sc, nullptr, run_mode, error,
2131 step_in_avoids_code_without_debug_info,
2132 step_out_avoids_code_without_debug_info);
2134 new_plan_sp = QueueThreadPlanForStepSingleInstruction(
2135 false, abort_other_plans, run_mode, error);
2138 new_plan_sp->SetIsMasterPlan(true);
2139 new_plan_sp->SetOkayToDiscard(false);
2141 // Why do we need to set the current thread by ID here???
2142 process->GetThreadList().SetSelectedThreadByID(GetID());
2143 error = process->Resume();
2145 error.SetErrorString("process not stopped");
2150 Status Thread::StepOver(bool source_step,
2151 LazyBool step_out_avoids_code_without_debug_info) {
2153 Process *process = GetProcess().get();
2154 if (StateIsStoppedState(process->GetState(), true)) {
2155 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2156 ThreadPlanSP new_plan_sp;
2158 const lldb::RunMode run_mode = eOnlyThisThread;
2159 const bool abort_other_plans = false;
2161 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2162 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2163 new_plan_sp = QueueThreadPlanForStepOverRange(
2164 abort_other_plans, sc.line_entry, sc, run_mode, error,
2165 step_out_avoids_code_without_debug_info);
2167 new_plan_sp = QueueThreadPlanForStepSingleInstruction(
2168 true, abort_other_plans, run_mode, error);
2171 new_plan_sp->SetIsMasterPlan(true);
2172 new_plan_sp->SetOkayToDiscard(false);
2174 // Why do we need to set the current thread by ID here???
2175 process->GetThreadList().SetSelectedThreadByID(GetID());
2176 error = process->Resume();
2178 error.SetErrorString("process not stopped");
2183 Status Thread::StepOut() {
2185 Process *process = GetProcess().get();
2186 if (StateIsStoppedState(process->GetState(), true)) {
2187 const bool first_instruction = false;
2188 const bool stop_other_threads = false;
2189 const bool abort_other_plans = false;
2191 ThreadPlanSP new_plan_sp(QueueThreadPlanForStepOut(
2192 abort_other_plans, nullptr, first_instruction, stop_other_threads,
2193 eVoteYes, eVoteNoOpinion, 0, error));
2195 new_plan_sp->SetIsMasterPlan(true);
2196 new_plan_sp->SetOkayToDiscard(false);
2198 // Why do we need to set the current thread by ID here???
2199 process->GetThreadList().SetSelectedThreadByID(GetID());
2200 error = process->Resume();
2202 error.SetErrorString("process not stopped");
2207 ValueObjectSP Thread::GetCurrentException() {
2208 if (auto frame_sp = GetStackFrameAtIndex(0))
2209 if (auto recognized_frame = frame_sp->GetRecognizedFrame())
2210 if (auto e = recognized_frame->GetExceptionObject())
2213 // FIXME: For now, only ObjC exceptions are supported. This should really
2214 // iterate over all language runtimes and ask them all to give us the current
2216 if (auto runtime = GetProcess()->GetObjCLanguageRuntime())
2217 if (auto e = runtime->GetExceptionObjectForThread(shared_from_this()))
2220 return ValueObjectSP();
2223 ThreadSP Thread::GetCurrentExceptionBacktrace() {
2224 ValueObjectSP exception = GetCurrentException();
2225 if (!exception) return ThreadSP();
2227 // FIXME: For now, only ObjC exceptions are supported. This should really
2228 // iterate over all language runtimes and ask them all to give us the current
2230 auto runtime = GetProcess()->GetObjCLanguageRuntime();
2231 if (!runtime) return ThreadSP();
2233 return runtime->GetBacktraceThreadFromException(exception);