MemoryManagementUnix.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. using Mono.Unix.Native;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Runtime.InteropServices;
  6. using System.Runtime.Versioning;
  7. namespace Ryujinx.Memory
  8. {
  9. [SupportedOSPlatform("linux")]
  10. [SupportedOSPlatform("macos")]
  11. static class MemoryManagementUnix
  12. {
  13. private struct UnixSharedMemory
  14. {
  15. public IntPtr Pointer;
  16. public ulong Size;
  17. public IntPtr SourcePointer;
  18. }
  19. [DllImport("libc", SetLastError = true)]
  20. public static extern IntPtr mremap(IntPtr old_address, ulong old_size, ulong new_size, MremapFlags flags, IntPtr new_address);
  21. [DllImport("libc", SetLastError = true)]
  22. public static extern int madvise(IntPtr address, ulong size, int advice);
  23. private const int MADV_DONTNEED = 4;
  24. private const int MADV_REMOVE = 9;
  25. private static readonly List<UnixSharedMemory> _sharedMemory = new List<UnixSharedMemory>();
  26. private static readonly ConcurrentDictionary<IntPtr, ulong> _sharedMemorySource = new ConcurrentDictionary<IntPtr, ulong>();
  27. private static readonly ConcurrentDictionary<IntPtr, ulong> _allocations = new ConcurrentDictionary<IntPtr, ulong>();
  28. public static IntPtr Allocate(ulong size)
  29. {
  30. return AllocateInternal(size, MmapProts.PROT_READ | MmapProts.PROT_WRITE);
  31. }
  32. public static IntPtr Reserve(ulong size)
  33. {
  34. return AllocateInternal(size, MmapProts.PROT_NONE);
  35. }
  36. private static IntPtr AllocateInternal(ulong size, MmapProts prot, bool shared = false)
  37. {
  38. MmapFlags flags = MmapFlags.MAP_ANONYMOUS;
  39. if (shared)
  40. {
  41. flags |= MmapFlags.MAP_SHARED | (MmapFlags)0x80000;
  42. }
  43. else
  44. {
  45. flags |= MmapFlags.MAP_PRIVATE;
  46. }
  47. if (prot == MmapProts.PROT_NONE)
  48. {
  49. flags |= MmapFlags.MAP_NORESERVE;
  50. }
  51. IntPtr ptr = Syscall.mmap(IntPtr.Zero, size, prot, flags, -1, 0);
  52. if (ptr == new IntPtr(-1L))
  53. {
  54. throw new OutOfMemoryException();
  55. }
  56. if (!_allocations.TryAdd(ptr, size))
  57. {
  58. // This should be impossible, kernel shouldn't return an already mapped address.
  59. throw new InvalidOperationException();
  60. }
  61. return ptr;
  62. }
  63. public static bool Commit(IntPtr address, ulong size)
  64. {
  65. bool success = Syscall.mprotect(address, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE) == 0;
  66. if (success)
  67. {
  68. foreach (var shared in _sharedMemory)
  69. {
  70. if ((ulong)address + size > (ulong)shared.SourcePointer && (ulong)address < (ulong)shared.SourcePointer + shared.Size)
  71. {
  72. ulong sharedAddress = ((ulong)address - (ulong)shared.SourcePointer) + (ulong)shared.Pointer;
  73. if (Syscall.mprotect((IntPtr)sharedAddress, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE) != 0)
  74. {
  75. return false;
  76. }
  77. }
  78. }
  79. }
  80. return success;
  81. }
  82. public static bool Decommit(IntPtr address, ulong size)
  83. {
  84. bool isShared;
  85. lock (_sharedMemory)
  86. {
  87. isShared = _sharedMemory.Exists(x => (ulong)address >= (ulong)x.Pointer && (ulong)address + size <= (ulong)x.Pointer + x.Size);
  88. }
  89. // Must be writable for madvise to work properly.
  90. Syscall.mprotect(address, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE);
  91. madvise(address, size, isShared ? MADV_REMOVE : MADV_DONTNEED);
  92. return Syscall.mprotect(address, size, MmapProts.PROT_NONE) == 0;
  93. }
  94. public static bool Reprotect(IntPtr address, ulong size, MemoryPermission permission)
  95. {
  96. return Syscall.mprotect(address, size, GetProtection(permission)) == 0;
  97. }
  98. private static MmapProts GetProtection(MemoryPermission permission)
  99. {
  100. return permission switch
  101. {
  102. MemoryPermission.None => MmapProts.PROT_NONE,
  103. MemoryPermission.Read => MmapProts.PROT_READ,
  104. MemoryPermission.ReadAndWrite => MmapProts.PROT_READ | MmapProts.PROT_WRITE,
  105. MemoryPermission.ReadAndExecute => MmapProts.PROT_READ | MmapProts.PROT_EXEC,
  106. MemoryPermission.ReadWriteExecute => MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC,
  107. MemoryPermission.Execute => MmapProts.PROT_EXEC,
  108. _ => throw new MemoryProtectionException(permission)
  109. };
  110. }
  111. public static bool Free(IntPtr address)
  112. {
  113. if (_allocations.TryRemove(address, out ulong size))
  114. {
  115. return Syscall.munmap(address, size) == 0;
  116. }
  117. return false;
  118. }
  119. public static IntPtr Remap(IntPtr target, IntPtr source, ulong size)
  120. {
  121. int flags = (int)MremapFlags.MREMAP_MAYMOVE;
  122. if (target != IntPtr.Zero)
  123. {
  124. flags |= 2;
  125. }
  126. IntPtr result = mremap(source, 0, size, (MremapFlags)(flags), target);
  127. if (result == IntPtr.Zero)
  128. {
  129. throw new InvalidOperationException();
  130. }
  131. return result;
  132. }
  133. public static IntPtr CreateSharedMemory(ulong size, bool reserve)
  134. {
  135. IntPtr result = AllocateInternal(
  136. size,
  137. reserve ? MmapProts.PROT_NONE : MmapProts.PROT_READ | MmapProts.PROT_WRITE,
  138. true);
  139. if (result == IntPtr.Zero)
  140. {
  141. throw new OutOfMemoryException();
  142. }
  143. _sharedMemorySource[result] = (ulong)size;
  144. return result;
  145. }
  146. public static void DestroySharedMemory(IntPtr handle)
  147. {
  148. lock (_sharedMemory)
  149. {
  150. foreach (var memory in _sharedMemory)
  151. {
  152. if (memory.SourcePointer == handle)
  153. {
  154. throw new InvalidOperationException("Shared memory cannot be destroyed unless fully unmapped.");
  155. }
  156. }
  157. }
  158. _sharedMemorySource.Remove(handle, out ulong _);
  159. }
  160. public static IntPtr MapSharedMemory(IntPtr handle)
  161. {
  162. // Try find the handle for this shared memory. If it is mapped, then we want to map
  163. // it a second time in another location.
  164. // If it is not mapped, then its handle is the mapping.
  165. ulong size = _sharedMemorySource[handle];
  166. if (size == 0)
  167. {
  168. throw new InvalidOperationException("Shared memory cannot be mapped after its source is unmapped.");
  169. }
  170. lock (_sharedMemory)
  171. {
  172. foreach (var memory in _sharedMemory)
  173. {
  174. if (memory.Pointer == handle)
  175. {
  176. IntPtr result = AllocateInternal(
  177. memory.Size,
  178. MmapProts.PROT_NONE
  179. );
  180. if (result == IntPtr.Zero)
  181. {
  182. throw new OutOfMemoryException();
  183. }
  184. Remap(result, handle, memory.Size);
  185. _sharedMemory.Add(new UnixSharedMemory
  186. {
  187. Pointer = result,
  188. Size = memory.Size,
  189. SourcePointer = handle
  190. });
  191. return result;
  192. }
  193. }
  194. _sharedMemory.Add(new UnixSharedMemory
  195. {
  196. Pointer = handle,
  197. Size = size,
  198. SourcePointer = handle
  199. });
  200. }
  201. return handle;
  202. }
  203. public static void UnmapSharedMemory(IntPtr address)
  204. {
  205. lock (_sharedMemory)
  206. {
  207. int removed = _sharedMemory.RemoveAll(memory =>
  208. {
  209. if (memory.Pointer == address)
  210. {
  211. if (memory.Pointer == memory.SourcePointer)
  212. {
  213. // After removing the original mapping, it cannot be mapped again.
  214. _sharedMemorySource[memory.SourcePointer] = 0;
  215. }
  216. Free(address);
  217. return true;
  218. }
  219. return false;
  220. });
  221. if (removed == 0)
  222. {
  223. throw new InvalidOperationException("Shared memory mapping could not be found.");
  224. }
  225. }
  226. }
  227. }
  228. }