LLVM  4.0.0
RuntimeDyld.h
Go to the documentation of this file.
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"
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 
32 namespace llvm {
33 
34 namespace 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.
40 class RuntimeDyldError : public ErrorInfo<RuntimeDyldError> {
41 public:
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 
50 private:
51  std::string ErrMsg;
52 };
53 
54 class RuntimeDyldImpl;
55 class RuntimeDyldCheckerImpl;
56 
57 class RuntimeDyld {
58  friend class RuntimeDyldCheckerImpl;
59 
60 protected:
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 
65 public:
66  /// \brief Information about the loaded object.
68  friend class RuntimeDyldImpl;
69 
70  public:
71  typedef std::map<object::SectionRef, unsigned> ObjSectionToIDMap;
72 
74  : RTDyld(RTDyld), ObjSecToIDMap(std::move(ObjSecToIDMap)) {}
75 
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 
87  };
88 
89  template <typename Derived> struct LoadedObjectInfoHelper : LoadedObjectInfo {
90  protected:
92  LoadedObjectInfoHelper() = default;
93 
94  public:
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.
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,
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(uint8_t *addr, uint64_t LoadAddr,
154  size_t Size) = 0;
155 
156  /// This method is called when object loading is complete and section page
157  /// permissions can be applied. It is up to the memory manager implementation
158  /// to decide whether or not to act on this method. The memory manager will
159  /// typically allocate all sections as read-write and then apply specific
160  /// permissions when this method is called. Code sections cannot be executed
161  /// until this function has been called. In addition, any cache coherency
162  /// operations needed to reliably use the memory are also performed.
163  ///
164  /// Returns true if an error occurred, false otherwise.
165  virtual bool finalizeMemory(std::string *ErrMsg = nullptr) = 0;
166 
167  /// This method is called after an object has been loaded into memory but
168  /// before relocations are applied to the loaded sections.
169  ///
170  /// Memory managers which are preparing code for execution in an external
171  /// address space can use this call to remap the section addresses for the
172  /// newly loaded object.
173  ///
174  /// For clients that do not need access to an ExecutionEngine instance this
175  /// method should be preferred to its cousin
176  /// MCJITMemoryManager::notifyObjectLoaded as this method is compatible with
177  /// ORC JIT stacks.
178  virtual void notifyObjectLoaded(RuntimeDyld &RTDyld,
179  const object::ObjectFile &Obj) {}
180 
181  private:
182  virtual void anchor();
183 
184  bool FinalizationLocked = false;
185  };
186 
187  /// \brief Construct a RuntimeDyld instance.
188  RuntimeDyld(MemoryManager &MemMgr, JITSymbolResolver &Resolver);
189  RuntimeDyld(const RuntimeDyld &) = delete;
190  void operator=(const RuntimeDyld &) = delete;
191  ~RuntimeDyld();
192 
193  /// Add the referenced object file to the list of objects to be loaded and
194  /// relocated.
195  std::unique_ptr<LoadedObjectInfo> loadObject(const object::ObjectFile &O);
196 
197  /// Get the address of our local copy of the symbol. This may or may not
198  /// be the address used for relocation (clients can copy the data around
199  /// and resolve relocatons based on where they put it).
200  void *getSymbolLocalAddress(StringRef Name) const;
201 
202  /// Get the target address and flags for the named symbol.
203  /// This address is the one used for relocation.
205 
206  /// Resolve the relocations for all symbols we currently know about.
207  void resolveRelocations();
208 
209  /// Map a section to its target address space value.
210  /// Map the address of a JIT section as returned from the memory manager
211  /// to the address in the target process as the running code will see it.
212  /// This is the address which will be used for relocation resolution.
213  void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
214 
215  /// Register any EH frame sections that have been loaded but not previously
216  /// registered with the memory manager. Note, RuntimeDyld is responsible
217  /// for identifying the EH frame and calling the memory manager with the
218  /// EH frame section data. However, the memory manager itself will handle
219  /// the actual target-specific EH frame registration.
220  void registerEHFrames();
221 
222  void deregisterEHFrames();
223 
224  bool hasError();
226 
227  /// By default, only sections that are "required for execution" are passed to
228  /// the RTDyldMemoryManager, and other sections are discarded. Passing 'true'
229  /// to this method will cause RuntimeDyld to pass all sections to its
230  /// memory manager regardless of whether they are "required to execute" in the
231  /// usual sense. This is useful for inspecting metadata sections that may not
232  /// contain relocations, E.g. Debug info, stackmaps.
233  ///
234  /// Must be called before the first object file is loaded.
235  void setProcessAllSections(bool ProcessAllSections) {
236  assert(!Dyld && "setProcessAllSections must be called before loadObject.");
237  this->ProcessAllSections = ProcessAllSections;
238  }
239 
240  /// Perform all actions needed to make the code owned by this RuntimeDyld
241  /// instance executable:
242  ///
243  /// 1) Apply relocations.
244  /// 2) Register EH frames.
245  /// 3) Update memory permissions*.
246  ///
247  /// * Finalization is potentially recursive**, and the 3rd step will only be
248  /// applied by the outermost call to finalize. This allows different
249  /// RuntimeDyld instances to share a memory manager without the innermost
250  /// finalization locking the memory and causing relocation fixup errors in
251  /// outer instances.
252  ///
253  /// ** Recursive finalization occurs when one RuntimeDyld instances needs the
254  /// address of a symbol owned by some other instance in order to apply
255  /// relocations.
256  ///
258 
259 private:
260  // RuntimeDyldImpl is the actual class. RuntimeDyld is just the public
261  // interface.
262  std::unique_ptr<RuntimeDyldImpl> Dyld;
263  MemoryManager &MemMgr;
264  JITSymbolResolver &Resolver;
265  bool ProcessAllSections;
266  RuntimeDyldCheckerImpl *Checker;
267 };
268 
269 } // end namespace llvm
270 
271 #endif // LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
virtual void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign, uintptr_t RODataSize, uint32_t RODataAlign, uintptr_t RWDataSize, uint32_t RWDataAlign)
Inform the memory manager about the total amount of memory required to allocate all sections to be lo...
Definition: RuntimeDyld.h:136
Information about the loaded object.
Definition: RuntimeDyld.h:67
std::unique_ptr< LoadedObjectInfo > loadObject(const object::ObjectFile &O)
Add the referenced object file to the list of objects to be loaded and relocated. ...
void registerEHFrames()
Register any EH frame sections that have been loaded but not previously registered with the memory ma...
void operator=(const RuntimeDyld &)=delete
StringRef getErrorString()
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: RuntimeDyld.cpp:62
This class is the base class for all object file types.
Definition: ObjectFile.h:178
uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override
Obtain the Load Address of a section by SectionRef.
virtual bool needsToReserveAllocationSpace()
Override to return true to enable the reserveAllocationSpace callback.
Definition: RuntimeDyld.h:143
virtual void deregisterEHFrames(uint8_t *addr, uint64_t LoadAddr, size_t Size)=0
JITEvaluatedSymbol getSymbol(StringRef Name) const
Get the target address and flags for the named symbol.
const std::string & getErrorMessage() const
Definition: RuntimeDyld.h:47
RuntimeDyldError(std::string ErrMsg)
Definition: RuntimeDyld.h:44
void * getSymbolLocalAddress(StringRef Name) const
Get the address of our local copy of the symbol.
void setProcessAllSections(bool ProcessAllSections)
By default, only sections that are "required for execution" are passed to the RTDyldMemoryManager, and other sections are discarded.
Definition: RuntimeDyld.h:235
RuntimeDyld(MemoryManager &MemMgr, JITSymbolResolver &Resolver)
Construct a RuntimeDyld instance.
virtual bool finalizeMemory(std::string *ErrMsg=nullptr)=0
This method is called when object loading is complete and section page permissions can be applied...
virtual void notifyObjectLoaded(RuntimeDyld &RTDyld, const object::ObjectFile &Obj)
This method is called after an object has been loaded into memory but before relocations are applied ...
Definition: RuntimeDyld.h:178
Symbol resolution.
Definition: JITSymbol.h:165
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: RuntimeDyld.cpp:58
virtual uint8_t * allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool IsReadOnly)=0
Allocate a memory block of (at least) the given size suitable for data.
virtual uint8_t * allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName)=0
Allocate a memory block of (at least) the given size suitable for executable code.
virtual object::OwningBinary< object::ObjectFile > getObjectForDebug(const object::ObjectFile &Obj) const =0
An inferface for inquiring the load address of a loaded object file to be used by the DIContext imple...
Definition: DIContext.h:176
Represents a symbol that has been evaluated to an address already.
Definition: JITSymbol.h:88
Base class for user error types.
std::map< object::SectionRef, unsigned > ObjSectionToIDMap
Definition: RuntimeDyld.h:71
Base class for errors originating in RuntimeDyld, e.g.
Definition: RuntimeDyld.h:40
std::unique_ptr< llvm::LoadedObjectInfo > clone() const override
Obtain a copy of this LoadedObjectInfo.
Definition: RuntimeDyld.h:99
void finalizeWithMemoryManagerLocking()
Perform all actions needed to make the code owned by this RuntimeDyld instance executable: ...
const char SectionName[]
Definition: AMDGPUPTNote.h:24
void resolveRelocations()
Resolve the relocations for all symbols we currently know about.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LoadedObjectInfoHelper(RuntimeDyldImpl &RTDyld, LoadedObjectInfo::ObjSectionToIDMap ObjSecToIDMap)
Definition: RuntimeDyld.h:95
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
void reassignSectionAddress(unsigned SectionID, uint64_t Addr)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size)=0
Register the EH frames with the runtime so that c++ exceptions work.
void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress)
Map a section to its target address space value.
LoadedObjectInfo(RuntimeDyldImpl &RTDyld, ObjSectionToIDMap ObjSecToIDMap)
Definition: RuntimeDyld.h:73
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:70
virtual ~MemoryManager()=default