RuntimeDyld.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- RuntimeDyld.h - Run-time dynamic linker for MC-JIT -------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // Interface for the runtime dynamic linker facilities of the MC-JIT.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
  18. #define LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
  19. #include "llvm/ADT/FunctionExtras.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/DebugInfo/DIContext.h"
  23. #include "llvm/ExecutionEngine/JITSymbol.h"
  24. #include "llvm/Object/ObjectFile.h"
  25. #include "llvm/Support/Error.h"
  26. #include <algorithm>
  27. #include <cassert>
  28. #include <cstddef>
  29. #include <cstdint>
  30. #include <map>
  31. #include <memory>
  32. #include <string>
  33. #include <system_error>
  34. namespace llvm {
  35. namespace object {
  36. template <typename T> class OwningBinary;
  37. } // end namespace object
  38. /// Base class for errors originating in RuntimeDyld, e.g. missing relocation
  39. /// support.
  40. class RuntimeDyldError : public ErrorInfo<RuntimeDyldError> {
  41. public:
  42. static char ID;
  43. RuntimeDyldError(std::string ErrMsg) : ErrMsg(std::move(ErrMsg)) {}
  44. void log(raw_ostream &OS) const override;
  45. const std::string &getErrorMessage() const { return ErrMsg; }
  46. std::error_code convertToErrorCode() const override;
  47. private:
  48. std::string ErrMsg;
  49. };
  50. class RuntimeDyldImpl;
  51. class RuntimeDyld {
  52. public:
  53. // Change the address associated with a section when resolving relocations.
  54. // Any relocations already associated with the symbol will be re-resolved.
  55. void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
  56. using NotifyStubEmittedFunction = std::function<void(
  57. StringRef FileName, StringRef SectionName, StringRef SymbolName,
  58. unsigned SectionID, uint32_t StubOffset)>;
  59. /// Information about the loaded object.
  60. class LoadedObjectInfo : public llvm::LoadedObjectInfo {
  61. friend class RuntimeDyldImpl;
  62. public:
  63. using ObjSectionToIDMap = std::map<object::SectionRef, unsigned>;
  64. LoadedObjectInfo(RuntimeDyldImpl &RTDyld, ObjSectionToIDMap ObjSecToIDMap)
  65. : RTDyld(RTDyld), ObjSecToIDMap(std::move(ObjSecToIDMap)) {}
  66. virtual object::OwningBinary<object::ObjectFile>
  67. getObjectForDebug(const object::ObjectFile &Obj) const = 0;
  68. uint64_t
  69. getSectionLoadAddress(const object::SectionRef &Sec) const override;
  70. protected:
  71. virtual void anchor();
  72. RuntimeDyldImpl &RTDyld;
  73. ObjSectionToIDMap ObjSecToIDMap;
  74. };
  75. /// Memory Management.
  76. class MemoryManager {
  77. friend class RuntimeDyld;
  78. public:
  79. MemoryManager() = default;
  80. virtual ~MemoryManager() = default;
  81. /// Allocate a memory block of (at least) the given size suitable for
  82. /// executable code. The SectionID is a unique identifier assigned by the
  83. /// RuntimeDyld instance, and optionally recorded by the memory manager to
  84. /// access a loaded section.
  85. virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
  86. unsigned SectionID,
  87. StringRef SectionName) = 0;
  88. /// Allocate a memory block of (at least) the given size suitable for data.
  89. /// The SectionID is a unique identifier assigned by the JIT engine, and
  90. /// optionally recorded by the memory manager to access a loaded section.
  91. virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
  92. unsigned SectionID,
  93. StringRef SectionName,
  94. bool IsReadOnly) = 0;
  95. /// An allocated TLS section
  96. struct TLSSection {
  97. /// The pointer to the initialization image
  98. uint8_t *InitializationImage;
  99. /// The TLS offset
  100. intptr_t Offset;
  101. };
  102. /// Allocate a memory block of (at least) the given size to be used for
  103. /// thread-local storage (TLS).
  104. virtual TLSSection allocateTLSSection(uintptr_t Size, unsigned Alignment,
  105. unsigned SectionID,
  106. StringRef SectionName);
  107. /// Inform the memory manager about the total amount of memory required to
  108. /// allocate all sections to be loaded:
  109. /// \p CodeSize - the total size of all code sections
  110. /// \p DataSizeRO - the total size of all read-only data sections
  111. /// \p DataSizeRW - the total size of all read-write data sections
  112. ///
  113. /// Note that by default the callback is disabled. To enable it
  114. /// redefine the method needsToReserveAllocationSpace to return true.
  115. virtual void reserveAllocationSpace(uintptr_t CodeSize, Align CodeAlign,
  116. uintptr_t RODataSize, Align RODataAlign,
  117. uintptr_t RWDataSize,
  118. Align RWDataAlign) {}
  119. /// Override to return true to enable the reserveAllocationSpace callback.
  120. virtual bool needsToReserveAllocationSpace() { return false; }
  121. /// Override to return false to tell LLVM no stub space will be needed.
  122. /// This requires some guarantees depending on architecuture, but when
  123. /// you know what you are doing it saves allocated space.
  124. virtual bool allowStubAllocation() const { return true; }
  125. /// Register the EH frames with the runtime so that c++ exceptions work.
  126. ///
  127. /// \p Addr parameter provides the local address of the EH frame section
  128. /// data, while \p LoadAddr provides the address of the data in the target
  129. /// address space. If the section has not been remapped (which will usually
  130. /// be the case for local execution) these two values will be the same.
  131. virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
  132. size_t Size) = 0;
  133. virtual void deregisterEHFrames() = 0;
  134. /// This method is called when object loading is complete and section page
  135. /// permissions can be applied. It is up to the memory manager implementation
  136. /// to decide whether or not to act on this method. The memory manager will
  137. /// typically allocate all sections as read-write and then apply specific
  138. /// permissions when this method is called. Code sections cannot be executed
  139. /// until this function has been called. In addition, any cache coherency
  140. /// operations needed to reliably use the memory are also performed.
  141. ///
  142. /// Returns true if an error occurred, false otherwise.
  143. virtual bool finalizeMemory(std::string *ErrMsg = nullptr) = 0;
  144. /// This method is called after an object has been loaded into memory but
  145. /// before relocations are applied to the loaded sections.
  146. ///
  147. /// Memory managers which are preparing code for execution in an external
  148. /// address space can use this call to remap the section addresses for the
  149. /// newly loaded object.
  150. ///
  151. /// For clients that do not need access to an ExecutionEngine instance this
  152. /// method should be preferred to its cousin
  153. /// MCJITMemoryManager::notifyObjectLoaded as this method is compatible with
  154. /// ORC JIT stacks.
  155. virtual void notifyObjectLoaded(RuntimeDyld &RTDyld,
  156. const object::ObjectFile &Obj) {}
  157. private:
  158. virtual void anchor();
  159. bool FinalizationLocked = false;
  160. };
  161. /// Construct a RuntimeDyld instance.
  162. RuntimeDyld(MemoryManager &MemMgr, JITSymbolResolver &Resolver);
  163. RuntimeDyld(const RuntimeDyld &) = delete;
  164. RuntimeDyld &operator=(const RuntimeDyld &) = delete;
  165. ~RuntimeDyld();
  166. /// Add the referenced object file to the list of objects to be loaded and
  167. /// relocated.
  168. std::unique_ptr<LoadedObjectInfo> loadObject(const object::ObjectFile &O);
  169. /// Get the address of our local copy of the symbol. This may or may not
  170. /// be the address used for relocation (clients can copy the data around
  171. /// and resolve relocatons based on where they put it).
  172. void *getSymbolLocalAddress(StringRef Name) const;
  173. /// Get the section ID for the section containing the given symbol.
  174. unsigned getSymbolSectionID(StringRef Name) const;
  175. /// Get the target address and flags for the named symbol.
  176. /// This address is the one used for relocation.
  177. JITEvaluatedSymbol getSymbol(StringRef Name) const;
  178. /// Returns a copy of the symbol table. This can be used by on-finalized
  179. /// callbacks to extract the symbol table before throwing away the
  180. /// RuntimeDyld instance. Because the map keys (StringRefs) are backed by
  181. /// strings inside the RuntimeDyld instance, the map should be processed
  182. /// before the RuntimeDyld instance is discarded.
  183. std::map<StringRef, JITEvaluatedSymbol> getSymbolTable() const;
  184. /// Resolve the relocations for all symbols we currently know about.
  185. void resolveRelocations();
  186. /// Map a section to its target address space value.
  187. /// Map the address of a JIT section as returned from the memory manager
  188. /// to the address in the target process as the running code will see it.
  189. /// This is the address which will be used for relocation resolution.
  190. void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
  191. /// Returns the section's working memory.
  192. StringRef getSectionContent(unsigned SectionID) const;
  193. /// If the section was loaded, return the section's load address,
  194. /// otherwise return std::nullopt.
  195. uint64_t getSectionLoadAddress(unsigned SectionID) const;
  196. /// Set the NotifyStubEmitted callback. This is used for debugging
  197. /// purposes. A callback is made for each stub that is generated.
  198. void setNotifyStubEmitted(NotifyStubEmittedFunction NotifyStubEmitted) {
  199. this->NotifyStubEmitted = std::move(NotifyStubEmitted);
  200. }
  201. /// Register any EH frame sections that have been loaded but not previously
  202. /// registered with the memory manager. Note, RuntimeDyld is responsible
  203. /// for identifying the EH frame and calling the memory manager with the
  204. /// EH frame section data. However, the memory manager itself will handle
  205. /// the actual target-specific EH frame registration.
  206. void registerEHFrames();
  207. void deregisterEHFrames();
  208. bool hasError();
  209. StringRef getErrorString();
  210. /// By default, only sections that are "required for execution" are passed to
  211. /// the RTDyldMemoryManager, and other sections are discarded. Passing 'true'
  212. /// to this method will cause RuntimeDyld to pass all sections to its
  213. /// memory manager regardless of whether they are "required to execute" in the
  214. /// usual sense. This is useful for inspecting metadata sections that may not
  215. /// contain relocations, E.g. Debug info, stackmaps.
  216. ///
  217. /// Must be called before the first object file is loaded.
  218. void setProcessAllSections(bool ProcessAllSections) {
  219. assert(!Dyld && "setProcessAllSections must be called before loadObject.");
  220. this->ProcessAllSections = ProcessAllSections;
  221. }
  222. /// Perform all actions needed to make the code owned by this RuntimeDyld
  223. /// instance executable:
  224. ///
  225. /// 1) Apply relocations.
  226. /// 2) Register EH frames.
  227. /// 3) Update memory permissions*.
  228. ///
  229. /// * Finalization is potentially recursive**, and the 3rd step will only be
  230. /// applied by the outermost call to finalize. This allows different
  231. /// RuntimeDyld instances to share a memory manager without the innermost
  232. /// finalization locking the memory and causing relocation fixup errors in
  233. /// outer instances.
  234. ///
  235. /// ** Recursive finalization occurs when one RuntimeDyld instances needs the
  236. /// address of a symbol owned by some other instance in order to apply
  237. /// relocations.
  238. ///
  239. void finalizeWithMemoryManagerLocking();
  240. private:
  241. friend void jitLinkForORC(
  242. object::OwningBinary<object::ObjectFile> O,
  243. RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver,
  244. bool ProcessAllSections,
  245. unique_function<Error(const object::ObjectFile &Obj, LoadedObjectInfo &,
  246. std::map<StringRef, JITEvaluatedSymbol>)>
  247. OnLoaded,
  248. unique_function<void(object::OwningBinary<object::ObjectFile> O,
  249. std::unique_ptr<LoadedObjectInfo>, Error)>
  250. OnEmitted);
  251. // RuntimeDyldImpl is the actual class. RuntimeDyld is just the public
  252. // interface.
  253. std::unique_ptr<RuntimeDyldImpl> Dyld;
  254. MemoryManager &MemMgr;
  255. JITSymbolResolver &Resolver;
  256. bool ProcessAllSections;
  257. NotifyStubEmittedFunction NotifyStubEmitted;
  258. };
  259. // Asynchronous JIT link for ORC.
  260. //
  261. // Warning: This API is experimental and probably should not be used by anyone
  262. // but ORC's RTDyldObjectLinkingLayer2. Internally it constructs a RuntimeDyld
  263. // instance and uses continuation passing to perform the fix-up and finalize
  264. // steps asynchronously.
  265. void jitLinkForORC(
  266. object::OwningBinary<object::ObjectFile> O,
  267. RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver,
  268. bool ProcessAllSections,
  269. unique_function<Error(const object::ObjectFile &Obj,
  270. RuntimeDyld::LoadedObjectInfo &,
  271. std::map<StringRef, JITEvaluatedSymbol>)>
  272. OnLoaded,
  273. unique_function<void(object::OwningBinary<object::ObjectFile>,
  274. std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>
  275. OnEmitted);
  276. } // end namespace llvm
  277. #endif // LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
  278. #ifdef __GNUC__
  279. #pragma GCC diagnostic pop
  280. #endif