PlaceholderManager.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. using Ryujinx.Common.Memory.PartialUnmaps;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Runtime.CompilerServices;
  5. using System.Runtime.Versioning;
  6. using System.Threading;
  7. namespace Ryujinx.Memory.WindowsShared
  8. {
  9. /// <summary>
  10. /// Windows memory placeholder manager.
  11. /// </summary>
  12. [SupportedOSPlatform("windows")]
  13. class PlaceholderManager
  14. {
  15. private const int InitialOverlapsSize = 10;
  16. private readonly MappingTree<ulong> _mappings;
  17. private readonly MappingTree<MemoryPermission> _protections;
  18. private readonly IntPtr _partialUnmapStatePtr;
  19. private readonly Thread _partialUnmapTrimThread;
  20. /// <summary>
  21. /// Creates a new instance of the Windows memory placeholder manager.
  22. /// </summary>
  23. public PlaceholderManager()
  24. {
  25. _mappings = new MappingTree<ulong>();
  26. _protections = new MappingTree<MemoryPermission>();
  27. _partialUnmapStatePtr = PartialUnmapState.GlobalState;
  28. _partialUnmapTrimThread = new Thread(TrimThreadLocalMapLoop);
  29. _partialUnmapTrimThread.Name = "CPU.PartialUnmapTrimThread";
  30. _partialUnmapTrimThread.IsBackground = true;
  31. _partialUnmapTrimThread.Start();
  32. }
  33. /// <summary>
  34. /// Gets a reference to the partial unmap state struct.
  35. /// </summary>
  36. /// <returns>A reference to the partial unmap state struct</returns>
  37. private unsafe ref PartialUnmapState GetPartialUnmapState()
  38. {
  39. return ref Unsafe.AsRef<PartialUnmapState>((void*)_partialUnmapStatePtr);
  40. }
  41. /// <summary>
  42. /// Trims inactive threads from the partial unmap state's thread mapping every few seconds.
  43. /// Should be run in a Background thread so that it doesn't stop the program from closing.
  44. /// </summary>
  45. private void TrimThreadLocalMapLoop()
  46. {
  47. while (true)
  48. {
  49. Thread.Sleep(2000);
  50. GetPartialUnmapState().TrimThreads();
  51. }
  52. }
  53. /// <summary>
  54. /// Reserves a range of the address space to be later mapped as shared memory views.
  55. /// </summary>
  56. /// <param name="address">Start address of the region to reserve</param>
  57. /// <param name="size">Size in bytes of the region to reserve</param>
  58. public void ReserveRange(ulong address, ulong size)
  59. {
  60. lock (_mappings)
  61. {
  62. _mappings.Add(new RangeNode<ulong>(address, address + size, ulong.MaxValue));
  63. }
  64. lock (_protections)
  65. {
  66. _protections.Add(new RangeNode<MemoryPermission>(address, size, MemoryPermission.None));
  67. }
  68. }
  69. /// <summary>
  70. /// Unreserves a range of memory that has been previously reserved with <see cref="ReserveRange"/>.
  71. /// </summary>
  72. /// <param name="address">Start address of the region to unreserve</param>
  73. /// <param name="size">Size in bytes of the region to unreserve</param>
  74. /// <exception cref="WindowsApiException">Thrown when the Windows API returns an error unreserving the memory</exception>
  75. public void UnreserveRange(ulong address, ulong size)
  76. {
  77. ulong endAddress = address + size;
  78. lock (_mappings)
  79. {
  80. RangeNode<ulong> node = _mappings.GetNode(new RangeNode<ulong>(address, address + 1UL, default));
  81. for (; node != null; node = node.Successor)
  82. {
  83. if (IsMapped(node.Value))
  84. {
  85. if (!WindowsApi.UnmapViewOfFile2(WindowsApi.CurrentProcessHandle, (IntPtr)node.Start, 2))
  86. {
  87. throw new WindowsApiException("UnmapViewOfFile2");
  88. }
  89. }
  90. _mappings.Remove(node);
  91. if (node.End >= endAddress)
  92. {
  93. break;
  94. }
  95. }
  96. }
  97. RemoveProtection(address, size);
  98. }
  99. /// <summary>
  100. /// Maps a shared memory view on a previously reserved memory region.
  101. /// </summary>
  102. /// <param name="sharedMemory">Shared memory that will be the backing storage for the view</param>
  103. /// <param name="srcOffset">Offset in the shared memory to map</param>
  104. /// <param name="location">Address to map the view into</param>
  105. /// <param name="size">Size of the view in bytes</param>
  106. /// <param name="owner">Memory block that owns the mapping</param>
  107. public void MapView(IntPtr sharedMemory, ulong srcOffset, IntPtr location, IntPtr size, MemoryBlock owner)
  108. {
  109. ref var partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock;
  110. partialUnmapLock.AcquireReaderLock();
  111. try
  112. {
  113. UnmapViewInternal(sharedMemory, location, size, owner, updateProtection: false);
  114. MapViewInternal(sharedMemory, srcOffset, location, size);
  115. }
  116. finally
  117. {
  118. partialUnmapLock.ReleaseReaderLock();
  119. }
  120. }
  121. /// <summary>
  122. /// Maps a shared memory view on a previously reserved memory region.
  123. /// </summary>
  124. /// <param name="sharedMemory">Shared memory that will be the backing storage for the view</param>
  125. /// <param name="srcOffset">Offset in the shared memory to map</param>
  126. /// <param name="location">Address to map the view into</param>
  127. /// <param name="size">Size of the view in bytes</param>
  128. /// <exception cref="WindowsApiException">Thrown when the Windows API returns an error mapping the memory</exception>
  129. private void MapViewInternal(IntPtr sharedMemory, ulong srcOffset, IntPtr location, IntPtr size)
  130. {
  131. SplitForMap((ulong)location, (ulong)size, srcOffset);
  132. var ptr = WindowsApi.MapViewOfFile3(
  133. sharedMemory,
  134. WindowsApi.CurrentProcessHandle,
  135. location,
  136. srcOffset,
  137. size,
  138. 0x4000,
  139. MemoryProtection.ReadWrite,
  140. IntPtr.Zero,
  141. 0);
  142. if (ptr == IntPtr.Zero)
  143. {
  144. throw new WindowsApiException("MapViewOfFile3");
  145. }
  146. UpdateProtection((ulong)location, (ulong)size, MemoryPermission.ReadAndWrite);
  147. }
  148. /// <summary>
  149. /// Splits a larger placeholder, slicing at the start and end address, for a new memory mapping.
  150. /// </summary>
  151. /// <param name="address">Address to split</param>
  152. /// <param name="size">Size of the new region</param>
  153. /// <param name="backingOffset">Offset in the shared memory that will be mapped</param>
  154. private void SplitForMap(ulong address, ulong size, ulong backingOffset)
  155. {
  156. ulong endAddress = address + size;
  157. var overlaps = new RangeNode<ulong>[InitialOverlapsSize];
  158. lock (_mappings)
  159. {
  160. int count = _mappings.GetNodes(address, endAddress, ref overlaps);
  161. Debug.Assert(count == 1);
  162. Debug.Assert(!IsMapped(overlaps[0].Value));
  163. var overlap = overlaps[0];
  164. ulong overlapStart = overlap.Start;
  165. ulong overlapEnd = overlap.End;
  166. ulong overlapValue = overlap.Value;
  167. _mappings.Remove(overlap);
  168. bool overlapStartsBefore = overlapStart < address;
  169. bool overlapEndsAfter = overlapEnd > endAddress;
  170. if (overlapStartsBefore && overlapEndsAfter)
  171. {
  172. CheckFreeResult(WindowsApi.VirtualFree(
  173. (IntPtr)address,
  174. (IntPtr)size,
  175. AllocationType.Release | AllocationType.PreservePlaceholder));
  176. _mappings.Add(new RangeNode<ulong>(overlapStart, address, overlapValue));
  177. _mappings.Add(new RangeNode<ulong>(endAddress, overlapEnd, AddBackingOffset(overlapValue, endAddress - overlapStart)));
  178. }
  179. else if (overlapStartsBefore)
  180. {
  181. ulong overlappedSize = overlapEnd - address;
  182. CheckFreeResult(WindowsApi.VirtualFree(
  183. (IntPtr)address,
  184. (IntPtr)overlappedSize,
  185. AllocationType.Release | AllocationType.PreservePlaceholder));
  186. _mappings.Add(new RangeNode<ulong>(overlapStart, address, overlapValue));
  187. }
  188. else if (overlapEndsAfter)
  189. {
  190. ulong overlappedSize = endAddress - overlapStart;
  191. CheckFreeResult(WindowsApi.VirtualFree(
  192. (IntPtr)overlapStart,
  193. (IntPtr)overlappedSize,
  194. AllocationType.Release | AllocationType.PreservePlaceholder));
  195. _mappings.Add(new RangeNode<ulong>(endAddress, overlapEnd, AddBackingOffset(overlapValue, overlappedSize)));
  196. }
  197. _mappings.Add(new RangeNode<ulong>(address, endAddress, backingOffset));
  198. }
  199. }
  200. /// <summary>
  201. /// Unmaps a view that has been previously mapped with <see cref="MapView"/>.
  202. /// </summary>
  203. /// <remarks>
  204. /// For "partial unmaps" (when not the entire mapped range is being unmapped), it might be
  205. /// necessary to unmap the whole range and then remap the sub-ranges that should remain mapped.
  206. /// </remarks>
  207. /// <param name="sharedMemory">Shared memory that the view being unmapped belongs to</param>
  208. /// <param name="location">Address to unmap</param>
  209. /// <param name="size">Size of the region to unmap in bytes</param>
  210. /// <param name="owner">Memory block that owns the mapping</param>
  211. public void UnmapView(IntPtr sharedMemory, IntPtr location, IntPtr size, MemoryBlock owner)
  212. {
  213. ref var partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock;
  214. partialUnmapLock.AcquireReaderLock();
  215. try
  216. {
  217. UnmapViewInternal(sharedMemory, location, size, owner, updateProtection: true);
  218. }
  219. finally
  220. {
  221. partialUnmapLock.ReleaseReaderLock();
  222. }
  223. }
  224. /// <summary>
  225. /// Unmaps a view that has been previously mapped with <see cref="MapView"/>.
  226. /// </summary>
  227. /// <remarks>
  228. /// For "partial unmaps" (when not the entire mapped range is being unmapped), it might be
  229. /// necessary to unmap the whole range and then remap the sub-ranges that should remain mapped.
  230. /// </remarks>
  231. /// <param name="sharedMemory">Shared memory that the view being unmapped belongs to</param>
  232. /// <param name="location">Address to unmap</param>
  233. /// <param name="size">Size of the region to unmap in bytes</param>
  234. /// <param name="owner">Memory block that owns the mapping</param>
  235. /// <param name="updateProtection">Indicates if the memory protections should be updated after the unmap</param>
  236. /// <exception cref="WindowsApiException">Thrown when the Windows API returns an error unmapping or remapping the memory</exception>
  237. private void UnmapViewInternal(IntPtr sharedMemory, IntPtr location, IntPtr size, MemoryBlock owner, bool updateProtection)
  238. {
  239. ulong startAddress = (ulong)location;
  240. ulong unmapSize = (ulong)size;
  241. ulong endAddress = startAddress + unmapSize;
  242. var overlaps = new RangeNode<ulong>[InitialOverlapsSize];
  243. int count;
  244. lock (_mappings)
  245. {
  246. count = _mappings.GetNodes(startAddress, endAddress, ref overlaps);
  247. }
  248. for (int index = 0; index < count; index++)
  249. {
  250. var overlap = overlaps[index];
  251. if (IsMapped(overlap.Value))
  252. {
  253. lock (_mappings)
  254. {
  255. _mappings.Remove(overlap);
  256. _mappings.Add(new RangeNode<ulong>(overlap.Start, overlap.End, ulong.MaxValue));
  257. }
  258. bool overlapStartsBefore = overlap.Start < startAddress;
  259. bool overlapEndsAfter = overlap.End > endAddress;
  260. if (overlapStartsBefore || overlapEndsAfter)
  261. {
  262. // If the overlap extends beyond the region we are unmapping,
  263. // then we need to re-map the regions that are supposed to remain mapped.
  264. // This is necessary because Windows does not support partial view unmaps.
  265. // That is, you can only fully unmap a view that was previously mapped, you can't just unmap a chunck of it.
  266. ref var partialUnmapState = ref GetPartialUnmapState();
  267. ref var partialUnmapLock = ref partialUnmapState.PartialUnmapLock;
  268. partialUnmapLock.UpgradeToWriterLock();
  269. try
  270. {
  271. partialUnmapState.PartialUnmapsCount++;
  272. if (!WindowsApi.UnmapViewOfFile2(WindowsApi.CurrentProcessHandle, (IntPtr)overlap.Start, 2))
  273. {
  274. throw new WindowsApiException("UnmapViewOfFile2");
  275. }
  276. if (overlapStartsBefore)
  277. {
  278. ulong remapSize = startAddress - overlap.Start;
  279. MapViewInternal(sharedMemory, overlap.Value, (IntPtr)overlap.Start, (IntPtr)remapSize);
  280. RestoreRangeProtection(overlap.Start, remapSize);
  281. }
  282. if (overlapEndsAfter)
  283. {
  284. ulong overlappedSize = endAddress - overlap.Start;
  285. ulong remapBackingOffset = overlap.Value + overlappedSize;
  286. ulong remapAddress = overlap.Start + overlappedSize;
  287. ulong remapSize = overlap.End - endAddress;
  288. MapViewInternal(sharedMemory, remapBackingOffset, (IntPtr)remapAddress, (IntPtr)remapSize);
  289. RestoreRangeProtection(remapAddress, remapSize);
  290. }
  291. }
  292. finally
  293. {
  294. partialUnmapLock.DowngradeFromWriterLock();
  295. }
  296. }
  297. else if (!WindowsApi.UnmapViewOfFile2(WindowsApi.CurrentProcessHandle, (IntPtr)overlap.Start, 2))
  298. {
  299. throw new WindowsApiException("UnmapViewOfFile2");
  300. }
  301. }
  302. }
  303. CoalesceForUnmap(startAddress, unmapSize, owner);
  304. if (updateProtection)
  305. {
  306. UpdateProtection(startAddress, unmapSize, MemoryPermission.None);
  307. }
  308. }
  309. /// <summary>
  310. /// Coalesces adjacent placeholders after unmap.
  311. /// </summary>
  312. /// <param name="address">Address of the region that was unmapped</param>
  313. /// <param name="size">Size of the region that was unmapped in bytes</param>
  314. /// <param name="owner">Memory block that owns the mapping</param>
  315. private void CoalesceForUnmap(ulong address, ulong size, MemoryBlock owner)
  316. {
  317. ulong endAddress = address + size;
  318. ulong blockAddress = (ulong)owner.Pointer;
  319. ulong blockEnd = blockAddress + owner.Size;
  320. var overlaps = new RangeNode<ulong>[InitialOverlapsSize];
  321. int unmappedCount = 0;
  322. lock (_mappings)
  323. {
  324. int count = _mappings.GetNodes(address, endAddress, ref overlaps);
  325. if (count == 0)
  326. {
  327. // Nothing to coalesce if we no overlaps.
  328. return;
  329. }
  330. RangeNode<ulong> predecessor = overlaps[0].Predecessor;
  331. RangeNode<ulong> successor = overlaps[count - 1].Successor;
  332. for (int index = 0; index < count; index++)
  333. {
  334. var overlap = overlaps[index];
  335. if (!IsMapped(overlap.Value))
  336. {
  337. address = Math.Min(address, overlap.Start);
  338. endAddress = Math.Max(endAddress, overlap.End);
  339. _mappings.Remove(overlap);
  340. unmappedCount++;
  341. }
  342. }
  343. if (predecessor != null && !IsMapped(predecessor.Value) && predecessor.Start >= blockAddress)
  344. {
  345. address = Math.Min(address, predecessor.Start);
  346. _mappings.Remove(predecessor);
  347. unmappedCount++;
  348. }
  349. if (successor != null && !IsMapped(successor.Value) && successor.End <= blockEnd)
  350. {
  351. endAddress = Math.Max(endAddress, successor.End);
  352. _mappings.Remove(successor);
  353. unmappedCount++;
  354. }
  355. _mappings.Add(new RangeNode<ulong>(address, endAddress, ulong.MaxValue));
  356. }
  357. if (unmappedCount > 1)
  358. {
  359. size = endAddress - address;
  360. CheckFreeResult(WindowsApi.VirtualFree(
  361. (IntPtr)address,
  362. (IntPtr)size,
  363. AllocationType.Release | AllocationType.CoalescePlaceholders));
  364. }
  365. }
  366. /// <summary>
  367. /// Reprotects a region of memory that has been mapped.
  368. /// </summary>
  369. /// <param name="address">Address of the region to reprotect</param>
  370. /// <param name="size">Size of the region to reprotect in bytes</param>
  371. /// <param name="permission">New permissions</param>
  372. /// <returns>True if the reprotection was successful, false otherwise</returns>
  373. public bool ReprotectView(IntPtr address, IntPtr size, MemoryPermission permission)
  374. {
  375. ref var partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock;
  376. partialUnmapLock.AcquireReaderLock();
  377. try
  378. {
  379. return ReprotectViewInternal(address, size, permission, false);
  380. }
  381. finally
  382. {
  383. partialUnmapLock.ReleaseReaderLock();
  384. }
  385. }
  386. /// <summary>
  387. /// Reprotects a region of memory that has been mapped.
  388. /// </summary>
  389. /// <param name="address">Address of the region to reprotect</param>
  390. /// <param name="size">Size of the region to reprotect in bytes</param>
  391. /// <param name="permission">New permissions</param>
  392. /// <param name="throwOnError">Throw an exception instead of returning an error if the operation fails</param>
  393. /// <returns>True if the reprotection was successful or if <paramref name="throwOnError"/> is true, false otherwise</returns>
  394. /// <exception cref="WindowsApiException">If <paramref name="throwOnError"/> is true, it is thrown when the Windows API returns an error reprotecting the memory</exception>
  395. private bool ReprotectViewInternal(IntPtr address, IntPtr size, MemoryPermission permission, bool throwOnError)
  396. {
  397. ulong reprotectAddress = (ulong)address;
  398. ulong reprotectSize = (ulong)size;
  399. ulong endAddress = reprotectAddress + reprotectSize;
  400. var overlaps = new RangeNode<ulong>[InitialOverlapsSize];
  401. int count;
  402. lock (_mappings)
  403. {
  404. count = _mappings.GetNodes(reprotectAddress, endAddress, ref overlaps);
  405. }
  406. bool success = true;
  407. for (int index = 0; index < count; index++)
  408. {
  409. var overlap = overlaps[index];
  410. ulong mappedAddress = overlap.Start;
  411. ulong mappedSize = overlap.End - overlap.Start;
  412. if (mappedAddress < reprotectAddress)
  413. {
  414. ulong delta = reprotectAddress - mappedAddress;
  415. mappedAddress = reprotectAddress;
  416. mappedSize -= delta;
  417. }
  418. ulong mappedEndAddress = mappedAddress + mappedSize;
  419. if (mappedEndAddress > endAddress)
  420. {
  421. ulong delta = mappedEndAddress - endAddress;
  422. mappedSize -= delta;
  423. }
  424. if (!WindowsApi.VirtualProtect((IntPtr)mappedAddress, (IntPtr)mappedSize, WindowsApi.GetProtection(permission), out _))
  425. {
  426. if (throwOnError)
  427. {
  428. throw new WindowsApiException("VirtualProtect");
  429. }
  430. success = false;
  431. }
  432. }
  433. UpdateProtection(reprotectAddress, reprotectSize, permission);
  434. return success;
  435. }
  436. /// <summary>
  437. /// Checks the result of a VirtualFree operation, throwing if needed.
  438. /// </summary>
  439. /// <param name="success">Operation result</param>
  440. /// <exception cref="WindowsApiException">Thrown if <paramref name="success"/> is false</exception>
  441. private static void CheckFreeResult(bool success)
  442. {
  443. if (!success)
  444. {
  445. throw new WindowsApiException("VirtualFree");
  446. }
  447. }
  448. /// <summary>
  449. /// Adds an offset to a backing offset. This will do nothing if the backing offset is the special "unmapped" value.
  450. /// </summary>
  451. /// <param name="backingOffset">Backing offset</param>
  452. /// <param name="offset">Offset to be added</param>
  453. /// <returns>Added offset or just <paramref name="backingOffset"/> if the region is unmapped</returns>
  454. private static ulong AddBackingOffset(ulong backingOffset, ulong offset)
  455. {
  456. if (backingOffset == ulong.MaxValue)
  457. {
  458. return backingOffset;
  459. }
  460. return backingOffset + offset;
  461. }
  462. /// <summary>
  463. /// Checks if a region is unmapped.
  464. /// </summary>
  465. /// <param name="backingOffset">Backing offset to check</param>
  466. /// <returns>True if the backing offset is the special "unmapped" value, false otherwise</returns>
  467. private static bool IsMapped(ulong backingOffset)
  468. {
  469. return backingOffset != ulong.MaxValue;
  470. }
  471. /// <summary>
  472. /// Adds a protection to the list of protections.
  473. /// </summary>
  474. /// <param name="address">Address of the protected region</param>
  475. /// <param name="size">Size of the protected region in bytes</param>
  476. /// <param name="permission">Memory permissions of the region</param>
  477. private void UpdateProtection(ulong address, ulong size, MemoryPermission permission)
  478. {
  479. ulong endAddress = address + size;
  480. var overlaps = new RangeNode<MemoryPermission>[InitialOverlapsSize];
  481. int count;
  482. lock (_protections)
  483. {
  484. count = _protections.GetNodes(address, endAddress, ref overlaps);
  485. if (count == 1 &&
  486. overlaps[0].Start <= address &&
  487. overlaps[0].End >= endAddress &&
  488. overlaps[0].Value == permission)
  489. {
  490. return;
  491. }
  492. ulong startAddress = address;
  493. for (int index = 0; index < count; index++)
  494. {
  495. var protection = overlaps[index];
  496. ulong protAddress = protection.Start;
  497. ulong protEndAddress = protection.End;
  498. MemoryPermission protPermission = protection.Value;
  499. _protections.Remove(protection);
  500. if (protection.Value == permission)
  501. {
  502. if (startAddress > protAddress)
  503. {
  504. startAddress = protAddress;
  505. }
  506. if (endAddress < protEndAddress)
  507. {
  508. endAddress = protEndAddress;
  509. }
  510. }
  511. else
  512. {
  513. if (startAddress > protAddress)
  514. {
  515. _protections.Add(new RangeNode<MemoryPermission>(protAddress, startAddress, protPermission));
  516. }
  517. if (endAddress < protEndAddress)
  518. {
  519. _protections.Add(new RangeNode<MemoryPermission>(endAddress, protEndAddress, protPermission));
  520. }
  521. }
  522. }
  523. _protections.Add(new RangeNode<MemoryPermission>(startAddress, endAddress, permission));
  524. }
  525. }
  526. /// <summary>
  527. /// Removes protection from the list of protections.
  528. /// </summary>
  529. /// <param name="address">Address of the protected region</param>
  530. /// <param name="size">Size of the protected region in bytes</param>
  531. private void RemoveProtection(ulong address, ulong size)
  532. {
  533. ulong endAddress = address + size;
  534. var overlaps = new RangeNode<MemoryPermission>[InitialOverlapsSize];
  535. int count;
  536. lock (_protections)
  537. {
  538. count = _protections.GetNodes(address, endAddress, ref overlaps);
  539. for (int index = 0; index < count; index++)
  540. {
  541. var protection = overlaps[index];
  542. ulong protAddress = protection.Start;
  543. ulong protEndAddress = protection.End;
  544. MemoryPermission protPermission = protection.Value;
  545. _protections.Remove(protection);
  546. if (address > protAddress)
  547. {
  548. _protections.Add(new RangeNode<MemoryPermission>(protAddress, address, protPermission));
  549. }
  550. if (endAddress < protEndAddress)
  551. {
  552. _protections.Add(new RangeNode<MemoryPermission>(endAddress, protEndAddress, protPermission));
  553. }
  554. }
  555. }
  556. }
  557. /// <summary>
  558. /// Restores the protection of a given memory region that was remapped, using the protections list.
  559. /// </summary>
  560. /// <param name="address">Address of the remapped region</param>
  561. /// <param name="size">Size of the remapped region in bytes</param>
  562. private void RestoreRangeProtection(ulong address, ulong size)
  563. {
  564. ulong endAddress = address + size;
  565. var overlaps = new RangeNode<MemoryPermission>[InitialOverlapsSize];
  566. int count;
  567. lock (_protections)
  568. {
  569. count = _protections.GetNodes(address, endAddress, ref overlaps);
  570. }
  571. ulong startAddress = address;
  572. for (int index = 0; index < count; index++)
  573. {
  574. var protection = overlaps[index];
  575. // If protection is R/W we don't need to reprotect as views are initially mapped as R/W.
  576. if (protection.Value == MemoryPermission.ReadAndWrite)
  577. {
  578. continue;
  579. }
  580. ulong protAddress = protection.Start;
  581. ulong protEndAddress = protection.End;
  582. if (protAddress < address)
  583. {
  584. protAddress = address;
  585. }
  586. if (protEndAddress > endAddress)
  587. {
  588. protEndAddress = endAddress;
  589. }
  590. ReprotectViewInternal((IntPtr)protAddress, (IntPtr)(protEndAddress - protAddress), protection.Value, true);
  591. }
  592. }
  593. }
  594. }