blob: 0d693ce0aebf5c4ade03c92738f8cfede0849c51 [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 Callanan279584c2011-03-15 00:17:19 +000050#include "clang/StaticAnalyzer/Frontend/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"
Sean Callanan65dafa82010-08-27 01:01:44 +000055#include "llvm/LLVMContext.h"
Sean Callanan279584c2011-03-15 00:17:19 +000056#include "llvm/Module.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000057#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();
Sean Callanan279584c2011-03-15 00:17:19 +0000115 case ASTDumpXML: return new ASTDumpXMLAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000116 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();
Sean Callanan65dafa82010-08-27 01:01:44 +0000130 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();
Sean Callananad293092011-01-18 23:32:05 +0000156 //case RunAnalysis: return new AnalysisAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000157 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
Greg Clayton395fc332011-02-15 21:59:32 +0000180ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
181 ClangExpression &expr) :
182 m_expr (expr),
Sean Callanan65dafa82010-08-27 01:01:44 +0000183 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;
Greg Clayton395fc332011-02-15 21:59:32 +0000195
Sean Callanan65dafa82010-08-27 01:01:44 +0000196 // 1. Create a new compiler instance.
197 m_compiler.reset(new CompilerInstance());
Sean Callanan65dafa82010-08-27 01:01:44 +0000198
199 // 2. Set options.
200
201 // Parse expressions as Objective C++ regardless of context.
202 // Our hook into Clang's lookup mechanism only works in C++.
203 m_compiler->getLangOpts().CPlusPlus = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000204
205 // Setup objective C
Sean Callanan65dafa82010-08-27 01:01:44 +0000206 m_compiler->getLangOpts().ObjC1 = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000207 m_compiler->getLangOpts().ObjC2 = true;
Sean Callananc7674af2011-01-17 23:42:46 +0000208
Greg Clayton395fc332011-02-15 21:59:32 +0000209 Process *process = NULL;
210 if (exe_scope)
211 process = exe_scope->CalculateProcess();
212
Sean Callananc7674af2011-01-17 23:42:46 +0000213 if (process)
214 {
215 if (process->GetObjCLanguageRuntime())
216 {
Greg Claytonb3448432011-03-24 21:19:54 +0000217 if (process->GetObjCLanguageRuntime()->GetRuntimeVersion() == eAppleObjC_V2)
Sean Callananc7674af2011-01-17 23:42:46 +0000218 {
219 m_compiler->getLangOpts().ObjCNonFragileABI = true; // NOT i386
220 m_compiler->getLangOpts().ObjCNonFragileABI2 = true; // NOT i386
221 }
222 }
223 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000224
Sean Callanan65dafa82010-08-27 01:01:44 +0000225 m_compiler->getLangOpts().ThreadsafeStatics = false;
226 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
227 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
228
229 // Set CodeGen options
230 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
231 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
232
233 // Disable some warnings.
234 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
235
236 // Set the target triple.
Greg Clayton395fc332011-02-15 21:59:32 +0000237 Target *target = NULL;
238 if (exe_scope)
239 target = exe_scope->CalculateTarget();
240
241 // TODO: figure out what to really do when we don't have a valid target.
242 // Sometimes this will be ok to just use the host target triple (when we
243 // evaluate say "2+3", but other expressions like breakpoint conditions
244 // and other things that _are_ target specific really shouldn't just be
245 // using the host triple. This needs to be fixed in a better way.
246 if (target && target->GetArchitecture().IsValid())
Sean Callanan2a8c3382011-04-14 02:01:31 +0000247 {
248 std::string triple = target->GetArchitecture().GetTriple().str();
249
250 int dash_count = 0;
251 for (int i = 0; i < triple.size(); ++i)
252 {
253 if (triple[i] == '-')
254 dash_count++;
255 if (dash_count == 3)
256 {
257 triple.resize(i);
258 break;
259 }
260 }
261
262 m_compiler->getTargetOpts().Triple = triple;
263 }
Greg Clayton395fc332011-02-15 21:59:32 +0000264 else
Sean Callanan2a8c3382011-04-14 02:01:31 +0000265 {
Greg Clayton395fc332011-02-15 21:59:32 +0000266 m_compiler->getTargetOpts().Triple = llvm::sys::getHostTriple();
Sean Callanan2a8c3382011-04-14 02:01:31 +0000267 }
268
Sean Callanan65dafa82010-08-27 01:01:44 +0000269 // 3. Set up various important bits of infrastructure.
270 m_compiler->createDiagnostics(0, 0);
271
272 // Create the target instance.
273 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
274 m_compiler->getTargetOpts()));
275
276 assert (m_compiler->hasTarget());
277
278 // Inform the target of the language options
279 //
280 // FIXME: We shouldn't need to do this, the target should be immutable once
281 // created. This complexity should be lifted elsewhere.
282 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
283
284 // 4. Set up the diagnostic buffer for reporting errors
285
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000286 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000287
288 // 5. Set up the source management objects inside the compiler
289
Greg Clayton22defe82010-12-02 23:20:03 +0000290 clang::FileSystemOptions file_system_options;
291 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000292
Sean Callanan65dafa82010-08-27 01:01:44 +0000293 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000294 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000295
296 m_compiler->createFileManager();
297 m_compiler->createPreprocessor();
298
299 // 6. Most of this we get from the CompilerInstance, but we
300 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000301 m_selector_table.reset(new SelectorTable());
Sean Callanan65dafa82010-08-27 01:01:44 +0000302 m_builtin_context.reset(new Builtin::Context(m_compiler->getTarget()));
303
304 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
305 m_compiler->getSourceManager(),
306 m_compiler->getTarget(),
307 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000308 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000309 *m_builtin_context.get(),
310 0));
311
312 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
313
314 if (decl_map)
315 {
316 OwningPtr<clang::ExternalASTSource> ast_source(new ClangASTSource(*ast_context, *decl_map));
317 ast_context->setExternalSource(ast_source);
318 }
319
320 m_compiler->setASTContext(ast_context.release());
321
Greg Clayton8de27c72010-10-15 22:48:33 +0000322 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000323
Sean Callanan279584c2011-03-15 00:17:19 +0000324 m_llvm_context.reset(new LLVMContext());
Sean Callanan65dafa82010-08-27 01:01:44 +0000325 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
326 module_name,
327 m_compiler->getCodeGenOpts(),
Sean Callanan279584c2011-03-15 00:17:19 +0000328 *m_llvm_context));
Sean Callanan65dafa82010-08-27 01:01:44 +0000329}
330
331ClangExpressionParser::~ClangExpressionParser()
332{
333}
334
335unsigned
336ClangExpressionParser::Parse (Stream &stream)
337{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000338 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
339
340 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000341
342 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
343 FileID memory_buffer_file_id = m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
344
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000345 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000346
347 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
348
349 if (ast_transformer)
350 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
351 else
352 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
353
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000354 diag_buf->EndSourceFile();
Sean Callanan65dafa82010-08-27 01:01:44 +0000355
356 TextDiagnosticBuffer::const_iterator diag_iterator;
357
358 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000359
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000360 for (diag_iterator = diag_buf->warn_begin();
361 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000362 ++diag_iterator)
363 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
364
365 num_errors = 0;
366
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000367 for (diag_iterator = diag_buf->err_begin();
368 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000369 ++diag_iterator)
370 {
371 num_errors++;
372 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
373 }
374
Sean Callanan7617c292010-11-01 20:28:09 +0000375 for (diag_iterator = diag_buf->note_begin();
376 diag_iterator != diag_buf->note_end();
377 ++diag_iterator)
378 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
379
Sean Callanan65dafa82010-08-27 01:01:44 +0000380 return num_errors;
381}
382
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000383static bool FindFunctionInModule (std::string &mangled_name,
384 llvm::Module *module,
385 const char *orig_name)
386{
387 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
388 fi != fe;
389 ++fi)
390 {
391 if (fi->getName().str().find(orig_name) != std::string::npos)
392 {
393 mangled_name = fi->getName().str();
394 return true;
395 }
396 }
397
398 return false;
399}
400
Sean Callanan65dafa82010-08-27 01:01:44 +0000401Error
402ClangExpressionParser::MakeDWARF ()
403{
404 Error err;
405
406 llvm::Module *module = m_code_generator->GetModule();
407
408 if (!module)
409 {
410 err.SetErrorToGenericError();
411 err.SetErrorString("IR doesn't contain a module");
412 return err;
413 }
414
Greg Clayton427f2902010-12-14 02:59:59 +0000415 ClangExpressionVariableList *local_variables = m_expr.LocalVariables();
Sean Callanan65dafa82010-08-27 01:01:44 +0000416 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
417
418 if (!local_variables)
419 {
420 err.SetErrorToGenericError();
421 err.SetErrorString("Can't convert an expression without a VariableList to DWARF");
422 return err;
423 }
424
425 if (!decl_map)
426 {
427 err.SetErrorToGenericError();
428 err.SetErrorString("Can't convert an expression without a DeclMap to DWARF");
429 return err;
430 }
431
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000432 std::string function_name;
433
434 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
435 {
436 err.SetErrorToGenericError();
437 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
438 return err;
439 }
440
441 IRToDWARF ir_to_dwarf(*local_variables, decl_map, m_expr.DwarfOpcodeStream(), function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000442
443 if (!ir_to_dwarf.runOnModule(*module))
444 {
445 err.SetErrorToGenericError();
446 err.SetErrorString("Couldn't convert the expression to DWARF");
447 return err;
448 }
449
450 err.Clear();
451 return err;
452}
453
454Error
Greg Claytond0882d02011-01-19 23:00:49 +0000455ClangExpressionParser::MakeJIT (lldb::addr_t &func_allocation_addr,
456 lldb::addr_t &func_addr,
Sean Callanan830a9032010-08-27 23:31:21 +0000457 lldb::addr_t &func_end,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000458 ExecutionContext &exe_ctx,
459 lldb::ClangExpressionVariableSP *const_result)
Sean Callanan65dafa82010-08-27 01:01:44 +0000460{
Greg Claytond0882d02011-01-19 23:00:49 +0000461 func_allocation_addr = LLDB_INVALID_ADDRESS;
462 func_addr = LLDB_INVALID_ADDRESS;
463 func_end = LLDB_INVALID_ADDRESS;
Greg Claytone005f2c2010-11-06 01:53:30 +0000464 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000465
Sean Callanan65dafa82010-08-27 01:01:44 +0000466 Error err;
467
468 llvm::Module *module = m_code_generator->ReleaseModule();
469
470 if (!module)
471 {
472 err.SetErrorToGenericError();
473 err.SetErrorString("IR doesn't contain a module");
474 return err;
475 }
476
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000477 // Find the actual name of the function (it's often mangled somehow)
478
479 std::string function_name;
480
481 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
482 {
483 err.SetErrorToGenericError();
484 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
485 return err;
486 }
487 else
488 {
489 if(log)
490 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
491 }
492
Sean Callanan65dafa82010-08-27 01:01:44 +0000493 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
494
495 if (decl_map)
496 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000497 Stream *error_stream = NULL;
498
499 if (exe_ctx.target)
500 error_stream = &exe_ctx.target->GetDebugger().GetErrorStream();
501
Sean Callanane8a59a82010-09-13 21:34:21 +0000502 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000503 m_expr.NeedsVariableResolution(),
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000504 const_result,
Sean Callanan97c924e2011-01-27 01:07:04 +0000505 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000506 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000507
508 if (!ir_for_target.runOnModule(*module))
509 {
510 err.SetErrorToGenericError();
511 err.SetErrorString("Couldn't convert the expression to DWARF");
512 return err;
513 }
Sean Callananf18d91c2010-09-01 00:58:00 +0000514
Jim Inghamd1686902010-10-14 23:45:03 +0000515 if (m_expr.NeedsValidation() && exe_ctx.process->GetDynamicCheckers())
Sean Callananf18d91c2010-09-01 00:58:00 +0000516 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000517 IRDynamicChecks ir_dynamic_checks(*exe_ctx.process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000518
519 if (!ir_dynamic_checks.runOnModule(*module))
520 {
521 err.SetErrorToGenericError();
522 err.SetErrorString("Couldn't add dynamic checks to the expression");
523 return err;
524 }
525 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000526 }
527
Greg Claytond0882d02011-01-19 23:00:49 +0000528 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
529 // below so we don't need to free it.
530 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000531
532 std::string error_string;
Sean Callanan9ac3a962010-11-02 23:20:00 +0000533
Sean Callananc2c6f772010-10-26 00:31:56 +0000534 llvm::TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
535
Sean Callanan65dafa82010-08-27 01:01:44 +0000536 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
537 &error_string,
Greg Claytond0882d02011-01-19 23:00:49 +0000538 jit_memory_manager,
Sean Callananc2c6f772010-10-26 00:31:56 +0000539 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000540 true,
541 CodeModel::Small));
Sean Callanan9ac3a962010-11-02 23:20:00 +0000542
Sean Callanan65dafa82010-08-27 01:01:44 +0000543 if (!m_execution_engine.get())
544 {
545 err.SetErrorToGenericError();
546 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
547 return err;
548 }
549
550 m_execution_engine->DisableLazyCompilation();
551
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000552 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000553
554 // We don't actually need the function pointer here, this just forces it to get resolved.
555
556 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
557
558 // Errors usually cause failures in the JIT, but if we're lucky we get here.
559
560 if (!fun_ptr)
561 {
562 err.SetErrorToGenericError();
563 err.SetErrorString("Couldn't JIT the function");
564 return err;
565 }
566
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000567 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000568
569 ExecutionContext &exc_context(exe_ctx);
570
571 if (exc_context.process == NULL)
572 {
573 err.SetErrorToGenericError();
574 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
575 return err;
576 }
577
578 // Look over the regions allocated for the function compiled. The JIT
579 // tries to allocate the functions & stubs close together, so we should try to
580 // write them that way too...
581 // For now I only write functions with no stubs, globals, exception tables,
582 // etc. So I only need to write the functions.
583
584 size_t alloc_size = 0;
585
Greg Claytond0882d02011-01-19 23:00:49 +0000586 std::map<uint8_t *, uint8_t *>::iterator fun_pos = jit_memory_manager->m_functions.begin();
587 std::map<uint8_t *, uint8_t *>::iterator fun_end = jit_memory_manager->m_functions.end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000588
589 for (; fun_pos != fun_end; ++fun_pos)
590 alloc_size += (*fun_pos).second - (*fun_pos).first;
591
592 Error alloc_error;
Greg Claytond0882d02011-01-19 23:00:49 +0000593 func_allocation_addr = exc_context.process->AllocateMemory (alloc_size,
594 lldb::ePermissionsReadable|lldb::ePermissionsExecutable,
595 alloc_error);
Sean Callanan65dafa82010-08-27 01:01:44 +0000596
Greg Claytond0882d02011-01-19 23:00:49 +0000597 if (func_allocation_addr == LLDB_INVALID_ADDRESS)
Sean Callanan65dafa82010-08-27 01:01:44 +0000598 {
599 err.SetErrorToGenericError();
600 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
601 return err;
602 }
603
Greg Claytond0882d02011-01-19 23:00:49 +0000604 lldb::addr_t cursor = func_allocation_addr;
Sean Callanan65dafa82010-08-27 01:01:44 +0000605
Greg Claytond0882d02011-01-19 23:00:49 +0000606 for (fun_pos = jit_memory_manager->m_functions.begin(); fun_pos != fun_end; fun_pos++)
Sean Callanan65dafa82010-08-27 01:01:44 +0000607 {
608 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
609 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
610 size_t size = lend - lstart;
611
612 Error write_error;
613
614 if (exc_context.process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
615 {
616 err.SetErrorToGenericError();
617 err.SetErrorStringWithFormat("Couldn't copy JITted function into the target: %s", write_error.AsCString("unknown error"));
618 return err;
619 }
620
Greg Claytond0882d02011-01-19 23:00:49 +0000621 jit_memory_manager->AddToLocalToRemoteMap (lstart, size, cursor);
Sean Callanan65dafa82010-08-27 01:01:44 +0000622 cursor += size;
623 }
624
625 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
626
627 for (pos = m_jitted_functions.begin(); pos != end; pos++)
628 {
Greg Claytond0882d02011-01-19 23:00:49 +0000629 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000630
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000631 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000632 {
Greg Claytond0882d02011-01-19 23:00:49 +0000633 func_end = jit_memory_manager->GetRemoteRangeForLocal ((*pos).m_local_addr).second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000634 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000635 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000636 }
637
Sean Callanan6dff8272010-11-08 03:49:50 +0000638 if (log)
639 {
640 log->Printf("Code can be run in the target.");
641
642 StreamString disassembly_stream;
643
Greg Claytond0882d02011-01-19 23:00:49 +0000644 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000645
646 if (!err.Success())
647 {
648 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
649 }
650 else
651 {
652 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
653 }
654 }
655
Sean Callanan65dafa82010-08-27 01:01:44 +0000656 err.Clear();
657 return err;
658}
659
660Error
Greg Claytond0882d02011-01-19 23:00:49 +0000661ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000662{
Greg Claytone005f2c2010-11-06 01:53:30 +0000663 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000664
665 const char *name = m_expr.FunctionName();
666
667 Error ret;
668
669 ret.Clear();
670
671 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
672 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
673
674 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
675
676 for (pos = m_jitted_functions.begin(); pos < end; pos++)
677 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000678 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000679 {
680 func_local_addr = pos->m_local_addr;
681 func_remote_addr = pos->m_remote_addr;
682 }
683 }
684
685 if (func_local_addr == LLDB_INVALID_ADDRESS)
686 {
687 ret.SetErrorToGenericError();
688 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
689 return ret;
690 }
691
692 if(log)
693 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
694
695 std::pair <lldb::addr_t, lldb::addr_t> func_range;
696
Greg Claytond0882d02011-01-19 23:00:49 +0000697 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000698
699 if (func_range.first == 0 && func_range.second == 0)
700 {
701 ret.SetErrorToGenericError();
702 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
703 return ret;
704 }
705
706 if(log)
707 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
708
709 if (!exe_ctx.target)
710 {
711 ret.SetErrorToGenericError();
712 ret.SetErrorString("Couldn't find the target");
713 }
714
715 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
716
717 Error err;
718 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
719
720 if (!err.Success())
721 {
722 ret.SetErrorToGenericError();
723 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
724 return ret;
725 }
726
727 ArchSpec arch(exe_ctx.target->GetArchitecture());
728
Greg Clayton149731c2011-03-25 18:03:16 +0000729 Disassembler *disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000730
731 if (disassembler == NULL)
732 {
733 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000734 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000735 return ret;
736 }
737
738 if (!exe_ctx.process)
739 {
740 ret.SetErrorToGenericError();
741 ret.SetErrorString("Couldn't find the process");
742 return ret;
743 }
744
745 DataExtractor extractor(buffer_sp,
746 exe_ctx.process->GetByteOrder(),
747 exe_ctx.target->GetArchitecture().GetAddressByteSize());
748
Greg Claytone005f2c2010-11-06 01:53:30 +0000749 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000750 {
751 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000752 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000753 0,
754 extractor.GetByteSize(),
755 func_remote_addr,
756 16,
757 DataExtractor::TypeUInt8);
758 }
759
Jim Inghamaa3e3e12011-03-22 01:48:42 +0000760 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000761
Greg Clayton5c4c7462010-10-06 03:09:58 +0000762 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000763 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000764 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
765 instruction_index < num_instructions;
766 ++instruction_index)
767 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000768 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000769 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000770 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000771 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000772 true,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000773 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000774 true);
775 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000776 }
777
778 return ret;
779}