1 //===-- llvm-rtdyld.cpp - MCJIT Testing Tool ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is a testing tool for use with the MC-JIT LLVM components.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/ExecutionEngine/JITMemoryManager.h"
17 #include "llvm/ExecutionEngine/RuntimeDyld.h"
18 #include "llvm/Object/MachOObject.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "llvm/Support/Memory.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Support/system_error.h"
26 using namespace llvm::object;
28 static cl::opt<std::string>
29 InputFile(cl::Positional, cl::desc("<input file>"), cl::init("-"));
35 static cl::opt<ActionType>
36 Action(cl::desc("Action to perform:"),
38 cl::values(clEnumValN(AC_Execute, "execute",
39 "Load, link, and execute the inputs."),
44 static const char *ProgramName;
46 static void Message(const char *Type, const Twine &Msg) {
47 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
50 static int Error(const Twine &Msg) {
51 Message("error", Msg);
57 static int executeInput() {
58 // Load the input memory buffer.
59 OwningPtr<MemoryBuffer> InputBuffer;
60 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFile, InputBuffer))
61 return Error("unable to read input: '" + ec.message() + "'");
63 // Instantiate a dynamic linker.
64 RuntimeDyld Dyld(JITMemoryManager::CreateDefaultMemManager());
66 // Load the object file into it.
67 if (Dyld.loadObject(InputBuffer.take())) {
68 return Error(Dyld.getErrorString());
71 // Get the address of "_main".
72 void *MainAddress = Dyld.getSymbolAddress("_main");
74 return Error("no definition for '_main'");
76 // Invalidate the instruction cache.
77 sys::MemoryBlock Data = Dyld.getMemoryBlock();
78 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
80 // Make sure the memory is executable.
82 if (!sys::Memory::setExecutable(Data, &ErrorStr))
83 return Error("unable to mark function executable: '" + ErrorStr + "'");
85 // Dispatch to _main().
86 errs() << "loaded '_main' at: " << MainAddress << "\n";
88 int (*Main)(int, const char**) =
89 (int(*)(int,const char**)) uintptr_t(MainAddress);
90 const char **Argv = new const char*[2];
91 Argv[0] = InputFile.c_str();
96 int main(int argc, char **argv) {
97 ProgramName = argv[0];
98 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
100 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
105 return executeInput();