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/DynamicLibrary.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/Memory.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/PrettyStackTrace.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <system_error>
30 using namespace llvm::object;
32 static cl::list<std::string>
33 InputFileList(cl::Positional, cl::ZeroOrMore,
34 cl::desc("<input file>"));
41 static cl::opt<ActionType>
42 Action(cl::desc("Action to perform:"),
44 cl::values(clEnumValN(AC_Execute, "execute",
45 "Load, link, and execute the inputs."),
46 clEnumValN(AC_PrintLineInfo, "printline",
47 "Load, link, and print line information for each function."),
50 static cl::opt<std::string>
52 cl::desc("Function to call as entry point."),
55 static cl::list<std::string>
57 cl::desc("Add library."),
62 // A trivial memory manager that doesn't do anything fancy, just uses the
63 // support library allocation routines directly.
64 class TrivialMemoryManager : public RTDyldMemoryManager {
66 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
67 SmallVector<sys::MemoryBlock, 16> DataMemory;
69 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
71 StringRef SectionName) override;
72 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
73 unsigned SectionID, StringRef SectionName,
74 bool IsReadOnly) override;
76 void *getPointerToNamedFunction(const std::string &Name,
77 bool AbortOnFailure = true) override {
81 bool finalizeMemory(std::string *ErrMsg) override { return false; }
83 // Invalidate instruction cache for sections with execute permissions.
84 // Some platforms with separate data cache and instruction cache require
85 // explicit cache flush, otherwise JIT code manipulations (like resolved
86 // relocations) will get to the data cache but not to the instruction cache.
87 virtual void invalidateInstructionCache();
90 uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
93 StringRef SectionName) {
94 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
95 FunctionMemory.push_back(MB);
96 return (uint8_t*)MB.base();
99 uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
102 StringRef SectionName,
104 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
105 DataMemory.push_back(MB);
106 return (uint8_t*)MB.base();
109 void TrivialMemoryManager::invalidateInstructionCache() {
110 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
111 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
112 FunctionMemory[i].size());
114 for (int i = 0, e = DataMemory.size(); i != e; ++i)
115 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
116 DataMemory[i].size());
119 static const char *ProgramName;
121 static void Message(const char *Type, const Twine &Msg) {
122 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
125 static int Error(const Twine &Msg) {
126 Message("error", Msg);
130 static void loadDylibs() {
131 for (const std::string &Dylib : Dylibs) {
132 if (sys::fs::is_regular_file(Dylib)) {
134 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
135 llvm::errs() << "Error loading '" << Dylib << "': "
138 llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
145 static int printLineInfoForInput() {
146 // Load any dylibs requested on the command line.
149 // If we don't have any input files, read from stdin.
150 if (!InputFileList.size())
151 InputFileList.push_back("-");
152 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
153 // Instantiate a dynamic linker.
154 TrivialMemoryManager MemMgr;
155 RuntimeDyld Dyld(&MemMgr);
157 // Load the input memory buffer.
158 std::unique_ptr<MemoryBuffer> InputBuffer;
159 std::unique_ptr<ObjectImage> LoadedObject;
160 if (std::error_code ec =
161 MemoryBuffer::getFileOrSTDIN(InputFileList[i], InputBuffer))
162 return Error("unable to read input: '" + ec.message() + "'");
164 // Load the object file
165 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
167 return Error(Dyld.getErrorString());
170 // Resolve all the relocations we can.
171 Dyld.resolveRelocations();
173 std::unique_ptr<DIContext> Context(
174 DIContext::getDWARFContext(LoadedObject->getObjectFile()));
176 // Use symbol info to iterate functions in the object.
177 for (object::symbol_iterator I = LoadedObject->begin_symbols(),
178 E = LoadedObject->end_symbols();
180 object::SymbolRef::Type SymType;
181 if (I->getType(SymType)) continue;
182 if (SymType == object::SymbolRef::ST_Function) {
186 if (I->getName(Name)) continue;
187 if (I->getAddress(Addr)) continue;
188 if (I->getSize(Size)) continue;
190 outs() << "Function: " << Name << ", Size = " << Size << "\n";
192 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
193 DILineInfoTable::iterator Begin = Lines.begin();
194 DILineInfoTable::iterator End = Lines.end();
195 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
196 outs() << " Line info @ " << It->first - Addr << ": "
197 << It->second.FileName << ", line:" << It->second.Line << "\n";
206 static int executeInput() {
207 // Load any dylibs requested on the command line.
210 // Instantiate a dynamic linker.
211 TrivialMemoryManager MemMgr;
212 RuntimeDyld Dyld(&MemMgr);
214 // If we don't have any input files, read from stdin.
215 if (!InputFileList.size())
216 InputFileList.push_back("-");
217 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
218 // Load the input memory buffer.
219 std::unique_ptr<MemoryBuffer> InputBuffer;
220 std::unique_ptr<ObjectImage> LoadedObject;
221 if (std::error_code ec =
222 MemoryBuffer::getFileOrSTDIN(InputFileList[i], InputBuffer))
223 return Error("unable to read input: '" + ec.message() + "'");
225 // Load the object file
226 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
228 return Error(Dyld.getErrorString());
232 // Resolve all the relocations we can.
233 Dyld.resolveRelocations();
234 // Clear instruction cache before code will be executed.
235 MemMgr.invalidateInstructionCache();
237 // FIXME: Error out if there are unresolved relocations.
239 // Get the address of the entry point (_main by default).
240 void *MainAddress = Dyld.getSymbolAddress(EntryPoint);
242 return Error("no definition for '" + EntryPoint + "'");
244 // Invalidate the instruction cache for each loaded function.
245 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
246 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
247 // Make sure the memory is executable.
248 std::string ErrorStr;
249 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
250 if (!sys::Memory::setExecutable(Data, &ErrorStr))
251 return Error("unable to mark function executable: '" + ErrorStr + "'");
254 // Dispatch to _main().
255 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
257 int (*Main)(int, const char**) =
258 (int(*)(int,const char**)) uintptr_t(MainAddress);
259 const char **Argv = new const char*[2];
260 // Use the name of the first input object module as argv[0] for the target.
261 Argv[0] = InputFileList[0].c_str();
263 return Main(1, Argv);
266 int main(int argc, char **argv) {
267 sys::PrintStackTraceOnErrorSignal();
268 PrettyStackTraceProgram X(argc, argv);
270 ProgramName = argv[0];
271 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
273 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
277 return executeInput();
278 case AC_PrintLineInfo:
279 return printLineInfoForInput();