llvm-rtdyld.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. //===-- 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. #include "llvm/ADT/StringMap.h"
  14. #include "llvm/DebugInfo/DIContext.h"
  15. #include "llvm/DebugInfo/DWARF/DWARFContext.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/MCDisassembler.h"
  22. #include "llvm/MC/MCInstPrinter.h"
  23. #include "llvm/MC/MCInstrInfo.h"
  24. #include "llvm/MC/MCRegisterInfo.h"
  25. #include "llvm/MC/MCSubtargetInfo.h"
  26. #include "llvm/Object/MachO.h"
  27. #include "llvm/Object/SymbolSize.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"
  38. #include <list>
  39. #include <system_error>
  40. using namespace llvm;
  41. using namespace llvm::object;
  42. static cl::list<std::string>
  43. InputFileList(cl::Positional, cl::ZeroOrMore,
  44. cl::desc("<input file>"));
  45. enum ActionType {
  46. AC_Execute,
  47. AC_PrintObjectLineInfo,
  48. AC_PrintLineInfo,
  49. AC_PrintDebugLineInfo,
  50. AC_Verify
  51. };
  52. static cl::opt<ActionType>
  53. Action(cl::desc("Action to perform:"),
  54. cl::init(AC_Execute),
  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_PrintDebugLineInfo, "printdebugline",
  60. "Load, link, and print line information for each function using the debug object"),
  61. clEnumValN(AC_PrintObjectLineInfo, "printobjline",
  62. "Like -printlineinfo but does not load the object first"),
  63. clEnumValN(AC_Verify, "verify",
  64. "Load, link and verify the resulting memory image.")));
  65. static cl::opt<std::string>
  66. EntryPoint("entry",
  67. cl::desc("Function to call as entry point."),
  68. cl::init("_main"));
  69. static cl::list<std::string>
  70. Dylibs("dylib",
  71. cl::desc("Add library."),
  72. cl::ZeroOrMore);
  73. static cl::opt<std::string>
  74. TripleName("triple", cl::desc("Target triple for disassembler"));
  75. static cl::opt<std::string>
  76. MCPU("mcpu",
  77. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  78. cl::value_desc("cpu-name"),
  79. cl::init(""));
  80. static cl::list<std::string>
  81. CheckFiles("check",
  82. cl::desc("File containing RuntimeDyld verifier checks."),
  83. cl::ZeroOrMore);
  84. static cl::opt<uint64_t>
  85. PreallocMemory("preallocate",
  86. cl::desc("Allocate memory upfront rather than on-demand"),
  87. cl::init(0));
  88. static cl::opt<uint64_t>
  89. TargetAddrStart("target-addr-start",
  90. cl::desc("For -verify only: start of phony target address "
  91. "range."),
  92. cl::init(4096), // Start at "page 1" - no allocating at "null".
  93. cl::Hidden);
  94. static cl::opt<uint64_t>
  95. TargetAddrEnd("target-addr-end",
  96. cl::desc("For -verify only: end of phony target address range."),
  97. cl::init(~0ULL),
  98. cl::Hidden);
  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."),
  103. cl::init(0),
  104. cl::Hidden);
  105. static cl::list<std::string>
  106. SpecificSectionMappings("map-section",
  107. cl::desc("For -verify only: Map a section to a "
  108. "specific address."),
  109. cl::ZeroOrMore,
  110. cl::Hidden);
  111. static cl::list<std::string>
  112. DummySymbolMappings("dummy-extern",
  113. cl::desc("For -verify only: Inject a symbol into the extern "
  114. "symbol table."),
  115. cl::ZeroOrMore,
  116. cl::Hidden);
  117. static cl::opt<bool>
  118. PrintAllocationRequests("print-alloc-requests",
  119. cl::desc("Print allocation requests made to the memory "
  120. "manager by RuntimeDyld"),
  121. cl::Hidden);
  122. /* *** */
  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 {
  126. public:
  127. SmallVector<sys::MemoryBlock, 16> FunctionMemory;
  128. SmallVector<sys::MemoryBlock, 16> DataMemory;
  129. uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
  130. unsigned SectionID,
  131. StringRef SectionName) override;
  132. uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
  133. unsigned SectionID, StringRef SectionName,
  134. bool IsReadOnly) override;
  135. void *getPointerToNamedFunction(const std::string &Name,
  136. bool AbortOnFailure = true) override {
  137. return nullptr;
  138. }
  139. bool finalizeMemory(std::string *ErrMsg) override { return false; }
  140. void addDummySymbol(const std::string &Name, uint64_t Addr) {
  141. DummyExterns[Name] = Addr;
  142. }
  143. JITSymbol findSymbol(const std::string &Name) override {
  144. auto I = DummyExterns.find(Name);
  145. if (I != DummyExterns.end())
  146. return JITSymbol(I->second, JITSymbolFlags::Exported);
  147. return RTDyldMemoryManager::findSymbol(Name);
  148. }
  149. void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
  150. size_t Size) override {}
  151. void deregisterEHFrames() override {}
  152. void preallocateSlab(uint64_t Size) {
  153. std::string Err;
  154. sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, &Err);
  155. if (!MB.base())
  156. report_fatal_error("Can't allocate enough memory: " + Err);
  157. PreallocSlab = MB;
  158. UsePreallocation = true;
  159. SlabSize = Size;
  160. }
  161. uint8_t *allocateFromSlab(uintptr_t Size, unsigned Alignment, bool isCode) {
  162. Size = alignTo(Size, Alignment);
  163. if (CurrentSlabOffset + Size > SlabSize)
  164. report_fatal_error("Can't allocate enough memory. Tune --preallocate");
  165. uintptr_t OldSlabOffset = CurrentSlabOffset;
  166. sys::MemoryBlock MB((void *)OldSlabOffset, Size);
  167. if (isCode)
  168. FunctionMemory.push_back(MB);
  169. else
  170. DataMemory.push_back(MB);
  171. CurrentSlabOffset += Size;
  172. return (uint8_t*)OldSlabOffset;
  173. }
  174. private:
  175. std::map<std::string, uint64_t> DummyExterns;
  176. sys::MemoryBlock PreallocSlab;
  177. bool UsePreallocation = false;
  178. uintptr_t SlabSize = 0;
  179. uintptr_t CurrentSlabOffset = 0;
  180. };
  181. uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
  182. unsigned Alignment,
  183. unsigned SectionID,
  184. StringRef SectionName) {
  185. if (PrintAllocationRequests)
  186. outs() << "allocateCodeSection(Size = " << Size << ", Alignment = "
  187. << Alignment << ", SectionName = " << SectionName << ")\n";
  188. if (UsePreallocation)
  189. return allocateFromSlab(Size, Alignment, true /* isCode */);
  190. std::string Err;
  191. sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, &Err);
  192. if (!MB.base())
  193. report_fatal_error("MemoryManager allocation failed: " + Err);
  194. FunctionMemory.push_back(MB);
  195. return (uint8_t*)MB.base();
  196. }
  197. uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
  198. unsigned Alignment,
  199. unsigned SectionID,
  200. StringRef SectionName,
  201. bool IsReadOnly) {
  202. if (PrintAllocationRequests)
  203. outs() << "allocateDataSection(Size = " << Size << ", Alignment = "
  204. << Alignment << ", SectionName = " << SectionName << ")\n";
  205. if (UsePreallocation)
  206. return allocateFromSlab(Size, Alignment, false /* isCode */);
  207. std::string Err;
  208. sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, &Err);
  209. if (!MB.base())
  210. report_fatal_error("MemoryManager allocation failed: " + Err);
  211. DataMemory.push_back(MB);
  212. return (uint8_t*)MB.base();
  213. }
  214. static const char *ProgramName;
  215. static void ErrorAndExit(const Twine &Msg) {
  216. errs() << ProgramName << ": error: " << Msg << "\n";
  217. exit(1);
  218. }
  219. static void loadDylibs() {
  220. for (const std::string &Dylib : Dylibs) {
  221. if (!sys::fs::is_regular_file(Dylib))
  222. report_fatal_error("Dylib not found: '" + Dylib + "'.");
  223. std::string ErrMsg;
  224. if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
  225. report_fatal_error("Error loading '" + Dylib + "': " + ErrMsg);
  226. }
  227. }
  228. /* *** */
  229. static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
  230. assert(LoadObjects || !UseDebugObj);
  231. // Load any dylibs requested on the command line.
  232. loadDylibs();
  233. // If we don't have any input files, read from stdin.
  234. if (!InputFileList.size())
  235. InputFileList.push_back("-");
  236. for (auto &File : InputFileList) {
  237. // Instantiate a dynamic linker.
  238. TrivialMemoryManager MemMgr;
  239. RuntimeDyld Dyld(MemMgr, MemMgr);
  240. // Load the input memory buffer.
  241. ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
  242. MemoryBuffer::getFileOrSTDIN(File);
  243. if (std::error_code EC = InputBuffer.getError())
  244. ErrorAndExit("unable to read input: '" + EC.message() + "'");
  245. Expected<std::unique_ptr<ObjectFile>> MaybeObj(
  246. ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
  247. if (!MaybeObj) {
  248. std::string Buf;
  249. raw_string_ostream OS(Buf);
  250. logAllUnhandledErrors(MaybeObj.takeError(), OS, "");
  251. OS.flush();
  252. ErrorAndExit("unable to create object file: '" + Buf + "'");
  253. }
  254. ObjectFile &Obj = **MaybeObj;
  255. OwningBinary<ObjectFile> DebugObj;
  256. std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
  257. ObjectFile *SymbolObj = &Obj;
  258. if (LoadObjects) {
  259. // Load the object file
  260. LoadedObjInfo =
  261. Dyld.loadObject(Obj);
  262. if (Dyld.hasError())
  263. ErrorAndExit(Dyld.getErrorString());
  264. // Resolve all the relocations we can.
  265. Dyld.resolveRelocations();
  266. if (UseDebugObj) {
  267. DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
  268. SymbolObj = DebugObj.getBinary();
  269. LoadedObjInfo.reset();
  270. }
  271. }
  272. std::unique_ptr<DIContext> Context(
  273. new DWARFContextInMemory(*SymbolObj,LoadedObjInfo.get()));
  274. std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
  275. object::computeSymbolSizes(*SymbolObj);
  276. // Use symbol info to iterate functions in the object.
  277. for (const auto &P : SymAddr) {
  278. object::SymbolRef Sym = P.first;
  279. Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
  280. if (!TypeOrErr) {
  281. // TODO: Actually report errors helpfully.
  282. consumeError(TypeOrErr.takeError());
  283. continue;
  284. }
  285. SymbolRef::Type Type = *TypeOrErr;
  286. if (Type == object::SymbolRef::ST_Function) {
  287. Expected<StringRef> Name = Sym.getName();
  288. if (!Name) {
  289. // TODO: Actually report errors helpfully.
  290. consumeError(Name.takeError());
  291. continue;
  292. }
  293. Expected<uint64_t> AddrOrErr = Sym.getAddress();
  294. if (!AddrOrErr) {
  295. // TODO: Actually report errors helpfully.
  296. consumeError(AddrOrErr.takeError());
  297. continue;
  298. }
  299. uint64_t Addr = *AddrOrErr;
  300. uint64_t Size = P.second;
  301. // If we're not using the debug object, compute the address of the
  302. // symbol in memory (rather than that in the unrelocated object file)
  303. // and use that to query the DWARFContext.
  304. if (!UseDebugObj && LoadObjects) {
  305. auto SecOrErr = Sym.getSection();
  306. if (!SecOrErr) {
  307. // TODO: Actually report errors helpfully.
  308. consumeError(SecOrErr.takeError());
  309. continue;
  310. }
  311. object::section_iterator Sec = *SecOrErr;
  312. StringRef SecName;
  313. Sec->getName(SecName);
  314. uint64_t SectionLoadAddress =
  315. LoadedObjInfo->getSectionLoadAddress(*Sec);
  316. if (SectionLoadAddress != 0)
  317. Addr += SectionLoadAddress - Sec->getAddress();
  318. }
  319. outs() << "Function: " << *Name << ", Size = " << Size
  320. << ", Addr = " << Addr << "\n";
  321. DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
  322. for (auto &D : Lines) {
  323. outs() << " Line info @ " << D.first - Addr << ": "
  324. << D.second.FileName << ", line:" << D.second.Line << "\n";
  325. }
  326. }
  327. }
  328. }
  329. return 0;
  330. }
  331. static void doPreallocation(TrivialMemoryManager &MemMgr) {
  332. // Allocate a slab of memory upfront, if required. This is used if
  333. // we want to test small code models.
  334. if (static_cast<intptr_t>(PreallocMemory) < 0)
  335. report_fatal_error("Pre-allocated bytes of memory must be a positive integer.");
  336. // FIXME: Limit the amount of memory that can be preallocated?
  337. if (PreallocMemory != 0)
  338. MemMgr.preallocateSlab(PreallocMemory);
  339. }
  340. static int executeInput() {
  341. // Load any dylibs requested on the command line.
  342. loadDylibs();
  343. // Instantiate a dynamic linker.
  344. TrivialMemoryManager MemMgr;
  345. doPreallocation(MemMgr);
  346. RuntimeDyld Dyld(MemMgr, MemMgr);
  347. // If we don't have any input files, read from stdin.
  348. if (!InputFileList.size())
  349. InputFileList.push_back("-");
  350. for (auto &File : InputFileList) {
  351. // Load the input memory buffer.
  352. ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
  353. MemoryBuffer::getFileOrSTDIN(File);
  354. if (std::error_code EC = InputBuffer.getError())
  355. ErrorAndExit("unable to read input: '" + EC.message() + "'");
  356. Expected<std::unique_ptr<ObjectFile>> MaybeObj(
  357. ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
  358. if (!MaybeObj) {
  359. std::string Buf;
  360. raw_string_ostream OS(Buf);
  361. logAllUnhandledErrors(MaybeObj.takeError(), OS, "");
  362. OS.flush();
  363. ErrorAndExit("unable to create object file: '" + Buf + "'");
  364. }
  365. ObjectFile &Obj = **MaybeObj;
  366. // Load the object file
  367. Dyld.loadObject(Obj);
  368. if (Dyld.hasError()) {
  369. ErrorAndExit(Dyld.getErrorString());
  370. }
  371. }
  372. // Resove all the relocations we can.
  373. // FIXME: Error out if there are unresolved relocations.
  374. Dyld.resolveRelocations();
  375. // Get the address of the entry point (_main by default).
  376. void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
  377. if (!MainAddress)
  378. ErrorAndExit("no definition for '" + EntryPoint + "'");
  379. // Invalidate the instruction cache for each loaded function.
  380. for (auto &FM : MemMgr.FunctionMemory) {
  381. // Make sure the memory is executable.
  382. // setExecutable will call InvalidateInstructionCache.
  383. std::string ErrorStr;
  384. if (!sys::Memory::setExecutable(FM, &ErrorStr))
  385. ErrorAndExit("unable to mark function executable: '" + ErrorStr + "'");
  386. }
  387. // Dispatch to _main().
  388. errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
  389. int (*Main)(int, const char**) =
  390. (int(*)(int,const char**)) uintptr_t(MainAddress);
  391. const char **Argv = new const char*[2];
  392. // Use the name of the first input object module as argv[0] for the target.
  393. Argv[0] = InputFileList[0].c_str();
  394. Argv[1] = nullptr;
  395. return Main(1, Argv);
  396. }
  397. static int checkAllExpressions(RuntimeDyldChecker &Checker) {
  398. for (const auto& CheckerFileName : CheckFiles) {
  399. ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
  400. MemoryBuffer::getFileOrSTDIN(CheckerFileName);
  401. if (std::error_code EC = CheckerFileBuf.getError())
  402. ErrorAndExit("unable to read input '" + CheckerFileName + "': " +
  403. EC.message());
  404. if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
  405. CheckerFileBuf.get().get()))
  406. ErrorAndExit("some checks in '" + CheckerFileName + "' failed");
  407. }
  408. return 0;
  409. }
  410. void applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
  411. for (StringRef Mapping : SpecificSectionMappings) {
  412. size_t EqualsIdx = Mapping.find_first_of("=");
  413. std::string SectionIDStr = Mapping.substr(0, EqualsIdx);
  414. size_t ComaIdx = Mapping.find_first_of(",");
  415. if (ComaIdx == StringRef::npos)
  416. report_fatal_error("Invalid section specification '" + Mapping +
  417. "'. Should be '<file name>,<section name>=<addr>'");
  418. std::string FileName = SectionIDStr.substr(0, ComaIdx);
  419. std::string SectionName = SectionIDStr.substr(ComaIdx + 1);
  420. uint64_t OldAddrInt;
  421. std::string ErrorMsg;
  422. std::tie(OldAddrInt, ErrorMsg) =
  423. Checker.getSectionAddr(FileName, SectionName, true);
  424. if (ErrorMsg != "")
  425. report_fatal_error(ErrorMsg);
  426. void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
  427. std::string NewAddrStr = Mapping.substr(EqualsIdx + 1);
  428. uint64_t NewAddr;
  429. if (StringRef(NewAddrStr).getAsInteger(0, NewAddr))
  430. report_fatal_error("Invalid section address in mapping '" + Mapping +
  431. "'.");
  432. Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
  433. }
  434. }
  435. // Scatter sections in all directions!
  436. // Remaps section addresses for -verify mode. The following command line options
  437. // can be used to customize the layout of the memory within the phony target's
  438. // address space:
  439. // -target-addr-start <s> -- Specify where the phony target address range starts.
  440. // -target-addr-end <e> -- Specify where the phony target address range ends.
  441. // -target-section-sep <d> -- Specify how big a gap should be left between the
  442. // end of one section and the start of the next.
  443. // Defaults to zero. Set to something big
  444. // (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
  445. //
  446. static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple,
  447. TrivialMemoryManager &MemMgr,
  448. RuntimeDyldChecker &Checker) {
  449. // Set up a work list (section addr/size pairs).
  450. typedef std::list<std::pair<void*, uint64_t>> WorklistT;
  451. WorklistT Worklist;
  452. for (const auto& CodeSection : MemMgr.FunctionMemory)
  453. Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
  454. for (const auto& DataSection : MemMgr.DataMemory)
  455. Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
  456. // Apply any section-specific mappings that were requested on the command
  457. // line.
  458. applySpecificSectionMappings(Checker);
  459. // Keep an "already allocated" mapping of section target addresses to sizes.
  460. // Sections whose address mappings aren't specified on the command line will
  461. // allocated around the explicitly mapped sections while maintaining the
  462. // minimum separation.
  463. std::map<uint64_t, uint64_t> AlreadyAllocated;
  464. // Move the previously applied mappings (whether explicitly specified on the
  465. // command line, or implicitly set by RuntimeDyld) into the already-allocated
  466. // map.
  467. for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
  468. I != E;) {
  469. WorklistT::iterator Tmp = I;
  470. ++I;
  471. auto LoadAddr = Checker.getSectionLoadAddress(Tmp->first);
  472. if (LoadAddr &&
  473. *LoadAddr != static_cast<uint64_t>(
  474. reinterpret_cast<uintptr_t>(Tmp->first))) {
  475. AlreadyAllocated[*LoadAddr] = Tmp->second;
  476. Worklist.erase(Tmp);
  477. }
  478. }
  479. // If the -target-addr-end option wasn't explicitly passed, then set it to a
  480. // sensible default based on the target triple.
  481. if (TargetAddrEnd.getNumOccurrences() == 0) {
  482. if (TargetTriple.isArch16Bit())
  483. TargetAddrEnd = (1ULL << 16) - 1;
  484. else if (TargetTriple.isArch32Bit())
  485. TargetAddrEnd = (1ULL << 32) - 1;
  486. // TargetAddrEnd already has a sensible default for 64-bit systems, so
  487. // there's nothing to do in the 64-bit case.
  488. }
  489. // Process any elements remaining in the worklist.
  490. while (!Worklist.empty()) {
  491. std::pair<void*, uint64_t> CurEntry = Worklist.front();
  492. Worklist.pop_front();
  493. uint64_t NextSectionAddr = TargetAddrStart;
  494. for (const auto &Alloc : AlreadyAllocated)
  495. if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
  496. break;
  497. else
  498. NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
  499. AlreadyAllocated[NextSectionAddr] = CurEntry.second;
  500. Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
  501. }
  502. // Add dummy symbols to the memory manager.
  503. for (const auto &Mapping : DummySymbolMappings) {
  504. size_t EqualsIdx = Mapping.find_first_of('=');
  505. if (EqualsIdx == StringRef::npos)
  506. report_fatal_error("Invalid dummy symbol specification '" + Mapping +
  507. "'. Should be '<symbol name>=<addr>'");
  508. std::string Symbol = Mapping.substr(0, EqualsIdx);
  509. std::string AddrStr = Mapping.substr(EqualsIdx + 1);
  510. uint64_t Addr;
  511. if (StringRef(AddrStr).getAsInteger(0, Addr))
  512. report_fatal_error("Invalid symbol mapping '" + Mapping + "'.");
  513. MemMgr.addDummySymbol(Symbol, Addr);
  514. }
  515. }
  516. // Load and link the objects specified on the command line, but do not execute
  517. // anything. Instead, attach a RuntimeDyldChecker instance and call it to
  518. // verify the correctness of the linked memory.
  519. static int linkAndVerify() {
  520. // Check for missing triple.
  521. if (TripleName == "")
  522. ErrorAndExit("-triple required when running in -verify mode.");
  523. // Look up the target and build the disassembler.
  524. Triple TheTriple(Triple::normalize(TripleName));
  525. std::string ErrorStr;
  526. const Target *TheTarget =
  527. TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
  528. if (!TheTarget)
  529. ErrorAndExit("Error accessing target '" + TripleName + "': " + ErrorStr);
  530. TripleName = TheTriple.getTriple();
  531. std::unique_ptr<MCSubtargetInfo> STI(
  532. TheTarget->createMCSubtargetInfo(TripleName, MCPU, ""));
  533. if (!STI)
  534. ErrorAndExit("Unable to create subtarget info!");
  535. std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
  536. if (!MRI)
  537. ErrorAndExit("Unable to create target register info!");
  538. std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
  539. if (!MAI)
  540. ErrorAndExit("Unable to create target asm info!");
  541. MCContext Ctx(MAI.get(), MRI.get(), nullptr);
  542. std::unique_ptr<MCDisassembler> Disassembler(
  543. TheTarget->createMCDisassembler(*STI, Ctx));
  544. if (!Disassembler)
  545. ErrorAndExit("Unable to create disassembler!");
  546. std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  547. std::unique_ptr<MCInstPrinter> InstPrinter(
  548. TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
  549. // Load any dylibs requested on the command line.
  550. loadDylibs();
  551. // Instantiate a dynamic linker.
  552. TrivialMemoryManager MemMgr;
  553. doPreallocation(MemMgr);
  554. RuntimeDyld Dyld(MemMgr, MemMgr);
  555. Dyld.setProcessAllSections(true);
  556. RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
  557. llvm::dbgs());
  558. // If we don't have any input files, read from stdin.
  559. if (!InputFileList.size())
  560. InputFileList.push_back("-");
  561. for (auto &Filename : InputFileList) {
  562. // Load the input memory buffer.
  563. ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
  564. MemoryBuffer::getFileOrSTDIN(Filename);
  565. if (std::error_code EC = InputBuffer.getError())
  566. ErrorAndExit("unable to read input: '" + EC.message() + "'");
  567. Expected<std::unique_ptr<ObjectFile>> MaybeObj(
  568. ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
  569. if (!MaybeObj) {
  570. std::string Buf;
  571. raw_string_ostream OS(Buf);
  572. logAllUnhandledErrors(MaybeObj.takeError(), OS, "");
  573. OS.flush();
  574. ErrorAndExit("unable to create object file: '" + Buf + "'");
  575. }
  576. ObjectFile &Obj = **MaybeObj;
  577. // Load the object file
  578. Dyld.loadObject(Obj);
  579. if (Dyld.hasError()) {
  580. ErrorAndExit(Dyld.getErrorString());
  581. }
  582. }
  583. // Re-map the section addresses into the phony target address space and add
  584. // dummy symbols.
  585. remapSectionsAndSymbols(TheTriple, MemMgr, Checker);
  586. // Resolve all the relocations we can.
  587. Dyld.resolveRelocations();
  588. // Register EH frames.
  589. Dyld.registerEHFrames();
  590. int ErrorCode = checkAllExpressions(Checker);
  591. if (Dyld.hasError())
  592. ErrorAndExit("RTDyld reported an error applying relocations:\n " +
  593. Dyld.getErrorString());
  594. return ErrorCode;
  595. }
  596. int main(int argc, char **argv) {
  597. sys::PrintStackTraceOnErrorSignal(argv[0]);
  598. PrettyStackTraceProgram X(argc, argv);
  599. ProgramName = argv[0];
  600. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  601. llvm::InitializeAllTargetInfos();
  602. llvm::InitializeAllTargetMCs();
  603. llvm::InitializeAllDisassemblers();
  604. cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
  605. switch (Action) {
  606. case AC_Execute:
  607. return executeInput();
  608. case AC_PrintDebugLineInfo:
  609. return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true);
  610. case AC_PrintLineInfo:
  611. return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false);
  612. case AC_PrintObjectLineInfo:
  613. return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false);
  614. case AC_Verify:
  615. return linkAndVerify();
  616. }
  617. }