xref: /llvm-project/lldb/source/Expression/LLVMUserExpression.cpp (revision 1dbee8f0437f0d6a5890c728e5847334644f8157)
1 //===-- LLVMUserExpression.cpp ----------------------------------*- C++ -*-===//
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 
10 #include "lldb/Expression/LLVMUserExpression.h"
11 #include "lldb/Core/Module.h"
12 #include "lldb/Core/StreamFile.h"
13 #include "lldb/Core/ValueObjectConstResult.h"
14 #include "lldb/Expression/DiagnosticManager.h"
15 #include "lldb/Expression/ExpressionVariable.h"
16 #include "lldb/Expression/IRExecutionUnit.h"
17 #include "lldb/Expression/IRInterpreter.h"
18 #include "lldb/Expression/Materializer.h"
19 #include "lldb/Host/HostInfo.h"
20 #include "lldb/Symbol/Block.h"
21 #include "lldb/Symbol/Function.h"
22 #include "lldb/Symbol/ObjectFile.h"
23 #include "lldb/Symbol/SymbolVendor.h"
24 #include "lldb/Symbol/Type.h"
25 #include "lldb/Symbol/VariableList.h"
26 #include "lldb/Target/ExecutionContext.h"
27 #include "lldb/Target/Process.h"
28 #include "lldb/Target/StackFrame.h"
29 #include "lldb/Target/Target.h"
30 #include "lldb/Target/ThreadPlan.h"
31 #include "lldb/Target/ThreadPlanCallUserExpression.h"
32 #include "lldb/Utility/ConstString.h"
33 #include "lldb/Utility/Log.h"
34 #include "lldb/Utility/StreamString.h"
35 
36 using namespace lldb_private;
37 
38 LLVMUserExpression::LLVMUserExpression(ExecutionContextScope &exe_scope,
39                                        llvm::StringRef expr,
40                                        llvm::StringRef prefix,
41                                        lldb::LanguageType language,
42                                        ResultType desired_type,
43                                        const EvaluateExpressionOptions &options,
44                                        ExpressionKind kind)
45     : UserExpression(exe_scope, expr, prefix, language, desired_type, options,
46                      kind),
47       m_stack_frame_bottom(LLDB_INVALID_ADDRESS),
48       m_stack_frame_top(LLDB_INVALID_ADDRESS), m_allow_cxx(false),
49       m_allow_objc(false), m_transformed_text(), m_execution_unit_sp(),
50       m_materializer_up(), m_jit_module_wp(),
51       m_can_interpret(false), m_materialized_address(LLDB_INVALID_ADDRESS) {}
52 
53 LLVMUserExpression::~LLVMUserExpression() {
54   if (m_target) {
55     lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock());
56     if (jit_module_sp)
57       m_target->GetImages().Remove(jit_module_sp);
58   }
59 }
60 
61 lldb::ExpressionResults
62 LLVMUserExpression::DoExecute(DiagnosticManager &diagnostic_manager,
63                               ExecutionContext &exe_ctx,
64                               const EvaluateExpressionOptions &options,
65                               lldb::UserExpressionSP &shared_ptr_to_me,
66                               lldb::ExpressionVariableSP &result) {
67   // The expression log is quite verbose, and if you're just tracking the
68   // execution of the expression, it's quite convenient to have these logs come
69   // out with the STEP log as well.
70   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
71                                                   LIBLLDB_LOG_STEP));
72 
73   if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret) {
74     lldb::addr_t struct_address = LLDB_INVALID_ADDRESS;
75 
76     if (!PrepareToExecuteJITExpression(diagnostic_manager, exe_ctx,
77                                        struct_address)) {
78       diagnostic_manager.Printf(
79           eDiagnosticSeverityError,
80           "errored out in %s, couldn't PrepareToExecuteJITExpression",
81           __FUNCTION__);
82       return lldb::eExpressionSetupError;
83     }
84 
85     lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS;
86     lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS;
87 
88     if (m_can_interpret) {
89       llvm::Module *module = m_execution_unit_sp->GetModule();
90       llvm::Function *function = m_execution_unit_sp->GetFunction();
91 
92       if (!module || !function) {
93         diagnostic_manager.PutString(
94             eDiagnosticSeverityError,
95             "supposed to interpret, but nothing is there");
96         return lldb::eExpressionSetupError;
97       }
98 
99       Status interpreter_error;
100 
101       std::vector<lldb::addr_t> args;
102 
103       if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager)) {
104         diagnostic_manager.Printf(eDiagnosticSeverityError,
105                                   "errored out in %s, couldn't AddArguments",
106                                   __FUNCTION__);
107         return lldb::eExpressionSetupError;
108       }
109 
110       function_stack_bottom = m_stack_frame_bottom;
111       function_stack_top = m_stack_frame_top;
112 
113       IRInterpreter::Interpret(*module, *function, args, *m_execution_unit_sp,
114                                interpreter_error, function_stack_bottom,
115                                function_stack_top, exe_ctx);
116 
117       if (!interpreter_error.Success()) {
118         diagnostic_manager.Printf(eDiagnosticSeverityError,
119                                   "supposed to interpret, but failed: %s",
120                                   interpreter_error.AsCString());
121         return lldb::eExpressionDiscarded;
122       }
123     } else {
124       if (!exe_ctx.HasThreadScope()) {
125         diagnostic_manager.Printf(eDiagnosticSeverityError,
126                                   "%s called with no thread selected",
127                                   __FUNCTION__);
128         return lldb::eExpressionSetupError;
129       }
130 
131       Address wrapper_address(m_jit_start_addr);
132 
133       std::vector<lldb::addr_t> args;
134 
135       if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager)) {
136         diagnostic_manager.Printf(eDiagnosticSeverityError,
137                                   "errored out in %s, couldn't AddArguments",
138                                   __FUNCTION__);
139         return lldb::eExpressionSetupError;
140       }
141 
142       lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallUserExpression(
143           exe_ctx.GetThreadRef(), wrapper_address, args, options,
144           shared_ptr_to_me));
145 
146       StreamString ss;
147       if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
148         diagnostic_manager.PutString(eDiagnosticSeverityError, ss.GetString());
149         return lldb::eExpressionSetupError;
150       }
151 
152       ThreadPlanCallUserExpression *user_expression_plan =
153           static_cast<ThreadPlanCallUserExpression *>(call_plan_sp.get());
154 
155       lldb::addr_t function_stack_pointer =
156           user_expression_plan->GetFunctionStackPointer();
157 
158       function_stack_bottom = function_stack_pointer - HostInfo::GetPageSize();
159       function_stack_top = function_stack_pointer;
160 
161       LLDB_LOGF(
162           log,
163           "-- [UserExpression::Execute] Execution of expression begins --");
164 
165       if (exe_ctx.GetProcessPtr())
166         exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
167 
168       lldb::ExpressionResults execution_result =
169           exe_ctx.GetProcessRef().RunThreadPlan(exe_ctx, call_plan_sp, options,
170                                                 diagnostic_manager);
171 
172       if (exe_ctx.GetProcessPtr())
173         exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
174 
175       LLDB_LOGF(log, "-- [UserExpression::Execute] Execution of expression "
176                      "completed --");
177 
178       if (execution_result == lldb::eExpressionInterrupted ||
179           execution_result == lldb::eExpressionHitBreakpoint) {
180         const char *error_desc = nullptr;
181 
182         if (call_plan_sp) {
183           lldb::StopInfoSP real_stop_info_sp = call_plan_sp->GetRealStopInfo();
184           if (real_stop_info_sp)
185             error_desc = real_stop_info_sp->GetDescription();
186         }
187         if (error_desc)
188           diagnostic_manager.Printf(eDiagnosticSeverityError,
189                                     "Execution was interrupted, reason: %s.",
190                                     error_desc);
191         else
192           diagnostic_manager.PutString(eDiagnosticSeverityError,
193                                        "Execution was interrupted.");
194 
195         if ((execution_result == lldb::eExpressionInterrupted &&
196              options.DoesUnwindOnError()) ||
197             (execution_result == lldb::eExpressionHitBreakpoint &&
198              options.DoesIgnoreBreakpoints()))
199           diagnostic_manager.AppendMessageToDiagnostic(
200               "The process has been returned to the state before expression "
201               "evaluation.");
202         else {
203           if (execution_result == lldb::eExpressionHitBreakpoint)
204             user_expression_plan->TransferExpressionOwnership();
205           diagnostic_manager.AppendMessageToDiagnostic(
206               "The process has been left at the point where it was "
207               "interrupted, "
208               "use \"thread return -x\" to return to the state before "
209               "expression evaluation.");
210         }
211 
212         return execution_result;
213       } else if (execution_result == lldb::eExpressionStoppedForDebug) {
214         diagnostic_manager.PutString(
215             eDiagnosticSeverityRemark,
216             "Execution was halted at the first instruction of the expression "
217             "function because \"debug\" was requested.\n"
218             "Use \"thread return -x\" to return to the state before expression "
219             "evaluation.");
220         return execution_result;
221       } else if (execution_result != lldb::eExpressionCompleted) {
222         diagnostic_manager.Printf(
223             eDiagnosticSeverityError,
224             "Couldn't execute function; result was %s",
225             Process::ExecutionResultAsCString(execution_result));
226         return execution_result;
227       }
228     }
229 
230     if (FinalizeJITExecution(diagnostic_manager, exe_ctx, result,
231                              function_stack_bottom, function_stack_top)) {
232       return lldb::eExpressionCompleted;
233     } else {
234       return lldb::eExpressionResultUnavailable;
235     }
236   } else {
237     diagnostic_manager.PutString(
238         eDiagnosticSeverityError,
239         "Expression can't be run, because there is no JIT compiled function");
240     return lldb::eExpressionSetupError;
241   }
242 }
243 
244 bool LLVMUserExpression::FinalizeJITExecution(
245     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
246     lldb::ExpressionVariableSP &result, lldb::addr_t function_stack_bottom,
247     lldb::addr_t function_stack_top) {
248   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
249 
250   LLDB_LOGF(log, "-- [UserExpression::FinalizeJITExecution] Dematerializing "
251                  "after execution --");
252 
253   if (!m_dematerializer_sp) {
254     diagnostic_manager.Printf(eDiagnosticSeverityError,
255                               "Couldn't apply expression side effects : no "
256                               "dematerializer is present");
257     return false;
258   }
259 
260   Status dematerialize_error;
261 
262   m_dematerializer_sp->Dematerialize(dematerialize_error, function_stack_bottom,
263                                      function_stack_top);
264 
265   if (!dematerialize_error.Success()) {
266     diagnostic_manager.Printf(eDiagnosticSeverityError,
267                               "Couldn't apply expression side effects : %s",
268                               dematerialize_error.AsCString("unknown error"));
269     return false;
270   }
271 
272   result =
273       GetResultAfterDematerialization(exe_ctx.GetBestExecutionContextScope());
274 
275   if (result)
276     result->TransferAddress();
277 
278   m_dematerializer_sp.reset();
279 
280   return true;
281 }
282 
283 bool LLVMUserExpression::PrepareToExecuteJITExpression(
284     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
285     lldb::addr_t &struct_address) {
286   lldb::TargetSP target;
287   lldb::ProcessSP process;
288   lldb::StackFrameSP frame;
289 
290   if (!LockAndCheckContext(exe_ctx, target, process, frame)) {
291     diagnostic_manager.PutString(
292         eDiagnosticSeverityError,
293         "The context has changed before we could JIT the expression!");
294     return false;
295   }
296 
297   if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret) {
298     if (m_materialized_address == LLDB_INVALID_ADDRESS) {
299       Status alloc_error;
300 
301       IRMemoryMap::AllocationPolicy policy =
302           m_can_interpret ? IRMemoryMap::eAllocationPolicyHostOnly
303                           : IRMemoryMap::eAllocationPolicyMirror;
304 
305       const bool zero_memory = false;
306 
307       m_materialized_address = m_execution_unit_sp->Malloc(
308           m_materializer_up->GetStructByteSize(),
309           m_materializer_up->GetStructAlignment(),
310           lldb::ePermissionsReadable | lldb::ePermissionsWritable, policy,
311           zero_memory, alloc_error);
312 
313       if (!alloc_error.Success()) {
314         diagnostic_manager.Printf(
315             eDiagnosticSeverityError,
316             "Couldn't allocate space for materialized struct: %s",
317             alloc_error.AsCString());
318         return false;
319       }
320     }
321 
322     struct_address = m_materialized_address;
323 
324     if (m_can_interpret && m_stack_frame_bottom == LLDB_INVALID_ADDRESS) {
325       Status alloc_error;
326 
327       const size_t stack_frame_size = 512 * 1024;
328 
329       const bool zero_memory = false;
330 
331       m_stack_frame_bottom = m_execution_unit_sp->Malloc(
332           stack_frame_size, 8,
333           lldb::ePermissionsReadable | lldb::ePermissionsWritable,
334           IRMemoryMap::eAllocationPolicyHostOnly, zero_memory, alloc_error);
335 
336       m_stack_frame_top = m_stack_frame_bottom + stack_frame_size;
337 
338       if (!alloc_error.Success()) {
339         diagnostic_manager.Printf(
340             eDiagnosticSeverityError,
341             "Couldn't allocate space for the stack frame: %s",
342             alloc_error.AsCString());
343         return false;
344       }
345     }
346 
347     Status materialize_error;
348 
349     m_dematerializer_sp = m_materializer_up->Materialize(
350         frame, *m_execution_unit_sp, struct_address, materialize_error);
351 
352     if (!materialize_error.Success()) {
353       diagnostic_manager.Printf(eDiagnosticSeverityError,
354                                 "Couldn't materialize: %s",
355                                 materialize_error.AsCString());
356       return false;
357     }
358   }
359   return true;
360 }
361 
362 lldb::ModuleSP LLVMUserExpression::GetJITModule() {
363   if (m_execution_unit_sp)
364     return m_execution_unit_sp->GetJITModule();
365   return lldb::ModuleSP();
366 }
367