Path: blob/main/contrib/llvm-project/lldb/source/Target/ThreadPlanCallFunction.cpp
39587 views
//===-- ThreadPlanCallFunction.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/ThreadPlanCallFunction.h"9#include "lldb/Breakpoint/Breakpoint.h"10#include "lldb/Breakpoint/BreakpointLocation.h"11#include "lldb/Core/Address.h"12#include "lldb/Core/DumpRegisterValue.h"13#include "lldb/Core/Module.h"14#include "lldb/Symbol/ObjectFile.h"15#include "lldb/Target/ABI.h"16#include "lldb/Target/LanguageRuntime.h"17#include "lldb/Target/Process.h"18#include "lldb/Target/RegisterContext.h"19#include "lldb/Target/StopInfo.h"20#include "lldb/Target/Target.h"21#include "lldb/Target/Thread.h"22#include "lldb/Target/ThreadPlanRunToAddress.h"23#include "lldb/Utility/LLDBLog.h"24#include "lldb/Utility/Log.h"25#include "lldb/Utility/Stream.h"2627#include <memory>2829using namespace lldb;30using namespace lldb_private;3132// ThreadPlanCallFunction: Plan to call a single function33bool ThreadPlanCallFunction::ConstructorSetup(34Thread &thread, ABI *&abi, lldb::addr_t &start_load_addr,35lldb::addr_t &function_load_addr) {36SetIsControllingPlan(true);37SetOkayToDiscard(false);38SetPrivate(true);3940ProcessSP process_sp(thread.GetProcess());41if (!process_sp)42return false;4344abi = process_sp->GetABI().get();4546if (!abi)47return false;4849Log *log = GetLog(LLDBLog::Step);5051SetBreakpoints();5253m_function_sp = thread.GetRegisterContext()->GetSP() - abi->GetRedZoneSize();54// If we can't read memory at the point of the process where we are planning55// to put our function, we're not going to get any further...56Status error;57process_sp->ReadUnsignedIntegerFromMemory(m_function_sp, 4, 0, error);58if (!error.Success()) {59m_constructor_errors.Printf(60"Trying to put the stack in unreadable memory at: 0x%" PRIx64 ".",61m_function_sp);62LLDB_LOGF(log, "ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),63m_constructor_errors.GetData());64return false;65}6667llvm::Expected<Address> start_address = GetTarget().GetEntryPointAddress();68if (!start_address) {69m_constructor_errors.Printf(70"%s", llvm::toString(start_address.takeError()).c_str());71LLDB_LOGF(log, "ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),72m_constructor_errors.GetData());73return false;74}7576m_start_addr = *start_address;77start_load_addr = m_start_addr.GetLoadAddress(&GetTarget());7879// Checkpoint the thread state so we can restore it later.80if (log && log->GetVerbose())81ReportRegisterState("About to checkpoint thread before function call. "82"Original register state was:");8384if (!thread.CheckpointThreadState(m_stored_thread_state)) {85m_constructor_errors.Printf("Setting up ThreadPlanCallFunction, failed to "86"checkpoint thread state.");87LLDB_LOGF(log, "ThreadPlanCallFunction(%p): %s.", static_cast<void *>(this),88m_constructor_errors.GetData());89return false;90}91function_load_addr = m_function_addr.GetLoadAddress(&GetTarget());9293return true;94}9596ThreadPlanCallFunction::ThreadPlanCallFunction(97Thread &thread, const Address &function, const CompilerType &return_type,98llvm::ArrayRef<addr_t> args, const EvaluateExpressionOptions &options)99: ThreadPlan(ThreadPlan::eKindCallFunction, "Call function plan", thread,100eVoteNoOpinion, eVoteNoOpinion),101m_valid(false), m_stop_other_threads(options.GetStopOthers()),102m_unwind_on_error(options.DoesUnwindOnError()),103m_ignore_breakpoints(options.DoesIgnoreBreakpoints()),104m_debug_execution(options.GetDebug()),105m_trap_exceptions(options.GetTrapExceptions()), m_function_addr(function),106m_start_addr(), m_function_sp(0), m_subplan_sp(),107m_cxx_language_runtime(nullptr), m_objc_language_runtime(nullptr),108m_stored_thread_state(), m_real_stop_info_sp(), m_constructor_errors(),109m_return_valobj_sp(), m_takedown_done(false),110m_should_clear_objc_exception_bp(false),111m_should_clear_cxx_exception_bp(false),112m_stop_address(LLDB_INVALID_ADDRESS), m_return_type(return_type) {113lldb::addr_t start_load_addr = LLDB_INVALID_ADDRESS;114lldb::addr_t function_load_addr = LLDB_INVALID_ADDRESS;115ABI *abi = nullptr;116117if (!ConstructorSetup(thread, abi, start_load_addr, function_load_addr))118return;119120if (!abi->PrepareTrivialCall(thread, m_function_sp, function_load_addr,121start_load_addr, args))122return;123124ReportRegisterState("Function call was set up. Register state was:");125126m_valid = true;127}128129ThreadPlanCallFunction::ThreadPlanCallFunction(130Thread &thread, const Address &function,131const EvaluateExpressionOptions &options)132: ThreadPlan(ThreadPlan::eKindCallFunction, "Call function plan", thread,133eVoteNoOpinion, eVoteNoOpinion),134m_valid(false), m_stop_other_threads(options.GetStopOthers()),135m_unwind_on_error(options.DoesUnwindOnError()),136m_ignore_breakpoints(options.DoesIgnoreBreakpoints()),137m_debug_execution(options.GetDebug()),138m_trap_exceptions(options.GetTrapExceptions()), m_function_addr(function),139m_start_addr(), m_function_sp(0), m_subplan_sp(),140m_cxx_language_runtime(nullptr), m_objc_language_runtime(nullptr),141m_stored_thread_state(), m_real_stop_info_sp(), m_constructor_errors(),142m_return_valobj_sp(), m_takedown_done(false),143m_should_clear_objc_exception_bp(false),144m_should_clear_cxx_exception_bp(false),145m_stop_address(LLDB_INVALID_ADDRESS), m_return_type(CompilerType()) {}146147ThreadPlanCallFunction::~ThreadPlanCallFunction() {148DoTakedown(PlanSucceeded());149}150151void ThreadPlanCallFunction::ReportRegisterState(const char *message) {152Log *log = GetLog(LLDBLog::Step);153if (log && log->GetVerbose()) {154StreamString strm;155RegisterContext *reg_ctx = GetThread().GetRegisterContext().get();156157log->PutCString(message);158159RegisterValue reg_value;160161for (uint32_t reg_idx = 0, num_registers = reg_ctx->GetRegisterCount();162reg_idx < num_registers; ++reg_idx) {163const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg_idx);164if (reg_ctx->ReadRegister(reg_info, reg_value)) {165DumpRegisterValue(reg_value, strm, *reg_info, true, false,166eFormatDefault);167strm.EOL();168}169}170log->PutString(strm.GetString());171}172}173174void ThreadPlanCallFunction::DoTakedown(bool success) {175Log *log = GetLog(LLDBLog::Step);176177if (!m_valid) {178// Don't call DoTakedown if we were never valid to begin with.179LLDB_LOGF(log,180"ThreadPlanCallFunction(%p): Log called on "181"ThreadPlanCallFunction that was never valid.",182static_cast<void *>(this));183return;184}185186if (!m_takedown_done) {187Thread &thread = GetThread();188if (success) {189SetReturnValue();190}191LLDB_LOGF(log,192"ThreadPlanCallFunction(%p): DoTakedown called for thread "193"0x%4.4" PRIx64 ", m_valid: %d complete: %d.\n",194static_cast<void *>(this), m_tid, m_valid, IsPlanComplete());195m_takedown_done = true;196m_stop_address =197thread.GetStackFrameAtIndex(0)->GetRegisterContext()->GetPC();198m_real_stop_info_sp = GetPrivateStopInfo();199if (!thread.RestoreRegisterStateFromCheckpoint(m_stored_thread_state)) {200LLDB_LOGF(log,201"ThreadPlanCallFunction(%p): DoTakedown failed to restore "202"register state",203static_cast<void *>(this));204}205SetPlanComplete(success);206ClearBreakpoints();207if (log && log->GetVerbose())208ReportRegisterState("Restoring thread state after function call. "209"Restored register state:");210} else {211LLDB_LOGF(log,212"ThreadPlanCallFunction(%p): DoTakedown called as no-op for "213"thread 0x%4.4" PRIx64 ", m_valid: %d complete: %d.\n",214static_cast<void *>(this), m_tid, m_valid, IsPlanComplete());215}216}217218void ThreadPlanCallFunction::DidPop() { DoTakedown(PlanSucceeded()); }219220void ThreadPlanCallFunction::GetDescription(Stream *s, DescriptionLevel level) {221if (level == eDescriptionLevelBrief) {222s->Printf("Function call thread plan");223} else {224s->Printf("Thread plan to call 0x%" PRIx64,225m_function_addr.GetLoadAddress(&GetTarget()));226}227}228229bool ThreadPlanCallFunction::ValidatePlan(Stream *error) {230if (!m_valid) {231if (error) {232if (m_constructor_errors.GetSize() > 0)233error->PutCString(m_constructor_errors.GetString());234else235error->PutCString("Unknown error");236}237return false;238}239240return true;241}242243Vote ThreadPlanCallFunction::ShouldReportStop(Event *event_ptr) {244if (m_takedown_done || IsPlanComplete())245return eVoteYes;246else247return ThreadPlan::ShouldReportStop(event_ptr);248}249250bool ThreadPlanCallFunction::DoPlanExplainsStop(Event *event_ptr) {251Log *log(GetLog(LLDBLog::Step | LLDBLog::Process));252m_real_stop_info_sp = GetPrivateStopInfo();253254// If our subplan knows why we stopped, even if it's done (which would255// forward the question to us) we answer yes.256if (m_subplan_sp && m_subplan_sp->PlanExplainsStop(event_ptr)) {257SetPlanComplete();258return true;259}260261// Check if the breakpoint is one of ours.262263StopReason stop_reason;264if (!m_real_stop_info_sp)265stop_reason = eStopReasonNone;266else267stop_reason = m_real_stop_info_sp->GetStopReason();268LLDB_LOG(log,269"ThreadPlanCallFunction::PlanExplainsStop: Got stop reason - {0}.",270Thread::StopReasonAsString(stop_reason));271272if (stop_reason == eStopReasonBreakpoint && BreakpointsExplainStop())273return true;274275// One more quirk here. If this event was from Halt interrupting the target,276// then we should not consider ourselves complete. Return true to277// acknowledge the stop.278if (Process::ProcessEventData::GetInterruptedFromEvent(event_ptr)) {279LLDB_LOGF(log, "ThreadPlanCallFunction::PlanExplainsStop: The event is an "280"Interrupt, returning true.");281return true;282}283// We control breakpoints separately from other "stop reasons." So first,284// check the case where we stopped for an internal breakpoint, in that case,285// continue on. If it is not an internal breakpoint, consult286// m_ignore_breakpoints.287288if (stop_reason == eStopReasonBreakpoint) {289uint64_t break_site_id = m_real_stop_info_sp->GetValue();290BreakpointSiteSP bp_site_sp;291bp_site_sp = m_process.GetBreakpointSiteList().FindByID(break_site_id);292if (bp_site_sp) {293uint32_t num_owners = bp_site_sp->GetNumberOfConstituents();294bool is_internal = true;295for (uint32_t i = 0; i < num_owners; i++) {296Breakpoint &bp = bp_site_sp->GetConstituentAtIndex(i)->GetBreakpoint();297LLDB_LOGF(log,298"ThreadPlanCallFunction::PlanExplainsStop: hit "299"breakpoint %d while calling function",300bp.GetID());301302if (!bp.IsInternal()) {303is_internal = false;304break;305}306}307if (is_internal) {308LLDB_LOGF(log, "ThreadPlanCallFunction::PlanExplainsStop hit an "309"internal breakpoint, not stopping.");310return false;311}312}313314if (m_ignore_breakpoints) {315LLDB_LOGF(log,316"ThreadPlanCallFunction::PlanExplainsStop: we are ignoring "317"breakpoints, overriding breakpoint stop info ShouldStop, "318"returning true");319m_real_stop_info_sp->OverrideShouldStop(false);320return true;321} else {322LLDB_LOGF(log, "ThreadPlanCallFunction::PlanExplainsStop: we are not "323"ignoring breakpoints, overriding breakpoint stop info "324"ShouldStop, returning true");325m_real_stop_info_sp->OverrideShouldStop(true);326return false;327}328} else if (!m_unwind_on_error) {329// If we don't want to discard this plan, than any stop we don't understand330// should be propagated up the stack.331return false;332} else {333// If the subplan is running, any crashes are attributable to us. If we334// want to discard the plan, then we say we explain the stop but if we are335// going to be discarded, let whoever is above us explain the stop. But336// don't discard the plan if the stop would restart itself (for instance if337// it is a signal that is set not to stop. Check that here first. We just338// say we explain the stop but aren't done and everything will continue on339// from there.340341if (m_real_stop_info_sp &&342m_real_stop_info_sp->ShouldStopSynchronous(event_ptr)) {343SetPlanComplete(false);344return m_subplan_sp ? m_unwind_on_error : false;345} else346return true;347}348}349350bool ThreadPlanCallFunction::ShouldStop(Event *event_ptr) {351// We do some computation in DoPlanExplainsStop that may or may not set the352// plan as complete. We need to do that here to make sure our state is353// correct.354DoPlanExplainsStop(event_ptr);355356if (IsPlanComplete()) {357ReportRegisterState("Function completed. Register state was:");358return true;359} else {360return false;361}362}363364bool ThreadPlanCallFunction::StopOthers() { return m_stop_other_threads; }365366StateType ThreadPlanCallFunction::GetPlanRunState() { return eStateRunning; }367368void ThreadPlanCallFunction::DidPush() {369//#define SINGLE_STEP_EXPRESSIONS370371// Now set the thread state to "no reason" so we don't run with whatever372// signal was outstanding... Wait till the plan is pushed so we aren't373// changing the stop info till we're about to run.374375GetThread().SetStopInfoToNothing();376377#ifndef SINGLE_STEP_EXPRESSIONS378Thread &thread = GetThread();379m_subplan_sp = std::make_shared<ThreadPlanRunToAddress>(thread, m_start_addr,380m_stop_other_threads);381382thread.QueueThreadPlan(m_subplan_sp, false);383m_subplan_sp->SetPrivate(true);384#endif385}386387bool ThreadPlanCallFunction::WillStop() { return true; }388389bool ThreadPlanCallFunction::MischiefManaged() {390Log *log = GetLog(LLDBLog::Step);391392if (IsPlanComplete()) {393LLDB_LOGF(log, "ThreadPlanCallFunction(%p): Completed call function plan.",394static_cast<void *>(this));395396ThreadPlan::MischiefManaged();397return true;398} else {399return false;400}401}402403void ThreadPlanCallFunction::SetBreakpoints() {404if (m_trap_exceptions) {405m_cxx_language_runtime =406m_process.GetLanguageRuntime(eLanguageTypeC_plus_plus);407m_objc_language_runtime = m_process.GetLanguageRuntime(eLanguageTypeObjC);408409if (m_cxx_language_runtime) {410m_should_clear_cxx_exception_bp =411!m_cxx_language_runtime->ExceptionBreakpointsAreSet();412m_cxx_language_runtime->SetExceptionBreakpoints();413}414if (m_objc_language_runtime) {415m_should_clear_objc_exception_bp =416!m_objc_language_runtime->ExceptionBreakpointsAreSet();417m_objc_language_runtime->SetExceptionBreakpoints();418}419}420}421422void ThreadPlanCallFunction::ClearBreakpoints() {423if (m_trap_exceptions) {424if (m_cxx_language_runtime && m_should_clear_cxx_exception_bp)425m_cxx_language_runtime->ClearExceptionBreakpoints();426if (m_objc_language_runtime && m_should_clear_objc_exception_bp)427m_objc_language_runtime->ClearExceptionBreakpoints();428}429}430431bool ThreadPlanCallFunction::BreakpointsExplainStop() {432StopInfoSP stop_info_sp = GetPrivateStopInfo();433434if (m_trap_exceptions) {435if ((m_cxx_language_runtime &&436m_cxx_language_runtime->ExceptionBreakpointsExplainStop(437stop_info_sp)) ||438(m_objc_language_runtime &&439m_objc_language_runtime->ExceptionBreakpointsExplainStop(440stop_info_sp))) {441Log *log = GetLog(LLDBLog::Step);442LLDB_LOGF(log, "ThreadPlanCallFunction::BreakpointsExplainStop - Hit an "443"exception breakpoint, setting plan complete.");444445SetPlanComplete(false);446447// If the user has set the ObjC language breakpoint, it would normally448// get priority over our internal catcher breakpoint, but in this case we449// can't let that happen, so force the ShouldStop here.450stop_info_sp->OverrideShouldStop(true);451return true;452}453}454455return false;456}457458void ThreadPlanCallFunction::SetStopOthers(bool new_value) {459m_subplan_sp->SetStopOthers(new_value);460}461462void ThreadPlanCallFunction::RestoreThreadState() {463GetThread().RestoreThreadStateFromCheckpoint(m_stored_thread_state);464}465466void ThreadPlanCallFunction::SetReturnValue() {467const ABI *abi = m_process.GetABI().get();468if (abi && m_return_type.IsValid()) {469const bool persistent = false;470m_return_valobj_sp =471abi->GetReturnValueObject(GetThread(), m_return_type, persistent);472}473}474475476