Reland "[lldb] Implement basic support for reverse-continue" (#125242)
[llvm-project.git] / lldb / source / Target / Thread.cpp
blob2c4d925c7322276834fe9753d50eed4f3d6db902
1 //===-- Thread.cpp --------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Target/Thread.h"
10 #include "lldb/Breakpoint/BreakpointLocation.h"
11 #include "lldb/Core/Debugger.h"
12 #include "lldb/Core/FormatEntity.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/StructuredDataImpl.h"
15 #include "lldb/Host/Host.h"
16 #include "lldb/Interpreter/OptionValueFileSpecList.h"
17 #include "lldb/Interpreter/OptionValueProperties.h"
18 #include "lldb/Interpreter/Property.h"
19 #include "lldb/Symbol/Function.h"
20 #include "lldb/Target/ABI.h"
21 #include "lldb/Target/DynamicLoader.h"
22 #include "lldb/Target/ExecutionContext.h"
23 #include "lldb/Target/LanguageRuntime.h"
24 #include "lldb/Target/Process.h"
25 #include "lldb/Target/RegisterContext.h"
26 #include "lldb/Target/ScriptedThreadPlan.h"
27 #include "lldb/Target/StackFrameRecognizer.h"
28 #include "lldb/Target/StopInfo.h"
29 #include "lldb/Target/SystemRuntime.h"
30 #include "lldb/Target/Target.h"
31 #include "lldb/Target/ThreadPlan.h"
32 #include "lldb/Target/ThreadPlanBase.h"
33 #include "lldb/Target/ThreadPlanCallFunction.h"
34 #include "lldb/Target/ThreadPlanRunToAddress.h"
35 #include "lldb/Target/ThreadPlanStack.h"
36 #include "lldb/Target/ThreadPlanStepInRange.h"
37 #include "lldb/Target/ThreadPlanStepInstruction.h"
38 #include "lldb/Target/ThreadPlanStepOut.h"
39 #include "lldb/Target/ThreadPlanStepOverBreakpoint.h"
40 #include "lldb/Target/ThreadPlanStepOverRange.h"
41 #include "lldb/Target/ThreadPlanStepThrough.h"
42 #include "lldb/Target/ThreadPlanStepUntil.h"
43 #include "lldb/Target/ThreadSpec.h"
44 #include "lldb/Target/UnwindLLDB.h"
45 #include "lldb/Utility/LLDBLog.h"
46 #include "lldb/Utility/Log.h"
47 #include "lldb/Utility/RegularExpression.h"
48 #include "lldb/Utility/State.h"
49 #include "lldb/Utility/Stream.h"
50 #include "lldb/Utility/StreamString.h"
51 #include "lldb/ValueObject/ValueObject.h"
52 #include "lldb/ValueObject/ValueObjectConstResult.h"
53 #include "lldb/lldb-enumerations.h"
55 #include <memory>
56 #include <optional>
58 using namespace lldb;
59 using namespace lldb_private;
61 ThreadProperties &Thread::GetGlobalProperties() {
62 // NOTE: intentional leak so we don't crash if global destructor chain gets
63 // called as other threads still use the result of this function
64 static ThreadProperties *g_settings_ptr = new ThreadProperties(true);
65 return *g_settings_ptr;
68 #define LLDB_PROPERTIES_thread
69 #include "TargetProperties.inc"
71 enum {
72 #define LLDB_PROPERTIES_thread
73 #include "TargetPropertiesEnum.inc"
76 class ThreadOptionValueProperties
77 : public Cloneable<ThreadOptionValueProperties, OptionValueProperties> {
78 public:
79 ThreadOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}
81 const Property *
82 GetPropertyAtIndex(size_t idx,
83 const ExecutionContext *exe_ctx) const override {
84 // When getting the value for a key from the thread options, we will always
85 // try and grab the setting from the current thread if there is one. Else
86 // we just use the one from this instance.
87 if (exe_ctx) {
88 Thread *thread = exe_ctx->GetThreadPtr();
89 if (thread) {
90 ThreadOptionValueProperties *instance_properties =
91 static_cast<ThreadOptionValueProperties *>(
92 thread->GetValueProperties().get());
93 if (this != instance_properties)
94 return instance_properties->ProtectedGetPropertyAtIndex(idx);
97 return ProtectedGetPropertyAtIndex(idx);
101 ThreadProperties::ThreadProperties(bool is_global) : Properties() {
102 if (is_global) {
103 m_collection_sp = std::make_shared<ThreadOptionValueProperties>("thread");
104 m_collection_sp->Initialize(g_thread_properties);
105 } else
106 m_collection_sp =
107 OptionValueProperties::CreateLocalCopy(Thread::GetGlobalProperties());
110 ThreadProperties::~ThreadProperties() = default;
112 const RegularExpression *ThreadProperties::GetSymbolsToAvoidRegexp() {
113 const uint32_t idx = ePropertyStepAvoidRegex;
114 return GetPropertyAtIndexAs<const RegularExpression *>(idx);
117 FileSpecList ThreadProperties::GetLibrariesToAvoid() const {
118 const uint32_t idx = ePropertyStepAvoidLibraries;
119 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
122 bool ThreadProperties::GetTraceEnabledState() const {
123 const uint32_t idx = ePropertyEnableThreadTrace;
124 return GetPropertyAtIndexAs<bool>(
125 idx, g_thread_properties[idx].default_uint_value != 0);
128 bool ThreadProperties::GetStepInAvoidsNoDebug() const {
129 const uint32_t idx = ePropertyStepInAvoidsNoDebug;
130 return GetPropertyAtIndexAs<bool>(
131 idx, g_thread_properties[idx].default_uint_value != 0);
134 bool ThreadProperties::GetStepOutAvoidsNoDebug() const {
135 const uint32_t idx = ePropertyStepOutAvoidsNoDebug;
136 return GetPropertyAtIndexAs<bool>(
137 idx, g_thread_properties[idx].default_uint_value != 0);
140 uint64_t ThreadProperties::GetMaxBacktraceDepth() const {
141 const uint32_t idx = ePropertyMaxBacktraceDepth;
142 return GetPropertyAtIndexAs<uint64_t>(
143 idx, g_thread_properties[idx].default_uint_value);
146 uint64_t ThreadProperties::GetSingleThreadPlanTimeout() const {
147 const uint32_t idx = ePropertySingleThreadPlanTimeout;
148 return GetPropertyAtIndexAs<uint64_t>(
149 idx, g_thread_properties[idx].default_uint_value);
152 // Thread Event Data
154 llvm::StringRef Thread::ThreadEventData::GetFlavorString() {
155 return "Thread::ThreadEventData";
158 Thread::ThreadEventData::ThreadEventData(const lldb::ThreadSP thread_sp)
159 : m_thread_sp(thread_sp), m_stack_id() {}
161 Thread::ThreadEventData::ThreadEventData(const lldb::ThreadSP thread_sp,
162 const StackID &stack_id)
163 : m_thread_sp(thread_sp), m_stack_id(stack_id) {}
165 Thread::ThreadEventData::ThreadEventData() : m_thread_sp(), m_stack_id() {}
167 Thread::ThreadEventData::~ThreadEventData() = default;
169 void Thread::ThreadEventData::Dump(Stream *s) const {}
171 const Thread::ThreadEventData *
172 Thread::ThreadEventData::GetEventDataFromEvent(const Event *event_ptr) {
173 if (event_ptr) {
174 const EventData *event_data = event_ptr->GetData();
175 if (event_data &&
176 event_data->GetFlavor() == ThreadEventData::GetFlavorString())
177 return static_cast<const ThreadEventData *>(event_ptr->GetData());
179 return nullptr;
182 ThreadSP Thread::ThreadEventData::GetThreadFromEvent(const Event *event_ptr) {
183 ThreadSP thread_sp;
184 const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
185 if (event_data)
186 thread_sp = event_data->GetThread();
187 return thread_sp;
190 StackID Thread::ThreadEventData::GetStackIDFromEvent(const Event *event_ptr) {
191 StackID stack_id;
192 const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
193 if (event_data)
194 stack_id = event_data->GetStackID();
195 return stack_id;
198 StackFrameSP
199 Thread::ThreadEventData::GetStackFrameFromEvent(const Event *event_ptr) {
200 const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
201 StackFrameSP frame_sp;
202 if (event_data) {
203 ThreadSP thread_sp = event_data->GetThread();
204 if (thread_sp) {
205 frame_sp = thread_sp->GetStackFrameList()->GetFrameWithStackID(
206 event_data->GetStackID());
209 return frame_sp;
212 // Thread class
214 llvm::StringRef Thread::GetStaticBroadcasterClass() {
215 static constexpr llvm::StringLiteral class_name("lldb.thread");
216 return class_name;
219 Thread::Thread(Process &process, lldb::tid_t tid, bool use_invalid_index_id)
220 : ThreadProperties(false), UserID(tid),
221 Broadcaster(process.GetTarget().GetDebugger().GetBroadcasterManager(),
222 Thread::GetStaticBroadcasterClass().str()),
223 m_process_wp(process.shared_from_this()), m_stop_info_sp(),
224 m_stop_info_stop_id(0), m_stop_info_override_stop_id(0),
225 m_should_run_before_public_stop(false),
226 m_index_id(use_invalid_index_id ? LLDB_INVALID_INDEX32
227 : process.GetNextThreadIndexID(tid)),
228 m_reg_context_sp(), m_state(eStateUnloaded), m_state_mutex(),
229 m_frame_mutex(), m_curr_frames_sp(), m_prev_frames_sp(),
230 m_prev_framezero_pc(), m_resume_signal(LLDB_INVALID_SIGNAL_NUMBER),
231 m_resume_state(eStateRunning), m_temporary_resume_state(eStateRunning),
232 m_unwinder_up(), m_destroy_called(false),
233 m_override_should_notify(eLazyBoolCalculate),
234 m_extended_info_fetched(false), m_extended_info() {
235 Log *log = GetLog(LLDBLog::Object);
236 LLDB_LOGF(log, "%p Thread::Thread(tid = 0x%4.4" PRIx64 ")",
237 static_cast<void *>(this), GetID());
239 CheckInWithManager();
242 Thread::~Thread() {
243 Log *log = GetLog(LLDBLog::Object);
244 LLDB_LOGF(log, "%p Thread::~Thread(tid = 0x%4.4" PRIx64 ")",
245 static_cast<void *>(this), GetID());
246 /// If you hit this assert, it means your derived class forgot to call
247 /// DestroyThread in its destructor.
248 assert(m_destroy_called);
251 void Thread::DestroyThread() {
252 m_destroy_called = true;
253 m_stop_info_sp.reset();
254 m_reg_context_sp.reset();
255 m_unwinder_up.reset();
256 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
257 m_curr_frames_sp.reset();
258 m_prev_frames_sp.reset();
259 m_prev_framezero_pc.reset();
262 void Thread::BroadcastSelectedFrameChange(StackID &new_frame_id) {
263 if (EventTypeHasListeners(eBroadcastBitSelectedFrameChanged)) {
264 auto data_sp =
265 std::make_shared<ThreadEventData>(shared_from_this(), new_frame_id);
266 BroadcastEvent(eBroadcastBitSelectedFrameChanged, data_sp);
270 lldb::StackFrameSP
271 Thread::GetSelectedFrame(SelectMostRelevant select_most_relevant) {
272 StackFrameListSP stack_frame_list_sp(GetStackFrameList());
273 StackFrameSP frame_sp = stack_frame_list_sp->GetFrameAtIndex(
274 stack_frame_list_sp->GetSelectedFrameIndex(select_most_relevant));
275 FrameSelectedCallback(frame_sp.get());
276 return frame_sp;
279 uint32_t Thread::SetSelectedFrame(lldb_private::StackFrame *frame,
280 bool broadcast) {
281 uint32_t ret_value = GetStackFrameList()->SetSelectedFrame(frame);
282 if (broadcast)
283 BroadcastSelectedFrameChange(frame->GetStackID());
284 FrameSelectedCallback(frame);
285 return ret_value;
288 bool Thread::SetSelectedFrameByIndex(uint32_t frame_idx, bool broadcast) {
289 StackFrameSP frame_sp(GetStackFrameList()->GetFrameAtIndex(frame_idx));
290 if (frame_sp) {
291 GetStackFrameList()->SetSelectedFrame(frame_sp.get());
292 if (broadcast)
293 BroadcastSelectedFrameChange(frame_sp->GetStackID());
294 FrameSelectedCallback(frame_sp.get());
295 return true;
296 } else
297 return false;
300 bool Thread::SetSelectedFrameByIndexNoisily(uint32_t frame_idx,
301 Stream &output_stream) {
302 const bool broadcast = true;
303 bool success = SetSelectedFrameByIndex(frame_idx, broadcast);
304 if (success) {
305 StackFrameSP frame_sp = GetSelectedFrame(DoNoSelectMostRelevantFrame);
306 if (frame_sp) {
307 bool already_shown = false;
308 SymbolContext frame_sc(
309 frame_sp->GetSymbolContext(eSymbolContextLineEntry));
310 const Debugger &debugger = GetProcess()->GetTarget().GetDebugger();
311 if (debugger.GetUseExternalEditor() && frame_sc.line_entry.GetFile() &&
312 frame_sc.line_entry.line != 0) {
313 if (llvm::Error e = Host::OpenFileInExternalEditor(
314 debugger.GetExternalEditor(), frame_sc.line_entry.GetFile(),
315 frame_sc.line_entry.line)) {
316 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), std::move(e),
317 "OpenFileInExternalEditor failed: {0}");
318 } else {
319 already_shown = true;
323 bool show_frame_info = true;
324 bool show_source = !already_shown;
325 FrameSelectedCallback(frame_sp.get());
326 return frame_sp->GetStatus(output_stream, show_frame_info, show_source);
328 return false;
329 } else
330 return false;
333 void Thread::FrameSelectedCallback(StackFrame *frame) {
334 if (!frame)
335 return;
337 if (frame->HasDebugInformation() &&
338 (GetProcess()->GetWarningsOptimization() ||
339 GetProcess()->GetWarningsUnsupportedLanguage())) {
340 SymbolContext sc =
341 frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextModule);
342 GetProcess()->PrintWarningOptimization(sc);
343 GetProcess()->PrintWarningUnsupportedLanguage(sc);
347 lldb::StopInfoSP Thread::GetStopInfo() {
348 if (m_destroy_called)
349 return m_stop_info_sp;
351 ThreadPlanSP completed_plan_sp(GetCompletedPlan());
352 ProcessSP process_sp(GetProcess());
353 const uint32_t stop_id = process_sp ? process_sp->GetStopID() : UINT32_MAX;
355 // Here we select the stop info according to priorirty: - m_stop_info_sp (if
356 // not trace) - preset value - completed plan stop info - new value with plan
357 // from completed plan stack - m_stop_info_sp (trace stop reason is OK now) -
358 // ask GetPrivateStopInfo to set stop info
360 bool have_valid_stop_info = m_stop_info_sp &&
361 m_stop_info_sp ->IsValid() &&
362 m_stop_info_stop_id == stop_id;
363 bool have_valid_completed_plan = completed_plan_sp && completed_plan_sp->PlanSucceeded();
364 bool plan_failed = completed_plan_sp && !completed_plan_sp->PlanSucceeded();
365 bool plan_overrides_trace =
366 have_valid_stop_info && have_valid_completed_plan
367 && (m_stop_info_sp->GetStopReason() == eStopReasonTrace);
369 if (have_valid_stop_info && !plan_overrides_trace && !plan_failed) {
370 return m_stop_info_sp;
371 } else if (completed_plan_sp) {
372 return StopInfo::CreateStopReasonWithPlan(
373 completed_plan_sp, GetReturnValueObject(), GetExpressionVariable());
374 } else {
375 GetPrivateStopInfo();
376 return m_stop_info_sp;
380 void Thread::CalculatePublicStopInfo() {
381 ResetStopInfo();
382 SetStopInfo(GetStopInfo());
385 lldb::StopInfoSP Thread::GetPrivateStopInfo(bool calculate) {
386 if (!calculate)
387 return m_stop_info_sp;
389 if (m_destroy_called)
390 return m_stop_info_sp;
392 ProcessSP process_sp(GetProcess());
393 if (process_sp) {
394 const uint32_t process_stop_id = process_sp->GetStopID();
395 if (m_stop_info_stop_id != process_stop_id) {
396 // We preserve the old stop info for a variety of reasons:
397 // 1) Someone has already updated it by the time we get here
398 // 2) We didn't get to execute the breakpoint instruction we stopped at
399 // 3) This is a virtual step so we didn't actually run
400 // 4) If this thread wasn't allowed to run the last time round.
401 if (m_stop_info_sp) {
402 if (m_stop_info_sp->IsValid() || IsStillAtLastBreakpointHit() ||
403 GetCurrentPlan()->IsVirtualStep()
404 || GetTemporaryResumeState() == eStateSuspended)
405 SetStopInfo(m_stop_info_sp);
406 else
407 m_stop_info_sp.reset();
410 if (!m_stop_info_sp) {
411 if (!CalculateStopInfo())
412 SetStopInfo(StopInfoSP());
416 // The stop info can be manually set by calling Thread::SetStopInfo() prior
417 // to this function ever getting called, so we can't rely on
418 // "m_stop_info_stop_id != process_stop_id" as the condition for the if
419 // statement below, we must also check the stop info to see if we need to
420 // override it. See the header documentation in
421 // Architecture::OverrideStopInfo() for more information on the stop
422 // info override callback.
423 if (m_stop_info_override_stop_id != process_stop_id) {
424 m_stop_info_override_stop_id = process_stop_id;
425 if (m_stop_info_sp) {
426 if (const Architecture *arch =
427 process_sp->GetTarget().GetArchitecturePlugin())
428 arch->OverrideStopInfo(*this);
433 // If we were resuming the process and it was interrupted,
434 // return no stop reason. This thread would like to resume.
435 if (m_stop_info_sp && m_stop_info_sp->WasContinueInterrupted(*this))
436 return {};
438 return m_stop_info_sp;
441 lldb::StopReason Thread::GetStopReason() {
442 lldb::StopInfoSP stop_info_sp(GetStopInfo());
443 if (stop_info_sp)
444 return stop_info_sp->GetStopReason();
445 return eStopReasonNone;
448 bool Thread::StopInfoIsUpToDate() const {
449 ProcessSP process_sp(GetProcess());
450 if (process_sp)
451 return m_stop_info_stop_id == process_sp->GetStopID();
452 else
453 return true; // Process is no longer around so stop info is always up to
454 // date...
457 void Thread::ResetStopInfo() {
458 if (m_stop_info_sp) {
459 m_stop_info_sp.reset();
463 void Thread::SetStopInfo(const lldb::StopInfoSP &stop_info_sp) {
464 m_stop_info_sp = stop_info_sp;
465 if (m_stop_info_sp) {
466 m_stop_info_sp->MakeStopInfoValid();
467 // If we are overriding the ShouldReportStop, do that here:
468 if (m_override_should_notify != eLazyBoolCalculate)
469 m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==
470 eLazyBoolYes);
473 ProcessSP process_sp(GetProcess());
474 if (process_sp)
475 m_stop_info_stop_id = process_sp->GetStopID();
476 else
477 m_stop_info_stop_id = UINT32_MAX;
478 Log *log = GetLog(LLDBLog::Thread);
479 LLDB_LOGF(log, "%p: tid = 0x%" PRIx64 ": stop info = %s (stop_id = %u)",
480 static_cast<void *>(this), GetID(),
481 stop_info_sp ? stop_info_sp->GetDescription() : "<NULL>",
482 m_stop_info_stop_id);
485 void Thread::SetShouldReportStop(Vote vote) {
486 if (vote == eVoteNoOpinion)
487 return;
488 else {
489 m_override_should_notify = (vote == eVoteYes ? eLazyBoolYes : eLazyBoolNo);
490 if (m_stop_info_sp)
491 m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==
492 eLazyBoolYes);
496 void Thread::SetStopInfoToNothing() {
497 // Note, we can't just NULL out the private reason, or the native thread
498 // implementation will try to go calculate it again. For now, just set it to
499 // a Unix Signal with an invalid signal number.
500 SetStopInfo(
501 StopInfo::CreateStopReasonWithSignal(*this, LLDB_INVALID_SIGNAL_NUMBER));
504 bool Thread::ThreadStoppedForAReason() { return (bool)GetPrivateStopInfo(); }
506 bool Thread::CheckpointThreadState(ThreadStateCheckpoint &saved_state) {
507 saved_state.register_backup_sp.reset();
508 lldb::StackFrameSP frame_sp(GetStackFrameAtIndex(0));
509 if (frame_sp) {
510 lldb::RegisterCheckpointSP reg_checkpoint_sp(
511 new RegisterCheckpoint(RegisterCheckpoint::Reason::eExpression));
512 if (reg_checkpoint_sp) {
513 lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());
514 if (reg_ctx_sp && reg_ctx_sp->ReadAllRegisterValues(*reg_checkpoint_sp))
515 saved_state.register_backup_sp = reg_checkpoint_sp;
518 if (!saved_state.register_backup_sp)
519 return false;
521 saved_state.stop_info_sp = GetStopInfo();
522 ProcessSP process_sp(GetProcess());
523 if (process_sp)
524 saved_state.orig_stop_id = process_sp->GetStopID();
525 saved_state.current_inlined_depth = GetCurrentInlinedDepth();
526 saved_state.m_completed_plan_checkpoint =
527 GetPlans().CheckpointCompletedPlans();
529 return true;
532 bool Thread::RestoreRegisterStateFromCheckpoint(
533 ThreadStateCheckpoint &saved_state) {
534 if (saved_state.register_backup_sp) {
535 lldb::StackFrameSP frame_sp(GetStackFrameAtIndex(0));
536 if (frame_sp) {
537 lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());
538 if (reg_ctx_sp) {
539 bool ret =
540 reg_ctx_sp->WriteAllRegisterValues(*saved_state.register_backup_sp);
542 // Clear out all stack frames as our world just changed.
543 ClearStackFrames();
544 reg_ctx_sp->InvalidateIfNeeded(true);
545 if (m_unwinder_up)
546 m_unwinder_up->Clear();
547 return ret;
551 return false;
554 void Thread::RestoreThreadStateFromCheckpoint(
555 ThreadStateCheckpoint &saved_state) {
556 if (saved_state.stop_info_sp)
557 saved_state.stop_info_sp->MakeStopInfoValid();
558 SetStopInfo(saved_state.stop_info_sp);
559 GetStackFrameList()->SetCurrentInlinedDepth(
560 saved_state.current_inlined_depth);
561 GetPlans().RestoreCompletedPlanCheckpoint(
562 saved_state.m_completed_plan_checkpoint);
565 StateType Thread::GetState() const {
566 // If any other threads access this we will need a mutex for it
567 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
568 return m_state;
571 void Thread::SetState(StateType state) {
572 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
573 m_state = state;
576 std::string Thread::GetStopDescription() {
577 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
579 if (!frame_sp)
580 return GetStopDescriptionRaw();
582 auto recognized_frame_sp = frame_sp->GetRecognizedFrame();
584 if (!recognized_frame_sp)
585 return GetStopDescriptionRaw();
587 std::string recognized_stop_description =
588 recognized_frame_sp->GetStopDescription();
590 if (!recognized_stop_description.empty())
591 return recognized_stop_description;
593 return GetStopDescriptionRaw();
596 std::string Thread::GetStopDescriptionRaw() {
597 StopInfoSP stop_info_sp = GetStopInfo();
598 std::string raw_stop_description;
599 if (stop_info_sp && stop_info_sp->IsValid()) {
600 raw_stop_description = stop_info_sp->GetDescription();
601 assert((!raw_stop_description.empty() ||
602 stop_info_sp->GetStopReason() == eStopReasonNone) &&
603 "StopInfo returned an empty description.");
605 return raw_stop_description;
608 void Thread::WillStop() {
609 ThreadPlan *current_plan = GetCurrentPlan();
611 // FIXME: I may decide to disallow threads with no plans. In which
612 // case this should go to an assert.
614 if (!current_plan)
615 return;
617 current_plan->WillStop();
620 bool Thread::SetupToStepOverBreakpointIfNeeded(RunDirection direction) {
621 if (GetResumeState() != eStateSuspended) {
622 // First check whether this thread is going to "actually" resume at all.
623 // For instance, if we're stepping from one level to the next of an
624 // virtual inlined call stack, we just change the inlined call stack index
625 // without actually running this thread. In that case, for this thread we
626 // shouldn't push a step over breakpoint plan or do that work.
627 if (GetCurrentPlan()->IsVirtualStep())
628 return false;
630 // If we're at a breakpoint push the step-over breakpoint plan. Do this
631 // before telling the current plan it will resume, since we might change
632 // what the current plan is.
634 lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext());
635 ProcessSP process_sp(GetProcess());
636 if (reg_ctx_sp && process_sp && direction == eRunForward) {
637 const addr_t thread_pc = reg_ctx_sp->GetPC();
638 BreakpointSiteSP bp_site_sp =
639 process_sp->GetBreakpointSiteList().FindByAddress(thread_pc);
640 if (bp_site_sp) {
641 // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the
642 // target may not require anything special to step over a breakpoint.
644 ThreadPlan *cur_plan = GetCurrentPlan();
646 bool push_step_over_bp_plan = false;
647 if (cur_plan->GetKind() == ThreadPlan::eKindStepOverBreakpoint) {
648 ThreadPlanStepOverBreakpoint *bp_plan =
649 (ThreadPlanStepOverBreakpoint *)cur_plan;
650 if (bp_plan->GetBreakpointLoadAddress() != thread_pc)
651 push_step_over_bp_plan = true;
652 } else
653 push_step_over_bp_plan = true;
655 if (push_step_over_bp_plan) {
656 ThreadPlanSP step_bp_plan_sp(new ThreadPlanStepOverBreakpoint(*this));
657 if (step_bp_plan_sp) {
658 step_bp_plan_sp->SetPrivate(true);
660 if (GetCurrentPlan()->RunState() != eStateStepping) {
661 ThreadPlanStepOverBreakpoint *step_bp_plan =
662 static_cast<ThreadPlanStepOverBreakpoint *>(
663 step_bp_plan_sp.get());
664 step_bp_plan->SetAutoContinue(true);
666 QueueThreadPlan(step_bp_plan_sp, false);
667 return true;
673 return false;
676 bool Thread::ShouldResume(StateType resume_state) {
677 // At this point clear the completed plan stack.
678 GetPlans().WillResume();
679 m_override_should_notify = eLazyBoolCalculate;
681 StateType prev_resume_state = GetTemporaryResumeState();
683 SetTemporaryResumeState(resume_state);
685 lldb::ThreadSP backing_thread_sp(GetBackingThread());
686 if (backing_thread_sp)
687 backing_thread_sp->SetTemporaryResumeState(resume_state);
689 // Make sure m_stop_info_sp is valid. Don't do this for threads we suspended
690 // in the previous run.
691 if (prev_resume_state != eStateSuspended)
692 GetPrivateStopInfo();
694 // This is a little dubious, but we are trying to limit how often we actually
695 // fetch stop info from the target, 'cause that slows down single stepping.
696 // So assume that if we got to the point where we're about to resume, and we
697 // haven't yet had to fetch the stop reason, then it doesn't need to know
698 // about the fact that we are resuming...
699 const uint32_t process_stop_id = GetProcess()->GetStopID();
700 if (m_stop_info_stop_id == process_stop_id &&
701 (m_stop_info_sp && m_stop_info_sp->IsValid())) {
702 StopInfo *stop_info = GetPrivateStopInfo().get();
703 if (stop_info)
704 stop_info->WillResume(resume_state);
707 // Tell all the plans that we are about to resume in case they need to clear
708 // any state. We distinguish between the plan on the top of the stack and the
709 // lower plans in case a plan needs to do any special business before it
710 // runs.
712 bool need_to_resume = false;
713 ThreadPlan *plan_ptr = GetCurrentPlan();
714 if (plan_ptr) {
715 need_to_resume = plan_ptr->WillResume(resume_state, true);
717 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
718 plan_ptr->WillResume(resume_state, false);
721 // If the WillResume for the plan says we are faking a resume, then it will
722 // have set an appropriate stop info. In that case, don't reset it here.
724 if (need_to_resume && resume_state != eStateSuspended) {
725 m_stop_info_sp.reset();
729 if (need_to_resume) {
730 ClearStackFrames();
731 // Let Thread subclasses do any special work they need to prior to resuming
732 WillResume(resume_state);
735 return need_to_resume;
738 void Thread::DidResume() {
739 SetResumeSignal(LLDB_INVALID_SIGNAL_NUMBER);
740 // This will get recomputed each time when we stop.
741 SetShouldRunBeforePublicStop(false);
744 void Thread::DidStop() { SetState(eStateStopped); }
746 bool Thread::ShouldStop(Event *event_ptr) {
747 ThreadPlan *current_plan = GetCurrentPlan();
749 bool should_stop = true;
751 Log *log = GetLog(LLDBLog::Step);
753 if (GetResumeState() == eStateSuspended) {
754 LLDB_LOGF(log,
755 "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
756 ", should_stop = 0 (ignore since thread was suspended)",
757 __FUNCTION__, GetID(), GetProtocolID());
758 return false;
761 if (GetTemporaryResumeState() == eStateSuspended) {
762 LLDB_LOGF(log,
763 "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
764 ", should_stop = 0 (ignore since thread was suspended)",
765 __FUNCTION__, GetID(), GetProtocolID());
766 return false;
769 // Based on the current thread plan and process stop info, check if this
770 // thread caused the process to stop. NOTE: this must take place before the
771 // plan is moved from the current plan stack to the completed plan stack.
772 if (!ThreadStoppedForAReason()) {
773 LLDB_LOGF(log,
774 "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
775 ", pc = 0x%16.16" PRIx64
776 ", should_stop = 0 (ignore since no stop reason)",
777 __FUNCTION__, GetID(), GetProtocolID(),
778 GetRegisterContext() ? GetRegisterContext()->GetPC()
779 : LLDB_INVALID_ADDRESS);
780 return false;
783 // Clear the "must run me before stop" if it was set:
784 SetShouldRunBeforePublicStop(false);
786 if (log) {
787 LLDB_LOGF(log,
788 "Thread::%s(%p) for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
789 ", pc = 0x%16.16" PRIx64,
790 __FUNCTION__, static_cast<void *>(this), GetID(), GetProtocolID(),
791 GetRegisterContext() ? GetRegisterContext()->GetPC()
792 : LLDB_INVALID_ADDRESS);
793 LLDB_LOGF(log, "^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^");
794 StreamString s;
795 s.IndentMore();
796 GetProcess()->DumpThreadPlansForTID(
797 s, GetID(), eDescriptionLevelVerbose, true /* internal */,
798 false /* condense_trivial */, true /* skip_unreported */);
799 LLDB_LOGF(log, "Plan stack initial state:\n%s", s.GetData());
802 // The top most plan always gets to do the trace log...
803 current_plan->DoTraceLog();
805 // First query the stop info's ShouldStopSynchronous. This handles
806 // "synchronous" stop reasons, for example the breakpoint command on internal
807 // breakpoints. If a synchronous stop reason says we should not stop, then
808 // we don't have to do any more work on this stop.
809 StopInfoSP private_stop_info(GetPrivateStopInfo());
810 if (private_stop_info &&
811 !private_stop_info->ShouldStopSynchronous(event_ptr)) {
812 LLDB_LOGF(log, "StopInfo::ShouldStop async callback says we should not "
813 "stop, returning ShouldStop of false.");
814 return false;
817 // If we've already been restarted, don't query the plans since the state
818 // they would examine is not current.
819 if (Process::ProcessEventData::GetRestartedFromEvent(event_ptr))
820 return false;
822 // Before the plans see the state of the world, calculate the current inlined
823 // depth.
824 GetStackFrameList()->CalculateCurrentInlinedDepth();
826 // If the base plan doesn't understand why we stopped, then we have to find a
827 // plan that does. If that plan is still working, then we don't need to do
828 // any more work. If the plan that explains the stop is done, then we should
829 // pop all the plans below it, and pop it, and then let the plans above it
830 // decide whether they still need to do more work.
832 bool done_processing_current_plan = false;
833 if (!current_plan->PlanExplainsStop(event_ptr)) {
834 if (current_plan->TracerExplainsStop()) {
835 done_processing_current_plan = true;
836 should_stop = false;
837 } else {
838 // Leaf plan that does not explain the stop should be popped.
839 // The plan should be push itself later again before resuming to stay
840 // as leaf.
841 if (current_plan->IsLeafPlan())
842 PopPlan();
844 // If the current plan doesn't explain the stop, then find one that does
845 // and let it handle the situation.
846 ThreadPlan *plan_ptr = current_plan;
847 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
848 if (plan_ptr->PlanExplainsStop(event_ptr)) {
849 LLDB_LOGF(log, "Plan %s explains stop.", plan_ptr->GetName());
851 should_stop = plan_ptr->ShouldStop(event_ptr);
853 // plan_ptr explains the stop, next check whether plan_ptr is done,
854 // if so, then we should take it and all the plans below it off the
855 // stack.
857 if (plan_ptr->MischiefManaged()) {
858 // We're going to pop the plans up to and including the plan that
859 // explains the stop.
860 ThreadPlan *prev_plan_ptr = GetPreviousPlan(plan_ptr);
862 do {
863 if (should_stop)
864 current_plan->WillStop();
865 PopPlan();
866 } while ((current_plan = GetCurrentPlan()) != prev_plan_ptr);
867 // Now, if the responsible plan was not "Okay to discard" then
868 // we're done, otherwise we forward this to the next plan in the
869 // stack below.
870 done_processing_current_plan =
871 (plan_ptr->IsControllingPlan() && !plan_ptr->OkayToDiscard());
872 } else {
873 bool should_force_run = plan_ptr->ShouldRunBeforePublicStop();
874 if (should_force_run) {
875 SetShouldRunBeforePublicStop(true);
876 should_stop = false;
878 done_processing_current_plan = true;
880 break;
886 if (!done_processing_current_plan) {
887 bool override_stop = false;
889 // We're starting from the base plan, so just let it decide;
890 if (current_plan->IsBasePlan()) {
891 should_stop = current_plan->ShouldStop(event_ptr);
892 LLDB_LOGF(log, "Base plan says should stop: %i.", should_stop);
893 } else {
894 // Otherwise, don't let the base plan override what the other plans say
895 // to do, since presumably if there were other plans they would know what
896 // to do...
897 while (true) {
898 if (current_plan->IsBasePlan())
899 break;
901 should_stop = current_plan->ShouldStop(event_ptr);
902 LLDB_LOGF(log, "Plan %s should stop: %d.", current_plan->GetName(),
903 should_stop);
904 if (current_plan->MischiefManaged()) {
905 if (should_stop)
906 current_plan->WillStop();
908 if (current_plan->ShouldAutoContinue(event_ptr)) {
909 override_stop = true;
910 LLDB_LOGF(log, "Plan %s auto-continue: true.",
911 current_plan->GetName());
914 // If a Controlling Plan wants to stop, we let it. Otherwise, see if
915 // the plan's parent wants to stop.
917 PopPlan();
918 if (should_stop && current_plan->IsControllingPlan() &&
919 !current_plan->OkayToDiscard()) {
920 break;
923 current_plan = GetCurrentPlan();
924 if (current_plan == nullptr) {
925 break;
927 } else {
928 break;
933 if (override_stop)
934 should_stop = false;
937 // One other potential problem is that we set up a controlling plan, then stop
938 // in before it is complete - for instance by hitting a breakpoint during a
939 // step-over - then do some step/finish/etc operations that wind up past the
940 // end point condition of the initial plan. We don't want to strand the
941 // original plan on the stack, This code clears stale plans off the stack.
943 if (should_stop) {
944 ThreadPlan *plan_ptr = GetCurrentPlan();
946 // Discard the stale plans and all plans below them in the stack, plus move
947 // the completed plans to the completed plan stack
948 while (!plan_ptr->IsBasePlan()) {
949 bool stale = plan_ptr->IsPlanStale();
950 ThreadPlan *examined_plan = plan_ptr;
951 plan_ptr = GetPreviousPlan(examined_plan);
953 if (stale) {
954 LLDB_LOGF(
955 log,
956 "Plan %s being discarded in cleanup, it says it is already done.",
957 examined_plan->GetName());
958 while (GetCurrentPlan() != examined_plan) {
959 DiscardPlan();
961 if (examined_plan->IsPlanComplete()) {
962 // plan is complete but does not explain the stop (example: step to a
963 // line with breakpoint), let us move the plan to
964 // completed_plan_stack anyway
965 PopPlan();
966 } else
967 DiscardPlan();
972 if (log) {
973 StreamString s;
974 s.IndentMore();
975 GetProcess()->DumpThreadPlansForTID(
976 s, GetID(), eDescriptionLevelVerbose, true /* internal */,
977 false /* condense_trivial */, true /* skip_unreported */);
978 LLDB_LOGF(log, "Plan stack final state:\n%s", s.GetData());
979 LLDB_LOGF(log, "vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv",
980 should_stop);
982 return should_stop;
985 Vote Thread::ShouldReportStop(Event *event_ptr) {
986 StateType thread_state = GetResumeState();
987 StateType temp_thread_state = GetTemporaryResumeState();
989 Log *log = GetLog(LLDBLog::Step);
991 if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
992 LLDB_LOGF(log,
993 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
994 ": returning vote %i (state was suspended or invalid)",
995 GetID(), eVoteNoOpinion);
996 return eVoteNoOpinion;
999 if (temp_thread_state == eStateSuspended ||
1000 temp_thread_state == eStateInvalid) {
1001 LLDB_LOGF(log,
1002 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1003 ": returning vote %i (temporary state was suspended or invalid)",
1004 GetID(), eVoteNoOpinion);
1005 return eVoteNoOpinion;
1008 if (!ThreadStoppedForAReason()) {
1009 LLDB_LOGF(log,
1010 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1011 ": returning vote %i (thread didn't stop for a reason.)",
1012 GetID(), eVoteNoOpinion);
1013 return eVoteNoOpinion;
1016 if (GetPlans().AnyCompletedPlans()) {
1017 // Pass skip_private = false to GetCompletedPlan, since we want to ask
1018 // the last plan, regardless of whether it is private or not.
1019 LLDB_LOGF(log,
1020 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1021 ": returning vote for complete stack's back plan",
1022 GetID());
1023 return GetPlans().GetCompletedPlan(false)->ShouldReportStop(event_ptr);
1024 } else {
1025 Vote thread_vote = eVoteNoOpinion;
1026 ThreadPlan *plan_ptr = GetCurrentPlan();
1027 while (true) {
1028 if (plan_ptr->PlanExplainsStop(event_ptr)) {
1029 thread_vote = plan_ptr->ShouldReportStop(event_ptr);
1030 break;
1032 if (plan_ptr->IsBasePlan())
1033 break;
1034 else
1035 plan_ptr = GetPreviousPlan(plan_ptr);
1037 LLDB_LOGF(log,
1038 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1039 ": returning vote %i for current plan",
1040 GetID(), thread_vote);
1042 return thread_vote;
1046 Vote Thread::ShouldReportRun(Event *event_ptr) {
1047 StateType thread_state = GetResumeState();
1049 if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
1050 return eVoteNoOpinion;
1053 Log *log = GetLog(LLDBLog::Step);
1054 if (GetPlans().AnyCompletedPlans()) {
1055 // Pass skip_private = false to GetCompletedPlan, since we want to ask
1056 // the last plan, regardless of whether it is private or not.
1057 LLDB_LOGF(log,
1058 "Current Plan for thread %d(%p) (0x%4.4" PRIx64
1059 ", %s): %s being asked whether we should report run.",
1060 GetIndexID(), static_cast<void *>(this), GetID(),
1061 StateAsCString(GetTemporaryResumeState()),
1062 GetCompletedPlan()->GetName());
1064 return GetPlans().GetCompletedPlan(false)->ShouldReportRun(event_ptr);
1065 } else {
1066 LLDB_LOGF(log,
1067 "Current Plan for thread %d(%p) (0x%4.4" PRIx64
1068 ", %s): %s being asked whether we should report run.",
1069 GetIndexID(), static_cast<void *>(this), GetID(),
1070 StateAsCString(GetTemporaryResumeState()),
1071 GetCurrentPlan()->GetName());
1073 return GetCurrentPlan()->ShouldReportRun(event_ptr);
1077 bool Thread::MatchesSpec(const ThreadSpec *spec) {
1078 return (spec == nullptr) ? true : spec->ThreadPassesBasicTests(*this);
1081 ThreadPlanStack &Thread::GetPlans() const {
1082 ThreadPlanStack *plans = GetProcess()->FindThreadPlans(GetID());
1083 if (plans)
1084 return *plans;
1086 // History threads don't have a thread plan, but they do ask get asked to
1087 // describe themselves, which usually involves pulling out the stop reason.
1088 // That in turn will check for a completed plan on the ThreadPlanStack.
1089 // Instead of special-casing at that point, we return a Stack with a
1090 // ThreadPlanNull as its base plan. That will give the right answers to the
1091 // queries GetDescription makes, and only assert if you try to run the thread.
1092 if (!m_null_plan_stack_up)
1093 m_null_plan_stack_up = std::make_unique<ThreadPlanStack>(*this, true);
1094 return *m_null_plan_stack_up;
1097 void Thread::PushPlan(ThreadPlanSP thread_plan_sp) {
1098 assert(thread_plan_sp && "Don't push an empty thread plan.");
1100 Log *log = GetLog(LLDBLog::Step);
1101 if (log) {
1102 StreamString s;
1103 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelFull);
1104 LLDB_LOGF(log, "Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".",
1105 static_cast<void *>(this), s.GetData(),
1106 thread_plan_sp->GetThread().GetID());
1109 GetPlans().PushPlan(std::move(thread_plan_sp));
1112 void Thread::PopPlan() {
1113 Log *log = GetLog(LLDBLog::Step);
1114 ThreadPlanSP popped_plan_sp = GetPlans().PopPlan();
1115 if (log) {
1116 LLDB_LOGF(log, "Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1117 popped_plan_sp->GetName(), popped_plan_sp->GetThread().GetID());
1121 void Thread::DiscardPlan() {
1122 Log *log = GetLog(LLDBLog::Step);
1123 ThreadPlanSP discarded_plan_sp = GetPlans().DiscardPlan();
1125 LLDB_LOGF(log, "Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1126 discarded_plan_sp->GetName(),
1127 discarded_plan_sp->GetThread().GetID());
1130 void Thread::AutoCompleteThreadPlans(CompletionRequest &request) const {
1131 const ThreadPlanStack &plans = GetPlans();
1132 if (!plans.AnyPlans())
1133 return;
1135 // Iterate from the second plan (index: 1) to skip the base plan.
1136 ThreadPlanSP p;
1137 uint32_t i = 1;
1138 while ((p = plans.GetPlanByIndex(i, false))) {
1139 StreamString strm;
1140 p->GetDescription(&strm, eDescriptionLevelInitial);
1141 request.TryCompleteCurrentArg(std::to_string(i), strm.GetString());
1142 i++;
1146 ThreadPlan *Thread::GetCurrentPlan() const {
1147 return GetPlans().GetCurrentPlan().get();
1150 ThreadPlanSP Thread::GetCompletedPlan() const {
1151 return GetPlans().GetCompletedPlan();
1154 ValueObjectSP Thread::GetReturnValueObject() const {
1155 return GetPlans().GetReturnValueObject();
1158 ExpressionVariableSP Thread::GetExpressionVariable() const {
1159 return GetPlans().GetExpressionVariable();
1162 bool Thread::IsThreadPlanDone(ThreadPlan *plan) const {
1163 return GetPlans().IsPlanDone(plan);
1166 bool Thread::WasThreadPlanDiscarded(ThreadPlan *plan) const {
1167 return GetPlans().WasPlanDiscarded(plan);
1170 bool Thread::CompletedPlanOverridesBreakpoint() const {
1171 return GetPlans().AnyCompletedPlans();
1174 ThreadPlan *Thread::GetPreviousPlan(ThreadPlan *current_plan) const{
1175 return GetPlans().GetPreviousPlan(current_plan);
1178 Status Thread::QueueThreadPlan(ThreadPlanSP &thread_plan_sp,
1179 bool abort_other_plans) {
1180 Status status;
1181 StreamString s;
1182 if (!thread_plan_sp->ValidatePlan(&s)) {
1183 DiscardThreadPlansUpToPlan(thread_plan_sp);
1184 thread_plan_sp.reset();
1185 return Status(s.GetString().str());
1188 if (abort_other_plans)
1189 DiscardThreadPlans(true);
1191 PushPlan(thread_plan_sp);
1193 // This seems a little funny, but I don't want to have to split up the
1194 // constructor and the DidPush in the scripted plan, that seems annoying.
1195 // That means the constructor has to be in DidPush. So I have to validate the
1196 // plan AFTER pushing it, and then take it off again...
1197 if (!thread_plan_sp->ValidatePlan(&s)) {
1198 DiscardThreadPlansUpToPlan(thread_plan_sp);
1199 thread_plan_sp.reset();
1200 return Status(s.GetString().str());
1203 return status;
1206 bool Thread::DiscardUserThreadPlansUpToIndex(uint32_t plan_index) {
1207 // Count the user thread plans from the back end to get the number of the one
1208 // we want to discard:
1210 ThreadPlan *up_to_plan_ptr = GetPlans().GetPlanByIndex(plan_index).get();
1211 if (up_to_plan_ptr == nullptr)
1212 return false;
1214 DiscardThreadPlansUpToPlan(up_to_plan_ptr);
1215 return true;
1218 void Thread::DiscardThreadPlansUpToPlan(lldb::ThreadPlanSP &up_to_plan_sp) {
1219 DiscardThreadPlansUpToPlan(up_to_plan_sp.get());
1222 void Thread::DiscardThreadPlansUpToPlan(ThreadPlan *up_to_plan_ptr) {
1223 Log *log = GetLog(LLDBLog::Step);
1224 LLDB_LOGF(log,
1225 "Discarding thread plans for thread tid = 0x%4.4" PRIx64
1226 ", up to %p",
1227 GetID(), static_cast<void *>(up_to_plan_ptr));
1228 GetPlans().DiscardPlansUpToPlan(up_to_plan_ptr);
1231 void Thread::DiscardThreadPlans(bool force) {
1232 Log *log = GetLog(LLDBLog::Step);
1233 if (log) {
1234 LLDB_LOGF(log,
1235 "Discarding thread plans for thread (tid = 0x%4.4" PRIx64
1236 ", force %d)",
1237 GetID(), force);
1240 if (force) {
1241 GetPlans().DiscardAllPlans();
1242 return;
1244 GetPlans().DiscardConsultingControllingPlans();
1247 Status Thread::UnwindInnermostExpression() {
1248 Status error;
1249 ThreadPlan *innermost_expr_plan = GetPlans().GetInnermostExpression();
1250 if (!innermost_expr_plan) {
1251 error = Status::FromErrorString(
1252 "No expressions currently active on this thread");
1253 return error;
1255 DiscardThreadPlansUpToPlan(innermost_expr_plan);
1256 return error;
1259 ThreadPlanSP Thread::QueueBasePlan(bool abort_other_plans) {
1260 ThreadPlanSP thread_plan_sp(new ThreadPlanBase(*this));
1261 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1262 return thread_plan_sp;
1265 ThreadPlanSP Thread::QueueThreadPlanForStepSingleInstruction(
1266 bool step_over, bool abort_other_plans, bool stop_other_threads,
1267 Status &status) {
1268 ThreadPlanSP thread_plan_sp(new ThreadPlanStepInstruction(
1269 *this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
1270 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1271 return thread_plan_sp;
1274 ThreadPlanSP Thread::QueueThreadPlanForStepOverRange(
1275 bool abort_other_plans, const AddressRange &range,
1276 const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1277 Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
1278 ThreadPlanSP thread_plan_sp;
1279 thread_plan_sp = std::make_shared<ThreadPlanStepOverRange>(
1280 *this, range, addr_context, stop_other_threads,
1281 step_out_avoids_code_withoug_debug_info);
1283 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1284 return thread_plan_sp;
1287 // Call the QueueThreadPlanForStepOverRange method which takes an address
1288 // range.
1289 ThreadPlanSP Thread::QueueThreadPlanForStepOverRange(
1290 bool abort_other_plans, const LineEntry &line_entry,
1291 const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1292 Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
1293 const bool include_inlined_functions = true;
1294 auto address_range =
1295 line_entry.GetSameLineContiguousAddressRange(include_inlined_functions);
1296 return QueueThreadPlanForStepOverRange(
1297 abort_other_plans, address_range, addr_context, stop_other_threads,
1298 status, step_out_avoids_code_withoug_debug_info);
1301 ThreadPlanSP Thread::QueueThreadPlanForStepInRange(
1302 bool abort_other_plans, const AddressRange &range,
1303 const SymbolContext &addr_context, const char *step_in_target,
1304 lldb::RunMode stop_other_threads, Status &status,
1305 LazyBool step_in_avoids_code_without_debug_info,
1306 LazyBool step_out_avoids_code_without_debug_info) {
1307 ThreadPlanSP thread_plan_sp(new ThreadPlanStepInRange(
1308 *this, range, addr_context, step_in_target, stop_other_threads,
1309 step_in_avoids_code_without_debug_info,
1310 step_out_avoids_code_without_debug_info));
1311 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1312 return thread_plan_sp;
1315 // Call the QueueThreadPlanForStepInRange method which takes an address range.
1316 ThreadPlanSP Thread::QueueThreadPlanForStepInRange(
1317 bool abort_other_plans, const LineEntry &line_entry,
1318 const SymbolContext &addr_context, const char *step_in_target,
1319 lldb::RunMode stop_other_threads, Status &status,
1320 LazyBool step_in_avoids_code_without_debug_info,
1321 LazyBool step_out_avoids_code_without_debug_info) {
1322 const bool include_inlined_functions = false;
1323 return QueueThreadPlanForStepInRange(
1324 abort_other_plans,
1325 line_entry.GetSameLineContiguousAddressRange(include_inlined_functions),
1326 addr_context, step_in_target, stop_other_threads, status,
1327 step_in_avoids_code_without_debug_info,
1328 step_out_avoids_code_without_debug_info);
1331 ThreadPlanSP Thread::QueueThreadPlanForStepOut(
1332 bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1333 bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote,
1334 uint32_t frame_idx, Status &status,
1335 LazyBool step_out_avoids_code_without_debug_info) {
1336 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1337 *this, addr_context, first_insn, stop_other_threads, report_stop_vote,
1338 report_run_vote, frame_idx, step_out_avoids_code_without_debug_info));
1340 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1341 return thread_plan_sp;
1344 ThreadPlanSP Thread::QueueThreadPlanForStepOutNoShouldStop(
1345 bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1346 bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote,
1347 uint32_t frame_idx, Status &status, bool continue_to_next_branch) {
1348 const bool calculate_return_value =
1349 false; // No need to calculate the return value here.
1350 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1351 *this, addr_context, first_insn, stop_other_threads, report_stop_vote,
1352 report_run_vote, frame_idx, eLazyBoolNo, continue_to_next_branch,
1353 calculate_return_value));
1355 ThreadPlanStepOut *new_plan =
1356 static_cast<ThreadPlanStepOut *>(thread_plan_sp.get());
1357 new_plan->ClearShouldStopHereCallbacks();
1359 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1360 return thread_plan_sp;
1363 ThreadPlanSP Thread::QueueThreadPlanForStepThrough(StackID &return_stack_id,
1364 bool abort_other_plans,
1365 bool stop_other_threads,
1366 Status &status) {
1367 ThreadPlanSP thread_plan_sp(
1368 new ThreadPlanStepThrough(*this, return_stack_id, stop_other_threads));
1369 if (!thread_plan_sp || !thread_plan_sp->ValidatePlan(nullptr))
1370 return ThreadPlanSP();
1372 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1373 return thread_plan_sp;
1376 ThreadPlanSP Thread::QueueThreadPlanForRunToAddress(bool abort_other_plans,
1377 Address &target_addr,
1378 bool stop_other_threads,
1379 Status &status) {
1380 ThreadPlanSP thread_plan_sp(
1381 new ThreadPlanRunToAddress(*this, target_addr, stop_other_threads));
1383 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1384 return thread_plan_sp;
1387 ThreadPlanSP Thread::QueueThreadPlanForStepUntil(
1388 bool abort_other_plans, lldb::addr_t *address_list, size_t num_addresses,
1389 bool stop_other_threads, uint32_t frame_idx, Status &status) {
1390 ThreadPlanSP thread_plan_sp(new ThreadPlanStepUntil(
1391 *this, address_list, num_addresses, stop_other_threads, frame_idx));
1393 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1394 return thread_plan_sp;
1397 lldb::ThreadPlanSP Thread::QueueThreadPlanForStepScripted(
1398 bool abort_other_plans, const char *class_name,
1399 StructuredData::ObjectSP extra_args_sp, bool stop_other_threads,
1400 Status &status) {
1402 ThreadPlanSP thread_plan_sp(new ScriptedThreadPlan(
1403 *this, class_name, StructuredDataImpl(extra_args_sp)));
1404 thread_plan_sp->SetStopOthers(stop_other_threads);
1405 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1406 return thread_plan_sp;
1409 uint32_t Thread::GetIndexID() const { return m_index_id; }
1411 TargetSP Thread::CalculateTarget() {
1412 TargetSP target_sp;
1413 ProcessSP process_sp(GetProcess());
1414 if (process_sp)
1415 target_sp = process_sp->CalculateTarget();
1416 return target_sp;
1419 ProcessSP Thread::CalculateProcess() { return GetProcess(); }
1421 ThreadSP Thread::CalculateThread() { return shared_from_this(); }
1423 StackFrameSP Thread::CalculateStackFrame() { return StackFrameSP(); }
1425 void Thread::CalculateExecutionContext(ExecutionContext &exe_ctx) {
1426 exe_ctx.SetContext(shared_from_this());
1429 StackFrameListSP Thread::GetStackFrameList() {
1430 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1432 if (!m_curr_frames_sp)
1433 m_curr_frames_sp =
1434 std::make_shared<StackFrameList>(*this, m_prev_frames_sp, true);
1436 return m_curr_frames_sp;
1439 std::optional<addr_t> Thread::GetPreviousFrameZeroPC() {
1440 return m_prev_framezero_pc;
1443 void Thread::ClearStackFrames() {
1444 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1446 GetUnwinder().Clear();
1447 m_prev_framezero_pc.reset();
1448 if (RegisterContextSP reg_ctx_sp = GetRegisterContext())
1449 m_prev_framezero_pc = reg_ctx_sp->GetPC();
1451 // Only store away the old "reference" StackFrameList if we got all its
1452 // frames:
1453 // FIXME: At some point we can try to splice in the frames we have fetched
1454 // into the new frame as we make it, but let's not try that now.
1455 if (m_curr_frames_sp && m_curr_frames_sp->WereAllFramesFetched())
1456 m_prev_frames_sp.swap(m_curr_frames_sp);
1457 m_curr_frames_sp.reset();
1459 m_extended_info.reset();
1460 m_extended_info_fetched = false;
1463 lldb::StackFrameSP Thread::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) {
1464 return GetStackFrameList()->GetFrameWithConcreteFrameIndex(unwind_idx);
1467 Status Thread::ReturnFromFrameWithIndex(uint32_t frame_idx,
1468 lldb::ValueObjectSP return_value_sp,
1469 bool broadcast) {
1470 StackFrameSP frame_sp = GetStackFrameAtIndex(frame_idx);
1471 Status return_error;
1473 if (!frame_sp) {
1474 return_error = Status::FromErrorStringWithFormat(
1475 "Could not find frame with index %d in thread 0x%" PRIx64 ".",
1476 frame_idx, GetID());
1479 return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
1482 Status Thread::ReturnFromFrame(lldb::StackFrameSP frame_sp,
1483 lldb::ValueObjectSP return_value_sp,
1484 bool broadcast) {
1485 Status return_error;
1487 if (!frame_sp) {
1488 return_error = Status::FromErrorString("Can't return to a null frame.");
1489 return return_error;
1492 Thread *thread = frame_sp->GetThread().get();
1493 uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
1494 StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
1495 if (!older_frame_sp) {
1496 return_error = Status::FromErrorString("No older frame to return to.");
1497 return return_error;
1500 if (return_value_sp) {
1501 lldb::ABISP abi = thread->GetProcess()->GetABI();
1502 if (!abi) {
1503 return_error =
1504 Status::FromErrorString("Could not find ABI to set return value.");
1505 return return_error;
1507 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
1509 // FIXME: ValueObject::Cast doesn't currently work correctly, at least not
1510 // for scalars.
1511 // Turn that back on when that works.
1512 if (/* DISABLES CODE */ (false) && sc.function != nullptr) {
1513 Type *function_type = sc.function->GetType();
1514 if (function_type) {
1515 CompilerType return_type =
1516 sc.function->GetCompilerType().GetFunctionReturnType();
1517 if (return_type) {
1518 StreamString s;
1519 return_type.DumpTypeDescription(&s);
1520 ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type);
1521 if (cast_value_sp) {
1522 cast_value_sp->SetFormat(eFormatHex);
1523 return_value_sp = cast_value_sp;
1529 return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
1530 if (!return_error.Success())
1531 return return_error;
1534 // Now write the return registers for the chosen frame: Note, we can't use
1535 // ReadAllRegisterValues->WriteAllRegisterValues, since the read & write cook
1536 // their data
1538 StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);
1539 if (youngest_frame_sp) {
1540 lldb::RegisterContextSP reg_ctx_sp(youngest_frame_sp->GetRegisterContext());
1541 if (reg_ctx_sp) {
1542 bool copy_success = reg_ctx_sp->CopyFromRegisterContext(
1543 older_frame_sp->GetRegisterContext());
1544 if (copy_success) {
1545 thread->DiscardThreadPlans(true);
1546 thread->ClearStackFrames();
1547 if (broadcast && EventTypeHasListeners(eBroadcastBitStackChanged)) {
1548 auto data_sp = std::make_shared<ThreadEventData>(shared_from_this());
1549 BroadcastEvent(eBroadcastBitStackChanged, data_sp);
1551 } else {
1552 return_error =
1553 Status::FromErrorString("Could not reset register values.");
1555 } else {
1556 return_error = Status::FromErrorString("Frame has no register context.");
1558 } else {
1559 return_error = Status::FromErrorString("Returned past top frame.");
1561 return return_error;
1564 static void DumpAddressList(Stream &s, const std::vector<Address> &list,
1565 ExecutionContextScope *exe_scope) {
1566 for (size_t n = 0; n < list.size(); n++) {
1567 s << "\t";
1568 list[n].Dump(&s, exe_scope, Address::DumpStyleResolvedDescription,
1569 Address::DumpStyleSectionNameOffset);
1570 s << "\n";
1574 Status Thread::JumpToLine(const FileSpec &file, uint32_t line,
1575 bool can_leave_function, std::string *warnings) {
1576 ExecutionContext exe_ctx(GetStackFrameAtIndex(0));
1577 Target *target = exe_ctx.GetTargetPtr();
1578 TargetSP target_sp = exe_ctx.GetTargetSP();
1579 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1580 StackFrame *frame = exe_ctx.GetFramePtr();
1581 const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction);
1583 // Find candidate locations.
1584 std::vector<Address> candidates, within_function, outside_function;
1585 target->GetImages().FindAddressesForLine(target_sp, file, line, sc.function,
1586 within_function, outside_function);
1588 // If possible, we try and stay within the current function. Within a
1589 // function, we accept multiple locations (optimized code may do this,
1590 // there's no solution here so we do the best we can). However if we're
1591 // trying to leave the function, we don't know how to pick the right
1592 // location, so if there's more than one then we bail.
1593 if (!within_function.empty())
1594 candidates = within_function;
1595 else if (outside_function.size() == 1 && can_leave_function)
1596 candidates = outside_function;
1598 // Check if we got anything.
1599 if (candidates.empty()) {
1600 if (outside_function.empty()) {
1601 return Status::FromErrorStringWithFormat(
1602 "Cannot locate an address for %s:%i.", file.GetFilename().AsCString(),
1603 line);
1604 } else if (outside_function.size() == 1) {
1605 return Status::FromErrorStringWithFormat(
1606 "%s:%i is outside the current function.",
1607 file.GetFilename().AsCString(), line);
1608 } else {
1609 StreamString sstr;
1610 DumpAddressList(sstr, outside_function, target);
1611 return Status::FromErrorStringWithFormat(
1612 "%s:%i has multiple candidate locations:\n%s",
1613 file.GetFilename().AsCString(), line, sstr.GetData());
1617 // Accept the first location, warn about any others.
1618 Address dest = candidates[0];
1619 if (warnings && candidates.size() > 1) {
1620 StreamString sstr;
1621 sstr.Printf("%s:%i appears multiple times in this function, selecting the "
1622 "first location:\n",
1623 file.GetFilename().AsCString(), line);
1624 DumpAddressList(sstr, candidates, target);
1625 *warnings = std::string(sstr.GetString());
1628 if (!reg_ctx->SetPC(dest))
1629 return Status::FromErrorString("Cannot change PC to target address.");
1631 return Status();
1634 bool Thread::DumpUsingFormat(Stream &strm, uint32_t frame_idx,
1635 const FormatEntity::Entry *format) {
1636 ExecutionContext exe_ctx(shared_from_this());
1637 Process *process = exe_ctx.GetProcessPtr();
1638 if (!process || !format)
1639 return false;
1641 StackFrameSP frame_sp;
1642 SymbolContext frame_sc;
1643 if (frame_idx != LLDB_INVALID_FRAME_ID) {
1644 frame_sp = GetStackFrameAtIndex(frame_idx);
1645 if (frame_sp) {
1646 exe_ctx.SetFrameSP(frame_sp);
1647 frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
1651 return FormatEntity::Format(*format, strm, frame_sp ? &frame_sc : nullptr,
1652 &exe_ctx, nullptr, nullptr, false, false);
1655 void Thread::DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx,
1656 bool stop_format) {
1657 ExecutionContext exe_ctx(shared_from_this());
1659 const FormatEntity::Entry *thread_format;
1660 if (stop_format)
1661 thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadStopFormat();
1662 else
1663 thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
1665 assert(thread_format);
1667 DumpUsingFormat(strm, frame_idx, thread_format);
1670 void Thread::SettingsInitialize() {}
1672 void Thread::SettingsTerminate() {}
1674 lldb::addr_t Thread::GetThreadPointer() {
1675 if (m_reg_context_sp)
1676 return m_reg_context_sp->GetThreadPointer();
1677 return LLDB_INVALID_ADDRESS;
1680 addr_t Thread::GetThreadLocalData(const ModuleSP module,
1681 lldb::addr_t tls_file_addr) {
1682 // The default implementation is to ask the dynamic loader for it. This can
1683 // be overridden for specific platforms.
1684 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
1685 if (loader)
1686 return loader->GetThreadLocalData(module, shared_from_this(),
1687 tls_file_addr);
1688 else
1689 return LLDB_INVALID_ADDRESS;
1692 bool Thread::SafeToCallFunctions() {
1693 Process *process = GetProcess().get();
1694 if (process) {
1695 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
1696 if (loader && loader->IsFullyInitialized() == false)
1697 return false;
1699 SystemRuntime *runtime = process->GetSystemRuntime();
1700 if (runtime) {
1701 return runtime->SafeToCallFunctionsOnThisThread(shared_from_this());
1704 return true;
1707 lldb::StackFrameSP
1708 Thread::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) {
1709 return GetStackFrameList()->GetStackFrameSPForStackFramePtr(stack_frame_ptr);
1712 std::string Thread::StopReasonAsString(lldb::StopReason reason) {
1713 switch (reason) {
1714 case eStopReasonInvalid:
1715 return "invalid";
1716 case eStopReasonNone:
1717 return "none";
1718 case eStopReasonTrace:
1719 return "trace";
1720 case eStopReasonBreakpoint:
1721 return "breakpoint";
1722 case eStopReasonWatchpoint:
1723 return "watchpoint";
1724 case eStopReasonSignal:
1725 return "signal";
1726 case eStopReasonException:
1727 return "exception";
1728 case eStopReasonExec:
1729 return "exec";
1730 case eStopReasonFork:
1731 return "fork";
1732 case eStopReasonVFork:
1733 return "vfork";
1734 case eStopReasonVForkDone:
1735 return "vfork done";
1736 case eStopReasonPlanComplete:
1737 return "plan complete";
1738 case eStopReasonThreadExiting:
1739 return "thread exiting";
1740 case eStopReasonInstrumentation:
1741 return "instrumentation break";
1742 case eStopReasonProcessorTrace:
1743 return "processor trace";
1744 case eStopReasonInterrupt:
1745 return "async interrupt";
1746 case eStopReasonHistoryBoundary:
1747 return "history boundary";
1750 return "StopReason = " + std::to_string(reason);
1753 std::string Thread::RunModeAsString(lldb::RunMode mode) {
1754 switch (mode) {
1755 case eOnlyThisThread:
1756 return "only this thread";
1757 case eAllThreads:
1758 return "all threads";
1759 case eOnlyDuringStepping:
1760 return "only during stepping";
1763 return "RunMode = " + std::to_string(mode);
1766 size_t Thread::GetStatus(Stream &strm, uint32_t start_frame,
1767 uint32_t num_frames, uint32_t num_frames_with_source,
1768 bool stop_format, bool show_hidden, bool only_stacks) {
1770 if (!only_stacks) {
1771 ExecutionContext exe_ctx(shared_from_this());
1772 Target *target = exe_ctx.GetTargetPtr();
1773 Process *process = exe_ctx.GetProcessPtr();
1774 strm.Indent();
1775 bool is_selected = false;
1776 if (process) {
1777 if (process->GetThreadList().GetSelectedThread().get() == this)
1778 is_selected = true;
1780 strm.Printf("%c ", is_selected ? '*' : ' ');
1781 if (target && target->GetDebugger().GetUseExternalEditor()) {
1782 StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
1783 if (frame_sp) {
1784 SymbolContext frame_sc(
1785 frame_sp->GetSymbolContext(eSymbolContextLineEntry));
1786 if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.GetFile()) {
1787 if (llvm::Error e = Host::OpenFileInExternalEditor(
1788 target->GetDebugger().GetExternalEditor(),
1789 frame_sc.line_entry.GetFile(), frame_sc.line_entry.line)) {
1790 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), std::move(e),
1791 "OpenFileInExternalEditor failed: {0}");
1797 DumpUsingSettingsFormat(strm, start_frame, stop_format);
1800 size_t num_frames_shown = 0;
1801 if (num_frames > 0) {
1802 strm.IndentMore();
1804 const bool show_frame_info = true;
1805 const bool show_frame_unique = only_stacks;
1806 const char *selected_frame_marker = nullptr;
1807 if (num_frames == 1 || only_stacks ||
1808 (GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID()))
1809 strm.IndentMore();
1810 else
1811 selected_frame_marker = "* ";
1813 num_frames_shown = GetStackFrameList()->GetStatus(
1814 strm, start_frame, num_frames, show_frame_info, num_frames_with_source,
1815 show_frame_unique, show_hidden, selected_frame_marker);
1816 if (num_frames == 1)
1817 strm.IndentLess();
1818 strm.IndentLess();
1820 return num_frames_shown;
1823 bool Thread::GetDescription(Stream &strm, lldb::DescriptionLevel level,
1824 bool print_json_thread, bool print_json_stopinfo) {
1825 const bool stop_format = false;
1826 DumpUsingSettingsFormat(strm, 0, stop_format);
1827 strm.Printf("\n");
1829 StructuredData::ObjectSP thread_info = GetExtendedInfo();
1831 if (print_json_thread || print_json_stopinfo) {
1832 if (thread_info && print_json_thread) {
1833 thread_info->Dump(strm);
1834 strm.Printf("\n");
1837 if (print_json_stopinfo && m_stop_info_sp) {
1838 StructuredData::ObjectSP stop_info = m_stop_info_sp->GetExtendedInfo();
1839 if (stop_info) {
1840 stop_info->Dump(strm);
1841 strm.Printf("\n");
1845 return true;
1848 if (thread_info) {
1849 StructuredData::ObjectSP activity =
1850 thread_info->GetObjectForDotSeparatedPath("activity");
1851 StructuredData::ObjectSP breadcrumb =
1852 thread_info->GetObjectForDotSeparatedPath("breadcrumb");
1853 StructuredData::ObjectSP messages =
1854 thread_info->GetObjectForDotSeparatedPath("trace_messages");
1856 bool printed_activity = false;
1857 if (activity && activity->GetType() == eStructuredDataTypeDictionary) {
1858 StructuredData::Dictionary *activity_dict = activity->GetAsDictionary();
1859 StructuredData::ObjectSP id = activity_dict->GetValueForKey("id");
1860 StructuredData::ObjectSP name = activity_dict->GetValueForKey("name");
1861 if (name && name->GetType() == eStructuredDataTypeString && id &&
1862 id->GetType() == eStructuredDataTypeInteger) {
1863 strm.Format(" Activity '{0}', {1:x}\n",
1864 name->GetAsString()->GetValue(),
1865 id->GetUnsignedIntegerValue());
1867 printed_activity = true;
1869 bool printed_breadcrumb = false;
1870 if (breadcrumb && breadcrumb->GetType() == eStructuredDataTypeDictionary) {
1871 if (printed_activity)
1872 strm.Printf("\n");
1873 StructuredData::Dictionary *breadcrumb_dict =
1874 breadcrumb->GetAsDictionary();
1875 StructuredData::ObjectSP breadcrumb_text =
1876 breadcrumb_dict->GetValueForKey("name");
1877 if (breadcrumb_text &&
1878 breadcrumb_text->GetType() == eStructuredDataTypeString) {
1879 strm.Format(" Current Breadcrumb: {0}\n",
1880 breadcrumb_text->GetAsString()->GetValue());
1882 printed_breadcrumb = true;
1884 if (messages && messages->GetType() == eStructuredDataTypeArray) {
1885 if (printed_breadcrumb)
1886 strm.Printf("\n");
1887 StructuredData::Array *messages_array = messages->GetAsArray();
1888 const size_t msg_count = messages_array->GetSize();
1889 if (msg_count > 0) {
1890 strm.Printf(" %zu trace messages:\n", msg_count);
1891 for (size_t i = 0; i < msg_count; i++) {
1892 StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i);
1893 if (message && message->GetType() == eStructuredDataTypeDictionary) {
1894 StructuredData::Dictionary *message_dict =
1895 message->GetAsDictionary();
1896 StructuredData::ObjectSP message_text =
1897 message_dict->GetValueForKey("message");
1898 if (message_text &&
1899 message_text->GetType() == eStructuredDataTypeString) {
1900 strm.Format(" {0}\n", message_text->GetAsString()->GetValue());
1908 return true;
1911 size_t Thread::GetStackFrameStatus(Stream &strm, uint32_t first_frame,
1912 uint32_t num_frames, bool show_frame_info,
1913 uint32_t num_frames_with_source,
1914 bool show_hidden) {
1915 return GetStackFrameList()->GetStatus(strm, first_frame, num_frames,
1916 show_frame_info, num_frames_with_source,
1917 /*show_unique*/ false, show_hidden);
1920 Unwind &Thread::GetUnwinder() {
1921 if (!m_unwinder_up)
1922 m_unwinder_up = std::make_unique<UnwindLLDB>(*this);
1923 return *m_unwinder_up;
1926 void Thread::Flush() {
1927 ClearStackFrames();
1928 m_reg_context_sp.reset();
1931 bool Thread::IsStillAtLastBreakpointHit() {
1932 // If we are currently stopped at a breakpoint, always return that stopinfo
1933 // and don't reset it. This allows threads to maintain their breakpoint
1934 // stopinfo, such as when thread-stepping in multithreaded programs.
1935 if (m_stop_info_sp) {
1936 StopReason stop_reason = m_stop_info_sp->GetStopReason();
1937 if (stop_reason == lldb::eStopReasonBreakpoint) {
1938 uint64_t value = m_stop_info_sp->GetValue();
1939 lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext());
1940 if (reg_ctx_sp) {
1941 lldb::addr_t pc = reg_ctx_sp->GetPC();
1942 BreakpointSiteSP bp_site_sp =
1943 GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1944 if (bp_site_sp && static_cast<break_id_t>(value) == bp_site_sp->GetID())
1945 return true;
1949 return false;
1952 Status Thread::StepIn(bool source_step,
1953 LazyBool step_in_avoids_code_without_debug_info,
1954 LazyBool step_out_avoids_code_without_debug_info)
1957 Status error;
1958 Process *process = GetProcess().get();
1959 if (StateIsStoppedState(process->GetState(), true)) {
1960 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
1961 ThreadPlanSP new_plan_sp;
1962 const lldb::RunMode run_mode = eOnlyThisThread;
1963 const bool abort_other_plans = false;
1965 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
1966 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
1967 new_plan_sp = QueueThreadPlanForStepInRange(
1968 abort_other_plans, sc.line_entry, sc, nullptr, run_mode, error,
1969 step_in_avoids_code_without_debug_info,
1970 step_out_avoids_code_without_debug_info);
1971 } else {
1972 new_plan_sp = QueueThreadPlanForStepSingleInstruction(
1973 false, abort_other_plans, run_mode, error);
1976 new_plan_sp->SetIsControllingPlan(true);
1977 new_plan_sp->SetOkayToDiscard(false);
1979 // Why do we need to set the current thread by ID here???
1980 process->GetThreadList().SetSelectedThreadByID(GetID());
1981 error = process->Resume();
1982 } else {
1983 error = Status::FromErrorString("process not stopped");
1985 return error;
1988 Status Thread::StepOver(bool source_step,
1989 LazyBool step_out_avoids_code_without_debug_info) {
1990 Status error;
1991 Process *process = GetProcess().get();
1992 if (StateIsStoppedState(process->GetState(), true)) {
1993 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
1994 ThreadPlanSP new_plan_sp;
1996 const lldb::RunMode run_mode = eOnlyThisThread;
1997 const bool abort_other_plans = false;
1999 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2000 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2001 new_plan_sp = QueueThreadPlanForStepOverRange(
2002 abort_other_plans, sc.line_entry, sc, run_mode, error,
2003 step_out_avoids_code_without_debug_info);
2004 } else {
2005 new_plan_sp = QueueThreadPlanForStepSingleInstruction(
2006 true, abort_other_plans, run_mode, error);
2009 new_plan_sp->SetIsControllingPlan(true);
2010 new_plan_sp->SetOkayToDiscard(false);
2012 // Why do we need to set the current thread by ID here???
2013 process->GetThreadList().SetSelectedThreadByID(GetID());
2014 error = process->Resume();
2015 } else {
2016 error = Status::FromErrorString("process not stopped");
2018 return error;
2021 Status Thread::StepOut(uint32_t frame_idx) {
2022 Status error;
2023 Process *process = GetProcess().get();
2024 if (StateIsStoppedState(process->GetState(), true)) {
2025 const bool first_instruction = false;
2026 const bool stop_other_threads = false;
2027 const bool abort_other_plans = false;
2029 ThreadPlanSP new_plan_sp(QueueThreadPlanForStepOut(
2030 abort_other_plans, nullptr, first_instruction, stop_other_threads,
2031 eVoteYes, eVoteNoOpinion, frame_idx, error));
2033 new_plan_sp->SetIsControllingPlan(true);
2034 new_plan_sp->SetOkayToDiscard(false);
2036 // Why do we need to set the current thread by ID here???
2037 process->GetThreadList().SetSelectedThreadByID(GetID());
2038 error = process->Resume();
2039 } else {
2040 error = Status::FromErrorString("process not stopped");
2042 return error;
2045 ValueObjectSP Thread::GetCurrentException() {
2046 if (auto frame_sp = GetStackFrameAtIndex(0))
2047 if (auto recognized_frame = frame_sp->GetRecognizedFrame())
2048 if (auto e = recognized_frame->GetExceptionObject())
2049 return e;
2051 // NOTE: Even though this behavior is generalized, only ObjC is actually
2052 // supported at the moment.
2053 for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
2054 if (auto e = runtime->GetExceptionObjectForThread(shared_from_this()))
2055 return e;
2058 return ValueObjectSP();
2061 ThreadSP Thread::GetCurrentExceptionBacktrace() {
2062 ValueObjectSP exception = GetCurrentException();
2063 if (!exception)
2064 return ThreadSP();
2066 // NOTE: Even though this behavior is generalized, only ObjC is actually
2067 // supported at the moment.
2068 for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
2069 if (auto bt = runtime->GetBacktraceThreadFromException(exception))
2070 return bt;
2073 return ThreadSP();
2076 lldb::ValueObjectSP Thread::GetSiginfoValue() {
2077 ProcessSP process_sp = GetProcess();
2078 assert(process_sp);
2079 Target &target = process_sp->GetTarget();
2080 PlatformSP platform_sp = target.GetPlatform();
2081 assert(platform_sp);
2082 ArchSpec arch = target.GetArchitecture();
2084 CompilerType type = platform_sp->GetSiginfoType(arch.GetTriple());
2085 if (!type.IsValid())
2086 return ValueObjectConstResult::Create(
2087 &target, Status::FromErrorString("no siginfo_t for the platform"));
2089 std::optional<uint64_t> type_size = type.GetByteSize(nullptr);
2090 assert(type_size);
2091 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> data =
2092 GetSiginfo(*type_size);
2093 if (!data)
2094 return ValueObjectConstResult::Create(&target,
2095 Status::FromError(data.takeError()));
2097 DataExtractor data_extractor{data.get()->getBufferStart(), data.get()->getBufferSize(),
2098 process_sp->GetByteOrder(), arch.GetAddressByteSize()};
2099 return ValueObjectConstResult::Create(&target, type, ConstString("__lldb_siginfo"), data_extractor);