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 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 448 449 // Don't do anything if this is not a C++ module configuration. 450 if (!SupportsCxxModuleImport(language)) 451 return LogConfigError("Language doesn't support C++ modules"); 452 453 Target *target = exe_ctx.GetTargetPtr(); 454 if (!target) 455 return LogConfigError("No target"); 456 457 if (!target->GetEnableImportStdModule()) 458 return LogConfigError("Importing std module not enabled in settings"); 459 460 StackFrame *frame = exe_ctx.GetFramePtr(); 461 if (!frame) 462 return LogConfigError("No frame"); 463 464 Block *block = frame->GetFrameBlock(); 465 if (!block) 466 return LogConfigError("No block"); 467 468 SymbolContext sc; 469 block->CalculateSymbolContext(&sc); 470 if (!sc.comp_unit) 471 return LogConfigError("Couldn't calculate symbol context"); 472 473 // Build a list of files we need to analyze to build the configuration. 474 FileSpecList files; 475 for (const FileSpec &f : sc.comp_unit->GetSupportFiles()) 476 files.AppendIfUnique(f); 477 // We also need to look at external modules in the case of -gmodules as they 478 // contain the support files for libc++ and the C library. 479 sc.comp_unit->ForEachExternalModule([&files](lldb::ModuleSP module) { 480 for (std::size_t i = 0; i < module->GetNumCompileUnits(); ++i) { 481 const FileSpecList &support_files = 482 module->GetCompileUnitAtIndex(i)->GetSupportFiles(); 483 for (const FileSpec &f : support_files) { 484 files.AppendIfUnique(f); 485 } 486 } 487 }); 488 489 LLDB_LOG(log, "[C++ module config] Found {0} support files to analyze", 490 files.GetSize()); 491 if (log && log->GetVerbose()) { 492 for (const FileSpec &f : files) 493 LLDB_LOGV(log, "[C++ module config] Analyzing support file: {0}", 494 f.GetPath()); 495 } 496 497 // Try to create a configuration from the files. If there is no valid 498 // configuration possible with the files, this just returns an invalid 499 // configuration. 500 return CppModuleConfiguration(files); 501 } 502 503 bool ClangUserExpression::PrepareForParsing( 504 DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, 505 bool for_completion) { 506 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 507 508 InstallContext(exe_ctx); 509 510 if (!SetupPersistentState(diagnostic_manager, exe_ctx)) 511 return false; 512 513 Status err; 514 ScanContext(exe_ctx, err); 515 516 if (!err.Success()) { 517 diagnostic_manager.PutString(eDiagnosticSeverityWarning, err.AsCString()); 518 } 519 520 //////////////////////////////////// 521 // Generate the expression 522 // 523 524 ApplyObjcCastHack(m_expr_text); 525 526 SetupDeclVendor(exe_ctx, m_target); 527 528 CppModuleConfiguration module_config = GetModuleConfig(m_language, exe_ctx); 529 llvm::ArrayRef<std::string> imported_modules = 530 module_config.GetImportedModules(); 531 m_imported_cpp_modules = !imported_modules.empty(); 532 m_include_directories = module_config.GetIncludeDirs(); 533 534 LLDB_LOG(log, "List of imported modules in expression: {0}", 535 llvm::make_range(imported_modules.begin(), imported_modules.end())); 536 LLDB_LOG(log, "List of include directories gathered for modules: {0}", 537 llvm::make_range(m_include_directories.begin(), 538 m_include_directories.end())); 539 540 UpdateLanguageForExpr(); 541 CreateSourceCode(diagnostic_manager, exe_ctx, imported_modules, 542 for_completion); 543 return true; 544 } 545 546 bool ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager, 547 ExecutionContext &exe_ctx, 548 lldb_private::ExecutionPolicy execution_policy, 549 bool keep_result_in_memory, 550 bool generate_debug_info) { 551 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 552 553 if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ false)) 554 return false; 555 556 LLDB_LOGF(log, "Parsing the following code:\n%s", m_transformed_text.c_str()); 557 558 //////////////////////////////////// 559 // Set up the target and compiler 560 // 561 562 Target *target = exe_ctx.GetTargetPtr(); 563 564 if (!target) { 565 diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target"); 566 return false; 567 } 568 569 ////////////////////////// 570 // Parse the expression 571 // 572 573 m_materializer_up.reset(new Materializer()); 574 575 ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory); 576 577 auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); }); 578 579 if (!DeclMap()->WillParse(exe_ctx, m_materializer_up.get())) { 580 diagnostic_manager.PutString( 581 eDiagnosticSeverityError, 582 "current process state is unsuitable for expression parsing"); 583 return false; 584 } 585 586 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) { 587 DeclMap()->SetLookupsEnabled(true); 588 } 589 590 Process *process = exe_ctx.GetProcessPtr(); 591 ExecutionContextScope *exe_scope = process; 592 593 if (!exe_scope) 594 exe_scope = exe_ctx.GetTargetPtr(); 595 596 // We use a shared pointer here so we can use the original parser - if it 597 // succeeds or the rewrite parser we might make if it fails. But the 598 // parser_sp will never be empty. 599 600 ClangExpressionParser parser(exe_scope, *this, generate_debug_info, 601 m_include_directories, m_filename); 602 603 unsigned num_errors = parser.Parse(diagnostic_manager); 604 605 // Check here for FixItHints. If there are any try to apply the fixits and 606 // set the fixed text in m_fixed_text before returning an error. 607 if (num_errors) { 608 if (diagnostic_manager.HasFixIts()) { 609 if (parser.RewriteExpression(diagnostic_manager)) { 610 size_t fixed_start; 611 size_t fixed_end; 612 const std::string &fixed_expression = 613 diagnostic_manager.GetFixedExpression(); 614 // Retrieve the original expression in case we don't have a top level 615 // expression (which has no surrounding source code). 616 if (m_source_code && 617 m_source_code->GetOriginalBodyBounds(fixed_expression, m_expr_lang, 618 fixed_start, fixed_end)) 619 m_fixed_text = 620 fixed_expression.substr(fixed_start, fixed_end - fixed_start); 621 } 622 } 623 return false; 624 } 625 626 ////////////////////////////////////////////////////////////////////////////// 627 // Prepare the output of the parser for execution, evaluating it statically 628 // if possible 629 // 630 631 { 632 Status jit_error = parser.PrepareForExecution( 633 m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx, 634 m_can_interpret, execution_policy); 635 636 if (!jit_error.Success()) { 637 const char *error_cstr = jit_error.AsCString(); 638 if (error_cstr && error_cstr[0]) 639 diagnostic_manager.PutString(eDiagnosticSeverityError, error_cstr); 640 else 641 diagnostic_manager.PutString(eDiagnosticSeverityError, 642 "expression can't be interpreted or run"); 643 return false; 644 } 645 } 646 647 if (exe_ctx.GetProcessPtr() && execution_policy == eExecutionPolicyTopLevel) { 648 Status static_init_error = 649 parser.RunStaticInitializers(m_execution_unit_sp, exe_ctx); 650 651 if (!static_init_error.Success()) { 652 const char *error_cstr = static_init_error.AsCString(); 653 if (error_cstr && error_cstr[0]) 654 diagnostic_manager.Printf(eDiagnosticSeverityError, 655 "couldn't run static initializers: %s\n", 656 error_cstr); 657 else 658 diagnostic_manager.PutString(eDiagnosticSeverityError, 659 "couldn't run static initializers\n"); 660 return false; 661 } 662 } 663 664 if (m_execution_unit_sp) { 665 bool register_execution_unit = false; 666 667 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) { 668 register_execution_unit = true; 669 } 670 671 // If there is more than one external function in the execution unit, it 672 // needs to keep living even if it's not top level, because the result 673 // could refer to that function. 674 675 if (m_execution_unit_sp->GetJittedFunctions().size() > 1) { 676 register_execution_unit = true; 677 } 678 679 if (register_execution_unit) 680 exe_ctx.GetTargetPtr() 681 ->GetPersistentExpressionStateForLanguage(m_language) 682 ->RegisterExecutionUnit(m_execution_unit_sp); 683 } 684 685 if (generate_debug_info) { 686 lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule()); 687 688 if (jit_module_sp) { 689 ConstString const_func_name(FunctionName()); 690 FileSpec jit_file; 691 jit_file.GetFilename() = const_func_name; 692 jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString()); 693 m_jit_module_wp = jit_module_sp; 694 target->GetImages().Append(jit_module_sp); 695 } 696 } 697 698 if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS) 699 m_jit_process_wp = lldb::ProcessWP(process->shared_from_this()); 700 return true; 701 } 702 703 /// Converts an absolute position inside a given code string into 704 /// a column/line pair. 705 /// 706 /// \param[in] abs_pos 707 /// A absolute position in the code string that we want to convert 708 /// to a column/line pair. 709 /// 710 /// \param[in] code 711 /// A multi-line string usually representing source code. 712 /// 713 /// \param[out] line 714 /// The line in the code that contains the given absolute position. 715 /// The first line in the string is indexed as 1. 716 /// 717 /// \param[out] column 718 /// The column in the line that contains the absolute position. 719 /// The first character in a line is indexed as 0. 720 static void AbsPosToLineColumnPos(size_t abs_pos, llvm::StringRef code, 721 unsigned &line, unsigned &column) { 722 // Reset to code position to beginning of the file. 723 line = 0; 724 column = 0; 725 726 assert(abs_pos <= code.size() && "Absolute position outside code string?"); 727 728 // We have to walk up to the position and count lines/columns. 729 for (std::size_t i = 0; i < abs_pos; ++i) { 730 // If we hit a line break, we go back to column 0 and enter a new line. 731 // We only handle \n because that's what we internally use to make new 732 // lines for our temporary code strings. 733 if (code[i] == '\n') { 734 ++line; 735 column = 0; 736 continue; 737 } 738 ++column; 739 } 740 } 741 742 bool ClangUserExpression::Complete(ExecutionContext &exe_ctx, 743 CompletionRequest &request, 744 unsigned complete_pos) { 745 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 746 747 // We don't want any visible feedback when completing an expression. Mostly 748 // because the results we get from an incomplete invocation are probably not 749 // correct. 750 DiagnosticManager diagnostic_manager; 751 752 if (!PrepareForParsing(diagnostic_manager, exe_ctx, /*for_completion*/ true)) 753 return false; 754 755 LLDB_LOGF(log, "Parsing the following code:\n%s", m_transformed_text.c_str()); 756 757 ////////////////////////// 758 // Parse the expression 759 // 760 761 m_materializer_up.reset(new Materializer()); 762 763 ResetDeclMap(exe_ctx, m_result_delegate, /*keep result in memory*/ true); 764 765 auto on_exit = llvm::make_scope_exit([this]() { ResetDeclMap(); }); 766 767 if (!DeclMap()->WillParse(exe_ctx, m_materializer_up.get())) { 768 diagnostic_manager.PutString( 769 eDiagnosticSeverityError, 770 "current process state is unsuitable for expression parsing"); 771 772 return false; 773 } 774 775 if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) { 776 DeclMap()->SetLookupsEnabled(true); 777 } 778 779 Process *process = exe_ctx.GetProcessPtr(); 780 ExecutionContextScope *exe_scope = process; 781 782 if (!exe_scope) 783 exe_scope = exe_ctx.GetTargetPtr(); 784 785 ClangExpressionParser parser(exe_scope, *this, false); 786 787 // We have to find the source code location where the user text is inside 788 // the transformed expression code. When creating the transformed text, we 789 // already stored the absolute position in the m_transformed_text string. The 790 // only thing left to do is to transform it into the line:column format that 791 // Clang expects. 792 793 // The line and column of the user expression inside the transformed source 794 // code. 795 unsigned user_expr_line, user_expr_column; 796 if (m_user_expression_start_pos.hasValue()) 797 AbsPosToLineColumnPos(*m_user_expression_start_pos, m_transformed_text, 798 user_expr_line, user_expr_column); 799 else 800 return false; 801 802 // The actual column where we have to complete is the start column of the 803 // user expression + the offset inside the user code that we were given. 804 const unsigned completion_column = user_expr_column + complete_pos; 805 parser.Complete(request, user_expr_line, completion_column, complete_pos); 806 807 return true; 808 } 809 810 bool ClangUserExpression::AddArguments(ExecutionContext &exe_ctx, 811 std::vector<lldb::addr_t> &args, 812 lldb::addr_t struct_address, 813 DiagnosticManager &diagnostic_manager) { 814 lldb::addr_t object_ptr = LLDB_INVALID_ADDRESS; 815 lldb::addr_t cmd_ptr = LLDB_INVALID_ADDRESS; 816 817 if (m_needs_object_ptr) { 818 lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP(); 819 if (!frame_sp) 820 return true; 821 822 ConstString object_name; 823 824 if (m_in_cplusplus_method) { 825 object_name.SetCString("this"); 826 } else if (m_in_objectivec_method) { 827 object_name.SetCString("self"); 828 } else { 829 diagnostic_manager.PutString( 830 eDiagnosticSeverityError, 831 "need object pointer but don't know the language"); 832 return false; 833 } 834 835 Status object_ptr_error; 836 837 if (m_ctx_obj) { 838 AddressType address_type; 839 object_ptr = m_ctx_obj->GetAddressOf(false, &address_type); 840 if (object_ptr == LLDB_INVALID_ADDRESS || 841 address_type != eAddressTypeLoad) 842 object_ptr_error.SetErrorString("Can't get context object's " 843 "debuggee address"); 844 } else 845 object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error); 846 847 if (!object_ptr_error.Success()) { 848 exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Printf( 849 "warning: `%s' is not accessible (substituting 0)\n", 850 object_name.AsCString()); 851 object_ptr = 0; 852 } 853 854 if (m_in_objectivec_method) { 855 ConstString cmd_name("_cmd"); 856 857 cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error); 858 859 if (!object_ptr_error.Success()) { 860 diagnostic_manager.Printf( 861 eDiagnosticSeverityWarning, 862 "couldn't get cmd pointer (substituting NULL): %s", 863 object_ptr_error.AsCString()); 864 cmd_ptr = 0; 865 } 866 } 867 868 args.push_back(object_ptr); 869 870 if (m_in_objectivec_method) 871 args.push_back(cmd_ptr); 872 873 args.push_back(struct_address); 874 } else { 875 args.push_back(struct_address); 876 } 877 return true; 878 } 879 880 lldb::ExpressionVariableSP ClangUserExpression::GetResultAfterDematerialization( 881 ExecutionContextScope *exe_scope) { 882 return m_result_delegate.GetVariable(); 883 } 884 885 void ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap( 886 ExecutionContext &exe_ctx, 887 Materializer::PersistentVariableDelegate &delegate, 888 bool keep_result_in_memory, 889 ValueObject *ctx_obj) { 890 m_expr_decl_map_up.reset( 891 new ClangExpressionDeclMap(keep_result_in_memory, &delegate, exe_ctx, 892 ctx_obj)); 893 } 894 895 clang::ASTConsumer * 896 ClangUserExpression::ClangUserExpressionHelper::ASTTransformer( 897 clang::ASTConsumer *passthrough) { 898 m_result_synthesizer_up.reset( 899 new ASTResultSynthesizer(passthrough, m_top_level, m_target)); 900 901 return m_result_synthesizer_up.get(); 902 } 903 904 void ClangUserExpression::ClangUserExpressionHelper::CommitPersistentDecls() { 905 if (m_result_synthesizer_up) { 906 m_result_synthesizer_up->CommitPersistentDecls(); 907 } 908 } 909 910 ConstString ClangUserExpression::ResultDelegate::GetName() { 911 auto prefix = m_persistent_state->GetPersistentVariablePrefix(); 912 return m_persistent_state->GetNextPersistentVariableName(*m_target_sp, 913 prefix); 914 } 915 916 void ClangUserExpression::ResultDelegate::DidDematerialize( 917 lldb::ExpressionVariableSP &variable) { 918 m_variable = variable; 919 } 920 921 void ClangUserExpression::ResultDelegate::RegisterPersistentState( 922 PersistentExpressionState *persistent_state) { 923 m_persistent_state = persistent_state; 924 } 925 926 lldb::ExpressionVariableSP &ClangUserExpression::ResultDelegate::GetVariable() { 927 return m_variable; 928 } 929