MemoryManagementUnix.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using Mono.Unix.Native;
  2. using System;
  3. namespace ChocolArm64.Memory
  4. {
  5. static class MemoryManagementUnix
  6. {
  7. public static IntPtr Allocate(ulong size)
  8. {
  9. ulong pageSize = (ulong)Syscall.sysconf(SysconfName._SC_PAGESIZE);
  10. const MmapProts prot = MmapProts.PROT_READ | MmapProts.PROT_WRITE;
  11. const MmapFlags flags = MmapFlags.MAP_PRIVATE | MmapFlags.MAP_ANONYMOUS;
  12. IntPtr ptr = Syscall.mmap(IntPtr.Zero, size + pageSize, prot, flags, -1, 0);
  13. if (ptr == IntPtr.Zero)
  14. {
  15. throw new OutOfMemoryException();
  16. }
  17. unsafe
  18. {
  19. ptr = new IntPtr(ptr.ToInt64() + (long)pageSize);
  20. *((ulong*)ptr - 1) = size;
  21. }
  22. return ptr;
  23. }
  24. public static bool Reprotect(IntPtr address, ulong size, MemoryProtection protection)
  25. {
  26. MmapProts prot = GetProtection(protection);
  27. return Syscall.mprotect(address, size, prot) == 0;
  28. }
  29. private static MmapProts GetProtection(MemoryProtection protection)
  30. {
  31. switch (protection)
  32. {
  33. case MemoryProtection.None: return MmapProts.PROT_NONE;
  34. case MemoryProtection.Read: return MmapProts.PROT_READ;
  35. case MemoryProtection.ReadAndWrite: return MmapProts.PROT_READ | MmapProts.PROT_WRITE;
  36. case MemoryProtection.ReadAndExecute: return MmapProts.PROT_READ | MmapProts.PROT_EXEC;
  37. case MemoryProtection.Execute: return MmapProts.PROT_EXEC;
  38. default: throw new ArgumentException($"Invalid permission \"{protection}\".");
  39. }
  40. }
  41. public static bool Free(IntPtr address)
  42. {
  43. ulong pageSize = (ulong)Syscall.sysconf(SysconfName._SC_PAGESIZE);
  44. ulong size;
  45. unsafe
  46. {
  47. size = *((ulong*)address - 1);
  48. address = new IntPtr(address.ToInt64() - (long)pageSize);
  49. }
  50. return Syscall.munmap(address, size + pageSize) == 0;
  51. }
  52. }
  53. }