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     MemMgr->deregisterEHFrames();
86 }
87 
88 void RTDyldObjectLinkingLayer::emit(MaterializationResponsibility R,
89                                     std::unique_ptr<MemoryBuffer> O) {
90   assert(O && "Object must not be null");
91   dbgs() << "Emitting via RTDyldObjectLinkingLayer:\n"
92          << R.getSymbols() << "\n";
93   // This method launches an asynchronous link step that will fulfill our
94   // materialization responsibility. We need to switch R to be heap
95   // allocated before that happens so it can live as long as the asynchronous
96   // link needs it to (i.e. it must be able to outlive this method).
97   auto SharedR = std::make_shared<MaterializationResponsibility>(std::move(R));
98 
99   auto &ES = getExecutionSession();
100 
101   // Create a MemoryBufferRef backed MemoryBuffer (i.e. shallow) copy of the
102   // the underlying buffer to pass into RuntimeDyld. This allows us to hold
103   // ownership of the real underlying buffer and return it to the user once
104   // the object has been emitted.
105   auto ObjBuffer = MemoryBuffer::getMemBuffer(O->getMemBufferRef(), false);
106 
107   auto Obj = object::ObjectFile::createObjectFile(*ObjBuffer);
108 
109   if (!Obj) {
110     getExecutionSession().reportError(Obj.takeError());
111     SharedR->failMaterialization();
112     return;
113   }
114 
115   // Collect the internal symbols from the object file: We will need to
116   // filter these later.
117   auto InternalSymbols = std::make_shared<std::set<StringRef>>();
118   {
119     for (auto &Sym : (*Obj)->symbols()) {
120       if (!(Sym.getFlags() & object::BasicSymbolRef::SF_Global)) {
121         if (auto SymName = Sym.getName())
122           InternalSymbols->insert(*SymName);
123         else {
124           ES.reportError(SymName.takeError());
125           R.failMaterialization();
126           return;
127         }
128       }
129     }
130   }
131 
132   auto K = R.getVModuleKey();
133   RuntimeDyld::MemoryManager *MemMgr = nullptr;
134 
135   // Create a record a memory manager for this object.
136   {
137     auto Tmp = GetMemoryManager();
138     std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
139     MemMgrs.push_back(std::move(Tmp));
140     MemMgr = MemMgrs.back().get();
141   }
142 
143   JITDylibSearchOrderResolver Resolver(*SharedR);
144 
145   jitLinkForORC(
146       **Obj, std::move(O), *MemMgr, Resolver, ProcessAllSections,
147       [this, K, SharedR, &Obj, InternalSymbols](
148           std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
149           std::map<StringRef, JITEvaluatedSymbol> ResolvedSymbols) {
150         return onObjLoad(K, *SharedR, **Obj, std::move(LoadedObjInfo),
151                          ResolvedSymbols, *InternalSymbols);
152       },
153       [this, K, SharedR, O = std::move(O)](Error Err) mutable {
154         onObjEmit(K, std::move(O), *SharedR, std::move(Err));
155       });
156 }
157 
158 Error RTDyldObjectLinkingLayer::onObjLoad(
159     VModuleKey K, MaterializationResponsibility &R, object::ObjectFile &Obj,
160     std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
161     std::map<StringRef, JITEvaluatedSymbol> Resolved,
162     std::set<StringRef> &InternalSymbols) {
163   SymbolFlagsMap ExtraSymbolsToClaim;
164   SymbolMap Symbols;
165 
166   // Hack to support COFF constant pool comdats introduced during compilation:
167   // (See http://llvm.org/PR40074)
168   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(&Obj)) {
169     auto &ES = getExecutionSession();
170 
171     // For all resolved symbols that are not already in the responsibilty set:
172     // check whether the symbol is in a comdat section and if so mark it as
173     // weak.
174     for (auto &Sym : COFFObj->symbols()) {
175       if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
176         continue;
177       auto Name = Sym.getName();
178       if (!Name)
179         return Name.takeError();
180       auto I = Resolved.find(*Name);
181 
182       // Skip unresolved symbols, internal symbols, and symbols that are
183       // already in the responsibility set.
184       if (I == Resolved.end() || InternalSymbols.count(*Name) ||
185           R.getSymbols().count(ES.intern(*Name)))
186         continue;
187       auto Sec = Sym.getSection();
188       if (!Sec)
189         return Sec.takeError();
190       if (*Sec == COFFObj->section_end())
191         continue;
192       auto &COFFSec = *COFFObj->getCOFFSection(**Sec);
193       if (COFFSec.Characteristics & COFF::IMAGE_SCN_LNK_COMDAT)
194         I->second.setFlags(I->second.getFlags() | JITSymbolFlags::Weak);
195     }
196   }
197 
198   for (auto &KV : Resolved) {
199     // Scan the symbols and add them to the Symbols map for resolution.
200 
201     // We never claim internal symbols.
202     if (InternalSymbols.count(KV.first))
203       continue;
204 
205     auto InternedName = getExecutionSession().intern(KV.first);
206     auto Flags = KV.second.getFlags();
207 
208     // Override object flags and claim responsibility for symbols if
209     // requested.
210     if (OverrideObjectFlags || AutoClaimObjectSymbols) {
211       auto I = R.getSymbols().find(InternedName);
212 
213       if (OverrideObjectFlags && I != R.getSymbols().end())
214         Flags = I->second;
215       else if (AutoClaimObjectSymbols && I == R.getSymbols().end())
216         ExtraSymbolsToClaim[InternedName] = Flags;
217     }
218 
219     Symbols[InternedName] = JITEvaluatedSymbol(KV.second.getAddress(), Flags);
220   }
221 
222   if (!ExtraSymbolsToClaim.empty()) {
223     if (auto Err = R.defineMaterializing(ExtraSymbolsToClaim))
224       return Err;
225 
226     // If we claimed responsibility for any weak symbols but were rejected then
227     // we need to remove them from the resolved set.
228     for (auto &KV : ExtraSymbolsToClaim)
229       if (KV.second.isWeak() && !R.getSymbols().count(KV.first))
230         Symbols.erase(KV.first);
231   }
232 
233   if (const auto &InitSym = R.getInitializerSymbol())
234     Symbols[InitSym] = JITEvaluatedSymbol();
235 
236   if (auto Err = R.notifyResolved(Symbols)) {
237     R.failMaterialization();
238     return Err;
239   }
240 
241   if (NotifyLoaded)
242     NotifyLoaded(K, Obj, *LoadedObjInfo);
243 
244   return Error::success();
245 }
246 
247 void RTDyldObjectLinkingLayer::onObjEmit(
248     VModuleKey K, std::unique_ptr<MemoryBuffer> ObjBuffer,
249     MaterializationResponsibility &R, Error Err) {
250   if (Err) {
251     getExecutionSession().reportError(std::move(Err));
252     R.failMaterialization();
253     return;
254   }
255 
256   if (auto Err = R.notifyEmitted()) {
257     getExecutionSession().reportError(std::move(Err));
258     R.failMaterialization();
259     return;
260   }
261 
262   if (NotifyEmitted)
263     NotifyEmitted(K, std::move(ObjBuffer));
264 }
265 
266 LegacyRTDyldObjectLinkingLayer::LegacyRTDyldObjectLinkingLayer(
267     ExecutionSession &ES, ResourcesGetter GetResources,
268     NotifyLoadedFtor NotifyLoaded, NotifyFinalizedFtor NotifyFinalized,
269     NotifyFreedFtor NotifyFreed)
270     : ES(ES), GetResources(std::move(GetResources)),
271       NotifyLoaded(std::move(NotifyLoaded)),
272       NotifyFinalized(std::move(NotifyFinalized)),
273       NotifyFreed(std::move(NotifyFreed)), ProcessAllSections(false) {}
274 
275 } // End namespace orc.
276 } // End namespace llvm.
277