Path: blob/main/contrib/llvm-project/lldb/source/Expression/FunctionCaller.cpp
39587 views
//===-- FunctionCaller.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//===----------------------------------------------------------------------===//789#include "lldb/Expression/FunctionCaller.h"10#include "lldb/Core/Module.h"11#include "lldb/Core/ValueObject.h"12#include "lldb/Core/ValueObjectList.h"13#include "lldb/Expression/DiagnosticManager.h"14#include "lldb/Expression/IRExecutionUnit.h"15#include "lldb/Interpreter/CommandReturnObject.h"16#include "lldb/Symbol/Function.h"17#include "lldb/Symbol/Type.h"18#include "lldb/Target/ExecutionContext.h"19#include "lldb/Target/Process.h"20#include "lldb/Target/RegisterContext.h"21#include "lldb/Target/Target.h"22#include "lldb/Target/Thread.h"23#include "lldb/Target/ThreadPlan.h"24#include "lldb/Target/ThreadPlanCallFunction.h"25#include "lldb/Utility/DataExtractor.h"26#include "lldb/Utility/LLDBLog.h"27#include "lldb/Utility/Log.h"28#include "lldb/Utility/State.h"2930using namespace lldb_private;3132char FunctionCaller::ID;3334// FunctionCaller constructor35FunctionCaller::FunctionCaller(ExecutionContextScope &exe_scope,36const CompilerType &return_type,37const Address &functionAddress,38const ValueList &arg_value_list,39const char *name)40: Expression(exe_scope), m_execution_unit_sp(), m_parser(),41m_jit_module_wp(), m_name(name ? name : "<unknown>"),42m_function_ptr(nullptr), m_function_addr(functionAddress),43m_function_return_type(return_type),44m_wrapper_function_name("__lldb_caller_function"),45m_wrapper_struct_name("__lldb_caller_struct"), m_wrapper_args_addrs(),46m_struct_valid(false), m_struct_size(0), m_return_size(0),47m_return_offset(0), m_arg_values(arg_value_list), m_compiled(false),48m_JITted(false) {49m_jit_process_wp = lldb::ProcessWP(exe_scope.CalculateProcess());50// Can't make a FunctionCaller without a process.51assert(m_jit_process_wp.lock());52}5354// Destructor55FunctionCaller::~FunctionCaller() {56lldb::ProcessSP process_sp(m_jit_process_wp.lock());57if (process_sp) {58lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock());59if (jit_module_sp)60process_sp->GetTarget().GetImages().Remove(jit_module_sp);61}62}6364bool FunctionCaller::WriteFunctionWrapper(65ExecutionContext &exe_ctx, DiagnosticManager &diagnostic_manager) {66Process *process = exe_ctx.GetProcessPtr();6768if (!process) {69diagnostic_manager.Printf(lldb::eSeverityError, "no process.");70return false;71}7273lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());7475if (process != jit_process_sp.get()) {76diagnostic_manager.Printf(lldb::eSeverityError,77"process does not match the stored process.");78return false;79}8081if (process->GetState() != lldb::eStateStopped) {82diagnostic_manager.Printf(lldb::eSeverityError, "process is not stopped");83return false;84}8586if (!m_compiled) {87diagnostic_manager.Printf(lldb::eSeverityError, "function not compiled");88return false;89}9091if (m_JITted)92return true;9394bool can_interpret = false; // should stay that way9596Status jit_error(m_parser->PrepareForExecution(97m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,98can_interpret, eExecutionPolicyAlways));99100if (!jit_error.Success()) {101diagnostic_manager.Printf(lldb::eSeverityError,102"Error in PrepareForExecution: %s.",103jit_error.AsCString());104return false;105}106107if (m_parser->GetGenerateDebugInfo()) {108lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());109110if (jit_module_sp) {111ConstString const_func_name(FunctionName());112FileSpec jit_file;113jit_file.SetFilename(const_func_name);114jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());115m_jit_module_wp = jit_module_sp;116process->GetTarget().GetImages().Append(jit_module_sp,117true /* notify */);118}119}120if (process && m_jit_start_addr)121m_jit_process_wp = process->shared_from_this();122123m_JITted = true;124125return true;126}127128bool FunctionCaller::WriteFunctionArguments(129ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,130DiagnosticManager &diagnostic_manager) {131return WriteFunctionArguments(exe_ctx, args_addr_ref, m_arg_values,132diagnostic_manager);133}134135// FIXME: Assure that the ValueList we were passed in is consistent with the one136// that defined this function.137138bool FunctionCaller::WriteFunctionArguments(139ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref,140ValueList &arg_values, DiagnosticManager &diagnostic_manager) {141// All the information to reconstruct the struct is provided by the142// StructExtractor.143if (!m_struct_valid) {144diagnostic_manager.PutString(lldb::eSeverityError,145"Argument information was not correctly "146"parsed, so the function cannot be called.");147return false;148}149150Status error;151lldb::ExpressionResults return_value = lldb::eExpressionSetupError;152153Process *process = exe_ctx.GetProcessPtr();154155if (process == nullptr)156return return_value;157158lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());159160if (process != jit_process_sp.get())161return false;162163if (args_addr_ref == LLDB_INVALID_ADDRESS) {164args_addr_ref = process->AllocateMemory(165m_struct_size, lldb::ePermissionsReadable | lldb::ePermissionsWritable,166error);167if (args_addr_ref == LLDB_INVALID_ADDRESS)168return false;169m_wrapper_args_addrs.push_back(args_addr_ref);170} else {171// Make sure this is an address that we've already handed out.172if (find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),173args_addr_ref) == m_wrapper_args_addrs.end()) {174return false;175}176}177178// TODO: verify fun_addr needs to be a callable address179Scalar fun_addr(180m_function_addr.GetCallableLoadAddress(exe_ctx.GetTargetPtr()));181uint64_t first_offset = m_member_offsets[0];182process->WriteScalarToMemory(args_addr_ref + first_offset, fun_addr,183process->GetAddressByteSize(), error);184185// FIXME: We will need to extend this for Variadic functions.186187Status value_error;188189size_t num_args = arg_values.GetSize();190if (num_args != m_arg_values.GetSize()) {191diagnostic_manager.Printf(192lldb::eSeverityError,193"Wrong number of arguments - was: %" PRIu64 " should be: %" PRIu64 "",194(uint64_t)num_args, (uint64_t)m_arg_values.GetSize());195return false;196}197198for (size_t i = 0; i < num_args; i++) {199// FIXME: We should sanity check sizes.200201uint64_t offset = m_member_offsets[i + 1]; // Clang sizes are in bytes.202Value *arg_value = arg_values.GetValueAtIndex(i);203204// FIXME: For now just do scalars:205206// Special case: if it's a pointer, don't do anything (the ABI supports207// passing cstrings)208209if (arg_value->GetValueType() == Value::ValueType::HostAddress &&210arg_value->GetContextType() == Value::ContextType::Invalid &&211arg_value->GetCompilerType().IsPointerType())212continue;213214const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx);215216if (!process->WriteScalarToMemory(args_addr_ref + offset, arg_scalar,217arg_scalar.GetByteSize(), error))218return false;219}220221return true;222}223224bool FunctionCaller::InsertFunction(ExecutionContext &exe_ctx,225lldb::addr_t &args_addr_ref,226DiagnosticManager &diagnostic_manager) {227// Since we might need to call allocate memory and maybe call code to make228// the caller, we need to be stopped.229Process *process = exe_ctx.GetProcessPtr();230if (!process) {231diagnostic_manager.PutString(lldb::eSeverityError, "no process");232return false;233}234if (process->GetState() != lldb::eStateStopped) {235diagnostic_manager.PutString(lldb::eSeverityError, "process running");236return false;237}238if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)239return false;240if (!WriteFunctionWrapper(exe_ctx, diagnostic_manager))241return false;242if (!WriteFunctionArguments(exe_ctx, args_addr_ref, diagnostic_manager))243return false;244245Log *log = GetLog(LLDBLog::Step);246LLDB_LOGF(log, "Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n",247m_jit_start_addr, args_addr_ref);248249return true;250}251252lldb::ThreadPlanSP FunctionCaller::GetThreadPlanToCallFunction(253ExecutionContext &exe_ctx, lldb::addr_t args_addr,254const EvaluateExpressionOptions &options,255DiagnosticManager &diagnostic_manager) {256Log *log(GetLog(LLDBLog::Expressions | LLDBLog::Step));257258LLDB_LOGF(log,259"-- [FunctionCaller::GetThreadPlanToCallFunction] Creating "260"thread plan to call function \"%s\" --",261m_name.c_str());262263// FIXME: Use the errors Stream for better error reporting.264Thread *thread = exe_ctx.GetThreadPtr();265if (thread == nullptr) {266diagnostic_manager.PutString(267lldb::eSeverityError, "Can't call a function without a valid thread.");268return nullptr;269}270271// Okay, now run the function:272273Address wrapper_address(m_jit_start_addr);274275lldb::addr_t args = {args_addr};276277lldb::ThreadPlanSP new_plan_sp(new ThreadPlanCallFunction(278*thread, wrapper_address, CompilerType(), args, options));279new_plan_sp->SetIsControllingPlan(true);280new_plan_sp->SetOkayToDiscard(false);281return new_plan_sp;282}283284bool FunctionCaller::FetchFunctionResults(ExecutionContext &exe_ctx,285lldb::addr_t args_addr,286Value &ret_value) {287// Read the return value - it is the last field in the struct:288// FIXME: How does clang tell us there's no return value? We need to handle289// that case.290// FIXME: Create our ThreadPlanCallFunction with the return CompilerType, and291// then use GetReturnValueObject292// to fetch the value. That way we can fetch any values we need.293294Log *log(GetLog(LLDBLog::Expressions | LLDBLog::Step));295296LLDB_LOGF(log,297"-- [FunctionCaller::FetchFunctionResults] Fetching function "298"results for \"%s\"--",299m_name.c_str());300301Process *process = exe_ctx.GetProcessPtr();302303if (process == nullptr)304return false;305306lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());307308if (process != jit_process_sp.get())309return false;310311Status error;312ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory(313args_addr + m_return_offset, m_return_size, 0, error);314315if (error.Fail())316return false;317318ret_value.SetCompilerType(m_function_return_type);319ret_value.SetValueType(Value::ValueType::Scalar);320return true;321}322323void FunctionCaller::DeallocateFunctionResults(ExecutionContext &exe_ctx,324lldb::addr_t args_addr) {325std::list<lldb::addr_t>::iterator pos;326pos = std::find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(),327args_addr);328if (pos != m_wrapper_args_addrs.end())329m_wrapper_args_addrs.erase(pos);330331exe_ctx.GetProcessRef().DeallocateMemory(args_addr);332}333334lldb::ExpressionResults FunctionCaller::ExecuteFunction(335ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr,336const EvaluateExpressionOptions &options,337DiagnosticManager &diagnostic_manager, Value &results) {338lldb::ExpressionResults return_value = lldb::eExpressionSetupError;339340// FunctionCaller::ExecuteFunction execution is always just to get the341// result. Unless explicitly asked for, ignore breakpoints and unwind on342// error.343const bool enable_debugging =344exe_ctx.GetTargetPtr() &&345exe_ctx.GetTargetPtr()->GetDebugUtilityExpression();346EvaluateExpressionOptions real_options = options;347real_options.SetDebug(false); // This halts the expression for debugging.348real_options.SetGenerateDebugInfo(enable_debugging);349real_options.SetUnwindOnError(!enable_debugging);350real_options.SetIgnoreBreakpoints(!enable_debugging);351352lldb::addr_t args_addr;353354if (args_addr_ptr != nullptr)355args_addr = *args_addr_ptr;356else357args_addr = LLDB_INVALID_ADDRESS;358359if (CompileFunction(exe_ctx.GetThreadSP(), diagnostic_manager) != 0)360return lldb::eExpressionSetupError;361362if (args_addr == LLDB_INVALID_ADDRESS) {363if (!InsertFunction(exe_ctx, args_addr, diagnostic_manager))364return lldb::eExpressionSetupError;365}366367Log *log(GetLog(LLDBLog::Expressions | LLDBLog::Step));368369LLDB_LOGF(log,370"== [FunctionCaller::ExecuteFunction] Executing function \"%s\" ==",371m_name.c_str());372373lldb::ThreadPlanSP call_plan_sp = GetThreadPlanToCallFunction(374exe_ctx, args_addr, real_options, diagnostic_manager);375if (!call_plan_sp)376return lldb::eExpressionSetupError;377378// We need to make sure we record the fact that we are running an expression379// here otherwise this fact will fail to be recorded when fetching an380// Objective-C object description381if (exe_ctx.GetProcessPtr())382exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);383384return_value = exe_ctx.GetProcessRef().RunThreadPlan(385exe_ctx, call_plan_sp, real_options, diagnostic_manager);386387if (log) {388if (return_value != lldb::eExpressionCompleted) {389LLDB_LOGF(log,390"== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "391"completed abnormally: %s ==",392m_name.c_str(),393Process::ExecutionResultAsCString(return_value));394} else {395LLDB_LOGF(log,396"== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "397"completed normally ==",398m_name.c_str());399}400}401402if (exe_ctx.GetProcessPtr())403exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);404405if (args_addr_ptr != nullptr)406*args_addr_ptr = args_addr;407408if (return_value != lldb::eExpressionCompleted)409return return_value;410411FetchFunctionResults(exe_ctx, args_addr, results);412413if (args_addr_ptr == nullptr)414DeallocateFunctionResults(exe_ctx, args_addr);415416return lldb::eExpressionCompleted;417}418419420