LLDB mainline
LLVMUserExpression.cpp
Go to the documentation of this file.
1//===-- LLVMUserExpression.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
10#include "lldb/Core/Module.h"
16#include "lldb/Host/HostInfo.h"
17#include "lldb/Symbol/Block.h"
21#include "lldb/Symbol/Type.h"
23#include "lldb/Target/ABI.h"
25#include "lldb/Target/Process.h"
27#include "lldb/Target/Target.h"
33#include "lldb/Utility/Log.h"
34#include "lldb/Utility/Policy.h"
37
38using namespace lldb;
39using namespace lldb_private;
40
42
44 llvm::StringRef expr,
45 llvm::StringRef prefix,
46 SourceLanguage language,
47 ResultType desired_type,
48 const EvaluateExpressionOptions &options)
49 : UserExpression(exe_scope, expr, prefix, language, desired_type, options),
55
57 if (m_target) {
58 lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock());
59 if (jit_module_sp)
60 m_target->GetImages().Remove(jit_module_sp);
61 }
62}
63
66 ExecutionContext &exe_ctx,
67 const EvaluateExpressionOptions &options,
68 lldb::UserExpressionSP &shared_ptr_to_me,
69 lldb::ExpressionVariableSP &result_sp) {
70 // The expression log is quite verbose, and if you're just tracking the
71 // execution of the expression, it's quite convenient to have these logs come
72 // out with the STEP log as well.
74
76 diagnostic_manager.PutString(
78 "Expression can't be run, because there is no JIT compiled function");
80 }
81
82 lldb::addr_t struct_address = LLDB_INVALID_ADDRESS;
83
84 if (!PrepareToExecuteJITExpression(diagnostic_manager, exe_ctx,
85 struct_address)) {
86 diagnostic_manager.Printf(
88 "errored out in %s, couldn't PrepareToExecuteJITExpression",
89 __FUNCTION__);
91 }
92
93 lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS;
94 lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS;
95
96 lldb::ValueObjectSP error_backstop_result_sp;
97
98 if (m_can_interpret) {
99 llvm::Module *module = m_execution_unit_sp->GetModule();
100 llvm::Function *function = m_execution_unit_sp->GetFunction();
101
102 if (!module || !function) {
103 diagnostic_manager.PutString(
104 lldb::eSeverityError, "supposed to interpret, but nothing is there");
106 }
107
108 Status interpreter_error;
109
110 std::vector<lldb::addr_t> args;
111
112 if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager)) {
113 diagnostic_manager.Printf(lldb::eSeverityError,
114 "errored out in %s, couldn't AddArguments",
115 __FUNCTION__);
117 }
118
119 function_stack_bottom = m_stack_frame_bottom;
120 function_stack_top = m_stack_frame_top;
121
122 IRInterpreter::Interpret(*module, *function, args, *m_execution_unit_sp,
123 interpreter_error, function_stack_bottom,
124 function_stack_top, exe_ctx, options.GetTimeout());
125
126 if (!interpreter_error.Success()) {
127 diagnostic_manager.Printf(lldb::eSeverityError,
128 "supposed to interpret, but failed: %s",
129 interpreter_error.AsCString());
131 }
132 } else {
133 if (!exe_ctx.HasThreadScope()) {
134 diagnostic_manager.Printf(lldb::eSeverityError,
135 "%s called with no thread selected",
136 __FUNCTION__);
138 }
139
140 // Store away the thread ID for error reporting, in case it exits
141 // during execution:
142 lldb::tid_t expr_thread_id = exe_ctx.GetThreadRef().GetID();
143
144 Address wrapper_address(m_jit_start_addr);
145
146 std::vector<lldb::addr_t> args;
147
148 if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager)) {
149 diagnostic_manager.Printf(lldb::eSeverityError,
150 "errored out in %s, couldn't AddArguments",
151 __FUNCTION__);
153 }
154
156 exe_ctx.GetThreadRef(), wrapper_address, args, options,
157 shared_ptr_to_me));
158
159 StreamString ss;
160 if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
161 diagnostic_manager.PutString(lldb::eSeverityError, ss.GetString());
163 }
164
165 ThreadPlanCallUserExpression *user_expression_plan =
166 static_cast<ThreadPlanCallUserExpression *>(call_plan_sp.get());
167
168 lldb::addr_t function_stack_pointer =
169 user_expression_plan->GetFunctionStackPointer();
170
171 function_stack_bottom = function_stack_pointer - HostInfo::GetPageSize();
172 function_stack_top = function_stack_pointer;
173
174 LLDB_LOGF(log,
175 "-- [UserExpression::Execute] Execution of expression begins --");
176
177 if (exe_ctx.GetProcessPtr())
179
180 PolicyStack::Guard expr_policy_guard =
182
183 lldb::ExpressionResults execution_result =
184 exe_ctx.GetProcessRef().RunThreadPlan(exe_ctx, call_plan_sp, options,
185 diagnostic_manager);
186
187 if (exe_ctx.GetProcessPtr())
188 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
189
190 LLDB_LOGF(log, "-- [UserExpression::Execute] Execution of expression "
191 "completed --");
192
193 if (execution_result == lldb::eExpressionInterrupted ||
194 execution_result == lldb::eExpressionHitBreakpoint) {
195 const char *error_desc = nullptr;
196 const char *explanation = execution_result == lldb::eExpressionInterrupted
197 ? "was interrupted"
198 : "hit a breakpoint";
199
200 if (user_expression_plan) {
201 if (auto real_stop_info_sp = user_expression_plan->GetRealStopInfo())
202 error_desc = real_stop_info_sp->GetDescription();
203 }
204
205 if (error_desc)
206 diagnostic_manager.Printf(lldb::eSeverityError,
207 "Expression execution %s: %s.", explanation,
208 error_desc);
209 else
210 diagnostic_manager.Printf(lldb::eSeverityError,
211 "Expression execution %s.", explanation);
212
213 if ((execution_result == lldb::eExpressionInterrupted &&
214 options.DoesUnwindOnError()) ||
215 (execution_result == lldb::eExpressionHitBreakpoint &&
216 options.DoesIgnoreBreakpoints()))
217 diagnostic_manager.AppendMessageToDiagnostic(
218 "The process has been returned to the state before expression "
219 "evaluation.");
220 else {
221 if (execution_result == lldb::eExpressionHitBreakpoint)
222 user_expression_plan->TransferExpressionOwnership();
223 diagnostic_manager.AppendMessageToDiagnostic(
224 "The process has been left at the point where it was "
225 "interrupted, use \"thread return -x\" to return to the state "
226 "before expression evaluation.");
227 }
228
229 return execution_result;
230 }
231
232 if (execution_result == lldb::eExpressionStoppedForDebug) {
233 diagnostic_manager.PutString(
235 "Expression execution was halted at the first instruction of the "
236 "expression function because \"debug\" was requested.\n"
237 "Use \"thread return -x\" to return to the state before expression "
238 "evaluation.");
239 return execution_result;
240 }
241
242 if (execution_result == lldb::eExpressionCompleted &&
243 user_expression_plan->HitErrorBackstop()) {
244 lldb::ValueObjectSP error_sp =
245 user_expression_plan->GetReturnValueObject();
246 if (error_sp && error_sp->GetError().Success())
247 error_backstop_result_sp = error_sp;
248 }
249
250 if (execution_result == lldb::eExpressionThreadVanished) {
251 diagnostic_manager.Printf(lldb::eSeverityError,
252 "Couldn't execute expression: the thread on "
253 "which the expression was being run (0x%" PRIx64
254 ") exited during its execution.",
255 expr_thread_id);
256 return execution_result;
257 }
258
259 if (execution_result != lldb::eExpressionCompleted) {
260 diagnostic_manager.Printf(lldb::eSeverityError,
261 "Couldn't execute expression: result was %s",
262 toString(execution_result).c_str());
263 return execution_result;
264 }
265 }
266
267 if (error_backstop_result_sp) {
268 Target *target = exe_ctx.GetTargetPtr();
269 PersistentExpressionState *expression_state =
271 Language().AsLanguageType());
272 if (expression_state)
273 result_sp =
274 expression_state->CreatePersistentVariable(error_backstop_result_sp);
275
277 }
278
279 if (FinalizeJITExecution(diagnostic_manager, exe_ctx, result_sp,
280 function_stack_bottom, function_stack_top))
282
284}
285
287 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
288 lldb::ExpressionVariableSP &result, lldb::addr_t function_stack_bottom,
289 lldb::addr_t function_stack_top) {
291
292 LLDB_LOGF(log, "-- [UserExpression::FinalizeJITExecution] Dematerializing "
293 "after execution --");
294
295 if (!m_dematerializer_sp) {
296 diagnostic_manager.Printf(lldb::eSeverityError,
297 "Couldn't apply expression side effects : no "
298 "dematerializer is present");
299 return false;
300 }
301
302 Status dematerialize_error;
303
304 m_dematerializer_sp->Dematerialize(dematerialize_error, function_stack_bottom,
305 function_stack_top);
306
307 if (!dematerialize_error.Success()) {
308 diagnostic_manager.Printf(lldb::eSeverityError,
309 "Couldn't apply expression side effects : %s",
310 dematerialize_error.AsCString("unknown error"));
311 return false;
312 }
313
314 result =
316
317 if (result) {
318 // TransferAddress also does the offset_to_top calculation, so record the
319 // dynamic option before we do that.
320 if (EvaluateExpressionOptions *options = GetOptions())
321 result->PreserveDynamicOption(options->GetUseDynamic());
322 result->TransferAddress();
323 }
324
325 m_dematerializer_sp.reset();
326
327 return true;
328}
329
331 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
332 lldb::addr_t &struct_address) {
333 lldb::TargetSP target;
334 lldb::ProcessSP process;
335 lldb::StackFrameSP frame;
336
337 if (!LockAndCheckContext(exe_ctx, target, process, frame)) {
338 diagnostic_manager.PutString(
340 "The context has changed before we could JIT the expression!");
341 return false;
342 }
343
344 // Early out if no JIT'd expr and can't interpret.
346 return true;
347
348 if (!PrepareArgumentStruct(diagnostic_manager, frame, struct_address))
349 return false;
350
351 if (m_can_interpret && !AllocateInterpreterStackFrame(diagnostic_manager,
352 *target, process.get()))
353 return false;
354
355 return true;
356}
357
359 DiagnosticManager &diagnostic_manager, Target &target, Process *process) {
361 return true;
362
363 size_t stack_frame_size = target.GetExprAllocSize();
364 if (stack_frame_size == 0) {
365 ABISP abi_sp;
366 if (process && (abi_sp = process->GetABI()))
367 stack_frame_size = abi_sp->GetStackFrameSize();
368 else
369 stack_frame_size = 512 * 1024;
370 }
371
372 const bool zero_memory = false;
373 if (auto address_or_error = m_execution_unit_sp->Malloc(
374 stack_frame_size, 8,
375 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
377 m_stack_frame_bottom = *address_or_error;
378 m_stack_frame_top = m_stack_frame_bottom + stack_frame_size;
379 return true;
380 } else {
381 diagnostic_manager.Printf(lldb::eSeverityError,
382 "Couldn't allocate space for the stack frame: %s",
383 toString(address_or_error.takeError()).c_str());
384 return false;
385 }
386}
387
389 DiagnosticManager &diagnostic_manager, lldb::StackFrameSP &frame,
390 lldb::addr_t &struct_address) {
391
396
397 const bool zero_memory = false;
398 if (auto address_or_error = m_execution_unit_sp->Malloc(
399 m_materializer_up->GetStructByteSize(),
400 m_materializer_up->GetStructAlignment(),
401 lldb::ePermissionsReadable | lldb::ePermissionsWritable, policy,
402 zero_memory)) {
403 m_materialized_address = *address_or_error;
404 } else {
405 diagnostic_manager.Printf(
407 "Couldn't allocate space for materialized struct: %s",
408 toString(address_or_error.takeError()).c_str());
409 return false;
410 }
411 }
412
413 struct_address = m_materialized_address;
414
415 Status materialize_error;
416
418 frame, *m_execution_unit_sp, struct_address, materialize_error);
419
420 if (!materialize_error.Success()) {
421 diagnostic_manager.Printf(lldb::eSeverityError, "Couldn't materialize: %s",
422 materialize_error.AsCString());
423 return false;
424 }
425
426 return true;
427}
#define LLDB_LOGF(log,...)
Definition Log.h:389
static bool Interpret(llvm::Module &module, llvm::Function &function, llvm::ArrayRef< lldb::addr_t > args, lldb_private::IRExecutionUnit &execution_unit, lldb_private::Status &error, lldb::addr_t stack_frame_bottom, lldb::addr_t stack_frame_top, lldb_private::ExecutionContext &exe_ctx, lldb_private::Timeout< std::micro > timeout)
A section + offset based address class.
Definition Address.h:62
size_t void PutString(lldb::Severity severity, llvm::StringRef str)
void AppendMessageToDiagnostic(llvm::StringRef str)
size_t Printf(lldb::Severity severity, const char *format,...) __attribute__((format(printf
const Timeout< std::micro > & GetTimeout() const
Definition Target.h:429
"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.
bool HasThreadScope() const
Returns true the ExecutionContext object contains a valid target, process, and thread.
ExecutionContextScope * GetBestExecutionContextScope() const
Process & GetProcessRef() const
Returns a reference to the process object.
Target * GetTargetPtr() const
Returns a pointer to the target object.
Process * GetProcessPtr() const
Returns a pointer to the process object.
Thread & GetThreadRef() const
Returns a reference to the thread object.
lldb::addr_t m_jit_start_addr
An expression might have a process, but it doesn't need to (e.g.
Definition Expression.h:92
@ eAllocationPolicyHostOnly
This allocation was created in the host and will never make it into the process.
Definition IRMemoryMap.h:43
@ eAllocationPolicyMirror
The intent is that this allocation exist both in the host and the process and have the same content i...
Definition IRMemoryMap.h:47
lldb::ExpressionResults DoExecute(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, lldb::UserExpressionSP &shared_ptr_to_me, lldb::ExpressionVariableSP &result) override
std::string m_transformed_text
The text of the expression, as send to the parser.
bool m_can_interpret
True if the expression could be evaluated statically; false otherwise.
std::unique_ptr< Materializer > m_materializer_up
The materializer to use when running the expression.
bool m_allow_cxx
True if the language allows C++.
Target * m_target
The target for storing persistent data like types and variables.
bool FinalizeJITExecution(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, lldb::ExpressionVariableSP &result, lldb::addr_t function_stack_bottom=LLDB_INVALID_ADDRESS, lldb::addr_t function_stack_top=LLDB_INVALID_ADDRESS) override
Apply the side effects of the function to program state.
bool PrepareToExecuteJITExpression(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, lldb::addr_t &struct_address)
bool PrepareArgumentStruct(DiagnosticManager &diagnostic_manager, lldb::StackFrameSP &frame, lldb::addr_t &struct_address)
Prepare the struct holding the expression arguments.
lldb::addr_t m_stack_frame_bottom
The bottom of the allocated stack frame.
LLVMUserExpression(ExecutionContextScope &exe_scope, llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language, ResultType desired_type, const EvaluateExpressionOptions &options)
std::shared_ptr< IRExecutionUnit > m_execution_unit_sp
The execution unit the expression is stored in.
bool m_allow_objc
True if the language allows Objective-C.
Materializer::DematerializerSP m_dematerializer_sp
The dematerializer.
lldb::addr_t m_stack_frame_top
The top of the allocated stack frame.
virtual bool AddArguments(ExecutionContext &exe_ctx, std::vector< lldb::addr_t > &args, lldb::addr_t struct_address, DiagnosticManager &diagnostic_manager)=0
lldb::addr_t m_materialized_address
The address at which the arguments to the expression have been materialized.
bool AllocateInterpreterStackFrame(DiagnosticManager &diagnostic_manager, Target &target, Process *process)
Allocate the interpreter's private, host-only stack, if one has not been allocated already.
virtual lldb::ExpressionVariableSP CreatePersistentVariable(const lldb::ValueObjectSP &valobj_sp)=0
RAII guard that pops a policy on destruction.
Definition Policy.h:112
Guard PushPublicStateRunningExpression()
Definition Policy.h:140
static PolicyStack & Get()
Definition Policy.cpp:21
A plug-in interface definition class for debugging a process.
Definition Process.h:369
lldb::ExpressionResults RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp, const EvaluateExpressionOptions &requested_options, DiagnosticManager &diagnostic_manager)
Definition Process.cpp:5260
void SetRunningUserExpression(bool on)
Definition Process.cpp:1519
const lldb::ABISP & GetABI()
Definition Process.cpp:1529
An error handling class.
Definition Status.h:118
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
bool Success() const
Test for success condition.
Definition Status.cpp:303
llvm::StringRef GetString() const
uint64_t GetExprAllocSize() const
Definition Target.cpp:5784
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition Target.cpp:2823
lldb::ValueObjectSP GetReturnValueObject() override
bool HitErrorBackstop() const
Whether the call completed by throwing an error that reached the language runtime's error backstop.
virtual lldb::ExpressionVariableSP GetResultAfterDematerialization(ExecutionContextScope *exe_scope)
bool LockAndCheckContext(ExecutionContext &exe_ctx, lldb::TargetSP &target_sp, lldb::ProcessSP &process_sp, lldb::StackFrameSP &frame_sp)
SourceLanguage Language() const override
Return the language that should be used when parsing.
UserExpression(ExecutionContextScope &exe_scope, llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language, ResultType desired_type, const EvaluateExpressionOptions &options)
Constructor.
EvaluateExpressionOptions * GetOptions() override
#define LLDB_INVALID_ADDRESS
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:338
std::string toString(FormatterBytecode::OpCodes op)
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::ExpressionVariable > ExpressionVariableSP
std::shared_ptr< lldb_private::UserExpression > UserExpressionSP
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eExpressionHitBreakpoint
@ eExpressionInterrupted
@ eExpressionDiscarded
@ eExpressionStoppedForDebug
@ eExpressionResultUnavailable
@ eExpressionThreadVanished
@ eExpressionSetupError
std::shared_ptr< lldb_private::Process > ProcessSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
uint64_t tid_t
Definition lldb-types.h:85
std::shared_ptr< lldb_private::Module > ModuleSP
A type-erased pair of llvm::dwarf::SourceLanguageName and version.
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47