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/RuntimeDyld.h"
17 #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDisassembler.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCRegisterInfo.h"
24 #include "llvm/Object/MachO.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/DynamicLibrary.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/Memory.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/Signals.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/TargetSelect.h"
36 #include <system_error>
39 using namespace llvm::object;
41 static cl::list<std::string>
42 InputFileList(cl::Positional, cl::ZeroOrMore,
43 cl::desc("<input file>"));
51 static cl::opt<ActionType>
52 Action(cl::desc("Action to perform:"),
54 cl::values(clEnumValN(AC_Execute, "execute",
55 "Load, link, and execute the inputs."),
56 clEnumValN(AC_PrintLineInfo, "printline",
57 "Load, link, and print line information for each function."),
58 clEnumValN(AC_Verify, "verify",
59 "Load, link and verify the resulting memory image."),
62 static cl::opt<std::string>
64 cl::desc("Function to call as entry point."),
67 static cl::list<std::string>
69 cl::desc("Add library."),
72 static cl::opt<std::string>
73 TripleName("triple", cl::desc("Target triple for disassembler"));
75 static cl::list<std::string>
77 cl::desc("File containing RuntimeDyld verifier checks."),
80 static cl::opt<uint64_t>
81 TargetAddrStart("target-addr-start",
82 cl::desc("For -verify only: start of phony target address "
84 cl::init(4096), // Start at "page 1" - no allocating at "null".
87 static cl::opt<uint64_t>
88 TargetAddrEnd("target-addr-end",
89 cl::desc("For -verify only: end of phony target address range."),
93 static cl::opt<uint64_t>
94 TargetSectionSep("target-section-sep",
95 cl::desc("For -verify only: Separation between sections in "
96 "phony target address space."),
100 static cl::list<std::string>
101 SpecificSectionMappings("map-section",
102 cl::desc("Map a section to a specific address."),
107 // A trivial memory manager that doesn't do anything fancy, just uses the
108 // support library allocation routines directly.
109 class TrivialMemoryManager : public RTDyldMemoryManager {
111 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
112 SmallVector<sys::MemoryBlock, 16> DataMemory;
114 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
116 StringRef SectionName) override;
117 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
118 unsigned SectionID, StringRef SectionName,
119 bool IsReadOnly) override;
121 void *getPointerToNamedFunction(const std::string &Name,
122 bool AbortOnFailure = true) override {
126 bool finalizeMemory(std::string *ErrMsg) override { return false; }
128 // Invalidate instruction cache for sections with execute permissions.
129 // Some platforms with separate data cache and instruction cache require
130 // explicit cache flush, otherwise JIT code manipulations (like resolved
131 // relocations) will get to the data cache but not to the instruction cache.
132 virtual void invalidateInstructionCache();
135 uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
138 StringRef SectionName) {
139 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
140 FunctionMemory.push_back(MB);
141 return (uint8_t*)MB.base();
144 uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
147 StringRef SectionName,
149 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
150 DataMemory.push_back(MB);
151 return (uint8_t*)MB.base();
154 void TrivialMemoryManager::invalidateInstructionCache() {
155 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
156 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
157 FunctionMemory[i].size());
159 for (int i = 0, e = DataMemory.size(); i != e; ++i)
160 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
161 DataMemory[i].size());
164 static const char *ProgramName;
166 static void Message(const char *Type, const Twine &Msg) {
167 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
170 static int Error(const Twine &Msg) {
171 Message("error", Msg);
175 static void loadDylibs() {
176 for (const std::string &Dylib : Dylibs) {
177 if (sys::fs::is_regular_file(Dylib)) {
179 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
180 llvm::errs() << "Error loading '" << Dylib << "': "
183 llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
189 static int printLineInfoForInput() {
190 // Load any dylibs requested on the command line.
193 // If we don't have any input files, read from stdin.
194 if (!InputFileList.size())
195 InputFileList.push_back("-");
196 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
197 // Instantiate a dynamic linker.
198 TrivialMemoryManager MemMgr;
199 RuntimeDyld Dyld(&MemMgr);
201 // Load the input memory buffer.
203 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
204 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
205 if (std::error_code EC = InputBuffer.getError())
206 return Error("unable to read input: '" + EC.message() + "'");
208 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
209 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
211 if (std::error_code EC = MaybeObj.getError())
212 return Error("unable to create object file: '" + EC.message() + "'");
214 ObjectFile &Obj = **MaybeObj;
216 // Load the object file
217 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo =
218 Dyld.loadObject(Obj);
221 return Error(Dyld.getErrorString());
223 // Resolve all the relocations we can.
224 Dyld.resolveRelocations();
226 OwningBinary<ObjectFile> DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
228 std::unique_ptr<DIContext> Context(
229 DIContext::getDWARFContext(*DebugObj.getBinary()));
231 // Use symbol info to iterate functions in the object.
232 for (object::symbol_iterator I = DebugObj.getBinary()->symbol_begin(),
233 E = DebugObj.getBinary()->symbol_end();
235 object::SymbolRef::Type SymType;
236 if (I->getType(SymType)) continue;
237 if (SymType == object::SymbolRef::ST_Function) {
241 if (I->getName(Name)) continue;
242 if (I->getAddress(Addr)) continue;
243 if (I->getSize(Size)) continue;
245 outs() << "Function: " << Name << ", Size = " << Size << "\n";
247 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
248 DILineInfoTable::iterator Begin = Lines.begin();
249 DILineInfoTable::iterator End = Lines.end();
250 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
251 outs() << " Line info @ " << It->first - Addr << ": "
252 << It->second.FileName << ", line:" << It->second.Line << "\n";
261 static int executeInput() {
262 // Load any dylibs requested on the command line.
265 // Instantiate a dynamic linker.
266 TrivialMemoryManager MemMgr;
267 RuntimeDyld Dyld(&MemMgr);
269 // If we don't have any input files, read from stdin.
270 if (!InputFileList.size())
271 InputFileList.push_back("-");
272 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
273 // Load the input memory buffer.
274 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
275 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
276 if (std::error_code EC = InputBuffer.getError())
277 return Error("unable to read input: '" + EC.message() + "'");
278 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
279 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
281 if (std::error_code EC = MaybeObj.getError())
282 return Error("unable to create object file: '" + EC.message() + "'");
284 ObjectFile &Obj = **MaybeObj;
286 // Load the object file
287 Dyld.loadObject(Obj);
288 if (Dyld.hasError()) {
289 return Error(Dyld.getErrorString());
293 // Resolve all the relocations we can.
294 Dyld.resolveRelocations();
295 // Clear instruction cache before code will be executed.
296 MemMgr.invalidateInstructionCache();
298 // FIXME: Error out if there are unresolved relocations.
300 // Get the address of the entry point (_main by default).
301 void *MainAddress = Dyld.getSymbolAddress(EntryPoint);
303 return Error("no definition for '" + EntryPoint + "'");
305 // Invalidate the instruction cache for each loaded function.
306 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
307 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
308 // Make sure the memory is executable.
309 std::string ErrorStr;
310 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
311 if (!sys::Memory::setExecutable(Data, &ErrorStr))
312 return Error("unable to mark function executable: '" + ErrorStr + "'");
315 // Dispatch to _main().
316 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
318 int (*Main)(int, const char**) =
319 (int(*)(int,const char**)) uintptr_t(MainAddress);
320 const char **Argv = new const char*[2];
321 // Use the name of the first input object module as argv[0] for the target.
322 Argv[0] = InputFileList[0].c_str();
324 return Main(1, Argv);
327 static int checkAllExpressions(RuntimeDyldChecker &Checker) {
328 for (const auto& CheckerFileName : CheckFiles) {
329 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
330 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
331 if (std::error_code EC = CheckerFileBuf.getError())
332 return Error("unable to read input '" + CheckerFileName + "': " +
335 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
336 CheckerFileBuf.get().get()))
337 return Error("some checks in '" + CheckerFileName + "' failed");
342 std::map<void*, uint64_t>
343 applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
345 std::map<void*, uint64_t> SpecificMappings;
347 for (StringRef Mapping : SpecificSectionMappings) {
349 size_t EqualsIdx = Mapping.find_first_of("=");
350 StringRef SectionIDStr = Mapping.substr(0, EqualsIdx);
351 size_t ComaIdx = Mapping.find_first_of(",");
353 if (ComaIdx == StringRef::npos) {
354 errs() << "Invalid section specification '" << Mapping
355 << "'. Should be '<file name>,<section name>=<addr>'\n";
359 StringRef FileName = SectionIDStr.substr(0, ComaIdx);
360 StringRef SectionName = SectionIDStr.substr(ComaIdx + 1);
363 std::string ErrorMsg;
364 std::tie(OldAddrInt, ErrorMsg) =
365 Checker.getSectionAddr(FileName, SectionName, true);
367 if (ErrorMsg != "") {
372 void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
374 StringRef NewAddrStr = Mapping.substr(EqualsIdx + 1);
377 if (NewAddrStr.getAsInteger(0, NewAddr)) {
378 errs() << "Invalid section address in mapping: " << Mapping << "\n";
382 Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
383 SpecificMappings[OldAddr] = NewAddr;
386 return SpecificMappings;
389 // Scatter sections in all directions!
390 // Remaps section addresses for -verify mode. The following command line options
391 // can be used to customize the layout of the memory within the phony target's
393 // -target-addr-start <s> -- Specify where the phony target addres range starts.
394 // -target-addr-end <e> -- Specify where the phony target address range ends.
395 // -target-section-sep <d> -- Specify how big a gap should be left between the
396 // end of one section and the start of the next.
397 // Defaults to zero. Set to something big
398 // (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
400 void remapSections(const llvm::Triple &TargetTriple,
401 const TrivialMemoryManager &MemMgr,
402 RuntimeDyldChecker &Checker) {
404 // Set up a work list (section addr/size pairs).
405 typedef std::list<std::pair<void*, uint64_t>> WorklistT;
408 for (const auto& CodeSection : MemMgr.FunctionMemory)
409 Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
410 for (const auto& DataSection : MemMgr.DataMemory)
411 Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
413 // Apply any section-specific mappings that were requested on the command
415 typedef std::map<void*, uint64_t> AppliedMappingsT;
416 AppliedMappingsT AppliedMappings = applySpecificSectionMappings(Checker);
418 // Keep an "already allocated" mapping of section target addresses to sizes.
419 // Sections whose address mappings aren't specified on the command line will
420 // allocated around the explicitly mapped sections while maintaining the
421 // minimum separation.
422 std::map<uint64_t, uint64_t> AlreadyAllocated;
424 // Move the previously applied mappings into the already-allocated map.
425 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
427 WorklistT::iterator Tmp = I;
429 AppliedMappingsT::iterator AI = AppliedMappings.find(Tmp->first);
431 if (AI != AppliedMappings.end()) {
432 AlreadyAllocated[AI->second] = Tmp->second;
437 // If the -target-addr-end option wasn't explicitly passed, then set it to a
438 // sensible default based on the target triple.
439 if (TargetAddrEnd.getNumOccurrences() == 0) {
440 if (TargetTriple.isArch16Bit())
441 TargetAddrEnd = (1ULL << 16) - 1;
442 else if (TargetTriple.isArch32Bit())
443 TargetAddrEnd = (1ULL << 32) - 1;
444 // TargetAddrEnd already has a sensible default for 64-bit systems, so
445 // there's nothing to do in the 64-bit case.
448 // Process any elements remaining in the worklist.
449 while (!Worklist.empty()) {
450 std::pair<void*, uint64_t> CurEntry = Worklist.front();
451 Worklist.pop_front();
453 uint64_t NextSectionAddr = TargetAddrStart;
455 for (const auto &Alloc : AlreadyAllocated)
456 if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
459 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
461 AlreadyAllocated[NextSectionAddr] = CurEntry.second;
462 Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
467 // Load and link the objects specified on the command line, but do not execute
468 // anything. Instead, attach a RuntimeDyldChecker instance and call it to
469 // verify the correctness of the linked memory.
470 static int linkAndVerify() {
472 // Check for missing triple.
473 if (TripleName == "") {
474 llvm::errs() << "Error: -triple required when running in -verify mode.\n";
478 // Look up the target and build the disassembler.
479 Triple TheTriple(Triple::normalize(TripleName));
480 std::string ErrorStr;
481 const Target *TheTarget =
482 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
484 llvm::errs() << "Error accessing target '" << TripleName << "': "
488 TripleName = TheTriple.getTriple();
490 std::unique_ptr<MCSubtargetInfo> STI(
491 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
492 assert(STI && "Unable to create subtarget info!");
494 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
495 assert(MRI && "Unable to create target register info!");
497 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
498 assert(MAI && "Unable to create target asm info!");
500 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
502 std::unique_ptr<MCDisassembler> Disassembler(
503 TheTarget->createMCDisassembler(*STI, Ctx));
504 assert(Disassembler && "Unable to create disassembler!");
506 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
508 std::unique_ptr<MCInstPrinter> InstPrinter(
509 TheTarget->createMCInstPrinter(0, *MAI, *MII, *MRI, *STI));
511 // Load any dylibs requested on the command line.
514 // Instantiate a dynamic linker.
515 TrivialMemoryManager MemMgr;
516 RuntimeDyld Dyld(&MemMgr);
517 Dyld.setProcessAllSections(true);
518 RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
521 // If we don't have any input files, read from stdin.
522 if (!InputFileList.size())
523 InputFileList.push_back("-");
524 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
525 // Load the input memory buffer.
526 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
527 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
529 if (std::error_code EC = InputBuffer.getError())
530 return Error("unable to read input: '" + EC.message() + "'");
532 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
533 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
535 if (std::error_code EC = MaybeObj.getError())
536 return Error("unable to create object file: '" + EC.message() + "'");
538 ObjectFile &Obj = **MaybeObj;
540 // Load the object file
541 Dyld.loadObject(Obj);
542 if (Dyld.hasError()) {
543 return Error(Dyld.getErrorString());
547 // Re-map the section addresses into the phony target address space.
548 remapSections(TheTriple, MemMgr, Checker);
550 // Resolve all the relocations we can.
551 Dyld.resolveRelocations();
553 // Register EH frames.
554 Dyld.registerEHFrames();
556 int ErrorCode = checkAllExpressions(Checker);
557 if (Dyld.hasError()) {
558 errs() << "RTDyld reported an error applying relocations:\n "
559 << Dyld.getErrorString() << "\n";
566 int main(int argc, char **argv) {
567 sys::PrintStackTraceOnErrorSignal();
568 PrettyStackTraceProgram X(argc, argv);
570 ProgramName = argv[0];
571 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
573 llvm::InitializeAllTargetInfos();
574 llvm::InitializeAllTargetMCs();
575 llvm::InitializeAllDisassemblers();
577 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
581 return executeInput();
582 case AC_PrintLineInfo:
583 return printLineInfoForInput();
585 return linkAndVerify();