PlaceholderManager.cs 29 KB

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