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 #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 "ClangUserExpression.h" 20 21 #include "ASTResultSynthesizer.h" 22 #include "ClangExpressionDeclMap.h" 23 #include "ClangExpressionParser.h" 24 #include "ClangModulesDeclVendor.h" 25 #include "ClangPersistentVariables.h" 26 #include "ClangDiagnostic.h" 27 28 #include "lldb/Core/ConstString.h" 29 #include "lldb/Core/Debugger.h" 30 #include "lldb/Core/Log.h" 31 #include "lldb/Core/Module.h" 32 #include "lldb/Core/StreamFile.h" 33 #include "lldb/Core/StreamString.h" 34 #include "lldb/Core/ValueObjectConstResult.h" 35 #include "lldb/Expression/ExpressionSourceCode.h" 36 #include "lldb/Expression/IRExecutionUnit.h" 37 #include "lldb/Expression/IRInterpreter.h" 38 #include "lldb/Expression/Materializer.h" 39 #include "lldb/Host/HostInfo.h" 40 #include "lldb/Symbol/Block.h" 41 #include "lldb/Symbol/ClangASTContext.h" 42 #include "lldb/Symbol/Function.h" 43 #include "lldb/Symbol/ObjectFile.h" 44 #include "lldb/Symbol/SymbolVendor.h" 45 #include "lldb/Symbol/Type.h" 46 #include "lldb/Symbol/ClangExternalASTSourceCommon.h" 47 #include "lldb/Symbol/VariableList.h" 48 #include "lldb/Target/ExecutionContext.h" 49 #include "lldb/Target/Process.h" 50 #include "lldb/Target/StackFrame.h" 51 #include "lldb/Target/Target.h" 52 #include "lldb/Target/ThreadPlan.h" 53 #include "lldb/Target/ThreadPlanCallUserExpression.h" 54 55 #include "clang/AST/DeclCXX.h" 56 #include "clang/AST/DeclObjC.h" 57 58 using namespace lldb_private; 59 60 ClangUserExpression::ClangUserExpression(ExecutionContextScope &exe_scope, const char *expr, const char *expr_prefix, 61 lldb::LanguageType language, ResultType desired_type, 62 const EvaluateExpressionOptions &options) 63 : LLVMUserExpression(exe_scope, expr, expr_prefix, language, desired_type, options), 64 m_type_system_helper(*m_target_wp.lock().get(), options.GetExecutionPolicy() == eExecutionPolicyTopLevel) 65 { 66 switch (m_language) 67 { 68 case lldb::eLanguageTypeC_plus_plus: 69 m_allow_cxx = true; 70 break; 71 case lldb::eLanguageTypeObjC: 72 m_allow_objc = true; 73 break; 74 case lldb::eLanguageTypeObjC_plus_plus: 75 default: 76 m_allow_cxx = true; 77 m_allow_objc = true; 78 break; 79 } 80 } 81 82 ClangUserExpression::~ClangUserExpression () 83 { 84 } 85 86 void 87 ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err) 88 { 89 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 90 91 if (log) 92 log->Printf("ClangUserExpression::ScanContext()"); 93 94 m_target = exe_ctx.GetTargetPtr(); 95 96 if (!(m_allow_cxx || m_allow_objc)) 97 { 98 if (log) 99 log->Printf(" [CUE::SC] Settings inhibit C++ and Objective-C"); 100 return; 101 } 102 103 StackFrame *frame = exe_ctx.GetFramePtr(); 104 if (frame == NULL) 105 { 106 if (log) 107 log->Printf(" [CUE::SC] Null stack frame"); 108 return; 109 } 110 111 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction | lldb::eSymbolContextBlock); 112 113 if (!sym_ctx.function) 114 { 115 if (log) 116 log->Printf(" [CUE::SC] Null function"); 117 return; 118 } 119 120 // Find the block that defines the function represented by "sym_ctx" 121 Block *function_block = sym_ctx.GetFunctionBlock(); 122 123 if (!function_block) 124 { 125 if (log) 126 log->Printf(" [CUE::SC] Null function block"); 127 return; 128 } 129 130 CompilerDeclContext decl_context = function_block->GetDeclContext(); 131 132 if (!decl_context) 133 { 134 if (log) 135 log->Printf(" [CUE::SC] Null decl context"); 136 return; 137 } 138 139 if (clang::CXXMethodDecl *method_decl = ClangASTContext::DeclContextGetAsCXXMethodDecl(decl_context)) 140 { 141 if (m_allow_cxx && method_decl->isInstance()) 142 { 143 if (m_enforce_valid_object) 144 { 145 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true)); 146 147 const char *thisErrorString = "Stopped in a C++ method, but 'this' isn't available; pretending we are in a generic context"; 148 149 if (!variable_list_sp) 150 { 151 err.SetErrorString(thisErrorString); 152 return; 153 } 154 155 lldb::VariableSP this_var_sp (variable_list_sp->FindVariable(ConstString("this"))); 156 157 if (!this_var_sp || 158 !this_var_sp->IsInScope(frame) || 159 !this_var_sp->LocationIsValidForFrame (frame)) 160 { 161 err.SetErrorString(thisErrorString); 162 return; 163 } 164 } 165 166 m_in_cplusplus_method = true; 167 m_needs_object_ptr = true; 168 } 169 } 170 else if (clang::ObjCMethodDecl *method_decl = ClangASTContext::DeclContextGetAsObjCMethodDecl(decl_context)) 171 { 172 if (m_allow_objc) 173 { 174 if (m_enforce_valid_object) 175 { 176 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true)); 177 178 const char *selfErrorString = "Stopped in an Objective-C method, but 'self' isn't available; pretending we are in a generic context"; 179 180 if (!variable_list_sp) 181 { 182 err.SetErrorString(selfErrorString); 183 return; 184 } 185 186 lldb::VariableSP self_variable_sp = variable_list_sp->FindVariable(ConstString("self")); 187 188 if (!self_variable_sp || 189 !self_variable_sp->IsInScope(frame) || 190 !self_variable_sp->LocationIsValidForFrame (frame)) 191 { 192 err.SetErrorString(selfErrorString); 193 return; 194 } 195 } 196 197 m_in_objectivec_method = true; 198 m_needs_object_ptr = true; 199 200 if (!method_decl->isInstanceMethod()) 201 m_in_static_method = true; 202 } 203 } 204 else if (clang::FunctionDecl *function_decl = ClangASTContext::DeclContextGetAsFunctionDecl(decl_context)) 205 { 206 // We might also have a function that said in the debug information that it captured an 207 // object pointer. The best way to deal with getting to the ivars at present is by pretending 208 // that this is a method of a class in whatever runtime the debug info says the object pointer 209 // belongs to. Do that here. 210 211 ClangASTMetadata *metadata = ClangASTContext::DeclContextGetMetaData (decl_context, function_decl); 212 if (metadata && metadata->HasObjectPtr()) 213 { 214 lldb::LanguageType language = metadata->GetObjectPtrLanguage(); 215 if (language == lldb::eLanguageTypeC_plus_plus) 216 { 217 if (m_enforce_valid_object) 218 { 219 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true)); 220 221 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"; 222 223 if (!variable_list_sp) 224 { 225 err.SetErrorString(thisErrorString); 226 return; 227 } 228 229 lldb::VariableSP this_var_sp (variable_list_sp->FindVariable(ConstString("this"))); 230 231 if (!this_var_sp || 232 !this_var_sp->IsInScope(frame) || 233 !this_var_sp->LocationIsValidForFrame (frame)) 234 { 235 err.SetErrorString(thisErrorString); 236 return; 237 } 238 } 239 240 m_in_cplusplus_method = true; 241 m_needs_object_ptr = true; 242 } 243 else if (language == lldb::eLanguageTypeObjC) 244 { 245 if (m_enforce_valid_object) 246 { 247 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true)); 248 249 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"; 250 251 if (!variable_list_sp) 252 { 253 err.SetErrorString(selfErrorString); 254 return; 255 } 256 257 lldb::VariableSP self_variable_sp = variable_list_sp->FindVariable(ConstString("self")); 258 259 if (!self_variable_sp || 260 !self_variable_sp->IsInScope(frame) || 261 !self_variable_sp->LocationIsValidForFrame (frame)) 262 { 263 err.SetErrorString(selfErrorString); 264 return; 265 } 266 267 Type *self_type = self_variable_sp->GetType(); 268 269 if (!self_type) 270 { 271 err.SetErrorString(selfErrorString); 272 return; 273 } 274 275 CompilerType self_clang_type = self_type->GetForwardCompilerType (); 276 277 if (!self_clang_type) 278 { 279 err.SetErrorString(selfErrorString); 280 return; 281 } 282 283 if (ClangASTContext::IsObjCClassType(self_clang_type)) 284 { 285 return; 286 } 287 else if (ClangASTContext::IsObjCObjectPointerType(self_clang_type)) 288 { 289 m_in_objectivec_method = true; 290 m_needs_object_ptr = true; 291 } 292 else 293 { 294 err.SetErrorString(selfErrorString); 295 return; 296 } 297 } 298 else 299 { 300 m_in_objectivec_method = true; 301 m_needs_object_ptr = true; 302 } 303 } 304 } 305 } 306 } 307 308 // This is a really nasty hack, meant to fix Objective-C expressions of the form 309 // (int)[myArray count]. Right now, because the type information for count is 310 // not available, [myArray count] returns id, which can't be directly cast to 311 // int without causing a clang error. 312 static void 313 ApplyObjcCastHack(std::string &expr) 314 { 315 #define OBJC_CAST_HACK_FROM "(int)[" 316 #define OBJC_CAST_HACK_TO "(int)(long long)[" 317 318 size_t from_offset; 319 320 while ((from_offset = expr.find(OBJC_CAST_HACK_FROM)) != expr.npos) 321 expr.replace(from_offset, sizeof(OBJC_CAST_HACK_FROM) - 1, OBJC_CAST_HACK_TO); 322 323 #undef OBJC_CAST_HACK_TO 324 #undef OBJC_CAST_HACK_FROM 325 } 326 327 bool 328 ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, 329 lldb_private::ExecutionPolicy execution_policy, bool keep_result_in_memory, 330 bool generate_debug_info) 331 { 332 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 333 334 Error err; 335 336 InstallContext(exe_ctx); 337 338 if (Target *target = exe_ctx.GetTargetPtr()) 339 { 340 if (PersistentExpressionState *persistent_state = target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC)) 341 { 342 m_result_delegate.RegisterPersistentState(persistent_state); 343 } 344 else 345 { 346 diagnostic_manager.PutCString(eDiagnosticSeverityError, "couldn't start parsing (no persistent data)"); 347 return false; 348 } 349 } 350 else 351 { 352 diagnostic_manager.PutCString(eDiagnosticSeverityError, "error: couldn't start parsing (no target)"); 353 return false; 354 } 355 356 ScanContext(exe_ctx, err); 357 358 if (!err.Success()) 359 { 360 diagnostic_manager.PutCString(eDiagnosticSeverityWarning, err.AsCString()); 361 } 362 363 //////////////////////////////////// 364 // Generate the expression 365 // 366 367 ApplyObjcCastHack(m_expr_text); 368 //ApplyUnicharHack(m_expr_text); 369 370 std::string prefix = m_expr_prefix; 371 372 if (ClangModulesDeclVendor *decl_vendor = m_target->GetClangModulesDeclVendor()) 373 { 374 const ClangModulesDeclVendor::ModuleVector &hand_imported_modules = llvm::cast<ClangPersistentVariables>(m_target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC))->GetHandLoadedClangModules(); 375 ClangModulesDeclVendor::ModuleVector modules_for_macros; 376 377 for (ClangModulesDeclVendor::ModuleID module : hand_imported_modules) 378 { 379 modules_for_macros.push_back(module); 380 } 381 382 if (m_target->GetEnableAutoImportClangModules()) 383 { 384 if (StackFrame *frame = exe_ctx.GetFramePtr()) 385 { 386 if (Block *block = frame->GetFrameBlock()) 387 { 388 SymbolContext sc; 389 390 block->CalculateSymbolContext(&sc); 391 392 if (sc.comp_unit) 393 { 394 StreamString error_stream; 395 396 decl_vendor->AddModulesForCompileUnit(*sc.comp_unit, modules_for_macros, error_stream); 397 } 398 } 399 } 400 } 401 } 402 403 lldb::LanguageType lang_type = lldb::eLanguageTypeUnknown; 404 405 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) 406 { 407 m_transformed_text = m_expr_text; 408 } 409 else 410 { 411 std::unique_ptr<ExpressionSourceCode> source_code( 412 ExpressionSourceCode::CreateWrapped(prefix.c_str(), m_expr_text.c_str())); 413 414 if (m_in_cplusplus_method) 415 lang_type = lldb::eLanguageTypeC_plus_plus; 416 else if (m_in_objectivec_method) 417 lang_type = lldb::eLanguageTypeObjC; 418 else 419 lang_type = lldb::eLanguageTypeC; 420 421 if (!source_code->GetText(m_transformed_text, lang_type, m_in_static_method, exe_ctx)) 422 { 423 diagnostic_manager.PutCString(eDiagnosticSeverityError, "couldn't construct expression body"); 424 return false; 425 } 426 } 427 428 if (log) 429 log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str()); 430 431 //////////////////////////////////// 432 // Set up the target and compiler 433 // 434 435 Target *target = exe_ctx.GetTargetPtr(); 436 437 if (!target) 438 { 439 diagnostic_manager.PutCString(eDiagnosticSeverityError, "invalid target"); 440 return false; 441 } 442 443 ////////////////////////// 444 // Parse the expression 445 // 446 447 m_materializer_ap.reset(new Materializer()); 448 449 ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory); 450 451 class OnExit 452 { 453 public: 454 typedef std::function <void (void)> Callback; 455 456 OnExit (Callback const &callback) : 457 m_callback(callback) 458 { 459 } 460 461 ~OnExit () 462 { 463 m_callback(); 464 } 465 private: 466 Callback m_callback; 467 }; 468 469 OnExit on_exit([this]() { ResetDeclMap(); }); 470 471 if (!DeclMap()->WillParse(exe_ctx, m_materializer_ap.get())) 472 { 473 diagnostic_manager.PutCString(eDiagnosticSeverityError, 474 "current process state is unsuitable for expression parsing"); 475 476 ResetDeclMap(); // We are being careful here in the case of breakpoint conditions. 477 478 return false; 479 } 480 481 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) 482 { 483 DeclMap()->SetLookupsEnabled(true); 484 } 485 486 Process *process = exe_ctx.GetProcessPtr(); 487 ExecutionContextScope *exe_scope = process; 488 489 if (!exe_scope) 490 exe_scope = exe_ctx.GetTargetPtr(); 491 492 // We use a shared pointer here so we can use the original parser - if it succeeds 493 // or the rewrite parser we might make if it fails. But the parser_sp will never be empty. 494 495 ClangExpressionParser parser(exe_scope, *this, generate_debug_info); 496 497 unsigned num_errors = parser.Parse(diagnostic_manager); 498 499 // Check here for FixItHints. If there are any try to apply the fixits and set the fixed text in m_fixed_text 500 // before returning an error. 501 if (num_errors) 502 { 503 if (diagnostic_manager.HasFixIts()) 504 { 505 if (parser.RewriteExpression(diagnostic_manager)) 506 { 507 size_t fixed_start; 508 size_t fixed_end; 509 const std::string &fixed_expression = diagnostic_manager.GetFixedExpression(); 510 if (ExpressionSourceCode::GetOriginalBodyBounds(fixed_expression, lang_type, fixed_start, fixed_end)) 511 m_fixed_text = fixed_expression.substr(fixed_start, fixed_end - fixed_start); 512 } 513 } 514 515 ResetDeclMap(); // We are being careful here in the case of breakpoint conditions. 516 517 return false; 518 } 519 520 ////////////////////////////////////////////////////////////////////////////////////////// 521 // Prepare the output of the parser for execution, evaluating it statically if possible 522 // 523 524 { 525 Error jit_error = parser.PrepareForExecution(m_jit_start_addr, 526 m_jit_end_addr, 527 m_execution_unit_sp, 528 exe_ctx, 529 m_can_interpret, 530 execution_policy); 531 532 if (!jit_error.Success()) 533 { 534 const char *error_cstr = jit_error.AsCString(); 535 if (error_cstr && error_cstr[0]) 536 diagnostic_manager.PutCString(eDiagnosticSeverityError, error_cstr); 537 else 538 diagnostic_manager.PutCString(eDiagnosticSeverityError, "expression can't be interpreted or run"); 539 return false; 540 } 541 } 542 543 if (exe_ctx.GetProcessPtr() && execution_policy == eExecutionPolicyTopLevel) 544 { 545 Error static_init_error = parser.RunStaticInitializers(m_execution_unit_sp, exe_ctx); 546 547 if (!static_init_error.Success()) 548 { 549 const char *error_cstr = static_init_error.AsCString(); 550 if (error_cstr && error_cstr[0]) 551 diagnostic_manager.Printf(eDiagnosticSeverityError, "couldn't run static initializers: %s\n", 552 error_cstr); 553 else 554 diagnostic_manager.PutCString(eDiagnosticSeverityError, "couldn't run static initializers\n"); 555 return false; 556 } 557 } 558 559 if (m_execution_unit_sp) 560 { 561 bool register_execution_unit = false; 562 563 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) 564 { 565 register_execution_unit = true; 566 } 567 568 // If there is more than one external function in the execution 569 // unit, it needs to keep living even if it's not top level, because 570 // the result could refer to that function. 571 572 if (m_execution_unit_sp->GetJittedFunctions().size() > 1) 573 { 574 register_execution_unit = true; 575 } 576 577 if (register_execution_unit) 578 { 579 llvm::cast<PersistentExpressionState>( 580 exe_ctx.GetTargetPtr()->GetPersistentExpressionStateForLanguage(m_language)) 581 ->RegisterExecutionUnit(m_execution_unit_sp); 582 } 583 } 584 585 if (generate_debug_info) 586 { 587 lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule()); 588 589 if (jit_module_sp) 590 { 591 ConstString const_func_name(FunctionName()); 592 FileSpec jit_file; 593 jit_file.GetFilename() = const_func_name; 594 jit_module_sp->SetFileSpecAndObjectName (jit_file, ConstString()); 595 m_jit_module_wp = jit_module_sp; 596 target->GetImages().Append(jit_module_sp); 597 } 598 } 599 600 ResetDeclMap(); // Make this go away since we don't need any of its state after parsing. This also gets rid of any 601 // ClangASTImporter::Minions. 602 603 if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS) 604 m_jit_process_wp = lldb::ProcessWP(process->shared_from_this()); 605 return true; 606 } 607 608 bool 609 ClangUserExpression::AddArguments(ExecutionContext &exe_ctx, std::vector<lldb::addr_t> &args, 610 lldb::addr_t struct_address, DiagnosticManager &diagnostic_manager) 611 { 612 lldb::addr_t object_ptr = LLDB_INVALID_ADDRESS; 613 lldb::addr_t cmd_ptr = LLDB_INVALID_ADDRESS; 614 615 if (m_needs_object_ptr) 616 { 617 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP(); 618 if (!frame_sp) 619 return true; 620 621 ConstString object_name; 622 623 if (m_in_cplusplus_method) 624 { 625 object_name.SetCString("this"); 626 } 627 else if (m_in_objectivec_method) 628 { 629 object_name.SetCString("self"); 630 } 631 else 632 { 633 diagnostic_manager.PutCString(eDiagnosticSeverityError, "need object pointer but don't know the language"); 634 return false; 635 } 636 637 Error object_ptr_error; 638 639 object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error); 640 641 if (!object_ptr_error.Success()) 642 { 643 exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Printf("warning: `%s' is not accessible (subsituting 0)\n", object_name.AsCString()); 644 object_ptr = 0; 645 } 646 647 if (m_in_objectivec_method) 648 { 649 ConstString cmd_name("_cmd"); 650 651 cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error); 652 653 if (!object_ptr_error.Success()) 654 { 655 diagnostic_manager.Printf(eDiagnosticSeverityWarning, 656 "couldn't get cmd pointer (substituting NULL): %s", 657 object_ptr_error.AsCString()); 658 cmd_ptr = 0; 659 } 660 } 661 662 args.push_back(object_ptr); 663 664 if (m_in_objectivec_method) 665 args.push_back(cmd_ptr); 666 667 args.push_back(struct_address); 668 } 669 else 670 { 671 args.push_back(struct_address); 672 } 673 return true; 674 } 675 676 lldb::ExpressionVariableSP 677 ClangUserExpression::GetResultAfterDematerialization(ExecutionContextScope *exe_scope) 678 { 679 return m_result_delegate.GetVariable(); 680 } 681 682 void 683 ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap(ExecutionContext &exe_ctx, Materializer::PersistentVariableDelegate &delegate, bool keep_result_in_memory) 684 { 685 m_expr_decl_map_up.reset(new ClangExpressionDeclMap(keep_result_in_memory, &delegate, exe_ctx)); 686 } 687 688 clang::ASTConsumer * 689 ClangUserExpression::ClangUserExpressionHelper::ASTTransformer(clang::ASTConsumer *passthrough) 690 { 691 m_result_synthesizer_up.reset(new ASTResultSynthesizer(passthrough, m_top_level, m_target)); 692 693 return m_result_synthesizer_up.get(); 694 } 695 696 void 697 ClangUserExpression::ClangUserExpressionHelper::CommitPersistentDecls() 698 { 699 if (m_result_synthesizer_up.get()) 700 { 701 m_result_synthesizer_up->CommitPersistentDecls(); 702 } 703 } 704 705 ClangUserExpression::ResultDelegate::ResultDelegate() 706 { 707 } 708 709 ConstString 710 ClangUserExpression::ResultDelegate::GetName() 711 { 712 return m_persistent_state->GetNextPersistentVariableName(); 713 } 714 715 void 716 ClangUserExpression::ResultDelegate::DidDematerialize(lldb::ExpressionVariableSP &variable) 717 { 718 m_variable = variable; 719 } 720 721 void 722 ClangUserExpression::ResultDelegate::RegisterPersistentState(PersistentExpressionState *persistent_state) 723 { 724 m_persistent_state = persistent_state; 725 } 726 727 lldb::ExpressionVariableSP & 728 ClangUserExpression::ResultDelegate::GetVariable() 729 { 730 return m_variable; 731 } 732 733