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