blob: fcda9e7f8a8e0d36b17faee8f598eb0d6c661e46 [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"
Lang Hamese1c11382014-06-27 20:20:57 +000019#include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
20#include "llvm/MC/MCAsmInfo.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCDisassembler.h"
23#include "llvm/MC/MCInstrInfo.h"
24#include "llvm/MC/MCInstPrinter.h"
25#include "llvm/MC/MCRegisterInfo.h"
Rafael Espindola6e040c02013-04-26 20:07:33 +000026#include "llvm/Object/MachO.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000027#include "llvm/Support/CommandLine.h"
Lang Hamesd311c0e2014-05-13 22:37:41 +000028#include "llvm/Support/DynamicLibrary.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000029#include "llvm/Support/ManagedStatic.h"
30#include "llvm/Support/Memory.h"
31#include "llvm/Support/MemoryBuffer.h"
Alp Toker9f679322013-11-05 09:33:43 +000032#include "llvm/Support/PrettyStackTrace.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000033#include "llvm/Support/raw_ostream.h"
Lang Hamese1c11382014-06-27 20:20:57 +000034#include "llvm/Support/Signals.h"
35#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/TargetSelect.h"
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000037#include <system_error>
Lang Hamese1c11382014-06-27 20:20:57 +000038
Jim Grosbach0072cdb2011-03-18 17:11:39 +000039using namespace llvm;
40using namespace llvm::object;
41
Jim Grosbach7cb41d72011-04-13 15:49:40 +000042static cl::list<std::string>
43InputFileList(cl::Positional, cl::ZeroOrMore,
44 cl::desc("<input file>"));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000045
46enum ActionType {
Andrew Kaylord55d7012013-01-25 22:50:58 +000047 AC_Execute,
Lang Hamese1c11382014-06-27 20:20:57 +000048 AC_PrintLineInfo,
49 AC_Verify
Jim Grosbach0072cdb2011-03-18 17:11:39 +000050};
51
52static cl::opt<ActionType>
53Action(cl::desc("Action to perform:"),
54 cl::init(AC_Execute),
55 cl::values(clEnumValN(AC_Execute, "execute",
56 "Load, link, and execute the inputs."),
Andrew Kaylord55d7012013-01-25 22:50:58 +000057 clEnumValN(AC_PrintLineInfo, "printline",
58 "Load, link, and print line information for each function."),
Lang Hamese1c11382014-06-27 20:20:57 +000059 clEnumValN(AC_Verify, "verify",
60 "Load, link and verify the resulting memory image."),
Jim Grosbach0072cdb2011-03-18 17:11:39 +000061 clEnumValEnd));
62
Jim Grosbachd35159a2011-04-13 15:38:30 +000063static cl::opt<std::string>
64EntryPoint("entry",
65 cl::desc("Function to call as entry point."),
66 cl::init("_main"));
67
Lang Hamesd311c0e2014-05-13 22:37:41 +000068static cl::list<std::string>
69Dylibs("dylib",
70 cl::desc("Add library."),
71 cl::ZeroOrMore);
72
Lang Hamese1c11382014-06-27 20:20:57 +000073static cl::opt<std::string>
74TripleName("triple", cl::desc("Target triple for disassembler"));
75
76static cl::list<std::string>
77CheckFiles("check",
78 cl::desc("File containing RuntimeDyld verifier checks."),
79 cl::ZeroOrMore);
80
Jim Grosbach0072cdb2011-03-18 17:11:39 +000081/* *** */
82
Jim Grosbach2dcef0502011-04-04 23:04:39 +000083// A trivial memory manager that doesn't do anything fancy, just uses the
84// support library allocation routines directly.
85class TrivialMemoryManager : public RTDyldMemoryManager {
86public:
Jim Grosbach3ed03f12011-04-12 00:23:32 +000087 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +000088 SmallVector<sys::MemoryBlock, 16> DataMemory;
89
90 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +000091 unsigned SectionID,
92 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +000093 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +000094 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +000095 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +000096
Craig Toppere56917c2014-03-08 08:27:28 +000097 void *getPointerToNamedFunction(const std::string &Name,
98 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +000099 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000100 }
101
Craig Toppere56917c2014-03-08 08:27:28 +0000102 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000103
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000104 // Invalidate instruction cache for sections with execute permissions.
105 // Some platforms with separate data cache and instruction cache require
106 // explicit cache flush, otherwise JIT code manipulations (like resolved
107 // relocations) will get to the data cache but not to the instruction cache.
108 virtual void invalidateInstructionCache();
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000109};
110
Jim Grosbacheff0a402012-01-16 22:26:39 +0000111uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
112 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000113 unsigned SectionID,
114 StringRef SectionName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000115 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000116 FunctionMemory.push_back(MB);
117 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +0000118}
119
120uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
121 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000122 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000123 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000124 bool IsReadOnly) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000125 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000126 DataMemory.push_back(MB);
127 return (uint8_t*)MB.base();
128}
129
130void TrivialMemoryManager::invalidateInstructionCache() {
131 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
132 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
133 FunctionMemory[i].size());
134
135 for (int i = 0, e = DataMemory.size(); i != e; ++i)
136 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
137 DataMemory[i].size());
Jim Grosbacheff0a402012-01-16 22:26:39 +0000138}
139
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000140static const char *ProgramName;
141
142static void Message(const char *Type, const Twine &Msg) {
143 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
144}
145
146static int Error(const Twine &Msg) {
147 Message("error", Msg);
148 return 1;
149}
150
Lang Hamesd311c0e2014-05-13 22:37:41 +0000151static void loadDylibs() {
152 for (const std::string &Dylib : Dylibs) {
153 if (sys::fs::is_regular_file(Dylib)) {
154 std::string ErrMsg;
155 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
156 llvm::errs() << "Error loading '" << Dylib << "': "
157 << ErrMsg << "\n";
158 } else
159 llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
160 }
161}
162
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000163/* *** */
164
Andrew Kaylord55d7012013-01-25 22:50:58 +0000165static int printLineInfoForInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000166 // Load any dylibs requested on the command line.
167 loadDylibs();
168
Andrew Kaylord55d7012013-01-25 22:50:58 +0000169 // If we don't have any input files, read from stdin.
170 if (!InputFileList.size())
171 InputFileList.push_back("-");
172 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
173 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000174 TrivialMemoryManager MemMgr;
175 RuntimeDyld Dyld(&MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000176
177 // Load the input memory buffer.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000178 std::unique_ptr<MemoryBuffer> InputBuffer;
179 std::unique_ptr<ObjectImage> LoadedObject;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000180 if (std::error_code ec =
181 MemoryBuffer::getFileOrSTDIN(InputFileList[i], InputBuffer))
Andrew Kaylord55d7012013-01-25 22:50:58 +0000182 return Error("unable to read input: '" + ec.message() + "'");
183
184 // Load the object file
Ahmed Charles96c9d952014-03-05 10:19:29 +0000185 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
Andrew Kaylord55d7012013-01-25 22:50:58 +0000186 if (!LoadedObject) {
187 return Error(Dyld.getErrorString());
188 }
189
190 // Resolve all the relocations we can.
191 Dyld.resolveRelocations();
192
Ahmed Charles56440fd2014-03-06 05:51:42 +0000193 std::unique_ptr<DIContext> Context(
194 DIContext::getDWARFContext(LoadedObject->getObjectFile()));
Andrew Kaylord55d7012013-01-25 22:50:58 +0000195
196 // Use symbol info to iterate functions in the object.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000197 for (object::symbol_iterator I = LoadedObject->begin_symbols(),
198 E = LoadedObject->end_symbols();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000199 I != E; ++I) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000200 object::SymbolRef::Type SymType;
201 if (I->getType(SymType)) continue;
202 if (SymType == object::SymbolRef::ST_Function) {
203 StringRef Name;
204 uint64_t Addr;
205 uint64_t Size;
206 if (I->getName(Name)) continue;
207 if (I->getAddress(Addr)) continue;
208 if (I->getSize(Size)) continue;
209
210 outs() << "Function: " << Name << ", Size = " << Size << "\n";
211
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000212 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
213 DILineInfoTable::iterator Begin = Lines.begin();
214 DILineInfoTable::iterator End = Lines.end();
215 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
216 outs() << " Line info @ " << It->first - Addr << ": "
Alexey Samsonovd0109992014-04-18 21:36:39 +0000217 << It->second.FileName << ", line:" << It->second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000218 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000219 }
220 }
221 }
222
223 return 0;
224}
225
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000226static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000227 // Load any dylibs requested on the command line.
228 loadDylibs();
229
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000230 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000231 TrivialMemoryManager MemMgr;
232 RuntimeDyld Dyld(&MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000233
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000234 // If we don't have any input files, read from stdin.
235 if (!InputFileList.size())
236 InputFileList.push_back("-");
237 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
238 // Load the input memory buffer.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000239 std::unique_ptr<MemoryBuffer> InputBuffer;
240 std::unique_ptr<ObjectImage> LoadedObject;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000241 if (std::error_code ec =
242 MemoryBuffer::getFileOrSTDIN(InputFileList[i], InputBuffer))
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000243 return Error("unable to read input: '" + ec.message() + "'");
244
Andrew Kayloradc70562012-10-02 21:18:39 +0000245 // Load the object file
Ahmed Charles96c9d952014-03-05 10:19:29 +0000246 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
Andrew Kayloradc70562012-10-02 21:18:39 +0000247 if (!LoadedObject) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000248 return Error(Dyld.getErrorString());
249 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000250 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000251
Jim Grosbach733d3052011-04-12 21:20:41 +0000252 // Resolve all the relocations we can.
253 Dyld.resolveRelocations();
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000254 // Clear instruction cache before code will be executed.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000255 MemMgr.invalidateInstructionCache();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000256
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000257 // FIXME: Error out if there are unresolved relocations.
258
Jim Grosbachd35159a2011-04-13 15:38:30 +0000259 // Get the address of the entry point (_main by default).
260 void *MainAddress = Dyld.getSymbolAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000261 if (!MainAddress)
Jim Grosbachd35159a2011-04-13 15:38:30 +0000262 return Error("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000263
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000264 // Invalidate the instruction cache for each loaded function.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000265 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
266 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000267 // Make sure the memory is executable.
268 std::string ErrorStr;
269 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
270 if (!sys::Memory::setExecutable(Data, &ErrorStr))
271 return Error("unable to mark function executable: '" + ErrorStr + "'");
272 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000273
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000274 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000275 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000276
277 int (*Main)(int, const char**) =
278 (int(*)(int,const char**)) uintptr_t(MainAddress);
279 const char **Argv = new const char*[2];
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000280 // Use the name of the first input object module as argv[0] for the target.
281 Argv[0] = InputFileList[0].c_str();
Craig Toppere6cb63e2014-04-25 04:24:47 +0000282 Argv[1] = nullptr;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000283 return Main(1, Argv);
284}
285
Lang Hamese1c11382014-06-27 20:20:57 +0000286static int checkAllExpressions(RuntimeDyldChecker &Checker) {
287 for (const auto& CheckerFileName : CheckFiles) {
288 std::unique_ptr<MemoryBuffer> CheckerFileBuf;
289 if (std::error_code EC =
290 MemoryBuffer::getFileOrSTDIN(CheckerFileName, CheckerFileBuf))
291 return Error("unable to read input '" + CheckerFileName + "': " +
292 EC.message());
293
294 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:", CheckerFileBuf.get()))
295 return Error("some checks in '" + CheckerFileName + "' failed");
296 }
297 return 0;
298}
299
300static int linkAndVerify() {
301
302 // Check for missing triple.
303 if (TripleName == "") {
304 llvm::errs() << "Error: -triple required when running in -verify mode.\n";
305 return 1;
306 }
307
308 // Look up the target and build the disassembler.
309 Triple TheTriple(Triple::normalize(TripleName));
310 std::string ErrorStr;
311 const Target *TheTarget =
312 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
313 if (!TheTarget) {
314 llvm::errs() << "Error accessing target '" << TripleName << "': "
315 << ErrorStr << "\n";
316 return 1;
317 }
318 TripleName = TheTriple.getTriple();
319
320 std::unique_ptr<MCSubtargetInfo> STI(
321 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
322 assert(STI && "Unable to create subtarget info!");
323
324 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
325 assert(MRI && "Unable to create target register info!");
326
327 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
328 assert(MAI && "Unable to create target asm info!");
329
330 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
331
332 std::unique_ptr<MCDisassembler> Disassembler(
333 TheTarget->createMCDisassembler(*STI, Ctx));
334 assert(Disassembler && "Unable to create disassembler!");
335
336 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
337
338 std::unique_ptr<MCInstPrinter> InstPrinter(
339 TheTarget->createMCInstPrinter(0, *MAI, *MII, *MRI, *STI));
340
341 // Load any dylibs requested on the command line.
342 loadDylibs();
343
344 // Instantiate a dynamic linker.
345 TrivialMemoryManager MemMgr;
346 RuntimeDyld Dyld(&MemMgr);
347
348 // If we don't have any input files, read from stdin.
349 if (!InputFileList.size())
350 InputFileList.push_back("-");
351 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
352 // Load the input memory buffer.
353 std::unique_ptr<MemoryBuffer> InputBuffer;
354 std::unique_ptr<ObjectImage> LoadedObject;
355 if (std::error_code ec =
356 MemoryBuffer::getFileOrSTDIN(InputFileList[i], InputBuffer))
357 return Error("unable to read input: '" + ec.message() + "'");
358
359 // Load the object file
360 LoadedObject.reset(
361 Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
362 if (!LoadedObject) {
363 return Error(Dyld.getErrorString());
364 }
365 }
366
367 // Resolve all the relocations we can.
368 Dyld.resolveRelocations();
369
370 RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
371 llvm::dbgs());
372 return checkAllExpressions(Checker);
373}
374
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000375int main(int argc, char **argv) {
Alp Toker9f679322013-11-05 09:33:43 +0000376 sys::PrintStackTraceOnErrorSignal();
377 PrettyStackTraceProgram X(argc, argv);
378
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000379 ProgramName = argv[0];
380 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
381
Lang Hamese1c11382014-06-27 20:20:57 +0000382 llvm::InitializeAllTargetInfos();
383 llvm::InitializeAllTargetMCs();
384 llvm::InitializeAllDisassemblers();
385
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000386 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
387
388 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000389 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000390 return executeInput();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000391 case AC_PrintLineInfo:
392 return printLineInfoForInput();
Lang Hamese1c11382014-06-27 20:20:57 +0000393 case AC_Verify:
394 return linkAndVerify();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000395 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000396}