Path: blob/main/contrib/llvm-project/lldb/source/Expression/LLVMUserExpression.cpp
39587 views
//===-- LLVMUserExpression.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/LLVMUserExpression.h"10#include "lldb/Core/Module.h"11#include "lldb/Core/ValueObjectConstResult.h"12#include "lldb/Expression/DiagnosticManager.h"13#include "lldb/Expression/ExpressionVariable.h"14#include "lldb/Expression/IRExecutionUnit.h"15#include "lldb/Expression/IRInterpreter.h"16#include "lldb/Expression/Materializer.h"17#include "lldb/Host/HostInfo.h"18#include "lldb/Symbol/Block.h"19#include "lldb/Symbol/Function.h"20#include "lldb/Symbol/ObjectFile.h"21#include "lldb/Symbol/SymbolVendor.h"22#include "lldb/Symbol/Type.h"23#include "lldb/Symbol/VariableList.h"24#include "lldb/Target/ABI.h"25#include "lldb/Target/ExecutionContext.h"26#include "lldb/Target/Process.h"27#include "lldb/Target/StackFrame.h"28#include "lldb/Target/Target.h"29#include "lldb/Target/ThreadPlan.h"30#include "lldb/Target/ThreadPlanCallUserExpression.h"31#include "lldb/Utility/ConstString.h"32#include "lldb/Utility/LLDBLog.h"33#include "lldb/Utility/Log.h"34#include "lldb/Utility/StreamString.h"3536using namespace lldb;37using namespace lldb_private;3839char LLVMUserExpression::ID;4041LLVMUserExpression::LLVMUserExpression(ExecutionContextScope &exe_scope,42llvm::StringRef expr,43llvm::StringRef prefix,44SourceLanguage language,45ResultType desired_type,46const EvaluateExpressionOptions &options)47: UserExpression(exe_scope, expr, prefix, language, desired_type, options),48m_stack_frame_bottom(LLDB_INVALID_ADDRESS),49m_stack_frame_top(LLDB_INVALID_ADDRESS), m_allow_cxx(false),50m_allow_objc(false), m_transformed_text(), m_execution_unit_sp(),51m_materializer_up(), m_jit_module_wp(), m_target(nullptr),52m_can_interpret(false), m_materialized_address(LLDB_INVALID_ADDRESS) {}5354LLVMUserExpression::~LLVMUserExpression() {55if (m_target) {56lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock());57if (jit_module_sp)58m_target->GetImages().Remove(jit_module_sp);59}60}6162lldb::ExpressionResults63LLVMUserExpression::DoExecute(DiagnosticManager &diagnostic_manager,64ExecutionContext &exe_ctx,65const EvaluateExpressionOptions &options,66lldb::UserExpressionSP &shared_ptr_to_me,67lldb::ExpressionVariableSP &result) {68// The expression log is quite verbose, and if you're just tracking the69// execution of the expression, it's quite convenient to have these logs come70// out with the STEP log as well.71Log *log(GetLog(LLDBLog::Expressions | LLDBLog::Step));7273if (m_jit_start_addr == LLDB_INVALID_ADDRESS && !m_can_interpret) {74diagnostic_manager.PutString(75lldb::eSeverityError,76"Expression can't be run, because there is no JIT compiled function");77return lldb::eExpressionSetupError;78}7980lldb::addr_t struct_address = LLDB_INVALID_ADDRESS;8182if (!PrepareToExecuteJITExpression(diagnostic_manager, exe_ctx,83struct_address)) {84diagnostic_manager.Printf(85lldb::eSeverityError,86"errored out in %s, couldn't PrepareToExecuteJITExpression",87__FUNCTION__);88return lldb::eExpressionSetupError;89}9091lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS;92lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS;9394if (m_can_interpret) {95llvm::Module *module = m_execution_unit_sp->GetModule();96llvm::Function *function = m_execution_unit_sp->GetFunction();9798if (!module || !function) {99diagnostic_manager.PutString(100lldb::eSeverityError, "supposed to interpret, but nothing is there");101return lldb::eExpressionSetupError;102}103104Status interpreter_error;105106std::vector<lldb::addr_t> args;107108if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager)) {109diagnostic_manager.Printf(lldb::eSeverityError,110"errored out in %s, couldn't AddArguments",111__FUNCTION__);112return lldb::eExpressionSetupError;113}114115function_stack_bottom = m_stack_frame_bottom;116function_stack_top = m_stack_frame_top;117118IRInterpreter::Interpret(*module, *function, args, *m_execution_unit_sp,119interpreter_error, function_stack_bottom,120function_stack_top, exe_ctx, options.GetTimeout());121122if (!interpreter_error.Success()) {123diagnostic_manager.Printf(lldb::eSeverityError,124"supposed to interpret, but failed: %s",125interpreter_error.AsCString());126return lldb::eExpressionDiscarded;127}128} else {129if (!exe_ctx.HasThreadScope()) {130diagnostic_manager.Printf(lldb::eSeverityError,131"%s called with no thread selected",132__FUNCTION__);133return lldb::eExpressionSetupError;134}135136// Store away the thread ID for error reporting, in case it exits137// during execution:138lldb::tid_t expr_thread_id = exe_ctx.GetThreadRef().GetID();139140Address wrapper_address(m_jit_start_addr);141142std::vector<lldb::addr_t> args;143144if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager)) {145diagnostic_manager.Printf(lldb::eSeverityError,146"errored out in %s, couldn't AddArguments",147__FUNCTION__);148return lldb::eExpressionSetupError;149}150151lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallUserExpression(152exe_ctx.GetThreadRef(), wrapper_address, args, options,153shared_ptr_to_me));154155StreamString ss;156if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {157diagnostic_manager.PutString(lldb::eSeverityError, ss.GetString());158return lldb::eExpressionSetupError;159}160161ThreadPlanCallUserExpression *user_expression_plan =162static_cast<ThreadPlanCallUserExpression *>(call_plan_sp.get());163164lldb::addr_t function_stack_pointer =165user_expression_plan->GetFunctionStackPointer();166167function_stack_bottom = function_stack_pointer - HostInfo::GetPageSize();168function_stack_top = function_stack_pointer;169170LLDB_LOGF(log,171"-- [UserExpression::Execute] Execution of expression begins --");172173if (exe_ctx.GetProcessPtr())174exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);175176lldb::ExpressionResults execution_result =177exe_ctx.GetProcessRef().RunThreadPlan(exe_ctx, call_plan_sp, options,178diagnostic_manager);179180if (exe_ctx.GetProcessPtr())181exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);182183LLDB_LOGF(log, "-- [UserExpression::Execute] Execution of expression "184"completed --");185186if (execution_result == lldb::eExpressionInterrupted ||187execution_result == lldb::eExpressionHitBreakpoint) {188const char *error_desc = nullptr;189190if (user_expression_plan) {191if (auto real_stop_info_sp = user_expression_plan->GetRealStopInfo())192error_desc = real_stop_info_sp->GetDescription();193}194if (error_desc)195diagnostic_manager.Printf(lldb::eSeverityError,196"Execution was interrupted, reason: %s.",197error_desc);198else199diagnostic_manager.PutString(lldb::eSeverityError,200"Execution was interrupted.");201202if ((execution_result == lldb::eExpressionInterrupted &&203options.DoesUnwindOnError()) ||204(execution_result == lldb::eExpressionHitBreakpoint &&205options.DoesIgnoreBreakpoints()))206diagnostic_manager.AppendMessageToDiagnostic(207"The process has been returned to the state before expression "208"evaluation.");209else {210if (execution_result == lldb::eExpressionHitBreakpoint)211user_expression_plan->TransferExpressionOwnership();212diagnostic_manager.AppendMessageToDiagnostic(213"The process has been left at the point where it was "214"interrupted, "215"use \"thread return -x\" to return to the state before "216"expression evaluation.");217}218219return execution_result;220} else if (execution_result == lldb::eExpressionStoppedForDebug) {221diagnostic_manager.PutString(222lldb::eSeverityInfo,223"Execution was halted at the first instruction of the expression "224"function because \"debug\" was requested.\n"225"Use \"thread return -x\" to return to the state before expression "226"evaluation.");227return execution_result;228} else if (execution_result == lldb::eExpressionThreadVanished) {229diagnostic_manager.Printf(230lldb::eSeverityError,231"Couldn't complete execution; the thread "232"on which the expression was being run: 0x%" PRIx64233" exited during its execution.",234expr_thread_id);235return execution_result;236} else if (execution_result != lldb::eExpressionCompleted) {237diagnostic_manager.Printf(238lldb::eSeverityError, "Couldn't execute function; result was %s",239Process::ExecutionResultAsCString(execution_result));240return execution_result;241}242}243244if (FinalizeJITExecution(diagnostic_manager, exe_ctx, result,245function_stack_bottom, function_stack_top)) {246return lldb::eExpressionCompleted;247} else {248return lldb::eExpressionResultUnavailable;249}250}251252bool LLVMUserExpression::FinalizeJITExecution(253DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,254lldb::ExpressionVariableSP &result, lldb::addr_t function_stack_bottom,255lldb::addr_t function_stack_top) {256Log *log = GetLog(LLDBLog::Expressions);257258LLDB_LOGF(log, "-- [UserExpression::FinalizeJITExecution] Dematerializing "259"after execution --");260261if (!m_dematerializer_sp) {262diagnostic_manager.Printf(lldb::eSeverityError,263"Couldn't apply expression side effects : no "264"dematerializer is present");265return false;266}267268Status dematerialize_error;269270m_dematerializer_sp->Dematerialize(dematerialize_error, function_stack_bottom,271function_stack_top);272273if (!dematerialize_error.Success()) {274diagnostic_manager.Printf(lldb::eSeverityError,275"Couldn't apply expression side effects : %s",276dematerialize_error.AsCString("unknown error"));277return false;278}279280result =281GetResultAfterDematerialization(exe_ctx.GetBestExecutionContextScope());282283if (result)284result->TransferAddress();285286m_dematerializer_sp.reset();287288return true;289}290291bool LLVMUserExpression::PrepareToExecuteJITExpression(292DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,293lldb::addr_t &struct_address) {294lldb::TargetSP target;295lldb::ProcessSP process;296lldb::StackFrameSP frame;297298if (!LockAndCheckContext(exe_ctx, target, process, frame)) {299diagnostic_manager.PutString(300lldb::eSeverityError,301"The context has changed before we could JIT the expression!");302return false;303}304305if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret) {306if (m_materialized_address == LLDB_INVALID_ADDRESS) {307Status alloc_error;308309IRMemoryMap::AllocationPolicy policy =310m_can_interpret ? IRMemoryMap::eAllocationPolicyHostOnly311: IRMemoryMap::eAllocationPolicyMirror;312313const bool zero_memory = false;314315m_materialized_address = m_execution_unit_sp->Malloc(316m_materializer_up->GetStructByteSize(),317m_materializer_up->GetStructAlignment(),318lldb::ePermissionsReadable | lldb::ePermissionsWritable, policy,319zero_memory, alloc_error);320321if (!alloc_error.Success()) {322diagnostic_manager.Printf(323lldb::eSeverityError,324"Couldn't allocate space for materialized struct: %s",325alloc_error.AsCString());326return false;327}328}329330struct_address = m_materialized_address;331332if (m_can_interpret && m_stack_frame_bottom == LLDB_INVALID_ADDRESS) {333Status alloc_error;334335size_t stack_frame_size = target->GetExprAllocSize();336if (stack_frame_size == 0) {337ABISP abi_sp;338if (process && (abi_sp = process->GetABI()))339stack_frame_size = abi_sp->GetStackFrameSize();340else341stack_frame_size = 512 * 1024;342}343344const bool zero_memory = false;345346m_stack_frame_bottom = m_execution_unit_sp->Malloc(347stack_frame_size, 8,348lldb::ePermissionsReadable | lldb::ePermissionsWritable,349IRMemoryMap::eAllocationPolicyHostOnly, zero_memory, alloc_error);350351m_stack_frame_top = m_stack_frame_bottom + stack_frame_size;352353if (!alloc_error.Success()) {354diagnostic_manager.Printf(355lldb::eSeverityError,356"Couldn't allocate space for the stack frame: %s",357alloc_error.AsCString());358return false;359}360}361362Status materialize_error;363364m_dematerializer_sp = m_materializer_up->Materialize(365frame, *m_execution_unit_sp, struct_address, materialize_error);366367if (!materialize_error.Success()) {368diagnostic_manager.Printf(lldb::eSeverityError,369"Couldn't materialize: %s",370materialize_error.AsCString());371return false;372}373}374return true;375}376377378379