PlaceholderManager.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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. }
  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 = new RangeNode<ulong>[InitialOverlapsSize];
  75. int count;
  76. lock (_mappings)
  77. {
  78. count = _mappings.GetNodes(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 = new RangeNode<ulong>[InitialOverlapsSize];
  159. lock (_mappings)
  160. {
  161. int count = _mappings.GetNodes(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(new RangeNode<ulong>(overlapStart, address, overlapValue));
  179. _mappings.Add(new RangeNode<ulong>(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(new RangeNode<ulong>(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(new RangeNode<ulong>(endAddress, overlapEnd, AddBackingOffset(overlapValue, overlappedSize)));
  198. }
  199. _mappings.Add(new RangeNode<ulong>(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 = new RangeNode<ulong>[InitialOverlapsSize];
  244. int count;
  245. lock (_mappings)
  246. {
  247. count = _mappings.GetNodes(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(new RangeNode<ulong>(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 = new RangeNode<ulong>[InitialOverlapsSize];
  323. int unmappedCount = 0;
  324. lock (_mappings)
  325. {
  326. int count = _mappings.GetNodes(address, endAddress, ref overlaps);
  327. if (count == 0)
  328. {
  329. // Nothing to coalesce if we no overlaps.
  330. return;
  331. }
  332. RangeNode<ulong> predecessor = overlaps[0].Predecessor;
  333. RangeNode<ulong> successor = overlaps[count - 1].Successor;
  334. for (int index = 0; index < count; index++)
  335. {
  336. var overlap = overlaps[index];
  337. if (!IsMapped(overlap.Value))
  338. {
  339. address = Math.Min(address, overlap.Start);
  340. endAddress = Math.Max(endAddress, overlap.End);
  341. _mappings.Remove(overlap);
  342. unmappedCount++;
  343. }
  344. }
  345. if (predecessor != null && !IsMapped(predecessor.Value) && predecessor.Start >= blockAddress)
  346. {
  347. address = Math.Min(address, predecessor.Start);
  348. _mappings.Remove(predecessor);
  349. unmappedCount++;
  350. }
  351. if (successor != null && !IsMapped(successor.Value) && successor.End <= blockEnd)
  352. {
  353. endAddress = Math.Max(endAddress, successor.End);
  354. _mappings.Remove(successor);
  355. unmappedCount++;
  356. }
  357. _mappings.Add(new RangeNode<ulong>(address, endAddress, ulong.MaxValue));
  358. }
  359. if (unmappedCount > 1)
  360. {
  361. size = endAddress - address;
  362. CheckFreeResult(WindowsApi.VirtualFree(
  363. (IntPtr)address,
  364. (IntPtr)size,
  365. AllocationType.Release | AllocationType.CoalescePlaceholders));
  366. }
  367. }
  368. /// <summary>
  369. /// Reprotects a region of memory that has been mapped.
  370. /// </summary>
  371. /// <param name="address">Address of the region to reprotect</param>
  372. /// <param name="size">Size of the region to reprotect in bytes</param>
  373. /// <param name="permission">New permissions</param>
  374. /// <returns>True if the reprotection was successful, false otherwise</returns>
  375. public bool ReprotectView(IntPtr address, IntPtr size, MemoryPermission permission)
  376. {
  377. ref var partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock;
  378. partialUnmapLock.AcquireReaderLock();
  379. try
  380. {
  381. return ReprotectViewInternal(address, size, permission, false);
  382. }
  383. finally
  384. {
  385. partialUnmapLock.ReleaseReaderLock();
  386. }
  387. }
  388. /// <summary>
  389. /// Reprotects a region of memory that has been mapped.
  390. /// </summary>
  391. /// <param name="address">Address of the region to reprotect</param>
  392. /// <param name="size">Size of the region to reprotect in bytes</param>
  393. /// <param name="permission">New permissions</param>
  394. /// <param name="throwOnError">Throw an exception instead of returning an error if the operation fails</param>
  395. /// <returns>True if the reprotection was successful or if <paramref name="throwOnError"/> is true, false otherwise</returns>
  396. /// <exception cref="WindowsApiException">If <paramref name="throwOnError"/> is true, it is thrown when the Windows API returns an error reprotecting the memory</exception>
  397. private bool ReprotectViewInternal(IntPtr address, IntPtr size, MemoryPermission permission, bool throwOnError)
  398. {
  399. ulong reprotectAddress = (ulong)address;
  400. ulong reprotectSize = (ulong)size;
  401. ulong endAddress = reprotectAddress + reprotectSize;
  402. var overlaps = new RangeNode<ulong>[InitialOverlapsSize];
  403. int count;
  404. lock (_mappings)
  405. {
  406. count = _mappings.GetNodes(reprotectAddress, endAddress, ref overlaps);
  407. }
  408. bool success = true;
  409. for (int index = 0; index < count; index++)
  410. {
  411. var overlap = overlaps[index];
  412. ulong mappedAddress = overlap.Start;
  413. ulong mappedSize = overlap.End - overlap.Start;
  414. if (mappedAddress < reprotectAddress)
  415. {
  416. ulong delta = reprotectAddress - mappedAddress;
  417. mappedAddress = reprotectAddress;
  418. mappedSize -= delta;
  419. }
  420. ulong mappedEndAddress = mappedAddress + mappedSize;
  421. if (mappedEndAddress > endAddress)
  422. {
  423. ulong delta = mappedEndAddress - endAddress;
  424. mappedSize -= delta;
  425. }
  426. if (!WindowsApi.VirtualProtect((IntPtr)mappedAddress, (IntPtr)mappedSize, WindowsApi.GetProtection(permission), out _))
  427. {
  428. if (throwOnError)
  429. {
  430. throw new WindowsApiException("VirtualProtect");
  431. }
  432. success = false;
  433. }
  434. // We only keep track of "non-standard" protections,
  435. // that is, everything that is not just RW (which is the default when views are mapped).
  436. if (permission == MemoryPermission.ReadAndWrite)
  437. {
  438. RemoveProtection(mappedAddress, mappedSize);
  439. }
  440. else
  441. {
  442. AddProtection(mappedAddress, mappedSize, permission);
  443. }
  444. }
  445. return success;
  446. }
  447. /// <summary>
  448. /// Checks the result of a VirtualFree operation, throwing if needed.
  449. /// </summary>
  450. /// <param name="success">Operation result</param>
  451. /// <exception cref="WindowsApiException">Thrown if <paramref name="success"/> is false</exception>
  452. private static void CheckFreeResult(bool success)
  453. {
  454. if (!success)
  455. {
  456. throw new WindowsApiException("VirtualFree");
  457. }
  458. }
  459. /// <summary>
  460. /// Adds an offset to a backing offset. This will do nothing if the backing offset is the special "unmapped" value.
  461. /// </summary>
  462. /// <param name="backingOffset">Backing offset</param>
  463. /// <param name="offset">Offset to be added</param>
  464. /// <returns>Added offset or just <paramref name="backingOffset"/> if the region is unmapped</returns>
  465. private static ulong AddBackingOffset(ulong backingOffset, ulong offset)
  466. {
  467. if (backingOffset == ulong.MaxValue)
  468. {
  469. return backingOffset;
  470. }
  471. return backingOffset + offset;
  472. }
  473. /// <summary>
  474. /// Checks if a region is unmapped.
  475. /// </summary>
  476. /// <param name="backingOffset">Backing offset to check</param>
  477. /// <returns>True if the backing offset is the special "unmapped" value, false otherwise</returns>
  478. private static bool IsMapped(ulong backingOffset)
  479. {
  480. return backingOffset != ulong.MaxValue;
  481. }
  482. /// <summary>
  483. /// Adds a protection to the list of protections.
  484. /// </summary>
  485. /// <param name="address">Address of the protected region</param>
  486. /// <param name="size">Size of the protected region in bytes</param>
  487. /// <param name="permission">Memory permissions of the region</param>
  488. private void AddProtection(ulong address, ulong size, MemoryPermission permission)
  489. {
  490. ulong endAddress = address + size;
  491. var overlaps = new RangeNode<MemoryPermission>[InitialOverlapsSize];
  492. int count;
  493. lock (_protections)
  494. {
  495. count = _protections.GetNodes(address, endAddress, ref overlaps);
  496. if (count == 1 &&
  497. overlaps[0].Start <= address &&
  498. overlaps[0].End >= endAddress &&
  499. overlaps[0].Value == permission)
  500. {
  501. return;
  502. }
  503. ulong startAddress = address;
  504. for (int index = 0; index < count; index++)
  505. {
  506. var protection = overlaps[index];
  507. ulong protAddress = protection.Start;
  508. ulong protEndAddress = protection.End;
  509. MemoryPermission protPermission = protection.Value;
  510. _protections.Remove(protection);
  511. if (protection.Value == permission)
  512. {
  513. if (startAddress > protAddress)
  514. {
  515. startAddress = protAddress;
  516. }
  517. if (endAddress < protEndAddress)
  518. {
  519. endAddress = protEndAddress;
  520. }
  521. }
  522. else
  523. {
  524. if (startAddress > protAddress)
  525. {
  526. _protections.Add(new RangeNode<MemoryPermission>(protAddress, startAddress, protPermission));
  527. }
  528. if (endAddress < protEndAddress)
  529. {
  530. _protections.Add(new RangeNode<MemoryPermission>(endAddress, protEndAddress, protPermission));
  531. }
  532. }
  533. }
  534. _protections.Add(new RangeNode<MemoryPermission>(startAddress, endAddress, permission));
  535. }
  536. }
  537. /// <summary>
  538. /// Removes protection from the list of protections.
  539. /// </summary>
  540. /// <param name="address">Address of the protected region</param>
  541. /// <param name="size">Size of the protected region in bytes</param>
  542. private void RemoveProtection(ulong address, ulong size)
  543. {
  544. ulong endAddress = address + size;
  545. var overlaps = new RangeNode<MemoryPermission>[InitialOverlapsSize];
  546. int count;
  547. lock (_protections)
  548. {
  549. count = _protections.GetNodes(address, endAddress, ref overlaps);
  550. for (int index = 0; index < count; index++)
  551. {
  552. var protection = overlaps[index];
  553. ulong protAddress = protection.Start;
  554. ulong protEndAddress = protection.End;
  555. MemoryPermission protPermission = protection.Value;
  556. _protections.Remove(protection);
  557. if (address > protAddress)
  558. {
  559. _protections.Add(new RangeNode<MemoryPermission>(protAddress, address, protPermission));
  560. }
  561. if (endAddress < protEndAddress)
  562. {
  563. _protections.Add(new RangeNode<MemoryPermission>(endAddress, protEndAddress, protPermission));
  564. }
  565. }
  566. }
  567. }
  568. /// <summary>
  569. /// Restores the protection of a given memory region that was remapped, using the protections list.
  570. /// </summary>
  571. /// <param name="address">Address of the remapped region</param>
  572. /// <param name="size">Size of the remapped region in bytes</param>
  573. private void RestoreRangeProtection(ulong address, ulong size)
  574. {
  575. ulong endAddress = address + size;
  576. var overlaps = new RangeNode<MemoryPermission>[InitialOverlapsSize];
  577. int count;
  578. lock (_protections)
  579. {
  580. count = _protections.GetNodes(address, endAddress, ref overlaps);
  581. }
  582. ulong startAddress = address;
  583. for (int index = 0; index < count; index++)
  584. {
  585. var protection = overlaps[index];
  586. ulong protAddress = protection.Start;
  587. ulong protEndAddress = protection.End;
  588. if (protAddress < address)
  589. {
  590. protAddress = address;
  591. }
  592. if (protEndAddress > endAddress)
  593. {
  594. protEndAddress = endAddress;
  595. }
  596. ReprotectViewInternal((IntPtr)protAddress, (IntPtr)(protEndAddress - protAddress), protection.Value, true);
  597. }
  598. }
  599. }
  600. }