1 //===-- RTDyldObjectLinkingLayer.cpp - RuntimeDyld backed ORC ObjectLayer -===//
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 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
11
12 namespace {
13
14 using namespace llvm;
15 using namespace llvm::orc;
16
17 class JITDylibSearchOrderResolver : public JITSymbolResolver {
18 public:
JITDylibSearchOrderResolver(MaterializationResponsibility & MR)19 JITDylibSearchOrderResolver(MaterializationResponsibility &MR) : MR(MR) {}
20
lookup(const LookupSet & Symbols,OnResolvedFunction OnResolved)21 void lookup(const LookupSet &Symbols, OnResolvedFunction OnResolved) {
22 auto &ES = MR.getTargetJITDylib().getExecutionSession();
23 SymbolNameSet InternedSymbols;
24
25 // Intern the requested symbols: lookup takes interned strings.
26 for (auto &S : Symbols)
27 InternedSymbols.insert(ES.intern(S));
28
29 // Build an OnResolve callback to unwrap the interned strings and pass them
30 // to the OnResolved callback.
31 // FIXME: Switch to move capture of OnResolved once we have c++14.
32 auto OnResolvedWithUnwrap =
33 [OnResolved](Expected<SymbolMap> InternedResult) {
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 // We're not waiting for symbols to be ready. Just log any errors.
46 auto OnReady = [&ES](Error Err) { ES.reportError(std::move(Err)); };
47
48 // Register dependencies for all symbols contained in this set.
49 auto RegisterDependencies = [&](const SymbolDependenceMap &Deps) {
50 MR.addDependenciesForAll(Deps);
51 };
52
53 JITDylibSearchList SearchOrder;
54 MR.getTargetJITDylib().withSearchOrderDo(
55 [&](const JITDylibSearchList &JDs) { SearchOrder = JDs; });
56 ES.lookup(SearchOrder, InternedSymbols, OnResolvedWithUnwrap, OnReady,
57 RegisterDependencies);
58 }
59
getResponsibilitySet(const LookupSet & Symbols)60 Expected<LookupSet> getResponsibilitySet(const LookupSet &Symbols) {
61 LookupSet Result;
62
63 for (auto &KV : MR.getSymbols()) {
64 if (Symbols.count(*KV.first))
65 Result.insert(*KV.first);
66 }
67
68 return Result;
69 }
70
71 private:
72 MaterializationResponsibility &MR;
73 };
74
75 } // end anonymous namespace
76
77 namespace llvm {
78 namespace orc {
79
RTDyldObjectLinkingLayer(ExecutionSession & ES,GetMemoryManagerFunction GetMemoryManager,NotifyLoadedFunction NotifyLoaded,NotifyEmittedFunction NotifyEmitted)80 RTDyldObjectLinkingLayer::RTDyldObjectLinkingLayer(
81 ExecutionSession &ES, GetMemoryManagerFunction GetMemoryManager,
82 NotifyLoadedFunction NotifyLoaded, NotifyEmittedFunction NotifyEmitted)
83 : ObjectLayer(ES), GetMemoryManager(GetMemoryManager),
84 NotifyLoaded(std::move(NotifyLoaded)),
85 NotifyEmitted(std::move(NotifyEmitted)) {}
86
emit(MaterializationResponsibility R,std::unique_ptr<MemoryBuffer> O)87 void RTDyldObjectLinkingLayer::emit(MaterializationResponsibility R,
88 std::unique_ptr<MemoryBuffer> O) {
89 assert(O && "Object must not be null");
90
91 // This method launches an asynchronous link step that will fulfill our
92 // materialization responsibility. We need to switch R to be heap
93 // allocated before that happens so it can live as long as the asynchronous
94 // link needs it to (i.e. it must be able to outlive this method).
95 auto SharedR = std::make_shared<MaterializationResponsibility>(std::move(R));
96
97 auto &ES = getExecutionSession();
98
99 auto Obj = object::ObjectFile::createObjectFile(*O);
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 /* Thoughts on proper cross-dylib weak symbol handling:
138 *
139 * Change selection of canonical defs to be a manually triggered process, and
140 * add a 'canonical' bit to symbol definitions. When canonical def selection
141 * is triggered, sweep the JITDylibs to mark defs as canonical, discard
142 * duplicate defs.
143 */
144 jitLinkForORC(
145 **Obj, std::move(O), *MemMgr, Resolver, ProcessAllSections,
146 [this, K, SharedR, &Obj, InternalSymbols](
147 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
148 std::map<StringRef, JITEvaluatedSymbol> ResolvedSymbols) {
149 return onObjLoad(K, *SharedR, **Obj, std::move(LoadedObjInfo),
150 ResolvedSymbols, *InternalSymbols);
151 },
152 [this, K, SharedR](Error Err) {
153 onObjEmit(K, *SharedR, std::move(Err));
154 });
155 }
156
onObjLoad(VModuleKey K,MaterializationResponsibility & R,object::ObjectFile & Obj,std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,std::map<StringRef,JITEvaluatedSymbol> Resolved,std::set<StringRef> & InternalSymbols)157 Error RTDyldObjectLinkingLayer::onObjLoad(
158 VModuleKey K, MaterializationResponsibility &R, object::ObjectFile &Obj,
159 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
160 std::map<StringRef, JITEvaluatedSymbol> Resolved,
161 std::set<StringRef> &InternalSymbols) {
162 SymbolFlagsMap ExtraSymbolsToClaim;
163 SymbolMap Symbols;
164 for (auto &KV : Resolved) {
165 // Scan the symbols and add them to the Symbols map for resolution.
166
167 // We never claim internal symbols.
168 if (InternalSymbols.count(KV.first))
169 continue;
170
171 auto InternedName = getExecutionSession().intern(KV.first);
172 auto Flags = KV.second.getFlags();
173
174 // Override object flags and claim responsibility for symbols if
175 // requested.
176 if (OverrideObjectFlags || AutoClaimObjectSymbols) {
177 auto I = R.getSymbols().find(InternedName);
178
179 if (OverrideObjectFlags && I != R.getSymbols().end())
180 Flags = JITSymbolFlags::stripTransientFlags(I->second);
181 else if (AutoClaimObjectSymbols && I == R.getSymbols().end())
182 ExtraSymbolsToClaim[InternedName] = Flags;
183 }
184
185 Symbols[InternedName] = JITEvaluatedSymbol(KV.second.getAddress(), Flags);
186 }
187
188 if (!ExtraSymbolsToClaim.empty())
189 if (auto Err = R.defineMaterializing(ExtraSymbolsToClaim))
190 return Err;
191
192 R.resolve(Symbols);
193
194 if (NotifyLoaded)
195 NotifyLoaded(K, Obj, *LoadedObjInfo);
196
197 return Error::success();
198 }
199
onObjEmit(VModuleKey K,MaterializationResponsibility & R,Error Err)200 void RTDyldObjectLinkingLayer::onObjEmit(VModuleKey K,
201 MaterializationResponsibility &R,
202 Error Err) {
203 if (Err) {
204 getExecutionSession().reportError(std::move(Err));
205 R.failMaterialization();
206 return;
207 }
208
209 R.emit();
210
211 if (NotifyEmitted)
212 NotifyEmitted(K);
213 }
214
215 } // End namespace orc.
216 } // End namespace llvm.
217