ee398e7b4cfcbea811db3f5f89084cb26bacc590
[oota-llvm.git] / tools / llvm-rtdyld / llvm-rtdyld.cpp
1 //===-- llvm-rtdyld.cpp - MCJIT Testing Tool ------------------------------===//
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 // This is a testing tool for use with the MC-JIT LLVM components.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/ExecutionEngine/RuntimeDyld.h"
17 #include "llvm/Object/MachOObject.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/ManagedStatic.h"
20 #include "llvm/Support/Memory.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Support/system_error.h"
24 using namespace llvm;
25 using namespace llvm::object;
26
27 static cl::opt<std::string>
28 InputFile(cl::Positional, cl::desc("<input file>"), cl::init("-"));
29
30 enum ActionType {
31   AC_Execute
32 };
33
34 static cl::opt<ActionType>
35 Action(cl::desc("Action to perform:"),
36        cl::init(AC_Execute),
37        cl::values(clEnumValN(AC_Execute, "execute",
38                              "Load, link, and execute the inputs."),
39                   clEnumValEnd));
40
41 static cl::opt<std::string>
42 EntryPoint("entry",
43            cl::desc("Function to call as entry point."),
44            cl::init("_main"));
45
46 /* *** */
47
48 // A trivial memory manager that doesn't do anything fancy, just uses the
49 // support library allocation routines directly.
50 class TrivialMemoryManager : public RTDyldMemoryManager {
51 public:
52   SmallVector<sys::MemoryBlock, 16> FunctionMemory;
53
54   uint8_t *startFunctionBody(const char *Name, uintptr_t &Size);
55   void endFunctionBody(const char *Name, uint8_t *FunctionStart,
56                        uint8_t *FunctionEnd);
57 };
58
59 uint8_t *TrivialMemoryManager::startFunctionBody(const char *Name,
60                                                  uintptr_t &Size) {
61   return (uint8_t*)sys::Memory::AllocateRWX(Size, 0, 0).base();
62 }
63
64 void TrivialMemoryManager::endFunctionBody(const char *Name,
65                                            uint8_t *FunctionStart,
66                                            uint8_t *FunctionEnd) {
67   uintptr_t Size = FunctionEnd - FunctionStart + 1;
68   FunctionMemory.push_back(sys::MemoryBlock(FunctionStart, Size));
69 }
70
71 static const char *ProgramName;
72
73 static void Message(const char *Type, const Twine &Msg) {
74   errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
75 }
76
77 static int Error(const Twine &Msg) {
78   Message("error", Msg);
79   return 1;
80 }
81
82 /* *** */
83
84 static int executeInput() {
85   // Load the input memory buffer.
86   OwningPtr<MemoryBuffer> InputBuffer;
87   if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFile, InputBuffer))
88     return Error("unable to read input: '" + ec.message() + "'");
89
90   // Instantiate a dynamic linker.
91   TrivialMemoryManager *MemMgr = new TrivialMemoryManager;
92   RuntimeDyld Dyld(MemMgr);
93
94   // Load the object file into it.
95   if (Dyld.loadObject(InputBuffer.take())) {
96     return Error(Dyld.getErrorString());
97   }
98   // Resolve all the relocations we can.
99   Dyld.resolveRelocations();
100
101   // Get the address of the entry point (_main by default).
102   void *MainAddress = Dyld.getSymbolAddress(EntryPoint);
103   if (MainAddress == 0)
104     return Error("no definition for '" + EntryPoint + "'");
105
106   // Invalidate the instruction cache for each loaded function.
107   for (unsigned i = 0, e = MemMgr->FunctionMemory.size(); i != e; ++i) {
108     sys::MemoryBlock &Data = MemMgr->FunctionMemory[i];
109     // Make sure the memory is executable.
110     std::string ErrorStr;
111     sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
112     if (!sys::Memory::setExecutable(Data, &ErrorStr))
113       return Error("unable to mark function executable: '" + ErrorStr + "'");
114   }
115
116
117   // Dispatch to _main().
118   errs() << "loaded '_main' at: " << (void*)MainAddress << "\n";
119
120   int (*Main)(int, const char**) =
121     (int(*)(int,const char**)) uintptr_t(MainAddress);
122   const char **Argv = new const char*[2];
123   Argv[0] = InputFile.c_str();
124   Argv[1] = 0;
125   return Main(1, Argv);
126 }
127
128 int main(int argc, char **argv) {
129   ProgramName = argv[0];
130   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
131
132   cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
133
134   switch (Action) {
135   default:
136   case AC_Execute:
137     return executeInput();
138   }
139
140   return 0;
141 }