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