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/DebugInfo/DWARF/DWARFContext.h"
17 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
18 #include "llvm/ExecutionEngine/RuntimeDyld.h"
19 #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/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCRegisterInfo.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/Object/MachO.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/DynamicLibrary.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/Memory.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/PrettyStackTrace.h"
34 #include "llvm/Support/Signals.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/TargetSelect.h"
37 #include "llvm/Support/raw_ostream.h"
39 #include <system_error>
42 using namespace llvm::object;
44 static cl::list<std::string>
45 InputFileList(cl::Positional, cl::ZeroOrMore,
46 cl::desc("<input file>"));
51 AC_PrintDebugLineInfo,
55 static cl::opt<ActionType>
56 Action(cl::desc("Action to perform:"),
58 cl::values(clEnumValN(AC_Execute, "execute",
59 "Load, link, and execute the inputs."),
60 clEnumValN(AC_PrintLineInfo, "printline",
61 "Load, link, and print line information for each function."),
62 clEnumValN(AC_PrintDebugLineInfo, "printdebugline",
63 "Load, link, and print line information for each function using the debug object"),
64 clEnumValN(AC_Verify, "verify",
65 "Load, link and verify the resulting memory image."),
68 static cl::opt<std::string>
70 cl::desc("Function to call as entry point."),
73 static cl::list<std::string>
75 cl::desc("Add library."),
78 static cl::opt<std::string>
79 TripleName("triple", cl::desc("Target triple for disassembler"));
81 static cl::list<std::string>
83 cl::desc("File containing RuntimeDyld verifier checks."),
86 static cl::opt<uint64_t>
87 TargetAddrStart("target-addr-start",
88 cl::desc("For -verify only: start of phony target address "
90 cl::init(4096), // Start at "page 1" - no allocating at "null".
93 static cl::opt<uint64_t>
94 TargetAddrEnd("target-addr-end",
95 cl::desc("For -verify only: end of phony target address range."),
99 static cl::opt<uint64_t>
100 TargetSectionSep("target-section-sep",
101 cl::desc("For -verify only: Separation between sections in "
102 "phony target address space."),
106 static cl::list<std::string>
107 SpecificSectionMappings("map-section",
108 cl::desc("Map a section to a specific address."),
113 // A trivial memory manager that doesn't do anything fancy, just uses the
114 // support library allocation routines directly.
115 class TrivialMemoryManager : public RTDyldMemoryManager {
117 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
118 SmallVector<sys::MemoryBlock, 16> DataMemory;
120 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
122 StringRef SectionName) override;
123 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
124 unsigned SectionID, StringRef SectionName,
125 bool IsReadOnly) override;
127 void *getPointerToNamedFunction(const std::string &Name,
128 bool AbortOnFailure = true) override {
132 bool finalizeMemory(std::string *ErrMsg) override { return false; }
134 // Invalidate instruction cache for sections with execute permissions.
135 // Some platforms with separate data cache and instruction cache require
136 // explicit cache flush, otherwise JIT code manipulations (like resolved
137 // relocations) will get to the data cache but not to the instruction cache.
138 virtual void invalidateInstructionCache();
141 uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
144 StringRef SectionName) {
145 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
146 FunctionMemory.push_back(MB);
147 return (uint8_t*)MB.base();
150 uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
153 StringRef SectionName,
155 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
156 DataMemory.push_back(MB);
157 return (uint8_t*)MB.base();
160 void TrivialMemoryManager::invalidateInstructionCache() {
161 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
162 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
163 FunctionMemory[i].size());
165 for (int i = 0, e = DataMemory.size(); i != e; ++i)
166 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
167 DataMemory[i].size());
170 static const char *ProgramName;
172 static void Message(const char *Type, const Twine &Msg) {
173 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
176 static int Error(const Twine &Msg) {
177 Message("error", Msg);
181 static void loadDylibs() {
182 for (const std::string &Dylib : Dylibs) {
183 if (sys::fs::is_regular_file(Dylib)) {
185 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
186 llvm::errs() << "Error loading '" << Dylib << "': "
189 llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
195 static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
196 assert(LoadObjects || !UseDebugObj);
198 // Load any dylibs requested on the command line.
201 // If we don't have any input files, read from stdin.
202 if (!InputFileList.size())
203 InputFileList.push_back("-");
204 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
205 // Instantiate a dynamic linker.
206 TrivialMemoryManager MemMgr;
207 RuntimeDyld Dyld(MemMgr, MemMgr);
209 // Load the input memory buffer.
211 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
212 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
213 if (std::error_code EC = InputBuffer.getError())
214 return Error("unable to read input: '" + EC.message() + "'");
216 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
217 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
219 if (std::error_code EC = MaybeObj.getError())
220 return Error("unable to create object file: '" + EC.message() + "'");
222 ObjectFile &Obj = **MaybeObj;
224 OwningBinary<ObjectFile> DebugObj;
225 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
226 ObjectFile *SymbolObj = &Obj;
228 // Load the object file
230 Dyld.loadObject(Obj);
233 return Error(Dyld.getErrorString());
235 // Resolve all the relocations we can.
236 Dyld.resolveRelocations();
239 DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
240 SymbolObj = DebugObj.getBinary();
244 std::unique_ptr<DIContext> Context(
245 new DWARFContextInMemory(*SymbolObj,LoadedObjInfo.get()));
247 // Use symbol info to iterate functions in the object.
248 for (object::symbol_iterator I = SymbolObj->symbol_begin(),
249 E = SymbolObj->symbol_end();
251 object::SymbolRef::Type SymType;
252 if (I->getType(SymType)) continue;
253 if (SymType == object::SymbolRef::ST_Function) {
257 if (I->getName(Name)) continue;
258 if (I->getAddress(Addr)) continue;
259 if (I->getSize(Size)) continue;
261 // If we're not using the debug object, compute the address of the
262 // symbol in memory (rather than that in the unrelocated object file)
263 // and use that to query the DWARFContext.
264 if (!UseDebugObj && LoadObjects) {
265 object::section_iterator Sec(SymbolObj->section_end());
268 Sec->getName(SecName);
269 uint64_t SectionLoadAddress =
270 LoadedObjInfo->getSectionLoadAddress(SecName);
271 if (SectionLoadAddress != 0)
272 Addr += SectionLoadAddress - Sec->getAddress();
275 outs() << "Function: " << Name << ", Size = " << Size << ", Addr = " << Addr << "\n";
277 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
278 DILineInfoTable::iterator Begin = Lines.begin();
279 DILineInfoTable::iterator End = Lines.end();
280 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
281 outs() << " Line info @ " << It->first - Addr << ": "
282 << It->second.FileName << ", line:" << It->second.Line << "\n";
291 static int executeInput() {
292 // Load any dylibs requested on the command line.
295 // Instantiate a dynamic linker.
296 TrivialMemoryManager MemMgr;
297 RuntimeDyld Dyld(MemMgr, MemMgr);
299 // FIXME: Preserve buffers until resolveRelocations time to work around a bug
300 // in RuntimeDyldELF.
301 // This fixme should be fixed ASAP. This is a very brittle workaround.
302 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
304 // If we don't have any input files, read from stdin.
305 if (!InputFileList.size())
306 InputFileList.push_back("-");
307 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
308 // Load the input memory buffer.
309 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
310 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
311 if (std::error_code EC = InputBuffer.getError())
312 return Error("unable to read input: '" + EC.message() + "'");
313 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
314 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
316 if (std::error_code EC = MaybeObj.getError())
317 return Error("unable to create object file: '" + EC.message() + "'");
319 ObjectFile &Obj = **MaybeObj;
320 InputBuffers.push_back(std::move(*InputBuffer));
322 // Load the object file
323 Dyld.loadObject(Obj);
324 if (Dyld.hasError()) {
325 return Error(Dyld.getErrorString());
329 // Resolve all the relocations we can.
330 Dyld.resolveRelocations();
331 // Clear instruction cache before code will be executed.
332 MemMgr.invalidateInstructionCache();
334 // FIXME: Error out if there are unresolved relocations.
336 // Get the address of the entry point (_main by default).
337 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
339 return Error("no definition for '" + EntryPoint + "'");
341 // Invalidate the instruction cache for each loaded function.
342 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
343 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
344 // Make sure the memory is executable.
345 std::string ErrorStr;
346 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
347 if (!sys::Memory::setExecutable(Data, &ErrorStr))
348 return Error("unable to mark function executable: '" + ErrorStr + "'");
351 // Dispatch to _main().
352 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
354 int (*Main)(int, const char**) =
355 (int(*)(int,const char**)) uintptr_t(MainAddress);
356 const char **Argv = new const char*[2];
357 // Use the name of the first input object module as argv[0] for the target.
358 Argv[0] = InputFileList[0].c_str();
360 return Main(1, Argv);
363 static int checkAllExpressions(RuntimeDyldChecker &Checker) {
364 for (const auto& CheckerFileName : CheckFiles) {
365 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
366 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
367 if (std::error_code EC = CheckerFileBuf.getError())
368 return Error("unable to read input '" + CheckerFileName + "': " +
371 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
372 CheckerFileBuf.get().get()))
373 return Error("some checks in '" + CheckerFileName + "' failed");
378 static std::map<void *, uint64_t>
379 applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
381 std::map<void*, uint64_t> SpecificMappings;
383 for (StringRef Mapping : SpecificSectionMappings) {
385 size_t EqualsIdx = Mapping.find_first_of("=");
386 StringRef SectionIDStr = Mapping.substr(0, EqualsIdx);
387 size_t ComaIdx = Mapping.find_first_of(",");
389 if (ComaIdx == StringRef::npos) {
390 errs() << "Invalid section specification '" << Mapping
391 << "'. Should be '<file name>,<section name>=<addr>'\n";
395 StringRef FileName = SectionIDStr.substr(0, ComaIdx);
396 StringRef SectionName = SectionIDStr.substr(ComaIdx + 1);
399 std::string ErrorMsg;
400 std::tie(OldAddrInt, ErrorMsg) =
401 Checker.getSectionAddr(FileName, SectionName, true);
403 if (ErrorMsg != "") {
408 void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
410 StringRef NewAddrStr = Mapping.substr(EqualsIdx + 1);
413 if (NewAddrStr.getAsInteger(0, NewAddr)) {
414 errs() << "Invalid section address in mapping: " << Mapping << "\n";
418 Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
419 SpecificMappings[OldAddr] = NewAddr;
422 return SpecificMappings;
425 // Scatter sections in all directions!
426 // Remaps section addresses for -verify mode. The following command line options
427 // can be used to customize the layout of the memory within the phony target's
429 // -target-addr-start <s> -- Specify where the phony target addres range starts.
430 // -target-addr-end <e> -- Specify where the phony target address range ends.
431 // -target-section-sep <d> -- Specify how big a gap should be left between the
432 // end of one section and the start of the next.
433 // Defaults to zero. Set to something big
434 // (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
436 static void remapSections(const llvm::Triple &TargetTriple,
437 const TrivialMemoryManager &MemMgr,
438 RuntimeDyldChecker &Checker) {
440 // Set up a work list (section addr/size pairs).
441 typedef std::list<std::pair<void*, uint64_t>> WorklistT;
444 for (const auto& CodeSection : MemMgr.FunctionMemory)
445 Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
446 for (const auto& DataSection : MemMgr.DataMemory)
447 Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
449 // Apply any section-specific mappings that were requested on the command
451 typedef std::map<void*, uint64_t> AppliedMappingsT;
452 AppliedMappingsT AppliedMappings = applySpecificSectionMappings(Checker);
454 // Keep an "already allocated" mapping of section target addresses to sizes.
455 // Sections whose address mappings aren't specified on the command line will
456 // allocated around the explicitly mapped sections while maintaining the
457 // minimum separation.
458 std::map<uint64_t, uint64_t> AlreadyAllocated;
460 // Move the previously applied mappings into the already-allocated map.
461 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
463 WorklistT::iterator Tmp = I;
465 AppliedMappingsT::iterator AI = AppliedMappings.find(Tmp->first);
467 if (AI != AppliedMappings.end()) {
468 AlreadyAllocated[AI->second] = Tmp->second;
473 // If the -target-addr-end option wasn't explicitly passed, then set it to a
474 // sensible default based on the target triple.
475 if (TargetAddrEnd.getNumOccurrences() == 0) {
476 if (TargetTriple.isArch16Bit())
477 TargetAddrEnd = (1ULL << 16) - 1;
478 else if (TargetTriple.isArch32Bit())
479 TargetAddrEnd = (1ULL << 32) - 1;
480 // TargetAddrEnd already has a sensible default for 64-bit systems, so
481 // there's nothing to do in the 64-bit case.
484 // Process any elements remaining in the worklist.
485 while (!Worklist.empty()) {
486 std::pair<void*, uint64_t> CurEntry = Worklist.front();
487 Worklist.pop_front();
489 uint64_t NextSectionAddr = TargetAddrStart;
491 for (const auto &Alloc : AlreadyAllocated)
492 if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
495 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
497 AlreadyAllocated[NextSectionAddr] = CurEntry.second;
498 Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
503 // Load and link the objects specified on the command line, but do not execute
504 // anything. Instead, attach a RuntimeDyldChecker instance and call it to
505 // verify the correctness of the linked memory.
506 static int linkAndVerify() {
508 // Check for missing triple.
509 if (TripleName == "") {
510 llvm::errs() << "Error: -triple required when running in -verify mode.\n";
514 // Look up the target and build the disassembler.
515 Triple TheTriple(Triple::normalize(TripleName));
516 std::string ErrorStr;
517 const Target *TheTarget =
518 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
520 llvm::errs() << "Error accessing target '" << TripleName << "': "
524 TripleName = TheTriple.getTriple();
526 std::unique_ptr<MCSubtargetInfo> STI(
527 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
528 assert(STI && "Unable to create subtarget info!");
530 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
531 assert(MRI && "Unable to create target register info!");
533 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
534 assert(MAI && "Unable to create target asm info!");
536 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
538 std::unique_ptr<MCDisassembler> Disassembler(
539 TheTarget->createMCDisassembler(*STI, Ctx));
540 assert(Disassembler && "Unable to create disassembler!");
542 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
544 std::unique_ptr<MCInstPrinter> InstPrinter(
545 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
547 // Load any dylibs requested on the command line.
550 // Instantiate a dynamic linker.
551 TrivialMemoryManager MemMgr;
552 RuntimeDyld Dyld(MemMgr, MemMgr);
553 Dyld.setProcessAllSections(true);
554 RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
557 // FIXME: Preserve buffers until resolveRelocations time to work around a bug
558 // in RuntimeDyldELF.
559 // This fixme should be fixed ASAP. This is a very brittle workaround.
560 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
562 // If we don't have any input files, read from stdin.
563 if (!InputFileList.size())
564 InputFileList.push_back("-");
565 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
566 // Load the input memory buffer.
567 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
568 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
570 if (std::error_code EC = InputBuffer.getError())
571 return Error("unable to read input: '" + EC.message() + "'");
573 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
574 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
576 if (std::error_code EC = MaybeObj.getError())
577 return Error("unable to create object file: '" + EC.message() + "'");
579 ObjectFile &Obj = **MaybeObj;
580 InputBuffers.push_back(std::move(*InputBuffer));
582 // Load the object file
583 Dyld.loadObject(Obj);
584 if (Dyld.hasError()) {
585 return Error(Dyld.getErrorString());
589 // Re-map the section addresses into the phony target address space.
590 remapSections(TheTriple, MemMgr, Checker);
592 // Resolve all the relocations we can.
593 Dyld.resolveRelocations();
595 // Register EH frames.
596 Dyld.registerEHFrames();
598 int ErrorCode = checkAllExpressions(Checker);
599 if (Dyld.hasError()) {
600 errs() << "RTDyld reported an error applying relocations:\n "
601 << Dyld.getErrorString() << "\n";
608 int main(int argc, char **argv) {
609 sys::PrintStackTraceOnErrorSignal();
610 PrettyStackTraceProgram X(argc, argv);
612 ProgramName = argv[0];
613 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
615 llvm::InitializeAllTargetInfos();
616 llvm::InitializeAllTargetMCs();
617 llvm::InitializeAllDisassemblers();
619 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
623 return executeInput();
624 case AC_PrintDebugLineInfo:
625 return printLineInfoForInput(true,true);
626 case AC_PrintLineInfo:
627 return printLineInfoForInput(true,false);
629 return linkAndVerify();