RuntimeDyld.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. protected:
  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. public:
  57. using NotifyStubEmittedFunction = std::function<void(
  58. StringRef FileName, StringRef SectionName, StringRef SymbolName,
  59. unsigned SectionID, uint32_t StubOffset)>;
  60. /// Information about the loaded object.
  61. class LoadedObjectInfo : public llvm::LoadedObjectInfo {
  62. friend class RuntimeDyldImpl;
  63. public:
  64. using ObjSectionToIDMap = std::map<object::SectionRef, unsigned>;
  65. LoadedObjectInfo(RuntimeDyldImpl &RTDyld, ObjSectionToIDMap ObjSecToIDMap)
  66. : RTDyld(RTDyld), ObjSecToIDMap(std::move(ObjSecToIDMap)) {}
  67. virtual object::OwningBinary<object::ObjectFile>
  68. getObjectForDebug(const object::ObjectFile &Obj) const = 0;
  69. uint64_t
  70. getSectionLoadAddress(const object::SectionRef &Sec) const override;
  71. protected:
  72. virtual void anchor();
  73. RuntimeDyldImpl &RTDyld;
  74. ObjSectionToIDMap ObjSecToIDMap;
  75. };
  76. /// Memory Management.
  77. class MemoryManager {
  78. friend class RuntimeDyld;
  79. public:
  80. MemoryManager() = default;
  81. virtual ~MemoryManager() = default;
  82. /// Allocate a memory block of (at least) the given size suitable for
  83. /// executable code. The SectionID is a unique identifier assigned by the
  84. /// RuntimeDyld instance, and optionally recorded by the memory manager to
  85. /// access a loaded section.
  86. virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
  87. unsigned SectionID,
  88. StringRef SectionName) = 0;
  89. /// Allocate a memory block of (at least) the given size suitable for data.
  90. /// The SectionID is a unique identifier assigned by the JIT engine, and
  91. /// optionally recorded by the memory manager to access a loaded section.
  92. virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
  93. unsigned SectionID,
  94. StringRef SectionName,
  95. bool IsReadOnly) = 0;
  96. /// Inform the memory manager about the total amount of memory required to
  97. /// allocate all sections to be loaded:
  98. /// \p CodeSize - the total size of all code sections
  99. /// \p DataSizeRO - the total size of all read-only data sections
  100. /// \p DataSizeRW - the total size of all read-write data sections
  101. ///
  102. /// Note that by default the callback is disabled. To enable it
  103. /// redefine the method needsToReserveAllocationSpace to return true.
  104. virtual void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign,
  105. uintptr_t RODataSize,
  106. uint32_t RODataAlign,
  107. uintptr_t RWDataSize,
  108. uint32_t RWDataAlign) {}
  109. /// Override to return true to enable the reserveAllocationSpace callback.
  110. virtual bool needsToReserveAllocationSpace() { return false; }
  111. /// Register the EH frames with the runtime so that c++ exceptions work.
  112. ///
  113. /// \p Addr parameter provides the local address of the EH frame section
  114. /// data, while \p LoadAddr provides the address of the data in the target
  115. /// address space. If the section has not been remapped (which will usually
  116. /// be the case for local execution) these two values will be the same.
  117. virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
  118. size_t Size) = 0;
  119. virtual void deregisterEHFrames() = 0;
  120. /// This method is called when object loading is complete and section page
  121. /// permissions can be applied. It is up to the memory manager implementation
  122. /// to decide whether or not to act on this method. The memory manager will
  123. /// typically allocate all sections as read-write and then apply specific
  124. /// permissions when this method is called. Code sections cannot be executed
  125. /// until this function has been called. In addition, any cache coherency
  126. /// operations needed to reliably use the memory are also performed.
  127. ///
  128. /// Returns true if an error occurred, false otherwise.
  129. virtual bool finalizeMemory(std::string *ErrMsg = nullptr) = 0;
  130. /// This method is called after an object has been loaded into memory but
  131. /// before relocations are applied to the loaded sections.
  132. ///
  133. /// Memory managers which are preparing code for execution in an external
  134. /// address space can use this call to remap the section addresses for the
  135. /// newly loaded object.
  136. ///
  137. /// For clients that do not need access to an ExecutionEngine instance this
  138. /// method should be preferred to its cousin
  139. /// MCJITMemoryManager::notifyObjectLoaded as this method is compatible with
  140. /// ORC JIT stacks.
  141. virtual void notifyObjectLoaded(RuntimeDyld &RTDyld,
  142. const object::ObjectFile &Obj) {}
  143. private:
  144. virtual void anchor();
  145. bool FinalizationLocked = false;
  146. };
  147. /// Construct a RuntimeDyld instance.
  148. RuntimeDyld(MemoryManager &MemMgr, JITSymbolResolver &Resolver);
  149. RuntimeDyld(const RuntimeDyld &) = delete;
  150. RuntimeDyld &operator=(const RuntimeDyld &) = delete;
  151. ~RuntimeDyld();
  152. /// Add the referenced object file to the list of objects to be loaded and
  153. /// relocated.
  154. std::unique_ptr<LoadedObjectInfo> loadObject(const object::ObjectFile &O);
  155. /// Get the address of our local copy of the symbol. This may or may not
  156. /// be the address used for relocation (clients can copy the data around
  157. /// and resolve relocatons based on where they put it).
  158. void *getSymbolLocalAddress(StringRef Name) const;
  159. /// Get the section ID for the section containing the given symbol.
  160. unsigned getSymbolSectionID(StringRef Name) const;
  161. /// Get the target address and flags for the named symbol.
  162. /// This address is the one used for relocation.
  163. JITEvaluatedSymbol getSymbol(StringRef Name) const;
  164. /// Returns a copy of the symbol table. This can be used by on-finalized
  165. /// callbacks to extract the symbol table before throwing away the
  166. /// RuntimeDyld instance. Because the map keys (StringRefs) are backed by
  167. /// strings inside the RuntimeDyld instance, the map should be processed
  168. /// before the RuntimeDyld instance is discarded.
  169. std::map<StringRef, JITEvaluatedSymbol> getSymbolTable() const;
  170. /// Resolve the relocations for all symbols we currently know about.
  171. void resolveRelocations();
  172. /// Map a section to its target address space value.
  173. /// Map the address of a JIT section as returned from the memory manager
  174. /// to the address in the target process as the running code will see it.
  175. /// This is the address which will be used for relocation resolution.
  176. void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
  177. /// Returns the section's working memory.
  178. StringRef getSectionContent(unsigned SectionID) const;
  179. /// If the section was loaded, return the section's load address,
  180. /// otherwise return None.
  181. uint64_t getSectionLoadAddress(unsigned SectionID) const;
  182. /// Set the NotifyStubEmitted callback. This is used for debugging
  183. /// purposes. A callback is made for each stub that is generated.
  184. void setNotifyStubEmitted(NotifyStubEmittedFunction NotifyStubEmitted) {
  185. this->NotifyStubEmitted = std::move(NotifyStubEmitted);
  186. }
  187. /// Register any EH frame sections that have been loaded but not previously
  188. /// registered with the memory manager. Note, RuntimeDyld is responsible
  189. /// for identifying the EH frame and calling the memory manager with the
  190. /// EH frame section data. However, the memory manager itself will handle
  191. /// the actual target-specific EH frame registration.
  192. void registerEHFrames();
  193. void deregisterEHFrames();
  194. bool hasError();
  195. StringRef getErrorString();
  196. /// By default, only sections that are "required for execution" are passed to
  197. /// the RTDyldMemoryManager, and other sections are discarded. Passing 'true'
  198. /// to this method will cause RuntimeDyld to pass all sections to its
  199. /// memory manager regardless of whether they are "required to execute" in the
  200. /// usual sense. This is useful for inspecting metadata sections that may not
  201. /// contain relocations, E.g. Debug info, stackmaps.
  202. ///
  203. /// Must be called before the first object file is loaded.
  204. void setProcessAllSections(bool ProcessAllSections) {
  205. assert(!Dyld && "setProcessAllSections must be called before loadObject.");
  206. this->ProcessAllSections = ProcessAllSections;
  207. }
  208. /// Perform all actions needed to make the code owned by this RuntimeDyld
  209. /// instance executable:
  210. ///
  211. /// 1) Apply relocations.
  212. /// 2) Register EH frames.
  213. /// 3) Update memory permissions*.
  214. ///
  215. /// * Finalization is potentially recursive**, and the 3rd step will only be
  216. /// applied by the outermost call to finalize. This allows different
  217. /// RuntimeDyld instances to share a memory manager without the innermost
  218. /// finalization locking the memory and causing relocation fixup errors in
  219. /// outer instances.
  220. ///
  221. /// ** Recursive finalization occurs when one RuntimeDyld instances needs the
  222. /// address of a symbol owned by some other instance in order to apply
  223. /// relocations.
  224. ///
  225. void finalizeWithMemoryManagerLocking();
  226. private:
  227. friend void jitLinkForORC(
  228. object::OwningBinary<object::ObjectFile> O,
  229. RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver,
  230. bool ProcessAllSections,
  231. unique_function<Error(const object::ObjectFile &Obj, LoadedObjectInfo &,
  232. std::map<StringRef, JITEvaluatedSymbol>)>
  233. OnLoaded,
  234. unique_function<void(object::OwningBinary<object::ObjectFile> O,
  235. std::unique_ptr<LoadedObjectInfo>, Error)>
  236. OnEmitted);
  237. // RuntimeDyldImpl is the actual class. RuntimeDyld is just the public
  238. // interface.
  239. std::unique_ptr<RuntimeDyldImpl> Dyld;
  240. MemoryManager &MemMgr;
  241. JITSymbolResolver &Resolver;
  242. bool ProcessAllSections;
  243. NotifyStubEmittedFunction NotifyStubEmitted;
  244. };
  245. // Asynchronous JIT link for ORC.
  246. //
  247. // Warning: This API is experimental and probably should not be used by anyone
  248. // but ORC's RTDyldObjectLinkingLayer2. Internally it constructs a RuntimeDyld
  249. // instance and uses continuation passing to perform the fix-up and finalize
  250. // steps asynchronously.
  251. void jitLinkForORC(
  252. object::OwningBinary<object::ObjectFile> O,
  253. RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver,
  254. bool ProcessAllSections,
  255. unique_function<Error(const object::ObjectFile &Obj,
  256. RuntimeDyld::LoadedObjectInfo &,
  257. std::map<StringRef, JITEvaluatedSymbol>)>
  258. OnLoaded,
  259. unique_function<void(object::OwningBinary<object::ObjectFile>,
  260. std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>
  261. OnEmitted);
  262. } // end namespace llvm
  263. #endif // LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
  264. #ifdef __GNUC__
  265. #pragma GCC diagnostic pop
  266. #endif