sourcehook/sh_memory.h
author David Anderson <dvander@alliedmods.net>
Sat Apr 16 23:33:57 2005 +0000 (2005-04-16)
changeset 10 406d8e5ddfc4
parent 1 586787053c73
child 34 11e62a912700
permissions -rw-r--r--
Added license/author tags to files
     1 /* ======== SourceHook ========
     2 * Copyright (C) 2004-2005 Metamod:Source Development Team
     3 * No warranties of any kind
     4 *
     5 * License: zlib/libpng
     6 *
     7 * Author(s): Pavol "PM OnoTo" Marko, Scott "Damaged Soul" Ehlert
     8 * Contributors: lancevorgin, XAD, theqizmo
     9 * ============================
    10 */
    11 
    12 #ifndef __SHINT_MEMORY_H__
    13 #define __SHINT_MEMORY_H__
    14 
    15 // Feb 17 / 2005:
    16 //  Unprotect now sets to readwrite
    17 //  The vtable doesn't need to be executable anyway
    18 
    19 # if	/********/ defined _WIN32
    20 #		include <windows.h>
    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
    27 #		include <limits.h>
    28 #		ifndef PAGESIZE
    29 #			define PAGESIZE 4096
    30 #		endif
    31 #		define SH_MEM_READ PROT_READ
    32 #		define SH_MEM_WRITE PROT_WRITE
    33 #		define SH_MEM_EXEC PROT_EXEC
    34 
    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*)((int)(x) & ~(PAGESIZE-1))
    38 
    39 # else
    40 #		error Unsupported OS/Compiler
    41 # endif
    42 
    43 
    44 namespace SourceHook
    45 {
    46 	inline bool SetMemAccess(void *addr, size_t len, int access)
    47 	{
    48 # ifdef __linux__
    49 		return mprotect(SH_LALIGN(addr), len, access)==0 ? true : false;
    50 # else
    51 		DWORD tmp;
    52 		DWORD prot;
    53 		switch (access)
    54 		{
    55 		case SH_MEM_READ:
    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;
    61 		default:
    62 		case SH_MEM_READ | SH_MEM_WRITE | SH_MEM_EXEC:
    63 			prot = PAGE_EXECUTE_READWRITE; break;
    64 		}
    65 		return VirtualProtect(addr, len, prot, &tmp) ? true : false;
    66 # endif
    67 	}
    68 
    69 }
    70 
    71 #endif