blob: a2385c8149dae325f4f08cd4f2be016d9aea14bf [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"
24#include "lldb/Target/Process.h"
25#include "lldb/Target/Target.h"
26
27#include "clang/AST/ASTContext.h"
28#include "clang/AST/ExternalASTSource.h"
29#include "clang/Basic/FileManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/Version.h"
32#include "clang/Checker/FrontendActions.h"
33#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"
44#include "clang/Frontend/VerifyDiagnosticsClient.h"
45#include "clang/Lex/Preprocessor.h"
Sean Callanan47a5c4c2010-09-23 03:01:22 +000046#include "clang/Parse/ParseAST.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000047#include "clang/Rewrite/FrontendActions.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000048#include "clang/Sema/SemaConsumer.h"
49
50#include "llvm/ADT/StringRef.h"
51#include "llvm/ExecutionEngine/ExecutionEngine.h"
52#include "llvm/ExecutionEngine/JIT.h"
53#include "llvm/Module.h"
54#include "llvm/LLVMContext.h"
55#include "llvm/Support/ErrorHandling.h"
56#include "llvm/Support/MemoryBuffer.h"
57#include "llvm/System/DynamicLibrary.h"
58#include "llvm/System/Host.h"
59#include "llvm/System/Signals.h"
60#include "llvm/Target/TargetRegistry.h"
61#include "llvm/Target/TargetSelect.h"
62
63using namespace clang;
64using namespace llvm;
65using namespace lldb_private;
66
67//===----------------------------------------------------------------------===//
68// Utility Methods for Clang
69//===----------------------------------------------------------------------===//
70
71std::string GetBuiltinIncludePath(const char *Argv0) {
72 llvm::sys::Path P =
73 llvm::sys::Path::GetMainExecutable(Argv0,
74 (void*)(intptr_t) GetBuiltinIncludePath);
75
76 if (!P.isEmpty()) {
77 P.eraseComponent(); // Remove /clang from foo/bin/clang
78 P.eraseComponent(); // Remove /bin from foo/bin
79
80 // Get foo/lib/clang/<version>/include
81 P.appendComponent("lib");
82 P.appendComponent("clang");
83 P.appendComponent(CLANG_VERSION_STRING);
84 P.appendComponent("include");
85 }
86
87 return P.str();
88}
89
90
91//===----------------------------------------------------------------------===//
92// Main driver for Clang
93//===----------------------------------------------------------------------===//
94
95static void LLVMErrorHandler(void *UserData, const std::string &Message) {
96 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
97
98 Diags.Report(diag::err_fe_error_backend) << Message;
99
100 // We cannot recover from llvm errors.
101 exit(1);
102}
103
104static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
105 using namespace clang::frontend;
106
107 switch (CI.getFrontendOpts().ProgramAction) {
108 default:
109 llvm_unreachable("Invalid program action!");
110
111 case ASTDump: return new ASTDumpAction();
112 case ASTPrint: return new ASTPrintAction();
113 case ASTPrintXML: return new ASTPrintXMLAction();
114 case ASTView: return new ASTViewAction();
115 case BoostCon: return new BoostConAction();
116 case DumpRawTokens: return new DumpRawTokensAction();
117 case DumpTokens: return new DumpTokensAction();
118 case EmitAssembly: return new EmitAssemblyAction();
119 case EmitBC: return new EmitBCAction();
120 case EmitHTML: return new HTMLPrintAction();
121 case EmitLLVM: return new EmitLLVMAction();
122 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
123 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
124 case EmitObj: return new EmitObjAction();
125 case FixIt: return new FixItAction();
126 case GeneratePCH: return new GeneratePCHAction();
127 case GeneratePTH: return new GeneratePTHAction();
128 case InheritanceView: return new InheritanceViewAction();
129 case InitOnly: return new InitOnlyAction();
130 case ParseSyntaxOnly: return new SyntaxOnlyAction();
131
132 case PluginAction: {
133 for (FrontendPluginRegistry::iterator it =
134 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
135 it != ie; ++it) {
136 if (it->getName() == CI.getFrontendOpts().ActionName) {
137 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
138 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
139 return 0;
140 return P.take();
141 }
142 }
143
144 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
145 << CI.getFrontendOpts().ActionName;
146 return 0;
147 }
148
149 case PrintDeclContext: return new DeclContextPrintAction();
150 case PrintPreamble: return new PrintPreambleAction();
151 case PrintPreprocessedInput: return new PrintPreprocessedAction();
152 case RewriteMacros: return new RewriteMacrosAction();
153 case RewriteObjC: return new RewriteObjCAction();
154 case RewriteTest: return new RewriteTestAction();
155 case RunAnalysis: return new AnalysisAction();
156 case RunPreprocessorOnly: return new PreprocessOnlyAction();
157 }
158}
159
160static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
161 // Create the underlying action.
162 FrontendAction *Act = CreateFrontendBaseAction(CI);
163 if (!Act)
164 return 0;
165
166 // If there are any AST files to merge, create a frontend action
167 // adaptor to perform the merge.
168 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
169 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
170 CI.getFrontendOpts().ASTMergeFiles.size());
171
172 return Act;
173}
174
175//===----------------------------------------------------------------------===//
176// Implementation of ClangExpressionParser
177//===----------------------------------------------------------------------===//
178
179ClangExpressionParser::ClangExpressionParser(const char *target_triple,
180 ClangExpression &expr) :
181 m_expr(expr),
182 m_target_triple (),
183 m_compiler (),
184 m_code_generator (NULL),
185 m_execution_engine (),
186 m_jitted_functions ()
187{
188 // Initialize targets first, so that --version shows registered targets.
189 static struct InitializeLLVM {
190 InitializeLLVM() {
191 llvm::InitializeAllTargets();
192 llvm::InitializeAllAsmPrinters();
193 }
194 } InitializeLLVM;
195
196 if (target_triple && target_triple[0])
197 m_target_triple = target_triple;
198 else
199 m_target_triple = llvm::sys::getHostTriple();
200
201 // 1. Create a new compiler instance.
202 m_compiler.reset(new CompilerInstance());
203 m_compiler->setLLVMContext(new LLVMContext());
204
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;
210 m_compiler->getLangOpts().ObjC1 = true;
211 m_compiler->getLangOpts().ThreadsafeStatics = false;
212 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
213 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
214
215 // Set CodeGen options
216 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
217 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
218
219 // Disable some warnings.
220 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
221
222 // Set the target triple.
223 m_compiler->getTargetOpts().Triple = m_target_triple;
224
225 // 3. Set up various important bits of infrastructure.
226 m_compiler->createDiagnostics(0, 0);
227
228 // Create the target instance.
229 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
230 m_compiler->getTargetOpts()));
231
232 assert (m_compiler->hasTarget());
233
234 // Inform the target of the language options
235 //
236 // FIXME: We shouldn't need to do this, the target should be immutable once
237 // created. This complexity should be lifted elsewhere.
238 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
239
240 // 4. Set up the diagnostic buffer for reporting errors
241
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000242 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000243
244 // 5. Set up the source management objects inside the compiler
245
246 if (!m_compiler->hasSourceManager())
247 m_compiler->createSourceManager();
248
249 m_compiler->createFileManager();
250 m_compiler->createPreprocessor();
251
252 // 6. Most of this we get from the CompilerInstance, but we
253 // also want to give the context an ExternalASTSource.
254 SelectorTable selector_table;
255 m_builtin_context.reset(new Builtin::Context(m_compiler->getTarget()));
256
257 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
258 m_compiler->getSourceManager(),
259 m_compiler->getTarget(),
260 m_compiler->getPreprocessor().getIdentifierTable(),
261 selector_table,
262 *m_builtin_context.get(),
263 0));
264
265 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
266
267 if (decl_map)
268 {
269 OwningPtr<clang::ExternalASTSource> ast_source(new ClangASTSource(*ast_context, *decl_map));
270 ast_context->setExternalSource(ast_source);
271 }
272
273 m_compiler->setASTContext(ast_context.release());
274
Greg Clayton8de27c72010-10-15 22:48:33 +0000275 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000276
277 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
278 module_name,
279 m_compiler->getCodeGenOpts(),
280 m_compiler->getLLVMContext()));
281}
282
283ClangExpressionParser::~ClangExpressionParser()
284{
285}
286
287unsigned
288ClangExpressionParser::Parse (Stream &stream)
289{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000290 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
291
292 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000293
294 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
295 FileID memory_buffer_file_id = m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
296
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000297 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000298
299 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
300
301 if (ast_transformer)
302 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
303 else
304 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
305
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000306 diag_buf->EndSourceFile();
Sean Callanan65dafa82010-08-27 01:01:44 +0000307
308 TextDiagnosticBuffer::const_iterator diag_iterator;
309
310 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000311
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000312 for (diag_iterator = diag_buf->warn_begin();
313 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000314 ++diag_iterator)
315 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
316
317 num_errors = 0;
318
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000319 for (diag_iterator = diag_buf->err_begin();
320 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000321 ++diag_iterator)
322 {
323 num_errors++;
324 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
325 }
326
Sean Callanan7617c292010-11-01 20:28:09 +0000327 for (diag_iterator = diag_buf->note_begin();
328 diag_iterator != diag_buf->note_end();
329 ++diag_iterator)
330 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
331
Sean Callanan65dafa82010-08-27 01:01:44 +0000332 return num_errors;
333}
334
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000335static bool FindFunctionInModule (std::string &mangled_name,
336 llvm::Module *module,
337 const char *orig_name)
338{
339 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
340 fi != fe;
341 ++fi)
342 {
343 if (fi->getName().str().find(orig_name) != std::string::npos)
344 {
345 mangled_name = fi->getName().str();
346 return true;
347 }
348 }
349
350 return false;
351}
352
Sean Callanan65dafa82010-08-27 01:01:44 +0000353Error
354ClangExpressionParser::MakeDWARF ()
355{
356 Error err;
357
358 llvm::Module *module = m_code_generator->GetModule();
359
360 if (!module)
361 {
362 err.SetErrorToGenericError();
363 err.SetErrorString("IR doesn't contain a module");
364 return err;
365 }
366
367 ClangExpressionVariableStore *local_variables = m_expr.LocalVariables();
368 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
369
370 if (!local_variables)
371 {
372 err.SetErrorToGenericError();
373 err.SetErrorString("Can't convert an expression without a VariableList to DWARF");
374 return err;
375 }
376
377 if (!decl_map)
378 {
379 err.SetErrorToGenericError();
380 err.SetErrorString("Can't convert an expression without a DeclMap to DWARF");
381 return err;
382 }
383
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000384 std::string function_name;
385
386 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
387 {
388 err.SetErrorToGenericError();
389 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
390 return err;
391 }
392
393 IRToDWARF ir_to_dwarf(*local_variables, decl_map, m_expr.DwarfOpcodeStream(), function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000394
395 if (!ir_to_dwarf.runOnModule(*module))
396 {
397 err.SetErrorToGenericError();
398 err.SetErrorString("Couldn't convert the expression to DWARF");
399 return err;
400 }
401
402 err.Clear();
403 return err;
404}
405
406Error
Sean Callanan830a9032010-08-27 23:31:21 +0000407ClangExpressionParser::MakeJIT (lldb::addr_t &func_addr,
408 lldb::addr_t &func_end,
409 ExecutionContext &exe_ctx)
Sean Callanan65dafa82010-08-27 01:01:44 +0000410{
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000411 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
412
Sean Callanan65dafa82010-08-27 01:01:44 +0000413 Error err;
414
415 llvm::Module *module = m_code_generator->ReleaseModule();
416
417 if (!module)
418 {
419 err.SetErrorToGenericError();
420 err.SetErrorString("IR doesn't contain a module");
421 return err;
422 }
423
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000424 // Find the actual name of the function (it's often mangled somehow)
425
426 std::string function_name;
427
428 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
429 {
430 err.SetErrorToGenericError();
431 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
432 return err;
433 }
434 else
435 {
436 if(log)
437 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
438 }
439
Sean Callanan65dafa82010-08-27 01:01:44 +0000440 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
441
442 if (decl_map)
443 {
Sean Callanane8a59a82010-09-13 21:34:21 +0000444 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000445 m_expr.NeedsVariableResolution(),
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000446 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000447
448 if (!ir_for_target.runOnModule(*module))
449 {
450 err.SetErrorToGenericError();
451 err.SetErrorString("Couldn't convert the expression to DWARF");
452 return err;
453 }
Sean Callananf18d91c2010-09-01 00:58:00 +0000454
Jim Inghamd1686902010-10-14 23:45:03 +0000455 if (m_expr.NeedsValidation() && exe_ctx.process->GetDynamicCheckers())
Sean Callananf18d91c2010-09-01 00:58:00 +0000456 {
Sean Callanan7a60b942010-10-08 01:58:41 +0000457 /*
458 Disabled temporarily - TODO Centralize and re-enable this inside Process to avoid race conditions
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000459 IRDynamicChecks ir_dynamic_checks(*exe_ctx.process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000460
461 if (!ir_dynamic_checks.runOnModule(*module))
462 {
463 err.SetErrorToGenericError();
464 err.SetErrorString("Couldn't add dynamic checks to the expression");
465 return err;
466 }
Sean Callanan7a60b942010-10-08 01:58:41 +0000467 */
Sean Callanane8a59a82010-09-13 21:34:21 +0000468 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000469 }
470
471 m_jit_mm = new RecordingMemoryManager();
472
473 std::string error_string;
474
Sean Callananc2c6f772010-10-26 00:31:56 +0000475 llvm::Reloc::Model relocation_model = llvm::TargetMachine::getRelocationModel();
476
477 llvm::TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
478
Sean Callanan65dafa82010-08-27 01:01:44 +0000479 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
480 &error_string,
481 m_jit_mm,
Sean Callananc2c6f772010-10-26 00:31:56 +0000482 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000483 true,
484 CodeModel::Small));
485
Sean Callananc2c6f772010-10-26 00:31:56 +0000486 llvm::TargetMachine::setRelocationModel(relocation_model);
487
Sean Callanan65dafa82010-08-27 01:01:44 +0000488 if (!m_execution_engine.get())
489 {
490 err.SetErrorToGenericError();
491 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
492 return err;
493 }
494
495 m_execution_engine->DisableLazyCompilation();
496
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000497 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000498
499 // We don't actually need the function pointer here, this just forces it to get resolved.
500
501 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
502
503 // Errors usually cause failures in the JIT, but if we're lucky we get here.
504
505 if (!fun_ptr)
506 {
507 err.SetErrorToGenericError();
508 err.SetErrorString("Couldn't JIT the function");
509 return err;
510 }
511
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000512 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000513
514 ExecutionContext &exc_context(exe_ctx);
515
516 if (exc_context.process == NULL)
517 {
518 err.SetErrorToGenericError();
519 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
520 return err;
521 }
522
523 // Look over the regions allocated for the function compiled. The JIT
524 // tries to allocate the functions & stubs close together, so we should try to
525 // write them that way too...
526 // For now I only write functions with no stubs, globals, exception tables,
527 // etc. So I only need to write the functions.
528
529 size_t alloc_size = 0;
530
531 std::map<uint8_t *, uint8_t *>::iterator fun_pos = m_jit_mm->m_functions.begin();
532 std::map<uint8_t *, uint8_t *>::iterator fun_end = m_jit_mm->m_functions.end();
533
534 for (; fun_pos != fun_end; ++fun_pos)
535 alloc_size += (*fun_pos).second - (*fun_pos).first;
536
537 Error alloc_error;
538 lldb::addr_t target_addr = exc_context.process->AllocateMemory (alloc_size, lldb::ePermissionsReadable|lldb::ePermissionsExecutable, alloc_error);
539
540 if (target_addr == LLDB_INVALID_ADDRESS)
541 {
542 err.SetErrorToGenericError();
543 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
544 return err;
545 }
546
547 lldb::addr_t cursor = target_addr;
548
549 for (fun_pos = m_jit_mm->m_functions.begin(); fun_pos != fun_end; fun_pos++)
550 {
551 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
552 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
553 size_t size = lend - lstart;
554
555 Error write_error;
556
557 if (exc_context.process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
558 {
559 err.SetErrorToGenericError();
560 err.SetErrorStringWithFormat("Couldn't copy JITted function into the target: %s", write_error.AsCString("unknown error"));
561 return err;
562 }
563
564 m_jit_mm->AddToLocalToRemoteMap (lstart, size, cursor);
565 cursor += size;
566 }
567
568 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
569
570 for (pos = m_jitted_functions.begin(); pos != end; pos++)
571 {
572 (*pos).m_remote_addr = m_jit_mm->GetRemoteAddressForLocal ((*pos).m_local_addr);
573
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000574 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000575 {
576 func_end = m_jit_mm->GetRemoteRangeForLocal ((*pos).m_local_addr).second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000577 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000578 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000579 }
580
581 err.Clear();
582 return err;
583}
584
585Error
586ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx)
587{
588 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
589
590 const char *name = m_expr.FunctionName();
591
592 Error ret;
593
594 ret.Clear();
595
596 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
597 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
598
599 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
600
601 for (pos = m_jitted_functions.begin(); pos < end; pos++)
602 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000603 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000604 {
605 func_local_addr = pos->m_local_addr;
606 func_remote_addr = pos->m_remote_addr;
607 }
608 }
609
610 if (func_local_addr == LLDB_INVALID_ADDRESS)
611 {
612 ret.SetErrorToGenericError();
613 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
614 return ret;
615 }
616
617 if(log)
618 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
619
620 std::pair <lldb::addr_t, lldb::addr_t> func_range;
621
622 func_range = m_jit_mm->GetRemoteRangeForLocal(func_local_addr);
623
624 if (func_range.first == 0 && func_range.second == 0)
625 {
626 ret.SetErrorToGenericError();
627 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
628 return ret;
629 }
630
631 if(log)
632 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
633
634 if (!exe_ctx.target)
635 {
636 ret.SetErrorToGenericError();
637 ret.SetErrorString("Couldn't find the target");
638 }
639
640 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
641
642 Error err;
643 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
644
645 if (!err.Success())
646 {
647 ret.SetErrorToGenericError();
648 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
649 return ret;
650 }
651
652 ArchSpec arch(exe_ctx.target->GetArchitecture());
653
654 Disassembler *disassembler = Disassembler::FindPlugin(arch);
655
656 if (disassembler == NULL)
657 {
658 ret.SetErrorToGenericError();
659 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.AsCString());
660 return ret;
661 }
662
663 if (!exe_ctx.process)
664 {
665 ret.SetErrorToGenericError();
666 ret.SetErrorString("Couldn't find the process");
667 return ret;
668 }
669
670 DataExtractor extractor(buffer_sp,
671 exe_ctx.process->GetByteOrder(),
672 exe_ctx.target->GetArchitecture().GetAddressByteSize());
673
674 if(log)
675 {
676 log->Printf("Function data has contents:");
677 extractor.PutToLog (log,
678 0,
679 extractor.GetByteSize(),
680 func_remote_addr,
681 16,
682 DataExtractor::TypeUInt8);
683 }
684
Greg Clayton5c4c7462010-10-06 03:09:58 +0000685 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX);
Sean Callanan65dafa82010-08-27 01:01:44 +0000686
Greg Clayton5c4c7462010-10-06 03:09:58 +0000687 InstructionList &instruction_list = disassembler->GetInstructionList();
Sean Callanan65dafa82010-08-27 01:01:44 +0000688
689 uint32_t bytes_offset = 0;
690
691 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
692 instruction_index < num_instructions;
693 ++instruction_index)
694 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000695 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000696 instruction->Dump (&stream,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000697 true,
Sean Callanan65dafa82010-08-27 01:01:44 +0000698 &extractor,
699 bytes_offset,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000700 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000701 true);
702 stream.PutChar('\n');
703 bytes_offset += instruction->GetByteSize();
704 }
705
706 return ret;
707}