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"
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"
39#include "lldb/Utility/Log.h"
40#include "lldb/Utility/State.h"
42
43using namespace lldb_private;
44
46
48 llvm::StringRef expr, llvm::StringRef prefix,
49 lldb::LanguageType language,
50 ResultType desired_type,
51 const EvaluateExpressionOptions &options)
52 : Expression(exe_scope), m_expr_text(std::string(expr)),
53 m_expr_prefix(std::string(prefix)), m_language(language),
54 m_desired_type(desired_type), m_options(options) {}
55
57
60
61 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
62
63 if (frame_sp)
64 m_address = frame_sp->GetFrameCodeAddress();
65}
66
68 lldb::TargetSP &target_sp,
69 lldb::ProcessSP &process_sp,
70 lldb::StackFrameSP &frame_sp) {
71 lldb::ProcessSP expected_process_sp = m_jit_process_wp.lock();
72 process_sp = exe_ctx.GetProcessSP();
73
74 if (process_sp != expected_process_sp)
75 return false;
76
77 process_sp = exe_ctx.GetProcessSP();
78 target_sp = exe_ctx.GetTargetSP();
79 frame_sp = exe_ctx.GetFrameSP();
80
81 if (m_address.IsValid()) {
82 if (!frame_sp)
83 return false;
85 frame_sp->GetFrameCodeAddress(),
86 target_sp.get()) == 0);
87 }
88
89 return true;
90}
91
93 lldb::TargetSP target_sp;
94 lldb::ProcessSP process_sp;
95 lldb::StackFrameSP frame_sp;
96
97 return LockAndCheckContext(exe_ctx, target_sp, process_sp, frame_sp);
98}
99
101 lldb::StackFrameSP frame_sp, llvm::StringRef object_name, Status &err) {
102 err.Clear();
103
104 if (!frame_sp) {
106 "Couldn't load '{0}' because the context is incomplete", object_name);
107 return {};
108 }
109
110 lldb::VariableSP var_sp;
111 lldb::ValueObjectSP valobj_sp;
112
113 return frame_sp->GetValueForVariableExpressionPath(
114 object_name, lldb::eNoDynamicValues,
119 var_sp, err);
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, Status &error,
148 std::string *fixed_expression, ValueObject *ctx_obj) {
150
151 if (ctx_obj) {
152 static unsigned const ctx_type_mask = lldb::TypeFlags::eTypeIsClass |
153 lldb::TypeFlags::eTypeIsStructUnion |
154 lldb::TypeFlags::eTypeIsReference;
155 if (!(ctx_obj->GetTypeInfo() & ctx_type_mask)) {
156 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
157 "an invalid type, can't run expressions.");
158 error.SetErrorString("a context object of an invalid type passed");
160 }
161 }
162
163 if (ctx_obj && ctx_obj->GetTypeInfo() & lldb::TypeFlags::eTypeIsReference) {
165 lldb::ValueObjectSP deref_ctx_sp = ctx_obj->Dereference(error);
166 if (!error.Success()) {
167 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
168 "a reference type that can't be dereferenced, can't run "
169 "expressions.");
170 error.SetErrorString(
171 "passed context object of an reference type cannot be deferenced");
173 }
174
175 ctx_obj = deref_ctx_sp.get();
176 }
177
178 lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy();
179 lldb::LanguageType language = options.GetLanguage();
180 const ResultType desired_type = options.DoesCoerceToId()
184
185 Target *target = exe_ctx.GetTargetPtr();
186 if (!target) {
187 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a NULL target, can't "
188 "run expressions.");
189 error.SetErrorString("expression passed a null target");
191 }
192
193 Process *process = exe_ctx.GetProcessPtr();
194
195 if (process == nullptr && execution_policy == eExecutionPolicyAlways) {
196 LLDB_LOG(log, "== [UserExpression::Evaluate] No process, but the policy is "
197 "eExecutionPolicyAlways");
198
199 error.SetErrorString("expression needed to run but couldn't: no process");
200
201 return execution_results;
202 }
203
204 // Since we might need to allocate memory, we need to be stopped to run
205 // an expression.
206 if (process != nullptr && process->GetState() != lldb::eStateStopped) {
207 error.SetErrorStringWithFormatv(
208 "unable to evaluate expression while the process is {0}: the process "
209 "must be stopped because the expression might require allocating "
210 "memory.",
211 StateAsCString(process->GetState()));
212 return execution_results;
213 }
214
215 // Explicitly force the IR interpreter to evaluate the expression when the
216 // there is no process that supports running the expression for us. Don't
217 // change the execution policy if we have the special top-level policy that
218 // doesn't contain any expression and there is nothing to interpret.
219 if (execution_policy != eExecutionPolicyTopLevel &&
220 (process == nullptr || !process->CanJIT()))
221 execution_policy = eExecutionPolicyNever;
222
223 // We need to set the expression execution thread here, turns out parse can
224 // call functions in the process of looking up symbols, which will escape the
225 // context set by exe_ctx passed to Execute.
226 lldb::ThreadSP thread_sp = exe_ctx.GetThreadSP();
227 ThreadList::ExpressionExecutionThreadPusher execution_thread_pusher(
228 thread_sp);
229
230 llvm::StringRef full_prefix;
231 llvm::StringRef option_prefix(options.GetPrefix());
232 std::string full_prefix_storage;
233 if (!prefix.empty() && !option_prefix.empty()) {
234 full_prefix_storage = std::string(prefix);
235 full_prefix_storage.append(std::string(option_prefix));
236 full_prefix = full_prefix_storage;
237 } else if (!prefix.empty())
238 full_prefix = prefix;
239 else
240 full_prefix = option_prefix;
241
242 // If the language was not specified in the expression command, set it to the
243 // language in the target's properties if specified, else default to the
244 // langage for the frame.
245 if (language == lldb::eLanguageTypeUnknown) {
247 language = target->GetLanguage();
248 else if (StackFrame *frame = exe_ctx.GetFramePtr())
249 language = frame->GetLanguage();
250 }
251
252 lldb::UserExpressionSP user_expression_sp(
253 target->GetUserExpressionForLanguage(expr, full_prefix, language,
254 desired_type, options, ctx_obj,
255 error));
256 if (error.Fail() || !user_expression_sp) {
257 LLDB_LOG(log, "== [UserExpression::Evaluate] Getting expression: {0} ==",
258 error.AsCString());
260 }
261
262 LLDB_LOG(log, "== [UserExpression::Evaluate] Parsing expression {0} ==",
263 expr.str());
264
265 const bool keep_expression_in_memory = true;
266 const bool generate_debug_info = options.GetGenerateDebugInfo();
267
269 error.SetErrorString("expression interrupted by callback before parse");
270 result_valobj_sp = ValueObjectConstResult::Create(
273 }
274
275 DiagnosticManager diagnostic_manager;
276
277 bool parse_success =
278 user_expression_sp->Parse(diagnostic_manager, exe_ctx, execution_policy,
279 keep_expression_in_memory, generate_debug_info);
280
281 // Calculate the fixed expression always, since we need it for errors.
282 std::string tmp_fixed_expression;
283 if (fixed_expression == nullptr)
284 fixed_expression = &tmp_fixed_expression;
285
286 *fixed_expression = user_expression_sp->GetFixedText().str();
287
288 // If there is a fixed expression, try to parse it:
289 if (!parse_success) {
290 // Delete the expression that failed to parse before attempting to parse
291 // the next expression.
292 user_expression_sp.reset();
293
294 execution_results = lldb::eExpressionParseError;
295 if (!fixed_expression->empty() && options.GetAutoApplyFixIts()) {
296 const uint64_t max_fix_retries = options.GetRetriesWithFixIts();
297 for (uint64_t i = 0; i < max_fix_retries; ++i) {
298 // Try parsing the fixed expression.
299 lldb::UserExpressionSP fixed_expression_sp(
301 fixed_expression->c_str(), full_prefix, language, desired_type,
302 options, ctx_obj, error));
303 DiagnosticManager fixed_diagnostic_manager;
304 parse_success = fixed_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 user_expression_sp = fixed_expression_sp;
310 break;
311 } else {
312 // The fixed expression also didn't parse. Let's check for any new
313 // Fix-Its we could try.
314 if (!fixed_expression_sp->GetFixedText().empty()) {
315 *fixed_expression = fixed_expression_sp->GetFixedText().str();
316 } else {
317 // Fixed expression didn't compile without a fixit, don't retry and
318 // don't tell the user about it.
319 fixed_expression->clear();
320 break;
321 }
322 }
323 }
324 }
325
326 if (!parse_success) {
327 std::string msg;
328 {
329 llvm::raw_string_ostream os(msg);
330 if (!diagnostic_manager.Diagnostics().empty())
331 os << diagnostic_manager.GetString();
332 else
333 os << "expression failed to parse (no further compiler diagnostics)";
334 if (target->GetEnableNotifyAboutFixIts() && fixed_expression &&
335 !fixed_expression->empty())
336 os << "\nfixed expression suggested:\n " << *fixed_expression;
337 }
338 error.SetExpressionError(execution_results, msg.c_str());
339 }
340 }
341
342 if (parse_success) {
343 lldb::ExpressionVariableSP expr_result;
344
345 if (execution_policy == eExecutionPolicyNever &&
346 !user_expression_sp->CanInterpret()) {
347 LLDB_LOG(log, "== [UserExpression::Evaluate] Expression may not run, but "
348 "is not constant ==");
349
350 if (!diagnostic_manager.Diagnostics().size())
351 error.SetExpressionError(lldb::eExpressionSetupError,
352 "expression needed to run but couldn't");
353 } else if (execution_policy == eExecutionPolicyTopLevel) {
356 } else {
358 error.SetExpressionError(
360 "expression interrupted by callback before execution");
361 result_valobj_sp = ValueObjectConstResult::Create(
364 }
365
366 diagnostic_manager.Clear();
367
368 LLDB_LOG(log, "== [UserExpression::Evaluate] Executing expression ==");
369
370 execution_results =
371 user_expression_sp->Execute(diagnostic_manager, exe_ctx, options,
372 user_expression_sp, expr_result);
373
374 if (execution_results != lldb::eExpressionCompleted) {
375 LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
376 "abnormally ==");
377
378 if (!diagnostic_manager.Diagnostics().size())
379 error.SetExpressionError(
380 execution_results, "expression failed to execute, unknown error");
381 else
382 error.SetExpressionError(execution_results,
383 diagnostic_manager.GetString().c_str());
384 } else {
385 if (expr_result) {
386 result_valobj_sp = expr_result->GetValueObject();
387 result_valobj_sp->SetPreferredDisplayLanguage(language);
388
389 LLDB_LOG(log,
390 "== [UserExpression::Evaluate] Execution completed "
391 "normally with result {0} ==",
392 result_valobj_sp->GetValueAsCString());
393 } else {
394 LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
395 "normally with no result ==");
396
398 }
399 }
400 }
401 }
402
404 error.SetExpressionError(
406 "expression interrupted by callback after complete");
408 }
409
410 if (result_valobj_sp.get() == nullptr) {
411 result_valobj_sp = ValueObjectConstResult::Create(
413 }
414
415 return execution_results;
416}
417
420 ExecutionContext &exe_ctx,
421 const EvaluateExpressionOptions &options,
422 lldb::UserExpressionSP &shared_ptr_to_me,
423 lldb::ExpressionVariableSP &result_var) {
425 diagnostic_manager, exe_ctx, options, shared_ptr_to_me, result_var);
426 Target *target = exe_ctx.GetTargetPtr();
427 if (options.GetSuppressPersistentResult() && result_var && target) {
428 if (auto *persistent_state =
430 persistent_state->RemovePersistentVariable(result_var);
431 }
432 return expr_result;
433}
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:342
static int CompareLoadAddress(const Address &lhs, const Address &rhs, Target *target)
Definition: Address.cpp:941
bool IsValid() const
Check if the object state is valid.
Definition: Address.h:355
std::string GetString(char separator='\n')
const DiagnosticList & Diagnostics()
const char * GetPrefix() const
Definition: Target.h:319
uint64_t GetRetriesWithFixIts() const
Definition: Target.h:440
bool InvokeCancelCallback(lldb::ExpressionEvaluationPhase phase) const
Definition: Target.h:402
ExecutionPolicy GetExecutionPolicy() const
Definition: Target.h:307
lldb::LanguageType GetLanguage() const
Definition: Target.h:313
"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.
Encapsulates a single expression for use in lldb.
Definition: Expression.h:31
lldb::ProcessWP m_jit_process_wp
Expression's always have to have a target...
Definition: Expression.h:91
A plug-in interface definition class for debugging a process.
Definition: Process.h:341
lldb::StateType GetState()
Get accessor for the current process state.
Definition: Process.cpp:1301
bool CanJIT()
Determines whether executing JIT-compiled code in this process is possible.
Definition: Process.cpp:2313
This base class provides an interface to stack frames.
Definition: StackFrame.h:42
@ eExpressionPathOptionsNoSyntheticArrayRange
Definition: StackFrame.h:48
@ eExpressionPathOptionsNoSyntheticChildren
Definition: StackFrame.h:47
An error handling class.
Definition: Status.h:44
void SetErrorStringWithFormatv(const char *format, Args &&... args)
Definition: Status.h:169
void Clear()
Clear the object state.
Definition: Status.cpp:167
bool Success() const
Test for success condition.
Definition: Status.cpp:279
bool GetEnableNotifyAboutFixIts() const
Definition: Target.cpp:4530
lldb::LanguageType GetLanguage() const
Definition: Target.cpp:4649
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition: Target.cpp:2486
UserExpression * GetUserExpressionForLanguage(llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, Expression::ResultType desired_type, const EvaluateExpressionOptions &options, ValueObject *ctx_obj, Status &error)
Definition: Target.cpp:2506
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.
virtual lldb::ExpressionResults DoExecute(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, lldb::UserExpressionSP &shared_ptr_to_me, lldb::ExpressionVariableSP &result)=0
void InstallContext(ExecutionContext &exe_ctx)
Populate m_in_cplusplus_method and m_in_objectivec_method based on the environment.
UserExpression(ExecutionContextScope &exe_scope, llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, ResultType desired_type, const EvaluateExpressionOptions &options)
Constructor.
static const Status::ValueType kNoResult
ValueObject::GetError() returns this if there is no result from the expression.
static lldb::ExpressionResults Evaluate(ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, llvm::StringRef expr_cstr, llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp, Status &error, 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...
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::LanguageType m_language
The language to use when parsing (eLanguageTypeUnknown means use defaults)
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.
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)
Definition: ValueObject.h:378
virtual lldb::ValueObjectSP Dereference(Status &error)
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:314
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
Definition: lldb-forward.h:412
std::shared_ptr< lldb_private::Thread > ThreadSP
Definition: lldb-forward.h:438
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Definition: lldb-forward.h:472
std::shared_ptr< lldb_private::ExpressionVariable > ExpressionVariableSP
Definition: lldb-forward.h:343
@ eStateStopped
Process or thread is stopped and can be examined.
LanguageType
Programming language type.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eErrorTypeGeneric
Generic errors that can be any value.
std::shared_ptr< lldb_private::UserExpression > UserExpressionSP
Definition: lldb-forward.h:324
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eExpressionInterrupted
@ eExpressionParseError
@ eExpressionSetupError
std::shared_ptr< lldb_private::Process > ProcessSP
Definition: lldb-forward.h:381
std::shared_ptr< lldb_private::Variable > VariableSP
Definition: lldb-forward.h:474
uint64_t addr_t
Definition: lldb-types.h:79
std::shared_ptr< lldb_private::Target > TargetSP
Definition: lldb-forward.h:436
@ eNoDynamicValues