MemoryManagementUnix.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using Mono.Unix.Native;
  2. using System;
  3. namespace ARMeilleure.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, Memory.MemoryProtection protection)
  25. {
  26. MmapProts prot = GetProtection(protection);
  27. return Syscall.mprotect(address, size, prot) == 0;
  28. }
  29. private static MmapProts GetProtection(Memory.MemoryProtection protection)
  30. {
  31. switch (protection)
  32. {
  33. case Memory.MemoryProtection.None: return MmapProts.PROT_NONE;
  34. case Memory.MemoryProtection.Read: return MmapProts.PROT_READ;
  35. case Memory.MemoryProtection.ReadAndWrite: return MmapProts.PROT_READ | MmapProts.PROT_WRITE;
  36. case Memory.MemoryProtection.ReadAndExecute: return MmapProts.PROT_READ | MmapProts.PROT_EXEC;
  37. case Memory.MemoryProtection.ReadWriteExecute: return MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC;
  38. case Memory.MemoryProtection.Execute: return MmapProts.PROT_EXEC;
  39. default: throw new ArgumentException($"Invalid permission \"{protection}\".");
  40. }
  41. }
  42. public static bool Free(IntPtr address)
  43. {
  44. ulong pageSize = (ulong)Syscall.sysconf(SysconfName._SC_PAGESIZE);
  45. ulong size;
  46. unsafe
  47. {
  48. size = *((ulong*)address - 1);
  49. address = new IntPtr(address.ToInt64() - (long)pageSize);
  50. }
  51. return Syscall.munmap(address, size + pageSize) == 0;
  52. }
  53. }
  54. }