blob: 17cc5a84c0d1cdca0e715fe51d47a5fce9a1f757 [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 Callanan24312442011-08-23 21:20:51 +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 {
323 OwningPtr<clang::ExternalASTSource> ast_source(new ClangASTSource(*ast_context, *decl_map));
324 ast_context->setExternalSource(ast_source);
325 }
326
327 m_compiler->setASTContext(ast_context.release());
328
Greg Clayton8de27c72010-10-15 22:48:33 +0000329 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000330
Sean Callanan279584c2011-03-15 00:17:19 +0000331 m_llvm_context.reset(new LLVMContext());
Sean Callanan65dafa82010-08-27 01:01:44 +0000332 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
333 module_name,
334 m_compiler->getCodeGenOpts(),
Sean Callanan279584c2011-03-15 00:17:19 +0000335 *m_llvm_context));
Sean Callanan65dafa82010-08-27 01:01:44 +0000336}
337
338ClangExpressionParser::~ClangExpressionParser()
339{
340}
341
342unsigned
343ClangExpressionParser::Parse (Stream &stream)
344{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000345 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
346
347 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000348
349 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
350 FileID memory_buffer_file_id = m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
351
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000352 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000353
354 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
355
356 if (ast_transformer)
357 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
358 else
359 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
360
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000361 diag_buf->EndSourceFile();
Sean Callananfb3058e2011-05-12 23:54:16 +0000362
Sean Callanan65dafa82010-08-27 01:01:44 +0000363 TextDiagnosticBuffer::const_iterator diag_iterator;
364
365 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000366
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000367 for (diag_iterator = diag_buf->warn_begin();
368 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000369 ++diag_iterator)
370 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
371
372 num_errors = 0;
373
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000374 for (diag_iterator = diag_buf->err_begin();
375 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000376 ++diag_iterator)
377 {
378 num_errors++;
379 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
380 }
381
Sean Callanan7617c292010-11-01 20:28:09 +0000382 for (diag_iterator = diag_buf->note_begin();
383 diag_iterator != diag_buf->note_end();
384 ++diag_iterator)
385 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
386
Sean Callananfb3058e2011-05-12 23:54:16 +0000387 if (!num_errors)
388 {
389 if (m_expr.DeclMap() && !m_expr.DeclMap()->ResolveUnknownTypes())
390 {
391 stream.Printf("error: Couldn't infer the type of a variable\n");
392 num_errors++;
393 }
394 }
395
Sean Callanan65dafa82010-08-27 01:01:44 +0000396 return num_errors;
397}
398
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000399static bool FindFunctionInModule (std::string &mangled_name,
400 llvm::Module *module,
401 const char *orig_name)
402{
403 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
404 fi != fe;
405 ++fi)
406 {
407 if (fi->getName().str().find(orig_name) != std::string::npos)
408 {
409 mangled_name = fi->getName().str();
410 return true;
411 }
412 }
413
414 return false;
415}
416
Sean Callanan65dafa82010-08-27 01:01:44 +0000417Error
Sean Callanan47dc4572011-09-15 02:13:07 +0000418ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_allocation_addr,
419 lldb::addr_t &func_addr,
420 lldb::addr_t &func_end,
421 ExecutionContext &exe_ctx,
422 IRForTarget::StaticDataAllocator *data_allocator,
423 bool &evaluated_statically,
424 lldb::ClangExpressionVariableSP &const_result,
425 ExecutionPolicy execution_policy)
Sean Callanan65dafa82010-08-27 01:01:44 +0000426{
Greg Claytond0882d02011-01-19 23:00:49 +0000427 func_allocation_addr = LLDB_INVALID_ADDRESS;
428 func_addr = LLDB_INVALID_ADDRESS;
429 func_end = LLDB_INVALID_ADDRESS;
Greg Claytone005f2c2010-11-06 01:53:30 +0000430 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000431
Sean Callanan65dafa82010-08-27 01:01:44 +0000432 Error err;
433
434 llvm::Module *module = m_code_generator->ReleaseModule();
435
436 if (!module)
437 {
438 err.SetErrorToGenericError();
439 err.SetErrorString("IR doesn't contain a module");
440 return err;
441 }
442
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000443 // Find the actual name of the function (it's often mangled somehow)
444
445 std::string function_name;
446
447 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
448 {
449 err.SetErrorToGenericError();
450 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
451 return err;
452 }
453 else
454 {
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000455 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000456 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
457 }
458
Sean Callanan65dafa82010-08-27 01:01:44 +0000459 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
460
461 if (decl_map)
462 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000463 Stream *error_stream = NULL;
Greg Clayton567e7f32011-09-22 04:58:26 +0000464 Target *target = exe_ctx.GetTargetPtr();
465 if (target)
466 error_stream = &target->GetDebugger().GetErrorStream();
Sean Callanan97c924e2011-01-27 01:07:04 +0000467
Sean Callanan47dc4572011-09-15 02:13:07 +0000468 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000469 m_expr.NeedsVariableResolution(),
Sean Callanan47dc4572011-09-15 02:13:07 +0000470 execution_policy,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000471 const_result,
Sean Callananc0492742011-05-23 21:40:23 +0000472 data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +0000473 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000474 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000475
476 if (!ir_for_target.runOnModule(*module))
477 {
478 err.SetErrorToGenericError();
Sean Callanan47dc4572011-09-15 02:13:07 +0000479 err.SetErrorString("Couldn't prepare the expression for execution in the target");
Sean Callanan65dafa82010-08-27 01:01:44 +0000480 return err;
481 }
Sean Callananf18d91c2010-09-01 00:58:00 +0000482
Sean Callanan47dc4572011-09-15 02:13:07 +0000483 if (execution_policy != eExecutionPolicyAlways && ir_for_target.interpretSuccess())
Sean Callanan696cf5f2011-05-07 01:06:41 +0000484 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000485 evaluated_statically = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000486 err.Clear();
487 return err;
488 }
489
Greg Clayton567e7f32011-09-22 04:58:26 +0000490 Process *process = exe_ctx.GetProcessPtr();
491
492 if (!process || execution_policy == eExecutionPolicyNever)
Sean Callanan47dc4572011-09-15 02:13:07 +0000493 {
494 err.SetErrorToGenericError();
495 err.SetErrorString("Execution needed to run in the target, but the target can't be run");
496 return err;
497 }
498
Sean Callanan6cf6c472011-09-20 23:01:51 +0000499 if (execution_policy != eExecutionPolicyNever &&
500 m_expr.NeedsValidation() &&
Greg Clayton567e7f32011-09-22 04:58:26 +0000501 process)
Sean Callananf18d91c2010-09-01 00:58:00 +0000502 {
Greg Clayton567e7f32011-09-22 04:58:26 +0000503 if (!process->GetDynamicCheckers())
Sean Callanan6cf6c472011-09-20 23:01:51 +0000504 {
505 DynamicCheckerFunctions *dynamic_checkers = new DynamicCheckerFunctions();
506
507 StreamString install_errors;
508
509 if (!dynamic_checkers->Install(install_errors, exe_ctx))
510 {
511 if (install_errors.GetString().empty())
512 err.SetErrorString ("couldn't install checkers, unknown error");
513 else
514 err.SetErrorString (install_errors.GetString().c_str());
515
516 return err;
517 }
518
Greg Clayton567e7f32011-09-22 04:58:26 +0000519 process->SetDynamicCheckers(dynamic_checkers);
Sean Callanan6cf6c472011-09-20 23:01:51 +0000520
521 if (log)
522 log->Printf("== [ClangUserExpression::Evaluate] Finished installing dynamic checkers ==");
523 }
524
Greg Clayton567e7f32011-09-22 04:58:26 +0000525 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000526
527 if (!ir_dynamic_checks.runOnModule(*module))
528 {
529 err.SetErrorToGenericError();
530 err.SetErrorString("Couldn't add dynamic checks to the expression");
531 return err;
532 }
533 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000534 }
535
Greg Claytond0882d02011-01-19 23:00:49 +0000536 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
537 // below so we don't need to free it.
538 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000539
540 std::string error_string;
Sean Callanan9b6898f2011-07-30 02:42:06 +0000541
Greg Clayton2f085c62011-05-15 01:25:55 +0000542#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +0000543 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
544 &error_string,
Greg Claytond0882d02011-01-19 23:00:49 +0000545 jit_memory_manager,
Sean Callananc2c6f772010-10-26 00:31:56 +0000546 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000547 true,
Peter Collingbournec4d4fb52011-07-30 22:42:24 +0000548 Reloc::Default,
Sean Callanan65dafa82010-08-27 01:01:44 +0000549 CodeModel::Small));
Greg Clayton2f085c62011-05-15 01:25:55 +0000550#else
551 EngineBuilder builder(module);
552 builder.setEngineKind(EngineKind::JIT)
553 .setErrorStr(&error_string)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000554 .setRelocationModel(llvm::Reloc::PIC_)
Greg Clayton2f085c62011-05-15 01:25:55 +0000555 .setJITMemoryManager(jit_memory_manager)
556 .setOptLevel(CodeGenOpt::Less)
557 .setAllocateGVsWithCode(true)
558 .setCodeModel(CodeModel::Small)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000559 .setUseMCJIT(true);
Greg Clayton2f085c62011-05-15 01:25:55 +0000560 m_execution_engine.reset(builder.create());
561#endif
Sean Callanan9ac3a962010-11-02 23:20:00 +0000562
Sean Callanan65dafa82010-08-27 01:01:44 +0000563 if (!m_execution_engine.get())
564 {
565 err.SetErrorToGenericError();
566 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
567 return err;
568 }
569
570 m_execution_engine->DisableLazyCompilation();
571
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000572 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000573
574 // We don't actually need the function pointer here, this just forces it to get resolved.
575
576 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
577
578 // Errors usually cause failures in the JIT, but if we're lucky we get here.
579
580 if (!fun_ptr)
581 {
582 err.SetErrorToGenericError();
583 err.SetErrorString("Couldn't JIT the function");
584 return err;
585 }
586
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000587 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000588
Greg Clayton567e7f32011-09-22 04:58:26 +0000589
590 Process *process = exe_ctx.GetProcessPtr();
591 if (process == NULL)
Sean Callanan65dafa82010-08-27 01:01:44 +0000592 {
593 err.SetErrorToGenericError();
594 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
595 return err;
596 }
597
598 // Look over the regions allocated for the function compiled. The JIT
599 // tries to allocate the functions & stubs close together, so we should try to
600 // write them that way too...
601 // For now I only write functions with no stubs, globals, exception tables,
602 // etc. So I only need to write the functions.
603
604 size_t alloc_size = 0;
605
Greg Claytond0882d02011-01-19 23:00:49 +0000606 std::map<uint8_t *, uint8_t *>::iterator fun_pos = jit_memory_manager->m_functions.begin();
607 std::map<uint8_t *, uint8_t *>::iterator fun_end = jit_memory_manager->m_functions.end();
Greg Clayton9d2b3212011-05-15 23:56:52 +0000608
Sean Callanan65dafa82010-08-27 01:01:44 +0000609 for (; fun_pos != fun_end; ++fun_pos)
Greg Clayton9d2b3212011-05-15 23:56:52 +0000610 {
611 size_t mem_size = fun_pos->second - fun_pos->first;
612 if (log)
613 log->Printf ("JIT memory: [%p - %p) size = %zu", fun_pos->first, fun_pos->second, mem_size);
614 alloc_size += mem_size;
615 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000616
617 Error alloc_error;
Greg Clayton567e7f32011-09-22 04:58:26 +0000618 func_allocation_addr = process->AllocateMemory (alloc_size,
Greg Claytond0882d02011-01-19 23:00:49 +0000619 lldb::ePermissionsReadable|lldb::ePermissionsExecutable,
620 alloc_error);
Sean Callanan65dafa82010-08-27 01:01:44 +0000621
Greg Claytond0882d02011-01-19 23:00:49 +0000622 if (func_allocation_addr == LLDB_INVALID_ADDRESS)
Sean Callanan65dafa82010-08-27 01:01:44 +0000623 {
624 err.SetErrorToGenericError();
625 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
626 return err;
627 }
628
Greg Claytond0882d02011-01-19 23:00:49 +0000629 lldb::addr_t cursor = func_allocation_addr;
Sean Callanan65dafa82010-08-27 01:01:44 +0000630
Greg Claytond0882d02011-01-19 23:00:49 +0000631 for (fun_pos = jit_memory_manager->m_functions.begin(); fun_pos != fun_end; fun_pos++)
Sean Callanan65dafa82010-08-27 01:01:44 +0000632 {
633 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
634 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
635 size_t size = lend - lstart;
636
637 Error write_error;
638
Greg Clayton567e7f32011-09-22 04:58:26 +0000639 if (process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
Sean Callanan65dafa82010-08-27 01:01:44 +0000640 {
641 err.SetErrorToGenericError();
Greg Claytonc0fa5332011-05-22 22:46:53 +0000642 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 +0000643 return err;
644 }
645
Greg Claytond0882d02011-01-19 23:00:49 +0000646 jit_memory_manager->AddToLocalToRemoteMap (lstart, size, cursor);
Sean Callanan65dafa82010-08-27 01:01:44 +0000647 cursor += size;
648 }
649
650 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
651
652 for (pos = m_jitted_functions.begin(); pos != end; pos++)
653 {
Greg Claytond0882d02011-01-19 23:00:49 +0000654 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000655
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000656 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000657 {
Greg Claytond0882d02011-01-19 23:00:49 +0000658 func_end = jit_memory_manager->GetRemoteRangeForLocal ((*pos).m_local_addr).second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000659 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000660 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000661 }
662
Sean Callanan6dff8272010-11-08 03:49:50 +0000663 if (log)
664 {
665 log->Printf("Code can be run in the target.");
666
667 StreamString disassembly_stream;
668
Greg Claytond0882d02011-01-19 23:00:49 +0000669 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000670
671 if (!err.Success())
672 {
673 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
674 }
675 else
676 {
677 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
678 }
679 }
680
Sean Callanan65dafa82010-08-27 01:01:44 +0000681 err.Clear();
682 return err;
683}
684
685Error
Greg Claytond0882d02011-01-19 23:00:49 +0000686ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000687{
Greg Claytone005f2c2010-11-06 01:53:30 +0000688 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000689
690 const char *name = m_expr.FunctionName();
691
692 Error ret;
693
694 ret.Clear();
695
696 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
697 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
698
699 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
700
701 for (pos = m_jitted_functions.begin(); pos < end; pos++)
702 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000703 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000704 {
705 func_local_addr = pos->m_local_addr;
706 func_remote_addr = pos->m_remote_addr;
707 }
708 }
709
710 if (func_local_addr == LLDB_INVALID_ADDRESS)
711 {
712 ret.SetErrorToGenericError();
713 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
714 return ret;
715 }
716
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000717 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000718 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
719
720 std::pair <lldb::addr_t, lldb::addr_t> func_range;
721
Greg Claytond0882d02011-01-19 23:00:49 +0000722 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000723
724 if (func_range.first == 0 && func_range.second == 0)
725 {
726 ret.SetErrorToGenericError();
727 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
728 return ret;
729 }
730
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000731 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000732 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
733
Greg Clayton567e7f32011-09-22 04:58:26 +0000734 Target *target = exe_ctx.GetTargetPtr();
735 if (!target)
Sean Callanan65dafa82010-08-27 01:01:44 +0000736 {
737 ret.SetErrorToGenericError();
738 ret.SetErrorString("Couldn't find the target");
739 }
740
741 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
742
Greg Clayton567e7f32011-09-22 04:58:26 +0000743 Process *process = exe_ctx.GetProcessPtr();
Sean Callanan65dafa82010-08-27 01:01:44 +0000744 Error err;
Greg Clayton567e7f32011-09-22 04:58:26 +0000745 process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
Sean Callanan65dafa82010-08-27 01:01:44 +0000746
747 if (!err.Success())
748 {
749 ret.SetErrorToGenericError();
750 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
751 return ret;
752 }
753
Greg Clayton567e7f32011-09-22 04:58:26 +0000754 ArchSpec arch(target->GetArchitecture());
Sean Callanan65dafa82010-08-27 01:01:44 +0000755
Greg Clayton149731c2011-03-25 18:03:16 +0000756 Disassembler *disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000757
758 if (disassembler == NULL)
759 {
760 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000761 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000762 return ret;
763 }
764
Greg Clayton567e7f32011-09-22 04:58:26 +0000765 if (!process)
Sean Callanan65dafa82010-08-27 01:01:44 +0000766 {
767 ret.SetErrorToGenericError();
768 ret.SetErrorString("Couldn't find the process");
769 return ret;
770 }
771
772 DataExtractor extractor(buffer_sp,
Greg Clayton567e7f32011-09-22 04:58:26 +0000773 process->GetByteOrder(),
774 target->GetArchitecture().GetAddressByteSize());
Sean Callanan65dafa82010-08-27 01:01:44 +0000775
Greg Claytone005f2c2010-11-06 01:53:30 +0000776 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000777 {
778 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000779 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000780 0,
781 extractor.GetByteSize(),
782 func_remote_addr,
783 16,
784 DataExtractor::TypeUInt8);
785 }
786
Jim Inghamaa3e3e12011-03-22 01:48:42 +0000787 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000788
Greg Clayton5c4c7462010-10-06 03:09:58 +0000789 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000790 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000791 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
792 instruction_index < num_instructions;
793 ++instruction_index)
794 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000795 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000796 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000797 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000798 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000799 true,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000800 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000801 true);
802 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000803 }
804
805 return ret;
806}