MemoryBlock.cs 19 KB

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