PlaceholderManager.cs 29 KB

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