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 //===----------------------------------------------------------------------===//
10 #include <sys/types.h>
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ValueObjectConstResult.h"
18 #include "lldb/Expression/DiagnosticManager.h"
19 #include "lldb/Expression/ExpressionVariable.h"
20 #include "lldb/Expression/IRExecutionUnit.h"
21 #include "lldb/Expression/IRInterpreter.h"
22 #include "lldb/Expression/Materializer.h"
23 #include "lldb/Expression/UserExpression.h"
24 #include "lldb/Host/HostInfo.h"
25 #include "lldb/Symbol/Block.h"
26 #include "lldb/Symbol/Function.h"
27 #include "lldb/Symbol/ObjectFile.h"
28 #include "lldb/Symbol/SymbolVendor.h"
29 #include "lldb/Symbol/Type.h"
30 #include "lldb/Symbol/TypeSystem.h"
31 #include "lldb/Symbol/VariableList.h"
32 #include "lldb/Target/ExecutionContext.h"
33 #include "lldb/Target/Process.h"
34 #include "lldb/Target/StackFrame.h"
35 #include "lldb/Target/Target.h"
36 #include "lldb/Target/ThreadPlan.h"
37 #include "lldb/Target/ThreadPlanCallUserExpression.h"
38 #include "lldb/Utility/LLDBLog.h"
39 #include "lldb/Utility/Log.h"
40 #include "lldb/Utility/State.h"
41 #include "lldb/Utility/StreamString.h"
43 using namespace lldb_private
;
45 char UserExpression::ID
;
47 UserExpression::UserExpression(ExecutionContextScope
&exe_scope
,
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
) {}
56 UserExpression::~UserExpression() = default;
58 void UserExpression::InstallContext(ExecutionContext
&exe_ctx
) {
59 m_jit_process_wp
= exe_ctx
.GetProcessSP();
61 lldb::StackFrameSP frame_sp
= exe_ctx
.GetFrameSP();
64 m_address
= frame_sp
->GetFrameCodeAddress();
67 bool UserExpression::LockAndCheckContext(ExecutionContext
&exe_ctx
,
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();
74 if (process_sp
!= expected_process_sp
)
77 process_sp
= exe_ctx
.GetProcessSP();
78 target_sp
= exe_ctx
.GetTargetSP();
79 frame_sp
= exe_ctx
.GetFrameSP();
81 if (m_address
.IsValid()) {
84 return (Address::CompareLoadAddress(m_address
,
85 frame_sp
->GetFrameCodeAddress(),
86 target_sp
.get()) == 0);
92 bool UserExpression::MatchesContext(ExecutionContext
&exe_ctx
) {
93 lldb::TargetSP target_sp
;
94 lldb::ProcessSP process_sp
;
95 lldb::StackFrameSP frame_sp
;
97 return LockAndCheckContext(exe_ctx
, target_sp
, process_sp
, frame_sp
);
100 lldb::ValueObjectSP
UserExpression::GetObjectPointerValueObject(
101 lldb::StackFrameSP frame_sp
, llvm::StringRef object_name
, Status
&err
) {
105 err
.SetErrorStringWithFormatv(
106 "Couldn't load '{0}' because the context is incomplete", object_name
);
110 lldb::VariableSP var_sp
;
111 lldb::ValueObjectSP valobj_sp
;
113 return frame_sp
->GetValueForVariableExpressionPath(
114 object_name
, lldb::eNoDynamicValues
,
115 StackFrame::eExpressionPathOptionCheckPtrVsMember
|
116 StackFrame::eExpressionPathOptionsNoFragileObjcIvar
|
117 StackFrame::eExpressionPathOptionsNoSyntheticChildren
|
118 StackFrame::eExpressionPathOptionsNoSyntheticArrayRange
,
122 lldb::addr_t
UserExpression::GetObjectPointer(lldb::StackFrameSP frame_sp
,
123 llvm::StringRef object_name
,
126 GetObjectPointerValueObject(std::move(frame_sp
), object_name
, err
);
128 if (!err
.Success() || !valobj_sp
.get())
129 return LLDB_INVALID_ADDRESS
;
131 lldb::addr_t ret
= valobj_sp
->GetValueAsUnsigned(LLDB_INVALID_ADDRESS
);
133 if (ret
== LLDB_INVALID_ADDRESS
) {
134 err
.SetErrorStringWithFormatv(
135 "Couldn't load '{0}' because its value couldn't be evaluated",
137 return LLDB_INVALID_ADDRESS
;
143 lldb::ExpressionResults
144 UserExpression::Evaluate(ExecutionContext
&exe_ctx
,
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
) {
149 Log
*log(GetLog(LLDBLog::Expressions
| LLDBLog::Step
));
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");
159 return lldb::eExpressionSetupError
;
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 "
170 error
.SetErrorString(
171 "passed context object of an reference type cannot be deferenced");
172 return lldb::eExpressionSetupError
;
175 ctx_obj
= deref_ctx_sp
.get();
178 lldb_private::ExecutionPolicy execution_policy
= options
.GetExecutionPolicy();
179 lldb::LanguageType language
= options
.GetLanguage();
180 const ResultType desired_type
= options
.DoesCoerceToId()
181 ? UserExpression::eResultTypeId
182 : UserExpression::eResultTypeAny
;
183 lldb::ExpressionResults execution_results
= lldb::eExpressionSetupError
;
185 Target
*target
= exe_ctx
.GetTargetPtr();
187 LLDB_LOG(log
, "== [UserExpression::Evaluate] Passed a NULL target, can't "
189 error
.SetErrorString("expression passed a null target");
190 return lldb::eExpressionSetupError
;
193 Process
*process
= exe_ctx
.GetProcessPtr();
195 if (process
== nullptr && execution_policy
== eExecutionPolicyAlways
) {
196 LLDB_LOG(log
, "== [UserExpression::Evaluate] No process, but the policy is "
197 "eExecutionPolicyAlways");
199 error
.SetErrorString("expression needed to run but couldn't: no process");
201 return execution_results
;
204 // Since we might need to allocate memory, we need to be stopped to run
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 "
211 StateAsCString(process
->GetState()));
212 return execution_results
;
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
;
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(
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
;
240 full_prefix
= option_prefix
;
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
) {
246 if (target
->GetLanguage() != lldb::eLanguageTypeUnknown
)
247 language
= target
->GetLanguage();
248 else if (StackFrame
*frame
= exe_ctx
.GetFramePtr())
249 language
= frame
->GetLanguage();
252 lldb::UserExpressionSP
user_expression_sp(
253 target
->GetUserExpressionForLanguage(expr
, full_prefix
, language
,
254 desired_type
, options
, ctx_obj
,
256 if (error
.Fail() || !user_expression_sp
) {
257 LLDB_LOG(log
, "== [UserExpression::Evaluate] Getting expression: {0} ==",
259 return lldb::eExpressionSetupError
;
262 LLDB_LOG(log
, "== [UserExpression::Evaluate] Parsing expression {0} ==",
265 const bool keep_expression_in_memory
= true;
266 const bool generate_debug_info
= options
.GetGenerateDebugInfo();
268 if (options
.InvokeCancelCallback(lldb::eExpressionEvaluationParse
)) {
269 error
.SetErrorString("expression interrupted by callback before parse");
270 result_valobj_sp
= ValueObjectConstResult::Create(
271 exe_ctx
.GetBestExecutionContextScope(), error
);
272 return lldb::eExpressionInterrupted
;
275 DiagnosticManager diagnostic_manager
;
278 user_expression_sp
->Parse(diagnostic_manager
, exe_ctx
, execution_policy
,
279 keep_expression_in_memory
, generate_debug_info
);
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
;
286 *fixed_expression
= user_expression_sp
->GetFixedText().str();
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();
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(
300 target
->GetUserExpressionForLanguage(
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
);
308 diagnostic_manager
.Clear();
309 user_expression_sp
= fixed_expression_sp
;
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();
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();
326 if (!parse_success
) {
329 llvm::raw_string_ostream
os(msg
);
330 if (!diagnostic_manager
.Diagnostics().empty())
331 os
<< diagnostic_manager
.GetString();
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
;
338 error
.SetExpressionError(execution_results
, msg
.c_str());
343 lldb::ExpressionVariableSP expr_result
;
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 ==");
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
) {
354 error
.SetError(UserExpression::kNoResult
, lldb::eErrorTypeGeneric
);
355 return lldb::eExpressionCompleted
;
357 if (options
.InvokeCancelCallback(lldb::eExpressionEvaluationExecution
)) {
358 error
.SetExpressionError(
359 lldb::eExpressionInterrupted
,
360 "expression interrupted by callback before execution");
361 result_valobj_sp
= ValueObjectConstResult::Create(
362 exe_ctx
.GetBestExecutionContextScope(), error
);
363 return lldb::eExpressionInterrupted
;
366 diagnostic_manager
.Clear();
368 LLDB_LOG(log
, "== [UserExpression::Evaluate] Executing expression ==");
371 user_expression_sp
->Execute(diagnostic_manager
, exe_ctx
, options
,
372 user_expression_sp
, expr_result
);
374 if (execution_results
!= lldb::eExpressionCompleted
) {
375 LLDB_LOG(log
, "== [UserExpression::Evaluate] Execution completed "
378 if (!diagnostic_manager
.Diagnostics().size())
379 error
.SetExpressionError(
380 execution_results
, "expression failed to execute, unknown error");
382 error
.SetExpressionError(execution_results
,
383 diagnostic_manager
.GetString().c_str());
386 result_valobj_sp
= expr_result
->GetValueObject();
387 result_valobj_sp
->SetPreferredDisplayLanguage(language
);
390 "== [UserExpression::Evaluate] Execution completed "
391 "normally with result {0} ==",
392 result_valobj_sp
->GetValueAsCString());
394 LLDB_LOG(log
, "== [UserExpression::Evaluate] Execution completed "
395 "normally with no result ==");
397 error
.SetError(UserExpression::kNoResult
, lldb::eErrorTypeGeneric
);
403 if (options
.InvokeCancelCallback(lldb::eExpressionEvaluationComplete
)) {
404 error
.SetExpressionError(
405 lldb::eExpressionInterrupted
,
406 "expression interrupted by callback after complete");
407 return lldb::eExpressionInterrupted
;
410 if (result_valobj_sp
.get() == nullptr) {
411 result_valobj_sp
= ValueObjectConstResult::Create(
412 exe_ctx
.GetBestExecutionContextScope(), error
);
415 return execution_results
;
418 lldb::ExpressionResults
419 UserExpression::Execute(DiagnosticManager
&diagnostic_manager
,
420 ExecutionContext
&exe_ctx
,
421 const EvaluateExpressionOptions
&options
,
422 lldb::UserExpressionSP
&shared_ptr_to_me
,
423 lldb::ExpressionVariableSP
&result_var
) {
424 lldb::ExpressionResults expr_result
= DoExecute(
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
=
429 target
->GetPersistentExpressionStateForLanguage(m_language
))
430 persistent_state
->RemovePersistentVariable(result_var
);