1 //===-- ClangUserExpression.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 #include <stdio.h>
12 #if HAVE_SYS_TYPES_H
13 # include <sys/types.h>
14 #endif
15
16 // C++ Includes
17 #include <cstdlib>
18 #include <string>
19 #include <map>
20
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"
48
49 #include "clang/AST/DeclCXX.h"
50 #include "clang/AST/DeclObjC.h"
51
52 using namespace lldb_private;
53
ClangUserExpression(const char * expr,const char * expr_prefix,lldb::LanguageType language,ResultType desired_type)54 ClangUserExpression::ClangUserExpression (const char *expr,
55 const char *expr_prefix,
56 lldb::LanguageType language,
57 ResultType desired_type) :
58 ClangExpression (),
59 m_stack_frame_bottom (LLDB_INVALID_ADDRESS),
60 m_stack_frame_top (LLDB_INVALID_ADDRESS),
61 m_expr_text (expr),
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),
67 m_cplusplus (false),
68 m_objectivec (false),
69 m_static_method(false),
70 m_needs_object_ptr (false),
71 m_const_object (false),
72 m_target (NULL),
73 m_can_interpret (false),
74 m_materialized_address (LLDB_INVALID_ADDRESS)
75 {
76 switch (m_language)
77 {
78 case lldb::eLanguageTypeC_plus_plus:
79 m_allow_cxx = true;
80 break;
81 case lldb::eLanguageTypeObjC:
82 m_allow_objc = true;
83 break;
84 case lldb::eLanguageTypeObjC_plus_plus:
85 default:
86 m_allow_cxx = true;
87 m_allow_objc = true;
88 break;
89 }
90 }
91
~ClangUserExpression()92 ClangUserExpression::~ClangUserExpression ()
93 {
94 }
95
96 clang::ASTConsumer *
ASTTransformer(clang::ASTConsumer * passthrough)97 ClangUserExpression::ASTTransformer (clang::ASTConsumer *passthrough)
98 {
99 m_result_synthesizer.reset(new ASTResultSynthesizer(passthrough,
100 *m_target));
101
102 return m_result_synthesizer.get();
103 }
104
105 void
ScanContext(ExecutionContext & exe_ctx,Error & err)106 ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err)
107 {
108 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
109
110 if (log)
111 log->Printf("ClangUserExpression::ScanContext()");
112
113 m_target = exe_ctx.GetTargetPtr();
114
115 if (!(m_allow_cxx || m_allow_objc))
116 {
117 if (log)
118 log->Printf(" [CUE::SC] Settings inhibit C++ and Objective-C");
119 return;
120 }
121
122 StackFrame *frame = exe_ctx.GetFramePtr();
123 if (frame == NULL)
124 {
125 if (log)
126 log->Printf(" [CUE::SC] Null stack frame");
127 return;
128 }
129
130 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction | lldb::eSymbolContextBlock);
131
132 if (!sym_ctx.function)
133 {
134 if (log)
135 log->Printf(" [CUE::SC] Null function");
136 return;
137 }
138
139 // Find the block that defines the function represented by "sym_ctx"
140 Block *function_block = sym_ctx.GetFunctionBlock();
141
142 if (!function_block)
143 {
144 if (log)
145 log->Printf(" [CUE::SC] Null function block");
146 return;
147 }
148
149 clang::DeclContext *decl_context = function_block->GetClangDeclContext();
150
151 if (!decl_context)
152 {
153 if (log)
154 log->Printf(" [CUE::SC] Null decl context");
155 return;
156 }
157
158 if (clang::CXXMethodDecl *method_decl = llvm::dyn_cast<clang::CXXMethodDecl>(decl_context))
159 {
160 if (m_allow_cxx && method_decl->isInstance())
161 {
162 if (m_enforce_valid_object)
163 {
164 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
165
166 const char *thisErrorString = "Stopped in a C++ method, but 'this' isn't available; pretending we are in a generic context";
167
168 if (!variable_list_sp)
169 {
170 err.SetErrorString(thisErrorString);
171 return;
172 }
173
174 lldb::VariableSP this_var_sp (variable_list_sp->FindVariable(ConstString("this")));
175
176 if (!this_var_sp ||
177 !this_var_sp->IsInScope(frame) ||
178 !this_var_sp->LocationIsValidForFrame (frame))
179 {
180 err.SetErrorString(thisErrorString);
181 return;
182 }
183 }
184
185 m_cplusplus = true;
186 m_needs_object_ptr = true;
187 }
188 }
189 else if (clang::ObjCMethodDecl *method_decl = llvm::dyn_cast<clang::ObjCMethodDecl>(decl_context))
190 {
191 if (m_allow_objc)
192 {
193 if (m_enforce_valid_object)
194 {
195 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
196
197 const char *selfErrorString = "Stopped in an Objective-C method, but 'self' isn't available; pretending we are in a generic context";
198
199 if (!variable_list_sp)
200 {
201 err.SetErrorString(selfErrorString);
202 return;
203 }
204
205 lldb::VariableSP self_variable_sp = variable_list_sp->FindVariable(ConstString("self"));
206
207 if (!self_variable_sp ||
208 !self_variable_sp->IsInScope(frame) ||
209 !self_variable_sp->LocationIsValidForFrame (frame))
210 {
211 err.SetErrorString(selfErrorString);
212 return;
213 }
214 }
215
216 m_objectivec = true;
217 m_needs_object_ptr = true;
218
219 if (!method_decl->isInstanceMethod())
220 m_static_method = true;
221 }
222 }
223 else if (clang::FunctionDecl *function_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_context))
224 {
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.
229
230 ClangASTMetadata *metadata = ClangASTContext::GetMetadata (&decl_context->getParentASTContext(), function_decl);
231 if (metadata && metadata->HasObjectPtr())
232 {
233 lldb::LanguageType language = metadata->GetObjectPtrLanguage();
234 if (language == lldb::eLanguageTypeC_plus_plus)
235 {
236 if (m_enforce_valid_object)
237 {
238 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
239
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";
241
242 if (!variable_list_sp)
243 {
244 err.SetErrorString(thisErrorString);
245 return;
246 }
247
248 lldb::VariableSP this_var_sp (variable_list_sp->FindVariable(ConstString("this")));
249
250 if (!this_var_sp ||
251 !this_var_sp->IsInScope(frame) ||
252 !this_var_sp->LocationIsValidForFrame (frame))
253 {
254 err.SetErrorString(thisErrorString);
255 return;
256 }
257 }
258
259 m_cplusplus = true;
260 m_needs_object_ptr = true;
261 }
262 else if (language == lldb::eLanguageTypeObjC)
263 {
264 if (m_enforce_valid_object)
265 {
266 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
267
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";
269
270 if (!variable_list_sp)
271 {
272 err.SetErrorString(selfErrorString);
273 return;
274 }
275
276 lldb::VariableSP self_variable_sp = variable_list_sp->FindVariable(ConstString("self"));
277
278 if (!self_variable_sp ||
279 !self_variable_sp->IsInScope(frame) ||
280 !self_variable_sp->LocationIsValidForFrame (frame))
281 {
282 err.SetErrorString(selfErrorString);
283 return;
284 }
285
286 Type *self_type = self_variable_sp->GetType();
287
288 if (!self_type)
289 {
290 err.SetErrorString(selfErrorString);
291 return;
292 }
293
294 ClangASTType self_clang_type = self_type->GetClangForwardType();
295
296 if (!self_clang_type)
297 {
298 err.SetErrorString(selfErrorString);
299 return;
300 }
301
302 if (self_clang_type.IsObjCClassType())
303 {
304 return;
305 }
306 else if (self_clang_type.IsObjCObjectPointerType())
307 {
308 m_objectivec = true;
309 m_needs_object_ptr = true;
310 }
311 else
312 {
313 err.SetErrorString(selfErrorString);
314 return;
315 }
316 }
317 else
318 {
319 m_objectivec = true;
320 m_needs_object_ptr = true;
321 }
322 }
323 }
324 }
325 }
326
327 void
InstallContext(ExecutionContext & exe_ctx)328 ClangUserExpression::InstallContext (ExecutionContext &exe_ctx)
329 {
330 m_process_wp = exe_ctx.GetProcessSP();
331
332 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
333
334 if (frame_sp)
335 m_address = frame_sp->GetFrameCodeAddress();
336 }
337
338 bool
LockAndCheckContext(ExecutionContext & exe_ctx,lldb::TargetSP & target_sp,lldb::ProcessSP & process_sp,lldb::StackFrameSP & frame_sp)339 ClangUserExpression::LockAndCheckContext (ExecutionContext &exe_ctx,
340 lldb::TargetSP &target_sp,
341 lldb::ProcessSP &process_sp,
342 lldb::StackFrameSP &frame_sp)
343 {
344 lldb::ProcessSP expected_process_sp = m_process_wp.lock();
345 process_sp = exe_ctx.GetProcessSP();
346
347 if (process_sp != expected_process_sp)
348 return false;
349
350 process_sp = exe_ctx.GetProcessSP();
351 target_sp = exe_ctx.GetTargetSP();
352 frame_sp = exe_ctx.GetFrameSP();
353
354 if (m_address.IsValid())
355 {
356 if (!frame_sp)
357 return false;
358 else
359 return (0 == Address::CompareLoadAddress(m_address, frame_sp->GetFrameCodeAddress(), target_sp.get()));
360 }
361
362 return true;
363 }
364
365 bool
MatchesContext(ExecutionContext & exe_ctx)366 ClangUserExpression::MatchesContext (ExecutionContext &exe_ctx)
367 {
368 lldb::TargetSP target_sp;
369 lldb::ProcessSP process_sp;
370 lldb::StackFrameSP frame_sp;
371
372 return LockAndCheckContext(exe_ctx, target_sp, process_sp, frame_sp);
373 }
374
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.
379 static void
ApplyObjcCastHack(std::string & expr)380 ApplyObjcCastHack(std::string &expr)
381 {
382 #define OBJC_CAST_HACK_FROM "(int)["
383 #define OBJC_CAST_HACK_TO "(int)(long long)["
384
385 size_t from_offset;
386
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);
389
390 #undef OBJC_CAST_HACK_TO
391 #undef OBJC_CAST_HACK_FROM
392 }
393
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.
399 static void
ApplyUnicharHack(std::string & expr)400 ApplyUnicharHack(std::string &expr)
401 {
402 #define UNICHAR_HACK_FROM "unichar"
403 #define UNICHAR_HACK_TO "unsigned short"
404
405 size_t from_offset;
406
407 while ((from_offset = expr.find(UNICHAR_HACK_FROM)) != expr.npos)
408 expr.replace(from_offset, sizeof(UNICHAR_HACK_FROM) - 1, UNICHAR_HACK_TO);
409
410 #undef UNICHAR_HACK_TO
411 #undef UNICHAR_HACK_FROM
412 }
413
414 bool
Parse(Stream & error_stream,ExecutionContext & exe_ctx,lldb_private::ExecutionPolicy execution_policy,bool keep_result_in_memory)415 ClangUserExpression::Parse (Stream &error_stream,
416 ExecutionContext &exe_ctx,
417 lldb_private::ExecutionPolicy execution_policy,
418 bool keep_result_in_memory)
419 {
420 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
421
422 Error err;
423
424 InstallContext(exe_ctx);
425
426 ScanContext(exe_ctx, err);
427
428 if (!err.Success())
429 {
430 error_stream.Printf("warning: %s\n", err.AsCString());
431 }
432
433 StreamString m_transformed_stream;
434
435 ////////////////////////////////////
436 // Generate the expression
437 //
438
439 ApplyObjcCastHack(m_expr_text);
440 //ApplyUnicharHack(m_expr_text);
441
442 std::unique_ptr<ExpressionSourceCode> source_code (ExpressionSourceCode::CreateWrapped(m_expr_prefix.c_str(), m_expr_text.c_str()));
443
444 lldb::LanguageType lang_type;
445
446 if (m_cplusplus)
447 lang_type = lldb::eLanguageTypeC_plus_plus;
448 else if(m_objectivec)
449 lang_type = lldb::eLanguageTypeObjC;
450 else
451 lang_type = lldb::eLanguageTypeC;
452
453 if (!source_code->GetText(m_transformed_text, lang_type, m_const_object, m_static_method))
454 {
455 error_stream.PutCString ("error: couldn't construct expression body");
456 return false;
457 }
458
459 if (log)
460 log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());
461
462 ////////////////////////////////////
463 // Set up the target and compiler
464 //
465
466 Target *target = exe_ctx.GetTargetPtr();
467
468 if (!target)
469 {
470 error_stream.PutCString ("error: invalid target\n");
471 return false;
472 }
473
474 //////////////////////////
475 // Parse the expression
476 //
477
478 m_materializer_ap.reset(new Materializer());
479
480 m_expr_decl_map.reset(new ClangExpressionDeclMap(keep_result_in_memory, exe_ctx));
481
482 class OnExit
483 {
484 public:
485 typedef std::function <void (void)> Callback;
486
487 OnExit (Callback const &callback) :
488 m_callback(callback)
489 {
490 }
491
492 ~OnExit ()
493 {
494 m_callback();
495 }
496 private:
497 Callback m_callback;
498 };
499
500 OnExit on_exit([this]() { m_expr_decl_map.reset(); });
501
502 if (!m_expr_decl_map->WillParse(exe_ctx, m_materializer_ap.get()))
503 {
504 error_stream.PutCString ("error: current process state is unsuitable for expression parsing\n");
505
506 m_expr_decl_map.reset(); // We are being careful here in the case of breakpoint conditions.
507
508 return false;
509 }
510
511 Process *process = exe_ctx.GetProcessPtr();
512 ExecutionContextScope *exe_scope = process;
513
514 if (!exe_scope)
515 exe_scope = exe_ctx.GetTargetPtr();
516
517 ClangExpressionParser parser(exe_scope, *this);
518
519 unsigned num_errors = parser.Parse (error_stream);
520
521 if (num_errors)
522 {
523 error_stream.Printf ("error: %d errors parsing expression\n", num_errors);
524
525 m_expr_decl_map.reset(); // We are being careful here in the case of breakpoint conditions.
526
527 return false;
528 }
529
530 //////////////////////////////////////////////////////////////////////////////////////////
531 // Prepare the output of the parser for execution, evaluating it statically if possible
532 //
533
534 Error jit_error = parser.PrepareForExecution (m_jit_start_addr,
535 m_jit_end_addr,
536 m_execution_unit_ap,
537 exe_ctx,
538 m_can_interpret,
539 execution_policy);
540
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.
542
543 if (jit_error.Success())
544 {
545 if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
546 m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
547 return true;
548 }
549 else
550 {
551 const char *error_cstr = jit_error.AsCString();
552 if (error_cstr && error_cstr[0])
553 error_stream.Printf ("error: %s\n", error_cstr);
554 else
555 error_stream.Printf ("error: expression can't be interpreted or run\n");
556 return false;
557 }
558 }
559
560 static lldb::addr_t
GetObjectPointer(lldb::StackFrameSP frame_sp,ConstString & object_name,Error & err)561 GetObjectPointer (lldb::StackFrameSP frame_sp,
562 ConstString &object_name,
563 Error &err)
564 {
565 err.Clear();
566
567 if (!frame_sp)
568 {
569 err.SetErrorStringWithFormat("Couldn't load '%s' because the context is incomplete", object_name.AsCString());
570 return LLDB_INVALID_ADDRESS;
571 }
572
573 lldb::VariableSP var_sp;
574 lldb::ValueObjectSP valobj_sp;
575
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,
583 var_sp,
584 err);
585
586 if (!err.Success())
587 return LLDB_INVALID_ADDRESS;
588
589 lldb::addr_t ret = valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
590
591 if (ret == LLDB_INVALID_ADDRESS)
592 {
593 err.SetErrorStringWithFormat("Couldn't load '%s' because its value couldn't be evaluated", object_name.AsCString());
594 return LLDB_INVALID_ADDRESS;
595 }
596
597 return ret;
598 }
599
600 bool
PrepareToExecuteJITExpression(Stream & error_stream,ExecutionContext & exe_ctx,lldb::addr_t & struct_address,lldb::addr_t & object_ptr,lldb::addr_t & cmd_ptr)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)
606 {
607 lldb::TargetSP target;
608 lldb::ProcessSP process;
609 lldb::StackFrameSP frame;
610
611 if (!LockAndCheckContext(exe_ctx,
612 target,
613 process,
614 frame))
615 {
616 error_stream.Printf("The context has changed before we could JIT the expression!\n");
617 return false;
618 }
619
620 if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret)
621 {
622 if (m_needs_object_ptr)
623 {
624 ConstString object_name;
625
626 if (m_cplusplus)
627 {
628 object_name.SetCString("this");
629 }
630 else if (m_objectivec)
631 {
632 object_name.SetCString("self");
633 }
634 else
635 {
636 error_stream.Printf("Need object pointer but don't know the language\n");
637 return false;
638 }
639
640 Error object_ptr_error;
641
642 object_ptr = GetObjectPointer(frame, object_name, object_ptr_error);
643
644 if (!object_ptr_error.Success())
645 {
646 error_stream.Printf("warning: couldn't get required object pointer (substituting NULL): %s\n", object_ptr_error.AsCString());
647 object_ptr = 0;
648 }
649
650 if (m_objectivec)
651 {
652 ConstString cmd_name("_cmd");
653
654 cmd_ptr = GetObjectPointer(frame, cmd_name, object_ptr_error);
655
656 if (!object_ptr_error.Success())
657 {
658 error_stream.Printf("warning: couldn't get cmd pointer (substituting NULL): %s\n", object_ptr_error.AsCString());
659 cmd_ptr = 0;
660 }
661 }
662 }
663
664 if (m_materialized_address == LLDB_INVALID_ADDRESS)
665 {
666 Error alloc_error;
667
668 IRMemoryMap::AllocationPolicy policy = m_can_interpret ? IRMemoryMap::eAllocationPolicyHostOnly : IRMemoryMap::eAllocationPolicyMirror;
669
670 m_materialized_address = m_execution_unit_ap->Malloc(m_materializer_ap->GetStructByteSize(),
671 m_materializer_ap->GetStructAlignment(),
672 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
673 policy,
674 alloc_error);
675
676 if (!alloc_error.Success())
677 {
678 error_stream.Printf("Couldn't allocate space for materialized struct: %s\n", alloc_error.AsCString());
679 return false;
680 }
681 }
682
683 struct_address = m_materialized_address;
684
685 if (m_can_interpret && m_stack_frame_bottom == LLDB_INVALID_ADDRESS)
686 {
687 Error alloc_error;
688
689 const size_t stack_frame_size = 512 * 1024;
690
691 m_stack_frame_bottom = m_execution_unit_ap->Malloc(stack_frame_size,
692 8,
693 lldb::ePermissionsReadable | lldb::ePermissionsWritable,
694 IRMemoryMap::eAllocationPolicyHostOnly,
695 alloc_error);
696
697 m_stack_frame_top = m_stack_frame_bottom + stack_frame_size;
698
699 if (!alloc_error.Success())
700 {
701 error_stream.Printf("Couldn't allocate space for the stack frame: %s\n", alloc_error.AsCString());
702 return false;
703 }
704 }
705
706 Error materialize_error;
707
708 m_dematerializer_sp = m_materializer_ap->Materialize(frame, *m_execution_unit_ap, struct_address, materialize_error);
709
710 if (!materialize_error.Success())
711 {
712 error_stream.Printf("Couldn't materialize struct: %s\n", materialize_error.AsCString());
713 return false;
714 }
715 }
716 return true;
717 }
718
719 bool
FinalizeJITExecution(Stream & error_stream,ExecutionContext & exe_ctx,lldb::ClangExpressionVariableSP & result,lldb::addr_t function_stack_bottom,lldb::addr_t function_stack_top)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)
725 {
726 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
727
728 if (log)
729 log->Printf("-- [ClangUserExpression::FinalizeJITExecution] Dematerializing after execution --");
730
731 if (!m_dematerializer_sp)
732 {
733 error_stream.Printf ("Couldn't apply expression side effects : no dematerializer is present");
734 return false;
735 }
736
737 Error dematerialize_error;
738
739 m_dematerializer_sp->Dematerialize(dematerialize_error, result, function_stack_bottom, function_stack_top);
740
741 if (!dematerialize_error.Success())
742 {
743 error_stream.Printf ("Couldn't apply expression side effects : %s\n", dematerialize_error.AsCString("unknown error"));
744 return false;
745 }
746
747 if (result)
748 result->TransferAddress();
749
750 m_dematerializer_sp.reset();
751
752 return true;
753 }
754
755 ExecutionResults
Execute(Stream & error_stream,ExecutionContext & exe_ctx,const EvaluateExpressionOptions & options,ClangUserExpression::ClangUserExpressionSP & shared_ptr_to_me,lldb::ClangExpressionVariableSP & result)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)
761 {
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));
765
766 if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret)
767 {
768 lldb::addr_t struct_address = LLDB_INVALID_ADDRESS;
769
770 lldb::addr_t object_ptr = 0;
771 lldb::addr_t cmd_ptr = 0;
772
773 if (!PrepareToExecuteJITExpression (error_stream, exe_ctx, struct_address, object_ptr, cmd_ptr))
774 {
775 error_stream.Printf("Errored out in %s, couldn't PrepareToExecuteJITExpression", __FUNCTION__);
776 return eExecutionSetupError;
777 }
778
779 lldb::addr_t function_stack_bottom = LLDB_INVALID_ADDRESS;
780 lldb::addr_t function_stack_top = LLDB_INVALID_ADDRESS;
781
782 if (m_can_interpret)
783 {
784 llvm::Module *module = m_execution_unit_ap->GetModule();
785 llvm::Function *function = m_execution_unit_ap->GetFunction();
786
787 if (!module || !function)
788 {
789 error_stream.Printf("Supposed to interpret, but nothing is there");
790 return eExecutionSetupError;
791 }
792
793 Error interpreter_error;
794
795 llvm::SmallVector <lldb::addr_t, 3> args;
796
797 if (m_needs_object_ptr)
798 {
799 args.push_back(object_ptr);
800
801 if (m_objectivec)
802 args.push_back(cmd_ptr);
803 }
804
805 args.push_back(struct_address);
806
807 function_stack_bottom = m_stack_frame_bottom;
808 function_stack_top = m_stack_frame_top;
809
810 IRInterpreter::Interpret (*module,
811 *function,
812 args,
813 *m_execution_unit_ap.get(),
814 interpreter_error,
815 function_stack_bottom,
816 function_stack_top);
817
818 if (!interpreter_error.Success())
819 {
820 error_stream.Printf("Supposed to interpret, but failed: %s", interpreter_error.AsCString());
821 return eExecutionDiscarded;
822 }
823 }
824 else
825 {
826 Address wrapper_address (m_jit_start_addr);
827
828 llvm::SmallVector <lldb::addr_t, 3> args;
829
830 if (m_needs_object_ptr) {
831 args.push_back(object_ptr);
832 if (m_objectivec)
833 args.push_back(cmd_ptr);
834 }
835
836 args.push_back(struct_address);
837
838 lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallUserExpression (exe_ctx.GetThreadRef(),
839 wrapper_address,
840 args,
841 options,
842 shared_ptr_to_me));
843
844 if (!call_plan_sp || !call_plan_sp->ValidatePlan (&error_stream))
845 return eExecutionSetupError;
846
847 lldb::addr_t function_stack_pointer = static_cast<ThreadPlanCallFunction *>(call_plan_sp.get())->GetFunctionStackPointer();
848
849 function_stack_bottom = function_stack_pointer - Host::GetPageSize();
850 function_stack_top = function_stack_pointer;
851
852 if (log)
853 log->Printf("-- [ClangUserExpression::Execute] Execution of expression begins --");
854
855 if (exe_ctx.GetProcessPtr())
856 exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
857
858 ExecutionResults execution_result = exe_ctx.GetProcessRef().RunThreadPlan (exe_ctx,
859 call_plan_sp,
860 options,
861 error_stream);
862
863 if (exe_ctx.GetProcessPtr())
864 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
865
866 if (log)
867 log->Printf("-- [ClangUserExpression::Execute] Execution of expression completed --");
868
869 if (execution_result == eExecutionInterrupted || execution_result == eExecutionHitBreakpoint)
870 {
871 const char *error_desc = NULL;
872
873 if (call_plan_sp)
874 {
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();
878 }
879 if (error_desc)
880 error_stream.Printf ("Execution was interrupted, reason: %s.", error_desc);
881 else
882 error_stream.PutCString ("Execution was interrupted.");
883
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.");
887 else
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.");
889
890 return execution_result;
891 }
892 else if (execution_result == eExecutionStoppedForDebug)
893 {
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;
897 }
898 else if (execution_result != eExecutionCompleted)
899 {
900 error_stream.Printf ("Couldn't execute function; result was %s\n", Process::ExecutionResultAsCString (execution_result));
901 return execution_result;
902 }
903 }
904
905 if (FinalizeJITExecution (error_stream, exe_ctx, result, function_stack_bottom, function_stack_top))
906 {
907 return eExecutionCompleted;
908 }
909 else
910 {
911 return eExecutionSetupError;
912 }
913 }
914 else
915 {
916 error_stream.Printf("Expression can't be run, because there is no JIT compiled function");
917 return eExecutionSetupError;
918 }
919 }
920
921 ExecutionResults
Evaluate(ExecutionContext & exe_ctx,const EvaluateExpressionOptions & options,const char * expr_cstr,const char * expr_prefix,lldb::ValueObjectSP & result_valobj_sp,Error & error)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,
927 Error &error)
928 {
929 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
930
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;
935
936 Process *process = exe_ctx.GetProcessPtr();
937
938 if (process == NULL || process->GetState() != lldb::eStateStopped)
939 {
940 if (execution_policy == eExecutionPolicyAlways)
941 {
942 if (log)
943 log->Printf("== [ClangUserExpression::Evaluate] Expression may not run, but is not constant ==");
944
945 error.SetErrorString ("expression needed to run but couldn't");
946
947 return execution_results;
948 }
949 }
950
951 if (process == NULL || !process->CanJIT())
952 execution_policy = eExecutionPolicyNever;
953
954 ClangUserExpressionSP user_expression_sp (new ClangUserExpression (expr_cstr, expr_prefix, language, desired_type));
955
956 StreamString error_stream;
957
958 if (log)
959 log->Printf("== [ClangUserExpression::Evaluate] Parsing expression %s ==", expr_cstr);
960
961 const bool keep_expression_in_memory = true;
962
963 if (!user_expression_sp->Parse (error_stream, exe_ctx, execution_policy, keep_expression_in_memory))
964 {
965 if (error_stream.GetString().empty())
966 error.SetErrorString ("expression failed to parse, unknown error");
967 else
968 error.SetErrorString (error_stream.GetString().c_str());
969 }
970 else
971 {
972 lldb::ClangExpressionVariableSP expr_result;
973
974 if (execution_policy == eExecutionPolicyNever &&
975 !user_expression_sp->CanInterpret())
976 {
977 if (log)
978 log->Printf("== [ClangUserExpression::Evaluate] Expression may not run, but is not constant ==");
979
980 if (error_stream.GetString().empty())
981 error.SetErrorString ("expression needed to run but couldn't");
982 }
983 else
984 {
985 error_stream.GetString().clear();
986
987 if (log)
988 log->Printf("== [ClangUserExpression::Evaluate] Executing expression ==");
989
990 execution_results = user_expression_sp->Execute (error_stream,
991 exe_ctx,
992 options,
993 user_expression_sp,
994 expr_result);
995
996 if (execution_results != eExecutionCompleted)
997 {
998 if (log)
999 log->Printf("== [ClangUserExpression::Evaluate] Execution completed abnormally ==");
1000
1001 if (error_stream.GetString().empty())
1002 error.SetErrorString ("expression failed to execute, unknown error");
1003 else
1004 error.SetErrorString (error_stream.GetString().c_str());
1005 }
1006 else
1007 {
1008 if (expr_result)
1009 {
1010 result_valobj_sp = expr_result->GetValueObject();
1011
1012 if (log)
1013 log->Printf("== [ClangUserExpression::Evaluate] Execution completed normally with result %s ==", result_valobj_sp->GetValueAsCString());
1014 }
1015 else
1016 {
1017 if (log)
1018 log->Printf("== [ClangUserExpression::Evaluate] Execution completed normally with no result ==");
1019
1020 error.SetError(ClangUserExpression::kNoResult, lldb::eErrorTypeGeneric);
1021 }
1022 }
1023 }
1024 }
1025
1026 if (result_valobj_sp.get() == NULL)
1027 {
1028 result_valobj_sp = ValueObjectConstResult::Create (exe_ctx.GetBestExecutionContextScope(), error);
1029 }
1030
1031 return execution_results;
1032 }
1033