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#include "llvm/BinaryFormat/Dwarf.h"
43
44using namespace lldb_private;
45
47
49 llvm::StringRef expr, llvm::StringRef prefix,
50 SourceLanguage language, 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 SourceLanguage 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) {
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 if (!fixed_expression_sp)
304 break;
305 DiagnosticManager fixed_diagnostic_manager;
306 parse_success = fixed_expression_sp->Parse(
307 fixed_diagnostic_manager, exe_ctx, execution_policy,
308 keep_expression_in_memory, generate_debug_info);
309 if (parse_success) {
310 diagnostic_manager.Clear();
311 user_expression_sp = fixed_expression_sp;
312 break;
313 }
314 // The fixed expression also didn't parse. Let's check for any new
315 // fixits we could try.
316 if (!fixed_expression_sp->GetFixedText().empty()) {
317 *fixed_expression = fixed_expression_sp->GetFixedText().str();
318 } else {
319 // Fixed expression didn't compile without a fixit, don't retry and
320 // don't tell the user about it.
321 fixed_expression->clear();
322 break;
323 }
324 }
325 }
326
327 if (!parse_success) {
328 std::string msg;
329 {
330 llvm::raw_string_ostream os(msg);
331 if (!diagnostic_manager.Diagnostics().empty())
332 os << diagnostic_manager.GetString();
333 else
334 os << "expression failed to parse (no further compiler diagnostics)";
335 if (target->GetEnableNotifyAboutFixIts() && fixed_expression &&
336 !fixed_expression->empty())
337 os << "\nfixed expression suggested:\n " << *fixed_expression;
338 }
339 error.SetExpressionError(execution_results, msg.c_str());
340 }
341 }
342
343 if (parse_success) {
344 lldb::ExpressionVariableSP expr_result;
345
346 if (execution_policy == eExecutionPolicyNever &&
347 !user_expression_sp->CanInterpret()) {
348 LLDB_LOG(log, "== [UserExpression::Evaluate] Expression may not run, but "
349 "is not constant ==");
350
351 if (!diagnostic_manager.Diagnostics().size())
352 error.SetExpressionError(lldb::eExpressionSetupError,
353 "expression needed to run but couldn't");
354 } else if (execution_policy == eExecutionPolicyTopLevel) {
357 } else {
359 error.SetExpressionError(
361 "expression interrupted by callback before execution");
362 result_valobj_sp = ValueObjectConstResult::Create(
365 }
366
367 diagnostic_manager.Clear();
368
369 LLDB_LOG(log, "== [UserExpression::Evaluate] Executing expression ==");
370
371 execution_results =
372 user_expression_sp->Execute(diagnostic_manager, exe_ctx, options,
373 user_expression_sp, expr_result);
374
375 if (execution_results != lldb::eExpressionCompleted) {
376 LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
377 "abnormally ==");
378
379 if (!diagnostic_manager.Diagnostics().size())
380 error.SetExpressionError(
381 execution_results, "expression failed to execute, unknown error");
382 else
383 error.SetExpressionError(execution_results,
384 diagnostic_manager.GetString().c_str());
385 } else {
386 if (expr_result) {
387 result_valobj_sp = expr_result->GetValueObject();
388 result_valobj_sp->SetPreferredDisplayLanguage(
389 language.AsLanguageType());
390
391 LLDB_LOG(log,
392 "== [UserExpression::Evaluate] Execution completed "
393 "normally with result {0} ==",
394 result_valobj_sp->GetValueAsCString());
395 } else {
396 LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
397 "normally with no result ==");
398
400 }
401 }
402 }
403 }
404
406 error.SetExpressionError(
408 "expression interrupted by callback after complete");
410 }
411
412 if (result_valobj_sp.get() == nullptr) {
413 result_valobj_sp = ValueObjectConstResult::Create(
415 }
416
417 return execution_results;
418}
419
422 ExecutionContext &exe_ctx,
423 const EvaluateExpressionOptions &options,
424 lldb::UserExpressionSP &shared_ptr_to_me,
425 lldb::ExpressionVariableSP &result_var) {
427 diagnostic_manager, exe_ctx, options, shared_ptr_to_me, result_var);
428 Target *target = exe_ctx.GetTargetPtr();
429 if (options.GetSuppressPersistentResult() && result_var && target) {
430 if (auto *persistent_state =
433 persistent_state->RemovePersistentVariable(result_var);
434 }
435 return expr_result;
436}
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:359
static int CompareLoadAddress(const Address &lhs, const Address &rhs, Target *target)
Definition: Address.cpp:942
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:333
uint64_t GetRetriesWithFixIts() const
Definition: Target.h:454
SourceLanguage GetLanguage() const
Definition: Target.h:318
bool InvokeCancelCallback(lldb::ExpressionEvaluationPhase phase) const
Definition: Target.h:416
ExecutionPolicy GetExecutionPolicy() const
Definition: Target.h:312
"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:88
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:1335
bool CanJIT()
Determines whether executing JIT-compiled code in this process is possible.
Definition: Process.cpp:2470
This base class provides an interface to stack frames.
Definition: StackFrame.h:43
@ eExpressionPathOptionsNoSyntheticArrayRange
Definition: StackFrame.h:49
@ eExpressionPathOptionsNoSyntheticChildren
Definition: StackFrame.h:48
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:166
bool Success() const
Test for success condition.
Definition: Status.cpp:278
bool GetEnableNotifyAboutFixIts() const
Definition: Target.cpp:4548
SourceLanguage GetLanguage() const
Definition: Target.cpp:4667
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition: Target.cpp:2494
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:2514
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
void InstallContext(ExecutionContext &exe_ctx)
Populate m_in_cplusplus_method and m_in_objectivec_method based on the environment.
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::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)
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.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:331
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:420
std::shared_ptr< lldb_private::Thread > ThreadSP
Definition: lldb-forward.h:446
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Definition: lldb-forward.h:480
std::shared_ptr< lldb_private::ExpressionVariable > ExpressionVariableSP
Definition: lldb-forward.h:349
@ eStateStopped
Process or thread is stopped and can be examined.
@ 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:330
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eExpressionInterrupted
@ eExpressionParseError
@ eExpressionSetupError
std::shared_ptr< lldb_private::Process > ProcessSP
Definition: lldb-forward.h:387
std::shared_ptr< lldb_private::Variable > VariableSP
Definition: lldb-forward.h:482
uint64_t addr_t
Definition: lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
Definition: lldb-forward.h:444
@ eNoDynamicValues
A type-erased pair of llvm::dwarf::SourceLanguageName and version.
lldb::LanguageType AsLanguageType() const
Definition: Language.cpp:546