PlaceholderManager.cs 28 KB

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