PlaceholderManager.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.Versioning;
  4. using System.Threading;
  5. namespace Ryujinx.Memory.WindowsShared
  6. {
  7. /// <summary>
  8. /// Windows memory placeholder manager.
  9. /// </summary>
  10. [SupportedOSPlatform("windows")]
  11. class PlaceholderManager
  12. {
  13. private const ulong MinimumPageSize = 0x1000;
  14. [ThreadStatic]
  15. private static int _threadLocalPartialUnmapsCount;
  16. private readonly IntervalTree<ulong, ulong> _mappings;
  17. private readonly IntervalTree<ulong, MemoryPermission> _protections;
  18. private readonly ReaderWriterLock _partialUnmapLock;
  19. private int _partialUnmapsCount;
  20. /// <summary>
  21. /// Creates a new instance of the Windows memory placeholder manager.
  22. /// </summary>
  23. public PlaceholderManager()
  24. {
  25. _mappings = new IntervalTree<ulong, ulong>();
  26. _protections = new IntervalTree<ulong, MemoryPermission>();
  27. _partialUnmapLock = new ReaderWriterLock();
  28. }
  29. /// <summary>
  30. /// Reserves a range of the address space to be later mapped as shared memory views.
  31. /// </summary>
  32. /// <param name="address">Start address of the region to reserve</param>
  33. /// <param name="size">Size in bytes of the region to reserve</param>
  34. public void ReserveRange(ulong address, ulong size)
  35. {
  36. lock (_mappings)
  37. {
  38. _mappings.Add(address, address + size, ulong.MaxValue);
  39. }
  40. }
  41. /// <summary>
  42. /// Maps a shared memory view on a previously reserved memory region.
  43. /// </summary>
  44. /// <param name="sharedMemory">Shared memory that will be the backing storage for the view</param>
  45. /// <param name="srcOffset">Offset in the shared memory to map</param>
  46. /// <param name="location">Address to map the view into</param>
  47. /// <param name="size">Size of the view in bytes</param>
  48. public void MapView(IntPtr sharedMemory, ulong srcOffset, IntPtr location, IntPtr size)
  49. {
  50. _partialUnmapLock.AcquireReaderLock(Timeout.Infinite);
  51. try
  52. {
  53. UnmapViewInternal(sharedMemory, location, size);
  54. MapViewInternal(sharedMemory, srcOffset, location, size);
  55. }
  56. finally
  57. {
  58. _partialUnmapLock.ReleaseReaderLock();
  59. }
  60. }
  61. /// <summary>
  62. /// Maps a shared memory view on a previously reserved memory region.
  63. /// </summary>
  64. /// <param name="sharedMemory">Shared memory that will be the backing storage for the view</param>
  65. /// <param name="srcOffset">Offset in the shared memory to map</param>
  66. /// <param name="location">Address to map the view into</param>
  67. /// <param name="size">Size of the view in bytes</param>
  68. /// <exception cref="WindowsApiException">Thrown when the Windows API returns an error mapping the memory</exception>
  69. private void MapViewInternal(IntPtr sharedMemory, ulong srcOffset, IntPtr location, IntPtr size)
  70. {
  71. SplitForMap((ulong)location, (ulong)size, srcOffset);
  72. var ptr = WindowsApi.MapViewOfFile3(
  73. sharedMemory,
  74. WindowsApi.CurrentProcessHandle,
  75. location,
  76. srcOffset,
  77. size,
  78. 0x4000,
  79. MemoryProtection.ReadWrite,
  80. IntPtr.Zero,
  81. 0);
  82. if (ptr == IntPtr.Zero)
  83. {
  84. throw new WindowsApiException("MapViewOfFile3");
  85. }
  86. }
  87. /// <summary>
  88. /// Splits a larger placeholder, slicing at the start and end address, for a new memory mapping.
  89. /// </summary>
  90. /// <param name="address">Address to split</param>
  91. /// <param name="size">Size of the new region</param>
  92. /// <param name="backingOffset">Offset in the shared memory that will be mapped</param>
  93. private void SplitForMap(ulong address, ulong size, ulong backingOffset)
  94. {
  95. ulong endAddress = address + size;
  96. var overlaps = Array.Empty<IntervalTreeNode<ulong, ulong>>();
  97. lock (_mappings)
  98. {
  99. int count = _mappings.Get(address, endAddress, ref overlaps);
  100. Debug.Assert(count == 1);
  101. Debug.Assert(!IsMapped(overlaps[0].Value));
  102. var overlap = overlaps[0];
  103. // Tree operations might modify the node start/end values, so save a copy before we modify the tree.
  104. ulong overlapStart = overlap.Start;
  105. ulong overlapEnd = overlap.End;
  106. ulong overlapValue = overlap.Value;
  107. _mappings.Remove(overlap);
  108. bool overlapStartsBefore = overlapStart < address;
  109. bool overlapEndsAfter = overlapEnd > endAddress;
  110. if (overlapStartsBefore && overlapEndsAfter)
  111. {
  112. CheckFreeResult(WindowsApi.VirtualFree(
  113. (IntPtr)address,
  114. (IntPtr)size,
  115. AllocationType.Release | AllocationType.PreservePlaceholder));
  116. _mappings.Add(overlapStart, address, overlapValue);
  117. _mappings.Add(endAddress, overlapEnd, AddBackingOffset(overlapValue, endAddress - overlapStart));
  118. }
  119. else if (overlapStartsBefore)
  120. {
  121. ulong overlappedSize = overlapEnd - address;
  122. CheckFreeResult(WindowsApi.VirtualFree(
  123. (IntPtr)address,
  124. (IntPtr)overlappedSize,
  125. AllocationType.Release | AllocationType.PreservePlaceholder));
  126. _mappings.Add(overlapStart, address, overlapValue);
  127. }
  128. else if (overlapEndsAfter)
  129. {
  130. ulong overlappedSize = endAddress - overlapStart;
  131. CheckFreeResult(WindowsApi.VirtualFree(
  132. (IntPtr)overlapStart,
  133. (IntPtr)overlappedSize,
  134. AllocationType.Release | AllocationType.PreservePlaceholder));
  135. _mappings.Add(endAddress, overlapEnd, AddBackingOffset(overlapValue, overlappedSize));
  136. }
  137. _mappings.Add(address, endAddress, backingOffset);
  138. }
  139. }
  140. /// <summary>
  141. /// Unmaps a view that has been previously mapped with <see cref="MapView"/>.
  142. /// </summary>
  143. /// <remarks>
  144. /// For "partial unmaps" (when not the entire mapped range is being unmapped), it might be
  145. /// necessary to unmap the whole range and then remap the sub-ranges that should remain mapped.
  146. /// </remarks>
  147. /// <param name="sharedMemory">Shared memory that the view being unmapped belongs to</param>
  148. /// <param name="location">Address to unmap</param>
  149. /// <param name="size">Size of the region to unmap in bytes</param>
  150. public void UnmapView(IntPtr sharedMemory, IntPtr location, IntPtr size)
  151. {
  152. _partialUnmapLock.AcquireReaderLock(Timeout.Infinite);
  153. try
  154. {
  155. UnmapViewInternal(sharedMemory, location, size);
  156. }
  157. finally
  158. {
  159. _partialUnmapLock.ReleaseReaderLock();
  160. }
  161. }
  162. /// <summary>
  163. /// Unmaps a view that has been previously mapped with <see cref="MapView"/>.
  164. /// </summary>
  165. /// <remarks>
  166. /// For "partial unmaps" (when not the entire mapped range is being unmapped), it might be
  167. /// necessary to unmap the whole range and then remap the sub-ranges that should remain mapped.
  168. /// </remarks>
  169. /// <param name="sharedMemory">Shared memory that the view being unmapped belongs to</param>
  170. /// <param name="location">Address to unmap</param>
  171. /// <param name="size">Size of the region to unmap in bytes</param>
  172. /// <exception cref="WindowsApiException">Thrown when the Windows API returns an error unmapping or remapping the memory</exception>
  173. private void UnmapViewInternal(IntPtr sharedMemory, IntPtr location, IntPtr size)
  174. {
  175. ulong startAddress = (ulong)location;
  176. ulong unmapSize = (ulong)size;
  177. ulong endAddress = startAddress + unmapSize;
  178. var overlaps = Array.Empty<IntervalTreeNode<ulong, ulong>>();
  179. int count;
  180. lock (_mappings)
  181. {
  182. count = _mappings.Get(startAddress, endAddress, ref overlaps);
  183. }
  184. for (int index = 0; index < count; index++)
  185. {
  186. var overlap = overlaps[index];
  187. if (IsMapped(overlap.Value))
  188. {
  189. if (!WindowsApi.UnmapViewOfFile2(WindowsApi.CurrentProcessHandle, (IntPtr)overlap.Start, 2))
  190. {
  191. throw new WindowsApiException("UnmapViewOfFile2");
  192. }
  193. // Tree operations might modify the node start/end values, so save a copy before we modify the tree.
  194. ulong overlapStart = overlap.Start;
  195. ulong overlapEnd = overlap.End;
  196. ulong overlapValue = overlap.Value;
  197. lock (_mappings)
  198. {
  199. _mappings.Remove(overlap);
  200. _mappings.Add(overlapStart, overlapEnd, ulong.MaxValue);
  201. }
  202. bool overlapStartsBefore = overlapStart < startAddress;
  203. bool overlapEndsAfter = overlapEnd > endAddress;
  204. if (overlapStartsBefore || overlapEndsAfter)
  205. {
  206. // If the overlap extends beyond the region we are unmapping,
  207. // then we need to re-map the regions that are supposed to remain mapped.
  208. // This is necessary because Windows does not support partial view unmaps.
  209. // That is, you can only fully unmap a view that was previously mapped, you can't just unmap a chunck of it.
  210. LockCookie lockCookie = _partialUnmapLock.UpgradeToWriterLock(Timeout.Infinite);
  211. _partialUnmapsCount++;
  212. if (overlapStartsBefore)
  213. {
  214. ulong remapSize = startAddress - overlapStart;
  215. MapViewInternal(sharedMemory, overlapValue, (IntPtr)overlapStart, (IntPtr)remapSize);
  216. RestoreRangeProtection(overlapStart, remapSize);
  217. }
  218. if (overlapEndsAfter)
  219. {
  220. ulong overlappedSize = endAddress - overlapStart;
  221. ulong remapBackingOffset = overlapValue + overlappedSize;
  222. ulong remapAddress = overlapStart + overlappedSize;
  223. ulong remapSize = overlapEnd - endAddress;
  224. MapViewInternal(sharedMemory, remapBackingOffset, (IntPtr)remapAddress, (IntPtr)remapSize);
  225. RestoreRangeProtection(remapAddress, remapSize);
  226. }
  227. _partialUnmapLock.DowngradeFromWriterLock(ref lockCookie);
  228. }
  229. }
  230. }
  231. CoalesceForUnmap(startAddress, unmapSize);
  232. RemoveProtection(startAddress, unmapSize);
  233. }
  234. /// <summary>
  235. /// Coalesces adjacent placeholders after unmap.
  236. /// </summary>
  237. /// <param name="address">Address of the region that was unmapped</param>
  238. /// <param name="size">Size of the region that was unmapped in bytes</param>
  239. private void CoalesceForUnmap(ulong address, ulong size)
  240. {
  241. ulong endAddress = address + size;
  242. var overlaps = Array.Empty<IntervalTreeNode<ulong, ulong>>();
  243. int unmappedCount = 0;
  244. lock (_mappings)
  245. {
  246. int count = _mappings.Get(address - MinimumPageSize, endAddress + MinimumPageSize, ref overlaps);
  247. if (count < 2)
  248. {
  249. // Nothing to coalesce if we only have 1 or no overlaps.
  250. return;
  251. }
  252. for (int index = 0; index < count; index++)
  253. {
  254. var overlap = overlaps[index];
  255. if (!IsMapped(overlap.Value))
  256. {
  257. if (address > overlap.Start)
  258. {
  259. address = overlap.Start;
  260. }
  261. if (endAddress < overlap.End)
  262. {
  263. endAddress = overlap.End;
  264. }
  265. _mappings.Remove(overlap);
  266. unmappedCount++;
  267. }
  268. }
  269. _mappings.Add(address, endAddress, ulong.MaxValue);
  270. }
  271. if (unmappedCount > 1)
  272. {
  273. size = endAddress - address;
  274. CheckFreeResult(WindowsApi.VirtualFree(
  275. (IntPtr)address,
  276. (IntPtr)size,
  277. AllocationType.Release | AllocationType.CoalescePlaceholders));
  278. }
  279. }
  280. /// <summary>
  281. /// Reprotects a region of memory that has been mapped.
  282. /// </summary>
  283. /// <param name="address">Address of the region to reprotect</param>
  284. /// <param name="size">Size of the region to reprotect in bytes</param>
  285. /// <param name="permission">New permissions</param>
  286. /// <returns>True if the reprotection was successful, false otherwise</returns>
  287. public bool ReprotectView(IntPtr address, IntPtr size, MemoryPermission permission)
  288. {
  289. _partialUnmapLock.AcquireReaderLock(Timeout.Infinite);
  290. try
  291. {
  292. return ReprotectViewInternal(address, size, permission, false);
  293. }
  294. finally
  295. {
  296. _partialUnmapLock.ReleaseReaderLock();
  297. }
  298. }
  299. /// <summary>
  300. /// Reprotects a region of memory that has been mapped.
  301. /// </summary>
  302. /// <param name="address">Address of the region to reprotect</param>
  303. /// <param name="size">Size of the region to reprotect in bytes</param>
  304. /// <param name="permission">New permissions</param>
  305. /// <param name="throwOnError">Throw an exception instead of returning an error if the operation fails</param>
  306. /// <returns>True if the reprotection was successful or if <paramref name="throwOnError"/> is true, false otherwise</returns>
  307. /// <exception cref="WindowsApiException">If <paramref name="throwOnError"/> is true, it is thrown when the Windows API returns an error reprotecting the memory</exception>
  308. private bool ReprotectViewInternal(IntPtr address, IntPtr size, MemoryPermission permission, bool throwOnError)
  309. {
  310. ulong reprotectAddress = (ulong)address;
  311. ulong reprotectSize = (ulong)size;
  312. ulong endAddress = reprotectAddress + reprotectSize;
  313. var overlaps = Array.Empty<IntervalTreeNode<ulong, ulong>>();
  314. int count;
  315. lock (_mappings)
  316. {
  317. count = _mappings.Get(reprotectAddress, endAddress, ref overlaps);
  318. }
  319. bool success = true;
  320. for (int index = 0; index < count; index++)
  321. {
  322. var overlap = overlaps[index];
  323. ulong mappedAddress = overlap.Start;
  324. ulong mappedSize = overlap.End - overlap.Start;
  325. if (mappedAddress < reprotectAddress)
  326. {
  327. ulong delta = reprotectAddress - mappedAddress;
  328. mappedAddress = reprotectAddress;
  329. mappedSize -= delta;
  330. }
  331. ulong mappedEndAddress = mappedAddress + mappedSize;
  332. if (mappedEndAddress > endAddress)
  333. {
  334. ulong delta = mappedEndAddress - endAddress;
  335. mappedSize -= delta;
  336. }
  337. if (!WindowsApi.VirtualProtect((IntPtr)mappedAddress, (IntPtr)mappedSize, WindowsApi.GetProtection(permission), out _))
  338. {
  339. if (throwOnError)
  340. {
  341. throw new WindowsApiException("VirtualProtect");
  342. }
  343. success = false;
  344. }
  345. // We only keep track of "non-standard" protections,
  346. // that is, everything that is not just RW (which is the default when views are mapped).
  347. if (permission == MemoryPermission.ReadAndWrite)
  348. {
  349. RemoveProtection(mappedAddress, mappedSize);
  350. }
  351. else
  352. {
  353. AddProtection(mappedAddress, mappedSize, permission);
  354. }
  355. }
  356. return success;
  357. }
  358. /// <summary>
  359. /// Checks the result of a VirtualFree operation, throwing if needed.
  360. /// </summary>
  361. /// <param name="success">Operation result</param>
  362. /// <exception cref="WindowsApiException">Thrown if <paramref name="success"/> is false</exception>
  363. private static void CheckFreeResult(bool success)
  364. {
  365. if (!success)
  366. {
  367. throw new WindowsApiException("VirtualFree");
  368. }
  369. }
  370. /// <summary>
  371. /// Adds an offset to a backing offset. This will do nothing if the backing offset is the special "unmapped" value.
  372. /// </summary>
  373. /// <param name="backingOffset">Backing offset</param>
  374. /// <param name="offset">Offset to be added</param>
  375. /// <returns>Added offset or just <paramref name="backingOffset"/> if the region is unmapped</returns>
  376. private static ulong AddBackingOffset(ulong backingOffset, ulong offset)
  377. {
  378. if (backingOffset == ulong.MaxValue)
  379. {
  380. return backingOffset;
  381. }
  382. return backingOffset + offset;
  383. }
  384. /// <summary>
  385. /// Checks if a region is unmapped.
  386. /// </summary>
  387. /// <param name="backingOffset">Backing offset to check</param>
  388. /// <returns>True if the backing offset is the special "unmapped" value, false otherwise</returns>
  389. private static bool IsMapped(ulong backingOffset)
  390. {
  391. return backingOffset != ulong.MaxValue;
  392. }
  393. /// <summary>
  394. /// Adds a protection to the list of protections.
  395. /// </summary>
  396. /// <param name="address">Address of the protected region</param>
  397. /// <param name="size">Size of the protected region in bytes</param>
  398. /// <param name="permission">Memory permissions of the region</param>
  399. private void AddProtection(ulong address, ulong size, MemoryPermission permission)
  400. {
  401. ulong endAddress = address + size;
  402. var overlaps = Array.Empty<IntervalTreeNode<ulong, MemoryPermission>>();
  403. int count;
  404. lock (_protections)
  405. {
  406. count = _protections.Get(address, endAddress, ref overlaps);
  407. if (count == 1 &&
  408. overlaps[0].Start <= address &&
  409. overlaps[0].End >= endAddress &&
  410. overlaps[0].Value == permission)
  411. {
  412. return;
  413. }
  414. ulong startAddress = address;
  415. for (int index = 0; index < count; index++)
  416. {
  417. var protection = overlaps[index];
  418. ulong protAddress = protection.Start;
  419. ulong protEndAddress = protection.End;
  420. MemoryPermission protPermission = protection.Value;
  421. _protections.Remove(protection);
  422. if (protection.Value == permission)
  423. {
  424. if (startAddress > protAddress)
  425. {
  426. startAddress = protAddress;
  427. }
  428. if (endAddress < protEndAddress)
  429. {
  430. endAddress = protEndAddress;
  431. }
  432. }
  433. else
  434. {
  435. if (startAddress > protAddress)
  436. {
  437. _protections.Add(protAddress, startAddress, protPermission);
  438. }
  439. if (endAddress < protEndAddress)
  440. {
  441. _protections.Add(endAddress, protEndAddress, protPermission);
  442. }
  443. }
  444. }
  445. _protections.Add(startAddress, endAddress, permission);
  446. }
  447. }
  448. /// <summary>
  449. /// Removes protection from the list of protections.
  450. /// </summary>
  451. /// <param name="address">Address of the protected region</param>
  452. /// <param name="size">Size of the protected region in bytes</param>
  453. private void RemoveProtection(ulong address, ulong size)
  454. {
  455. ulong endAddress = address + size;
  456. var overlaps = Array.Empty<IntervalTreeNode<ulong, MemoryPermission>>();
  457. int count;
  458. lock (_protections)
  459. {
  460. count = _protections.Get(address, endAddress, ref overlaps);
  461. for (int index = 0; index < count; index++)
  462. {
  463. var protection = overlaps[index];
  464. ulong protAddress = protection.Start;
  465. ulong protEndAddress = protection.End;
  466. MemoryPermission protPermission = protection.Value;
  467. _protections.Remove(protection);
  468. if (address > protAddress)
  469. {
  470. _protections.Add(protAddress, address, protPermission);
  471. }
  472. if (endAddress < protEndAddress)
  473. {
  474. _protections.Add(endAddress, protEndAddress, protPermission);
  475. }
  476. }
  477. }
  478. }
  479. /// <summary>
  480. /// Restores the protection of a given memory region that was remapped, using the protections list.
  481. /// </summary>
  482. /// <param name="address">Address of the remapped region</param>
  483. /// <param name="size">Size of the remapped region in bytes</param>
  484. private void RestoreRangeProtection(ulong address, ulong size)
  485. {
  486. ulong endAddress = address + size;
  487. var overlaps = Array.Empty<IntervalTreeNode<ulong, MemoryPermission>>();
  488. int count;
  489. lock (_protections)
  490. {
  491. count = _protections.Get(address, endAddress, ref overlaps);
  492. }
  493. ulong startAddress = address;
  494. for (int index = 0; index < count; index++)
  495. {
  496. var protection = overlaps[index];
  497. ulong protAddress = protection.Start;
  498. ulong protEndAddress = protection.End;
  499. if (protAddress < address)
  500. {
  501. protAddress = address;
  502. }
  503. if (protEndAddress > endAddress)
  504. {
  505. protEndAddress = endAddress;
  506. }
  507. ReprotectViewInternal((IntPtr)protAddress, (IntPtr)(protEndAddress - protAddress), protection.Value, true);
  508. }
  509. }
  510. /// <summary>
  511. /// Checks if an access violation handler should retry execution due to a fault caused by partial unmap.
  512. /// </summary>
  513. /// <remarks>
  514. /// Due to Windows limitations, <see cref="UnmapView"/> might need to unmap more memory than requested.
  515. /// The additional memory that was unmapped is later remapped, however this leaves a time gap where the
  516. /// memory might be accessed but is unmapped. Users of the API must compensate for that by catching the
  517. /// access violation and retrying if it happened between the unmap and remap operation.
  518. /// This method can be used to decide if retrying in such cases is necessary or not.
  519. /// </remarks>
  520. /// <returns>True if execution should be retried, false otherwise</returns>
  521. public bool RetryFromAccessViolation()
  522. {
  523. _partialUnmapLock.AcquireReaderLock(Timeout.Infinite);
  524. bool retry = _threadLocalPartialUnmapsCount != _partialUnmapsCount;
  525. if (retry)
  526. {
  527. _threadLocalPartialUnmapsCount = _partialUnmapsCount;
  528. }
  529. _partialUnmapLock.ReleaseReaderLock();
  530. return retry;
  531. }
  532. }
  533. }