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"
25#include "lldb/Host/HostInfo.h"
26#include "lldb/Symbol/Block.h"
30#include "lldb/Symbol/Type.h"
34#include "lldb/Target/Process.h"
36#include "lldb/Target/Target.h"
41#include "lldb/Utility/Log.h"
43
44using namespace lldb_private;
45
47
49 llvm::StringRef expr, llvm::StringRef prefix,
50 lldb::LanguageType language,
51 ResultType desired_type,
52 const EvaluateExpressionOptions &options)
53 : Expression(exe_scope), m_expr_text(std::string(expr)),
54 m_expr_prefix(std::string(prefix)), m_language(language),
55 m_desired_type(desired_type), m_options(options) {}
56
58
61
62 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
63
64 if (frame_sp)
65 m_address = frame_sp->GetFrameCodeAddress();
66}
67
69 lldb::TargetSP &target_sp,
70 lldb::ProcessSP &process_sp,
71 lldb::StackFrameSP &frame_sp) {
72 lldb::ProcessSP expected_process_sp = m_jit_process_wp.lock();
73 process_sp = exe_ctx.GetProcessSP();
74
75 if (process_sp != expected_process_sp)
76 return false;
77
78 process_sp = exe_ctx.GetProcessSP();
79 target_sp = exe_ctx.GetTargetSP();
80 frame_sp = exe_ctx.GetFrameSP();
81
82 if (m_address.IsValid()) {
83 if (!frame_sp)
84 return false;
86 frame_sp->GetFrameCodeAddress(),
87 target_sp.get()) == 0);
88 }
89
90 return true;
91}
92
94 lldb::TargetSP target_sp;
95 lldb::ProcessSP process_sp;
96 lldb::StackFrameSP frame_sp;
97
98 return LockAndCheckContext(exe_ctx, target_sp, process_sp, frame_sp);
99}
100
102 lldb::StackFrameSP frame_sp, ConstString const &object_name, Status &err) {
103 err.Clear();
104
105 if (!frame_sp) {
107 "Couldn't load '%s' because the context is incomplete",
108 object_name.AsCString());
109 return {};
110 }
111
112 lldb::VariableSP var_sp;
113 lldb::ValueObjectSP valobj_sp;
114
115 return frame_sp->GetValueForVariableExpressionPath(
121 var_sp, err);
122}
123
125 ConstString &object_name,
126 Status &err) {
127 auto valobj_sp =
128 GetObjectPointerValueObject(std::move(frame_sp), object_name, err);
129
130 if (!err.Success() || !valobj_sp.get())
132
133 lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
134
135 if (ret == LLDB_INVALID_ADDRESS) {
137 "Couldn't load '%s' because its value couldn't be evaluated",
138 object_name.AsCString());
140 }
141
142 return ret;
143}
144
147 const EvaluateExpressionOptions &options,
148 llvm::StringRef expr, llvm::StringRef prefix,
149 lldb::ValueObjectSP &result_valobj_sp, Status &error,
150 std::string *fixed_expression, ValueObject *ctx_obj) {
152
153 if (ctx_obj) {
154 static unsigned const ctx_type_mask = lldb::TypeFlags::eTypeIsClass |
155 lldb::TypeFlags::eTypeIsStructUnion |
156 lldb::TypeFlags::eTypeIsReference;
157 if (!(ctx_obj->GetTypeInfo() & ctx_type_mask)) {
158 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
159 "an invalid type, can't run expressions.");
160 error.SetErrorString("a context object of an invalid type passed");
162 }
163 }
164
165 if (ctx_obj && ctx_obj->GetTypeInfo() & lldb::TypeFlags::eTypeIsReference) {
167 lldb::ValueObjectSP deref_ctx_sp = ctx_obj->Dereference(error);
168 if (!error.Success()) {
169 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
170 "a reference type that can't be dereferenced, can't run "
171 "expressions.");
172 error.SetErrorString(
173 "passed context object of an reference type cannot be deferenced");
175 }
176
177 ctx_obj = deref_ctx_sp.get();
178 }
179
180 lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy();
181 lldb::LanguageType language = options.GetLanguage();
182 const ResultType desired_type = options.DoesCoerceToId()
186
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 error.SetErrorString("expression passed a null target");
193 }
194
195 Process *process = exe_ctx.GetProcessPtr();
196
197 if (process == nullptr && execution_policy == eExecutionPolicyAlways) {
198 LLDB_LOG(log, "== [UserExpression::Evaluate] No process, but the policy is "
199 "eExecutionPolicyAlways");
200
201 error.SetErrorString("expression needed to run but couldn't: no process");
202
203 return execution_results;
204 }
205 // Since we might need to call allocate memory and maybe call code to make
206 // the caller, we need to be stopped.
207 if (process != nullptr && process->GetState() != lldb::eStateStopped) {
208 error.SetErrorString("Can't make a function caller while the process is "
209 "running");
210 return execution_results;
211 }
212
213
214 // Explicitly force the IR interpreter to evaluate the expression when the
215 // there is no process that supports running the expression for us. Don't
216 // change the execution policy if we have the special top-level policy that
217 // doesn't contain any expression and there is nothing to interpret.
218 if (execution_policy != eExecutionPolicyTopLevel &&
219 (process == nullptr || !process->CanJIT()))
220 execution_policy = eExecutionPolicyNever;
221
222 // We need to set the expression execution thread here, turns out parse can
223 // call functions in the process of looking up symbols, which will escape the
224 // context set by exe_ctx passed to Execute.
225 lldb::ThreadSP thread_sp = exe_ctx.GetThreadSP();
226 ThreadList::ExpressionExecutionThreadPusher execution_thread_pusher(
227 thread_sp);
228
229 llvm::StringRef full_prefix;
230 llvm::StringRef option_prefix(options.GetPrefix());
231 std::string full_prefix_storage;
232 if (!prefix.empty() && !option_prefix.empty()) {
233 full_prefix_storage = std::string(prefix);
234 full_prefix_storage.append(std::string(option_prefix));
235 full_prefix = full_prefix_storage;
236 } else if (!prefix.empty())
237 full_prefix = prefix;
238 else
239 full_prefix = option_prefix;
240
241 // If the language was not specified in the expression command, set it to the
242 // language in the target's properties if specified, else default to the
243 // langage for the frame.
244 if (language == lldb::eLanguageTypeUnknown) {
246 language = target->GetLanguage();
247 else if (StackFrame *frame = exe_ctx.GetFramePtr())
248 language = frame->GetLanguage();
249 }
250
251 lldb::UserExpressionSP user_expression_sp(
252 target->GetUserExpressionForLanguage(expr, full_prefix, language,
253 desired_type, options, ctx_obj,
254 error));
255 if (error.Fail()) {
256 LLDB_LOG(log, "== [UserExpression::Evaluate] Getting expression: {0} ==",
257 error.AsCString());
259 }
260
261 LLDB_LOG(log, "== [UserExpression::Evaluate] Parsing expression {0} ==",
262 expr.str());
263
264 const bool keep_expression_in_memory = true;
265 const bool generate_debug_info = options.GetGenerateDebugInfo();
266
268 error.SetErrorString("expression interrupted by callback before parse");
269 result_valobj_sp = ValueObjectConstResult::Create(
272 }
273
274 DiagnosticManager diagnostic_manager;
275
276 bool parse_success =
277 user_expression_sp->Parse(diagnostic_manager, exe_ctx, execution_policy,
278 keep_expression_in_memory, generate_debug_info);
279
280 // Calculate the fixed expression always, since we need it for errors.
281 std::string tmp_fixed_expression;
282 if (fixed_expression == nullptr)
283 fixed_expression = &tmp_fixed_expression;
284
285 *fixed_expression = user_expression_sp->GetFixedText().str();
286
287 // If there is a fixed expression, try to parse it:
288 if (!parse_success) {
289 // Delete the expression that failed to parse before attempting to parse
290 // the next expression.
291 user_expression_sp.reset();
292
293 execution_results = lldb::eExpressionParseError;
294 if (!fixed_expression->empty() && options.GetAutoApplyFixIts()) {
295 const uint64_t max_fix_retries = options.GetRetriesWithFixIts();
296 for (uint64_t i = 0; i < max_fix_retries; ++i) {
297 // Try parsing the fixed expression.
298 lldb::UserExpressionSP fixed_expression_sp(
300 fixed_expression->c_str(), full_prefix, language, desired_type,
301 options, ctx_obj, error));
302 DiagnosticManager fixed_diagnostic_manager;
303 parse_success = fixed_expression_sp->Parse(
304 fixed_diagnostic_manager, exe_ctx, execution_policy,
305 keep_expression_in_memory, generate_debug_info);
306 if (parse_success) {
307 diagnostic_manager.Clear();
308 user_expression_sp = fixed_expression_sp;
309 break;
310 } else {
311 // The fixed expression also didn't parse. Let's check for any new
312 // Fix-Its we could try.
313 if (!fixed_expression_sp->GetFixedText().empty()) {
314 *fixed_expression = fixed_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
325 if (!parse_success) {
326 std::string msg;
327 {
328 llvm::raw_string_ostream os(msg);
329 os << "expression failed to parse:\n";
330 if (!diagnostic_manager.Diagnostics().empty())
331 os << diagnostic_manager.GetString();
332 else
333 os << "unknown error";
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:337
static int CompareLoadAddress(const Address &lhs, const Address &rhs, Target *target)
Definition: Address.cpp:935
bool IsValid() const
Check if the object state is valid.
Definition: Address.h:345
A uniqued constant string class.
Definition: ConstString.h:39
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
Definition: ConstString.h:192
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
Definition: ConstString.h:201
std::string GetString(char separator='\n')
const DiagnosticList & Diagnostics()
const char * GetPrefix() const
Definition: Target.h:309
uint64_t GetRetriesWithFixIts() const
Definition: Target.h:430
bool InvokeCancelCallback(lldb::ExpressionEvaluationPhase phase) const
Definition: Target.h:392
ExecutionPolicy GetExecutionPolicy() const
Definition: Target.h:297
lldb::LanguageType GetLanguage() const
Definition: Target.h:303
"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:33
lldb::ProcessWP m_jit_process_wp
Expression's always have to have a target...
Definition: Expression.h:93
A plug-in interface definition class for debugging a process.
Definition: Process.h:343
lldb::StateType GetState()
Get accessor for the current process state.
Definition: Process.cpp:1295
bool CanJIT()
Determines whether executing JIT-compiled code in this process is possible.
Definition: Process.cpp:2299
This base class provides an interface to stack frames.
Definition: StackFrame.h:41
@ eExpressionPathOptionsNoSyntheticArrayRange
Definition: StackFrame.h:47
@ eExpressionPathOptionsNoSyntheticChildren
Definition: StackFrame.h:46
An error handling class.
Definition: Status.h:44
void Clear()
Clear the object state.
Definition: Status.cpp:167
int SetErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Set the current error string to a formatted error string.
Definition: Status.cpp:255
bool Success() const
Test for success condition.
Definition: Status.cpp:287
bool GetEnableNotifyAboutFixIts() const
Definition: Target.cpp:4437
lldb::LanguageType GetLanguage() const
Definition: Target.cpp:4550
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition: Target.cpp:2396
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:2415
Address m_address
The address the process is stopped in.
~UserExpression() override
Destructor.
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, ConstString &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 lldb::ValueObjectSP GetObjectPointerValueObject(lldb::StackFrameSP frame, ConstString const &object_name, Status &err)
Return ValueObject for a given variable name in the current stack frame.
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)
virtual lldb::ValueObjectSP Dereference(Status &error)
virtual uint32_t GetTypeInfo(CompilerType *pointee_or_element_compiler_type=nullptr)
Definition: ValueObject.h:378
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:74
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:309
ExecutionPolicy
Expression execution policies.
@ eExpressionEvaluationComplete
@ eExpressionEvaluationParse
@ eExpressionEvaluationExecution
@ 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.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eExpressionInterrupted
@ eExpressionParseError
@ eExpressionSetupError
uint64_t addr_t
Definition: lldb-types.h:79
@ eNoDynamicValues