MemoryManagementUnix.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 Commit(IntPtr address, ulong size)
  25. {
  26. return Syscall.mprotect(address, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE) == 0;
  27. }
  28. public static bool Reprotect(IntPtr address, ulong size, Memory.MemoryProtection protection)
  29. {
  30. MmapProts prot = GetProtection(protection);
  31. return Syscall.mprotect(address, size, prot) == 0;
  32. }
  33. public static IntPtr Reserve(ulong size)
  34. {
  35. ulong pageSize = (ulong)Syscall.sysconf(SysconfName._SC_PAGESIZE);
  36. const MmapProts prot = MmapProts.PROT_NONE;
  37. const MmapFlags flags = MmapFlags.MAP_PRIVATE | MmapFlags.MAP_ANONYMOUS;
  38. IntPtr ptr = Syscall.mmap(IntPtr.Zero, size + pageSize, prot, flags, -1, 0);
  39. if (ptr == IntPtr.Zero)
  40. {
  41. throw new OutOfMemoryException();
  42. }
  43. return ptr;
  44. }
  45. private static MmapProts GetProtection(Memory.MemoryProtection protection)
  46. {
  47. switch (protection)
  48. {
  49. case Memory.MemoryProtection.None: return MmapProts.PROT_NONE;
  50. case Memory.MemoryProtection.Read: return MmapProts.PROT_READ;
  51. case Memory.MemoryProtection.ReadAndWrite: return MmapProts.PROT_READ | MmapProts.PROT_WRITE;
  52. case Memory.MemoryProtection.ReadAndExecute: return MmapProts.PROT_READ | MmapProts.PROT_EXEC;
  53. case Memory.MemoryProtection.ReadWriteExecute: return MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC;
  54. case Memory.MemoryProtection.Execute: return MmapProts.PROT_EXEC;
  55. default: throw new ArgumentException($"Invalid permission \"{protection}\".");
  56. }
  57. }
  58. public static bool Free(IntPtr address)
  59. {
  60. ulong pageSize = (ulong)Syscall.sysconf(SysconfName._SC_PAGESIZE);
  61. ulong size;
  62. unsafe
  63. {
  64. size = *((ulong*)address - 1);
  65. address = new IntPtr(address.ToInt64() - (long)pageSize);
  66. }
  67. return Syscall.munmap(address, size + pageSize) == 0;
  68. }
  69. }
  70. }