2015-08-26 15:18:01 +00:00
|
|
|
#include "stdafx.h"
|
2015-10-17 17:47:18 +00:00
|
|
|
#include "Utilities/Log.h"
|
2015-08-26 15:18:01 +00:00
|
|
|
#include "VirtualMemory.h"
|
|
|
|
#ifdef _WIN32
|
|
|
|
#include <Windows.h>
|
|
|
|
#else
|
|
|
|
#include <sys/mman.h>
|
|
|
|
#include <sys/stat.h>
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include <sys/types.h>
|
|
|
|
#endif
|
|
|
|
|
|
|
|
namespace memory_helper
|
|
|
|
{
|
|
|
|
void* reserve_memory(size_t size)
|
|
|
|
{
|
|
|
|
#ifdef _WIN32
|
2015-10-23 14:42:34 +00:00
|
|
|
void* ret = VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_NOACCESS);
|
|
|
|
if (ret == NULL)
|
|
|
|
{
|
|
|
|
LOG_ERROR(HLE, "reserve_memory VirtualAlloc failed.");
|
|
|
|
return (void*)VM_FAILURE;
|
|
|
|
}
|
2015-08-26 15:18:01 +00:00
|
|
|
#else
|
2015-10-23 14:42:34 +00:00
|
|
|
void* ret = mmap(nullptr, size, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0);
|
|
|
|
if (ret == (void*)VM_FAILURE)
|
|
|
|
{
|
|
|
|
LOG_ERROR(HLE, "reserve_memory mmap failed.");
|
|
|
|
}
|
2015-08-26 15:18:01 +00:00
|
|
|
#endif
|
2015-10-23 14:42:34 +00:00
|
|
|
return ret;
|
2015-08-26 15:18:01 +00:00
|
|
|
}
|
|
|
|
|
2015-10-17 17:47:18 +00:00
|
|
|
s32 commit_page_memory(void* pointer, size_t page_size)
|
2015-08-26 15:18:01 +00:00
|
|
|
{
|
|
|
|
#ifdef _WIN32
|
2015-10-17 17:47:18 +00:00
|
|
|
if (VirtualAlloc((u8*)pointer, page_size, MEM_COMMIT, PAGE_READWRITE) == NULL)
|
|
|
|
{
|
|
|
|
LOG_ERROR(HLE, "commit_page_memory VirtualAlloc failed.");
|
2015-10-23 14:42:34 +00:00
|
|
|
return VM_FAILURE;
|
2015-10-17 17:47:18 +00:00
|
|
|
}
|
2015-08-26 15:18:01 +00:00
|
|
|
#else
|
2015-10-23 14:42:34 +00:00
|
|
|
s32 ret = mprotect((u8*)pointer, page_size, PROT_READ | PROT_WRITE);
|
|
|
|
if (ret < VM_SUCCESS)
|
2015-10-17 17:47:18 +00:00
|
|
|
{
|
|
|
|
LOG_ERROR(HLE, "commit_page_memory mprotect failed. (%d)", ret);
|
2015-10-23 14:42:34 +00:00
|
|
|
return VM_FAILURE;
|
2015-10-17 17:47:18 +00:00
|
|
|
}
|
2015-08-26 15:18:01 +00:00
|
|
|
#endif
|
2015-10-23 14:42:34 +00:00
|
|
|
return VM_SUCCESS;
|
2015-08-26 15:18:01 +00:00
|
|
|
}
|
|
|
|
|
2015-10-23 14:42:34 +00:00
|
|
|
s32 free_reserved_memory(void* pointer, size_t size)
|
2015-08-26 15:18:01 +00:00
|
|
|
{
|
|
|
|
#ifdef _WIN32
|
2015-10-23 14:42:34 +00:00
|
|
|
if (VirtualFree(pointer, 0, MEM_RELEASE) == 0)
|
|
|
|
{
|
|
|
|
LOG_ERROR(HLE, "free_reserved_memory VirtualFree failed.");
|
|
|
|
return VM_FAILURE;
|
|
|
|
}
|
2015-08-26 15:18:01 +00:00
|
|
|
#else
|
2015-10-23 14:42:34 +00:00
|
|
|
if (munmap(pointer, size) != VM_SUCCESS)
|
|
|
|
{
|
|
|
|
LOG_ERROR(HLE, "free_reserved_memory munmap failed.");
|
|
|
|
return VM_FAILURE;
|
|
|
|
}
|
2015-08-26 15:18:01 +00:00
|
|
|
#endif
|
2015-10-23 14:42:34 +00:00
|
|
|
return VM_SUCCESS;
|
2015-08-26 15:18:01 +00:00
|
|
|
}
|
2015-09-26 20:46:04 +00:00
|
|
|
}
|