From 314603bc42120c0c40571eaaa9c8f022992c70a6 Mon Sep 17 00:00:00 2001 From: Zeex Date: Mon, 2 Nov 2020 03:18:01 +0600 Subject: Fix address overflow in trampoline Allocate memory for storing the trampoline code via mmap() with MAP_32BIT flag to make sure that it stays withing 2GB range. Also, add missing calls to subhook_free() in the C test program (C++ calls it implicitly already via destructor). --- subhook_unix.c | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) (limited to 'subhook_unix.c') diff --git a/subhook_unix.c b/subhook_unix.c index 31f927e..3bde083 100644 --- a/subhook_unix.c +++ b/subhook_unix.c @@ -28,15 +28,26 @@ #include #include -void *subhook_unprotect(void *address, size_t size) { +#define SUBHOOK_CODE_PROTECT_FLAGS (PROT_READ | PROT_WRITE | PROT_EXEC) + +int subhook_unprotect(void *address, size_t size) { long pagesize; pagesize = sysconf(_SC_PAGESIZE); address = (void *)((long)address & ~(pagesize - 1)); - if (mprotect(address, size, PROT_READ | PROT_WRITE | PROT_EXEC) == 0) { - return address; - } else { - return NULL; - } + return mprotect(address, size, SUBHOOK_CODE_PROTECT_FLAGS); +} + +void *subhook_alloc_code(size_t size) { + return mmap(NULL, + size, + SUBHOOK_CODE_PROTECT_FLAGS, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT, + -1, + 0); +} + +int subhok_free_code(void *address, size_t size) { + return munmap(address, size); } -- cgit v1.1