MemoryBlock.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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 : IDisposable
  10. {
  11. private IntPtr _pointer;
  12. /// <summary>
  13. /// Pointer to the memory block data.
  14. /// </summary>
  15. public IntPtr Pointer => _pointer;
  16. /// <summary>
  17. /// Size of the memory block.
  18. /// </summary>
  19. public ulong Size { get; }
  20. /// <summary>
  21. /// Initializes a new instance of the memory block class.
  22. /// </summary>
  23. /// <param name="size">Size of the memory block</param>
  24. /// <param name="flags">Flags that controls memory block memory allocation</param>
  25. /// <exception cref="OutOfMemoryException">Throw when there's no enough memory to allocate the requested size</exception>
  26. /// <exception cref="PlatformNotSupportedException">Throw when the current platform is not supported</exception>
  27. public MemoryBlock(ulong size, MemoryAllocationFlags flags = MemoryAllocationFlags.None)
  28. {
  29. if (flags.HasFlag(MemoryAllocationFlags.Reserve))
  30. {
  31. _pointer = MemoryManagement.Reserve(size);
  32. }
  33. else
  34. {
  35. _pointer = MemoryManagement.Allocate(size);
  36. }
  37. Size = size;
  38. }
  39. /// <summary>
  40. /// Commits a region of memory that has previously been reserved.
  41. /// This can be used to allocate memory on demand.
  42. /// </summary>
  43. /// <param name="offset">Starting offset of the range to be committed</param>
  44. /// <param name="size">Size of the range to be committed</param>
  45. /// <returns>True if the operation was successful, false otherwise</returns>
  46. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  47. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  48. public bool Commit(ulong offset, ulong size)
  49. {
  50. return MemoryManagement.Commit(GetPointerInternal(offset, size), size);
  51. }
  52. /// <summary>
  53. /// Reprotects a region of memory.
  54. /// </summary>
  55. /// <param name="offset">Starting offset of the range to be reprotected</param>
  56. /// <param name="size">Size of the range to be reprotected</param>
  57. /// <param name="permission">New memory permissions</param>
  58. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  59. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  60. /// <exception cref="MemoryProtectionException">Throw when <paramref name="permission"/> is invalid</exception>
  61. public void Reprotect(ulong offset, ulong size, MemoryPermission permission)
  62. {
  63. MemoryManagement.Reprotect(GetPointerInternal(offset, size), size, permission);
  64. }
  65. /// <summary>
  66. /// Reads bytes from the memory block.
  67. /// </summary>
  68. /// <param name="offset">Starting offset of the range being read</param>
  69. /// <param name="data">Span where the bytes being read will be copied to</param>
  70. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  71. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified for the the data is out of range</exception>
  72. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  73. public void Read(ulong offset, Span<byte> data)
  74. {
  75. GetSpan(offset, data.Length).CopyTo(data);
  76. }
  77. /// <summary>
  78. /// Reads data from the memory block.
  79. /// </summary>
  80. /// <typeparam name="T">Type of the data</typeparam>
  81. /// <param name="offset">Offset where the data is located</param>
  82. /// <returns>Data at the specified address</returns>
  83. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  84. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified for the the data is out of range</exception>
  85. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  86. public T Read<T>(ulong offset) where T : unmanaged
  87. {
  88. return GetRef<T>(offset);
  89. }
  90. /// <summary>
  91. /// Writes bytes to the memory block.
  92. /// </summary>
  93. /// <param name="offset">Starting offset of the range being written</param>
  94. /// <param name="data">Span where the bytes being written will be copied from</param>
  95. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  96. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified for the the data is out of range</exception>
  97. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  98. public void Write(ulong offset, ReadOnlySpan<byte> data)
  99. {
  100. data.CopyTo(GetSpan(offset, data.Length));
  101. }
  102. /// <summary>
  103. /// Writes data to the memory block.
  104. /// </summary>
  105. /// <typeparam name="T">Type of the data being written</typeparam>
  106. /// <param name="offset">Offset to write the data into</param>
  107. /// <param name="data">Data to be written</param>
  108. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  109. /// <exception cref="InvalidMemoryRegionException">Throw when the memory region specified for the the data is out of range</exception>
  110. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  111. public void Write<T>(ulong offset, T data) where T : unmanaged
  112. {
  113. GetRef<T>(offset) = data;
  114. }
  115. /// <summary>
  116. /// Copies data from one memory location to another.
  117. /// </summary>
  118. /// <param name="dstOffset">Destination offset to write the data into</param>
  119. /// <param name="srcOffset">Source offset to read the data from</param>
  120. /// <param name="size">Size of the copy in bytes</param>
  121. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  122. /// <exception cref="InvalidMemoryRegionException">Throw when <paramref name="srcOffset"/>, <paramref name="dstOffset"/> or <paramref name="size"/> is out of range</exception>
  123. public void Copy(ulong dstOffset, ulong srcOffset, ulong size)
  124. {
  125. const int MaxChunkSize = 1 << 30;
  126. for (ulong offset = 0; offset < size; offset += MaxChunkSize)
  127. {
  128. int copySize = (int)Math.Min(MaxChunkSize, size - offset);
  129. Write(dstOffset + offset, GetSpan(srcOffset + offset, copySize));
  130. }
  131. }
  132. /// <summary>
  133. /// Fills a region of memory with zeros.
  134. /// </summary>
  135. /// <param name="offset">Offset of the region to fill with zeros</param>
  136. /// <param name="size">Size in bytes of the region to fill</param>
  137. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  138. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  139. public void ZeroFill(ulong offset, ulong size)
  140. {
  141. const int MaxChunkSize = 1 << 30;
  142. for (ulong subOffset = 0; subOffset < size; subOffset += MaxChunkSize)
  143. {
  144. int copySize = (int)Math.Min(MaxChunkSize, size - subOffset);
  145. GetSpan(offset + subOffset, copySize).Fill(0);
  146. }
  147. }
  148. /// <summary>
  149. /// Gets a reference of the data at a given memory block region.
  150. /// </summary>
  151. /// <typeparam name="T">Data type</typeparam>
  152. /// <param name="offset">Offset of the memory region</param>
  153. /// <returns>A reference to the given memory region data</returns>
  154. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  155. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  156. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  157. public unsafe ref T GetRef<T>(ulong offset) where T : unmanaged
  158. {
  159. IntPtr ptr = _pointer;
  160. if (ptr == IntPtr.Zero)
  161. {
  162. ThrowObjectDisposed();
  163. }
  164. int size = Unsafe.SizeOf<T>();
  165. ulong endOffset = offset + (ulong)size;
  166. if (endOffset > Size || endOffset < offset)
  167. {
  168. ThrowInvalidMemoryRegionException();
  169. }
  170. return ref Unsafe.AsRef<T>((void*)PtrAddr(ptr, offset));
  171. }
  172. /// <summary>
  173. /// Gets the pointer of a given memory block region.
  174. /// </summary>
  175. /// <param name="offset">Start offset of the memory region</param>
  176. /// <param name="size">Size in bytes of the region</param>
  177. /// <returns>The pointer to the memory region</returns>
  178. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  179. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  180. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  181. public IntPtr GetPointer(ulong offset, int size) => GetPointerInternal(offset, (ulong)size);
  182. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  183. private IntPtr GetPointerInternal(ulong offset, ulong size)
  184. {
  185. IntPtr ptr = _pointer;
  186. if (ptr == IntPtr.Zero)
  187. {
  188. ThrowObjectDisposed();
  189. }
  190. ulong endOffset = offset + size;
  191. if (endOffset > Size || endOffset < offset)
  192. {
  193. ThrowInvalidMemoryRegionException();
  194. }
  195. return PtrAddr(ptr, offset);
  196. }
  197. /// <summary>
  198. /// Gets the <see cref="Span{T}"/> of a given memory block region.
  199. /// </summary>
  200. /// <param name="offset">Start offset of the memory region</param>
  201. /// <param name="size">Size in bytes of the region</param>
  202. /// <returns>Span of the memory region</returns>
  203. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  204. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  205. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  206. public unsafe Span<byte> GetSpan(ulong offset, int size)
  207. {
  208. return new Span<byte>((void*)GetPointer(offset, size), size);
  209. }
  210. /// <summary>
  211. /// Gets the <see cref="Memory{T}"/> of a given memory block region.
  212. /// </summary>
  213. /// <param name="offset">Start offset of the memory region</param>
  214. /// <param name="size">Size in bytes of the region</param>
  215. /// <returns>Memory of the memory region</returns>
  216. /// <exception cref="ObjectDisposedException">Throw when the memory block has already been disposed</exception>
  217. /// <exception cref="InvalidMemoryRegionException">Throw when either <paramref name="offset"/> or <paramref name="size"/> are out of range</exception>
  218. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  219. public unsafe Memory<byte> GetMemory(ulong offset, int size)
  220. {
  221. return new NativeMemoryManager<byte>((byte*)GetPointer(offset, size), size).Memory;
  222. }
  223. /// <summary>
  224. /// Adds a 64-bits offset to a native pointer.
  225. /// </summary>
  226. /// <param name="pointer">Native pointer</param>
  227. /// <param name="offset">Offset to add</param>
  228. /// <returns>Native pointer with the added offset</returns>
  229. private IntPtr PtrAddr(IntPtr pointer, ulong offset)
  230. {
  231. return (IntPtr)(pointer.ToInt64() + (long)offset);
  232. }
  233. /// <summary>
  234. /// Frees the memory allocated for this memory block.
  235. /// </summary>
  236. /// <remarks>
  237. /// It's an error to use the memory block after disposal.
  238. /// </remarks>
  239. public void Dispose() => FreeMemory();
  240. ~MemoryBlock() => FreeMemory();
  241. private void FreeMemory()
  242. {
  243. IntPtr ptr = Interlocked.Exchange(ref _pointer, IntPtr.Zero);
  244. // If pointer is null, the memory was already freed or never allocated.
  245. if (ptr != IntPtr.Zero)
  246. {
  247. MemoryManagement.Free(ptr);
  248. }
  249. }
  250. private void ThrowObjectDisposed() => throw new ObjectDisposedException(nameof(MemoryBlock));
  251. private void ThrowInvalidMemoryRegionException() => throw new InvalidMemoryRegionException();
  252. }
  253. }