blob: 29d3c3e8441a5de76575cbfc019344725e4aebbb [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
181ClangExpressionParser::ClangExpressionParser(const char *target_triple,
Sean Callananc7674af2011-01-17 23:42:46 +0000182 Process *process,
Sean Callanan65dafa82010-08-27 01:01:44 +0000183 ClangExpression &expr) :
184 m_expr(expr),
185 m_target_triple (),
186 m_compiler (),
187 m_code_generator (NULL),
188 m_execution_engine (),
189 m_jitted_functions ()
190{
191 // Initialize targets first, so that --version shows registered targets.
192 static struct InitializeLLVM {
193 InitializeLLVM() {
194 llvm::InitializeAllTargets();
195 llvm::InitializeAllAsmPrinters();
196 }
197 } InitializeLLVM;
198
199 if (target_triple && target_triple[0])
200 m_target_triple = target_triple;
201 else
202 m_target_triple = llvm::sys::getHostTriple();
203
204 // 1. Create a new compiler instance.
205 m_compiler.reset(new CompilerInstance());
206 m_compiler->setLLVMContext(new LLVMContext());
207
208 // 2. Set options.
209
210 // Parse expressions as Objective C++ regardless of context.
211 // Our hook into Clang's lookup mechanism only works in C++.
212 m_compiler->getLangOpts().CPlusPlus = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000213
214 // Setup objective C
Sean Callanan65dafa82010-08-27 01:01:44 +0000215 m_compiler->getLangOpts().ObjC1 = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000216 m_compiler->getLangOpts().ObjC2 = true;
Sean Callananc7674af2011-01-17 23:42:46 +0000217
218 if (process)
219 {
220 if (process->GetObjCLanguageRuntime())
221 {
222 if (process->GetObjCLanguageRuntime()->GetRuntimeVersion() == lldb::eAppleObjC_V2)
223 {
224 m_compiler->getLangOpts().ObjCNonFragileABI = true; // NOT i386
225 m_compiler->getLangOpts().ObjCNonFragileABI2 = true; // NOT i386
226 }
227 }
228 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000229
Sean Callanan65dafa82010-08-27 01:01:44 +0000230 m_compiler->getLangOpts().ThreadsafeStatics = false;
231 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
232 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
233
234 // Set CodeGen options
235 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
236 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
237
238 // Disable some warnings.
239 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
240
241 // Set the target triple.
242 m_compiler->getTargetOpts().Triple = m_target_triple;
243
244 // 3. Set up various important bits of infrastructure.
245 m_compiler->createDiagnostics(0, 0);
246
247 // Create the target instance.
248 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
249 m_compiler->getTargetOpts()));
250
251 assert (m_compiler->hasTarget());
252
253 // Inform the target of the language options
254 //
255 // FIXME: We shouldn't need to do this, the target should be immutable once
256 // created. This complexity should be lifted elsewhere.
257 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
258
259 // 4. Set up the diagnostic buffer for reporting errors
260
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000261 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000262
263 // 5. Set up the source management objects inside the compiler
264
Greg Clayton22defe82010-12-02 23:20:03 +0000265 clang::FileSystemOptions file_system_options;
266 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000267
Sean Callanan65dafa82010-08-27 01:01:44 +0000268 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000269 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000270
271 m_compiler->createFileManager();
272 m_compiler->createPreprocessor();
273
274 // 6. Most of this we get from the CompilerInstance, but we
275 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000276 m_selector_table.reset(new SelectorTable());
Sean Callanan65dafa82010-08-27 01:01:44 +0000277 m_builtin_context.reset(new Builtin::Context(m_compiler->getTarget()));
278
279 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
280 m_compiler->getSourceManager(),
281 m_compiler->getTarget(),
282 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000283 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000284 *m_builtin_context.get(),
285 0));
286
287 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
288
289 if (decl_map)
290 {
291 OwningPtr<clang::ExternalASTSource> ast_source(new ClangASTSource(*ast_context, *decl_map));
292 ast_context->setExternalSource(ast_source);
293 }
294
295 m_compiler->setASTContext(ast_context.release());
296
Greg Clayton8de27c72010-10-15 22:48:33 +0000297 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000298
299 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
300 module_name,
301 m_compiler->getCodeGenOpts(),
302 m_compiler->getLLVMContext()));
303}
304
305ClangExpressionParser::~ClangExpressionParser()
306{
307}
308
309unsigned
310ClangExpressionParser::Parse (Stream &stream)
311{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000312 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
313
314 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000315
316 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
317 FileID memory_buffer_file_id = m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
318
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000319 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000320
321 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
322
323 if (ast_transformer)
324 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
325 else
326 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
327
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000328 diag_buf->EndSourceFile();
Sean Callanan65dafa82010-08-27 01:01:44 +0000329
330 TextDiagnosticBuffer::const_iterator diag_iterator;
331
332 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000333
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000334 for (diag_iterator = diag_buf->warn_begin();
335 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000336 ++diag_iterator)
337 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
338
339 num_errors = 0;
340
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000341 for (diag_iterator = diag_buf->err_begin();
342 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000343 ++diag_iterator)
344 {
345 num_errors++;
346 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
347 }
348
Sean Callanan7617c292010-11-01 20:28:09 +0000349 for (diag_iterator = diag_buf->note_begin();
350 diag_iterator != diag_buf->note_end();
351 ++diag_iterator)
352 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
353
Sean Callanan65dafa82010-08-27 01:01:44 +0000354 return num_errors;
355}
356
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000357static bool FindFunctionInModule (std::string &mangled_name,
358 llvm::Module *module,
359 const char *orig_name)
360{
361 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
362 fi != fe;
363 ++fi)
364 {
365 if (fi->getName().str().find(orig_name) != std::string::npos)
366 {
367 mangled_name = fi->getName().str();
368 return true;
369 }
370 }
371
372 return false;
373}
374
Sean Callanan65dafa82010-08-27 01:01:44 +0000375Error
376ClangExpressionParser::MakeDWARF ()
377{
378 Error err;
379
380 llvm::Module *module = m_code_generator->GetModule();
381
382 if (!module)
383 {
384 err.SetErrorToGenericError();
385 err.SetErrorString("IR doesn't contain a module");
386 return err;
387 }
388
Greg Clayton427f2902010-12-14 02:59:59 +0000389 ClangExpressionVariableList *local_variables = m_expr.LocalVariables();
Sean Callanan65dafa82010-08-27 01:01:44 +0000390 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
391
392 if (!local_variables)
393 {
394 err.SetErrorToGenericError();
395 err.SetErrorString("Can't convert an expression without a VariableList to DWARF");
396 return err;
397 }
398
399 if (!decl_map)
400 {
401 err.SetErrorToGenericError();
402 err.SetErrorString("Can't convert an expression without a DeclMap to DWARF");
403 return err;
404 }
405
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000406 std::string function_name;
407
408 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
409 {
410 err.SetErrorToGenericError();
411 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
412 return err;
413 }
414
415 IRToDWARF ir_to_dwarf(*local_variables, decl_map, m_expr.DwarfOpcodeStream(), function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000416
417 if (!ir_to_dwarf.runOnModule(*module))
418 {
419 err.SetErrorToGenericError();
420 err.SetErrorString("Couldn't convert the expression to DWARF");
421 return err;
422 }
423
424 err.Clear();
425 return err;
426}
427
428Error
Greg Claytond0882d02011-01-19 23:00:49 +0000429ClangExpressionParser::MakeJIT (lldb::addr_t &func_allocation_addr,
430 lldb::addr_t &func_addr,
Sean Callanan830a9032010-08-27 23:31:21 +0000431 lldb::addr_t &func_end,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000432 ExecutionContext &exe_ctx,
433 lldb::ClangExpressionVariableSP *const_result)
Sean Callanan65dafa82010-08-27 01:01:44 +0000434{
Greg Claytond0882d02011-01-19 23:00:49 +0000435 func_allocation_addr = LLDB_INVALID_ADDRESS;
436 func_addr = LLDB_INVALID_ADDRESS;
437 func_end = LLDB_INVALID_ADDRESS;
Greg Claytone005f2c2010-11-06 01:53:30 +0000438 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000439
Sean Callanan65dafa82010-08-27 01:01:44 +0000440 Error err;
441
442 llvm::Module *module = m_code_generator->ReleaseModule();
443
444 if (!module)
445 {
446 err.SetErrorToGenericError();
447 err.SetErrorString("IR doesn't contain a module");
448 return err;
449 }
450
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000451 // Find the actual name of the function (it's often mangled somehow)
452
453 std::string function_name;
454
455 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
456 {
457 err.SetErrorToGenericError();
458 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
459 return err;
460 }
461 else
462 {
463 if(log)
464 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
465 }
466
Sean Callanan65dafa82010-08-27 01:01:44 +0000467 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
468
469 if (decl_map)
470 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000471 Stream *error_stream = NULL;
472
473 if (exe_ctx.target)
474 error_stream = &exe_ctx.target->GetDebugger().GetErrorStream();
475
Sean Callanane8a59a82010-09-13 21:34:21 +0000476 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000477 m_expr.NeedsVariableResolution(),
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000478 const_result,
Sean Callanan97c924e2011-01-27 01:07:04 +0000479 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000480 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000481
482 if (!ir_for_target.runOnModule(*module))
483 {
484 err.SetErrorToGenericError();
485 err.SetErrorString("Couldn't convert the expression to DWARF");
486 return err;
487 }
Sean Callananf18d91c2010-09-01 00:58:00 +0000488
Jim Inghamd1686902010-10-14 23:45:03 +0000489 if (m_expr.NeedsValidation() && exe_ctx.process->GetDynamicCheckers())
Sean Callananf18d91c2010-09-01 00:58:00 +0000490 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000491 IRDynamicChecks ir_dynamic_checks(*exe_ctx.process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000492
493 if (!ir_dynamic_checks.runOnModule(*module))
494 {
495 err.SetErrorToGenericError();
496 err.SetErrorString("Couldn't add dynamic checks to the expression");
497 return err;
498 }
499 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000500 }
501
Greg Claytond0882d02011-01-19 23:00:49 +0000502 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
503 // below so we don't need to free it.
504 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000505
506 std::string error_string;
Sean Callanan9ac3a962010-11-02 23:20:00 +0000507
Sean Callananc2c6f772010-10-26 00:31:56 +0000508 llvm::TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
509
Sean Callanan65dafa82010-08-27 01:01:44 +0000510 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
511 &error_string,
Greg Claytond0882d02011-01-19 23:00:49 +0000512 jit_memory_manager,
Sean Callananc2c6f772010-10-26 00:31:56 +0000513 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000514 true,
515 CodeModel::Small));
Sean Callanan9ac3a962010-11-02 23:20:00 +0000516
Sean Callanan65dafa82010-08-27 01:01:44 +0000517 if (!m_execution_engine.get())
518 {
519 err.SetErrorToGenericError();
520 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
521 return err;
522 }
523
524 m_execution_engine->DisableLazyCompilation();
525
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000526 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000527
528 // We don't actually need the function pointer here, this just forces it to get resolved.
529
530 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
531
532 // Errors usually cause failures in the JIT, but if we're lucky we get here.
533
534 if (!fun_ptr)
535 {
536 err.SetErrorToGenericError();
537 err.SetErrorString("Couldn't JIT the function");
538 return err;
539 }
540
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000541 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000542
543 ExecutionContext &exc_context(exe_ctx);
544
545 if (exc_context.process == NULL)
546 {
547 err.SetErrorToGenericError();
548 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
549 return err;
550 }
551
552 // Look over the regions allocated for the function compiled. The JIT
553 // tries to allocate the functions & stubs close together, so we should try to
554 // write them that way too...
555 // For now I only write functions with no stubs, globals, exception tables,
556 // etc. So I only need to write the functions.
557
558 size_t alloc_size = 0;
559
Greg Claytond0882d02011-01-19 23:00:49 +0000560 std::map<uint8_t *, uint8_t *>::iterator fun_pos = jit_memory_manager->m_functions.begin();
561 std::map<uint8_t *, uint8_t *>::iterator fun_end = jit_memory_manager->m_functions.end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000562
563 for (; fun_pos != fun_end; ++fun_pos)
564 alloc_size += (*fun_pos).second - (*fun_pos).first;
565
566 Error alloc_error;
Greg Claytond0882d02011-01-19 23:00:49 +0000567 func_allocation_addr = exc_context.process->AllocateMemory (alloc_size,
568 lldb::ePermissionsReadable|lldb::ePermissionsExecutable,
569 alloc_error);
Sean Callanan65dafa82010-08-27 01:01:44 +0000570
Greg Claytond0882d02011-01-19 23:00:49 +0000571 if (func_allocation_addr == LLDB_INVALID_ADDRESS)
Sean Callanan65dafa82010-08-27 01:01:44 +0000572 {
573 err.SetErrorToGenericError();
574 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
575 return err;
576 }
577
Greg Claytond0882d02011-01-19 23:00:49 +0000578 lldb::addr_t cursor = func_allocation_addr;
Sean Callanan65dafa82010-08-27 01:01:44 +0000579
Greg Claytond0882d02011-01-19 23:00:49 +0000580 for (fun_pos = jit_memory_manager->m_functions.begin(); fun_pos != fun_end; fun_pos++)
Sean Callanan65dafa82010-08-27 01:01:44 +0000581 {
582 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
583 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
584 size_t size = lend - lstart;
585
586 Error write_error;
587
588 if (exc_context.process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
589 {
590 err.SetErrorToGenericError();
591 err.SetErrorStringWithFormat("Couldn't copy JITted function into the target: %s", write_error.AsCString("unknown error"));
592 return err;
593 }
594
Greg Claytond0882d02011-01-19 23:00:49 +0000595 jit_memory_manager->AddToLocalToRemoteMap (lstart, size, cursor);
Sean Callanan65dafa82010-08-27 01:01:44 +0000596 cursor += size;
597 }
598
599 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
600
601 for (pos = m_jitted_functions.begin(); pos != end; pos++)
602 {
Greg Claytond0882d02011-01-19 23:00:49 +0000603 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000604
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000605 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000606 {
Greg Claytond0882d02011-01-19 23:00:49 +0000607 func_end = jit_memory_manager->GetRemoteRangeForLocal ((*pos).m_local_addr).second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000608 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000609 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000610 }
611
Sean Callanan6dff8272010-11-08 03:49:50 +0000612 if (log)
613 {
614 log->Printf("Code can be run in the target.");
615
616 StreamString disassembly_stream;
617
Greg Claytond0882d02011-01-19 23:00:49 +0000618 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000619
620 if (!err.Success())
621 {
622 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
623 }
624 else
625 {
626 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
627 }
628 }
629
Sean Callanan65dafa82010-08-27 01:01:44 +0000630 err.Clear();
631 return err;
632}
633
634Error
Greg Claytond0882d02011-01-19 23:00:49 +0000635ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000636{
Greg Claytone005f2c2010-11-06 01:53:30 +0000637 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000638
639 const char *name = m_expr.FunctionName();
640
641 Error ret;
642
643 ret.Clear();
644
645 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
646 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
647
648 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
649
650 for (pos = m_jitted_functions.begin(); pos < end; pos++)
651 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000652 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000653 {
654 func_local_addr = pos->m_local_addr;
655 func_remote_addr = pos->m_remote_addr;
656 }
657 }
658
659 if (func_local_addr == LLDB_INVALID_ADDRESS)
660 {
661 ret.SetErrorToGenericError();
662 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
663 return ret;
664 }
665
666 if(log)
667 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
668
669 std::pair <lldb::addr_t, lldb::addr_t> func_range;
670
Greg Claytond0882d02011-01-19 23:00:49 +0000671 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000672
673 if (func_range.first == 0 && func_range.second == 0)
674 {
675 ret.SetErrorToGenericError();
676 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
677 return ret;
678 }
679
680 if(log)
681 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
682
683 if (!exe_ctx.target)
684 {
685 ret.SetErrorToGenericError();
686 ret.SetErrorString("Couldn't find the target");
687 }
688
689 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
690
691 Error err;
692 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
693
694 if (!err.Success())
695 {
696 ret.SetErrorToGenericError();
697 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
698 return ret;
699 }
700
701 ArchSpec arch(exe_ctx.target->GetArchitecture());
702
703 Disassembler *disassembler = Disassembler::FindPlugin(arch);
704
705 if (disassembler == NULL)
706 {
707 ret.SetErrorToGenericError();
708 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.AsCString());
709 return ret;
710 }
711
712 if (!exe_ctx.process)
713 {
714 ret.SetErrorToGenericError();
715 ret.SetErrorString("Couldn't find the process");
716 return ret;
717 }
718
719 DataExtractor extractor(buffer_sp,
720 exe_ctx.process->GetByteOrder(),
721 exe_ctx.target->GetArchitecture().GetAddressByteSize());
722
Greg Claytone005f2c2010-11-06 01:53:30 +0000723 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000724 {
725 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000726 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000727 0,
728 extractor.GetByteSize(),
729 func_remote_addr,
730 16,
731 DataExtractor::TypeUInt8);
732 }
733
Greg Clayton5c4c7462010-10-06 03:09:58 +0000734 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX);
Sean Callanan65dafa82010-08-27 01:01:44 +0000735
Greg Clayton5c4c7462010-10-06 03:09:58 +0000736 InstructionList &instruction_list = disassembler->GetInstructionList();
Sean Callanan65dafa82010-08-27 01:01:44 +0000737
738 uint32_t bytes_offset = 0;
739
740 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
741 instruction_index < num_instructions;
742 ++instruction_index)
743 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000744 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000745 instruction->Dump (&stream,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000746 true,
Sean Callanan65dafa82010-08-27 01:01:44 +0000747 &extractor,
748 bytes_offset,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000749 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000750 true);
751 stream.PutChar('\n');
752 bytes_offset += instruction->GetByteSize();
753 }
754
755 return ret;
756}