blob: 531595eacddd3a2c1ac921f1bf404601b04d882d [file] [log] [blame]
Jim Grosbach0072cdb2011-03-18 17:11:39 +00001//===-- 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
Jim Grosbach0072cdb2011-03-18 17:11:39 +000014#include "llvm/ADT/OwningPtr.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000015#include "llvm/ADT/StringMap.h"
Andrew Kaylord55d7012013-01-25 22:50:58 +000016#include "llvm/DebugInfo/DIContext.h"
Andrew Kayloradc70562012-10-02 21:18:39 +000017#include "llvm/ExecutionEngine/ObjectBuffer.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/ExecutionEngine/ObjectImage.h"
19#include "llvm/ExecutionEngine/RuntimeDyld.h"
Rafael Espindola6e040c02013-04-26 20:07:33 +000020#include "llvm/Object/MachO.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000021#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/ManagedStatic.h"
23#include "llvm/Support/Memory.h"
24#include "llvm/Support/MemoryBuffer.h"
Alp Toker9f679322013-11-05 09:33:43 +000025#include "llvm/Support/PrettyStackTrace.h"
26#include "llvm/Support/Signals.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000027#include "llvm/Support/raw_ostream.h"
28#include "llvm/Support/system_error.h"
29using namespace llvm;
30using namespace llvm::object;
31
Jim Grosbach7cb41d72011-04-13 15:49:40 +000032static cl::list<std::string>
33InputFileList(cl::Positional, cl::ZeroOrMore,
34 cl::desc("<input file>"));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000035
36enum ActionType {
Andrew Kaylord55d7012013-01-25 22:50:58 +000037 AC_Execute,
38 AC_PrintLineInfo
Jim Grosbach0072cdb2011-03-18 17:11:39 +000039};
40
41static cl::opt<ActionType>
42Action(cl::desc("Action to perform:"),
43 cl::init(AC_Execute),
44 cl::values(clEnumValN(AC_Execute, "execute",
45 "Load, link, and execute the inputs."),
Andrew Kaylord55d7012013-01-25 22:50:58 +000046 clEnumValN(AC_PrintLineInfo, "printline",
47 "Load, link, and print line information for each function."),
Jim Grosbach0072cdb2011-03-18 17:11:39 +000048 clEnumValEnd));
49
Jim Grosbachd35159a2011-04-13 15:38:30 +000050static cl::opt<std::string>
51EntryPoint("entry",
52 cl::desc("Function to call as entry point."),
53 cl::init("_main"));
54
Jim Grosbach0072cdb2011-03-18 17:11:39 +000055/* *** */
56
Jim Grosbach2dcef0502011-04-04 23:04:39 +000057// A trivial memory manager that doesn't do anything fancy, just uses the
58// support library allocation routines directly.
59class TrivialMemoryManager : public RTDyldMemoryManager {
60public:
Jim Grosbach3ed03f12011-04-12 00:23:32 +000061 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +000062 SmallVector<sys::MemoryBlock, 16> DataMemory;
63
64 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +000065 unsigned SectionID, StringRef SectionName);
Jim Grosbacheff0a402012-01-16 22:26:39 +000066 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +000067 unsigned SectionID, StringRef SectionName,
68 bool IsReadOnly);
Jim Grosbach3ed03f12011-04-12 00:23:32 +000069
Danil Malyshevbfee5422012-03-28 21:46:36 +000070 virtual void *getPointerToNamedFunction(const std::string &Name,
71 bool AbortOnFailure = true) {
72 return 0;
73 }
74
David Tweed2e7efed2013-05-17 10:01:46 +000075 bool finalizeMemory(std::string *ErrMsg) { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +000076
Danil Malyshev8c17fbd2012-05-16 18:50:11 +000077 // 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();
Jim Grosbach2dcef0502011-04-04 23:04:39 +000082};
83
Jim Grosbacheff0a402012-01-16 22:26:39 +000084uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
85 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +000086 unsigned SectionID,
87 StringRef SectionName) {
Danil Malyshev8c17fbd2012-05-16 18:50:11 +000088 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, 0, 0);
89 FunctionMemory.push_back(MB);
90 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +000091}
92
93uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
94 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +000095 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +000096 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +000097 bool IsReadOnly) {
Danil Malyshev8c17fbd2012-05-16 18:50:11 +000098 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, 0, 0);
99 DataMemory.push_back(MB);
100 return (uint8_t*)MB.base();
101}
102
103void TrivialMemoryManager::invalidateInstructionCache() {
104 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
105 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
106 FunctionMemory[i].size());
107
108 for (int i = 0, e = DataMemory.size(); i != e; ++i)
109 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
110 DataMemory[i].size());
Jim Grosbacheff0a402012-01-16 22:26:39 +0000111}
112
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000113static const char *ProgramName;
114
115static void Message(const char *Type, const Twine &Msg) {
116 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
117}
118
119static int Error(const Twine &Msg) {
120 Message("error", Msg);
121 return 1;
122}
123
124/* *** */
125
Andrew Kaylord55d7012013-01-25 22:50:58 +0000126static 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.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000132 TrivialMemoryManager MemMgr;
133 RuntimeDyld Dyld(&MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000134
135 // Load the input memory buffer.
136 OwningPtr<MemoryBuffer> InputBuffer;
137 OwningPtr<ObjectImage> LoadedObject;
138 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFileList[i],
139 InputBuffer))
140 return Error("unable to read input: '" + ec.message() + "'");
141
142 // Load the object file
143 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.take())));
144 if (!LoadedObject) {
145 return Error(Dyld.getErrorString());
146 }
147
148 // Resolve all the relocations we can.
149 Dyld.resolveRelocations();
150
151 OwningPtr<DIContext> Context(DIContext::getDWARFContext(LoadedObject->getObjectFile()));
152
153 // Use symbol info to iterate functions in the object.
154 error_code ec;
155 for (object::symbol_iterator I = LoadedObject->begin_symbols(),
156 E = LoadedObject->end_symbols();
157 I != E && !ec;
158 I.increment(ec)) {
159 object::SymbolRef::Type SymType;
160 if (I->getType(SymType)) continue;
161 if (SymType == object::SymbolRef::ST_Function) {
162 StringRef Name;
163 uint64_t Addr;
164 uint64_t Size;
165 if (I->getName(Name)) continue;
166 if (I->getAddress(Addr)) continue;
167 if (I->getSize(Size)) continue;
168
169 outs() << "Function: " << Name << ", Size = " << Size << "\n";
170
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000171 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
172 DILineInfoTable::iterator Begin = Lines.begin();
173 DILineInfoTable::iterator End = Lines.end();
174 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
175 outs() << " Line info @ " << It->first - Addr << ": "
176 << It->second.getFileName()
177 << ", line:" << It->second.getLine() << "\n";
178 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000179 }
180 }
181 }
182
183 return 0;
184}
185
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000186static int executeInput() {
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000187 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000188 TrivialMemoryManager MemMgr;
189 RuntimeDyld Dyld(&MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000190
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000191 // If we don't have any input files, read from stdin.
192 if (!InputFileList.size())
193 InputFileList.push_back("-");
194 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
195 // Load the input memory buffer.
196 OwningPtr<MemoryBuffer> InputBuffer;
Andrew Kayloradc70562012-10-02 21:18:39 +0000197 OwningPtr<ObjectImage> LoadedObject;
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000198 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFileList[i],
199 InputBuffer))
200 return Error("unable to read input: '" + ec.message() + "'");
201
Andrew Kayloradc70562012-10-02 21:18:39 +0000202 // Load the object file
203 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.take())));
204 if (!LoadedObject) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000205 return Error(Dyld.getErrorString());
206 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000207 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000208
Jim Grosbach733d3052011-04-12 21:20:41 +0000209 // Resolve all the relocations we can.
210 Dyld.resolveRelocations();
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000211 // Clear instruction cache before code will be executed.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000212 MemMgr.invalidateInstructionCache();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000213
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000214 // FIXME: Error out if there are unresolved relocations.
215
Jim Grosbachd35159a2011-04-13 15:38:30 +0000216 // Get the address of the entry point (_main by default).
217 void *MainAddress = Dyld.getSymbolAddress(EntryPoint);
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000218 if (MainAddress == 0)
Jim Grosbachd35159a2011-04-13 15:38:30 +0000219 return Error("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000220
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000221 // Invalidate the instruction cache for each loaded function.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000222 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
223 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000224 // Make sure the memory is executable.
225 std::string ErrorStr;
226 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
227 if (!sys::Memory::setExecutable(Data, &ErrorStr))
228 return Error("unable to mark function executable: '" + ErrorStr + "'");
229 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000230
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000231 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000232 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000233
234 int (*Main)(int, const char**) =
235 (int(*)(int,const char**)) uintptr_t(MainAddress);
236 const char **Argv = new const char*[2];
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000237 // Use the name of the first input object module as argv[0] for the target.
238 Argv[0] = InputFileList[0].c_str();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000239 Argv[1] = 0;
240 return Main(1, Argv);
241}
242
243int main(int argc, char **argv) {
Alp Toker9f679322013-11-05 09:33:43 +0000244 sys::PrintStackTraceOnErrorSignal();
245 PrettyStackTraceProgram X(argc, argv);
246
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000247 ProgramName = argv[0];
248 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
249
250 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
251
252 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000253 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000254 return executeInput();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000255 case AC_PrintLineInfo:
256 return printLineInfoForInput();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000257 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000258}