llvm-rtdyld.cpp 37 KB

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