project64/Source/Common/MemoryManagement.cpp

76 lines
2.0 KiB
C++
Raw Normal View History

2016-01-13 09:39:23 +00:00
#include "stdafx.h"
#include <windows.h>
#include "MemoryManagement.h"
2016-01-17 05:54:08 +00:00
static bool TranslateFromMemProtect(MEM_PROTECTION memProtection, int & OsMemProtection)
2016-01-13 09:39:23 +00:00
{
2016-01-17 05:54:08 +00:00
switch (memProtection)
{
case MEM_NOACCESS: OsMemProtection = PAGE_NOACCESS; break;
case MEM_READONLY: OsMemProtection = PAGE_READONLY; break;
case MEM_READWRITE: OsMemProtection = PAGE_READWRITE; break;
case MEM_EXECUTE_READWRITE: OsMemProtection = PAGE_EXECUTE_READWRITE; break;
default:
return false;
}
return true;
2016-01-13 09:39:23 +00:00
}
static bool TranslateToMemProtect(int OsMemProtection, MEM_PROTECTION & memProtection)
{
switch (OsMemProtection)
{
case PAGE_NOACCESS: memProtection = MEM_NOACCESS; break;
case PAGE_READONLY: memProtection = MEM_READONLY; break;
case PAGE_READWRITE: memProtection = MEM_READWRITE; break;
case PAGE_EXECUTE_READWRITE: memProtection = MEM_EXECUTE_READWRITE; break;
default:
return false;
}
return true;
}
2016-01-13 09:39:23 +00:00
void* AllocateAddressSpace(size_t size)
{
2016-01-17 05:54:08 +00:00
return VirtualAlloc(NULL, size, MEM_RESERVE | MEM_TOP_DOWN, PAGE_NOACCESS);
2016-01-13 09:39:23 +00:00
}
bool FreeAddressSpace(void* addr, size_t size)
{
2016-01-17 05:54:08 +00:00
return VirtualFree(addr, 0, MEM_RELEASE) != 0;
2016-01-13 09:39:23 +00:00
}
void* CommitMemory(void* addr, size_t size, MEM_PROTECTION memProtection)
{
2016-01-17 05:54:08 +00:00
int OsMemProtection;
if (!TranslateFromMemProtect(memProtection, OsMemProtection))
{
return NULL;
}
return VirtualAlloc(addr, size, MEM_COMMIT, OsMemProtection);
2016-01-13 09:39:23 +00:00
}
bool DecommitMemory(void* addr, size_t size)
{
return VirtualFree((void*)addr, size, MEM_DECOMMIT) != 0;
}
bool ProtectMemory(void* addr, size_t size, MEM_PROTECTION memProtection, MEM_PROTECTION * OldProtect)
{
2016-01-17 05:54:08 +00:00
int OsMemProtection;
if (!TranslateFromMemProtect(memProtection, OsMemProtection))
{
return NULL;
}
2016-01-13 09:39:23 +00:00
2016-01-17 05:54:08 +00:00
DWORD OldOsProtect;
2016-01-13 09:39:23 +00:00
BOOL res = VirtualProtect(addr, size, OsMemProtection, &OldOsProtect);
2016-01-17 05:54:08 +00:00
if (OldProtect != NULL)
{
if (!TranslateToMemProtect(OldOsProtect, *OldProtect))
{
return NULL;
}
2016-01-17 05:54:08 +00:00
}
return res != 0;
}