From f83a700f54a1c3241ec4dc6249f604bbe9d5325e Mon Sep 17 00:00:00 2001 From: zilmar Date: Thu, 28 Apr 2016 17:27:17 +1000 Subject: [PATCH] [Common] Make MemoryManagement.cpp more Android friendly --- Source/Common/MemoryManagement.cpp | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/Source/Common/MemoryManagement.cpp b/Source/Common/MemoryManagement.cpp index 50d2e66dd..e528c2d61 100644 --- a/Source/Common/MemoryManagement.cpp +++ b/Source/Common/MemoryManagement.cpp @@ -1,7 +1,12 @@ #include "stdafx.h" +#ifdef _WIN32 #include +#else +#include +#endif #include "MemoryManagement.h" +#ifdef _WIN32 static bool TranslateFromMemProtect(MEM_PROTECTION memProtection, int & OsMemProtection) { switch (memProtection) @@ -29,34 +34,64 @@ static bool TranslateToMemProtect(int OsMemProtection, MEM_PROTECTION & memProte } return true; } +#endif void* AllocateAddressSpace(size_t size) { +#ifdef _WIN32 return VirtualAlloc(NULL, size, MEM_RESERVE | MEM_TOP_DOWN, PAGE_NOACCESS); +#else + void * ptr = mmap((void*)0, size, PROT_NONE, MAP_PRIVATE|MAP_ANON, -1, 0); + msync(ptr, size, MS_SYNC|MS_INVALIDATE); + return ptr; +#endif } bool FreeAddressSpace(void* addr, size_t size) { +#ifdef _WIN32 return VirtualFree(addr, 0, MEM_RELEASE) != 0; +#else + msync(addr, size, MS_SYNC); + munmap(addr, size); +#endif } void* CommitMemory(void* addr, size_t size, MEM_PROTECTION memProtection) { +#ifdef _WIN32 int OsMemProtection; if (!TranslateFromMemProtect(memProtection, OsMemProtection)) { return NULL; } return VirtualAlloc(addr, size, MEM_COMMIT, OsMemProtection); +#else + void * ptr = mmap(addr, size, PROT_READ|PROT_WRITE, MAP_FIXED|MAP_SHARED|MAP_ANON, -1, 0); + msync(addr, size, MS_SYNC|MS_INVALIDATE); + return ptr; +#endif } bool DecommitMemory(void* addr, size_t size) { +#ifdef _WIN32 return VirtualFree((void*)addr, size, MEM_DECOMMIT) != 0; +#else + // instead of unmapping the address, we're just gonna trick + // the TLB to mark this as a new mapped area which, due to + // demand paging, will not be committed until used. + + mmap(addr, size, PROT_NONE, MAP_FIXED|MAP_PRIVATE|MAP_ANON, -1, 0); + msync(addr, size, MS_SYNC|MS_INVALIDATE); + + return true; +#endif } bool ProtectMemory(void* addr, size_t size, MEM_PROTECTION memProtection, MEM_PROTECTION * OldProtect) { +#ifdef _WIN32 int OsMemProtection; if (!TranslateFromMemProtect(memProtection, OsMemProtection)) { @@ -73,4 +108,7 @@ bool ProtectMemory(void* addr, size_t size, MEM_PROTECTION memProtection, MEM_PR } } return res != 0; +#else + return false; +#endif } \ No newline at end of file