1 //===-- ClangUserExpression.cpp ---------------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "lldb/Host/Config.h" 10 11 #include <stdio.h> 12 #if HAVE_SYS_TYPES_H 13 #include <sys/types.h> 14 #endif 15 16 #include <cstdlib> 17 #include <map> 18 #include <string> 19 20 #include "ClangUserExpression.h" 21 22 #include "ASTResultSynthesizer.h" 23 #include "ClangDiagnostic.h" 24 #include "ClangExpressionDeclMap.h" 25 #include "ClangExpressionParser.h" 26 #include "ClangModulesDeclVendor.h" 27 #include "ClangPersistentVariables.h" 28 #include "CppModuleConfiguration.h" 29 30 #include "lldb/Core/Debugger.h" 31 #include "lldb/Core/Module.h" 32 #include "lldb/Core/StreamFile.h" 33 #include "lldb/Core/ValueObjectConstResult.h" 34 #include "lldb/Expression/ExpressionSourceCode.h" 35 #include "lldb/Expression/IRExecutionUnit.h" 36 #include "lldb/Expression/IRInterpreter.h" 37 #include "lldb/Expression/Materializer.h" 38 #include "lldb/Host/HostInfo.h" 39 #include "lldb/Symbol/Block.h" 40 #include "lldb/Symbol/ClangASTContext.h" 41 #include "lldb/Symbol/ClangExternalASTSourceCommon.h" 42 #include "lldb/Symbol/CompileUnit.h" 43 #include "lldb/Symbol/Function.h" 44 #include "lldb/Symbol/ObjectFile.h" 45 #include "lldb/Symbol/SymbolVendor.h" 46 #include "lldb/Symbol/Type.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 #include "lldb/Utility/ConstString.h" 55 #include "lldb/Utility/Log.h" 56 #include "lldb/Utility/StreamString.h" 57 58 #include "clang/AST/DeclCXX.h" 59 #include "clang/AST/DeclObjC.h" 60 61 #include "llvm/ADT/ScopeExit.h" 62 63 using namespace lldb_private; 64 65 ClangUserExpression::ClangUserExpression( 66 ExecutionContextScope &exe_scope, llvm::StringRef expr, 67 llvm::StringRef prefix, lldb::LanguageType language, 68 ResultType desired_type, const EvaluateExpressionOptions &options, 69 ValueObject *ctx_obj) 70 : LLVMUserExpression(exe_scope, expr, prefix, language, desired_type, 71 options, eKindClangUserExpression), 72 m_type_system_helper(*m_target_wp.lock(), options.GetExecutionPolicy() == 73 eExecutionPolicyTopLevel), 74 m_result_delegate(exe_scope.CalculateTarget()), m_ctx_obj(ctx_obj) { 75 switch (m_language) { 76 case lldb::eLanguageTypeC_plus_plus: 77 m_allow_cxx = true; 78 break; 79 case lldb::eLanguageTypeObjC: 80 m_allow_objc = true; 81 break; 82 case lldb::eLanguageTypeObjC_plus_plus: 83 default: 84 m_allow_cxx = true; 85 m_allow_objc = true; 86 break; 87 } 88 } 89 90 ClangUserExpression::~ClangUserExpression() {} 91 92 void ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Status &err) { 93 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 94 95 LLDB_LOGF(log, "ClangUserExpression::ScanContext()"); 96 97 m_target = exe_ctx.GetTargetPtr(); 98 99 if (!(m_allow_cxx || m_allow_objc)) { 100 LLDB_LOGF(log, " [CUE::SC] Settings inhibit C++ and Objective-C"); 101 return; 102 } 103 104 StackFrame *frame = exe_ctx.GetFramePtr(); 105 if (frame == nullptr) { 106 LLDB_LOGF(log, " [CUE::SC] Null stack frame"); 107 return; 108 } 109 110 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction | 111 lldb::eSymbolContextBlock); 112 113 if (!sym_ctx.function) { 114 LLDB_LOGF(log, " [CUE::SC] Null function"); 115 return; 116 } 117 118 // Find the block that defines the function represented by "sym_ctx" 119 Block *function_block = sym_ctx.GetFunctionBlock(); 120 121 if (!function_block) { 122 LLDB_LOGF(log, " [CUE::SC] Null function block"); 123 return; 124 } 125 126 CompilerDeclContext decl_context = function_block->GetDeclContext(); 127 128 if (!decl_context) { 129 LLDB_LOGF(log, " [CUE::SC] Null decl context"); 130 return; 131 } 132 133 if (m_ctx_obj) { 134 switch (m_ctx_obj->GetObjectRuntimeLanguage()) { 135 case lldb::eLanguageTypeC: 136 case lldb::eLanguageTypeC89: 137 case lldb::eLanguageTypeC99: 138 case lldb::eLanguageTypeC11: 139 case lldb::eLanguageTypeC_plus_plus: 140 case lldb::eLanguageTypeC_plus_plus_03: 141 case lldb::eLanguageTypeC_plus_plus_11: 142 case lldb::eLanguageTypeC_plus_plus_14: 143 m_in_cplusplus_method = true; 144 break; 145 case lldb::eLanguageTypeObjC: 146 case lldb::eLanguageTypeObjC_plus_plus: 147 m_in_objectivec_method = true; 148 break; 149 default: 150 break; 151 } 152 m_needs_object_ptr = true; 153 } else if (clang::CXXMethodDecl *method_decl = 154 ClangASTContext::DeclContextGetAsCXXMethodDecl(decl_context)) { 155 if (m_allow_cxx && method_decl->isInstance()) { 156 if (m_enforce_valid_object) { 157 lldb::VariableListSP variable_list_sp( 158 function_block->GetBlockVariableList(true)); 159 160 const char *thisErrorString = "Stopped in a C++ method, but 'this' " 161 "isn't available; pretending we are in a " 162 "generic context"; 163 164 if (!variable_list_sp) { 165 err.SetErrorString(thisErrorString); 166 return; 167 } 168 169 lldb::VariableSP this_var_sp( 170 variable_list_sp->FindVariable(ConstString("this"))); 171 172 if (!this_var_sp || !this_var_sp->IsInScope(frame) || 173 !this_var_sp->LocationIsValidForFrame(frame)) { 174 err.SetErrorString(thisErrorString); 175 return; 176 } 177 } 178 179 m_in_cplusplus_method = true; 180 m_needs_object_ptr = true; 181 } 182 } else if (clang::ObjCMethodDecl *method_decl = 183 ClangASTContext::DeclContextGetAsObjCMethodDecl( 184 decl_context)) { 185 if (m_allow_objc) { 186 if (m_enforce_valid_object) { 187 lldb::VariableListSP variable_list_sp( 188 function_block->GetBlockVariableList(true)); 189 190 const char *selfErrorString = "Stopped in an Objective-C method, but " 191 "'self' isn't available; pretending we " 192 "are in a generic context"; 193 194 if (!variable_list_sp) { 195 err.SetErrorString(selfErrorString); 196 return; 197 } 198 199 lldb::VariableSP self_variable_sp = 200 variable_list_sp->FindVariable(ConstString("self")); 201 202 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) || 203 !self_variable_sp->LocationIsValidForFrame(frame)) { 204 err.SetErrorString(selfErrorString); 205 return; 206 } 207 } 208 209 m_in_objectivec_method = true; 210 m_needs_object_ptr = true; 211 212 if (!method_decl->isInstanceMethod()) 213 m_in_static_method = true; 214 } 215 } else if (clang::FunctionDecl *function_decl = 216 ClangASTContext::DeclContextGetAsFunctionDecl(decl_context)) { 217 // We might also have a function that said in the debug information that it 218 // captured an object pointer. The best way to deal with getting to the 219 // ivars at present is by pretending that this is a method of a class in 220 // whatever runtime the debug info says the object pointer belongs to. Do 221 // that here. 222 223 ClangASTMetadata *metadata = 224 ClangASTContext::DeclContextGetMetaData(decl_context, function_decl); 225 if (metadata && metadata->HasObjectPtr()) { 226 lldb::LanguageType language = metadata->GetObjectPtrLanguage(); 227 if (language == lldb::eLanguageTypeC_plus_plus) { 228 if (m_enforce_valid_object) { 229 lldb::VariableListSP variable_list_sp( 230 function_block->GetBlockVariableList(true)); 231 232 const char *thisErrorString = "Stopped in a context claiming to " 233 "capture a C++ object pointer, but " 234 "'this' isn't available; pretending we " 235 "are in a generic context"; 236 237 if (!variable_list_sp) { 238 err.SetErrorString(thisErrorString); 239 return; 240 } 241 242 lldb::VariableSP this_var_sp( 243 variable_list_sp->FindVariable(ConstString("this"))); 244 245 if (!this_var_sp || !this_var_sp->IsInScope(frame) || 246 !this_var_sp->LocationIsValidForFrame(frame)) { 247 err.SetErrorString(thisErrorString); 248 return; 249 } 250 } 251 252 m_in_cplusplus_method = true; 253 m_needs_object_ptr = true; 254 } else if (language == lldb::eLanguageTypeObjC) { 255 if (m_enforce_valid_object) { 256 lldb::VariableListSP variable_list_sp( 257 function_block->GetBlockVariableList(true)); 258 259 const char *selfErrorString = 260 "Stopped in a context claiming to capture an Objective-C object " 261 "pointer, but 'self' isn't available; pretending we are in a " 262 "generic context"; 263 264 if (!variable_list_sp) { 265 err.SetErrorString(selfErrorString); 266 return; 267 } 268 269 lldb::VariableSP self_variable_sp = 270 variable_list_sp->FindVariable(ConstString("self")); 271 272 if (!self_variable_sp || !self_variable_sp->IsInScope(frame) || 273 !self_variable_sp->LocationIsValidForFrame(frame)) { 274 err.SetErrorString(selfErrorString); 275 return; 276 } 277 278 Type *self_type = self_variable_sp->GetType(); 279 280 if (!self_type) { 281 err.SetErrorString(selfErrorString); 282 return; 283 } 284 285 CompilerType self_clang_type = self_type->GetForwardCompilerType(); 286 287 if (!self_clang_type) { 288 err.SetErrorString(selfErrorString); 289 return; 290 } 291 292 if (ClangASTContext::IsObjCClassType(self_clang_type)) { 293 return; 294 } else if (ClangASTContext::IsObjCObjectPointerType( 295 self_clang_type)) { 296 m_in_objectivec_method = true; 297 m_needs_object_ptr = true; 298 } else { 299 err.SetErrorString(selfErrorString); 300 return; 301 } 302 } else { 303 m_in_objectivec_method = true; 304 m_needs_object_ptr = true; 305 } 306 } 307 } 308 } 309 } 310 311 // This is a really nasty hack, meant to fix Objective-C expressions of the 312 // form (int)[myArray count]. Right now, because the type information for 313 // count is not available, [myArray count] returns id, which can't be directly 314 // cast to int without causing a clang error. 315 static void ApplyObjcCastHack(std::string &expr) { 316 const std::string from = "(int)["; 317 const std::string to = "(int)(long long)["; 318 319 size_t offset; 320 321 while ((offset = expr.find(from)) != expr.npos) 322 expr.replace(offset, from.size(), to); 323 } 324 325 bool ClangUserExpression::SetupPersistentState(DiagnosticManager &diagnostic_manager, 326 ExecutionContext &exe_ctx) { 327 if (Target *target = exe_ctx.GetTargetPtr()) { 328 if (PersistentExpressionState *persistent_state = 329 target->GetPersistentExpressionStateForLanguage( 330 lldb::eLanguageTypeC)) { 331 m_clang_state = llvm::cast<ClangPersistentVariables>(persistent_state); 332 m_result_delegate.RegisterPersistentState(persistent_state); 333 } else { 334 diagnostic_manager.PutString( 335 eDiagnosticSeverityError, 336 "couldn't start parsing (no persistent data)"); 337 return false; 338 } 339 } else { 340 diagnostic_manager.PutString(eDiagnosticSeverityError, 341 "error: couldn't start parsing (no target)"); 342 return false; 343 } 344 return true; 345 } 346 347 static void SetupDeclVendor(ExecutionContext &exe_ctx, Target *target) { 348 if (ClangModulesDeclVendor *decl_vendor = 349 target->GetClangModulesDeclVendor()) { 350 const ClangModulesDeclVendor::ModuleVector &hand_imported_modules = 351 llvm::cast<ClangPersistentVariables>( 352 target->GetPersistentExpressionStateForLanguage( 353 lldb::eLanguageTypeC)) 354 ->GetHandLoadedClangModules(); 355 ClangModulesDeclVendor::ModuleVector modules_for_macros; 356 357 for (ClangModulesDeclVendor::ModuleID module : hand_imported_modules) { 358 modules_for_macros.push_back(module); 359 } 360 361 if (target->GetEnableAutoImportClangModules()) { 362 if (StackFrame *frame = exe_ctx.GetFramePtr()) { 363 if (Block *block = frame->GetFrameBlock()) { 364 SymbolContext sc; 365 366 block->CalculateSymbolContext(&sc); 367 368 if (sc.comp_unit) { 369 StreamString error_stream; 370 371 decl_vendor->AddModulesForCompileUnit( 372 *sc.comp_unit, modules_for_macros, error_stream); 373 } 374 } 375 } 376 } 377 } 378 } 379 380 void ClangUserExpression::UpdateLanguageForExpr() { 381 m_expr_lang = lldb::LanguageType::eLanguageTypeUnknown; 382 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) 383 return; 384 if (m_in_cplusplus_method) 385 m_expr_lang = lldb::eLanguageTypeC_plus_plus; 386 else if (m_in_objectivec_method) 387 m_expr_lang = lldb::eLanguageTypeObjC; 388 else 389 m_expr_lang = lldb::eLanguageTypeC; 390 } 391 392 void ClangUserExpression::CreateSourceCode( 393 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, 394 std::vector<std::string> modules_to_import, bool for_completion) { 395 396 m_filename = m_clang_state->GetNextExprFileName(); 397 std::string prefix = m_expr_prefix; 398 399 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) { 400 m_transformed_text = m_expr_text; 401 } else { 402 m_source_code.reset(ClangExpressionSourceCode::CreateWrapped( 403 m_filename, prefix.c_str(), m_expr_text.c_str())); 404 405 if (!m_source_code->GetText(m_transformed_text, m_expr_lang, 406 m_in_static_method, exe_ctx, !m_ctx_obj, 407 for_completion, modules_to_import)) { 408 diagnostic_manager.PutString(eDiagnosticSeverityError, 409 "couldn't construct expression body"); 410 return; 411 } 412 413 // Find and store the start position of the original code inside the 414 // transformed code. We need this later for the code completion. 415 std::size_t original_start; 416 std::size_t original_end; 417 bool found_bounds = m_source_code->GetOriginalBodyBounds( 418 m_transformed_text, m_expr_lang, original_start, original_end); 419 if (found_bounds) 420 m_user_expression_start_pos = original_start; 421 } 422 } 423 424 static bool SupportsCxxModuleImport(lldb::LanguageType language) { 425 switch (language) { 426 case lldb::eLanguageTypeC_plus_plus: 427 case lldb::eLanguageTypeC_plus_plus_03: 428 case lldb::eLanguageTypeC_plus_plus_11: 429 case lldb::eLanguageTypeC_plus_plus_14: 430 case lldb::eLanguageTypeObjC_plus_plus: 431 return true; 432 default: 433 return false; 434 } 435 } 436 437 /// Utility method that puts a message into the expression log and 438 /// returns an invalid module configuration. 439 static CppModuleConfiguration LogConfigError(const std::string &msg) { 440 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 441 LLDB_LOG(log, "[C++ module config] {0}", msg); 442 return CppModuleConfiguration(); 443 } 444 445 CppModuleConfiguration GetModuleConfig(lldb::LanguageType language, 446 ExecutionContext &exe_ctx) { 447 // Don't do anything if this is not a C++ module configuration. 448 if (!SupportsCxxModuleImport(language)) 449 return LogConfigError("Language doesn't support C++ modules"); 450 451 Target *target = exe_ctx.GetTargetPtr(); 452 if (!target) 453 return LogConfigError("No target"); 454 455 if (!target->GetEnableImportStdModule()) 456 return LogConfigError("Importing std module not enabled in settings"); 457 458 StackFrame *frame = exe_ctx.GetFramePtr(); 459 if (!frame) 460 return LogConfigError("No frame"); 461 462 Block *block = frame->GetFrameBlock(); 463 if (!block) 464 return LogConfigError("No block"); 465 466 SymbolContext sc; 467 block->CalculateSymbolContext(&sc); 468 if (!sc.comp_unit) 469 return LogConfigError("Couldn't calculate symbol context"); 470 471 // Build a list of files we need to analyze to build the configuration. 472 FileSpecList files; 473 for (const FileSpec &f : sc.comp_unit->GetSupportFiles()) 474 files.AppendIfUnique(f); 475 // We also need to look at external modules in the case of -gmodules as they 476 // contain the support files for libc++ and the C library. 477 sc.comp_unit->ForEachExternalModule([&files](lldb::ModuleSP module) { 478 for (std::size_t i = 0; i < module->GetNumCompileUnits(); ++i) { 479 const FileSpecList &support_files = 480 module->GetCompileUnitAtIndex(i)->GetSupportFiles(); 481 for (const FileSpec &f : support_files) { 482 files.AppendIfUnique(f); 483 } 484 } 485 }); 486 // Try to create a configuration from the files. If there is no valid 487 // configuration possible with the files, this just returns an invalid 488 // configuration. 489 return CppModuleConfiguration(files); 490 } 491 492 bool ClangUserExpression::PrepareForParsing( 493 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, 494 bool for_completion) { 495 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 496 497 InstallContext(exe_ctx); 498 499 if (!SetupPersistentState(diagnostic_manager, exe_ctx)) 500 return false; 501 502 Status err; 503 ScanContext(exe_ctx, err); 504 505 if (!err.Success()) { 506 diagnostic_manager.PutString(eDiagnosticSeverityWarning, err.AsCString()); 507 } 508 509 //////////////////////////////////// 510 // Generate the expression 511 // 512 513 ApplyObjcCastHack(m_expr_text); 514 515 SetupDeclVendor(exe_ctx, m_target); 516 517 CppModuleConfiguration module_config = GetModuleConfig(m_language, exe_ctx); 518 llvm::ArrayRef<std::string> imported_modules = 519 module_config.GetImportedModules(); 520 m_imported_cpp_modules = !imported_modules.empty(); 521 m_include_directories = module_config.GetIncludeDirs(); 522 523 LLDB_LOG(log, "List of imported modules in expression: {0}", 524 llvm::make_range(imported_modules.begin(), imported_modules.end())); 525 LLDB_LOG(log, "List of include directories gathered for modules: {0}", 526 llvm::make_range(m_include_directories.begin(), 527 m_include_directories.end())); 528 529 UpdateLanguageForExpr(); 530 CreateSourceCode(diagnostic_manager, exe_ctx, imported_modules, 531 for_completion); 532 return true; 533 } 534 535 bool ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager, 536 ExecutionContext &exe_ctx, 537 lldb_private::ExecutionPolicy execution_policy, 538 bool keep_result_in_memory, 539 bool generate_debug_info) { 540 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 541 542 if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ false)) 543 return false; 544 545 LLDB_LOGF(log, "Parsing the following code:\n%s", m_transformed_text.c_str()); 546 547 //////////////////////////////////// 548 // Set up the target and compiler 549 // 550 551 Target *target = exe_ctx.GetTargetPtr(); 552 553 if (!target) { 554 diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target"); 555 return false; 556 } 557 558 ////////////////////////// 559 // Parse the expression 560 // 561 562 m_materializer_up.reset(new Materializer()); 563 564 ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory); 565 566 auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); }); 567 568 if (!DeclMap()->WillParse(exe_ctx, m_materializer_up.get())) { 569 diagnostic_manager.PutString( 570 eDiagnosticSeverityError, 571 "current process state is unsuitable for expression parsing"); 572 return false; 573 } 574 575 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) { 576 DeclMap()->SetLookupsEnabled(true); 577 } 578 579 Process *process = exe_ctx.GetProcessPtr(); 580 ExecutionContextScope *exe_scope = process; 581 582 if (!exe_scope) 583 exe_scope = exe_ctx.GetTargetPtr(); 584 585 // We use a shared pointer here so we can use the original parser - if it 586 // succeeds or the rewrite parser we might make if it fails. But the 587 // parser_sp will never be empty. 588 589 ClangExpressionParser parser(exe_scope, *this, generate_debug_info, 590 m_include_directories, m_filename); 591 592 unsigned num_errors = parser.Parse(diagnostic_manager); 593 594 // Check here for FixItHints. If there are any try to apply the fixits and 595 // set the fixed text in m_fixed_text before returning an error. 596 if (num_errors) { 597 if (diagnostic_manager.HasFixIts()) { 598 if (parser.RewriteExpression(diagnostic_manager)) { 599 size_t fixed_start; 600 size_t fixed_end; 601 const std::string &fixed_expression = 602 diagnostic_manager.GetFixedExpression(); 603 // Retrieve the original expression in case we don't have a top level 604 // expression (which has no surrounding source code). 605 if (m_source_code && 606 m_source_code->GetOriginalBodyBounds(fixed_expression, m_expr_lang, 607 fixed_start, fixed_end)) 608 m_fixed_text = 609 fixed_expression.substr(fixed_start, fixed_end - fixed_start); 610 } 611 } 612 return false; 613 } 614 615 ////////////////////////////////////////////////////////////////////////////// 616 // Prepare the output of the parser for execution, evaluating it statically 617 // if possible 618 // 619 620 { 621 Status jit_error = parser.PrepareForExecution( 622 m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx, 623 m_can_interpret, execution_policy); 624 625 if (!jit_error.Success()) { 626 const char *error_cstr = jit_error.AsCString(); 627 if (error_cstr && error_cstr[0]) 628 diagnostic_manager.PutString(eDiagnosticSeverityError, error_cstr); 629 else 630 diagnostic_manager.PutString(eDiagnosticSeverityError, 631 "expression can't be interpreted or run"); 632 return false; 633 } 634 } 635 636 if (exe_ctx.GetProcessPtr() && execution_policy == eExecutionPolicyTopLevel) { 637 Status static_init_error = 638 parser.RunStaticInitializers(m_execution_unit_sp, exe_ctx); 639 640 if (!static_init_error.Success()) { 641 const char *error_cstr = static_init_error.AsCString(); 642 if (error_cstr && error_cstr[0]) 643 diagnostic_manager.Printf(eDiagnosticSeverityError, 644 "couldn't run static initializers: %s\n", 645 error_cstr); 646 else 647 diagnostic_manager.PutString(eDiagnosticSeverityError, 648 "couldn't run static initializers\n"); 649 return false; 650 } 651 } 652 653 if (m_execution_unit_sp) { 654 bool register_execution_unit = false; 655 656 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) { 657 register_execution_unit = true; 658 } 659 660 // If there is more than one external function in the execution unit, it 661 // needs to keep living even if it's not top level, because the result 662 // could refer to that function. 663 664 if (m_execution_unit_sp->GetJittedFunctions().size() > 1) { 665 register_execution_unit = true; 666 } 667 668 if (register_execution_unit) 669 exe_ctx.GetTargetPtr() 670 ->GetPersistentExpressionStateForLanguage(m_language) 671 ->RegisterExecutionUnit(m_execution_unit_sp); 672 } 673 674 if (generate_debug_info) { 675 lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule()); 676 677 if (jit_module_sp) { 678 ConstString const_func_name(FunctionName()); 679 FileSpec jit_file; 680 jit_file.GetFilename() = const_func_name; 681 jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString()); 682 m_jit_module_wp = jit_module_sp; 683 target->GetImages().Append(jit_module_sp); 684 } 685 } 686 687 if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS) 688 m_jit_process_wp = lldb::ProcessWP(process->shared_from_this()); 689 return true; 690 } 691 692 /// Converts an absolute position inside a given code string into 693 /// a column/line pair. 694 /// 695 /// \param[in] abs_pos 696 /// A absolute position in the code string that we want to convert 697 /// to a column/line pair. 698 /// 699 /// \param[in] code 700 /// A multi-line string usually representing source code. 701 /// 702 /// \param[out] line 703 /// The line in the code that contains the given absolute position. 704 /// The first line in the string is indexed as 1. 705 /// 706 /// \param[out] column 707 /// The column in the line that contains the absolute position. 708 /// The first character in a line is indexed as 0. 709 static void AbsPosToLineColumnPos(size_t abs_pos, llvm::StringRef code, 710 unsigned &line, unsigned &column) { 711 // Reset to code position to beginning of the file. 712 line = 0; 713 column = 0; 714 715 assert(abs_pos <= code.size() && "Absolute position outside code string?"); 716 717 // We have to walk up to the position and count lines/columns. 718 for (std::size_t i = 0; i < abs_pos; ++i) { 719 // If we hit a line break, we go back to column 0 and enter a new line. 720 // We only handle \n because that's what we internally use to make new 721 // lines for our temporary code strings. 722 if (code[i] == '\n') { 723 ++line; 724 column = 0; 725 continue; 726 } 727 ++column; 728 } 729 } 730 731 bool ClangUserExpression::Complete(ExecutionContext &exe_ctx, 732 CompletionRequest &request, 733 unsigned complete_pos) { 734 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 735 736 // We don't want any visible feedback when completing an expression. Mostly 737 // because the results we get from an incomplete invocation are probably not 738 // correct. 739 DiagnosticManager diagnostic_manager; 740 741 if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ true)) 742 return false; 743 744 LLDB_LOGF(log, "Parsing the following code:\n%s", m_transformed_text.c_str()); 745 746 ////////////////////////// 747 // Parse the expression 748 // 749 750 m_materializer_up.reset(new Materializer()); 751 752 ResetDeclMap(exe_ctx, m_result_delegate, /*keep result in memory*/ true); 753 754 auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); }); 755 756 if (!DeclMap()->WillParse(exe_ctx, m_materializer_up.get())) { 757 diagnostic_manager.PutString( 758 eDiagnosticSeverityError, 759 "current process state is unsuitable for expression parsing"); 760 761 return false; 762 } 763 764 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) { 765 DeclMap()->SetLookupsEnabled(true); 766 } 767 768 Process *process = exe_ctx.GetProcessPtr(); 769 ExecutionContextScope *exe_scope = process; 770 771 if (!exe_scope) 772 exe_scope = exe_ctx.GetTargetPtr(); 773 774 ClangExpressionParser parser(exe_scope, *this, false); 775 776 // We have to find the source code location where the user text is inside 777 // the transformed expression code. When creating the transformed text, we 778 // already stored the absolute position in the m_transformed_text string. The 779 // only thing left to do is to transform it into the line:column format that 780 // Clang expects. 781 782 // The line and column of the user expression inside the transformed source 783 // code. 784 unsigned user_expr_line, user_expr_column; 785 if (m_user_expression_start_pos.hasValue()) 786 AbsPosToLineColumnPos(*m_user_expression_start_pos, m_transformed_text, 787 user_expr_line, user_expr_column); 788 else 789 return false; 790 791 // The actual column where we have to complete is the start column of the 792 // user expression + the offset inside the user code that we were given. 793 const unsigned completion_column = user_expr_column + complete_pos; 794 parser.Complete(request, user_expr_line, completion_column, complete_pos); 795 796 return true; 797 } 798 799 bool ClangUserExpression::AddArguments(ExecutionContext &exe_ctx, 800 std::vector<lldb::addr_t> &args, 801 lldb::addr_t struct_address, 802 DiagnosticManager &diagnostic_manager) { 803 lldb::addr_t object_ptr = LLDB_INVALID_ADDRESS; 804 lldb::addr_t cmd_ptr = LLDB_INVALID_ADDRESS; 805 806 if (m_needs_object_ptr) { 807 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP(); 808 if (!frame_sp) 809 return true; 810 811 ConstString object_name; 812 813 if (m_in_cplusplus_method) { 814 object_name.SetCString("this"); 815 } else if (m_in_objectivec_method) { 816 object_name.SetCString("self"); 817 } else { 818 diagnostic_manager.PutString( 819 eDiagnosticSeverityError, 820 "need object pointer but don't know the language"); 821 return false; 822 } 823 824 Status object_ptr_error; 825 826 if (m_ctx_obj) { 827 AddressType address_type; 828 object_ptr = m_ctx_obj->GetAddressOf(false, &address_type); 829 if (object_ptr == LLDB_INVALID_ADDRESS || 830 address_type != eAddressTypeLoad) 831 object_ptr_error.SetErrorString("Can't get context object's " 832 "debuggee address"); 833 } else 834 object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error); 835 836 if (!object_ptr_error.Success()) { 837 exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Printf( 838 "warning: `%s' is not accessible (substituting 0)\n", 839 object_name.AsCString()); 840 object_ptr = 0; 841 } 842 843 if (m_in_objectivec_method) { 844 ConstString cmd_name("_cmd"); 845 846 cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error); 847 848 if (!object_ptr_error.Success()) { 849 diagnostic_manager.Printf( 850 eDiagnosticSeverityWarning, 851 "couldn't get cmd pointer (substituting NULL): %s", 852 object_ptr_error.AsCString()); 853 cmd_ptr = 0; 854 } 855 } 856 857 args.push_back(object_ptr); 858 859 if (m_in_objectivec_method) 860 args.push_back(cmd_ptr); 861 862 args.push_back(struct_address); 863 } else { 864 args.push_back(struct_address); 865 } 866 return true; 867 } 868 869 lldb::ExpressionVariableSP ClangUserExpression::GetResultAfterDematerialization( 870 ExecutionContextScope *exe_scope) { 871 return m_result_delegate.GetVariable(); 872 } 873 874 void ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap( 875 ExecutionContext &exe_ctx, 876 Materializer::PersistentVariableDelegate &delegate, 877 bool keep_result_in_memory, 878 ValueObject *ctx_obj) { 879 m_expr_decl_map_up.reset( 880 new ClangExpressionDeclMap(keep_result_in_memory, &delegate, exe_ctx, 881 ctx_obj)); 882 } 883 884 clang::ASTConsumer * 885 ClangUserExpression::ClangUserExpressionHelper::ASTTransformer( 886 clang::ASTConsumer *passthrough) { 887 m_result_synthesizer_up.reset( 888 new ASTResultSynthesizer(passthrough, m_top_level, m_target)); 889 890 return m_result_synthesizer_up.get(); 891 } 892 893 void ClangUserExpression::ClangUserExpressionHelper::CommitPersistentDecls() { 894 if (m_result_synthesizer_up) { 895 m_result_synthesizer_up->CommitPersistentDecls(); 896 } 897 } 898 899 ConstString ClangUserExpression::ResultDelegate::GetName() { 900 auto prefix = m_persistent_state->GetPersistentVariablePrefix(); 901 return m_persistent_state->GetNextPersistentVariableName(*m_target_sp, 902 prefix); 903 } 904 905 void ClangUserExpression::ResultDelegate::DidDematerialize( 906 lldb::ExpressionVariableSP &variable) { 907 m_variable = variable; 908 } 909 910 void ClangUserExpression::ResultDelegate::RegisterPersistentState( 911 PersistentExpressionState *persistent_state) { 912 m_persistent_state = persistent_state; 913 } 914 915 lldb::ExpressionVariableSP &ClangUserExpression::ResultDelegate::GetVariable() { 916 return m_variable; 917 } 918