blob: 0c07bcb6a50eea8c6f664cd21adf08f453e6d17a [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/IRForTarget.h"
23#include "lldb/Expression/IRToDWARF.h"
24#include "lldb/Expression/RecordingMemoryManager.h"
25#include "lldb/Target/ExecutionContext.h"
Sean Callananc7674af2011-01-17 23:42:46 +000026#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000027#include "lldb/Target/Process.h"
28#include "lldb/Target/Target.h"
29
30#include "clang/AST/ASTContext.h"
31#include "clang/AST/ExternalASTSource.h"
32#include "clang/Basic/FileManager.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Version.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000035#include "clang/CodeGen/CodeGenAction.h"
36#include "clang/CodeGen/ModuleBuilder.h"
37#include "clang/Driver/CC1Options.h"
38#include "clang/Driver/OptTable.h"
39#include "clang/Frontend/CompilerInstance.h"
40#include "clang/Frontend/CompilerInvocation.h"
41#include "clang/Frontend/FrontendActions.h"
42#include "clang/Frontend/FrontendDiagnostic.h"
43#include "clang/Frontend/FrontendPluginRegistry.h"
44#include "clang/Frontend/TextDiagnosticBuffer.h"
45#include "clang/Frontend/TextDiagnosticPrinter.h"
46#include "clang/Frontend/VerifyDiagnosticsClient.h"
47#include "clang/Lex/Preprocessor.h"
Sean Callanan47a5c4c2010-09-23 03:01:22 +000048#include "clang/Parse/ParseAST.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000049#include "clang/Rewrite/FrontendActions.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000050#include "clang/Sema/SemaConsumer.h"
Sean Callanan279584c2011-03-15 00:17:19 +000051#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000052
53#include "llvm/ADT/StringRef.h"
54#include "llvm/ExecutionEngine/ExecutionEngine.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000055
56#define USE_STANDARD_JIT
57#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +000058#include "llvm/ExecutionEngine/JIT.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000059#else
60#include "llvm/ExecutionEngine/MCJIT.h"
61#endif
Sean Callanan65dafa82010-08-27 01:01:44 +000062#include "llvm/LLVMContext.h"
Sean Callanan279584c2011-03-15 00:17:19 +000063#include "llvm/Module.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000064#include "llvm/Support/ErrorHandling.h"
65#include "llvm/Support/MemoryBuffer.h"
Greg Clayton22defe82010-12-02 23:20:03 +000066#include "llvm/Support/DynamicLibrary.h"
67#include "llvm/Support/Host.h"
68#include "llvm/Support/Signals.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000069#include "llvm/Target/TargetRegistry.h"
70#include "llvm/Target/TargetSelect.h"
71
72using namespace clang;
73using namespace llvm;
74using namespace lldb_private;
75
76//===----------------------------------------------------------------------===//
77// Utility Methods for Clang
78//===----------------------------------------------------------------------===//
79
80std::string GetBuiltinIncludePath(const char *Argv0) {
81 llvm::sys::Path P =
82 llvm::sys::Path::GetMainExecutable(Argv0,
83 (void*)(intptr_t) GetBuiltinIncludePath);
84
85 if (!P.isEmpty()) {
86 P.eraseComponent(); // Remove /clang from foo/bin/clang
87 P.eraseComponent(); // Remove /bin from foo/bin
88
89 // Get foo/lib/clang/<version>/include
90 P.appendComponent("lib");
91 P.appendComponent("clang");
92 P.appendComponent(CLANG_VERSION_STRING);
93 P.appendComponent("include");
94 }
95
96 return P.str();
97}
98
99
100//===----------------------------------------------------------------------===//
101// Main driver for Clang
102//===----------------------------------------------------------------------===//
103
104static void LLVMErrorHandler(void *UserData, const std::string &Message) {
105 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
106
107 Diags.Report(diag::err_fe_error_backend) << Message;
108
109 // We cannot recover from llvm errors.
110 exit(1);
111}
112
113static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
114 using namespace clang::frontend;
115
116 switch (CI.getFrontendOpts().ProgramAction) {
117 default:
118 llvm_unreachable("Invalid program action!");
119
120 case ASTDump: return new ASTDumpAction();
121 case ASTPrint: return new ASTPrintAction();
Sean Callanan279584c2011-03-15 00:17:19 +0000122 case ASTDumpXML: return new ASTDumpXMLAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000123 case ASTView: return new ASTViewAction();
124 case BoostCon: return new BoostConAction();
125 case DumpRawTokens: return new DumpRawTokensAction();
126 case DumpTokens: return new DumpTokensAction();
127 case EmitAssembly: return new EmitAssemblyAction();
128 case EmitBC: return new EmitBCAction();
129 case EmitHTML: return new HTMLPrintAction();
130 case EmitLLVM: return new EmitLLVMAction();
131 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
132 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
133 case EmitObj: return new EmitObjAction();
134 case FixIt: return new FixItAction();
135 case GeneratePCH: return new GeneratePCHAction();
136 case GeneratePTH: return new GeneratePTHAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000137 case InitOnly: return new InitOnlyAction();
138 case ParseSyntaxOnly: return new SyntaxOnlyAction();
139
140 case PluginAction: {
141 for (FrontendPluginRegistry::iterator it =
142 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
143 it != ie; ++it) {
144 if (it->getName() == CI.getFrontendOpts().ActionName) {
145 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
146 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
147 return 0;
148 return P.take();
149 }
150 }
151
152 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
153 << CI.getFrontendOpts().ActionName;
154 return 0;
155 }
156
157 case PrintDeclContext: return new DeclContextPrintAction();
158 case PrintPreamble: return new PrintPreambleAction();
159 case PrintPreprocessedInput: return new PrintPreprocessedAction();
160 case RewriteMacros: return new RewriteMacrosAction();
161 case RewriteObjC: return new RewriteObjCAction();
162 case RewriteTest: return new RewriteTestAction();
Sean Callananad293092011-01-18 23:32:05 +0000163 //case RunAnalysis: return new AnalysisAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000164 case RunPreprocessorOnly: return new PreprocessOnlyAction();
165 }
166}
167
168static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
169 // Create the underlying action.
170 FrontendAction *Act = CreateFrontendBaseAction(CI);
171 if (!Act)
172 return 0;
173
174 // If there are any AST files to merge, create a frontend action
175 // adaptor to perform the merge.
176 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
177 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
178 CI.getFrontendOpts().ASTMergeFiles.size());
179
180 return Act;
181}
182
183//===----------------------------------------------------------------------===//
184// Implementation of ClangExpressionParser
185//===----------------------------------------------------------------------===//
186
Greg Clayton395fc332011-02-15 21:59:32 +0000187ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
188 ClangExpression &expr) :
189 m_expr (expr),
Sean Callanan65dafa82010-08-27 01:01:44 +0000190 m_compiler (),
191 m_code_generator (NULL),
192 m_execution_engine (),
193 m_jitted_functions ()
194{
195 // Initialize targets first, so that --version shows registered targets.
196 static struct InitializeLLVM {
197 InitializeLLVM() {
198 llvm::InitializeAllTargets();
199 llvm::InitializeAllAsmPrinters();
200 }
201 } InitializeLLVM;
Greg Clayton395fc332011-02-15 21:59:32 +0000202
Sean Callanan65dafa82010-08-27 01:01:44 +0000203 // 1. Create a new compiler instance.
204 m_compiler.reset(new CompilerInstance());
Sean Callanan65dafa82010-08-27 01:01:44 +0000205
206 // 2. Set options.
207
208 // Parse expressions as Objective C++ regardless of context.
209 // Our hook into Clang's lookup mechanism only works in C++.
210 m_compiler->getLangOpts().CPlusPlus = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000211
212 // Setup objective C
Sean Callanan65dafa82010-08-27 01:01:44 +0000213 m_compiler->getLangOpts().ObjC1 = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000214 m_compiler->getLangOpts().ObjC2 = true;
Sean Callananc7674af2011-01-17 23:42:46 +0000215
Greg Clayton395fc332011-02-15 21:59:32 +0000216 Process *process = NULL;
217 if (exe_scope)
218 process = exe_scope->CalculateProcess();
219
Sean Callananc7674af2011-01-17 23:42:46 +0000220 if (process)
221 {
222 if (process->GetObjCLanguageRuntime())
223 {
Greg Claytonb3448432011-03-24 21:19:54 +0000224 if (process->GetObjCLanguageRuntime()->GetRuntimeVersion() == eAppleObjC_V2)
Sean Callananc7674af2011-01-17 23:42:46 +0000225 {
226 m_compiler->getLangOpts().ObjCNonFragileABI = true; // NOT i386
227 m_compiler->getLangOpts().ObjCNonFragileABI2 = true; // NOT i386
228 }
229 }
230 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000231
Sean Callanan65dafa82010-08-27 01:01:44 +0000232 m_compiler->getLangOpts().ThreadsafeStatics = false;
233 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
234 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
235
236 // Set CodeGen options
237 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
238 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
239
240 // Disable some warnings.
241 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
242
243 // Set the target triple.
Greg Clayton395fc332011-02-15 21:59:32 +0000244 Target *target = NULL;
245 if (exe_scope)
246 target = exe_scope->CalculateTarget();
247
248 // TODO: figure out what to really do when we don't have a valid target.
249 // Sometimes this will be ok to just use the host target triple (when we
250 // evaluate say "2+3", but other expressions like breakpoint conditions
251 // and other things that _are_ target specific really shouldn't just be
252 // using the host triple. This needs to be fixed in a better way.
253 if (target && target->GetArchitecture().IsValid())
Sean Callanan2a8c3382011-04-14 02:01:31 +0000254 {
255 std::string triple = target->GetArchitecture().GetTriple().str();
256
257 int dash_count = 0;
258 for (int i = 0; i < triple.size(); ++i)
259 {
260 if (triple[i] == '-')
261 dash_count++;
262 if (dash_count == 3)
263 {
264 triple.resize(i);
265 break;
266 }
267 }
268
269 m_compiler->getTargetOpts().Triple = triple;
270 }
Greg Clayton395fc332011-02-15 21:59:32 +0000271 else
Sean Callanan2a8c3382011-04-14 02:01:31 +0000272 {
Greg Clayton395fc332011-02-15 21:59:32 +0000273 m_compiler->getTargetOpts().Triple = llvm::sys::getHostTriple();
Sean Callanan2a8c3382011-04-14 02:01:31 +0000274 }
275
Sean Callanan65dafa82010-08-27 01:01:44 +0000276 // 3. Set up various important bits of infrastructure.
277 m_compiler->createDiagnostics(0, 0);
278
279 // Create the target instance.
280 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
281 m_compiler->getTargetOpts()));
282
283 assert (m_compiler->hasTarget());
284
285 // Inform the target of the language options
286 //
287 // FIXME: We shouldn't need to do this, the target should be immutable once
288 // created. This complexity should be lifted elsewhere.
289 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
290
291 // 4. Set up the diagnostic buffer for reporting errors
292
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000293 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000294
295 // 5. Set up the source management objects inside the compiler
296
Greg Clayton22defe82010-12-02 23:20:03 +0000297 clang::FileSystemOptions file_system_options;
298 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000299
Sean Callanan65dafa82010-08-27 01:01:44 +0000300 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000301 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000302
303 m_compiler->createFileManager();
304 m_compiler->createPreprocessor();
305
306 // 6. Most of this we get from the CompilerInstance, but we
307 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000308 m_selector_table.reset(new SelectorTable());
Sean Callanan65dafa82010-08-27 01:01:44 +0000309 m_builtin_context.reset(new Builtin::Context(m_compiler->getTarget()));
310
311 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
312 m_compiler->getSourceManager(),
313 m_compiler->getTarget(),
314 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000315 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000316 *m_builtin_context.get(),
317 0));
318
319 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
320
321 if (decl_map)
322 {
323 OwningPtr<clang::ExternalASTSource> ast_source(new ClangASTSource(*ast_context, *decl_map));
324 ast_context->setExternalSource(ast_source);
325 }
326
327 m_compiler->setASTContext(ast_context.release());
328
Greg Clayton8de27c72010-10-15 22:48:33 +0000329 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000330
Sean Callanan279584c2011-03-15 00:17:19 +0000331 m_llvm_context.reset(new LLVMContext());
Sean Callanan65dafa82010-08-27 01:01:44 +0000332 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
333 module_name,
334 m_compiler->getCodeGenOpts(),
Sean Callanan279584c2011-03-15 00:17:19 +0000335 *m_llvm_context));
Sean Callanan65dafa82010-08-27 01:01:44 +0000336}
337
338ClangExpressionParser::~ClangExpressionParser()
339{
340}
341
342unsigned
343ClangExpressionParser::Parse (Stream &stream)
344{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000345 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
346
347 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000348
349 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
350 FileID memory_buffer_file_id = m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
351
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000352 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000353
354 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
355
356 if (ast_transformer)
357 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
358 else
359 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
360
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000361 diag_buf->EndSourceFile();
Sean Callananfb3058e2011-05-12 23:54:16 +0000362
Sean Callanan65dafa82010-08-27 01:01:44 +0000363 TextDiagnosticBuffer::const_iterator diag_iterator;
364
365 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000366
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000367 for (diag_iterator = diag_buf->warn_begin();
368 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000369 ++diag_iterator)
370 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
371
372 num_errors = 0;
373
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000374 for (diag_iterator = diag_buf->err_begin();
375 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000376 ++diag_iterator)
377 {
378 num_errors++;
379 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
380 }
381
Sean Callanan7617c292010-11-01 20:28:09 +0000382 for (diag_iterator = diag_buf->note_begin();
383 diag_iterator != diag_buf->note_end();
384 ++diag_iterator)
385 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
386
Sean Callananfb3058e2011-05-12 23:54:16 +0000387 if (!num_errors)
388 {
389 if (m_expr.DeclMap() && !m_expr.DeclMap()->ResolveUnknownTypes())
390 {
391 stream.Printf("error: Couldn't infer the type of a variable\n");
392 num_errors++;
393 }
394 }
395
Sean Callanan65dafa82010-08-27 01:01:44 +0000396 return num_errors;
397}
398
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000399static bool FindFunctionInModule (std::string &mangled_name,
400 llvm::Module *module,
401 const char *orig_name)
402{
403 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
404 fi != fe;
405 ++fi)
406 {
407 if (fi->getName().str().find(orig_name) != std::string::npos)
408 {
409 mangled_name = fi->getName().str();
410 return true;
411 }
412 }
413
414 return false;
415}
416
Sean Callanan65dafa82010-08-27 01:01:44 +0000417Error
418ClangExpressionParser::MakeDWARF ()
419{
420 Error err;
421
422 llvm::Module *module = m_code_generator->GetModule();
423
424 if (!module)
425 {
426 err.SetErrorToGenericError();
427 err.SetErrorString("IR doesn't contain a module");
428 return err;
429 }
430
Greg Clayton427f2902010-12-14 02:59:59 +0000431 ClangExpressionVariableList *local_variables = m_expr.LocalVariables();
Sean Callanan65dafa82010-08-27 01:01:44 +0000432 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
433
434 if (!local_variables)
435 {
436 err.SetErrorToGenericError();
437 err.SetErrorString("Can't convert an expression without a VariableList to DWARF");
438 return err;
439 }
440
441 if (!decl_map)
442 {
443 err.SetErrorToGenericError();
444 err.SetErrorString("Can't convert an expression without a DeclMap to DWARF");
445 return err;
446 }
447
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000448 std::string function_name;
449
450 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
451 {
452 err.SetErrorToGenericError();
453 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
454 return err;
455 }
456
457 IRToDWARF ir_to_dwarf(*local_variables, decl_map, m_expr.DwarfOpcodeStream(), function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000458
459 if (!ir_to_dwarf.runOnModule(*module))
460 {
461 err.SetErrorToGenericError();
462 err.SetErrorString("Couldn't convert the expression to DWARF");
463 return err;
464 }
465
466 err.Clear();
467 return err;
468}
469
470Error
Greg Claytond0882d02011-01-19 23:00:49 +0000471ClangExpressionParser::MakeJIT (lldb::addr_t &func_allocation_addr,
472 lldb::addr_t &func_addr,
Sean Callanan830a9032010-08-27 23:31:21 +0000473 lldb::addr_t &func_end,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000474 ExecutionContext &exe_ctx,
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 Callanan97c924e2011-01-27 01:07:04 +0000522 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000523 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000524
525 if (!ir_for_target.runOnModule(*module))
526 {
527 err.SetErrorToGenericError();
528 err.SetErrorString("Couldn't convert the expression to DWARF");
529 return err;
530 }
Sean Callananf18d91c2010-09-01 00:58:00 +0000531
Sean Callanan696cf5f2011-05-07 01:06:41 +0000532 if (jit_only_if_needed && const_result.get())
533 {
534 err.Clear();
535 return err;
536 }
537
Jim Inghamd1686902010-10-14 23:45:03 +0000538 if (m_expr.NeedsValidation() && exe_ctx.process->GetDynamicCheckers())
Sean Callananf18d91c2010-09-01 00:58:00 +0000539 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000540 IRDynamicChecks ir_dynamic_checks(*exe_ctx.process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000541
542 if (!ir_dynamic_checks.runOnModule(*module))
543 {
544 err.SetErrorToGenericError();
545 err.SetErrorString("Couldn't add dynamic checks to the expression");
546 return err;
547 }
548 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000549 }
550
Greg Claytond0882d02011-01-19 23:00:49 +0000551 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
552 // below so we don't need to free it.
553 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000554
555 std::string error_string;
Sean Callanan9ac3a962010-11-02 23:20:00 +0000556
Sean Callananc2c6f772010-10-26 00:31:56 +0000557 llvm::TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
558
Greg Clayton2f085c62011-05-15 01:25:55 +0000559#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +0000560 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
561 &error_string,
Greg Claytond0882d02011-01-19 23:00:49 +0000562 jit_memory_manager,
Sean Callananc2c6f772010-10-26 00:31:56 +0000563 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000564 true,
565 CodeModel::Small));
Greg Clayton2f085c62011-05-15 01:25:55 +0000566#else
567 EngineBuilder builder(module);
568 builder.setEngineKind(EngineKind::JIT)
569 .setErrorStr(&error_string)
570 .setJITMemoryManager(jit_memory_manager)
571 .setOptLevel(CodeGenOpt::Less)
572 .setAllocateGVsWithCode(true)
573 .setCodeModel(CodeModel::Small)
574 .setUseMCJIT(true);
575 m_execution_engine.reset(builder.create());
576#endif
Sean Callanan9ac3a962010-11-02 23:20:00 +0000577
Sean Callanan65dafa82010-08-27 01:01:44 +0000578 if (!m_execution_engine.get())
579 {
580 err.SetErrorToGenericError();
581 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
582 return err;
583 }
584
585 m_execution_engine->DisableLazyCompilation();
586
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000587 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000588
589 // We don't actually need the function pointer here, this just forces it to get resolved.
590
591 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
592
593 // Errors usually cause failures in the JIT, but if we're lucky we get here.
594
595 if (!fun_ptr)
596 {
597 err.SetErrorToGenericError();
598 err.SetErrorString("Couldn't JIT the function");
599 return err;
600 }
601
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000602 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000603
604 ExecutionContext &exc_context(exe_ctx);
605
606 if (exc_context.process == NULL)
607 {
608 err.SetErrorToGenericError();
609 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
610 return err;
611 }
612
613 // Look over the regions allocated for the function compiled. The JIT
614 // tries to allocate the functions & stubs close together, so we should try to
615 // write them that way too...
616 // For now I only write functions with no stubs, globals, exception tables,
617 // etc. So I only need to write the functions.
618
619 size_t alloc_size = 0;
620
Greg Claytond0882d02011-01-19 23:00:49 +0000621 std::map<uint8_t *, uint8_t *>::iterator fun_pos = jit_memory_manager->m_functions.begin();
622 std::map<uint8_t *, uint8_t *>::iterator fun_end = jit_memory_manager->m_functions.end();
Greg Clayton9d2b3212011-05-15 23:56:52 +0000623
Sean Callanan65dafa82010-08-27 01:01:44 +0000624 for (; fun_pos != fun_end; ++fun_pos)
Greg Clayton9d2b3212011-05-15 23:56:52 +0000625 {
626 size_t mem_size = fun_pos->second - fun_pos->first;
627 if (log)
628 log->Printf ("JIT memory: [%p - %p) size = %zu", fun_pos->first, fun_pos->second, mem_size);
629 alloc_size += mem_size;
630 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000631
632 Error alloc_error;
Greg Claytond0882d02011-01-19 23:00:49 +0000633 func_allocation_addr = exc_context.process->AllocateMemory (alloc_size,
634 lldb::ePermissionsReadable|lldb::ePermissionsExecutable,
635 alloc_error);
Sean Callanan65dafa82010-08-27 01:01:44 +0000636
Greg Claytond0882d02011-01-19 23:00:49 +0000637 if (func_allocation_addr == LLDB_INVALID_ADDRESS)
Sean Callanan65dafa82010-08-27 01:01:44 +0000638 {
639 err.SetErrorToGenericError();
640 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
641 return err;
642 }
643
Greg Claytond0882d02011-01-19 23:00:49 +0000644 lldb::addr_t cursor = func_allocation_addr;
Sean Callanan65dafa82010-08-27 01:01:44 +0000645
Greg Claytond0882d02011-01-19 23:00:49 +0000646 for (fun_pos = jit_memory_manager->m_functions.begin(); fun_pos != fun_end; fun_pos++)
Sean Callanan65dafa82010-08-27 01:01:44 +0000647 {
648 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
649 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
650 size_t size = lend - lstart;
651
652 Error write_error;
653
654 if (exc_context.process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
655 {
656 err.SetErrorToGenericError();
657 err.SetErrorStringWithFormat("Couldn't copy JITted function into the target: %s", write_error.AsCString("unknown error"));
658 return err;
659 }
660
Greg Claytond0882d02011-01-19 23:00:49 +0000661 jit_memory_manager->AddToLocalToRemoteMap (lstart, size, cursor);
Sean Callanan65dafa82010-08-27 01:01:44 +0000662 cursor += size;
663 }
664
665 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
666
667 for (pos = m_jitted_functions.begin(); pos != end; pos++)
668 {
Greg Claytond0882d02011-01-19 23:00:49 +0000669 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000670
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000671 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000672 {
Greg Claytond0882d02011-01-19 23:00:49 +0000673 func_end = jit_memory_manager->GetRemoteRangeForLocal ((*pos).m_local_addr).second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000674 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000675 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000676 }
677
Sean Callanan6dff8272010-11-08 03:49:50 +0000678 if (log)
679 {
680 log->Printf("Code can be run in the target.");
681
682 StreamString disassembly_stream;
683
Greg Claytond0882d02011-01-19 23:00:49 +0000684 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000685
686 if (!err.Success())
687 {
688 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
689 }
690 else
691 {
692 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
693 }
694 }
695
Sean Callanan65dafa82010-08-27 01:01:44 +0000696 err.Clear();
697 return err;
698}
699
700Error
Greg Claytond0882d02011-01-19 23:00:49 +0000701ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000702{
Greg Claytone005f2c2010-11-06 01:53:30 +0000703 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000704
705 const char *name = m_expr.FunctionName();
706
707 Error ret;
708
709 ret.Clear();
710
711 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
712 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
713
714 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
715
716 for (pos = m_jitted_functions.begin(); pos < end; pos++)
717 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000718 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000719 {
720 func_local_addr = pos->m_local_addr;
721 func_remote_addr = pos->m_remote_addr;
722 }
723 }
724
725 if (func_local_addr == LLDB_INVALID_ADDRESS)
726 {
727 ret.SetErrorToGenericError();
728 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
729 return ret;
730 }
731
732 if(log)
733 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
734
735 std::pair <lldb::addr_t, lldb::addr_t> func_range;
736
Greg Claytond0882d02011-01-19 23:00:49 +0000737 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000738
739 if (func_range.first == 0 && func_range.second == 0)
740 {
741 ret.SetErrorToGenericError();
742 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
743 return ret;
744 }
745
746 if(log)
747 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
748
749 if (!exe_ctx.target)
750 {
751 ret.SetErrorToGenericError();
752 ret.SetErrorString("Couldn't find the target");
753 }
754
755 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
756
757 Error err;
758 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
759
760 if (!err.Success())
761 {
762 ret.SetErrorToGenericError();
763 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
764 return ret;
765 }
766
767 ArchSpec arch(exe_ctx.target->GetArchitecture());
768
Greg Clayton149731c2011-03-25 18:03:16 +0000769 Disassembler *disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000770
771 if (disassembler == NULL)
772 {
773 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000774 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000775 return ret;
776 }
777
778 if (!exe_ctx.process)
779 {
780 ret.SetErrorToGenericError();
781 ret.SetErrorString("Couldn't find the process");
782 return ret;
783 }
784
785 DataExtractor extractor(buffer_sp,
786 exe_ctx.process->GetByteOrder(),
787 exe_ctx.target->GetArchitecture().GetAddressByteSize());
788
Greg Claytone005f2c2010-11-06 01:53:30 +0000789 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000790 {
791 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000792 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000793 0,
794 extractor.GetByteSize(),
795 func_remote_addr,
796 16,
797 DataExtractor::TypeUInt8);
798 }
799
Jim Inghamaa3e3e12011-03-22 01:48:42 +0000800 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000801
Greg Clayton5c4c7462010-10-06 03:09:58 +0000802 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000803 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000804 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
805 instruction_index < num_instructions;
806 ++instruction_index)
807 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000808 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000809 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000810 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000811 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000812 true,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000813 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000814 true);
815 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000816 }
817
818 return ret;
819}