1 /* ======== SourceHook ========
2 * Copyright (C) 2004-2005 Metamod:Source Development Team
3 * No warranties of any kind
7 * Author(s): Pavol "PM OnoTo" Marko, Scott "Damaged Soul" Ehlert
8 * Contributors: lancevorgin, XAD, theqizmo
9 * ============================
12 #ifndef __SHINT_MEMORY_H__
13 #define __SHINT_MEMORY_H__
16 // Unprotect now sets to readwrite
17 // The vtable doesn't need to be executable anyway
19 # if /********/ defined _WIN32
21 # define SH_MEM_READ 1
22 # define SH_MEM_WRITE 2
23 # define SH_MEM_EXEC 4
24 # elif /******/ defined __linux__
25 # include <sys/mman.h>
26 // http://www.die.net/doc/linux/man/man2/mprotect.2.html
29 # define PAGESIZE 4096
31 # define SH_MEM_READ PROT_READ
32 # define SH_MEM_WRITE PROT_WRITE
33 # define SH_MEM_EXEC PROT_EXEC
35 // We need to align addr down to pagesize on linux
36 // We assume PAGESIZE is a power of two
37 # define SH_LALIGN(x) (void*)((intptr_t)(x) & ~(PAGESIZE-1))
38 # define SH_LALDIF(x) ((intptr_t)(x) & (PAGESIZE-1))
40 # error Unsupported OS/Compiler
46 inline bool SetMemAccess(void *addr, size_t len, int access)
49 return mprotect(SH_LALIGN(addr), len + SH_LALDIF(addr), access)==0 ? true : false;
56 prot = PAGE_READONLY; break;
57 case SH_MEM_READ | SH_MEM_WRITE:
58 prot = PAGE_READWRITE; break;
59 case SH_MEM_READ | SH_MEM_EXEC:
60 prot = PAGE_EXECUTE_READ; break;
62 case SH_MEM_READ | SH_MEM_WRITE | SH_MEM_EXEC:
63 prot = PAGE_EXECUTE_READWRITE; break;
65 return VirtualProtect(addr, len, prot, &tmp) ? true : false;