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/DiagnosticManager.h"
22 #include "lldb/Expression/ExpressionSourceCode.h"
23 #include "lldb/Expression/IRExecutionUnit.h"
24 #include "lldb/Expression/IRInterpreter.h"
25 #include "lldb/Expression/Materializer.h"
26 #include "lldb/Host/HostInfo.h"
27 #include "lldb/Symbol/Block.h"
28 #include "lldb/Symbol/ClangASTContext.h"
29 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
30 #include "lldb/Symbol/Function.h"
31 #include "lldb/Symbol/ObjectFile.h"
32 #include "lldb/Symbol/SymbolVendor.h"
33 #include "lldb/Symbol/Type.h"
34 #include "lldb/Symbol/VariableList.h"
35 #include "lldb/Target/ExecutionContext.h"
36 #include "lldb/Target/Process.h"
37 #include "lldb/Target/StackFrame.h"
38 #include "lldb/Target/Target.h"
39 #include "lldb/Target/ThreadPlan.h"
40 #include "lldb/Target/ThreadPlanCallUserExpression.h"
41 
42 using namespace lldb_private;
43 
44 LLVMUserExpression::LLVMUserExpression(ExecutionContextScope &exe_scope,
45                                        const char *expr,
46                                        const char *expr_prefix,
47                                        lldb::LanguageType language,
48                                        ResultType desired_type,
49                                        const EvaluateExpressionOptions &options)
50     : UserExpression(exe_scope, expr, expr_prefix, language, desired_type, options),
51       m_stack_frame_bottom(LLDB_INVALID_ADDRESS),
52       m_stack_frame_top(LLDB_INVALID_ADDRESS),
53       m_transformed_text(),
54       m_execution_unit_sp(),
55       m_materializer_ap(),
56       m_jit_module_wp(),
57       m_enforce_valid_object(true),
58       m_in_cplusplus_method(false),
59       m_in_objectivec_method(false),
60       m_in_static_method(false),
61       m_needs_object_ptr(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::DoExecute(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
80                               const EvaluateExpressionOptions &options, lldb::UserExpressionSP &shared_ptr_to_me,
81                               lldb::ExpressionVariableSP &result)
82 {
83     // The expression log is quite verbose, and if you're just tracking the execution of the
84     // expression, it's quite convenient to have these logs come out with the STEP log as well.
85     Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
86 
87     if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret)
88     {
89         lldb::addr_t struct_address = LLDB_INVALID_ADDRESS;
90 
91         if (!PrepareToExecuteJITExpression(diagnostic_manager, exe_ctx, struct_address))
92         {
93             diagnostic_manager.Printf(eDiagnosticSeverityError,
94                                       "errored out in %s, couldn't PrepareToExecuteJITExpression", __FUNCTION__);
95             return lldb::eExpressionSetupError;
96         }
97 
98         lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS;
99         lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS;
100 
101         if (m_can_interpret)
102         {
103             llvm::Module *module = m_execution_unit_sp->GetModule();
104             llvm::Function *function = m_execution_unit_sp->GetFunction();
105 
106             if (!module || !function)
107             {
108                 diagnostic_manager.PutCString(eDiagnosticSeverityError, "supposed to interpret, but nothing is there");
109                 return lldb::eExpressionSetupError;
110             }
111 
112             Error interpreter_error;
113 
114             std::vector<lldb::addr_t> args;
115 
116             if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager))
117             {
118                 diagnostic_manager.Printf(eDiagnosticSeverityError, "errored out in %s, couldn't AddArguments",
119                                           __FUNCTION__);
120                 return lldb::eExpressionSetupError;
121             }
122 
123             function_stack_bottom = m_stack_frame_bottom;
124             function_stack_top = m_stack_frame_top;
125 
126             IRInterpreter::Interpret(*module, *function, args, *m_execution_unit_sp.get(), interpreter_error,
127                 function_stack_bottom, function_stack_top, exe_ctx);
128 
129             if (!interpreter_error.Success())
130             {
131                 diagnostic_manager.Printf(eDiagnosticSeverityError, "supposed to interpret, but failed: %s",
132                                           interpreter_error.AsCString());
133                 return lldb::eExpressionDiscarded;
134             }
135         }
136         else
137         {
138             if (!exe_ctx.HasThreadScope())
139             {
140                 diagnostic_manager.Printf(eDiagnosticSeverityError, "%s called with no thread selected", __FUNCTION__);
141                 return lldb::eExpressionSetupError;
142             }
143 
144             Address wrapper_address(m_jit_start_addr);
145 
146             std::vector<lldb::addr_t> args;
147 
148             if (!AddArguments(exe_ctx, args, struct_address, diagnostic_manager))
149             {
150                 diagnostic_manager.Printf(eDiagnosticSeverityError, "errored out in %s, couldn't AddArguments",
151                                           __FUNCTION__);
152                 return lldb::eExpressionSetupError;
153             }
154 
155             lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallUserExpression(exe_ctx.GetThreadRef(), wrapper_address,
156                                                                              args, options, shared_ptr_to_me));
157 
158             StreamString ss;
159             if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss))
160             {
161                 diagnostic_manager.PutCString(eDiagnosticSeverityError, ss.GetData());
162                 return lldb::eExpressionSetupError;
163             }
164 
165             ThreadPlanCallUserExpression *user_expression_plan =
166                 static_cast<ThreadPlanCallUserExpression *>(call_plan_sp.get());
167 
168             lldb::addr_t function_stack_pointer = user_expression_plan->GetFunctionStackPointer();
169 
170             function_stack_bottom = function_stack_pointer - HostInfo::GetPageSize();
171             function_stack_top = function_stack_pointer;
172 
173             if (log)
174                 log->Printf("-- [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, diagnostic_manager);
181 
182             if (exe_ctx.GetProcessPtr())
183                 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
184 
185             if (log)
186                 log->Printf("-- [UserExpression::Execute] Execution of expression completed --");
187 
188             if (execution_result == lldb::eExpressionInterrupted || execution_result == lldb::eExpressionHitBreakpoint)
189             {
190                 const char *error_desc = NULL;
191 
192                 if (call_plan_sp)
193                 {
194                     lldb::StopInfoSP real_stop_info_sp = call_plan_sp->GetRealStopInfo();
195                     if (real_stop_info_sp)
196                         error_desc = real_stop_info_sp->GetDescription();
197                 }
198                 if (error_desc)
199                     diagnostic_manager.Printf(eDiagnosticSeverityError, "Execution was interrupted, reason: %s.",
200                                               error_desc);
201                 else
202                     diagnostic_manager.PutCString(eDiagnosticSeverityError, "Execution was interrupted.");
203 
204                 if ((execution_result == lldb::eExpressionInterrupted && options.DoesUnwindOnError()) ||
205                     (execution_result == lldb::eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints()))
206                     diagnostic_manager.AppendMessageToDiagnostic(
207                         "The process has been returned to the state before expression evaluation.");
208                 else
209                 {
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 interrupted, "
214                         "use \"thread return -x\" to return to the state before expression evaluation.");
215                 }
216 
217                 return execution_result;
218             }
219             else if (execution_result == lldb::eExpressionStoppedForDebug)
220             {
221                 diagnostic_manager.PutCString(
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 evaluation.");
226                 return execution_result;
227             }
228             else if (execution_result != lldb::eExpressionCompleted)
229             {
230                 diagnostic_manager.Printf(eDiagnosticSeverityError, "Couldn't execute function; result was %s",
231                                           Process::ExecutionResultAsCString(execution_result));
232                 return execution_result;
233             }
234         }
235 
236         if (FinalizeJITExecution(diagnostic_manager, exe_ctx, result, function_stack_bottom, function_stack_top))
237         {
238             return lldb::eExpressionCompleted;
239         }
240         else
241         {
242             return lldb::eExpressionResultUnavailable;
243         }
244     }
245     else
246     {
247         diagnostic_manager.PutCString(eDiagnosticSeverityError,
248                                       "Expression can't be run, because there is no JIT compiled function");
249         return lldb::eExpressionSetupError;
250     }
251 }
252 
253 bool
254 LLVMUserExpression::FinalizeJITExecution(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
255                                          lldb::ExpressionVariableSP &result, lldb::addr_t function_stack_bottom,
256                                          lldb::addr_t function_stack_top)
257 {
258     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
259 
260     if (log)
261         log->Printf("-- [UserExpression::FinalizeJITExecution] Dematerializing after execution --");
262 
263     if (!m_dematerializer_sp)
264     {
265         diagnostic_manager.Printf(eDiagnosticSeverityError,
266                                   "Couldn't apply expression side effects : no dematerializer is present");
267         return false;
268     }
269 
270     Error dematerialize_error;
271 
272     m_dematerializer_sp->Dematerialize(dematerialize_error, function_stack_bottom, function_stack_top);
273 
274     if (!dematerialize_error.Success())
275     {
276         diagnostic_manager.Printf(eDiagnosticSeverityError, "Couldn't apply expression side effects : %s",
277                                   dematerialize_error.AsCString("unknown error"));
278         return false;
279     }
280 
281     result = 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
292 LLVMUserExpression::PrepareToExecuteJITExpression(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx,
293                                                   lldb::addr_t &struct_address)
294 {
295     lldb::TargetSP target;
296     lldb::ProcessSP process;
297     lldb::StackFrameSP frame;
298 
299     if (!LockAndCheckContext(exe_ctx, target, process, frame))
300     {
301         diagnostic_manager.PutCString(eDiagnosticSeverityError,
302                                       "The context has changed before we could JIT the expression!");
303         return false;
304     }
305 
306     if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret)
307     {
308         if (m_materialized_address == LLDB_INVALID_ADDRESS)
309         {
310             Error alloc_error;
311 
312             IRMemoryMap::AllocationPolicy policy =
313                 m_can_interpret ? IRMemoryMap::eAllocationPolicyHostOnly : IRMemoryMap::eAllocationPolicyMirror;
314 
315             const bool zero_memory = false;
316 
317             m_materialized_address = m_execution_unit_sp->Malloc(m_materializer_ap->GetStructByteSize(),
318                                                                  m_materializer_ap->GetStructAlignment(),
319                                                                  lldb::ePermissionsReadable | lldb::ePermissionsWritable,
320                                                                  policy,
321                                                                  zero_memory,
322                                                                  alloc_error);
323 
324             if (!alloc_error.Success())
325             {
326                 diagnostic_manager.Printf(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         {
337             Error alloc_error;
338 
339             const size_t stack_frame_size = 512 * 1024;
340 
341             const bool zero_memory = false;
342 
343             m_stack_frame_bottom = m_execution_unit_sp->Malloc(stack_frame_size,
344                                                                8,
345                                                                lldb::ePermissionsReadable | lldb::ePermissionsWritable,
346                                                                IRMemoryMap::eAllocationPolicyHostOnly,
347                                                                zero_memory,
348                                                                alloc_error);
349 
350             m_stack_frame_top = m_stack_frame_bottom + stack_frame_size;
351 
352             if (!alloc_error.Success())
353             {
354                 diagnostic_manager.Printf(eDiagnosticSeverityError, "Couldn't allocate space for the stack frame: %s",
355                                           alloc_error.AsCString());
356                 return false;
357             }
358         }
359 
360         Error materialize_error;
361 
362         m_dematerializer_sp =
363             m_materializer_ap->Materialize(frame, *m_execution_unit_sp, struct_address, materialize_error);
364 
365         if (!materialize_error.Success())
366         {
367             diagnostic_manager.Printf(eDiagnosticSeverityError, "Couldn't materialize: %s",
368                                       materialize_error.AsCString());
369             return false;
370         }
371     }
372     return true;
373 }
374 
375 lldb::ModuleSP
376 LLVMUserExpression::GetJITModule()
377 {
378     if (m_execution_unit_sp)
379         return m_execution_unit_sp->GetJITModule();
380     return lldb::ModuleSP();
381 }
382