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/DWARF/DIContext.h"
16 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
17 #include "llvm/ExecutionEngine/RuntimeDyld.h"
18 #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDisassembler.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/Object/MachO.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/DynamicLibrary.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/Memory.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/PrettyStackTrace.h"
32 #include "llvm/Support/Signals.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/TargetSelect.h"
35 #include "llvm/Support/raw_ostream.h"
37 #include <system_error>
40 using namespace llvm::object;
42 static cl::list<std::string>
43 InputFileList(cl::Positional, cl::ZeroOrMore,
44 cl::desc("<input file>"));
52 static cl::opt<ActionType>
53 Action(cl::desc("Action to perform:"),
55 cl::values(clEnumValN(AC_Execute, "execute",
56 "Load, link, and execute the inputs."),
57 clEnumValN(AC_PrintLineInfo, "printline",
58 "Load, link, and print line information for each function."),
59 clEnumValN(AC_Verify, "verify",
60 "Load, link and verify the resulting memory image."),
63 static cl::opt<std::string>
65 cl::desc("Function to call as entry point."),
68 static cl::list<std::string>
70 cl::desc("Add library."),
73 static cl::opt<std::string>
74 TripleName("triple", cl::desc("Target triple for disassembler"));
76 static cl::list<std::string>
78 cl::desc("File containing RuntimeDyld verifier checks."),
81 static cl::opt<uint64_t>
82 TargetAddrStart("target-addr-start",
83 cl::desc("For -verify only: start of phony target address "
85 cl::init(4096), // Start at "page 1" - no allocating at "null".
88 static cl::opt<uint64_t>
89 TargetAddrEnd("target-addr-end",
90 cl::desc("For -verify only: end of phony target address range."),
94 static cl::opt<uint64_t>
95 TargetSectionSep("target-section-sep",
96 cl::desc("For -verify only: Separation between sections in "
97 "phony target address space."),
101 static cl::list<std::string>
102 SpecificSectionMappings("map-section",
103 cl::desc("Map a section to a specific address."),
108 // A trivial memory manager that doesn't do anything fancy, just uses the
109 // support library allocation routines directly.
110 class TrivialMemoryManager : public RTDyldMemoryManager {
112 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
113 SmallVector<sys::MemoryBlock, 16> DataMemory;
115 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
117 StringRef SectionName) override;
118 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
119 unsigned SectionID, StringRef SectionName,
120 bool IsReadOnly) override;
122 void *getPointerToNamedFunction(const std::string &Name,
123 bool AbortOnFailure = true) override {
127 bool finalizeMemory(std::string *ErrMsg) override { return false; }
129 // Invalidate instruction cache for sections with execute permissions.
130 // Some platforms with separate data cache and instruction cache require
131 // explicit cache flush, otherwise JIT code manipulations (like resolved
132 // relocations) will get to the data cache but not to the instruction cache.
133 virtual void invalidateInstructionCache();
136 uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
139 StringRef SectionName) {
140 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
141 FunctionMemory.push_back(MB);
142 return (uint8_t*)MB.base();
145 uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
148 StringRef SectionName,
150 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
151 DataMemory.push_back(MB);
152 return (uint8_t*)MB.base();
155 void TrivialMemoryManager::invalidateInstructionCache() {
156 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
157 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
158 FunctionMemory[i].size());
160 for (int i = 0, e = DataMemory.size(); i != e; ++i)
161 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
162 DataMemory[i].size());
165 static const char *ProgramName;
167 static void Message(const char *Type, const Twine &Msg) {
168 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
171 static int Error(const Twine &Msg) {
172 Message("error", Msg);
176 static void loadDylibs() {
177 for (const std::string &Dylib : Dylibs) {
178 if (sys::fs::is_regular_file(Dylib)) {
180 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
181 llvm::errs() << "Error loading '" << Dylib << "': "
184 llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
190 static int printLineInfoForInput() {
191 // Load any dylibs requested on the command line.
194 // If we don't have any input files, read from stdin.
195 if (!InputFileList.size())
196 InputFileList.push_back("-");
197 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
198 // Instantiate a dynamic linker.
199 TrivialMemoryManager MemMgr;
200 RuntimeDyld Dyld(MemMgr, MemMgr);
202 // Load the input memory buffer.
204 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
205 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
206 if (std::error_code EC = InputBuffer.getError())
207 return Error("unable to read input: '" + EC.message() + "'");
209 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
210 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
212 if (std::error_code EC = MaybeObj.getError())
213 return Error("unable to create object file: '" + EC.message() + "'");
215 ObjectFile &Obj = **MaybeObj;
217 // Load the object file
218 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo =
219 Dyld.loadObject(Obj);
222 return Error(Dyld.getErrorString());
224 // Resolve all the relocations we can.
225 Dyld.resolveRelocations();
227 OwningBinary<ObjectFile> DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
229 std::unique_ptr<DIContext> Context(
230 DIContext::getDWARFContext(*DebugObj.getBinary()));
232 // Use symbol info to iterate functions in the object.
233 for (object::symbol_iterator I = DebugObj.getBinary()->symbol_begin(),
234 E = DebugObj.getBinary()->symbol_end();
236 object::SymbolRef::Type SymType;
237 if (I->getType(SymType)) continue;
238 if (SymType == object::SymbolRef::ST_Function) {
242 if (I->getName(Name)) continue;
243 if (I->getAddress(Addr)) continue;
244 if (I->getSize(Size)) continue;
246 outs() << "Function: " << Name << ", Size = " << Size << "\n";
248 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
249 DILineInfoTable::iterator Begin = Lines.begin();
250 DILineInfoTable::iterator End = Lines.end();
251 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
252 outs() << " Line info @ " << It->first - Addr << ": "
253 << It->second.FileName << ", line:" << It->second.Line << "\n";
262 static int executeInput() {
263 // Load any dylibs requested on the command line.
266 // Instantiate a dynamic linker.
267 TrivialMemoryManager MemMgr;
268 RuntimeDyld Dyld(MemMgr, MemMgr);
270 // FIXME: Preserve buffers until resolveRelocations time to work around a bug
271 // in RuntimeDyldELF.
272 // This fixme should be fixed ASAP. This is a very brittle workaround.
273 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
275 // If we don't have any input files, read from stdin.
276 if (!InputFileList.size())
277 InputFileList.push_back("-");
278 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
279 // Load the input memory buffer.
280 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
281 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
282 if (std::error_code EC = InputBuffer.getError())
283 return Error("unable to read input: '" + EC.message() + "'");
284 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
285 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
287 if (std::error_code EC = MaybeObj.getError())
288 return Error("unable to create object file: '" + EC.message() + "'");
290 ObjectFile &Obj = **MaybeObj;
291 InputBuffers.push_back(std::move(*InputBuffer));
293 // Load the object file
294 Dyld.loadObject(Obj);
295 if (Dyld.hasError()) {
296 return Error(Dyld.getErrorString());
300 // Resolve all the relocations we can.
301 Dyld.resolveRelocations();
302 // Clear instruction cache before code will be executed.
303 MemMgr.invalidateInstructionCache();
305 // FIXME: Error out if there are unresolved relocations.
307 // Get the address of the entry point (_main by default).
308 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
310 return Error("no definition for '" + EntryPoint + "'");
312 // Invalidate the instruction cache for each loaded function.
313 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
314 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
315 // Make sure the memory is executable.
316 std::string ErrorStr;
317 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
318 if (!sys::Memory::setExecutable(Data, &ErrorStr))
319 return Error("unable to mark function executable: '" + ErrorStr + "'");
322 // Dispatch to _main().
323 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
325 int (*Main)(int, const char**) =
326 (int(*)(int,const char**)) uintptr_t(MainAddress);
327 const char **Argv = new const char*[2];
328 // Use the name of the first input object module as argv[0] for the target.
329 Argv[0] = InputFileList[0].c_str();
331 return Main(1, Argv);
334 static int checkAllExpressions(RuntimeDyldChecker &Checker) {
335 for (const auto& CheckerFileName : CheckFiles) {
336 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
337 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
338 if (std::error_code EC = CheckerFileBuf.getError())
339 return Error("unable to read input '" + CheckerFileName + "': " +
342 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
343 CheckerFileBuf.get().get()))
344 return Error("some checks in '" + CheckerFileName + "' failed");
349 static std::map<void *, uint64_t>
350 applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
352 std::map<void*, uint64_t> SpecificMappings;
354 for (StringRef Mapping : SpecificSectionMappings) {
356 size_t EqualsIdx = Mapping.find_first_of("=");
357 StringRef SectionIDStr = Mapping.substr(0, EqualsIdx);
358 size_t ComaIdx = Mapping.find_first_of(",");
360 if (ComaIdx == StringRef::npos) {
361 errs() << "Invalid section specification '" << Mapping
362 << "'. Should be '<file name>,<section name>=<addr>'\n";
366 StringRef FileName = SectionIDStr.substr(0, ComaIdx);
367 StringRef SectionName = SectionIDStr.substr(ComaIdx + 1);
370 std::string ErrorMsg;
371 std::tie(OldAddrInt, ErrorMsg) =
372 Checker.getSectionAddr(FileName, SectionName, true);
374 if (ErrorMsg != "") {
379 void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
381 StringRef NewAddrStr = Mapping.substr(EqualsIdx + 1);
384 if (NewAddrStr.getAsInteger(0, NewAddr)) {
385 errs() << "Invalid section address in mapping: " << Mapping << "\n";
389 Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
390 SpecificMappings[OldAddr] = NewAddr;
393 return SpecificMappings;
396 // Scatter sections in all directions!
397 // Remaps section addresses for -verify mode. The following command line options
398 // can be used to customize the layout of the memory within the phony target's
400 // -target-addr-start <s> -- Specify where the phony target addres range starts.
401 // -target-addr-end <e> -- Specify where the phony target address range ends.
402 // -target-section-sep <d> -- Specify how big a gap should be left between the
403 // end of one section and the start of the next.
404 // Defaults to zero. Set to something big
405 // (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
407 static void remapSections(const llvm::Triple &TargetTriple,
408 const TrivialMemoryManager &MemMgr,
409 RuntimeDyldChecker &Checker) {
411 // Set up a work list (section addr/size pairs).
412 typedef std::list<std::pair<void*, uint64_t>> WorklistT;
415 for (const auto& CodeSection : MemMgr.FunctionMemory)
416 Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
417 for (const auto& DataSection : MemMgr.DataMemory)
418 Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
420 // Apply any section-specific mappings that were requested on the command
422 typedef std::map<void*, uint64_t> AppliedMappingsT;
423 AppliedMappingsT AppliedMappings = applySpecificSectionMappings(Checker);
425 // Keep an "already allocated" mapping of section target addresses to sizes.
426 // Sections whose address mappings aren't specified on the command line will
427 // allocated around the explicitly mapped sections while maintaining the
428 // minimum separation.
429 std::map<uint64_t, uint64_t> AlreadyAllocated;
431 // Move the previously applied mappings into the already-allocated map.
432 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
434 WorklistT::iterator Tmp = I;
436 AppliedMappingsT::iterator AI = AppliedMappings.find(Tmp->first);
438 if (AI != AppliedMappings.end()) {
439 AlreadyAllocated[AI->second] = Tmp->second;
444 // If the -target-addr-end option wasn't explicitly passed, then set it to a
445 // sensible default based on the target triple.
446 if (TargetAddrEnd.getNumOccurrences() == 0) {
447 if (TargetTriple.isArch16Bit())
448 TargetAddrEnd = (1ULL << 16) - 1;
449 else if (TargetTriple.isArch32Bit())
450 TargetAddrEnd = (1ULL << 32) - 1;
451 // TargetAddrEnd already has a sensible default for 64-bit systems, so
452 // there's nothing to do in the 64-bit case.
455 // Process any elements remaining in the worklist.
456 while (!Worklist.empty()) {
457 std::pair<void*, uint64_t> CurEntry = Worklist.front();
458 Worklist.pop_front();
460 uint64_t NextSectionAddr = TargetAddrStart;
462 for (const auto &Alloc : AlreadyAllocated)
463 if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
466 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
468 AlreadyAllocated[NextSectionAddr] = CurEntry.second;
469 Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
474 // Load and link the objects specified on the command line, but do not execute
475 // anything. Instead, attach a RuntimeDyldChecker instance and call it to
476 // verify the correctness of the linked memory.
477 static int linkAndVerify() {
479 // Check for missing triple.
480 if (TripleName == "") {
481 llvm::errs() << "Error: -triple required when running in -verify mode.\n";
485 // Look up the target and build the disassembler.
486 Triple TheTriple(Triple::normalize(TripleName));
487 std::string ErrorStr;
488 const Target *TheTarget =
489 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
491 llvm::errs() << "Error accessing target '" << TripleName << "': "
495 TripleName = TheTriple.getTriple();
497 std::unique_ptr<MCSubtargetInfo> STI(
498 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
499 assert(STI && "Unable to create subtarget info!");
501 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
502 assert(MRI && "Unable to create target register info!");
504 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
505 assert(MAI && "Unable to create target asm info!");
507 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
509 std::unique_ptr<MCDisassembler> Disassembler(
510 TheTarget->createMCDisassembler(*STI, Ctx));
511 assert(Disassembler && "Unable to create disassembler!");
513 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
515 std::unique_ptr<MCInstPrinter> InstPrinter(
516 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
518 // Load any dylibs requested on the command line.
521 // Instantiate a dynamic linker.
522 TrivialMemoryManager MemMgr;
523 RuntimeDyld Dyld(MemMgr, MemMgr);
524 Dyld.setProcessAllSections(true);
525 RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
528 // FIXME: Preserve buffers until resolveRelocations time to work around a bug
529 // in RuntimeDyldELF.
530 // This fixme should be fixed ASAP. This is a very brittle workaround.
531 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
533 // If we don't have any input files, read from stdin.
534 if (!InputFileList.size())
535 InputFileList.push_back("-");
536 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
537 // Load the input memory buffer.
538 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
539 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
541 if (std::error_code EC = InputBuffer.getError())
542 return Error("unable to read input: '" + EC.message() + "'");
544 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
545 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
547 if (std::error_code EC = MaybeObj.getError())
548 return Error("unable to create object file: '" + EC.message() + "'");
550 ObjectFile &Obj = **MaybeObj;
551 InputBuffers.push_back(std::move(*InputBuffer));
553 // Load the object file
554 Dyld.loadObject(Obj);
555 if (Dyld.hasError()) {
556 return Error(Dyld.getErrorString());
560 // Re-map the section addresses into the phony target address space.
561 remapSections(TheTriple, MemMgr, Checker);
563 // Resolve all the relocations we can.
564 Dyld.resolveRelocations();
566 // Register EH frames.
567 Dyld.registerEHFrames();
569 int ErrorCode = checkAllExpressions(Checker);
570 if (Dyld.hasError()) {
571 errs() << "RTDyld reported an error applying relocations:\n "
572 << Dyld.getErrorString() << "\n";
579 int main(int argc, char **argv) {
580 sys::PrintStackTraceOnErrorSignal();
581 PrettyStackTraceProgram X(argc, argv);
583 ProgramName = argv[0];
584 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
586 llvm::InitializeAllTargetInfos();
587 llvm::InitializeAllTargetMCs();
588 llvm::InitializeAllDisassemblers();
590 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
594 return executeInput();
595 case AC_PrintLineInfo:
596 return printLineInfoForInput();
598 return linkAndVerify();