2019-02-18 18:52:06 -05:00
|
|
|
using Mono.Unix.Native;
|
|
|
|
using System;
|
|
|
|
|
|
|
|
namespace ChocolArm64.Memory
|
|
|
|
{
|
2019-02-24 02:24:35 -05:00
|
|
|
static class MemoryManagementUnix
|
2019-02-18 18:52:06 -05:00
|
|
|
{
|
|
|
|
public static IntPtr Allocate(ulong size)
|
|
|
|
{
|
|
|
|
ulong pageSize = (ulong)Syscall.sysconf(SysconfName._SC_PAGESIZE);
|
|
|
|
|
|
|
|
const MmapProts prot = MmapProts.PROT_READ | MmapProts.PROT_WRITE;
|
|
|
|
|
|
|
|
const MmapFlags flags = MmapFlags.MAP_PRIVATE | MmapFlags.MAP_ANONYMOUS;
|
|
|
|
|
|
|
|
IntPtr ptr = Syscall.mmap(IntPtr.Zero, size + pageSize, prot, flags, -1, 0);
|
|
|
|
|
|
|
|
if (ptr == IntPtr.Zero)
|
|
|
|
{
|
|
|
|
throw new OutOfMemoryException();
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe
|
|
|
|
{
|
|
|
|
ptr = new IntPtr(ptr.ToInt64() + (long)pageSize);
|
|
|
|
|
|
|
|
*((ulong*)ptr - 1) = size;
|
|
|
|
}
|
|
|
|
|
|
|
|
return ptr;
|
|
|
|
}
|
|
|
|
|
2019-07-01 22:39:22 -04:00
|
|
|
public static bool Reprotect(IntPtr address, ulong size, MemoryProtection protection)
|
2019-02-18 18:52:06 -05:00
|
|
|
{
|
|
|
|
MmapProts prot = GetProtection(protection);
|
|
|
|
|
|
|
|
return Syscall.mprotect(address, size, prot) == 0;
|
|
|
|
}
|
|
|
|
|
2019-07-01 22:39:22 -04:00
|
|
|
private static MmapProts GetProtection(MemoryProtection protection)
|
2019-02-18 18:52:06 -05:00
|
|
|
{
|
|
|
|
switch (protection)
|
|
|
|
{
|
2019-07-01 22:39:22 -04:00
|
|
|
case MemoryProtection.None: return MmapProts.PROT_NONE;
|
|
|
|
case MemoryProtection.Read: return MmapProts.PROT_READ;
|
|
|
|
case MemoryProtection.ReadAndWrite: return MmapProts.PROT_READ | MmapProts.PROT_WRITE;
|
|
|
|
case MemoryProtection.ReadAndExecute: return MmapProts.PROT_READ | MmapProts.PROT_EXEC;
|
|
|
|
case MemoryProtection.Execute: return MmapProts.PROT_EXEC;
|
2019-02-18 18:52:06 -05:00
|
|
|
|
|
|
|
default: throw new ArgumentException($"Invalid permission \"{protection}\".");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public static bool Free(IntPtr address)
|
|
|
|
{
|
|
|
|
ulong pageSize = (ulong)Syscall.sysconf(SysconfName._SC_PAGESIZE);
|
|
|
|
|
|
|
|
ulong size;
|
|
|
|
|
|
|
|
unsafe
|
|
|
|
{
|
|
|
|
size = *((ulong*)address - 1);
|
|
|
|
|
|
|
|
address = new IntPtr(address.ToInt64() - (long)pageSize);
|
|
|
|
}
|
|
|
|
|
|
|
|
return Syscall.munmap(address, size + pageSize) == 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|