1 //===-- RTDyldObjectLinkingLayer.cpp - RuntimeDyld backed ORC ObjectLayer -===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
10 #include "llvm/Object/COFF.h"
11 
12 namespace {
13 
14 using namespace llvm;
15 using namespace llvm::orc;
16 
17 class JITDylibSearchOrderResolver : public JITSymbolResolver {
18 public:
19   JITDylibSearchOrderResolver(MaterializationResponsibility &MR) : MR(MR) {}
20 
21   void lookup(const LookupSet &Symbols, OnResolvedFunction OnResolved) {
22     auto &ES = MR.getTargetJITDylib().getExecutionSession();
23     SymbolLookupSet InternedSymbols;
24 
25     // Intern the requested symbols: lookup takes interned strings.
26     for (auto &S : Symbols)
27       InternedSymbols.add(ES.intern(S));
28 
29     // Build an OnResolve callback to unwrap the interned strings and pass them
30     // to the OnResolved callback.
31     auto OnResolvedWithUnwrap =
32         [OnResolved = std::move(OnResolved)](
33             Expected<SymbolMap> InternedResult) mutable {
34           if (!InternedResult) {
35             OnResolved(InternedResult.takeError());
36             return;
37           }
38 
39           LookupResult Result;
40           for (auto &KV : *InternedResult)
41             Result[*KV.first] = std::move(KV.second);
42           OnResolved(Result);
43         };
44 
45     // Register dependencies for all symbols contained in this set.
46     auto RegisterDependencies = [&](const SymbolDependenceMap &Deps) {
47       MR.addDependenciesForAll(Deps);
48     };
49 
50     JITDylibSearchOrder SearchOrder;
51     MR.getTargetJITDylib().withSearchOrderDo(
52         [&](const JITDylibSearchOrder &JDs) { SearchOrder = JDs; });
53     ES.lookup(LookupKind::Static, SearchOrder, InternedSymbols,
54               SymbolState::Resolved, std::move(OnResolvedWithUnwrap),
55               RegisterDependencies);
56   }
57 
58   Expected<LookupSet> getResponsibilitySet(const LookupSet &Symbols) {
59     LookupSet Result;
60 
61     for (auto &KV : MR.getSymbols()) {
62       if (Symbols.count(*KV.first))
63         Result.insert(*KV.first);
64     }
65 
66     return Result;
67   }
68 
69 private:
70   MaterializationResponsibility &MR;
71 };
72 
73 } // end anonymous namespace
74 
75 namespace llvm {
76 namespace orc {
77 
78 RTDyldObjectLinkingLayer::RTDyldObjectLinkingLayer(
79     ExecutionSession &ES, GetMemoryManagerFunction GetMemoryManager)
80     : ObjectLayer(ES), GetMemoryManager(GetMemoryManager) {}
81 
82 RTDyldObjectLinkingLayer::~RTDyldObjectLinkingLayer() {
83   std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
84   for (auto &MemMgr : MemMgrs) {
85     for (auto *L : EventListeners)
86       L->notifyFreeingObject(
87           static_cast<uint64_t>(reinterpret_cast<uintptr_t>(MemMgr.get())));
88     MemMgr->deregisterEHFrames();
89   }
90 }
91 
92 void RTDyldObjectLinkingLayer::emit(MaterializationResponsibility R,
93                                     std::unique_ptr<MemoryBuffer> O) {
94   assert(O && "Object must not be null");
95 
96   // This method launches an asynchronous link step that will fulfill our
97   // materialization responsibility. We need to switch R to be heap
98   // allocated before that happens so it can live as long as the asynchronous
99   // link needs it to (i.e. it must be able to outlive this method).
100   auto SharedR = std::make_shared<MaterializationResponsibility>(std::move(R));
101 
102   auto &ES = getExecutionSession();
103 
104   // Create a MemoryBufferRef backed MemoryBuffer (i.e. shallow) copy of the
105   // the underlying buffer to pass into RuntimeDyld. This allows us to hold
106   // ownership of the real underlying buffer and return it to the user once
107   // the object has been emitted.
108   auto ObjBuffer = MemoryBuffer::getMemBuffer(O->getMemBufferRef(), false);
109 
110   auto Obj = object::ObjectFile::createObjectFile(*ObjBuffer);
111 
112   if (!Obj) {
113     getExecutionSession().reportError(Obj.takeError());
114     SharedR->failMaterialization();
115     return;
116   }
117 
118   // Collect the internal symbols from the object file: We will need to
119   // filter these later.
120   auto InternalSymbols = std::make_shared<std::set<StringRef>>();
121   {
122     for (auto &Sym : (*Obj)->symbols()) {
123 
124       // Skip file symbols.
125       if (auto SymType = Sym.getType()) {
126         if (*SymType == object::SymbolRef::ST_File)
127           continue;
128       } else {
129         ES.reportError(SymType.takeError());
130         R.failMaterialization();
131         return;
132       }
133 
134       // Don't include symbols that aren't global.
135       if (!(Sym.getFlags() & object::BasicSymbolRef::SF_Global)) {
136         if (auto SymName = Sym.getName())
137           InternalSymbols->insert(*SymName);
138         else {
139           ES.reportError(SymName.takeError());
140           R.failMaterialization();
141           return;
142         }
143       }
144     }
145   }
146 
147   auto K = R.getVModuleKey();
148   RuntimeDyld::MemoryManager *MemMgr = nullptr;
149 
150   // Create a record a memory manager for this object.
151   {
152     auto Tmp = GetMemoryManager();
153     std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
154     MemMgrs.push_back(std::move(Tmp));
155     MemMgr = MemMgrs.back().get();
156   }
157 
158   JITDylibSearchOrderResolver Resolver(*SharedR);
159 
160   jitLinkForORC(
161       **Obj, std::move(O), *MemMgr, Resolver, ProcessAllSections,
162       [this, K, SharedR, &Obj, MemMgr, InternalSymbols](
163           std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
164           std::map<StringRef, JITEvaluatedSymbol> ResolvedSymbols) {
165         return onObjLoad(K, *SharedR, **Obj, MemMgr, std::move(LoadedObjInfo),
166                          ResolvedSymbols, *InternalSymbols);
167       },
168       [this, K, SharedR, &Obj, O = std::move(O), MemMgr](Error Err) mutable {
169         onObjEmit(K, *SharedR, **Obj, std::move(O), MemMgr, std::move(Err));
170       });
171 }
172 
173 void RTDyldObjectLinkingLayer::registerJITEventListener(JITEventListener &L) {
174   std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
175   assert(llvm::none_of(EventListeners,
176                        [&](JITEventListener *O) { return O == &L; }) &&
177          "Listener has already been registered");
178   EventListeners.push_back(&L);
179 }
180 
181 void RTDyldObjectLinkingLayer::unregisterJITEventListener(JITEventListener &L) {
182   std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
183   auto I = llvm::find(EventListeners, &L);
184   assert(I != EventListeners.end() && "Listener not registered");
185   EventListeners.erase(I);
186 }
187 
188 Error RTDyldObjectLinkingLayer::onObjLoad(
189     VModuleKey K, MaterializationResponsibility &R, object::ObjectFile &Obj,
190     RuntimeDyld::MemoryManager *MemMgr,
191     std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
192     std::map<StringRef, JITEvaluatedSymbol> Resolved,
193     std::set<StringRef> &InternalSymbols) {
194   SymbolFlagsMap ExtraSymbolsToClaim;
195   SymbolMap Symbols;
196 
197   // Hack to support COFF constant pool comdats introduced during compilation:
198   // (See http://llvm.org/PR40074)
199   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(&Obj)) {
200     auto &ES = getExecutionSession();
201 
202     // For all resolved symbols that are not already in the responsibilty set:
203     // check whether the symbol is in a comdat section and if so mark it as
204     // weak.
205     for (auto &Sym : COFFObj->symbols()) {
206       if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
207         continue;
208       auto Name = Sym.getName();
209       if (!Name)
210         return Name.takeError();
211       auto I = Resolved.find(*Name);
212 
213       // Skip unresolved symbols, internal symbols, and symbols that are
214       // already in the responsibility set.
215       if (I == Resolved.end() || InternalSymbols.count(*Name) ||
216           R.getSymbols().count(ES.intern(*Name)))
217         continue;
218       auto Sec = Sym.getSection();
219       if (!Sec)
220         return Sec.takeError();
221       if (*Sec == COFFObj->section_end())
222         continue;
223       auto &COFFSec = *COFFObj->getCOFFSection(**Sec);
224       if (COFFSec.Characteristics & COFF::IMAGE_SCN_LNK_COMDAT)
225         I->second.setFlags(I->second.getFlags() | JITSymbolFlags::Weak);
226     }
227   }
228 
229   for (auto &KV : Resolved) {
230     // Scan the symbols and add them to the Symbols map for resolution.
231 
232     // We never claim internal symbols.
233     if (InternalSymbols.count(KV.first))
234       continue;
235 
236     auto InternedName = getExecutionSession().intern(KV.first);
237     auto Flags = KV.second.getFlags();
238 
239     // Override object flags and claim responsibility for symbols if
240     // requested.
241     if (OverrideObjectFlags || AutoClaimObjectSymbols) {
242       auto I = R.getSymbols().find(InternedName);
243 
244       if (OverrideObjectFlags && I != R.getSymbols().end())
245         Flags = I->second;
246       else if (AutoClaimObjectSymbols && I == R.getSymbols().end())
247         ExtraSymbolsToClaim[InternedName] = Flags;
248     }
249 
250     Symbols[InternedName] = JITEvaluatedSymbol(KV.second.getAddress(), Flags);
251   }
252 
253   if (!ExtraSymbolsToClaim.empty()) {
254     if (auto Err = R.defineMaterializing(ExtraSymbolsToClaim))
255       return Err;
256 
257     // If we claimed responsibility for any weak symbols but were rejected then
258     // we need to remove them from the resolved set.
259     for (auto &KV : ExtraSymbolsToClaim)
260       if (KV.second.isWeak() && !R.getSymbols().count(KV.first))
261         Symbols.erase(KV.first);
262   }
263 
264   if (const auto &InitSym = R.getInitializerSymbol())
265     Symbols[InitSym] = JITEvaluatedSymbol();
266 
267   if (auto Err = R.notifyResolved(Symbols)) {
268     R.failMaterialization();
269     return Err;
270   }
271 
272   if (NotifyLoaded)
273     NotifyLoaded(K, Obj, *LoadedObjInfo);
274 
275   std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
276   assert(!LoadedObjInfos.count(MemMgr) && "Duplicate loaded info for MemMgr");
277   LoadedObjInfos[MemMgr] = std::move(LoadedObjInfo);
278 
279   return Error::success();
280 }
281 
282 void RTDyldObjectLinkingLayer::onObjEmit(
283     VModuleKey K, MaterializationResponsibility &R, object::ObjectFile &Obj,
284     std::unique_ptr<MemoryBuffer> ObjBuffer, RuntimeDyld::MemoryManager *MemMgr,
285     Error Err) {
286   if (Err) {
287     getExecutionSession().reportError(std::move(Err));
288     R.failMaterialization();
289     return;
290   }
291 
292   if (auto Err = R.notifyEmitted()) {
293     getExecutionSession().reportError(std::move(Err));
294     R.failMaterialization();
295     return;
296   }
297 
298   if (NotifyEmitted)
299     NotifyEmitted(K, std::move(ObjBuffer));
300 
301   // Run EventListener notifyLoaded callbacks.
302   std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
303   auto LOIItr = LoadedObjInfos.find(MemMgr);
304   assert(LOIItr != LoadedObjInfos.end() && "LoadedObjInfo missing");
305   for (auto *L : EventListeners)
306     L->notifyObjectLoaded(
307         static_cast<uint64_t>(reinterpret_cast<uintptr_t>(MemMgr)), Obj,
308         *LOIItr->second);
309   LoadedObjInfos.erase(MemMgr);
310 }
311 
312 LegacyRTDyldObjectLinkingLayer::LegacyRTDyldObjectLinkingLayer(
313     ExecutionSession &ES, ResourcesGetter GetResources,
314     NotifyLoadedFtor NotifyLoaded, NotifyFinalizedFtor NotifyFinalized,
315     NotifyFreedFtor NotifyFreed)
316     : ES(ES), GetResources(std::move(GetResources)),
317       NotifyLoaded(std::move(NotifyLoaded)),
318       NotifyFinalized(std::move(NotifyFinalized)),
319       NotifyFreed(std::move(NotifyFreed)), ProcessAllSections(false) {}
320 
321 } // End namespace orc.
322 } // End namespace llvm.
323