PlaceholderManager.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. using Ryujinx.Common.Memory.PartialUnmaps;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Runtime.CompilerServices;
  5. using System.Runtime.Versioning;
  6. using System.Threading;
  7. namespace Ryujinx.Memory.WindowsShared
  8. {
  9. /// <summary>
  10. /// Windows memory placeholder manager.
  11. /// </summary>
  12. [SupportedOSPlatform("windows")]
  13. class PlaceholderManager
  14. {
  15. private const int InitialOverlapsSize = 10;
  16. private readonly MappingTree<ulong> _mappings;
  17. private readonly MappingTree<MemoryPermission> _protections;
  18. private readonly IntPtr _partialUnmapStatePtr;
  19. private readonly Thread _partialUnmapTrimThread;
  20. /// <summary>
  21. /// Creates a new instance of the Windows memory placeholder manager.
  22. /// </summary>
  23. public PlaceholderManager()
  24. {
  25. _mappings = new MappingTree<ulong>();
  26. _protections = new MappingTree<MemoryPermission>();
  27. _partialUnmapStatePtr = PartialUnmapState.GlobalState;
  28. _partialUnmapTrimThread = new Thread(TrimThreadLocalMapLoop);
  29. _partialUnmapTrimThread.Name = "CPU.PartialUnmapTrimThread";
  30. _partialUnmapTrimThread.IsBackground = true;
  31. _partialUnmapTrimThread.Start();
  32. }
  33. /// <summary>
  34. /// Gets a reference to the partial unmap state struct.
  35. /// </summary>
  36. /// <returns>A reference to the partial unmap state struct</returns>
  37. private unsafe ref PartialUnmapState GetPartialUnmapState()
  38. {
  39. return ref Unsafe.AsRef<PartialUnmapState>((void*)_partialUnmapStatePtr);
  40. }
  41. /// <summary>
  42. /// Trims inactive threads from the partial unmap state's thread mapping every few seconds.
  43. /// Should be run in a Background thread so that it doesn't stop the program from closing.
  44. /// </summary>
  45. private void TrimThreadLocalMapLoop()
  46. {
  47. while (true)
  48. {
  49. Thread.Sleep(2000);
  50. GetPartialUnmapState().TrimThreads();
  51. }
  52. }
  53. /// <summary>
  54. /// Reserves a range of the address space to be later mapped as shared memory views.
  55. /// </summary>
  56. /// <param name="address">Start address of the region to reserve</param>
  57. /// <param name="size">Size in bytes of the region to reserve</param>
  58. public void ReserveRange(ulong address, ulong size)
  59. {
  60. lock (_mappings)
  61. {
  62. _mappings.Add(new RangeNode<ulong>(address, address + size, ulong.MaxValue));
  63. }
  64. lock (_protections)
  65. {
  66. _protections.Add(new RangeNode<MemoryPermission>(address, size, MemoryPermission.None));
  67. }
  68. }
  69. /// <summary>
  70. /// Unreserves a range of memory that has been previously reserved with <see cref="ReserveRange"/>.
  71. /// </summary>
  72. /// <param name="address">Start address of the region to unreserve</param>
  73. /// <param name="size">Size in bytes of the region to unreserve</param>
  74. /// <exception cref="WindowsApiException">Thrown when the Windows API returns an error unreserving the memory</exception>
  75. public void UnreserveRange(ulong address, ulong size)
  76. {
  77. ulong endAddress = address + size;
  78. var overlaps = new RangeNode<ulong>[InitialOverlapsSize];
  79. int count;
  80. lock (_mappings)
  81. {
  82. count = _mappings.GetNodes(address, endAddress, ref overlaps);
  83. for (int index = 0; index < count; index++)
  84. {
  85. var overlap = overlaps[index];
  86. if (IsMapped(overlap.Value))
  87. {
  88. if (!WindowsApi.UnmapViewOfFile2(WindowsApi.CurrentProcessHandle, (IntPtr)overlap.Start, 2))
  89. {
  90. throw new WindowsApiException("UnmapViewOfFile2");
  91. }
  92. }
  93. _mappings.Remove(overlap);
  94. }
  95. }
  96. RemoveProtection(address, size);
  97. }
  98. /// <summary>
  99. /// Maps a shared memory view on a previously reserved memory region.
  100. /// </summary>
  101. /// <param name="sharedMemory">Shared memory that will be the backing storage for the view</param>
  102. /// <param name="srcOffset">Offset in the shared memory to map</param>
  103. /// <param name="location">Address to map the view into</param>
  104. /// <param name="size">Size of the view in bytes</param>
  105. /// <param name="owner">Memory block that owns the mapping</param>
  106. public void MapView(IntPtr sharedMemory, ulong srcOffset, IntPtr location, IntPtr size, MemoryBlock owner)
  107. {
  108. ref var partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock;
  109. partialUnmapLock.AcquireReaderLock();
  110. try
  111. {
  112. UnmapViewInternal(sharedMemory, location, size, owner, updateProtection: false);
  113. MapViewInternal(sharedMemory, srcOffset, location, size);
  114. }
  115. finally
  116. {
  117. partialUnmapLock.ReleaseReaderLock();
  118. }
  119. }
  120. /// <summary>
  121. /// Maps a shared memory view on a previously reserved memory region.
  122. /// </summary>
  123. /// <param name="sharedMemory">Shared memory that will be the backing storage for the view</param>
  124. /// <param name="srcOffset">Offset in the shared memory to map</param>
  125. /// <param name="location">Address to map the view into</param>
  126. /// <param name="size">Size of the view in bytes</param>
  127. /// <exception cref="WindowsApiException">Thrown when the Windows API returns an error mapping the memory</exception>
  128. private void MapViewInternal(IntPtr sharedMemory, ulong srcOffset, IntPtr location, IntPtr size)
  129. {
  130. SplitForMap((ulong)location, (ulong)size, srcOffset);
  131. var ptr = WindowsApi.MapViewOfFile3(
  132. sharedMemory,
  133. WindowsApi.CurrentProcessHandle,
  134. location,
  135. srcOffset,
  136. size,
  137. 0x4000,
  138. MemoryProtection.ReadWrite,
  139. IntPtr.Zero,
  140. 0);
  141. if (ptr == IntPtr.Zero)
  142. {
  143. throw new WindowsApiException("MapViewOfFile3");
  144. }
  145. UpdateProtection((ulong)location, (ulong)size, MemoryPermission.ReadAndWrite);
  146. }
  147. /// <summary>
  148. /// Splits a larger placeholder, slicing at the start and end address, for a new memory mapping.
  149. /// </summary>
  150. /// <param name="address">Address to split</param>
  151. /// <param name="size">Size of the new region</param>
  152. /// <param name="backingOffset">Offset in the shared memory that will be mapped</param>
  153. private void SplitForMap(ulong address, ulong size, ulong backingOffset)
  154. {
  155. ulong endAddress = address + size;
  156. var overlaps = new RangeNode<ulong>[InitialOverlapsSize];
  157. lock (_mappings)
  158. {
  159. int count = _mappings.GetNodes(address, endAddress, ref overlaps);
  160. Debug.Assert(count == 1);
  161. Debug.Assert(!IsMapped(overlaps[0].Value));
  162. var overlap = overlaps[0];
  163. ulong overlapStart = overlap.Start;
  164. ulong overlapEnd = overlap.End;
  165. ulong overlapValue = overlap.Value;
  166. _mappings.Remove(overlap);
  167. bool overlapStartsBefore = overlapStart < address;
  168. bool overlapEndsAfter = overlapEnd > endAddress;
  169. if (overlapStartsBefore && overlapEndsAfter)
  170. {
  171. CheckFreeResult(WindowsApi.VirtualFree(
  172. (IntPtr)address,
  173. (IntPtr)size,
  174. AllocationType.Release | AllocationType.PreservePlaceholder));
  175. _mappings.Add(new RangeNode<ulong>(overlapStart, address, overlapValue));
  176. _mappings.Add(new RangeNode<ulong>(endAddress, overlapEnd, AddBackingOffset(overlapValue, endAddress - overlapStart)));
  177. }
  178. else if (overlapStartsBefore)
  179. {
  180. ulong overlappedSize = overlapEnd - address;
  181. CheckFreeResult(WindowsApi.VirtualFree(
  182. (IntPtr)address,
  183. (IntPtr)overlappedSize,
  184. AllocationType.Release | AllocationType.PreservePlaceholder));
  185. _mappings.Add(new RangeNode<ulong>(overlapStart, address, overlapValue));
  186. }
  187. else if (overlapEndsAfter)
  188. {
  189. ulong overlappedSize = endAddress - overlapStart;
  190. CheckFreeResult(WindowsApi.VirtualFree(
  191. (IntPtr)overlapStart,
  192. (IntPtr)overlappedSize,
  193. AllocationType.Release | AllocationType.PreservePlaceholder));
  194. _mappings.Add(new RangeNode<ulong>(endAddress, overlapEnd, AddBackingOffset(overlapValue, overlappedSize)));
  195. }
  196. _mappings.Add(new RangeNode<ulong>(address, endAddress, backingOffset));
  197. }
  198. }
  199. /// <summary>
  200. /// Unmaps a view that has been previously mapped with <see cref="MapView"/>.
  201. /// </summary>
  202. /// <remarks>
  203. /// For "partial unmaps" (when not the entire mapped range is being unmapped), it might be
  204. /// necessary to unmap the whole range and then remap the sub-ranges that should remain mapped.
  205. /// </remarks>
  206. /// <param name="sharedMemory">Shared memory that the view being unmapped belongs to</param>
  207. /// <param name="location">Address to unmap</param>
  208. /// <param name="size">Size of the region to unmap in bytes</param>
  209. /// <param name="owner">Memory block that owns the mapping</param>
  210. public void UnmapView(IntPtr sharedMemory, IntPtr location, IntPtr size, MemoryBlock owner)
  211. {
  212. ref var partialUnmapLock = ref GetPartialUnmapState().PartialUnmapLock;
  213. partialUnmapLock.AcquireReaderLock();
  214. try
  215. {
  216. UnmapViewInternal(sharedMemory, location, size, owner, updateProtection: true);
  217. }
  218. finally
  219. {
  220. partialUnmapLock.ReleaseReaderLock();
  221. }
  222. }
  223. /// <summary>
  224. /// Unmaps a view that has been previously mapped with <see cref="MapView"/>.
  225. /// </summary>
  226. /// <remarks>
  227. /// For "partial unmaps" (when not the entire mapped range is being unmapped), it might be
  228. /// necessary to unmap the whole range and then remap the sub-ranges that should remain mapped.
  229. /// </remarks>
  230. /// <param name="sharedMemory">Shared memory that the view being unmapped belongs to</param>
  231. /// <param name="location">Address to unmap</param>
  232. /// <param name="size">Size of the region to unmap in bytes</param>
  233. /// <param name="owner">Memory block that owns the mapping</param>
  234. /// <param name="updateProtection">Indicates if the memory protections should be updated after the unmap</param>
  235. /// <exception cref="WindowsApiException">Thrown when the Windows API returns an error unmapping or remapping the memory</exception>
  236. private void UnmapViewInternal(IntPtr sharedMemory, IntPtr location, IntPtr size, MemoryBlock owner, bool updateProtection)
  237. {
  238. ulong startAddress = (ulong)location;
  239. ulong unmapSize = (ulong)size;
  240. ulong endAddress = startAddress + unmapSize;
  241. var overlaps = new RangeNode<ulong>[InitialOverlapsSize];
  242. int count;
  243. lock (_mappings)
  244. {
  245. count = _mappings.GetNodes(startAddress, endAddress, ref overlaps);
  246. }
  247. for (int index = 0; index < count; index++)
  248. {
  249. var overlap = overlaps[index];
  250. if (IsMapped(overlap.Value))
  251. {
  252. ulong overlapStart = overlap.Start;
  253. ulong overlapEnd = overlap.End;
  254. ulong overlapValue = overlap.Value;
  255. lock (_mappings)
  256. {
  257. _mappings.Remove(overlap);
  258. _mappings.Add(new RangeNode<ulong>(overlapStart, overlapEnd, ulong.MaxValue));
  259. }
  260. bool overlapStartsBefore = overlapStart < startAddress;
  261. bool overlapEndsAfter = overlapEnd > 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)overlapStart, 2))
  275. {
  276. throw new WindowsApiException("UnmapViewOfFile2");
  277. }
  278. if (overlapStartsBefore)
  279. {
  280. ulong remapSize = startAddress - overlapStart;
  281. MapViewInternal(sharedMemory, overlapValue, (IntPtr)overlapStart, (IntPtr)remapSize);
  282. RestoreRangeProtection(overlapStart, remapSize);
  283. }
  284. if (overlapEndsAfter)
  285. {
  286. ulong overlappedSize = endAddress - overlapStart;
  287. ulong remapBackingOffset = overlapValue + overlappedSize;
  288. ulong remapAddress = overlapStart + overlappedSize;
  289. ulong remapSize = overlapEnd - 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)overlapStart, 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. 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. }
  435. UpdateProtection(reprotectAddress, reprotectSize, permission);
  436. return success;
  437. }
  438. /// <summary>
  439. /// Checks the result of a VirtualFree operation, throwing if needed.
  440. /// </summary>
  441. /// <param name="success">Operation result</param>
  442. /// <exception cref="WindowsApiException">Thrown if <paramref name="success"/> is false</exception>
  443. private static void CheckFreeResult(bool success)
  444. {
  445. if (!success)
  446. {
  447. throw new WindowsApiException("VirtualFree");
  448. }
  449. }
  450. /// <summary>
  451. /// Adds an offset to a backing offset. This will do nothing if the backing offset is the special "unmapped" value.
  452. /// </summary>
  453. /// <param name="backingOffset">Backing offset</param>
  454. /// <param name="offset">Offset to be added</param>
  455. /// <returns>Added offset or just <paramref name="backingOffset"/> if the region is unmapped</returns>
  456. private static ulong AddBackingOffset(ulong backingOffset, ulong offset)
  457. {
  458. if (backingOffset == ulong.MaxValue)
  459. {
  460. return backingOffset;
  461. }
  462. return backingOffset + offset;
  463. }
  464. /// <summary>
  465. /// Checks if a region is unmapped.
  466. /// </summary>
  467. /// <param name="backingOffset">Backing offset to check</param>
  468. /// <returns>True if the backing offset is the special "unmapped" value, false otherwise</returns>
  469. private static bool IsMapped(ulong backingOffset)
  470. {
  471. return backingOffset != ulong.MaxValue;
  472. }
  473. /// <summary>
  474. /// Adds a protection to the list of protections.
  475. /// </summary>
  476. /// <param name="address">Address of the protected region</param>
  477. /// <param name="size">Size of the protected region in bytes</param>
  478. /// <param name="permission">Memory permissions of the region</param>
  479. private void UpdateProtection(ulong address, ulong size, MemoryPermission permission)
  480. {
  481. ulong endAddress = address + size;
  482. var overlaps = new RangeNode<MemoryPermission>[InitialOverlapsSize];
  483. int count;
  484. lock (_protections)
  485. {
  486. count = _protections.GetNodes(address, endAddress, ref overlaps);
  487. if (count == 1 &&
  488. overlaps[0].Start <= address &&
  489. overlaps[0].End >= endAddress &&
  490. overlaps[0].Value == permission)
  491. {
  492. return;
  493. }
  494. ulong startAddress = address;
  495. for (int index = 0; index < count; index++)
  496. {
  497. var protection = overlaps[index];
  498. ulong protAddress = protection.Start;
  499. ulong protEndAddress = protection.End;
  500. MemoryPermission protPermission = protection.Value;
  501. _protections.Remove(protection);
  502. if (protection.Value == permission)
  503. {
  504. if (startAddress > protAddress)
  505. {
  506. startAddress = protAddress;
  507. }
  508. if (endAddress < protEndAddress)
  509. {
  510. endAddress = protEndAddress;
  511. }
  512. }
  513. else
  514. {
  515. if (startAddress > protAddress)
  516. {
  517. _protections.Add(new RangeNode<MemoryPermission>(protAddress, startAddress, protPermission));
  518. }
  519. if (endAddress < protEndAddress)
  520. {
  521. _protections.Add(new RangeNode<MemoryPermission>(endAddress, protEndAddress, protPermission));
  522. }
  523. }
  524. }
  525. _protections.Add(new RangeNode<MemoryPermission>(startAddress, endAddress, permission));
  526. }
  527. }
  528. /// <summary>
  529. /// Removes protection from the list of protections.
  530. /// </summary>
  531. /// <param name="address">Address of the protected region</param>
  532. /// <param name="size">Size of the protected region in bytes</param>
  533. private void RemoveProtection(ulong address, ulong size)
  534. {
  535. ulong endAddress = address + size;
  536. var overlaps = new RangeNode<MemoryPermission>[InitialOverlapsSize];
  537. int count;
  538. lock (_protections)
  539. {
  540. count = _protections.GetNodes(address, endAddress, ref overlaps);
  541. for (int index = 0; index < count; index++)
  542. {
  543. var protection = overlaps[index];
  544. ulong protAddress = protection.Start;
  545. ulong protEndAddress = protection.End;
  546. MemoryPermission protPermission = protection.Value;
  547. _protections.Remove(protection);
  548. if (address > protAddress)
  549. {
  550. _protections.Add(new RangeNode<MemoryPermission>(protAddress, address, protPermission));
  551. }
  552. if (endAddress < protEndAddress)
  553. {
  554. _protections.Add(new RangeNode<MemoryPermission>(endAddress, protEndAddress, protPermission));
  555. }
  556. }
  557. }
  558. }
  559. /// <summary>
  560. /// Restores the protection of a given memory region that was remapped, using the protections list.
  561. /// </summary>
  562. /// <param name="address">Address of the remapped region</param>
  563. /// <param name="size">Size of the remapped region in bytes</param>
  564. private void RestoreRangeProtection(ulong address, ulong size)
  565. {
  566. ulong endAddress = address + size;
  567. var overlaps = new RangeNode<MemoryPermission>[InitialOverlapsSize];
  568. int count;
  569. lock (_protections)
  570. {
  571. count = _protections.GetNodes(address, endAddress, ref overlaps);
  572. }
  573. ulong startAddress = address;
  574. for (int index = 0; index < count; index++)
  575. {
  576. var protection = overlaps[index];
  577. // If protection is R/W we don't need to reprotect as views are initially mapped as R/W.
  578. if (protection.Value == MemoryPermission.ReadAndWrite)
  579. {
  580. continue;
  581. }
  582. ulong protAddress = protection.Start;
  583. ulong protEndAddress = protection.End;
  584. if (protAddress < address)
  585. {
  586. protAddress = address;
  587. }
  588. if (protEndAddress > endAddress)
  589. {
  590. protEndAddress = endAddress;
  591. }
  592. ReprotectViewInternal((IntPtr)protAddress, (IntPtr)(protEndAddress - protAddress), protection.Value, true);
  593. }
  594. }
  595. }
  596. }