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