blob: 255013ea0f896821aa4e1e323a910ee498620b1f [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
Sean Callananc0492742011-05-23 21:40:23 +000055//#define USE_STANDARD_JIT
Greg Clayton2f085c62011-05-15 01:25:55 +000056#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +000057#include "llvm/ExecutionEngine/JIT.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000058#else
59#include "llvm/ExecutionEngine/MCJIT.h"
60#endif
Sean Callanan65dafa82010-08-27 01:01:44 +000061#include "llvm/LLVMContext.h"
Sean Callanan279584c2011-03-15 00:17:19 +000062#include "llvm/Module.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000063#include "llvm/Support/ErrorHandling.h"
64#include "llvm/Support/MemoryBuffer.h"
Greg Clayton22defe82010-12-02 23:20:03 +000065#include "llvm/Support/DynamicLibrary.h"
66#include "llvm/Support/Host.h"
67#include "llvm/Support/Signals.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000068#include "llvm/Target/TargetRegistry.h"
69#include "llvm/Target/TargetSelect.h"
70
71using namespace clang;
72using namespace llvm;
73using namespace lldb_private;
74
75//===----------------------------------------------------------------------===//
76// Utility Methods for Clang
77//===----------------------------------------------------------------------===//
78
79std::string GetBuiltinIncludePath(const char *Argv0) {
80 llvm::sys::Path P =
81 llvm::sys::Path::GetMainExecutable(Argv0,
82 (void*)(intptr_t) GetBuiltinIncludePath);
83
84 if (!P.isEmpty()) {
85 P.eraseComponent(); // Remove /clang from foo/bin/clang
86 P.eraseComponent(); // Remove /bin from foo/bin
87
88 // Get foo/lib/clang/<version>/include
89 P.appendComponent("lib");
90 P.appendComponent("clang");
91 P.appendComponent(CLANG_VERSION_STRING);
92 P.appendComponent("include");
93 }
94
95 return P.str();
96}
97
98
99//===----------------------------------------------------------------------===//
100// Main driver for Clang
101//===----------------------------------------------------------------------===//
102
103static void LLVMErrorHandler(void *UserData, const std::string &Message) {
104 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
105
106 Diags.Report(diag::err_fe_error_backend) << Message;
107
108 // We cannot recover from llvm errors.
109 exit(1);
110}
111
112static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
113 using namespace clang::frontend;
114
115 switch (CI.getFrontendOpts().ProgramAction) {
116 default:
117 llvm_unreachable("Invalid program action!");
118
119 case ASTDump: return new ASTDumpAction();
120 case ASTPrint: return new ASTPrintAction();
Sean Callanan279584c2011-03-15 00:17:19 +0000121 case ASTDumpXML: return new ASTDumpXMLAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000122 case ASTView: return new ASTViewAction();
123 case BoostCon: return new BoostConAction();
124 case DumpRawTokens: return new DumpRawTokensAction();
125 case DumpTokens: return new DumpTokensAction();
126 case EmitAssembly: return new EmitAssemblyAction();
127 case EmitBC: return new EmitBCAction();
128 case EmitHTML: return new HTMLPrintAction();
129 case EmitLLVM: return new EmitLLVMAction();
130 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
131 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
132 case EmitObj: return new EmitObjAction();
133 case FixIt: return new FixItAction();
134 case GeneratePCH: return new GeneratePCHAction();
135 case GeneratePTH: return new GeneratePTHAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000136 case InitOnly: return new InitOnlyAction();
137 case ParseSyntaxOnly: return new SyntaxOnlyAction();
138
139 case PluginAction: {
140 for (FrontendPluginRegistry::iterator it =
141 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
142 it != ie; ++it) {
143 if (it->getName() == CI.getFrontendOpts().ActionName) {
144 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
145 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
146 return 0;
147 return P.take();
148 }
149 }
150
151 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
152 << CI.getFrontendOpts().ActionName;
153 return 0;
154 }
155
156 case PrintDeclContext: return new DeclContextPrintAction();
157 case PrintPreamble: return new PrintPreambleAction();
158 case PrintPreprocessedInput: return new PrintPreprocessedAction();
159 case RewriteMacros: return new RewriteMacrosAction();
160 case RewriteObjC: return new RewriteObjCAction();
161 case RewriteTest: return new RewriteTestAction();
Sean Callananad293092011-01-18 23:32:05 +0000162 //case RunAnalysis: return new AnalysisAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000163 case RunPreprocessorOnly: return new PreprocessOnlyAction();
164 }
165}
166
167static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
168 // Create the underlying action.
169 FrontendAction *Act = CreateFrontendBaseAction(CI);
170 if (!Act)
171 return 0;
172
173 // If there are any AST files to merge, create a frontend action
174 // adaptor to perform the merge.
175 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
176 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
177 CI.getFrontendOpts().ASTMergeFiles.size());
178
179 return Act;
180}
181
182//===----------------------------------------------------------------------===//
183// Implementation of ClangExpressionParser
184//===----------------------------------------------------------------------===//
185
Greg Clayton395fc332011-02-15 21:59:32 +0000186ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
187 ClangExpression &expr) :
188 m_expr (expr),
Sean Callanan65dafa82010-08-27 01:01:44 +0000189 m_compiler (),
190 m_code_generator (NULL),
191 m_execution_engine (),
192 m_jitted_functions ()
193{
194 // Initialize targets first, so that --version shows registered targets.
195 static struct InitializeLLVM {
196 InitializeLLVM() {
197 llvm::InitializeAllTargets();
198 llvm::InitializeAllAsmPrinters();
199 }
200 } InitializeLLVM;
Greg Clayton395fc332011-02-15 21:59:32 +0000201
Sean Callanan65dafa82010-08-27 01:01:44 +0000202 // 1. Create a new compiler instance.
203 m_compiler.reset(new CompilerInstance());
Sean Callanan65dafa82010-08-27 01:01:44 +0000204
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;
Greg Claytonf51ed302011-01-15 01:32:14 +0000210
211 // Setup objective C
Sean Callanan65dafa82010-08-27 01:01:44 +0000212 m_compiler->getLangOpts().ObjC1 = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000213 m_compiler->getLangOpts().ObjC2 = true;
Sean Callananc7674af2011-01-17 23:42:46 +0000214
Greg Clayton395fc332011-02-15 21:59:32 +0000215 Process *process = NULL;
216 if (exe_scope)
217 process = exe_scope->CalculateProcess();
218
Sean Callananc7674af2011-01-17 23:42:46 +0000219 if (process)
220 {
221 if (process->GetObjCLanguageRuntime())
222 {
Greg Claytonb3448432011-03-24 21:19:54 +0000223 if (process->GetObjCLanguageRuntime()->GetRuntimeVersion() == eAppleObjC_V2)
Sean Callananc7674af2011-01-17 23:42:46 +0000224 {
225 m_compiler->getLangOpts().ObjCNonFragileABI = true; // NOT i386
226 m_compiler->getLangOpts().ObjCNonFragileABI2 = true; // NOT i386
227 }
228 }
229 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000230
Sean Callanan65dafa82010-08-27 01:01:44 +0000231 m_compiler->getLangOpts().ThreadsafeStatics = false;
232 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
233 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
234
235 // Set CodeGen options
236 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
237 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
238
239 // Disable some warnings.
240 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
241
242 // Set the target triple.
Greg Clayton395fc332011-02-15 21:59:32 +0000243 Target *target = NULL;
244 if (exe_scope)
245 target = exe_scope->CalculateTarget();
246
247 // TODO: figure out what to really do when we don't have a valid target.
248 // Sometimes this will be ok to just use the host target triple (when we
249 // evaluate say "2+3", but other expressions like breakpoint conditions
250 // and other things that _are_ target specific really shouldn't just be
251 // using the host triple. This needs to be fixed in a better way.
252 if (target && target->GetArchitecture().IsValid())
Sean Callanan2a8c3382011-04-14 02:01:31 +0000253 {
254 std::string triple = target->GetArchitecture().GetTriple().str();
255
256 int dash_count = 0;
257 for (int i = 0; i < triple.size(); ++i)
258 {
259 if (triple[i] == '-')
260 dash_count++;
261 if (dash_count == 3)
262 {
263 triple.resize(i);
264 break;
265 }
266 }
267
268 m_compiler->getTargetOpts().Triple = triple;
269 }
Greg Clayton395fc332011-02-15 21:59:32 +0000270 else
Sean Callanan2a8c3382011-04-14 02:01:31 +0000271 {
Greg Clayton395fc332011-02-15 21:59:32 +0000272 m_compiler->getTargetOpts().Triple = llvm::sys::getHostTriple();
Sean Callanan2a8c3382011-04-14 02:01:31 +0000273 }
274
Sean Callanan65dafa82010-08-27 01:01:44 +0000275 // 3. Set up various important bits of infrastructure.
276 m_compiler->createDiagnostics(0, 0);
277
278 // Create the target instance.
279 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
280 m_compiler->getTargetOpts()));
281
282 assert (m_compiler->hasTarget());
283
284 // Inform the target of the language options
285 //
286 // FIXME: We shouldn't need to do this, the target should be immutable once
287 // created. This complexity should be lifted elsewhere.
288 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
289
290 // 4. Set up the diagnostic buffer for reporting errors
291
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000292 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000293
294 // 5. Set up the source management objects inside the compiler
295
Greg Clayton22defe82010-12-02 23:20:03 +0000296 clang::FileSystemOptions file_system_options;
297 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000298
Sean Callanan65dafa82010-08-27 01:01:44 +0000299 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000300 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000301
302 m_compiler->createFileManager();
303 m_compiler->createPreprocessor();
304
305 // 6. Most of this we get from the CompilerInstance, but we
306 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000307 m_selector_table.reset(new SelectorTable());
Sean Callanan65dafa82010-08-27 01:01:44 +0000308 m_builtin_context.reset(new Builtin::Context(m_compiler->getTarget()));
309
310 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
311 m_compiler->getSourceManager(),
312 m_compiler->getTarget(),
313 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000314 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000315 *m_builtin_context.get(),
316 0));
317
318 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
319
320 if (decl_map)
321 {
322 OwningPtr<clang::ExternalASTSource> ast_source(new ClangASTSource(*ast_context, *decl_map));
323 ast_context->setExternalSource(ast_source);
324 }
325
326 m_compiler->setASTContext(ast_context.release());
327
Greg Clayton8de27c72010-10-15 22:48:33 +0000328 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000329
Sean Callanan279584c2011-03-15 00:17:19 +0000330 m_llvm_context.reset(new LLVMContext());
Sean Callanan65dafa82010-08-27 01:01:44 +0000331 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
332 module_name,
333 m_compiler->getCodeGenOpts(),
Sean Callanan279584c2011-03-15 00:17:19 +0000334 *m_llvm_context));
Sean Callanan65dafa82010-08-27 01:01:44 +0000335}
336
337ClangExpressionParser::~ClangExpressionParser()
338{
339}
340
341unsigned
342ClangExpressionParser::Parse (Stream &stream)
343{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000344 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
345
346 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000347
348 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
349 FileID memory_buffer_file_id = m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
350
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000351 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000352
353 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
354
355 if (ast_transformer)
356 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
357 else
358 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
359
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000360 diag_buf->EndSourceFile();
Sean Callananfb3058e2011-05-12 23:54:16 +0000361
Sean Callanan65dafa82010-08-27 01:01:44 +0000362 TextDiagnosticBuffer::const_iterator diag_iterator;
363
364 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000365
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000366 for (diag_iterator = diag_buf->warn_begin();
367 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000368 ++diag_iterator)
369 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
370
371 num_errors = 0;
372
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000373 for (diag_iterator = diag_buf->err_begin();
374 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000375 ++diag_iterator)
376 {
377 num_errors++;
378 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
379 }
380
Sean Callanan7617c292010-11-01 20:28:09 +0000381 for (diag_iterator = diag_buf->note_begin();
382 diag_iterator != diag_buf->note_end();
383 ++diag_iterator)
384 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
385
Sean Callananfb3058e2011-05-12 23:54:16 +0000386 if (!num_errors)
387 {
388 if (m_expr.DeclMap() && !m_expr.DeclMap()->ResolveUnknownTypes())
389 {
390 stream.Printf("error: Couldn't infer the type of a variable\n");
391 num_errors++;
392 }
393 }
394
Sean Callanan65dafa82010-08-27 01:01:44 +0000395 return num_errors;
396}
397
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000398static bool FindFunctionInModule (std::string &mangled_name,
399 llvm::Module *module,
400 const char *orig_name)
401{
402 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
403 fi != fe;
404 ++fi)
405 {
406 if (fi->getName().str().find(orig_name) != std::string::npos)
407 {
408 mangled_name = fi->getName().str();
409 return true;
410 }
411 }
412
413 return false;
414}
415
Sean Callanan65dafa82010-08-27 01:01:44 +0000416Error
417ClangExpressionParser::MakeDWARF ()
418{
419 Error err;
420
421 llvm::Module *module = m_code_generator->GetModule();
422
423 if (!module)
424 {
425 err.SetErrorToGenericError();
426 err.SetErrorString("IR doesn't contain a module");
427 return err;
428 }
429
Greg Clayton427f2902010-12-14 02:59:59 +0000430 ClangExpressionVariableList *local_variables = m_expr.LocalVariables();
Sean Callanan65dafa82010-08-27 01:01:44 +0000431 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
432
433 if (!local_variables)
434 {
435 err.SetErrorToGenericError();
436 err.SetErrorString("Can't convert an expression without a VariableList to DWARF");
437 return err;
438 }
439
440 if (!decl_map)
441 {
442 err.SetErrorToGenericError();
443 err.SetErrorString("Can't convert an expression without a DeclMap to DWARF");
444 return err;
445 }
446
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000447 std::string function_name;
448
449 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
450 {
451 err.SetErrorToGenericError();
452 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
453 return err;
454 }
455
456 IRToDWARF ir_to_dwarf(*local_variables, decl_map, m_expr.DwarfOpcodeStream(), function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000457
458 if (!ir_to_dwarf.runOnModule(*module))
459 {
460 err.SetErrorToGenericError();
461 err.SetErrorString("Couldn't convert the expression to DWARF");
462 return err;
463 }
464
465 err.Clear();
466 return err;
467}
468
469Error
Greg Claytond0882d02011-01-19 23:00:49 +0000470ClangExpressionParser::MakeJIT (lldb::addr_t &func_allocation_addr,
471 lldb::addr_t &func_addr,
Sean Callanan830a9032010-08-27 23:31:21 +0000472 lldb::addr_t &func_end,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000473 ExecutionContext &exe_ctx,
Sean Callananc0492742011-05-23 21:40:23 +0000474 IRForTarget::StaticDataAllocator *data_allocator,
Sean Callanan696cf5f2011-05-07 01:06:41 +0000475 lldb::ClangExpressionVariableSP &const_result,
476 bool jit_only_if_needed)
Sean Callanan65dafa82010-08-27 01:01:44 +0000477{
Greg Claytond0882d02011-01-19 23:00:49 +0000478 func_allocation_addr = LLDB_INVALID_ADDRESS;
479 func_addr = LLDB_INVALID_ADDRESS;
480 func_end = LLDB_INVALID_ADDRESS;
Greg Claytone005f2c2010-11-06 01:53:30 +0000481 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000482
Sean Callanan65dafa82010-08-27 01:01:44 +0000483 Error err;
484
485 llvm::Module *module = m_code_generator->ReleaseModule();
486
487 if (!module)
488 {
489 err.SetErrorToGenericError();
490 err.SetErrorString("IR doesn't contain a module");
491 return err;
492 }
493
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000494 // Find the actual name of the function (it's often mangled somehow)
495
496 std::string function_name;
497
498 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
499 {
500 err.SetErrorToGenericError();
501 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
502 return err;
503 }
504 else
505 {
506 if(log)
507 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
508 }
509
Sean Callanan65dafa82010-08-27 01:01:44 +0000510 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
511
512 if (decl_map)
513 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000514 Stream *error_stream = NULL;
515
516 if (exe_ctx.target)
517 error_stream = &exe_ctx.target->GetDebugger().GetErrorStream();
518
Sean Callanane8a59a82010-09-13 21:34:21 +0000519 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000520 m_expr.NeedsVariableResolution(),
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000521 const_result,
Sean Callananc0492742011-05-23 21:40:23 +0000522 data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +0000523 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000524 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000525
526 if (!ir_for_target.runOnModule(*module))
527 {
528 err.SetErrorToGenericError();
529 err.SetErrorString("Couldn't convert the expression to DWARF");
530 return err;
531 }
Sean Callananf18d91c2010-09-01 00:58:00 +0000532
Sean Callanan696cf5f2011-05-07 01:06:41 +0000533 if (jit_only_if_needed && const_result.get())
534 {
535 err.Clear();
536 return err;
537 }
538
Jim Inghamd1686902010-10-14 23:45:03 +0000539 if (m_expr.NeedsValidation() && exe_ctx.process->GetDynamicCheckers())
Sean Callananf18d91c2010-09-01 00:58:00 +0000540 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000541 IRDynamicChecks ir_dynamic_checks(*exe_ctx.process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000542
543 if (!ir_dynamic_checks.runOnModule(*module))
544 {
545 err.SetErrorToGenericError();
546 err.SetErrorString("Couldn't add dynamic checks to the expression");
547 return err;
548 }
549 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000550 }
551
Greg Claytond0882d02011-01-19 23:00:49 +0000552 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
553 // below so we don't need to free it.
554 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000555
556 std::string error_string;
Sean Callanan9ac3a962010-11-02 23:20:00 +0000557
Sean Callananc2c6f772010-10-26 00:31:56 +0000558 llvm::TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
559
Greg Clayton2f085c62011-05-15 01:25:55 +0000560#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +0000561 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
562 &error_string,
Greg Claytond0882d02011-01-19 23:00:49 +0000563 jit_memory_manager,
Sean Callananc2c6f772010-10-26 00:31:56 +0000564 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000565 true,
566 CodeModel::Small));
Greg Clayton2f085c62011-05-15 01:25:55 +0000567#else
568 EngineBuilder builder(module);
569 builder.setEngineKind(EngineKind::JIT)
570 .setErrorStr(&error_string)
571 .setJITMemoryManager(jit_memory_manager)
572 .setOptLevel(CodeGenOpt::Less)
573 .setAllocateGVsWithCode(true)
574 .setCodeModel(CodeModel::Small)
575 .setUseMCJIT(true);
576 m_execution_engine.reset(builder.create());
577#endif
Sean Callanan9ac3a962010-11-02 23:20:00 +0000578
Sean Callanan65dafa82010-08-27 01:01:44 +0000579 if (!m_execution_engine.get())
580 {
581 err.SetErrorToGenericError();
582 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
583 return err;
584 }
585
586 m_execution_engine->DisableLazyCompilation();
587
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000588 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000589
590 // We don't actually need the function pointer here, this just forces it to get resolved.
591
592 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
593
594 // Errors usually cause failures in the JIT, but if we're lucky we get here.
595
596 if (!fun_ptr)
597 {
598 err.SetErrorToGenericError();
599 err.SetErrorString("Couldn't JIT the function");
600 return err;
601 }
602
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000603 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000604
605 ExecutionContext &exc_context(exe_ctx);
606
607 if (exc_context.process == NULL)
608 {
609 err.SetErrorToGenericError();
610 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
611 return err;
612 }
613
614 // Look over the regions allocated for the function compiled. The JIT
615 // tries to allocate the functions & stubs close together, so we should try to
616 // write them that way too...
617 // For now I only write functions with no stubs, globals, exception tables,
618 // etc. So I only need to write the functions.
619
620 size_t alloc_size = 0;
621
Greg Claytond0882d02011-01-19 23:00:49 +0000622 std::map<uint8_t *, uint8_t *>::iterator fun_pos = jit_memory_manager->m_functions.begin();
623 std::map<uint8_t *, uint8_t *>::iterator fun_end = jit_memory_manager->m_functions.end();
Greg Clayton9d2b3212011-05-15 23:56:52 +0000624
Sean Callanan65dafa82010-08-27 01:01:44 +0000625 for (; fun_pos != fun_end; ++fun_pos)
Greg Clayton9d2b3212011-05-15 23:56:52 +0000626 {
627 size_t mem_size = fun_pos->second - fun_pos->first;
628 if (log)
629 log->Printf ("JIT memory: [%p - %p) size = %zu", fun_pos->first, fun_pos->second, mem_size);
630 alloc_size += mem_size;
631 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000632
633 Error alloc_error;
Greg Claytond0882d02011-01-19 23:00:49 +0000634 func_allocation_addr = exc_context.process->AllocateMemory (alloc_size,
635 lldb::ePermissionsReadable|lldb::ePermissionsExecutable,
636 alloc_error);
Sean Callanan65dafa82010-08-27 01:01:44 +0000637
Greg Claytond0882d02011-01-19 23:00:49 +0000638 if (func_allocation_addr == LLDB_INVALID_ADDRESS)
Sean Callanan65dafa82010-08-27 01:01:44 +0000639 {
640 err.SetErrorToGenericError();
641 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
642 return err;
643 }
644
Greg Claytond0882d02011-01-19 23:00:49 +0000645 lldb::addr_t cursor = func_allocation_addr;
Sean Callanan65dafa82010-08-27 01:01:44 +0000646
Greg Claytond0882d02011-01-19 23:00:49 +0000647 for (fun_pos = jit_memory_manager->m_functions.begin(); fun_pos != fun_end; fun_pos++)
Sean Callanan65dafa82010-08-27 01:01:44 +0000648 {
649 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
650 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
651 size_t size = lend - lstart;
652
653 Error write_error;
654
655 if (exc_context.process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
656 {
657 err.SetErrorToGenericError();
Greg Claytonc0fa5332011-05-22 22:46:53 +0000658 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 +0000659 return err;
660 }
661
Greg Claytond0882d02011-01-19 23:00:49 +0000662 jit_memory_manager->AddToLocalToRemoteMap (lstart, size, cursor);
Sean Callanan65dafa82010-08-27 01:01:44 +0000663 cursor += size;
664 }
665
666 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
667
668 for (pos = m_jitted_functions.begin(); pos != end; pos++)
669 {
Greg Claytond0882d02011-01-19 23:00:49 +0000670 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000671
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000672 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000673 {
Greg Claytond0882d02011-01-19 23:00:49 +0000674 func_end = jit_memory_manager->GetRemoteRangeForLocal ((*pos).m_local_addr).second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000675 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000676 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000677 }
678
Sean Callanan6dff8272010-11-08 03:49:50 +0000679 if (log)
680 {
681 log->Printf("Code can be run in the target.");
682
683 StreamString disassembly_stream;
684
Greg Claytond0882d02011-01-19 23:00:49 +0000685 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000686
687 if (!err.Success())
688 {
689 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
690 }
691 else
692 {
693 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
694 }
695 }
696
Sean Callanan65dafa82010-08-27 01:01:44 +0000697 err.Clear();
698 return err;
699}
700
701Error
Greg Claytond0882d02011-01-19 23:00:49 +0000702ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000703{
Greg Claytone005f2c2010-11-06 01:53:30 +0000704 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000705
706 const char *name = m_expr.FunctionName();
707
708 Error ret;
709
710 ret.Clear();
711
712 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
713 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
714
715 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
716
717 for (pos = m_jitted_functions.begin(); pos < end; pos++)
718 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000719 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000720 {
721 func_local_addr = pos->m_local_addr;
722 func_remote_addr = pos->m_remote_addr;
723 }
724 }
725
726 if (func_local_addr == LLDB_INVALID_ADDRESS)
727 {
728 ret.SetErrorToGenericError();
729 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
730 return ret;
731 }
732
733 if(log)
734 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
735
736 std::pair <lldb::addr_t, lldb::addr_t> func_range;
737
Greg Claytond0882d02011-01-19 23:00:49 +0000738 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000739
740 if (func_range.first == 0 && func_range.second == 0)
741 {
742 ret.SetErrorToGenericError();
743 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
744 return ret;
745 }
746
747 if(log)
748 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
749
750 if (!exe_ctx.target)
751 {
752 ret.SetErrorToGenericError();
753 ret.SetErrorString("Couldn't find the target");
754 }
755
756 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
757
758 Error err;
759 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
760
761 if (!err.Success())
762 {
763 ret.SetErrorToGenericError();
764 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
765 return ret;
766 }
767
768 ArchSpec arch(exe_ctx.target->GetArchitecture());
769
Greg Clayton149731c2011-03-25 18:03:16 +0000770 Disassembler *disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000771
772 if (disassembler == NULL)
773 {
774 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000775 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000776 return ret;
777 }
778
779 if (!exe_ctx.process)
780 {
781 ret.SetErrorToGenericError();
782 ret.SetErrorString("Couldn't find the process");
783 return ret;
784 }
785
786 DataExtractor extractor(buffer_sp,
787 exe_ctx.process->GetByteOrder(),
788 exe_ctx.target->GetArchitecture().GetAddressByteSize());
789
Greg Claytone005f2c2010-11-06 01:53:30 +0000790 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000791 {
792 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000793 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000794 0,
795 extractor.GetByteSize(),
796 func_remote_addr,
797 16,
798 DataExtractor::TypeUInt8);
799 }
800
Jim Inghamaa3e3e12011-03-22 01:48:42 +0000801 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000802
Greg Clayton5c4c7462010-10-06 03:09:58 +0000803 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000804 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000805 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
806 instruction_index < num_instructions;
807 ++instruction_index)
808 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000809 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000810 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000811 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000812 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000813 true,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000814 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000815 true);
816 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000817 }
818
819 return ret;
820}