MemoryBlock.cs 21 KB

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