1//===-- RuntimeDyld.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 runtime dynamic linker facilities of the MC-JIT.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
15#define LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
16
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/DebugInfo/DIContext.h"
20#include "llvm/ExecutionEngine/JITSymbol.h"
21#include "llvm/Object/ObjectFile.h"
22#include "llvm/Support/Error.h"
23#include <algorithm>
24#include <cassert>
25#include <cstddef>
26#include <cstdint>
27#include <map>
28#include <memory>
29#include <string>
30#include <system_error>
31
32namespace llvm {
33
34namespace object {
35  template <typename T> class OwningBinary;
36} // end namespace object
37
38/// Base class for errors originating in RuntimeDyld, e.g. missing relocation
39/// support.
40class RuntimeDyldError : public ErrorInfo<RuntimeDyldError> {
41public:
42  static char ID;
43
44  RuntimeDyldError(std::string ErrMsg) : ErrMsg(std::move(ErrMsg)) {}
45
46  void log(raw_ostream &OS) const override;
47  const std::string &getErrorMessage() const { return ErrMsg; }
48  std::error_code convertToErrorCode() const override;
49
50private:
51  std::string ErrMsg;
52};
53
54class RuntimeDyldImpl;
55class RuntimeDyldCheckerImpl;
56
57class RuntimeDyld {
58  friend class RuntimeDyldCheckerImpl;
59
60protected:
61  // Change the address associated with a section when resolving relocations.
62  // Any relocations already associated with the symbol will be re-resolved.
63  void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
64
65public:
66  /// \brief Information about the loaded object.
67  class LoadedObjectInfo : public llvm::LoadedObjectInfo {
68    friend class RuntimeDyldImpl;
69
70  public:
71    typedef std::map<object::SectionRef, unsigned> ObjSectionToIDMap;
72
73    LoadedObjectInfo(RuntimeDyldImpl &RTDyld, ObjSectionToIDMap ObjSecToIDMap)
74        : RTDyld(RTDyld), ObjSecToIDMap(std::move(ObjSecToIDMap)) {}
75
76    virtual object::OwningBinary<object::ObjectFile>
77    getObjectForDebug(const object::ObjectFile &Obj) const = 0;
78
79    uint64_t
80    getSectionLoadAddress(const object::SectionRef &Sec) const override;
81
82  protected:
83    virtual void anchor();
84
85    RuntimeDyldImpl &RTDyld;
86    ObjSectionToIDMap ObjSecToIDMap;
87  };
88
89  template <typename Derived> struct LoadedObjectInfoHelper : LoadedObjectInfo {
90  protected:
91    LoadedObjectInfoHelper(const LoadedObjectInfoHelper &) = default;
92    LoadedObjectInfoHelper() = default;
93
94  public:
95    LoadedObjectInfoHelper(RuntimeDyldImpl &RTDyld,
96                           LoadedObjectInfo::ObjSectionToIDMap ObjSecToIDMap)
97        : LoadedObjectInfo(RTDyld, std::move(ObjSecToIDMap)) {}
98
99    std::unique_ptr<llvm::LoadedObjectInfo> clone() const override {
100      return llvm::make_unique<Derived>(static_cast<const Derived &>(*this));
101    }
102  };
103
104  /// \brief Memory Management.
105  class MemoryManager {
106    friend class RuntimeDyld;
107
108  public:
109    MemoryManager() = default;
110    virtual ~MemoryManager() = default;
111
112    /// Allocate a memory block of (at least) the given size suitable for
113    /// executable code. The SectionID is a unique identifier assigned by the
114    /// RuntimeDyld instance, and optionally recorded by the memory manager to
115    /// access a loaded section.
116    virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
117                                         unsigned SectionID,
118                                         StringRef SectionName) = 0;
119
120    /// Allocate a memory block of (at least) the given size suitable for data.
121    /// The SectionID is a unique identifier assigned by the JIT engine, and
122    /// optionally recorded by the memory manager to access a loaded section.
123    virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
124                                         unsigned SectionID,
125                                         StringRef SectionName,
126                                         bool IsReadOnly) = 0;
127
128    /// Inform the memory manager about the total amount of memory required to
129    /// allocate all sections to be loaded:
130    /// \p CodeSize - the total size of all code sections
131    /// \p DataSizeRO - the total size of all read-only data sections
132    /// \p DataSizeRW - the total size of all read-write data sections
133    ///
134    /// Note that by default the callback is disabled. To enable it
135    /// redefine the method needsToReserveAllocationSpace to return true.
136    virtual void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign,
137                                        uintptr_t RODataSize,
138                                        uint32_t RODataAlign,
139                                        uintptr_t RWDataSize,
140                                        uint32_t RWDataAlign) {}
141
142    /// Override to return true to enable the reserveAllocationSpace callback.
143    virtual bool needsToReserveAllocationSpace() { return false; }
144
145    /// Register the EH frames with the runtime so that c++ exceptions work.
146    ///
147    /// \p Addr parameter provides the local address of the EH frame section
148    /// data, while \p LoadAddr provides the address of the data in the target
149    /// address space.  If the section has not been remapped (which will usually
150    /// be the case for local execution) these two values will be the same.
151    virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
152                                  size_t Size) = 0;
153    virtual void deregisterEHFrames() = 0;
154
155    /// This method is called when object loading is complete and section page
156    /// permissions can be applied.  It is up to the memory manager implementation
157    /// to decide whether or not to act on this method.  The memory manager will
158    /// typically allocate all sections as read-write and then apply specific
159    /// permissions when this method is called.  Code sections cannot be executed
160    /// until this function has been called.  In addition, any cache coherency
161    /// operations needed to reliably use the memory are also performed.
162    ///
163    /// Returns true if an error occurred, false otherwise.
164    virtual bool finalizeMemory(std::string *ErrMsg = nullptr) = 0;
165
166    /// This method is called after an object has been loaded into memory but
167    /// before relocations are applied to the loaded sections.
168    ///
169    /// Memory managers which are preparing code for execution in an external
170    /// address space can use this call to remap the section addresses for the
171    /// newly loaded object.
172    ///
173    /// For clients that do not need access to an ExecutionEngine instance this
174    /// method should be preferred to its cousin
175    /// MCJITMemoryManager::notifyObjectLoaded as this method is compatible with
176    /// ORC JIT stacks.
177    virtual void notifyObjectLoaded(RuntimeDyld &RTDyld,
178                                    const object::ObjectFile &Obj) {}
179
180  private:
181    virtual void anchor();
182
183    bool FinalizationLocked = false;
184  };
185
186  /// \brief Construct a RuntimeDyld instance.
187  RuntimeDyld(MemoryManager &MemMgr, JITSymbolResolver &Resolver);
188  RuntimeDyld(const RuntimeDyld &) = delete;
189  void operator=(const RuntimeDyld &) = delete;
190  ~RuntimeDyld();
191
192  /// Add the referenced object file to the list of objects to be loaded and
193  /// relocated.
194  std::unique_ptr<LoadedObjectInfo> loadObject(const object::ObjectFile &O);
195
196  /// Get the address of our local copy of the symbol. This may or may not
197  /// be the address used for relocation (clients can copy the data around
198  /// and resolve relocatons based on where they put it).
199  void *getSymbolLocalAddress(StringRef Name) const;
200
201  /// Get the target address and flags for the named symbol.
202  /// This address is the one used for relocation.
203  JITEvaluatedSymbol getSymbol(StringRef Name) const;
204
205  /// Resolve the relocations for all symbols we currently know about.
206  void resolveRelocations();
207
208  /// Map a section to its target address space value.
209  /// Map the address of a JIT section as returned from the memory manager
210  /// to the address in the target process as the running code will see it.
211  /// This is the address which will be used for relocation resolution.
212  void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
213
214  /// Register any EH frame sections that have been loaded but not previously
215  /// registered with the memory manager.  Note, RuntimeDyld is responsible
216  /// for identifying the EH frame and calling the memory manager with the
217  /// EH frame section data.  However, the memory manager itself will handle
218  /// the actual target-specific EH frame registration.
219  void registerEHFrames();
220
221  void deregisterEHFrames();
222
223  bool hasError();
224  StringRef getErrorString();
225
226  /// By default, only sections that are "required for execution" are passed to
227  /// the RTDyldMemoryManager, and other sections are discarded. Passing 'true'
228  /// to this method will cause RuntimeDyld to pass all sections to its
229  /// memory manager regardless of whether they are "required to execute" in the
230  /// usual sense. This is useful for inspecting metadata sections that may not
231  /// contain relocations, E.g. Debug info, stackmaps.
232  ///
233  /// Must be called before the first object file is loaded.
234  void setProcessAllSections(bool ProcessAllSections) {
235    assert(!Dyld && "setProcessAllSections must be called before loadObject.");
236    this->ProcessAllSections = ProcessAllSections;
237  }
238
239  /// Perform all actions needed to make the code owned by this RuntimeDyld
240  /// instance executable:
241  ///
242  /// 1) Apply relocations.
243  /// 2) Register EH frames.
244  /// 3) Update memory permissions*.
245  ///
246  /// * Finalization is potentially recursive**, and the 3rd step will only be
247  ///   applied by the outermost call to finalize. This allows different
248  ///   RuntimeDyld instances to share a memory manager without the innermost
249  ///   finalization locking the memory and causing relocation fixup errors in
250  ///   outer instances.
251  ///
252  /// ** Recursive finalization occurs when one RuntimeDyld instances needs the
253  ///   address of a symbol owned by some other instance in order to apply
254  ///   relocations.
255  ///
256  void finalizeWithMemoryManagerLocking();
257
258private:
259  // RuntimeDyldImpl is the actual class. RuntimeDyld is just the public
260  // interface.
261  std::unique_ptr<RuntimeDyldImpl> Dyld;
262  MemoryManager &MemMgr;
263  JITSymbolResolver &Resolver;
264  bool ProcessAllSections;
265  RuntimeDyldCheckerImpl *Checker;
266};
267
268} // end namespace llvm
269
270#endif // LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
271