1 //===-- UserExpression.cpp ------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Host/Config.h"
13 #include <sys/types.h>
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/StreamFile.h"
22 #include "lldb/Core/ValueObjectConstResult.h"
23 #include "lldb/Expression/DiagnosticManager.h"
24 #include "lldb/Expression/ExpressionVariable.h"
25 #include "lldb/Expression/IRExecutionUnit.h"
26 #include "lldb/Expression/IRInterpreter.h"
27 #include "lldb/Expression/Materializer.h"
28 #include "lldb/Expression/UserExpression.h"
29 #include "lldb/Host/HostInfo.h"
30 #include "lldb/Symbol/Block.h"
31 #include "lldb/Symbol/Function.h"
32 #include "lldb/Symbol/ObjectFile.h"
33 #include "lldb/Symbol/SymbolVendor.h"
34 #include "lldb/Symbol/Type.h"
35 #include "lldb/Symbol/TypeSystem.h"
36 #include "lldb/Symbol/VariableList.h"
37 #include "lldb/Target/ExecutionContext.h"
38 #include "lldb/Target/Process.h"
39 #include "lldb/Target/StackFrame.h"
40 #include "lldb/Target/Target.h"
41 #include "lldb/Target/ThreadPlan.h"
42 #include "lldb/Target/ThreadPlanCallUserExpression.h"
43 #include "lldb/Utility/ConstString.h"
44 #include "lldb/Utility/Log.h"
45 #include "lldb/Utility/StreamString.h"
47 using namespace lldb_private;
49 char UserExpression::ID;
51 UserExpression::UserExpression(ExecutionContextScope &exe_scope,
52 llvm::StringRef expr, llvm::StringRef prefix,
53 lldb::LanguageType language,
54 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) {}
60 UserExpression::~UserExpression() {}
62 void UserExpression::InstallContext(ExecutionContext &exe_ctx) {
63 m_jit_process_wp = exe_ctx.GetProcessSP();
65 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
68 m_address = frame_sp->GetFrameCodeAddress();
71 bool UserExpression::LockAndCheckContext(ExecutionContext &exe_ctx,
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();
78 if (process_sp != expected_process_sp)
81 process_sp = exe_ctx.GetProcessSP();
82 target_sp = exe_ctx.GetTargetSP();
83 frame_sp = exe_ctx.GetFrameSP();
85 if (m_address.IsValid()) {
88 return (Address::CompareLoadAddress(m_address,
89 frame_sp->GetFrameCodeAddress(),
90 target_sp.get()) == 0);
96 bool UserExpression::MatchesContext(ExecutionContext &exe_ctx) {
97 lldb::TargetSP target_sp;
98 lldb::ProcessSP process_sp;
99 lldb::StackFrameSP frame_sp;
101 return LockAndCheckContext(exe_ctx, target_sp, process_sp, frame_sp);
104 lldb::addr_t UserExpression::GetObjectPointer(lldb::StackFrameSP frame_sp,
105 ConstString &object_name,
110 err.SetErrorStringWithFormat(
111 "Couldn't load '%s' because the context is incomplete",
112 object_name.AsCString());
113 return LLDB_INVALID_ADDRESS;
116 lldb::VariableSP var_sp;
117 lldb::ValueObjectSP valobj_sp;
119 valobj_sp = frame_sp->GetValueForVariableExpressionPath(
120 object_name.GetStringRef(), lldb::eNoDynamicValues,
121 StackFrame::eExpressionPathOptionCheckPtrVsMember |
122 StackFrame::eExpressionPathOptionsNoFragileObjcIvar |
123 StackFrame::eExpressionPathOptionsNoSyntheticChildren |
124 StackFrame::eExpressionPathOptionsNoSyntheticArrayRange,
127 if (!err.Success() || !valobj_sp.get())
128 return LLDB_INVALID_ADDRESS;
130 lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
132 if (ret == LLDB_INVALID_ADDRESS) {
133 err.SetErrorStringWithFormat(
134 "Couldn't load '%s' because its value couldn't be evaluated",
135 object_name.AsCString());
136 return LLDB_INVALID_ADDRESS;
142 lldb::ExpressionResults
143 UserExpression::Evaluate(ExecutionContext &exe_ctx,
144 const EvaluateExpressionOptions &options,
145 llvm::StringRef expr, llvm::StringRef prefix,
146 lldb::ValueObjectSP &result_valobj_sp, Status &error,
147 std::string *fixed_expression, ValueObject *ctx_obj) {
148 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
152 static unsigned const ctx_type_mask =
153 lldb::TypeFlags::eTypeIsClass | lldb::TypeFlags::eTypeIsStructUnion;
154 if (!(ctx_obj->GetTypeInfo() & ctx_type_mask)) {
155 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a context object of "
156 "an invalid type, can't run expressions.");
157 error.SetErrorString("a context object of an invalid type passed");
158 return lldb::eExpressionSetupError;
162 lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy();
163 lldb::LanguageType language = options.GetLanguage();
164 const ResultType desired_type = options.DoesCoerceToId()
165 ? UserExpression::eResultTypeId
166 : UserExpression::eResultTypeAny;
167 lldb::ExpressionResults execution_results = lldb::eExpressionSetupError;
169 Target *target = exe_ctx.GetTargetPtr();
171 LLDB_LOG(log, "== [UserExpression::Evaluate] Passed a NULL target, can't "
173 error.SetErrorString("expression passed a null target");
174 return lldb::eExpressionSetupError;
177 Process *process = exe_ctx.GetProcessPtr();
179 if (process == nullptr || process->GetState() != lldb::eStateStopped) {
180 if (execution_policy == eExecutionPolicyAlways) {
181 LLDB_LOG(log, "== [UserExpression::Evaluate] Expression may not run, but "
182 "is not constant ==");
184 error.SetErrorString("expression needed to run but couldn't");
186 return execution_results;
190 if (process == nullptr || !process->CanJIT())
191 execution_policy = eExecutionPolicyNever;
193 // We need to set the expression execution thread here, turns out parse can
194 // call functions in the process of looking up symbols, which will escape the
195 // context set by exe_ctx passed to Execute.
196 lldb::ThreadSP thread_sp = exe_ctx.GetThreadSP();
197 ThreadList::ExpressionExecutionThreadPusher execution_thread_pusher(
200 llvm::StringRef full_prefix;
201 llvm::StringRef option_prefix(options.GetPrefix());
202 std::string full_prefix_storage;
203 if (!prefix.empty() && !option_prefix.empty()) {
204 full_prefix_storage = std::string(prefix);
205 full_prefix_storage.append(std::string(option_prefix));
206 full_prefix = full_prefix_storage;
207 } else if (!prefix.empty())
208 full_prefix = prefix;
210 full_prefix = option_prefix;
212 // If the language was not specified in the expression command, set it to the
213 // language in the target's properties if specified, else default to the
214 // langage for the frame.
215 if (language == lldb::eLanguageTypeUnknown) {
216 if (target->GetLanguage() != lldb::eLanguageTypeUnknown)
217 language = target->GetLanguage();
218 else if (StackFrame *frame = exe_ctx.GetFramePtr())
219 language = frame->GetLanguage();
222 lldb::UserExpressionSP user_expression_sp(
223 target->GetUserExpressionForLanguage(expr, full_prefix, language,
224 desired_type, options, ctx_obj,
227 LLDB_LOG(log, "== [UserExpression::Evaluate] Getting expression: {0} ==",
229 return lldb::eExpressionSetupError;
232 LLDB_LOG(log, "== [UserExpression::Evaluate] Parsing expression {0} ==",
235 const bool keep_expression_in_memory = true;
236 const bool generate_debug_info = options.GetGenerateDebugInfo();
238 if (options.InvokeCancelCallback(lldb::eExpressionEvaluationParse)) {
239 error.SetErrorString("expression interrupted by callback before parse");
240 result_valobj_sp = ValueObjectConstResult::Create(
241 exe_ctx.GetBestExecutionContextScope(), error);
242 return lldb::eExpressionInterrupted;
245 DiagnosticManager diagnostic_manager;
248 user_expression_sp->Parse(diagnostic_manager, exe_ctx, execution_policy,
249 keep_expression_in_memory, generate_debug_info);
251 // Calculate the fixed expression always, since we need it for errors.
252 std::string tmp_fixed_expression;
253 if (fixed_expression == nullptr)
254 fixed_expression = &tmp_fixed_expression;
256 const char *fixed_text = user_expression_sp->GetFixedText();
257 if (fixed_text != nullptr)
258 fixed_expression->append(fixed_text);
260 // If there is a fixed expression, try to parse it:
261 if (!parse_success) {
262 // Delete the expression that failed to parse before attempting to parse
263 // the next expression.
264 user_expression_sp.reset();
266 execution_results = lldb::eExpressionParseError;
267 if (fixed_expression && !fixed_expression->empty() &&
268 options.GetAutoApplyFixIts()) {
269 const uint64_t max_fix_retries = options.GetRetriesWithFixIts();
270 for (uint64_t i = 0; i < max_fix_retries; ++i) {
271 // Try parsing the fixed expression.
272 lldb::UserExpressionSP fixed_expression_sp(
273 target->GetUserExpressionForLanguage(
274 fixed_expression->c_str(), full_prefix, language, desired_type,
275 options, ctx_obj, error));
276 DiagnosticManager fixed_diagnostic_manager;
277 parse_success = fixed_expression_sp->Parse(
278 fixed_diagnostic_manager, exe_ctx, execution_policy,
279 keep_expression_in_memory, generate_debug_info);
281 diagnostic_manager.Clear();
282 user_expression_sp = fixed_expression_sp;
285 // The fixed expression also didn't parse. Let's check for any new
286 // Fix-Its we could try.
287 if (fixed_expression_sp->GetFixedText()) {
288 *fixed_expression = fixed_expression_sp->GetFixedText();
290 // Fixed expression didn't compile without a fixit, don't retry and
291 // don't tell the user about it.
292 fixed_expression->clear();
299 if (!parse_success) {
300 if (!fixed_expression->empty() && target->GetEnableNotifyAboutFixIts()) {
301 error.SetExpressionErrorWithFormat(
303 "expression failed to parse, fixed expression suggested:\n %s",
304 fixed_expression->c_str());
306 if (!diagnostic_manager.Diagnostics().size())
307 error.SetExpressionError(execution_results,
308 "expression failed to parse, unknown error");
310 error.SetExpressionError(execution_results,
311 diagnostic_manager.GetString().c_str());
317 lldb::ExpressionVariableSP expr_result;
319 if (execution_policy == eExecutionPolicyNever &&
320 !user_expression_sp->CanInterpret()) {
321 LLDB_LOG(log, "== [UserExpression::Evaluate] Expression may not run, but "
322 "is not constant ==");
324 if (!diagnostic_manager.Diagnostics().size())
325 error.SetExpressionError(lldb::eExpressionSetupError,
326 "expression needed to run but couldn't");
327 } else if (execution_policy == eExecutionPolicyTopLevel) {
328 error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric);
329 return lldb::eExpressionCompleted;
331 if (options.InvokeCancelCallback(lldb::eExpressionEvaluationExecution)) {
332 error.SetExpressionError(
333 lldb::eExpressionInterrupted,
334 "expression interrupted by callback before execution");
335 result_valobj_sp = ValueObjectConstResult::Create(
336 exe_ctx.GetBestExecutionContextScope(), error);
337 return lldb::eExpressionInterrupted;
340 diagnostic_manager.Clear();
342 LLDB_LOG(log, "== [UserExpression::Evaluate] Executing expression ==");
345 user_expression_sp->Execute(diagnostic_manager, exe_ctx, options,
346 user_expression_sp, expr_result);
348 if (execution_results != lldb::eExpressionCompleted) {
349 LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
352 if (!diagnostic_manager.Diagnostics().size())
353 error.SetExpressionError(
354 execution_results, "expression failed to execute, unknown error");
356 error.SetExpressionError(execution_results,
357 diagnostic_manager.GetString().c_str());
360 result_valobj_sp = expr_result->GetValueObject();
363 "== [UserExpression::Evaluate] Execution completed "
364 "normally with result %s ==",
365 result_valobj_sp->GetValueAsCString());
367 LLDB_LOG(log, "== [UserExpression::Evaluate] Execution completed "
368 "normally with no result ==");
370 error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric);
376 if (options.InvokeCancelCallback(lldb::eExpressionEvaluationComplete)) {
377 error.SetExpressionError(
378 lldb::eExpressionInterrupted,
379 "expression interrupted by callback after complete");
380 return lldb::eExpressionInterrupted;
383 if (result_valobj_sp.get() == nullptr) {
384 result_valobj_sp = ValueObjectConstResult::Create(
385 exe_ctx.GetBestExecutionContextScope(), error);
388 return execution_results;
391 lldb::ExpressionResults
392 UserExpression::Execute(DiagnosticManager &diagnostic_manager,
393 ExecutionContext &exe_ctx,
394 const EvaluateExpressionOptions &options,
395 lldb::UserExpressionSP &shared_ptr_to_me,
396 lldb::ExpressionVariableSP &result_var) {
397 lldb::ExpressionResults expr_result = DoExecute(
398 diagnostic_manager, exe_ctx, options, shared_ptr_to_me, result_var);
399 Target *target = exe_ctx.GetTargetPtr();
400 if (options.GetResultIsInternal() && result_var && target) {
401 if (auto *persistent_state =
402 target->GetPersistentExpressionStateForLanguage(m_language))
403 persistent_state->RemovePersistentVariable(result_var);