llvm-rtdyld.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. //===-- llvm-rtdyld.cpp - MCJIT Testing Tool ------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This is a testing tool for use with the MC-JIT LLVM components.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/StringMap.h"
  13. #include "llvm/DebugInfo/DIContext.h"
  14. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  15. #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
  16. #include "llvm/ExecutionEngine/RuntimeDyld.h"
  17. #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
  18. #include "llvm/MC/MCAsmInfo.h"
  19. #include "llvm/MC/MCContext.h"
  20. #include "llvm/MC/MCDisassembler/MCDisassembler.h"
  21. #include "llvm/MC/MCInstPrinter.h"
  22. #include "llvm/MC/MCInstrInfo.h"
  23. #include "llvm/MC/MCRegisterInfo.h"
  24. #include "llvm/MC/MCSubtargetInfo.h"
  25. #include "llvm/MC/MCTargetOptions.h"
  26. #include "llvm/Object/SymbolSize.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/DynamicLibrary.h"
  29. #include "llvm/Support/InitLLVM.h"
  30. #include "llvm/Support/MSVCErrorWorkarounds.h"
  31. #include "llvm/Support/Memory.h"
  32. #include "llvm/Support/MemoryBuffer.h"
  33. #include "llvm/Support/Path.h"
  34. #include "llvm/Support/TargetRegistry.h"
  35. #include "llvm/Support/TargetSelect.h"
  36. #include "llvm/Support/Timer.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include <future>
  39. #include <list>
  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 files>"));
  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::list<std::string> InputArgv("args", cl::Positional,
  74. cl::desc("<program arguments>..."),
  75. cl::ZeroOrMore, cl::PositionalEatsArgs);
  76. static cl::opt<std::string>
  77. TripleName("triple", cl::desc("Target triple for disassembler"));
  78. static cl::opt<std::string>
  79. MCPU("mcpu",
  80. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  81. cl::value_desc("cpu-name"),
  82. cl::init(""));
  83. static cl::list<std::string>
  84. CheckFiles("check",
  85. cl::desc("File containing RuntimeDyld verifier checks."),
  86. cl::ZeroOrMore);
  87. static cl::opt<uint64_t>
  88. PreallocMemory("preallocate",
  89. cl::desc("Allocate memory upfront rather than on-demand"),
  90. cl::init(0));
  91. static cl::opt<uint64_t> TargetAddrStart(
  92. "target-addr-start",
  93. cl::desc("For -verify only: start of phony target address "
  94. "range."),
  95. cl::init(4096), // Start at "page 1" - no allocating at "null".
  96. cl::Hidden);
  97. static cl::opt<uint64_t> TargetAddrEnd(
  98. "target-addr-end",
  99. cl::desc("For -verify only: end of phony target address range."),
  100. cl::init(~0ULL), cl::Hidden);
  101. static cl::opt<uint64_t> TargetSectionSep(
  102. "target-section-sep",
  103. cl::desc("For -verify only: Separation between sections in "
  104. "phony target address space."),
  105. cl::init(0), cl::Hidden);
  106. static cl::list<std::string>
  107. SpecificSectionMappings("map-section",
  108. cl::desc("For -verify only: Map a section to a "
  109. "specific address."),
  110. cl::ZeroOrMore,
  111. cl::Hidden);
  112. static cl::list<std::string>
  113. DummySymbolMappings("dummy-extern",
  114. cl::desc("For -verify only: Inject a symbol into the extern "
  115. "symbol table."),
  116. cl::ZeroOrMore,
  117. cl::Hidden);
  118. static cl::opt<bool>
  119. PrintAllocationRequests("print-alloc-requests",
  120. cl::desc("Print allocation requests made to the memory "
  121. "manager by RuntimeDyld"),
  122. cl::Hidden);
  123. static cl::opt<bool> ShowTimes("show-times",
  124. cl::desc("Show times for llvm-rtdyld phases"),
  125. cl::init(false));
  126. ExitOnError ExitOnErr;
  127. struct RTDyldTimers {
  128. TimerGroup RTDyldTG{"llvm-rtdyld timers", "timers for llvm-rtdyld phases"};
  129. Timer LoadObjectsTimer{"load", "time to load/add object files", RTDyldTG};
  130. Timer LinkTimer{"link", "time to link object files", RTDyldTG};
  131. Timer RunTimer{"run", "time to execute jitlink'd code", RTDyldTG};
  132. };
  133. std::unique_ptr<RTDyldTimers> Timers;
  134. /* *** */
  135. using SectionIDMap = StringMap<unsigned>;
  136. using FileToSectionIDMap = StringMap<SectionIDMap>;
  137. void dumpFileToSectionIDMap(const FileToSectionIDMap &FileToSecIDMap) {
  138. for (const auto &KV : FileToSecIDMap) {
  139. llvm::dbgs() << "In " << KV.first() << "\n";
  140. for (auto &KV2 : KV.second)
  141. llvm::dbgs() << " \"" << KV2.first() << "\" -> " << KV2.second << "\n";
  142. }
  143. }
  144. Expected<unsigned> getSectionId(const FileToSectionIDMap &FileToSecIDMap,
  145. StringRef FileName, StringRef SectionName) {
  146. auto I = FileToSecIDMap.find(FileName);
  147. if (I == FileToSecIDMap.end())
  148. return make_error<StringError>("No file named " + FileName,
  149. inconvertibleErrorCode());
  150. auto &SectionIDs = I->second;
  151. auto J = SectionIDs.find(SectionName);
  152. if (J == SectionIDs.end())
  153. return make_error<StringError>("No section named \"" + SectionName +
  154. "\" in file " + FileName,
  155. inconvertibleErrorCode());
  156. return J->second;
  157. }
  158. // A trivial memory manager that doesn't do anything fancy, just uses the
  159. // support library allocation routines directly.
  160. class TrivialMemoryManager : public RTDyldMemoryManager {
  161. public:
  162. struct SectionInfo {
  163. SectionInfo(StringRef Name, sys::MemoryBlock MB, unsigned SectionID)
  164. : Name(std::string(Name)), MB(std::move(MB)), SectionID(SectionID) {}
  165. std::string Name;
  166. sys::MemoryBlock MB;
  167. unsigned SectionID = ~0U;
  168. };
  169. SmallVector<SectionInfo, 16> FunctionMemory;
  170. SmallVector<SectionInfo, 16> DataMemory;
  171. uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
  172. unsigned SectionID,
  173. StringRef SectionName) override;
  174. uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
  175. unsigned SectionID, StringRef SectionName,
  176. bool IsReadOnly) override;
  177. /// If non null, records subsequent Name -> SectionID mappings.
  178. void setSectionIDsMap(SectionIDMap *SecIDMap) {
  179. this->SecIDMap = SecIDMap;
  180. }
  181. void *getPointerToNamedFunction(const std::string &Name,
  182. bool AbortOnFailure = true) override {
  183. return nullptr;
  184. }
  185. bool finalizeMemory(std::string *ErrMsg) override { return false; }
  186. void addDummySymbol(const std::string &Name, uint64_t Addr) {
  187. DummyExterns[Name] = Addr;
  188. }
  189. JITSymbol findSymbol(const std::string &Name) override {
  190. auto I = DummyExterns.find(Name);
  191. if (I != DummyExterns.end())
  192. return JITSymbol(I->second, JITSymbolFlags::Exported);
  193. if (auto Sym = RTDyldMemoryManager::findSymbol(Name))
  194. return Sym;
  195. else if (auto Err = Sym.takeError())
  196. ExitOnErr(std::move(Err));
  197. else
  198. ExitOnErr(make_error<StringError>("Could not find definition for \"" +
  199. Name + "\"",
  200. inconvertibleErrorCode()));
  201. llvm_unreachable("Should have returned or exited by now");
  202. }
  203. void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
  204. size_t Size) override {}
  205. void deregisterEHFrames() override {}
  206. void preallocateSlab(uint64_t Size) {
  207. std::error_code EC;
  208. sys::MemoryBlock MB =
  209. sys::Memory::allocateMappedMemory(Size, nullptr,
  210. sys::Memory::MF_READ |
  211. sys::Memory::MF_WRITE,
  212. EC);
  213. if (!MB.base())
  214. report_fatal_error("Can't allocate enough memory: " + EC.message());
  215. PreallocSlab = MB;
  216. UsePreallocation = true;
  217. SlabSize = Size;
  218. }
  219. uint8_t *allocateFromSlab(uintptr_t Size, unsigned Alignment, bool isCode,
  220. StringRef SectionName, unsigned SectionID) {
  221. Size = alignTo(Size, Alignment);
  222. if (CurrentSlabOffset + Size > SlabSize)
  223. report_fatal_error("Can't allocate enough memory. Tune --preallocate");
  224. uintptr_t OldSlabOffset = CurrentSlabOffset;
  225. sys::MemoryBlock MB((void *)OldSlabOffset, Size);
  226. if (isCode)
  227. FunctionMemory.push_back(SectionInfo(SectionName, MB, SectionID));
  228. else
  229. DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
  230. CurrentSlabOffset += Size;
  231. return (uint8_t*)OldSlabOffset;
  232. }
  233. private:
  234. std::map<std::string, uint64_t> DummyExterns;
  235. sys::MemoryBlock PreallocSlab;
  236. bool UsePreallocation = false;
  237. uintptr_t SlabSize = 0;
  238. uintptr_t CurrentSlabOffset = 0;
  239. SectionIDMap *SecIDMap = nullptr;
  240. };
  241. uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
  242. unsigned Alignment,
  243. unsigned SectionID,
  244. StringRef SectionName) {
  245. if (PrintAllocationRequests)
  246. outs() << "allocateCodeSection(Size = " << Size << ", Alignment = "
  247. << Alignment << ", SectionName = " << SectionName << ")\n";
  248. if (SecIDMap)
  249. (*SecIDMap)[SectionName] = SectionID;
  250. if (UsePreallocation)
  251. return allocateFromSlab(Size, Alignment, true /* isCode */,
  252. SectionName, SectionID);
  253. std::error_code EC;
  254. sys::MemoryBlock MB =
  255. sys::Memory::allocateMappedMemory(Size, nullptr,
  256. sys::Memory::MF_READ |
  257. sys::Memory::MF_WRITE,
  258. EC);
  259. if (!MB.base())
  260. report_fatal_error("MemoryManager allocation failed: " + EC.message());
  261. FunctionMemory.push_back(SectionInfo(SectionName, MB, SectionID));
  262. return (uint8_t*)MB.base();
  263. }
  264. uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
  265. unsigned Alignment,
  266. unsigned SectionID,
  267. StringRef SectionName,
  268. bool IsReadOnly) {
  269. if (PrintAllocationRequests)
  270. outs() << "allocateDataSection(Size = " << Size << ", Alignment = "
  271. << Alignment << ", SectionName = " << SectionName << ")\n";
  272. if (SecIDMap)
  273. (*SecIDMap)[SectionName] = SectionID;
  274. if (UsePreallocation)
  275. return allocateFromSlab(Size, Alignment, false /* isCode */, SectionName,
  276. SectionID);
  277. std::error_code EC;
  278. sys::MemoryBlock MB =
  279. sys::Memory::allocateMappedMemory(Size, nullptr,
  280. sys::Memory::MF_READ |
  281. sys::Memory::MF_WRITE,
  282. EC);
  283. if (!MB.base())
  284. report_fatal_error("MemoryManager allocation failed: " + EC.message());
  285. DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
  286. return (uint8_t*)MB.base();
  287. }
  288. static const char *ProgramName;
  289. static void ErrorAndExit(const Twine &Msg) {
  290. errs() << ProgramName << ": error: " << Msg << "\n";
  291. exit(1);
  292. }
  293. static void loadDylibs() {
  294. for (const std::string &Dylib : Dylibs) {
  295. if (!sys::fs::is_regular_file(Dylib))
  296. report_fatal_error("Dylib not found: '" + Dylib + "'.");
  297. std::string ErrMsg;
  298. if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
  299. report_fatal_error("Error loading '" + Dylib + "': " + ErrMsg);
  300. }
  301. }
  302. /* *** */
  303. static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
  304. assert(LoadObjects || !UseDebugObj);
  305. // Load any dylibs requested on the command line.
  306. loadDylibs();
  307. // If we don't have any input files, read from stdin.
  308. if (!InputFileList.size())
  309. InputFileList.push_back("-");
  310. for (auto &File : InputFileList) {
  311. // Instantiate a dynamic linker.
  312. TrivialMemoryManager MemMgr;
  313. RuntimeDyld Dyld(MemMgr, MemMgr);
  314. // Load the input memory buffer.
  315. ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
  316. MemoryBuffer::getFileOrSTDIN(File);
  317. if (std::error_code EC = InputBuffer.getError())
  318. ErrorAndExit("unable to read input: '" + EC.message() + "'");
  319. Expected<std::unique_ptr<ObjectFile>> MaybeObj(
  320. ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
  321. if (!MaybeObj) {
  322. std::string Buf;
  323. raw_string_ostream OS(Buf);
  324. logAllUnhandledErrors(MaybeObj.takeError(), OS);
  325. OS.flush();
  326. ErrorAndExit("unable to create object file: '" + Buf + "'");
  327. }
  328. ObjectFile &Obj = **MaybeObj;
  329. OwningBinary<ObjectFile> DebugObj;
  330. std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
  331. ObjectFile *SymbolObj = &Obj;
  332. if (LoadObjects) {
  333. // Load the object file
  334. LoadedObjInfo =
  335. Dyld.loadObject(Obj);
  336. if (Dyld.hasError())
  337. ErrorAndExit(Dyld.getErrorString());
  338. // Resolve all the relocations we can.
  339. Dyld.resolveRelocations();
  340. if (UseDebugObj) {
  341. DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
  342. SymbolObj = DebugObj.getBinary();
  343. LoadedObjInfo.reset();
  344. }
  345. }
  346. std::unique_ptr<DIContext> Context =
  347. DWARFContext::create(*SymbolObj, LoadedObjInfo.get());
  348. std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
  349. object::computeSymbolSizes(*SymbolObj);
  350. // Use symbol info to iterate functions in the object.
  351. for (const auto &P : SymAddr) {
  352. object::SymbolRef Sym = P.first;
  353. Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
  354. if (!TypeOrErr) {
  355. // TODO: Actually report errors helpfully.
  356. consumeError(TypeOrErr.takeError());
  357. continue;
  358. }
  359. SymbolRef::Type Type = *TypeOrErr;
  360. if (Type == object::SymbolRef::ST_Function) {
  361. Expected<StringRef> Name = Sym.getName();
  362. if (!Name) {
  363. // TODO: Actually report errors helpfully.
  364. consumeError(Name.takeError());
  365. continue;
  366. }
  367. Expected<uint64_t> AddrOrErr = Sym.getAddress();
  368. if (!AddrOrErr) {
  369. // TODO: Actually report errors helpfully.
  370. consumeError(AddrOrErr.takeError());
  371. continue;
  372. }
  373. uint64_t Addr = *AddrOrErr;
  374. object::SectionedAddress Address;
  375. uint64_t Size = P.second;
  376. // If we're not using the debug object, compute the address of the
  377. // symbol in memory (rather than that in the unrelocated object file)
  378. // and use that to query the DWARFContext.
  379. if (!UseDebugObj && LoadObjects) {
  380. auto SecOrErr = Sym.getSection();
  381. if (!SecOrErr) {
  382. // TODO: Actually report errors helpfully.
  383. consumeError(SecOrErr.takeError());
  384. continue;
  385. }
  386. object::section_iterator Sec = *SecOrErr;
  387. Address.SectionIndex = Sec->getIndex();
  388. uint64_t SectionLoadAddress =
  389. LoadedObjInfo->getSectionLoadAddress(*Sec);
  390. if (SectionLoadAddress != 0)
  391. Addr += SectionLoadAddress - Sec->getAddress();
  392. } else if (auto SecOrErr = Sym.getSection())
  393. Address.SectionIndex = SecOrErr.get()->getIndex();
  394. outs() << "Function: " << *Name << ", Size = " << Size
  395. << ", Addr = " << Addr << "\n";
  396. Address.Address = Addr;
  397. DILineInfoTable Lines =
  398. Context->getLineInfoForAddressRange(Address, Size);
  399. for (auto &D : Lines) {
  400. outs() << " Line info @ " << D.first - Addr << ": "
  401. << D.second.FileName << ", line:" << D.second.Line << "\n";
  402. }
  403. }
  404. }
  405. }
  406. return 0;
  407. }
  408. static void doPreallocation(TrivialMemoryManager &MemMgr) {
  409. // Allocate a slab of memory upfront, if required. This is used if
  410. // we want to test small code models.
  411. if (static_cast<intptr_t>(PreallocMemory) < 0)
  412. report_fatal_error("Pre-allocated bytes of memory must be a positive integer.");
  413. // FIXME: Limit the amount of memory that can be preallocated?
  414. if (PreallocMemory != 0)
  415. MemMgr.preallocateSlab(PreallocMemory);
  416. }
  417. static int executeInput() {
  418. // Load any dylibs requested on the command line.
  419. loadDylibs();
  420. // Instantiate a dynamic linker.
  421. TrivialMemoryManager MemMgr;
  422. doPreallocation(MemMgr);
  423. RuntimeDyld Dyld(MemMgr, MemMgr);
  424. // If we don't have any input files, read from stdin.
  425. if (!InputFileList.size())
  426. InputFileList.push_back("-");
  427. {
  428. TimeRegion TR(Timers ? &Timers->LoadObjectsTimer : nullptr);
  429. for (auto &File : InputFileList) {
  430. // Load the input memory buffer.
  431. ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
  432. MemoryBuffer::getFileOrSTDIN(File);
  433. if (std::error_code EC = InputBuffer.getError())
  434. ErrorAndExit("unable to read input: '" + EC.message() + "'");
  435. Expected<std::unique_ptr<ObjectFile>> MaybeObj(
  436. ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
  437. if (!MaybeObj) {
  438. std::string Buf;
  439. raw_string_ostream OS(Buf);
  440. logAllUnhandledErrors(MaybeObj.takeError(), OS);
  441. OS.flush();
  442. ErrorAndExit("unable to create object file: '" + Buf + "'");
  443. }
  444. ObjectFile &Obj = **MaybeObj;
  445. // Load the object file
  446. Dyld.loadObject(Obj);
  447. if (Dyld.hasError()) {
  448. ErrorAndExit(Dyld.getErrorString());
  449. }
  450. }
  451. }
  452. {
  453. TimeRegion TR(Timers ? &Timers->LinkTimer : nullptr);
  454. // Resove all the relocations we can.
  455. // FIXME: Error out if there are unresolved relocations.
  456. Dyld.resolveRelocations();
  457. }
  458. // Get the address of the entry point (_main by default).
  459. void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
  460. if (!MainAddress)
  461. ErrorAndExit("no definition for '" + EntryPoint + "'");
  462. // Invalidate the instruction cache for each loaded function.
  463. for (auto &FM : MemMgr.FunctionMemory) {
  464. auto &FM_MB = FM.MB;
  465. // Make sure the memory is executable.
  466. // setExecutable will call InvalidateInstructionCache.
  467. if (auto EC = sys::Memory::protectMappedMemory(FM_MB,
  468. sys::Memory::MF_READ |
  469. sys::Memory::MF_EXEC))
  470. ErrorAndExit("unable to mark function executable: '" + EC.message() +
  471. "'");
  472. }
  473. // Dispatch to _main().
  474. errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
  475. int (*Main)(int, const char**) =
  476. (int(*)(int,const char**)) uintptr_t(MainAddress);
  477. std::vector<const char *> Argv;
  478. // Use the name of the first input object module as argv[0] for the target.
  479. Argv.push_back(InputFileList[0].data());
  480. for (auto &Arg : InputArgv)
  481. Argv.push_back(Arg.data());
  482. Argv.push_back(nullptr);
  483. int Result = 0;
  484. {
  485. TimeRegion TR(Timers ? &Timers->RunTimer : nullptr);
  486. Result = Main(Argv.size() - 1, Argv.data());
  487. }
  488. return Result;
  489. }
  490. static int checkAllExpressions(RuntimeDyldChecker &Checker) {
  491. for (const auto& CheckerFileName : CheckFiles) {
  492. ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
  493. MemoryBuffer::getFileOrSTDIN(CheckerFileName);
  494. if (std::error_code EC = CheckerFileBuf.getError())
  495. ErrorAndExit("unable to read input '" + CheckerFileName + "': " +
  496. EC.message());
  497. if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
  498. CheckerFileBuf.get().get()))
  499. ErrorAndExit("some checks in '" + CheckerFileName + "' failed");
  500. }
  501. return 0;
  502. }
  503. void applySpecificSectionMappings(RuntimeDyld &Dyld,
  504. const FileToSectionIDMap &FileToSecIDMap) {
  505. for (StringRef Mapping : SpecificSectionMappings) {
  506. size_t EqualsIdx = Mapping.find_first_of("=");
  507. std::string SectionIDStr = std::string(Mapping.substr(0, EqualsIdx));
  508. size_t ComaIdx = Mapping.find_first_of(",");
  509. if (ComaIdx == StringRef::npos)
  510. report_fatal_error("Invalid section specification '" + Mapping +
  511. "'. Should be '<file name>,<section name>=<addr>'");
  512. std::string FileName = SectionIDStr.substr(0, ComaIdx);
  513. std::string SectionName = SectionIDStr.substr(ComaIdx + 1);
  514. unsigned SectionID =
  515. ExitOnErr(getSectionId(FileToSecIDMap, FileName, SectionName));
  516. auto* OldAddr = Dyld.getSectionContent(SectionID).data();
  517. std::string NewAddrStr = std::string(Mapping.substr(EqualsIdx + 1));
  518. uint64_t NewAddr;
  519. if (StringRef(NewAddrStr).getAsInteger(0, NewAddr))
  520. report_fatal_error("Invalid section address in mapping '" + Mapping +
  521. "'.");
  522. Dyld.mapSectionAddress(OldAddr, NewAddr);
  523. }
  524. }
  525. // Scatter sections in all directions!
  526. // Remaps section addresses for -verify mode. The following command line options
  527. // can be used to customize the layout of the memory within the phony target's
  528. // address space:
  529. // -target-addr-start <s> -- Specify where the phony target address range starts.
  530. // -target-addr-end <e> -- Specify where the phony target address range ends.
  531. // -target-section-sep <d> -- Specify how big a gap should be left between the
  532. // end of one section and the start of the next.
  533. // Defaults to zero. Set to something big
  534. // (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
  535. //
  536. static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple,
  537. RuntimeDyld &Dyld,
  538. TrivialMemoryManager &MemMgr) {
  539. // Set up a work list (section addr/size pairs).
  540. typedef std::list<const TrivialMemoryManager::SectionInfo*> WorklistT;
  541. WorklistT Worklist;
  542. for (const auto& CodeSection : MemMgr.FunctionMemory)
  543. Worklist.push_back(&CodeSection);
  544. for (const auto& DataSection : MemMgr.DataMemory)
  545. Worklist.push_back(&DataSection);
  546. // Keep an "already allocated" mapping of section target addresses to sizes.
  547. // Sections whose address mappings aren't specified on the command line will
  548. // allocated around the explicitly mapped sections while maintaining the
  549. // minimum separation.
  550. std::map<uint64_t, uint64_t> AlreadyAllocated;
  551. // Move the previously applied mappings (whether explicitly specified on the
  552. // command line, or implicitly set by RuntimeDyld) into the already-allocated
  553. // map.
  554. for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
  555. I != E;) {
  556. WorklistT::iterator Tmp = I;
  557. ++I;
  558. auto LoadAddr = Dyld.getSectionLoadAddress((*Tmp)->SectionID);
  559. if (LoadAddr != static_cast<uint64_t>(
  560. reinterpret_cast<uintptr_t>((*Tmp)->MB.base()))) {
  561. // A section will have a LoadAddr of 0 if it wasn't loaded for whatever
  562. // reason (e.g. zero byte COFF sections). Don't include those sections in
  563. // the allocation map.
  564. if (LoadAddr != 0)
  565. AlreadyAllocated[LoadAddr] = (*Tmp)->MB.allocatedSize();
  566. Worklist.erase(Tmp);
  567. }
  568. }
  569. // If the -target-addr-end option wasn't explicitly passed, then set it to a
  570. // sensible default based on the target triple.
  571. if (TargetAddrEnd.getNumOccurrences() == 0) {
  572. if (TargetTriple.isArch16Bit())
  573. TargetAddrEnd = (1ULL << 16) - 1;
  574. else if (TargetTriple.isArch32Bit())
  575. TargetAddrEnd = (1ULL << 32) - 1;
  576. // TargetAddrEnd already has a sensible default for 64-bit systems, so
  577. // there's nothing to do in the 64-bit case.
  578. }
  579. // Process any elements remaining in the worklist.
  580. while (!Worklist.empty()) {
  581. auto *CurEntry = Worklist.front();
  582. Worklist.pop_front();
  583. uint64_t NextSectionAddr = TargetAddrStart;
  584. for (const auto &Alloc : AlreadyAllocated)
  585. if (NextSectionAddr + CurEntry->MB.allocatedSize() + TargetSectionSep <=
  586. Alloc.first)
  587. break;
  588. else
  589. NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
  590. Dyld.mapSectionAddress(CurEntry->MB.base(), NextSectionAddr);
  591. AlreadyAllocated[NextSectionAddr] = CurEntry->MB.allocatedSize();
  592. }
  593. // Add dummy symbols to the memory manager.
  594. for (const auto &Mapping : DummySymbolMappings) {
  595. size_t EqualsIdx = Mapping.find_first_of('=');
  596. if (EqualsIdx == StringRef::npos)
  597. report_fatal_error("Invalid dummy symbol specification '" + Mapping +
  598. "'. Should be '<symbol name>=<addr>'");
  599. std::string Symbol = Mapping.substr(0, EqualsIdx);
  600. std::string AddrStr = Mapping.substr(EqualsIdx + 1);
  601. uint64_t Addr;
  602. if (StringRef(AddrStr).getAsInteger(0, Addr))
  603. report_fatal_error("Invalid symbol mapping '" + Mapping + "'.");
  604. MemMgr.addDummySymbol(Symbol, Addr);
  605. }
  606. }
  607. // Load and link the objects specified on the command line, but do not execute
  608. // anything. Instead, attach a RuntimeDyldChecker instance and call it to
  609. // verify the correctness of the linked memory.
  610. static int linkAndVerify() {
  611. // Check for missing triple.
  612. if (TripleName == "")
  613. ErrorAndExit("-triple required when running in -verify mode.");
  614. // Look up the target and build the disassembler.
  615. Triple TheTriple(Triple::normalize(TripleName));
  616. std::string ErrorStr;
  617. const Target *TheTarget =
  618. TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
  619. if (!TheTarget)
  620. ErrorAndExit("Error accessing target '" + TripleName + "': " + ErrorStr);
  621. TripleName = TheTriple.getTriple();
  622. std::unique_ptr<MCSubtargetInfo> STI(
  623. TheTarget->createMCSubtargetInfo(TripleName, MCPU, ""));
  624. if (!STI)
  625. ErrorAndExit("Unable to create subtarget info!");
  626. std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
  627. if (!MRI)
  628. ErrorAndExit("Unable to create target register info!");
  629. MCTargetOptions MCOptions;
  630. std::unique_ptr<MCAsmInfo> MAI(
  631. TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
  632. if (!MAI)
  633. ErrorAndExit("Unable to create target asm info!");
  634. MCContext Ctx(MAI.get(), MRI.get(), nullptr);
  635. std::unique_ptr<MCDisassembler> Disassembler(
  636. TheTarget->createMCDisassembler(*STI, Ctx));
  637. if (!Disassembler)
  638. ErrorAndExit("Unable to create disassembler!");
  639. std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  640. if (!MII)
  641. ErrorAndExit("Unable to create target instruction info!");
  642. std::unique_ptr<MCInstPrinter> InstPrinter(
  643. TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
  644. // Load any dylibs requested on the command line.
  645. loadDylibs();
  646. // Instantiate a dynamic linker.
  647. TrivialMemoryManager MemMgr;
  648. doPreallocation(MemMgr);
  649. struct StubID {
  650. unsigned SectionID;
  651. uint32_t Offset;
  652. };
  653. using StubInfos = StringMap<StubID>;
  654. using StubContainers = StringMap<StubInfos>;
  655. StubContainers StubMap;
  656. RuntimeDyld Dyld(MemMgr, MemMgr);
  657. Dyld.setProcessAllSections(true);
  658. Dyld.setNotifyStubEmitted([&StubMap](StringRef FilePath,
  659. StringRef SectionName,
  660. StringRef SymbolName, unsigned SectionID,
  661. uint32_t StubOffset) {
  662. std::string ContainerName =
  663. (sys::path::filename(FilePath) + "/" + SectionName).str();
  664. StubMap[ContainerName][SymbolName] = {SectionID, StubOffset};
  665. });
  666. auto GetSymbolInfo =
  667. [&Dyld, &MemMgr](
  668. StringRef Symbol) -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
  669. RuntimeDyldChecker::MemoryRegionInfo SymInfo;
  670. // First get the target address.
  671. if (auto InternalSymbol = Dyld.getSymbol(Symbol))
  672. SymInfo.setTargetAddress(InternalSymbol.getAddress());
  673. else {
  674. // Symbol not found in RuntimeDyld. Fall back to external lookup.
  675. #ifdef _MSC_VER
  676. using ExpectedLookupResult =
  677. MSVCPExpected<JITSymbolResolver::LookupResult>;
  678. #else
  679. using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
  680. #endif
  681. auto ResultP = std::make_shared<std::promise<ExpectedLookupResult>>();
  682. auto ResultF = ResultP->get_future();
  683. MemMgr.lookup(JITSymbolResolver::LookupSet({Symbol}),
  684. [=](Expected<JITSymbolResolver::LookupResult> Result) {
  685. ResultP->set_value(std::move(Result));
  686. });
  687. auto Result = ResultF.get();
  688. if (!Result)
  689. return Result.takeError();
  690. auto I = Result->find(Symbol);
  691. assert(I != Result->end() &&
  692. "Expected symbol address if no error occurred");
  693. SymInfo.setTargetAddress(I->second.getAddress());
  694. }
  695. // Now find the symbol content if possible (otherwise leave content as a
  696. // default-constructed StringRef).
  697. if (auto *SymAddr = Dyld.getSymbolLocalAddress(Symbol)) {
  698. unsigned SectionID = Dyld.getSymbolSectionID(Symbol);
  699. if (SectionID != ~0U) {
  700. char *CSymAddr = static_cast<char *>(SymAddr);
  701. StringRef SecContent = Dyld.getSectionContent(SectionID);
  702. uint64_t SymSize = SecContent.size() - (CSymAddr - SecContent.data());
  703. SymInfo.setContent(StringRef(CSymAddr, SymSize));
  704. }
  705. }
  706. return SymInfo;
  707. };
  708. auto IsSymbolValid = [&Dyld, GetSymbolInfo](StringRef Symbol) {
  709. if (Dyld.getSymbol(Symbol))
  710. return true;
  711. auto SymInfo = GetSymbolInfo(Symbol);
  712. if (!SymInfo) {
  713. logAllUnhandledErrors(SymInfo.takeError(), errs(), "RTDyldChecker: ");
  714. return false;
  715. }
  716. return SymInfo->getTargetAddress() != 0;
  717. };
  718. FileToSectionIDMap FileToSecIDMap;
  719. auto GetSectionInfo = [&Dyld, &FileToSecIDMap](StringRef FileName,
  720. StringRef SectionName)
  721. -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
  722. auto SectionID = getSectionId(FileToSecIDMap, FileName, SectionName);
  723. if (!SectionID)
  724. return SectionID.takeError();
  725. RuntimeDyldChecker::MemoryRegionInfo SecInfo;
  726. SecInfo.setTargetAddress(Dyld.getSectionLoadAddress(*SectionID));
  727. SecInfo.setContent(Dyld.getSectionContent(*SectionID));
  728. return SecInfo;
  729. };
  730. auto GetStubInfo = [&Dyld, &StubMap](StringRef StubContainer,
  731. StringRef SymbolName)
  732. -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
  733. if (!StubMap.count(StubContainer))
  734. return make_error<StringError>("Stub container not found: " +
  735. StubContainer,
  736. inconvertibleErrorCode());
  737. if (!StubMap[StubContainer].count(SymbolName))
  738. return make_error<StringError>("Symbol name " + SymbolName +
  739. " in stub container " + StubContainer,
  740. inconvertibleErrorCode());
  741. auto &SI = StubMap[StubContainer][SymbolName];
  742. RuntimeDyldChecker::MemoryRegionInfo StubMemInfo;
  743. StubMemInfo.setTargetAddress(Dyld.getSectionLoadAddress(SI.SectionID) +
  744. SI.Offset);
  745. StubMemInfo.setContent(
  746. Dyld.getSectionContent(SI.SectionID).substr(SI.Offset));
  747. return StubMemInfo;
  748. };
  749. // We will initialize this below once we have the first object file and can
  750. // know the endianness.
  751. std::unique_ptr<RuntimeDyldChecker> Checker;
  752. // If we don't have any input files, read from stdin.
  753. if (!InputFileList.size())
  754. InputFileList.push_back("-");
  755. for (auto &InputFile : InputFileList) {
  756. // Load the input memory buffer.
  757. ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
  758. MemoryBuffer::getFileOrSTDIN(InputFile);
  759. if (std::error_code EC = InputBuffer.getError())
  760. ErrorAndExit("unable to read input: '" + EC.message() + "'");
  761. Expected<std::unique_ptr<ObjectFile>> MaybeObj(
  762. ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
  763. if (!MaybeObj) {
  764. std::string Buf;
  765. raw_string_ostream OS(Buf);
  766. logAllUnhandledErrors(MaybeObj.takeError(), OS);
  767. OS.flush();
  768. ErrorAndExit("unable to create object file: '" + Buf + "'");
  769. }
  770. ObjectFile &Obj = **MaybeObj;
  771. if (!Checker)
  772. Checker = std::make_unique<RuntimeDyldChecker>(
  773. IsSymbolValid, GetSymbolInfo, GetSectionInfo, GetStubInfo,
  774. GetStubInfo, Obj.isLittleEndian() ? support::little : support::big,
  775. Disassembler.get(), InstPrinter.get(), dbgs());
  776. auto FileName = sys::path::filename(InputFile);
  777. MemMgr.setSectionIDsMap(&FileToSecIDMap[FileName]);
  778. // Load the object file
  779. Dyld.loadObject(Obj);
  780. if (Dyld.hasError()) {
  781. ErrorAndExit(Dyld.getErrorString());
  782. }
  783. }
  784. // Re-map the section addresses into the phony target address space and add
  785. // dummy symbols.
  786. applySpecificSectionMappings(Dyld, FileToSecIDMap);
  787. remapSectionsAndSymbols(TheTriple, Dyld, MemMgr);
  788. // Resolve all the relocations we can.
  789. Dyld.resolveRelocations();
  790. // Register EH frames.
  791. Dyld.registerEHFrames();
  792. int ErrorCode = checkAllExpressions(*Checker);
  793. if (Dyld.hasError())
  794. ErrorAndExit("RTDyld reported an error applying relocations:\n " +
  795. Dyld.getErrorString());
  796. return ErrorCode;
  797. }
  798. int main(int argc, char **argv) {
  799. InitLLVM X(argc, argv);
  800. ProgramName = argv[0];
  801. llvm::InitializeAllTargetInfos();
  802. llvm::InitializeAllTargetMCs();
  803. llvm::InitializeAllDisassemblers();
  804. cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
  805. ExitOnErr.setBanner(std::string(argv[0]) + ": ");
  806. Timers = ShowTimes ? std::make_unique<RTDyldTimers>() : nullptr;
  807. int Result;
  808. switch (Action) {
  809. case AC_Execute:
  810. Result = executeInput();
  811. break;
  812. case AC_PrintDebugLineInfo:
  813. Result =
  814. printLineInfoForInput(/* LoadObjects */ true, /* UseDebugObj */ true);
  815. break;
  816. case AC_PrintLineInfo:
  817. Result =
  818. printLineInfoForInput(/* LoadObjects */ true, /* UseDebugObj */ false);
  819. break;
  820. case AC_PrintObjectLineInfo:
  821. Result =
  822. printLineInfoForInput(/* LoadObjects */ false, /* UseDebugObj */ false);
  823. break;
  824. case AC_Verify:
  825. Result = linkAndVerify();
  826. break;
  827. }
  828. return Result;
  829. }