blob: 01095b509696acb9f277de00c45782b420a663f2 [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();
126 case BoostCon: return new BoostConAction();
127 case DumpRawTokens: return new DumpRawTokensAction();
128 case DumpTokens: return new DumpTokensAction();
129 case EmitAssembly: return new EmitAssemblyAction();
130 case EmitBC: return new EmitBCAction();
131 case EmitHTML: return new HTMLPrintAction();
132 case EmitLLVM: return new EmitLLVMAction();
133 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
134 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
135 case EmitObj: return new EmitObjAction();
136 case FixIt: return new FixItAction();
137 case GeneratePCH: return new GeneratePCHAction();
138 case GeneratePTH: return new GeneratePTHAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000139 case InitOnly: return new InitOnlyAction();
140 case ParseSyntaxOnly: return new SyntaxOnlyAction();
141
142 case PluginAction: {
143 for (FrontendPluginRegistry::iterator it =
144 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
145 it != ie; ++it) {
146 if (it->getName() == CI.getFrontendOpts().ActionName) {
147 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
148 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
149 return 0;
150 return P.take();
151 }
152 }
153
154 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
155 << CI.getFrontendOpts().ActionName;
156 return 0;
157 }
158
159 case PrintDeclContext: return new DeclContextPrintAction();
160 case PrintPreamble: return new PrintPreambleAction();
161 case PrintPreprocessedInput: return new PrintPreprocessedAction();
162 case RewriteMacros: return new RewriteMacrosAction();
163 case RewriteObjC: return new RewriteObjCAction();
164 case RewriteTest: return new RewriteTestAction();
Sean Callananad293092011-01-18 23:32:05 +0000165 //case RunAnalysis: return new AnalysisAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000166 case RunPreprocessorOnly: return new PreprocessOnlyAction();
167 }
168}
169
170static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
171 // Create the underlying action.
172 FrontendAction *Act = CreateFrontendBaseAction(CI);
173 if (!Act)
174 return 0;
175
176 // If there are any AST files to merge, create a frontend action
177 // adaptor to perform the merge.
178 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
179 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
180 CI.getFrontendOpts().ASTMergeFiles.size());
181
182 return Act;
183}
184
185//===----------------------------------------------------------------------===//
186// Implementation of ClangExpressionParser
187//===----------------------------------------------------------------------===//
188
Greg Clayton395fc332011-02-15 21:59:32 +0000189ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
190 ClangExpression &expr) :
191 m_expr (expr),
Sean Callanan65dafa82010-08-27 01:01:44 +0000192 m_compiler (),
193 m_code_generator (NULL),
194 m_execution_engine (),
195 m_jitted_functions ()
196{
197 // Initialize targets first, so that --version shows registered targets.
198 static struct InitializeLLVM {
199 InitializeLLVM() {
200 llvm::InitializeAllTargets();
201 llvm::InitializeAllAsmPrinters();
202 }
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 Callanan9ac3a962010-11-02 23:20:00 +0000560
Sean Callananc2c6f772010-10-26 00:31:56 +0000561 llvm::TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
562
Greg Clayton2f085c62011-05-15 01:25:55 +0000563#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +0000564 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
565 &error_string,
Greg Claytond0882d02011-01-19 23:00:49 +0000566 jit_memory_manager,
Sean Callananc2c6f772010-10-26 00:31:56 +0000567 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000568 true,
569 CodeModel::Small));
Greg Clayton2f085c62011-05-15 01:25:55 +0000570#else
571 EngineBuilder builder(module);
572 builder.setEngineKind(EngineKind::JIT)
573 .setErrorStr(&error_string)
574 .setJITMemoryManager(jit_memory_manager)
575 .setOptLevel(CodeGenOpt::Less)
576 .setAllocateGVsWithCode(true)
577 .setCodeModel(CodeModel::Small)
578 .setUseMCJIT(true);
579 m_execution_engine.reset(builder.create());
580#endif
Sean Callanan9ac3a962010-11-02 23:20:00 +0000581
Sean Callanan65dafa82010-08-27 01:01:44 +0000582 if (!m_execution_engine.get())
583 {
584 err.SetErrorToGenericError();
585 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
586 return err;
587 }
588
589 m_execution_engine->DisableLazyCompilation();
590
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000591 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000592
593 // We don't actually need the function pointer here, this just forces it to get resolved.
594
595 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
596
597 // Errors usually cause failures in the JIT, but if we're lucky we get here.
598
599 if (!fun_ptr)
600 {
601 err.SetErrorToGenericError();
602 err.SetErrorString("Couldn't JIT the function");
603 return err;
604 }
605
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000606 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000607
608 ExecutionContext &exc_context(exe_ctx);
609
610 if (exc_context.process == NULL)
611 {
612 err.SetErrorToGenericError();
613 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
614 return err;
615 }
616
617 // Look over the regions allocated for the function compiled. The JIT
618 // tries to allocate the functions & stubs close together, so we should try to
619 // write them that way too...
620 // For now I only write functions with no stubs, globals, exception tables,
621 // etc. So I only need to write the functions.
622
623 size_t alloc_size = 0;
624
Greg Claytond0882d02011-01-19 23:00:49 +0000625 std::map<uint8_t *, uint8_t *>::iterator fun_pos = jit_memory_manager->m_functions.begin();
626 std::map<uint8_t *, uint8_t *>::iterator fun_end = jit_memory_manager->m_functions.end();
Greg Clayton9d2b3212011-05-15 23:56:52 +0000627
Sean Callanan65dafa82010-08-27 01:01:44 +0000628 for (; fun_pos != fun_end; ++fun_pos)
Greg Clayton9d2b3212011-05-15 23:56:52 +0000629 {
630 size_t mem_size = fun_pos->second - fun_pos->first;
631 if (log)
632 log->Printf ("JIT memory: [%p - %p) size = %zu", fun_pos->first, fun_pos->second, mem_size);
633 alloc_size += mem_size;
634 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000635
636 Error alloc_error;
Greg Claytond0882d02011-01-19 23:00:49 +0000637 func_allocation_addr = exc_context.process->AllocateMemory (alloc_size,
638 lldb::ePermissionsReadable|lldb::ePermissionsExecutable,
639 alloc_error);
Sean Callanan65dafa82010-08-27 01:01:44 +0000640
Greg Claytond0882d02011-01-19 23:00:49 +0000641 if (func_allocation_addr == LLDB_INVALID_ADDRESS)
Sean Callanan65dafa82010-08-27 01:01:44 +0000642 {
643 err.SetErrorToGenericError();
644 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
645 return err;
646 }
647
Greg Claytond0882d02011-01-19 23:00:49 +0000648 lldb::addr_t cursor = func_allocation_addr;
Sean Callanan65dafa82010-08-27 01:01:44 +0000649
Greg Claytond0882d02011-01-19 23:00:49 +0000650 for (fun_pos = jit_memory_manager->m_functions.begin(); fun_pos != fun_end; fun_pos++)
Sean Callanan65dafa82010-08-27 01:01:44 +0000651 {
652 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
653 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
654 size_t size = lend - lstart;
655
656 Error write_error;
657
658 if (exc_context.process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
659 {
660 err.SetErrorToGenericError();
Greg Claytonc0fa5332011-05-22 22:46:53 +0000661 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 +0000662 return err;
663 }
664
Greg Claytond0882d02011-01-19 23:00:49 +0000665 jit_memory_manager->AddToLocalToRemoteMap (lstart, size, cursor);
Sean Callanan65dafa82010-08-27 01:01:44 +0000666 cursor += size;
667 }
668
669 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
670
671 for (pos = m_jitted_functions.begin(); pos != end; pos++)
672 {
Greg Claytond0882d02011-01-19 23:00:49 +0000673 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000674
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000675 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000676 {
Greg Claytond0882d02011-01-19 23:00:49 +0000677 func_end = jit_memory_manager->GetRemoteRangeForLocal ((*pos).m_local_addr).second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000678 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000679 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000680 }
681
Sean Callanan6dff8272010-11-08 03:49:50 +0000682 if (log)
683 {
684 log->Printf("Code can be run in the target.");
685
686 StreamString disassembly_stream;
687
Greg Claytond0882d02011-01-19 23:00:49 +0000688 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000689
690 if (!err.Success())
691 {
692 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
693 }
694 else
695 {
696 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
697 }
698 }
699
Sean Callanan65dafa82010-08-27 01:01:44 +0000700 err.Clear();
701 return err;
702}
703
704Error
Greg Claytond0882d02011-01-19 23:00:49 +0000705ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000706{
Greg Claytone005f2c2010-11-06 01:53:30 +0000707 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000708
709 const char *name = m_expr.FunctionName();
710
711 Error ret;
712
713 ret.Clear();
714
715 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
716 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
717
718 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
719
720 for (pos = m_jitted_functions.begin(); pos < end; pos++)
721 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000722 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000723 {
724 func_local_addr = pos->m_local_addr;
725 func_remote_addr = pos->m_remote_addr;
726 }
727 }
728
729 if (func_local_addr == LLDB_INVALID_ADDRESS)
730 {
731 ret.SetErrorToGenericError();
732 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
733 return ret;
734 }
735
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000736 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000737 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
738
739 std::pair <lldb::addr_t, lldb::addr_t> func_range;
740
Greg Claytond0882d02011-01-19 23:00:49 +0000741 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000742
743 if (func_range.first == 0 && func_range.second == 0)
744 {
745 ret.SetErrorToGenericError();
746 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
747 return ret;
748 }
749
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000750 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000751 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
752
753 if (!exe_ctx.target)
754 {
755 ret.SetErrorToGenericError();
756 ret.SetErrorString("Couldn't find the target");
757 }
758
759 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
760
761 Error err;
762 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
763
764 if (!err.Success())
765 {
766 ret.SetErrorToGenericError();
767 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
768 return ret;
769 }
770
771 ArchSpec arch(exe_ctx.target->GetArchitecture());
772
Greg Clayton149731c2011-03-25 18:03:16 +0000773 Disassembler *disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000774
775 if (disassembler == NULL)
776 {
777 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000778 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000779 return ret;
780 }
781
782 if (!exe_ctx.process)
783 {
784 ret.SetErrorToGenericError();
785 ret.SetErrorString("Couldn't find the process");
786 return ret;
787 }
788
789 DataExtractor extractor(buffer_sp,
790 exe_ctx.process->GetByteOrder(),
791 exe_ctx.target->GetArchitecture().GetAddressByteSize());
792
Greg Claytone005f2c2010-11-06 01:53:30 +0000793 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000794 {
795 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000796 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000797 0,
798 extractor.GetByteSize(),
799 func_remote_addr,
800 16,
801 DataExtractor::TypeUInt8);
802 }
803
Jim Inghamaa3e3e12011-03-22 01:48:42 +0000804 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000805
Greg Clayton5c4c7462010-10-06 03:09:58 +0000806 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000807 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000808 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
809 instruction_index < num_instructions;
810 ++instruction_index)
811 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000812 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000813 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000814 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000815 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000816 true,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000817 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000818 true);
819 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000820 }
821
822 return ret;
823}