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