Path: blob/main/contrib/llvm-project/lldb/source/Commands/CommandObjectExpression.cpp
39587 views
//===-- CommandObjectExpression.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 "llvm/ADT/StringRef.h"910#include "CommandObjectExpression.h"11#include "lldb/Core/Debugger.h"12#include "lldb/Expression/ExpressionVariable.h"13#include "lldb/Expression/REPL.h"14#include "lldb/Expression/UserExpression.h"15#include "lldb/Host/OptionParser.h"16#include "lldb/Interpreter/CommandInterpreter.h"17#include "lldb/Interpreter/CommandOptionArgumentTable.h"18#include "lldb/Interpreter/CommandReturnObject.h"19#include "lldb/Interpreter/OptionArgParser.h"20#include "lldb/Target/Language.h"21#include "lldb/Target/Process.h"22#include "lldb/Target/StackFrame.h"23#include "lldb/Target/Target.h"24#include "lldb/lldb-enumerations.h"25#include "lldb/lldb-private-enumerations.h"2627using namespace lldb;28using namespace lldb_private;2930CommandObjectExpression::CommandOptions::CommandOptions() = default;3132CommandObjectExpression::CommandOptions::~CommandOptions() = default;3334#define LLDB_OPTIONS_expression35#include "CommandOptions.inc"3637Status CommandObjectExpression::CommandOptions::SetOptionValue(38uint32_t option_idx, llvm::StringRef option_arg,39ExecutionContext *execution_context) {40Status error;4142const int short_option = GetDefinitions()[option_idx].short_option;4344switch (short_option) {45case 'l':46language = Language::GetLanguageTypeFromString(option_arg);47if (language == eLanguageTypeUnknown) {48StreamString sstr;49sstr.Printf("unknown language type: '%s' for expression. "50"List of supported languages:\n",51option_arg.str().c_str());5253Language::PrintSupportedLanguagesForExpressions(sstr, " ", "\n");54error.SetErrorString(sstr.GetString());55}56break;5758case 'a': {59bool success;60bool result;61result = OptionArgParser::ToBoolean(option_arg, true, &success);62if (!success)63error.SetErrorStringWithFormat(64"invalid all-threads value setting: \"%s\"",65option_arg.str().c_str());66else67try_all_threads = result;68} break;6970case 'i': {71bool success;72bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);73if (success)74ignore_breakpoints = tmp_value;75else76error.SetErrorStringWithFormat(77"could not convert \"%s\" to a boolean value.",78option_arg.str().c_str());79break;80}8182case 'j': {83bool success;84bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);85if (success)86allow_jit = tmp_value;87else88error.SetErrorStringWithFormat(89"could not convert \"%s\" to a boolean value.",90option_arg.str().c_str());91break;92}9394case 't':95if (option_arg.getAsInteger(0, timeout)) {96timeout = 0;97error.SetErrorStringWithFormat("invalid timeout setting \"%s\"",98option_arg.str().c_str());99}100break;101102case 'u': {103bool success;104bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);105if (success)106unwind_on_error = tmp_value;107else108error.SetErrorStringWithFormat(109"could not convert \"%s\" to a boolean value.",110option_arg.str().c_str());111break;112}113114case 'v':115if (option_arg.empty()) {116m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull;117break;118}119m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity)120OptionArgParser::ToOptionEnum(121option_arg, GetDefinitions()[option_idx].enum_values, 0, error);122if (!error.Success())123error.SetErrorStringWithFormat(124"unrecognized value for description-verbosity '%s'",125option_arg.str().c_str());126break;127128case 'g':129debug = true;130unwind_on_error = false;131ignore_breakpoints = false;132break;133134case 'p':135top_level = true;136break;137138case 'X': {139bool success;140bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);141if (success)142auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo;143else144error.SetErrorStringWithFormat(145"could not convert \"%s\" to a boolean value.",146option_arg.str().c_str());147break;148}149150case '\x01': {151bool success;152bool persist_result =153OptionArgParser::ToBoolean(option_arg, true, &success);154if (success)155suppress_persistent_result = !persist_result ? eLazyBoolYes : eLazyBoolNo;156else157error.SetErrorStringWithFormat(158"could not convert \"%s\" to a boolean value.",159option_arg.str().c_str());160break;161}162163default:164llvm_unreachable("Unimplemented option");165}166167return error;168}169170void CommandObjectExpression::CommandOptions::OptionParsingStarting(171ExecutionContext *execution_context) {172auto process_sp =173execution_context ? execution_context->GetProcessSP() : ProcessSP();174if (process_sp) {175ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions();176unwind_on_error = process_sp->GetUnwindOnErrorInExpressions();177} else {178ignore_breakpoints = true;179unwind_on_error = true;180}181182show_summary = true;183try_all_threads = true;184timeout = 0;185debug = false;186language = eLanguageTypeUnknown;187m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact;188auto_apply_fixits = eLazyBoolCalculate;189top_level = false;190allow_jit = true;191suppress_persistent_result = eLazyBoolCalculate;192}193194llvm::ArrayRef<OptionDefinition>195CommandObjectExpression::CommandOptions::GetDefinitions() {196return llvm::ArrayRef(g_expression_options);197}198199EvaluateExpressionOptions200CommandObjectExpression::CommandOptions::GetEvaluateExpressionOptions(201const Target &target, const OptionGroupValueObjectDisplay &display_opts) {202EvaluateExpressionOptions options;203options.SetCoerceToId(display_opts.use_objc);204options.SetUnwindOnError(unwind_on_error);205options.SetIgnoreBreakpoints(ignore_breakpoints);206options.SetKeepInMemory(true);207options.SetUseDynamic(display_opts.use_dynamic);208options.SetTryAllThreads(try_all_threads);209options.SetDebug(debug);210options.SetLanguage(language);211options.SetExecutionPolicy(212allow_jit ? EvaluateExpressionOptions::default_execution_policy213: lldb_private::eExecutionPolicyNever);214215bool auto_apply_fixits;216if (this->auto_apply_fixits == eLazyBoolCalculate)217auto_apply_fixits = target.GetEnableAutoApplyFixIts();218else219auto_apply_fixits = this->auto_apply_fixits == eLazyBoolYes;220221options.SetAutoApplyFixIts(auto_apply_fixits);222options.SetRetriesWithFixIts(target.GetNumberOfRetriesWithFixits());223224if (top_level)225options.SetExecutionPolicy(eExecutionPolicyTopLevel);226227// If there is any chance we are going to stop and want to see what went228// wrong with our expression, we should generate debug info229if (!ignore_breakpoints || !unwind_on_error)230options.SetGenerateDebugInfo(true);231232if (timeout > 0)233options.SetTimeout(std::chrono::microseconds(timeout));234else235options.SetTimeout(std::nullopt);236return options;237}238239bool CommandObjectExpression::CommandOptions::ShouldSuppressResult(240const OptionGroupValueObjectDisplay &display_opts) const {241// Explicitly disabling persistent results takes precedence over the242// m_verbosity/use_objc logic.243if (suppress_persistent_result != eLazyBoolCalculate)244return suppress_persistent_result == eLazyBoolYes;245246return display_opts.use_objc &&247m_verbosity == eLanguageRuntimeDescriptionDisplayVerbosityCompact;248}249250CommandObjectExpression::CommandObjectExpression(251CommandInterpreter &interpreter)252: CommandObjectRaw(interpreter, "expression",253"Evaluate an expression on the current "254"thread. Displays any returned value "255"with LLDB's default formatting.",256"",257eCommandProcessMustBePaused | eCommandTryTargetAPILock),258IOHandlerDelegate(IOHandlerDelegate::Completion::Expression),259m_format_options(eFormatDefault),260m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false,261true),262m_expr_line_count(0) {263SetHelpLong(264R"(265Single and multi-line expressions:266267)"268" The expression provided on the command line must be a complete expression \269with no newlines. To evaluate a multi-line expression, \270hit a return after an empty expression, and lldb will enter the multi-line expression editor. \271Hit return on an empty line to end the multi-line expression."272273R"(274275Timeouts:276277)"278" If the expression can be evaluated statically (without running code) then it will be. \279Otherwise, by default the expression will run on the current thread with a short timeout: \280currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \281and resumed with all threads running. You can use the -a option to disable retrying on all \282threads. You can use the -t option to set a shorter timeout."283R"(284285User defined variables:286287)"288" You can define your own variables for convenience or to be used in subsequent expressions. \289You define them the same way you would define variables in C. If the first character of \290your user defined variable is a $, then the variable's value will be available in future \291expressions, otherwise it will just be available in the current expression."292R"(293294Continuing evaluation after a breakpoint:295296)"297" If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \298you are done with your investigation, you can either remove the expression execution frames \299from the stack with \"thread return -x\" or if you are still interested in the expression result \300you can issue the \"continue\" command and the expression evaluation will complete and the \301expression result will be available using the \"thread.completed-expression\" key in the thread \302format."303304R"(305306Examples:307308expr my_struct->a = my_array[3]309expr -f bin -- (index * 8) + 5310expr unsigned int $foo = 5311expr char c[] = \"foo\"; c[0])");312313AddSimpleArgumentList(eArgTypeExpression);314315// Add the "--format" and "--gdb-format"316m_option_group.Append(&m_format_options,317OptionGroupFormat::OPTION_GROUP_FORMAT |318OptionGroupFormat::OPTION_GROUP_GDB_FMT,319LLDB_OPT_SET_1);320m_option_group.Append(&m_command_options);321m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL,322LLDB_OPT_SET_1 | LLDB_OPT_SET_2);323m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);324m_option_group.Finalize();325}326327CommandObjectExpression::~CommandObjectExpression() = default;328329Options *CommandObjectExpression::GetOptions() { return &m_option_group; }330331void CommandObjectExpression::HandleCompletion(CompletionRequest &request) {332EvaluateExpressionOptions options;333options.SetCoerceToId(m_varobj_options.use_objc);334options.SetLanguage(m_command_options.language);335options.SetExecutionPolicy(lldb_private::eExecutionPolicyNever);336options.SetAutoApplyFixIts(false);337options.SetGenerateDebugInfo(false);338339ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());340341// Get out before we start doing things that expect a valid frame pointer.342if (exe_ctx.GetFramePtr() == nullptr)343return;344345Target *exe_target = exe_ctx.GetTargetPtr();346Target &target = exe_target ? *exe_target : GetDummyTarget();347348unsigned cursor_pos = request.GetRawCursorPos();349// Get the full user input including the suffix. The suffix is necessary350// as OptionsWithRaw will use it to detect if the cursor is cursor is in the351// argument part of in the raw input part of the arguments. If we cut of352// of the suffix then "expr -arg[cursor] --" would interpret the "-arg" as353// the raw input (as the "--" is hidden in the suffix).354llvm::StringRef code = request.GetRawLineWithUnusedSuffix();355356const std::size_t original_code_size = code.size();357358// Remove the first token which is 'expr' or some alias/abbreviation of that.359code = llvm::getToken(code).second.ltrim();360OptionsWithRaw args(code);361code = args.GetRawPart();362363// The position where the expression starts in the command line.364assert(original_code_size >= code.size());365std::size_t raw_start = original_code_size - code.size();366367// Check if the cursor is actually in the expression string, and if not, we368// exit.369// FIXME: We should complete the options here.370if (cursor_pos < raw_start)371return;372373// Make the cursor_pos again relative to the start of the code string.374assert(cursor_pos >= raw_start);375cursor_pos -= raw_start;376377auto language = exe_ctx.GetFrameRef().GetLanguage();378379Status error;380lldb::UserExpressionSP expr(target.GetUserExpressionForLanguage(381code, llvm::StringRef(), language, UserExpression::eResultTypeAny,382options, nullptr, error));383if (error.Fail())384return;385386expr->Complete(exe_ctx, request, cursor_pos);387}388389static lldb_private::Status390CanBeUsedForElementCountPrinting(ValueObject &valobj) {391CompilerType type(valobj.GetCompilerType());392CompilerType pointee;393if (!type.IsPointerType(&pointee))394return Status("as it does not refer to a pointer");395if (pointee.IsVoidType())396return Status("as it refers to a pointer to void");397return Status();398}399400bool CommandObjectExpression::EvaluateExpression(llvm::StringRef expr,401Stream &output_stream,402Stream &error_stream,403CommandReturnObject &result) {404// Don't use m_exe_ctx as this might be called asynchronously after the405// command object DoExecute has finished when doing multi-line expression406// that use an input reader...407ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());408Target *exe_target = exe_ctx.GetTargetPtr();409Target &target = exe_target ? *exe_target : GetDummyTarget();410411lldb::ValueObjectSP result_valobj_sp;412StackFrame *frame = exe_ctx.GetFramePtr();413414if (m_command_options.top_level && !m_command_options.allow_jit) {415result.AppendErrorWithFormat(416"Can't disable JIT compilation for top-level expressions.\n");417return false;418}419420EvaluateExpressionOptions eval_options =421m_command_options.GetEvaluateExpressionOptions(target, m_varobj_options);422// This command manually removes the result variable, make sure expression423// evaluation doesn't do it first.424eval_options.SetSuppressPersistentResult(false);425426ExpressionResults success = target.EvaluateExpression(427expr, frame, result_valobj_sp, eval_options, &m_fixed_expression);428429// Only mention Fix-Its if the expression evaluator applied them.430// Compiler errors refer to the final expression after applying Fix-It(s).431if (!m_fixed_expression.empty() && target.GetEnableNotifyAboutFixIts()) {432error_stream << " Evaluated this expression after applying Fix-It(s):\n";433error_stream << " " << m_fixed_expression << "\n";434}435436if (result_valobj_sp) {437Format format = m_format_options.GetFormat();438439if (result_valobj_sp->GetError().Success()) {440if (format != eFormatVoid) {441if (format != eFormatDefault)442result_valobj_sp->SetFormat(format);443444if (m_varobj_options.elem_count > 0) {445Status error(CanBeUsedForElementCountPrinting(*result_valobj_sp));446if (error.Fail()) {447result.AppendErrorWithFormat(448"expression cannot be used with --element-count %s\n",449error.AsCString(""));450return false;451}452}453454bool suppress_result =455m_command_options.ShouldSuppressResult(m_varobj_options);456457DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(458m_command_options.m_verbosity, format));459options.SetHideRootName(suppress_result);460options.SetVariableFormatDisplayLanguage(461result_valobj_sp->GetPreferredDisplayLanguage());462463if (llvm::Error error =464result_valobj_sp->Dump(output_stream, options)) {465result.AppendError(toString(std::move(error)));466return false;467}468469if (suppress_result)470if (auto result_var_sp =471target.GetPersistentVariable(result_valobj_sp->GetName())) {472auto language = result_valobj_sp->GetPreferredDisplayLanguage();473if (auto *persistent_state =474target.GetPersistentExpressionStateForLanguage(language))475persistent_state->RemovePersistentVariable(result_var_sp);476}477result.SetStatus(eReturnStatusSuccessFinishResult);478}479} else {480if (result_valobj_sp->GetError().GetError() ==481UserExpression::kNoResult) {482if (format != eFormatVoid && GetDebugger().GetNotifyVoid()) {483error_stream.PutCString("(void)\n");484}485486result.SetStatus(eReturnStatusSuccessFinishResult);487} else {488const char *error_cstr = result_valobj_sp->GetError().AsCString();489if (error_cstr && error_cstr[0]) {490const size_t error_cstr_len = strlen(error_cstr);491const bool ends_with_newline = error_cstr[error_cstr_len - 1] == '\n';492if (strstr(error_cstr, "error:") != error_cstr)493error_stream.PutCString("error: ");494error_stream.Write(error_cstr, error_cstr_len);495if (!ends_with_newline)496error_stream.EOL();497} else {498error_stream.PutCString("error: unknown error\n");499}500501result.SetStatus(eReturnStatusFailed);502}503}504} else {505error_stream.Printf("error: unknown error\n");506}507508return (success != eExpressionSetupError &&509success != eExpressionParseError);510}511512void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler,513std::string &line) {514io_handler.SetIsDone(true);515StreamFileSP output_sp = io_handler.GetOutputStreamFileSP();516StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();517518CommandReturnObject return_obj(519GetCommandInterpreter().GetDebugger().GetUseColor());520EvaluateExpression(line.c_str(), *output_sp, *error_sp, return_obj);521if (output_sp)522output_sp->Flush();523if (error_sp)524error_sp->Flush();525}526527bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler,528StringList &lines) {529// An empty lines is used to indicate the end of input530const size_t num_lines = lines.GetSize();531if (num_lines > 0 && lines[num_lines - 1].empty()) {532// Remove the last empty line from "lines" so it doesn't appear in our533// resulting input and return true to indicate we are done getting lines534lines.PopBack();535return true;536}537return false;538}539540void CommandObjectExpression::GetMultilineExpression() {541m_expr_lines.clear();542m_expr_line_count = 0;543544Debugger &debugger = GetCommandInterpreter().GetDebugger();545bool color_prompt = debugger.GetUseColor();546const bool multiple_lines = true; // Get multiple lines547IOHandlerSP io_handler_sp(548new IOHandlerEditline(debugger, IOHandler::Type::Expression,549"lldb-expr", // Name of input reader for history550llvm::StringRef(), // No prompt551llvm::StringRef(), // Continuation prompt552multiple_lines, color_prompt,5531, // Show line numbers starting at 1554*this));555556StreamFileSP output_sp = io_handler_sp->GetOutputStreamFileSP();557if (output_sp) {558output_sp->PutCString(559"Enter expressions, then terminate with an empty line to evaluate:\n");560output_sp->Flush();561}562debugger.RunIOHandlerAsync(io_handler_sp);563}564565static EvaluateExpressionOptions566GetExprOptions(ExecutionContext &ctx,567CommandObjectExpression::CommandOptions command_options) {568command_options.OptionParsingStarting(&ctx);569570// Default certain settings for REPL regardless of the global settings.571command_options.unwind_on_error = false;572command_options.ignore_breakpoints = false;573command_options.debug = false;574575EvaluateExpressionOptions expr_options;576expr_options.SetUnwindOnError(command_options.unwind_on_error);577expr_options.SetIgnoreBreakpoints(command_options.ignore_breakpoints);578expr_options.SetTryAllThreads(command_options.try_all_threads);579580if (command_options.timeout > 0)581expr_options.SetTimeout(std::chrono::microseconds(command_options.timeout));582else583expr_options.SetTimeout(std::nullopt);584585return expr_options;586}587588void CommandObjectExpression::DoExecute(llvm::StringRef command,589CommandReturnObject &result) {590m_fixed_expression.clear();591auto exe_ctx = GetCommandInterpreter().GetExecutionContext();592m_option_group.NotifyOptionParsingStarting(&exe_ctx);593594if (command.empty()) {595GetMultilineExpression();596return;597}598599OptionsWithRaw args(command);600llvm::StringRef expr = args.GetRawPart();601602if (args.HasArgs()) {603if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group, exe_ctx))604return;605606if (m_repl_option.GetOptionValue().GetCurrentValue()) {607Target &target = GetSelectedOrDummyTarget();608// Drop into REPL609m_expr_lines.clear();610m_expr_line_count = 0;611612Debugger &debugger = target.GetDebugger();613614// Check if the LLDB command interpreter is sitting on top of a REPL615// that launched it...616if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter,617IOHandler::Type::REPL)) {618// the LLDB command interpreter is sitting on top of a REPL that619// launched it, so just say the command interpreter is done and620// fall back to the existing REPL621m_interpreter.GetIOHandler(false)->SetIsDone(true);622} else {623// We are launching the REPL on top of the current LLDB command624// interpreter, so just push one625bool initialize = false;626Status repl_error;627REPLSP repl_sp(target.GetREPL(repl_error, m_command_options.language,628nullptr, false));629630if (!repl_sp) {631initialize = true;632repl_sp = target.GetREPL(repl_error, m_command_options.language,633nullptr, true);634if (!repl_error.Success()) {635result.SetError(repl_error);636return;637}638}639640if (repl_sp) {641if (initialize) {642repl_sp->SetEvaluateOptions(643GetExprOptions(exe_ctx, m_command_options));644repl_sp->SetFormatOptions(m_format_options);645repl_sp->SetValueObjectDisplayOptions(m_varobj_options);646}647648IOHandlerSP io_handler_sp(repl_sp->GetIOHandler());649io_handler_sp->SetIsDone(false);650debugger.RunIOHandlerAsync(io_handler_sp);651} else {652repl_error.SetErrorStringWithFormat(653"Couldn't create a REPL for %s",654Language::GetNameForLanguageType(m_command_options.language));655result.SetError(repl_error);656return;657}658}659}660// No expression following options661else if (expr.empty()) {662GetMultilineExpression();663return;664}665}666667Target &target = GetSelectedOrDummyTarget();668if (EvaluateExpression(expr, result.GetOutputStream(),669result.GetErrorStream(), result)) {670671if (!m_fixed_expression.empty() && target.GetEnableNotifyAboutFixIts()) {672CommandHistory &history = m_interpreter.GetCommandHistory();673// FIXME: Can we figure out what the user actually typed (e.g. some alias674// for expr???)675// If we can it would be nice to show that.676std::string fixed_command("expression ");677if (args.HasArgs()) {678// Add in any options that might have been in the original command:679fixed_command.append(std::string(args.GetArgStringWithDelimiter()));680fixed_command.append(m_fixed_expression);681} else682fixed_command.append(m_fixed_expression);683history.AppendString(fixed_command);684}685return;686}687result.SetStatus(eReturnStatusFailed);688}689690691