blob: adc5a9ecb7ed518a9cbad6ccad36a51a7f5cc5ed [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"
14#include "lldb/Core/Disassembler.h"
15#include "lldb/Core/Stream.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000016#include "lldb/Core/StreamString.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000017#include "lldb/Expression/ClangASTSource.h"
18#include "lldb/Expression/ClangExpression.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000019#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000020#include "lldb/Expression/IRForTarget.h"
21#include "lldb/Expression/IRToDWARF.h"
22#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"
33#include "clang/Checker/FrontendActions.h"
34#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"
50
51#include "llvm/ADT/StringRef.h"
52#include "llvm/ExecutionEngine/ExecutionEngine.h"
53#include "llvm/ExecutionEngine/JIT.h"
54#include "llvm/Module.h"
55#include "llvm/LLVMContext.h"
56#include "llvm/Support/ErrorHandling.h"
57#include "llvm/Support/MemoryBuffer.h"
Greg Clayton22defe82010-12-02 23:20:03 +000058#include "llvm/Support/DynamicLibrary.h"
59#include "llvm/Support/Host.h"
60#include "llvm/Support/Signals.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000061#include "llvm/Target/TargetRegistry.h"
62#include "llvm/Target/TargetSelect.h"
63
64using namespace clang;
65using namespace llvm;
66using namespace lldb_private;
67
68//===----------------------------------------------------------------------===//
69// Utility Methods for Clang
70//===----------------------------------------------------------------------===//
71
72std::string GetBuiltinIncludePath(const char *Argv0) {
73 llvm::sys::Path P =
74 llvm::sys::Path::GetMainExecutable(Argv0,
75 (void*)(intptr_t) GetBuiltinIncludePath);
76
77 if (!P.isEmpty()) {
78 P.eraseComponent(); // Remove /clang from foo/bin/clang
79 P.eraseComponent(); // Remove /bin from foo/bin
80
81 // Get foo/lib/clang/<version>/include
82 P.appendComponent("lib");
83 P.appendComponent("clang");
84 P.appendComponent(CLANG_VERSION_STRING);
85 P.appendComponent("include");
86 }
87
88 return P.str();
89}
90
91
92//===----------------------------------------------------------------------===//
93// Main driver for Clang
94//===----------------------------------------------------------------------===//
95
96static void LLVMErrorHandler(void *UserData, const std::string &Message) {
97 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
98
99 Diags.Report(diag::err_fe_error_backend) << Message;
100
101 // We cannot recover from llvm errors.
102 exit(1);
103}
104
105static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
106 using namespace clang::frontend;
107
108 switch (CI.getFrontendOpts().ProgramAction) {
109 default:
110 llvm_unreachable("Invalid program action!");
111
112 case ASTDump: return new ASTDumpAction();
113 case ASTPrint: return new ASTPrintAction();
114 case ASTPrintXML: return new ASTPrintXMLAction();
115 case ASTView: return new ASTViewAction();
116 case BoostCon: return new BoostConAction();
117 case DumpRawTokens: return new DumpRawTokensAction();
118 case DumpTokens: return new DumpTokensAction();
119 case EmitAssembly: return new EmitAssemblyAction();
120 case EmitBC: return new EmitBCAction();
121 case EmitHTML: return new HTMLPrintAction();
122 case EmitLLVM: return new EmitLLVMAction();
123 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
124 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
125 case EmitObj: return new EmitObjAction();
126 case FixIt: return new FixItAction();
127 case GeneratePCH: return new GeneratePCHAction();
128 case GeneratePTH: return new GeneratePTHAction();
129 case InheritanceView: return new InheritanceViewAction();
130 case InitOnly: return new InitOnlyAction();
131 case ParseSyntaxOnly: return new SyntaxOnlyAction();
132
133 case PluginAction: {
134 for (FrontendPluginRegistry::iterator it =
135 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
136 it != ie; ++it) {
137 if (it->getName() == CI.getFrontendOpts().ActionName) {
138 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
139 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
140 return 0;
141 return P.take();
142 }
143 }
144
145 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
146 << CI.getFrontendOpts().ActionName;
147 return 0;
148 }
149
150 case PrintDeclContext: return new DeclContextPrintAction();
151 case PrintPreamble: return new PrintPreambleAction();
152 case PrintPreprocessedInput: return new PrintPreprocessedAction();
153 case RewriteMacros: return new RewriteMacrosAction();
154 case RewriteObjC: return new RewriteObjCAction();
155 case RewriteTest: return new RewriteTestAction();
156 case RunAnalysis: return new AnalysisAction();
157 case RunPreprocessorOnly: return new PreprocessOnlyAction();
158 }
159}
160
161static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
162 // Create the underlying action.
163 FrontendAction *Act = CreateFrontendBaseAction(CI);
164 if (!Act)
165 return 0;
166
167 // If there are any AST files to merge, create a frontend action
168 // adaptor to perform the merge.
169 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
170 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
171 CI.getFrontendOpts().ASTMergeFiles.size());
172
173 return Act;
174}
175
176//===----------------------------------------------------------------------===//
177// Implementation of ClangExpressionParser
178//===----------------------------------------------------------------------===//
179
180ClangExpressionParser::ClangExpressionParser(const char *target_triple,
Sean Callananc7674af2011-01-17 23:42:46 +0000181 Process *process,
Sean Callanan65dafa82010-08-27 01:01:44 +0000182 ClangExpression &expr) :
183 m_expr(expr),
184 m_target_triple (),
185 m_compiler (),
186 m_code_generator (NULL),
187 m_execution_engine (),
188 m_jitted_functions ()
189{
190 // Initialize targets first, so that --version shows registered targets.
191 static struct InitializeLLVM {
192 InitializeLLVM() {
193 llvm::InitializeAllTargets();
194 llvm::InitializeAllAsmPrinters();
195 }
196 } InitializeLLVM;
197
198 if (target_triple && target_triple[0])
199 m_target_triple = target_triple;
200 else
201 m_target_triple = llvm::sys::getHostTriple();
202
203 // 1. Create a new compiler instance.
204 m_compiler.reset(new CompilerInstance());
205 m_compiler->setLLVMContext(new LLVMContext());
206
207 // 2. Set options.
208
209 // Parse expressions as Objective C++ regardless of context.
210 // Our hook into Clang's lookup mechanism only works in C++.
211 m_compiler->getLangOpts().CPlusPlus = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000212
213 // Setup objective C
Sean Callanan65dafa82010-08-27 01:01:44 +0000214 m_compiler->getLangOpts().ObjC1 = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000215 m_compiler->getLangOpts().ObjC2 = true;
Sean Callananc7674af2011-01-17 23:42:46 +0000216
217 if (process)
218 {
219 if (process->GetObjCLanguageRuntime())
220 {
221 if (process->GetObjCLanguageRuntime()->GetRuntimeVersion() == lldb::eAppleObjC_V2)
222 {
223 m_compiler->getLangOpts().ObjCNonFragileABI = true; // NOT i386
224 m_compiler->getLangOpts().ObjCNonFragileABI2 = true; // NOT i386
225 }
226 }
227 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000228
Sean Callanan65dafa82010-08-27 01:01:44 +0000229 m_compiler->getLangOpts().ThreadsafeStatics = false;
230 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
231 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
232
233 // Set CodeGen options
234 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
235 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
236
237 // Disable some warnings.
238 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
239
240 // Set the target triple.
241 m_compiler->getTargetOpts().Triple = m_target_triple;
242
243 // 3. Set up various important bits of infrastructure.
244 m_compiler->createDiagnostics(0, 0);
245
246 // Create the target instance.
247 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
248 m_compiler->getTargetOpts()));
249
250 assert (m_compiler->hasTarget());
251
252 // Inform the target of the language options
253 //
254 // FIXME: We shouldn't need to do this, the target should be immutable once
255 // created. This complexity should be lifted elsewhere.
256 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
257
258 // 4. Set up the diagnostic buffer for reporting errors
259
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000260 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000261
262 // 5. Set up the source management objects inside the compiler
263
Greg Clayton22defe82010-12-02 23:20:03 +0000264 clang::FileSystemOptions file_system_options;
265 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000266
Sean Callanan65dafa82010-08-27 01:01:44 +0000267 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000268 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000269
270 m_compiler->createFileManager();
271 m_compiler->createPreprocessor();
272
273 // 6. Most of this we get from the CompilerInstance, but we
274 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000275 m_selector_table.reset(new SelectorTable());
Sean Callanan65dafa82010-08-27 01:01:44 +0000276 m_builtin_context.reset(new Builtin::Context(m_compiler->getTarget()));
277
278 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
279 m_compiler->getSourceManager(),
280 m_compiler->getTarget(),
281 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000282 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000283 *m_builtin_context.get(),
284 0));
285
286 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
287
288 if (decl_map)
289 {
290 OwningPtr<clang::ExternalASTSource> ast_source(new ClangASTSource(*ast_context, *decl_map));
291 ast_context->setExternalSource(ast_source);
292 }
293
294 m_compiler->setASTContext(ast_context.release());
295
Greg Clayton8de27c72010-10-15 22:48:33 +0000296 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000297
298 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
299 module_name,
300 m_compiler->getCodeGenOpts(),
301 m_compiler->getLLVMContext()));
302}
303
304ClangExpressionParser::~ClangExpressionParser()
305{
306}
307
308unsigned
309ClangExpressionParser::Parse (Stream &stream)
310{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000311 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
312
313 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000314
315 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
316 FileID memory_buffer_file_id = m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
317
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000318 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000319
320 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
321
322 if (ast_transformer)
323 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
324 else
325 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
326
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000327 diag_buf->EndSourceFile();
Sean Callanan65dafa82010-08-27 01:01:44 +0000328
329 TextDiagnosticBuffer::const_iterator diag_iterator;
330
331 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000332
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000333 for (diag_iterator = diag_buf->warn_begin();
334 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000335 ++diag_iterator)
336 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
337
338 num_errors = 0;
339
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000340 for (diag_iterator = diag_buf->err_begin();
341 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000342 ++diag_iterator)
343 {
344 num_errors++;
345 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
346 }
347
Sean Callanan7617c292010-11-01 20:28:09 +0000348 for (diag_iterator = diag_buf->note_begin();
349 diag_iterator != diag_buf->note_end();
350 ++diag_iterator)
351 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
352
Sean Callanan65dafa82010-08-27 01:01:44 +0000353 return num_errors;
354}
355
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000356static bool FindFunctionInModule (std::string &mangled_name,
357 llvm::Module *module,
358 const char *orig_name)
359{
360 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
361 fi != fe;
362 ++fi)
363 {
364 if (fi->getName().str().find(orig_name) != std::string::npos)
365 {
366 mangled_name = fi->getName().str();
367 return true;
368 }
369 }
370
371 return false;
372}
373
Sean Callanan65dafa82010-08-27 01:01:44 +0000374Error
375ClangExpressionParser::MakeDWARF ()
376{
377 Error err;
378
379 llvm::Module *module = m_code_generator->GetModule();
380
381 if (!module)
382 {
383 err.SetErrorToGenericError();
384 err.SetErrorString("IR doesn't contain a module");
385 return err;
386 }
387
Greg Clayton427f2902010-12-14 02:59:59 +0000388 ClangExpressionVariableList *local_variables = m_expr.LocalVariables();
Sean Callanan65dafa82010-08-27 01:01:44 +0000389 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
390
391 if (!local_variables)
392 {
393 err.SetErrorToGenericError();
394 err.SetErrorString("Can't convert an expression without a VariableList to DWARF");
395 return err;
396 }
397
398 if (!decl_map)
399 {
400 err.SetErrorToGenericError();
401 err.SetErrorString("Can't convert an expression without a DeclMap to DWARF");
402 return err;
403 }
404
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000405 std::string function_name;
406
407 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
408 {
409 err.SetErrorToGenericError();
410 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
411 return err;
412 }
413
414 IRToDWARF ir_to_dwarf(*local_variables, decl_map, m_expr.DwarfOpcodeStream(), function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000415
416 if (!ir_to_dwarf.runOnModule(*module))
417 {
418 err.SetErrorToGenericError();
419 err.SetErrorString("Couldn't convert the expression to DWARF");
420 return err;
421 }
422
423 err.Clear();
424 return err;
425}
426
427Error
Sean Callanan830a9032010-08-27 23:31:21 +0000428ClangExpressionParser::MakeJIT (lldb::addr_t &func_addr,
429 lldb::addr_t &func_end,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000430 ExecutionContext &exe_ctx,
431 lldb::ClangExpressionVariableSP *const_result)
Sean Callanan65dafa82010-08-27 01:01:44 +0000432{
Greg Claytone005f2c2010-11-06 01:53:30 +0000433 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000434
Sean Callanan65dafa82010-08-27 01:01:44 +0000435 Error err;
436
437 llvm::Module *module = m_code_generator->ReleaseModule();
438
439 if (!module)
440 {
441 err.SetErrorToGenericError();
442 err.SetErrorString("IR doesn't contain a module");
443 return err;
444 }
445
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000446 // Find the actual name of the function (it's often mangled somehow)
447
448 std::string function_name;
449
450 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
451 {
452 err.SetErrorToGenericError();
453 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
454 return err;
455 }
456 else
457 {
458 if(log)
459 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
460 }
461
Sean Callanan65dafa82010-08-27 01:01:44 +0000462 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
463
464 if (decl_map)
465 {
Sean Callanane8a59a82010-09-13 21:34:21 +0000466 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000467 m_expr.NeedsVariableResolution(),
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000468 const_result,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000469 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000470
471 if (!ir_for_target.runOnModule(*module))
472 {
473 err.SetErrorToGenericError();
474 err.SetErrorString("Couldn't convert the expression to DWARF");
475 return err;
476 }
Sean Callananf18d91c2010-09-01 00:58:00 +0000477
Jim Inghamd1686902010-10-14 23:45:03 +0000478 if (m_expr.NeedsValidation() && exe_ctx.process->GetDynamicCheckers())
Sean Callananf18d91c2010-09-01 00:58:00 +0000479 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000480 IRDynamicChecks ir_dynamic_checks(*exe_ctx.process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000481
482 if (!ir_dynamic_checks.runOnModule(*module))
483 {
484 err.SetErrorToGenericError();
485 err.SetErrorString("Couldn't add dynamic checks to the expression");
486 return err;
487 }
488 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000489 }
490
491 m_jit_mm = new RecordingMemoryManager();
492
493 std::string error_string;
Sean Callanan9ac3a962010-11-02 23:20:00 +0000494
Sean Callananc2c6f772010-10-26 00:31:56 +0000495 llvm::TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
496
Sean Callanan65dafa82010-08-27 01:01:44 +0000497 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
498 &error_string,
499 m_jit_mm,
Sean Callananc2c6f772010-10-26 00:31:56 +0000500 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000501 true,
502 CodeModel::Small));
Sean Callanan9ac3a962010-11-02 23:20:00 +0000503
Sean Callanan65dafa82010-08-27 01:01:44 +0000504 if (!m_execution_engine.get())
505 {
506 err.SetErrorToGenericError();
507 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
508 return err;
509 }
510
511 m_execution_engine->DisableLazyCompilation();
512
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000513 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000514
515 // We don't actually need the function pointer here, this just forces it to get resolved.
516
517 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
518
519 // Errors usually cause failures in the JIT, but if we're lucky we get here.
520
521 if (!fun_ptr)
522 {
523 err.SetErrorToGenericError();
524 err.SetErrorString("Couldn't JIT the function");
525 return err;
526 }
527
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000528 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000529
530 ExecutionContext &exc_context(exe_ctx);
531
532 if (exc_context.process == NULL)
533 {
534 err.SetErrorToGenericError();
535 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
536 return err;
537 }
538
539 // Look over the regions allocated for the function compiled. The JIT
540 // tries to allocate the functions & stubs close together, so we should try to
541 // write them that way too...
542 // For now I only write functions with no stubs, globals, exception tables,
543 // etc. So I only need to write the functions.
544
545 size_t alloc_size = 0;
546
547 std::map<uint8_t *, uint8_t *>::iterator fun_pos = m_jit_mm->m_functions.begin();
548 std::map<uint8_t *, uint8_t *>::iterator fun_end = m_jit_mm->m_functions.end();
549
550 for (; fun_pos != fun_end; ++fun_pos)
551 alloc_size += (*fun_pos).second - (*fun_pos).first;
552
553 Error alloc_error;
554 lldb::addr_t target_addr = exc_context.process->AllocateMemory (alloc_size, lldb::ePermissionsReadable|lldb::ePermissionsExecutable, alloc_error);
555
556 if (target_addr == LLDB_INVALID_ADDRESS)
557 {
558 err.SetErrorToGenericError();
559 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
560 return err;
561 }
562
563 lldb::addr_t cursor = target_addr;
564
565 for (fun_pos = m_jit_mm->m_functions.begin(); fun_pos != fun_end; fun_pos++)
566 {
567 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
568 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
569 size_t size = lend - lstart;
570
571 Error write_error;
572
573 if (exc_context.process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
574 {
575 err.SetErrorToGenericError();
576 err.SetErrorStringWithFormat("Couldn't copy JITted function into the target: %s", write_error.AsCString("unknown error"));
577 return err;
578 }
579
580 m_jit_mm->AddToLocalToRemoteMap (lstart, size, cursor);
581 cursor += size;
582 }
583
584 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
585
586 for (pos = m_jitted_functions.begin(); pos != end; pos++)
587 {
588 (*pos).m_remote_addr = m_jit_mm->GetRemoteAddressForLocal ((*pos).m_local_addr);
589
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000590 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000591 {
592 func_end = m_jit_mm->GetRemoteRangeForLocal ((*pos).m_local_addr).second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000593 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000594 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000595 }
596
Sean Callanan6dff8272010-11-08 03:49:50 +0000597 if (log)
598 {
599 log->Printf("Code can be run in the target.");
600
601 StreamString disassembly_stream;
602
603 Error err = DisassembleFunction(disassembly_stream, exe_ctx);
604
605 if (!err.Success())
606 {
607 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
608 }
609 else
610 {
611 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
612 }
613 }
614
Sean Callanan65dafa82010-08-27 01:01:44 +0000615 err.Clear();
616 return err;
617}
618
619Error
620ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx)
621{
Greg Claytone005f2c2010-11-06 01:53:30 +0000622 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000623
624 const char *name = m_expr.FunctionName();
625
626 Error ret;
627
628 ret.Clear();
629
630 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
631 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
632
633 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
634
635 for (pos = m_jitted_functions.begin(); pos < end; pos++)
636 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000637 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000638 {
639 func_local_addr = pos->m_local_addr;
640 func_remote_addr = pos->m_remote_addr;
641 }
642 }
643
644 if (func_local_addr == LLDB_INVALID_ADDRESS)
645 {
646 ret.SetErrorToGenericError();
647 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
648 return ret;
649 }
650
651 if(log)
652 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
653
654 std::pair <lldb::addr_t, lldb::addr_t> func_range;
655
656 func_range = m_jit_mm->GetRemoteRangeForLocal(func_local_addr);
657
658 if (func_range.first == 0 && func_range.second == 0)
659 {
660 ret.SetErrorToGenericError();
661 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
662 return ret;
663 }
664
665 if(log)
666 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
667
668 if (!exe_ctx.target)
669 {
670 ret.SetErrorToGenericError();
671 ret.SetErrorString("Couldn't find the target");
672 }
673
674 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
675
676 Error err;
677 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
678
679 if (!err.Success())
680 {
681 ret.SetErrorToGenericError();
682 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
683 return ret;
684 }
685
686 ArchSpec arch(exe_ctx.target->GetArchitecture());
687
688 Disassembler *disassembler = Disassembler::FindPlugin(arch);
689
690 if (disassembler == NULL)
691 {
692 ret.SetErrorToGenericError();
693 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.AsCString());
694 return ret;
695 }
696
697 if (!exe_ctx.process)
698 {
699 ret.SetErrorToGenericError();
700 ret.SetErrorString("Couldn't find the process");
701 return ret;
702 }
703
704 DataExtractor extractor(buffer_sp,
705 exe_ctx.process->GetByteOrder(),
706 exe_ctx.target->GetArchitecture().GetAddressByteSize());
707
Greg Claytone005f2c2010-11-06 01:53:30 +0000708 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000709 {
710 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000711 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000712 0,
713 extractor.GetByteSize(),
714 func_remote_addr,
715 16,
716 DataExtractor::TypeUInt8);
717 }
718
Greg Clayton5c4c7462010-10-06 03:09:58 +0000719 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX);
Sean Callanan65dafa82010-08-27 01:01:44 +0000720
Greg Clayton5c4c7462010-10-06 03:09:58 +0000721 InstructionList &instruction_list = disassembler->GetInstructionList();
Sean Callanan65dafa82010-08-27 01:01:44 +0000722
723 uint32_t bytes_offset = 0;
724
725 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
726 instruction_index < num_instructions;
727 ++instruction_index)
728 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000729 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000730 instruction->Dump (&stream,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000731 true,
Sean Callanan65dafa82010-08-27 01:01:44 +0000732 &extractor,
733 bytes_offset,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000734 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000735 true);
736 stream.PutChar('\n');
737 bytes_offset += instruction->GetByteSize();
738 }
739
740 return ret;
741}