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
14#ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDIMPL_H
15#define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDIMPL_H
16
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"
30#include <map>
31#include <unordered_map>
32#include <system_error>
33
34using namespace llvm;
35using namespace llvm::object;
36
37namespace llvm {
38
39class Twine;
40
41#define UNIMPLEMENTED_RELOC(RelType) \
42  case RelType: \
43    return make_error<RuntimeDyldError>("Unimplemented relocation: " #RelType)
44
45/// SectionEntry - represents a section emitted into memory by the dynamic
46/// linker.
47class SectionEntry {
48  /// Name - section name.
49  std::string Name;
50
51  /// Address - address in the linker's memory where the section resides.
52  uint8_t *Address;
53
54  /// Size - section size. Doesn't include the stubs.
55  size_t Size;
56
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.
61  uint64_t LoadAddress;
62
63  /// StubOffset - used for architectures with stub functions for far
64  /// relocations (like ARM).
65  uintptr_t StubOffset;
66
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;
70
71  /// ObjAddress - address of the section in the in-memory object file.  Used
72  /// for calculating relocations in some object formats (like MachO).
73  uintptr_t ObjAddress;
74
75public:
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"
82    // warning:
83    (void)AllocationSize;
84  }
85
86  StringRef getName() const { return Name; }
87
88  uint8_t *getAddress() const { return Address; }
89
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;
94  }
95
96  size_t getSize() const { return Size; }
97
98  uint64_t getLoadAddress() const { return LoadAddress; }
99  void setLoadAddress(uint64_t LA) { LoadAddress = LA; }
100
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;
105  }
106
107  uintptr_t getStubOffset() const { return StubOffset; }
108
109  void advanceStubOffset(unsigned StubSize) {
110    StubOffset += StubSize;
111    assert(StubOffset <= AllocationSize && "Not enough space allocated!");
112  }
113
114  uintptr_t getObjAddress() const { return ObjAddress; }
115};
116
117/// RelocationEntry - used to represent relocations internally in the dynamic
118/// linker.
119class RelocationEntry {
120public:
121  /// SectionID - the section this relocation points to.
122  unsigned SectionID;
123
124  /// Offset - offset into the section.
125  uint64_t Offset;
126
127  /// RelType - relocation type.
128  uint32_t RelType;
129
130  /// Addend - the relocation addend encoded in the instruction itself.  Also
131  /// used to make a relocation section relative instead of symbol relative.
132  int64_t Addend;
133
134  struct SectionPair {
135      uint32_t SectionA;
136      uint32_t SectionB;
137  };
138
139  /// SymOffset - Section offset of the relocation entry's symbol (used for GOT
140  /// lookup).
141  union {
142    uint64_t SymOffset;
143    SectionPair Sections;
144  };
145
146  /// True if this is a PCRel relocation (MachO specific).
147  bool IsPCRel;
148
149  /// The size of this relocation (MachO specific).
150  unsigned Size;
151
152  RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend)
153      : SectionID(id), Offset(offset), RelType(type), Addend(addend),
154        SymOffset(0), IsPCRel(false), Size(0) {}
155
156  RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
157                  uint64_t symoffset)
158      : SectionID(id), Offset(offset), RelType(type), Addend(addend),
159        SymOffset(symoffset), IsPCRel(false), Size(0) {}
160
161  RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
162                  bool IsPCRel, unsigned Size)
163      : SectionID(id), Offset(offset), RelType(type), Addend(addend),
164        SymOffset(0), IsPCRel(IsPCRel), Size(Size) {}
165
166  RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
167                  unsigned SectionA, uint64_t SectionAOffset, unsigned SectionB,
168                  uint64_t SectionBOffset, bool IsPCRel, unsigned Size)
169      : SectionID(id), Offset(offset), RelType(type),
170        Addend(SectionAOffset - SectionBOffset + addend), IsPCRel(IsPCRel),
171        Size(Size) {
172    Sections.SectionA = SectionA;
173    Sections.SectionB = SectionB;
174  }
175};
176
177class RelocationValueRef {
178public:
179  unsigned SectionID;
180  uint64_t Offset;
181  int64_t Addend;
182  const char *SymbolName;
183  RelocationValueRef() : SectionID(0), Offset(0), Addend(0),
184                         SymbolName(nullptr) {}
185
186  inline bool operator==(const RelocationValueRef &Other) const {
187    return SectionID == Other.SectionID && Offset == Other.Offset &&
188           Addend == Other.Addend && SymbolName == Other.SymbolName;
189  }
190  inline bool operator<(const RelocationValueRef &Other) const {
191    if (SectionID != Other.SectionID)
192      return SectionID < Other.SectionID;
193    if (Offset != Other.Offset)
194      return Offset < Other.Offset;
195    if (Addend != Other.Addend)
196      return Addend < Other.Addend;
197    return SymbolName < Other.SymbolName;
198  }
199};
200
201/// @brief Symbol info for RuntimeDyld.
202class SymbolTableEntry : public JITSymbolBase {
203public:
204  SymbolTableEntry()
205    : JITSymbolBase(JITSymbolFlags::None), Offset(0), SectionID(0) {}
206
207  SymbolTableEntry(unsigned SectionID, uint64_t Offset, JITSymbolFlags Flags)
208    : JITSymbolBase(Flags), Offset(Offset), SectionID(SectionID) {}
209
210  unsigned getSectionID() const { return SectionID; }
211  uint64_t getOffset() const { return Offset; }
212
213private:
214  uint64_t Offset;
215  unsigned SectionID;
216};
217
218typedef StringMap<SymbolTableEntry> RTDyldSymbolTable;
219
220class RuntimeDyldImpl {
221  friend class RuntimeDyld::LoadedObjectInfo;
222  friend class RuntimeDyldCheckerImpl;
223protected:
224  static const unsigned AbsoluteSymbolSection = ~0U;
225
226  // The MemoryManager to load objects into.
227  RuntimeDyld::MemoryManager &MemMgr;
228
229  // The symbol resolver to use for external symbols.
230  RuntimeDyld::SymbolResolver &Resolver;
231
232  // Attached RuntimeDyldChecker instance. Null if no instance attached.
233  RuntimeDyldCheckerImpl *Checker;
234
235  // A list of all sections emitted by the dynamic linker.  These sections are
236  // referenced in the code by means of their index in this list - SectionID.
237  typedef SmallVector<SectionEntry, 64> SectionList;
238  SectionList Sections;
239
240  typedef unsigned SID; // Type for SectionIDs
241#define RTDYLD_INVALID_SECTION_ID ((RuntimeDyldImpl::SID)(-1))
242
243  // Keep a map of sections from object file to the SectionID which
244  // references it.
245  typedef std::map<SectionRef, unsigned> ObjSectionToIDMap;
246
247  // A global symbol table for symbols from all loaded modules.
248  RTDyldSymbolTable GlobalSymbolTable;
249
250  // Keep a map of common symbols to their info pairs
251  typedef std::vector<SymbolRef> CommonSymbolList;
252
253  // For each symbol, keep a list of relocations based on it. Anytime
254  // its address is reassigned (the JIT re-compiled the function, e.g.),
255  // the relocations get re-resolved.
256  // The symbol (or section) the relocation is sourced from is the Key
257  // in the relocation list where it's stored.
258  typedef SmallVector<RelocationEntry, 64> RelocationList;
259  // Relocations to sections already loaded. Indexed by SectionID which is the
260  // source of the address. The target where the address will be written is
261  // SectionID/Offset in the relocation itself.
262  std::unordered_map<unsigned, RelocationList> Relocations;
263
264  // Relocations to external symbols that are not yet resolved.  Symbols are
265  // external when they aren't found in the global symbol table of all loaded
266  // modules.  This map is indexed by symbol name.
267  StringMap<RelocationList> ExternalSymbolRelocations;
268
269
270  typedef std::map<RelocationValueRef, uintptr_t> StubMap;
271
272  Triple::ArchType Arch;
273  bool IsTargetLittleEndian;
274  bool IsMipsO32ABI;
275  bool IsMipsN64ABI;
276
277  // True if all sections should be passed to the memory manager, false if only
278  // sections containing relocations should be. Defaults to 'false'.
279  bool ProcessAllSections;
280
281  // This mutex prevents simultaneously loading objects from two different
282  // threads.  This keeps us from having to protect individual data structures
283  // and guarantees that section allocation requests to the memory manager
284  // won't be interleaved between modules.  It is also used in mapSectionAddress
285  // and resolveRelocations to protect write access to internal data structures.
286  //
287  // loadObject may be called on the same thread during the handling of of
288  // processRelocations, and that's OK.  The handling of the relocation lists
289  // is written in such a way as to work correctly if new elements are added to
290  // the end of the list while the list is being processed.
291  sys::Mutex lock;
292
293  virtual unsigned getMaxStubSize() = 0;
294  virtual unsigned getStubAlignment() = 0;
295
296  bool HasError;
297  std::string ErrorStr;
298
299  uint64_t getSectionLoadAddress(unsigned SectionID) const {
300    return Sections[SectionID].getLoadAddress();
301  }
302
303  uint8_t *getSectionAddress(unsigned SectionID) const {
304    return Sections[SectionID].getAddress();
305  }
306
307  void writeInt16BE(uint8_t *Addr, uint16_t Value) {
308    if (IsTargetLittleEndian)
309      sys::swapByteOrder(Value);
310    *Addr       = (Value >> 8) & 0xFF;
311    *(Addr + 1) = Value & 0xFF;
312  }
313
314  void writeInt32BE(uint8_t *Addr, uint32_t Value) {
315    if (IsTargetLittleEndian)
316      sys::swapByteOrder(Value);
317    *Addr       = (Value >> 24) & 0xFF;
318    *(Addr + 1) = (Value >> 16) & 0xFF;
319    *(Addr + 2) = (Value >> 8) & 0xFF;
320    *(Addr + 3) = Value & 0xFF;
321  }
322
323  void writeInt64BE(uint8_t *Addr, uint64_t Value) {
324    if (IsTargetLittleEndian)
325      sys::swapByteOrder(Value);
326    *Addr       = (Value >> 56) & 0xFF;
327    *(Addr + 1) = (Value >> 48) & 0xFF;
328    *(Addr + 2) = (Value >> 40) & 0xFF;
329    *(Addr + 3) = (Value >> 32) & 0xFF;
330    *(Addr + 4) = (Value >> 24) & 0xFF;
331    *(Addr + 5) = (Value >> 16) & 0xFF;
332    *(Addr + 6) = (Value >> 8) & 0xFF;
333    *(Addr + 7) = Value & 0xFF;
334  }
335
336  virtual void setMipsABI(const ObjectFile &Obj) {
337    IsMipsO32ABI = false;
338    IsMipsN64ABI = false;
339  }
340
341  /// Endian-aware read Read the least significant Size bytes from Src.
342  uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const;
343
344  /// Endian-aware write. Write the least significant Size bytes from Value to
345  /// Dst.
346  void writeBytesUnaligned(uint64_t Value, uint8_t *Dst, unsigned Size) const;
347
348  /// \brief Given the common symbols discovered in the object file, emit a
349  /// new section for them and update the symbol mappings in the object and
350  /// symbol table.
351  Error emitCommonSymbols(const ObjectFile &Obj,
352                          CommonSymbolList &CommonSymbols);
353
354  /// \brief Emits section data from the object file to the MemoryManager.
355  /// \param IsCode if it's true then allocateCodeSection() will be
356  ///        used for emits, else allocateDataSection() will be used.
357  /// \return SectionID.
358  Expected<unsigned> emitSection(const ObjectFile &Obj,
359                                 const SectionRef &Section,
360                                 bool IsCode);
361
362  /// \brief Find Section in LocalSections. If the secton is not found - emit
363  ///        it and store in LocalSections.
364  /// \param IsCode if it's true then allocateCodeSection() will be
365  ///        used for emmits, else allocateDataSection() will be used.
366  /// \return SectionID.
367  Expected<unsigned> findOrEmitSection(const ObjectFile &Obj,
368                                       const SectionRef &Section, bool IsCode,
369                                       ObjSectionToIDMap &LocalSections);
370
371  // \brief Add a relocation entry that uses the given section.
372  void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID);
373
374  // \brief Add a relocation entry that uses the given symbol.  This symbol may
375  // be found in the global symbol table, or it may be external.
376  void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName);
377
378  /// \brief Emits long jump instruction to Addr.
379  /// \return Pointer to the memory area for emitting target address.
380  uint8_t *createStubFunction(uint8_t *Addr, unsigned AbiVariant = 0);
381
382  /// \brief Resolves relocations from Relocs list with address from Value.
383  void resolveRelocationList(const RelocationList &Relocs, uint64_t Value);
384
385  /// \brief A object file specific relocation resolver
386  /// \param RE The relocation to be resolved
387  /// \param Value Target symbol address to apply the relocation action
388  virtual void resolveRelocation(const RelocationEntry &RE, uint64_t Value) = 0;
389
390  /// \brief Parses one or more object file relocations (some object files use
391  ///        relocation pairs) and stores it to Relocations or SymbolRelocations
392  ///        (this depends on the object file type).
393  /// \return Iterator to the next relocation that needs to be parsed.
394  virtual Expected<relocation_iterator>
395  processRelocationRef(unsigned SectionID, relocation_iterator RelI,
396                       const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID,
397                       StubMap &Stubs) = 0;
398
399  /// \brief Resolve relocations to external symbols.
400  void resolveExternalSymbols();
401
402  // \brief Compute an upper bound of the memory that is required to load all
403  // sections
404  Error computeTotalAllocSize(const ObjectFile &Obj,
405                              uint64_t &CodeSize, uint32_t &CodeAlign,
406                              uint64_t &RODataSize, uint32_t &RODataAlign,
407                              uint64_t &RWDataSize, uint32_t &RWDataAlign);
408
409  // \brief Compute the stub buffer size required for a section
410  unsigned computeSectionStubBufSize(const ObjectFile &Obj,
411                                     const SectionRef &Section);
412
413  // \brief Implementation of the generic part of the loadObject algorithm.
414  Expected<ObjSectionToIDMap> loadObjectImpl(const object::ObjectFile &Obj);
415
416  // \brief Return true if the relocation R may require allocating a stub.
417  virtual bool relocationNeedsStub(const RelocationRef &R) const {
418    return true;    // Conservative answer
419  }
420
421public:
422  RuntimeDyldImpl(RuntimeDyld::MemoryManager &MemMgr,
423                  RuntimeDyld::SymbolResolver &Resolver)
424    : MemMgr(MemMgr), Resolver(Resolver), Checker(nullptr),
425      ProcessAllSections(false), HasError(false) {
426  }
427
428  virtual ~RuntimeDyldImpl();
429
430  void setProcessAllSections(bool ProcessAllSections) {
431    this->ProcessAllSections = ProcessAllSections;
432  }
433
434  void setRuntimeDyldChecker(RuntimeDyldCheckerImpl *Checker) {
435    this->Checker = Checker;
436  }
437
438  virtual std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
439  loadObject(const object::ObjectFile &Obj) = 0;
440
441  uint8_t* getSymbolLocalAddress(StringRef Name) const {
442    // FIXME: Just look up as a function for now. Overly simple of course.
443    // Work in progress.
444    RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
445    if (pos == GlobalSymbolTable.end())
446      return nullptr;
447    const auto &SymInfo = pos->second;
448    // Absolute symbols do not have a local address.
449    if (SymInfo.getSectionID() == AbsoluteSymbolSection)
450      return nullptr;
451    return getSectionAddress(SymInfo.getSectionID()) + SymInfo.getOffset();
452  }
453
454  RuntimeDyld::SymbolInfo getSymbol(StringRef Name) const {
455    // FIXME: Just look up as a function for now. Overly simple of course.
456    // Work in progress.
457    RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
458    if (pos == GlobalSymbolTable.end())
459      return nullptr;
460    const auto &SymEntry = pos->second;
461    uint64_t SectionAddr = 0;
462    if (SymEntry.getSectionID() != AbsoluteSymbolSection)
463      SectionAddr = getSectionLoadAddress(SymEntry.getSectionID());
464    uint64_t TargetAddr = SectionAddr + SymEntry.getOffset();
465    return RuntimeDyld::SymbolInfo(TargetAddr, SymEntry.getFlags());
466  }
467
468  void resolveRelocations();
469
470  void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
471
472  void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
473
474  // Is the linker in an error state?
475  bool hasError() { return HasError; }
476
477  // Mark the error condition as handled and continue.
478  void clearError() { HasError = false; }
479
480  // Get the error message.
481  StringRef getErrorString() { return ErrorStr; }
482
483  virtual bool isCompatibleFile(const ObjectFile &Obj) const = 0;
484
485  virtual void registerEHFrames();
486
487  virtual void deregisterEHFrames();
488
489  virtual Error finalizeLoad(const ObjectFile &ObjImg,
490                             ObjSectionToIDMap &SectionMap) {
491    return Error::success();
492  }
493};
494
495} // end namespace llvm
496
497#endif
498