LLVM  5.0.0
RTDyldObjectLinkingLayer.h
Go to the documentation of this file.
1 //===- RTDyldObjectLinkingLayer.h - RTDyld-based jit linking ---*- 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 // Contains the definition for an RTDyld-based, in-process object linking layer.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_EXECUTIONENGINE_ORC_RTDYLDOBJECTLINKINGLAYER_H
15 #define LLVM_EXECUTIONENGINE_ORC_RTDYLDOBJECTLINKINGLAYER_H
16 
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Object/ObjectFile.h"
23 #include "llvm/Support/Error.h"
24 #include <algorithm>
25 #include <cassert>
26 #include <functional>
27 #include <list>
28 #include <memory>
29 #include <string>
30 #include <utility>
31 #include <vector>
32 
33 namespace llvm {
34 namespace orc {
35 
37 public:
38 
39  using ObjectPtr =
40  std::shared_ptr<object::OwningBinary<object::ObjectFile>>;
41 
42 protected:
43 
44  /// @brief Holds a set of objects to be allocated/linked as a unit in the JIT.
45  ///
46  /// An instance of this class will be created for each set of objects added
47  /// via JITObjectLayer::addObject. Deleting the instance (via
48  /// removeObject) frees its memory, removing all symbol definitions that
49  /// had been provided by this instance. Higher level layers are responsible
50  /// for taking any action required to handle the missing symbols.
51  class LinkedObject {
52  public:
53  LinkedObject() = default;
54  LinkedObject(const LinkedObject&) = delete;
55  void operator=(const LinkedObject&) = delete;
56  virtual ~LinkedObject() = default;
57 
58  virtual void finalize() = 0;
59 
61  getSymbolMaterializer(std::string Name) = 0;
62 
63  virtual void mapSectionAddress(const void *LocalAddress,
64  JITTargetAddress TargetAddr) const = 0;
65 
66  JITSymbol getSymbol(StringRef Name, bool ExportedSymbolsOnly) {
67  auto SymEntry = SymbolTable.find(Name);
68  if (SymEntry == SymbolTable.end())
69  return nullptr;
70  if (!SymEntry->second.getFlags().isExported() && ExportedSymbolsOnly)
71  return nullptr;
72  if (!Finalized)
73  return JITSymbol(getSymbolMaterializer(Name),
74  SymEntry->second.getFlags());
75  return JITSymbol(SymEntry->second);
76  }
77 
78  protected:
80  bool Finalized = false;
81  };
82 
83  using LinkedObjectListT = std::list<std::unique_ptr<LinkedObject>>;
84 
85 public:
86  /// @brief Handle to a set of loaded objects.
87  using ObjHandleT = LinkedObjectListT::iterator;
88 };
89 
90 /// @brief Bare bones object linking layer.
91 ///
92 /// This class is intended to be used as the base layer for a JIT. It allows
93 /// object files to be loaded into memory, linked, and the addresses of their
94 /// symbols queried. All objects added to this layer can see each other's
95 /// symbols.
97 public:
98 
100 
101  /// @brief Functor for receiving object-loaded notifications.
102  using NotifyLoadedFtor = std::function<void(ObjHandleT, const ObjectPtr &Obj,
103  const LoadedObjectInfo &)>;
104 
105  /// @brief Functor for receiving finalization notifications.
106  using NotifyFinalizedFtor = std::function<void(ObjHandleT)>;
107 
108 private:
109 
110 
111  template <typename MemoryManagerPtrT, typename SymbolResolverPtrT,
112  typename FinalizerFtor>
113  class ConcreteLinkedObject : public LinkedObject {
114  public:
115  ConcreteLinkedObject(ObjectPtr Obj, MemoryManagerPtrT MemMgr,
116  SymbolResolverPtrT Resolver,
117  FinalizerFtor Finalizer,
118  bool ProcessAllSections)
119  : MemMgr(std::move(MemMgr)),
120  PFC(llvm::make_unique<PreFinalizeContents>(std::move(Obj),
121  std::move(Resolver),
122  std::move(Finalizer),
123  ProcessAllSections)) {
124  buildInitialSymbolTable(PFC->Obj);
125  }
126 
127  ~ConcreteLinkedObject() override {
128  MemMgr->deregisterEHFrames();
129  }
130 
131  void setHandle(ObjHandleT H) {
132  PFC->Handle = H;
133  }
134 
135  void finalize() override {
136  assert(PFC && "mapSectionAddress called on finalized LinkedObject");
137 
138  RuntimeDyld RTDyld(*MemMgr, *PFC->Resolver);
139  RTDyld.setProcessAllSections(PFC->ProcessAllSections);
140  PFC->RTDyld = &RTDyld;
141 
142  this->Finalized = true;
143  PFC->Finalizer(PFC->Handle, RTDyld, std::move(PFC->Obj),
144  [&]() {
145  this->updateSymbolTable(RTDyld);
146  });
147 
148  // Release resources.
149  PFC = nullptr;
150  }
151 
152  JITSymbol::GetAddressFtor getSymbolMaterializer(std::string Name) override {
153  return
154  [this, Name]() {
155  // The symbol may be materialized between the creation of this lambda
156  // and its execution, so we need to double check.
157  if (!this->Finalized)
158  this->finalize();
159  return this->getSymbol(Name, false).getAddress();
160  };
161  }
162 
163  void mapSectionAddress(const void *LocalAddress,
164  JITTargetAddress TargetAddr) const override {
165  assert(PFC && "mapSectionAddress called on finalized LinkedObject");
166  assert(PFC->RTDyld && "mapSectionAddress called on raw LinkedObject");
167  PFC->RTDyld->mapSectionAddress(LocalAddress, TargetAddr);
168  }
169 
170  private:
171 
172  void buildInitialSymbolTable(const ObjectPtr &Obj) {
173  for (auto &Symbol : Obj->getBinary()->symbols()) {
174  if (Symbol.getFlags() & object::SymbolRef::SF_Undefined)
175  continue;
176  Expected<StringRef> SymbolName = Symbol.getName();
177  // FIXME: Raise an error for bad symbols.
178  if (!SymbolName) {
179  consumeError(SymbolName.takeError());
180  continue;
181  }
183  SymbolTable.insert(
184  std::make_pair(*SymbolName, JITEvaluatedSymbol(0, Flags)));
185  }
186  }
187 
188  void updateSymbolTable(const RuntimeDyld &RTDyld) {
189  for (auto &SymEntry : SymbolTable)
190  SymEntry.second = RTDyld.getSymbol(SymEntry.first());
191  }
192 
193  // Contains the information needed prior to finalization: the object files,
194  // memory manager, resolver, and flags needed for RuntimeDyld.
195  struct PreFinalizeContents {
196  PreFinalizeContents(ObjectPtr Obj, SymbolResolverPtrT Resolver,
197  FinalizerFtor Finalizer, bool ProcessAllSections)
198  : Obj(std::move(Obj)), Resolver(std::move(Resolver)),
199  Finalizer(std::move(Finalizer)),
200  ProcessAllSections(ProcessAllSections) {}
201 
202  ObjectPtr Obj;
203  SymbolResolverPtrT Resolver;
204  FinalizerFtor Finalizer;
205  bool ProcessAllSections;
206  ObjHandleT Handle;
207  RuntimeDyld *RTDyld;
208  };
209 
210  MemoryManagerPtrT MemMgr;
211  std::unique_ptr<PreFinalizeContents> PFC;
212  };
213 
214  template <typename MemoryManagerPtrT, typename SymbolResolverPtrT,
215  typename FinalizerFtor>
216  std::unique_ptr<
217  ConcreteLinkedObject<MemoryManagerPtrT, SymbolResolverPtrT, FinalizerFtor>>
218  createLinkedObject(ObjectPtr Obj, MemoryManagerPtrT MemMgr,
219  SymbolResolverPtrT Resolver,
220  FinalizerFtor Finalizer,
221  bool ProcessAllSections) {
222  using LOS = ConcreteLinkedObject<MemoryManagerPtrT, SymbolResolverPtrT,
223  FinalizerFtor>;
224  return llvm::make_unique<LOS>(std::move(Obj), std::move(MemMgr),
225  std::move(Resolver), std::move(Finalizer),
226  ProcessAllSections);
227  }
228 
229 public:
230 
231  /// @brief Functor for creating memory managers.
232  using MemoryManagerGetter =
233  std::function<std::shared_ptr<RuntimeDyld::MemoryManager>()>;
234 
235  /// @brief Construct an ObjectLinkingLayer with the given NotifyLoaded,
236  /// and NotifyFinalized functors.
238  MemoryManagerGetter GetMemMgr,
239  NotifyLoadedFtor NotifyLoaded = NotifyLoadedFtor(),
240  NotifyFinalizedFtor NotifyFinalized = NotifyFinalizedFtor())
241  : GetMemMgr(GetMemMgr),
242  NotifyLoaded(std::move(NotifyLoaded)),
243  NotifyFinalized(std::move(NotifyFinalized)),
244  ProcessAllSections(false) {}
245 
246  /// @brief Set the 'ProcessAllSections' flag.
247  ///
248  /// If set to true, all sections in each object file will be allocated using
249  /// the memory manager, rather than just the sections required for execution.
250  ///
251  /// This is kludgy, and may be removed in the future.
252  void setProcessAllSections(bool ProcessAllSections) {
253  this->ProcessAllSections = ProcessAllSections;
254  }
255 
256  /// @brief Add a set of objects (or archives) that will be treated as a unit
257  /// for the purposes of symbol lookup and memory management.
258  ///
259  /// @return A handle that can be used to refer to the loaded objects (for
260  /// symbol searching, finalization, freeing memory, etc.).
262  std::shared_ptr<JITSymbolResolver> Resolver) {
263  auto Finalizer = [&](ObjHandleT H, RuntimeDyld &RTDyld,
264  const ObjectPtr &ObjToLoad,
265  std::function<void()> LOSHandleLoad) {
266  std::unique_ptr<RuntimeDyld::LoadedObjectInfo> Info =
267  RTDyld.loadObject(*ObjToLoad->getBinary());
268 
269  LOSHandleLoad();
270 
271  if (this->NotifyLoaded)
272  this->NotifyLoaded(H, ObjToLoad, *Info);
273 
274  RTDyld.finalizeWithMemoryManagerLocking();
275 
276  if (this->NotifyFinalized)
277  this->NotifyFinalized(H);
278  };
279 
280  auto LO =
281  createLinkedObject(std::move(Obj), GetMemMgr(),
282  std::move(Resolver), std::move(Finalizer),
283  ProcessAllSections);
284  // LOS is an owning-ptr. Keep a non-owning one so that we can set the handle
285  // below.
286  auto *LOPtr = LO.get();
287 
288  ObjHandleT Handle = LinkedObjList.insert(LinkedObjList.end(), std::move(LO));
289  LOPtr->setHandle(Handle);
290 
291  return Handle;
292  }
293 
294  /// @brief Remove the set of objects associated with handle H.
295  ///
296  /// All memory allocated for the objects will be freed, and the sections and
297  /// symbols they provided will no longer be available. No attempt is made to
298  /// re-emit the missing symbols, and any use of these symbols (directly or
299  /// indirectly) will result in undefined behavior. If dependence tracking is
300  /// required to detect or resolve such issues it should be added at a higher
301  /// layer.
303  // How do we invalidate the symbols in H?
304  LinkedObjList.erase(H);
305  return Error::success();
306  }
307 
308  /// @brief Search for the given named symbol.
309  /// @param Name The name of the symbol to search for.
310  /// @param ExportedSymbolsOnly If true, search only for exported symbols.
311  /// @return A handle for the given named symbol, if it exists.
312  JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly) {
313  for (auto I = LinkedObjList.begin(), E = LinkedObjList.end(); I != E;
314  ++I)
315  if (auto Symbol = findSymbolIn(I, Name, ExportedSymbolsOnly))
316  return Symbol;
317 
318  return nullptr;
319  }
320 
321  /// @brief Search for the given named symbol in the context of the set of
322  /// loaded objects represented by the handle H.
323  /// @param H The handle for the object set to search in.
324  /// @param Name The name of the symbol to search for.
325  /// @param ExportedSymbolsOnly If true, search only for exported symbols.
326  /// @return A handle for the given named symbol, if it is found in the
327  /// given object set.
329  bool ExportedSymbolsOnly) {
330  return (*H)->getSymbol(Name, ExportedSymbolsOnly);
331  }
332 
333  /// @brief Map section addresses for the objects associated with the handle H.
334  void mapSectionAddress(ObjHandleT H, const void *LocalAddress,
335  JITTargetAddress TargetAddr) {
336  (*H)->mapSectionAddress(LocalAddress, TargetAddr);
337  }
338 
339  /// @brief Immediately emit and finalize the object set represented by the
340  /// given handle.
341  /// @param H Handle for object set to emit/finalize.
343  (*H)->finalize();
344  return Error::success();
345  }
346 
347 private:
348 
349  LinkedObjectListT LinkedObjList;
350  MemoryManagerGetter GetMemMgr;
351  NotifyLoadedFtor NotifyLoaded;
352  NotifyFinalizedFtor NotifyFinalized;
353  bool ProcessAllSections = false;
354 };
355 
356 } // end namespace orc
357 } // end namespace llvm
358 
359 #endif // LLVM_EXECUTIONENGINE_ORC_RTDYLDOBJECTLINKINGLAYER_H
Error emitAndFinalize(ObjHandleT H)
Immediately emit and finalize the object set represented by the given handle.
Represents a symbol in the JIT.
Definition: JITSymbol.h:122
std::shared_ptr< object::OwningBinary< object::ObjectFile >> ObjectPtr
JITSymbol getSymbol(StringRef Name, bool ExportedSymbolsOnly)
Holds a set of objects to be allocated/linked as a unit in the JIT.
std::list< std::unique_ptr< LinkedObject >> LinkedObjectListT
Bare bones object linking layer.
LinkedObjectListT::iterator ObjHandleT
Handle to a set of loaded objects.
void mapSectionAddress(ObjHandleT H, const void *LocalAddress, JITTargetAddress TargetAddr)
Map section addresses for the objects associated with the handle H.
std::function< std::shared_ptr< RuntimeDyld::MemoryManager >()> MemoryManagerGetter
Functor for creating memory managers.
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
Error removeObject(ObjHandleT H)
Remove the set of objects associated with handle H.
JITSymbol findSymbolIn(ObjHandleT H, StringRef Name, bool ExportedSymbolsOnly)
Search for the given named symbol in the context of the set of loaded objects represented by the hand...
uint64_t JITTargetAddress
Represents an address in the target process's address space.
Definition: JITSymbol.h:37
Expected< const typename ELFT::Sym * > getSymbol(typename ELFT::SymRange Symbols, uint32_t Index)
Definition: ELF.h:243
const char * Name
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:221
Function Alias Analysis false
#define H(x, y, z)
Definition: MD5.cpp:57
virtual void mapSectionAddress(const void *LocalAddress, JITTargetAddress TargetAddr) const =0
static JITSymbolFlags fromObjectSymbol(const object::BasicSymbolRef &Symbol)
Construct a JITSymbolFlags value based on the flags of the given libobject symbol.
Definition: JITSymbol.cpp:32
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:593
static ErrorSuccess success()
Create a success value.
Definition: Error.h:311
#define E
Definition: LargeTest.cpp:27
JITSymbol findSymbolIn(ModuleHandleT H, const std::string &Name, bool ExportedSymbolsOnly)
std::function< void(ObjHandleT, const ObjectPtr &Obj, const LoadedObjectInfo &)> NotifyLoadedFtor
Functor for receiving object-loaded notifications.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:220
An inferface for inquiring the load address of a loaded object file to be used by the DIContext imple...
Definition: DIContext.h:192
void setProcessAllSections(bool ProcessAllSections)
Set the 'ProcessAllSections' flag.
virtual JITSymbol::GetAddressFtor getSymbolMaterializer(std::string Name)=0
std::function< Expected< JITTargetAddress >()> GetAddressFtor
Definition: JITSymbol.h:124
static std::vector< std::string > Flags
Definition: FlagsTest.cpp:8
JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly)
Search for the given named symbol.
#define I(x, y, z)
Definition: MD5.cpp:58
RTDyldObjectLinkingLayer(MemoryManagerGetter GetMemMgr, NotifyLoadedFtor NotifyLoaded=NotifyLoadedFtor(), NotifyFinalizedFtor NotifyFinalized=NotifyFinalizedFtor())
Construct an ObjectLinkingLayer with the given NotifyLoaded, and NotifyFinalized functors.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Expected< ObjHandleT > addObject(ObjectPtr Obj, std::shared_ptr< JITSymbolResolver > Resolver)
Add a set of objects (or archives) that will be treated as a unit for the purposes of symbol lookup a...
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
print Print MemDeps of function
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
std::function< void(ObjHandleT)> NotifyFinalizedFtor
Functor for receiving finalization notifications.
void operator=(const LinkedObject &)=delete