PlaceholderManager.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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. RangeNode<ulong> successorNode;
  82. for (; node != null; node = successorNode)
  83. {
  84. successorNode = node.Successor;
  85. if (IsMapped(node.Value))
  86. {
  87. if (!WindowsApi.UnmapViewOfFile2(WindowsApi.CurrentProcessHandle, (IntPtr)node.Start, 2))
  88. {
  89. throw new WindowsApiException("UnmapViewOfFile2");
  90. }
  91. }
  92. _mappings.Remove(node);
  93. if (node.End >= endAddress)
  94. {
  95. break;
  96. }
  97. }
  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, updateProtection: false);
  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. UpdateProtection((ulong)location, (ulong)size, MemoryPermission.ReadAndWrite);
  149. }
  150. /// <summary>
  151. /// Splits a larger placeholder, slicing at the start and end address, for a new memory mapping.
  152. /// </summary>
  153. /// <param name="address">Address to split</param>
  154. /// <param name="size">Size of the new region</param>
  155. /// <param name="backingOffset">Offset in the shared memory that will be mapped</param>
  156. private void SplitForMap(ulong address, ulong size, ulong backingOffset)
  157. {
  158. ulong endAddress = address + size;
  159. var overlaps = new RangeNode<ulong>[InitialOverlapsSize];
  160. lock (_mappings)
  161. {
  162. int count = _mappings.GetNodes(address, endAddress, ref overlaps);
  163. Debug.Assert(count == 1);
  164. Debug.Assert(!IsMapped(overlaps[0].Value));
  165. var overlap = overlaps[0];
  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, updateProtection: true);
  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. /// <param name="updateProtection">Indicates if the memory protections should be updated after the unmap</param>
  238. /// <exception cref="WindowsApiException">Thrown when the Windows API returns an error unmapping or remapping the memory</exception>
  239. private void UnmapViewInternal(IntPtr sharedMemory, IntPtr location, IntPtr size, MemoryBlock owner, bool updateProtection)
  240. {
  241. ulong startAddress = (ulong)location;
  242. ulong unmapSize = (ulong)size;
  243. ulong endAddress = startAddress + unmapSize;
  244. var overlaps = new RangeNode<ulong>[InitialOverlapsSize];
  245. int count;
  246. lock (_mappings)
  247. {
  248. count = _mappings.GetNodes(startAddress, endAddress, ref overlaps);
  249. }
  250. for (int index = 0; index < count; index++)
  251. {
  252. var overlap = overlaps[index];
  253. if (IsMapped(overlap.Value))
  254. {
  255. lock (_mappings)
  256. {
  257. _mappings.Remove(overlap);
  258. _mappings.Add(new RangeNode<ulong>(overlap.Start, overlap.End, ulong.MaxValue));
  259. }
  260. bool overlapStartsBefore = overlap.Start < startAddress;
  261. bool overlapEndsAfter = overlap.End > endAddress;
  262. if (overlapStartsBefore || overlapEndsAfter)
  263. {
  264. // If the overlap extends beyond the region we are unmapping,
  265. // then we need to re-map the regions that are supposed to remain mapped.
  266. // This is necessary because Windows does not support partial view unmaps.
  267. // That is, you can only fully unmap a view that was previously mapped, you can't just unmap a chunck of it.
  268. ref var partialUnmapState = ref GetPartialUnmapState();
  269. ref var partialUnmapLock = ref partialUnmapState.PartialUnmapLock;
  270. partialUnmapLock.UpgradeToWriterLock();
  271. try
  272. {
  273. partialUnmapState.PartialUnmapsCount++;
  274. if (!WindowsApi.UnmapViewOfFile2(WindowsApi.CurrentProcessHandle, (IntPtr)overlap.Start, 2))
  275. {
  276. throw new WindowsApiException("UnmapViewOfFile2");
  277. }
  278. if (overlapStartsBefore)
  279. {
  280. ulong remapSize = startAddress - overlap.Start;
  281. MapViewInternal(sharedMemory, overlap.Value, (IntPtr)overlap.Start, (IntPtr)remapSize);
  282. RestoreRangeProtection(overlap.Start, remapSize);
  283. }
  284. if (overlapEndsAfter)
  285. {
  286. ulong overlappedSize = endAddress - overlap.Start;
  287. ulong remapBackingOffset = overlap.Value + overlappedSize;
  288. ulong remapAddress = overlap.Start + overlappedSize;
  289. ulong remapSize = overlap.End - endAddress;
  290. MapViewInternal(sharedMemory, remapBackingOffset, (IntPtr)remapAddress, (IntPtr)remapSize);
  291. RestoreRangeProtection(remapAddress, remapSize);
  292. }
  293. }
  294. finally
  295. {
  296. partialUnmapLock.DowngradeFromWriterLock();
  297. }
  298. }
  299. else if (!WindowsApi.UnmapViewOfFile2(WindowsApi.CurrentProcessHandle, (IntPtr)overlap.Start, 2))
  300. {
  301. throw new WindowsApiException("UnmapViewOfFile2");
  302. }
  303. }
  304. }
  305. CoalesceForUnmap(startAddress, unmapSize, owner);
  306. if (updateProtection)
  307. {
  308. UpdateProtection(startAddress, unmapSize, MemoryPermission.None);
  309. }
  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. int unmappedCount = 0;
  323. lock (_mappings)
  324. {
  325. RangeNode<ulong> node = _mappings.GetNode(new RangeNode<ulong>(address, address + 1UL, default));
  326. if (node == null)
  327. {
  328. // Nothing to coalesce if we have no overlaps.
  329. return;
  330. }
  331. RangeNode<ulong> predecessor = node.Predecessor;
  332. RangeNode<ulong> successor = null;
  333. for (; node != null; node = successor)
  334. {
  335. successor = node.Successor;
  336. var overlap = node;
  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. if (node.End >= endAddress)
  345. {
  346. break;
  347. }
  348. }
  349. if (predecessor != null && !IsMapped(predecessor.Value) && predecessor.Start >= blockAddress)
  350. {
  351. address = Math.Min(address, predecessor.Start);
  352. _mappings.Remove(predecessor);
  353. unmappedCount++;
  354. }
  355. if (successor != null && !IsMapped(successor.Value) && successor.End <= blockEnd)
  356. {
  357. endAddress = Math.Max(endAddress, successor.End);
  358. _mappings.Remove(successor);
  359. unmappedCount++;
  360. }
  361. _mappings.Add(new RangeNode<ulong>(address, endAddress, ulong.MaxValue));
  362. }
  363. if (unmappedCount > 1)
  364. {
  365. size = endAddress - address;
  366. CheckFreeResult(WindowsApi.VirtualFree(
  367. (IntPtr)address,
  368. (IntPtr)size,
  369. AllocationType.Release | AllocationType.CoalescePlaceholders));
  370. }
  371. }
  372. /// <summary>
  373. /// Reprotects a region of memory that has been mapped.
  374. /// </summary>
  375. /// <param name="address">Address of the region to reprotect</param>
  376. /// <param name="size">Size of the region to reprotect in bytes</param>
  377. /// <param name="permission">New permissions</param>
  378. /// <returns>True if the reprotection was successful, false otherwise</returns>
  379. public bool ReprotectView(IntPtr address, IntPtr size, MemoryPermission permission)
  380. {
  381. ref var partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock;
  382. partialUnmapLock.AcquireReaderLock();
  383. try
  384. {
  385. return ReprotectViewInternal(address, size, permission, false);
  386. }
  387. finally
  388. {
  389. partialUnmapLock.ReleaseReaderLock();
  390. }
  391. }
  392. /// <summary>
  393. /// Reprotects a region of memory that has been mapped.
  394. /// </summary>
  395. /// <param name="address">Address of the region to reprotect</param>
  396. /// <param name="size">Size of the region to reprotect in bytes</param>
  397. /// <param name="permission">New permissions</param>
  398. /// <param name="throwOnError">Throw an exception instead of returning an error if the operation fails</param>
  399. /// <returns>True if the reprotection was successful or if <paramref name="throwOnError"/> is true, false otherwise</returns>
  400. /// <exception cref="WindowsApiException">If <paramref name="throwOnError"/> is true, it is thrown when the Windows API returns an error reprotecting the memory</exception>
  401. private bool ReprotectViewInternal(IntPtr address, IntPtr size, MemoryPermission permission, bool throwOnError)
  402. {
  403. ulong reprotectAddress = (ulong)address;
  404. ulong reprotectSize = (ulong)size;
  405. ulong endAddress = reprotectAddress + reprotectSize;
  406. bool success = true;
  407. lock (_mappings)
  408. {
  409. RangeNode<ulong> node = _mappings.GetNode(new RangeNode<ulong>(reprotectAddress, reprotectAddress + 1UL, default));
  410. RangeNode<ulong> successorNode;
  411. for (; node != null; node = successorNode)
  412. {
  413. successorNode = node.Successor;
  414. var overlap = node;
  415. ulong mappedAddress = overlap.Start;
  416. ulong mappedSize = overlap.End - overlap.Start;
  417. if (mappedAddress < reprotectAddress)
  418. {
  419. ulong delta = reprotectAddress - mappedAddress;
  420. mappedAddress = reprotectAddress;
  421. mappedSize -= delta;
  422. }
  423. ulong mappedEndAddress = mappedAddress + mappedSize;
  424. if (mappedEndAddress > endAddress)
  425. {
  426. ulong delta = mappedEndAddress - endAddress;
  427. mappedSize -= delta;
  428. }
  429. if (!WindowsApi.VirtualProtect((IntPtr)mappedAddress, (IntPtr)mappedSize, WindowsApi.GetProtection(permission), out _))
  430. {
  431. if (throwOnError)
  432. {
  433. throw new WindowsApiException("VirtualProtect");
  434. }
  435. success = false;
  436. }
  437. if (node.End >= endAddress)
  438. {
  439. break;
  440. }
  441. }
  442. }
  443. UpdateProtection(reprotectAddress, reprotectSize, permission);
  444. return success;
  445. }
  446. /// <summary>
  447. /// Checks the result of a VirtualFree operation, throwing if needed.
  448. /// </summary>
  449. /// <param name="success">Operation result</param>
  450. /// <exception cref="WindowsApiException">Thrown if <paramref name="success"/> is false</exception>
  451. private static void CheckFreeResult(bool success)
  452. {
  453. if (!success)
  454. {
  455. throw new WindowsApiException("VirtualFree");
  456. }
  457. }
  458. /// <summary>
  459. /// Adds an offset to a backing offset. This will do nothing if the backing offset is the special "unmapped" value.
  460. /// </summary>
  461. /// <param name="backingOffset">Backing offset</param>
  462. /// <param name="offset">Offset to be added</param>
  463. /// <returns>Added offset or just <paramref name="backingOffset"/> if the region is unmapped</returns>
  464. private static ulong AddBackingOffset(ulong backingOffset, ulong offset)
  465. {
  466. if (backingOffset == ulong.MaxValue)
  467. {
  468. return backingOffset;
  469. }
  470. return backingOffset + offset;
  471. }
  472. /// <summary>
  473. /// Checks if a region is unmapped.
  474. /// </summary>
  475. /// <param name="backingOffset">Backing offset to check</param>
  476. /// <returns>True if the backing offset is the special "unmapped" value, false otherwise</returns>
  477. private static bool IsMapped(ulong backingOffset)
  478. {
  479. return backingOffset != ulong.MaxValue;
  480. }
  481. /// <summary>
  482. /// Adds a protection to the list of protections.
  483. /// </summary>
  484. /// <param name="address">Address of the protected region</param>
  485. /// <param name="size">Size of the protected region in bytes</param>
  486. /// <param name="permission">Memory permissions of the region</param>
  487. private void UpdateProtection(ulong address, ulong size, MemoryPermission permission)
  488. {
  489. ulong endAddress = address + size;
  490. lock (_protections)
  491. {
  492. RangeNode<MemoryPermission> node = _protections.GetNode(new RangeNode<MemoryPermission>(address, address + 1UL, default));
  493. if (node != null &&
  494. node.Start <= address &&
  495. node.End >= endAddress &&
  496. node.Value == permission)
  497. {
  498. return;
  499. }
  500. RangeNode<MemoryPermission> successorNode;
  501. ulong startAddress = address;
  502. for (; node != null; node = successorNode)
  503. {
  504. successorNode = node.Successor;
  505. var protection = node;
  506. ulong protAddress = protection.Start;
  507. ulong protEndAddress = protection.End;
  508. MemoryPermission protPermission = protection.Value;
  509. _protections.Remove(protection);
  510. if (protection.Value == permission)
  511. {
  512. if (startAddress > protAddress)
  513. {
  514. startAddress = protAddress;
  515. }
  516. if (endAddress < protEndAddress)
  517. {
  518. endAddress = protEndAddress;
  519. }
  520. }
  521. else
  522. {
  523. if (startAddress > protAddress)
  524. {
  525. _protections.Add(new RangeNode<MemoryPermission>(protAddress, startAddress, protPermission));
  526. }
  527. if (endAddress < protEndAddress)
  528. {
  529. _protections.Add(new RangeNode<MemoryPermission>(endAddress, protEndAddress, protPermission));
  530. }
  531. }
  532. if (node.End >= endAddress)
  533. {
  534. break;
  535. }
  536. }
  537. _protections.Add(new RangeNode<MemoryPermission>(startAddress, endAddress, permission));
  538. }
  539. }
  540. /// <summary>
  541. /// Removes protection from the list of protections.
  542. /// </summary>
  543. /// <param name="address">Address of the protected region</param>
  544. /// <param name="size">Size of the protected region in bytes</param>
  545. private void RemoveProtection(ulong address, ulong size)
  546. {
  547. ulong endAddress = address + size;
  548. lock (_protections)
  549. {
  550. RangeNode<MemoryPermission> node = _protections.GetNode(new RangeNode<MemoryPermission>(address, address + 1UL, default));
  551. RangeNode<MemoryPermission> successorNode;
  552. for (; node != null; node = successorNode)
  553. {
  554. successorNode = node.Successor;
  555. var protection = node;
  556. ulong protAddress = protection.Start;
  557. ulong protEndAddress = protection.End;
  558. MemoryPermission protPermission = protection.Value;
  559. _protections.Remove(protection);
  560. if (address > protAddress)
  561. {
  562. _protections.Add(new RangeNode<MemoryPermission>(protAddress, address, protPermission));
  563. }
  564. if (endAddress < protEndAddress)
  565. {
  566. _protections.Add(new RangeNode<MemoryPermission>(endAddress, protEndAddress, protPermission));
  567. }
  568. if (node.End >= endAddress)
  569. {
  570. break;
  571. }
  572. }
  573. }
  574. }
  575. /// <summary>
  576. /// Restores the protection of a given memory region that was remapped, using the protections list.
  577. /// </summary>
  578. /// <param name="address">Address of the remapped region</param>
  579. /// <param name="size">Size of the remapped region in bytes</param>
  580. private void RestoreRangeProtection(ulong address, ulong size)
  581. {
  582. ulong endAddress = address + size;
  583. var overlaps = new RangeNode<MemoryPermission>[InitialOverlapsSize];
  584. int count;
  585. lock (_protections)
  586. {
  587. count = _protections.GetNodes(address, endAddress, ref overlaps);
  588. }
  589. ulong startAddress = address;
  590. for (int index = 0; index < count; index++)
  591. {
  592. var protection = overlaps[index];
  593. // If protection is R/W we don't need to reprotect as views are initially mapped as R/W.
  594. if (protection.Value == MemoryPermission.ReadAndWrite)
  595. {
  596. continue;
  597. }
  598. ulong protAddress = protection.Start;
  599. ulong protEndAddress = protection.End;
  600. if (protAddress < address)
  601. {
  602. protAddress = address;
  603. }
  604. if (protEndAddress > endAddress)
  605. {
  606. protEndAddress = endAddress;
  607. }
  608. ReprotectViewInternal((IntPtr)protAddress, (IntPtr)(protEndAddress - protAddress), protection.Value, true);
  609. }
  610. }
  611. }
  612. }