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:
19   JITDylibSearchOrderResolver(MaterializationResponsibility &MR) : MR(MR) {}
20 
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     MR.getTargetJITDylib().withSearchOrderDo([&](const JITDylibList &JDs) {
54       ES.lookup(JDs, InternedSymbols, OnResolvedWithUnwrap, OnReady,
55                 RegisterDependencies);
56     });
57   }
58 
59   Expected<LookupSet> getResponsibilitySet(const LookupSet &Symbols) {
60     LookupSet Result;
61 
62     for (auto &KV : MR.getSymbols()) {
63       if (Symbols.count(*KV.first))
64         Result.insert(*KV.first);
65     }
66 
67     return Result;
68   }
69 
70 private:
71   MaterializationResponsibility &MR;
72 };
73 
74 } // end anonymous namespace
75 
76 namespace llvm {
77 namespace orc {
78 
79 RTDyldObjectLinkingLayer2::RTDyldObjectLinkingLayer2(
80     ExecutionSession &ES, GetMemoryManagerFunction GetMemoryManager,
81     NotifyLoadedFunction NotifyLoaded, NotifyEmittedFunction NotifyEmitted)
82     : ObjectLayer(ES), GetMemoryManager(GetMemoryManager),
83       NotifyLoaded(std::move(NotifyLoaded)),
84       NotifyEmitted(std::move(NotifyEmitted)) {}
85 
86 void RTDyldObjectLinkingLayer2::emit(MaterializationResponsibility R,
87                                      VModuleKey K,
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 MemoryManager = GetMemoryManager(K);
125   auto &MemMgr = *MemoryManager;
126   {
127     std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
128 
129     assert(!MemMgrs.count(K) &&
130            "A memory manager already exists for this key?");
131     MemMgrs[K] = std::move(MemoryManager);
132   }
133 
134   JITDylibSearchOrderResolver Resolver(*SharedR);
135 
136   /* Thoughts on proper cross-dylib weak symbol handling:
137    *
138    * Change selection of canonical defs to be a manually triggered process, and
139    * add a 'canonical' bit to symbol definitions. When canonical def selection
140    * is triggered, sweep the JITDylibs to mark defs as canonical, discard
141    * duplicate defs.
142    */
143   jitLinkForORC(
144       **Obj, std::move(O), MemMgr, Resolver, ProcessAllSections,
145       [this, K, SharedR, &Obj, InternalSymbols](
146           std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
147           std::map<StringRef, JITEvaluatedSymbol> ResolvedSymbols) {
148         return onObjLoad(K, *SharedR, **Obj, std::move(LoadedObjInfo),
149                          ResolvedSymbols, *InternalSymbols);
150       },
151       [this, K, SharedR](Error Err) {
152         onObjEmit(K, *SharedR, std::move(Err));
153       });
154 }
155 
156 Error RTDyldObjectLinkingLayer2::onObjLoad(
157     VModuleKey K, MaterializationResponsibility &R, object::ObjectFile &Obj,
158     std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
159     std::map<StringRef, JITEvaluatedSymbol> Resolved,
160     std::set<StringRef> &InternalSymbols) {
161   SymbolFlagsMap ExtraSymbolsToClaim;
162   SymbolMap Symbols;
163   for (auto &KV : Resolved) {
164     // Scan the symbols and add them to the Symbols map for resolution.
165 
166     // We never claim internal symbols.
167     if (InternalSymbols.count(KV.first))
168       continue;
169 
170     auto InternedName = getExecutionSession().intern(KV.first);
171     auto Flags = KV.second.getFlags();
172 
173     // Override object flags and claim responsibility for symbols if
174     // requested.
175     if (OverrideObjectFlags || AutoClaimObjectSymbols) {
176       auto I = R.getSymbols().find(InternedName);
177 
178       if (OverrideObjectFlags && I != R.getSymbols().end())
179         Flags = JITSymbolFlags::stripTransientFlags(I->second);
180       else if (AutoClaimObjectSymbols && I == R.getSymbols().end())
181         ExtraSymbolsToClaim[InternedName] = Flags;
182     }
183 
184     Symbols[InternedName] = JITEvaluatedSymbol(KV.second.getAddress(), Flags);
185   }
186 
187   if (!ExtraSymbolsToClaim.empty())
188     if (auto Err = R.defineMaterializing(ExtraSymbolsToClaim))
189       return Err;
190 
191   R.resolve(Symbols);
192 
193   if (NotifyLoaded)
194     NotifyLoaded(K, Obj, *LoadedObjInfo);
195 
196   return Error::success();
197 }
198 
199 void RTDyldObjectLinkingLayer2::onObjEmit(VModuleKey K,
200                                           MaterializationResponsibility &R,
201                                           Error Err) {
202   if (Err) {
203     getExecutionSession().reportError(std::move(Err));
204     R.failMaterialization();
205     return;
206   }
207 
208   R.emit();
209 
210   if (NotifyEmitted)
211     NotifyEmitted(K);
212 }
213 
214 } // End namespace orc.
215 } // End namespace llvm.
216