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