LLDB mainline
UserExpression.cpp
Go to the documentation of this file.
1//===-- UserExpression.cpp ------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include <cstdio>
10#include <sys/types.h>
11
12#include <cstdlib>
13#include <map>
14#include <string>
15
16#include "lldb/Core/Module.h"
17#include "lldb/Core/Progress.h"
24#include "lldb/Host/HostInfo.h"
25#include "lldb/Symbol/Block.h"
29#include "lldb/Symbol/Type.h"
33#include "lldb/Target/Process.h"
35#include "lldb/Target/Target.h"
40#include "lldb/Utility/Log.h"
41#include "lldb/Utility/State.h"
45#include "llvm/BinaryFormat/Dwarf.h"
46
47using namespace lldb_private;
48
50
52 llvm::StringRef expr, llvm::StringRef prefix,
53 SourceLanguage language, ResultType desired_type,
54 const EvaluateExpressionOptions &options)
55 : Expression(exe_scope), m_expr_text(std::string(expr)),
56 m_expr_prefix(std::string(prefix)), m_language(language),
57 m_desired_type(desired_type), m_options(options) {}
58
60
63
64 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
65
66 if (frame_sp)
67 m_address = frame_sp->GetFrameCodeAddress();
68}
69
71 lldb::TargetSP &target_sp,
72 lldb::ProcessSP &process_sp,
73 lldb::StackFrameSP &frame_sp) {
74 lldb::ProcessSP expected_process_sp = m_jit_process_wp.lock();
75 process_sp = exe_ctx.GetProcessSP();
76
77 if (process_sp != expected_process_sp)
78 return false;
79
80 process_sp = exe_ctx.GetProcessSP();
81 target_sp = exe_ctx.GetTargetSP();
82 frame_sp = exe_ctx.GetFrameSP();
83
84 if (m_address.IsValid()) {
85 if (!frame_sp)
86 return false;
88 frame_sp->GetFrameCodeAddress(),
89 target_sp.get()) == 0);
90 }
91
92 return true;
93}
94
96 lldb::TargetSP target_sp;
97 lldb::ProcessSP process_sp;
98 lldb::StackFrameSP frame_sp;
99
100 return LockAndCheckContext(exe_ctx, target_sp, process_sp, frame_sp);
101}
102
104 lldb::StackFrameSP frame_sp, llvm::StringRef object_name, Status &err) {
105 err.Clear();
106
107 if (!frame_sp) {
109 "Couldn't load '{0}' because the context is incomplete", object_name);
110 return {};
111 }
112
113 if (auto var_list_sp = frame_sp->GetInScopeVariableList(false))
114 if (auto var_sp =
115 var_list_sp->FindVariable(ConstString(object_name), false))
116 return frame_sp->GetValueObjectForFrameVariable(var_sp,
118
119 return {};
120}
121
123 llvm::StringRef object_name,
124 Status &err) {
125 auto valobj_sp =
126 GetObjectPointerValueObject(std::move(frame_sp), object_name, err);
127
128 if (!err.Success() || !valobj_sp.get())
130
131 lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
132
133 if (ret == LLDB_INVALID_ADDRESS) {
135 "Couldn't load '{0}' because its value couldn't be evaluated",
136 object_name);
138 }
139
140 return ret;
141}
142
145 const EvaluateExpressionOptions &options,
146 llvm::StringRef expr, llvm::StringRef prefix,
147 lldb::ValueObjectSP &result_valobj_sp,
148 std::string *fixed_expression, ValueObject *ctx_obj) {
150 auto set_error = [&](Status error) {
151 result_valobj_sp = ValueObjectConstResult::Create(
152 exe_ctx.GetBestExecutionContextScope(), std::move(error));
153 };
154
155 if (ctx_obj) {
156 static unsigned const ctx_type_mask = lldb::TypeFlags::eTypeIsClass |
157 lldb::TypeFlags::eTypeIsStructUnion |
158 lldb::TypeFlags::eTypeIsReference;
159 if (!(ctx_obj->GetTypeInfo() & ctx_type_mask)) {
160 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
161 "an invalid type, can't run expressions.");
162 set_error(Status("a context object of an invalid type passed"));
164 }
165 }
166
167 if (ctx_obj && ctx_obj->GetTypeInfo() & lldb::TypeFlags::eTypeIsReference) {
169 lldb::ValueObjectSP deref_ctx_sp = ctx_obj->Dereference(error);
170 if (!error.Success()) {
171 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
172 "a reference type that can't be dereferenced, can't run "
173 "expressions.");
174 set_error(Status(
175 "passed context object of an reference type cannot be deferenced"));
177 }
178
179 ctx_obj = deref_ctx_sp.get();
180 }
181
182 lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy();
183 SourceLanguage language = options.GetLanguage();
184 const ResultType desired_type = options.DoesCoerceToId()
187 Target *target = exe_ctx.GetTargetPtr();
188 if (!target) {
189 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a NULL target, can't "
190 "run expressions.");
191 set_error(Status("expression passed a null target"));
193 }
194
195 Process *process = exe_ctx.GetProcessPtr();
196
197 if (!process && execution_policy == eExecutionPolicyAlways) {
198 LLDB_LOG(log, "== [UserExpression::Evaluate] No process, but the policy is "
199 "eExecutionPolicyAlways");
200
201 set_error(Status("expression needed to run but couldn't: no process"));
202
204 }
205
206 // Since we might need to allocate memory, we need to be stopped to run
207 // an expression.
208 if (process && process->GetState() != lldb::eStateStopped) {
210 "unable to evaluate expression while the process is {0}: the process "
211 "must be stopped because the expression might require allocating "
212 "memory.",
213 StateAsCString(process->GetState())));
215 }
216
217 // Explicitly force the IR interpreter to evaluate the expression when the
218 // there is no process that supports running the expression for us. Don't
219 // change the execution policy if we have the special top-level policy that
220 // doesn't contain any expression and there is nothing to interpret.
221 if (execution_policy != eExecutionPolicyTopLevel &&
222 (process == nullptr || !process->CanJIT()))
223 execution_policy = eExecutionPolicyNever;
224
225 // We need to set the expression execution thread here, turns out parse can
226 // call functions in the process of looking up symbols, which will escape the
227 // context set by exe_ctx passed to Execute.
228 lldb::ThreadSP thread_sp = exe_ctx.GetThreadSP();
229 ThreadList::ExpressionExecutionThreadPusher execution_thread_pusher(
230 thread_sp);
231
232 llvm::StringRef full_prefix;
233 llvm::StringRef option_prefix(options.GetPrefix());
234 std::string full_prefix_storage;
235 if (!prefix.empty() && !option_prefix.empty()) {
236 full_prefix_storage = std::string(prefix);
237 full_prefix_storage.append(std::string(option_prefix));
238 full_prefix = full_prefix_storage;
239 } else if (!prefix.empty())
240 full_prefix = prefix;
241 else
242 full_prefix = option_prefix;
243
244 // If the language was not specified in the expression command, set it to the
245 // language in the target's properties if specified, else default to the
246 // langage for the frame.
247 if (!language) {
248 if (target->GetLanguage())
249 language = target->GetLanguage();
250 else if (StackFrame *frame = exe_ctx.GetFramePtr())
251 language = frame->GetLanguage();
252 }
253
255 lldb::UserExpressionSP user_expression_sp(
257 expr, full_prefix, language, desired_type, options, ctx_obj, error));
258 if (error.Fail() || !user_expression_sp) {
259 LLDB_LOG(log, "== [UserExpression::Evaluate] Getting expression: {0} ==",
260 error.AsCString());
261 set_error(std::move(error));
263 }
264
265 LLDB_LOG(log, "== [UserExpression::Evaluate] Parsing expression {0} ==",
266 expr.str());
267
268 const bool keep_expression_in_memory = true;
269 const bool generate_debug_info = options.GetGenerateDebugInfo();
270
272 set_error(Status("expression interrupted by callback before parse"));
274 }
275
276 DiagnosticManager diagnostic_manager;
277
278 bool parse_success =
279 user_expression_sp->Parse(diagnostic_manager, exe_ctx, execution_policy,
280 keep_expression_in_memory, generate_debug_info);
281
282 // Calculate the fixed expression always, since we need it for errors.
283 std::string tmp_fixed_expression;
284 if (fixed_expression == nullptr)
285 fixed_expression = &tmp_fixed_expression;
286
287 *fixed_expression = user_expression_sp->GetFixedText().str();
289
290 // If there is a fixed expression, try to parse it:
291 if (!parse_success) {
292 execution_results = lldb::eExpressionParseError;
293 if (!fixed_expression->empty() && options.GetAutoApplyFixIts()) {
294 const uint64_t max_fix_retries = options.GetRetriesWithFixIts();
295 for (uint64_t i = 0; i < max_fix_retries; ++i) {
296 // Try parsing the fixed expression.
297 user_expression_sp.reset(target->GetUserExpressionForLanguage(
298 fixed_expression->c_str(), full_prefix, language, desired_type,
299 options, ctx_obj, error));
300 if (!user_expression_sp)
301 break;
302
303 DiagnosticManager fixed_diagnostic_manager;
304 parse_success = user_expression_sp->Parse(
305 fixed_diagnostic_manager, exe_ctx, execution_policy,
306 keep_expression_in_memory, generate_debug_info);
307 if (parse_success) {
308 diagnostic_manager.Clear();
309 break;
310 }
311 // The fixed expression also didn't parse. Let's check for any new
312 // fixits we could try.
313 if (!user_expression_sp->GetFixedText().empty()) {
314 *fixed_expression = user_expression_sp->GetFixedText().str();
315 } else {
316 // Fixed expression didn't compile without a fixit, don't retry and
317 // don't tell the user about it.
318 fixed_expression->clear();
319 break;
320 }
321 }
322 }
323
324 if (!parse_success) {
325 if (user_expression_sp)
326 user_expression_sp->FixupParseErrorDiagnostics(diagnostic_manager);
327
328 if (target->GetEnableNotifyAboutFixIts() && fixed_expression &&
329 !fixed_expression->empty()) {
330 std::string fixit =
331 "fixed expression suggested:\n " + *fixed_expression;
332 diagnostic_manager.AddDiagnostic(fixit, lldb::eSeverityInfo,
334 }
335 if (diagnostic_manager.Diagnostics().empty())
336 error = Status::FromError(llvm::make_error<ExpressionError>(
337 execution_results,
338 "expression failed to parse (no further compiler diagnostics)"));
339 else
340 error =
341 Status::FromError(diagnostic_manager.GetAsError(execution_results));
342 }
343 }
344
345 if (parse_success) {
346 lldb::ExpressionVariableSP expr_result;
347
348 if (execution_policy == eExecutionPolicyNever &&
349 !user_expression_sp->CanInterpret()) {
350 LLDB_LOG(log, "== [UserExpression::Evaluate] Expression may not run, but "
351 "is not constant ==");
352
353 if (diagnostic_manager.Diagnostics().empty())
354 error = Status::FromError(llvm::make_error<ExpressionError>(
356 "expression needed to run but couldn't"));
357 } else if (execution_policy == eExecutionPolicyTopLevel) {
360 } else {
362 set_error(Status::FromError(llvm::make_error<ExpressionError>(
364 "expression interrupted by callback before execution")));
366 }
367
368 diagnostic_manager.Clear();
369
370 LLDB_LOG(log, "== [UserExpression::Evaluate] Executing expression ==");
371
372 execution_results =
373 user_expression_sp->Execute(diagnostic_manager, exe_ctx, options,
374 user_expression_sp, expr_result);
375
376 if (execution_results != lldb::eExpressionCompleted) {
377 LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
378 "abnormally ==");
379
380 if (diagnostic_manager.Diagnostics().empty())
381 error = Status::FromError(llvm::make_error<ExpressionError>(
382 execution_results,
383 "expression failed to execute, unknown error"));
384 else
386 diagnostic_manager.GetAsError(execution_results));
387 } else {
388 if (expr_result) {
389 result_valobj_sp = expr_result->GetValueObject();
390 result_valobj_sp->SetPreferredDisplayLanguage(
391 language.AsLanguageType());
392
393 LLDB_LOG(log,
394 "== [UserExpression::Evaluate] Execution completed "
395 "normally with result {0} ==",
396 result_valobj_sp->GetValueAsCString());
397 } else {
398 LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
399 "normally with no result ==");
400
402 }
403 }
404 }
405 }
406
408 set_error(Status::FromError(llvm::make_error<ExpressionError>(
410 "expression interrupted by callback after complete")));
412 }
413
414 if (error.Fail())
415 set_error(std::move(error));
416 return execution_results;
417}
418
421 ExecutionContext &exe_ctx,
422 const EvaluateExpressionOptions &options,
423 lldb::UserExpressionSP &shared_ptr_to_me,
424 lldb::ExpressionVariableSP &result_var) {
425 Debugger *debugger =
426 exe_ctx.GetTargetPtr() ? &exe_ctx.GetTargetPtr()->GetDebugger() : nullptr;
427
428 Progress progress("Running expression",
429 m_options.IsForUtilityExpr() ? "LLDB utility" : m_expr_text,
430 {}, debugger);
431
433 diagnostic_manager, exe_ctx, options, shared_ptr_to_me, result_var);
434 Target *target = exe_ctx.GetTargetPtr();
435 if (options.GetSuppressPersistentResult() && result_var && target) {
436 if (auto *persistent_state =
438 m_language.AsLanguageType()))
439 persistent_state->RemovePersistentVariable(result_var);
440 }
441 return expr_result;
442}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:364
static int CompareLoadAddress(const Address &lhs, const Address &rhs, Target *target)
Definition Address.cpp:929
A uniqued constant string class.
Definition ConstString.h:40
A class to manage flag bits.
Definition Debugger.h:100
const DiagnosticList & Diagnostics() const
llvm::Error GetAsError(lldb::ExpressionResults result, llvm::Twine message={}) const
Returns an ExpressionError with arg as error code.
void AddDiagnostic(llvm::StringRef message, lldb::Severity severity, DiagnosticOrigin origin, uint32_t compiler_id=LLDB_INVALID_COMPILER_ID)
SourceLanguage GetLanguage() const
Definition Target.h:352
bool InvokeCancelCallback(lldb::ExpressionEvaluationPhase phase) const
Definition Target.h:458
ExecutionPolicy GetExecutionPolicy() const
Definition Target.h:346
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
ExecutionContextScope * GetBestExecutionContextScope() const
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
const lldb::ProcessSP & GetProcessSP() const
Get accessor to get the process shared pointer.
StackFrame * GetFramePtr() const
Returns a pointer to the frame object.
const lldb::StackFrameSP & GetFrameSP() const
Get accessor to get the frame shared pointer.
Target * GetTargetPtr() const
Returns a pointer to the target object.
const lldb::ThreadSP & GetThreadSP() const
Get accessor to get the thread shared pointer.
Process * GetProcessPtr() const
Returns a pointer to the process object.
lldb::ProcessWP m_jit_process_wp
Expression's always have to have a target...
Definition Expression.h:89
Expression(Target &target)
A plug-in interface definition class for debugging a process.
Definition Process.h:355
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1259
bool CanJIT()
Determines whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2582
A Progress indicator helper class.
Definition Progress.h:60
This base class provides an interface to stack frames.
Definition StackFrame.h:44
An error handling class.
Definition Status.h:118
void Clear()
Clear the object state.
Definition Status.cpp:214
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
bool GetEnableNotifyAboutFixIts() const
Definition Target.cpp:4930
SourceLanguage GetLanguage() const
Definition Target.cpp:5049
Debugger & GetDebugger() const
Definition Target.h:1240
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition Target.cpp:2672
UserExpression * GetUserExpressionForLanguage(llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language, Expression::ResultType desired_type, const EvaluateExpressionOptions &options, ValueObject *ctx_obj, Status &error)
Definition Target.cpp:2692
Address m_address
The address the process is stopped in.
~UserExpression() override
Destructor.
static lldb::ValueObjectSP GetObjectPointerValueObject(lldb::StackFrameSP frame, llvm::StringRef object_name, Status &err)
Return ValueObject for a given variable name in the current stack frame.
SourceLanguage m_language
The language to use when parsing (unknown means use defaults).
virtual lldb::ExpressionResults DoExecute(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, lldb::UserExpressionSP &shared_ptr_to_me, lldb::ExpressionVariableSP &result)=0
ResultType m_desired_type
The type to coerce the expression's result to.
static lldb::ExpressionResults Evaluate(ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, llvm::StringRef expr_cstr, llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp, std::string *fixed_expression=nullptr, ValueObject *ctx_obj=nullptr)
Evaluate one expression in the scratch context of the target passed in the exe_ctx and return its res...
void InstallContext(ExecutionContext &exe_ctx)
Populate m_in_cplusplus_method and m_in_objectivec_method based on the environment.
std::string m_expr_prefix
The text of the translation-level definitions, as provided by the user.
static const Status::ValueType kNoResult
ValueObject::GetError() returns this if there is no result from the expression.
std::string m_expr_text
The text of the expression, as typed by the user.
EvaluateExpressionOptions m_options
Additional options provided by the user.
bool LockAndCheckContext(ExecutionContext &exe_ctx, lldb::TargetSP &target_sp, lldb::ProcessSP &process_sp, lldb::StackFrameSP &frame_sp)
bool MatchesContext(ExecutionContext &exe_ctx)
static lldb::addr_t GetObjectPointer(lldb::StackFrameSP frame_sp, llvm::StringRef object_name, Status &err)
lldb::ExpressionResults Execute(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, lldb::UserExpressionSP &shared_ptr_to_me, lldb::ExpressionVariableSP &result)
Execute the parsed expression by callinng the derived class's DoExecute method.
UserExpression(ExecutionContextScope &exe_scope, llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language, ResultType desired_type, const EvaluateExpressionOptions &options)
Constructor.
static char ID
LLVM RTTI support.
static lldb::ValueObjectSP Create(ExecutionContextScope *exe_scope, lldb::ByteOrder byte_order, uint32_t addr_byte_size, lldb::addr_t address=LLDB_INVALID_ADDRESS)
uint32_t GetTypeInfo(CompilerType *pointee_or_element_compiler_type=nullptr)
virtual lldb::ValueObjectSP Dereference(Status &error)
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:327
ExecutionPolicy
Expression execution policies.
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition State.cpp:14
@ eExpressionEvaluationComplete
@ eExpressionEvaluationParse
@ eExpressionEvaluationExecution
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::ExpressionVariable > ExpressionVariableSP
@ eStateStopped
Process or thread is stopped and can be examined.
@ eErrorTypeGeneric
Generic errors that can be any value.
std::shared_ptr< lldb_private::UserExpression > UserExpressionSP
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eExpressionInterrupted
@ eExpressionParseError
@ eExpressionSetupError
std::shared_ptr< lldb_private::Process > ProcessSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
A type-erased pair of llvm::dwarf::SourceLanguageName and version.
lldb::LanguageType AsLanguageType() const
Definition Language.cpp:614