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 
11 namespace {
12 
13 using namespace llvm;
14 using namespace llvm::orc;
15 
16 class JITDylibSearchOrderResolver : public JITSymbolResolver {
17 public:
18   JITDylibSearchOrderResolver(MaterializationResponsibility &MR) : MR(MR) {}
19 
20   void lookup(const LookupSet &Symbols, OnResolvedFunction OnResolved) {
21     auto &ES = MR.getTargetJITDylib().getExecutionSession();
22     SymbolLookupSet InternedSymbols;
23 
24     // Intern the requested symbols: lookup takes interned strings.
25     for (auto &S : Symbols)
26       InternedSymbols.add(ES.intern(S));
27 
28     // Build an OnResolve callback to unwrap the interned strings and pass them
29     // to the OnResolved callback.
30     auto OnResolvedWithUnwrap =
31         [OnResolved = std::move(OnResolved)](
32             Expected<SymbolMap> InternedResult) mutable {
33           if (!InternedResult) {
34             OnResolved(InternedResult.takeError());
35             return;
36           }
37 
38           LookupResult Result;
39           for (auto &KV : *InternedResult)
40             Result[*KV.first] = std::move(KV.second);
41           OnResolved(Result);
42         };
43 
44     // Register dependencies for all symbols contained in this set.
45     auto RegisterDependencies = [&](const SymbolDependenceMap &Deps) {
46       MR.addDependenciesForAll(Deps);
47     };
48 
49     JITDylibSearchOrder SearchOrder;
50     MR.getTargetJITDylib().withSearchOrderDo(
51         [&](const JITDylibSearchOrder &JDs) { SearchOrder = JDs; });
52     ES.lookup(LookupKind::Static, SearchOrder, InternedSymbols,
53               SymbolState::Resolved, std::move(OnResolvedWithUnwrap),
54               RegisterDependencies);
55   }
56 
57   Expected<LookupSet> getResponsibilitySet(const LookupSet &Symbols) {
58     LookupSet Result;
59 
60     for (auto &KV : MR.getSymbols()) {
61       if (Symbols.count(*KV.first))
62         Result.insert(*KV.first);
63     }
64 
65     return Result;
66   }
67 
68 private:
69   MaterializationResponsibility &MR;
70 };
71 
72 } // end anonymous namespace
73 
74 namespace llvm {
75 namespace orc {
76 
77 RTDyldObjectLinkingLayer::RTDyldObjectLinkingLayer(
78     ExecutionSession &ES, GetMemoryManagerFunction GetMemoryManager)
79     : ObjectLayer(ES), GetMemoryManager(GetMemoryManager) {}
80 
81 void RTDyldObjectLinkingLayer::emit(MaterializationResponsibility R,
82                                     std::unique_ptr<MemoryBuffer> O) {
83   assert(O && "Object must not be null");
84 
85   // This method launches an asynchronous link step that will fulfill our
86   // materialization responsibility. We need to switch R to be heap
87   // allocated before that happens so it can live as long as the asynchronous
88   // link needs it to (i.e. it must be able to outlive this method).
89   auto SharedR = std::make_shared<MaterializationResponsibility>(std::move(R));
90 
91   auto &ES = getExecutionSession();
92 
93   // Create a MemoryBufferRef backed MemoryBuffer (i.e. shallow) copy of the
94   // the underlying buffer to pass into RuntimeDyld. This allows us to hold
95   // ownership of the real underlying buffer and return it to the user once
96   // the object has been emitted.
97   auto ObjBuffer = MemoryBuffer::getMemBuffer(O->getMemBufferRef(), false);
98 
99   auto Obj = object::ObjectFile::createObjectFile(*ObjBuffer);
100 
101   if (!Obj) {
102     getExecutionSession().reportError(Obj.takeError());
103     SharedR->failMaterialization();
104     return;
105   }
106 
107   // Collect the internal symbols from the object file: We will need to
108   // filter these later.
109   auto InternalSymbols = std::make_shared<std::set<StringRef>>();
110   {
111     for (auto &Sym : (*Obj)->symbols()) {
112       if (!(Sym.getFlags() & object::BasicSymbolRef::SF_Global)) {
113         if (auto SymName = Sym.getName())
114           InternalSymbols->insert(*SymName);
115         else {
116           ES.reportError(SymName.takeError());
117           R.failMaterialization();
118           return;
119         }
120       }
121     }
122   }
123 
124   auto K = R.getVModuleKey();
125   RuntimeDyld::MemoryManager *MemMgr = nullptr;
126 
127   // Create a record a memory manager for this object.
128   {
129     auto Tmp = GetMemoryManager();
130     std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
131     MemMgrs.push_back(std::move(Tmp));
132     MemMgr = MemMgrs.back().get();
133   }
134 
135   JITDylibSearchOrderResolver Resolver(*SharedR);
136 
137   jitLinkForORC(
138       **Obj, std::move(O), *MemMgr, Resolver, ProcessAllSections,
139       [this, K, SharedR, &Obj, InternalSymbols](
140           std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
141           std::map<StringRef, JITEvaluatedSymbol> ResolvedSymbols) {
142         return onObjLoad(K, *SharedR, **Obj, std::move(LoadedObjInfo),
143                          ResolvedSymbols, *InternalSymbols);
144       },
145       [this, K, SharedR, O = std::move(O)](Error Err) mutable {
146         onObjEmit(K, std::move(O), *SharedR, std::move(Err));
147       });
148 }
149 
150 Error RTDyldObjectLinkingLayer::onObjLoad(
151     VModuleKey K, MaterializationResponsibility &R, object::ObjectFile &Obj,
152     std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
153     std::map<StringRef, JITEvaluatedSymbol> Resolved,
154     std::set<StringRef> &InternalSymbols) {
155   SymbolFlagsMap ExtraSymbolsToClaim;
156   SymbolMap Symbols;
157   for (auto &KV : Resolved) {
158     // Scan the symbols and add them to the Symbols map for resolution.
159 
160     // We never claim internal symbols.
161     if (InternalSymbols.count(KV.first))
162       continue;
163 
164     auto InternedName = getExecutionSession().intern(KV.first);
165     auto Flags = KV.second.getFlags();
166 
167     // Override object flags and claim responsibility for symbols if
168     // requested.
169     if (OverrideObjectFlags || AutoClaimObjectSymbols) {
170       auto I = R.getSymbols().find(InternedName);
171 
172       if (OverrideObjectFlags && I != R.getSymbols().end())
173         Flags = I->second;
174       else if (AutoClaimObjectSymbols && I == R.getSymbols().end())
175         ExtraSymbolsToClaim[InternedName] = Flags;
176     }
177 
178     Symbols[InternedName] = JITEvaluatedSymbol(KV.second.getAddress(), Flags);
179   }
180 
181   if (!ExtraSymbolsToClaim.empty())
182     if (auto Err = R.defineMaterializing(ExtraSymbolsToClaim))
183       return Err;
184 
185   if (auto Err = R.notifyResolved(Symbols)) {
186     R.failMaterialization();
187     return Err;
188   }
189 
190   if (NotifyLoaded)
191     NotifyLoaded(K, Obj, *LoadedObjInfo);
192 
193   return Error::success();
194 }
195 
196 void RTDyldObjectLinkingLayer::onObjEmit(
197     VModuleKey K, std::unique_ptr<MemoryBuffer> ObjBuffer,
198     MaterializationResponsibility &R, Error Err) {
199   if (Err) {
200     getExecutionSession().reportError(std::move(Err));
201     R.failMaterialization();
202     return;
203   }
204 
205   if (auto Err = R.notifyEmitted()) {
206     getExecutionSession().reportError(std::move(Err));
207     R.failMaterialization();
208     return;
209   }
210 
211   if (NotifyEmitted)
212     NotifyEmitted(K, std::move(ObjBuffer));
213 }
214 
215 LegacyRTDyldObjectLinkingLayer::LegacyRTDyldObjectLinkingLayer(
216     ExecutionSession &ES, ResourcesGetter GetResources,
217     NotifyLoadedFtor NotifyLoaded, NotifyFinalizedFtor NotifyFinalized,
218     NotifyFreedFtor NotifyFreed)
219     : ES(ES), GetResources(std::move(GetResources)),
220       NotifyLoaded(std::move(NotifyLoaded)),
221       NotifyFinalized(std::move(NotifyFinalized)),
222       NotifyFreed(std::move(NotifyFreed)), ProcessAllSections(false) {}
223 
224 } // End namespace orc.
225 } // End namespace llvm.
226