sourcehook/sh_memory.h
author Pavol Marko <pavolmarko@gmail.com>
Thu Apr 14 16:17:40 2005 +0000 (2005-04-14)
changeset 3 5a9efd949f83
parent 1 586787053c73
child 10 406d8e5ddfc4
permissions -rw-r--r--
Fixed bugs with multiple and virtual inheritance
     1 /* ======== SourceMod ========
     2 * Copyright (C) 2004-2005 SourceMod Development Team
     3 * No warranties of any kind
     4 *
     5 * File: shint_memory.h
     6 *     Memory unprotection
     7 *
     8 * License: See LICENSE.txt
     9 *
    10 * Author(s): PM, Damaged Soul
    11 * Contributors: lancevorgin, XAD, theqizmo, Damaged-Soul
    12 * ============================
    13 */
    14 
    15 #ifndef __SHINT_MEMORY_H__
    16 #define __SHINT_MEMORY_H__
    17 
    18 // Feb 17 / 2005:
    19 //  Unprotect now sets to readwrite
    20 //  The vtable doesn't need to be executable anyway
    21 
    22 # if	/********/ defined _WIN32
    23 #		include <windows.h>
    24 #		define SH_MEM_READ 1
    25 #		define SH_MEM_WRITE 2
    26 #		define SH_MEM_EXEC 4
    27 # elif /******/ defined __linux__
    28 #		include <sys/mman.h>
    29 // http://www.die.net/doc/linux/man/man2/mprotect.2.html
    30 #		include <limits.h>
    31 #		ifndef PAGESIZE
    32 #			define PAGESIZE 4096
    33 #		endif
    34 #		define SH_MEM_READ PROT_READ
    35 #		define SH_MEM_WRITE PROT_WRITE
    36 #		define SH_MEM_EXEC PROT_EXEC
    37 
    38 // We need to align addr down to pagesize on linux
    39 // We assume PAGESIZE is a power of two
    40 #		define SH_LALIGN(x) (void*)((int)(x) & ~(PAGESIZE-1))
    41 
    42 # else
    43 #		error Unsupported OS/Compiler
    44 # endif
    45 
    46 
    47 namespace SourceHook
    48 {
    49 	inline bool SetMemAccess(void *addr, size_t len, int access)
    50 	{
    51 # ifdef __linux__
    52 		return mprotect(SH_LALIGN(addr), len, access)==0 ? true : false;
    53 # else
    54 		DWORD tmp;
    55 		DWORD prot;
    56 		switch (access)
    57 		{
    58 		case SH_MEM_READ:
    59 			prot = PAGE_READONLY; break;
    60 		case SH_MEM_READ | SH_MEM_WRITE:
    61 			prot = PAGE_READWRITE; break;
    62 		case SH_MEM_READ | SH_MEM_EXEC:
    63 			prot = PAGE_EXECUTE_READ; break;
    64 		default:
    65 		case SH_MEM_READ | SH_MEM_WRITE | SH_MEM_EXEC:
    66 			prot = PAGE_EXECUTE_READWRITE; break;
    67 		}
    68 		return VirtualProtect(addr, len, prot, &tmp) ? true : false;
    69 # endif
    70 	}
    71 
    72 }
    73 
    74 #endif