1 //===-- ClangExpressionParser.cpp -------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // C Includes 11 // C++ Includes 12 // Other libraries and framework includes 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/ASTDiagnostic.h" 15 #include "clang/AST/ExternalASTSource.h" 16 #include "clang/Basic/DiagnosticIDs.h" 17 #include "clang/Basic/FileManager.h" 18 #include "clang/Basic/SourceLocation.h" 19 #include "clang/Basic/TargetInfo.h" 20 #include "clang/Basic/Version.h" 21 #include "clang/CodeGen/CodeGenAction.h" 22 #include "clang/CodeGen/ModuleBuilder.h" 23 #include "clang/Edit/Commit.h" 24 #include "clang/Edit/EditsReceiver.h" 25 #include "clang/Edit/EditedSource.h" 26 #include "clang/Frontend/CompilerInstance.h" 27 #include "clang/Frontend/CompilerInvocation.h" 28 #include "clang/Frontend/FrontendActions.h" 29 #include "clang/Frontend/FrontendDiagnostic.h" 30 #include "clang/Frontend/FrontendPluginRegistry.h" 31 #include "clang/Frontend/TextDiagnosticBuffer.h" 32 #include "clang/Frontend/TextDiagnosticPrinter.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Parse/ParseAST.h" 35 #include "clang/Rewrite/Frontend/FrontendActions.h" 36 #include "clang/Rewrite/Core/Rewriter.h" 37 #include "clang/Sema/SemaConsumer.h" 38 #include "clang/StaticAnalyzer/Frontend/FrontendActions.h" 39 40 #include "llvm/ADT/StringRef.h" 41 #include "llvm/ExecutionEngine/ExecutionEngine.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Support/FileSystem.h" 44 #include "llvm/Support/TargetSelect.h" 45 46 #pragma clang diagnostic push 47 #pragma clang diagnostic ignored "-Wglobal-constructors" 48 #include "llvm/ExecutionEngine/MCJIT.h" 49 #pragma clang diagnostic pop 50 51 #include "llvm/IR/LLVMContext.h" 52 #include "llvm/IR/Module.h" 53 #include "llvm/Support/ErrorHandling.h" 54 #include "llvm/Support/MemoryBuffer.h" 55 #include "llvm/Support/DynamicLibrary.h" 56 #include "llvm/Support/Host.h" 57 #include "llvm/Support/Signals.h" 58 59 // Project includes 60 #include "ClangExpressionParser.h" 61 #include "ClangDiagnostic.h" 62 63 #include "ClangASTSource.h" 64 #include "ClangExpressionHelper.h" 65 #include "ClangExpressionDeclMap.h" 66 #include "ClangModulesDeclVendor.h" 67 #include "ClangPersistentVariables.h" 68 #include "IRForTarget.h" 69 70 #include "lldb/Core/ArchSpec.h" 71 #include "lldb/Core/DataBufferHeap.h" 72 #include "lldb/Core/Debugger.h" 73 #include "lldb/Core/Disassembler.h" 74 #include "lldb/Core/Log.h" 75 #include "lldb/Core/Module.h" 76 #include "lldb/Core/Stream.h" 77 #include "lldb/Core/StreamFile.h" 78 #include "lldb/Core/StreamString.h" 79 #include "lldb/Core/StringList.h" 80 #include "lldb/Expression/IRDynamicChecks.h" 81 #include "lldb/Expression/IRExecutionUnit.h" 82 #include "lldb/Expression/IRInterpreter.h" 83 #include "lldb/Host/File.h" 84 #include "lldb/Host/HostInfo.h" 85 #include "lldb/Symbol/ClangASTContext.h" 86 #include "lldb/Symbol/SymbolVendor.h" 87 #include "lldb/Target/ExecutionContext.h" 88 #include "lldb/Target/Language.h" 89 #include "lldb/Target/ObjCLanguageRuntime.h" 90 #include "lldb/Target/Process.h" 91 #include "lldb/Target/Target.h" 92 #include "lldb/Target/ThreadPlanCallFunction.h" 93 #include "lldb/Utility/LLDBAssert.h" 94 95 using namespace clang; 96 using namespace llvm; 97 using namespace lldb_private; 98 99 //===----------------------------------------------------------------------===// 100 // Utility Methods for Clang 101 //===----------------------------------------------------------------------===// 102 103 104 class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks 105 { 106 ClangModulesDeclVendor &m_decl_vendor; 107 ClangPersistentVariables &m_persistent_vars; 108 StreamString m_error_stream; 109 bool m_has_errors = false; 110 111 public: 112 LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor, 113 ClangPersistentVariables &persistent_vars) : 114 m_decl_vendor(decl_vendor), 115 m_persistent_vars(persistent_vars) 116 { 117 } 118 119 void 120 moduleImport(SourceLocation import_location, 121 clang::ModuleIdPath path, 122 const clang::Module * /*null*/) override 123 { 124 std::vector<ConstString> string_path; 125 126 for (const std::pair<IdentifierInfo *, SourceLocation> &component : path) 127 { 128 string_path.push_back(ConstString(component.first->getName())); 129 } 130 131 StreamString error_stream; 132 133 ClangModulesDeclVendor::ModuleVector exported_modules; 134 135 if (!m_decl_vendor.AddModule(string_path, &exported_modules, m_error_stream)) 136 { 137 m_has_errors = true; 138 } 139 140 for (ClangModulesDeclVendor::ModuleID module : exported_modules) 141 { 142 m_persistent_vars.AddHandLoadedClangModule(module); 143 } 144 } 145 146 bool hasErrors() 147 { 148 return m_has_errors; 149 } 150 151 const std::string &getErrorString() 152 { 153 return m_error_stream.GetString(); 154 } 155 }; 156 157 class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer 158 { 159 public: 160 ClangDiagnosticManagerAdapter() : m_passthrough(new clang::TextDiagnosticBuffer) {} 161 162 ClangDiagnosticManagerAdapter(const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough) 163 : m_passthrough(passthrough) 164 { 165 } 166 167 void 168 ResetManager(DiagnosticManager *manager = nullptr) 169 { 170 m_manager = manager; 171 } 172 173 void 174 HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info) 175 { 176 if (m_manager) 177 { 178 llvm::SmallVector<char, 32> diag_str; 179 Info.FormatDiagnostic(diag_str); 180 diag_str.push_back('\0'); 181 const char *data = diag_str.data(); 182 183 DiagnosticSeverity severity; 184 bool make_new_diagnostic = true; 185 186 switch (DiagLevel) 187 { 188 case DiagnosticsEngine::Level::Fatal: 189 case DiagnosticsEngine::Level::Error: 190 severity = eDiagnosticSeverityError; 191 break; 192 case DiagnosticsEngine::Level::Warning: 193 severity = eDiagnosticSeverityWarning; 194 break; 195 case DiagnosticsEngine::Level::Remark: 196 case DiagnosticsEngine::Level::Ignored: 197 severity = eDiagnosticSeverityRemark; 198 break; 199 case DiagnosticsEngine::Level::Note: 200 m_manager->AppendMessageToDiagnostic(data); 201 make_new_diagnostic = false; 202 } 203 if (make_new_diagnostic) 204 { 205 ClangDiagnostic *new_diagnostic = new ClangDiagnostic(data, severity, Info.getID()); 206 m_manager->AddDiagnostic(new_diagnostic); 207 208 // Don't store away warning fixits, since the compiler doesn't have enough 209 // context in an expression for the warning to be useful. 210 // FIXME: Should we try to filter out FixIts that apply to our generated 211 // code, and not the user's expression? 212 if (severity == eDiagnosticSeverityError) 213 { 214 size_t num_fixit_hints = Info.getNumFixItHints(); 215 for (size_t i = 0; i < num_fixit_hints; i++) 216 { 217 const clang::FixItHint &fixit = Info.getFixItHint(i); 218 if (!fixit.isNull()) 219 new_diagnostic->AddFixitHint(fixit); 220 } 221 } 222 } 223 } 224 225 m_passthrough->HandleDiagnostic(DiagLevel, Info); 226 } 227 228 void 229 FlushDiagnostics(DiagnosticsEngine &Diags) 230 { 231 m_passthrough->FlushDiagnostics(Diags); 232 } 233 234 DiagnosticConsumer * 235 clone(DiagnosticsEngine &Diags) const 236 { 237 return new ClangDiagnosticManagerAdapter(m_passthrough); 238 } 239 240 clang::TextDiagnosticBuffer * 241 GetPassthrough() 242 { 243 return m_passthrough.get(); 244 } 245 246 private: 247 DiagnosticManager *m_manager = nullptr; 248 std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough; 249 }; 250 251 //===----------------------------------------------------------------------===// 252 // Implementation of ClangExpressionParser 253 //===----------------------------------------------------------------------===// 254 255 ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope, 256 Expression &expr, 257 bool generate_debug_info) : 258 ExpressionParser (exe_scope, expr, generate_debug_info), 259 m_compiler (), 260 m_code_generator (), 261 m_pp_callbacks(nullptr) 262 { 263 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 264 265 // 1. Create a new compiler instance. 266 m_compiler.reset(new CompilerInstance()); 267 lldb::LanguageType frame_lang = expr.Language(); // defaults to lldb::eLanguageTypeUnknown 268 bool overridden_target_opts = false; 269 lldb_private::LanguageRuntime *lang_rt = nullptr; 270 lldb::TargetSP target_sp; 271 if (exe_scope) 272 target_sp = exe_scope->CalculateTarget(); 273 274 ArchSpec target_arch; 275 if (target_sp) 276 target_arch = target_sp->GetArchitecture(); 277 278 const auto target_machine = target_arch.GetMachine(); 279 280 // If the expression is being evaluated in the context of an existing 281 // stack frame, we introspect to see if the language runtime is available. 282 auto frame = exe_scope->CalculateStackFrame(); 283 284 // Make sure the user hasn't provided a preferred execution language 285 // with `expression --language X -- ...` 286 if (frame && frame_lang == lldb::eLanguageTypeUnknown) 287 frame_lang = frame->GetLanguage(); 288 289 if (frame_lang != lldb::eLanguageTypeUnknown) 290 { 291 lang_rt = exe_scope->CalculateProcess()->GetLanguageRuntime(frame_lang); 292 if (log) 293 log->Printf("Frame has language of type %s", Language::GetNameForLanguageType(frame_lang)); 294 } 295 296 // 2. Configure the compiler with a set of default options that are appropriate 297 // for most situations. 298 if (target_sp && target_arch.IsValid()) 299 { 300 std::string triple = target_arch.GetTriple().str(); 301 m_compiler->getTargetOpts().Triple = triple; 302 if (log) 303 log->Printf("Using %s as the target triple", m_compiler->getTargetOpts().Triple.c_str()); 304 } 305 else 306 { 307 // If we get here we don't have a valid target and just have to guess. 308 // Sometimes this will be ok to just use the host target triple (when we evaluate say "2+3", but other 309 // expressions like breakpoint conditions and other things that _are_ target specific really shouldn't just be 310 // using the host triple. In such a case the language runtime should expose an overridden options set (3), 311 // below. 312 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple(); 313 if (log) 314 log->Printf("Using default target triple of %s", m_compiler->getTargetOpts().Triple.c_str()); 315 } 316 // Now add some special fixes for known architectures: 317 // Any arm32 iOS environment, but not on arm64 318 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos && 319 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos && 320 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) 321 { 322 m_compiler->getTargetOpts().ABI = "apcs-gnu"; 323 } 324 // Supported subsets of x86 325 if (target_machine == llvm::Triple::x86 || 326 target_machine == llvm::Triple::x86_64) 327 { 328 m_compiler->getTargetOpts().Features.push_back("+sse"); 329 m_compiler->getTargetOpts().Features.push_back("+sse2"); 330 } 331 332 // Set the target CPU to generate code for. 333 // This will be empty for any CPU that doesn't really need to make a special CPU string. 334 m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU(); 335 336 // 3. Now allow the runtime to provide custom configuration options for the target. 337 // In this case, a specialized language runtime is available and we can query it for extra options. 338 // For 99% of use cases, this will not be needed and should be provided when basic platform detection is not enough. 339 if (lang_rt) 340 overridden_target_opts = lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts()); 341 342 if (overridden_target_opts) 343 if (log) 344 { 345 log->Debug("Using overridden target options for the expression evaluation"); 346 347 auto opts = m_compiler->getTargetOpts(); 348 log->Debug("Triple: '%s'", opts.Triple.c_str()); 349 log->Debug("CPU: '%s'", opts.CPU.c_str()); 350 log->Debug("FPMath: '%s'", opts.FPMath.c_str()); 351 log->Debug("ABI: '%s'", opts.ABI.c_str()); 352 log->Debug("LinkerVersion: '%s'", opts.LinkerVersion.c_str()); 353 StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten"); 354 StringList::LogDump(log, opts.Features, "Features"); 355 StringList::LogDump(log, opts.Reciprocals, "Reciprocals"); 356 } 357 358 // 4. Create and install the target on the compiler. 359 m_compiler->createDiagnostics(); 360 auto target_info = TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts); 361 if (log) 362 { 363 log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign()); 364 log->Printf("Target datalayout string: '%s'", target_info->getDataLayout().getStringRepresentation().c_str()); 365 log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str()); 366 log->Printf("Target vector alignment: %d", target_info->getMaxVectorAlign()); 367 } 368 m_compiler->setTarget(target_info); 369 370 assert (m_compiler->hasTarget()); 371 372 // 5. Set language options. 373 lldb::LanguageType language = expr.Language(); 374 375 switch (language) 376 { 377 case lldb::eLanguageTypeC: 378 case lldb::eLanguageTypeC89: 379 case lldb::eLanguageTypeC99: 380 case lldb::eLanguageTypeC11: 381 // FIXME: the following language option is a temporary workaround, 382 // to "ask for C, get C++." 383 // For now, the expression parser must use C++ anytime the 384 // language is a C family language, because the expression parser 385 // uses features of C++ to capture values. 386 m_compiler->getLangOpts().CPlusPlus = true; 387 break; 388 case lldb::eLanguageTypeObjC: 389 m_compiler->getLangOpts().ObjC1 = true; 390 m_compiler->getLangOpts().ObjC2 = true; 391 // FIXME: the following language option is a temporary workaround, 392 // to "ask for ObjC, get ObjC++" (see comment above). 393 m_compiler->getLangOpts().CPlusPlus = true; 394 break; 395 case lldb::eLanguageTypeC_plus_plus: 396 case lldb::eLanguageTypeC_plus_plus_11: 397 case lldb::eLanguageTypeC_plus_plus_14: 398 m_compiler->getLangOpts().CPlusPlus11 = true; 399 m_compiler->getHeaderSearchOpts().UseLibcxx = true; 400 LLVM_FALLTHROUGH; 401 case lldb::eLanguageTypeC_plus_plus_03: 402 m_compiler->getLangOpts().CPlusPlus = true; 403 // FIXME: the following language option is a temporary workaround, 404 // to "ask for C++, get ObjC++". Apple hopes to remove this requirement 405 // on non-Apple platforms, but for now it is needed. 406 m_compiler->getLangOpts().ObjC1 = true; 407 break; 408 case lldb::eLanguageTypeObjC_plus_plus: 409 case lldb::eLanguageTypeUnknown: 410 default: 411 m_compiler->getLangOpts().ObjC1 = true; 412 m_compiler->getLangOpts().ObjC2 = true; 413 m_compiler->getLangOpts().CPlusPlus = true; 414 m_compiler->getLangOpts().CPlusPlus11 = true; 415 m_compiler->getHeaderSearchOpts().UseLibcxx = true; 416 break; 417 } 418 419 m_compiler->getLangOpts().Bool = true; 420 m_compiler->getLangOpts().WChar = true; 421 m_compiler->getLangOpts().Blocks = true; 422 m_compiler->getLangOpts().DebuggerSupport = true; // Features specifically for debugger clients 423 if (expr.DesiredResultType() == Expression::eResultTypeId) 424 m_compiler->getLangOpts().DebuggerCastResultToId = true; 425 426 m_compiler->getLangOpts().CharIsSigned = 427 ArchSpec(m_compiler->getTargetOpts().Triple.c_str()).CharIsSignedByDefault(); 428 429 // Spell checking is a nice feature, but it ends up completing a 430 // lot of types that we didn't strictly speaking need to complete. 431 // As a result, we spend a long time parsing and importing debug 432 // information. 433 m_compiler->getLangOpts().SpellChecking = false; 434 435 lldb::ProcessSP process_sp; 436 if (exe_scope) 437 process_sp = exe_scope->CalculateProcess(); 438 439 if (process_sp && m_compiler->getLangOpts().ObjC1) 440 { 441 if (process_sp->GetObjCLanguageRuntime()) 442 { 443 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() == ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2) 444 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7)); 445 else 446 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX, VersionTuple(10, 7)); 447 448 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing()) 449 m_compiler->getLangOpts().DebuggerObjCLiteral = true; 450 } 451 } 452 453 m_compiler->getLangOpts().ThreadsafeStatics = false; 454 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access 455 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name 456 457 // Set CodeGen options 458 m_compiler->getCodeGenOpts().EmitDeclMetadata = true; 459 m_compiler->getCodeGenOpts().InstrumentFunctions = false; 460 m_compiler->getCodeGenOpts().DisableFPElim = true; 461 m_compiler->getCodeGenOpts().OmitLeafFramePointer = false; 462 if (generate_debug_info) 463 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo); 464 else 465 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo); 466 467 // Disable some warnings. 468 m_compiler->getDiagnostics().setSeverityForGroup(clang::diag::Flavor::WarningOrError, 469 "unused-value", clang::diag::Severity::Ignored, SourceLocation()); 470 m_compiler->getDiagnostics().setSeverityForGroup(clang::diag::Flavor::WarningOrError, 471 "odr", clang::diag::Severity::Ignored, SourceLocation()); 472 473 // Inform the target of the language options 474 // 475 // FIXME: We shouldn't need to do this, the target should be immutable once 476 // created. This complexity should be lifted elsewhere. 477 m_compiler->getTarget().adjust(m_compiler->getLangOpts()); 478 479 // 6. Set up the diagnostic buffer for reporting errors 480 481 m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter); 482 483 // 7. Set up the source management objects inside the compiler 484 485 clang::FileSystemOptions file_system_options; 486 m_file_manager.reset(new clang::FileManager(file_system_options)); 487 488 if (!m_compiler->hasSourceManager()) 489 m_compiler->createSourceManager(*m_file_manager.get()); 490 491 m_compiler->createFileManager(); 492 m_compiler->createPreprocessor(TU_Complete); 493 494 if (ClangModulesDeclVendor *decl_vendor = target_sp->GetClangModulesDeclVendor()) 495 { 496 ClangPersistentVariables *clang_persistent_vars = llvm::cast<ClangPersistentVariables>(target_sp->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC)); 497 std::unique_ptr<PPCallbacks> pp_callbacks(new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars)); 498 m_pp_callbacks = static_cast<LLDBPreprocessorCallbacks*>(pp_callbacks.get()); 499 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks)); 500 } 501 502 // 8. Most of this we get from the CompilerInstance, but we 503 // also want to give the context an ExternalASTSource. 504 m_selector_table.reset(new SelectorTable()); 505 m_builtin_context.reset(new Builtin::Context()); 506 507 std::unique_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(), 508 m_compiler->getSourceManager(), 509 m_compiler->getPreprocessor().getIdentifierTable(), 510 *m_selector_table.get(), 511 *m_builtin_context.get())); 512 513 ast_context->InitBuiltinTypes(m_compiler->getTarget()); 514 515 ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); 516 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap(); 517 518 if (decl_map) 519 { 520 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source(decl_map->CreateProxy()); 521 decl_map->InstallASTContext(ast_context.get()); 522 ast_context->setExternalSource(ast_source); 523 } 524 525 m_ast_context.reset(new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str())); 526 m_ast_context->setASTContext(ast_context.get()); 527 m_compiler->setASTContext(ast_context.release()); 528 529 std::string module_name("$__lldb_module"); 530 531 m_llvm_context.reset(new LLVMContext()); 532 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(), 533 module_name, 534 m_compiler->getHeaderSearchOpts(), 535 m_compiler->getPreprocessorOpts(), 536 m_compiler->getCodeGenOpts(), 537 *m_llvm_context)); 538 } 539 540 ClangExpressionParser::~ClangExpressionParser() 541 { 542 } 543 544 unsigned 545 ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) 546 { 547 ClangDiagnosticManagerAdapter *adapter = 548 static_cast<ClangDiagnosticManagerAdapter *>(m_compiler->getDiagnostics().getClient()); 549 clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough(); 550 diag_buf->FlushDiagnostics(m_compiler->getDiagnostics()); 551 552 adapter->ResetManager(&diagnostic_manager); 553 554 const char *expr_text = m_expr.Text(); 555 556 clang::SourceManager &source_mgr = m_compiler->getSourceManager(); 557 bool created_main_file = false; 558 if (m_compiler->getCodeGenOpts().getDebugInfo() == codegenoptions::FullDebugInfo) 559 { 560 int temp_fd = -1; 561 llvm::SmallString<PATH_MAX> result_path; 562 FileSpec tmpdir_file_spec; 563 if (HostInfo::GetLLDBPath(lldb::ePathTypeLLDBTempSystemDir, tmpdir_file_spec)) 564 { 565 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr"); 566 std::string temp_source_path = tmpdir_file_spec.GetPath(); 567 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path); 568 } 569 else 570 { 571 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path); 572 } 573 574 if (temp_fd != -1) 575 { 576 lldb_private::File file(temp_fd, true); 577 const size_t expr_text_len = strlen(expr_text); 578 size_t bytes_written = expr_text_len; 579 if (file.Write(expr_text, bytes_written).Success()) 580 { 581 if (bytes_written == expr_text_len) 582 { 583 file.Close(); 584 source_mgr.setMainFileID(source_mgr.createFileID(m_file_manager->getFile(result_path), 585 SourceLocation(), SrcMgr::C_User)); 586 created_main_file = true; 587 } 588 } 589 } 590 } 591 592 if (!created_main_file) 593 { 594 std::unique_ptr<MemoryBuffer> memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__); 595 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer))); 596 } 597 598 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor()); 599 600 ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); 601 602 ASTConsumer *ast_transformer = type_system_helper->ASTTransformer(m_code_generator.get()); 603 604 if (ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap()) 605 decl_map->InstallCodeGenerator(m_code_generator.get()); 606 607 if (ast_transformer) 608 { 609 ast_transformer->Initialize(m_compiler->getASTContext()); 610 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext()); 611 } 612 else 613 { 614 m_code_generator->Initialize(m_compiler->getASTContext()); 615 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext()); 616 } 617 618 diag_buf->EndSourceFile(); 619 620 unsigned num_errors = diag_buf->getNumErrors(); 621 622 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) 623 { 624 num_errors++; 625 diagnostic_manager.PutCString(eDiagnosticSeverityError, "while importing modules:"); 626 diagnostic_manager.AppendMessageToDiagnostic(m_pp_callbacks->getErrorString().c_str()); 627 } 628 629 if (!num_errors) 630 { 631 if (type_system_helper->DeclMap() && !type_system_helper->DeclMap()->ResolveUnknownTypes()) 632 { 633 diagnostic_manager.Printf(eDiagnosticSeverityError, "Couldn't infer the type of a variable"); 634 num_errors++; 635 } 636 } 637 638 if (!num_errors) 639 { 640 type_system_helper->CommitPersistentDecls(); 641 } 642 643 adapter->ResetManager(); 644 645 return num_errors; 646 } 647 648 bool 649 ClangExpressionParser::RewriteExpression(DiagnosticManager &diagnostic_manager) 650 { 651 clang::SourceManager &source_manager = m_compiler->getSourceManager(); 652 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(), nullptr); 653 clang::edit::Commit commit(editor); 654 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts()); 655 656 class RewritesReceiver : public edit::EditsReceiver { 657 Rewriter &rewrite; 658 659 public: 660 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) { } 661 662 void insert(SourceLocation loc, StringRef text) override { 663 rewrite.InsertText(loc, text); 664 } 665 void replace(CharSourceRange range, StringRef text) override { 666 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text); 667 } 668 }; 669 670 RewritesReceiver rewrites_receiver(rewriter); 671 672 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics(); 673 size_t num_diags = diagnostics.size(); 674 if (num_diags == 0) 675 return false; 676 677 for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) 678 { 679 const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag); 680 if (diagnostic && diagnostic->HasFixIts()) 681 { 682 for (const FixItHint &fixit : diagnostic->FixIts()) 683 { 684 // This is cobbed from clang::Rewrite::FixItRewriter. 685 if (fixit.CodeToInsert.empty()) 686 { 687 if (fixit.InsertFromRange.isValid()) 688 { 689 commit.insertFromRange(fixit.RemoveRange.getBegin(), 690 fixit.InsertFromRange, /*afterToken=*/false, 691 fixit.BeforePreviousInsertions); 692 } 693 else 694 commit.remove(fixit.RemoveRange); 695 } 696 else 697 { 698 if (fixit.RemoveRange.isTokenRange() || 699 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd()) 700 commit.replace(fixit.RemoveRange, fixit.CodeToInsert); 701 else 702 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert, 703 /*afterToken=*/false, fixit.BeforePreviousInsertions); 704 } 705 } 706 } 707 } 708 709 // FIXME - do we want to try to propagate specific errors here? 710 if (!commit.isCommitable()) 711 return false; 712 else if (!editor.commit(commit)) 713 return false; 714 715 // Now play all the edits, and stash the result in the diagnostic manager. 716 editor.applyRewrites(rewrites_receiver); 717 RewriteBuffer &main_file_buffer = rewriter.getEditBuffer(source_manager.getMainFileID()); 718 719 std::string fixed_expression; 720 llvm::raw_string_ostream out_stream(fixed_expression); 721 722 main_file_buffer.write(out_stream); 723 out_stream.flush(); 724 diagnostic_manager.SetFixedExpression(fixed_expression); 725 726 return true; 727 } 728 729 static bool FindFunctionInModule (ConstString &mangled_name, 730 llvm::Module *module, 731 const char *orig_name) 732 { 733 for (const auto &func : module->getFunctionList()) 734 { 735 const StringRef &name = func.getName(); 736 if (name.find(orig_name) != StringRef::npos) 737 { 738 mangled_name.SetString(name); 739 return true; 740 } 741 } 742 743 return false; 744 } 745 746 lldb_private::Error 747 ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr, 748 lldb::addr_t &func_end, 749 lldb::IRExecutionUnitSP &execution_unit_sp, 750 ExecutionContext &exe_ctx, 751 bool &can_interpret, 752 ExecutionPolicy execution_policy) 753 { 754 func_addr = LLDB_INVALID_ADDRESS; 755 func_end = LLDB_INVALID_ADDRESS; 756 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 757 758 lldb_private::Error err; 759 760 std::unique_ptr<llvm::Module> llvm_module_ap (m_code_generator->ReleaseModule()); 761 762 if (!llvm_module_ap.get()) 763 { 764 err.SetErrorToGenericError(); 765 err.SetErrorString("IR doesn't contain a module"); 766 return err; 767 } 768 769 ConstString function_name; 770 771 if (execution_policy != eExecutionPolicyTopLevel) 772 { 773 // Find the actual name of the function (it's often mangled somehow) 774 775 if (!FindFunctionInModule(function_name, llvm_module_ap.get(), m_expr.FunctionName())) 776 { 777 err.SetErrorToGenericError(); 778 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName()); 779 return err; 780 } 781 else 782 { 783 if (log) 784 log->Printf("Found function %s for %s", function_name.AsCString(), m_expr.FunctionName()); 785 } 786 } 787 788 SymbolContext sc; 789 790 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) 791 { 792 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything); 793 } 794 else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) 795 { 796 sc.target_sp = target_sp; 797 } 798 799 execution_unit_sp.reset(new IRExecutionUnit (m_llvm_context, // handed off here 800 llvm_module_ap, // handed off here 801 function_name, 802 exe_ctx.GetTargetSP(), 803 sc, 804 m_compiler->getTargetOpts().Features)); 805 806 ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); 807 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap(); // result can be NULL 808 809 if (decl_map) 810 { 811 Stream *error_stream = NULL; 812 Target *target = exe_ctx.GetTargetPtr(); 813 if (target) 814 error_stream = target->GetDebugger().GetErrorFile().get(); 815 816 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(), *execution_unit_sp, error_stream, 817 function_name.AsCString()); 818 819 bool ir_can_run = ir_for_target.runOnModule(*execution_unit_sp->GetModule()); 820 821 Process *process = exe_ctx.GetProcessPtr(); 822 823 if (execution_policy != eExecutionPolicyAlways && execution_policy != eExecutionPolicyTopLevel) 824 { 825 lldb_private::Error interpret_error; 826 827 bool interpret_function_calls = !process ? false : process->CanInterpretFunctionCalls(); 828 can_interpret = 829 IRInterpreter::CanInterpret(*execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(), 830 interpret_error, interpret_function_calls); 831 832 if (!can_interpret && execution_policy == eExecutionPolicyNever) 833 { 834 err.SetErrorStringWithFormat("Can't run the expression locally: %s", interpret_error.AsCString()); 835 return err; 836 } 837 } 838 839 if (!ir_can_run) 840 { 841 err.SetErrorString("The expression could not be prepared to run in the target"); 842 return err; 843 } 844 845 if (!process && execution_policy == eExecutionPolicyAlways) 846 { 847 err.SetErrorString("Expression needed to run in the target, but the target can't be run"); 848 return err; 849 } 850 851 if (!process && execution_policy == eExecutionPolicyTopLevel) 852 { 853 err.SetErrorString( 854 "Top-level code needs to be inserted into a runnable target, but the target can't be run"); 855 return err; 856 } 857 858 if (execution_policy == eExecutionPolicyAlways || 859 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) 860 { 861 if (m_expr.NeedsValidation() && process) 862 { 863 if (!process->GetDynamicCheckers()) 864 { 865 DynamicCheckerFunctions *dynamic_checkers = new DynamicCheckerFunctions(); 866 867 DiagnosticManager install_diagnostics; 868 869 if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) 870 { 871 if (install_diagnostics.Diagnostics().size()) 872 err.SetErrorString("couldn't install checkers, unknown error"); 873 else 874 err.SetErrorString(install_diagnostics.GetString().c_str()); 875 876 return err; 877 } 878 879 process->SetDynamicCheckers(dynamic_checkers); 880 881 if (log) 882 log->Printf("== [ClangUserExpression::Evaluate] Finished installing dynamic checkers =="); 883 } 884 885 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), function_name.AsCString()); 886 887 if (!ir_dynamic_checks.runOnModule(*execution_unit_sp->GetModule())) 888 { 889 err.SetErrorToGenericError(); 890 err.SetErrorString("Couldn't add dynamic checks to the expression"); 891 return err; 892 } 893 } 894 } 895 896 if (execution_policy == eExecutionPolicyAlways || execution_policy == eExecutionPolicyTopLevel || 897 !can_interpret) 898 { 899 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end); 900 } 901 } 902 else 903 { 904 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end); 905 } 906 907 return err; 908 } 909 910 lldb_private::Error 911 ClangExpressionParser::RunStaticInitializers (lldb::IRExecutionUnitSP &execution_unit_sp, 912 ExecutionContext &exe_ctx) 913 { 914 lldb_private::Error err; 915 916 lldbassert(execution_unit_sp.get()); 917 lldbassert(exe_ctx.HasThreadScope()); 918 919 if (!execution_unit_sp.get()) 920 { 921 err.SetErrorString ("can't run static initializers for a NULL execution unit"); 922 return err; 923 } 924 925 if (!exe_ctx.HasThreadScope()) 926 { 927 err.SetErrorString ("can't run static initializers without a thread"); 928 return err; 929 } 930 931 std::vector<lldb::addr_t> static_initializers; 932 933 execution_unit_sp->GetStaticInitializers(static_initializers); 934 935 for (lldb::addr_t static_initializer : static_initializers) 936 { 937 EvaluateExpressionOptions options; 938 939 lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(exe_ctx.GetThreadRef(), 940 Address(static_initializer), 941 CompilerType(), 942 llvm::ArrayRef<lldb::addr_t>(), 943 options)); 944 945 DiagnosticManager execution_errors; 946 lldb::ExpressionResults results = exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(exe_ctx, call_static_initializer, options, execution_errors); 947 948 if (results != lldb::eExpressionCompleted) 949 { 950 err.SetErrorStringWithFormat ("couldn't run static initializer: %s", execution_errors.GetString().c_str()); 951 return err; 952 } 953 } 954 955 return err; 956 } 957