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