MemoryBlock.cs 13 KB

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