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/ExternalASTSource.h" 15 #include "clang/Basic/FileManager.h" 16 #include "clang/Basic/SourceLocation.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/Basic/Version.h" 19 #include "clang/CodeGen/CodeGenAction.h" 20 #include "clang/CodeGen/ModuleBuilder.h" 21 #include "clang/Frontend/CompilerInstance.h" 22 #include "clang/Frontend/CompilerInvocation.h" 23 #include "clang/Frontend/FrontendActions.h" 24 #include "clang/Frontend/FrontendDiagnostic.h" 25 #include "clang/Frontend/FrontendPluginRegistry.h" 26 #include "clang/Frontend/TextDiagnosticBuffer.h" 27 #include "clang/Frontend/TextDiagnosticPrinter.h" 28 #include "clang/Lex/Preprocessor.h" 29 #include "clang/Parse/ParseAST.h" 30 #include "clang/Rewrite/Frontend/FrontendActions.h" 31 #include "clang/Sema/SemaConsumer.h" 32 #include "clang/StaticAnalyzer/Frontend/FrontendActions.h" 33 34 #include "llvm/ADT/StringRef.h" 35 #include "llvm/ExecutionEngine/ExecutionEngine.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/FileSystem.h" 38 #include "llvm/Support/TargetSelect.h" 39 40 #include "llvm/ExecutionEngine/MCJIT.h" 41 #include "llvm/IR/LLVMContext.h" 42 #include "llvm/IR/Module.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Support/MemoryBuffer.h" 45 #include "llvm/Support/DynamicLibrary.h" 46 #include "llvm/Support/Host.h" 47 #include "llvm/Support/Signals.h" 48 49 // Project includes 50 #include "ClangExpressionParser.h" 51 52 #include "ClangASTSource.h" 53 #include "ClangExpressionHelper.h" 54 #include "ClangExpressionDeclMap.h" 55 #include "ClangModulesDeclVendor.h" 56 #include "ClangPersistentVariables.h" 57 #include "IRForTarget.h" 58 59 #include "lldb/Core/ArchSpec.h" 60 #include "lldb/Core/DataBufferHeap.h" 61 #include "lldb/Core/Debugger.h" 62 #include "lldb/Core/Disassembler.h" 63 #include "lldb/Core/Log.h" 64 #include "lldb/Core/Module.h" 65 #include "lldb/Core/Stream.h" 66 #include "lldb/Core/StreamFile.h" 67 #include "lldb/Core/StringList.h" 68 #include "lldb/Core/StreamString.h" 69 #include "lldb/Expression/IRExecutionUnit.h" 70 #include "lldb/Expression/IRDynamicChecks.h" 71 #include "lldb/Expression/IRInterpreter.h" 72 #include "lldb/Host/File.h" 73 #include "lldb/Host/HostInfo.h" 74 #include "lldb/Symbol/ClangASTContext.h" 75 #include "lldb/Symbol/SymbolVendor.h" 76 #include "lldb/Target/ExecutionContext.h" 77 #include "lldb/Target/ObjCLanguageRuntime.h" 78 #include "lldb/Target/Process.h" 79 #include "lldb/Target/Target.h" 80 #include "lldb/Target/Language.h" 81 82 using namespace clang; 83 using namespace llvm; 84 using namespace lldb_private; 85 86 //===----------------------------------------------------------------------===// 87 // Utility Methods for Clang 88 //===----------------------------------------------------------------------===// 89 90 std::string GetBuiltinIncludePath(const char *Argv0) { 91 SmallString<128> P(llvm::sys::fs::getMainExecutable( 92 Argv0, (void *)(intptr_t) GetBuiltinIncludePath)); 93 94 if (!P.empty()) { 95 llvm::sys::path::remove_filename(P); // Remove /clang from foo/bin/clang 96 llvm::sys::path::remove_filename(P); // Remove /bin from foo/bin 97 98 // Get foo/lib/clang/<version>/include 99 llvm::sys::path::append(P, "lib", "clang", CLANG_VERSION_STRING, 100 "include"); 101 } 102 103 return P.str(); 104 } 105 106 class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks 107 { 108 ClangModulesDeclVendor &m_decl_vendor; 109 ClangPersistentVariables &m_persistent_vars; 110 StreamString m_error_stream; 111 bool m_has_errors = false; 112 113 public: 114 LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor, 115 ClangPersistentVariables &persistent_vars) : 116 m_decl_vendor(decl_vendor), 117 m_persistent_vars(persistent_vars) 118 { 119 } 120 121 void 122 moduleImport(SourceLocation import_location, 123 clang::ModuleIdPath path, 124 const clang::Module * /*null*/) override 125 { 126 std::vector<ConstString> string_path; 127 128 for (const std::pair<IdentifierInfo *, SourceLocation> &component : path) 129 { 130 string_path.push_back(ConstString(component.first->getName())); 131 } 132 133 StreamString error_stream; 134 135 ClangModulesDeclVendor::ModuleVector exported_modules; 136 137 if (!m_decl_vendor.AddModule(string_path, &exported_modules, m_error_stream)) 138 { 139 m_has_errors = true; 140 } 141 142 for (ClangModulesDeclVendor::ModuleID module : exported_modules) 143 { 144 m_persistent_vars.AddHandLoadedClangModule(module); 145 } 146 } 147 148 bool hasErrors() 149 { 150 return m_has_errors; 151 } 152 153 const std::string &getErrorString() 154 { 155 return m_error_stream.GetString(); 156 } 157 }; 158 159 //===----------------------------------------------------------------------===// 160 // Implementation of ClangExpressionParser 161 //===----------------------------------------------------------------------===// 162 163 ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope, 164 Expression &expr, 165 bool generate_debug_info) : 166 ExpressionParser (exe_scope, expr, generate_debug_info), 167 m_compiler (), 168 m_code_generator (), 169 m_pp_callbacks(nullptr) 170 { 171 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 172 173 // 1. Create a new compiler instance. 174 m_compiler.reset(new CompilerInstance()); 175 lldb::LanguageType frame_lang = expr.Language(); // defaults to lldb::eLanguageTypeUnknown 176 bool overridden_target_opts = false; 177 lldb_private::LanguageRuntime *lang_rt = nullptr; 178 lldb::TargetSP target_sp; 179 if (exe_scope) 180 target_sp = exe_scope->CalculateTarget(); 181 182 // If the expression is being evaluated in the context of an existing 183 // stack frame, we introspect to see if the language runtime is available. 184 auto frame = exe_scope->CalculateStackFrame(); 185 186 // Make sure the user hasn't provided a preferred execution language 187 // with `expression --language X -- ...` 188 if (frame && frame_lang == lldb::eLanguageTypeUnknown) 189 frame_lang = frame->GetLanguage(); 190 191 if (frame_lang != lldb::eLanguageTypeUnknown) 192 { 193 lang_rt = exe_scope->CalculateProcess()->GetLanguageRuntime(frame_lang); 194 if (log) 195 log->Printf("Frame has language of type %s", Language::GetNameForLanguageType(frame_lang)); 196 } 197 198 // 2. Configure the compiler with a set of default options that are appropriate 199 // for most situations. 200 if (target_sp && target_sp->GetArchitecture().IsValid()) 201 { 202 std::string triple = target_sp->GetArchitecture().GetTriple().str(); 203 m_compiler->getTargetOpts().Triple = triple; 204 if (log) 205 log->Printf("Using %s as the target triple", m_compiler->getTargetOpts().Triple.c_str()); 206 } 207 else 208 { 209 // If we get here we don't have a valid target and just have to guess. 210 // Sometimes this will be ok to just use the host target triple (when we evaluate say "2+3", but other 211 // expressions like breakpoint conditions and other things that _are_ target specific really shouldn't just be 212 // using the host triple. In such a case the language runtime should expose an overridden options set (3), 213 // below. 214 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple(); 215 if (log) 216 log->Printf("Using default target triple of %s", m_compiler->getTargetOpts().Triple.c_str()); 217 } 218 // Now add some special fixes for known architectures: 219 // Any arm32 iOS environment, but not on arm64 220 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos && 221 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos && 222 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) 223 { 224 m_compiler->getTargetOpts().ABI = "apcs-gnu"; 225 } 226 // Supported subsets of x86 227 if (target_sp->GetArchitecture().GetMachine() == llvm::Triple::x86 || 228 target_sp->GetArchitecture().GetMachine() == llvm::Triple::x86_64) 229 { 230 m_compiler->getTargetOpts().Features.push_back("+sse"); 231 m_compiler->getTargetOpts().Features.push_back("+sse2"); 232 } 233 234 // 3. Now allow the runtime to provide custom configuration options for the target. 235 // In this case, a specialized language runtime is available and we can query it for extra options. 236 // For 99% of use cases, this will not be needed and should be provided when basic platform detection is not enough. 237 if (lang_rt) 238 overridden_target_opts = lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts()); 239 240 if (overridden_target_opts) 241 if (log) 242 { 243 log->Debug("Using overridden target options for the expression evaluation"); 244 245 auto opts = m_compiler->getTargetOpts(); 246 log->Debug("Triple: '%s'", opts.Triple.c_str()); 247 log->Debug("CPU: '%s'", opts.CPU.c_str()); 248 log->Debug("FPMath: '%s'", opts.FPMath.c_str()); 249 log->Debug("ABI: '%s'", opts.ABI.c_str()); 250 log->Debug("LinkerVersion: '%s'", opts.LinkerVersion.c_str()); 251 StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten"); 252 StringList::LogDump(log, opts.Features, "Features"); 253 StringList::LogDump(log, opts.Reciprocals, "Reciprocals"); 254 } 255 256 // 4. Create and install the target on the compiler. 257 m_compiler->createDiagnostics(); 258 auto target_info = TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts); 259 if (log) 260 { 261 log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign()); 262 log->Printf("Target datalayout string: '%s'", target_info->getDataLayoutString()); 263 log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str()); 264 log->Printf("Target vector alignment: %d", target_info->getMaxVectorAlign()); 265 } 266 m_compiler->setTarget(target_info); 267 268 assert (m_compiler->hasTarget()); 269 270 // 5. Set language options. 271 lldb::LanguageType language = expr.Language(); 272 273 switch (language) 274 { 275 case lldb::eLanguageTypeC: 276 case lldb::eLanguageTypeC89: 277 case lldb::eLanguageTypeC99: 278 case lldb::eLanguageTypeC11: 279 // FIXME: the following language option is a temporary workaround, 280 // to "ask for C, get C++." 281 // For now, the expression parser must use C++ anytime the 282 // language is a C family language, because the expression parser 283 // uses features of C++ to capture values. 284 m_compiler->getLangOpts().CPlusPlus = true; 285 break; 286 case lldb::eLanguageTypeObjC: 287 m_compiler->getLangOpts().ObjC1 = true; 288 m_compiler->getLangOpts().ObjC2 = true; 289 // FIXME: the following language option is a temporary workaround, 290 // to "ask for ObjC, get ObjC++" (see comment above). 291 m_compiler->getLangOpts().CPlusPlus = true; 292 break; 293 case lldb::eLanguageTypeC_plus_plus: 294 case lldb::eLanguageTypeC_plus_plus_11: 295 case lldb::eLanguageTypeC_plus_plus_14: 296 m_compiler->getLangOpts().CPlusPlus11 = true; 297 m_compiler->getHeaderSearchOpts().UseLibcxx = true; 298 // fall thru ... 299 case lldb::eLanguageTypeC_plus_plus_03: 300 m_compiler->getLangOpts().CPlusPlus = true; 301 // FIXME: the following language option is a temporary workaround, 302 // to "ask for C++, get ObjC++". Apple hopes to remove this requirement 303 // on non-Apple platforms, but for now it is needed. 304 m_compiler->getLangOpts().ObjC1 = true; 305 break; 306 case lldb::eLanguageTypeObjC_plus_plus: 307 case lldb::eLanguageTypeUnknown: 308 default: 309 m_compiler->getLangOpts().ObjC1 = true; 310 m_compiler->getLangOpts().ObjC2 = true; 311 m_compiler->getLangOpts().CPlusPlus = true; 312 m_compiler->getLangOpts().CPlusPlus11 = true; 313 m_compiler->getHeaderSearchOpts().UseLibcxx = true; 314 break; 315 } 316 317 m_compiler->getLangOpts().Bool = true; 318 m_compiler->getLangOpts().WChar = true; 319 m_compiler->getLangOpts().Blocks = true; 320 m_compiler->getLangOpts().DebuggerSupport = true; // Features specifically for debugger clients 321 if (expr.DesiredResultType() == Expression::eResultTypeId) 322 m_compiler->getLangOpts().DebuggerCastResultToId = true; 323 324 m_compiler->getLangOpts().CharIsSigned = 325 ArchSpec(m_compiler->getTargetOpts().Triple.c_str()).CharIsSignedByDefault(); 326 327 // Spell checking is a nice feature, but it ends up completing a 328 // lot of types that we didn't strictly speaking need to complete. 329 // As a result, we spend a long time parsing and importing debug 330 // information. 331 m_compiler->getLangOpts().SpellChecking = false; 332 333 lldb::ProcessSP process_sp; 334 if (exe_scope) 335 process_sp = exe_scope->CalculateProcess(); 336 337 if (process_sp && m_compiler->getLangOpts().ObjC1) 338 { 339 if (process_sp->GetObjCLanguageRuntime()) 340 { 341 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() == ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2) 342 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7)); 343 else 344 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX, VersionTuple(10, 7)); 345 346 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing()) 347 m_compiler->getLangOpts().DebuggerObjCLiteral = true; 348 } 349 } 350 351 m_compiler->getLangOpts().ThreadsafeStatics = false; 352 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access 353 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name 354 355 // Set CodeGen options 356 m_compiler->getCodeGenOpts().EmitDeclMetadata = true; 357 m_compiler->getCodeGenOpts().InstrumentFunctions = false; 358 m_compiler->getCodeGenOpts().DisableFPElim = true; 359 m_compiler->getCodeGenOpts().OmitLeafFramePointer = false; 360 if (generate_debug_info) 361 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo); 362 else 363 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo); 364 365 // Disable some warnings. 366 m_compiler->getDiagnostics().setSeverityForGroup(clang::diag::Flavor::WarningOrError, 367 "unused-value", clang::diag::Severity::Ignored, SourceLocation()); 368 m_compiler->getDiagnostics().setSeverityForGroup(clang::diag::Flavor::WarningOrError, 369 "odr", clang::diag::Severity::Ignored, SourceLocation()); 370 371 // Inform the target of the language options 372 // 373 // FIXME: We shouldn't need to do this, the target should be immutable once 374 // created. This complexity should be lifted elsewhere. 375 m_compiler->getTarget().adjust(m_compiler->getLangOpts()); 376 377 // 6. Set up the diagnostic buffer for reporting errors 378 379 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer); 380 381 // 7. Set up the source management objects inside the compiler 382 383 clang::FileSystemOptions file_system_options; 384 m_file_manager.reset(new clang::FileManager(file_system_options)); 385 386 if (!m_compiler->hasSourceManager()) 387 m_compiler->createSourceManager(*m_file_manager.get()); 388 389 m_compiler->createFileManager(); 390 m_compiler->createPreprocessor(TU_Complete); 391 392 if (ClangModulesDeclVendor *decl_vendor = target_sp->GetClangModulesDeclVendor()) 393 { 394 ClangPersistentVariables *clang_persistent_vars = llvm::cast<ClangPersistentVariables>(target_sp->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC)); 395 std::unique_ptr<PPCallbacks> pp_callbacks(new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars)); 396 m_pp_callbacks = static_cast<LLDBPreprocessorCallbacks*>(pp_callbacks.get()); 397 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks)); 398 } 399 400 // 8. Most of this we get from the CompilerInstance, but we 401 // also want to give the context an ExternalASTSource. 402 m_selector_table.reset(new SelectorTable()); 403 m_builtin_context.reset(new Builtin::Context()); 404 405 std::unique_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(), 406 m_compiler->getSourceManager(), 407 m_compiler->getPreprocessor().getIdentifierTable(), 408 *m_selector_table.get(), 409 *m_builtin_context.get())); 410 411 ast_context->InitBuiltinTypes(m_compiler->getTarget()); 412 413 ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); 414 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap(); 415 416 if (decl_map) 417 { 418 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source(decl_map->CreateProxy()); 419 decl_map->InstallASTContext(ast_context.get()); 420 ast_context->setExternalSource(ast_source); 421 } 422 423 m_ast_context.reset(new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str())); 424 m_ast_context->setASTContext(ast_context.get()); 425 m_compiler->setASTContext(ast_context.release()); 426 427 std::string module_name("$__lldb_module"); 428 429 m_llvm_context.reset(new LLVMContext()); 430 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(), 431 module_name, 432 m_compiler->getHeaderSearchOpts(), 433 m_compiler->getPreprocessorOpts(), 434 m_compiler->getCodeGenOpts(), 435 *m_llvm_context)); 436 } 437 438 ClangExpressionParser::~ClangExpressionParser() 439 { 440 } 441 442 unsigned 443 ClangExpressionParser::Parse (Stream &stream) 444 { 445 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient()); 446 447 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics()); 448 449 const char *expr_text = m_expr.Text(); 450 451 clang::SourceManager &SourceMgr = m_compiler->getSourceManager(); 452 bool created_main_file = false; 453 if (m_compiler->getCodeGenOpts().getDebugInfo() == codegenoptions::FullDebugInfo) 454 { 455 std::string temp_source_path; 456 457 int temp_fd = -1; 458 llvm::SmallString<PATH_MAX> result_path; 459 FileSpec tmpdir_file_spec; 460 if (HostInfo::GetLLDBPath(lldb::ePathTypeLLDBTempSystemDir, tmpdir_file_spec)) 461 { 462 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr"); 463 temp_source_path = tmpdir_file_spec.GetPath(); 464 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path); 465 } 466 else 467 { 468 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path); 469 } 470 471 if (temp_fd != -1) 472 { 473 lldb_private::File file (temp_fd, true); 474 const size_t expr_text_len = strlen(expr_text); 475 size_t bytes_written = expr_text_len; 476 if (file.Write(expr_text, bytes_written).Success()) 477 { 478 if (bytes_written == expr_text_len) 479 { 480 file.Close(); 481 SourceMgr.setMainFileID(SourceMgr.createFileID( 482 m_file_manager->getFile(result_path), 483 SourceLocation(), SrcMgr::C_User)); 484 created_main_file = true; 485 } 486 } 487 } 488 } 489 490 if (!created_main_file) 491 { 492 std::unique_ptr<MemoryBuffer> memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__); 493 SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(memory_buffer))); 494 } 495 496 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor()); 497 498 ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); 499 500 ASTConsumer *ast_transformer = type_system_helper->ASTTransformer(m_code_generator.get()); 501 502 if (ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap()) 503 decl_map->InstallCodeGenerator(m_code_generator.get()); 504 505 if (ast_transformer) 506 { 507 ast_transformer->Initialize(m_compiler->getASTContext()); 508 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext()); 509 } 510 else 511 { 512 m_code_generator->Initialize(m_compiler->getASTContext()); 513 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext()); 514 } 515 516 diag_buf->EndSourceFile(); 517 518 TextDiagnosticBuffer::const_iterator diag_iterator; 519 520 int num_errors = 0; 521 522 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) 523 { 524 num_errors++; 525 526 stream.PutCString(m_pp_callbacks->getErrorString().c_str()); 527 } 528 529 for (diag_iterator = diag_buf->warn_begin(); 530 diag_iterator != diag_buf->warn_end(); 531 ++diag_iterator) 532 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str()); 533 534 for (diag_iterator = diag_buf->err_begin(); 535 diag_iterator != diag_buf->err_end(); 536 ++diag_iterator) 537 { 538 num_errors++; 539 stream.Printf("error: %s\n", (*diag_iterator).second.c_str()); 540 } 541 542 for (diag_iterator = diag_buf->note_begin(); 543 diag_iterator != diag_buf->note_end(); 544 ++diag_iterator) 545 stream.Printf("note: %s\n", (*diag_iterator).second.c_str()); 546 547 if (!num_errors) 548 { 549 if (type_system_helper->DeclMap() && !type_system_helper->DeclMap()->ResolveUnknownTypes()) 550 { 551 stream.Printf("error: Couldn't infer the type of a variable\n"); 552 num_errors++; 553 } 554 } 555 556 return num_errors; 557 } 558 559 static bool FindFunctionInModule (ConstString &mangled_name, 560 llvm::Module *module, 561 const char *orig_name) 562 { 563 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end(); 564 fi != fe; 565 ++fi) 566 { 567 if (fi->getName().str().find(orig_name) != std::string::npos) 568 { 569 mangled_name.SetCString(fi->getName().str().c_str()); 570 return true; 571 } 572 } 573 574 return false; 575 } 576 577 Error 578 ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr, 579 lldb::addr_t &func_end, 580 lldb::IRExecutionUnitSP &execution_unit_sp, 581 ExecutionContext &exe_ctx, 582 bool &can_interpret, 583 ExecutionPolicy execution_policy) 584 { 585 func_addr = LLDB_INVALID_ADDRESS; 586 func_end = LLDB_INVALID_ADDRESS; 587 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 588 589 Error err; 590 591 std::unique_ptr<llvm::Module> llvm_module_ap (m_code_generator->ReleaseModule()); 592 593 if (!llvm_module_ap.get()) 594 { 595 err.SetErrorToGenericError(); 596 err.SetErrorString("IR doesn't contain a module"); 597 return err; 598 } 599 600 // Find the actual name of the function (it's often mangled somehow) 601 602 ConstString function_name; 603 604 if (!FindFunctionInModule(function_name, llvm_module_ap.get(), m_expr.FunctionName())) 605 { 606 err.SetErrorToGenericError(); 607 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName()); 608 return err; 609 } 610 else 611 { 612 if (log) 613 log->Printf("Found function %s for %s", function_name.AsCString(), m_expr.FunctionName()); 614 } 615 616 execution_unit_sp.reset(new IRExecutionUnit (m_llvm_context, // handed off here 617 llvm_module_ap, // handed off here 618 function_name, 619 exe_ctx.GetTargetSP(), 620 m_compiler->getTargetOpts().Features)); 621 622 ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); 623 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap(); // result can be NULL 624 625 if (decl_map) 626 { 627 Stream *error_stream = NULL; 628 Target *target = exe_ctx.GetTargetPtr(); 629 if (target) 630 error_stream = target->GetDebugger().GetErrorFile().get(); 631 632 IRForTarget ir_for_target(decl_map, 633 m_expr.NeedsVariableResolution(), 634 *execution_unit_sp, 635 error_stream, 636 function_name.AsCString()); 637 638 bool ir_can_run = ir_for_target.runOnModule(*execution_unit_sp->GetModule()); 639 640 Error interpret_error; 641 Process *process = exe_ctx.GetProcessPtr(); 642 643 bool interpret_function_calls = !process ? false : process->CanInterpretFunctionCalls(); 644 can_interpret = IRInterpreter::CanInterpret(*execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(), interpret_error, interpret_function_calls); 645 646 647 if (!ir_can_run) 648 { 649 err.SetErrorString("The expression could not be prepared to run in the target"); 650 return err; 651 } 652 653 if (!can_interpret && execution_policy == eExecutionPolicyNever) 654 { 655 err.SetErrorStringWithFormat("Can't run the expression locally: %s", interpret_error.AsCString()); 656 return err; 657 } 658 659 if (!process && execution_policy == eExecutionPolicyAlways) 660 { 661 err.SetErrorString("Expression needed to run in the target, but the target can't be run"); 662 return err; 663 } 664 665 if (execution_policy == eExecutionPolicyAlways || !can_interpret) 666 { 667 if (m_expr.NeedsValidation() && process) 668 { 669 if (!process->GetDynamicCheckers()) 670 { 671 DynamicCheckerFunctions *dynamic_checkers = new DynamicCheckerFunctions(); 672 673 StreamString install_errors; 674 675 if (!dynamic_checkers->Install(install_errors, exe_ctx)) 676 { 677 if (install_errors.GetString().empty()) 678 err.SetErrorString ("couldn't install checkers, unknown error"); 679 else 680 err.SetErrorString (install_errors.GetString().c_str()); 681 682 return err; 683 } 684 685 process->SetDynamicCheckers(dynamic_checkers); 686 687 if (log) 688 log->Printf("== [ClangUserExpression::Evaluate] Finished installing dynamic checkers =="); 689 } 690 691 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), function_name.AsCString()); 692 693 if (!ir_dynamic_checks.runOnModule(*execution_unit_sp->GetModule())) 694 { 695 err.SetErrorToGenericError(); 696 err.SetErrorString("Couldn't add dynamic checks to the expression"); 697 return err; 698 } 699 } 700 701 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end); 702 } 703 } 704 else 705 { 706 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end); 707 } 708 709 return err; 710 } 711