MemoryBlock.cs 22 KB

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