MemoryManagementUnix.cs 9.0 KB

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