1 //===-- ClangExpressionParser.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 <cctype> 10 #include "clang/AST/ASTContext.h" 11 #include "clang/AST/ASTDiagnostic.h" 12 #include "clang/AST/ExternalASTSource.h" 13 #include "clang/AST/PrettyPrinter.h" 14 #include "clang/Basic/DiagnosticIDs.h" 15 #include "clang/Basic/FileManager.h" 16 #include "clang/Basic/SourceLocation.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/Basic/Version.h" 19 #include "clang/CodeGen/CodeGenAction.h" 20 #include "clang/CodeGen/ModuleBuilder.h" 21 #include "clang/Edit/Commit.h" 22 #include "clang/Edit/EditedSource.h" 23 #include "clang/Edit/EditsReceiver.h" 24 #include "clang/Frontend/CompilerInstance.h" 25 #include "clang/Frontend/CompilerInvocation.h" 26 #include "clang/Frontend/FrontendActions.h" 27 #include "clang/Frontend/FrontendDiagnostic.h" 28 #include "clang/Frontend/FrontendPluginRegistry.h" 29 #include "clang/Frontend/TextDiagnosticBuffer.h" 30 #include "clang/Frontend/TextDiagnosticPrinter.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Parse/ParseAST.h" 33 #include "clang/Rewrite/Core/Rewriter.h" 34 #include "clang/Rewrite/Frontend/FrontendActions.h" 35 #include "clang/Sema/CodeCompleteConsumer.h" 36 #include "clang/Sema/Sema.h" 37 #include "clang/Sema/SemaConsumer.h" 38 39 #include "llvm/ADT/StringRef.h" 40 #include "llvm/ExecutionEngine/ExecutionEngine.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/FileSystem.h" 43 #include "llvm/Support/TargetSelect.h" 44 45 #pragma clang diagnostic push 46 #pragma clang diagnostic ignored "-Wglobal-constructors" 47 #include "llvm/ExecutionEngine/MCJIT.h" 48 #pragma clang diagnostic pop 49 50 #include "llvm/IR/LLVMContext.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/Support/DynamicLibrary.h" 53 #include "llvm/Support/ErrorHandling.h" 54 #include "llvm/Support/Host.h" 55 #include "llvm/Support/MemoryBuffer.h" 56 #include "llvm/Support/Signals.h" 57 58 #include "ClangDiagnostic.h" 59 #include "ClangExpressionParser.h" 60 61 #include "ClangASTSource.h" 62 #include "ClangExpressionDeclMap.h" 63 #include "ClangExpressionHelper.h" 64 #include "ClangModulesDeclVendor.h" 65 #include "ClangPersistentVariables.h" 66 #include "IRForTarget.h" 67 68 #include "lldb/Core/Debugger.h" 69 #include "lldb/Core/Disassembler.h" 70 #include "lldb/Core/Module.h" 71 #include "lldb/Core/StreamFile.h" 72 #include "lldb/Expression/IRDynamicChecks.h" 73 #include "lldb/Expression/IRExecutionUnit.h" 74 #include "lldb/Expression/IRInterpreter.h" 75 #include "lldb/Host/File.h" 76 #include "lldb/Host/HostInfo.h" 77 #include "lldb/Symbol/ClangASTContext.h" 78 #include "lldb/Symbol/SymbolVendor.h" 79 #include "lldb/Target/ExecutionContext.h" 80 #include "lldb/Target/Language.h" 81 #include "lldb/Target/ObjCLanguageRuntime.h" 82 #include "lldb/Target/Process.h" 83 #include "lldb/Target/Target.h" 84 #include "lldb/Target/ThreadPlanCallFunction.h" 85 #include "lldb/Utility/DataBufferHeap.h" 86 #include "lldb/Utility/LLDBAssert.h" 87 #include "lldb/Utility/Log.h" 88 #include "lldb/Utility/Stream.h" 89 #include "lldb/Utility/StreamString.h" 90 #include "lldb/Utility/StringList.h" 91 92 using namespace clang; 93 using namespace llvm; 94 using namespace lldb_private; 95 96 //===----------------------------------------------------------------------===// 97 // Utility Methods for Clang 98 //===----------------------------------------------------------------------===// 99 100 class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks { 101 ClangModulesDeclVendor &m_decl_vendor; 102 ClangPersistentVariables &m_persistent_vars; 103 StreamString m_error_stream; 104 bool m_has_errors = false; 105 106 public: 107 LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor, 108 ClangPersistentVariables &persistent_vars) 109 : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars) {} 110 111 void moduleImport(SourceLocation import_location, clang::ModuleIdPath path, 112 const clang::Module * /*null*/) override { 113 std::vector<ConstString> string_path; 114 115 for (const std::pair<IdentifierInfo *, SourceLocation> &component : path) { 116 string_path.push_back(ConstString(component.first->getName())); 117 } 118 119 StreamString error_stream; 120 121 ClangModulesDeclVendor::ModuleVector exported_modules; 122 123 if (!m_decl_vendor.AddModule(string_path, &exported_modules, 124 m_error_stream)) { 125 m_has_errors = true; 126 } 127 128 for (ClangModulesDeclVendor::ModuleID module : exported_modules) { 129 m_persistent_vars.AddHandLoadedClangModule(module); 130 } 131 } 132 133 bool hasErrors() { return m_has_errors; } 134 135 llvm::StringRef getErrorString() { return m_error_stream.GetString(); } 136 }; 137 138 class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer { 139 public: 140 ClangDiagnosticManagerAdapter() 141 : m_passthrough(new clang::TextDiagnosticBuffer) {} 142 143 ClangDiagnosticManagerAdapter( 144 const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough) 145 : m_passthrough(passthrough) {} 146 147 void ResetManager(DiagnosticManager *manager = nullptr) { 148 m_manager = manager; 149 } 150 151 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, 152 const clang::Diagnostic &Info) { 153 if (m_manager) { 154 llvm::SmallVector<char, 32> diag_str; 155 Info.FormatDiagnostic(diag_str); 156 diag_str.push_back('\0'); 157 const char *data = diag_str.data(); 158 159 lldb_private::DiagnosticSeverity severity; 160 bool make_new_diagnostic = true; 161 162 switch (DiagLevel) { 163 case DiagnosticsEngine::Level::Fatal: 164 case DiagnosticsEngine::Level::Error: 165 severity = eDiagnosticSeverityError; 166 break; 167 case DiagnosticsEngine::Level::Warning: 168 severity = eDiagnosticSeverityWarning; 169 break; 170 case DiagnosticsEngine::Level::Remark: 171 case DiagnosticsEngine::Level::Ignored: 172 severity = eDiagnosticSeverityRemark; 173 break; 174 case DiagnosticsEngine::Level::Note: 175 m_manager->AppendMessageToDiagnostic(data); 176 make_new_diagnostic = false; 177 } 178 if (make_new_diagnostic) { 179 ClangDiagnostic *new_diagnostic = 180 new ClangDiagnostic(data, severity, Info.getID()); 181 m_manager->AddDiagnostic(new_diagnostic); 182 183 // Don't store away warning fixits, since the compiler doesn't have 184 // enough context in an expression for the warning to be useful. 185 // FIXME: Should we try to filter out FixIts that apply to our generated 186 // code, and not the user's expression? 187 if (severity == eDiagnosticSeverityError) { 188 size_t num_fixit_hints = Info.getNumFixItHints(); 189 for (size_t i = 0; i < num_fixit_hints; i++) { 190 const clang::FixItHint &fixit = Info.getFixItHint(i); 191 if (!fixit.isNull()) 192 new_diagnostic->AddFixitHint(fixit); 193 } 194 } 195 } 196 } 197 198 m_passthrough->HandleDiagnostic(DiagLevel, Info); 199 } 200 201 void FlushDiagnostics(DiagnosticsEngine &Diags) { 202 m_passthrough->FlushDiagnostics(Diags); 203 } 204 205 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const { 206 return new ClangDiagnosticManagerAdapter(m_passthrough); 207 } 208 209 clang::TextDiagnosticBuffer *GetPassthrough() { return m_passthrough.get(); } 210 211 private: 212 DiagnosticManager *m_manager = nullptr; 213 std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough; 214 }; 215 216 //===----------------------------------------------------------------------===// 217 // Implementation of ClangExpressionParser 218 //===----------------------------------------------------------------------===// 219 220 ClangExpressionParser::ClangExpressionParser(ExecutionContextScope *exe_scope, 221 Expression &expr, 222 bool generate_debug_info) 223 : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(), 224 m_pp_callbacks(nullptr) { 225 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 226 227 // We can't compile expressions without a target. So if the exe_scope is 228 // null or doesn't have a target, then we just need to get out of here. I'll 229 // lldb_assert and not make any of the compiler objects since 230 // I can't return errors directly from the constructor. Further calls will 231 // check if the compiler was made and 232 // bag out if it wasn't. 233 234 if (!exe_scope) { 235 lldb_assert(exe_scope, "Can't make an expression parser with a null scope.", 236 __FUNCTION__, __FILE__, __LINE__); 237 return; 238 } 239 240 lldb::TargetSP target_sp; 241 target_sp = exe_scope->CalculateTarget(); 242 if (!target_sp) { 243 lldb_assert(target_sp.get(), 244 "Can't make an expression parser with a null target.", 245 __FUNCTION__, __FILE__, __LINE__); 246 return; 247 } 248 249 // 1. Create a new compiler instance. 250 m_compiler.reset(new CompilerInstance()); 251 lldb::LanguageType frame_lang = 252 expr.Language(); // defaults to lldb::eLanguageTypeUnknown 253 bool overridden_target_opts = false; 254 lldb_private::LanguageRuntime *lang_rt = nullptr; 255 256 std::string abi; 257 ArchSpec target_arch; 258 target_arch = target_sp->GetArchitecture(); 259 260 const auto target_machine = target_arch.GetMachine(); 261 262 // If the expression is being evaluated in the context of an existing stack 263 // frame, we introspect to see if the language runtime is available. 264 265 lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame(); 266 lldb::ProcessSP process_sp = exe_scope->CalculateProcess(); 267 268 // Make sure the user hasn't provided a preferred execution language with 269 // `expression --language X -- ...` 270 if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown) 271 frame_lang = frame_sp->GetLanguage(); 272 273 if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) { 274 lang_rt = process_sp->GetLanguageRuntime(frame_lang); 275 if (log) 276 log->Printf("Frame has language of type %s", 277 Language::GetNameForLanguageType(frame_lang)); 278 } 279 280 // 2. Configure the compiler with a set of default options that are 281 // appropriate for most situations. 282 if (target_arch.IsValid()) { 283 std::string triple = target_arch.GetTriple().str(); 284 m_compiler->getTargetOpts().Triple = triple; 285 if (log) 286 log->Printf("Using %s as the target triple", 287 m_compiler->getTargetOpts().Triple.c_str()); 288 } else { 289 // If we get here we don't have a valid target and just have to guess. 290 // Sometimes this will be ok to just use the host target triple (when we 291 // evaluate say "2+3", but other expressions like breakpoint conditions and 292 // other things that _are_ target specific really shouldn't just be using 293 // the host triple. In such a case the language runtime should expose an 294 // overridden options set (3), below. 295 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple(); 296 if (log) 297 log->Printf("Using default target triple of %s", 298 m_compiler->getTargetOpts().Triple.c_str()); 299 } 300 // Now add some special fixes for known architectures: Any arm32 iOS 301 // environment, but not on arm64 302 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos && 303 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos && 304 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) { 305 m_compiler->getTargetOpts().ABI = "apcs-gnu"; 306 } 307 // Supported subsets of x86 308 if (target_machine == llvm::Triple::x86 || 309 target_machine == llvm::Triple::x86_64) { 310 m_compiler->getTargetOpts().Features.push_back("+sse"); 311 m_compiler->getTargetOpts().Features.push_back("+sse2"); 312 } 313 314 // Set the target CPU to generate code for. This will be empty for any CPU 315 // that doesn't really need to make a special 316 // CPU string. 317 m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU(); 318 319 // Set the target ABI 320 abi = GetClangTargetABI(target_arch); 321 if (!abi.empty()) 322 m_compiler->getTargetOpts().ABI = abi; 323 324 // 3. Now allow the runtime to provide custom configuration options for the 325 // target. In this case, a specialized language runtime is available and we 326 // can query it for extra options. For 99% of use cases, this will not be 327 // needed and should be provided when basic platform detection is not enough. 328 if (lang_rt) 329 overridden_target_opts = 330 lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts()); 331 332 if (overridden_target_opts) 333 if (log && log->GetVerbose()) { 334 LLDB_LOGV( 335 log, "Using overridden target options for the expression evaluation"); 336 337 auto opts = m_compiler->getTargetOpts(); 338 LLDB_LOGV(log, "Triple: '{0}'", opts.Triple); 339 LLDB_LOGV(log, "CPU: '{0}'", opts.CPU); 340 LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath); 341 LLDB_LOGV(log, "ABI: '{0}'", opts.ABI); 342 LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion); 343 StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten"); 344 StringList::LogDump(log, opts.Features, "Features"); 345 } 346 347 // 4. Create and install the target on the compiler. 348 m_compiler->createDiagnostics(); 349 auto target_info = TargetInfo::CreateTargetInfo( 350 m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts); 351 if (log) { 352 log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign()); 353 log->Printf("Target datalayout string: '%s'", 354 target_info->getDataLayout().getStringRepresentation().c_str()); 355 log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str()); 356 log->Printf("Target vector alignment: %d", 357 target_info->getMaxVectorAlign()); 358 } 359 m_compiler->setTarget(target_info); 360 361 assert(m_compiler->hasTarget()); 362 363 // 5. Set language options. 364 lldb::LanguageType language = expr.Language(); 365 366 switch (language) { 367 case lldb::eLanguageTypeC: 368 case lldb::eLanguageTypeC89: 369 case lldb::eLanguageTypeC99: 370 case lldb::eLanguageTypeC11: 371 // FIXME: the following language option is a temporary workaround, 372 // to "ask for C, get C++." 373 // For now, the expression parser must use C++ anytime the language is a C 374 // family language, because the expression parser uses features of C++ to 375 // capture values. 376 m_compiler->getLangOpts().CPlusPlus = true; 377 break; 378 case lldb::eLanguageTypeObjC: 379 m_compiler->getLangOpts().ObjC = true; 380 // FIXME: the following language option is a temporary workaround, 381 // to "ask for ObjC, get ObjC++" (see comment above). 382 m_compiler->getLangOpts().CPlusPlus = true; 383 384 // Clang now sets as default C++14 as the default standard (with 385 // GNU extensions), so we do the same here to avoid mismatches that 386 // cause compiler error when evaluating expressions (e.g. nullptr not found 387 // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see 388 // two lines below) so we decide to be consistent with that, but this could 389 // be re-evaluated in the future. 390 m_compiler->getLangOpts().CPlusPlus11 = true; 391 break; 392 case lldb::eLanguageTypeC_plus_plus: 393 case lldb::eLanguageTypeC_plus_plus_11: 394 case lldb::eLanguageTypeC_plus_plus_14: 395 m_compiler->getLangOpts().CPlusPlus11 = true; 396 m_compiler->getHeaderSearchOpts().UseLibcxx = true; 397 LLVM_FALLTHROUGH; 398 case lldb::eLanguageTypeC_plus_plus_03: 399 m_compiler->getLangOpts().CPlusPlus = true; 400 if (process_sp) 401 m_compiler->getLangOpts().ObjC = 402 process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr; 403 break; 404 case lldb::eLanguageTypeObjC_plus_plus: 405 case lldb::eLanguageTypeUnknown: 406 default: 407 m_compiler->getLangOpts().ObjC = true; 408 m_compiler->getLangOpts().CPlusPlus = true; 409 m_compiler->getLangOpts().CPlusPlus11 = true; 410 m_compiler->getHeaderSearchOpts().UseLibcxx = true; 411 break; 412 } 413 414 m_compiler->getLangOpts().Bool = true; 415 m_compiler->getLangOpts().WChar = true; 416 m_compiler->getLangOpts().Blocks = true; 417 m_compiler->getLangOpts().DebuggerSupport = 418 true; // Features specifically for debugger clients 419 if (expr.DesiredResultType() == Expression::eResultTypeId) 420 m_compiler->getLangOpts().DebuggerCastResultToId = true; 421 422 m_compiler->getLangOpts().CharIsSigned = 423 ArchSpec(m_compiler->getTargetOpts().Triple.c_str()) 424 .CharIsSignedByDefault(); 425 426 // Spell checking is a nice feature, but it ends up completing a lot of types 427 // that we didn't strictly speaking need to complete. As a result, we spend a 428 // long time parsing and importing debug information. 429 m_compiler->getLangOpts().SpellChecking = false; 430 431 if (process_sp && m_compiler->getLangOpts().ObjC) { 432 if (process_sp->GetObjCLanguageRuntime()) { 433 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() == 434 ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2) 435 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX, 436 VersionTuple(10, 7)); 437 else 438 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX, 439 VersionTuple(10, 7)); 440 441 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing()) 442 m_compiler->getLangOpts().DebuggerObjCLiteral = true; 443 } 444 } 445 446 m_compiler->getLangOpts().ThreadsafeStatics = false; 447 m_compiler->getLangOpts().AccessControl = 448 false; // Debuggers get universal access 449 m_compiler->getLangOpts().DollarIdents = 450 true; // $ indicates a persistent variable name 451 // We enable all builtin functions beside the builtins from libc/libm (e.g. 452 // 'fopen'). Those libc functions are already correctly handled by LLDB, and 453 // additionally enabling them as expandable builtins is breaking Clang. 454 m_compiler->getLangOpts().NoBuiltin = true; 455 456 // Set CodeGen options 457 m_compiler->getCodeGenOpts().EmitDeclMetadata = true; 458 m_compiler->getCodeGenOpts().InstrumentFunctions = false; 459 m_compiler->getCodeGenOpts().DisableFPElim = true; 460 m_compiler->getCodeGenOpts().OmitLeafFramePointer = false; 461 if (generate_debug_info) 462 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo); 463 else 464 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo); 465 466 // Disable some warnings. 467 m_compiler->getDiagnostics().setSeverityForGroup( 468 clang::diag::Flavor::WarningOrError, "unused-value", 469 clang::diag::Severity::Ignored, SourceLocation()); 470 m_compiler->getDiagnostics().setSeverityForGroup( 471 clang::diag::Flavor::WarningOrError, "odr", 472 clang::diag::Severity::Ignored, SourceLocation()); 473 474 // Inform the target of the language options 475 // 476 // FIXME: We shouldn't need to do this, the target should be immutable once 477 // created. This complexity should be lifted elsewhere. 478 m_compiler->getTarget().adjust(m_compiler->getLangOpts()); 479 480 // 6. Set up the diagnostic buffer for reporting errors 481 482 m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter); 483 484 // 7. Set up the source management objects inside the compiler 485 486 clang::FileSystemOptions file_system_options; 487 m_file_manager.reset(new clang::FileManager(file_system_options)); 488 489 if (!m_compiler->hasSourceManager()) 490 m_compiler->createSourceManager(*m_file_manager.get()); 491 492 m_compiler->createFileManager(); 493 m_compiler->createPreprocessor(TU_Complete); 494 495 if (ClangModulesDeclVendor *decl_vendor = 496 target_sp->GetClangModulesDeclVendor()) { 497 ClangPersistentVariables *clang_persistent_vars = 498 llvm::cast<ClangPersistentVariables>( 499 target_sp->GetPersistentExpressionStateForLanguage( 500 lldb::eLanguageTypeC)); 501 std::unique_ptr<PPCallbacks> pp_callbacks( 502 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars)); 503 m_pp_callbacks = 504 static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get()); 505 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks)); 506 } 507 508 // 8. Most of this we get from the CompilerInstance, but we also want to give 509 // the context an ExternalASTSource. 510 511 auto &PP = m_compiler->getPreprocessor(); 512 auto &builtin_context = PP.getBuiltinInfo(); 513 builtin_context.initializeBuiltins(PP.getIdentifierTable(), 514 m_compiler->getLangOpts()); 515 516 m_compiler->createASTContext(); 517 clang::ASTContext &ast_context = m_compiler->getASTContext(); 518 519 ClangExpressionHelper *type_system_helper = 520 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); 521 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap(); 522 523 if (decl_map) { 524 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source( 525 decl_map->CreateProxy()); 526 decl_map->InstallASTContext(ast_context, m_compiler->getFileManager()); 527 ast_context.setExternalSource(ast_source); 528 } 529 530 m_ast_context.reset( 531 new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str())); 532 m_ast_context->setASTContext(&ast_context); 533 534 std::string module_name("$__lldb_module"); 535 536 m_llvm_context.reset(new LLVMContext()); 537 m_code_generator.reset(CreateLLVMCodeGen( 538 m_compiler->getDiagnostics(), module_name, 539 m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(), 540 m_compiler->getCodeGenOpts(), *m_llvm_context)); 541 } 542 543 ClangExpressionParser::~ClangExpressionParser() {} 544 545 namespace { 546 547 //---------------------------------------------------------------------- 548 /// @class CodeComplete 549 /// 550 /// A code completion consumer for the clang Sema that is responsible for 551 /// creating the completion suggestions when a user requests completion 552 /// of an incomplete `expr` invocation. 553 //---------------------------------------------------------------------- 554 class CodeComplete : public CodeCompleteConsumer { 555 CodeCompletionTUInfo m_info; 556 557 std::string m_expr; 558 unsigned m_position = 0; 559 CompletionRequest &m_request; 560 /// The printing policy we use when printing declarations for our completion 561 /// descriptions. 562 clang::PrintingPolicy m_desc_policy; 563 564 /// Returns true if the given character can be used in an identifier. 565 /// This also returns true for numbers because for completion we usually 566 /// just iterate backwards over iterators. 567 /// 568 /// Note: lldb uses '$' in its internal identifiers, so we also allow this. 569 static bool IsIdChar(char c) { 570 return c == '_' || std::isalnum(c) || c == '$'; 571 } 572 573 /// Returns true if the given character is used to separate arguments 574 /// in the command line of lldb. 575 static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; } 576 577 /// Drops all tokens in front of the expression that are unrelated for 578 /// the completion of the cmd line. 'unrelated' means here that the token 579 /// is not interested for the lldb completion API result. 580 StringRef dropUnrelatedFrontTokens(StringRef cmd) { 581 if (cmd.empty()) 582 return cmd; 583 584 // If we are at the start of a word, then all tokens are unrelated to 585 // the current completion logic. 586 if (IsTokenSeparator(cmd.back())) 587 return StringRef(); 588 589 // Remove all previous tokens from the string as they are unrelated 590 // to completing the current token. 591 StringRef to_remove = cmd; 592 while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) { 593 to_remove = to_remove.drop_back(); 594 } 595 cmd = cmd.drop_front(to_remove.size()); 596 597 return cmd; 598 } 599 600 /// Removes the last identifier token from the given cmd line. 601 StringRef removeLastToken(StringRef cmd) { 602 while (!cmd.empty() && IsIdChar(cmd.back())) { 603 cmd = cmd.drop_back(); 604 } 605 return cmd; 606 } 607 608 /// Attemps to merge the given completion from the given position into the 609 /// existing command. Returns the completion string that can be returned to 610 /// the lldb completion API. 611 std::string mergeCompletion(StringRef existing, unsigned pos, 612 StringRef completion) { 613 StringRef existing_command = existing.substr(0, pos); 614 // We rewrite the last token with the completion, so let's drop that 615 // token from the command. 616 existing_command = removeLastToken(existing_command); 617 // We also should remove all previous tokens from the command as they 618 // would otherwise be added to the completion that already has the 619 // completion. 620 existing_command = dropUnrelatedFrontTokens(existing_command); 621 return existing_command.str() + completion.str(); 622 } 623 624 public: 625 /// Constructs a CodeComplete consumer that can be attached to a Sema. 626 /// @param[out] matches 627 /// The list of matches that the lldb completion API expects as a result. 628 /// This may already contain matches, so it's only allowed to append 629 /// to this variable. 630 /// @param[out] expr 631 /// The whole expression string that we are currently parsing. This 632 /// string needs to be equal to the input the user typed, and NOT the 633 /// final code that Clang is parsing. 634 /// @param[out] position 635 /// The character position of the user cursor in the `expr` parameter. 636 /// 637 CodeComplete(CompletionRequest &request, clang::LangOptions ops, 638 std::string expr, unsigned position) 639 : CodeCompleteConsumer(CodeCompleteOptions(), false), 640 m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr), 641 m_position(position), m_request(request), m_desc_policy(ops) { 642 643 // Ensure that the printing policy is producing a description that is as 644 // short as possible. 645 m_desc_policy.SuppressScope = true; 646 m_desc_policy.SuppressTagKeyword = true; 647 m_desc_policy.FullyQualifiedName = false; 648 m_desc_policy.TerseOutput = true; 649 m_desc_policy.IncludeNewlines = false; 650 m_desc_policy.UseVoidForZeroParams = false; 651 m_desc_policy.Bool = true; 652 } 653 654 /// Deregisters and destroys this code-completion consumer. 655 virtual ~CodeComplete() {} 656 657 /// \name Code-completion filtering 658 /// Check if the result should be filtered out. 659 bool isResultFilteredOut(StringRef Filter, 660 CodeCompletionResult Result) override { 661 // This code is mostly copied from CodeCompleteConsumer. 662 switch (Result.Kind) { 663 case CodeCompletionResult::RK_Declaration: 664 return !( 665 Result.Declaration->getIdentifier() && 666 Result.Declaration->getIdentifier()->getName().startswith(Filter)); 667 case CodeCompletionResult::RK_Keyword: 668 return !StringRef(Result.Keyword).startswith(Filter); 669 case CodeCompletionResult::RK_Macro: 670 return !Result.Macro->getName().startswith(Filter); 671 case CodeCompletionResult::RK_Pattern: 672 return !StringRef(Result.Pattern->getAsString()).startswith(Filter); 673 } 674 // If we trigger this assert or the above switch yields a warning, then 675 // CodeCompletionResult has been enhanced with more kinds of completion 676 // results. Expand the switch above in this case. 677 assert(false && "Unknown completion result type?"); 678 // If we reach this, then we should just ignore whatever kind of unknown 679 // result we got back. We probably can't turn it into any kind of useful 680 // completion suggestion with the existing code. 681 return true; 682 } 683 684 /// \name Code-completion callbacks 685 /// Process the finalized code-completion results. 686 void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context, 687 CodeCompletionResult *Results, 688 unsigned NumResults) override { 689 690 // The Sema put the incomplete token we try to complete in here during 691 // lexing, so we need to retrieve it here to know what we are completing. 692 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter(); 693 694 // Iterate over all the results. Filter out results we don't want and 695 // process the rest. 696 for (unsigned I = 0; I != NumResults; ++I) { 697 // Filter the results with the information from the Sema. 698 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I])) 699 continue; 700 701 CodeCompletionResult &R = Results[I]; 702 std::string ToInsert; 703 std::string Description; 704 // Handle the different completion kinds that come from the Sema. 705 switch (R.Kind) { 706 case CodeCompletionResult::RK_Declaration: { 707 const NamedDecl *D = R.Declaration; 708 ToInsert = R.Declaration->getNameAsString(); 709 // If we have a function decl that has no arguments we want to 710 // complete the empty parantheses for the user. If the function has 711 // arguments, we at least complete the opening bracket. 712 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) { 713 if (F->getNumParams() == 0) 714 ToInsert += "()"; 715 else 716 ToInsert += "("; 717 raw_string_ostream OS(Description); 718 F->print(OS, m_desc_policy, false); 719 OS.flush(); 720 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) { 721 Description = V->getType().getAsString(m_desc_policy); 722 } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) { 723 Description = F->getType().getAsString(m_desc_policy); 724 } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) { 725 // If we try to complete a namespace, then we can directly append 726 // the '::'. 727 if (!N->isAnonymousNamespace()) 728 ToInsert += "::"; 729 } 730 break; 731 } 732 case CodeCompletionResult::RK_Keyword: 733 ToInsert = R.Keyword; 734 break; 735 case CodeCompletionResult::RK_Macro: 736 ToInsert = R.Macro->getName().str(); 737 break; 738 case CodeCompletionResult::RK_Pattern: 739 ToInsert = R.Pattern->getTypedText(); 740 break; 741 } 742 // At this point all information is in the ToInsert string. 743 744 // We also filter some internal lldb identifiers here. The user 745 // shouldn't see these. 746 if (StringRef(ToInsert).startswith("$__lldb_")) 747 continue; 748 if (!ToInsert.empty()) { 749 // Merge the suggested Token into the existing command line to comply 750 // with the kind of result the lldb API expects. 751 std::string CompletionSuggestion = 752 mergeCompletion(m_expr, m_position, ToInsert); 753 m_request.AddCompletion(CompletionSuggestion, Description); 754 } 755 } 756 } 757 758 /// \param S the semantic-analyzer object for which code-completion is being 759 /// done. 760 /// 761 /// \param CurrentArg the index of the current argument. 762 /// 763 /// \param Candidates an array of overload candidates. 764 /// 765 /// \param NumCandidates the number of overload candidates 766 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, 767 OverloadCandidate *Candidates, 768 unsigned NumCandidates, 769 SourceLocation OpenParLoc) override { 770 // At the moment we don't filter out any overloaded candidates. 771 } 772 773 CodeCompletionAllocator &getAllocator() override { 774 return m_info.getAllocator(); 775 } 776 777 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; } 778 }; 779 } // namespace 780 781 bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line, 782 unsigned pos, unsigned typed_pos) { 783 DiagnosticManager mgr; 784 // We need the raw user expression here because that's what the CodeComplete 785 // class uses to provide completion suggestions. 786 // However, the `Text` method only gives us the transformed expression here. 787 // To actually get the raw user input here, we have to cast our expression to 788 // the LLVMUserExpression which exposes the right API. This should never fail 789 // as we always have a ClangUserExpression whenever we call this. 790 LLVMUserExpression &llvm_expr = *static_cast<LLVMUserExpression *>(&m_expr); 791 CodeComplete CC(request, m_compiler->getLangOpts(), llvm_expr.GetUserText(), 792 typed_pos); 793 // We don't need a code generator for parsing. 794 m_code_generator.reset(); 795 // Start parsing the expression with our custom code completion consumer. 796 ParseInternal(mgr, &CC, line, pos); 797 return true; 798 } 799 800 unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) { 801 return ParseInternal(diagnostic_manager); 802 } 803 804 unsigned 805 ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager, 806 CodeCompleteConsumer *completion_consumer, 807 unsigned completion_line, 808 unsigned completion_column) { 809 ClangDiagnosticManagerAdapter *adapter = 810 static_cast<ClangDiagnosticManagerAdapter *>( 811 m_compiler->getDiagnostics().getClient()); 812 clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough(); 813 diag_buf->FlushDiagnostics(m_compiler->getDiagnostics()); 814 815 adapter->ResetManager(&diagnostic_manager); 816 817 const char *expr_text = m_expr.Text(); 818 819 clang::SourceManager &source_mgr = m_compiler->getSourceManager(); 820 bool created_main_file = false; 821 822 // Clang wants to do completion on a real file known by Clang's file manager, 823 // so we have to create one to make this work. 824 // TODO: We probably could also simulate to Clang's file manager that there 825 // is a real file that contains our code. 826 bool should_create_file = completion_consumer != nullptr; 827 828 // We also want a real file on disk if we generate full debug info. 829 should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() == 830 codegenoptions::FullDebugInfo; 831 832 if (should_create_file) { 833 int temp_fd = -1; 834 llvm::SmallString<128> result_path; 835 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) { 836 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr"); 837 std::string temp_source_path = tmpdir_file_spec.GetPath(); 838 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path); 839 } else { 840 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path); 841 } 842 843 if (temp_fd != -1) { 844 lldb_private::File file(temp_fd, true); 845 const size_t expr_text_len = strlen(expr_text); 846 size_t bytes_written = expr_text_len; 847 if (file.Write(expr_text, bytes_written).Success()) { 848 if (bytes_written == expr_text_len) { 849 file.Close(); 850 source_mgr.setMainFileID( 851 source_mgr.createFileID(m_file_manager->getFile(result_path), 852 SourceLocation(), SrcMgr::C_User)); 853 created_main_file = true; 854 } 855 } 856 } 857 } 858 859 if (!created_main_file) { 860 std::unique_ptr<MemoryBuffer> memory_buffer = 861 MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__); 862 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer))); 863 } 864 865 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), 866 &m_compiler->getPreprocessor()); 867 868 ClangExpressionHelper *type_system_helper = 869 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); 870 871 ASTConsumer *ast_transformer = 872 type_system_helper->ASTTransformer(m_code_generator.get()); 873 874 if (ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap()) 875 decl_map->InstallCodeGenerator(m_code_generator.get()); 876 877 // If we want to parse for code completion, we need to attach our code 878 // completion consumer to the Sema and specify a completion position. 879 // While parsing the Sema will call this consumer with the provided 880 // completion suggestions. 881 if (completion_consumer) { 882 auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID()); 883 auto &PP = m_compiler->getPreprocessor(); 884 // Lines and columns start at 1 in Clang, but code completion positions are 885 // indexed from 0, so we need to add 1 to the line and column here. 886 ++completion_line; 887 ++completion_column; 888 PP.SetCodeCompletionPoint(main_file, completion_line, completion_column); 889 } 890 891 if (ast_transformer) { 892 ast_transformer->Initialize(m_compiler->getASTContext()); 893 ParseAST(m_compiler->getPreprocessor(), ast_transformer, 894 m_compiler->getASTContext(), false, TU_Complete, 895 completion_consumer); 896 } else { 897 m_code_generator->Initialize(m_compiler->getASTContext()); 898 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), 899 m_compiler->getASTContext(), false, TU_Complete, 900 completion_consumer); 901 } 902 903 diag_buf->EndSourceFile(); 904 905 unsigned num_errors = diag_buf->getNumErrors(); 906 907 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) { 908 num_errors++; 909 diagnostic_manager.PutString(eDiagnosticSeverityError, 910 "while importing modules:"); 911 diagnostic_manager.AppendMessageToDiagnostic( 912 m_pp_callbacks->getErrorString()); 913 } 914 915 if (!num_errors) { 916 if (type_system_helper->DeclMap() && 917 !type_system_helper->DeclMap()->ResolveUnknownTypes()) { 918 diagnostic_manager.Printf(eDiagnosticSeverityError, 919 "Couldn't infer the type of a variable"); 920 num_errors++; 921 } 922 } 923 924 if (!num_errors) { 925 type_system_helper->CommitPersistentDecls(); 926 } 927 928 adapter->ResetManager(); 929 930 return num_errors; 931 } 932 933 std::string 934 ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) { 935 std::string abi; 936 937 if (target_arch.IsMIPS()) { 938 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) { 939 case ArchSpec::eMIPSABI_N64: 940 abi = "n64"; 941 break; 942 case ArchSpec::eMIPSABI_N32: 943 abi = "n32"; 944 break; 945 case ArchSpec::eMIPSABI_O32: 946 abi = "o32"; 947 break; 948 default: 949 break; 950 } 951 } 952 return abi; 953 } 954 955 bool ClangExpressionParser::RewriteExpression( 956 DiagnosticManager &diagnostic_manager) { 957 clang::SourceManager &source_manager = m_compiler->getSourceManager(); 958 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(), 959 nullptr); 960 clang::edit::Commit commit(editor); 961 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts()); 962 963 class RewritesReceiver : public edit::EditsReceiver { 964 Rewriter &rewrite; 965 966 public: 967 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {} 968 969 void insert(SourceLocation loc, StringRef text) override { 970 rewrite.InsertText(loc, text); 971 } 972 void replace(CharSourceRange range, StringRef text) override { 973 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text); 974 } 975 }; 976 977 RewritesReceiver rewrites_receiver(rewriter); 978 979 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics(); 980 size_t num_diags = diagnostics.size(); 981 if (num_diags == 0) 982 return false; 983 984 for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) { 985 const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag); 986 if (diagnostic && diagnostic->HasFixIts()) { 987 for (const FixItHint &fixit : diagnostic->FixIts()) { 988 // This is cobbed from clang::Rewrite::FixItRewriter. 989 if (fixit.CodeToInsert.empty()) { 990 if (fixit.InsertFromRange.isValid()) { 991 commit.insertFromRange(fixit.RemoveRange.getBegin(), 992 fixit.InsertFromRange, /*afterToken=*/false, 993 fixit.BeforePreviousInsertions); 994 } else 995 commit.remove(fixit.RemoveRange); 996 } else { 997 if (fixit.RemoveRange.isTokenRange() || 998 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd()) 999 commit.replace(fixit.RemoveRange, fixit.CodeToInsert); 1000 else 1001 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert, 1002 /*afterToken=*/false, fixit.BeforePreviousInsertions); 1003 } 1004 } 1005 } 1006 } 1007 1008 // FIXME - do we want to try to propagate specific errors here? 1009 if (!commit.isCommitable()) 1010 return false; 1011 else if (!editor.commit(commit)) 1012 return false; 1013 1014 // Now play all the edits, and stash the result in the diagnostic manager. 1015 editor.applyRewrites(rewrites_receiver); 1016 RewriteBuffer &main_file_buffer = 1017 rewriter.getEditBuffer(source_manager.getMainFileID()); 1018 1019 std::string fixed_expression; 1020 llvm::raw_string_ostream out_stream(fixed_expression); 1021 1022 main_file_buffer.write(out_stream); 1023 out_stream.flush(); 1024 diagnostic_manager.SetFixedExpression(fixed_expression); 1025 1026 return true; 1027 } 1028 1029 static bool FindFunctionInModule(ConstString &mangled_name, 1030 llvm::Module *module, const char *orig_name) { 1031 for (const auto &func : module->getFunctionList()) { 1032 const StringRef &name = func.getName(); 1033 if (name.find(orig_name) != StringRef::npos) { 1034 mangled_name.SetString(name); 1035 return true; 1036 } 1037 } 1038 1039 return false; 1040 } 1041 1042 lldb_private::Status ClangExpressionParser::PrepareForExecution( 1043 lldb::addr_t &func_addr, lldb::addr_t &func_end, 1044 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx, 1045 bool &can_interpret, ExecutionPolicy execution_policy) { 1046 func_addr = LLDB_INVALID_ADDRESS; 1047 func_end = LLDB_INVALID_ADDRESS; 1048 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1049 1050 lldb_private::Status err; 1051 1052 std::unique_ptr<llvm::Module> llvm_module_ap( 1053 m_code_generator->ReleaseModule()); 1054 1055 if (!llvm_module_ap.get()) { 1056 err.SetErrorToGenericError(); 1057 err.SetErrorString("IR doesn't contain a module"); 1058 return err; 1059 } 1060 1061 ConstString function_name; 1062 1063 if (execution_policy != eExecutionPolicyTopLevel) { 1064 // Find the actual name of the function (it's often mangled somehow) 1065 1066 if (!FindFunctionInModule(function_name, llvm_module_ap.get(), 1067 m_expr.FunctionName())) { 1068 err.SetErrorToGenericError(); 1069 err.SetErrorStringWithFormat("Couldn't find %s() in the module", 1070 m_expr.FunctionName()); 1071 return err; 1072 } else { 1073 if (log) 1074 log->Printf("Found function %s for %s", function_name.AsCString(), 1075 m_expr.FunctionName()); 1076 } 1077 } 1078 1079 SymbolContext sc; 1080 1081 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) { 1082 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything); 1083 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) { 1084 sc.target_sp = target_sp; 1085 } 1086 1087 LLVMUserExpression::IRPasses custom_passes; 1088 { 1089 auto lang = m_expr.Language(); 1090 if (log) 1091 log->Printf("%s - Current expression language is %s\n", __FUNCTION__, 1092 Language::GetNameForLanguageType(lang)); 1093 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP(); 1094 if (process_sp && lang != lldb::eLanguageTypeUnknown) { 1095 auto runtime = process_sp->GetLanguageRuntime(lang); 1096 if (runtime) 1097 runtime->GetIRPasses(custom_passes); 1098 } 1099 } 1100 1101 if (custom_passes.EarlyPasses) { 1102 if (log) 1103 log->Printf("%s - Running Early IR Passes from LanguageRuntime on " 1104 "expression module '%s'", 1105 __FUNCTION__, m_expr.FunctionName()); 1106 1107 custom_passes.EarlyPasses->run(*llvm_module_ap); 1108 } 1109 1110 execution_unit_sp.reset( 1111 new IRExecutionUnit(m_llvm_context, // handed off here 1112 llvm_module_ap, // handed off here 1113 function_name, exe_ctx.GetTargetSP(), sc, 1114 m_compiler->getTargetOpts().Features)); 1115 1116 ClangExpressionHelper *type_system_helper = 1117 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); 1118 ClangExpressionDeclMap *decl_map = 1119 type_system_helper->DeclMap(); // result can be NULL 1120 1121 if (decl_map) { 1122 Stream *error_stream = NULL; 1123 Target *target = exe_ctx.GetTargetPtr(); 1124 error_stream = target->GetDebugger().GetErrorFile().get(); 1125 1126 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(), 1127 *execution_unit_sp, *error_stream, 1128 function_name.AsCString()); 1129 1130 bool ir_can_run = 1131 ir_for_target.runOnModule(*execution_unit_sp->GetModule()); 1132 1133 if (!ir_can_run) { 1134 err.SetErrorString( 1135 "The expression could not be prepared to run in the target"); 1136 return err; 1137 } 1138 1139 Process *process = exe_ctx.GetProcessPtr(); 1140 1141 if (execution_policy != eExecutionPolicyAlways && 1142 execution_policy != eExecutionPolicyTopLevel) { 1143 lldb_private::Status interpret_error; 1144 1145 bool interpret_function_calls = 1146 !process ? false : process->CanInterpretFunctionCalls(); 1147 can_interpret = IRInterpreter::CanInterpret( 1148 *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(), 1149 interpret_error, interpret_function_calls); 1150 1151 if (!can_interpret && execution_policy == eExecutionPolicyNever) { 1152 err.SetErrorStringWithFormat("Can't run the expression locally: %s", 1153 interpret_error.AsCString()); 1154 return err; 1155 } 1156 } 1157 1158 if (!process && execution_policy == eExecutionPolicyAlways) { 1159 err.SetErrorString("Expression needed to run in the target, but the " 1160 "target can't be run"); 1161 return err; 1162 } 1163 1164 if (!process && execution_policy == eExecutionPolicyTopLevel) { 1165 err.SetErrorString("Top-level code needs to be inserted into a runnable " 1166 "target, but the target can't be run"); 1167 return err; 1168 } 1169 1170 if (execution_policy == eExecutionPolicyAlways || 1171 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) { 1172 if (m_expr.NeedsValidation() && process) { 1173 if (!process->GetDynamicCheckers()) { 1174 DynamicCheckerFunctions *dynamic_checkers = 1175 new DynamicCheckerFunctions(); 1176 1177 DiagnosticManager install_diagnostics; 1178 1179 if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) { 1180 if (install_diagnostics.Diagnostics().size()) 1181 err.SetErrorString(install_diagnostics.GetString().c_str()); 1182 else 1183 err.SetErrorString("couldn't install checkers, unknown error"); 1184 1185 return err; 1186 } 1187 1188 process->SetDynamicCheckers(dynamic_checkers); 1189 1190 if (log) 1191 log->Printf("== [ClangUserExpression::Evaluate] Finished " 1192 "installing dynamic checkers =="); 1193 } 1194 1195 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), 1196 function_name.AsCString()); 1197 1198 llvm::Module *module = execution_unit_sp->GetModule(); 1199 if (!module || !ir_dynamic_checks.runOnModule(*module)) { 1200 err.SetErrorToGenericError(); 1201 err.SetErrorString("Couldn't add dynamic checks to the expression"); 1202 return err; 1203 } 1204 1205 if (custom_passes.LatePasses) { 1206 if (log) 1207 log->Printf("%s - Running Late IR Passes from LanguageRuntime on " 1208 "expression module '%s'", 1209 __FUNCTION__, m_expr.FunctionName()); 1210 1211 custom_passes.LatePasses->run(*module); 1212 } 1213 } 1214 } 1215 1216 if (execution_policy == eExecutionPolicyAlways || 1217 execution_policy == eExecutionPolicyTopLevel || !can_interpret) { 1218 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end); 1219 } 1220 } else { 1221 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end); 1222 } 1223 1224 return err; 1225 } 1226 1227 lldb_private::Status ClangExpressionParser::RunStaticInitializers( 1228 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) { 1229 lldb_private::Status err; 1230 1231 lldbassert(execution_unit_sp.get()); 1232 lldbassert(exe_ctx.HasThreadScope()); 1233 1234 if (!execution_unit_sp.get()) { 1235 err.SetErrorString( 1236 "can't run static initializers for a NULL execution unit"); 1237 return err; 1238 } 1239 1240 if (!exe_ctx.HasThreadScope()) { 1241 err.SetErrorString("can't run static initializers without a thread"); 1242 return err; 1243 } 1244 1245 std::vector<lldb::addr_t> static_initializers; 1246 1247 execution_unit_sp->GetStaticInitializers(static_initializers); 1248 1249 for (lldb::addr_t static_initializer : static_initializers) { 1250 EvaluateExpressionOptions options; 1251 1252 lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction( 1253 exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(), 1254 llvm::ArrayRef<lldb::addr_t>(), options)); 1255 1256 DiagnosticManager execution_errors; 1257 lldb::ExpressionResults results = 1258 exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan( 1259 exe_ctx, call_static_initializer, options, execution_errors); 1260 1261 if (results != lldb::eExpressionCompleted) { 1262 err.SetErrorStringWithFormat("couldn't run static initializer: %s", 1263 execution_errors.GetString().c_str()); 1264 return err; 1265 } 1266 } 1267 1268 return err; 1269 } 1270