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/Object/SymbolSize.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/DynamicLibrary.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/Memory.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/raw_ostream.h"
40 #include <system_error>
43 using namespace llvm::object;
45 static cl::list<std::string>
46 InputFileList(cl::Positional, cl::ZeroOrMore,
47 cl::desc("<input file>"));
51 AC_PrintObjectLineInfo,
53 AC_PrintDebugLineInfo,
57 static cl::opt<ActionType>
58 Action(cl::desc("Action to perform:"),
60 cl::values(clEnumValN(AC_Execute, "execute",
61 "Load, link, and execute the inputs."),
62 clEnumValN(AC_PrintLineInfo, "printline",
63 "Load, link, and print line information for each function."),
64 clEnumValN(AC_PrintDebugLineInfo, "printdebugline",
65 "Load, link, and print line information for each function using the debug object"),
66 clEnumValN(AC_PrintObjectLineInfo, "printobjline",
67 "Like -printlineinfo but does not load the object first"),
68 clEnumValN(AC_Verify, "verify",
69 "Load, link and verify the resulting memory image."),
72 static cl::opt<std::string>
74 cl::desc("Function to call as entry point."),
77 static cl::list<std::string>
79 cl::desc("Add library."),
82 static cl::opt<std::string>
83 TripleName("triple", cl::desc("Target triple for disassembler"));
85 static cl::opt<std::string>
87 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
88 cl::value_desc("cpu-name"),
91 static cl::list<std::string>
93 cl::desc("File containing RuntimeDyld verifier checks."),
96 static cl::opt<uint64_t>
97 TargetAddrStart("target-addr-start",
98 cl::desc("For -verify only: start of phony target address "
100 cl::init(4096), // Start at "page 1" - no allocating at "null".
103 static cl::opt<uint64_t>
104 TargetAddrEnd("target-addr-end",
105 cl::desc("For -verify only: end of phony target address range."),
109 static cl::opt<uint64_t>
110 TargetSectionSep("target-section-sep",
111 cl::desc("For -verify only: Separation between sections in "
112 "phony target address space."),
116 static cl::list<std::string>
117 SpecificSectionMappings("map-section",
118 cl::desc("Map a section to a specific address."),
123 // A trivial memory manager that doesn't do anything fancy, just uses the
124 // support library allocation routines directly.
125 class TrivialMemoryManager : public RTDyldMemoryManager {
127 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
128 SmallVector<sys::MemoryBlock, 16> DataMemory;
130 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
132 StringRef SectionName) override;
133 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
134 unsigned SectionID, StringRef SectionName,
135 bool IsReadOnly) override;
137 void *getPointerToNamedFunction(const std::string &Name,
138 bool AbortOnFailure = true) override {
142 bool finalizeMemory(std::string *ErrMsg) override { return false; }
144 // Invalidate instruction cache for sections with execute permissions.
145 // Some platforms with separate data cache and instruction cache require
146 // explicit cache flush, otherwise JIT code manipulations (like resolved
147 // relocations) will get to the data cache but not to the instruction cache.
148 virtual void invalidateInstructionCache();
150 void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
151 size_t Size) override {}
152 void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr,
153 size_t Size) override {}
156 uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
159 StringRef SectionName) {
160 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
161 FunctionMemory.push_back(MB);
162 return (uint8_t*)MB.base();
165 uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
168 StringRef SectionName,
170 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
171 DataMemory.push_back(MB);
172 return (uint8_t*)MB.base();
175 void TrivialMemoryManager::invalidateInstructionCache() {
176 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
177 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
178 FunctionMemory[i].size());
180 for (int i = 0, e = DataMemory.size(); i != e; ++i)
181 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
182 DataMemory[i].size());
185 static const char *ProgramName;
187 static void Message(const char *Type, const Twine &Msg) {
188 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
191 static int Error(const Twine &Msg) {
192 Message("error", Msg);
196 static void loadDylibs() {
197 for (const std::string &Dylib : Dylibs) {
198 if (sys::fs::is_regular_file(Dylib)) {
200 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
201 llvm::errs() << "Error loading '" << Dylib << "': "
204 llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
210 static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
211 assert(LoadObjects || !UseDebugObj);
213 // Load any dylibs requested on the command line.
216 // If we don't have any input files, read from stdin.
217 if (!InputFileList.size())
218 InputFileList.push_back("-");
219 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
220 // Instantiate a dynamic linker.
221 TrivialMemoryManager MemMgr;
222 RuntimeDyld Dyld(MemMgr, MemMgr);
224 // Load the input memory buffer.
226 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
227 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
228 if (std::error_code EC = InputBuffer.getError())
229 return Error("unable to read input: '" + EC.message() + "'");
231 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
232 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
234 if (std::error_code EC = MaybeObj.getError())
235 return Error("unable to create object file: '" + EC.message() + "'");
237 ObjectFile &Obj = **MaybeObj;
239 OwningBinary<ObjectFile> DebugObj;
240 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
241 ObjectFile *SymbolObj = &Obj;
243 // Load the object file
245 Dyld.loadObject(Obj);
248 return Error(Dyld.getErrorString());
250 // Resolve all the relocations we can.
251 Dyld.resolveRelocations();
254 DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
255 SymbolObj = DebugObj.getBinary();
259 std::unique_ptr<DIContext> Context(
260 new DWARFContextInMemory(*SymbolObj,LoadedObjInfo.get()));
262 std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
263 object::computeSymbolSizes(*SymbolObj);
265 // Use symbol info to iterate functions in the object.
266 for (const auto &P : SymAddr) {
267 object::SymbolRef Sym = P.first;
268 if (Sym.getType() == object::SymbolRef::ST_Function) {
271 if (Sym.getName(Name))
273 if (Sym.getAddress(Addr))
276 uint64_t Size = P.second;
277 // If we're not using the debug object, compute the address of the
278 // symbol in memory (rather than that in the unrelocated object file)
279 // and use that to query the DWARFContext.
280 if (!UseDebugObj && LoadObjects) {
281 object::section_iterator Sec(SymbolObj->section_end());
284 Sec->getName(SecName);
285 uint64_t SectionLoadAddress =
286 LoadedObjInfo->getSectionLoadAddress(SecName);
287 if (SectionLoadAddress != 0)
288 Addr += SectionLoadAddress - Sec->getAddress();
291 outs() << "Function: " << Name << ", Size = " << Size << ", Addr = " << Addr << "\n";
293 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
294 DILineInfoTable::iterator Begin = Lines.begin();
295 DILineInfoTable::iterator End = Lines.end();
296 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
297 outs() << " Line info @ " << It->first - Addr << ": "
298 << It->second.FileName << ", line:" << It->second.Line << "\n";
307 static int executeInput() {
308 // Load any dylibs requested on the command line.
311 // Instantiate a dynamic linker.
312 TrivialMemoryManager MemMgr;
313 RuntimeDyld Dyld(MemMgr, MemMgr);
315 // FIXME: Preserve buffers until resolveRelocations time to work around a bug
316 // in RuntimeDyldELF.
317 // This fixme should be fixed ASAP. This is a very brittle workaround.
318 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
320 // If we don't have any input files, read from stdin.
321 if (!InputFileList.size())
322 InputFileList.push_back("-");
323 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
324 // Load the input memory buffer.
325 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
326 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
327 if (std::error_code EC = InputBuffer.getError())
328 return Error("unable to read input: '" + EC.message() + "'");
329 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
330 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
332 if (std::error_code EC = MaybeObj.getError())
333 return Error("unable to create object file: '" + EC.message() + "'");
335 ObjectFile &Obj = **MaybeObj;
336 InputBuffers.push_back(std::move(*InputBuffer));
338 // Load the object file
339 Dyld.loadObject(Obj);
340 if (Dyld.hasError()) {
341 return Error(Dyld.getErrorString());
345 // Resolve all the relocations we can.
346 Dyld.resolveRelocations();
347 // Clear instruction cache before code will be executed.
348 MemMgr.invalidateInstructionCache();
350 // FIXME: Error out if there are unresolved relocations.
352 // Get the address of the entry point (_main by default).
353 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
355 return Error("no definition for '" + EntryPoint + "'");
357 // Invalidate the instruction cache for each loaded function.
358 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
359 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
360 // Make sure the memory is executable.
361 std::string ErrorStr;
362 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
363 if (!sys::Memory::setExecutable(Data, &ErrorStr))
364 return Error("unable to mark function executable: '" + ErrorStr + "'");
367 // Dispatch to _main().
368 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
370 int (*Main)(int, const char**) =
371 (int(*)(int,const char**)) uintptr_t(MainAddress);
372 const char **Argv = new const char*[2];
373 // Use the name of the first input object module as argv[0] for the target.
374 Argv[0] = InputFileList[0].c_str();
376 return Main(1, Argv);
379 static int checkAllExpressions(RuntimeDyldChecker &Checker) {
380 for (const auto& CheckerFileName : CheckFiles) {
381 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
382 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
383 if (std::error_code EC = CheckerFileBuf.getError())
384 return Error("unable to read input '" + CheckerFileName + "': " +
387 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
388 CheckerFileBuf.get().get()))
389 return Error("some checks in '" + CheckerFileName + "' failed");
394 static std::map<void *, uint64_t>
395 applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
397 std::map<void*, uint64_t> SpecificMappings;
399 for (StringRef Mapping : SpecificSectionMappings) {
401 size_t EqualsIdx = Mapping.find_first_of("=");
402 StringRef SectionIDStr = Mapping.substr(0, EqualsIdx);
403 size_t ComaIdx = Mapping.find_first_of(",");
405 if (ComaIdx == StringRef::npos) {
406 errs() << "Invalid section specification '" << Mapping
407 << "'. Should be '<file name>,<section name>=<addr>'\n";
411 StringRef FileName = SectionIDStr.substr(0, ComaIdx);
412 StringRef SectionName = SectionIDStr.substr(ComaIdx + 1);
415 std::string ErrorMsg;
416 std::tie(OldAddrInt, ErrorMsg) =
417 Checker.getSectionAddr(FileName, SectionName, true);
419 if (ErrorMsg != "") {
424 void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
426 StringRef NewAddrStr = Mapping.substr(EqualsIdx + 1);
429 if (NewAddrStr.getAsInteger(0, NewAddr)) {
430 errs() << "Invalid section address in mapping: " << Mapping << "\n";
434 Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
435 SpecificMappings[OldAddr] = NewAddr;
438 return SpecificMappings;
441 // Scatter sections in all directions!
442 // Remaps section addresses for -verify mode. The following command line options
443 // can be used to customize the layout of the memory within the phony target's
445 // -target-addr-start <s> -- Specify where the phony target addres range starts.
446 // -target-addr-end <e> -- Specify where the phony target address range ends.
447 // -target-section-sep <d> -- Specify how big a gap should be left between the
448 // end of one section and the start of the next.
449 // Defaults to zero. Set to something big
450 // (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
452 static void remapSections(const llvm::Triple &TargetTriple,
453 const TrivialMemoryManager &MemMgr,
454 RuntimeDyldChecker &Checker) {
456 // Set up a work list (section addr/size pairs).
457 typedef std::list<std::pair<void*, uint64_t>> WorklistT;
460 for (const auto& CodeSection : MemMgr.FunctionMemory)
461 Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
462 for (const auto& DataSection : MemMgr.DataMemory)
463 Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
465 // Apply any section-specific mappings that were requested on the command
467 typedef std::map<void*, uint64_t> AppliedMappingsT;
468 AppliedMappingsT AppliedMappings = applySpecificSectionMappings(Checker);
470 // Keep an "already allocated" mapping of section target addresses to sizes.
471 // Sections whose address mappings aren't specified on the command line will
472 // allocated around the explicitly mapped sections while maintaining the
473 // minimum separation.
474 std::map<uint64_t, uint64_t> AlreadyAllocated;
476 // Move the previously applied mappings into the already-allocated map.
477 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
479 WorklistT::iterator Tmp = I;
481 AppliedMappingsT::iterator AI = AppliedMappings.find(Tmp->first);
483 if (AI != AppliedMappings.end()) {
484 AlreadyAllocated[AI->second] = Tmp->second;
489 // If the -target-addr-end option wasn't explicitly passed, then set it to a
490 // sensible default based on the target triple.
491 if (TargetAddrEnd.getNumOccurrences() == 0) {
492 if (TargetTriple.isArch16Bit())
493 TargetAddrEnd = (1ULL << 16) - 1;
494 else if (TargetTriple.isArch32Bit())
495 TargetAddrEnd = (1ULL << 32) - 1;
496 // TargetAddrEnd already has a sensible default for 64-bit systems, so
497 // there's nothing to do in the 64-bit case.
500 // Process any elements remaining in the worklist.
501 while (!Worklist.empty()) {
502 std::pair<void*, uint64_t> CurEntry = Worklist.front();
503 Worklist.pop_front();
505 uint64_t NextSectionAddr = TargetAddrStart;
507 for (const auto &Alloc : AlreadyAllocated)
508 if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
511 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
513 AlreadyAllocated[NextSectionAddr] = CurEntry.second;
514 Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
519 // Load and link the objects specified on the command line, but do not execute
520 // anything. Instead, attach a RuntimeDyldChecker instance and call it to
521 // verify the correctness of the linked memory.
522 static int linkAndVerify() {
524 // Check for missing triple.
525 if (TripleName == "") {
526 llvm::errs() << "Error: -triple required when running in -verify mode.\n";
530 // Look up the target and build the disassembler.
531 Triple TheTriple(Triple::normalize(TripleName));
532 std::string ErrorStr;
533 const Target *TheTarget =
534 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
536 llvm::errs() << "Error accessing target '" << TripleName << "': "
540 TripleName = TheTriple.getTriple();
542 std::unique_ptr<MCSubtargetInfo> STI(
543 TheTarget->createMCSubtargetInfo(TripleName, MCPU, ""));
544 assert(STI && "Unable to create subtarget info!");
546 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
547 assert(MRI && "Unable to create target register info!");
549 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
550 assert(MAI && "Unable to create target asm info!");
552 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
554 std::unique_ptr<MCDisassembler> Disassembler(
555 TheTarget->createMCDisassembler(*STI, Ctx));
556 assert(Disassembler && "Unable to create disassembler!");
558 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
560 std::unique_ptr<MCInstPrinter> InstPrinter(
561 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
563 // Load any dylibs requested on the command line.
566 // Instantiate a dynamic linker.
567 TrivialMemoryManager MemMgr;
568 RuntimeDyld Dyld(MemMgr, MemMgr);
569 Dyld.setProcessAllSections(true);
570 RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
573 // FIXME: Preserve buffers until resolveRelocations time to work around a bug
574 // in RuntimeDyldELF.
575 // This fixme should be fixed ASAP. This is a very brittle workaround.
576 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
578 // If we don't have any input files, read from stdin.
579 if (!InputFileList.size())
580 InputFileList.push_back("-");
581 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
582 // Load the input memory buffer.
583 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
584 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
586 if (std::error_code EC = InputBuffer.getError())
587 return Error("unable to read input: '" + EC.message() + "'");
589 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
590 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
592 if (std::error_code EC = MaybeObj.getError())
593 return Error("unable to create object file: '" + EC.message() + "'");
595 ObjectFile &Obj = **MaybeObj;
596 InputBuffers.push_back(std::move(*InputBuffer));
598 // Load the object file
599 Dyld.loadObject(Obj);
600 if (Dyld.hasError()) {
601 return Error(Dyld.getErrorString());
605 // Re-map the section addresses into the phony target address space.
606 remapSections(TheTriple, MemMgr, Checker);
608 // Resolve all the relocations we can.
609 Dyld.resolveRelocations();
611 // Register EH frames.
612 Dyld.registerEHFrames();
614 int ErrorCode = checkAllExpressions(Checker);
615 if (Dyld.hasError()) {
616 errs() << "RTDyld reported an error applying relocations:\n "
617 << Dyld.getErrorString() << "\n";
624 int main(int argc, char **argv) {
625 sys::PrintStackTraceOnErrorSignal();
626 PrettyStackTraceProgram X(argc, argv);
628 ProgramName = argv[0];
629 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
631 llvm::InitializeAllTargetInfos();
632 llvm::InitializeAllTargetMCs();
633 llvm::InitializeAllDisassemblers();
635 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
639 return executeInput();
640 case AC_PrintDebugLineInfo:
641 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true);
642 case AC_PrintLineInfo:
643 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false);
644 case AC_PrintObjectLineInfo:
645 return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false);
647 return linkAndVerify();