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/IRExecutionUnit.h"
16 #include "lldb/Expression/IRInterpreter.h"
17 #include "lldb/Expression/Materializer.h"
18 #include "lldb/Host/HostInfo.h"
19 #include "lldb/Symbol/Block.h"
20 #include "lldb/Symbol/ClangASTContext.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     : UserExpression(exe_scope, expr, prefix, language, desired_type, options),
46       m_stack_frame_bottom(LLDB_INVALID_ADDRESS),
47       m_stack_frame_top(LLDB_INVALID_ADDRESS), m_allow_cxx(false),
48       m_allow_objc(false), m_transformed_text(), m_execution_unit_sp(),
49       m_materializer_up(), m_jit_module_wp(), m_enforce_valid_object(true),
50       m_in_cplusplus_method(false), m_in_objectivec_method(false),
51       m_in_static_method(false), m_needs_object_ptr(false), m_target(NULL),
52       m_can_interpret(false), m_materialized_address(LLDB_INVALID_ADDRESS) {}
53 
54 LLVMUserExpression::~LLVMUserExpression() {
55   if (m_target) {
56     lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock());
57     if (jit_module_sp)
58       m_target->GetImages().Remove(jit_module_sp);
59   }
60 }
61 
62 lldb::ExpressionResults
63 LLVMUserExpression::DoExecute(DiagnosticManager &diagnostic_manager,
64                               ExecutionContext &exe_ctx,
65                               const EvaluateExpressionOptions &options,
66                               lldb::UserExpressionSP &shared_ptr_to_me,
67                               lldb::ExpressionVariableSP &result) {
68   // The expression log is quite verbose, and if you're just tracking the
69   // execution of the expression, it's quite convenient to have these logs come
70   // out with the STEP log as well.
71   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS |
72                                                   LIBLLDB_LOG_STEP));
73 
74   if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret) {
75     lldb::addr_t struct_address = LLDB_INVALID_ADDRESS;
76 
77     if (!PrepareToExecuteJITExpression(diagnostic_manager, exe_ctx,
78                                        struct_address)) {
79       diagnostic_manager.Printf(
80           eDiagnosticSeverityError,
81           "errored out in %s, couldn't PrepareToExecuteJITExpression",
82           __FUNCTION__);
83       return lldb::eExpressionSetupError;
84     }
85 
86     lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS;
87     lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS;
88 
89     if (m_can_interpret) {
90       llvm::Module *module = m_execution_unit_sp->GetModule();
91       llvm::Function *function = m_execution_unit_sp->GetFunction();
92 
93       if (!module || !function) {
94         diagnostic_manager.PutString(
95             eDiagnosticSeverityError,
96             "supposed to interpret, but nothing is there");
97         return lldb::eExpressionSetupError;
98       }
99 
100       Status interpreter_error;
101 
102       std::vector<lldb::addr_t> args;
103 
104       if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager)) {
105         diagnostic_manager.Printf(eDiagnosticSeverityError,
106                                   "errored out in %s, couldn't AddArguments",
107                                   __FUNCTION__);
108         return lldb::eExpressionSetupError;
109       }
110 
111       function_stack_bottom = m_stack_frame_bottom;
112       function_stack_top = m_stack_frame_top;
113 
114       IRInterpreter::Interpret(*module, *function, args, *m_execution_unit_sp,
115                                interpreter_error, function_stack_bottom,
116                                function_stack_top, exe_ctx);
117 
118       if (!interpreter_error.Success()) {
119         diagnostic_manager.Printf(eDiagnosticSeverityError,
120                                   "supposed to interpret, but failed: %s",
121                                   interpreter_error.AsCString());
122         return lldb::eExpressionDiscarded;
123       }
124     } else {
125       if (!exe_ctx.HasThreadScope()) {
126         diagnostic_manager.Printf(eDiagnosticSeverityError,
127                                   "%s called with no thread selected",
128                                   __FUNCTION__);
129         return lldb::eExpressionSetupError;
130       }
131 
132       Address wrapper_address(m_jit_start_addr);
133 
134       std::vector<lldb::addr_t> args;
135 
136       if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager)) {
137         diagnostic_manager.Printf(eDiagnosticSeverityError,
138                                   "errored out in %s, couldn't AddArguments",
139                                   __FUNCTION__);
140         return lldb::eExpressionSetupError;
141       }
142 
143       lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallUserExpression(
144           exe_ctx.GetThreadRef(), wrapper_address, args, options,
145           shared_ptr_to_me));
146 
147       StreamString ss;
148       if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
149         diagnostic_manager.PutString(eDiagnosticSeverityError, ss.GetString());
150         return lldb::eExpressionSetupError;
151       }
152 
153       ThreadPlanCallUserExpression *user_expression_plan =
154           static_cast<ThreadPlanCallUserExpression *>(call_plan_sp.get());
155 
156       lldb::addr_t function_stack_pointer =
157           user_expression_plan->GetFunctionStackPointer();
158 
159       function_stack_bottom = function_stack_pointer - HostInfo::GetPageSize();
160       function_stack_top = function_stack_pointer;
161 
162       if (log)
163         log->Printf(
164             "-- [UserExpression::Execute] Execution of expression begins --");
165 
166       if (exe_ctx.GetProcessPtr())
167         exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
168 
169       lldb::ExpressionResults execution_result =
170           exe_ctx.GetProcessRef().RunThreadPlan(exe_ctx, call_plan_sp, options,
171                                                 diagnostic_manager);
172 
173       if (exe_ctx.GetProcessPtr())
174         exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
175 
176       if (log)
177         log->Printf("-- [UserExpression::Execute] Execution of expression "
178                     "completed --");
179 
180       if (execution_result == lldb::eExpressionInterrupted ||
181           execution_result == lldb::eExpressionHitBreakpoint) {
182         const char *error_desc = NULL;
183 
184         if (call_plan_sp) {
185           lldb::StopInfoSP real_stop_info_sp = call_plan_sp->GetRealStopInfo();
186           if (real_stop_info_sp)
187             error_desc = real_stop_info_sp->GetDescription();
188         }
189         if (error_desc)
190           diagnostic_manager.Printf(eDiagnosticSeverityError,
191                                     "Execution was interrupted, reason: %s.",
192                                     error_desc);
193         else
194           diagnostic_manager.PutString(eDiagnosticSeverityError,
195                                        "Execution was interrupted.");
196 
197         if ((execution_result == lldb::eExpressionInterrupted &&
198              options.DoesUnwindOnError()) ||
199             (execution_result == lldb::eExpressionHitBreakpoint &&
200              options.DoesIgnoreBreakpoints()))
201           diagnostic_manager.AppendMessageToDiagnostic(
202               "The process has been returned to the state before expression "
203               "evaluation.");
204         else {
205           if (execution_result == lldb::eExpressionHitBreakpoint)
206             user_expression_plan->TransferExpressionOwnership();
207           diagnostic_manager.AppendMessageToDiagnostic(
208               "The process has been left at the point where it was "
209               "interrupted, "
210               "use \"thread return -x\" to return to the state before "
211               "expression evaluation.");
212         }
213 
214         return execution_result;
215       } else if (execution_result == lldb::eExpressionStoppedForDebug) {
216         diagnostic_manager.PutString(
217             eDiagnosticSeverityRemark,
218             "Execution was halted at the first instruction of the expression "
219             "function because \"debug\" was requested.\n"
220             "Use \"thread return -x\" to return to the state before expression "
221             "evaluation.");
222         return execution_result;
223       } else if (execution_result != lldb::eExpressionCompleted) {
224         diagnostic_manager.Printf(
225             eDiagnosticSeverityError,
226             "Couldn't execute function; result was %s",
227             Process::ExecutionResultAsCString(execution_result));
228         return execution_result;
229       }
230     }
231 
232     if (FinalizeJITExecution(diagnostic_manager, exe_ctx, result,
233                              function_stack_bottom, function_stack_top)) {
234       return lldb::eExpressionCompleted;
235     } else {
236       return lldb::eExpressionResultUnavailable;
237     }
238   } else {
239     diagnostic_manager.PutString(
240         eDiagnosticSeverityError,
241         "Expression can't be run, because there is no JIT compiled function");
242     return lldb::eExpressionSetupError;
243   }
244 }
245 
246 bool LLVMUserExpression::FinalizeJITExecution(
247     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
248     lldb::ExpressionVariableSP &result, lldb::addr_t function_stack_bottom,
249     lldb::addr_t function_stack_top) {
250   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
251 
252   if (log)
253     log->Printf("-- [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