blob: c3bdd7aecf5c32c9fd945dc8812b7bee9adbec98 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ClangExpression.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// C Includes
11#include <stdio.h>
12#if HAVE_SYS_TYPES_H
13# include <sys/types.h>
14#endif
15
16// C++ Includes
17#include <cstdlib>
18#include <string>
19#include <map>
20
21// Other libraries and framework includes
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/ExternalASTSource.h"
24#include "clang/Basic/FileManager.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Basic/Version.h"
Greg Claytonc4f51102010-07-02 18:39:06 +000027#include "clang/Checker/FrontendActions.h"
28#include "clang/CodeGen/CodeGenAction.h"
Chris Lattner24943d22010-06-08 16:52:24 +000029#include "clang/CodeGen/ModuleBuilder.h"
30#include "clang/Driver/CC1Options.h"
31#include "clang/Driver/OptTable.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "clang/Frontend/CompilerInstance.h"
33#include "clang/Frontend/CompilerInvocation.h"
34#include "clang/Frontend/FrontendActions.h"
35#include "clang/Frontend/FrontendDiagnostic.h"
36#include "clang/Frontend/FrontendPluginRegistry.h"
37#include "clang/Frontend/TextDiagnosticBuffer.h"
38#include "clang/Frontend/TextDiagnosticPrinter.h"
39#include "clang/Frontend/VerifyDiagnosticsClient.h"
40#include "clang/Lex/Preprocessor.h"
Greg Claytonc4f51102010-07-02 18:39:06 +000041#include "clang/Rewrite/FrontendActions.h"
Chris Lattner24943d22010-06-08 16:52:24 +000042#include "clang/Sema/ParseAST.h"
Sean Callanan8c6934d2010-07-01 20:08:22 +000043#include "clang/Sema/SemaConsumer.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "llvm/ExecutionEngine/ExecutionEngine.h"
45#include "llvm/ExecutionEngine/JIT.h"
46#include "llvm/Module.h"
47#include "llvm/ADT/StringRef.h"
48#include "llvm/LLVMContext.h"
49#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/System/DynamicLibrary.h"
51#include "llvm/System/Host.h"
52#include "llvm/System/Signals.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000053#include "llvm/Target/TargetRegistry.h"
Chris Lattner24943d22010-06-08 16:52:24 +000054#include "llvm/Target/TargetSelect.h"
55
56// Project includes
Sean Callanan848960c2010-06-23 23:18:04 +000057#include "lldb/Core/Log.h"
Greg Clayton1674b122010-07-21 22:12:05 +000058#include "lldb/Core/ClangForward.h"
Sean Callanan8541f2f2010-07-23 02:19:15 +000059#include "lldb/Core/DataBufferHeap.h"
60#include "lldb/Core/Disassembler.h"
Chris Lattner24943d22010-06-08 16:52:24 +000061#include "lldb/Expression/ClangExpression.h"
62#include "lldb/Expression/ClangASTSource.h"
Sean Callanan8c6934d2010-07-01 20:08:22 +000063#include "lldb/Expression/ClangResultSynthesizer.h"
Chris Lattner24943d22010-06-08 16:52:24 +000064#include "lldb/Expression/ClangStmtVisitor.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000065#include "lldb/Expression/IRForTarget.h"
Sean Callanandcb658b2010-07-02 21:09:36 +000066#include "lldb/Expression/IRToDWARF.h"
Chris Lattner24943d22010-06-08 16:52:24 +000067#include "lldb/Symbol/ClangASTContext.h"
68#include "lldb/Expression/RecordingMemoryManager.h"
69#include "lldb/Target/ExecutionContext.h"
70#include "lldb/Target/Process.h"
Sean Callanan8541f2f2010-07-23 02:19:15 +000071#include "lldb/Target/Target.h"
Chris Lattner24943d22010-06-08 16:52:24 +000072
Chris Lattner24943d22010-06-08 16:52:24 +000073#include "lldb/Core/StreamString.h"
74#include "lldb/Host/Mutex.h"
Chris Lattner24943d22010-06-08 16:52:24 +000075
76
77using namespace lldb_private;
78using namespace clang;
79using namespace llvm;
80
Chris Lattner24943d22010-06-08 16:52:24 +000081
82//===----------------------------------------------------------------------===//
83// Utility Methods
84//===----------------------------------------------------------------------===//
85
86std::string GetBuiltinIncludePath(const char *Argv0) {
87 llvm::sys::Path P =
88 llvm::sys::Path::GetMainExecutable(Argv0,
89 (void*)(intptr_t) GetBuiltinIncludePath);
90
91 if (!P.isEmpty()) {
92 P.eraseComponent(); // Remove /clang from foo/bin/clang
93 P.eraseComponent(); // Remove /bin from foo/bin
94
95 // Get foo/lib/clang/<version>/include
96 P.appendComponent("lib");
97 P.appendComponent("clang");
98 P.appendComponent(CLANG_VERSION_STRING);
99 P.appendComponent("include");
100 }
101
102 return P.str();
103}
104
105
106//===----------------------------------------------------------------------===//
107// Main driver
108//===----------------------------------------------------------------------===//
109
110void LLVMErrorHandler(void *UserData, const std::string &Message) {
111 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
112
113 Diags.Report(diag::err_fe_error_backend) << Message;
114
115 // We cannot recover from llvm errors.
116 exit(1);
117}
118
119static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
120 using namespace clang::frontend;
121
122 switch (CI.getFrontendOpts().ProgramAction) {
123 default:
124 llvm_unreachable("Invalid program action!");
125
126 case ASTDump: return new ASTDumpAction();
127 case ASTPrint: return new ASTPrintAction();
128 case ASTPrintXML: return new ASTPrintXMLAction();
129 case ASTView: return new ASTViewAction();
130 case DumpRawTokens: return new DumpRawTokensAction();
131 case DumpTokens: return new DumpTokensAction();
132 case EmitAssembly: return new EmitAssemblyAction();
133 case EmitBC: return new EmitBCAction();
134 case EmitHTML: return new HTMLPrintAction();
135 case EmitLLVM: return new EmitLLVMAction();
136 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
137 case EmitObj: return new EmitObjAction();
138 case FixIt: return new FixItAction();
139 case GeneratePCH: return new GeneratePCHAction();
140 case GeneratePTH: return new GeneratePTHAction();
141 case InheritanceView: return new InheritanceViewAction();
142 case InitOnly: return new InitOnlyAction();
143 case ParseNoop: return new ParseOnlyAction();
144 case ParsePrintCallbacks: return new PrintParseAction();
145 case ParseSyntaxOnly: return new SyntaxOnlyAction();
146
147 case PluginAction: {
148 if (CI.getFrontendOpts().ActionName == "help") {
149 llvm::errs() << "clang -cc1 plugins:\n";
150 for (FrontendPluginRegistry::iterator it =
151 FrontendPluginRegistry::begin(),
152 ie = FrontendPluginRegistry::end();
153 it != ie; ++it)
154 llvm::errs() << " " << it->getName() << " - " << it->getDesc() << "\n";
155 return 0;
156 }
157
158 for (FrontendPluginRegistry::iterator it =
159 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
160 it != ie; ++it) {
161 if (it->getName() == CI.getFrontendOpts().ActionName)
162 return it->instantiate();
163 }
164
165 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
166 << CI.getFrontendOpts().ActionName;
167 return 0;
168 }
169
170 case PrintDeclContext: return new DeclContextPrintAction();
171 case PrintPreprocessedInput: return new PrintPreprocessedAction();
172 case RewriteMacros: return new RewriteMacrosAction();
173 case RewriteObjC: return new RewriteObjCAction();
174 case RewriteTest: return new RewriteTestAction();
175 case RunAnalysis: return new AnalysisAction();
176 case RunPreprocessorOnly: return new PreprocessOnlyAction();
177 }
178}
179
180//----------------------------------------------------------------------
181// ClangExpression constructor
182//----------------------------------------------------------------------
183ClangExpression::ClangExpression(const char *target_triple,
184 ClangExpressionDeclMap *decl_map) :
185 m_target_triple (),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000186 m_decl_map (decl_map),
187 m_clang_ap (),
Chris Lattner24943d22010-06-08 16:52:24 +0000188 m_code_generator_ptr (NULL),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000189 m_jit_mm_ptr (NULL),
190 m_execution_engine (),
191 m_jitted_functions ()
Chris Lattner24943d22010-06-08 16:52:24 +0000192{
193 if (target_triple && target_triple[0])
194 m_target_triple = target_triple;
195 else
196 m_target_triple = llvm::sys::getHostTriple();
197}
198
199
200//----------------------------------------------------------------------
201// Destructor
202//----------------------------------------------------------------------
203ClangExpression::~ClangExpression()
204{
205 if (m_code_generator_ptr && !m_execution_engine.get())
206 delete m_code_generator_ptr;
207}
208
209bool
210ClangExpression::CreateCompilerInstance (bool &IsAST)
211{
212 // Initialize targets first, so that --version shows registered targets.
213 static struct InitializeLLVM {
214 InitializeLLVM() {
215 llvm::InitializeAllTargets();
216 llvm::InitializeAllAsmPrinters();
217 }
218 } InitializeLLVM;
219
220 // 1. Create a new compiler instance.
221 m_clang_ap.reset(new CompilerInstance());
222 m_clang_ap->setLLVMContext(new LLVMContext());
223
224 // 2. Set options.
225
226 // Parse expressions as Objective C++ regardless of context.
227 // Our hook into Clang's lookup mechanism only works in C++.
228 m_clang_ap->getLangOpts().CPlusPlus = true;
229 m_clang_ap->getLangOpts().ObjC1 = true;
Sean Callanan051052f2010-07-02 22:22:28 +0000230 m_clang_ap->getLangOpts().ThreadsafeStatics = false;
Sean Callanan8bce6652010-07-13 21:41:46 +0000231
232 // Set CodeGen options
233 m_clang_ap->getCodeGenOpts().EmitDeclMetadata = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000234
235 // Disable some warnings.
236 m_clang_ap->getDiagnosticOpts().Warnings.push_back("no-unused-value");
237
238 // Set the target triple.
239 m_clang_ap->getTargetOpts().Triple = m_target_triple;
240
241 // 3. Set up various important bits of infrastructure.
242
243 m_clang_ap->createDiagnostics(0, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000244
245 // Create the target instance.
246 m_clang_ap->setTarget(TargetInfo::CreateTargetInfo(m_clang_ap->getDiagnostics(),
247 m_clang_ap->getTargetOpts()));
248 if (!m_clang_ap->hasTarget())
249 {
250 m_clang_ap.reset();
251 return false;
252 }
253
254 // Inform the target of the language options
255 //
256 // FIXME: We shouldn't need to do this, the target should be immutable once
257 // created. This complexity should be lifted elsewhere.
258 m_clang_ap->getTarget().setForcedLangOptions(m_clang_ap->getLangOpts());
259
260 return m_clang_ap.get();
261}
262
263Mutex &
264ClangExpression::GetClangMutex ()
265{
266 static Mutex g_clang_mutex(Mutex::eMutexTypeRecursive); // Control access to the clang compiler
267 return g_clang_mutex;
268}
269
270
271clang::ASTContext *
272ClangExpression::GetASTContext ()
273{
274 CompilerInstance *compiler_instance = GetCompilerInstance();
275 if (compiler_instance)
276 return &compiler_instance->getASTContext();
277 return NULL;
278}
279
280unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000281ClangExpression::ParseExpression (const char *expr_text,
282 Stream &stream,
283 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000284{
285 // HACK: for now we have to make a function body around our expression
286 // since there is no way to parse a single expression line in LLVM/Clang.
Sean Callanan8bce6652010-07-13 21:41:46 +0000287 std::string func_expr("extern \"C\" void ___clang_expr(void *___clang_arg)\n{\n\t");
Chris Lattner24943d22010-06-08 16:52:24 +0000288 func_expr.append(expr_text);
289 func_expr.append(";\n}");
Sean Callanan8c6934d2010-07-01 20:08:22 +0000290 return ParseBareExpression (func_expr, stream, add_result_var);
Chris Lattner24943d22010-06-08 16:52:24 +0000291
292}
293
294unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000295ClangExpression::ParseBareExpression (llvm::StringRef expr_text,
296 Stream &stream,
297 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000298{
299 Mutex::Locker locker(GetClangMutex ());
300
301 TextDiagnosticBuffer text_diagnostic_buffer;
302
303 bool IsAST = false;
304 if (!CreateCompilerInstance (IsAST))
305 {
306 stream.Printf("error: couldn't create compiler instance\n");
307 return 1;
308 }
309
310 // This code is matched below by a setClient to NULL.
311 // We cannot return out of this code without doing that.
312 m_clang_ap->getDiagnostics().setClient(&text_diagnostic_buffer);
313 text_diagnostic_buffer.FlushDiagnostics (m_clang_ap->getDiagnostics());
314
315 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
316
317 if (!m_clang_ap->hasSourceManager())
318 m_clang_ap->createSourceManager();
319
320 m_clang_ap->createFileManager();
321 m_clang_ap->createPreprocessor();
322
323 // Build the ASTContext. Most of this we inherit from the
324 // CompilerInstance, but we also want to give the context
325 // an ExternalASTSource.
326 SelectorTable selector_table;
327 std::auto_ptr<Builtin::Context> builtin_ap(new Builtin::Context(m_clang_ap->getTarget()));
328 ASTContext *Context = new ASTContext(m_clang_ap->getLangOpts(),
329 m_clang_ap->getSourceManager(),
330 m_clang_ap->getTarget(),
331 m_clang_ap->getPreprocessor().getIdentifierTable(),
332 selector_table,
333 *builtin_ap.get());
334
335 llvm::OwningPtr<ExternalASTSource> ASTSource(new ClangASTSource(*Context, *m_decl_map));
336
337 if (m_decl_map)
338 {
339 Context->setExternalSource(ASTSource);
340 }
341
342 m_clang_ap->setASTContext(Context);
343
344 FileID memory_buffer_file_id = m_clang_ap->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
345 std::string module_name("test_func");
346 text_diagnostic_buffer.BeginSourceFile(m_clang_ap->getLangOpts(), &m_clang_ap->getPreprocessor());
347
348 if (m_code_generator_ptr)
349 delete m_code_generator_ptr;
350
351 m_code_generator_ptr = CreateLLVMCodeGen(m_clang_ap->getDiagnostics(),
352 module_name,
353 m_clang_ap->getCodeGenOpts(),
354 m_clang_ap->getLLVMContext());
355
356
357 // - CodeGeneration ASTConsumer (include/clang/ModuleBuilder.h), which will be passed in when you call...
358 // - Call clang::ParseAST (in lib/Sema/ParseAST.cpp) to parse the buffer. The CodeGenerator will generate code for __dbg_expr.
359 // - Once ParseAST completes, you can grab the llvm::Module from the CodeGenerator, which will have an llvm::Function you can hand off to the JIT.
Sean Callanan8c6934d2010-07-01 20:08:22 +0000360
361 if (add_result_var)
362 {
363 ClangResultSynthesizer result_synthesizer(m_code_generator_ptr);
364 ParseAST(m_clang_ap->getPreprocessor(), &result_synthesizer, m_clang_ap->getASTContext());
365 }
366 else
367 {
368 ParseAST(m_clang_ap->getPreprocessor(), m_code_generator_ptr, m_clang_ap->getASTContext());
369 }
370
Sean Callanan848960c2010-06-23 23:18:04 +0000371
Chris Lattner24943d22010-06-08 16:52:24 +0000372 text_diagnostic_buffer.EndSourceFile();
373
374 //compiler_instance->getASTContext().getTranslationUnitDecl()->dump();
375
376 //if (compiler_instance->getFrontendOpts().ShowStats) {
377 // compiler_instance->getFileManager().PrintStats();
378 // fprintf(stderr, "\n");
379 //}
380
381 // This code resolves the setClient above.
382 m_clang_ap->getDiagnostics().setClient(0);
383
384 TextDiagnosticBuffer::const_iterator diag_iterator;
385
386 int num_errors = 0;
387
388#ifdef COUNT_WARNINGS_AND_ERRORS
389 int num_warnings = 0;
390
391 for (diag_iterator = text_diagnostic_buffer.warn_begin();
392 diag_iterator != text_diagnostic_buffer.warn_end();
393 ++diag_iterator)
394 num_warnings++;
395
396 for (diag_iterator = text_diagnostic_buffer.err_begin();
397 diag_iterator != text_diagnostic_buffer.err_end();
398 ++diag_iterator)
399 num_errors++;
400
401 if (num_warnings || num_errors)
402 {
403 if (num_warnings)
404 stream.Printf("%u warning%s%s", num_warnings, (num_warnings == 1 ? "" : "s"), (num_errors ? " and " : ""));
405 if (num_errors)
406 stream.Printf("%u error%s", num_errors, (num_errors == 1 ? "" : "s"));
407 stream.Printf("\n");
408 }
409#endif
410
411 for (diag_iterator = text_diagnostic_buffer.warn_begin();
412 diag_iterator != text_diagnostic_buffer.warn_end();
413 ++diag_iterator)
414 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
415
416 num_errors = 0;
417
418 for (diag_iterator = text_diagnostic_buffer.err_begin();
419 diag_iterator != text_diagnostic_buffer.err_end();
420 ++diag_iterator)
421 {
422 num_errors++;
423 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
424 }
425
426 return num_errors;
427}
428
Chris Lattner24943d22010-06-08 16:52:24 +0000429static FrontendAction *
430CreateFrontendAction(CompilerInstance &CI)
431{
432 // Create the underlying action.
433 FrontendAction *Act = CreateFrontendBaseAction(CI);
434 if (!Act)
435 return 0;
436
437 // If there are any AST files to merge, create a frontend action
438 // adaptor to perform the merge.
439 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
440 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
441 CI.getFrontendOpts().ASTMergeFiles.size());
442
443 return Act;
444}
445
446
447unsigned
448ClangExpression::ConvertExpressionToDWARF (ClangExpressionVariableList& expr_local_variable_list,
449 StreamString &dwarf_opcode_strm)
450{
451 CompilerInstance *compiler_instance = GetCompilerInstance();
452
453 DeclarationName hack_func_name(&compiler_instance->getASTContext().Idents.get("___clang_expr"));
454 DeclContext::lookup_result result = compiler_instance->getASTContext().getTranslationUnitDecl()->lookup(hack_func_name);
455
456 if (result.first != result.second)
457 {
458 Decl *decl = *result.first;
459 Stmt *decl_stmt = decl->getBody();
460 if (decl_stmt)
461 {
462 ClangStmtVisitor visitor(compiler_instance->getASTContext(), expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
463
464 visitor.Visit (decl_stmt);
465 }
466 }
467 return 0;
468}
469
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000470bool
Sean Callanandcb658b2010-07-02 21:09:36 +0000471ClangExpression::ConvertIRToDWARF (ClangExpressionVariableList &expr_local_variable_list,
Sean Callanan848960c2010-06-23 23:18:04 +0000472 StreamString &dwarf_opcode_strm)
473{
474 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
475
476 llvm::Module *module = m_code_generator_ptr->GetModule();
477
478 if (!module)
479 {
480 if (log)
481 log->Printf("IR doesn't contain a module");
482
483 return 1;
484 }
485
Sean Callanandcb658b2010-07-02 21:09:36 +0000486 IRToDWARF ir_to_dwarf("IR to DWARF", expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
Sean Callanan8c6934d2010-07-01 20:08:22 +0000487
Sean Callanandcb658b2010-07-02 21:09:36 +0000488 return ir_to_dwarf.runOnModule(*module);
Sean Callanan848960c2010-06-23 23:18:04 +0000489}
490
Chris Lattner24943d22010-06-08 16:52:24 +0000491bool
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000492ClangExpression::PrepareIRForTarget (ClangExpressionVariableList &expr_local_variable_list)
493{
494 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
495
496 llvm::Module *module = m_code_generator_ptr->GetModule();
497
498 if (!module)
499 {
500 if (log)
501 log->Printf("IR doesn't contain a module");
502
503 return 1;
504 }
505
Sean Callanan8bce6652010-07-13 21:41:46 +0000506 llvm::Triple target_triple = m_clang_ap->getTarget().getTriple();
507
508 std::string err;
509
510 const llvm::Target *target = llvm::TargetRegistry::lookupTarget(m_target_triple, err);
511
512 if (!target)
513 {
514 if (log)
515 log->Printf("Couldn't find a target for %s", m_target_triple.c_str());
516
517 return 1;
518 }
519
520 std::auto_ptr<llvm::TargetMachine> target_machine(target->createTargetMachine(m_target_triple, ""));
521
522 IRForTarget ir_for_target("IR for target", m_decl_map, target_machine->getTargetData());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000523
524 return ir_for_target.runOnModule(*module);
525}
526
527bool
Chris Lattner24943d22010-06-08 16:52:24 +0000528ClangExpression::JITFunction (const ExecutionContext &exc_context, const char *name)
529{
530
531 llvm::Module *module = m_code_generator_ptr->GetModule();
532
533 if (module)
534 {
535 std::string error;
536
537 if (m_jit_mm_ptr == NULL)
538 m_jit_mm_ptr = new RecordingMemoryManager();
539
540 //llvm::InitializeNativeTarget();
541 if (m_execution_engine.get() == 0)
542 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module, &error, m_jit_mm_ptr));
543 m_execution_engine->DisableLazyCompilation();
544 llvm::Function *function = module->getFunction (llvm::StringRef (name));
545
546 // We don't actually need the function pointer here, this just forces it to get resolved.
547 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
548 // Note, you probably won't get here on error, since the LLVM JIT tends to just
549 // exit on error at present... So be careful.
550 if (fun_ptr == 0)
551 return false;
552 m_jitted_functions.push_back(ClangExpression::JittedFunction(name, (lldb::addr_t) fun_ptr));
553
554 }
555 return true;
556}
557
558bool
559ClangExpression::WriteJITCode (const ExecutionContext &exc_context)
560{
561 if (m_jit_mm_ptr == NULL)
562 return false;
563
564 if (exc_context.process == NULL)
565 return false;
566
567 // Look over the regions allocated for the function compiled. The JIT
568 // tries to allocate the functions & stubs close together, so we should try to
569 // write them that way too...
570 // For now I only write functions with no stubs, globals, exception tables,
571 // etc. So I only need to write the functions.
572
Greg Claytonbef15832010-07-14 00:18:15 +0000573 size_t alloc_size = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000574 std::map<uint8_t *, uint8_t *>::iterator fun_pos, fun_end = m_jit_mm_ptr->m_functions.end();
575 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
576 {
Greg Claytonbef15832010-07-14 00:18:15 +0000577 alloc_size += (*fun_pos).second - (*fun_pos).first;
Chris Lattner24943d22010-06-08 16:52:24 +0000578 }
579
580 Error error;
Greg Claytonbef15832010-07-14 00:18:15 +0000581 lldb::addr_t target_addr = exc_context.process->AllocateMemory (alloc_size, lldb::ePermissionsReadable|lldb::ePermissionsExecutable, error);
Chris Lattner24943d22010-06-08 16:52:24 +0000582
583 if (target_addr == LLDB_INVALID_ADDRESS)
584 return false;
585
586 lldb::addr_t cursor = target_addr;
587 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
588 {
589 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
590 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
591 size_t size = lend - lstart;
592 exc_context.process->WriteMemory(cursor, (void *) lstart, size, error);
593 m_jit_mm_ptr->AddToLocalToRemoteMap (lstart, size, cursor);
594 cursor += size;
595 }
596
597 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
598
599 for (pos = m_jitted_functions.begin(); pos != end; pos++)
600 {
601 (*pos).m_remote_addr = m_jit_mm_ptr->GetRemoteAddressForLocal ((*pos).m_local_addr);
602 }
603 return true;
604}
605
606lldb::addr_t
607ClangExpression::GetFunctionAddress (const char *name)
608{
609 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
610
611 for (pos = m_jitted_functions.begin(); pos < end; pos++)
612 {
613 if (strcmp ((*pos).m_name.c_str(), name) == 0)
614 return (*pos).m_remote_addr;
615 }
616 return LLDB_INVALID_ADDRESS;
617}
618
Sean Callanan8541f2f2010-07-23 02:19:15 +0000619Error
620ClangExpression::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, const char *name)
621{
622 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
623
624 Error ret;
625
626 ret.Clear();
627
628 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
629 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
630
631 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
632
633 for (pos = m_jitted_functions.begin(); pos < end; pos++)
634 {
635 if (strcmp(pos->m_name.c_str(), name) == 0)
636 {
637 func_local_addr = pos->m_local_addr;
638 func_remote_addr = pos->m_remote_addr;
639 }
640 }
641
642 if (func_local_addr == LLDB_INVALID_ADDRESS)
643 {
644 ret.SetErrorToGenericError();
645 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
646 return ret;
647 }
648
649 if(log)
650 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
651
652 std::pair <lldb::addr_t, lldb::addr_t> func_range;
653
654 func_range = m_jit_mm_ptr->GetRemoteRangeForLocal(func_local_addr);
655
656 if (func_range.first == 0 && func_range.second == 0)
657 {
658 ret.SetErrorToGenericError();
659 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
660 return ret;
661 }
662
663 if(log)
664 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
665
666 if (!exe_ctx.target)
667 {
668 ret.SetErrorToGenericError();
669 ret.SetErrorString("Couldn't find the target");
670 }
671
Sean Callanan32824aa2010-07-23 22:19:18 +0000672 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
Sean Callanan8541f2f2010-07-23 02:19:15 +0000673
674 Error err;
Sean Callanan32824aa2010-07-23 22:19:18 +0000675 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
Sean Callanan8541f2f2010-07-23 02:19:15 +0000676
677 if (!err.Success())
678 {
679 ret.SetErrorToGenericError();
680 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
681 return ret;
682 }
683
684 ArchSpec arch(exe_ctx.target->GetArchitecture());
685
686 Disassembler *disassembler = Disassembler::FindPlugin(arch);
687
688 if (disassembler == NULL)
689 {
690 ret.SetErrorToGenericError();
691 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.AsCString());
692 return ret;
693 }
694
695 if (!exe_ctx.process)
696 {
697 ret.SetErrorToGenericError();
698 ret.SetErrorString("Couldn't find the process");
699 return ret;
700 }
701
702 DataExtractor extractor(buffer_sp,
703 exe_ctx.process->GetByteOrder(),
Sean Callanan32824aa2010-07-23 22:19:18 +0000704 exe_ctx.target->GetArchitecture().GetAddressByteSize());
Sean Callanan8541f2f2010-07-23 02:19:15 +0000705
706 if(log)
707 {
708 log->Printf("Function data has contents:");
709 extractor.PutToLog (log,
710 0,
711 extractor.GetByteSize(),
Sean Callanan32824aa2010-07-23 22:19:18 +0000712 func_remote_addr,
Sean Callanan8541f2f2010-07-23 02:19:15 +0000713 16,
714 DataExtractor::TypeUInt8);
715 }
716
717 disassembler->DecodeInstructions(extractor, 0, UINT32_MAX);
718
719 Disassembler::InstructionList &instruction_list = disassembler->GetInstructionList();
720
721 uint32_t bytes_offset = 0;
722
723 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
724 instruction_index < num_instructions;
725 ++instruction_index)
726 {
727 Disassembler::Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index);
Sean Callanan32824aa2010-07-23 22:19:18 +0000728 Address addr(NULL, func_remote_addr + bytes_offset);
Sean Callanan8541f2f2010-07-23 02:19:15 +0000729 instruction->Dump (&stream,
Sean Callanan32824aa2010-07-23 22:19:18 +0000730 &addr,
Sean Callanan8541f2f2010-07-23 02:19:15 +0000731 &extractor,
732 bytes_offset,
733 exe_ctx,
734 true);
735 stream.PutChar('\n');
736 bytes_offset += instruction->GetByteSize();
737 }
738
739 return ret;
740}
741
Chris Lattner24943d22010-06-08 16:52:24 +0000742unsigned
743ClangExpression::Compile()
744{
745 Mutex::Locker locker(GetClangMutex ());
746 bool IsAST = false;
747
748 if (CreateCompilerInstance(IsAST))
749 {
750 // Validate/process some options
751 if (m_clang_ap->getHeaderSearchOpts().Verbose)
752 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
753 << " based upon " << PACKAGE_STRING
754 << " hosted on " << llvm::sys::getHostTriple() << "\n";
755
756 // Enforce certain implications.
757 if (!m_clang_ap->getFrontendOpts().ViewClassInheritance.empty())
758 m_clang_ap->getFrontendOpts().ProgramAction = frontend::InheritanceView;
759// if (!compiler_instance->getFrontendOpts().FixItSuffix.empty())
760// compiler_instance->getFrontendOpts().ProgramAction = frontend::FixIt;
761
762 for (unsigned i = 0, e = m_clang_ap->getFrontendOpts().Inputs.size(); i != e; ++i) {
Chris Lattner24943d22010-06-08 16:52:24 +0000763
764 // If we aren't using an AST file, setup the file and source managers and
765 // the preprocessor.
766 if (!IsAST) {
767 if (!i) {
768 // Create a file manager object to provide access to and cache the
769 // filesystem.
770 m_clang_ap->createFileManager();
771
772 // Create the source manager.
773 m_clang_ap->createSourceManager();
774 } else {
775 // Reset the ID tables if we are reusing the SourceManager.
776 m_clang_ap->getSourceManager().clearIDTables();
777 }
778
779 // Create the preprocessor.
780 m_clang_ap->createPreprocessor();
781 }
782
783 llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(*m_clang_ap.get()));
784 if (!Act)
785 break;
786
Greg Claytone41c4b22010-06-13 17:34:29 +0000787 if (Act->BeginSourceFile(*m_clang_ap,
788 m_clang_ap->getFrontendOpts().Inputs[i].second,
789 m_clang_ap->getFrontendOpts().Inputs[i].first)) {
Chris Lattner24943d22010-06-08 16:52:24 +0000790 Act->Execute();
791 Act->EndSourceFile();
792 }
793 }
794
795 if (m_clang_ap->getDiagnosticOpts().ShowCarets)
796 {
797 unsigned NumWarnings = m_clang_ap->getDiagnostics().getNumWarnings();
798 unsigned NumErrors = m_clang_ap->getDiagnostics().getNumErrors() -
799 m_clang_ap->getDiagnostics().getNumErrorsSuppressed();
800
801 if (NumWarnings || NumErrors)
802 {
803 if (NumWarnings)
804 fprintf (stderr, "%u warning%s%s", NumWarnings, (NumWarnings == 1 ? "" : "s"), (NumErrors ? " and " : ""));
805 if (NumErrors)
806 fprintf (stderr, "%u error%s", NumErrors, (NumErrors == 1 ? "" : "s"));
807 fprintf (stderr, " generated.\n");
808 }
809 }
810
811 if (m_clang_ap->getFrontendOpts().ShowStats) {
812 m_clang_ap->getFileManager().PrintStats();
813 fprintf(stderr, "\n");
814 }
815
816 // Return the appropriate status when verifying diagnostics.
817 //
818 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
819 // this.
820 if (m_clang_ap->getDiagnosticOpts().VerifyDiagnostics)
821 return static_cast<VerifyDiagnosticsClient&>(m_clang_ap->getDiagnosticClient()).HadErrors();
822
823 return m_clang_ap->getDiagnostics().getNumErrors();
824 }
825 return 1;
826}