SimpleExecutorMemoryManager.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. //===- SimpleExecuorMemoryManagare.cpp - Simple executor-side memory mgmt -===//
  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/TargetProcess/SimpleExecutorMemoryManager.h"
  9. #include "llvm/ExecutionEngine/Orc/Shared/OrcRTBridge.h"
  10. #include "llvm/Support/FormatVariadic.h"
  11. #define DEBUG_TYPE "orc"
  12. namespace llvm {
  13. namespace orc {
  14. namespace rt_bootstrap {
  15. SimpleExecutorMemoryManager::~SimpleExecutorMemoryManager() {
  16. assert(Allocations.empty() && "shutdown not called?");
  17. }
  18. Expected<ExecutorAddr> SimpleExecutorMemoryManager::allocate(uint64_t Size) {
  19. std::error_code EC;
  20. auto MB = sys::Memory::allocateMappedMemory(
  21. Size, nullptr, sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC);
  22. if (EC)
  23. return errorCodeToError(EC);
  24. std::lock_guard<std::mutex> Lock(M);
  25. assert(!Allocations.count(MB.base()) && "Duplicate allocation addr");
  26. Allocations[MB.base()].Size = Size;
  27. return ExecutorAddr::fromPtr(MB.base());
  28. }
  29. Error SimpleExecutorMemoryManager::finalize(tpctypes::FinalizeRequest &FR) {
  30. ExecutorAddr Base(~0ULL);
  31. std::vector<shared::WrapperFunctionCall> DeallocationActions;
  32. size_t SuccessfulFinalizationActions = 0;
  33. if (FR.Segments.empty()) {
  34. // NOTE: Finalizing nothing is currently a no-op. Should it be an error?
  35. if (FR.Actions.empty())
  36. return Error::success();
  37. else
  38. return make_error<StringError>("Finalization actions attached to empty "
  39. "finalization request",
  40. inconvertibleErrorCode());
  41. }
  42. for (auto &Seg : FR.Segments)
  43. Base = std::min(Base, Seg.Addr);
  44. for (auto &ActPair : FR.Actions)
  45. if (ActPair.Dealloc)
  46. DeallocationActions.push_back(ActPair.Dealloc);
  47. // Get the Allocation for this finalization.
  48. size_t AllocSize = 0;
  49. {
  50. std::lock_guard<std::mutex> Lock(M);
  51. auto I = Allocations.find(Base.toPtr<void *>());
  52. if (I == Allocations.end())
  53. return make_error<StringError>("Attempt to finalize unrecognized "
  54. "allocation " +
  55. formatv("{0:x}", Base.getValue()),
  56. inconvertibleErrorCode());
  57. AllocSize = I->second.Size;
  58. I->second.DeallocationActions = std::move(DeallocationActions);
  59. }
  60. ExecutorAddr AllocEnd = Base + ExecutorAddrDiff(AllocSize);
  61. // Bail-out function: this will run deallocation actions corresponding to any
  62. // completed finalization actions, then deallocate memory.
  63. auto BailOut = [&](Error Err) {
  64. std::pair<void *, Allocation> AllocToDestroy;
  65. // Get allocation to destory.
  66. {
  67. std::lock_guard<std::mutex> Lock(M);
  68. auto I = Allocations.find(Base.toPtr<void *>());
  69. // Check for missing allocation (effective a double free).
  70. if (I == Allocations.end())
  71. return joinErrors(
  72. std::move(Err),
  73. make_error<StringError>("No allocation entry found "
  74. "for " +
  75. formatv("{0:x}", Base.getValue()),
  76. inconvertibleErrorCode()));
  77. AllocToDestroy = std::move(*I);
  78. Allocations.erase(I);
  79. }
  80. // Run deallocation actions for all completed finalization actions.
  81. while (SuccessfulFinalizationActions)
  82. Err =
  83. joinErrors(std::move(Err), FR.Actions[--SuccessfulFinalizationActions]
  84. .Dealloc.runWithSPSRetErrorMerged());
  85. // Deallocate memory.
  86. sys::MemoryBlock MB(AllocToDestroy.first, AllocToDestroy.second.Size);
  87. if (auto EC = sys::Memory::releaseMappedMemory(MB))
  88. Err = joinErrors(std::move(Err), errorCodeToError(EC));
  89. return Err;
  90. };
  91. // Copy content and apply permissions.
  92. for (auto &Seg : FR.Segments) {
  93. // Check segment ranges.
  94. if (LLVM_UNLIKELY(Seg.Size < Seg.Content.size()))
  95. return BailOut(make_error<StringError>(
  96. formatv("Segment {0:x} content size ({1:x} bytes) "
  97. "exceeds segment size ({2:x} bytes)",
  98. Seg.Addr.getValue(), Seg.Content.size(), Seg.Size),
  99. inconvertibleErrorCode()));
  100. ExecutorAddr SegEnd = Seg.Addr + ExecutorAddrDiff(Seg.Size);
  101. if (LLVM_UNLIKELY(Seg.Addr < Base || SegEnd > AllocEnd))
  102. return BailOut(make_error<StringError>(
  103. formatv("Segment {0:x} -- {1:x} crosses boundary of "
  104. "allocation {2:x} -- {3:x}",
  105. Seg.Addr.getValue(), SegEnd.getValue(), Base.getValue(),
  106. AllocEnd.getValue()),
  107. inconvertibleErrorCode()));
  108. char *Mem = Seg.Addr.toPtr<char *>();
  109. memcpy(Mem, Seg.Content.data(), Seg.Content.size());
  110. memset(Mem + Seg.Content.size(), 0, Seg.Size - Seg.Content.size());
  111. assert(Seg.Size <= std::numeric_limits<size_t>::max());
  112. if (auto EC = sys::Memory::protectMappedMemory(
  113. {Mem, static_cast<size_t>(Seg.Size)},
  114. tpctypes::fromWireProtectionFlags(Seg.Prot)))
  115. return BailOut(errorCodeToError(EC));
  116. if (Seg.Prot & tpctypes::WPF_Exec)
  117. sys::Memory::InvalidateInstructionCache(Mem, Seg.Size);
  118. }
  119. // Run finalization actions.
  120. for (auto &ActPair : FR.Actions) {
  121. if (auto Err = ActPair.Finalize.runWithSPSRetErrorMerged())
  122. return BailOut(std::move(Err));
  123. ++SuccessfulFinalizationActions;
  124. }
  125. return Error::success();
  126. }
  127. Error SimpleExecutorMemoryManager::deallocate(
  128. const std::vector<ExecutorAddr> &Bases) {
  129. std::vector<std::pair<void *, Allocation>> AllocPairs;
  130. AllocPairs.reserve(Bases.size());
  131. // Get allocation to destory.
  132. Error Err = Error::success();
  133. {
  134. std::lock_guard<std::mutex> Lock(M);
  135. for (auto &Base : Bases) {
  136. auto I = Allocations.find(Base.toPtr<void *>());
  137. // Check for missing allocation (effective a double free).
  138. if (I != Allocations.end()) {
  139. AllocPairs.push_back(std::move(*I));
  140. Allocations.erase(I);
  141. } else
  142. Err = joinErrors(
  143. std::move(Err),
  144. make_error<StringError>("No allocation entry found "
  145. "for " +
  146. formatv("{0:x}", Base.getValue()),
  147. inconvertibleErrorCode()));
  148. }
  149. }
  150. while (!AllocPairs.empty()) {
  151. auto &P = AllocPairs.back();
  152. Err = joinErrors(std::move(Err), deallocateImpl(P.first, P.second));
  153. AllocPairs.pop_back();
  154. }
  155. return Err;
  156. }
  157. Error SimpleExecutorMemoryManager::shutdown() {
  158. AllocationsMap AM;
  159. {
  160. std::lock_guard<std::mutex> Lock(M);
  161. AM = std::move(Allocations);
  162. }
  163. Error Err = Error::success();
  164. for (auto &KV : AM)
  165. Err = joinErrors(std::move(Err), deallocateImpl(KV.first, KV.second));
  166. return Err;
  167. }
  168. void SimpleExecutorMemoryManager::addBootstrapSymbols(
  169. StringMap<ExecutorAddr> &M) {
  170. M[rt::SimpleExecutorMemoryManagerInstanceName] = ExecutorAddr::fromPtr(this);
  171. M[rt::SimpleExecutorMemoryManagerReserveWrapperName] =
  172. ExecutorAddr::fromPtr(&reserveWrapper);
  173. M[rt::SimpleExecutorMemoryManagerFinalizeWrapperName] =
  174. ExecutorAddr::fromPtr(&finalizeWrapper);
  175. M[rt::SimpleExecutorMemoryManagerDeallocateWrapperName] =
  176. ExecutorAddr::fromPtr(&deallocateWrapper);
  177. }
  178. Error SimpleExecutorMemoryManager::deallocateImpl(void *Base, Allocation &A) {
  179. Error Err = Error::success();
  180. while (!A.DeallocationActions.empty()) {
  181. Err = joinErrors(std::move(Err),
  182. A.DeallocationActions.back().runWithSPSRetErrorMerged());
  183. A.DeallocationActions.pop_back();
  184. }
  185. sys::MemoryBlock MB(Base, A.Size);
  186. if (auto EC = sys::Memory::releaseMappedMemory(MB))
  187. Err = joinErrors(std::move(Err), errorCodeToError(EC));
  188. return Err;
  189. }
  190. llvm::orc::shared::CWrapperFunctionResult
  191. SimpleExecutorMemoryManager::reserveWrapper(const char *ArgData,
  192. size_t ArgSize) {
  193. return shared::WrapperFunction<
  194. rt::SPSSimpleExecutorMemoryManagerReserveSignature>::
  195. handle(ArgData, ArgSize,
  196. shared::makeMethodWrapperHandler(
  197. &SimpleExecutorMemoryManager::allocate))
  198. .release();
  199. }
  200. llvm::orc::shared::CWrapperFunctionResult
  201. SimpleExecutorMemoryManager::finalizeWrapper(const char *ArgData,
  202. size_t ArgSize) {
  203. return shared::WrapperFunction<
  204. rt::SPSSimpleExecutorMemoryManagerFinalizeSignature>::
  205. handle(ArgData, ArgSize,
  206. shared::makeMethodWrapperHandler(
  207. &SimpleExecutorMemoryManager::finalize))
  208. .release();
  209. }
  210. llvm::orc::shared::CWrapperFunctionResult
  211. SimpleExecutorMemoryManager::deallocateWrapper(const char *ArgData,
  212. size_t ArgSize) {
  213. return shared::WrapperFunction<
  214. rt::SPSSimpleExecutorMemoryManagerDeallocateSignature>::
  215. handle(ArgData, ArgSize,
  216. shared::makeMethodWrapperHandler(
  217. &SimpleExecutorMemoryManager::deallocate))
  218. .release();
  219. }
  220. } // namespace rt_bootstrap
  221. } // end namespace orc
  222. } // end namespace llvm