1 //===-- ClangUserExpression.cpp ---------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
13 # include <sys/types.h>
21 #include "lldb/Core/ConstString.h"
22 #include "lldb/Core/Log.h"
23 #include "lldb/Core/StreamFile.h"
24 #include "lldb/Core/StreamString.h"
25 #include "lldb/Core/ValueObjectConstResult.h"
26 #include "lldb/Expression/ASTResultSynthesizer.h"
27 #include "lldb/Expression/ClangExpressionDeclMap.h"
28 #include "lldb/Expression/ClangExpressionParser.h"
29 #include "lldb/Expression/ClangFunction.h"
30 #include "lldb/Expression/ClangUserExpression.h"
31 #include "lldb/Expression/ExpressionSourceCode.h"
32 #include "lldb/Expression/IRExecutionUnit.h"
33 #include "lldb/Expression/IRInterpreter.h"
34 #include "lldb/Expression/Materializer.h"
35 #include "lldb/Host/Host.h"
36 #include "lldb/Symbol/Block.h"
37 #include "lldb/Symbol/ClangASTContext.h"
38 #include "lldb/Symbol/Function.h"
39 #include "lldb/Symbol/Type.h"
40 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
41 #include "lldb/Symbol/VariableList.h"
42 #include "lldb/Target/ExecutionContext.h"
43 #include "lldb/Target/Process.h"
44 #include "lldb/Target/StackFrame.h"
45 #include "lldb/Target/Target.h"
46 #include "lldb/Target/ThreadPlan.h"
47 #include "lldb/Target/ThreadPlanCallUserExpression.h"
49 #include "clang/AST/DeclCXX.h"
50 #include "clang/AST/DeclObjC.h"
52 using namespace lldb_private;
54 ClangUserExpression::ClangUserExpression (const char *expr,
55 const char *expr_prefix,
56 lldb::LanguageType language,
57 ResultType desired_type) :
59 m_stack_frame_bottom (LLDB_INVALID_ADDRESS),
60 m_stack_frame_top (LLDB_INVALID_ADDRESS),
62 m_expr_prefix (expr_prefix ? expr_prefix : ""),
63 m_language (language),
64 m_transformed_text (),
65 m_desired_type (desired_type),
66 m_enforce_valid_object (true),
69 m_static_method(false),
70 m_needs_object_ptr (false),
71 m_const_object (false),
73 m_can_interpret (false),
74 m_materialized_address (LLDB_INVALID_ADDRESS)
78 case lldb::eLanguageTypeC_plus_plus:
81 case lldb::eLanguageTypeObjC:
84 case lldb::eLanguageTypeObjC_plus_plus:
92 ClangUserExpression::~ClangUserExpression ()
97 ClangUserExpression::ASTTransformer (clang::ASTConsumer *passthrough)
99 m_result_synthesizer.reset(new ASTResultSynthesizer(passthrough,
102 return m_result_synthesizer.get();
106 ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err)
108 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
111 log->Printf("ClangUserExpression::ScanContext()");
113 m_target = exe_ctx.GetTargetPtr();
115 if (!(m_allow_cxx || m_allow_objc))
118 log->Printf(" [CUE::SC] Settings inhibit C++ and Objective-C");
122 StackFrame *frame = exe_ctx.GetFramePtr();
126 log->Printf(" [CUE::SC] Null stack frame");
130 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction | lldb::eSymbolContextBlock);
132 if (!sym_ctx.function)
135 log->Printf(" [CUE::SC] Null function");
139 // Find the block that defines the function represented by "sym_ctx"
140 Block *function_block = sym_ctx.GetFunctionBlock();
145 log->Printf(" [CUE::SC] Null function block");
149 clang::DeclContext *decl_context = function_block->GetClangDeclContext();
154 log->Printf(" [CUE::SC] Null decl context");
158 if (clang::CXXMethodDecl *method_decl = llvm::dyn_cast<clang::CXXMethodDecl>(decl_context))
160 if (m_allow_cxx && method_decl->isInstance())
162 if (m_enforce_valid_object)
164 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
166 const char *thisErrorString = "Stopped in a C++ method, but 'this' isn't available; pretending we are in a generic context";
168 if (!variable_list_sp)
170 err.SetErrorString(thisErrorString);
174 lldb::VariableSP this_var_sp (variable_list_sp->FindVariable(ConstString("this")));
177 !this_var_sp->IsInScope(frame) ||
178 !this_var_sp->LocationIsValidForFrame (frame))
180 err.SetErrorString(thisErrorString);
186 m_needs_object_ptr = true;
189 else if (clang::ObjCMethodDecl *method_decl = llvm::dyn_cast<clang::ObjCMethodDecl>(decl_context))
193 if (m_enforce_valid_object)
195 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
197 const char *selfErrorString = "Stopped in an Objective-C method, but 'self' isn't available; pretending we are in a generic context";
199 if (!variable_list_sp)
201 err.SetErrorString(selfErrorString);
205 lldb::VariableSP self_variable_sp = variable_list_sp->FindVariable(ConstString("self"));
207 if (!self_variable_sp ||
208 !self_variable_sp->IsInScope(frame) ||
209 !self_variable_sp->LocationIsValidForFrame (frame))
211 err.SetErrorString(selfErrorString);
217 m_needs_object_ptr = true;
219 if (!method_decl->isInstanceMethod())
220 m_static_method = true;
223 else if (clang::FunctionDecl *function_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_context))
225 // We might also have a function that said in the debug information that it captured an
226 // object pointer. The best way to deal with getting to the ivars at present it by pretending
227 // that this is a method of a class in whatever runtime the debug info says the object pointer
228 // belongs to. Do that here.
230 ClangASTMetadata *metadata = ClangASTContext::GetMetadata (&decl_context->getParentASTContext(), function_decl);
231 if (metadata && metadata->HasObjectPtr())
233 lldb::LanguageType language = metadata->GetObjectPtrLanguage();
234 if (language == lldb::eLanguageTypeC_plus_plus)
236 if (m_enforce_valid_object)
238 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
240 const char *thisErrorString = "Stopped in a context claiming to capture a C++ object pointer, but 'this' isn't available; pretending we are in a generic context";
242 if (!variable_list_sp)
244 err.SetErrorString(thisErrorString);
248 lldb::VariableSP this_var_sp (variable_list_sp->FindVariable(ConstString("this")));
251 !this_var_sp->IsInScope(frame) ||
252 !this_var_sp->LocationIsValidForFrame (frame))
254 err.SetErrorString(thisErrorString);
260 m_needs_object_ptr = true;
262 else if (language == lldb::eLanguageTypeObjC)
264 if (m_enforce_valid_object)
266 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
268 const char *selfErrorString = "Stopped in a context claiming to capture an Objective-C object pointer, but 'self' isn't available; pretending we are in a generic context";
270 if (!variable_list_sp)
272 err.SetErrorString(selfErrorString);
276 lldb::VariableSP self_variable_sp = variable_list_sp->FindVariable(ConstString("self"));
278 if (!self_variable_sp ||
279 !self_variable_sp->IsInScope(frame) ||
280 !self_variable_sp->LocationIsValidForFrame (frame))
282 err.SetErrorString(selfErrorString);
286 Type *self_type = self_variable_sp->GetType();
290 err.SetErrorString(selfErrorString);
294 ClangASTType self_clang_type = self_type->GetClangForwardType();
296 if (!self_clang_type)
298 err.SetErrorString(selfErrorString);
302 if (self_clang_type.IsObjCClassType())
306 else if (self_clang_type.IsObjCObjectPointerType())
309 m_needs_object_ptr = true;
313 err.SetErrorString(selfErrorString);
320 m_needs_object_ptr = true;
328 ClangUserExpression::InstallContext (ExecutionContext &exe_ctx)
330 m_process_wp = exe_ctx.GetProcessSP();
332 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
335 m_address = frame_sp->GetFrameCodeAddress();
339 ClangUserExpression::LockAndCheckContext (ExecutionContext &exe_ctx,
340 lldb::TargetSP &target_sp,
341 lldb::ProcessSP &process_sp,
342 lldb::StackFrameSP &frame_sp)
344 lldb::ProcessSP expected_process_sp = m_process_wp.lock();
345 process_sp = exe_ctx.GetProcessSP();
347 if (process_sp != expected_process_sp)
350 process_sp = exe_ctx.GetProcessSP();
351 target_sp = exe_ctx.GetTargetSP();
352 frame_sp = exe_ctx.GetFrameSP();
354 if (m_address.IsValid())
359 return (0 == Address::CompareLoadAddress(m_address, frame_sp->GetFrameCodeAddress(), target_sp.get()));
366 ClangUserExpression::MatchesContext (ExecutionContext &exe_ctx)
368 lldb::TargetSP target_sp;
369 lldb::ProcessSP process_sp;
370 lldb::StackFrameSP frame_sp;
372 return LockAndCheckContext(exe_ctx, target_sp, process_sp, frame_sp);
375 // This is a really nasty hack, meant to fix Objective-C expressions of the form
376 // (int)[myArray count]. Right now, because the type information for count is
377 // not available, [myArray count] returns id, which can't be directly cast to
378 // int without causing a clang error.
380 ApplyObjcCastHack(std::string &expr)
382 #define OBJC_CAST_HACK_FROM "(int)["
383 #define OBJC_CAST_HACK_TO "(int)(long long)["
387 while ((from_offset = expr.find(OBJC_CAST_HACK_FROM)) != expr.npos)
388 expr.replace(from_offset, sizeof(OBJC_CAST_HACK_FROM) - 1, OBJC_CAST_HACK_TO);
390 #undef OBJC_CAST_HACK_TO
391 #undef OBJC_CAST_HACK_FROM
394 // Another hack, meant to allow use of unichar despite it not being available in
395 // the type information. Although we could special-case it in type lookup,
396 // hopefully we'll figure out a way to #include the same environment as is
397 // present in the original source file rather than try to hack specific type
398 // definitions in as needed.
400 ApplyUnicharHack(std::string &expr)
402 #define UNICHAR_HACK_FROM "unichar"
403 #define UNICHAR_HACK_TO "unsigned short"
407 while ((from_offset = expr.find(UNICHAR_HACK_FROM)) != expr.npos)
408 expr.replace(from_offset, sizeof(UNICHAR_HACK_FROM) - 1, UNICHAR_HACK_TO);
410 #undef UNICHAR_HACK_TO
411 #undef UNICHAR_HACK_FROM
415 ClangUserExpression::Parse (Stream &error_stream,
416 ExecutionContext &exe_ctx,
417 lldb_private::ExecutionPolicy execution_policy,
418 bool keep_result_in_memory)
420 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
424 InstallContext(exe_ctx);
426 ScanContext(exe_ctx, err);
430 error_stream.Printf("warning: %s\n", err.AsCString());
433 StreamString m_transformed_stream;
435 ////////////////////////////////////
436 // Generate the expression
439 ApplyObjcCastHack(m_expr_text);
440 //ApplyUnicharHack(m_expr_text);
442 std::unique_ptr<ExpressionSourceCode> source_code (ExpressionSourceCode::CreateWrapped(m_expr_prefix.c_str(), m_expr_text.c_str()));
444 lldb::LanguageType lang_type;
447 lang_type = lldb::eLanguageTypeC_plus_plus;
448 else if(m_objectivec)
449 lang_type = lldb::eLanguageTypeObjC;
451 lang_type = lldb::eLanguageTypeC;
453 if (!source_code->GetText(m_transformed_text, lang_type, m_const_object, m_static_method))
455 error_stream.PutCString ("error: couldn't construct expression body");
460 log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());
462 ////////////////////////////////////
463 // Set up the target and compiler
466 Target *target = exe_ctx.GetTargetPtr();
470 error_stream.PutCString ("error: invalid target\n");
474 //////////////////////////
475 // Parse the expression
478 m_materializer_ap.reset(new Materializer());
480 m_expr_decl_map.reset(new ClangExpressionDeclMap(keep_result_in_memory, exe_ctx));
485 typedef std::function <void (void)> Callback;
487 OnExit (Callback const &callback) :
500 OnExit on_exit([this]() { m_expr_decl_map.reset(); });
502 if (!m_expr_decl_map->WillParse(exe_ctx, m_materializer_ap.get()))
504 error_stream.PutCString ("error: current process state is unsuitable for expression parsing\n");
506 m_expr_decl_map.reset(); // We are being careful here in the case of breakpoint conditions.
511 Process *process = exe_ctx.GetProcessPtr();
512 ExecutionContextScope *exe_scope = process;
515 exe_scope = exe_ctx.GetTargetPtr();
517 ClangExpressionParser parser(exe_scope, *this);
519 unsigned num_errors = parser.Parse (error_stream);
523 error_stream.Printf ("error: %d errors parsing expression\n", num_errors);
525 m_expr_decl_map.reset(); // We are being careful here in the case of breakpoint conditions.
530 //////////////////////////////////////////////////////////////////////////////////////////
531 // Prepare the output of the parser for execution, evaluating it statically if possible
534 Error jit_error = parser.PrepareForExecution (m_jit_start_addr,
541 m_expr_decl_map.reset(); // Make this go away since we don't need any of its state after parsing. This also gets rid of any ClangASTImporter::Minions.
543 if (jit_error.Success())
545 if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
546 m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
551 const char *error_cstr = jit_error.AsCString();
552 if (error_cstr && error_cstr[0])
553 error_stream.Printf ("error: %s\n", error_cstr);
555 error_stream.Printf ("error: expression can't be interpreted or run\n");
561 GetObjectPointer (lldb::StackFrameSP frame_sp,
562 ConstString &object_name,
569 err.SetErrorStringWithFormat("Couldn't load '%s' because the context is incomplete", object_name.AsCString());
570 return LLDB_INVALID_ADDRESS;
573 lldb::VariableSP var_sp;
574 lldb::ValueObjectSP valobj_sp;
576 valobj_sp = frame_sp->GetValueForVariableExpressionPath(object_name.AsCString(),
577 lldb::eNoDynamicValues,
578 StackFrame::eExpressionPathOptionCheckPtrVsMember ||
579 StackFrame::eExpressionPathOptionsAllowDirectIVarAccess ||
580 StackFrame::eExpressionPathOptionsNoFragileObjcIvar ||
581 StackFrame::eExpressionPathOptionsNoSyntheticChildren ||
582 StackFrame::eExpressionPathOptionsNoSyntheticArrayRange,
587 return LLDB_INVALID_ADDRESS;
589 lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
591 if (ret == LLDB_INVALID_ADDRESS)
593 err.SetErrorStringWithFormat("Couldn't load '%s' because its value couldn't be evaluated", object_name.AsCString());
594 return LLDB_INVALID_ADDRESS;
601 ClangUserExpression::PrepareToExecuteJITExpression (Stream &error_stream,
602 ExecutionContext &exe_ctx,
603 lldb::addr_t &struct_address,
604 lldb::addr_t &object_ptr,
605 lldb::addr_t &cmd_ptr)
607 lldb::TargetSP target;
608 lldb::ProcessSP process;
609 lldb::StackFrameSP frame;
611 if (!LockAndCheckContext(exe_ctx,
616 error_stream.Printf("The context has changed before we could JIT the expression!\n");
620 if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret)
622 if (m_needs_object_ptr)
624 ConstString object_name;
628 object_name.SetCString("this");
630 else if (m_objectivec)
632 object_name.SetCString("self");
636 error_stream.Printf("Need object pointer but don't know the language\n");
640 Error object_ptr_error;
642 object_ptr = GetObjectPointer(frame, object_name, object_ptr_error);
644 if (!object_ptr_error.Success())
646 error_stream.Printf("warning: couldn't get required object pointer (substituting NULL): %s\n", object_ptr_error.AsCString());
652 ConstString cmd_name("_cmd");
654 cmd_ptr = GetObjectPointer(frame, cmd_name, object_ptr_error);
656 if (!object_ptr_error.Success())
658 error_stream.Printf("warning: couldn't get cmd pointer (substituting NULL): %s\n", object_ptr_error.AsCString());
664 if (m_materialized_address == LLDB_INVALID_ADDRESS)
668 IRMemoryMap::AllocationPolicy policy = m_can_interpret ? IRMemoryMap::eAllocationPolicyHostOnly : IRMemoryMap::eAllocationPolicyMirror;
670 m_materialized_address = m_execution_unit_ap->Malloc(m_materializer_ap->GetStructByteSize(),
671 m_materializer_ap->GetStructAlignment(),
672 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
676 if (!alloc_error.Success())
678 error_stream.Printf("Couldn't allocate space for materialized struct: %s\n", alloc_error.AsCString());
683 struct_address = m_materialized_address;
685 if (m_can_interpret && m_stack_frame_bottom == LLDB_INVALID_ADDRESS)
689 const size_t stack_frame_size = 512 * 1024;
691 m_stack_frame_bottom = m_execution_unit_ap->Malloc(stack_frame_size,
693 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
694 IRMemoryMap::eAllocationPolicyHostOnly,
697 m_stack_frame_top = m_stack_frame_bottom + stack_frame_size;
699 if (!alloc_error.Success())
701 error_stream.Printf("Couldn't allocate space for the stack frame: %s\n", alloc_error.AsCString());
706 Error materialize_error;
708 m_dematerializer_sp = m_materializer_ap->Materialize(frame, *m_execution_unit_ap, struct_address, materialize_error);
710 if (!materialize_error.Success())
712 error_stream.Printf("Couldn't materialize struct: %s\n", materialize_error.AsCString());
720 ClangUserExpression::FinalizeJITExecution (Stream &error_stream,
721 ExecutionContext &exe_ctx,
722 lldb::ClangExpressionVariableSP &result,
723 lldb::addr_t function_stack_bottom,
724 lldb::addr_t function_stack_top)
726 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
729 log->Printf("-- [ClangUserExpression::FinalizeJITExecution] Dematerializing after execution --");
731 if (!m_dematerializer_sp)
733 error_stream.Printf ("Couldn't apply expression side effects : no dematerializer is present");
737 Error dematerialize_error;
739 m_dematerializer_sp->Dematerialize(dematerialize_error, result, function_stack_bottom, function_stack_top);
741 if (!dematerialize_error.Success())
743 error_stream.Printf ("Couldn't apply expression side effects : %s\n", dematerialize_error.AsCString("unknown error"));
748 result->TransferAddress();
750 m_dematerializer_sp.reset();
756 ClangUserExpression::Execute (Stream &error_stream,
757 ExecutionContext &exe_ctx,
758 const EvaluateExpressionOptions& options,
759 ClangUserExpression::ClangUserExpressionSP &shared_ptr_to_me,
760 lldb::ClangExpressionVariableSP &result)
762 // The expression log is quite verbose, and if you're just tracking the execution of the
763 // expression, it's quite convenient to have these logs come out with the STEP log as well.
764 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
766 if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret)
768 lldb::addr_t struct_address = LLDB_INVALID_ADDRESS;
770 lldb::addr_t object_ptr = 0;
771 lldb::addr_t cmd_ptr = 0;
773 if (!PrepareToExecuteJITExpression (error_stream, exe_ctx, struct_address, object_ptr, cmd_ptr))
775 error_stream.Printf("Errored out in %s, couldn't PrepareToExecuteJITExpression", __FUNCTION__);
776 return eExecutionSetupError;
779 lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS;
780 lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS;
784 llvm::Module *module = m_execution_unit_ap->GetModule();
785 llvm::Function *function = m_execution_unit_ap->GetFunction();
787 if (!module || !function)
789 error_stream.Printf("Supposed to interpret, but nothing is there");
790 return eExecutionSetupError;
793 Error interpreter_error;
795 llvm::SmallVector <lldb::addr_t, 3> args;
797 if (m_needs_object_ptr)
799 args.push_back(object_ptr);
802 args.push_back(cmd_ptr);
805 args.push_back(struct_address);
807 function_stack_bottom = m_stack_frame_bottom;
808 function_stack_top = m_stack_frame_top;
810 IRInterpreter::Interpret (*module,
813 *m_execution_unit_ap.get(),
815 function_stack_bottom,
818 if (!interpreter_error.Success())
820 error_stream.Printf("Supposed to interpret, but failed: %s", interpreter_error.AsCString());
821 return eExecutionDiscarded;
826 Address wrapper_address (m_jit_start_addr);
828 llvm::SmallVector <lldb::addr_t, 3> args;
830 if (m_needs_object_ptr) {
831 args.push_back(object_ptr);
833 args.push_back(cmd_ptr);
836 args.push_back(struct_address);
838 lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallUserExpression (exe_ctx.GetThreadRef(),
844 if (!call_plan_sp || !call_plan_sp->ValidatePlan (&error_stream))
845 return eExecutionSetupError;
847 lldb::addr_t function_stack_pointer = static_cast<ThreadPlanCallFunction *>(call_plan_sp.get())->GetFunctionStackPointer();
849 function_stack_bottom = function_stack_pointer - Host::GetPageSize();
850 function_stack_top = function_stack_pointer;
853 log->Printf("-- [ClangUserExpression::Execute] Execution of expression begins --");
855 if (exe_ctx.GetProcessPtr())
856 exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
858 ExecutionResults execution_result = exe_ctx.GetProcessRef().RunThreadPlan (exe_ctx,
863 if (exe_ctx.GetProcessPtr())
864 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
867 log->Printf("-- [ClangUserExpression::Execute] Execution of expression completed --");
869 if (execution_result == eExecutionInterrupted || execution_result == eExecutionHitBreakpoint)
871 const char *error_desc = NULL;
875 lldb::StopInfoSP real_stop_info_sp = call_plan_sp->GetRealStopInfo();
876 if (real_stop_info_sp)
877 error_desc = real_stop_info_sp->GetDescription();
880 error_stream.Printf ("Execution was interrupted, reason: %s.", error_desc);
882 error_stream.PutCString ("Execution was interrupted.");
884 if ((execution_result == eExecutionInterrupted && options.DoesUnwindOnError())
885 || (execution_result == eExecutionHitBreakpoint && options.DoesIgnoreBreakpoints()))
886 error_stream.PutCString ("\nThe process has been returned to the state before expression evaluation.");
888 error_stream.PutCString ("\nThe process has been left at the point where it was interrupted, use \"thread return -x\" to return to the state before expression evaluation.");
890 return execution_result;
892 else if (execution_result == eExecutionStoppedForDebug)
894 error_stream.PutCString ("Execution was halted at the first instruction of the expression function because \"debug\" was requested.\n"
895 "Use \"thread return -x\" to return to the state before expression evaluation.");
896 return execution_result;
898 else if (execution_result != eExecutionCompleted)
900 error_stream.Printf ("Couldn't execute function; result was %s\n", Process::ExecutionResultAsCString (execution_result));
901 return execution_result;
905 if (FinalizeJITExecution (error_stream, exe_ctx, result, function_stack_bottom, function_stack_top))
907 return eExecutionCompleted;
911 return eExecutionSetupError;
916 error_stream.Printf("Expression can't be run, because there is no JIT compiled function");
917 return eExecutionSetupError;
922 ClangUserExpression::Evaluate (ExecutionContext &exe_ctx,
923 const EvaluateExpressionOptions& options,
924 const char *expr_cstr,
925 const char *expr_prefix,
926 lldb::ValueObjectSP &result_valobj_sp,
929 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
931 lldb_private::ExecutionPolicy execution_policy = options.GetExecutionPolicy();
932 const lldb::LanguageType language = options.GetLanguage();
933 const ResultType desired_type = options.DoesCoerceToId() ? ClangUserExpression::eResultTypeId : ClangUserExpression::eResultTypeAny;
934 ExecutionResults execution_results = eExecutionSetupError;
936 Process *process = exe_ctx.GetProcessPtr();
938 if (process == NULL || process->GetState() != lldb::eStateStopped)
940 if (execution_policy == eExecutionPolicyAlways)
943 log->Printf("== [ClangUserExpression::Evaluate] Expression may not run, but is not constant ==");
945 error.SetErrorString ("expression needed to run but couldn't");
947 return execution_results;
951 if (process == NULL || !process->CanJIT())
952 execution_policy = eExecutionPolicyNever;
954 ClangUserExpressionSP user_expression_sp (new ClangUserExpression (expr_cstr, expr_prefix, language, desired_type));
956 StreamString error_stream;
959 log->Printf("== [ClangUserExpression::Evaluate] Parsing expression %s ==", expr_cstr);
961 const bool keep_expression_in_memory = true;
963 if (!user_expression_sp->Parse (error_stream, exe_ctx, execution_policy, keep_expression_in_memory))
965 if (error_stream.GetString().empty())
966 error.SetErrorString ("expression failed to parse, unknown error");
968 error.SetErrorString (error_stream.GetString().c_str());
972 lldb::ClangExpressionVariableSP expr_result;
974 if (execution_policy == eExecutionPolicyNever &&
975 !user_expression_sp->CanInterpret())
978 log->Printf("== [ClangUserExpression::Evaluate] Expression may not run, but is not constant ==");
980 if (error_stream.GetString().empty())
981 error.SetErrorString ("expression needed to run but couldn't");
985 error_stream.GetString().clear();
988 log->Printf("== [ClangUserExpression::Evaluate] Executing expression ==");
990 execution_results = user_expression_sp->Execute (error_stream,
996 if (execution_results != eExecutionCompleted)
999 log->Printf("== [ClangUserExpression::Evaluate] Execution completed abnormally ==");
1001 if (error_stream.GetString().empty())
1002 error.SetErrorString ("expression failed to execute, unknown error");
1004 error.SetErrorString (error_stream.GetString().c_str());
1010 result_valobj_sp = expr_result->GetValueObject();
1013 log->Printf("== [ClangUserExpression::Evaluate] Execution completed normally with result %s ==", result_valobj_sp->GetValueAsCString());
1018 log->Printf("== [ClangUserExpression::Evaluate] Execution completed normally with no result ==");
1020 error.SetError(ClangUserExpression::kNoResult, lldb::eErrorTypeGeneric);
1026 if (result_valobj_sp.get() == NULL)
1028 result_valobj_sp = ValueObjectConstResult::Create (exe_ctx.GetBestExecutionContextScope(), error);
1031 return execution_results;