core/sourcehook/sh_memory.h
author Scott Ehlert <ds@alliedmods.net>
Wed May 19 04:14:49 2010 -0500 (2010-05-19)
changeset 715 54fdca12a34a
parent 684 8015336442cb
child 733 2365240861a2
permissions -rw-r--r--
Updated .hgignore to ignore dylib binaries on OS X.
     1 /* ======== SourceHook ========
     2 * Copyright (C) 2004-2008 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 SH_XP == SH_XP_WINAPI
    20 #		include <windows.h>
    21 #		define SH_MEM_READ 1
    22 #		define SH_MEM_WRITE 2
    23 #		define SH_MEM_EXEC 4
    24 # elif SH_XP == SH_XP_POSIX
    25 #		include <sys/mman.h>
    26 #		include <stdio.h>
    27 #		include <signal.h>
    28 #		include <setjmp.h>
    29 #		include <stdint.h>
    30 // http://www.die.net/doc/linux/man/man2/mprotect.2.html
    31 #		include <limits.h>
    32 #		ifndef PAGESIZE
    33 #			define PAGESIZE 4096
    34 #		endif
    35 #		define SH_MEM_READ PROT_READ
    36 #		define SH_MEM_WRITE PROT_WRITE
    37 #		define SH_MEM_EXEC PROT_EXEC
    38 
    39 // We need to align addr down to pagesize on linux
    40 // We assume PAGESIZE is a power of two
    41 #		define SH_LALIGN(x) (void*)((uintptr_t)(x) & ~(PAGESIZE-1))
    42 #		define SH_LALDIF(x) ((uintptr_t)(x) % PAGESIZE)
    43 # else
    44 #		error Unsupported OS/Compiler
    45 # endif
    46 
    47 #include "sh_list.h"
    48 
    49 namespace SourceHook
    50 {
    51 	inline bool SetMemAccess(void *addr, size_t len, int access)
    52 	{
    53 # if SH_XP == SH_XP_POSIX
    54 		return mprotect(SH_LALIGN(addr), len + SH_LALDIF(addr), access)==0 ? true : false;
    55 # elif SH_XP == SH_XP_WINAPI
    56 		DWORD tmp;
    57 		DWORD prot;
    58 		switch (access)
    59 		{
    60 		case SH_MEM_READ:
    61 			prot = PAGE_READONLY; break;
    62 		case SH_MEM_READ | SH_MEM_WRITE:
    63 			prot = PAGE_READWRITE; break;
    64 		case SH_MEM_READ | SH_MEM_EXEC:
    65 			prot = PAGE_EXECUTE_READ; break;
    66 		default:
    67 		case SH_MEM_READ | SH_MEM_WRITE | SH_MEM_EXEC:
    68 			prot = PAGE_EXECUTE_READWRITE; break;
    69 		}
    70 		return VirtualProtect(addr, len, prot, &tmp) ? true : false;
    71 # endif
    72 	}
    73 
    74 #if SH_XP == SH_XP_POSIX
    75 	namespace
    76 	{
    77 		bool g_BadReadCalled;
    78 		jmp_buf g_BadReadJmpBuf;
    79 
    80 # if SH_SYS == SH_SYS_LINUX
    81 		static void BadReadHandler(int sig)
    82 		{
    83 			if (g_BadReadCalled)
    84 				longjmp(g_BadReadJmpBuf, 1);
    85 		}
    86 # elif SH_SYS == SH_SYS_APPLE
    87 		static void BadReadHandler(int signal, siginfo_t* my_siginfo, void* my_context)	
    88 		{
    89 			if (g_BadReadCalled)
    90 				longjmp(g_BadReadJmpBuf, 1);
    91 		}
    92 # endif
    93 	}
    94 #endif
    95 
    96 	/**
    97 	*	@brief Checks whether the specified memory region is (still) accessible
    98 	*
    99 	*	@param addr The lower boundary
   100 	*	@param len Length of the region to be checked
   101 	*/
   102 	namespace
   103 	{
   104 		bool ModuleInMemory(char *addr, size_t len)
   105 		{
   106 #if SH_SYS == SH_SYS_LINUX
   107 			// On linux, first check /proc/self/maps
   108 			long lower = reinterpret_cast<long>(addr);
   109 			long upper = lower + len;
   110 
   111 			FILE *pF = fopen("/proc/self/maps", "r");
   112 			if (pF)
   113 			{
   114 				// Linux /proc/self/maps -> parse
   115 				// Format:
   116 				// lower    upper    prot     stuff                 path
   117 				// 08048000-0804c000 r-xp 00000000 03:03 1010107    /bin/cat
   118 				long rlower, rupper;
   119 				while (fscanf(pF, "%lx-%lx", &rlower, &rupper) != EOF)
   120 				{
   121 					// Check whether we're IN THERE!
   122 					if (lower >= rlower && upper <= rupper)
   123 					{
   124 						fclose(pF);
   125 						return true;
   126 					}
   127 					// Read to end of line
   128 					int c;
   129 					while ((c = fgetc(pF)) != '\n')
   130 					{
   131 						if (c == EOF)
   132 							break;
   133 					}
   134 					if (c == EOF)
   135 						break;
   136 				}
   137 				fclose(pF);
   138 				return false;
   139 			}
   140 			pF = fopen("/proc/curproc/map", "r");
   141 			if (pF)
   142 			{
   143 				// FreeBSD /proc/curproc/map -> parse
   144 				// 0x804800 0x805500 13 15 0xc6e18960 r-x 21 0x0 COW NC vnode
   145 				long rlower, rupper;
   146 				while (fscanf(pF, "0x%lx 0x%lx", &rlower, &rupper) != EOF)
   147 				{
   148 					// Check whether we're IN THERE!
   149 					if (lower >= rlower && upper <= rupper)
   150 					{
   151 						fclose(pF);
   152 						return true;
   153 					}
   154 					// Read to end of line
   155 					int c;
   156 					while ((c = fgetc(pF)) != '\n')
   157 					{
   158 						if (c == EOF)
   159 							break;
   160 					}
   161 					if (c == EOF)
   162 						break;
   163 				}
   164 				fclose(pF);
   165 				return false;
   166 			}
   167 
   168 			// Both of the above failed, try to actually read and trap sigsegv (implemented by Damaged Soul)
   169 			void(*prevHandler)(int sig);
   170 			g_BadReadCalled = true;
   171 
   172 			if (setjmp(g_BadReadJmpBuf))
   173 				return true;
   174 
   175 			prevHandler = signal(SIGSEGV, BadReadHandler);
   176 
   177 			volatile const char *p = reinterpret_cast<const char*>(addr);
   178 			char dummy;
   179 
   180 			for (size_t i = 0; i < len; i++)
   181 				dummy = p[i];
   182 
   183 			g_BadReadCalled = false;
   184 
   185 			signal(SIGSEGV, prevHandler);
   186 
   187 			return false;
   188 #elif SH_SYS == SH_SYS_APPLE
   189 			struct sigaction sa, osa;
   190 			sa.sa_sigaction = BadReadHandler;
   191 			sa.sa_flags = SA_SIGINFO | SA_RESTART;
   192 
   193 			g_BadReadCalled = true;
   194 
   195 			if (setjmp(g_BadReadJmpBuf))
   196 				return false;
   197 
   198 			if (sigaction(SIGBUS, &sa, &osa) == -1)
   199 				return false;
   200 
   201 			volatile const char *p = reinterpret_cast<const char *>(addr);
   202 			char dummy;
   203 
   204 			for (size_t i = 0; i < len; i++)
   205 				dummy = p[i];
   206 
   207 			g_BadReadCalled = false;
   208 
   209 			sigaction(SIGBUS, &osa, NULL);
   210 
   211 			return true;
   212 #elif SH_XP == SH_XP_WINAPI
   213 			// On Win32, simply use IsBadReadPtr
   214 			return !IsBadReadPtr(addr, len);
   215 #endif
   216 		}
   217 	}
   218 }
   219 
   220 #endif