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
9
11#include "lldb/Core/Module.h"
18#include "lldb/Host/HostInfo.h"
19#include "lldb/Symbol/Block.h"
23#include "lldb/Symbol/Type.h"
25#include "lldb/Target/ABI.h"
27#include "lldb/Target/Process.h"
29#include "lldb/Target/Target.h"
34#include "lldb/Utility/Log.h"
36
37using namespace lldb;
38using namespace lldb_private;
39
41
43 llvm::StringRef expr,
44 llvm::StringRef prefix,
45 lldb::LanguageType language,
46 ResultType desired_type,
47 const EvaluateExpressionOptions &options)
48 : UserExpression(exe_scope, expr, prefix, language, desired_type, options),
49 m_stack_frame_bottom(LLDB_INVALID_ADDRESS),
50 m_stack_frame_top(LLDB_INVALID_ADDRESS), m_allow_cxx(false),
51 m_allow_objc(false), m_transformed_text(), m_execution_unit_sp(),
52 m_materializer_up(), m_jit_module_wp(), m_target(nullptr),
53 m_can_interpret(false), m_materialized_address(LLDB_INVALID_ADDRESS) {}
54
56 if (m_target) {
57 lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock());
58 if (jit_module_sp)
59 m_target->GetImages().Remove(jit_module_sp);
60 }
61}
62
65 ExecutionContext &exe_ctx,
66 const EvaluateExpressionOptions &options,
67 lldb::UserExpressionSP &shared_ptr_to_me,
69 // The expression log is quite verbose, and if you're just tracking the
70 // execution of the expression, it's quite convenient to have these logs come
71 // out with the STEP log as well.
73
75 diagnostic_manager.PutString(
77 "Expression can't be run, because there is no JIT compiled function");
79 }
80
81 lldb::addr_t struct_address = LLDB_INVALID_ADDRESS;
82
83 if (!PrepareToExecuteJITExpression(diagnostic_manager, exe_ctx,
84 struct_address)) {
85 diagnostic_manager.Printf(
87 "errored out in %s, couldn't PrepareToExecuteJITExpression",
88 __FUNCTION__);
90 }
91
92 lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS;
93 lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS;
94
95 if (m_can_interpret) {
96 llvm::Module *module = m_execution_unit_sp->GetModule();
97 llvm::Function *function = m_execution_unit_sp->GetFunction();
98
99 if (!module || !function) {
100 diagnostic_manager.PutString(
102 "supposed to interpret, but nothing is there");
104 }
105
106 Status interpreter_error;
107
108 std::vector<lldb::addr_t> args;
109
110 if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager)) {
111 diagnostic_manager.Printf(eDiagnosticSeverityError,
112 "errored out in %s, couldn't AddArguments",
113 __FUNCTION__);
115 }
116
117 function_stack_bottom = m_stack_frame_bottom;
118 function_stack_top = m_stack_frame_top;
119
120 IRInterpreter::Interpret(*module, *function, args, *m_execution_unit_sp,
121 interpreter_error, function_stack_bottom,
122 function_stack_top, exe_ctx, options.GetTimeout());
123
124 if (!interpreter_error.Success()) {
125 diagnostic_manager.Printf(eDiagnosticSeverityError,
126 "supposed to interpret, but failed: %s",
127 interpreter_error.AsCString());
129 }
130 } else {
131 if (!exe_ctx.HasThreadScope()) {
132 diagnostic_manager.Printf(eDiagnosticSeverityError,
133 "%s called with no thread selected",
134 __FUNCTION__);
136 }
137
138 // Store away the thread ID for error reporting, in case it exits
139 // during execution:
140 lldb::tid_t expr_thread_id = exe_ctx.GetThreadRef().GetID();
141
142 Address wrapper_address(m_jit_start_addr);
143
144 std::vector<lldb::addr_t> args;
145
146 if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager)) {
147 diagnostic_manager.Printf(eDiagnosticSeverityError,
148 "errored out in %s, couldn't AddArguments",
149 __FUNCTION__);
151 }
152
154 exe_ctx.GetThreadRef(), wrapper_address, args, options,
155 shared_ptr_to_me));
156
157 StreamString ss;
158 if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
159 diagnostic_manager.PutString(eDiagnosticSeverityError, ss.GetString());
161 }
162
163 ThreadPlanCallUserExpression *user_expression_plan =
164 static_cast<ThreadPlanCallUserExpression *>(call_plan_sp.get());
165
166 lldb::addr_t function_stack_pointer =
167 user_expression_plan->GetFunctionStackPointer();
168
169 function_stack_bottom = function_stack_pointer - HostInfo::GetPageSize();
170 function_stack_top = function_stack_pointer;
171
172 LLDB_LOGF(log,
173 "-- [UserExpression::Execute] Execution of expression begins --");
174
175 if (exe_ctx.GetProcessPtr())
177
178 lldb::ExpressionResults execution_result =
179 exe_ctx.GetProcessRef().RunThreadPlan(exe_ctx, call_plan_sp, options,
180 diagnostic_manager);
181
182 if (exe_ctx.GetProcessPtr())
183 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
184
185 LLDB_LOGF(log, "-- [UserExpression::Execute] Execution of expression "
186 "completed --");
187
188 if (execution_result == lldb::eExpressionInterrupted ||
189 execution_result == lldb::eExpressionHitBreakpoint) {
190 const char *error_desc = nullptr;
191
192 if (user_expression_plan) {
193 if (auto real_stop_info_sp = user_expression_plan->GetRealStopInfo())
194 error_desc = real_stop_info_sp->GetDescription();
195 }
196 if (error_desc)
197 diagnostic_manager.Printf(eDiagnosticSeverityError,
198 "Execution was interrupted, reason: %s.",
199 error_desc);
200 else
201 diagnostic_manager.PutString(eDiagnosticSeverityError,
202 "Execution was interrupted.");
203
204 if ((execution_result == lldb::eExpressionInterrupted &&
205 options.DoesUnwindOnError()) ||
206 (execution_result == lldb::eExpressionHitBreakpoint &&
207 options.DoesIgnoreBreakpoints()))
208 diagnostic_manager.AppendMessageToDiagnostic(
209 "The process has been returned to the state before expression "
210 "evaluation.");
211 else {
212 if (execution_result == lldb::eExpressionHitBreakpoint)
213 user_expression_plan->TransferExpressionOwnership();
214 diagnostic_manager.AppendMessageToDiagnostic(
215 "The process has been left at the point where it was "
216 "interrupted, "
217 "use \"thread return -x\" to return to the state before "
218 "expression evaluation.");
219 }
220
221 return execution_result;
222 } else if (execution_result == lldb::eExpressionStoppedForDebug) {
223 diagnostic_manager.PutString(
225 "Execution was halted at the first instruction of the expression "
226 "function because \"debug\" was requested.\n"
227 "Use \"thread return -x\" to return to the state before expression "
228 "evaluation.");
229 return execution_result;
230 } else if (execution_result == lldb::eExpressionThreadVanished) {
231 diagnostic_manager.Printf(
233 "Couldn't complete execution; the thread "
234 "on which the expression was being run: 0x%" PRIx64
235 " exited during its execution.",
236 expr_thread_id);
237 return execution_result;
238 } else if (execution_result != lldb::eExpressionCompleted) {
239 diagnostic_manager.Printf(
240 eDiagnosticSeverityError, "Couldn't execute function; result was %s",
241 Process::ExecutionResultAsCString(execution_result));
242 return execution_result;
243 }
244 }
245
246 if (FinalizeJITExecution(diagnostic_manager, exe_ctx, result,
247 function_stack_bottom, function_stack_top)) {
249 } else {
251 }
252}
253
255 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
256 lldb::ExpressionVariableSP &result, lldb::addr_t function_stack_bottom,
257 lldb::addr_t function_stack_top) {
259
260 LLDB_LOGF(log, "-- [UserExpression::FinalizeJITExecution] Dematerializing "
261 "after execution --");
262
263 if (!m_dematerializer_sp) {
264 diagnostic_manager.Printf(eDiagnosticSeverityError,
265 "Couldn't apply expression side effects : no "
266 "dematerializer is present");
267 return false;
268 }
269
270 Status dematerialize_error;
271
272 m_dematerializer_sp->Dematerialize(dematerialize_error, function_stack_bottom,
273 function_stack_top);
274
275 if (!dematerialize_error.Success()) {
276 diagnostic_manager.Printf(eDiagnosticSeverityError,
277 "Couldn't apply expression side effects : %s",
278 dematerialize_error.AsCString("unknown error"));
279 return false;
280 }
281
282 result =
284
285 if (result)
286 result->TransferAddress();
287
288 m_dematerializer_sp.reset();
289
290 return true;
291}
292
294 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
295 lldb::addr_t &struct_address) {
296 lldb::TargetSP target;
297 lldb::ProcessSP process;
298 lldb::StackFrameSP frame;
299
300 if (!LockAndCheckContext(exe_ctx, target, process, frame)) {
301 diagnostic_manager.PutString(
303 "The context has changed before we could JIT the expression!");
304 return false;
305 }
306
309 Status alloc_error;
310
314
315 const bool zero_memory = false;
316
318 m_materializer_up->GetStructByteSize(),
319 m_materializer_up->GetStructAlignment(),
320 lldb::ePermissionsReadable | lldb::ePermissionsWritable, policy,
321 zero_memory, alloc_error);
322
323 if (!alloc_error.Success()) {
324 diagnostic_manager.Printf(
326 "Couldn't allocate space for materialized struct: %s",
327 alloc_error.AsCString());
328 return false;
329 }
330 }
331
332 struct_address = m_materialized_address;
333
335 Status alloc_error;
336
337 size_t stack_frame_size = target->GetExprAllocSize();
338 if (stack_frame_size == 0) {
339 ABISP abi_sp;
340 if (process && (abi_sp = process->GetABI()))
341 stack_frame_size = abi_sp->GetStackFrameSize();
342 else
343 stack_frame_size = 512 * 1024;
344 }
345
346 const bool zero_memory = false;
347
349 stack_frame_size, 8,
350 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
351 IRMemoryMap::eAllocationPolicyHostOnly, zero_memory, alloc_error);
352
353 m_stack_frame_top = m_stack_frame_bottom + stack_frame_size;
354
355 if (!alloc_error.Success()) {
356 diagnostic_manager.Printf(
358 "Couldn't allocate space for the stack frame: %s",
359 alloc_error.AsCString());
360 return false;
361 }
362 }
363
364 Status materialize_error;
365
367 frame, *m_execution_unit_sp, struct_address, materialize_error);
368
369 if (!materialize_error.Success()) {
370 diagnostic_manager.Printf(eDiagnosticSeverityError,
371 "Couldn't materialize: %s",
372 materialize_error.AsCString());
373 return false;
374 }
375 }
376 return true;
377}
378
#define LLDB_LOGF(log,...)
Definition: Log.h:349
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 Printf(DiagnosticSeverity severity, const char *format,...) __attribute__((format(printf
void AppendMessageToDiagnostic(llvm::StringRef str)
size_t void PutString(DiagnosticSeverity severity, llvm::StringRef str)
const Timeout< std::micro > & GetTimeout() const
Definition: Target.h:351
"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.
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:94
@ eAllocationPolicyHostOnly
This allocation was created in the host and will never make it into the process.
Definition: IRMemoryMap.h:42
@ eAllocationPolicyMirror
The intent is that this allocation exist both in the host and the process and have the same content i...
Definition: IRMemoryMap.h:46
lldb::ExpressionResults DoExecute(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, lldb::UserExpressionSP &shared_ptr_to_me, lldb::ExpressionVariableSP &result) override
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.
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)
lldb::addr_t m_stack_frame_bottom
The bottom of the allocated stack frame.
std::shared_ptr< IRExecutionUnit > m_execution_unit_sp
The execution unit the expression is stored in.
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
LLVMUserExpression(ExecutionContextScope &exe_scope, llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, ResultType desired_type, const EvaluateExpressionOptions &options)
lldb::addr_t m_materialized_address
The address at which the arguments to the expression have been materialized.
bool Remove(const lldb::ModuleSP &module_sp, bool notify=true)
Remove a module from the module list.
Definition: ModuleList.cpp:334
lldb::ExpressionResults RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp, const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager)
Definition: Process.cpp:4730
void SetRunningUserExpression(bool on)
Definition: Process.cpp:1486
static const char * ExecutionResultAsCString(lldb::ExpressionResults result)
Definition: Process.cpp:5521
An error handling class.
Definition: Status.h:44
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:130
bool Success() const
Test for success condition.
Definition: Status.cpp:279
llvm::StringRef GetString() const
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:970
Encapsulates a one-time expression for use in lldb.
virtual lldb::ExpressionVariableSP GetResultAfterDematerialization(ExecutionContextScope *exe_scope)
bool LockAndCheckContext(ExecutionContext &exe_ctx, lldb::TargetSP &target_sp, lldb::ProcessSP &process_sp, lldb::StackFrameSP &frame_sp)
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
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:314
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
Definition: lldb-forward.h:441
std::shared_ptr< lldb_private::ABI > ABISP
Definition: lldb-forward.h:310
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
Definition: lldb-forward.h:412
std::shared_ptr< lldb_private::ExpressionVariable > ExpressionVariableSP
Definition: lldb-forward.h:343
LanguageType
Programming language type.
std::shared_ptr< lldb_private::UserExpression > UserExpressionSP
Definition: lldb-forward.h:324
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eExpressionHitBreakpoint
@ eExpressionInterrupted
@ eExpressionDiscarded
@ eExpressionStoppedForDebug
@ eExpressionResultUnavailable
@ eExpressionThreadVanished
@ eExpressionSetupError
std::shared_ptr< lldb_private::Process > ProcessSP
Definition: lldb-forward.h:381
uint64_t addr_t
Definition: lldb-types.h:79
std::shared_ptr< lldb_private::Target > TargetSP
Definition: lldb-forward.h:436
uint64_t tid_t
Definition: lldb-types.h:82
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:365
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition: UserID.h:47