-
Notifications
You must be signed in to change notification settings - Fork 1
/
memory.cpp
47 lines (42 loc) · 1.2 KB
/
memory.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <nall/memory.hpp>
namespace nall::memory {
NALL_HEADER_INLINE auto map(u32 size, bool executable) -> void* {
#if defined(API_WINDOWS)
DWORD protect = executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
return VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, protect);
#elif defined(API_POSIX)
int prot = PROT_READ | PROT_WRITE;
int flags = MAP_ANON | MAP_PRIVATE;
if(executable) {
prot |= PROT_EXEC;
#if defined(PLATFORM_MACOS)
flags |= MAP_JIT;
#endif
}
return mmap(nullptr, size, prot, flags, -1, 0);
#else
return nullptr;
#endif
}
NALL_HEADER_INLINE auto unmap(void* target, u32 size) -> void {
#if defined(API_WINDOWS)
VirtualFree(target, 0, MEM_RELEASE);
#elif defined(API_POSIX)
munmap(target, size);
#endif
}
NALL_HEADER_INLINE auto protect(void* target, u32 size, bool executable) -> void {
#if defined(API_WINDOWS)
DWORD protect = executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
DWORD oldProtect;
VirtualProtect(target, size, protect, &oldProtect);
#elif defined(API_POSIX)
int prot = PROT_READ | PROT_WRITE;
if(executable) {
prot |= PROT_EXEC;
}
int ret = mprotect(target, size, prot);
assert(ret == 0);
#endif
}
}