RuntimeDyldImpl.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. //===-- RuntimeDyldImpl.h - Run-time dynamic linker for MC-JIT --*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Interface for the implementations of runtime dynamic linker facilities.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDIMPL_H
  14. #define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDIMPL_H
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringMap.h"
  18. #include "llvm/ADT/Triple.h"
  19. #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
  20. #include "llvm/ExecutionEngine/RuntimeDyld.h"
  21. #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
  22. #include "llvm/Object/ObjectFile.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/Format.h"
  26. #include "llvm/Support/Host.h"
  27. #include "llvm/Support/Mutex.h"
  28. #include "llvm/Support/SwapByteOrder.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include <map>
  31. #include <system_error>
  32. using namespace llvm;
  33. using namespace llvm::object;
  34. namespace llvm {
  35. // Helper for extensive error checking in debug builds.
  36. inline std::error_code Check(std::error_code Err) {
  37. if (Err) {
  38. report_fatal_error(Err.message());
  39. }
  40. return Err;
  41. }
  42. class Twine;
  43. /// SectionEntry - represents a section emitted into memory by the dynamic
  44. /// linker.
  45. class SectionEntry {
  46. public:
  47. /// Name - section name.
  48. std::string Name;
  49. /// Address - address in the linker's memory where the section resides.
  50. uint8_t *Address;
  51. /// Size - section size. Doesn't include the stubs.
  52. size_t Size;
  53. /// LoadAddress - the address of the section in the target process's memory.
  54. /// Used for situations in which JIT-ed code is being executed in the address
  55. /// space of a separate process. If the code executes in the same address
  56. /// space where it was JIT-ed, this just equals Address.
  57. uint64_t LoadAddress;
  58. /// StubOffset - used for architectures with stub functions for far
  59. /// relocations (like ARM).
  60. uintptr_t StubOffset;
  61. /// ObjAddress - address of the section in the in-memory object file. Used
  62. /// for calculating relocations in some object formats (like MachO).
  63. uintptr_t ObjAddress;
  64. SectionEntry(StringRef name, uint8_t *address, size_t size,
  65. uintptr_t objAddress)
  66. : Name(name), Address(address), Size(size),
  67. LoadAddress(reinterpret_cast<uintptr_t>(address)), StubOffset(size),
  68. ObjAddress(objAddress) {}
  69. };
  70. /// RelocationEntry - used to represent relocations internally in the dynamic
  71. /// linker.
  72. class RelocationEntry {
  73. public:
  74. /// SectionID - the section this relocation points to.
  75. unsigned SectionID;
  76. /// Offset - offset into the section.
  77. uint64_t Offset;
  78. /// RelType - relocation type.
  79. uint32_t RelType;
  80. /// Addend - the relocation addend encoded in the instruction itself. Also
  81. /// used to make a relocation section relative instead of symbol relative.
  82. int64_t Addend;
  83. struct SectionPair {
  84. uint32_t SectionA;
  85. uint32_t SectionB;
  86. };
  87. /// SymOffset - Section offset of the relocation entry's symbol (used for GOT
  88. /// lookup).
  89. union {
  90. uint64_t SymOffset;
  91. SectionPair Sections;
  92. };
  93. /// True if this is a PCRel relocation (MachO specific).
  94. bool IsPCRel;
  95. /// The size of this relocation (MachO specific).
  96. unsigned Size;
  97. RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend)
  98. : SectionID(id), Offset(offset), RelType(type), Addend(addend),
  99. SymOffset(0), IsPCRel(false), Size(0) {}
  100. RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
  101. uint64_t symoffset)
  102. : SectionID(id), Offset(offset), RelType(type), Addend(addend),
  103. SymOffset(symoffset), IsPCRel(false), Size(0) {}
  104. RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
  105. bool IsPCRel, unsigned Size)
  106. : SectionID(id), Offset(offset), RelType(type), Addend(addend),
  107. SymOffset(0), IsPCRel(IsPCRel), Size(Size) {}
  108. RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
  109. unsigned SectionA, uint64_t SectionAOffset, unsigned SectionB,
  110. uint64_t SectionBOffset, bool IsPCRel, unsigned Size)
  111. : SectionID(id), Offset(offset), RelType(type),
  112. Addend(SectionAOffset - SectionBOffset + addend), IsPCRel(IsPCRel),
  113. Size(Size) {
  114. Sections.SectionA = SectionA;
  115. Sections.SectionB = SectionB;
  116. }
  117. };
  118. class RelocationValueRef {
  119. public:
  120. unsigned SectionID;
  121. uint64_t Offset;
  122. int64_t Addend;
  123. const char *SymbolName;
  124. RelocationValueRef() : SectionID(0), Offset(0), Addend(0),
  125. SymbolName(nullptr) {}
  126. inline bool operator==(const RelocationValueRef &Other) const {
  127. return SectionID == Other.SectionID && Offset == Other.Offset &&
  128. Addend == Other.Addend && SymbolName == Other.SymbolName;
  129. }
  130. inline bool operator<(const RelocationValueRef &Other) const {
  131. if (SectionID != Other.SectionID)
  132. return SectionID < Other.SectionID;
  133. if (Offset != Other.Offset)
  134. return Offset < Other.Offset;
  135. if (Addend != Other.Addend)
  136. return Addend < Other.Addend;
  137. return SymbolName < Other.SymbolName;
  138. }
  139. };
  140. /// @brief Symbol info for RuntimeDyld.
  141. class SymbolTableEntry : public JITSymbolBase {
  142. public:
  143. SymbolTableEntry()
  144. : JITSymbolBase(JITSymbolFlags::None), Offset(0), SectionID(0) {}
  145. SymbolTableEntry(unsigned SectionID, uint64_t Offset, JITSymbolFlags Flags)
  146. : JITSymbolBase(Flags), Offset(Offset), SectionID(SectionID) {}
  147. unsigned getSectionID() const { return SectionID; }
  148. uint64_t getOffset() const { return Offset; }
  149. private:
  150. uint64_t Offset;
  151. unsigned SectionID;
  152. };
  153. typedef StringMap<SymbolTableEntry> RTDyldSymbolTable;
  154. class RuntimeDyldImpl {
  155. friend class RuntimeDyld::LoadedObjectInfo;
  156. friend class RuntimeDyldCheckerImpl;
  157. protected:
  158. // The MemoryManager to load objects into.
  159. RuntimeDyld::MemoryManager &MemMgr;
  160. // The symbol resolver to use for external symbols.
  161. RuntimeDyld::SymbolResolver &Resolver;
  162. // Attached RuntimeDyldChecker instance. Null if no instance attached.
  163. RuntimeDyldCheckerImpl *Checker;
  164. // A list of all sections emitted by the dynamic linker. These sections are
  165. // referenced in the code by means of their index in this list - SectionID.
  166. typedef SmallVector<SectionEntry, 64> SectionList;
  167. SectionList Sections;
  168. typedef unsigned SID; // Type for SectionIDs
  169. #define RTDYLD_INVALID_SECTION_ID ((RuntimeDyldImpl::SID)(-1))
  170. // Keep a map of sections from object file to the SectionID which
  171. // references it.
  172. typedef std::map<SectionRef, unsigned> ObjSectionToIDMap;
  173. // A global symbol table for symbols from all loaded modules.
  174. RTDyldSymbolTable GlobalSymbolTable;
  175. // Keep a map of common symbols to their info pairs
  176. typedef std::vector<SymbolRef> CommonSymbolList;
  177. // For each symbol, keep a list of relocations based on it. Anytime
  178. // its address is reassigned (the JIT re-compiled the function, e.g.),
  179. // the relocations get re-resolved.
  180. // The symbol (or section) the relocation is sourced from is the Key
  181. // in the relocation list where it's stored.
  182. typedef SmallVector<RelocationEntry, 64> RelocationList;
  183. // Relocations to sections already loaded. Indexed by SectionID which is the
  184. // source of the address. The target where the address will be written is
  185. // SectionID/Offset in the relocation itself.
  186. DenseMap<unsigned, RelocationList> Relocations;
  187. // Relocations to external symbols that are not yet resolved. Symbols are
  188. // external when they aren't found in the global symbol table of all loaded
  189. // modules. This map is indexed by symbol name.
  190. StringMap<RelocationList> ExternalSymbolRelocations;
  191. typedef std::map<RelocationValueRef, uintptr_t> StubMap;
  192. Triple::ArchType Arch;
  193. bool IsTargetLittleEndian;
  194. bool IsMipsO32ABI;
  195. bool IsMipsN64ABI;
  196. // True if all sections should be passed to the memory manager, false if only
  197. // sections containing relocations should be. Defaults to 'false'.
  198. bool ProcessAllSections;
  199. // This mutex prevents simultaneously loading objects from two different
  200. // threads. This keeps us from having to protect individual data structures
  201. // and guarantees that section allocation requests to the memory manager
  202. // won't be interleaved between modules. It is also used in mapSectionAddress
  203. // and resolveRelocations to protect write access to internal data structures.
  204. //
  205. // loadObject may be called on the same thread during the handling of of
  206. // processRelocations, and that's OK. The handling of the relocation lists
  207. // is written in such a way as to work correctly if new elements are added to
  208. // the end of the list while the list is being processed.
  209. sys::Mutex lock;
  210. virtual unsigned getMaxStubSize() = 0;
  211. virtual unsigned getStubAlignment() = 0;
  212. bool HasError;
  213. std::string ErrorStr;
  214. // Set the error state and record an error string.
  215. bool Error(const Twine &Msg) {
  216. ErrorStr = Msg.str();
  217. HasError = true;
  218. return true;
  219. }
  220. uint64_t getSectionLoadAddress(unsigned SectionID) const {
  221. return Sections[SectionID].LoadAddress;
  222. }
  223. uint8_t *getSectionAddress(unsigned SectionID) const {
  224. return (uint8_t *)Sections[SectionID].Address;
  225. }
  226. void writeInt16BE(uint8_t *Addr, uint16_t Value) {
  227. if (IsTargetLittleEndian)
  228. sys::swapByteOrder(Value);
  229. *Addr = (Value >> 8) & 0xFF;
  230. *(Addr + 1) = Value & 0xFF;
  231. }
  232. void writeInt32BE(uint8_t *Addr, uint32_t Value) {
  233. if (IsTargetLittleEndian)
  234. sys::swapByteOrder(Value);
  235. *Addr = (Value >> 24) & 0xFF;
  236. *(Addr + 1) = (Value >> 16) & 0xFF;
  237. *(Addr + 2) = (Value >> 8) & 0xFF;
  238. *(Addr + 3) = Value & 0xFF;
  239. }
  240. void writeInt64BE(uint8_t *Addr, uint64_t Value) {
  241. if (IsTargetLittleEndian)
  242. sys::swapByteOrder(Value);
  243. *Addr = (Value >> 56) & 0xFF;
  244. *(Addr + 1) = (Value >> 48) & 0xFF;
  245. *(Addr + 2) = (Value >> 40) & 0xFF;
  246. *(Addr + 3) = (Value >> 32) & 0xFF;
  247. *(Addr + 4) = (Value >> 24) & 0xFF;
  248. *(Addr + 5) = (Value >> 16) & 0xFF;
  249. *(Addr + 6) = (Value >> 8) & 0xFF;
  250. *(Addr + 7) = Value & 0xFF;
  251. }
  252. virtual void setMipsABI(const ObjectFile &Obj) {
  253. IsMipsO32ABI = false;
  254. IsMipsN64ABI = false;
  255. }
  256. /// Endian-aware read Read the least significant Size bytes from Src.
  257. uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const;
  258. /// Endian-aware write. Write the least significant Size bytes from Value to
  259. /// Dst.
  260. void writeBytesUnaligned(uint64_t Value, uint8_t *Dst, unsigned Size) const;
  261. /// \brief Given the common symbols discovered in the object file, emit a
  262. /// new section for them and update the symbol mappings in the object and
  263. /// symbol table.
  264. void emitCommonSymbols(const ObjectFile &Obj, CommonSymbolList &CommonSymbols);
  265. /// \brief Emits section data from the object file to the MemoryManager.
  266. /// \param IsCode if it's true then allocateCodeSection() will be
  267. /// used for emits, else allocateDataSection() will be used.
  268. /// \return SectionID.
  269. unsigned emitSection(const ObjectFile &Obj, const SectionRef &Section,
  270. bool IsCode);
  271. /// \brief Find Section in LocalSections. If the secton is not found - emit
  272. /// it and store in LocalSections.
  273. /// \param IsCode if it's true then allocateCodeSection() will be
  274. /// used for emmits, else allocateDataSection() will be used.
  275. /// \return SectionID.
  276. unsigned findOrEmitSection(const ObjectFile &Obj, const SectionRef &Section,
  277. bool IsCode, ObjSectionToIDMap &LocalSections);
  278. // \brief Add a relocation entry that uses the given section.
  279. void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID);
  280. // \brief Add a relocation entry that uses the given symbol. This symbol may
  281. // be found in the global symbol table, or it may be external.
  282. void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName);
  283. /// \brief Emits long jump instruction to Addr.
  284. /// \return Pointer to the memory area for emitting target address.
  285. uint8_t *createStubFunction(uint8_t *Addr, unsigned AbiVariant = 0);
  286. /// \brief Resolves relocations from Relocs list with address from Value.
  287. void resolveRelocationList(const RelocationList &Relocs, uint64_t Value);
  288. /// \brief A object file specific relocation resolver
  289. /// \param RE The relocation to be resolved
  290. /// \param Value Target symbol address to apply the relocation action
  291. virtual void resolveRelocation(const RelocationEntry &RE, uint64_t Value) = 0;
  292. /// \brief Parses one or more object file relocations (some object files use
  293. /// relocation pairs) and stores it to Relocations or SymbolRelocations
  294. /// (this depends on the object file type).
  295. /// \return Iterator to the next relocation that needs to be parsed.
  296. virtual relocation_iterator
  297. processRelocationRef(unsigned SectionID, relocation_iterator RelI,
  298. const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID,
  299. StubMap &Stubs) = 0;
  300. /// \brief Resolve relocations to external symbols.
  301. void resolveExternalSymbols();
  302. // \brief Compute an upper bound of the memory that is required to load all
  303. // sections
  304. void computeTotalAllocSize(const ObjectFile &Obj, uint64_t &CodeSize,
  305. uint64_t &DataSizeRO, uint64_t &DataSizeRW);
  306. // \brief Compute the stub buffer size required for a section
  307. unsigned computeSectionStubBufSize(const ObjectFile &Obj,
  308. const SectionRef &Section);
  309. // \brief Implementation of the generic part of the loadObject algorithm.
  310. std::pair<unsigned, unsigned> loadObjectImpl(const object::ObjectFile &Obj);
  311. public:
  312. RuntimeDyldImpl(RuntimeDyld::MemoryManager &MemMgr,
  313. RuntimeDyld::SymbolResolver &Resolver)
  314. : MemMgr(MemMgr), Resolver(Resolver), Checker(nullptr),
  315. ProcessAllSections(false), HasError(false) {
  316. }
  317. virtual ~RuntimeDyldImpl();
  318. void setProcessAllSections(bool ProcessAllSections) {
  319. this->ProcessAllSections = ProcessAllSections;
  320. }
  321. void setRuntimeDyldChecker(RuntimeDyldCheckerImpl *Checker) {
  322. this->Checker = Checker;
  323. }
  324. virtual std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
  325. loadObject(const object::ObjectFile &Obj) = 0;
  326. uint8_t* getSymbolLocalAddress(StringRef Name) const {
  327. // FIXME: Just look up as a function for now. Overly simple of course.
  328. // Work in progress.
  329. RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
  330. if (pos == GlobalSymbolTable.end())
  331. return nullptr;
  332. const auto &SymInfo = pos->second;
  333. return getSectionAddress(SymInfo.getSectionID()) + SymInfo.getOffset();
  334. }
  335. RuntimeDyld::SymbolInfo getSymbol(StringRef Name) const {
  336. // FIXME: Just look up as a function for now. Overly simple of course.
  337. // Work in progress.
  338. RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
  339. if (pos == GlobalSymbolTable.end())
  340. return nullptr;
  341. const auto &SymEntry = pos->second;
  342. uint64_t TargetAddr =
  343. getSectionLoadAddress(SymEntry.getSectionID()) + SymEntry.getOffset();
  344. return RuntimeDyld::SymbolInfo(TargetAddr, SymEntry.getFlags());
  345. }
  346. void resolveRelocations();
  347. void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
  348. void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
  349. // Is the linker in an error state?
  350. bool hasError() { return HasError; }
  351. // Mark the error condition as handled and continue.
  352. void clearError() { HasError = false; }
  353. // Get the error message.
  354. StringRef getErrorString() { return ErrorStr; }
  355. virtual bool isCompatibleFile(const ObjectFile &Obj) const = 0;
  356. virtual void registerEHFrames();
  357. virtual void deregisterEHFrames();
  358. virtual void finalizeLoad(const ObjectFile &ObjImg,
  359. ObjSectionToIDMap &SectionMap) {}
  360. };
  361. } // end namespace llvm
  362. #endif