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"
36
37using namespace lldb;
38using namespace lldb_private;
39
41
43 llvm::StringRef expr,
44 llvm::StringRef prefix,
45 SourceLanguage language,
46 ResultType desired_type,
47 const EvaluateExpressionOptions &options)
48 : UserExpression(exe_scope, expr, prefix, language, desired_type, options),
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(
101 lldb::eSeverityError, "supposed to interpret, but nothing is there");
103 }
104
105 Status interpreter_error;
106
107 std::vector<lldb::addr_t> args;
108
109 if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager)) {
110 diagnostic_manager.Printf(lldb::eSeverityError,
111 "errored out in %s, couldn't AddArguments",
112 __FUNCTION__);
114 }
115
116 function_stack_bottom = m_stack_frame_bottom;
117 function_stack_top = m_stack_frame_top;
118
119 IRInterpreter::Interpret(*module, *function, args, *m_execution_unit_sp,
120 interpreter_error, function_stack_bottom,
121 function_stack_top, exe_ctx, options.GetTimeout());
122
123 if (!interpreter_error.Success()) {
124 diagnostic_manager.Printf(lldb::eSeverityError,
125 "supposed to interpret, but failed: %s",
126 interpreter_error.AsCString());
128 }
129 } else {
130 if (!exe_ctx.HasThreadScope()) {
131 diagnostic_manager.Printf(lldb::eSeverityError,
132 "%s called with no thread selected",
133 __FUNCTION__);
135 }
136
137 // Store away the thread ID for error reporting, in case it exits
138 // during execution:
139 lldb::tid_t expr_thread_id = exe_ctx.GetThreadRef().GetID();
140
141 Address wrapper_address(m_jit_start_addr);
142
143 std::vector<lldb::addr_t> args;
144
145 if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager)) {
146 diagnostic_manager.Printf(lldb::eSeverityError,
147 "errored out in %s, couldn't AddArguments",
148 __FUNCTION__);
150 }
151
153 exe_ctx.GetThreadRef(), wrapper_address, args, options,
154 shared_ptr_to_me));
155
156 StreamString ss;
157 if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
158 diagnostic_manager.PutString(lldb::eSeverityError, ss.GetString());
160 }
161
162 ThreadPlanCallUserExpression *user_expression_plan =
163 static_cast<ThreadPlanCallUserExpression *>(call_plan_sp.get());
164
165 lldb::addr_t function_stack_pointer =
166 user_expression_plan->GetFunctionStackPointer();
167
168 function_stack_bottom = function_stack_pointer - HostInfo::GetPageSize();
169 function_stack_top = function_stack_pointer;
170
171 LLDB_LOGF(log,
172 "-- [UserExpression::Execute] Execution of expression begins --");
173
174 if (exe_ctx.GetProcessPtr())
176
177 lldb::ExpressionResults execution_result =
178 exe_ctx.GetProcessRef().RunThreadPlan(exe_ctx, call_plan_sp, options,
179 diagnostic_manager);
180
181 if (exe_ctx.GetProcessPtr())
182 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
183
184 LLDB_LOGF(log, "-- [UserExpression::Execute] Execution of expression "
185 "completed --");
186
187 if (execution_result == lldb::eExpressionInterrupted ||
188 execution_result == lldb::eExpressionHitBreakpoint) {
189 const char *error_desc = nullptr;
190 const char *explanation = execution_result == lldb::eExpressionInterrupted
191 ? "was interrupted"
192 : "hit a breakpoint";
193
194 if (user_expression_plan) {
195 if (auto real_stop_info_sp = user_expression_plan->GetRealStopInfo())
196 error_desc = real_stop_info_sp->GetDescription();
197 }
198
199 if (error_desc)
200 diagnostic_manager.Printf(lldb::eSeverityError,
201 "Expression execution %s: %s.", explanation,
202 error_desc);
203 else
204 diagnostic_manager.Printf(lldb::eSeverityError,
205 "Expression execution %s.", explanation);
206
207 if ((execution_result == lldb::eExpressionInterrupted &&
208 options.DoesUnwindOnError()) ||
209 (execution_result == lldb::eExpressionHitBreakpoint &&
210 options.DoesIgnoreBreakpoints()))
211 diagnostic_manager.AppendMessageToDiagnostic(
212 "The process has been returned to the state before expression "
213 "evaluation.");
214 else {
215 if (execution_result == lldb::eExpressionHitBreakpoint)
216 user_expression_plan->TransferExpressionOwnership();
217 diagnostic_manager.AppendMessageToDiagnostic(
218 "The process has been left at the point where it was "
219 "interrupted, use \"thread return -x\" to return to the state "
220 "before expression evaluation.");
221 }
222
223 return execution_result;
224 }
225
226 if (execution_result == lldb::eExpressionStoppedForDebug) {
227 diagnostic_manager.PutString(
229 "Expression execution was halted at the first instruction of the "
230 "expression function because \"debug\" was requested.\n"
231 "Use \"thread return -x\" to return to the state before expression "
232 "evaluation.");
233 return execution_result;
234 }
235
236 if (execution_result == lldb::eExpressionThreadVanished) {
237 diagnostic_manager.Printf(lldb::eSeverityError,
238 "Couldn't execute expression: the thread on "
239 "which the expression was being run (0x%" PRIx64
240 ") exited during its execution.",
241 expr_thread_id);
242 return execution_result;
243 }
244
245 if (execution_result != lldb::eExpressionCompleted) {
246 diagnostic_manager.Printf(lldb::eSeverityError,
247 "Couldn't execute expression: result was %s",
248 toString(execution_result).c_str());
249 return execution_result;
250 }
251 }
252
253 if (FinalizeJITExecution(diagnostic_manager, exe_ctx, result,
254 function_stack_bottom, function_stack_top)) {
256 }
257
259}
260
262 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
263 lldb::ExpressionVariableSP &result, lldb::addr_t function_stack_bottom,
264 lldb::addr_t function_stack_top) {
266
267 LLDB_LOGF(log, "-- [UserExpression::FinalizeJITExecution] Dematerializing "
268 "after execution --");
269
270 if (!m_dematerializer_sp) {
271 diagnostic_manager.Printf(lldb::eSeverityError,
272 "Couldn't apply expression side effects : no "
273 "dematerializer is present");
274 return false;
275 }
276
277 Status dematerialize_error;
278
279 m_dematerializer_sp->Dematerialize(dematerialize_error, function_stack_bottom,
280 function_stack_top);
281
282 if (!dematerialize_error.Success()) {
283 diagnostic_manager.Printf(lldb::eSeverityError,
284 "Couldn't apply expression side effects : %s",
285 dematerialize_error.AsCString("unknown error"));
286 return false;
287 }
288
289 result =
291
292 if (result)
293 result->TransferAddress();
294
295 m_dematerializer_sp.reset();
296
297 return true;
298}
299
301 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
302 lldb::addr_t &struct_address) {
303 lldb::TargetSP target;
304 lldb::ProcessSP process;
305 lldb::StackFrameSP frame;
306
307 if (!LockAndCheckContext(exe_ctx, target, process, frame)) {
308 diagnostic_manager.PutString(
310 "The context has changed before we could JIT the expression!");
311 return false;
312 }
313
319
320 const bool zero_memory = false;
321 if (auto address_or_error = m_execution_unit_sp->Malloc(
322 m_materializer_up->GetStructByteSize(),
323 m_materializer_up->GetStructAlignment(),
324 lldb::ePermissionsReadable | lldb::ePermissionsWritable, policy,
325 zero_memory)) {
326 m_materialized_address = *address_or_error;
327 } else {
328 diagnostic_manager.Printf(
330 "Couldn't allocate space for materialized struct: %s",
331 toString(address_or_error.takeError()).c_str());
332 return false;
333 }
334 }
335
336 struct_address = m_materialized_address;
337
339 size_t stack_frame_size = target->GetExprAllocSize();
340 if (stack_frame_size == 0) {
341 ABISP abi_sp;
342 if (process && (abi_sp = process->GetABI()))
343 stack_frame_size = abi_sp->GetStackFrameSize();
344 else
345 stack_frame_size = 512 * 1024;
346 }
347
348 const bool zero_memory = false;
349 if (auto address_or_error = m_execution_unit_sp->Malloc(
350 stack_frame_size, 8,
351 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
353 m_stack_frame_bottom = *address_or_error;
354 m_stack_frame_top = m_stack_frame_bottom + stack_frame_size;
355 } else {
356 diagnostic_manager.Printf(
358 "Couldn't allocate space for the stack frame: %s",
359 toString(address_or_error.takeError()).c_str());
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(lldb::eSeverityError,
371 "Couldn't materialize: %s",
372 materialize_error.AsCString());
373 return false;
374 }
375 }
376 return true;
377}
#define LLDB_LOGF(log,...)
Definition Log.h:376
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:390
"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: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)
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.
lldb::ExpressionResults RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp, const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager)
Definition Process.cpp:4970
void SetRunningUserExpression(bool on)
Definition Process.cpp:1471
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:195
bool Success() const
Test for success condition.
Definition Status.cpp:304
llvm::StringRef GetString() const
virtual lldb::ExpressionVariableSP GetResultAfterDematerialization(ExecutionContextScope *exe_scope)
bool LockAndCheckContext(ExecutionContext &exe_ctx, lldb::TargetSP &target_sp, lldb::ProcessSP &process_sp, lldb::StackFrameSP &frame_sp)
UserExpression(ExecutionContextScope &exe_scope, llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language, ResultType desired_type, const EvaluateExpressionOptions &options)
Constructor.
#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:332
const char * toString(AppleArm64ExceptionClass EC)
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::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:84
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