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