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