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