1 //===-- RuntimeDyldImpl.h - Run-time dynamic linker for MC-JIT --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Interface for the implementations of runtime dynamic linker facilities.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDIMPL_H
15 #define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDIMPL_H
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
21 #include "llvm/ExecutionEngine/RuntimeDyld.h"
22 #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
23 #include "llvm/Object/ObjectFile.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/Format.h"
27 #include "llvm/Support/Host.h"
28 #include "llvm/Support/Mutex.h"
29 #include "llvm/Support/SwapByteOrder.h"
31 #include <system_error>
32 #include <unordered_map>
35 using namespace llvm::object;
41 #define UNIMPLEMENTED_RELOC(RelType) \
43 return make_error<RuntimeDyldError>("Unimplemented relocation: " #RelType)
45 /// SectionEntry - represents a section emitted into memory by the dynamic
48 /// Name - section name.
51 /// Address - address in the linker's memory where the section resides.
54 /// Size - section size. Doesn't include the stubs.
57 /// LoadAddress - the address of the section in the target process's memory.
58 /// Used for situations in which JIT-ed code is being executed in the address
59 /// space of a separate process. If the code executes in the same address
60 /// space where it was JIT-ed, this just equals Address.
63 /// StubOffset - used for architectures with stub functions for far
64 /// relocations (like ARM).
67 /// The total amount of space allocated for this section. This includes the
68 /// section size and the maximum amount of space that the stubs can occupy.
69 size_t AllocationSize;
71 /// ObjAddress - address of the section in the in-memory object file. Used
72 /// for calculating relocations in some object formats (like MachO).
76 SectionEntry(StringRef name, uint8_t *address, size_t size,
77 size_t allocationSize, uintptr_t objAddress)
78 : Name(name), Address(address), Size(size),
79 LoadAddress(reinterpret_cast<uintptr_t>(address)), StubOffset(size),
80 AllocationSize(allocationSize), ObjAddress(objAddress) {
81 // AllocationSize is used only in asserts, prevent an "unused private field"
86 StringRef getName() const { return Name; }
88 uint8_t *getAddress() const { return Address; }
90 /// \brief Return the address of this section with an offset.
91 uint8_t *getAddressWithOffset(unsigned OffsetBytes) const {
92 assert(OffsetBytes <= AllocationSize && "Offset out of bounds!");
93 return Address + OffsetBytes;
96 size_t getSize() const { return Size; }
98 uint64_t getLoadAddress() const { return LoadAddress; }
99 void setLoadAddress(uint64_t LA) { LoadAddress = LA; }
101 /// \brief Return the load address of this section with an offset.
102 uint64_t getLoadAddressWithOffset(unsigned OffsetBytes) const {
103 assert(OffsetBytes <= AllocationSize && "Offset out of bounds!");
104 return LoadAddress + OffsetBytes;
107 uintptr_t getStubOffset() const { return StubOffset; }
109 void advanceStubOffset(unsigned StubSize) {
110 StubOffset += StubSize;
111 assert(StubOffset <= AllocationSize && "Not enough space allocated!");
114 uintptr_t getObjAddress() const { return ObjAddress; }
117 /// RelocationEntry - used to represent relocations internally in the dynamic
119 class RelocationEntry {
121 /// SectionID - the section this relocation points to.
124 /// Offset - offset into the section.
127 /// RelType - relocation type.
130 /// Addend - the relocation addend encoded in the instruction itself. Also
131 /// used to make a relocation section relative instead of symbol relative.
139 /// SymOffset - Section offset of the relocation entry's symbol (used for GOT
143 SectionPair Sections;
146 /// True if this is a PCRel relocation (MachO specific).
149 /// The size of this relocation (MachO specific).
153 bool IsTargetThumbFunc;
155 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend)
156 : SectionID(id), Offset(offset), RelType(type), Addend(addend),
157 SymOffset(0), IsPCRel(false), Size(0), IsTargetThumbFunc(false) {}
159 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
161 : SectionID(id), Offset(offset), RelType(type), Addend(addend),
162 SymOffset(symoffset), IsPCRel(false), Size(0),
163 IsTargetThumbFunc(false) {}
165 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
166 bool IsPCRel, unsigned Size)
167 : SectionID(id), Offset(offset), RelType(type), Addend(addend),
168 SymOffset(0), IsPCRel(IsPCRel), Size(Size), IsTargetThumbFunc(false) {}
170 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
171 unsigned SectionA, uint64_t SectionAOffset, unsigned SectionB,
172 uint64_t SectionBOffset, bool IsPCRel, unsigned Size)
173 : SectionID(id), Offset(offset), RelType(type),
174 Addend(SectionAOffset - SectionBOffset + addend), IsPCRel(IsPCRel),
175 Size(Size), IsTargetThumbFunc(false) {
176 Sections.SectionA = SectionA;
177 Sections.SectionB = SectionB;
180 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
181 unsigned SectionA, uint64_t SectionAOffset, unsigned SectionB,
182 uint64_t SectionBOffset, bool IsPCRel, unsigned Size,
183 bool IsTargetThumbFunc)
184 : SectionID(id), Offset(offset), RelType(type),
185 Addend(SectionAOffset - SectionBOffset + addend), IsPCRel(IsPCRel),
186 Size(Size), IsTargetThumbFunc(IsTargetThumbFunc) {
187 Sections.SectionA = SectionA;
188 Sections.SectionB = SectionB;
192 class RelocationValueRef {
197 const char *SymbolName;
198 RelocationValueRef() : SectionID(0), Offset(0), Addend(0),
199 SymbolName(nullptr) {}
201 inline bool operator==(const RelocationValueRef &Other) const {
202 return SectionID == Other.SectionID && Offset == Other.Offset &&
203 Addend == Other.Addend && SymbolName == Other.SymbolName;
205 inline bool operator<(const RelocationValueRef &Other) const {
206 if (SectionID != Other.SectionID)
207 return SectionID < Other.SectionID;
208 if (Offset != Other.Offset)
209 return Offset < Other.Offset;
210 if (Addend != Other.Addend)
211 return Addend < Other.Addend;
212 return SymbolName < Other.SymbolName;
216 /// @brief Symbol info for RuntimeDyld.
217 class SymbolTableEntry {
220 : Offset(0), SectionID(0) {}
222 SymbolTableEntry(unsigned SectionID, uint64_t Offset, JITSymbolFlags Flags)
223 : Offset(Offset), SectionID(SectionID), Flags(Flags) {}
225 unsigned getSectionID() const { return SectionID; }
226 uint64_t getOffset() const { return Offset; }
228 JITSymbolFlags getFlags() const { return Flags; }
233 JITSymbolFlags Flags;
236 typedef StringMap<SymbolTableEntry> RTDyldSymbolTable;
238 class RuntimeDyldImpl {
239 friend class RuntimeDyld::LoadedObjectInfo;
240 friend class RuntimeDyldCheckerImpl;
242 static const unsigned AbsoluteSymbolSection = ~0U;
244 // The MemoryManager to load objects into.
245 RuntimeDyld::MemoryManager &MemMgr;
247 // The symbol resolver to use for external symbols.
248 JITSymbolResolver &Resolver;
250 // Attached RuntimeDyldChecker instance. Null if no instance attached.
251 RuntimeDyldCheckerImpl *Checker;
253 // A list of all sections emitted by the dynamic linker. These sections are
254 // referenced in the code by means of their index in this list - SectionID.
255 typedef SmallVector<SectionEntry, 64> SectionList;
256 SectionList Sections;
258 typedef unsigned SID; // Type for SectionIDs
259 #define RTDYLD_INVALID_SECTION_ID ((RuntimeDyldImpl::SID)(-1))
261 // Keep a map of sections from object file to the SectionID which
263 typedef std::map<SectionRef, unsigned> ObjSectionToIDMap;
265 // A global symbol table for symbols from all loaded modules.
266 RTDyldSymbolTable GlobalSymbolTable;
268 // Keep a map of common symbols to their info pairs
269 typedef std::vector<SymbolRef> CommonSymbolList;
271 // For each symbol, keep a list of relocations based on it. Anytime
272 // its address is reassigned (the JIT re-compiled the function, e.g.),
273 // the relocations get re-resolved.
274 // The symbol (or section) the relocation is sourced from is the Key
275 // in the relocation list where it's stored.
276 typedef SmallVector<RelocationEntry, 64> RelocationList;
277 // Relocations to sections already loaded. Indexed by SectionID which is the
278 // source of the address. The target where the address will be written is
279 // SectionID/Offset in the relocation itself.
280 std::unordered_map<unsigned, RelocationList> Relocations;
282 // Relocations to external symbols that are not yet resolved. Symbols are
283 // external when they aren't found in the global symbol table of all loaded
284 // modules. This map is indexed by symbol name.
285 StringMap<RelocationList> ExternalSymbolRelocations;
288 typedef std::map<RelocationValueRef, uintptr_t> StubMap;
290 Triple::ArchType Arch;
291 bool IsTargetLittleEndian;
296 // True if all sections should be passed to the memory manager, false if only
297 // sections containing relocations should be. Defaults to 'false'.
298 bool ProcessAllSections;
300 // This mutex prevents simultaneously loading objects from two different
301 // threads. This keeps us from having to protect individual data structures
302 // and guarantees that section allocation requests to the memory manager
303 // won't be interleaved between modules. It is also used in mapSectionAddress
304 // and resolveRelocations to protect write access to internal data structures.
306 // loadObject may be called on the same thread during the handling of of
307 // processRelocations, and that's OK. The handling of the relocation lists
308 // is written in such a way as to work correctly if new elements are added to
309 // the end of the list while the list is being processed.
312 virtual unsigned getMaxStubSize() = 0;
313 virtual unsigned getStubAlignment() = 0;
316 std::string ErrorStr;
318 uint64_t getSectionLoadAddress(unsigned SectionID) const {
319 return Sections[SectionID].getLoadAddress();
322 uint8_t *getSectionAddress(unsigned SectionID) const {
323 return Sections[SectionID].getAddress();
326 void writeInt16BE(uint8_t *Addr, uint16_t Value) {
327 if (IsTargetLittleEndian)
328 sys::swapByteOrder(Value);
329 *Addr = (Value >> 8) & 0xFF;
330 *(Addr + 1) = Value & 0xFF;
333 void writeInt32BE(uint8_t *Addr, uint32_t Value) {
334 if (IsTargetLittleEndian)
335 sys::swapByteOrder(Value);
336 *Addr = (Value >> 24) & 0xFF;
337 *(Addr + 1) = (Value >> 16) & 0xFF;
338 *(Addr + 2) = (Value >> 8) & 0xFF;
339 *(Addr + 3) = Value & 0xFF;
342 void writeInt64BE(uint8_t *Addr, uint64_t Value) {
343 if (IsTargetLittleEndian)
344 sys::swapByteOrder(Value);
345 *Addr = (Value >> 56) & 0xFF;
346 *(Addr + 1) = (Value >> 48) & 0xFF;
347 *(Addr + 2) = (Value >> 40) & 0xFF;
348 *(Addr + 3) = (Value >> 32) & 0xFF;
349 *(Addr + 4) = (Value >> 24) & 0xFF;
350 *(Addr + 5) = (Value >> 16) & 0xFF;
351 *(Addr + 6) = (Value >> 8) & 0xFF;
352 *(Addr + 7) = Value & 0xFF;
355 virtual void setMipsABI(const ObjectFile &Obj) {
356 IsMipsO32ABI = false;
357 IsMipsN32ABI = false;
358 IsMipsN64ABI = false;
361 /// Endian-aware read Read the least significant Size bytes from Src.
362 uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const;
364 /// Endian-aware write. Write the least significant Size bytes from Value to
366 void writeBytesUnaligned(uint64_t Value, uint8_t *Dst, unsigned Size) const;
368 /// \brief Given the common symbols discovered in the object file, emit a
369 /// new section for them and update the symbol mappings in the object and
371 Error emitCommonSymbols(const ObjectFile &Obj,
372 CommonSymbolList &CommonSymbols);
374 /// \brief Emits section data from the object file to the MemoryManager.
375 /// \param IsCode if it's true then allocateCodeSection() will be
376 /// used for emits, else allocateDataSection() will be used.
377 /// \return SectionID.
378 Expected<unsigned> emitSection(const ObjectFile &Obj,
379 const SectionRef &Section,
382 /// \brief Find Section in LocalSections. If the secton is not found - emit
383 /// it and store in LocalSections.
384 /// \param IsCode if it's true then allocateCodeSection() will be
385 /// used for emmits, else allocateDataSection() will be used.
386 /// \return SectionID.
387 Expected<unsigned> findOrEmitSection(const ObjectFile &Obj,
388 const SectionRef &Section, bool IsCode,
389 ObjSectionToIDMap &LocalSections);
391 // \brief Add a relocation entry that uses the given section.
392 void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID);
394 // \brief Add a relocation entry that uses the given symbol. This symbol may
395 // be found in the global symbol table, or it may be external.
396 void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName);
398 /// \brief Emits long jump instruction to Addr.
399 /// \return Pointer to the memory area for emitting target address.
400 uint8_t *createStubFunction(uint8_t *Addr, unsigned AbiVariant = 0);
402 /// \brief Resolves relocations from Relocs list with address from Value.
403 void resolveRelocationList(const RelocationList &Relocs, uint64_t Value);
405 /// \brief A object file specific relocation resolver
406 /// \param RE The relocation to be resolved
407 /// \param Value Target symbol address to apply the relocation action
408 virtual void resolveRelocation(const RelocationEntry &RE, uint64_t Value) = 0;
410 /// \brief Parses one or more object file relocations (some object files use
411 /// relocation pairs) and stores it to Relocations or SymbolRelocations
412 /// (this depends on the object file type).
413 /// \return Iterator to the next relocation that needs to be parsed.
414 virtual Expected<relocation_iterator>
415 processRelocationRef(unsigned SectionID, relocation_iterator RelI,
416 const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID,
419 /// \brief Resolve relocations to external symbols.
420 Error resolveExternalSymbols();
422 // \brief Compute an upper bound of the memory that is required to load all
424 Error computeTotalAllocSize(const ObjectFile &Obj,
425 uint64_t &CodeSize, uint32_t &CodeAlign,
426 uint64_t &RODataSize, uint32_t &RODataAlign,
427 uint64_t &RWDataSize, uint32_t &RWDataAlign);
429 // \brief Compute GOT size
430 unsigned computeGOTSize(const ObjectFile &Obj);
432 // \brief Compute the stub buffer size required for a section
433 unsigned computeSectionStubBufSize(const ObjectFile &Obj,
434 const SectionRef &Section);
436 // \brief Implementation of the generic part of the loadObject algorithm.
437 Expected<ObjSectionToIDMap> loadObjectImpl(const object::ObjectFile &Obj);
439 // \brief Return size of Global Offset Table (GOT) entry
440 virtual size_t getGOTEntrySize() { return 0; }
442 // \brief Return true if the relocation R may require allocating a GOT entry.
443 virtual bool relocationNeedsGot(const RelocationRef &R) const {
447 // \brief Return true if the relocation R may require allocating a stub.
448 virtual bool relocationNeedsStub(const RelocationRef &R) const {
449 return true; // Conservative answer
453 RuntimeDyldImpl(RuntimeDyld::MemoryManager &MemMgr,
454 JITSymbolResolver &Resolver)
455 : MemMgr(MemMgr), Resolver(Resolver), Checker(nullptr),
456 ProcessAllSections(false), HasError(false) {
459 virtual ~RuntimeDyldImpl();
461 void setProcessAllSections(bool ProcessAllSections) {
462 this->ProcessAllSections = ProcessAllSections;
465 void setRuntimeDyldChecker(RuntimeDyldCheckerImpl *Checker) {
466 this->Checker = Checker;
469 virtual std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
470 loadObject(const object::ObjectFile &Obj) = 0;
472 uint8_t* getSymbolLocalAddress(StringRef Name) const {
473 // FIXME: Just look up as a function for now. Overly simple of course.
475 RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
476 if (pos == GlobalSymbolTable.end())
478 const auto &SymInfo = pos->second;
479 // Absolute symbols do not have a local address.
480 if (SymInfo.getSectionID() == AbsoluteSymbolSection)
482 return getSectionAddress(SymInfo.getSectionID()) + SymInfo.getOffset();
485 JITEvaluatedSymbol getSymbol(StringRef Name) const {
486 // FIXME: Just look up as a function for now. Overly simple of course.
488 RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
489 if (pos == GlobalSymbolTable.end())
491 const auto &SymEntry = pos->second;
492 uint64_t SectionAddr = 0;
493 if (SymEntry.getSectionID() != AbsoluteSymbolSection)
494 SectionAddr = getSectionLoadAddress(SymEntry.getSectionID());
495 uint64_t TargetAddr = SectionAddr + SymEntry.getOffset();
496 return JITEvaluatedSymbol(TargetAddr, SymEntry.getFlags());
499 void resolveRelocations();
501 void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
503 void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
505 // Is the linker in an error state?
506 bool hasError() { return HasError; }
508 // Mark the error condition as handled and continue.
509 void clearError() { HasError = false; }
511 // Get the error message.
512 StringRef getErrorString() { return ErrorStr; }
514 virtual bool isCompatibleFile(const ObjectFile &Obj) const = 0;
516 virtual void registerEHFrames();
518 void deregisterEHFrames();
520 virtual Error finalizeLoad(const ObjectFile &ObjImg,
521 ObjSectionToIDMap &SectionMap) {
522 return Error::success();
526 } // end namespace llvm