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/Policy.h"
42#include "lldb/Utility/State.h"
46#include "llvm/BinaryFormat/Dwarf.h"
47
48using namespace lldb_private;
49
51
53 llvm::StringRef expr, llvm::StringRef prefix,
54 SourceLanguage language, ResultType desired_type,
55 const EvaluateExpressionOptions &options)
56 : Expression(exe_scope), m_expr_text(std::string(expr)),
57 m_expr_prefix(std::string(prefix)), m_language(language),
58 m_desired_type(desired_type), m_options(options) {}
59
61
64
65 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
66
67 if (frame_sp)
68 m_address = frame_sp->GetFrameCodeAddress();
69}
70
72 lldb::TargetSP &target_sp,
73 lldb::ProcessSP &process_sp,
74 lldb::StackFrameSP &frame_sp) {
75 lldb::ProcessSP expected_process_sp = m_jit_process_wp.lock();
76 process_sp = exe_ctx.GetProcessSP();
77
78 if (process_sp != expected_process_sp)
79 return false;
80
81 process_sp = exe_ctx.GetProcessSP();
82 target_sp = exe_ctx.GetTargetSP();
83 frame_sp = exe_ctx.GetFrameSP();
84
85 if (m_address.IsValid()) {
86 if (!frame_sp)
87 return false;
89 frame_sp->GetFrameCodeAddress(),
90 target_sp.get()) == 0);
91 }
92
93 return true;
94}
95
97 lldb::TargetSP target_sp;
98 lldb::ProcessSP process_sp;
99 lldb::StackFrameSP frame_sp;
100
101 return LockAndCheckContext(exe_ctx, target_sp, process_sp, frame_sp);
102}
103
105 lldb::StackFrameSP frame_sp, llvm::StringRef object_name, Status &err) {
106 err.Clear();
107
108 if (!frame_sp) {
110 "Couldn't load '{0}' because the context is incomplete", object_name);
111 return {};
112 }
113
114 if (auto var_list_sp = frame_sp->GetInScopeVariableList(false))
115 if (auto var_sp =
116 var_list_sp->FindVariable(ConstString(object_name), false))
117 return frame_sp->GetValueObjectForFrameVariable(var_sp,
119
120 return {};
121}
122
124 llvm::StringRef object_name,
125 Status &err) {
126 auto valobj_sp =
127 GetObjectPointerValueObject(std::move(frame_sp), object_name, err);
128
129 if (!err.Success() || !valobj_sp.get())
131
132 lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
133
134 if (ret == LLDB_INVALID_ADDRESS) {
136 "Couldn't load '{0}' because its value couldn't be evaluated",
137 object_name);
139 }
140
141 return ret;
142}
143
146 const EvaluateExpressionOptions &options,
147 llvm::StringRef expr, llvm::StringRef prefix,
148 lldb::ValueObjectSP &result_valobj_sp,
149 std::string *fixed_expression, ValueObject *ctx_obj) {
151 auto set_error = [&](Status error) {
152 result_valobj_sp = ValueObjectConstResult::Create(
153 exe_ctx.GetBestExecutionContextScope(), std::move(error));
154 };
155
156 if (!PolicyStack::Get().Current().capabilities.can_evaluate_expressions) {
157 LLDB_LOG(log, "== [UserExpression::Evaluate] The current policy doesn't "
158 "allow evaluating expressions ==");
159 set_error(Status::FromErrorString(
160 "expression evaluation is not allowed in this context"));
162 }
163
164 if (ctx_obj) {
165 static unsigned const ctx_type_mask = lldb::TypeFlags::eTypeIsClass |
166 lldb::TypeFlags::eTypeIsStructUnion |
167 lldb::TypeFlags::eTypeIsReference;
168 if (!(ctx_obj->GetTypeInfo() & ctx_type_mask)) {
169 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
170 "an invalid type, can't run expressions.");
171 set_error(Status("a context object of an invalid type passed"));
173 }
174 }
175
176 if (ctx_obj && ctx_obj->GetTypeInfo() & lldb::TypeFlags::eTypeIsReference) {
178 lldb::ValueObjectSP deref_ctx_sp = ctx_obj->Dereference(error);
179 if (!error.Success()) {
180 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
181 "a reference type that can't be dereferenced, can't run "
182 "expressions.");
183 set_error(Status(
184 "passed context object of an reference type cannot be deferenced"));
186 }
187
188 ctx_obj = deref_ctx_sp.get();
189 }
190
191 lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy();
192 SourceLanguage language = options.GetLanguage();
193 const ResultType desired_type = options.DoesCoerceToId()
196 Target *target = exe_ctx.GetTargetPtr();
197 if (!target) {
198 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a NULL target, can't "
199 "run expressions.");
200 set_error(Status("expression passed a null target"));
202 }
203
204 Process *process = exe_ctx.GetProcessPtr();
205
206 if (!process && execution_policy == eExecutionPolicyAlways) {
207 LLDB_LOG(log, "== [UserExpression::Evaluate] No process, but the policy is "
208 "eExecutionPolicyAlways");
209
210 set_error(Status("expression needed to run but couldn't: no process"));
211
213 }
214
215 // Since we might need to allocate memory, we need to be stopped to run
216 // an expression.
217 if (process && process->GetState() != lldb::eStateStopped) {
219 "unable to evaluate expression while the process is {0}: the process "
220 "must be stopped because the expression might require allocating "
221 "memory.",
222 StateAsCString(process->GetState())));
224 }
225
226 // Explicitly force the IR interpreter to evaluate the expression when the
227 // there is no process that supports running the expression for us. Don't
228 // change the execution policy if we have the special top-level policy that
229 // doesn't contain any expression and there is nothing to interpret.
230 if (execution_policy != eExecutionPolicyTopLevel &&
231 (process == nullptr || !process->CanJIT()))
232 execution_policy = eExecutionPolicyNever;
233
234 // We need to set the expression execution thread here, turns out parse can
235 // call functions in the process of looking up symbols, which will escape the
236 // context set by exe_ctx passed to Execute.
237 lldb::ThreadSP thread_sp = exe_ctx.GetThreadSP();
238 ThreadList::ExpressionExecutionThreadPusher execution_thread_pusher(
239 thread_sp);
240
241 llvm::StringRef full_prefix;
242 llvm::StringRef option_prefix(options.GetPrefix());
243 std::string full_prefix_storage;
244 if (!prefix.empty() && !option_prefix.empty()) {
245 full_prefix_storage = std::string(prefix);
246 full_prefix_storage.append(std::string(option_prefix));
247 full_prefix = full_prefix_storage;
248 } else if (!prefix.empty())
249 full_prefix = prefix;
250 else
251 full_prefix = option_prefix;
252
253 // If the language was not specified in the expression command, set it to the
254 // language in the target's properties if specified, else default to the
255 // langage for the frame.
256 if (!language) {
257 if (target->GetLanguage())
258 language = target->GetLanguage();
259 else if (StackFrame *frame = exe_ctx.GetFramePtr())
260 language = frame->GetLanguage();
261 }
262
264 lldb::UserExpressionSP user_expression_sp(
266 expr, full_prefix, language, desired_type, options, ctx_obj, error));
267 if (error.Fail() || !user_expression_sp) {
268 LLDB_LOG(log, "== [UserExpression::Evaluate] Getting expression: {0} ==",
269 error.AsCString());
270 set_error(std::move(error));
272 }
273
274 LLDB_LOG(log, "== [UserExpression::Evaluate] Parsing expression {0} ==",
275 expr.str());
276
277 const bool keep_expression_in_memory = true;
278 const bool generate_debug_info = options.GetGenerateDebugInfo();
279
281 set_error(Status("expression interrupted by callback before parse"));
283 }
284
285 DiagnosticManager diagnostic_manager;
286
287 bool parse_success =
288 user_expression_sp->Parse(diagnostic_manager, exe_ctx, execution_policy,
289 keep_expression_in_memory, generate_debug_info);
290
291 // Calculate the fixed expression always, since we need it for errors.
292 std::string tmp_fixed_expression;
293 if (fixed_expression == nullptr)
294 fixed_expression = &tmp_fixed_expression;
295
296 *fixed_expression = user_expression_sp->GetFixedText().str();
298
299 // If there is a fixed expression, try to parse it:
300 if (!parse_success) {
301 execution_results = lldb::eExpressionParseError;
302 if (!fixed_expression->empty() && options.GetAutoApplyFixIts()) {
303 const uint64_t max_fix_retries = options.GetRetriesWithFixIts();
304 for (uint64_t i = 0; i < max_fix_retries; ++i) {
305 // Try parsing the fixed expression.
306 user_expression_sp.reset(target->GetUserExpressionForLanguage(
307 fixed_expression->c_str(), full_prefix, language, desired_type,
308 options, ctx_obj, error));
309 if (!user_expression_sp)
310 break;
311
312 DiagnosticManager fixed_diagnostic_manager;
313 parse_success = user_expression_sp->Parse(
314 fixed_diagnostic_manager, exe_ctx, execution_policy,
315 keep_expression_in_memory, generate_debug_info);
316 if (parse_success) {
317 diagnostic_manager.Clear();
318 break;
319 }
320 // The fixed expression also didn't parse. Let's check for any new
321 // fixits we could try.
322 if (!user_expression_sp->GetFixedText().empty()) {
323 *fixed_expression = user_expression_sp->GetFixedText().str();
324 } else {
325 // Fixed expression didn't compile without a fixit, don't retry and
326 // don't tell the user about it.
327 fixed_expression->clear();
328 break;
329 }
330 }
331 }
332
333 if (!parse_success) {
334 if (user_expression_sp)
335 user_expression_sp->FixupParseErrorDiagnostics(diagnostic_manager);
336
337 if (target->GetEnableNotifyAboutFixIts() && fixed_expression &&
338 !fixed_expression->empty()) {
339 std::string fixit =
340 "fixed expression suggested:\n " + *fixed_expression;
341 diagnostic_manager.AddDiagnostic(fixit, lldb::eSeverityInfo,
343 }
344 if (diagnostic_manager.Diagnostics().empty())
345 error = Status::FromError(llvm::make_error<ExpressionError>(
346 execution_results,
347 "expression failed to parse (no further compiler diagnostics)"));
348 else
349 error =
350 Status::FromError(diagnostic_manager.GetAsError(execution_results));
351 }
352 }
353
354 if (parse_success) {
355 lldb::ExpressionVariableSP expr_result;
356
357 if (execution_policy == eExecutionPolicyNever &&
358 !user_expression_sp->CanInterpret()) {
359 LLDB_LOG(log, "== [UserExpression::Evaluate] Expression may not run, but "
360 "is not constant ==");
361
362 if (diagnostic_manager.Diagnostics().empty())
363 error = Status::FromError(llvm::make_error<ExpressionError>(
365 "expression needed to run but couldn't"));
366 } else if (execution_policy == eExecutionPolicyTopLevel) {
369 } else {
371 set_error(Status::FromError(llvm::make_error<ExpressionError>(
373 "expression interrupted by callback before execution")));
375 }
376
377 diagnostic_manager.Clear();
378
379 LLDB_LOG(log, "== [UserExpression::Evaluate] Executing expression ==");
380
381 execution_results =
382 user_expression_sp->Execute(diagnostic_manager, exe_ctx, options,
383 user_expression_sp, expr_result);
384
385 if (execution_results != lldb::eExpressionCompleted) {
386 LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
387 "abnormally ==");
388
389 if (diagnostic_manager.Diagnostics().empty())
390 error = Status::FromError(llvm::make_error<ExpressionError>(
391 execution_results,
392 "expression failed to execute, unknown error"));
393 else
395 diagnostic_manager.GetAsError(execution_results));
396 } else {
397 if (expr_result) {
398 result_valobj_sp = expr_result->GetValueObject();
399 result_valobj_sp->SetPreferredDisplayLanguage(
400 language.AsLanguageType());
401
402 LLDB_LOG(log,
403 "== [UserExpression::Evaluate] Execution completed "
404 "normally with result {0} ==",
405 result_valobj_sp->GetValueAsCString());
406 } else {
407 LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
408 "normally with no result ==");
409
411 }
412 }
413 }
414 }
415
417 set_error(Status::FromError(llvm::make_error<ExpressionError>(
419 "expression interrupted by callback after complete")));
421 }
422
423 if (error.Fail())
424 set_error(std::move(error));
425 return execution_results;
426}
427
430 ExecutionContext &exe_ctx,
431 const EvaluateExpressionOptions &options,
432 lldb::UserExpressionSP &shared_ptr_to_me,
433 lldb::ExpressionVariableSP &result_var) {
434 Debugger *debugger =
435 exe_ctx.GetTargetPtr() ? &exe_ctx.GetTargetPtr()->GetDebugger() : nullptr;
436
437 Progress progress("Running expression",
438 m_options.IsForUtilityExpr() ? "LLDB utility" : m_expr_text,
439 {}, debugger);
440
442 diagnostic_manager, exe_ctx, options, shared_ptr_to_me, result_var);
443 Target *target = exe_ctx.GetTargetPtr();
444 if (options.GetSuppressPersistentResult() && result_var && target) {
445 if (auto *persistent_state =
447 m_language.AsLanguageType()))
448 persistent_state->RemovePersistentVariable(result_var);
449 }
450 return expr_result;
451}
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:375
static int CompareLoadAddress(const Address &lhs, const Address &rhs, Target *target)
Definition Address.cpp:930
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:369
bool InvokeCancelCallback(lldb::ExpressionEvaluationPhase phase) const
Definition Target.h:479
ExecutionPolicy GetExecutionPolicy() const
Definition Target.h:363
"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)
static PolicyStack & Get()
Definition Policy.cpp:21
A plug-in interface definition class for debugging a process.
Definition Process.h:368
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1315
bool CanJIT()
Determines whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2758
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 FromErrorString(const char *str)
Definition Status.h:141
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:5612
SourceLanguage GetLanguage() const
Definition Target.cpp:5737
Debugger & GetDebugger() const
Definition Target.h:1356
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition Target.cpp:2807
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:2827
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, ValueObjectManager *manager=nullptr)
These routines create ValueObjectConstResult ValueObjects from various data sources.
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:338
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:628