MemoryBlock.cs 21 KB

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