blob: 8f27c5982c5a88ed6e6de5e1f474b9e367b86069 [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 Callananf18d91c2010-09-01 00:58:00 +000020#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000021#include "lldb/Expression/IRForTarget.h"
22#include "lldb/Expression/IRToDWARF.h"
23#include "lldb/Expression/RecordingMemoryManager.h"
24#include "lldb/Target/ExecutionContext.h"
Sean Callananc7674af2011-01-17 23:42:46 +000025#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000026#include "lldb/Target/Process.h"
27#include "lldb/Target/Target.h"
28
29#include "clang/AST/ASTContext.h"
30#include "clang/AST/ExternalASTSource.h"
31#include "clang/Basic/FileManager.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Basic/Version.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000034#include "clang/CodeGen/CodeGenAction.h"
35#include "clang/CodeGen/ModuleBuilder.h"
36#include "clang/Driver/CC1Options.h"
37#include "clang/Driver/OptTable.h"
38#include "clang/Frontend/CompilerInstance.h"
39#include "clang/Frontend/CompilerInvocation.h"
40#include "clang/Frontend/FrontendActions.h"
41#include "clang/Frontend/FrontendDiagnostic.h"
42#include "clang/Frontend/FrontendPluginRegistry.h"
43#include "clang/Frontend/TextDiagnosticBuffer.h"
44#include "clang/Frontend/TextDiagnosticPrinter.h"
45#include "clang/Frontend/VerifyDiagnosticsClient.h"
46#include "clang/Lex/Preprocessor.h"
Sean Callanan47a5c4c2010-09-23 03:01:22 +000047#include "clang/Parse/ParseAST.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000048#include "clang/Rewrite/FrontendActions.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000049#include "clang/Sema/SemaConsumer.h"
Sean Callananad293092011-01-18 23:32:05 +000050#include "clang/StaticAnalyzer/FrontendActions.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000051
52#include "llvm/ADT/StringRef.h"
53#include "llvm/ExecutionEngine/ExecutionEngine.h"
54#include "llvm/ExecutionEngine/JIT.h"
55#include "llvm/Module.h"
56#include "llvm/LLVMContext.h"
57#include "llvm/Support/ErrorHandling.h"
58#include "llvm/Support/MemoryBuffer.h"
Greg Clayton22defe82010-12-02 23:20:03 +000059#include "llvm/Support/DynamicLibrary.h"
60#include "llvm/Support/Host.h"
61#include "llvm/Support/Signals.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000062#include "llvm/Target/TargetRegistry.h"
63#include "llvm/Target/TargetSelect.h"
64
65using namespace clang;
66using namespace llvm;
67using namespace lldb_private;
68
69//===----------------------------------------------------------------------===//
70// Utility Methods for Clang
71//===----------------------------------------------------------------------===//
72
73std::string GetBuiltinIncludePath(const char *Argv0) {
74 llvm::sys::Path P =
75 llvm::sys::Path::GetMainExecutable(Argv0,
76 (void*)(intptr_t) GetBuiltinIncludePath);
77
78 if (!P.isEmpty()) {
79 P.eraseComponent(); // Remove /clang from foo/bin/clang
80 P.eraseComponent(); // Remove /bin from foo/bin
81
82 // Get foo/lib/clang/<version>/include
83 P.appendComponent("lib");
84 P.appendComponent("clang");
85 P.appendComponent(CLANG_VERSION_STRING);
86 P.appendComponent("include");
87 }
88
89 return P.str();
90}
91
92
93//===----------------------------------------------------------------------===//
94// Main driver for Clang
95//===----------------------------------------------------------------------===//
96
97static void LLVMErrorHandler(void *UserData, const std::string &Message) {
98 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
99
100 Diags.Report(diag::err_fe_error_backend) << Message;
101
102 // We cannot recover from llvm errors.
103 exit(1);
104}
105
106static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
107 using namespace clang::frontend;
108
109 switch (CI.getFrontendOpts().ProgramAction) {
110 default:
111 llvm_unreachable("Invalid program action!");
112
113 case ASTDump: return new ASTDumpAction();
114 case ASTPrint: return new ASTPrintAction();
115 case ASTPrintXML: return new ASTPrintXMLAction();
116 case ASTView: return new ASTViewAction();
117 case BoostCon: return new BoostConAction();
118 case DumpRawTokens: return new DumpRawTokensAction();
119 case DumpTokens: return new DumpTokensAction();
120 case EmitAssembly: return new EmitAssemblyAction();
121 case EmitBC: return new EmitBCAction();
122 case EmitHTML: return new HTMLPrintAction();
123 case EmitLLVM: return new EmitLLVMAction();
124 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
125 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
126 case EmitObj: return new EmitObjAction();
127 case FixIt: return new FixItAction();
128 case GeneratePCH: return new GeneratePCHAction();
129 case GeneratePTH: return new GeneratePTHAction();
130 case InheritanceView: return new InheritanceViewAction();
131 case InitOnly: return new InitOnlyAction();
132 case ParseSyntaxOnly: return new SyntaxOnlyAction();
133
134 case PluginAction: {
135 for (FrontendPluginRegistry::iterator it =
136 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
137 it != ie; ++it) {
138 if (it->getName() == CI.getFrontendOpts().ActionName) {
139 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
140 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
141 return 0;
142 return P.take();
143 }
144 }
145
146 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
147 << CI.getFrontendOpts().ActionName;
148 return 0;
149 }
150
151 case PrintDeclContext: return new DeclContextPrintAction();
152 case PrintPreamble: return new PrintPreambleAction();
153 case PrintPreprocessedInput: return new PrintPreprocessedAction();
154 case RewriteMacros: return new RewriteMacrosAction();
155 case RewriteObjC: return new RewriteObjCAction();
156 case RewriteTest: return new RewriteTestAction();
Sean Callananad293092011-01-18 23:32:05 +0000157 //case RunAnalysis: return new AnalysisAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000158 case RunPreprocessorOnly: return new PreprocessOnlyAction();
159 }
160}
161
162static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
163 // Create the underlying action.
164 FrontendAction *Act = CreateFrontendBaseAction(CI);
165 if (!Act)
166 return 0;
167
168 // If there are any AST files to merge, create a frontend action
169 // adaptor to perform the merge.
170 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
171 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
172 CI.getFrontendOpts().ASTMergeFiles.size());
173
174 return Act;
175}
176
177//===----------------------------------------------------------------------===//
178// Implementation of ClangExpressionParser
179//===----------------------------------------------------------------------===//
180
Greg Clayton395fc332011-02-15 21:59:32 +0000181ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
182 ClangExpression &expr) :
183 m_expr (expr),
Sean Callanan65dafa82010-08-27 01:01:44 +0000184 m_compiler (),
185 m_code_generator (NULL),
186 m_execution_engine (),
187 m_jitted_functions ()
188{
189 // Initialize targets first, so that --version shows registered targets.
190 static struct InitializeLLVM {
191 InitializeLLVM() {
192 llvm::InitializeAllTargets();
193 llvm::InitializeAllAsmPrinters();
194 }
195 } InitializeLLVM;
Greg Clayton395fc332011-02-15 21:59:32 +0000196
Sean Callanan65dafa82010-08-27 01:01:44 +0000197 // 1. Create a new compiler instance.
198 m_compiler.reset(new CompilerInstance());
199 m_compiler->setLLVMContext(new LLVMContext());
200
201 // 2. Set options.
202
203 // Parse expressions as Objective C++ regardless of context.
204 // Our hook into Clang's lookup mechanism only works in C++.
205 m_compiler->getLangOpts().CPlusPlus = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000206
207 // Setup objective C
Sean Callanan65dafa82010-08-27 01:01:44 +0000208 m_compiler->getLangOpts().ObjC1 = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000209 m_compiler->getLangOpts().ObjC2 = true;
Sean Callananc7674af2011-01-17 23:42:46 +0000210
Greg Clayton395fc332011-02-15 21:59:32 +0000211 Process *process = NULL;
212 if (exe_scope)
213 process = exe_scope->CalculateProcess();
214
Sean Callananc7674af2011-01-17 23:42:46 +0000215 if (process)
216 {
217 if (process->GetObjCLanguageRuntime())
218 {
219 if (process->GetObjCLanguageRuntime()->GetRuntimeVersion() == lldb::eAppleObjC_V2)
220 {
221 m_compiler->getLangOpts().ObjCNonFragileABI = true; // NOT i386
222 m_compiler->getLangOpts().ObjCNonFragileABI2 = true; // NOT i386
223 }
224 }
225 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000226
Sean Callanan65dafa82010-08-27 01:01:44 +0000227 m_compiler->getLangOpts().ThreadsafeStatics = false;
228 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
229 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
230
231 // Set CodeGen options
232 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
233 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
234
235 // Disable some warnings.
236 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
237
238 // Set the target triple.
Greg Clayton395fc332011-02-15 21:59:32 +0000239 Target *target = NULL;
240 if (exe_scope)
241 target = exe_scope->CalculateTarget();
242
243 // TODO: figure out what to really do when we don't have a valid target.
244 // Sometimes this will be ok to just use the host target triple (when we
245 // evaluate say "2+3", but other expressions like breakpoint conditions
246 // and other things that _are_ target specific really shouldn't just be
247 // using the host triple. This needs to be fixed in a better way.
248 if (target && target->GetArchitecture().IsValid())
249 m_compiler->getTargetOpts().Triple = target->GetArchitecture().GetTriple().str();
250 else
251 m_compiler->getTargetOpts().Triple = llvm::sys::getHostTriple();
Sean Callanan65dafa82010-08-27 01:01:44 +0000252
253 // 3. Set up various important bits of infrastructure.
254 m_compiler->createDiagnostics(0, 0);
255
256 // Create the target instance.
257 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
258 m_compiler->getTargetOpts()));
259
260 assert (m_compiler->hasTarget());
261
262 // Inform the target of the language options
263 //
264 // FIXME: We shouldn't need to do this, the target should be immutable once
265 // created. This complexity should be lifted elsewhere.
266 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
267
268 // 4. Set up the diagnostic buffer for reporting errors
269
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000270 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000271
272 // 5. Set up the source management objects inside the compiler
273
Greg Clayton22defe82010-12-02 23:20:03 +0000274 clang::FileSystemOptions file_system_options;
275 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000276
Sean Callanan65dafa82010-08-27 01:01:44 +0000277 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000278 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000279
280 m_compiler->createFileManager();
281 m_compiler->createPreprocessor();
282
283 // 6. Most of this we get from the CompilerInstance, but we
284 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000285 m_selector_table.reset(new SelectorTable());
Sean Callanan65dafa82010-08-27 01:01:44 +0000286 m_builtin_context.reset(new Builtin::Context(m_compiler->getTarget()));
287
288 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
289 m_compiler->getSourceManager(),
290 m_compiler->getTarget(),
291 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000292 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000293 *m_builtin_context.get(),
294 0));
295
296 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
297
298 if (decl_map)
299 {
300 OwningPtr<clang::ExternalASTSource> ast_source(new ClangASTSource(*ast_context, *decl_map));
301 ast_context->setExternalSource(ast_source);
302 }
303
304 m_compiler->setASTContext(ast_context.release());
305
Greg Clayton8de27c72010-10-15 22:48:33 +0000306 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000307
308 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
309 module_name,
310 m_compiler->getCodeGenOpts(),
311 m_compiler->getLLVMContext()));
312}
313
314ClangExpressionParser::~ClangExpressionParser()
315{
316}
317
318unsigned
319ClangExpressionParser::Parse (Stream &stream)
320{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000321 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
322
323 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000324
325 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
326 FileID memory_buffer_file_id = m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
327
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000328 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000329
330 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
331
332 if (ast_transformer)
333 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
334 else
335 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
336
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000337 diag_buf->EndSourceFile();
Sean Callanan65dafa82010-08-27 01:01:44 +0000338
339 TextDiagnosticBuffer::const_iterator diag_iterator;
340
341 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000342
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000343 for (diag_iterator = diag_buf->warn_begin();
344 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000345 ++diag_iterator)
346 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
347
348 num_errors = 0;
349
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000350 for (diag_iterator = diag_buf->err_begin();
351 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000352 ++diag_iterator)
353 {
354 num_errors++;
355 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
356 }
357
Sean Callanan7617c292010-11-01 20:28:09 +0000358 for (diag_iterator = diag_buf->note_begin();
359 diag_iterator != diag_buf->note_end();
360 ++diag_iterator)
361 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
362
Sean Callanan65dafa82010-08-27 01:01:44 +0000363 return num_errors;
364}
365
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000366static bool FindFunctionInModule (std::string &mangled_name,
367 llvm::Module *module,
368 const char *orig_name)
369{
370 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
371 fi != fe;
372 ++fi)
373 {
374 if (fi->getName().str().find(orig_name) != std::string::npos)
375 {
376 mangled_name = fi->getName().str();
377 return true;
378 }
379 }
380
381 return false;
382}
383
Sean Callanan65dafa82010-08-27 01:01:44 +0000384Error
385ClangExpressionParser::MakeDWARF ()
386{
387 Error err;
388
389 llvm::Module *module = m_code_generator->GetModule();
390
391 if (!module)
392 {
393 err.SetErrorToGenericError();
394 err.SetErrorString("IR doesn't contain a module");
395 return err;
396 }
397
Greg Clayton427f2902010-12-14 02:59:59 +0000398 ClangExpressionVariableList *local_variables = m_expr.LocalVariables();
Sean Callanan65dafa82010-08-27 01:01:44 +0000399 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
400
401 if (!local_variables)
402 {
403 err.SetErrorToGenericError();
404 err.SetErrorString("Can't convert an expression without a VariableList to DWARF");
405 return err;
406 }
407
408 if (!decl_map)
409 {
410 err.SetErrorToGenericError();
411 err.SetErrorString("Can't convert an expression without a DeclMap to DWARF");
412 return err;
413 }
414
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000415 std::string function_name;
416
417 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
418 {
419 err.SetErrorToGenericError();
420 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
421 return err;
422 }
423
424 IRToDWARF ir_to_dwarf(*local_variables, decl_map, m_expr.DwarfOpcodeStream(), function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000425
426 if (!ir_to_dwarf.runOnModule(*module))
427 {
428 err.SetErrorToGenericError();
429 err.SetErrorString("Couldn't convert the expression to DWARF");
430 return err;
431 }
432
433 err.Clear();
434 return err;
435}
436
437Error
Greg Claytond0882d02011-01-19 23:00:49 +0000438ClangExpressionParser::MakeJIT (lldb::addr_t &func_allocation_addr,
439 lldb::addr_t &func_addr,
Sean Callanan830a9032010-08-27 23:31:21 +0000440 lldb::addr_t &func_end,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000441 ExecutionContext &exe_ctx,
442 lldb::ClangExpressionVariableSP *const_result)
Sean Callanan65dafa82010-08-27 01:01:44 +0000443{
Greg Claytond0882d02011-01-19 23:00:49 +0000444 func_allocation_addr = LLDB_INVALID_ADDRESS;
445 func_addr = LLDB_INVALID_ADDRESS;
446 func_end = LLDB_INVALID_ADDRESS;
Greg Claytone005f2c2010-11-06 01:53:30 +0000447 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000448
Sean Callanan65dafa82010-08-27 01:01:44 +0000449 Error err;
450
451 llvm::Module *module = m_code_generator->ReleaseModule();
452
453 if (!module)
454 {
455 err.SetErrorToGenericError();
456 err.SetErrorString("IR doesn't contain a module");
457 return err;
458 }
459
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000460 // Find the actual name of the function (it's often mangled somehow)
461
462 std::string function_name;
463
464 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
465 {
466 err.SetErrorToGenericError();
467 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
468 return err;
469 }
470 else
471 {
472 if(log)
473 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
474 }
475
Sean Callanan65dafa82010-08-27 01:01:44 +0000476 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
477
478 if (decl_map)
479 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000480 Stream *error_stream = NULL;
481
482 if (exe_ctx.target)
483 error_stream = &exe_ctx.target->GetDebugger().GetErrorStream();
484
Sean Callanane8a59a82010-09-13 21:34:21 +0000485 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000486 m_expr.NeedsVariableResolution(),
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000487 const_result,
Sean Callanan97c924e2011-01-27 01:07:04 +0000488 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000489 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000490
491 if (!ir_for_target.runOnModule(*module))
492 {
493 err.SetErrorToGenericError();
494 err.SetErrorString("Couldn't convert the expression to DWARF");
495 return err;
496 }
Sean Callananf18d91c2010-09-01 00:58:00 +0000497
Jim Inghamd1686902010-10-14 23:45:03 +0000498 if (m_expr.NeedsValidation() && exe_ctx.process->GetDynamicCheckers())
Sean Callananf18d91c2010-09-01 00:58:00 +0000499 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000500 IRDynamicChecks ir_dynamic_checks(*exe_ctx.process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000501
502 if (!ir_dynamic_checks.runOnModule(*module))
503 {
504 err.SetErrorToGenericError();
505 err.SetErrorString("Couldn't add dynamic checks to the expression");
506 return err;
507 }
508 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000509 }
510
Greg Claytond0882d02011-01-19 23:00:49 +0000511 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
512 // below so we don't need to free it.
513 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000514
515 std::string error_string;
Sean Callanan9ac3a962010-11-02 23:20:00 +0000516
Sean Callananc2c6f772010-10-26 00:31:56 +0000517 llvm::TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
518
Sean Callanan65dafa82010-08-27 01:01:44 +0000519 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
520 &error_string,
Greg Claytond0882d02011-01-19 23:00:49 +0000521 jit_memory_manager,
Sean Callananc2c6f772010-10-26 00:31:56 +0000522 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000523 true,
524 CodeModel::Small));
Sean Callanan9ac3a962010-11-02 23:20:00 +0000525
Sean Callanan65dafa82010-08-27 01:01:44 +0000526 if (!m_execution_engine.get())
527 {
528 err.SetErrorToGenericError();
529 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
530 return err;
531 }
532
533 m_execution_engine->DisableLazyCompilation();
534
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000535 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000536
537 // We don't actually need the function pointer here, this just forces it to get resolved.
538
539 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
540
541 // Errors usually cause failures in the JIT, but if we're lucky we get here.
542
543 if (!fun_ptr)
544 {
545 err.SetErrorToGenericError();
546 err.SetErrorString("Couldn't JIT the function");
547 return err;
548 }
549
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000550 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000551
552 ExecutionContext &exc_context(exe_ctx);
553
554 if (exc_context.process == NULL)
555 {
556 err.SetErrorToGenericError();
557 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
558 return err;
559 }
560
561 // Look over the regions allocated for the function compiled. The JIT
562 // tries to allocate the functions & stubs close together, so we should try to
563 // write them that way too...
564 // For now I only write functions with no stubs, globals, exception tables,
565 // etc. So I only need to write the functions.
566
567 size_t alloc_size = 0;
568
Greg Claytond0882d02011-01-19 23:00:49 +0000569 std::map<uint8_t *, uint8_t *>::iterator fun_pos = jit_memory_manager->m_functions.begin();
570 std::map<uint8_t *, uint8_t *>::iterator fun_end = jit_memory_manager->m_functions.end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000571
572 for (; fun_pos != fun_end; ++fun_pos)
573 alloc_size += (*fun_pos).second - (*fun_pos).first;
574
575 Error alloc_error;
Greg Claytond0882d02011-01-19 23:00:49 +0000576 func_allocation_addr = exc_context.process->AllocateMemory (alloc_size,
577 lldb::ePermissionsReadable|lldb::ePermissionsExecutable,
578 alloc_error);
Sean Callanan65dafa82010-08-27 01:01:44 +0000579
Greg Claytond0882d02011-01-19 23:00:49 +0000580 if (func_allocation_addr == LLDB_INVALID_ADDRESS)
Sean Callanan65dafa82010-08-27 01:01:44 +0000581 {
582 err.SetErrorToGenericError();
583 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
584 return err;
585 }
586
Greg Claytond0882d02011-01-19 23:00:49 +0000587 lldb::addr_t cursor = func_allocation_addr;
Sean Callanan65dafa82010-08-27 01:01:44 +0000588
Greg Claytond0882d02011-01-19 23:00:49 +0000589 for (fun_pos = jit_memory_manager->m_functions.begin(); fun_pos != fun_end; fun_pos++)
Sean Callanan65dafa82010-08-27 01:01:44 +0000590 {
591 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
592 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
593 size_t size = lend - lstart;
594
595 Error write_error;
596
597 if (exc_context.process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
598 {
599 err.SetErrorToGenericError();
600 err.SetErrorStringWithFormat("Couldn't copy JITted function into the target: %s", write_error.AsCString("unknown error"));
601 return err;
602 }
603
Greg Claytond0882d02011-01-19 23:00:49 +0000604 jit_memory_manager->AddToLocalToRemoteMap (lstart, size, cursor);
Sean Callanan65dafa82010-08-27 01:01:44 +0000605 cursor += size;
606 }
607
608 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
609
610 for (pos = m_jitted_functions.begin(); pos != end; pos++)
611 {
Greg Claytond0882d02011-01-19 23:00:49 +0000612 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000613
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000614 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000615 {
Greg Claytond0882d02011-01-19 23:00:49 +0000616 func_end = jit_memory_manager->GetRemoteRangeForLocal ((*pos).m_local_addr).second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000617 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000618 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000619 }
620
Sean Callanan6dff8272010-11-08 03:49:50 +0000621 if (log)
622 {
623 log->Printf("Code can be run in the target.");
624
625 StreamString disassembly_stream;
626
Greg Claytond0882d02011-01-19 23:00:49 +0000627 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000628
629 if (!err.Success())
630 {
631 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
632 }
633 else
634 {
635 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
636 }
637 }
638
Sean Callanan65dafa82010-08-27 01:01:44 +0000639 err.Clear();
640 return err;
641}
642
643Error
Greg Claytond0882d02011-01-19 23:00:49 +0000644ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000645{
Greg Claytone005f2c2010-11-06 01:53:30 +0000646 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000647
648 const char *name = m_expr.FunctionName();
649
650 Error ret;
651
652 ret.Clear();
653
654 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
655 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
656
657 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
658
659 for (pos = m_jitted_functions.begin(); pos < end; pos++)
660 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000661 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000662 {
663 func_local_addr = pos->m_local_addr;
664 func_remote_addr = pos->m_remote_addr;
665 }
666 }
667
668 if (func_local_addr == LLDB_INVALID_ADDRESS)
669 {
670 ret.SetErrorToGenericError();
671 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
672 return ret;
673 }
674
675 if(log)
676 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
677
678 std::pair <lldb::addr_t, lldb::addr_t> func_range;
679
Greg Claytond0882d02011-01-19 23:00:49 +0000680 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000681
682 if (func_range.first == 0 && func_range.second == 0)
683 {
684 ret.SetErrorToGenericError();
685 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
686 return ret;
687 }
688
689 if(log)
690 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
691
692 if (!exe_ctx.target)
693 {
694 ret.SetErrorToGenericError();
695 ret.SetErrorString("Couldn't find the target");
696 }
697
698 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
699
700 Error err;
701 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
702
703 if (!err.Success())
704 {
705 ret.SetErrorToGenericError();
706 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
707 return ret;
708 }
709
710 ArchSpec arch(exe_ctx.target->GetArchitecture());
711
712 Disassembler *disassembler = Disassembler::FindPlugin(arch);
713
714 if (disassembler == NULL)
715 {
716 ret.SetErrorToGenericError();
717 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.AsCString());
718 return ret;
719 }
720
721 if (!exe_ctx.process)
722 {
723 ret.SetErrorToGenericError();
724 ret.SetErrorString("Couldn't find the process");
725 return ret;
726 }
727
728 DataExtractor extractor(buffer_sp,
729 exe_ctx.process->GetByteOrder(),
730 exe_ctx.target->GetArchitecture().GetAddressByteSize());
731
Greg Claytone005f2c2010-11-06 01:53:30 +0000732 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000733 {
734 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000735 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000736 0,
737 extractor.GetByteSize(),
738 func_remote_addr,
739 16,
740 DataExtractor::TypeUInt8);
741 }
742
Greg Clayton5c4c7462010-10-06 03:09:58 +0000743 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX);
Sean Callanan65dafa82010-08-27 01:01:44 +0000744
Greg Clayton5c4c7462010-10-06 03:09:58 +0000745 InstructionList &instruction_list = disassembler->GetInstructionList();
Sean Callanan65dafa82010-08-27 01:01:44 +0000746
747 uint32_t bytes_offset = 0;
748
749 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
750 instruction_index < num_instructions;
751 ++instruction_index)
752 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000753 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000754 instruction->Dump (&stream,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000755 true,
Sean Callanan65dafa82010-08-27 01:01:44 +0000756 &extractor,
757 bytes_offset,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000758 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000759 true);
760 stream.PutChar('\n');
761 bytes_offset += instruction->GetByteSize();
762 }
763
764 return ret;
765}