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   Expected<LookupResult> lookup(const LookupSet &Symbols) {
22     auto &ES = MR.getTargetJITDylib().getExecutionSession();
23     SymbolNameSet InternedSymbols;
24 
25     for (auto &S : Symbols)
26       InternedSymbols.insert(ES.getSymbolStringPool().intern(S));
27 
28     auto RegisterDependencies = [&](const SymbolDependenceMap &Deps) {
29       MR.addDependenciesForAll(Deps);
30     };
31 
32     auto InternedResult =
33         MR.getTargetJITDylib().withSearchOrderDo([&](const JITDylibList &JDs) {
34           return ES.lookup(JDs, InternedSymbols, RegisterDependencies, false);
35         });
36 
37     if (!InternedResult)
38       return InternedResult.takeError();
39 
40     LookupResult Result;
41     for (auto &KV : *InternedResult)
42       Result[*KV.first] = std::move(KV.second);
43 
44     return Result;
45   }
46 
47   Expected<LookupSet> getResponsibilitySet(const LookupSet &Symbols) {
48     LookupSet Result;
49 
50     for (auto &KV : MR.getSymbols()) {
51       if (Symbols.count(*KV.first))
52         Result.insert(*KV.first);
53     }
54 
55     return Result;
56   }
57 
58 private:
59   MaterializationResponsibility &MR;
60 };
61 
62 } // end anonymous namespace
63 
64 namespace llvm {
65 namespace orc {
66 
67 RTDyldObjectLinkingLayer2::RTDyldObjectLinkingLayer2(
68     ExecutionSession &ES, GetMemoryManagerFunction GetMemoryManager,
69     NotifyLoadedFunction NotifyLoaded, NotifyEmittedFunction NotifyEmitted)
70     : ObjectLayer(ES), GetMemoryManager(GetMemoryManager),
71       NotifyLoaded(std::move(NotifyLoaded)),
72       NotifyEmitted(std::move(NotifyEmitted)) {}
73 
74 void RTDyldObjectLinkingLayer2::emit(MaterializationResponsibility R,
75                                      VModuleKey K,
76                                      std::unique_ptr<MemoryBuffer> O) {
77   assert(O && "Object must not be null");
78 
79   auto &ES = getExecutionSession();
80 
81   auto ObjFile = object::ObjectFile::createObjectFile(*O);
82   if (!ObjFile) {
83     getExecutionSession().reportError(ObjFile.takeError());
84     R.failMaterialization();
85   }
86 
87   auto MemoryManager = GetMemoryManager(K);
88 
89   JITDylibSearchOrderResolver Resolver(R);
90   auto RTDyld = llvm::make_unique<RuntimeDyld>(*MemoryManager, Resolver);
91   RTDyld->setProcessAllSections(ProcessAllSections);
92 
93   {
94     std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
95 
96     assert(!MemMgrs.count(K) &&
97            "A memory manager already exists for this key?");
98     MemMgrs[K] = std::move(MemoryManager);
99   }
100 
101   auto Info = RTDyld->loadObject(**ObjFile);
102 
103   {
104     std::set<StringRef> InternalSymbols;
105     for (auto &Sym : (*ObjFile)->symbols()) {
106       if (!(Sym.getFlags() & object::BasicSymbolRef::SF_Global)) {
107         if (auto SymName = Sym.getName())
108           InternalSymbols.insert(*SymName);
109         else {
110           ES.reportError(SymName.takeError());
111           R.failMaterialization();
112           return;
113         }
114       }
115     }
116 
117     SymbolFlagsMap ExtraSymbolsToClaim;
118     SymbolMap Symbols;
119     for (auto &KV : RTDyld->getSymbolTable()) {
120       // Scan the symbols and add them to the Symbols map for resolution.
121 
122       // We never claim internal symbols.
123       if (InternalSymbols.count(KV.first))
124         continue;
125 
126       auto InternedName = ES.getSymbolStringPool().intern(KV.first);
127       auto Flags = KV.second.getFlags();
128 
129       // Override object flags and claim responsibility for symbols if
130       // requested.
131       if (OverrideObjectFlags || AutoClaimObjectSymbols) {
132         auto I = R.getSymbols().find(InternedName);
133 
134         if (OverrideObjectFlags && I != R.getSymbols().end())
135           Flags = JITSymbolFlags::stripTransientFlags(I->second);
136         else if (AutoClaimObjectSymbols && I == R.getSymbols().end())
137           ExtraSymbolsToClaim[InternedName] = Flags;
138       }
139 
140       Symbols[InternedName] = JITEvaluatedSymbol(KV.second.getAddress(), Flags);
141     }
142 
143     if (!ExtraSymbolsToClaim.empty())
144       if (auto Err = R.defineMaterializing(ExtraSymbolsToClaim)) {
145         ES.reportError(std::move(Err));
146         R.failMaterialization();
147         return;
148       }
149 
150     R.resolve(Symbols);
151   }
152 
153   if (NotifyLoaded)
154     NotifyLoaded(K, **ObjFile, *Info);
155 
156   RTDyld->finalizeWithMemoryManagerLocking();
157 
158   if (RTDyld->hasError()) {
159     ES.reportError(make_error<StringError>(RTDyld->getErrorString(),
160                                            inconvertibleErrorCode()));
161     R.failMaterialization();
162     return;
163   }
164 
165   R.emit();
166 
167   if (NotifyEmitted)
168     NotifyEmitted(K);
169 }
170 
171 } // End namespace orc.
172 } // End namespace llvm.
173