llvm-rtdyld.cpp 24 KB

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