1 //===-- LLVMUserExpression.cpp ----------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // C Includes
11 // C++ Includes
12 
13 // Project includes
14 #include "lldb/Expression/LLVMUserExpression.h"
15 #include "lldb/Core/ConstString.h"
16 #include "lldb/Core/Log.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/StreamFile.h"
19 #include "lldb/Core/StreamString.h"
20 #include "lldb/Core/ValueObjectConstResult.h"
21 #include "lldb/Expression/ExpressionSourceCode.h"
22 #include "lldb/Expression/IRExecutionUnit.h"
23 #include "lldb/Expression/IRInterpreter.h"
24 #include "lldb/Expression/Materializer.h"
25 #include "lldb/Host/HostInfo.h"
26 #include "lldb/Symbol/Block.h"
27 #include "lldb/Symbol/ClangASTContext.h"
28 #include "lldb/Symbol/Function.h"
29 #include "lldb/Symbol/ObjectFile.h"
30 #include "lldb/Symbol/SymbolVendor.h"
31 #include "lldb/Symbol/Type.h"
32 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
33 #include "lldb/Symbol/VariableList.h"
34 #include "lldb/Target/ExecutionContext.h"
35 #include "lldb/Target/Process.h"
36 #include "lldb/Target/StackFrame.h"
37 #include "lldb/Target/Target.h"
38 #include "lldb/Target/ThreadPlan.h"
39 #include "lldb/Target/ThreadPlanCallUserExpression.h"
40 
41 using namespace lldb_private;
42 
43 LLVMUserExpression::LLVMUserExpression(ExecutionContextScope &exe_scope,
44                                        const char *expr,
45                                        const char *expr_prefix,
46                                        lldb::LanguageType language,
47                                        ResultType desired_type,
48                                        const EvaluateExpressionOptions &options)
49     : UserExpression(exe_scope, expr, expr_prefix, language, desired_type, options),
50       m_stack_frame_bottom(LLDB_INVALID_ADDRESS),
51       m_stack_frame_top(LLDB_INVALID_ADDRESS),
52       m_transformed_text(),
53       m_execution_unit_sp(),
54       m_materializer_ap(),
55       m_jit_module_wp(),
56       m_enforce_valid_object(true),
57       m_in_cplusplus_method(false),
58       m_in_objectivec_method(false),
59       m_in_static_method(false),
60       m_needs_object_ptr(false),
61       m_const_object(false),
62       m_target(NULL),
63       m_can_interpret(false),
64       m_materialized_address(LLDB_INVALID_ADDRESS)
65 {
66 }
67 
68 LLVMUserExpression::~LLVMUserExpression()
69 {
70     if (m_target)
71     {
72         lldb::ModuleSP jit_module_sp(m_jit_module_wp.lock());
73         if (jit_module_sp)
74             m_target->GetImages().Remove(jit_module_sp);
75     }
76 }
77 
78 lldb::ExpressionResults
79 LLVMUserExpression::Execute(Stream &error_stream, ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options,
80                             lldb::UserExpressionSP &shared_ptr_to_me, lldb::ExpressionVariableSP &result)
81 {
82     // The expression log is quite verbose, and if you're just tracking the execution of the
83     // expression, it's quite convenient to have these logs come out with the STEP log as well.
84     Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
85 
86     if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret)
87     {
88         lldb::addr_t struct_address = LLDB_INVALID_ADDRESS;
89 
90         if (!PrepareToExecuteJITExpression(error_stream, exe_ctx, struct_address))
91         {
92             error_stream.Printf("Errored out in %s, couldn't PrepareToExecuteJITExpression", __FUNCTION__);
93             return lldb::eExpressionSetupError;
94         }
95 
96         lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS;
97         lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS;
98 
99         if (m_can_interpret)
100         {
101             llvm::Module *module = m_execution_unit_sp->GetModule();
102             llvm::Function *function = m_execution_unit_sp->GetFunction();
103 
104             if (!module || !function)
105             {
106                 error_stream.Printf("Supposed to interpret, but nothing is there");
107                 return lldb::eExpressionSetupError;
108             }
109 
110             Error interpreter_error;
111 
112             std::vector<lldb::addr_t> args;
113 
114             if (!AddArguments(exe_ctx, args, struct_address, error_stream))
115             {
116                 error_stream.Printf("Errored out in %s, couldn't AddArguments", __FUNCTION__);
117                 return lldb::eExpressionSetupError;
118             }
119 
120             function_stack_bottom = m_stack_frame_bottom;
121             function_stack_top = m_stack_frame_top;
122 
123             IRInterpreter::Interpret(*module, *function, args, *m_execution_unit_sp.get(), interpreter_error,
124                                      function_stack_bottom, function_stack_top, exe_ctx);
125 
126             if (!interpreter_error.Success())
127             {
128                 error_stream.Printf("Supposed to interpret, but failed: %s", interpreter_error.AsCString());
129                 return lldb::eExpressionDiscarded;
130             }
131         }
132         else
133         {
134             if (!exe_ctx.HasThreadScope())
135             {
136                 error_stream.Printf("UserExpression::Execute called with no thread selected.");
137                 return lldb::eExpressionSetupError;
138             }
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, error_stream))
145             {
146                 error_stream.Printf("Errored out in %s, couldn't AddArguments", __FUNCTION__);
147                 return lldb::eExpressionSetupError;
148             }
149 
150             lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallUserExpression(exe_ctx.GetThreadRef(), wrapper_address,
151                                                                              args, options, shared_ptr_to_me));
152 
153             if (!call_plan_sp || !call_plan_sp->ValidatePlan(&error_stream))
154                 return lldb::eExpressionSetupError;
155 
156             ThreadPlanCallUserExpression *user_expression_plan =
157                 static_cast<ThreadPlanCallUserExpression *>(call_plan_sp.get());
158 
159             lldb::addr_t function_stack_pointer = user_expression_plan->GetFunctionStackPointer();
160 
161             function_stack_bottom = function_stack_pointer - HostInfo::GetPageSize();
162             function_stack_top = function_stack_pointer;
163 
164             if (log)
165                 log->Printf("-- [UserExpression::Execute] Execution of expression begins --");
166 
167             if (exe_ctx.GetProcessPtr())
168                 exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
169 
170             lldb::ExpressionResults execution_result =
171                 exe_ctx.GetProcessRef().RunThreadPlan(exe_ctx, call_plan_sp, options, error_stream);
172 
173             if (exe_ctx.GetProcessPtr())
174                 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
175 
176             if (log)
177                 log->Printf("-- [UserExpression::Execute] Execution of expression completed --");
178 
179             if (execution_result == lldb::eExpressionInterrupted || execution_result == lldb::eExpressionHitBreakpoint)
180             {
181                 const char *error_desc = NULL;
182 
183                 if (call_plan_sp)
184                 {
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                     error_stream.Printf("Execution was interrupted, reason: %s.", error_desc);
191                 else
192                     error_stream.PutCString("Execution was interrupted.");
193 
194                 if ((execution_result == lldb::eExpressionInterrupted && options.DoesUnwindOnError()) ||
195                     (execution_result == lldb::eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints()))
196                     error_stream.PutCString(
197                         "\nThe process has been returned to the state before expression evaluation.");
198                 else
199                 {
200                     if (execution_result == lldb::eExpressionHitBreakpoint)
201                         user_expression_plan->TransferExpressionOwnership();
202                     error_stream.PutCString(
203                         "\nThe process has been left at the point where it was interrupted, "
204                         "use \"thread return -x\" to return to the state before expression evaluation.");
205                 }
206 
207                 return execution_result;
208             }
209             else if (execution_result == lldb::eExpressionStoppedForDebug)
210             {
211                 error_stream.PutCString(
212                     "Execution was halted at the first instruction of the expression "
213                     "function because \"debug\" was requested.\n"
214                     "Use \"thread return -x\" to return to the state before expression evaluation.");
215                 return execution_result;
216             }
217             else if (execution_result != lldb::eExpressionCompleted)
218             {
219                 error_stream.Printf("Couldn't execute function; result was %s\n",
220                                     Process::ExecutionResultAsCString(execution_result));
221                 return execution_result;
222             }
223         }
224 
225         if (FinalizeJITExecution(error_stream, exe_ctx, result, function_stack_bottom, function_stack_top))
226         {
227             return lldb::eExpressionCompleted;
228         }
229         else
230         {
231             return lldb::eExpressionResultUnavailable;
232         }
233     }
234     else
235     {
236         error_stream.Printf("Expression can't be run, because there is no JIT compiled function");
237         return lldb::eExpressionSetupError;
238     }
239 }
240 
241 bool
242 LLVMUserExpression::FinalizeJITExecution(Stream &error_stream, ExecutionContext &exe_ctx,
243                                          lldb::ExpressionVariableSP &result, lldb::addr_t function_stack_bottom,
244                                          lldb::addr_t function_stack_top)
245 {
246     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
247 
248     if (log)
249         log->Printf("-- [UserExpression::FinalizeJITExecution] Dematerializing after execution --");
250 
251     if (!m_dematerializer_sp)
252     {
253         error_stream.Printf("Couldn't apply expression side effects : no dematerializer is present");
254         return false;
255     }
256 
257     Error dematerialize_error;
258 
259     m_dematerializer_sp->Dematerialize(dematerialize_error, function_stack_bottom, function_stack_top);
260 
261     if (!dematerialize_error.Success())
262     {
263         error_stream.Printf("Couldn't apply expression side effects : %s\n",
264                             dematerialize_error.AsCString("unknown error"));
265         return false;
266     }
267 
268     result = GetResultAfterDematerialization(exe_ctx.GetBestExecutionContextScope());
269 
270     if (result)
271         result->TransferAddress();
272 
273     m_dematerializer_sp.reset();
274 
275     return true;
276 }
277 
278 bool
279 LLVMUserExpression::PrepareToExecuteJITExpression(Stream &error_stream, ExecutionContext &exe_ctx,
280                                                   lldb::addr_t &struct_address)
281 {
282     lldb::TargetSP target;
283     lldb::ProcessSP process;
284     lldb::StackFrameSP frame;
285 
286     if (!LockAndCheckContext(exe_ctx, target, process, frame))
287     {
288         error_stream.Printf("The context has changed before we could JIT the expression!\n");
289         return false;
290     }
291 
292     if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret)
293     {
294         if (m_materialized_address == LLDB_INVALID_ADDRESS)
295         {
296             Error alloc_error;
297 
298             IRMemoryMap::AllocationPolicy policy =
299                 m_can_interpret ? IRMemoryMap::eAllocationPolicyHostOnly : IRMemoryMap::eAllocationPolicyMirror;
300 
301             const bool zero_memory = false;
302 
303             m_materialized_address = m_execution_unit_sp->Malloc(m_materializer_ap->GetStructByteSize(),
304                                                                  m_materializer_ap->GetStructAlignment(),
305                                                                  lldb::ePermissionsReadable | lldb::ePermissionsWritable,
306                                                                  policy,
307                                                                  zero_memory,
308                                                                  alloc_error);
309 
310             if (!alloc_error.Success())
311             {
312                 error_stream.Printf("Couldn't allocate space for materialized struct: %s\n", alloc_error.AsCString());
313                 return false;
314             }
315         }
316 
317         struct_address = m_materialized_address;
318 
319         if (m_can_interpret && m_stack_frame_bottom == LLDB_INVALID_ADDRESS)
320         {
321             Error alloc_error;
322 
323             const size_t stack_frame_size = 512 * 1024;
324 
325             const bool zero_memory = false;
326 
327             m_stack_frame_bottom = m_execution_unit_sp->Malloc(stack_frame_size,
328                                                                8,
329                                                                lldb::ePermissionsReadable | lldb::ePermissionsWritable,
330                                                                IRMemoryMap::eAllocationPolicyHostOnly,
331                                                                zero_memory,
332                                                                alloc_error);
333 
334             m_stack_frame_top = m_stack_frame_bottom + stack_frame_size;
335 
336             if (!alloc_error.Success())
337             {
338                 error_stream.Printf("Couldn't allocate space for the stack frame: %s\n", alloc_error.AsCString());
339                 return false;
340             }
341         }
342 
343         Error materialize_error;
344 
345         m_dematerializer_sp =
346             m_materializer_ap->Materialize(frame, *m_execution_unit_sp, struct_address, materialize_error);
347 
348         if (!materialize_error.Success())
349         {
350             error_stream.Printf("Couldn't materialize: %s\n", materialize_error.AsCString());
351             return false;
352         }
353     }
354     return true;
355 }
356 
357 lldb::ModuleSP
358 LLVMUserExpression::GetJITModule()
359 {
360     if (m_execution_unit_sp)
361         return m_execution_unit_sp->GetJITModule();
362     return lldb::ModuleSP();
363 }
364