blob: 50518e78e732287c3f98f9bcfd5a259732c4fa3f [file] [log] [blame]
Sean Callanan65dafa82010-08-27 01:01:44 +00001//===-- 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#include "lldb/Expression/ClangExpressionParser.h"
11
12#include "lldb/Core/ArchSpec.h"
13#include "lldb/Core/DataBufferHeap.h"
Sean Callanan97c924e2011-01-27 01:07:04 +000014#include "lldb/Core/Debugger.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000015#include "lldb/Core/Disassembler.h"
16#include "lldb/Core/Stream.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000017#include "lldb/Core/StreamString.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000018#include "lldb/Expression/ClangASTSource.h"
19#include "lldb/Expression/ClangExpression.h"
Sean Callananfb3058e2011-05-12 23:54:16 +000020#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000021#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000022#include "lldb/Expression/RecordingMemoryManager.h"
23#include "lldb/Target/ExecutionContext.h"
Sean Callananc7674af2011-01-17 23:42:46 +000024#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000025#include "lldb/Target/Process.h"
26#include "lldb/Target/Target.h"
27
28#include "clang/AST/ASTContext.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/Basic/FileManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/Version.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000033#include "clang/CodeGen/CodeGenAction.h"
34#include "clang/CodeGen/ModuleBuilder.h"
35#include "clang/Driver/CC1Options.h"
36#include "clang/Driver/OptTable.h"
37#include "clang/Frontend/CompilerInstance.h"
38#include "clang/Frontend/CompilerInvocation.h"
39#include "clang/Frontend/FrontendActions.h"
40#include "clang/Frontend/FrontendDiagnostic.h"
41#include "clang/Frontend/FrontendPluginRegistry.h"
42#include "clang/Frontend/TextDiagnosticBuffer.h"
43#include "clang/Frontend/TextDiagnosticPrinter.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000044#include "clang/Lex/Preprocessor.h"
Sean Callanan47a5c4c2010-09-23 03:01:22 +000045#include "clang/Parse/ParseAST.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000046#include "clang/Rewrite/FrontendActions.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000047#include "clang/Sema/SemaConsumer.h"
Sean Callanan279584c2011-03-15 00:17:19 +000048#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000049
50#include "llvm/ADT/StringRef.h"
51#include "llvm/ExecutionEngine/ExecutionEngine.h"
Sean Callananc1535182011-10-07 23:18:13 +000052#include "llvm/Support/TargetSelect.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000053
Peter Collingbournec3f55732011-06-03 20:40:12 +000054#if !defined(__APPLE__)
55#define USE_STANDARD_JIT
56#endif
57
Greg Clayton2f085c62011-05-15 01:25:55 +000058#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +000059#include "llvm/ExecutionEngine/JIT.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000060#else
61#include "llvm/ExecutionEngine/MCJIT.h"
62#endif
Sean Callanan65dafa82010-08-27 01:01:44 +000063#include "llvm/LLVMContext.h"
Sean Callanan279584c2011-03-15 00:17:19 +000064#include "llvm/Module.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000065#include "llvm/Support/ErrorHandling.h"
66#include "llvm/Support/MemoryBuffer.h"
Greg Clayton22defe82010-12-02 23:20:03 +000067#include "llvm/Support/DynamicLibrary.h"
68#include "llvm/Support/Host.h"
69#include "llvm/Support/Signals.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000070
71using namespace clang;
72using namespace llvm;
73using namespace lldb_private;
74
75//===----------------------------------------------------------------------===//
76// Utility Methods for Clang
77//===----------------------------------------------------------------------===//
78
79std::string GetBuiltinIncludePath(const char *Argv0) {
80 llvm::sys::Path P =
81 llvm::sys::Path::GetMainExecutable(Argv0,
82 (void*)(intptr_t) GetBuiltinIncludePath);
83
84 if (!P.isEmpty()) {
85 P.eraseComponent(); // Remove /clang from foo/bin/clang
86 P.eraseComponent(); // Remove /bin from foo/bin
87
88 // Get foo/lib/clang/<version>/include
89 P.appendComponent("lib");
90 P.appendComponent("clang");
91 P.appendComponent(CLANG_VERSION_STRING);
92 P.appendComponent("include");
93 }
94
95 return P.str();
96}
97
98
99//===----------------------------------------------------------------------===//
100// Main driver for Clang
101//===----------------------------------------------------------------------===//
102
103static void LLVMErrorHandler(void *UserData, const std::string &Message) {
Sean Callananc1535182011-10-07 23:18:13 +0000104 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
Sean Callanan65dafa82010-08-27 01:01:44 +0000105
106 Diags.Report(diag::err_fe_error_backend) << Message;
107
108 // We cannot recover from llvm errors.
Sean Callananc1535182011-10-07 23:18:13 +0000109 assert(0);
Sean Callanan65dafa82010-08-27 01:01:44 +0000110}
111
112static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
113 using namespace clang::frontend;
114
115 switch (CI.getFrontendOpts().ProgramAction) {
116 default:
117 llvm_unreachable("Invalid program action!");
118
119 case ASTDump: return new ASTDumpAction();
120 case ASTPrint: return new ASTPrintAction();
Sean Callanan279584c2011-03-15 00:17:19 +0000121 case ASTDumpXML: return new ASTDumpXMLAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000122 case ASTView: return new ASTViewAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000123 case DumpRawTokens: return new DumpRawTokensAction();
124 case DumpTokens: return new DumpTokensAction();
125 case EmitAssembly: return new EmitAssemblyAction();
126 case EmitBC: return new EmitBCAction();
127 case EmitHTML: return new HTMLPrintAction();
128 case EmitLLVM: return new EmitLLVMAction();
129 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
130 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
131 case EmitObj: return new EmitObjAction();
132 case FixIt: return new FixItAction();
Sean Callananc1535182011-10-07 23:18:13 +0000133 case GeneratePCH: return new GeneratePCHAction(false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000134 case GeneratePTH: return new GeneratePTHAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000135 case InitOnly: return new InitOnlyAction();
136 case ParseSyntaxOnly: return new SyntaxOnlyAction();
137
138 case PluginAction: {
139 for (FrontendPluginRegistry::iterator it =
140 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
141 it != ie; ++it) {
142 if (it->getName() == CI.getFrontendOpts().ActionName) {
143 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
144 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
145 return 0;
146 return P.take();
147 }
148 }
149
150 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
151 << CI.getFrontendOpts().ActionName;
152 return 0;
153 }
154
155 case PrintDeclContext: return new DeclContextPrintAction();
156 case PrintPreamble: return new PrintPreambleAction();
157 case PrintPreprocessedInput: return new PrintPreprocessedAction();
158 case RewriteMacros: return new RewriteMacrosAction();
159 case RewriteObjC: return new RewriteObjCAction();
160 case RewriteTest: return new RewriteTestAction();
Sean Callananad293092011-01-18 23:32:05 +0000161 //case RunAnalysis: return new AnalysisAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000162 case RunPreprocessorOnly: return new PreprocessOnlyAction();
163 }
164}
165
166static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
167 // Create the underlying action.
168 FrontendAction *Act = CreateFrontendBaseAction(CI);
169 if (!Act)
170 return 0;
171
172 // If there are any AST files to merge, create a frontend action
173 // adaptor to perform the merge.
174 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
175 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
176 CI.getFrontendOpts().ASTMergeFiles.size());
177
178 return Act;
179}
180
181//===----------------------------------------------------------------------===//
182// Implementation of ClangExpressionParser
183//===----------------------------------------------------------------------===//
184
Greg Clayton395fc332011-02-15 21:59:32 +0000185ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
186 ClangExpression &expr) :
187 m_expr (expr),
Sean Callanan65dafa82010-08-27 01:01:44 +0000188 m_compiler (),
189 m_code_generator (NULL),
190 m_execution_engine (),
191 m_jitted_functions ()
192{
193 // Initialize targets first, so that --version shows registered targets.
194 static struct InitializeLLVM {
195 InitializeLLVM() {
196 llvm::InitializeAllTargets();
197 llvm::InitializeAllAsmPrinters();
Sean Callanan9b6898f2011-07-30 02:42:06 +0000198 llvm::InitializeAllTargetMCs();
Sean Callanan65dafa82010-08-27 01:01:44 +0000199 }
200 } InitializeLLVM;
Greg Clayton395fc332011-02-15 21:59:32 +0000201
Sean Callanan65dafa82010-08-27 01:01:44 +0000202 // 1. Create a new compiler instance.
203 m_compiler.reset(new CompilerInstance());
Sean Callanan65dafa82010-08-27 01:01:44 +0000204
205 // 2. Set options.
206
207 // Parse expressions as Objective C++ regardless of context.
208 // Our hook into Clang's lookup mechanism only works in C++.
209 m_compiler->getLangOpts().CPlusPlus = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000210
211 // Setup objective C
Sean Callanan65dafa82010-08-27 01:01:44 +0000212 m_compiler->getLangOpts().ObjC1 = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000213 m_compiler->getLangOpts().ObjC2 = true;
Sean Callananc7674af2011-01-17 23:42:46 +0000214
Greg Clayton395fc332011-02-15 21:59:32 +0000215 Process *process = NULL;
216 if (exe_scope)
217 process = exe_scope->CalculateProcess();
218
Sean Callananc7674af2011-01-17 23:42:46 +0000219 if (process)
220 {
221 if (process->GetObjCLanguageRuntime())
222 {
Greg Claytonb3448432011-03-24 21:19:54 +0000223 if (process->GetObjCLanguageRuntime()->GetRuntimeVersion() == eAppleObjC_V2)
Sean Callananc7674af2011-01-17 23:42:46 +0000224 {
225 m_compiler->getLangOpts().ObjCNonFragileABI = true; // NOT i386
226 m_compiler->getLangOpts().ObjCNonFragileABI2 = true; // NOT i386
227 }
228 }
229 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000230
Sean Callanan65dafa82010-08-27 01:01:44 +0000231 m_compiler->getLangOpts().ThreadsafeStatics = false;
232 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
233 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
Sean Callanan1cbfabd2011-10-21 23:40:00 +0000234 m_compiler->getLangOpts().DebuggerSupport = true; // Features specifically for debugger clients
Sean Callanan65dafa82010-08-27 01:01:44 +0000235
236 // Set CodeGen options
237 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
238 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
239
240 // Disable some warnings.
241 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
242
243 // Set the target triple.
Greg Clayton395fc332011-02-15 21:59:32 +0000244 Target *target = NULL;
245 if (exe_scope)
246 target = exe_scope->CalculateTarget();
247
248 // TODO: figure out what to really do when we don't have a valid target.
249 // Sometimes this will be ok to just use the host target triple (when we
250 // evaluate say "2+3", but other expressions like breakpoint conditions
251 // and other things that _are_ target specific really shouldn't just be
252 // using the host triple. This needs to be fixed in a better way.
253 if (target && target->GetArchitecture().IsValid())
Sean Callanan2a8c3382011-04-14 02:01:31 +0000254 {
255 std::string triple = target->GetArchitecture().GetTriple().str();
256
257 int dash_count = 0;
Johnny Chen2bc9eb32011-07-19 19:48:13 +0000258 for (size_t i = 0; i < triple.size(); ++i)
Sean Callanan2a8c3382011-04-14 02:01:31 +0000259 {
260 if (triple[i] == '-')
261 dash_count++;
262 if (dash_count == 3)
263 {
264 triple.resize(i);
265 break;
266 }
267 }
268
269 m_compiler->getTargetOpts().Triple = triple;
270 }
Greg Clayton395fc332011-02-15 21:59:32 +0000271 else
Sean Callanan2a8c3382011-04-14 02:01:31 +0000272 {
Greg Clayton395fc332011-02-15 21:59:32 +0000273 m_compiler->getTargetOpts().Triple = llvm::sys::getHostTriple();
Sean Callanan2a8c3382011-04-14 02:01:31 +0000274 }
275
Sean Callanan65dafa82010-08-27 01:01:44 +0000276 // 3. Set up various important bits of infrastructure.
277 m_compiler->createDiagnostics(0, 0);
278
279 // Create the target instance.
280 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
281 m_compiler->getTargetOpts()));
282
283 assert (m_compiler->hasTarget());
284
285 // Inform the target of the language options
286 //
287 // FIXME: We shouldn't need to do this, the target should be immutable once
288 // created. This complexity should be lifted elsewhere.
289 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
290
291 // 4. Set up the diagnostic buffer for reporting errors
292
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000293 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000294
295 // 5. Set up the source management objects inside the compiler
296
Greg Clayton22defe82010-12-02 23:20:03 +0000297 clang::FileSystemOptions file_system_options;
298 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000299
Sean Callanan65dafa82010-08-27 01:01:44 +0000300 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000301 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000302
303 m_compiler->createFileManager();
304 m_compiler->createPreprocessor();
305
306 // 6. Most of this we get from the CompilerInstance, but we
307 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000308 m_selector_table.reset(new SelectorTable());
Sean Callananc1535182011-10-07 23:18:13 +0000309 m_builtin_context.reset(new Builtin::Context());
Sean Callanan65dafa82010-08-27 01:01:44 +0000310
311 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
312 m_compiler->getSourceManager(),
Sean Callananc1535182011-10-07 23:18:13 +0000313 &m_compiler->getTarget(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000314 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000315 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000316 *m_builtin_context.get(),
317 0));
318
319 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
320
321 if (decl_map)
322 {
Sean Callananf76afff2011-10-28 23:38:38 +0000323 llvm::OwningPtr<clang::ExternalASTSource> ast_source(decl_map->CreateProxy());
324 decl_map->InstallASTContext(ast_context.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000325 ast_context->setExternalSource(ast_source);
326 }
327
328 m_compiler->setASTContext(ast_context.release());
329
Greg Clayton8de27c72010-10-15 22:48:33 +0000330 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000331
Sean Callanan279584c2011-03-15 00:17:19 +0000332 m_llvm_context.reset(new LLVMContext());
Sean Callanan65dafa82010-08-27 01:01:44 +0000333 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
334 module_name,
335 m_compiler->getCodeGenOpts(),
Sean Callanan279584c2011-03-15 00:17:19 +0000336 *m_llvm_context));
Sean Callanan65dafa82010-08-27 01:01:44 +0000337}
338
339ClangExpressionParser::~ClangExpressionParser()
340{
341}
342
343unsigned
344ClangExpressionParser::Parse (Stream &stream)
345{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000346 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
347
348 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000349
350 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
351 FileID memory_buffer_file_id = m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
352
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000353 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000354
355 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
356
357 if (ast_transformer)
358 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
359 else
360 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
361
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000362 diag_buf->EndSourceFile();
Sean Callananfb3058e2011-05-12 23:54:16 +0000363
Sean Callanan65dafa82010-08-27 01:01:44 +0000364 TextDiagnosticBuffer::const_iterator diag_iterator;
365
366 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000367
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000368 for (diag_iterator = diag_buf->warn_begin();
369 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000370 ++diag_iterator)
371 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
372
373 num_errors = 0;
374
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000375 for (diag_iterator = diag_buf->err_begin();
376 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000377 ++diag_iterator)
378 {
379 num_errors++;
380 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
381 }
382
Sean Callanan7617c292010-11-01 20:28:09 +0000383 for (diag_iterator = diag_buf->note_begin();
384 diag_iterator != diag_buf->note_end();
385 ++diag_iterator)
386 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
387
Sean Callananfb3058e2011-05-12 23:54:16 +0000388 if (!num_errors)
389 {
390 if (m_expr.DeclMap() && !m_expr.DeclMap()->ResolveUnknownTypes())
391 {
392 stream.Printf("error: Couldn't infer the type of a variable\n");
393 num_errors++;
394 }
395 }
396
Sean Callanan65dafa82010-08-27 01:01:44 +0000397 return num_errors;
398}
399
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000400static bool FindFunctionInModule (std::string &mangled_name,
401 llvm::Module *module,
402 const char *orig_name)
403{
404 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
405 fi != fe;
406 ++fi)
407 {
408 if (fi->getName().str().find(orig_name) != std::string::npos)
409 {
410 mangled_name = fi->getName().str();
411 return true;
412 }
413 }
414
415 return false;
416}
417
Sean Callanan65dafa82010-08-27 01:01:44 +0000418Error
Sean Callanan47dc4572011-09-15 02:13:07 +0000419ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_allocation_addr,
420 lldb::addr_t &func_addr,
421 lldb::addr_t &func_end,
422 ExecutionContext &exe_ctx,
423 IRForTarget::StaticDataAllocator *data_allocator,
424 bool &evaluated_statically,
425 lldb::ClangExpressionVariableSP &const_result,
426 ExecutionPolicy execution_policy)
Sean Callanan65dafa82010-08-27 01:01:44 +0000427{
Greg Claytond0882d02011-01-19 23:00:49 +0000428 func_allocation_addr = LLDB_INVALID_ADDRESS;
429 func_addr = LLDB_INVALID_ADDRESS;
430 func_end = LLDB_INVALID_ADDRESS;
Greg Claytone005f2c2010-11-06 01:53:30 +0000431 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000432
Sean Callanan65dafa82010-08-27 01:01:44 +0000433 Error err;
434
435 llvm::Module *module = m_code_generator->ReleaseModule();
436
437 if (!module)
438 {
439 err.SetErrorToGenericError();
440 err.SetErrorString("IR doesn't contain a module");
441 return err;
442 }
443
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000444 // Find the actual name of the function (it's often mangled somehow)
445
446 std::string function_name;
447
448 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
449 {
450 err.SetErrorToGenericError();
451 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
452 return err;
453 }
454 else
455 {
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000456 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000457 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
458 }
459
Sean Callanan65dafa82010-08-27 01:01:44 +0000460 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
461
462 if (decl_map)
463 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000464 Stream *error_stream = NULL;
Greg Clayton567e7f32011-09-22 04:58:26 +0000465 Target *target = exe_ctx.GetTargetPtr();
466 if (target)
467 error_stream = &target->GetDebugger().GetErrorStream();
Sean Callanan97c924e2011-01-27 01:07:04 +0000468
Sean Callanan47dc4572011-09-15 02:13:07 +0000469 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000470 m_expr.NeedsVariableResolution(),
Sean Callanan47dc4572011-09-15 02:13:07 +0000471 execution_policy,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000472 const_result,
Sean Callananc0492742011-05-23 21:40:23 +0000473 data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +0000474 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000475 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000476
477 if (!ir_for_target.runOnModule(*module))
478 {
479 err.SetErrorToGenericError();
Sean Callanan47dc4572011-09-15 02:13:07 +0000480 err.SetErrorString("Couldn't prepare the expression for execution in the target");
Sean Callanan65dafa82010-08-27 01:01:44 +0000481 return err;
482 }
Sean Callananf18d91c2010-09-01 00:58:00 +0000483
Sean Callanan47dc4572011-09-15 02:13:07 +0000484 if (execution_policy != eExecutionPolicyAlways && ir_for_target.interpretSuccess())
Sean Callanan696cf5f2011-05-07 01:06:41 +0000485 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000486 evaluated_statically = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000487 err.Clear();
488 return err;
489 }
490
Greg Clayton567e7f32011-09-22 04:58:26 +0000491 Process *process = exe_ctx.GetProcessPtr();
492
493 if (!process || execution_policy == eExecutionPolicyNever)
Sean Callanan47dc4572011-09-15 02:13:07 +0000494 {
495 err.SetErrorToGenericError();
496 err.SetErrorString("Execution needed to run in the target, but the target can't be run");
497 return err;
498 }
499
Sean Callanan6cf6c472011-09-20 23:01:51 +0000500 if (execution_policy != eExecutionPolicyNever &&
501 m_expr.NeedsValidation() &&
Greg Clayton567e7f32011-09-22 04:58:26 +0000502 process)
Sean Callananf18d91c2010-09-01 00:58:00 +0000503 {
Greg Clayton567e7f32011-09-22 04:58:26 +0000504 if (!process->GetDynamicCheckers())
Sean Callanan6cf6c472011-09-20 23:01:51 +0000505 {
506 DynamicCheckerFunctions *dynamic_checkers = new DynamicCheckerFunctions();
507
508 StreamString install_errors;
509
510 if (!dynamic_checkers->Install(install_errors, exe_ctx))
511 {
512 if (install_errors.GetString().empty())
513 err.SetErrorString ("couldn't install checkers, unknown error");
514 else
515 err.SetErrorString (install_errors.GetString().c_str());
516
517 return err;
518 }
519
Greg Clayton567e7f32011-09-22 04:58:26 +0000520 process->SetDynamicCheckers(dynamic_checkers);
Sean Callanan6cf6c472011-09-20 23:01:51 +0000521
522 if (log)
523 log->Printf("== [ClangUserExpression::Evaluate] Finished installing dynamic checkers ==");
524 }
525
Greg Clayton567e7f32011-09-22 04:58:26 +0000526 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000527
528 if (!ir_dynamic_checks.runOnModule(*module))
529 {
530 err.SetErrorToGenericError();
531 err.SetErrorString("Couldn't add dynamic checks to the expression");
532 return err;
533 }
534 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000535 }
536
Greg Claytond0882d02011-01-19 23:00:49 +0000537 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
538 // below so we don't need to free it.
539 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000540
541 std::string error_string;
Sean Callanan9b6898f2011-07-30 02:42:06 +0000542
Greg Clayton2f085c62011-05-15 01:25:55 +0000543#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +0000544 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
545 &error_string,
Greg Claytond0882d02011-01-19 23:00:49 +0000546 jit_memory_manager,
Sean Callananc2c6f772010-10-26 00:31:56 +0000547 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000548 true,
Peter Collingbournec4d4fb52011-07-30 22:42:24 +0000549 Reloc::Default,
Sean Callanan65dafa82010-08-27 01:01:44 +0000550 CodeModel::Small));
Greg Clayton2f085c62011-05-15 01:25:55 +0000551#else
552 EngineBuilder builder(module);
553 builder.setEngineKind(EngineKind::JIT)
554 .setErrorStr(&error_string)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000555 .setRelocationModel(llvm::Reloc::PIC_)
Greg Clayton2f085c62011-05-15 01:25:55 +0000556 .setJITMemoryManager(jit_memory_manager)
557 .setOptLevel(CodeGenOpt::Less)
558 .setAllocateGVsWithCode(true)
559 .setCodeModel(CodeModel::Small)
Sean Callanan16b53ab2011-10-12 00:12:34 +0000560 .setUseMCJIT(true);
Greg Clayton2f085c62011-05-15 01:25:55 +0000561 m_execution_engine.reset(builder.create());
562#endif
Sean Callanan9ac3a962010-11-02 23:20:00 +0000563
Sean Callanan65dafa82010-08-27 01:01:44 +0000564 if (!m_execution_engine.get())
565 {
566 err.SetErrorToGenericError();
567 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
568 return err;
569 }
570
571 m_execution_engine->DisableLazyCompilation();
572
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000573 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000574
575 // We don't actually need the function pointer here, this just forces it to get resolved.
576
577 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
578
579 // Errors usually cause failures in the JIT, but if we're lucky we get here.
580
581 if (!fun_ptr)
582 {
583 err.SetErrorToGenericError();
584 err.SetErrorString("Couldn't JIT the function");
585 return err;
586 }
587
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000588 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000589
Greg Clayton567e7f32011-09-22 04:58:26 +0000590
591 Process *process = exe_ctx.GetProcessPtr();
592 if (process == NULL)
Sean Callanan65dafa82010-08-27 01:01:44 +0000593 {
594 err.SetErrorToGenericError();
595 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
596 return err;
597 }
598
599 // Look over the regions allocated for the function compiled. The JIT
600 // tries to allocate the functions & stubs close together, so we should try to
601 // write them that way too...
602 // For now I only write functions with no stubs, globals, exception tables,
603 // etc. So I only need to write the functions.
604
605 size_t alloc_size = 0;
606
Greg Claytond0882d02011-01-19 23:00:49 +0000607 std::map<uint8_t *, uint8_t *>::iterator fun_pos = jit_memory_manager->m_functions.begin();
608 std::map<uint8_t *, uint8_t *>::iterator fun_end = jit_memory_manager->m_functions.end();
Greg Clayton9d2b3212011-05-15 23:56:52 +0000609
Sean Callanan65dafa82010-08-27 01:01:44 +0000610 for (; fun_pos != fun_end; ++fun_pos)
Greg Clayton9d2b3212011-05-15 23:56:52 +0000611 {
612 size_t mem_size = fun_pos->second - fun_pos->first;
613 if (log)
614 log->Printf ("JIT memory: [%p - %p) size = %zu", fun_pos->first, fun_pos->second, mem_size);
615 alloc_size += mem_size;
616 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000617
618 Error alloc_error;
Greg Clayton567e7f32011-09-22 04:58:26 +0000619 func_allocation_addr = process->AllocateMemory (alloc_size,
Greg Claytond0882d02011-01-19 23:00:49 +0000620 lldb::ePermissionsReadable|lldb::ePermissionsExecutable,
621 alloc_error);
Sean Callanan65dafa82010-08-27 01:01:44 +0000622
Greg Claytond0882d02011-01-19 23:00:49 +0000623 if (func_allocation_addr == LLDB_INVALID_ADDRESS)
Sean Callanan65dafa82010-08-27 01:01:44 +0000624 {
625 err.SetErrorToGenericError();
626 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
627 return err;
628 }
629
Greg Claytond0882d02011-01-19 23:00:49 +0000630 lldb::addr_t cursor = func_allocation_addr;
Sean Callanan65dafa82010-08-27 01:01:44 +0000631
Greg Claytond0882d02011-01-19 23:00:49 +0000632 for (fun_pos = jit_memory_manager->m_functions.begin(); fun_pos != fun_end; fun_pos++)
Sean Callanan65dafa82010-08-27 01:01:44 +0000633 {
634 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
635 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
636 size_t size = lend - lstart;
637
638 Error write_error;
639
Greg Clayton567e7f32011-09-22 04:58:26 +0000640 if (process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
Sean Callanan65dafa82010-08-27 01:01:44 +0000641 {
642 err.SetErrorToGenericError();
Greg Claytonc0fa5332011-05-22 22:46:53 +0000643 err.SetErrorStringWithFormat("Couldn't copy JIT code for function into the target: %s", write_error.AsCString("unknown error"));
Sean Callanan65dafa82010-08-27 01:01:44 +0000644 return err;
645 }
646
Greg Claytond0882d02011-01-19 23:00:49 +0000647 jit_memory_manager->AddToLocalToRemoteMap (lstart, size, cursor);
Sean Callanan65dafa82010-08-27 01:01:44 +0000648 cursor += size;
649 }
650
651 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
652
653 for (pos = m_jitted_functions.begin(); pos != end; pos++)
654 {
Greg Claytond0882d02011-01-19 23:00:49 +0000655 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000656
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000657 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000658 {
Greg Claytond0882d02011-01-19 23:00:49 +0000659 func_end = jit_memory_manager->GetRemoteRangeForLocal ((*pos).m_local_addr).second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000660 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000661 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000662 }
663
Sean Callanan6dff8272010-11-08 03:49:50 +0000664 if (log)
665 {
666 log->Printf("Code can be run in the target.");
667
668 StreamString disassembly_stream;
669
Greg Claytond0882d02011-01-19 23:00:49 +0000670 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000671
672 if (!err.Success())
673 {
674 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
675 }
676 else
677 {
678 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
679 }
680 }
681
Sean Callanan65dafa82010-08-27 01:01:44 +0000682 err.Clear();
683 return err;
684}
685
686Error
Greg Claytond0882d02011-01-19 23:00:49 +0000687ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000688{
Greg Claytone005f2c2010-11-06 01:53:30 +0000689 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000690
691 const char *name = m_expr.FunctionName();
692
693 Error ret;
694
695 ret.Clear();
696
697 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
698 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
699
700 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
701
702 for (pos = m_jitted_functions.begin(); pos < end; pos++)
703 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000704 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000705 {
706 func_local_addr = pos->m_local_addr;
707 func_remote_addr = pos->m_remote_addr;
708 }
709 }
710
711 if (func_local_addr == LLDB_INVALID_ADDRESS)
712 {
713 ret.SetErrorToGenericError();
714 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
715 return ret;
716 }
717
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000718 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000719 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
720
721 std::pair <lldb::addr_t, lldb::addr_t> func_range;
722
Greg Claytond0882d02011-01-19 23:00:49 +0000723 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000724
725 if (func_range.first == 0 && func_range.second == 0)
726 {
727 ret.SetErrorToGenericError();
728 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
729 return ret;
730 }
731
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000732 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000733 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
734
Greg Clayton567e7f32011-09-22 04:58:26 +0000735 Target *target = exe_ctx.GetTargetPtr();
736 if (!target)
Sean Callanan65dafa82010-08-27 01:01:44 +0000737 {
738 ret.SetErrorToGenericError();
739 ret.SetErrorString("Couldn't find the target");
740 }
741
742 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
743
Greg Clayton567e7f32011-09-22 04:58:26 +0000744 Process *process = exe_ctx.GetProcessPtr();
Sean Callanan65dafa82010-08-27 01:01:44 +0000745 Error err;
Greg Clayton567e7f32011-09-22 04:58:26 +0000746 process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
Sean Callanan65dafa82010-08-27 01:01:44 +0000747
748 if (!err.Success())
749 {
750 ret.SetErrorToGenericError();
751 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
752 return ret;
753 }
754
Greg Clayton567e7f32011-09-22 04:58:26 +0000755 ArchSpec arch(target->GetArchitecture());
Sean Callanan65dafa82010-08-27 01:01:44 +0000756
Greg Clayton149731c2011-03-25 18:03:16 +0000757 Disassembler *disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000758
759 if (disassembler == NULL)
760 {
761 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000762 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000763 return ret;
764 }
765
Greg Clayton567e7f32011-09-22 04:58:26 +0000766 if (!process)
Sean Callanan65dafa82010-08-27 01:01:44 +0000767 {
768 ret.SetErrorToGenericError();
769 ret.SetErrorString("Couldn't find the process");
770 return ret;
771 }
772
773 DataExtractor extractor(buffer_sp,
Greg Clayton567e7f32011-09-22 04:58:26 +0000774 process->GetByteOrder(),
775 target->GetArchitecture().GetAddressByteSize());
Sean Callanan65dafa82010-08-27 01:01:44 +0000776
Greg Claytone005f2c2010-11-06 01:53:30 +0000777 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000778 {
779 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000780 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000781 0,
782 extractor.GetByteSize(),
783 func_remote_addr,
784 16,
785 DataExtractor::TypeUInt8);
786 }
787
Jim Inghamaa3e3e12011-03-22 01:48:42 +0000788 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000789
Greg Clayton5c4c7462010-10-06 03:09:58 +0000790 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000791 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000792 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
793 instruction_index < num_instructions;
794 ++instruction_index)
795 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000796 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000797 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000798 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000799 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000800 true,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000801 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000802 true);
803 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000804 }
805
806 return ret;
807}