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,
68 lldb::ExpressionVariableSP &result_sp) {
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_sp,
254 function_stack_bottom, function_stack_top))
256
258}
259
261 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
262 lldb::ExpressionVariableSP &result, lldb::addr_t function_stack_bottom,
263 lldb::addr_t function_stack_top) {
265
266 LLDB_LOGF(log, "-- [UserExpression::FinalizeJITExecution] Dematerializing "
267 "after execution --");
268
269 if (!m_dematerializer_sp) {
270 diagnostic_manager.Printf(lldb::eSeverityError,
271 "Couldn't apply expression side effects : no "
272 "dematerializer is present");
273 return false;
274 }
275
276 Status dematerialize_error;
277
278 m_dematerializer_sp->Dematerialize(dematerialize_error, function_stack_bottom,
279 function_stack_top);
280
281 if (!dematerialize_error.Success()) {
282 diagnostic_manager.Printf(lldb::eSeverityError,
283 "Couldn't apply expression side effects : %s",
284 dematerialize_error.AsCString("unknown error"));
285 return false;
286 }
287
288 result =
290
291 if (result) {
292 // TransferAddress also does the offset_to_top calculation, so record the
293 // dynamic option before we do that.
294 if (EvaluateExpressionOptions *options = GetOptions())
295 result->PreserveDynamicOption(options->GetUseDynamic());
296 result->TransferAddress();
297 }
298
299 m_dematerializer_sp.reset();
300
301 return true;
302}
303
305 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
306 lldb::addr_t &struct_address) {
307 lldb::TargetSP target;
308 lldb::ProcessSP process;
309 lldb::StackFrameSP frame;
310
311 if (!LockAndCheckContext(exe_ctx, target, process, frame)) {
312 diagnostic_manager.PutString(
314 "The context has changed before we could JIT the expression!");
315 return false;
316 }
317
323
324 const bool zero_memory = false;
325 if (auto address_or_error = m_execution_unit_sp->Malloc(
326 m_materializer_up->GetStructByteSize(),
327 m_materializer_up->GetStructAlignment(),
328 lldb::ePermissionsReadable | lldb::ePermissionsWritable, policy,
329 zero_memory)) {
330 m_materialized_address = *address_or_error;
331 } else {
332 diagnostic_manager.Printf(
334 "Couldn't allocate space for materialized struct: %s",
335 toString(address_or_error.takeError()).c_str());
336 return false;
337 }
338 }
339
340 struct_address = m_materialized_address;
341
343 size_t stack_frame_size = target->GetExprAllocSize();
344 if (stack_frame_size == 0) {
345 ABISP abi_sp;
346 if (process && (abi_sp = process->GetABI()))
347 stack_frame_size = abi_sp->GetStackFrameSize();
348 else
349 stack_frame_size = 512 * 1024;
350 }
351
352 const bool zero_memory = false;
353 if (auto address_or_error = m_execution_unit_sp->Malloc(
354 stack_frame_size, 8,
355 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
357 m_stack_frame_bottom = *address_or_error;
358 m_stack_frame_top = m_stack_frame_bottom + stack_frame_size;
359 } else {
360 diagnostic_manager.Printf(
362 "Couldn't allocate space for the stack frame: %s",
363 toString(address_or_error.takeError()).c_str());
364 return false;
365 }
366 }
367
368 Status materialize_error;
369
371 frame, *m_execution_unit_sp, struct_address, materialize_error);
372
373 if (!materialize_error.Success()) {
374 diagnostic_manager.Printf(lldb::eSeverityError,
375 "Couldn't materialize: %s",
376 materialize_error.AsCString());
377 return false;
378 }
379 }
380 return true;
381}
#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:391
"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:5014
void SetRunningUserExpression(bool on)
Definition Process.cpp:1469
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.
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: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