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 char LLVMUserExpression::ID;
39 
40 LLVMUserExpression::LLVMUserExpression(ExecutionContextScope &exe_scope,
41                                        llvm::StringRef expr,
42                                        llvm::StringRef prefix,
43                                        lldb::LanguageType language,
44                                        ResultType desired_type,
45                                        const EvaluateExpressionOptions &options)
46     : UserExpression(exe_scope, expr, prefix, language, desired_type, options),
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(), m_can_interpret(false),
51       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     diagnostic_manager.PutString(
75         eDiagnosticSeverityError,
76         "Expression can't be run, because there is no JIT compiled function");
77     return lldb::eExpressionSetupError;
78   }
79 
80   lldb::addr_t struct_address = LLDB_INVALID_ADDRESS;
81 
82   if (!PrepareToExecuteJITExpression(diagnostic_manager, exe_ctx,
83                                      struct_address)) {
84     diagnostic_manager.Printf(
85         eDiagnosticSeverityError,
86         "errored out in %s, couldn't PrepareToExecuteJITExpression",
87         __FUNCTION__);
88     return lldb::eExpressionSetupError;
89   }
90 
91   lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS;
92   lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS;
93 
94   if (m_can_interpret) {
95     llvm::Module *module = m_execution_unit_sp->GetModule();
96     llvm::Function *function = m_execution_unit_sp->GetFunction();
97 
98     if (!module || !function) {
99       diagnostic_manager.PutString(
100           eDiagnosticSeverityError,
101           "supposed to interpret, but nothing is there");
102       return lldb::eExpressionSetupError;
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(eDiagnosticSeverityError,
111                                 "errored out in %s, couldn't AddArguments",
112                                 __FUNCTION__);
113       return lldb::eExpressionSetupError;
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);
122 
123     if (!interpreter_error.Success()) {
124       diagnostic_manager.Printf(eDiagnosticSeverityError,
125                                 "supposed to interpret, but failed: %s",
126                                 interpreter_error.AsCString());
127       return lldb::eExpressionDiscarded;
128     }
129   } else {
130     if (!exe_ctx.HasThreadScope()) {
131       diagnostic_manager.Printf(eDiagnosticSeverityError,
132                                 "%s called with no thread selected",
133                                 __FUNCTION__);
134       return lldb::eExpressionSetupError;
135     }
136 
137     Address wrapper_address(m_jit_start_addr);
138 
139     std::vector<lldb::addr_t> args;
140 
141     if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager)) {
142       diagnostic_manager.Printf(eDiagnosticSeverityError,
143                                 "errored out in %s, couldn't AddArguments",
144                                 __FUNCTION__);
145       return lldb::eExpressionSetupError;
146     }
147 
148     lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallUserExpression(
149         exe_ctx.GetThreadRef(), wrapper_address, args, options,
150         shared_ptr_to_me));
151 
152     StreamString ss;
153     if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
154       diagnostic_manager.PutString(eDiagnosticSeverityError, ss.GetString());
155       return lldb::eExpressionSetupError;
156     }
157 
158     ThreadPlanCallUserExpression *user_expression_plan =
159         static_cast<ThreadPlanCallUserExpression *>(call_plan_sp.get());
160 
161     lldb::addr_t function_stack_pointer =
162         user_expression_plan->GetFunctionStackPointer();
163 
164     function_stack_bottom = function_stack_pointer - HostInfo::GetPageSize();
165     function_stack_top = function_stack_pointer;
166 
167     LLDB_LOGF(log,
168               "-- [UserExpression::Execute] Execution of expression begins --");
169 
170     if (exe_ctx.GetProcessPtr())
171       exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
172 
173     lldb::ExpressionResults execution_result =
174         exe_ctx.GetProcessRef().RunThreadPlan(exe_ctx, call_plan_sp, options,
175                                               diagnostic_manager);
176 
177     if (exe_ctx.GetProcessPtr())
178       exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
179 
180     LLDB_LOGF(log, "-- [UserExpression::Execute] Execution of expression "
181                    "completed --");
182 
183     if (execution_result == lldb::eExpressionInterrupted ||
184         execution_result == lldb::eExpressionHitBreakpoint) {
185       const char *error_desc = nullptr;
186 
187       if (call_plan_sp) {
188         lldb::StopInfoSP real_stop_info_sp = call_plan_sp->GetRealStopInfo();
189         if (real_stop_info_sp)
190           error_desc = real_stop_info_sp->GetDescription();
191       }
192       if (error_desc)
193         diagnostic_manager.Printf(eDiagnosticSeverityError,
194                                   "Execution was interrupted, reason: %s.",
195                                   error_desc);
196       else
197         diagnostic_manager.PutString(eDiagnosticSeverityError,
198                                      "Execution was interrupted.");
199 
200       if ((execution_result == lldb::eExpressionInterrupted &&
201            options.DoesUnwindOnError()) ||
202           (execution_result == lldb::eExpressionHitBreakpoint &&
203            options.DoesIgnoreBreakpoints()))
204         diagnostic_manager.AppendMessageToDiagnostic(
205             "The process has been returned to the state before expression "
206             "evaluation.");
207       else {
208         if (execution_result == lldb::eExpressionHitBreakpoint)
209           user_expression_plan->TransferExpressionOwnership();
210         diagnostic_manager.AppendMessageToDiagnostic(
211             "The process has been left at the point where it was "
212             "interrupted, "
213             "use \"thread return -x\" to return to the state before "
214             "expression evaluation.");
215       }
216 
217       return execution_result;
218     } else if (execution_result == lldb::eExpressionStoppedForDebug) {
219       diagnostic_manager.PutString(
220           eDiagnosticSeverityRemark,
221           "Execution was halted at the first instruction of the expression "
222           "function because \"debug\" was requested.\n"
223           "Use \"thread return -x\" to return to the state before expression "
224           "evaluation.");
225       return execution_result;
226     } else if (execution_result != lldb::eExpressionCompleted) {
227       diagnostic_manager.Printf(
228           eDiagnosticSeverityError, "Couldn't execute function; result was %s",
229           Process::ExecutionResultAsCString(execution_result));
230       return execution_result;
231     }
232   }
233 
234   if (FinalizeJITExecution(diagnostic_manager, exe_ctx, result,
235                            function_stack_bottom, function_stack_top)) {
236     return lldb::eExpressionCompleted;
237   } else {
238     return lldb::eExpressionResultUnavailable;
239   }
240 }
241 
242 bool LLVMUserExpression::FinalizeJITExecution(
243     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
244     lldb::ExpressionVariableSP &result, lldb::addr_t function_stack_bottom,
245     lldb::addr_t function_stack_top) {
246   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
247 
248   LLDB_LOGF(log, "-- [UserExpression::FinalizeJITExecution] Dematerializing "
249                  "after execution --");
250 
251   if (!m_dematerializer_sp) {
252     diagnostic_manager.Printf(eDiagnosticSeverityError,
253                               "Couldn't apply expression side effects : no "
254                               "dematerializer is present");
255     return false;
256   }
257 
258   Status dematerialize_error;
259 
260   m_dematerializer_sp->Dematerialize(dematerialize_error, function_stack_bottom,
261                                      function_stack_top);
262 
263   if (!dematerialize_error.Success()) {
264     diagnostic_manager.Printf(eDiagnosticSeverityError,
265                               "Couldn't apply expression side effects : %s",
266                               dematerialize_error.AsCString("unknown error"));
267     return false;
268   }
269 
270   result =
271       GetResultAfterDematerialization(exe_ctx.GetBestExecutionContextScope());
272 
273   if (result)
274     result->TransferAddress();
275 
276   m_dematerializer_sp.reset();
277 
278   return true;
279 }
280 
281 bool LLVMUserExpression::PrepareToExecuteJITExpression(
282     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
283     lldb::addr_t &struct_address) {
284   lldb::TargetSP target;
285   lldb::ProcessSP process;
286   lldb::StackFrameSP frame;
287 
288   if (!LockAndCheckContext(exe_ctx, target, process, frame)) {
289     diagnostic_manager.PutString(
290         eDiagnosticSeverityError,
291         "The context has changed before we could JIT the expression!");
292     return false;
293   }
294 
295   if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret) {
296     if (m_materialized_address == LLDB_INVALID_ADDRESS) {
297       Status alloc_error;
298 
299       IRMemoryMap::AllocationPolicy policy =
300           m_can_interpret ? IRMemoryMap::eAllocationPolicyHostOnly
301                           : IRMemoryMap::eAllocationPolicyMirror;
302 
303       const bool zero_memory = false;
304 
305       m_materialized_address = m_execution_unit_sp->Malloc(
306           m_materializer_up->GetStructByteSize(),
307           m_materializer_up->GetStructAlignment(),
308           lldb::ePermissionsReadable | lldb::ePermissionsWritable, policy,
309           zero_memory, alloc_error);
310 
311       if (!alloc_error.Success()) {
312         diagnostic_manager.Printf(
313             eDiagnosticSeverityError,
314             "Couldn't allocate space for materialized struct: %s",
315             alloc_error.AsCString());
316         return false;
317       }
318     }
319 
320     struct_address = m_materialized_address;
321 
322     if (m_can_interpret && m_stack_frame_bottom == LLDB_INVALID_ADDRESS) {
323       Status alloc_error;
324 
325       const size_t stack_frame_size = 512 * 1024;
326 
327       const bool zero_memory = false;
328 
329       m_stack_frame_bottom = m_execution_unit_sp->Malloc(
330           stack_frame_size, 8,
331           lldb::ePermissionsReadable | lldb::ePermissionsWritable,
332           IRMemoryMap::eAllocationPolicyHostOnly, zero_memory, alloc_error);
333 
334       m_stack_frame_top = m_stack_frame_bottom + stack_frame_size;
335 
336       if (!alloc_error.Success()) {
337         diagnostic_manager.Printf(
338             eDiagnosticSeverityError,
339             "Couldn't allocate space for the stack frame: %s",
340             alloc_error.AsCString());
341         return false;
342       }
343     }
344 
345     Status materialize_error;
346 
347     m_dematerializer_sp = m_materializer_up->Materialize(
348         frame, *m_execution_unit_sp, struct_address, materialize_error);
349 
350     if (!materialize_error.Success()) {
351       diagnostic_manager.Printf(eDiagnosticSeverityError,
352                                 "Couldn't materialize: %s",
353                                 materialize_error.AsCString());
354       return false;
355     }
356   }
357   return true;
358 }
359 
360 lldb::ModuleSP LLVMUserExpression::GetJITModule() {
361   if (m_execution_unit_sp)
362     return m_execution_unit_sp->GetJITModule();
363   return lldb::ModuleSP();
364 }
365