blob: 547c02a13178c635b07750644ff80a115010ff56 [file] [log] [blame]
Jim Ingham151c0322015-09-15 21:13:50 +00001//===-- UserExpression.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#include <stdio.h>
11#if HAVE_SYS_TYPES_H
12# include <sys/types.h>
13#endif
14
15#include <cstdlib>
16#include <string>
17#include <map>
18
19#include "lldb/Core/ConstString.h"
20#include "lldb/Core/Log.h"
21#include "lldb/Core/Module.h"
22#include "lldb/Core/StreamFile.h"
23#include "lldb/Core/StreamString.h"
24#include "lldb/Core/ValueObjectConstResult.h"
25#include "lldb/Expression/ASTResultSynthesizer.h"
26#include "lldb/Expression/ClangExpressionDeclMap.h"
27#include "lldb/Expression/ClangExpressionParser.h"
28#include "lldb/Expression/ClangModulesDeclVendor.h"
29#include "lldb/Expression/ClangPersistentVariables.h"
30#include "lldb/Expression/ExpressionSourceCode.h"
31#include "lldb/Expression/IRExecutionUnit.h"
32#include "lldb/Expression/IRInterpreter.h"
33#include "lldb/Expression/Materializer.h"
34#include "lldb/Expression/UserExpression.h"
35#include "lldb/Host/HostInfo.h"
36#include "lldb/Symbol/Block.h"
37#include "lldb/Symbol/ClangASTContext.h"
38#include "lldb/Symbol/Function.h"
39#include "lldb/Symbol/ObjectFile.h"
40#include "lldb/Symbol/SymbolVendor.h"
41#include "lldb/Symbol/Type.h"
42#include "lldb/Symbol/ClangExternalASTSourceCommon.h"
43#include "lldb/Symbol/VariableList.h"
44#include "lldb/Target/ExecutionContext.h"
45#include "lldb/Target/Process.h"
46#include "lldb/Target/StackFrame.h"
47#include "lldb/Target/Target.h"
48#include "lldb/Target/ThreadPlan.h"
49#include "lldb/Target/ThreadPlanCallUserExpression.h"
50
51#include "clang/AST/DeclCXX.h"
52#include "clang/AST/DeclObjC.h"
53
54using namespace lldb_private;
55
56UserExpression::UserExpression (ExecutionContextScope &exe_scope,
57 const char *expr,
58 const char *expr_prefix,
59 lldb::LanguageType language,
60 ResultType desired_type) :
61 Expression (exe_scope),
62 m_stack_frame_bottom (LLDB_INVALID_ADDRESS),
63 m_stack_frame_top (LLDB_INVALID_ADDRESS),
64 m_expr_text (expr),
65 m_expr_prefix (expr_prefix ? expr_prefix : ""),
66 m_language (language),
67 m_transformed_text (),
68 m_desired_type (desired_type),
69 m_execution_unit_sp(),
70 m_materializer_ap(),
71 m_jit_module_wp(),
72 m_enforce_valid_object (true),
73 m_in_cplusplus_method (false),
74 m_in_objectivec_method (false),
75 m_in_static_method(false),
76 m_needs_object_ptr (false),
77 m_const_object (false),
78 m_target (NULL),
79 m_can_interpret (false),
80 m_materialized_address (LLDB_INVALID_ADDRESS)
81{
82}
83
84UserExpression::~UserExpression ()
85{
86 if (m_target)
87 {
88 lldb::ModuleSP jit_module_sp (m_jit_module_wp.lock());
89 if (jit_module_sp)
90 m_target->GetImages().Remove(jit_module_sp);
91 }
92}
93
94void
95UserExpression::InstallContext (ExecutionContext &exe_ctx)
96{
97 m_jit_process_wp = exe_ctx.GetProcessSP();
98
99 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
100
101 if (frame_sp)
102 m_address = frame_sp->GetFrameCodeAddress();
103}
104
105bool
106UserExpression::LockAndCheckContext (ExecutionContext &exe_ctx,
107 lldb::TargetSP &target_sp,
108 lldb::ProcessSP &process_sp,
109 lldb::StackFrameSP &frame_sp)
110{
111 lldb::ProcessSP expected_process_sp = m_jit_process_wp.lock();
112 process_sp = exe_ctx.GetProcessSP();
113
114 if (process_sp != expected_process_sp)
115 return false;
116
117 process_sp = exe_ctx.GetProcessSP();
118 target_sp = exe_ctx.GetTargetSP();
119 frame_sp = exe_ctx.GetFrameSP();
120
121 if (m_address.IsValid())
122 {
123 if (!frame_sp)
124 return false;
125 else
126 return (0 == Address::CompareLoadAddress(m_address, frame_sp->GetFrameCodeAddress(), target_sp.get()));
127 }
128
129 return true;
130}
131
132bool
133UserExpression::MatchesContext (ExecutionContext &exe_ctx)
134{
135 lldb::TargetSP target_sp;
136 lldb::ProcessSP process_sp;
137 lldb::StackFrameSP frame_sp;
138
139 return LockAndCheckContext(exe_ctx, target_sp, process_sp, frame_sp);
140}
141
142lldb::addr_t
143UserExpression::GetObjectPointer (lldb::StackFrameSP frame_sp,
144 ConstString &object_name,
145 Error &err)
146{
147 err.Clear();
148
149 if (!frame_sp)
150 {
151 err.SetErrorStringWithFormat("Couldn't load '%s' because the context is incomplete", object_name.AsCString());
152 return LLDB_INVALID_ADDRESS;
153 }
154
155 lldb::VariableSP var_sp;
156 lldb::ValueObjectSP valobj_sp;
157
158 valobj_sp = frame_sp->GetValueForVariableExpressionPath(object_name.AsCString(),
159 lldb::eNoDynamicValues,
160 StackFrame::eExpressionPathOptionCheckPtrVsMember |
161 StackFrame::eExpressionPathOptionsNoFragileObjcIvar |
162 StackFrame::eExpressionPathOptionsNoSyntheticChildren |
163 StackFrame::eExpressionPathOptionsNoSyntheticArrayRange,
164 var_sp,
165 err);
166
167 if (!err.Success() || !valobj_sp.get())
168 return LLDB_INVALID_ADDRESS;
169
170 lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
171
172 if (ret == LLDB_INVALID_ADDRESS)
173 {
174 err.SetErrorStringWithFormat("Couldn't load '%s' because its value couldn't be evaluated", object_name.AsCString());
175 return LLDB_INVALID_ADDRESS;
176 }
177
178 return ret;
179}
180
181bool
182UserExpression::PrepareToExecuteJITExpression (Stream &error_stream,
183 ExecutionContext &exe_ctx,
184 lldb::addr_t &struct_address)
185{
186 lldb::TargetSP target;
187 lldb::ProcessSP process;
188 lldb::StackFrameSP frame;
189
190 if (!LockAndCheckContext(exe_ctx,
191 target,
192 process,
193 frame))
194 {
195 error_stream.Printf("The context has changed before we could JIT the expression!\n");
196 return false;
197 }
198
199 if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret)
200 {
201 if (m_materialized_address == LLDB_INVALID_ADDRESS)
202 {
203 Error alloc_error;
204
205 IRMemoryMap::AllocationPolicy policy = m_can_interpret ? IRMemoryMap::eAllocationPolicyHostOnly : IRMemoryMap::eAllocationPolicyMirror;
206
207 m_materialized_address = m_execution_unit_sp->Malloc(m_materializer_ap->GetStructByteSize(),
208 m_materializer_ap->GetStructAlignment(),
209 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
210 policy,
211 alloc_error);
212
213 if (!alloc_error.Success())
214 {
215 error_stream.Printf("Couldn't allocate space for materialized struct: %s\n", alloc_error.AsCString());
216 return false;
217 }
218 }
219
220 struct_address = m_materialized_address;
221
222 if (m_can_interpret && m_stack_frame_bottom == LLDB_INVALID_ADDRESS)
223 {
224 Error alloc_error;
225
226 const size_t stack_frame_size = 512 * 1024;
227
228 m_stack_frame_bottom = m_execution_unit_sp->Malloc(stack_frame_size,
229 8,
230 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
231 IRMemoryMap::eAllocationPolicyHostOnly,
232 alloc_error);
233
234 m_stack_frame_top = m_stack_frame_bottom + stack_frame_size;
235
236 if (!alloc_error.Success())
237 {
238 error_stream.Printf("Couldn't allocate space for the stack frame: %s\n", alloc_error.AsCString());
239 return false;
240 }
241 }
242
243 Error materialize_error;
244
245 m_dematerializer_sp = m_materializer_ap->Materialize(frame, *m_execution_unit_sp, struct_address, materialize_error);
246
247 if (!materialize_error.Success())
248 {
249 error_stream.Printf("Couldn't materialize: %s\n", materialize_error.AsCString());
250 return false;
251 }
252 }
253 return true;
254}
255
256bool
257UserExpression::FinalizeJITExecution (Stream &error_stream,
258 ExecutionContext &exe_ctx,
259 lldb::ExpressionVariableSP &result,
260 lldb::addr_t function_stack_bottom,
261 lldb::addr_t function_stack_top)
262{
263 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
264
265 if (log)
266 log->Printf("-- [UserExpression::FinalizeJITExecution] Dematerializing after execution --");
267
268 if (!m_dematerializer_sp)
269 {
270 error_stream.Printf ("Couldn't apply expression side effects : no dematerializer is present");
271 return false;
272 }
273
274 Error dematerialize_error;
275
276 m_dematerializer_sp->Dematerialize(dematerialize_error, result, function_stack_bottom, function_stack_top);
277
278 if (!dematerialize_error.Success())
279 {
280 error_stream.Printf ("Couldn't apply expression side effects : %s\n", dematerialize_error.AsCString("unknown error"));
281 return false;
282 }
283
284 if (result)
285 result->TransferAddress();
286
287 m_dematerializer_sp.reset();
288
289 return true;
290}
291
292lldb::ExpressionResults
293UserExpression::Execute (Stream &error_stream,
294 ExecutionContext &exe_ctx,
295 const EvaluateExpressionOptions& options,
296 lldb::UserExpressionSP &shared_ptr_to_me,
297 lldb::ExpressionVariableSP &result)
298{
299 // The expression log is quite verbose, and if you're just tracking the execution of the
300 // expression, it's quite convenient to have these logs come out with the STEP log as well.
301 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
302
303 if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret)
304 {
305 lldb::addr_t struct_address = LLDB_INVALID_ADDRESS;
306
307 if (!PrepareToExecuteJITExpression (error_stream, exe_ctx, struct_address))
308 {
309 error_stream.Printf("Errored out in %s, couldn't PrepareToExecuteJITExpression", __FUNCTION__);
310 return lldb::eExpressionSetupError;
311 }
312
313 lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS;
314 lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS;
315
316 if (m_can_interpret)
317 {
318 llvm::Module *module = m_execution_unit_sp->GetModule();
319 llvm::Function *function = m_execution_unit_sp->GetFunction();
320
321 if (!module || !function)
322 {
323 error_stream.Printf("Supposed to interpret, but nothing is there");
324 return lldb::eExpressionSetupError;
325 }
326
327 Error interpreter_error;
328
329 std::vector<lldb::addr_t> args;
330
331 if (!AddInitialArguments(exe_ctx, args, error_stream))
332 {
333 error_stream.Printf ("Errored out in %s, couldn't AddInitialArguments", __FUNCTION__);
334 return lldb::eExpressionSetupError;
335 }
336
337 args.push_back(struct_address);
338
339 function_stack_bottom = m_stack_frame_bottom;
340 function_stack_top = m_stack_frame_top;
341
342 IRInterpreter::Interpret (*module,
343 *function,
344 args,
345 *m_execution_unit_sp.get(),
346 interpreter_error,
347 function_stack_bottom,
348 function_stack_top,
349 exe_ctx);
350
351 if (!interpreter_error.Success())
352 {
353 error_stream.Printf("Supposed to interpret, but failed: %s", interpreter_error.AsCString());
354 return lldb::eExpressionDiscarded;
355 }
356 }
357 else
358 {
359 if (!exe_ctx.HasThreadScope())
360 {
361 error_stream.Printf("UserExpression::Execute called with no thread selected.");
362 return lldb::eExpressionSetupError;
363 }
364
365 Address wrapper_address (m_jit_start_addr);
366
367 std::vector<lldb::addr_t> args;
368
369 if (!AddInitialArguments(exe_ctx, args, error_stream))
370 {
371 error_stream.Printf ("Errored out in %s, couldn't AddInitialArguments", __FUNCTION__);
372 return lldb::eExpressionSetupError;
373 }
374
375 args.push_back(struct_address);
376
377 lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallUserExpression (exe_ctx.GetThreadRef(),
378 wrapper_address,
379 args,
380 options,
381 shared_ptr_to_me));
382
383 if (!call_plan_sp || !call_plan_sp->ValidatePlan (&error_stream))
384 return lldb::eExpressionSetupError;
385
386 ThreadPlanCallUserExpression *user_expression_plan = static_cast<ThreadPlanCallUserExpression *>(call_plan_sp.get());
387
388 lldb::addr_t function_stack_pointer = user_expression_plan->GetFunctionStackPointer();
389
390 function_stack_bottom = function_stack_pointer - HostInfo::GetPageSize();
391 function_stack_top = function_stack_pointer;
392
393 if (log)
394 log->Printf("-- [UserExpression::Execute] Execution of expression begins --");
395
396 if (exe_ctx.GetProcessPtr())
397 exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
398
399 lldb::ExpressionResults execution_result = exe_ctx.GetProcessRef().RunThreadPlan (exe_ctx,
400 call_plan_sp,
401 options,
402 error_stream);
403
404 if (exe_ctx.GetProcessPtr())
405 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
406
407 if (log)
408 log->Printf("-- [UserExpression::Execute] Execution of expression completed --");
409
410 if (execution_result == lldb::eExpressionInterrupted || execution_result == lldb::eExpressionHitBreakpoint)
411 {
412 const char *error_desc = NULL;
413
414 if (call_plan_sp)
415 {
416 lldb::StopInfoSP real_stop_info_sp = call_plan_sp->GetRealStopInfo();
417 if (real_stop_info_sp)
418 error_desc = real_stop_info_sp->GetDescription();
419 }
420 if (error_desc)
421 error_stream.Printf ("Execution was interrupted, reason: %s.", error_desc);
422 else
423 error_stream.PutCString ("Execution was interrupted.");
424
425 if ((execution_result == lldb::eExpressionInterrupted && options.DoesUnwindOnError())
426 || (execution_result == lldb::eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints()))
427 error_stream.PutCString ("\nThe process has been returned to the state before expression evaluation.");
428 else
429 {
430 if (execution_result == lldb::eExpressionHitBreakpoint)
431 user_expression_plan->TransferExpressionOwnership();
432 error_stream.PutCString ("\nThe process has been left at the point where it was interrupted, "
433 "use \"thread return -x\" to return to the state before expression evaluation.");
434 }
435
436 return execution_result;
437 }
438 else if (execution_result == lldb::eExpressionStoppedForDebug)
439 {
440 error_stream.PutCString ("Execution was halted at the first instruction of the expression "
441 "function because \"debug\" was requested.\n"
442 "Use \"thread return -x\" to return to the state before expression evaluation.");
443 return execution_result;
444 }
445 else if (execution_result != lldb::eExpressionCompleted)
446 {
447 error_stream.Printf ("Couldn't execute function; result was %s\n", Process::ExecutionResultAsCString (execution_result));
448 return execution_result;
449 }
450 }
451
452 if (FinalizeJITExecution (error_stream, exe_ctx, result, function_stack_bottom, function_stack_top))
453 {
454 return lldb::eExpressionCompleted;
455 }
456 else
457 {
458 return lldb::eExpressionResultUnavailable;
459 }
460 }
461 else
462 {
463 error_stream.Printf("Expression can't be run, because there is no JIT compiled function");
464 return lldb::eExpressionSetupError;
465 }
466}
467
468lldb::ExpressionResults
469UserExpression::Evaluate (ExecutionContext &exe_ctx,
470 const EvaluateExpressionOptions& options,
471 const char *expr_cstr,
472 const char *expr_prefix,
473 lldb::ValueObjectSP &result_valobj_sp,
474 Error &error)
475{
476 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
477
478 lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy();
479 const lldb::LanguageType language = options.GetLanguage();
480 const ResultType desired_type = options.DoesCoerceToId() ? UserExpression::eResultTypeId : UserExpression::eResultTypeAny;
481 lldb::ExpressionResults execution_results = lldb::eExpressionSetupError;
482
483 Target *target = exe_ctx.GetTargetPtr();
484 if (!target)
485 {
486 if (log)
487 log->Printf("== [UserExpression::Evaluate] Passed a NULL target, can't run expressions.");
488 return lldb::eExpressionSetupError;
489 }
490
491 Process *process = exe_ctx.GetProcessPtr();
492
493 if (process == NULL || process->GetState() != lldb::eStateStopped)
494 {
495 if (execution_policy == eExecutionPolicyAlways)
496 {
497 if (log)
498 log->Printf("== [UserExpression::Evaluate] Expression may not run, but is not constant ==");
499
500 error.SetErrorString ("expression needed to run but couldn't");
501
502 return execution_results;
503 }
504 }
505
506 if (process == NULL || !process->CanJIT())
507 execution_policy = eExecutionPolicyNever;
508
509 const char *full_prefix = NULL;
510 const char *option_prefix = options.GetPrefix();
511 std::string full_prefix_storage;
512 if (expr_prefix && option_prefix)
513 {
514 full_prefix_storage.assign(expr_prefix);
515 full_prefix_storage.append(option_prefix);
516 if (!full_prefix_storage.empty())
517 full_prefix = full_prefix_storage.c_str();
518 }
519 else if (expr_prefix)
520 full_prefix = expr_prefix;
521 else
522 full_prefix = option_prefix;
523
524 lldb::UserExpressionSP user_expression_sp(target->GetUserExpressionForLanguage (expr_cstr,
525 full_prefix,
526 language,
527 desired_type,
528 error));
529 if (error.Fail())
530 {
531 if (log)
532 log->Printf ("== [UserExpression::Evaluate] Getting expression: %s ==", error.AsCString());
533 return lldb::eExpressionSetupError;
534 }
535
536 StreamString error_stream;
537
538 if (log)
539 log->Printf("== [UserExpression::Evaluate] Parsing expression %s ==", expr_cstr);
540
541 const bool keep_expression_in_memory = true;
542 const bool generate_debug_info = options.GetGenerateDebugInfo();
543
544 if (options.InvokeCancelCallback (lldb::eExpressionEvaluationParse))
545 {
546 error.SetErrorString ("expression interrupted by callback before parse");
547 result_valobj_sp = ValueObjectConstResult::Create (exe_ctx.GetBestExecutionContextScope(), error);
548 return lldb::eExpressionInterrupted;
549 }
550
551 if (!user_expression_sp->Parse (error_stream,
552 exe_ctx,
553 execution_policy,
554 keep_expression_in_memory,
555 generate_debug_info))
556 {
557 execution_results = lldb::eExpressionParseError;
558 if (error_stream.GetString().empty())
559 error.SetExpressionError (execution_results, "expression failed to parse, unknown error");
560 else
561 error.SetExpressionError (execution_results, error_stream.GetString().c_str());
562 }
563 else
564 {
565 lldb::ExpressionVariableSP expr_result;
566
567 if (execution_policy == eExecutionPolicyNever &&
568 !user_expression_sp->CanInterpret())
569 {
570 if (log)
571 log->Printf("== [UserExpression::Evaluate] Expression may not run, but is not constant ==");
572
573 if (error_stream.GetString().empty())
574 error.SetExpressionError (lldb::eExpressionSetupError, "expression needed to run but couldn't");
575 }
576 else
577 {
578 if (options.InvokeCancelCallback (lldb::eExpressionEvaluationExecution))
579 {
580 error.SetExpressionError (lldb::eExpressionInterrupted, "expression interrupted by callback before execution");
581 result_valobj_sp = ValueObjectConstResult::Create (exe_ctx.GetBestExecutionContextScope(), error);
582 return lldb::eExpressionInterrupted;
583 }
584
585 error_stream.GetString().clear();
586
587 if (log)
588 log->Printf("== [UserExpression::Evaluate] Executing expression ==");
589
590 execution_results = user_expression_sp->Execute (error_stream,
591 exe_ctx,
592 options,
593 user_expression_sp,
594 expr_result);
595
596 if (options.GetResultIsInternal() && expr_result && process)
597 {
598 process->GetTarget().GetPersistentVariables().RemovePersistentVariable (expr_result);
599 }
600
601 if (execution_results != lldb::eExpressionCompleted)
602 {
603 if (log)
604 log->Printf("== [UserExpression::Evaluate] Execution completed abnormally ==");
605
606 if (error_stream.GetString().empty())
607 error.SetExpressionError (execution_results, "expression failed to execute, unknown error");
608 else
609 error.SetExpressionError (execution_results, error_stream.GetString().c_str());
610 }
611 else
612 {
613 if (expr_result)
614 {
615 result_valobj_sp = expr_result->GetValueObject();
616
617 if (log)
618 log->Printf("== [UserExpression::Evaluate] Execution completed normally with result %s ==",
619 result_valobj_sp->GetValueAsCString());
620 }
621 else
622 {
623 if (log)
624 log->Printf("== [UserExpression::Evaluate] Execution completed normally with no result ==");
625
626 error.SetError(UserExpression::kNoResult, lldb::eErrorTypeGeneric);
627 }
628 }
629 }
630 }
631
632 if (options.InvokeCancelCallback(lldb::eExpressionEvaluationComplete))
633 {
634 error.SetExpressionError (lldb::eExpressionInterrupted, "expression interrupted by callback after complete");
635 return lldb::eExpressionInterrupted;
636 }
637
638 if (result_valobj_sp.get() == NULL)
639 {
640 result_valobj_sp = ValueObjectConstResult::Create (exe_ctx.GetBestExecutionContextScope(), error);
641 }
642
643 return execution_results;
644}