RTDyldObjectLinkingLayer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
  9. #include "llvm/Object/COFF.h"
  10. namespace {
  11. using namespace llvm;
  12. using namespace llvm::orc;
  13. class JITDylibSearchOrderResolver : public JITSymbolResolver {
  14. public:
  15. JITDylibSearchOrderResolver(MaterializationResponsibility &MR) : MR(MR) {}
  16. void lookup(const LookupSet &Symbols, OnResolvedFunction OnResolved) override {
  17. auto &ES = MR.getTargetJITDylib().getExecutionSession();
  18. SymbolLookupSet InternedSymbols;
  19. // Intern the requested symbols: lookup takes interned strings.
  20. for (auto &S : Symbols)
  21. InternedSymbols.add(ES.intern(S));
  22. // Build an OnResolve callback to unwrap the interned strings and pass them
  23. // to the OnResolved callback.
  24. auto OnResolvedWithUnwrap =
  25. [OnResolved = std::move(OnResolved)](
  26. Expected<SymbolMap> InternedResult) mutable {
  27. if (!InternedResult) {
  28. OnResolved(InternedResult.takeError());
  29. return;
  30. }
  31. LookupResult Result;
  32. for (auto &KV : *InternedResult)
  33. Result[*KV.first] = std::move(KV.second);
  34. OnResolved(Result);
  35. };
  36. // Register dependencies for all symbols contained in this set.
  37. auto RegisterDependencies = [&](const SymbolDependenceMap &Deps) {
  38. MR.addDependenciesForAll(Deps);
  39. };
  40. JITDylibSearchOrder LinkOrder;
  41. MR.getTargetJITDylib().withLinkOrderDo(
  42. [&](const JITDylibSearchOrder &LO) { LinkOrder = LO; });
  43. ES.lookup(LookupKind::Static, LinkOrder, InternedSymbols,
  44. SymbolState::Resolved, std::move(OnResolvedWithUnwrap),
  45. RegisterDependencies);
  46. }
  47. Expected<LookupSet> getResponsibilitySet(const LookupSet &Symbols) override {
  48. LookupSet Result;
  49. for (auto &KV : MR.getSymbols()) {
  50. if (Symbols.count(*KV.first))
  51. Result.insert(*KV.first);
  52. }
  53. return Result;
  54. }
  55. private:
  56. MaterializationResponsibility &MR;
  57. };
  58. } // end anonymous namespace
  59. namespace llvm {
  60. namespace orc {
  61. char RTDyldObjectLinkingLayer::ID;
  62. using BaseT = RTTIExtends<RTDyldObjectLinkingLayer, ObjectLayer>;
  63. RTDyldObjectLinkingLayer::RTDyldObjectLinkingLayer(
  64. ExecutionSession &ES, GetMemoryManagerFunction GetMemoryManager)
  65. : BaseT(ES), GetMemoryManager(std::move(GetMemoryManager)) {
  66. ES.registerResourceManager(*this);
  67. }
  68. RTDyldObjectLinkingLayer::~RTDyldObjectLinkingLayer() {
  69. assert(MemMgrs.empty() && "Layer destroyed with resources still attached");
  70. }
  71. void RTDyldObjectLinkingLayer::emit(
  72. std::unique_ptr<MaterializationResponsibility> R,
  73. std::unique_ptr<MemoryBuffer> O) {
  74. assert(O && "Object must not be null");
  75. auto &ES = getExecutionSession();
  76. auto Obj = object::ObjectFile::createObjectFile(*O);
  77. if (!Obj) {
  78. getExecutionSession().reportError(Obj.takeError());
  79. R->failMaterialization();
  80. return;
  81. }
  82. // Collect the internal symbols from the object file: We will need to
  83. // filter these later.
  84. auto InternalSymbols = std::make_shared<std::set<StringRef>>();
  85. {
  86. SymbolFlagsMap ExtraSymbolsToClaim;
  87. for (auto &Sym : (*Obj)->symbols()) {
  88. // Skip file symbols.
  89. if (auto SymType = Sym.getType()) {
  90. if (*SymType == object::SymbolRef::ST_File)
  91. continue;
  92. } else {
  93. ES.reportError(SymType.takeError());
  94. R->failMaterialization();
  95. return;
  96. }
  97. Expected<uint32_t> SymFlagsOrErr = Sym.getFlags();
  98. if (!SymFlagsOrErr) {
  99. // TODO: Test this error.
  100. ES.reportError(SymFlagsOrErr.takeError());
  101. R->failMaterialization();
  102. return;
  103. }
  104. // Try to claim responsibility of weak symbols
  105. // if AutoClaimObjectSymbols flag is set.
  106. if (AutoClaimObjectSymbols &&
  107. (*SymFlagsOrErr & object::BasicSymbolRef::SF_Weak)) {
  108. auto SymName = Sym.getName();
  109. if (!SymName) {
  110. ES.reportError(SymName.takeError());
  111. R->failMaterialization();
  112. return;
  113. }
  114. // Already included in responsibility set, skip it
  115. SymbolStringPtr SymbolName = ES.intern(*SymName);
  116. if (R->getSymbols().count(SymbolName))
  117. continue;
  118. auto SymFlags = JITSymbolFlags::fromObjectSymbol(Sym);
  119. if (!SymFlags) {
  120. ES.reportError(SymFlags.takeError());
  121. R->failMaterialization();
  122. return;
  123. }
  124. ExtraSymbolsToClaim[SymbolName] = *SymFlags;
  125. continue;
  126. }
  127. // Don't include symbols that aren't global.
  128. if (!(*SymFlagsOrErr & object::BasicSymbolRef::SF_Global)) {
  129. if (auto SymName = Sym.getName())
  130. InternalSymbols->insert(*SymName);
  131. else {
  132. ES.reportError(SymName.takeError());
  133. R->failMaterialization();
  134. return;
  135. }
  136. }
  137. }
  138. if (!ExtraSymbolsToClaim.empty()) {
  139. if (auto Err = R->defineMaterializing(ExtraSymbolsToClaim)) {
  140. ES.reportError(std::move(Err));
  141. R->failMaterialization();
  142. }
  143. }
  144. }
  145. auto MemMgr = GetMemoryManager();
  146. auto &MemMgrRef = *MemMgr;
  147. // Switch to shared ownership of MR so that it can be captured by both
  148. // lambdas below.
  149. std::shared_ptr<MaterializationResponsibility> SharedR(std::move(R));
  150. JITDylibSearchOrderResolver Resolver(*SharedR);
  151. jitLinkForORC(
  152. object::OwningBinary<object::ObjectFile>(std::move(*Obj), std::move(O)),
  153. MemMgrRef, Resolver, ProcessAllSections,
  154. [this, SharedR, &MemMgrRef, InternalSymbols](
  155. const object::ObjectFile &Obj,
  156. RuntimeDyld::LoadedObjectInfo &LoadedObjInfo,
  157. std::map<StringRef, JITEvaluatedSymbol> ResolvedSymbols) {
  158. return onObjLoad(*SharedR, Obj, MemMgrRef, LoadedObjInfo,
  159. ResolvedSymbols, *InternalSymbols);
  160. },
  161. [this, SharedR, MemMgr = std::move(MemMgr)](
  162. object::OwningBinary<object::ObjectFile> Obj,
  163. std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
  164. Error Err) mutable {
  165. onObjEmit(*SharedR, std::move(Obj), std::move(MemMgr),
  166. std::move(LoadedObjInfo), std::move(Err));
  167. });
  168. }
  169. void RTDyldObjectLinkingLayer::registerJITEventListener(JITEventListener &L) {
  170. std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
  171. assert(!llvm::is_contained(EventListeners, &L) &&
  172. "Listener has already been registered");
  173. EventListeners.push_back(&L);
  174. }
  175. void RTDyldObjectLinkingLayer::unregisterJITEventListener(JITEventListener &L) {
  176. std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
  177. auto I = llvm::find(EventListeners, &L);
  178. assert(I != EventListeners.end() && "Listener not registered");
  179. EventListeners.erase(I);
  180. }
  181. Error RTDyldObjectLinkingLayer::onObjLoad(
  182. MaterializationResponsibility &R, const object::ObjectFile &Obj,
  183. RuntimeDyld::MemoryManager &MemMgr,
  184. RuntimeDyld::LoadedObjectInfo &LoadedObjInfo,
  185. std::map<StringRef, JITEvaluatedSymbol> Resolved,
  186. std::set<StringRef> &InternalSymbols) {
  187. SymbolFlagsMap ExtraSymbolsToClaim;
  188. SymbolMap Symbols;
  189. // Hack to support COFF constant pool comdats introduced during compilation:
  190. // (See http://llvm.org/PR40074)
  191. if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(&Obj)) {
  192. auto &ES = getExecutionSession();
  193. // For all resolved symbols that are not already in the responsibilty set:
  194. // check whether the symbol is in a comdat section and if so mark it as
  195. // weak.
  196. for (auto &Sym : COFFObj->symbols()) {
  197. // getFlags() on COFF symbols can't fail.
  198. uint32_t SymFlags = cantFail(Sym.getFlags());
  199. if (SymFlags & object::BasicSymbolRef::SF_Undefined)
  200. continue;
  201. auto Name = Sym.getName();
  202. if (!Name)
  203. return Name.takeError();
  204. auto I = Resolved.find(*Name);
  205. // Skip unresolved symbols, internal symbols, and symbols that are
  206. // already in the responsibility set.
  207. if (I == Resolved.end() || InternalSymbols.count(*Name) ||
  208. R.getSymbols().count(ES.intern(*Name)))
  209. continue;
  210. auto Sec = Sym.getSection();
  211. if (!Sec)
  212. return Sec.takeError();
  213. if (*Sec == COFFObj->section_end())
  214. continue;
  215. auto &COFFSec = *COFFObj->getCOFFSection(**Sec);
  216. if (COFFSec.Characteristics & COFF::IMAGE_SCN_LNK_COMDAT)
  217. I->second.setFlags(I->second.getFlags() | JITSymbolFlags::Weak);
  218. }
  219. // Handle any aliases.
  220. for (auto &Sym : COFFObj->symbols()) {
  221. uint32_t SymFlags = cantFail(Sym.getFlags());
  222. if (SymFlags & object::BasicSymbolRef::SF_Undefined)
  223. continue;
  224. auto Name = Sym.getName();
  225. if (!Name)
  226. return Name.takeError();
  227. auto I = Resolved.find(*Name);
  228. // Skip already-resolved symbols, and symbols that we're not responsible
  229. // for.
  230. if (I != Resolved.end() || !R.getSymbols().count(ES.intern(*Name)))
  231. continue;
  232. // Skip anything other than weak externals.
  233. auto COFFSym = COFFObj->getCOFFSymbol(Sym);
  234. if (!COFFSym.isWeakExternal())
  235. continue;
  236. auto *WeakExternal = COFFSym.getAux<object::coff_aux_weak_external>();
  237. if (WeakExternal->Characteristics != COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS)
  238. continue;
  239. // We found an alias. Reuse the resolution of the alias target for the
  240. // alias itself.
  241. Expected<object::COFFSymbolRef> TargetSymbol =
  242. COFFObj->getSymbol(WeakExternal->TagIndex);
  243. if (!TargetSymbol)
  244. return TargetSymbol.takeError();
  245. Expected<StringRef> TargetName = COFFObj->getSymbolName(*TargetSymbol);
  246. if (!TargetName)
  247. return TargetName.takeError();
  248. auto J = Resolved.find(*TargetName);
  249. if (J == Resolved.end())
  250. return make_error<StringError>("Could alias target " + *TargetName +
  251. " not resolved",
  252. inconvertibleErrorCode());
  253. Resolved[*Name] = J->second;
  254. }
  255. }
  256. for (auto &KV : Resolved) {
  257. // Scan the symbols and add them to the Symbols map for resolution.
  258. // We never claim internal symbols.
  259. if (InternalSymbols.count(KV.first))
  260. continue;
  261. auto InternedName = getExecutionSession().intern(KV.first);
  262. auto Flags = KV.second.getFlags();
  263. auto I = R.getSymbols().find(InternedName);
  264. if (I != R.getSymbols().end()) {
  265. // Override object flags and claim responsibility for symbols if
  266. // requested.
  267. if (OverrideObjectFlags)
  268. Flags = I->second;
  269. else {
  270. // RuntimeDyld/MCJIT's weak tracking isn't compatible with ORC's. Even
  271. // if we're not overriding flags in general we should set the weak flag
  272. // according to the MaterializationResponsibility object symbol table.
  273. if (I->second.isWeak())
  274. Flags |= JITSymbolFlags::Weak;
  275. }
  276. } else if (AutoClaimObjectSymbols)
  277. ExtraSymbolsToClaim[InternedName] = Flags;
  278. Symbols[InternedName] = JITEvaluatedSymbol(KV.second.getAddress(), Flags);
  279. }
  280. if (!ExtraSymbolsToClaim.empty()) {
  281. if (auto Err = R.defineMaterializing(ExtraSymbolsToClaim))
  282. return Err;
  283. // If we claimed responsibility for any weak symbols but were rejected then
  284. // we need to remove them from the resolved set.
  285. for (auto &KV : ExtraSymbolsToClaim)
  286. if (KV.second.isWeak() && !R.getSymbols().count(KV.first))
  287. Symbols.erase(KV.first);
  288. }
  289. if (auto Err = R.notifyResolved(Symbols)) {
  290. R.failMaterialization();
  291. return Err;
  292. }
  293. if (NotifyLoaded)
  294. NotifyLoaded(R, Obj, LoadedObjInfo);
  295. return Error::success();
  296. }
  297. void RTDyldObjectLinkingLayer::onObjEmit(
  298. MaterializationResponsibility &R,
  299. object::OwningBinary<object::ObjectFile> O,
  300. std::unique_ptr<RuntimeDyld::MemoryManager> MemMgr,
  301. std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo, Error Err) {
  302. if (Err) {
  303. getExecutionSession().reportError(std::move(Err));
  304. R.failMaterialization();
  305. return;
  306. }
  307. if (auto Err = R.notifyEmitted()) {
  308. getExecutionSession().reportError(std::move(Err));
  309. R.failMaterialization();
  310. return;
  311. }
  312. std::unique_ptr<object::ObjectFile> Obj;
  313. std::unique_ptr<MemoryBuffer> ObjBuffer;
  314. std::tie(Obj, ObjBuffer) = O.takeBinary();
  315. // Run EventListener notifyLoaded callbacks.
  316. {
  317. std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
  318. for (auto *L : EventListeners)
  319. L->notifyObjectLoaded(pointerToJITTargetAddress(MemMgr.get()), *Obj,
  320. *LoadedObjInfo);
  321. }
  322. if (NotifyEmitted)
  323. NotifyEmitted(R, std::move(ObjBuffer));
  324. if (auto Err = R.withResourceKeyDo(
  325. [&](ResourceKey K) { MemMgrs[K].push_back(std::move(MemMgr)); })) {
  326. getExecutionSession().reportError(std::move(Err));
  327. R.failMaterialization();
  328. }
  329. }
  330. Error RTDyldObjectLinkingLayer::handleRemoveResources(JITDylib &JD,
  331. ResourceKey K) {
  332. std::vector<MemoryManagerUP> MemMgrsToRemove;
  333. getExecutionSession().runSessionLocked([&] {
  334. auto I = MemMgrs.find(K);
  335. if (I != MemMgrs.end()) {
  336. std::swap(MemMgrsToRemove, I->second);
  337. MemMgrs.erase(I);
  338. }
  339. });
  340. {
  341. std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
  342. for (auto &MemMgr : MemMgrsToRemove) {
  343. for (auto *L : EventListeners)
  344. L->notifyFreeingObject(pointerToJITTargetAddress(MemMgr.get()));
  345. MemMgr->deregisterEHFrames();
  346. }
  347. }
  348. return Error::success();
  349. }
  350. void RTDyldObjectLinkingLayer::handleTransferResources(JITDylib &JD,
  351. ResourceKey DstKey,
  352. ResourceKey SrcKey) {
  353. auto I = MemMgrs.find(SrcKey);
  354. if (I != MemMgrs.end()) {
  355. auto &SrcMemMgrs = I->second;
  356. auto &DstMemMgrs = MemMgrs[DstKey];
  357. DstMemMgrs.reserve(DstMemMgrs.size() + SrcMemMgrs.size());
  358. for (auto &MemMgr : SrcMemMgrs)
  359. DstMemMgrs.push_back(std::move(MemMgr));
  360. // Erase SrcKey entry using value rather than iterator I: I may have been
  361. // invalidated when we looked up DstKey.
  362. MemMgrs.erase(SrcKey);
  363. }
  364. }
  365. } // End namespace orc.
  366. } // End namespace llvm.