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,
64 unsigned SectionID, StringRef SectionName);
65 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
66 unsigned SectionID, StringRef SectionName,
69 virtual void *getPointerToNamedFunction(const std::string &Name,
70 bool AbortOnFailure = true) {
74 bool finalizeMemory(std::string *ErrMsg) { return false; }
76 // Invalidate instruction cache for sections with execute permissions.
77 // Some platforms with separate data cache and instruction cache require
78 // explicit cache flush, otherwise JIT code manipulations (like resolved
79 // relocations) will get to the data cache but not to the instruction cache.
80 virtual void invalidateInstructionCache();
83 uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
86 StringRef SectionName) {
87 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, 0, 0);
88 FunctionMemory.push_back(MB);
89 return (uint8_t*)MB.base();
92 uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
95 StringRef SectionName,
97 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, 0, 0);
98 DataMemory.push_back(MB);
99 return (uint8_t*)MB.base();
102 void TrivialMemoryManager::invalidateInstructionCache() {
103 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
104 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
105 FunctionMemory[i].size());
107 for (int i = 0, e = DataMemory.size(); i != e; ++i)
108 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
109 DataMemory[i].size());
112 static const char *ProgramName;
114 static void Message(const char *Type, const Twine &Msg) {
115 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
118 static int Error(const Twine &Msg) {
119 Message("error", Msg);
125 static int printLineInfoForInput() {
126 // If we don't have any input files, read from stdin.
127 if (!InputFileList.size())
128 InputFileList.push_back("-");
129 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
130 // Instantiate a dynamic linker.
131 TrivialMemoryManager MemMgr;
132 RuntimeDyld Dyld(&MemMgr);
134 // Load the input memory buffer.
135 std::unique_ptr<MemoryBuffer> InputBuffer;
136 std::unique_ptr<ObjectImage> LoadedObject;
137 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFileList[i],
139 return Error("unable to read input: '" + ec.message() + "'");
141 // Load the object file
142 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
144 return Error(Dyld.getErrorString());
147 // Resolve all the relocations we can.
148 Dyld.resolveRelocations();
150 std::unique_ptr<DIContext> Context(
151 DIContext::getDWARFContext(LoadedObject->getObjectFile()));
153 // Use symbol info to iterate functions in the object.
154 for (object::symbol_iterator I = LoadedObject->begin_symbols(),
155 E = LoadedObject->end_symbols();
157 object::SymbolRef::Type SymType;
158 if (I->getType(SymType)) continue;
159 if (SymType == object::SymbolRef::ST_Function) {
163 if (I->getName(Name)) continue;
164 if (I->getAddress(Addr)) continue;
165 if (I->getSize(Size)) continue;
167 outs() << "Function: " << Name << ", Size = " << Size << "\n";
169 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
170 DILineInfoTable::iterator Begin = Lines.begin();
171 DILineInfoTable::iterator End = Lines.end();
172 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
173 outs() << " Line info @ " << It->first - Addr << ": "
174 << It->second.getFileName()
175 << ", line:" << It->second.getLine() << "\n";
184 static int executeInput() {
185 // Instantiate a dynamic linker.
186 TrivialMemoryManager MemMgr;
187 RuntimeDyld Dyld(&MemMgr);
189 // If we don't have any input files, read from stdin.
190 if (!InputFileList.size())
191 InputFileList.push_back("-");
192 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
193 // Load the input memory buffer.
194 std::unique_ptr<MemoryBuffer> InputBuffer;
195 std::unique_ptr<ObjectImage> LoadedObject;
196 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFileList[i],
198 return Error("unable to read input: '" + ec.message() + "'");
200 // Load the object file
201 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
203 return Error(Dyld.getErrorString());
207 // Resolve all the relocations we can.
208 Dyld.resolveRelocations();
209 // Clear instruction cache before code will be executed.
210 MemMgr.invalidateInstructionCache();
212 // FIXME: Error out if there are unresolved relocations.
214 // Get the address of the entry point (_main by default).
215 void *MainAddress = Dyld.getSymbolAddress(EntryPoint);
216 if (MainAddress == 0)
217 return Error("no definition for '" + EntryPoint + "'");
219 // Invalidate the instruction cache for each loaded function.
220 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
221 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
222 // Make sure the memory is executable.
223 std::string ErrorStr;
224 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
225 if (!sys::Memory::setExecutable(Data, &ErrorStr))
226 return Error("unable to mark function executable: '" + ErrorStr + "'");
229 // Dispatch to _main().
230 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
232 int (*Main)(int, const char**) =
233 (int(*)(int,const char**)) uintptr_t(MainAddress);
234 const char **Argv = new const char*[2];
235 // Use the name of the first input object module as argv[0] for the target.
236 Argv[0] = InputFileList[0].c_str();
238 return Main(1, Argv);
241 int main(int argc, char **argv) {
242 sys::PrintStackTraceOnErrorSignal();
243 PrettyStackTraceProgram X(argc, argv);
245 ProgramName = argv[0];
246 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
248 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
252 return executeInput();
253 case AC_PrintLineInfo:
254 return printLineInfoForInput();