568f105166955fffb5da7002e3d9e1583ccc62eb
[oota-llvm.git] / include / llvm / ExecutionEngine / Orc / ObjectLinkingLayer.h
1 //===- ObjectLinkingLayer.h - Add object files to a JIT process -*- 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 the object layer of the JIT.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_EXECUTIONENGINE_ORC_OBJECTLINKINGLAYER_H
15 #define LLVM_EXECUTIONENGINE_ORC_OBJECTLINKINGLAYER_H
16
17 #include "LookasideRTDyldMM.h"
18 #include "llvm/ExecutionEngine/ExecutionEngine.h"
19 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
20 #include <list>
21 #include <memory>
22
23 namespace llvm {
24
25 class ObjectLinkingLayerBase {
26 protected:
27   /// @brief Holds a set of objects to be allocated/linked as a unit in the JIT.
28   ///
29   /// An instance of this class will be created for each set of objects added
30   /// via JITObjectLayer::addObjectSet. Deleting the instance (via
31   /// removeObjectSet) frees its memory, removing all symbol definitions that
32   /// had been provided by this instance. Higher level layers are responsible
33   /// for taking any action required to handle the missing symbols.
34   class LinkedObjectSet {
35     LinkedObjectSet(const LinkedObjectSet&) LLVM_DELETED_FUNCTION;
36     void operator=(const LinkedObjectSet&) LLVM_DELETED_FUNCTION;
37   public:
38     LinkedObjectSet(std::unique_ptr<RTDyldMemoryManager> MM)
39         : MM(std::move(MM)), RTDyld(llvm::make_unique<RuntimeDyld>(&*this->MM)),
40           State(Raw) {}
41
42     // MSVC 2012 cannot infer a move constructor, so write it out longhand.
43     LinkedObjectSet(LinkedObjectSet &&O)
44         : MM(std::move(O.MM)), RTDyld(std::move(O.RTDyld)), State(O.State) {}
45
46     std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
47     addObject(const object::ObjectFile &Obj) {
48       return RTDyld->loadObject(Obj);
49     }
50
51     uint64_t getSymbolAddress(StringRef Name, bool ExportedSymbolsOnly) {
52       if (ExportedSymbolsOnly)
53         return RTDyld->getExportedSymbolLoadAddress(Name);
54       return RTDyld->getSymbolLoadAddress(Name);
55     }
56
57     bool NeedsFinalization() const { return (State == Raw); }
58
59     void Finalize() {
60       State = Finalizing;
61       RTDyld->resolveRelocations();
62       RTDyld->registerEHFrames();
63       MM->finalizeMemory();
64       State = Finalized;
65     }
66
67     void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress) {
68       assert((State != Finalized) &&
69              "Attempting to remap sections for finalized objects.");
70       RTDyld->mapSectionAddress(LocalAddress, TargetAddress);
71     }
72
73   private:
74     std::unique_ptr<RTDyldMemoryManager> MM;
75     std::unique_ptr<RuntimeDyld> RTDyld;
76     enum { Raw, Finalizing, Finalized } State;
77   };
78
79   typedef std::list<LinkedObjectSet> LinkedObjectSetListT;
80
81 public:
82   /// @brief Handle to a set of loaded objects.
83   typedef LinkedObjectSetListT::iterator ObjSetHandleT;
84 };
85
86 /// @brief Default (no-op) action to perform when loading objects.
87 class DoNothingOnNotifyLoaded {
88 public:
89   template <typename ObjSetT, typename LoadResult>
90   void operator()(ObjectLinkingLayerBase::ObjSetHandleT, const ObjSetT &,
91                   const LoadResult &) {}
92 };
93
94 /// @brief Bare bones object linking layer.
95 ///
96 ///   This class is intended to be used as the base layer for a JIT. It allows
97 /// object files to be loaded into memory, linked, and the addresses of their
98 /// symbols queried. All objects added to this layer can see each other's
99 /// symbols.
100 template <typename NotifyLoadedFtor = DoNothingOnNotifyLoaded>
101 class ObjectLinkingLayer : public ObjectLinkingLayerBase {
102 public:
103
104   /// @brief LoadedObjectInfo list. Contains a list of owning pointers to
105   ///        RuntimeDyld::LoadedObjectInfo instances.
106   typedef std::vector<std::unique_ptr<RuntimeDyld::LoadedObjectInfo>>
107       LoadedObjInfoList;
108
109   /// @brief Functor to create RTDyldMemoryManager instances.
110   typedef std::function<std::unique_ptr<RTDyldMemoryManager>()> CreateRTDyldMMFtor;
111
112   /// @brief Functor for receiving finalization notifications.
113   typedef std::function<void(ObjSetHandleT)> NotifyFinalizedFtor;
114
115   /// @brief Construct an ObjectLinkingLayer with the given NotifyLoaded,
116   ///        NotifyFinalized and CreateMemoryManager functors.
117   ObjectLinkingLayer(
118       CreateRTDyldMMFtor CreateMemoryManager,
119       NotifyLoadedFtor NotifyLoaded,
120       NotifyFinalizedFtor NotifyFinalized)
121       : NotifyLoaded(std::move(NotifyLoaded)),
122         NotifyFinalized(std::move(NotifyFinalized)),
123         CreateMemoryManager(std::move(CreateMemoryManager)) {}
124
125   /// @brief Add a set of objects (or archives) that will be treated as a unit
126   ///        for the purposes of symbol lookup and memory management.
127   ///
128   /// @return A pair containing (1) A handle that can be used to free the memory
129   ///         allocated for the objects, and (2) a LoadedObjInfoList containing
130   ///         one LoadedObjInfo instance for each object at the corresponding
131   ///         index in the Objects list.
132   ///
133   ///   This version of this method allows the client to pass in an
134   /// RTDyldMemoryManager instance that will be used to allocate memory and look
135   /// up external symbol addresses for the given objects.
136   template <typename ObjSetT>
137   ObjSetHandleT addObjectSet(const ObjSetT &Objects,
138                              std::unique_ptr<RTDyldMemoryManager> MM) {
139
140     if (!MM) {
141       assert(CreateMemoryManager &&
142              "No memory manager or memory manager creator provided.");
143       MM = CreateMemoryManager();
144     }
145
146     ObjSetHandleT Handle = LinkedObjSetList.insert(
147         LinkedObjSetList.end(), LinkedObjectSet(std::move(MM)));
148     LinkedObjectSet &LOS = *Handle;
149     LoadedObjInfoList LoadedObjInfos;
150
151     for (auto &Obj : Objects)
152       LoadedObjInfos.push_back(LOS.addObject(*Obj));
153
154     NotifyLoaded(Handle, Objects, LoadedObjInfos);
155
156     return Handle;
157   }
158
159   /// @brief Map section addresses for the objects associated with the handle H.
160   void mapSectionAddress(ObjSetHandleT H, const void *LocalAddress,
161                          uint64_t TargetAddress) {
162     H->mapSectionAddress(LocalAddress, TargetAddress);
163   }
164
165   /// @brief Remove the set of objects associated with handle H.
166   ///
167   ///   All memory allocated for the objects will be freed, and the sections and
168   /// symbols they provided will no longer be available. No attempt is made to
169   /// re-emit the missing symbols, and any use of these symbols (directly or
170   /// indirectly) will result in undefined behavior. If dependence tracking is
171   /// required to detect or resolve such issues it should be added at a higher
172   /// layer.
173   void removeObjectSet(ObjSetHandleT H) {
174     // How do we invalidate the symbols in H?
175     LinkedObjSetList.erase(H);
176   }
177
178   /// @brief Get the address of a loaded symbol.
179   ///
180   /// @return The address in the target process's address space of the named
181   ///         symbol. Null if no such symbol is known.
182   ///
183   ///   This method will trigger the finalization of the linked object set
184   /// containing the definition of the given symbol, if it is found.
185   uint64_t getSymbolAddress(StringRef Name, bool ExportedSymbolsOnly) {
186     for (auto I = LinkedObjSetList.begin(), E = LinkedObjSetList.end(); I != E;
187          ++I)
188       if (uint64_t Addr = lookupSymbolAddressIn(I, Name, ExportedSymbolsOnly))
189         return Addr;
190
191     return 0;
192   }
193
194   /// @brief Search for a given symbol in the context of the set of loaded
195   ///        objects represented by the handle H.
196   ///
197   /// @return The address in the target process's address space of the named
198   ///         symbol. Null if the given object set does not contain a definition
199   ///         of this symbol.
200   ///
201   ///   This method will trigger the finalization of the linked object set
202   /// represented by the handle H if that set contains the requested symbol.
203   uint64_t lookupSymbolAddressIn(ObjSetHandleT H, StringRef Name,
204                                  bool ExportedSymbolsOnly) {
205     if (uint64_t Addr = H->getSymbolAddress(Name, ExportedSymbolsOnly)) {
206       if (H->NeedsFinalization()) {
207         H->Finalize();
208         if (NotifyFinalized)
209           NotifyFinalized(H);
210       }
211       return Addr;
212     }
213     return 0;
214   }
215
216 private:
217   LinkedObjectSetListT LinkedObjSetList;
218   NotifyLoadedFtor NotifyLoaded;
219   NotifyFinalizedFtor NotifyFinalized;
220   CreateRTDyldMMFtor CreateMemoryManager;
221 };
222
223 } // end namespace llvm
224
225 #endif // LLVM_EXECUTIONENGINE_ORC_OBJECTLINKINGLAYER_H