AMemoryWin32.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace ChocolArm64.Memory
  4. {
  5. static class AMemoryWin32
  6. {
  7. private const int MEM_COMMIT = 0x00001000;
  8. private const int MEM_RESERVE = 0x00002000;
  9. private const int MEM_WRITE_WATCH = 0x00200000;
  10. private const int PAGE_READWRITE = 0x04;
  11. private const int MEM_RELEASE = 0x8000;
  12. private const int WRITE_WATCH_FLAG_RESET = 1;
  13. [DllImport("kernel32.dll")]
  14. private static extern IntPtr VirtualAlloc(IntPtr lpAddress, IntPtr dwSize, int flAllocationType, int flProtect);
  15. [DllImport("kernel32.dll")]
  16. private static extern bool VirtualFree(IntPtr lpAddress, IntPtr dwSize, int dwFreeType);
  17. [DllImport("kernel32.dll")]
  18. private unsafe static extern int GetWriteWatch(
  19. int dwFlags,
  20. IntPtr lpBaseAddress,
  21. IntPtr dwRegionSize,
  22. IntPtr[] lpAddresses,
  23. long* lpdwCount,
  24. long* lpdwGranularity);
  25. public static IntPtr Allocate(IntPtr Size)
  26. {
  27. const int Flags = MEM_COMMIT | MEM_RESERVE | MEM_WRITE_WATCH;
  28. IntPtr Address = VirtualAlloc(IntPtr.Zero, Size, Flags, PAGE_READWRITE);
  29. if (Address == IntPtr.Zero)
  30. {
  31. throw new InvalidOperationException();
  32. }
  33. return Address;
  34. }
  35. public static void Free(IntPtr Address)
  36. {
  37. VirtualFree(Address, IntPtr.Zero, MEM_RELEASE);
  38. }
  39. public unsafe static long IsRegionModified(IntPtr Address, IntPtr Size, bool Reset)
  40. {
  41. IntPtr[] Addresses = new IntPtr[1];
  42. long Count = Addresses.Length;
  43. long Granularity;
  44. int Flags = Reset ? WRITE_WATCH_FLAG_RESET : 0;
  45. GetWriteWatch(
  46. Flags,
  47. Address,
  48. Size,
  49. Addresses,
  50. &Count,
  51. &Granularity);
  52. return Count != 0 ? Granularity : 0;
  53. }
  54. }
  55. }