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/DenseMap.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/Triple.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"
30 #include "llvm/Support/raw_ostream.h"
32 #include <system_error>
35 using namespace llvm::object;
39 // Helper for extensive error checking in debug builds.
40 inline std::error_code Check(std::error_code Err) {
42 report_fatal_error(Err.message());
49 /// SectionEntry - represents a section emitted into memory by the dynamic
53 /// Name - section name.
56 /// Address - address in the linker's memory where the section resides.
59 /// Size - section size. Doesn't include the stubs.
62 /// LoadAddress - the address of the section in the target process's memory.
63 /// Used for situations in which JIT-ed code is being executed in the address
64 /// space of a separate process. If the code executes in the same address
65 /// space where it was JIT-ed, this just equals Address.
68 /// StubOffset - used for architectures with stub functions for far
69 /// relocations (like ARM).
72 /// ObjAddress - address of the section in the in-memory object file. Used
73 /// for calculating relocations in some object formats (like MachO).
76 SectionEntry(StringRef name, uint8_t *address, size_t size,
78 : Name(name), Address(address), Size(size),
79 LoadAddress(reinterpret_cast<uintptr_t>(address)), StubOffset(size),
80 ObjAddress(objAddress) {}
83 /// RelocationEntry - used to represent relocations internally in the dynamic
85 class RelocationEntry {
87 /// SectionID - the section this relocation points to.
90 /// Offset - offset into the section.
93 /// RelType - relocation type.
96 /// Addend - the relocation addend encoded in the instruction itself. Also
97 /// used to make a relocation section relative instead of symbol relative.
105 /// SymOffset - Section offset of the relocation entry's symbol (used for GOT
109 SectionPair Sections;
112 /// True if this is a PCRel relocation (MachO specific).
115 /// The size of this relocation (MachO specific).
118 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend)
119 : SectionID(id), Offset(offset), RelType(type), Addend(addend),
120 SymOffset(0), IsPCRel(false), Size(0) {}
122 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
124 : SectionID(id), Offset(offset), RelType(type), Addend(addend),
125 SymOffset(symoffset), IsPCRel(false), Size(0) {}
127 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
128 bool IsPCRel, unsigned Size)
129 : SectionID(id), Offset(offset), RelType(type), Addend(addend),
130 SymOffset(0), IsPCRel(IsPCRel), Size(Size) {}
132 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
133 unsigned SectionA, uint64_t SectionAOffset, unsigned SectionB,
134 uint64_t SectionBOffset, bool IsPCRel, unsigned Size)
135 : SectionID(id), Offset(offset), RelType(type),
136 Addend(SectionAOffset - SectionBOffset + addend), IsPCRel(IsPCRel),
138 Sections.SectionA = SectionA;
139 Sections.SectionB = SectionB;
143 class RelocationValueRef {
148 const char *SymbolName;
149 RelocationValueRef() : SectionID(0), Offset(0), Addend(0),
150 SymbolName(nullptr) {}
152 inline bool operator==(const RelocationValueRef &Other) const {
153 return SectionID == Other.SectionID && Offset == Other.Offset &&
154 Addend == Other.Addend && SymbolName == Other.SymbolName;
156 inline bool operator<(const RelocationValueRef &Other) const {
157 if (SectionID != Other.SectionID)
158 return SectionID < Other.SectionID;
159 if (Offset != Other.Offset)
160 return Offset < Other.Offset;
161 if (Addend != Other.Addend)
162 return Addend < Other.Addend;
163 return SymbolName < Other.SymbolName;
167 /// @brief Symbol info for RuntimeDyld.
170 typedef enum { Hidden = 0, Default = 1 } Visibility;
172 SymbolInfo() : Offset(0), SectionID(0), Vis(Hidden) {}
174 SymbolInfo(unsigned SectionID, uint64_t Offset, Visibility Vis)
175 : Offset(Offset), SectionID(SectionID), Vis(Vis) {}
177 unsigned getSectionID() const { return SectionID; }
178 uint64_t getOffset() const { return Offset; }
179 Visibility getVisibility() const { return Vis; }
183 unsigned SectionID : 31;
187 typedef StringMap<SymbolInfo> RTDyldSymbolTable;
189 class RuntimeDyldImpl {
190 friend class RuntimeDyld::LoadedObjectInfo;
191 friend class RuntimeDyldCheckerImpl;
193 // The MemoryManager to load objects into.
194 RTDyldMemoryManager *MemMgr;
196 // Attached RuntimeDyldChecker instance. Null if no instance attached.
197 RuntimeDyldCheckerImpl *Checker;
199 // A list of all sections emitted by the dynamic linker. These sections are
200 // referenced in the code by means of their index in this list - SectionID.
201 typedef SmallVector<SectionEntry, 64> SectionList;
202 SectionList Sections;
204 typedef unsigned SID; // Type for SectionIDs
205 #define RTDYLD_INVALID_SECTION_ID ((SID)(-1))
207 // Keep a map of sections from object file to the SectionID which
209 typedef std::map<SectionRef, unsigned> ObjSectionToIDMap;
211 // A global symbol table for symbols from all loaded modules.
212 RTDyldSymbolTable GlobalSymbolTable;
214 // Keep a map of common symbols to their info pairs
215 typedef std::vector<SymbolRef> CommonSymbolList;
217 // For each symbol, keep a list of relocations based on it. Anytime
218 // its address is reassigned (the JIT re-compiled the function, e.g.),
219 // the relocations get re-resolved.
220 // The symbol (or section) the relocation is sourced from is the Key
221 // in the relocation list where it's stored.
222 typedef SmallVector<RelocationEntry, 64> RelocationList;
223 // Relocations to sections already loaded. Indexed by SectionID which is the
224 // source of the address. The target where the address will be written is
225 // SectionID/Offset in the relocation itself.
226 DenseMap<unsigned, RelocationList> Relocations;
228 // Relocations to external symbols that are not yet resolved. Symbols are
229 // external when they aren't found in the global symbol table of all loaded
230 // modules. This map is indexed by symbol name.
231 StringMap<RelocationList> ExternalSymbolRelocations;
234 typedef std::map<RelocationValueRef, uintptr_t> StubMap;
236 Triple::ArchType Arch;
237 bool IsTargetLittleEndian;
239 // True if all sections should be passed to the memory manager, false if only
240 // sections containing relocations should be. Defaults to 'false'.
241 bool ProcessAllSections;
243 // This mutex prevents simultaneously loading objects from two different
244 // threads. This keeps us from having to protect individual data structures
245 // and guarantees that section allocation requests to the memory manager
246 // won't be interleaved between modules. It is also used in mapSectionAddress
247 // and resolveRelocations to protect write access to internal data structures.
249 // loadObject may be called on the same thread during the handling of of
250 // processRelocations, and that's OK. The handling of the relocation lists
251 // is written in such a way as to work correctly if new elements are added to
252 // the end of the list while the list is being processed.
255 virtual unsigned getMaxStubSize() = 0;
256 virtual unsigned getStubAlignment() = 0;
259 std::string ErrorStr;
261 // Set the error state and record an error string.
262 bool Error(const Twine &Msg) {
263 ErrorStr = Msg.str();
268 uint64_t getSectionLoadAddress(unsigned SectionID) const {
269 return Sections[SectionID].LoadAddress;
272 uint8_t *getSectionAddress(unsigned SectionID) const {
273 return (uint8_t *)Sections[SectionID].Address;
276 void writeInt16BE(uint8_t *Addr, uint16_t Value) {
277 if (IsTargetLittleEndian)
278 sys::swapByteOrder(Value);
279 *Addr = (Value >> 8) & 0xFF;
280 *(Addr + 1) = Value & 0xFF;
283 void writeInt32BE(uint8_t *Addr, uint32_t Value) {
284 if (IsTargetLittleEndian)
285 sys::swapByteOrder(Value);
286 *Addr = (Value >> 24) & 0xFF;
287 *(Addr + 1) = (Value >> 16) & 0xFF;
288 *(Addr + 2) = (Value >> 8) & 0xFF;
289 *(Addr + 3) = Value & 0xFF;
292 void writeInt64BE(uint8_t *Addr, uint64_t Value) {
293 if (IsTargetLittleEndian)
294 sys::swapByteOrder(Value);
295 *Addr = (Value >> 56) & 0xFF;
296 *(Addr + 1) = (Value >> 48) & 0xFF;
297 *(Addr + 2) = (Value >> 40) & 0xFF;
298 *(Addr + 3) = (Value >> 32) & 0xFF;
299 *(Addr + 4) = (Value >> 24) & 0xFF;
300 *(Addr + 5) = (Value >> 16) & 0xFF;
301 *(Addr + 6) = (Value >> 8) & 0xFF;
302 *(Addr + 7) = Value & 0xFF;
305 /// Endian-aware read Read the least significant Size bytes from Src.
306 uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const;
308 /// Endian-aware write. Write the least significant Size bytes from Value to
310 void writeBytesUnaligned(uint64_t Value, uint8_t *Dst, unsigned Size) const;
312 /// \brief Given the common symbols discovered in the object file, emit a
313 /// new section for them and update the symbol mappings in the object and
315 void emitCommonSymbols(const ObjectFile &Obj, CommonSymbolList &CommonSymbols);
317 /// \brief Emits section data from the object file to the MemoryManager.
318 /// \param IsCode if it's true then allocateCodeSection() will be
319 /// used for emits, else allocateDataSection() will be used.
320 /// \return SectionID.
321 unsigned emitSection(const ObjectFile &Obj, const SectionRef &Section,
324 /// \brief Find Section in LocalSections. If the secton is not found - emit
325 /// it and store in LocalSections.
326 /// \param IsCode if it's true then allocateCodeSection() will be
327 /// used for emmits, else allocateDataSection() will be used.
328 /// \return SectionID.
329 unsigned findOrEmitSection(const ObjectFile &Obj, const SectionRef &Section,
330 bool IsCode, ObjSectionToIDMap &LocalSections);
332 // \brief Add a relocation entry that uses the given section.
333 void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID);
335 // \brief Add a relocation entry that uses the given symbol. This symbol may
336 // be found in the global symbol table, or it may be external.
337 void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName);
339 /// \brief Emits long jump instruction to Addr.
340 /// \return Pointer to the memory area for emitting target address.
341 uint8_t *createStubFunction(uint8_t *Addr, unsigned AbiVariant = 0);
343 /// \brief Resolves relocations from Relocs list with address from Value.
344 void resolveRelocationList(const RelocationList &Relocs, uint64_t Value);
346 /// \brief A object file specific relocation resolver
347 /// \param RE The relocation to be resolved
348 /// \param Value Target symbol address to apply the relocation action
349 virtual void resolveRelocation(const RelocationEntry &RE, uint64_t Value) = 0;
351 /// \brief Parses one or more object file relocations (some object files use
352 /// relocation pairs) and stores it to Relocations or SymbolRelocations
353 /// (this depends on the object file type).
354 /// \return Iterator to the next relocation that needs to be parsed.
355 virtual relocation_iterator
356 processRelocationRef(unsigned SectionID, relocation_iterator RelI,
357 const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID,
360 /// \brief Resolve relocations to external symbols.
361 void resolveExternalSymbols();
363 /// \brief Update GOT entries for external symbols.
364 // The base class does nothing. ELF overrides this.
365 virtual void updateGOTEntries(StringRef Name, uint64_t Addr) {}
367 // \brief Compute an upper bound of the memory that is required to load all
369 void computeTotalAllocSize(const ObjectFile &Obj, uint64_t &CodeSize,
370 uint64_t &DataSizeRO, uint64_t &DataSizeRW);
372 // \brief Compute the stub buffer size required for a section
373 unsigned computeSectionStubBufSize(const ObjectFile &Obj,
374 const SectionRef &Section);
376 // \brief Implementation of the generic part of the loadObject algorithm.
377 std::pair<unsigned, unsigned> loadObjectImpl(const object::ObjectFile &Obj);
380 RuntimeDyldImpl(RTDyldMemoryManager *mm)
381 : MemMgr(mm), Checker(nullptr), ProcessAllSections(false), HasError(false) {
384 virtual ~RuntimeDyldImpl();
386 void setProcessAllSections(bool ProcessAllSections) {
387 this->ProcessAllSections = ProcessAllSections;
390 void setRuntimeDyldChecker(RuntimeDyldCheckerImpl *Checker) {
391 this->Checker = Checker;
394 virtual std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
395 loadObject(const object::ObjectFile &Obj) = 0;
397 uint8_t* getSymbolAddress(StringRef Name) const {
398 // FIXME: Just look up as a function for now. Overly simple of course.
400 RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
401 if (pos == GlobalSymbolTable.end())
403 const auto &SymInfo = pos->second;
404 return getSectionAddress(SymInfo.getSectionID()) + SymInfo.getOffset();
407 uint64_t getSymbolLoadAddress(StringRef Name) const {
408 // FIXME: Just look up as a function for now. Overly simple of course.
410 RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
411 if (pos == GlobalSymbolTable.end())
413 const auto &SymInfo = pos->second;
414 return getSectionLoadAddress(SymInfo.getSectionID()) + SymInfo.getOffset();
417 uint64_t getExportedSymbolLoadAddress(StringRef Name) const {
418 RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
419 if (pos == GlobalSymbolTable.end())
421 const auto &SymInfo = pos->second;
422 if (SymInfo.getVisibility() == SymbolInfo::Hidden)
424 return getSectionLoadAddress(SymInfo.getSectionID()) + SymInfo.getOffset();
427 void resolveRelocations();
429 void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
431 void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
433 // Is the linker in an error state?
434 bool hasError() { return HasError; }
436 // Mark the error condition as handled and continue.
437 void clearError() { HasError = false; }
439 // Get the error message.
440 StringRef getErrorString() { return ErrorStr; }
442 virtual bool isCompatibleFile(const ObjectFile &Obj) const = 0;
444 virtual void registerEHFrames();
446 virtual void deregisterEHFrames();
448 virtual void finalizeLoad(const ObjectFile &ObjImg,
449 ObjSectionToIDMap &SectionMap) {}
452 } // end namespace llvm