blob: 028f99ab7e2456f43deb438e8a3f28f46aa3bc5c [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"
55#include "llvm/ExecutionEngine/JIT.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000056#include "llvm/LLVMContext.h"
Sean Callanan279584c2011-03-15 00:17:19 +000057#include "llvm/Module.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000058#include "llvm/Support/ErrorHandling.h"
59#include "llvm/Support/MemoryBuffer.h"
Greg Clayton22defe82010-12-02 23:20:03 +000060#include "llvm/Support/DynamicLibrary.h"
61#include "llvm/Support/Host.h"
62#include "llvm/Support/Signals.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000063#include "llvm/Target/TargetRegistry.h"
64#include "llvm/Target/TargetSelect.h"
65
66using namespace clang;
67using namespace llvm;
68using namespace lldb_private;
69
70//===----------------------------------------------------------------------===//
71// Utility Methods for Clang
72//===----------------------------------------------------------------------===//
73
74std::string GetBuiltinIncludePath(const char *Argv0) {
75 llvm::sys::Path P =
76 llvm::sys::Path::GetMainExecutable(Argv0,
77 (void*)(intptr_t) GetBuiltinIncludePath);
78
79 if (!P.isEmpty()) {
80 P.eraseComponent(); // Remove /clang from foo/bin/clang
81 P.eraseComponent(); // Remove /bin from foo/bin
82
83 // Get foo/lib/clang/<version>/include
84 P.appendComponent("lib");
85 P.appendComponent("clang");
86 P.appendComponent(CLANG_VERSION_STRING);
87 P.appendComponent("include");
88 }
89
90 return P.str();
91}
92
93
94//===----------------------------------------------------------------------===//
95// Main driver for Clang
96//===----------------------------------------------------------------------===//
97
98static void LLVMErrorHandler(void *UserData, const std::string &Message) {
99 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
100
101 Diags.Report(diag::err_fe_error_backend) << Message;
102
103 // We cannot recover from llvm errors.
104 exit(1);
105}
106
107static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
108 using namespace clang::frontend;
109
110 switch (CI.getFrontendOpts().ProgramAction) {
111 default:
112 llvm_unreachable("Invalid program action!");
113
114 case ASTDump: return new ASTDumpAction();
115 case ASTPrint: return new ASTPrintAction();
Sean Callanan279584c2011-03-15 00:17:19 +0000116 case ASTDumpXML: return new ASTDumpXMLAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000117 case ASTView: return new ASTViewAction();
118 case BoostCon: return new BoostConAction();
119 case DumpRawTokens: return new DumpRawTokensAction();
120 case DumpTokens: return new DumpTokensAction();
121 case EmitAssembly: return new EmitAssemblyAction();
122 case EmitBC: return new EmitBCAction();
123 case EmitHTML: return new HTMLPrintAction();
124 case EmitLLVM: return new EmitLLVMAction();
125 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
126 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
127 case EmitObj: return new EmitObjAction();
128 case FixIt: return new FixItAction();
129 case GeneratePCH: return new GeneratePCHAction();
130 case GeneratePTH: return new GeneratePTHAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000131 case InitOnly: return new InitOnlyAction();
132 case ParseSyntaxOnly: return new SyntaxOnlyAction();
133
134 case PluginAction: {
135 for (FrontendPluginRegistry::iterator it =
136 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
137 it != ie; ++it) {
138 if (it->getName() == CI.getFrontendOpts().ActionName) {
139 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
140 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
141 return 0;
142 return P.take();
143 }
144 }
145
146 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
147 << CI.getFrontendOpts().ActionName;
148 return 0;
149 }
150
151 case PrintDeclContext: return new DeclContextPrintAction();
152 case PrintPreamble: return new PrintPreambleAction();
153 case PrintPreprocessedInput: return new PrintPreprocessedAction();
154 case RewriteMacros: return new RewriteMacrosAction();
155 case RewriteObjC: return new RewriteObjCAction();
156 case RewriteTest: return new RewriteTestAction();
Sean Callananad293092011-01-18 23:32:05 +0000157 //case RunAnalysis: return new AnalysisAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000158 case RunPreprocessorOnly: return new PreprocessOnlyAction();
159 }
160}
161
162static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
163 // Create the underlying action.
164 FrontendAction *Act = CreateFrontendBaseAction(CI);
165 if (!Act)
166 return 0;
167
168 // If there are any AST files to merge, create a frontend action
169 // adaptor to perform the merge.
170 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
171 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
172 CI.getFrontendOpts().ASTMergeFiles.size());
173
174 return Act;
175}
176
177//===----------------------------------------------------------------------===//
178// Implementation of ClangExpressionParser
179//===----------------------------------------------------------------------===//
180
Greg Clayton395fc332011-02-15 21:59:32 +0000181ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
182 ClangExpression &expr) :
183 m_expr (expr),
Sean Callanan65dafa82010-08-27 01:01:44 +0000184 m_compiler (),
185 m_code_generator (NULL),
186 m_execution_engine (),
187 m_jitted_functions ()
188{
189 // Initialize targets first, so that --version shows registered targets.
190 static struct InitializeLLVM {
191 InitializeLLVM() {
192 llvm::InitializeAllTargets();
193 llvm::InitializeAllAsmPrinters();
194 }
195 } InitializeLLVM;
Greg Clayton395fc332011-02-15 21:59:32 +0000196
Sean Callanan65dafa82010-08-27 01:01:44 +0000197 // 1. Create a new compiler instance.
198 m_compiler.reset(new CompilerInstance());
Sean Callanan65dafa82010-08-27 01:01:44 +0000199
200 // 2. Set options.
201
202 // Parse expressions as Objective C++ regardless of context.
203 // Our hook into Clang's lookup mechanism only works in C++.
204 m_compiler->getLangOpts().CPlusPlus = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000205
206 // Setup objective C
Sean Callanan65dafa82010-08-27 01:01:44 +0000207 m_compiler->getLangOpts().ObjC1 = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000208 m_compiler->getLangOpts().ObjC2 = true;
Sean Callananc7674af2011-01-17 23:42:46 +0000209
Greg Clayton395fc332011-02-15 21:59:32 +0000210 Process *process = NULL;
211 if (exe_scope)
212 process = exe_scope->CalculateProcess();
213
Sean Callananc7674af2011-01-17 23:42:46 +0000214 if (process)
215 {
216 if (process->GetObjCLanguageRuntime())
217 {
Greg Claytonb3448432011-03-24 21:19:54 +0000218 if (process->GetObjCLanguageRuntime()->GetRuntimeVersion() == eAppleObjC_V2)
Sean Callananc7674af2011-01-17 23:42:46 +0000219 {
220 m_compiler->getLangOpts().ObjCNonFragileABI = true; // NOT i386
221 m_compiler->getLangOpts().ObjCNonFragileABI2 = true; // NOT i386
222 }
223 }
224 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000225
Sean Callanan65dafa82010-08-27 01:01:44 +0000226 m_compiler->getLangOpts().ThreadsafeStatics = false;
227 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
228 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
229
230 // Set CodeGen options
231 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
232 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
233
234 // Disable some warnings.
235 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
236
237 // Set the target triple.
Greg Clayton395fc332011-02-15 21:59:32 +0000238 Target *target = NULL;
239 if (exe_scope)
240 target = exe_scope->CalculateTarget();
241
242 // TODO: figure out what to really do when we don't have a valid target.
243 // Sometimes this will be ok to just use the host target triple (when we
244 // evaluate say "2+3", but other expressions like breakpoint conditions
245 // and other things that _are_ target specific really shouldn't just be
246 // using the host triple. This needs to be fixed in a better way.
247 if (target && target->GetArchitecture().IsValid())
Sean Callanan2a8c3382011-04-14 02:01:31 +0000248 {
249 std::string triple = target->GetArchitecture().GetTriple().str();
250
251 int dash_count = 0;
252 for (int i = 0; i < triple.size(); ++i)
253 {
254 if (triple[i] == '-')
255 dash_count++;
256 if (dash_count == 3)
257 {
258 triple.resize(i);
259 break;
260 }
261 }
262
263 m_compiler->getTargetOpts().Triple = triple;
264 }
Greg Clayton395fc332011-02-15 21:59:32 +0000265 else
Sean Callanan2a8c3382011-04-14 02:01:31 +0000266 {
Greg Clayton395fc332011-02-15 21:59:32 +0000267 m_compiler->getTargetOpts().Triple = llvm::sys::getHostTriple();
Sean Callanan2a8c3382011-04-14 02:01:31 +0000268 }
269
Sean Callanan65dafa82010-08-27 01:01:44 +0000270 // 3. Set up various important bits of infrastructure.
271 m_compiler->createDiagnostics(0, 0);
272
273 // Create the target instance.
274 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
275 m_compiler->getTargetOpts()));
276
277 assert (m_compiler->hasTarget());
278
279 // Inform the target of the language options
280 //
281 // FIXME: We shouldn't need to do this, the target should be immutable once
282 // created. This complexity should be lifted elsewhere.
283 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
284
285 // 4. Set up the diagnostic buffer for reporting errors
286
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000287 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000288
289 // 5. Set up the source management objects inside the compiler
290
Greg Clayton22defe82010-12-02 23:20:03 +0000291 clang::FileSystemOptions file_system_options;
292 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000293
Sean Callanan65dafa82010-08-27 01:01:44 +0000294 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000295 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000296
297 m_compiler->createFileManager();
298 m_compiler->createPreprocessor();
299
300 // 6. Most of this we get from the CompilerInstance, but we
301 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000302 m_selector_table.reset(new SelectorTable());
Sean Callanan65dafa82010-08-27 01:01:44 +0000303 m_builtin_context.reset(new Builtin::Context(m_compiler->getTarget()));
304
305 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
306 m_compiler->getSourceManager(),
307 m_compiler->getTarget(),
308 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000309 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000310 *m_builtin_context.get(),
311 0));
312
313 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
314
315 if (decl_map)
316 {
317 OwningPtr<clang::ExternalASTSource> ast_source(new ClangASTSource(*ast_context, *decl_map));
318 ast_context->setExternalSource(ast_source);
319 }
320
321 m_compiler->setASTContext(ast_context.release());
322
Greg Clayton8de27c72010-10-15 22:48:33 +0000323 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000324
Sean Callanan279584c2011-03-15 00:17:19 +0000325 m_llvm_context.reset(new LLVMContext());
Sean Callanan65dafa82010-08-27 01:01:44 +0000326 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
327 module_name,
328 m_compiler->getCodeGenOpts(),
Sean Callanan279584c2011-03-15 00:17:19 +0000329 *m_llvm_context));
Sean Callanan65dafa82010-08-27 01:01:44 +0000330}
331
332ClangExpressionParser::~ClangExpressionParser()
333{
334}
335
336unsigned
337ClangExpressionParser::Parse (Stream &stream)
338{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000339 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
340
341 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000342
343 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
344 FileID memory_buffer_file_id = m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
345
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000346 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000347
348 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
349
350 if (ast_transformer)
351 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
352 else
353 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
354
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000355 diag_buf->EndSourceFile();
Sean Callananfb3058e2011-05-12 23:54:16 +0000356
Sean Callanan65dafa82010-08-27 01:01:44 +0000357 TextDiagnosticBuffer::const_iterator diag_iterator;
358
359 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000360
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000361 for (diag_iterator = diag_buf->warn_begin();
362 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000363 ++diag_iterator)
364 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
365
366 num_errors = 0;
367
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000368 for (diag_iterator = diag_buf->err_begin();
369 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000370 ++diag_iterator)
371 {
372 num_errors++;
373 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
374 }
375
Sean Callanan7617c292010-11-01 20:28:09 +0000376 for (diag_iterator = diag_buf->note_begin();
377 diag_iterator != diag_buf->note_end();
378 ++diag_iterator)
379 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
380
Sean Callananfb3058e2011-05-12 23:54:16 +0000381 if (!num_errors)
382 {
383 if (m_expr.DeclMap() && !m_expr.DeclMap()->ResolveUnknownTypes())
384 {
385 stream.Printf("error: Couldn't infer the type of a variable\n");
386 num_errors++;
387 }
388 }
389
Sean Callanan65dafa82010-08-27 01:01:44 +0000390 return num_errors;
391}
392
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000393static bool FindFunctionInModule (std::string &mangled_name,
394 llvm::Module *module,
395 const char *orig_name)
396{
397 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
398 fi != fe;
399 ++fi)
400 {
401 if (fi->getName().str().find(orig_name) != std::string::npos)
402 {
403 mangled_name = fi->getName().str();
404 return true;
405 }
406 }
407
408 return false;
409}
410
Sean Callanan65dafa82010-08-27 01:01:44 +0000411Error
412ClangExpressionParser::MakeDWARF ()
413{
414 Error err;
415
416 llvm::Module *module = m_code_generator->GetModule();
417
418 if (!module)
419 {
420 err.SetErrorToGenericError();
421 err.SetErrorString("IR doesn't contain a module");
422 return err;
423 }
424
Greg Clayton427f2902010-12-14 02:59:59 +0000425 ClangExpressionVariableList *local_variables = m_expr.LocalVariables();
Sean Callanan65dafa82010-08-27 01:01:44 +0000426 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
427
428 if (!local_variables)
429 {
430 err.SetErrorToGenericError();
431 err.SetErrorString("Can't convert an expression without a VariableList to DWARF");
432 return err;
433 }
434
435 if (!decl_map)
436 {
437 err.SetErrorToGenericError();
438 err.SetErrorString("Can't convert an expression without a DeclMap to DWARF");
439 return err;
440 }
441
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000442 std::string function_name;
443
444 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
445 {
446 err.SetErrorToGenericError();
447 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
448 return err;
449 }
450
451 IRToDWARF ir_to_dwarf(*local_variables, decl_map, m_expr.DwarfOpcodeStream(), function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000452
453 if (!ir_to_dwarf.runOnModule(*module))
454 {
455 err.SetErrorToGenericError();
456 err.SetErrorString("Couldn't convert the expression to DWARF");
457 return err;
458 }
459
460 err.Clear();
461 return err;
462}
463
464Error
Greg Claytond0882d02011-01-19 23:00:49 +0000465ClangExpressionParser::MakeJIT (lldb::addr_t &func_allocation_addr,
466 lldb::addr_t &func_addr,
Sean Callanan830a9032010-08-27 23:31:21 +0000467 lldb::addr_t &func_end,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000468 ExecutionContext &exe_ctx,
Sean Callanan696cf5f2011-05-07 01:06:41 +0000469 lldb::ClangExpressionVariableSP &const_result,
470 bool jit_only_if_needed)
Sean Callanan65dafa82010-08-27 01:01:44 +0000471{
Greg Claytond0882d02011-01-19 23:00:49 +0000472 func_allocation_addr = LLDB_INVALID_ADDRESS;
473 func_addr = LLDB_INVALID_ADDRESS;
474 func_end = LLDB_INVALID_ADDRESS;
Greg Claytone005f2c2010-11-06 01:53:30 +0000475 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000476
Sean Callanan65dafa82010-08-27 01:01:44 +0000477 Error err;
478
479 llvm::Module *module = m_code_generator->ReleaseModule();
480
481 if (!module)
482 {
483 err.SetErrorToGenericError();
484 err.SetErrorString("IR doesn't contain a module");
485 return err;
486 }
487
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000488 // Find the actual name of the function (it's often mangled somehow)
489
490 std::string function_name;
491
492 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
493 {
494 err.SetErrorToGenericError();
495 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
496 return err;
497 }
498 else
499 {
500 if(log)
501 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
502 }
503
Sean Callanan65dafa82010-08-27 01:01:44 +0000504 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
505
506 if (decl_map)
507 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000508 Stream *error_stream = NULL;
509
510 if (exe_ctx.target)
511 error_stream = &exe_ctx.target->GetDebugger().GetErrorStream();
512
Sean Callanane8a59a82010-09-13 21:34:21 +0000513 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000514 m_expr.NeedsVariableResolution(),
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000515 const_result,
Sean Callanan97c924e2011-01-27 01:07:04 +0000516 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000517 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000518
519 if (!ir_for_target.runOnModule(*module))
520 {
521 err.SetErrorToGenericError();
522 err.SetErrorString("Couldn't convert the expression to DWARF");
523 return err;
524 }
Sean Callananf18d91c2010-09-01 00:58:00 +0000525
Sean Callanan696cf5f2011-05-07 01:06:41 +0000526 if (jit_only_if_needed && const_result.get())
527 {
528 err.Clear();
529 return err;
530 }
531
Jim Inghamd1686902010-10-14 23:45:03 +0000532 if (m_expr.NeedsValidation() && exe_ctx.process->GetDynamicCheckers())
Sean Callananf18d91c2010-09-01 00:58:00 +0000533 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000534 IRDynamicChecks ir_dynamic_checks(*exe_ctx.process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000535
536 if (!ir_dynamic_checks.runOnModule(*module))
537 {
538 err.SetErrorToGenericError();
539 err.SetErrorString("Couldn't add dynamic checks to the expression");
540 return err;
541 }
542 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000543 }
544
Greg Claytond0882d02011-01-19 23:00:49 +0000545 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
546 // below so we don't need to free it.
547 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000548
549 std::string error_string;
Sean Callanan9ac3a962010-11-02 23:20:00 +0000550
Sean Callananc2c6f772010-10-26 00:31:56 +0000551 llvm::TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
552
Sean Callanan65dafa82010-08-27 01:01:44 +0000553 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
554 &error_string,
Greg Claytond0882d02011-01-19 23:00:49 +0000555 jit_memory_manager,
Sean Callananc2c6f772010-10-26 00:31:56 +0000556 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000557 true,
558 CodeModel::Small));
Sean Callanan9ac3a962010-11-02 23:20:00 +0000559
Sean Callanan65dafa82010-08-27 01:01:44 +0000560 if (!m_execution_engine.get())
561 {
562 err.SetErrorToGenericError();
563 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
564 return err;
565 }
566
567 m_execution_engine->DisableLazyCompilation();
568
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000569 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000570
571 // We don't actually need the function pointer here, this just forces it to get resolved.
572
573 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
574
575 // Errors usually cause failures in the JIT, but if we're lucky we get here.
576
577 if (!fun_ptr)
578 {
579 err.SetErrorToGenericError();
580 err.SetErrorString("Couldn't JIT the function");
581 return err;
582 }
583
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000584 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000585
586 ExecutionContext &exc_context(exe_ctx);
587
588 if (exc_context.process == NULL)
589 {
590 err.SetErrorToGenericError();
591 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
592 return err;
593 }
594
595 // Look over the regions allocated for the function compiled. The JIT
596 // tries to allocate the functions & stubs close together, so we should try to
597 // write them that way too...
598 // For now I only write functions with no stubs, globals, exception tables,
599 // etc. So I only need to write the functions.
600
601 size_t alloc_size = 0;
602
Greg Claytond0882d02011-01-19 23:00:49 +0000603 std::map<uint8_t *, uint8_t *>::iterator fun_pos = jit_memory_manager->m_functions.begin();
604 std::map<uint8_t *, uint8_t *>::iterator fun_end = jit_memory_manager->m_functions.end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000605
606 for (; fun_pos != fun_end; ++fun_pos)
607 alloc_size += (*fun_pos).second - (*fun_pos).first;
608
609 Error alloc_error;
Greg Claytond0882d02011-01-19 23:00:49 +0000610 func_allocation_addr = exc_context.process->AllocateMemory (alloc_size,
611 lldb::ePermissionsReadable|lldb::ePermissionsExecutable,
612 alloc_error);
Sean Callanan65dafa82010-08-27 01:01:44 +0000613
Greg Claytond0882d02011-01-19 23:00:49 +0000614 if (func_allocation_addr == LLDB_INVALID_ADDRESS)
Sean Callanan65dafa82010-08-27 01:01:44 +0000615 {
616 err.SetErrorToGenericError();
617 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
618 return err;
619 }
620
Greg Claytond0882d02011-01-19 23:00:49 +0000621 lldb::addr_t cursor = func_allocation_addr;
Sean Callanan65dafa82010-08-27 01:01:44 +0000622
Greg Claytond0882d02011-01-19 23:00:49 +0000623 for (fun_pos = jit_memory_manager->m_functions.begin(); fun_pos != fun_end; fun_pos++)
Sean Callanan65dafa82010-08-27 01:01:44 +0000624 {
625 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
626 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
627 size_t size = lend - lstart;
628
629 Error write_error;
630
631 if (exc_context.process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
632 {
633 err.SetErrorToGenericError();
634 err.SetErrorStringWithFormat("Couldn't copy JITted function into the target: %s", write_error.AsCString("unknown error"));
635 return err;
636 }
637
Greg Claytond0882d02011-01-19 23:00:49 +0000638 jit_memory_manager->AddToLocalToRemoteMap (lstart, size, cursor);
Sean Callanan65dafa82010-08-27 01:01:44 +0000639 cursor += size;
640 }
641
642 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
643
644 for (pos = m_jitted_functions.begin(); pos != end; pos++)
645 {
Greg Claytond0882d02011-01-19 23:00:49 +0000646 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000647
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000648 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000649 {
Greg Claytond0882d02011-01-19 23:00:49 +0000650 func_end = jit_memory_manager->GetRemoteRangeForLocal ((*pos).m_local_addr).second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000651 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000652 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000653 }
654
Sean Callanan6dff8272010-11-08 03:49:50 +0000655 if (log)
656 {
657 log->Printf("Code can be run in the target.");
658
659 StreamString disassembly_stream;
660
Greg Claytond0882d02011-01-19 23:00:49 +0000661 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000662
663 if (!err.Success())
664 {
665 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
666 }
667 else
668 {
669 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
670 }
671 }
672
Sean Callanan65dafa82010-08-27 01:01:44 +0000673 err.Clear();
674 return err;
675}
676
677Error
Greg Claytond0882d02011-01-19 23:00:49 +0000678ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000679{
Greg Claytone005f2c2010-11-06 01:53:30 +0000680 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000681
682 const char *name = m_expr.FunctionName();
683
684 Error ret;
685
686 ret.Clear();
687
688 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
689 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
690
691 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
692
693 for (pos = m_jitted_functions.begin(); pos < end; pos++)
694 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000695 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000696 {
697 func_local_addr = pos->m_local_addr;
698 func_remote_addr = pos->m_remote_addr;
699 }
700 }
701
702 if (func_local_addr == LLDB_INVALID_ADDRESS)
703 {
704 ret.SetErrorToGenericError();
705 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
706 return ret;
707 }
708
709 if(log)
710 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
711
712 std::pair <lldb::addr_t, lldb::addr_t> func_range;
713
Greg Claytond0882d02011-01-19 23:00:49 +0000714 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000715
716 if (func_range.first == 0 && func_range.second == 0)
717 {
718 ret.SetErrorToGenericError();
719 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
720 return ret;
721 }
722
723 if(log)
724 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
725
726 if (!exe_ctx.target)
727 {
728 ret.SetErrorToGenericError();
729 ret.SetErrorString("Couldn't find the target");
730 }
731
732 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
733
734 Error err;
735 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
736
737 if (!err.Success())
738 {
739 ret.SetErrorToGenericError();
740 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
741 return ret;
742 }
743
744 ArchSpec arch(exe_ctx.target->GetArchitecture());
745
Greg Clayton149731c2011-03-25 18:03:16 +0000746 Disassembler *disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000747
748 if (disassembler == NULL)
749 {
750 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000751 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000752 return ret;
753 }
754
755 if (!exe_ctx.process)
756 {
757 ret.SetErrorToGenericError();
758 ret.SetErrorString("Couldn't find the process");
759 return ret;
760 }
761
762 DataExtractor extractor(buffer_sp,
763 exe_ctx.process->GetByteOrder(),
764 exe_ctx.target->GetArchitecture().GetAddressByteSize());
765
Greg Claytone005f2c2010-11-06 01:53:30 +0000766 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000767 {
768 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000769 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000770 0,
771 extractor.GetByteSize(),
772 func_remote_addr,
773 16,
774 DataExtractor::TypeUInt8);
775 }
776
Jim Inghamaa3e3e12011-03-22 01:48:42 +0000777 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000778
Greg Clayton5c4c7462010-10-06 03:09:58 +0000779 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000780 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000781 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
782 instruction_index < num_instructions;
783 ++instruction_index)
784 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000785 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000786 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000787 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000788 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000789 true,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000790 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000791 true);
792 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000793 }
794
795 return ret;
796}