blob: c8385c2bf94ae28714fdd63879259147b2324969 [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 Callananfb3058e2011-05-12 23:54:16 +000020#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000021#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000022#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"
Greg Clayton2f085c62011-05-15 01:25:55 +000054
Peter Collingbournec3f55732011-06-03 20:40:12 +000055#if !defined(__APPLE__)
56#define USE_STANDARD_JIT
57#endif
58
Greg Clayton2f085c62011-05-15 01:25:55 +000059#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +000060#include "llvm/ExecutionEngine/JIT.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000061#else
62#include "llvm/ExecutionEngine/MCJIT.h"
63#endif
Sean Callanan65dafa82010-08-27 01:01:44 +000064#include "llvm/LLVMContext.h"
Sean Callanan279584c2011-03-15 00:17:19 +000065#include "llvm/Module.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000066#include "llvm/Support/ErrorHandling.h"
67#include "llvm/Support/MemoryBuffer.h"
Greg Clayton22defe82010-12-02 23:20:03 +000068#include "llvm/Support/DynamicLibrary.h"
69#include "llvm/Support/Host.h"
70#include "llvm/Support/Signals.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000071#include "llvm/Target/TargetRegistry.h"
72#include "llvm/Target/TargetSelect.h"
73
74using namespace clang;
75using namespace llvm;
76using namespace lldb_private;
77
78//===----------------------------------------------------------------------===//
79// Utility Methods for Clang
80//===----------------------------------------------------------------------===//
81
82std::string GetBuiltinIncludePath(const char *Argv0) {
83 llvm::sys::Path P =
84 llvm::sys::Path::GetMainExecutable(Argv0,
85 (void*)(intptr_t) GetBuiltinIncludePath);
86
87 if (!P.isEmpty()) {
88 P.eraseComponent(); // Remove /clang from foo/bin/clang
89 P.eraseComponent(); // Remove /bin from foo/bin
90
91 // Get foo/lib/clang/<version>/include
92 P.appendComponent("lib");
93 P.appendComponent("clang");
94 P.appendComponent(CLANG_VERSION_STRING);
95 P.appendComponent("include");
96 }
97
98 return P.str();
99}
100
101
102//===----------------------------------------------------------------------===//
103// Main driver for Clang
104//===----------------------------------------------------------------------===//
105
106static void LLVMErrorHandler(void *UserData, const std::string &Message) {
107 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
108
109 Diags.Report(diag::err_fe_error_backend) << Message;
110
111 // We cannot recover from llvm errors.
112 exit(1);
113}
114
115static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
116 using namespace clang::frontend;
117
118 switch (CI.getFrontendOpts().ProgramAction) {
119 default:
120 llvm_unreachable("Invalid program action!");
121
122 case ASTDump: return new ASTDumpAction();
123 case ASTPrint: return new ASTPrintAction();
Sean Callanan279584c2011-03-15 00:17:19 +0000124 case ASTDumpXML: return new ASTDumpXMLAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000125 case ASTView: return new ASTViewAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000126 case DumpRawTokens: return new DumpRawTokensAction();
127 case DumpTokens: return new DumpTokensAction();
128 case EmitAssembly: return new EmitAssemblyAction();
129 case EmitBC: return new EmitBCAction();
130 case EmitHTML: return new HTMLPrintAction();
131 case EmitLLVM: return new EmitLLVMAction();
132 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
133 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
134 case EmitObj: return new EmitObjAction();
135 case FixIt: return new FixItAction();
136 case GeneratePCH: return new GeneratePCHAction();
137 case GeneratePTH: return new GeneratePTHAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000138 case InitOnly: return new InitOnlyAction();
139 case ParseSyntaxOnly: return new SyntaxOnlyAction();
140
141 case PluginAction: {
142 for (FrontendPluginRegistry::iterator it =
143 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
144 it != ie; ++it) {
145 if (it->getName() == CI.getFrontendOpts().ActionName) {
146 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
147 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
148 return 0;
149 return P.take();
150 }
151 }
152
153 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
154 << CI.getFrontendOpts().ActionName;
155 return 0;
156 }
157
158 case PrintDeclContext: return new DeclContextPrintAction();
159 case PrintPreamble: return new PrintPreambleAction();
160 case PrintPreprocessedInput: return new PrintPreprocessedAction();
161 case RewriteMacros: return new RewriteMacrosAction();
162 case RewriteObjC: return new RewriteObjCAction();
163 case RewriteTest: return new RewriteTestAction();
Sean Callananad293092011-01-18 23:32:05 +0000164 //case RunAnalysis: return new AnalysisAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000165 case RunPreprocessorOnly: return new PreprocessOnlyAction();
166 }
167}
168
169static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
170 // Create the underlying action.
171 FrontendAction *Act = CreateFrontendBaseAction(CI);
172 if (!Act)
173 return 0;
174
175 // If there are any AST files to merge, create a frontend action
176 // adaptor to perform the merge.
177 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
178 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
179 CI.getFrontendOpts().ASTMergeFiles.size());
180
181 return Act;
182}
183
184//===----------------------------------------------------------------------===//
185// Implementation of ClangExpressionParser
186//===----------------------------------------------------------------------===//
187
Greg Clayton395fc332011-02-15 21:59:32 +0000188ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
189 ClangExpression &expr) :
190 m_expr (expr),
Sean Callanan65dafa82010-08-27 01:01:44 +0000191 m_compiler (),
192 m_code_generator (NULL),
193 m_execution_engine (),
194 m_jitted_functions ()
195{
196 // Initialize targets first, so that --version shows registered targets.
197 static struct InitializeLLVM {
198 InitializeLLVM() {
199 llvm::InitializeAllTargets();
200 llvm::InitializeAllAsmPrinters();
Sean Callanan9b6898f2011-07-30 02:42:06 +0000201 llvm::InitializeAllTargetMCs();
Sean Callanan65dafa82010-08-27 01:01:44 +0000202 }
203 } InitializeLLVM;
Greg Clayton395fc332011-02-15 21:59:32 +0000204
Sean Callanan65dafa82010-08-27 01:01:44 +0000205 // 1. Create a new compiler instance.
206 m_compiler.reset(new CompilerInstance());
Sean Callanan65dafa82010-08-27 01:01:44 +0000207
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
Greg Clayton395fc332011-02-15 21:59:32 +0000218 Process *process = NULL;
219 if (exe_scope)
220 process = exe_scope->CalculateProcess();
221
Sean Callananc7674af2011-01-17 23:42:46 +0000222 if (process)
223 {
224 if (process->GetObjCLanguageRuntime())
225 {
Greg Claytonb3448432011-03-24 21:19:54 +0000226 if (process->GetObjCLanguageRuntime()->GetRuntimeVersion() == eAppleObjC_V2)
Sean Callananc7674af2011-01-17 23:42:46 +0000227 {
228 m_compiler->getLangOpts().ObjCNonFragileABI = true; // NOT i386
229 m_compiler->getLangOpts().ObjCNonFragileABI2 = true; // NOT i386
230 }
231 }
232 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000233
Sean Callanan65dafa82010-08-27 01:01:44 +0000234 m_compiler->getLangOpts().ThreadsafeStatics = false;
235 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
236 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
237
238 // Set CodeGen options
239 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
240 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
241
242 // Disable some warnings.
243 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
244
245 // Set the target triple.
Greg Clayton395fc332011-02-15 21:59:32 +0000246 Target *target = NULL;
247 if (exe_scope)
248 target = exe_scope->CalculateTarget();
249
250 // TODO: figure out what to really do when we don't have a valid target.
251 // Sometimes this will be ok to just use the host target triple (when we
252 // evaluate say "2+3", but other expressions like breakpoint conditions
253 // and other things that _are_ target specific really shouldn't just be
254 // using the host triple. This needs to be fixed in a better way.
255 if (target && target->GetArchitecture().IsValid())
Sean Callanan2a8c3382011-04-14 02:01:31 +0000256 {
257 std::string triple = target->GetArchitecture().GetTriple().str();
258
259 int dash_count = 0;
Johnny Chen2bc9eb32011-07-19 19:48:13 +0000260 for (size_t i = 0; i < triple.size(); ++i)
Sean Callanan2a8c3382011-04-14 02:01:31 +0000261 {
262 if (triple[i] == '-')
263 dash_count++;
264 if (dash_count == 3)
265 {
266 triple.resize(i);
267 break;
268 }
269 }
270
271 m_compiler->getTargetOpts().Triple = triple;
272 }
Greg Clayton395fc332011-02-15 21:59:32 +0000273 else
Sean Callanan2a8c3382011-04-14 02:01:31 +0000274 {
Greg Clayton395fc332011-02-15 21:59:32 +0000275 m_compiler->getTargetOpts().Triple = llvm::sys::getHostTriple();
Sean Callanan2a8c3382011-04-14 02:01:31 +0000276 }
277
Sean Callanan65dafa82010-08-27 01:01:44 +0000278 // 3. Set up various important bits of infrastructure.
279 m_compiler->createDiagnostics(0, 0);
280
281 // Create the target instance.
282 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
283 m_compiler->getTargetOpts()));
284
285 assert (m_compiler->hasTarget());
286
287 // Inform the target of the language options
288 //
289 // FIXME: We shouldn't need to do this, the target should be immutable once
290 // created. This complexity should be lifted elsewhere.
291 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
292
293 // 4. Set up the diagnostic buffer for reporting errors
294
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000295 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000296
297 // 5. Set up the source management objects inside the compiler
298
Greg Clayton22defe82010-12-02 23:20:03 +0000299 clang::FileSystemOptions file_system_options;
300 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000301
Sean Callanan65dafa82010-08-27 01:01:44 +0000302 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000303 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000304
305 m_compiler->createFileManager();
306 m_compiler->createPreprocessor();
307
308 // 6. Most of this we get from the CompilerInstance, but we
309 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000310 m_selector_table.reset(new SelectorTable());
Sean Callanan65dafa82010-08-27 01:01:44 +0000311 m_builtin_context.reset(new Builtin::Context(m_compiler->getTarget()));
312
313 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
314 m_compiler->getSourceManager(),
315 m_compiler->getTarget(),
316 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000317 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000318 *m_builtin_context.get(),
319 0));
320
321 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
322
323 if (decl_map)
324 {
325 OwningPtr<clang::ExternalASTSource> ast_source(new ClangASTSource(*ast_context, *decl_map));
326 ast_context->setExternalSource(ast_source);
327 }
328
329 m_compiler->setASTContext(ast_context.release());
330
Greg Clayton8de27c72010-10-15 22:48:33 +0000331 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000332
Sean Callanan279584c2011-03-15 00:17:19 +0000333 m_llvm_context.reset(new LLVMContext());
Sean Callanan65dafa82010-08-27 01:01:44 +0000334 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
335 module_name,
336 m_compiler->getCodeGenOpts(),
Sean Callanan279584c2011-03-15 00:17:19 +0000337 *m_llvm_context));
Sean Callanan65dafa82010-08-27 01:01:44 +0000338}
339
340ClangExpressionParser::~ClangExpressionParser()
341{
342}
343
344unsigned
345ClangExpressionParser::Parse (Stream &stream)
346{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000347 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
348
349 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000350
351 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
352 FileID memory_buffer_file_id = m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
353
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000354 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000355
356 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
357
358 if (ast_transformer)
359 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
360 else
361 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
362
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000363 diag_buf->EndSourceFile();
Sean Callananfb3058e2011-05-12 23:54:16 +0000364
Sean Callanan65dafa82010-08-27 01:01:44 +0000365 TextDiagnosticBuffer::const_iterator diag_iterator;
366
367 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000368
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000369 for (diag_iterator = diag_buf->warn_begin();
370 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000371 ++diag_iterator)
372 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
373
374 num_errors = 0;
375
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000376 for (diag_iterator = diag_buf->err_begin();
377 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000378 ++diag_iterator)
379 {
380 num_errors++;
381 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
382 }
383
Sean Callanan7617c292010-11-01 20:28:09 +0000384 for (diag_iterator = diag_buf->note_begin();
385 diag_iterator != diag_buf->note_end();
386 ++diag_iterator)
387 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
388
Sean Callananfb3058e2011-05-12 23:54:16 +0000389 if (!num_errors)
390 {
391 if (m_expr.DeclMap() && !m_expr.DeclMap()->ResolveUnknownTypes())
392 {
393 stream.Printf("error: Couldn't infer the type of a variable\n");
394 num_errors++;
395 }
396 }
397
Sean Callanan65dafa82010-08-27 01:01:44 +0000398 return num_errors;
399}
400
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000401static bool FindFunctionInModule (std::string &mangled_name,
402 llvm::Module *module,
403 const char *orig_name)
404{
405 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
406 fi != fe;
407 ++fi)
408 {
409 if (fi->getName().str().find(orig_name) != std::string::npos)
410 {
411 mangled_name = fi->getName().str();
412 return true;
413 }
414 }
415
416 return false;
417}
418
Sean Callanan65dafa82010-08-27 01:01:44 +0000419Error
420ClangExpressionParser::MakeDWARF ()
421{
422 Error err;
423
424 llvm::Module *module = m_code_generator->GetModule();
425
426 if (!module)
427 {
428 err.SetErrorToGenericError();
429 err.SetErrorString("IR doesn't contain a module");
430 return err;
431 }
432
Greg Clayton427f2902010-12-14 02:59:59 +0000433 ClangExpressionVariableList *local_variables = m_expr.LocalVariables();
Sean Callanan65dafa82010-08-27 01:01:44 +0000434 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
435
436 if (!local_variables)
437 {
438 err.SetErrorToGenericError();
439 err.SetErrorString("Can't convert an expression without a VariableList to DWARF");
440 return err;
441 }
442
443 if (!decl_map)
444 {
445 err.SetErrorToGenericError();
446 err.SetErrorString("Can't convert an expression without a DeclMap to DWARF");
447 return err;
448 }
449
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000450 std::string function_name;
451
452 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
453 {
454 err.SetErrorToGenericError();
455 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
456 return err;
457 }
458
459 IRToDWARF ir_to_dwarf(*local_variables, decl_map, m_expr.DwarfOpcodeStream(), function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000460
461 if (!ir_to_dwarf.runOnModule(*module))
462 {
463 err.SetErrorToGenericError();
464 err.SetErrorString("Couldn't convert the expression to DWARF");
465 return err;
466 }
467
468 err.Clear();
469 return err;
470}
471
472Error
Greg Claytond0882d02011-01-19 23:00:49 +0000473ClangExpressionParser::MakeJIT (lldb::addr_t &func_allocation_addr,
474 lldb::addr_t &func_addr,
Sean Callanan830a9032010-08-27 23:31:21 +0000475 lldb::addr_t &func_end,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000476 ExecutionContext &exe_ctx,
Sean Callananc0492742011-05-23 21:40:23 +0000477 IRForTarget::StaticDataAllocator *data_allocator,
Sean Callanan696cf5f2011-05-07 01:06:41 +0000478 lldb::ClangExpressionVariableSP &const_result,
479 bool jit_only_if_needed)
Sean Callanan65dafa82010-08-27 01:01:44 +0000480{
Greg Claytond0882d02011-01-19 23:00:49 +0000481 func_allocation_addr = LLDB_INVALID_ADDRESS;
482 func_addr = LLDB_INVALID_ADDRESS;
483 func_end = LLDB_INVALID_ADDRESS;
Greg Claytone005f2c2010-11-06 01:53:30 +0000484 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000485
Sean Callanan65dafa82010-08-27 01:01:44 +0000486 Error err;
487
488 llvm::Module *module = m_code_generator->ReleaseModule();
489
490 if (!module)
491 {
492 err.SetErrorToGenericError();
493 err.SetErrorString("IR doesn't contain a module");
494 return err;
495 }
496
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000497 // Find the actual name of the function (it's often mangled somehow)
498
499 std::string function_name;
500
501 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
502 {
503 err.SetErrorToGenericError();
504 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
505 return err;
506 }
507 else
508 {
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000509 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000510 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
511 }
512
Sean Callanan65dafa82010-08-27 01:01:44 +0000513 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
514
515 if (decl_map)
516 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000517 Stream *error_stream = NULL;
518
519 if (exe_ctx.target)
520 error_stream = &exe_ctx.target->GetDebugger().GetErrorStream();
521
Sean Callanane8a59a82010-09-13 21:34:21 +0000522 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000523 m_expr.NeedsVariableResolution(),
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000524 const_result,
Sean Callananc0492742011-05-23 21:40:23 +0000525 data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +0000526 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000527 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000528
529 if (!ir_for_target.runOnModule(*module))
530 {
531 err.SetErrorToGenericError();
532 err.SetErrorString("Couldn't convert the expression to DWARF");
533 return err;
534 }
Sean Callananf18d91c2010-09-01 00:58:00 +0000535
Sean Callanan696cf5f2011-05-07 01:06:41 +0000536 if (jit_only_if_needed && const_result.get())
537 {
538 err.Clear();
539 return err;
540 }
541
Jim Inghamd1686902010-10-14 23:45:03 +0000542 if (m_expr.NeedsValidation() && exe_ctx.process->GetDynamicCheckers())
Sean Callananf18d91c2010-09-01 00:58:00 +0000543 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000544 IRDynamicChecks ir_dynamic_checks(*exe_ctx.process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000545
546 if (!ir_dynamic_checks.runOnModule(*module))
547 {
548 err.SetErrorToGenericError();
549 err.SetErrorString("Couldn't add dynamic checks to the expression");
550 return err;
551 }
552 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000553 }
554
Greg Claytond0882d02011-01-19 23:00:49 +0000555 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
556 // below so we don't need to free it.
557 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000558
559 std::string error_string;
Sean Callanan9b6898f2011-07-30 02:42:06 +0000560
Greg Clayton2f085c62011-05-15 01:25:55 +0000561#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +0000562 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
563 &error_string,
Greg Claytond0882d02011-01-19 23:00:49 +0000564 jit_memory_manager,
Sean Callananc2c6f772010-10-26 00:31:56 +0000565 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000566 true,
567 CodeModel::Small));
Greg Clayton2f085c62011-05-15 01:25:55 +0000568#else
569 EngineBuilder builder(module);
570 builder.setEngineKind(EngineKind::JIT)
571 .setErrorStr(&error_string)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000572 .setRelocationModel(llvm::Reloc::PIC_)
Greg Clayton2f085c62011-05-15 01:25:55 +0000573 .setJITMemoryManager(jit_memory_manager)
574 .setOptLevel(CodeGenOpt::Less)
575 .setAllocateGVsWithCode(true)
576 .setCodeModel(CodeModel::Small)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000577 .setUseMCJIT(true);
Greg Clayton2f085c62011-05-15 01:25:55 +0000578 m_execution_engine.reset(builder.create());
579#endif
Sean Callanan9ac3a962010-11-02 23:20:00 +0000580
Sean Callanan65dafa82010-08-27 01:01:44 +0000581 if (!m_execution_engine.get())
582 {
583 err.SetErrorToGenericError();
584 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
585 return err;
586 }
587
588 m_execution_engine->DisableLazyCompilation();
589
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000590 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000591
592 // We don't actually need the function pointer here, this just forces it to get resolved.
593
594 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
595
596 // Errors usually cause failures in the JIT, but if we're lucky we get here.
597
598 if (!fun_ptr)
599 {
600 err.SetErrorToGenericError();
601 err.SetErrorString("Couldn't JIT the function");
602 return err;
603 }
604
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000605 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000606
607 ExecutionContext &exc_context(exe_ctx);
608
609 if (exc_context.process == NULL)
610 {
611 err.SetErrorToGenericError();
612 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
613 return err;
614 }
615
616 // Look over the regions allocated for the function compiled. The JIT
617 // tries to allocate the functions & stubs close together, so we should try to
618 // write them that way too...
619 // For now I only write functions with no stubs, globals, exception tables,
620 // etc. So I only need to write the functions.
621
622 size_t alloc_size = 0;
623
Greg Claytond0882d02011-01-19 23:00:49 +0000624 std::map<uint8_t *, uint8_t *>::iterator fun_pos = jit_memory_manager->m_functions.begin();
625 std::map<uint8_t *, uint8_t *>::iterator fun_end = jit_memory_manager->m_functions.end();
Greg Clayton9d2b3212011-05-15 23:56:52 +0000626
Sean Callanan65dafa82010-08-27 01:01:44 +0000627 for (; fun_pos != fun_end; ++fun_pos)
Greg Clayton9d2b3212011-05-15 23:56:52 +0000628 {
629 size_t mem_size = fun_pos->second - fun_pos->first;
630 if (log)
631 log->Printf ("JIT memory: [%p - %p) size = %zu", fun_pos->first, fun_pos->second, mem_size);
632 alloc_size += mem_size;
633 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000634
635 Error alloc_error;
Greg Claytond0882d02011-01-19 23:00:49 +0000636 func_allocation_addr = exc_context.process->AllocateMemory (alloc_size,
637 lldb::ePermissionsReadable|lldb::ePermissionsExecutable,
638 alloc_error);
Sean Callanan65dafa82010-08-27 01:01:44 +0000639
Greg Claytond0882d02011-01-19 23:00:49 +0000640 if (func_allocation_addr == LLDB_INVALID_ADDRESS)
Sean Callanan65dafa82010-08-27 01:01:44 +0000641 {
642 err.SetErrorToGenericError();
643 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
644 return err;
645 }
646
Greg Claytond0882d02011-01-19 23:00:49 +0000647 lldb::addr_t cursor = func_allocation_addr;
Sean Callanan65dafa82010-08-27 01:01:44 +0000648
Greg Claytond0882d02011-01-19 23:00:49 +0000649 for (fun_pos = jit_memory_manager->m_functions.begin(); fun_pos != fun_end; fun_pos++)
Sean Callanan65dafa82010-08-27 01:01:44 +0000650 {
651 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
652 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
653 size_t size = lend - lstart;
654
655 Error write_error;
656
657 if (exc_context.process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
658 {
659 err.SetErrorToGenericError();
Greg Claytonc0fa5332011-05-22 22:46:53 +0000660 err.SetErrorStringWithFormat("Couldn't copy JIT code for function into the target: %s", write_error.AsCString("unknown error"));
Sean Callanan65dafa82010-08-27 01:01:44 +0000661 return err;
662 }
663
Greg Claytond0882d02011-01-19 23:00:49 +0000664 jit_memory_manager->AddToLocalToRemoteMap (lstart, size, cursor);
Sean Callanan65dafa82010-08-27 01:01:44 +0000665 cursor += size;
666 }
667
668 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
669
670 for (pos = m_jitted_functions.begin(); pos != end; pos++)
671 {
Greg Claytond0882d02011-01-19 23:00:49 +0000672 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000673
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000674 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000675 {
Greg Claytond0882d02011-01-19 23:00:49 +0000676 func_end = jit_memory_manager->GetRemoteRangeForLocal ((*pos).m_local_addr).second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000677 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000678 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000679 }
680
Sean Callanan6dff8272010-11-08 03:49:50 +0000681 if (log)
682 {
683 log->Printf("Code can be run in the target.");
684
685 StreamString disassembly_stream;
686
Greg Claytond0882d02011-01-19 23:00:49 +0000687 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000688
689 if (!err.Success())
690 {
691 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
692 }
693 else
694 {
695 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
696 }
697 }
698
Sean Callanan65dafa82010-08-27 01:01:44 +0000699 err.Clear();
700 return err;
701}
702
703Error
Greg Claytond0882d02011-01-19 23:00:49 +0000704ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000705{
Greg Claytone005f2c2010-11-06 01:53:30 +0000706 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000707
708 const char *name = m_expr.FunctionName();
709
710 Error ret;
711
712 ret.Clear();
713
714 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
715 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
716
717 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
718
719 for (pos = m_jitted_functions.begin(); pos < end; pos++)
720 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000721 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000722 {
723 func_local_addr = pos->m_local_addr;
724 func_remote_addr = pos->m_remote_addr;
725 }
726 }
727
728 if (func_local_addr == LLDB_INVALID_ADDRESS)
729 {
730 ret.SetErrorToGenericError();
731 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
732 return ret;
733 }
734
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000735 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000736 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
737
738 std::pair <lldb::addr_t, lldb::addr_t> func_range;
739
Greg Claytond0882d02011-01-19 23:00:49 +0000740 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000741
742 if (func_range.first == 0 && func_range.second == 0)
743 {
744 ret.SetErrorToGenericError();
745 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
746 return ret;
747 }
748
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000749 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000750 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
751
752 if (!exe_ctx.target)
753 {
754 ret.SetErrorToGenericError();
755 ret.SetErrorString("Couldn't find the target");
756 }
757
758 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
759
760 Error err;
761 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
762
763 if (!err.Success())
764 {
765 ret.SetErrorToGenericError();
766 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
767 return ret;
768 }
769
770 ArchSpec arch(exe_ctx.target->GetArchitecture());
771
Greg Clayton149731c2011-03-25 18:03:16 +0000772 Disassembler *disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000773
774 if (disassembler == NULL)
775 {
776 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000777 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000778 return ret;
779 }
780
781 if (!exe_ctx.process)
782 {
783 ret.SetErrorToGenericError();
784 ret.SetErrorString("Couldn't find the process");
785 return ret;
786 }
787
788 DataExtractor extractor(buffer_sp,
789 exe_ctx.process->GetByteOrder(),
790 exe_ctx.target->GetArchitecture().GetAddressByteSize());
791
Greg Claytone005f2c2010-11-06 01:53:30 +0000792 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000793 {
794 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000795 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000796 0,
797 extractor.GetByteSize(),
798 func_remote_addr,
799 16,
800 DataExtractor::TypeUInt8);
801 }
802
Jim Inghamaa3e3e12011-03-22 01:48:42 +0000803 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000804
Greg Clayton5c4c7462010-10-06 03:09:58 +0000805 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000806 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000807 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
808 instruction_index < num_instructions;
809 ++instruction_index)
810 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000811 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000812 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000813 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000814 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000815 true,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000816 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000817 true);
818 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000819 }
820
821 return ret;
822}