Path: blob/main/contrib/llvm-project/lldb/source/Target/Thread.cpp
39587 views
//===-- Thread.cpp --------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "lldb/Target/Thread.h"9#include "lldb/Breakpoint/BreakpointLocation.h"10#include "lldb/Core/Debugger.h"11#include "lldb/Core/FormatEntity.h"12#include "lldb/Core/Module.h"13#include "lldb/Core/StructuredDataImpl.h"14#include "lldb/Core/ValueObject.h"15#include "lldb/Core/ValueObjectConstResult.h"16#include "lldb/Host/Host.h"17#include "lldb/Interpreter/OptionValueFileSpecList.h"18#include "lldb/Interpreter/OptionValueProperties.h"19#include "lldb/Interpreter/Property.h"20#include "lldb/Symbol/Function.h"21#include "lldb/Target/ABI.h"22#include "lldb/Target/DynamicLoader.h"23#include "lldb/Target/ExecutionContext.h"24#include "lldb/Target/LanguageRuntime.h"25#include "lldb/Target/Process.h"26#include "lldb/Target/RegisterContext.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/ThreadPlanPython.h"35#include "lldb/Target/ThreadPlanRunToAddress.h"36#include "lldb/Target/ThreadPlanStack.h"37#include "lldb/Target/ThreadPlanStepInRange.h"38#include "lldb/Target/ThreadPlanStepInstruction.h"39#include "lldb/Target/ThreadPlanStepOut.h"40#include "lldb/Target/ThreadPlanStepOverBreakpoint.h"41#include "lldb/Target/ThreadPlanStepOverRange.h"42#include "lldb/Target/ThreadPlanStepThrough.h"43#include "lldb/Target/ThreadPlanStepUntil.h"44#include "lldb/Target/ThreadSpec.h"45#include "lldb/Target/UnwindLLDB.h"46#include "lldb/Utility/LLDBLog.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"5354#include <memory>55#include <optional>5657using namespace lldb;58using namespace lldb_private;5960ThreadProperties &Thread::GetGlobalProperties() {61// NOTE: intentional leak so we don't crash if global destructor chain gets62// called as other threads still use the result of this function63static ThreadProperties *g_settings_ptr = new ThreadProperties(true);64return *g_settings_ptr;65}6667#define LLDB_PROPERTIES_thread68#include "TargetProperties.inc"6970enum {71#define LLDB_PROPERTIES_thread72#include "TargetPropertiesEnum.inc"73};7475class ThreadOptionValueProperties76: public Cloneable<ThreadOptionValueProperties, OptionValueProperties> {77public:78ThreadOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}7980const Property *81GetPropertyAtIndex(size_t idx,82const ExecutionContext *exe_ctx) const override {83// When getting the value for a key from the thread options, we will always84// try and grab the setting from the current thread if there is one. Else85// we just use the one from this instance.86if (exe_ctx) {87Thread *thread = exe_ctx->GetThreadPtr();88if (thread) {89ThreadOptionValueProperties *instance_properties =90static_cast<ThreadOptionValueProperties *>(91thread->GetValueProperties().get());92if (this != instance_properties)93return instance_properties->ProtectedGetPropertyAtIndex(idx);94}95}96return ProtectedGetPropertyAtIndex(idx);97}98};99100ThreadProperties::ThreadProperties(bool is_global) : Properties() {101if (is_global) {102m_collection_sp = std::make_shared<ThreadOptionValueProperties>("thread");103m_collection_sp->Initialize(g_thread_properties);104} else105m_collection_sp =106OptionValueProperties::CreateLocalCopy(Thread::GetGlobalProperties());107}108109ThreadProperties::~ThreadProperties() = default;110111const RegularExpression *ThreadProperties::GetSymbolsToAvoidRegexp() {112const uint32_t idx = ePropertyStepAvoidRegex;113return GetPropertyAtIndexAs<const RegularExpression *>(idx);114}115116FileSpecList ThreadProperties::GetLibrariesToAvoid() const {117const uint32_t idx = ePropertyStepAvoidLibraries;118return GetPropertyAtIndexAs<FileSpecList>(idx, {});119}120121bool ThreadProperties::GetTraceEnabledState() const {122const uint32_t idx = ePropertyEnableThreadTrace;123return GetPropertyAtIndexAs<bool>(124idx, g_thread_properties[idx].default_uint_value != 0);125}126127bool ThreadProperties::GetStepInAvoidsNoDebug() const {128const uint32_t idx = ePropertyStepInAvoidsNoDebug;129return GetPropertyAtIndexAs<bool>(130idx, g_thread_properties[idx].default_uint_value != 0);131}132133bool ThreadProperties::GetStepOutAvoidsNoDebug() const {134const uint32_t idx = ePropertyStepOutAvoidsNoDebug;135return GetPropertyAtIndexAs<bool>(136idx, g_thread_properties[idx].default_uint_value != 0);137}138139uint64_t ThreadProperties::GetMaxBacktraceDepth() const {140const uint32_t idx = ePropertyMaxBacktraceDepth;141return GetPropertyAtIndexAs<uint64_t>(142idx, g_thread_properties[idx].default_uint_value);143}144145// Thread Event Data146147llvm::StringRef Thread::ThreadEventData::GetFlavorString() {148return "Thread::ThreadEventData";149}150151Thread::ThreadEventData::ThreadEventData(const lldb::ThreadSP thread_sp)152: m_thread_sp(thread_sp), m_stack_id() {}153154Thread::ThreadEventData::ThreadEventData(const lldb::ThreadSP thread_sp,155const StackID &stack_id)156: m_thread_sp(thread_sp), m_stack_id(stack_id) {}157158Thread::ThreadEventData::ThreadEventData() : m_thread_sp(), m_stack_id() {}159160Thread::ThreadEventData::~ThreadEventData() = default;161162void Thread::ThreadEventData::Dump(Stream *s) const {}163164const Thread::ThreadEventData *165Thread::ThreadEventData::GetEventDataFromEvent(const Event *event_ptr) {166if (event_ptr) {167const EventData *event_data = event_ptr->GetData();168if (event_data &&169event_data->GetFlavor() == ThreadEventData::GetFlavorString())170return static_cast<const ThreadEventData *>(event_ptr->GetData());171}172return nullptr;173}174175ThreadSP Thread::ThreadEventData::GetThreadFromEvent(const Event *event_ptr) {176ThreadSP thread_sp;177const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);178if (event_data)179thread_sp = event_data->GetThread();180return thread_sp;181}182183StackID Thread::ThreadEventData::GetStackIDFromEvent(const Event *event_ptr) {184StackID stack_id;185const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);186if (event_data)187stack_id = event_data->GetStackID();188return stack_id;189}190191StackFrameSP192Thread::ThreadEventData::GetStackFrameFromEvent(const Event *event_ptr) {193const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);194StackFrameSP frame_sp;195if (event_data) {196ThreadSP thread_sp = event_data->GetThread();197if (thread_sp) {198frame_sp = thread_sp->GetStackFrameList()->GetFrameWithStackID(199event_data->GetStackID());200}201}202return frame_sp;203}204205// Thread class206207llvm::StringRef Thread::GetStaticBroadcasterClass() {208static constexpr llvm::StringLiteral class_name("lldb.thread");209return class_name;210}211212Thread::Thread(Process &process, lldb::tid_t tid, bool use_invalid_index_id)213: ThreadProperties(false), UserID(tid),214Broadcaster(process.GetTarget().GetDebugger().GetBroadcasterManager(),215Thread::GetStaticBroadcasterClass().str()),216m_process_wp(process.shared_from_this()), m_stop_info_sp(),217m_stop_info_stop_id(0), m_stop_info_override_stop_id(0),218m_should_run_before_public_stop(false),219m_index_id(use_invalid_index_id ? LLDB_INVALID_INDEX32220: process.GetNextThreadIndexID(tid)),221m_reg_context_sp(), m_state(eStateUnloaded), m_state_mutex(),222m_frame_mutex(), m_curr_frames_sp(), m_prev_frames_sp(),223m_prev_framezero_pc(), m_resume_signal(LLDB_INVALID_SIGNAL_NUMBER),224m_resume_state(eStateRunning), m_temporary_resume_state(eStateRunning),225m_unwinder_up(), m_destroy_called(false),226m_override_should_notify(eLazyBoolCalculate),227m_extended_info_fetched(false), m_extended_info() {228Log *log = GetLog(LLDBLog::Object);229LLDB_LOGF(log, "%p Thread::Thread(tid = 0x%4.4" PRIx64 ")",230static_cast<void *>(this), GetID());231232CheckInWithManager();233}234235Thread::~Thread() {236Log *log = GetLog(LLDBLog::Object);237LLDB_LOGF(log, "%p Thread::~Thread(tid = 0x%4.4" PRIx64 ")",238static_cast<void *>(this), GetID());239/// If you hit this assert, it means your derived class forgot to call240/// DoDestroy in its destructor.241assert(m_destroy_called);242}243244void Thread::DestroyThread() {245m_destroy_called = true;246m_stop_info_sp.reset();247m_reg_context_sp.reset();248m_unwinder_up.reset();249std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);250m_curr_frames_sp.reset();251m_prev_frames_sp.reset();252m_prev_framezero_pc.reset();253}254255void Thread::BroadcastSelectedFrameChange(StackID &new_frame_id) {256if (EventTypeHasListeners(eBroadcastBitSelectedFrameChanged)) {257auto data_sp =258std::make_shared<ThreadEventData>(shared_from_this(), new_frame_id);259BroadcastEvent(eBroadcastBitSelectedFrameChanged, data_sp);260}261}262263lldb::StackFrameSP264Thread::GetSelectedFrame(SelectMostRelevant select_most_relevant) {265StackFrameListSP stack_frame_list_sp(GetStackFrameList());266StackFrameSP frame_sp = stack_frame_list_sp->GetFrameAtIndex(267stack_frame_list_sp->GetSelectedFrameIndex(select_most_relevant));268FrameSelectedCallback(frame_sp.get());269return frame_sp;270}271272uint32_t Thread::SetSelectedFrame(lldb_private::StackFrame *frame,273bool broadcast) {274uint32_t ret_value = GetStackFrameList()->SetSelectedFrame(frame);275if (broadcast)276BroadcastSelectedFrameChange(frame->GetStackID());277FrameSelectedCallback(frame);278return ret_value;279}280281bool Thread::SetSelectedFrameByIndex(uint32_t frame_idx, bool broadcast) {282StackFrameSP frame_sp(GetStackFrameList()->GetFrameAtIndex(frame_idx));283if (frame_sp) {284GetStackFrameList()->SetSelectedFrame(frame_sp.get());285if (broadcast)286BroadcastSelectedFrameChange(frame_sp->GetStackID());287FrameSelectedCallback(frame_sp.get());288return true;289} else290return false;291}292293bool Thread::SetSelectedFrameByIndexNoisily(uint32_t frame_idx,294Stream &output_stream) {295const bool broadcast = true;296bool success = SetSelectedFrameByIndex(frame_idx, broadcast);297if (success) {298StackFrameSP frame_sp = GetSelectedFrame(DoNoSelectMostRelevantFrame);299if (frame_sp) {300bool already_shown = false;301SymbolContext frame_sc(302frame_sp->GetSymbolContext(eSymbolContextLineEntry));303const Debugger &debugger = GetProcess()->GetTarget().GetDebugger();304if (debugger.GetUseExternalEditor() && frame_sc.line_entry.GetFile() &&305frame_sc.line_entry.line != 0) {306if (llvm::Error e = Host::OpenFileInExternalEditor(307debugger.GetExternalEditor(), frame_sc.line_entry.GetFile(),308frame_sc.line_entry.line)) {309LLDB_LOG_ERROR(GetLog(LLDBLog::Host), std::move(e),310"OpenFileInExternalEditor failed: {0}");311} else {312already_shown = true;313}314}315316bool show_frame_info = true;317bool show_source = !already_shown;318FrameSelectedCallback(frame_sp.get());319return frame_sp->GetStatus(output_stream, show_frame_info, show_source);320}321return false;322} else323return false;324}325326void Thread::FrameSelectedCallback(StackFrame *frame) {327if (!frame)328return;329330if (frame->HasDebugInformation() &&331(GetProcess()->GetWarningsOptimization() ||332GetProcess()->GetWarningsUnsupportedLanguage())) {333SymbolContext sc =334frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextModule);335GetProcess()->PrintWarningOptimization(sc);336GetProcess()->PrintWarningUnsupportedLanguage(sc);337}338}339340lldb::StopInfoSP Thread::GetStopInfo() {341if (m_destroy_called)342return m_stop_info_sp;343344ThreadPlanSP completed_plan_sp(GetCompletedPlan());345ProcessSP process_sp(GetProcess());346const uint32_t stop_id = process_sp ? process_sp->GetStopID() : UINT32_MAX;347348// Here we select the stop info according to priorirty: - m_stop_info_sp (if349// not trace) - preset value - completed plan stop info - new value with plan350// from completed plan stack - m_stop_info_sp (trace stop reason is OK now) -351// ask GetPrivateStopInfo to set stop info352353bool have_valid_stop_info = m_stop_info_sp &&354m_stop_info_sp ->IsValid() &&355m_stop_info_stop_id == stop_id;356bool have_valid_completed_plan = completed_plan_sp && completed_plan_sp->PlanSucceeded();357bool plan_failed = completed_plan_sp && !completed_plan_sp->PlanSucceeded();358bool plan_overrides_trace =359have_valid_stop_info && have_valid_completed_plan360&& (m_stop_info_sp->GetStopReason() == eStopReasonTrace);361362if (have_valid_stop_info && !plan_overrides_trace && !plan_failed) {363return m_stop_info_sp;364} else if (completed_plan_sp) {365return StopInfo::CreateStopReasonWithPlan(366completed_plan_sp, GetReturnValueObject(), GetExpressionVariable());367} else {368GetPrivateStopInfo();369return m_stop_info_sp;370}371}372373void Thread::CalculatePublicStopInfo() {374ResetStopInfo();375SetStopInfo(GetStopInfo());376}377378lldb::StopInfoSP Thread::GetPrivateStopInfo(bool calculate) {379if (!calculate)380return m_stop_info_sp;381382if (m_destroy_called)383return m_stop_info_sp;384385ProcessSP process_sp(GetProcess());386if (process_sp) {387const uint32_t process_stop_id = process_sp->GetStopID();388if (m_stop_info_stop_id != process_stop_id) {389// We preserve the old stop info for a variety of reasons:390// 1) Someone has already updated it by the time we get here391// 2) We didn't get to execute the breakpoint instruction we stopped at392// 3) This is a virtual step so we didn't actually run393// 4) If this thread wasn't allowed to run the last time round.394if (m_stop_info_sp) {395if (m_stop_info_sp->IsValid() || IsStillAtLastBreakpointHit() ||396GetCurrentPlan()->IsVirtualStep()397|| GetTemporaryResumeState() == eStateSuspended)398SetStopInfo(m_stop_info_sp);399else400m_stop_info_sp.reset();401}402403if (!m_stop_info_sp) {404if (!CalculateStopInfo())405SetStopInfo(StopInfoSP());406}407}408409// The stop info can be manually set by calling Thread::SetStopInfo() prior410// to this function ever getting called, so we can't rely on411// "m_stop_info_stop_id != process_stop_id" as the condition for the if412// statement below, we must also check the stop info to see if we need to413// override it. See the header documentation in414// Architecture::OverrideStopInfo() for more information on the stop415// info override callback.416if (m_stop_info_override_stop_id != process_stop_id) {417m_stop_info_override_stop_id = process_stop_id;418if (m_stop_info_sp) {419if (const Architecture *arch =420process_sp->GetTarget().GetArchitecturePlugin())421arch->OverrideStopInfo(*this);422}423}424}425426// If we were resuming the process and it was interrupted,427// return no stop reason. This thread would like to resume.428if (m_stop_info_sp && m_stop_info_sp->WasContinueInterrupted(*this))429return {};430431return m_stop_info_sp;432}433434lldb::StopReason Thread::GetStopReason() {435lldb::StopInfoSP stop_info_sp(GetStopInfo());436if (stop_info_sp)437return stop_info_sp->GetStopReason();438return eStopReasonNone;439}440441bool Thread::StopInfoIsUpToDate() const {442ProcessSP process_sp(GetProcess());443if (process_sp)444return m_stop_info_stop_id == process_sp->GetStopID();445else446return true; // Process is no longer around so stop info is always up to447// date...448}449450void Thread::ResetStopInfo() {451if (m_stop_info_sp) {452m_stop_info_sp.reset();453}454}455456void Thread::SetStopInfo(const lldb::StopInfoSP &stop_info_sp) {457m_stop_info_sp = stop_info_sp;458if (m_stop_info_sp) {459m_stop_info_sp->MakeStopInfoValid();460// If we are overriding the ShouldReportStop, do that here:461if (m_override_should_notify != eLazyBoolCalculate)462m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==463eLazyBoolYes);464}465466ProcessSP process_sp(GetProcess());467if (process_sp)468m_stop_info_stop_id = process_sp->GetStopID();469else470m_stop_info_stop_id = UINT32_MAX;471Log *log = GetLog(LLDBLog::Thread);472LLDB_LOGF(log, "%p: tid = 0x%" PRIx64 ": stop info = %s (stop_id = %u)",473static_cast<void *>(this), GetID(),474stop_info_sp ? stop_info_sp->GetDescription() : "<NULL>",475m_stop_info_stop_id);476}477478void Thread::SetShouldReportStop(Vote vote) {479if (vote == eVoteNoOpinion)480return;481else {482m_override_should_notify = (vote == eVoteYes ? eLazyBoolYes : eLazyBoolNo);483if (m_stop_info_sp)484m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==485eLazyBoolYes);486}487}488489void Thread::SetStopInfoToNothing() {490// Note, we can't just NULL out the private reason, or the native thread491// implementation will try to go calculate it again. For now, just set it to492// a Unix Signal with an invalid signal number.493SetStopInfo(494StopInfo::CreateStopReasonWithSignal(*this, LLDB_INVALID_SIGNAL_NUMBER));495}496497bool Thread::ThreadStoppedForAReason() { return (bool)GetPrivateStopInfo(); }498499bool Thread::CheckpointThreadState(ThreadStateCheckpoint &saved_state) {500saved_state.register_backup_sp.reset();501lldb::StackFrameSP frame_sp(GetStackFrameAtIndex(0));502if (frame_sp) {503lldb::RegisterCheckpointSP reg_checkpoint_sp(504new RegisterCheckpoint(RegisterCheckpoint::Reason::eExpression));505if (reg_checkpoint_sp) {506lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());507if (reg_ctx_sp && reg_ctx_sp->ReadAllRegisterValues(*reg_checkpoint_sp))508saved_state.register_backup_sp = reg_checkpoint_sp;509}510}511if (!saved_state.register_backup_sp)512return false;513514saved_state.stop_info_sp = GetStopInfo();515ProcessSP process_sp(GetProcess());516if (process_sp)517saved_state.orig_stop_id = process_sp->GetStopID();518saved_state.current_inlined_depth = GetCurrentInlinedDepth();519saved_state.m_completed_plan_checkpoint =520GetPlans().CheckpointCompletedPlans();521522return true;523}524525bool Thread::RestoreRegisterStateFromCheckpoint(526ThreadStateCheckpoint &saved_state) {527if (saved_state.register_backup_sp) {528lldb::StackFrameSP frame_sp(GetStackFrameAtIndex(0));529if (frame_sp) {530lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());531if (reg_ctx_sp) {532bool ret =533reg_ctx_sp->WriteAllRegisterValues(*saved_state.register_backup_sp);534535// Clear out all stack frames as our world just changed.536ClearStackFrames();537reg_ctx_sp->InvalidateIfNeeded(true);538if (m_unwinder_up)539m_unwinder_up->Clear();540return ret;541}542}543}544return false;545}546547void Thread::RestoreThreadStateFromCheckpoint(548ThreadStateCheckpoint &saved_state) {549if (saved_state.stop_info_sp)550saved_state.stop_info_sp->MakeStopInfoValid();551SetStopInfo(saved_state.stop_info_sp);552GetStackFrameList()->SetCurrentInlinedDepth(553saved_state.current_inlined_depth);554GetPlans().RestoreCompletedPlanCheckpoint(555saved_state.m_completed_plan_checkpoint);556}557558StateType Thread::GetState() const {559// If any other threads access this we will need a mutex for it560std::lock_guard<std::recursive_mutex> guard(m_state_mutex);561return m_state;562}563564void Thread::SetState(StateType state) {565std::lock_guard<std::recursive_mutex> guard(m_state_mutex);566m_state = state;567}568569std::string Thread::GetStopDescription() {570StackFrameSP frame_sp = GetStackFrameAtIndex(0);571572if (!frame_sp)573return GetStopDescriptionRaw();574575auto recognized_frame_sp = frame_sp->GetRecognizedFrame();576577if (!recognized_frame_sp)578return GetStopDescriptionRaw();579580std::string recognized_stop_description =581recognized_frame_sp->GetStopDescription();582583if (!recognized_stop_description.empty())584return recognized_stop_description;585586return GetStopDescriptionRaw();587}588589std::string Thread::GetStopDescriptionRaw() {590StopInfoSP stop_info_sp = GetStopInfo();591std::string raw_stop_description;592if (stop_info_sp && stop_info_sp->IsValid()) {593raw_stop_description = stop_info_sp->GetDescription();594assert((!raw_stop_description.empty() ||595stop_info_sp->GetStopReason() == eStopReasonNone) &&596"StopInfo returned an empty description.");597}598return raw_stop_description;599}600601void Thread::WillStop() {602ThreadPlan *current_plan = GetCurrentPlan();603604// FIXME: I may decide to disallow threads with no plans. In which605// case this should go to an assert.606607if (!current_plan)608return;609610current_plan->WillStop();611}612613void Thread::SetupForResume() {614if (GetResumeState() != eStateSuspended) {615// If we're at a breakpoint push the step-over breakpoint plan. Do this616// before telling the current plan it will resume, since we might change617// what the current plan is.618619lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext());620if (reg_ctx_sp) {621const addr_t thread_pc = reg_ctx_sp->GetPC();622BreakpointSiteSP bp_site_sp =623GetProcess()->GetBreakpointSiteList().FindByAddress(thread_pc);624if (bp_site_sp) {625// Note, don't assume there's a ThreadPlanStepOverBreakpoint, the626// target may not require anything special to step over a breakpoint.627628ThreadPlan *cur_plan = GetCurrentPlan();629630bool push_step_over_bp_plan = false;631if (cur_plan->GetKind() == ThreadPlan::eKindStepOverBreakpoint) {632ThreadPlanStepOverBreakpoint *bp_plan =633(ThreadPlanStepOverBreakpoint *)cur_plan;634if (bp_plan->GetBreakpointLoadAddress() != thread_pc)635push_step_over_bp_plan = true;636} else637push_step_over_bp_plan = true;638639if (push_step_over_bp_plan) {640ThreadPlanSP step_bp_plan_sp(new ThreadPlanStepOverBreakpoint(*this));641if (step_bp_plan_sp) {642step_bp_plan_sp->SetPrivate(true);643644if (GetCurrentPlan()->RunState() != eStateStepping) {645ThreadPlanStepOverBreakpoint *step_bp_plan =646static_cast<ThreadPlanStepOverBreakpoint *>(647step_bp_plan_sp.get());648step_bp_plan->SetAutoContinue(true);649}650QueueThreadPlan(step_bp_plan_sp, false);651}652}653}654}655}656}657658bool Thread::ShouldResume(StateType resume_state) {659// At this point clear the completed plan stack.660GetPlans().WillResume();661m_override_should_notify = eLazyBoolCalculate;662663StateType prev_resume_state = GetTemporaryResumeState();664665SetTemporaryResumeState(resume_state);666667lldb::ThreadSP backing_thread_sp(GetBackingThread());668if (backing_thread_sp)669backing_thread_sp->SetTemporaryResumeState(resume_state);670671// Make sure m_stop_info_sp is valid. Don't do this for threads we suspended672// in the previous run.673if (prev_resume_state != eStateSuspended)674GetPrivateStopInfo();675676// This is a little dubious, but we are trying to limit how often we actually677// fetch stop info from the target, 'cause that slows down single stepping.678// So assume that if we got to the point where we're about to resume, and we679// haven't yet had to fetch the stop reason, then it doesn't need to know680// about the fact that we are resuming...681const uint32_t process_stop_id = GetProcess()->GetStopID();682if (m_stop_info_stop_id == process_stop_id &&683(m_stop_info_sp && m_stop_info_sp->IsValid())) {684StopInfo *stop_info = GetPrivateStopInfo().get();685if (stop_info)686stop_info->WillResume(resume_state);687}688689// Tell all the plans that we are about to resume in case they need to clear690// any state. We distinguish between the plan on the top of the stack and the691// lower plans in case a plan needs to do any special business before it692// runs.693694bool need_to_resume = false;695ThreadPlan *plan_ptr = GetCurrentPlan();696if (plan_ptr) {697need_to_resume = plan_ptr->WillResume(resume_state, true);698699while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {700plan_ptr->WillResume(resume_state, false);701}702703// If the WillResume for the plan says we are faking a resume, then it will704// have set an appropriate stop info. In that case, don't reset it here.705706if (need_to_resume && resume_state != eStateSuspended) {707m_stop_info_sp.reset();708}709}710711if (need_to_resume) {712ClearStackFrames();713// Let Thread subclasses do any special work they need to prior to resuming714WillResume(resume_state);715}716717return need_to_resume;718}719720void Thread::DidResume() {721SetResumeSignal(LLDB_INVALID_SIGNAL_NUMBER);722// This will get recomputed each time when we stop.723SetShouldRunBeforePublicStop(false);724}725726void Thread::DidStop() { SetState(eStateStopped); }727728bool Thread::ShouldStop(Event *event_ptr) {729ThreadPlan *current_plan = GetCurrentPlan();730731bool should_stop = true;732733Log *log = GetLog(LLDBLog::Step);734735if (GetResumeState() == eStateSuspended) {736LLDB_LOGF(log,737"Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64738", should_stop = 0 (ignore since thread was suspended)",739__FUNCTION__, GetID(), GetProtocolID());740return false;741}742743if (GetTemporaryResumeState() == eStateSuspended) {744LLDB_LOGF(log,745"Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64746", should_stop = 0 (ignore since thread was suspended)",747__FUNCTION__, GetID(), GetProtocolID());748return false;749}750751// Based on the current thread plan and process stop info, check if this752// thread caused the process to stop. NOTE: this must take place before the753// plan is moved from the current plan stack to the completed plan stack.754if (!ThreadStoppedForAReason()) {755LLDB_LOGF(log,756"Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64757", pc = 0x%16.16" PRIx64758", should_stop = 0 (ignore since no stop reason)",759__FUNCTION__, GetID(), GetProtocolID(),760GetRegisterContext() ? GetRegisterContext()->GetPC()761: LLDB_INVALID_ADDRESS);762return false;763}764765// Clear the "must run me before stop" if it was set:766SetShouldRunBeforePublicStop(false);767768if (log) {769LLDB_LOGF(log,770"Thread::%s(%p) for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64771", pc = 0x%16.16" PRIx64,772__FUNCTION__, static_cast<void *>(this), GetID(), GetProtocolID(),773GetRegisterContext() ? GetRegisterContext()->GetPC()774: LLDB_INVALID_ADDRESS);775LLDB_LOGF(log, "^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^");776StreamString s;777s.IndentMore();778GetProcess()->DumpThreadPlansForTID(779s, GetID(), eDescriptionLevelVerbose, true /* internal */,780false /* condense_trivial */, true /* skip_unreported */);781LLDB_LOGF(log, "Plan stack initial state:\n%s", s.GetData());782}783784// The top most plan always gets to do the trace log...785current_plan->DoTraceLog();786787// First query the stop info's ShouldStopSynchronous. This handles788// "synchronous" stop reasons, for example the breakpoint command on internal789// breakpoints. If a synchronous stop reason says we should not stop, then790// we don't have to do any more work on this stop.791StopInfoSP private_stop_info(GetPrivateStopInfo());792if (private_stop_info &&793!private_stop_info->ShouldStopSynchronous(event_ptr)) {794LLDB_LOGF(log, "StopInfo::ShouldStop async callback says we should not "795"stop, returning ShouldStop of false.");796return false;797}798799// If we've already been restarted, don't query the plans since the state800// they would examine is not current.801if (Process::ProcessEventData::GetRestartedFromEvent(event_ptr))802return false;803804// Before the plans see the state of the world, calculate the current inlined805// depth.806GetStackFrameList()->CalculateCurrentInlinedDepth();807808// If the base plan doesn't understand why we stopped, then we have to find a809// plan that does. If that plan is still working, then we don't need to do810// any more work. If the plan that explains the stop is done, then we should811// pop all the plans below it, and pop it, and then let the plans above it812// decide whether they still need to do more work.813814bool done_processing_current_plan = false;815816if (!current_plan->PlanExplainsStop(event_ptr)) {817if (current_plan->TracerExplainsStop()) {818done_processing_current_plan = true;819should_stop = false;820} else {821// If the current plan doesn't explain the stop, then find one that does822// and let it handle the situation.823ThreadPlan *plan_ptr = current_plan;824while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {825if (plan_ptr->PlanExplainsStop(event_ptr)) {826LLDB_LOGF(log, "Plan %s explains stop.", plan_ptr->GetName());827828should_stop = plan_ptr->ShouldStop(event_ptr);829830// plan_ptr explains the stop, next check whether plan_ptr is done,831// if so, then we should take it and all the plans below it off the832// stack.833834if (plan_ptr->MischiefManaged()) {835// We're going to pop the plans up to and including the plan that836// explains the stop.837ThreadPlan *prev_plan_ptr = GetPreviousPlan(plan_ptr);838839do {840if (should_stop)841current_plan->WillStop();842PopPlan();843} while ((current_plan = GetCurrentPlan()) != prev_plan_ptr);844// Now, if the responsible plan was not "Okay to discard" then845// we're done, otherwise we forward this to the next plan in the846// stack below.847done_processing_current_plan =848(plan_ptr->IsControllingPlan() && !plan_ptr->OkayToDiscard());849} else {850bool should_force_run = plan_ptr->ShouldRunBeforePublicStop();851if (should_force_run) {852SetShouldRunBeforePublicStop(true);853should_stop = false;854}855done_processing_current_plan = true;856}857break;858}859}860}861}862863if (!done_processing_current_plan) {864bool override_stop = false;865866// We're starting from the base plan, so just let it decide;867if (current_plan->IsBasePlan()) {868should_stop = current_plan->ShouldStop(event_ptr);869LLDB_LOGF(log, "Base plan says should stop: %i.", should_stop);870} else {871// Otherwise, don't let the base plan override what the other plans say872// to do, since presumably if there were other plans they would know what873// to do...874while (true) {875if (current_plan->IsBasePlan())876break;877878should_stop = current_plan->ShouldStop(event_ptr);879LLDB_LOGF(log, "Plan %s should stop: %d.", current_plan->GetName(),880should_stop);881if (current_plan->MischiefManaged()) {882if (should_stop)883current_plan->WillStop();884885if (current_plan->ShouldAutoContinue(event_ptr)) {886override_stop = true;887LLDB_LOGF(log, "Plan %s auto-continue: true.",888current_plan->GetName());889}890891// If a Controlling Plan wants to stop, we let it. Otherwise, see if892// the plan's parent wants to stop.893894PopPlan();895if (should_stop && current_plan->IsControllingPlan() &&896!current_plan->OkayToDiscard()) {897break;898}899900current_plan = GetCurrentPlan();901if (current_plan == nullptr) {902break;903}904} else {905break;906}907}908}909910if (override_stop)911should_stop = false;912}913914// One other potential problem is that we set up a controlling plan, then stop915// in before it is complete - for instance by hitting a breakpoint during a916// step-over - then do some step/finish/etc operations that wind up past the917// end point condition of the initial plan. We don't want to strand the918// original plan on the stack, This code clears stale plans off the stack.919920if (should_stop) {921ThreadPlan *plan_ptr = GetCurrentPlan();922923// Discard the stale plans and all plans below them in the stack, plus move924// the completed plans to the completed plan stack925while (!plan_ptr->IsBasePlan()) {926bool stale = plan_ptr->IsPlanStale();927ThreadPlan *examined_plan = plan_ptr;928plan_ptr = GetPreviousPlan(examined_plan);929930if (stale) {931LLDB_LOGF(932log,933"Plan %s being discarded in cleanup, it says it is already done.",934examined_plan->GetName());935while (GetCurrentPlan() != examined_plan) {936DiscardPlan();937}938if (examined_plan->IsPlanComplete()) {939// plan is complete but does not explain the stop (example: step to a940// line with breakpoint), let us move the plan to941// completed_plan_stack anyway942PopPlan();943} else944DiscardPlan();945}946}947}948949if (log) {950StreamString s;951s.IndentMore();952GetProcess()->DumpThreadPlansForTID(953s, GetID(), eDescriptionLevelVerbose, true /* internal */,954false /* condense_trivial */, true /* skip_unreported */);955LLDB_LOGF(log, "Plan stack final state:\n%s", s.GetData());956LLDB_LOGF(log, "vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv",957should_stop);958}959return should_stop;960}961962Vote Thread::ShouldReportStop(Event *event_ptr) {963StateType thread_state = GetResumeState();964StateType temp_thread_state = GetTemporaryResumeState();965966Log *log = GetLog(LLDBLog::Step);967968if (thread_state == eStateSuspended || thread_state == eStateInvalid) {969LLDB_LOGF(log,970"Thread::ShouldReportStop() tid = 0x%4.4" PRIx64971": returning vote %i (state was suspended or invalid)",972GetID(), eVoteNoOpinion);973return eVoteNoOpinion;974}975976if (temp_thread_state == eStateSuspended ||977temp_thread_state == eStateInvalid) {978LLDB_LOGF(log,979"Thread::ShouldReportStop() tid = 0x%4.4" PRIx64980": returning vote %i (temporary state was suspended or invalid)",981GetID(), eVoteNoOpinion);982return eVoteNoOpinion;983}984985if (!ThreadStoppedForAReason()) {986LLDB_LOGF(log,987"Thread::ShouldReportStop() tid = 0x%4.4" PRIx64988": returning vote %i (thread didn't stop for a reason.)",989GetID(), eVoteNoOpinion);990return eVoteNoOpinion;991}992993if (GetPlans().AnyCompletedPlans()) {994// Pass skip_private = false to GetCompletedPlan, since we want to ask995// the last plan, regardless of whether it is private or not.996LLDB_LOGF(log,997"Thread::ShouldReportStop() tid = 0x%4.4" PRIx64998": returning vote for complete stack's back plan",999GetID());1000return GetPlans().GetCompletedPlan(false)->ShouldReportStop(event_ptr);1001} else {1002Vote thread_vote = eVoteNoOpinion;1003ThreadPlan *plan_ptr = GetCurrentPlan();1004while (true) {1005if (plan_ptr->PlanExplainsStop(event_ptr)) {1006thread_vote = plan_ptr->ShouldReportStop(event_ptr);1007break;1008}1009if (plan_ptr->IsBasePlan())1010break;1011else1012plan_ptr = GetPreviousPlan(plan_ptr);1013}1014LLDB_LOGF(log,1015"Thread::ShouldReportStop() tid = 0x%4.4" PRIx641016": returning vote %i for current plan",1017GetID(), thread_vote);10181019return thread_vote;1020}1021}10221023Vote Thread::ShouldReportRun(Event *event_ptr) {1024StateType thread_state = GetResumeState();10251026if (thread_state == eStateSuspended || thread_state == eStateInvalid) {1027return eVoteNoOpinion;1028}10291030Log *log = GetLog(LLDBLog::Step);1031if (GetPlans().AnyCompletedPlans()) {1032// Pass skip_private = false to GetCompletedPlan, since we want to ask1033// the last plan, regardless of whether it is private or not.1034LLDB_LOGF(log,1035"Current Plan for thread %d(%p) (0x%4.4" PRIx641036", %s): %s being asked whether we should report run.",1037GetIndexID(), static_cast<void *>(this), GetID(),1038StateAsCString(GetTemporaryResumeState()),1039GetCompletedPlan()->GetName());10401041return GetPlans().GetCompletedPlan(false)->ShouldReportRun(event_ptr);1042} else {1043LLDB_LOGF(log,1044"Current Plan for thread %d(%p) (0x%4.4" PRIx641045", %s): %s being asked whether we should report run.",1046GetIndexID(), static_cast<void *>(this), GetID(),1047StateAsCString(GetTemporaryResumeState()),1048GetCurrentPlan()->GetName());10491050return GetCurrentPlan()->ShouldReportRun(event_ptr);1051}1052}10531054bool Thread::MatchesSpec(const ThreadSpec *spec) {1055return (spec == nullptr) ? true : spec->ThreadPassesBasicTests(*this);1056}10571058ThreadPlanStack &Thread::GetPlans() const {1059ThreadPlanStack *plans = GetProcess()->FindThreadPlans(GetID());1060if (plans)1061return *plans;10621063// History threads don't have a thread plan, but they do ask get asked to1064// describe themselves, which usually involves pulling out the stop reason.1065// That in turn will check for a completed plan on the ThreadPlanStack.1066// Instead of special-casing at that point, we return a Stack with a1067// ThreadPlanNull as its base plan. That will give the right answers to the1068// queries GetDescription makes, and only assert if you try to run the thread.1069if (!m_null_plan_stack_up)1070m_null_plan_stack_up = std::make_unique<ThreadPlanStack>(*this, true);1071return *m_null_plan_stack_up;1072}10731074void Thread::PushPlan(ThreadPlanSP thread_plan_sp) {1075assert(thread_plan_sp && "Don't push an empty thread plan.");10761077Log *log = GetLog(LLDBLog::Step);1078if (log) {1079StreamString s;1080thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelFull);1081LLDB_LOGF(log, "Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".",1082static_cast<void *>(this), s.GetData(),1083thread_plan_sp->GetThread().GetID());1084}10851086GetPlans().PushPlan(std::move(thread_plan_sp));1087}10881089void Thread::PopPlan() {1090Log *log = GetLog(LLDBLog::Step);1091ThreadPlanSP popped_plan_sp = GetPlans().PopPlan();1092if (log) {1093LLDB_LOGF(log, "Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".",1094popped_plan_sp->GetName(), popped_plan_sp->GetThread().GetID());1095}1096}10971098void Thread::DiscardPlan() {1099Log *log = GetLog(LLDBLog::Step);1100ThreadPlanSP discarded_plan_sp = GetPlans().DiscardPlan();11011102LLDB_LOGF(log, "Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".",1103discarded_plan_sp->GetName(),1104discarded_plan_sp->GetThread().GetID());1105}11061107void Thread::AutoCompleteThreadPlans(CompletionRequest &request) const {1108const ThreadPlanStack &plans = GetPlans();1109if (!plans.AnyPlans())1110return;11111112// Iterate from the second plan (index: 1) to skip the base plan.1113ThreadPlanSP p;1114uint32_t i = 1;1115while ((p = plans.GetPlanByIndex(i, false))) {1116StreamString strm;1117p->GetDescription(&strm, eDescriptionLevelInitial);1118request.TryCompleteCurrentArg(std::to_string(i), strm.GetString());1119i++;1120}1121}11221123ThreadPlan *Thread::GetCurrentPlan() const {1124return GetPlans().GetCurrentPlan().get();1125}11261127ThreadPlanSP Thread::GetCompletedPlan() const {1128return GetPlans().GetCompletedPlan();1129}11301131ValueObjectSP Thread::GetReturnValueObject() const {1132return GetPlans().GetReturnValueObject();1133}11341135ExpressionVariableSP Thread::GetExpressionVariable() const {1136return GetPlans().GetExpressionVariable();1137}11381139bool Thread::IsThreadPlanDone(ThreadPlan *plan) const {1140return GetPlans().IsPlanDone(plan);1141}11421143bool Thread::WasThreadPlanDiscarded(ThreadPlan *plan) const {1144return GetPlans().WasPlanDiscarded(plan);1145}11461147bool Thread::CompletedPlanOverridesBreakpoint() const {1148return GetPlans().AnyCompletedPlans();1149}11501151ThreadPlan *Thread::GetPreviousPlan(ThreadPlan *current_plan) const{1152return GetPlans().GetPreviousPlan(current_plan);1153}11541155Status Thread::QueueThreadPlan(ThreadPlanSP &thread_plan_sp,1156bool abort_other_plans) {1157Status status;1158StreamString s;1159if (!thread_plan_sp->ValidatePlan(&s)) {1160DiscardThreadPlansUpToPlan(thread_plan_sp);1161thread_plan_sp.reset();1162status.SetErrorString(s.GetString());1163return status;1164}11651166if (abort_other_plans)1167DiscardThreadPlans(true);11681169PushPlan(thread_plan_sp);11701171// This seems a little funny, but I don't want to have to split up the1172// constructor and the DidPush in the scripted plan, that seems annoying.1173// That means the constructor has to be in DidPush. So I have to validate the1174// plan AFTER pushing it, and then take it off again...1175if (!thread_plan_sp->ValidatePlan(&s)) {1176DiscardThreadPlansUpToPlan(thread_plan_sp);1177thread_plan_sp.reset();1178status.SetErrorString(s.GetString());1179return status;1180}11811182return status;1183}11841185bool Thread::DiscardUserThreadPlansUpToIndex(uint32_t plan_index) {1186// Count the user thread plans from the back end to get the number of the one1187// we want to discard:11881189ThreadPlan *up_to_plan_ptr = GetPlans().GetPlanByIndex(plan_index).get();1190if (up_to_plan_ptr == nullptr)1191return false;11921193DiscardThreadPlansUpToPlan(up_to_plan_ptr);1194return true;1195}11961197void Thread::DiscardThreadPlansUpToPlan(lldb::ThreadPlanSP &up_to_plan_sp) {1198DiscardThreadPlansUpToPlan(up_to_plan_sp.get());1199}12001201void Thread::DiscardThreadPlansUpToPlan(ThreadPlan *up_to_plan_ptr) {1202Log *log = GetLog(LLDBLog::Step);1203LLDB_LOGF(log,1204"Discarding thread plans for thread tid = 0x%4.4" PRIx641205", up to %p",1206GetID(), static_cast<void *>(up_to_plan_ptr));1207GetPlans().DiscardPlansUpToPlan(up_to_plan_ptr);1208}12091210void Thread::DiscardThreadPlans(bool force) {1211Log *log = GetLog(LLDBLog::Step);1212if (log) {1213LLDB_LOGF(log,1214"Discarding thread plans for thread (tid = 0x%4.4" PRIx641215", force %d)",1216GetID(), force);1217}12181219if (force) {1220GetPlans().DiscardAllPlans();1221return;1222}1223GetPlans().DiscardConsultingControllingPlans();1224}12251226Status Thread::UnwindInnermostExpression() {1227Status error;1228ThreadPlan *innermost_expr_plan = GetPlans().GetInnermostExpression();1229if (!innermost_expr_plan) {1230error.SetErrorString("No expressions currently active on this thread");1231return error;1232}1233DiscardThreadPlansUpToPlan(innermost_expr_plan);1234return error;1235}12361237ThreadPlanSP Thread::QueueBasePlan(bool abort_other_plans) {1238ThreadPlanSP thread_plan_sp(new ThreadPlanBase(*this));1239QueueThreadPlan(thread_plan_sp, abort_other_plans);1240return thread_plan_sp;1241}12421243ThreadPlanSP Thread::QueueThreadPlanForStepSingleInstruction(1244bool step_over, bool abort_other_plans, bool stop_other_threads,1245Status &status) {1246ThreadPlanSP thread_plan_sp(new ThreadPlanStepInstruction(1247*this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));1248status = QueueThreadPlan(thread_plan_sp, abort_other_plans);1249return thread_plan_sp;1250}12511252ThreadPlanSP Thread::QueueThreadPlanForStepOverRange(1253bool abort_other_plans, const AddressRange &range,1254const SymbolContext &addr_context, lldb::RunMode stop_other_threads,1255Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {1256ThreadPlanSP thread_plan_sp;1257thread_plan_sp = std::make_shared<ThreadPlanStepOverRange>(1258*this, range, addr_context, stop_other_threads,1259step_out_avoids_code_withoug_debug_info);12601261status = QueueThreadPlan(thread_plan_sp, abort_other_plans);1262return thread_plan_sp;1263}12641265// Call the QueueThreadPlanForStepOverRange method which takes an address1266// range.1267ThreadPlanSP Thread::QueueThreadPlanForStepOverRange(1268bool abort_other_plans, const LineEntry &line_entry,1269const SymbolContext &addr_context, lldb::RunMode stop_other_threads,1270Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {1271const bool include_inlined_functions = true;1272auto address_range =1273line_entry.GetSameLineContiguousAddressRange(include_inlined_functions);1274return QueueThreadPlanForStepOverRange(1275abort_other_plans, address_range, addr_context, stop_other_threads,1276status, step_out_avoids_code_withoug_debug_info);1277}12781279ThreadPlanSP Thread::QueueThreadPlanForStepInRange(1280bool abort_other_plans, const AddressRange &range,1281const SymbolContext &addr_context, const char *step_in_target,1282lldb::RunMode stop_other_threads, Status &status,1283LazyBool step_in_avoids_code_without_debug_info,1284LazyBool step_out_avoids_code_without_debug_info) {1285ThreadPlanSP thread_plan_sp(new ThreadPlanStepInRange(1286*this, range, addr_context, step_in_target, stop_other_threads,1287step_in_avoids_code_without_debug_info,1288step_out_avoids_code_without_debug_info));1289status = QueueThreadPlan(thread_plan_sp, abort_other_plans);1290return thread_plan_sp;1291}12921293// Call the QueueThreadPlanForStepInRange method which takes an address range.1294ThreadPlanSP Thread::QueueThreadPlanForStepInRange(1295bool abort_other_plans, const LineEntry &line_entry,1296const SymbolContext &addr_context, const char *step_in_target,1297lldb::RunMode stop_other_threads, Status &status,1298LazyBool step_in_avoids_code_without_debug_info,1299LazyBool step_out_avoids_code_without_debug_info) {1300const bool include_inlined_functions = false;1301return QueueThreadPlanForStepInRange(1302abort_other_plans,1303line_entry.GetSameLineContiguousAddressRange(include_inlined_functions),1304addr_context, step_in_target, stop_other_threads, status,1305step_in_avoids_code_without_debug_info,1306step_out_avoids_code_without_debug_info);1307}13081309ThreadPlanSP Thread::QueueThreadPlanForStepOut(1310bool abort_other_plans, SymbolContext *addr_context, bool first_insn,1311bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote,1312uint32_t frame_idx, Status &status,1313LazyBool step_out_avoids_code_without_debug_info) {1314ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(1315*this, addr_context, first_insn, stop_other_threads, report_stop_vote,1316report_run_vote, frame_idx, step_out_avoids_code_without_debug_info));13171318status = QueueThreadPlan(thread_plan_sp, abort_other_plans);1319return thread_plan_sp;1320}13211322ThreadPlanSP Thread::QueueThreadPlanForStepOutNoShouldStop(1323bool abort_other_plans, SymbolContext *addr_context, bool first_insn,1324bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote,1325uint32_t frame_idx, Status &status, bool continue_to_next_branch) {1326const bool calculate_return_value =1327false; // No need to calculate the return value here.1328ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(1329*this, addr_context, first_insn, stop_other_threads, report_stop_vote,1330report_run_vote, frame_idx, eLazyBoolNo, continue_to_next_branch,1331calculate_return_value));13321333ThreadPlanStepOut *new_plan =1334static_cast<ThreadPlanStepOut *>(thread_plan_sp.get());1335new_plan->ClearShouldStopHereCallbacks();13361337status = QueueThreadPlan(thread_plan_sp, abort_other_plans);1338return thread_plan_sp;1339}13401341ThreadPlanSP Thread::QueueThreadPlanForStepThrough(StackID &return_stack_id,1342bool abort_other_plans,1343bool stop_other_threads,1344Status &status) {1345ThreadPlanSP thread_plan_sp(1346new ThreadPlanStepThrough(*this, return_stack_id, stop_other_threads));1347if (!thread_plan_sp || !thread_plan_sp->ValidatePlan(nullptr))1348return ThreadPlanSP();13491350status = QueueThreadPlan(thread_plan_sp, abort_other_plans);1351return thread_plan_sp;1352}13531354ThreadPlanSP Thread::QueueThreadPlanForRunToAddress(bool abort_other_plans,1355Address &target_addr,1356bool stop_other_threads,1357Status &status) {1358ThreadPlanSP thread_plan_sp(1359new ThreadPlanRunToAddress(*this, target_addr, stop_other_threads));13601361status = QueueThreadPlan(thread_plan_sp, abort_other_plans);1362return thread_plan_sp;1363}13641365ThreadPlanSP Thread::QueueThreadPlanForStepUntil(1366bool abort_other_plans, lldb::addr_t *address_list, size_t num_addresses,1367bool stop_other_threads, uint32_t frame_idx, Status &status) {1368ThreadPlanSP thread_plan_sp(new ThreadPlanStepUntil(1369*this, address_list, num_addresses, stop_other_threads, frame_idx));13701371status = QueueThreadPlan(thread_plan_sp, abort_other_plans);1372return thread_plan_sp;1373}13741375lldb::ThreadPlanSP Thread::QueueThreadPlanForStepScripted(1376bool abort_other_plans, const char *class_name,1377StructuredData::ObjectSP extra_args_sp, bool stop_other_threads,1378Status &status) {13791380ThreadPlanSP thread_plan_sp(new ThreadPlanPython(1381*this, class_name, StructuredDataImpl(extra_args_sp)));1382thread_plan_sp->SetStopOthers(stop_other_threads);1383status = QueueThreadPlan(thread_plan_sp, abort_other_plans);1384return thread_plan_sp;1385}13861387uint32_t Thread::GetIndexID() const { return m_index_id; }13881389TargetSP Thread::CalculateTarget() {1390TargetSP target_sp;1391ProcessSP process_sp(GetProcess());1392if (process_sp)1393target_sp = process_sp->CalculateTarget();1394return target_sp;1395}13961397ProcessSP Thread::CalculateProcess() { return GetProcess(); }13981399ThreadSP Thread::CalculateThread() { return shared_from_this(); }14001401StackFrameSP Thread::CalculateStackFrame() { return StackFrameSP(); }14021403void Thread::CalculateExecutionContext(ExecutionContext &exe_ctx) {1404exe_ctx.SetContext(shared_from_this());1405}14061407StackFrameListSP Thread::GetStackFrameList() {1408std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);14091410if (!m_curr_frames_sp)1411m_curr_frames_sp =1412std::make_shared<StackFrameList>(*this, m_prev_frames_sp, true);14131414return m_curr_frames_sp;1415}14161417std::optional<addr_t> Thread::GetPreviousFrameZeroPC() {1418return m_prev_framezero_pc;1419}14201421void Thread::ClearStackFrames() {1422std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);14231424GetUnwinder().Clear();1425m_prev_framezero_pc.reset();1426if (RegisterContextSP reg_ctx_sp = GetRegisterContext())1427m_prev_framezero_pc = reg_ctx_sp->GetPC();14281429// Only store away the old "reference" StackFrameList if we got all its1430// frames:1431// FIXME: At some point we can try to splice in the frames we have fetched1432// into the new frame as we make it, but let's not try that now.1433if (m_curr_frames_sp && m_curr_frames_sp->GetAllFramesFetched())1434m_prev_frames_sp.swap(m_curr_frames_sp);1435m_curr_frames_sp.reset();14361437m_extended_info.reset();1438m_extended_info_fetched = false;1439}14401441lldb::StackFrameSP Thread::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) {1442return GetStackFrameList()->GetFrameWithConcreteFrameIndex(unwind_idx);1443}14441445Status Thread::ReturnFromFrameWithIndex(uint32_t frame_idx,1446lldb::ValueObjectSP return_value_sp,1447bool broadcast) {1448StackFrameSP frame_sp = GetStackFrameAtIndex(frame_idx);1449Status return_error;14501451if (!frame_sp) {1452return_error.SetErrorStringWithFormat(1453"Could not find frame with index %d in thread 0x%" PRIx64 ".",1454frame_idx, GetID());1455}14561457return ReturnFromFrame(frame_sp, return_value_sp, broadcast);1458}14591460Status Thread::ReturnFromFrame(lldb::StackFrameSP frame_sp,1461lldb::ValueObjectSP return_value_sp,1462bool broadcast) {1463Status return_error;14641465if (!frame_sp) {1466return_error.SetErrorString("Can't return to a null frame.");1467return return_error;1468}14691470Thread *thread = frame_sp->GetThread().get();1471uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;1472StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);1473if (!older_frame_sp) {1474return_error.SetErrorString("No older frame to return to.");1475return return_error;1476}14771478if (return_value_sp) {1479lldb::ABISP abi = thread->GetProcess()->GetABI();1480if (!abi) {1481return_error.SetErrorString("Could not find ABI to set return value.");1482return return_error;1483}1484SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);14851486// FIXME: ValueObject::Cast doesn't currently work correctly, at least not1487// for scalars.1488// Turn that back on when that works.1489if (/* DISABLES CODE */ (false) && sc.function != nullptr) {1490Type *function_type = sc.function->GetType();1491if (function_type) {1492CompilerType return_type =1493sc.function->GetCompilerType().GetFunctionReturnType();1494if (return_type) {1495StreamString s;1496return_type.DumpTypeDescription(&s);1497ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type);1498if (cast_value_sp) {1499cast_value_sp->SetFormat(eFormatHex);1500return_value_sp = cast_value_sp;1501}1502}1503}1504}15051506return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);1507if (!return_error.Success())1508return return_error;1509}15101511// Now write the return registers for the chosen frame: Note, we can't use1512// ReadAllRegisterValues->WriteAllRegisterValues, since the read & write cook1513// their data15141515StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);1516if (youngest_frame_sp) {1517lldb::RegisterContextSP reg_ctx_sp(youngest_frame_sp->GetRegisterContext());1518if (reg_ctx_sp) {1519bool copy_success = reg_ctx_sp->CopyFromRegisterContext(1520older_frame_sp->GetRegisterContext());1521if (copy_success) {1522thread->DiscardThreadPlans(true);1523thread->ClearStackFrames();1524if (broadcast && EventTypeHasListeners(eBroadcastBitStackChanged)) {1525auto data_sp = std::make_shared<ThreadEventData>(shared_from_this());1526BroadcastEvent(eBroadcastBitStackChanged, data_sp);1527}1528} else {1529return_error.SetErrorString("Could not reset register values.");1530}1531} else {1532return_error.SetErrorString("Frame has no register context.");1533}1534} else {1535return_error.SetErrorString("Returned past top frame.");1536}1537return return_error;1538}15391540static void DumpAddressList(Stream &s, const std::vector<Address> &list,1541ExecutionContextScope *exe_scope) {1542for (size_t n = 0; n < list.size(); n++) {1543s << "\t";1544list[n].Dump(&s, exe_scope, Address::DumpStyleResolvedDescription,1545Address::DumpStyleSectionNameOffset);1546s << "\n";1547}1548}15491550Status Thread::JumpToLine(const FileSpec &file, uint32_t line,1551bool can_leave_function, std::string *warnings) {1552ExecutionContext exe_ctx(GetStackFrameAtIndex(0));1553Target *target = exe_ctx.GetTargetPtr();1554TargetSP target_sp = exe_ctx.GetTargetSP();1555RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();1556StackFrame *frame = exe_ctx.GetFramePtr();1557const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction);15581559// Find candidate locations.1560std::vector<Address> candidates, within_function, outside_function;1561target->GetImages().FindAddressesForLine(target_sp, file, line, sc.function,1562within_function, outside_function);15631564// If possible, we try and stay within the current function. Within a1565// function, we accept multiple locations (optimized code may do this,1566// there's no solution here so we do the best we can). However if we're1567// trying to leave the function, we don't know how to pick the right1568// location, so if there's more than one then we bail.1569if (!within_function.empty())1570candidates = within_function;1571else if (outside_function.size() == 1 && can_leave_function)1572candidates = outside_function;15731574// Check if we got anything.1575if (candidates.empty()) {1576if (outside_function.empty()) {1577return Status("Cannot locate an address for %s:%i.",1578file.GetFilename().AsCString(), line);1579} else if (outside_function.size() == 1) {1580return Status("%s:%i is outside the current function.",1581file.GetFilename().AsCString(), line);1582} else {1583StreamString sstr;1584DumpAddressList(sstr, outside_function, target);1585return Status("%s:%i has multiple candidate locations:\n%s",1586file.GetFilename().AsCString(), line, sstr.GetData());1587}1588}15891590// Accept the first location, warn about any others.1591Address dest = candidates[0];1592if (warnings && candidates.size() > 1) {1593StreamString sstr;1594sstr.Printf("%s:%i appears multiple times in this function, selecting the "1595"first location:\n",1596file.GetFilename().AsCString(), line);1597DumpAddressList(sstr, candidates, target);1598*warnings = std::string(sstr.GetString());1599}16001601if (!reg_ctx->SetPC(dest))1602return Status("Cannot change PC to target address.");16031604return Status();1605}16061607bool Thread::DumpUsingFormat(Stream &strm, uint32_t frame_idx,1608const FormatEntity::Entry *format) {1609ExecutionContext exe_ctx(shared_from_this());1610Process *process = exe_ctx.GetProcessPtr();1611if (!process || !format)1612return false;16131614StackFrameSP frame_sp;1615SymbolContext frame_sc;1616if (frame_idx != LLDB_INVALID_FRAME_ID) {1617frame_sp = GetStackFrameAtIndex(frame_idx);1618if (frame_sp) {1619exe_ctx.SetFrameSP(frame_sp);1620frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);1621}1622}16231624return FormatEntity::Format(*format, strm, frame_sp ? &frame_sc : nullptr,1625&exe_ctx, nullptr, nullptr, false, false);1626}16271628void Thread::DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx,1629bool stop_format) {1630ExecutionContext exe_ctx(shared_from_this());16311632const FormatEntity::Entry *thread_format;1633if (stop_format)1634thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadStopFormat();1635else1636thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();16371638assert(thread_format);16391640DumpUsingFormat(strm, frame_idx, thread_format);1641}16421643void Thread::SettingsInitialize() {}16441645void Thread::SettingsTerminate() {}16461647lldb::addr_t Thread::GetThreadPointer() {1648if (m_reg_context_sp)1649return m_reg_context_sp->GetThreadPointer();1650return LLDB_INVALID_ADDRESS;1651}16521653addr_t Thread::GetThreadLocalData(const ModuleSP module,1654lldb::addr_t tls_file_addr) {1655// The default implementation is to ask the dynamic loader for it. This can1656// be overridden for specific platforms.1657DynamicLoader *loader = GetProcess()->GetDynamicLoader();1658if (loader)1659return loader->GetThreadLocalData(module, shared_from_this(),1660tls_file_addr);1661else1662return LLDB_INVALID_ADDRESS;1663}16641665bool Thread::SafeToCallFunctions() {1666Process *process = GetProcess().get();1667if (process) {1668DynamicLoader *loader = GetProcess()->GetDynamicLoader();1669if (loader && loader->IsFullyInitialized() == false)1670return false;16711672SystemRuntime *runtime = process->GetSystemRuntime();1673if (runtime) {1674return runtime->SafeToCallFunctionsOnThisThread(shared_from_this());1675}1676}1677return true;1678}16791680lldb::StackFrameSP1681Thread::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) {1682return GetStackFrameList()->GetStackFrameSPForStackFramePtr(stack_frame_ptr);1683}16841685std::string Thread::StopReasonAsString(lldb::StopReason reason) {1686switch (reason) {1687case eStopReasonInvalid:1688return "invalid";1689case eStopReasonNone:1690return "none";1691case eStopReasonTrace:1692return "trace";1693case eStopReasonBreakpoint:1694return "breakpoint";1695case eStopReasonWatchpoint:1696return "watchpoint";1697case eStopReasonSignal:1698return "signal";1699case eStopReasonException:1700return "exception";1701case eStopReasonExec:1702return "exec";1703case eStopReasonFork:1704return "fork";1705case eStopReasonVFork:1706return "vfork";1707case eStopReasonVForkDone:1708return "vfork done";1709case eStopReasonPlanComplete:1710return "plan complete";1711case eStopReasonThreadExiting:1712return "thread exiting";1713case eStopReasonInstrumentation:1714return "instrumentation break";1715case eStopReasonProcessorTrace:1716return "processor trace";1717}17181719return "StopReason = " + std::to_string(reason);1720}17211722std::string Thread::RunModeAsString(lldb::RunMode mode) {1723switch (mode) {1724case eOnlyThisThread:1725return "only this thread";1726case eAllThreads:1727return "all threads";1728case eOnlyDuringStepping:1729return "only during stepping";1730}17311732return "RunMode = " + std::to_string(mode);1733}17341735size_t Thread::GetStatus(Stream &strm, uint32_t start_frame,1736uint32_t num_frames, uint32_t num_frames_with_source,1737bool stop_format, bool only_stacks) {17381739if (!only_stacks) {1740ExecutionContext exe_ctx(shared_from_this());1741Target *target = exe_ctx.GetTargetPtr();1742Process *process = exe_ctx.GetProcessPtr();1743strm.Indent();1744bool is_selected = false;1745if (process) {1746if (process->GetThreadList().GetSelectedThread().get() == this)1747is_selected = true;1748}1749strm.Printf("%c ", is_selected ? '*' : ' ');1750if (target && target->GetDebugger().GetUseExternalEditor()) {1751StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);1752if (frame_sp) {1753SymbolContext frame_sc(1754frame_sp->GetSymbolContext(eSymbolContextLineEntry));1755if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.GetFile()) {1756if (llvm::Error e = Host::OpenFileInExternalEditor(1757target->GetDebugger().GetExternalEditor(),1758frame_sc.line_entry.GetFile(), frame_sc.line_entry.line)) {1759LLDB_LOG_ERROR(GetLog(LLDBLog::Host), std::move(e),1760"OpenFileInExternalEditor failed: {0}");1761}1762}1763}1764}17651766DumpUsingSettingsFormat(strm, start_frame, stop_format);1767}17681769size_t num_frames_shown = 0;1770if (num_frames > 0) {1771strm.IndentMore();17721773const bool show_frame_info = true;1774const bool show_frame_unique = only_stacks;1775const char *selected_frame_marker = nullptr;1776if (num_frames == 1 || only_stacks ||1777(GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID()))1778strm.IndentMore();1779else1780selected_frame_marker = "* ";17811782num_frames_shown = GetStackFrameList()->GetStatus(1783strm, start_frame, num_frames, show_frame_info, num_frames_with_source,1784show_frame_unique, selected_frame_marker);1785if (num_frames == 1)1786strm.IndentLess();1787strm.IndentLess();1788}1789return num_frames_shown;1790}17911792bool Thread::GetDescription(Stream &strm, lldb::DescriptionLevel level,1793bool print_json_thread, bool print_json_stopinfo) {1794const bool stop_format = false;1795DumpUsingSettingsFormat(strm, 0, stop_format);1796strm.Printf("\n");17971798StructuredData::ObjectSP thread_info = GetExtendedInfo();17991800if (print_json_thread || print_json_stopinfo) {1801if (thread_info && print_json_thread) {1802thread_info->Dump(strm);1803strm.Printf("\n");1804}18051806if (print_json_stopinfo && m_stop_info_sp) {1807StructuredData::ObjectSP stop_info = m_stop_info_sp->GetExtendedInfo();1808if (stop_info) {1809stop_info->Dump(strm);1810strm.Printf("\n");1811}1812}18131814return true;1815}18161817if (thread_info) {1818StructuredData::ObjectSP activity =1819thread_info->GetObjectForDotSeparatedPath("activity");1820StructuredData::ObjectSP breadcrumb =1821thread_info->GetObjectForDotSeparatedPath("breadcrumb");1822StructuredData::ObjectSP messages =1823thread_info->GetObjectForDotSeparatedPath("trace_messages");18241825bool printed_activity = false;1826if (activity && activity->GetType() == eStructuredDataTypeDictionary) {1827StructuredData::Dictionary *activity_dict = activity->GetAsDictionary();1828StructuredData::ObjectSP id = activity_dict->GetValueForKey("id");1829StructuredData::ObjectSP name = activity_dict->GetValueForKey("name");1830if (name && name->GetType() == eStructuredDataTypeString && id &&1831id->GetType() == eStructuredDataTypeInteger) {1832strm.Format(" Activity '{0}', {1:x}\n",1833name->GetAsString()->GetValue(),1834id->GetUnsignedIntegerValue());1835}1836printed_activity = true;1837}1838bool printed_breadcrumb = false;1839if (breadcrumb && breadcrumb->GetType() == eStructuredDataTypeDictionary) {1840if (printed_activity)1841strm.Printf("\n");1842StructuredData::Dictionary *breadcrumb_dict =1843breadcrumb->GetAsDictionary();1844StructuredData::ObjectSP breadcrumb_text =1845breadcrumb_dict->GetValueForKey("name");1846if (breadcrumb_text &&1847breadcrumb_text->GetType() == eStructuredDataTypeString) {1848strm.Format(" Current Breadcrumb: {0}\n",1849breadcrumb_text->GetAsString()->GetValue());1850}1851printed_breadcrumb = true;1852}1853if (messages && messages->GetType() == eStructuredDataTypeArray) {1854if (printed_breadcrumb)1855strm.Printf("\n");1856StructuredData::Array *messages_array = messages->GetAsArray();1857const size_t msg_count = messages_array->GetSize();1858if (msg_count > 0) {1859strm.Printf(" %zu trace messages:\n", msg_count);1860for (size_t i = 0; i < msg_count; i++) {1861StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i);1862if (message && message->GetType() == eStructuredDataTypeDictionary) {1863StructuredData::Dictionary *message_dict =1864message->GetAsDictionary();1865StructuredData::ObjectSP message_text =1866message_dict->GetValueForKey("message");1867if (message_text &&1868message_text->GetType() == eStructuredDataTypeString) {1869strm.Format(" {0}\n", message_text->GetAsString()->GetValue());1870}1871}1872}1873}1874}1875}18761877return true;1878}18791880size_t Thread::GetStackFrameStatus(Stream &strm, uint32_t first_frame,1881uint32_t num_frames, bool show_frame_info,1882uint32_t num_frames_with_source) {1883return GetStackFrameList()->GetStatus(1884strm, first_frame, num_frames, show_frame_info, num_frames_with_source);1885}18861887Unwind &Thread::GetUnwinder() {1888if (!m_unwinder_up)1889m_unwinder_up = std::make_unique<UnwindLLDB>(*this);1890return *m_unwinder_up;1891}18921893void Thread::Flush() {1894ClearStackFrames();1895m_reg_context_sp.reset();1896}18971898bool Thread::IsStillAtLastBreakpointHit() {1899// If we are currently stopped at a breakpoint, always return that stopinfo1900// and don't reset it. This allows threads to maintain their breakpoint1901// stopinfo, such as when thread-stepping in multithreaded programs.1902if (m_stop_info_sp) {1903StopReason stop_reason = m_stop_info_sp->GetStopReason();1904if (stop_reason == lldb::eStopReasonBreakpoint) {1905uint64_t value = m_stop_info_sp->GetValue();1906lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext());1907if (reg_ctx_sp) {1908lldb::addr_t pc = reg_ctx_sp->GetPC();1909BreakpointSiteSP bp_site_sp =1910GetProcess()->GetBreakpointSiteList().FindByAddress(pc);1911if (bp_site_sp && static_cast<break_id_t>(value) == bp_site_sp->GetID())1912return true;1913}1914}1915}1916return false;1917}19181919Status Thread::StepIn(bool source_step,1920LazyBool step_in_avoids_code_without_debug_info,1921LazyBool step_out_avoids_code_without_debug_info)19221923{1924Status error;1925Process *process = GetProcess().get();1926if (StateIsStoppedState(process->GetState(), true)) {1927StackFrameSP frame_sp = GetStackFrameAtIndex(0);1928ThreadPlanSP new_plan_sp;1929const lldb::RunMode run_mode = eOnlyThisThread;1930const bool abort_other_plans = false;19311932if (source_step && frame_sp && frame_sp->HasDebugInformation()) {1933SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));1934new_plan_sp = QueueThreadPlanForStepInRange(1935abort_other_plans, sc.line_entry, sc, nullptr, run_mode, error,1936step_in_avoids_code_without_debug_info,1937step_out_avoids_code_without_debug_info);1938} else {1939new_plan_sp = QueueThreadPlanForStepSingleInstruction(1940false, abort_other_plans, run_mode, error);1941}19421943new_plan_sp->SetIsControllingPlan(true);1944new_plan_sp->SetOkayToDiscard(false);19451946// Why do we need to set the current thread by ID here???1947process->GetThreadList().SetSelectedThreadByID(GetID());1948error = process->Resume();1949} else {1950error.SetErrorString("process not stopped");1951}1952return error;1953}19541955Status Thread::StepOver(bool source_step,1956LazyBool step_out_avoids_code_without_debug_info) {1957Status error;1958Process *process = GetProcess().get();1959if (StateIsStoppedState(process->GetState(), true)) {1960StackFrameSP frame_sp = GetStackFrameAtIndex(0);1961ThreadPlanSP new_plan_sp;19621963const lldb::RunMode run_mode = eOnlyThisThread;1964const bool abort_other_plans = false;19651966if (source_step && frame_sp && frame_sp->HasDebugInformation()) {1967SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));1968new_plan_sp = QueueThreadPlanForStepOverRange(1969abort_other_plans, sc.line_entry, sc, run_mode, error,1970step_out_avoids_code_without_debug_info);1971} else {1972new_plan_sp = QueueThreadPlanForStepSingleInstruction(1973true, abort_other_plans, run_mode, error);1974}19751976new_plan_sp->SetIsControllingPlan(true);1977new_plan_sp->SetOkayToDiscard(false);19781979// Why do we need to set the current thread by ID here???1980process->GetThreadList().SetSelectedThreadByID(GetID());1981error = process->Resume();1982} else {1983error.SetErrorString("process not stopped");1984}1985return error;1986}19871988Status Thread::StepOut(uint32_t frame_idx) {1989Status error;1990Process *process = GetProcess().get();1991if (StateIsStoppedState(process->GetState(), true)) {1992const bool first_instruction = false;1993const bool stop_other_threads = false;1994const bool abort_other_plans = false;19951996ThreadPlanSP new_plan_sp(QueueThreadPlanForStepOut(1997abort_other_plans, nullptr, first_instruction, stop_other_threads,1998eVoteYes, eVoteNoOpinion, frame_idx, error));19992000new_plan_sp->SetIsControllingPlan(true);2001new_plan_sp->SetOkayToDiscard(false);20022003// Why do we need to set the current thread by ID here???2004process->GetThreadList().SetSelectedThreadByID(GetID());2005error = process->Resume();2006} else {2007error.SetErrorString("process not stopped");2008}2009return error;2010}20112012ValueObjectSP Thread::GetCurrentException() {2013if (auto frame_sp = GetStackFrameAtIndex(0))2014if (auto recognized_frame = frame_sp->GetRecognizedFrame())2015if (auto e = recognized_frame->GetExceptionObject())2016return e;20172018// NOTE: Even though this behavior is generalized, only ObjC is actually2019// supported at the moment.2020for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {2021if (auto e = runtime->GetExceptionObjectForThread(shared_from_this()))2022return e;2023}20242025return ValueObjectSP();2026}20272028ThreadSP Thread::GetCurrentExceptionBacktrace() {2029ValueObjectSP exception = GetCurrentException();2030if (!exception)2031return ThreadSP();20322033// NOTE: Even though this behavior is generalized, only ObjC is actually2034// supported at the moment.2035for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {2036if (auto bt = runtime->GetBacktraceThreadFromException(exception))2037return bt;2038}20392040return ThreadSP();2041}20422043lldb::ValueObjectSP Thread::GetSiginfoValue() {2044ProcessSP process_sp = GetProcess();2045assert(process_sp);2046Target &target = process_sp->GetTarget();2047PlatformSP platform_sp = target.GetPlatform();2048assert(platform_sp);2049ArchSpec arch = target.GetArchitecture();20502051CompilerType type = platform_sp->GetSiginfoType(arch.GetTriple());2052if (!type.IsValid())2053return ValueObjectConstResult::Create(&target, Status("no siginfo_t for the platform"));20542055std::optional<uint64_t> type_size = type.GetByteSize(nullptr);2056assert(type_size);2057llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> data =2058GetSiginfo(*type_size);2059if (!data)2060return ValueObjectConstResult::Create(&target, Status(data.takeError()));20612062DataExtractor data_extractor{data.get()->getBufferStart(), data.get()->getBufferSize(),2063process_sp->GetByteOrder(), arch.GetAddressByteSize()};2064return ValueObjectConstResult::Create(&target, type, ConstString("__lldb_siginfo"), data_extractor);2065}206620672068