MemoryBlock.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Threading;
  4. namespace Ryujinx.Memory
  5. {
  6. /// <summary>
  7. /// Represents a block of contiguous physical guest memory.
  8. /// </summary>
  9. public sealed class MemoryBlock : IWritableBlock, IDisposable
  10. {
  11. private readonly bool _usesSharedMemory;
  12. private readonly bool _isMirror;
  13. private readonly bool _viewCompatible;
  14. private readonly bool _forJit;
  15. private IntPtr _sharedMemory;
  16. private IntPtr _pointer;
  17. /// <summary>
  18. /// Pointer to the memory block data.
  19. /// </summary>
  20. public IntPtr Pointer => _pointer;
  21. /// <summary>
  22. /// Size of the memory block.
  23. /// </summary>
  24. public ulong Size { get; }
  25. /// <summary>
  26. /// Creates a new instance of the memory block class.
  27. /// </summary>
  28. /// <param name="size">Size of the memory block in bytes</param>
  29. /// <param name="flags">Flags that controls memory block memory allocation</param>
  30. /// <exception cref="SystemException">Throw when there's an error while allocating the requested size</exception>
  31. /// <exception cref="PlatformNotSupportedException">Throw when the current platform is not supported</exception>
  32. public MemoryBlock(ulong size, MemoryAllocationFlags flags = MemoryAllocationFlags.None)
  33. {
  34. if (flags.HasFlag(MemoryAllocationFlags.Mirrorable))
  35. {
  36. _sharedMemory = MemoryManagement.CreateSharedMemory(size, flags.HasFlag(MemoryAllocationFlags.Reserve));
  37. if (!flags.HasFlag(MemoryAllocationFlags.NoMap))
  38. {
  39. _pointer = MemoryManagement.MapSharedMemory(_sharedMemory, size);
  40. }
  41. _usesSharedMemory = true;
  42. }
  43. else if (flags.HasFlag(MemoryAllocationFlags.Reserve))
  44. {
  45. _viewCompatible = flags.HasFlag(MemoryAllocationFlags.ViewCompatible);
  46. _forJit = flags.HasFlag(MemoryAllocationFlags.Jit);
  47. _pointer = MemoryManagement.Reserve(size, _forJit, _viewCompatible);
  48. }
  49. else
  50. {
  51. _forJit = flags.HasFlag(MemoryAllocationFlags.Jit);
  52. _pointer = MemoryManagement.Allocate(size, _forJit);
  53. }
  54. Size = size;
  55. }
  56. /// <summary>
  57. /// Creates a new instance of the memory block class, with a existing backing storage.
  58. /// </summary>
  59. /// <param name="size">Size of the memory block in bytes</param>
  60. /// <param name="sharedMemory">Shared memory to use as backing storage for this block</param>
  61. /// <exception cref="SystemException">Throw when there's an error while mapping the shared memory</exception>
  62. /// <exception cref="PlatformNotSupportedException">Throw when the current platform is not supported</exception>
  63. private MemoryBlock(ulong size, IntPtr sharedMemory)
  64. {
  65. _pointer = MemoryManagement.MapSharedMemory(sharedMemory, size);
  66. Size = size;
  67. _usesSharedMemory = true;
  68. _isMirror = true;
  69. }
  70. /// <summary>
  71. /// Creates a memory block that shares the backing storage with this block.
  72. /// The memory and page commitments will be shared, however memory protections are separate.
  73. /// </summary>
  74. /// <returns>A new memory block that shares storage with this one</returns>
  75. /// <exception cref="NotSupportedException">Throw when the current memory block does not support mirroring</exception>
  76. /// <exception cref="SystemException">Throw when there's an error while mapping the shared memory</exception>
  77. /// <exception cref="PlatformNotSupportedException">Throw when the current platform is not supported</exception>
  78. public MemoryBlock CreateMirror()
  79. {
  80. if (_sharedMemory == IntPtr.Zero)
  81. {
  82. throw new NotSupportedException("Mirroring is not supported on the memory block because the Mirrorable flag was not set.");
  83. }
  84. return new MemoryBlock(Size, _sharedMemory);
  85. }
  86. /// <summary>
  87. /// Commits a region of memory that has previously been reserved.
  88. /// This can be used to allocate memory on demand.
  89. /// </summary>
  90. /// <param name="offset">Starting offset of the range to be committed</param>
  91. /// <param name="size">Size of the range to be committed</param>
  92. /// <exception cref="SystemException">Throw when the operation was not successful</exception>
  93. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  94. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  95. public void Commit(ulong offset, ulong size)
  96. {
  97. MemoryManagement.Commit(GetPointerInternal(offset, size), size, _forJit);
  98. }
  99. /// <summary>
  100. /// Decommits a region of memory that has previously been reserved and optionally comitted.
  101. /// This can be used to free previously allocated memory on demand.
  102. /// </summary>
  103. /// <param name="offset">Starting offset of the range to be decommitted</param>
  104. /// <param name="size">Size of the range to be decommitted</param>
  105. /// <exception cref="SystemException">Throw when the operation was not successful</exception>
  106. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  107. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  108. public void Decommit(ulong offset, ulong size)
  109. {
  110. MemoryManagement.Decommit(GetPointerInternal(offset, size), size);
  111. }
  112. /// <summary>
  113. /// Maps a view of memory from another memory block.
  114. /// </summary>
  115. /// <param name="srcBlock">Memory block from where the backing memory will be taken</param>
  116. /// <param name="srcOffset">Offset on <paramref name="srcBlock"/> of the region that should be mapped</param>
  117. /// <param name="dstOffset">Offset to map the view into on this block</param>
  118. /// <param name="size">Size of the range to be mapped</param>
  119. /// <exception cref="NotSupportedException">Throw when the source memory block does not support mirroring</exception>
  120. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  121. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  122. public void MapView(MemoryBlock srcBlock, ulong srcOffset, ulong dstOffset, ulong size)
  123. {
  124. if (srcBlock._sharedMemory == IntPtr.Zero)
  125. {
  126. throw new ArgumentException("The source memory block is not mirrorable, and thus cannot be mapped on the current block.");
  127. }
  128. MemoryManagement.MapView(srcBlock._sharedMemory, srcOffset, GetPointerInternal(dstOffset, size), size, this);
  129. }
  130. /// <summary>
  131. /// Unmaps a view of memory from another memory block.
  132. /// </summary>
  133. /// <param name="srcBlock">Memory block from where the backing memory was taken during map</param>
  134. /// <param name="offset">Offset of the view previously mapped with <see cref="MapView"/></param>
  135. /// <param name="size">Size of the range to be unmapped</param>
  136. public void UnmapView(MemoryBlock srcBlock, ulong offset, ulong size)
  137. {
  138. MemoryManagement.UnmapView(srcBlock._sharedMemory, GetPointerInternal(offset, size), size, this);
  139. }
  140. /// <summary>
  141. /// Reprotects a region of memory.
  142. /// </summary>
  143. /// <param name="offset">Starting offset of the range to be reprotected</param>
  144. /// <param name="size">Size of the range to be reprotected</param>
  145. /// <param name="permission">New memory permissions</param>
  146. /// <param name="throwOnFail">True if a failed reprotect should throw</param>
  147. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  148. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  149. /// <exception cref="MemoryProtectionException">Throw when <paramref name="permission"/> is invalid</exception>
  150. public void Reprotect(ulong offset, ulong size, MemoryPermission permission, bool throwOnFail = true)
  151. {
  152. MemoryManagement.Reprotect(GetPointerInternal(offset, size), size, permission, _viewCompatible, throwOnFail);
  153. }
  154. /// <summary>
  155. /// Reads bytes from the memory block.
  156. /// </summary>
  157. /// <param name="offset">Starting offset of the range being read</param>
  158. /// <param name="data">Span where the bytes being read will be copied to</param>
  159. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  160. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified for the data is out of range</exception>
  161. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  162. public void Read(ulong offset, Span<byte> data)
  163. {
  164. GetSpan(offset, data.Length).CopyTo(data);
  165. }
  166. /// <summary>
  167. /// Reads data from the memory block.
  168. /// </summary>
  169. /// <typeparam name="T">Type of the data</typeparam>
  170. /// <param name="offset">Offset where the data is located</param>
  171. /// <returns>Data at the specified address</returns>
  172. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  173. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified for the data is out of range</exception>
  174. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  175. public T Read<T>(ulong offset) where T : unmanaged
  176. {
  177. return GetRef<T>(offset);
  178. }
  179. /// <summary>
  180. /// Writes bytes to the memory block.
  181. /// </summary>
  182. /// <param name="offset">Starting offset of the range being written</param>
  183. /// <param name="data">Span where the bytes being written will be copied from</param>
  184. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  185. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified for the data is out of range</exception>
  186. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  187. public void Write(ulong offset, ReadOnlySpan<byte> data)
  188. {
  189. data.CopyTo(GetSpan(offset, data.Length));
  190. }
  191. /// <summary>
  192. /// Writes data to the memory block.
  193. /// </summary>
  194. /// <typeparam name="T">Type of the data being written</typeparam>
  195. /// <param name="offset">Offset to write the data into</param>
  196. /// <param name="data">Data to be written</param>
  197. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  198. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified for the data is out of range</exception>
  199. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  200. public void Write<T>(ulong offset, T data) where T : unmanaged
  201. {
  202. GetRef<T>(offset) = data;
  203. }
  204. /// <summary>
  205. /// Copies data from one memory location to another.
  206. /// </summary>
  207. /// <param name="dstOffset">Destination offset to write the data into</param>
  208. /// <param name="srcOffset">Source offset to read the data from</param>
  209. /// <param name="size">Size of the copy in bytes</param>
  210. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  211. /// <exception cref="InvalidMemoryRegionException">Throw when <paramref name="srcOffset"/>, <paramref name="dstOffset"/> or <paramref name="size"/> is out of range</exception>
  212. public void Copy(ulong dstOffset, ulong srcOffset, ulong size)
  213. {
  214. const int MaxChunkSize = 1 << 24;
  215. for (ulong offset = 0; offset < size; offset += MaxChunkSize)
  216. {
  217. int copySize = (int)Math.Min(MaxChunkSize, size - offset);
  218. Write(dstOffset + offset, GetSpan(srcOffset + offset, copySize));
  219. }
  220. }
  221. /// <summary>
  222. /// Fills a region of memory with <paramref name="value"/>.
  223. /// </summary>
  224. /// <param name="offset">Offset of the region to fill with <paramref name="value"/></param>
  225. /// <param name="size">Size in bytes of the region to fill</param>
  226. /// <param name="value">Value to use for the fill</param>
  227. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  228. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  229. public void Fill(ulong offset, ulong size, byte value)
  230. {
  231. const int MaxChunkSize = 1 << 24;
  232. for (ulong subOffset = 0; subOffset < size; subOffset += MaxChunkSize)
  233. {
  234. int copySize = (int)Math.Min(MaxChunkSize, size - subOffset);
  235. GetSpan(offset + subOffset, copySize).Fill(value);
  236. }
  237. }
  238. /// <summary>
  239. /// Gets a reference of the data at a given memory block region.
  240. /// </summary>
  241. /// <typeparam name="T">Data type</typeparam>
  242. /// <param name="offset">Offset of the memory region</param>
  243. /// <returns>A reference to the given memory region data</returns>
  244. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  245. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  246. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  247. public unsafe ref T GetRef<T>(ulong offset) where T : unmanaged
  248. {
  249. IntPtr ptr = _pointer;
  250. ObjectDisposedException.ThrowIf(ptr == IntPtr.Zero, this);
  251. int size = Unsafe.SizeOf<T>();
  252. ulong endOffset = offset + (ulong)size;
  253. if (endOffset > Size || endOffset < offset)
  254. {
  255. ThrowInvalidMemoryRegionException();
  256. }
  257. return ref Unsafe.AsRef<T>((void*)PtrAddr(ptr, offset));
  258. }
  259. /// <summary>
  260. /// Gets the pointer of a given memory block region.
  261. /// </summary>
  262. /// <param name="offset">Start offset of the memory region</param>
  263. /// <param name="size">Size in bytes of the region</param>
  264. /// <returns>The pointer to the memory region</returns>
  265. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  266. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  267. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  268. public IntPtr GetPointer(ulong offset, ulong size) => GetPointerInternal(offset, size);
  269. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  270. private IntPtr GetPointerInternal(ulong offset, ulong size)
  271. {
  272. IntPtr ptr = _pointer;
  273. ObjectDisposedException.ThrowIf(ptr == IntPtr.Zero, this);
  274. ulong endOffset = offset + size;
  275. if (endOffset > Size || endOffset < offset)
  276. {
  277. ThrowInvalidMemoryRegionException();
  278. }
  279. return PtrAddr(ptr, offset);
  280. }
  281. /// <summary>
  282. /// Gets the <see cref="Span{T}"/> of a given memory block region.
  283. /// </summary>
  284. /// <param name="offset">Start offset of the memory region</param>
  285. /// <param name="size">Size in bytes of the region</param>
  286. /// <returns>Span of the memory region</returns>
  287. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  288. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  289. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  290. public unsafe Span<byte> GetSpan(ulong offset, int size)
  291. {
  292. return new Span<byte>((void*)GetPointerInternal(offset, (ulong)size), size);
  293. }
  294. /// <summary>
  295. /// Gets the <see cref="Memory{T}"/> of a given memory block region.
  296. /// </summary>
  297. /// <param name="offset">Start offset of the memory region</param>
  298. /// <param name="size">Size in bytes of the region</param>
  299. /// <returns>Memory of the memory region</returns>
  300. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  301. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  302. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  303. public unsafe Memory<byte> GetMemory(ulong offset, int size)
  304. {
  305. return new NativeMemoryManager<byte>((byte*)GetPointerInternal(offset, (ulong)size), size).Memory;
  306. }
  307. /// <summary>
  308. /// Gets a writable region of a given memory block region.
  309. /// </summary>
  310. /// <param name="offset">Start offset of the memory region</param>
  311. /// <param name="size">Size in bytes of the region</param>
  312. /// <returns>Writable region of the memory region</returns>
  313. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  314. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  315. public WritableRegion GetWritableRegion(ulong offset, int size)
  316. {
  317. return new WritableRegion(null, offset, GetMemory(offset, size));
  318. }
  319. /// <summary>
  320. /// Adds a 64-bits offset to a native pointer.
  321. /// </summary>
  322. /// <param name="pointer">Native pointer</param>
  323. /// <param name="offset">Offset to add</param>
  324. /// <returns>Native pointer with the added offset</returns>
  325. private static IntPtr PtrAddr(IntPtr pointer, ulong offset)
  326. {
  327. return new IntPtr(pointer.ToInt64() + (long)offset);
  328. }
  329. /// <summary>
  330. /// Frees the memory allocated for this memory block.
  331. /// </summary>
  332. /// <remarks>
  333. /// It's an error to use the memory block after disposal.
  334. /// </remarks>
  335. public void Dispose()
  336. {
  337. FreeMemory();
  338. GC.SuppressFinalize(this);
  339. }
  340. ~MemoryBlock() => FreeMemory();
  341. private void FreeMemory()
  342. {
  343. IntPtr ptr = Interlocked.Exchange(ref _pointer, IntPtr.Zero);
  344. // If pointer is null, the memory was already freed or never allocated.
  345. if (ptr != IntPtr.Zero)
  346. {
  347. if (_usesSharedMemory)
  348. {
  349. MemoryManagement.UnmapSharedMemory(ptr, Size);
  350. }
  351. else
  352. {
  353. MemoryManagement.Free(ptr, Size);
  354. }
  355. }
  356. if (!_isMirror)
  357. {
  358. IntPtr sharedMemory = Interlocked.Exchange(ref _sharedMemory, IntPtr.Zero);
  359. if (sharedMemory != IntPtr.Zero)
  360. {
  361. MemoryManagement.DestroySharedMemory(sharedMemory);
  362. }
  363. }
  364. }
  365. /// <summary>
  366. /// Checks if the specified memory allocation flags are supported on the current platform.
  367. /// </summary>
  368. /// <param name="flags">Flags to be checked</param>
  369. /// <returns>True if the platform supports all the flags, false otherwise</returns>
  370. public static bool SupportsFlags(MemoryAllocationFlags flags)
  371. {
  372. if (flags.HasFlag(MemoryAllocationFlags.ViewCompatible))
  373. {
  374. if (OperatingSystem.IsWindows())
  375. {
  376. return OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17134);
  377. }
  378. return OperatingSystem.IsLinux() || OperatingSystem.IsMacOS();
  379. }
  380. return true;
  381. }
  382. public static ulong GetPageSize()
  383. {
  384. return (ulong)Environment.SystemPageSize;
  385. }
  386. private static void ThrowInvalidMemoryRegionException() => throw new InvalidMemoryRegionException();
  387. }
  388. }