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,
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 if (m_can_interpret) {
97 llvm::Module *module = m_execution_unit_sp->GetModule();
98 llvm::Function *function = m_execution_unit_sp->GetFunction();
99
100 if (!module || !function) {
101 diagnostic_manager.PutString(
102 lldb::eSeverityError, "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(lldb::eSeverityError,
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(lldb::eSeverityError,
126 "supposed to interpret, but failed: %s",
127 interpreter_error.AsCString());
129 }
130 } else {
131 if (!exe_ctx.HasThreadScope()) {
132 diagnostic_manager.Printf(lldb::eSeverityError,
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(lldb::eSeverityError,
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(lldb::eSeverityError, 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 PolicyStack::Guard expr_policy_guard =
180
181 lldb::ExpressionResults execution_result =
182 exe_ctx.GetProcessRef().RunThreadPlan(exe_ctx, call_plan_sp, options,
183 diagnostic_manager);
184
185 if (exe_ctx.GetProcessPtr())
186 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
187
188 LLDB_LOGF(log, "-- [UserExpression::Execute] Execution of expression "
189 "completed --");
190
191 if (execution_result == lldb::eExpressionInterrupted ||
192 execution_result == lldb::eExpressionHitBreakpoint) {
193 const char *error_desc = nullptr;
194 const char *explanation = execution_result == lldb::eExpressionInterrupted
195 ? "was interrupted"
196 : "hit a breakpoint";
197
198 if (user_expression_plan) {
199 if (auto real_stop_info_sp = user_expression_plan->GetRealStopInfo())
200 error_desc = real_stop_info_sp->GetDescription();
201 }
202
203 if (error_desc)
204 diagnostic_manager.Printf(lldb::eSeverityError,
205 "Expression execution %s: %s.", explanation,
206 error_desc);
207 else
208 diagnostic_manager.Printf(lldb::eSeverityError,
209 "Expression execution %s.", explanation);
210
211 if ((execution_result == lldb::eExpressionInterrupted &&
212 options.DoesUnwindOnError()) ||
213 (execution_result == lldb::eExpressionHitBreakpoint &&
214 options.DoesIgnoreBreakpoints()))
215 diagnostic_manager.AppendMessageToDiagnostic(
216 "The process has been returned to the state before expression "
217 "evaluation.");
218 else {
219 if (execution_result == lldb::eExpressionHitBreakpoint)
220 user_expression_plan->TransferExpressionOwnership();
221 diagnostic_manager.AppendMessageToDiagnostic(
222 "The process has been left at the point where it was "
223 "interrupted, use \"thread return -x\" to return to the state "
224 "before expression evaluation.");
225 }
226
227 return execution_result;
228 }
229
230 if (execution_result == lldb::eExpressionStoppedForDebug) {
231 diagnostic_manager.PutString(
233 "Expression execution was halted at the first instruction of the "
234 "expression function because \"debug\" was requested.\n"
235 "Use \"thread return -x\" to return to the state before expression "
236 "evaluation.");
237 return execution_result;
238 }
239
240 if (execution_result == lldb::eExpressionThreadVanished) {
241 diagnostic_manager.Printf(lldb::eSeverityError,
242 "Couldn't execute expression: the thread on "
243 "which the expression was being run (0x%" PRIx64
244 ") exited during its execution.",
245 expr_thread_id);
246 return execution_result;
247 }
248
249 if (execution_result != lldb::eExpressionCompleted) {
250 diagnostic_manager.Printf(lldb::eSeverityError,
251 "Couldn't execute expression: result was %s",
252 toString(execution_result).c_str());
253 return execution_result;
254 }
255 }
256
257 if (FinalizeJITExecution(diagnostic_manager, exe_ctx, result,
258 function_stack_bottom, function_stack_top)) {
260 }
261
263}
264
266 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
267 lldb::ExpressionVariableSP &result, lldb::addr_t function_stack_bottom,
268 lldb::addr_t function_stack_top) {
270
271 LLDB_LOGF(log, "-- [UserExpression::FinalizeJITExecution] Dematerializing "
272 "after execution --");
273
274 if (!m_dematerializer_sp) {
275 diagnostic_manager.Printf(lldb::eSeverityError,
276 "Couldn't apply expression side effects : no "
277 "dematerializer is present");
278 return false;
279 }
280
281 Status dematerialize_error;
282
283 m_dematerializer_sp->Dematerialize(dematerialize_error, function_stack_bottom,
284 function_stack_top);
285
286 if (!dematerialize_error.Success()) {
287 diagnostic_manager.Printf(lldb::eSeverityError,
288 "Couldn't apply expression side effects : %s",
289 dematerialize_error.AsCString("unknown error"));
290 return false;
291 }
292
293 result =
295
296 if (result)
297 result->TransferAddress();
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:390
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:415
"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.
RAII guard that pops a policy on destruction.
Definition Policy.h:110
Guard PushPublicStateRunningExpression()
Definition Policy.h:138
static PolicyStack & Get()
Definition Policy.cpp:21
lldb::ExpressionResults RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp, const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager)
Definition Process.cpp:5172
void SetRunningUserExpression(bool on)
Definition Process.cpp:1482
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
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:339
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::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