MemoryBlock.cs 22 KB

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