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/DebugInfo/DIContext.h"
16 #include "llvm/ExecutionEngine/ObjectBuffer.h"
17 #include "llvm/ExecutionEngine/ObjectImage.h"
18 #include "llvm/ExecutionEngine/RuntimeDyld.h"
19 #include "llvm/Object/MachO.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/Memory.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/PrettyStackTrace.h"
25 #include "llvm/Support/Signals.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/system_error.h"
29 using namespace llvm::object;
31 static cl::list<std::string>
32 InputFileList(cl::Positional, cl::ZeroOrMore,
33 cl::desc("<input file>"));
40 static cl::opt<ActionType>
41 Action(cl::desc("Action to perform:"),
43 cl::values(clEnumValN(AC_Execute, "execute",
44 "Load, link, and execute the inputs."),
45 clEnumValN(AC_PrintLineInfo, "printline",
46 "Load, link, and print line information for each function."),
49 static cl::opt<std::string>
51 cl::desc("Function to call as entry point."),
56 // A trivial memory manager that doesn't do anything fancy, just uses the
57 // support library allocation routines directly.
58 class TrivialMemoryManager : public RTDyldMemoryManager {
60 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
61 SmallVector<sys::MemoryBlock, 16> DataMemory;
63 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
65 StringRef SectionName) override;
66 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
67 unsigned SectionID, StringRef SectionName,
68 bool IsReadOnly) override;
70 void *getPointerToNamedFunction(const std::string &Name,
71 bool AbortOnFailure = true) override {
75 bool finalizeMemory(std::string *ErrMsg) override { return false; }
77 // Invalidate instruction cache for sections with execute permissions.
78 // Some platforms with separate data cache and instruction cache require
79 // explicit cache flush, otherwise JIT code manipulations (like resolved
80 // relocations) will get to the data cache but not to the instruction cache.
81 virtual void invalidateInstructionCache();
84 uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
87 StringRef SectionName) {
88 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, 0, 0);
89 FunctionMemory.push_back(MB);
90 return (uint8_t*)MB.base();
93 uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
96 StringRef SectionName,
98 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, 0, 0);
99 DataMemory.push_back(MB);
100 return (uint8_t*)MB.base();
103 void TrivialMemoryManager::invalidateInstructionCache() {
104 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
105 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
106 FunctionMemory[i].size());
108 for (int i = 0, e = DataMemory.size(); i != e; ++i)
109 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
110 DataMemory[i].size());
113 static const char *ProgramName;
115 static void Message(const char *Type, const Twine &Msg) {
116 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
119 static int Error(const Twine &Msg) {
120 Message("error", Msg);
126 static int printLineInfoForInput() {
127 // If we don't have any input files, read from stdin.
128 if (!InputFileList.size())
129 InputFileList.push_back("-");
130 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
131 // Instantiate a dynamic linker.
132 TrivialMemoryManager MemMgr;
133 RuntimeDyld Dyld(&MemMgr);
135 // Load the input memory buffer.
136 std::unique_ptr<MemoryBuffer> InputBuffer;
137 std::unique_ptr<ObjectImage> LoadedObject;
138 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFileList[i],
140 return Error("unable to read input: '" + ec.message() + "'");
142 // Load the object file
143 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
145 return Error(Dyld.getErrorString());
148 // Resolve all the relocations we can.
149 Dyld.resolveRelocations();
151 std::unique_ptr<DIContext> Context(
152 DIContext::getDWARFContext(LoadedObject->getObjectFile()));
154 // Use symbol info to iterate functions in the object.
155 for (object::symbol_iterator I = LoadedObject->begin_symbols(),
156 E = LoadedObject->end_symbols();
158 object::SymbolRef::Type SymType;
159 if (I->getType(SymType)) continue;
160 if (SymType == object::SymbolRef::ST_Function) {
164 if (I->getName(Name)) continue;
165 if (I->getAddress(Addr)) continue;
166 if (I->getSize(Size)) continue;
168 outs() << "Function: " << Name << ", Size = " << Size << "\n";
170 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
171 DILineInfoTable::iterator Begin = Lines.begin();
172 DILineInfoTable::iterator End = Lines.end();
173 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
174 outs() << " Line info @ " << It->first - Addr << ": "
175 << It->second.getFileName()
176 << ", line:" << It->second.getLine() << "\n";
185 static int executeInput() {
186 // Instantiate a dynamic linker.
187 TrivialMemoryManager MemMgr;
188 RuntimeDyld Dyld(&MemMgr);
190 // If we don't have any input files, read from stdin.
191 if (!InputFileList.size())
192 InputFileList.push_back("-");
193 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
194 // Load the input memory buffer.
195 std::unique_ptr<MemoryBuffer> InputBuffer;
196 std::unique_ptr<ObjectImage> LoadedObject;
197 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFileList[i],
199 return Error("unable to read input: '" + ec.message() + "'");
201 // Load the object file
202 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
204 return Error(Dyld.getErrorString());
208 // Resolve all the relocations we can.
209 Dyld.resolveRelocations();
210 // Clear instruction cache before code will be executed.
211 MemMgr.invalidateInstructionCache();
213 // FIXME: Error out if there are unresolved relocations.
215 // Get the address of the entry point (_main by default).
216 void *MainAddress = Dyld.getSymbolAddress(EntryPoint);
217 if (MainAddress == 0)
218 return Error("no definition for '" + EntryPoint + "'");
220 // Invalidate the instruction cache for each loaded function.
221 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
222 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
223 // Make sure the memory is executable.
224 std::string ErrorStr;
225 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
226 if (!sys::Memory::setExecutable(Data, &ErrorStr))
227 return Error("unable to mark function executable: '" + ErrorStr + "'");
230 // Dispatch to _main().
231 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
233 int (*Main)(int, const char**) =
234 (int(*)(int,const char**)) uintptr_t(MainAddress);
235 const char **Argv = new const char*[2];
236 // Use the name of the first input object module as argv[0] for the target.
237 Argv[0] = InputFileList[0].c_str();
239 return Main(1, Argv);
242 int main(int argc, char **argv) {
243 sys::PrintStackTraceOnErrorSignal();
244 PrettyStackTraceProgram X(argc, argv);
246 ProgramName = argv[0];
247 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
249 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
253 return executeInput();
254 case AC_PrintLineInfo:
255 return printLineInfoForInput();