blob: df6d535c4307bdfa93278f8072f33e080f2f614f [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
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000014#include "llvm/ADT/StringMap.h"
Andrew Kaylord55d7012013-01-25 22:50:58 +000015#include "llvm/DebugInfo/DIContext.h"
Andrew Kayloradc70562012-10-02 21:18:39 +000016#include "llvm/ExecutionEngine/ObjectBuffer.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000017#include "llvm/ExecutionEngine/ObjectImage.h"
18#include "llvm/ExecutionEngine/RuntimeDyld.h"
Rafael Espindola6e040c02013-04-26 20:07:33 +000019#include "llvm/Object/MachO.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000020#include "llvm/Support/CommandLine.h"
Lang Hamesd311c0e2014-05-13 22:37:41 +000021#include "llvm/Support/DynamicLibrary.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000022#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"
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000028#include <system_error>
Jim Grosbach0072cdb2011-03-18 17:11:39 +000029using 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
Lang Hamesd311c0e2014-05-13 22:37:41 +000055static cl::list<std::string>
56Dylibs("dylib",
57 cl::desc("Add library."),
58 cl::ZeroOrMore);
59
Jim Grosbach0072cdb2011-03-18 17:11:39 +000060/* *** */
61
Jim Grosbach2dcef0502011-04-04 23:04:39 +000062// A trivial memory manager that doesn't do anything fancy, just uses the
63// support library allocation routines directly.
64class TrivialMemoryManager : public RTDyldMemoryManager {
65public:
Jim Grosbach3ed03f12011-04-12 00:23:32 +000066 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +000067 SmallVector<sys::MemoryBlock, 16> DataMemory;
68
69 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +000070 unsigned SectionID,
71 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +000072 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +000073 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +000074 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +000075
Craig Toppere56917c2014-03-08 08:27:28 +000076 void *getPointerToNamedFunction(const std::string &Name,
77 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +000078 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +000079 }
80
Craig Toppere56917c2014-03-08 08:27:28 +000081 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +000082
Danil Malyshev8c17fbd2012-05-16 18:50:11 +000083 // 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();
Jim Grosbach2dcef0502011-04-04 23:04:39 +000088};
89
Jim Grosbacheff0a402012-01-16 22:26:39 +000090uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
91 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +000092 unsigned SectionID,
93 StringRef SectionName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +000094 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +000095 FunctionMemory.push_back(MB);
96 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +000097}
98
99uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
100 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000101 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000102 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000103 bool IsReadOnly) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000104 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000105 DataMemory.push_back(MB);
106 return (uint8_t*)MB.base();
107}
108
109void TrivialMemoryManager::invalidateInstructionCache() {
110 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
111 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
112 FunctionMemory[i].size());
113
114 for (int i = 0, e = DataMemory.size(); i != e; ++i)
115 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
116 DataMemory[i].size());
Jim Grosbacheff0a402012-01-16 22:26:39 +0000117}
118
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000119static const char *ProgramName;
120
121static void Message(const char *Type, const Twine &Msg) {
122 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
123}
124
125static int Error(const Twine &Msg) {
126 Message("error", Msg);
127 return 1;
128}
129
Lang Hamesd311c0e2014-05-13 22:37:41 +0000130static void loadDylibs() {
131 for (const std::string &Dylib : Dylibs) {
132 if (sys::fs::is_regular_file(Dylib)) {
133 std::string ErrMsg;
134 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
135 llvm::errs() << "Error loading '" << Dylib << "': "
136 << ErrMsg << "\n";
137 } else
138 llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
139 }
140}
141
142
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000143/* *** */
144
Andrew Kaylord55d7012013-01-25 22:50:58 +0000145static int printLineInfoForInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000146 // Load any dylibs requested on the command line.
147 loadDylibs();
148
Andrew Kaylord55d7012013-01-25 22:50:58 +0000149 // 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.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000154 TrivialMemoryManager MemMgr;
155 RuntimeDyld Dyld(&MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000156
157 // Load the input memory buffer.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000158 std::unique_ptr<MemoryBuffer> InputBuffer;
159 std::unique_ptr<ObjectImage> LoadedObject;
Andrew Kaylord55d7012013-01-25 22:50:58 +0000160 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFileList[i],
161 InputBuffer))
162 return Error("unable to read input: '" + ec.message() + "'");
163
164 // Load the object file
Ahmed Charles96c9d952014-03-05 10:19:29 +0000165 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
Andrew Kaylord55d7012013-01-25 22:50:58 +0000166 if (!LoadedObject) {
167 return Error(Dyld.getErrorString());
168 }
169
170 // Resolve all the relocations we can.
171 Dyld.resolveRelocations();
172
Ahmed Charles56440fd2014-03-06 05:51:42 +0000173 std::unique_ptr<DIContext> Context(
174 DIContext::getDWARFContext(LoadedObject->getObjectFile()));
Andrew Kaylord55d7012013-01-25 22:50:58 +0000175
176 // Use symbol info to iterate functions in the object.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000177 for (object::symbol_iterator I = LoadedObject->begin_symbols(),
178 E = LoadedObject->end_symbols();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000179 I != E; ++I) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000180 object::SymbolRef::Type SymType;
181 if (I->getType(SymType)) continue;
182 if (SymType == object::SymbolRef::ST_Function) {
183 StringRef Name;
184 uint64_t Addr;
185 uint64_t Size;
186 if (I->getName(Name)) continue;
187 if (I->getAddress(Addr)) continue;
188 if (I->getSize(Size)) continue;
189
190 outs() << "Function: " << Name << ", Size = " << Size << "\n";
191
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000192 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 << ": "
Alexey Samsonovd0109992014-04-18 21:36:39 +0000197 << It->second.FileName << ", line:" << It->second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000198 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000199 }
200 }
201 }
202
203 return 0;
204}
205
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000206static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000207 // Load any dylibs requested on the command line.
208 loadDylibs();
209
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000210 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000211 TrivialMemoryManager MemMgr;
212 RuntimeDyld Dyld(&MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000213
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000214 // 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.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000219 std::unique_ptr<MemoryBuffer> InputBuffer;
220 std::unique_ptr<ObjectImage> LoadedObject;
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000221 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFileList[i],
222 InputBuffer))
223 return Error("unable to read input: '" + ec.message() + "'");
224
Andrew Kayloradc70562012-10-02 21:18:39 +0000225 // Load the object file
Ahmed Charles96c9d952014-03-05 10:19:29 +0000226 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
Andrew Kayloradc70562012-10-02 21:18:39 +0000227 if (!LoadedObject) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000228 return Error(Dyld.getErrorString());
229 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000230 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000231
Jim Grosbach733d3052011-04-12 21:20:41 +0000232 // Resolve all the relocations we can.
233 Dyld.resolveRelocations();
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000234 // Clear instruction cache before code will be executed.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000235 MemMgr.invalidateInstructionCache();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000236
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000237 // FIXME: Error out if there are unresolved relocations.
238
Jim Grosbachd35159a2011-04-13 15:38:30 +0000239 // Get the address of the entry point (_main by default).
240 void *MainAddress = Dyld.getSymbolAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000241 if (!MainAddress)
Jim Grosbachd35159a2011-04-13 15:38:30 +0000242 return Error("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000243
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000244 // Invalidate the instruction cache for each loaded function.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000245 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
246 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000247 // 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 + "'");
252 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000253
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000254 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000255 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000256
257 int (*Main)(int, const char**) =
258 (int(*)(int,const char**)) uintptr_t(MainAddress);
259 const char **Argv = new const char*[2];
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000260 // Use the name of the first input object module as argv[0] for the target.
261 Argv[0] = InputFileList[0].c_str();
Craig Toppere6cb63e2014-04-25 04:24:47 +0000262 Argv[1] = nullptr;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000263 return Main(1, Argv);
264}
265
266int main(int argc, char **argv) {
Alp Toker9f679322013-11-05 09:33:43 +0000267 sys::PrintStackTraceOnErrorSignal();
268 PrettyStackTraceProgram X(argc, argv);
269
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000270 ProgramName = argv[0];
271 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
272
273 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
274
275 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000276 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000277 return executeInput();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000278 case AC_PrintLineInfo:
279 return printLineInfoForInput();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000280 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000281}