core/sourcehook/sh_memory.h
author Scott Ehlert <ds@alliedmods.net>
Mon Apr 22 21:54:21 2013 -0500 (2013-04-22)
changeset 834 3cabb288e70a
parent 767 fd3ff8d792ce
permissions -rw-r--r--
Triggering a build.
     1 /* ======== SourceHook ========
     2 * Copyright (C) 2004-2010 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 #if SH_SYS == SH_SYS_APPLE
    47 # include <mach/mach.h>
    48 # include <mach/vm_region.h>
    49 # include <mach/mach_traps.h>
    50 #endif
    51 
    52 #include "sh_list.h"
    53 
    54 namespace SourceHook
    55 {
    56 	static inline bool GetPageBits(void *addr, int *bits)
    57 	{
    58 #if SH_SYS == SH_SYS_LINUX
    59 		// On linux, first check /proc/self/maps
    60 		unsigned long laddr = reinterpret_cast<unsigned long>(addr);
    61 
    62 		FILE *pF = fopen("/proc/self/maps", "r");
    63 		if (pF) {
    64 			// Linux /proc/self/maps -> parse
    65 			// Format:
    66 			// lower    upper    prot     stuff                 path
    67 			// 08048000-0804c000 r-xp 00000000 03:03 1010107    /bin/cat
    68 			unsigned long rlower, rupper;
    69 			char r, w, x;
    70 			while (fscanf(pF, "%lx-%lx %c%c%c", &rlower, &rupper, &r, &w, &x) != EOF) {
    71 				// Check whether we're IN THERE!
    72 				if (laddr >= rlower && laddr < rupper) {
    73 					fclose(pF);
    74 					*bits = 0;
    75 					if (r == 'r')
    76 						*bits |= SH_MEM_READ;
    77 					if (w == 'w')
    78 						*bits |= SH_MEM_WRITE;
    79 					if (x == 'x')
    80 						*bits |= SH_MEM_EXEC;
    81 					return true;
    82 				}
    83 				// Read to end of line
    84 				int c;
    85 				while ((c = fgetc(pF)) != '\n') {
    86 					if (c == EOF)
    87 						break;
    88 				}
    89 				if (c == EOF)
    90 					break;
    91 			}
    92 			fclose(pF);
    93 			return false;
    94 		}
    95 		pF = fopen("/proc/curproc/map", "r");
    96 		if (pF) {
    97 			// FreeBSD /proc/curproc/map -> parse
    98 			// 0x804800 0x805500 13 15 0xc6e18960 r-x 21 0x0 COW NC vnode
    99 			unsigned long rlower, rupper, ignoreLong;
   100 			int ignoreInt;
   101 			char r, w, x;
   102 			while (fscanf(pF, "0x%lx 0x%lx %d %d 0x%lx %c%c%c", &rlower, &rupper, &ignoreInt,
   103 						  &ignoreInt, &ignoreLong, &r, &w, &x) != EOF) {
   104 				// Check whether we're IN THERE!
   105 				if (laddr >= rlower && laddr < rupper) {
   106 					fclose(pF);
   107 					*bits = 0;
   108 					if (r == 'r')
   109 						*bits |= SH_MEM_READ;
   110 					if (r == 'w')
   111 						*bits |= SH_MEM_WRITE;
   112 					if (r == 'x')
   113 						*bits |= SH_MEM_EXEC;
   114 					return true;
   115 				}
   116 				// Read to end of line
   117 				int c;
   118 				while ((c = fgetc(pF)) != '\n') {
   119 					if (c == EOF)
   120 						break;
   121 				}
   122 				if (c == EOF)
   123 					break;
   124 			}
   125 			fclose(pF);
   126 			return false;
   127 		}
   128 		return false;
   129 #elif SH_SYS == SH_SYS_APPLE
   130 		vm_size_t ignoreSize;
   131 		vm_address_t vmaddr = (vm_address_t)addr;
   132 		vm_region_basic_info_data_t info;
   133 		vm_region_flavor_t flavor = VM_REGION_BASIC_INFO;
   134 		memory_object_name_t obj;
   135 
   136 		mach_msg_type_number_t count = VM_REGION_BASIC_INFO_COUNT;
   137 		kern_return_t kr = vm_region(mach_task_self(), &vmaddr, &ignoreSize, flavor,
   138 		                             (vm_region_info_t)&info, &count, &obj);
   139 		if (kr != KERN_SUCCESS)
   140 			return false;
   141 		*bits = 0;
   142 		if (info.protection & VM_PROT_READ)
   143 			*bits |= SH_MEM_READ;
   144 		if (info.protection & VM_PROT_WRITE)
   145 			*bits |= SH_MEM_WRITE;
   146 		if (info.protection & VM_PROT_EXECUTE)
   147 			*bits |= SH_MEM_EXEC;
   148 		return true;
   149 #elif SH_XP == SH_XP_WINAPI
   150 		SYSTEM_INFO info;
   151 		GetSystemInfo(&info);
   152 
   153 		MEMORY_BASIC_INFORMATION mem;
   154 		size_t base = size_t(addr) & ~size_t(info.dwPageSize - 1);
   155 		if (!VirtualQuery((void *)base, &mem, sizeof(mem)))
   156 			return false;
   157 		switch (mem.Protect) {
   158 			case PAGE_EXECUTE:
   159 				*bits = SH_MEM_EXEC;
   160 				break;
   161 			case PAGE_EXECUTE_READ:
   162 				*bits = SH_MEM_EXEC | SH_MEM_READ;
   163 				break;
   164 			case PAGE_EXECUTE_READWRITE:
   165 			case PAGE_EXECUTE_WRITECOPY:
   166 				*bits = SH_MEM_EXEC | SH_MEM_READ | SH_MEM_WRITE;
   167 				break;
   168 			case PAGE_NOACCESS:
   169 				*bits = 0;
   170 				break;
   171 			case PAGE_READONLY:
   172 				*bits = SH_MEM_READ;
   173 				break;
   174 			case PAGE_READWRITE:
   175 			case PAGE_WRITECOPY:
   176 				*bits = SH_MEM_READ | SH_MEM_WRITE;
   177 				break;
   178 			default:
   179 				return false;
   180 		}
   181 		return true;
   182 #endif
   183 	}
   184 
   185 	inline bool SetMemAccess(void *addr, size_t len, int access)
   186 	{
   187 # if SH_XP == SH_XP_POSIX
   188 		return mprotect(SH_LALIGN(addr), len + SH_LALDIF(addr), access)==0 ? true : false;
   189 # elif SH_XP == SH_XP_WINAPI
   190 		DWORD tmp;
   191 		DWORD prot;
   192 		switch (access)
   193 		{
   194 		case SH_MEM_READ:
   195 			prot = PAGE_READONLY; break;
   196 		case SH_MEM_READ | SH_MEM_WRITE:
   197 			prot = PAGE_READWRITE; break;
   198 		case SH_MEM_READ | SH_MEM_EXEC:
   199 			prot = PAGE_EXECUTE_READ; break;
   200 		default:
   201 		case SH_MEM_READ | SH_MEM_WRITE | SH_MEM_EXEC:
   202 			prot = PAGE_EXECUTE_READWRITE; break;
   203 		}
   204 		return VirtualProtect(addr, len, prot, &tmp) ? true : false;
   205 # endif
   206 	}
   207 
   208 	inline bool MakePageWritable(void *addr)
   209 	{
   210 		int bits;
   211 		if (GetPageBits(addr, &bits)) {
   212 			if (bits & SH_MEM_WRITE)
   213 				return true;
   214 			bits |= SH_MEM_WRITE;
   215 		} else {
   216 			bits = SH_MEM_READ | SH_MEM_WRITE | SH_MEM_EXEC;
   217 		}
   218 		return SetMemAccess(addr, sizeof(void *), bits);
   219 	}
   220 
   221 #if SH_XP == SH_XP_POSIX
   222 	namespace
   223 	{
   224 		bool g_BadReadCalled;
   225 		jmp_buf g_BadReadJmpBuf;
   226 
   227 # if SH_SYS == SH_SYS_LINUX
   228 		static void BadReadHandler(int sig)
   229 		{
   230 			if (g_BadReadCalled)
   231 				longjmp(g_BadReadJmpBuf, 1);
   232 		}
   233 # elif SH_SYS == SH_SYS_APPLE
   234 		static void BadReadHandler(int signal, siginfo_t* my_siginfo, void* my_context)	
   235 		{
   236 			if (g_BadReadCalled)
   237 				longjmp(g_BadReadJmpBuf, 1);
   238 		}
   239 # endif
   240 	}
   241 #endif
   242 
   243 	/**
   244 	*	@brief Checks whether the specified memory region is (still) accessible
   245 	*
   246 	*	@param addr The lower boundary
   247 	*	@param len Length of the region to be checked
   248 	*/
   249 	namespace
   250 	{
   251 		bool ModuleInMemory(char *addr, size_t len)
   252 		{
   253 #if SH_SYS == SH_SYS_LINUX
   254 			// On linux, first check /proc/self/maps
   255 			long lower = reinterpret_cast<long>(addr);
   256 			long upper = lower + len;
   257 
   258 			FILE *pF = fopen("/proc/self/maps", "r");
   259 			if (pF)
   260 			{
   261 				// Linux /proc/self/maps -> parse
   262 				// Format:
   263 				// lower    upper    prot     stuff                 path
   264 				// 08048000-0804c000 r-xp 00000000 03:03 1010107    /bin/cat
   265 				long rlower, rupper;
   266 				while (fscanf(pF, "%lx-%lx", &rlower, &rupper) != EOF)
   267 				{
   268 					// Check whether we're IN THERE!
   269 					if (lower >= rlower && upper <= rupper)
   270 					{
   271 						fclose(pF);
   272 						return true;
   273 					}
   274 					// Read to end of line
   275 					int c;
   276 					while ((c = fgetc(pF)) != '\n')
   277 					{
   278 						if (c == EOF)
   279 							break;
   280 					}
   281 					if (c == EOF)
   282 						break;
   283 				}
   284 				fclose(pF);
   285 				return false;
   286 			}
   287 			pF = fopen("/proc/curproc/map", "r");
   288 			if (pF)
   289 			{
   290 				// FreeBSD /proc/curproc/map -> parse
   291 				// 0x804800 0x805500 13 15 0xc6e18960 r-x 21 0x0 COW NC vnode
   292 				long rlower, rupper;
   293 				while (fscanf(pF, "0x%lx 0x%lx", &rlower, &rupper) != EOF)
   294 				{
   295 					// Check whether we're IN THERE!
   296 					if (lower >= rlower && upper <= rupper)
   297 					{
   298 						fclose(pF);
   299 						return true;
   300 					}
   301 					// Read to end of line
   302 					int c;
   303 					while ((c = fgetc(pF)) != '\n')
   304 					{
   305 						if (c == EOF)
   306 							break;
   307 					}
   308 					if (c == EOF)
   309 						break;
   310 				}
   311 				fclose(pF);
   312 				return false;
   313 			}
   314 
   315 			// Both of the above failed, try to actually read and trap sigsegv (implemented by Damaged Soul)
   316 			void(*prevHandler)(int sig);
   317 			g_BadReadCalled = true;
   318 
   319 			if (setjmp(g_BadReadJmpBuf))
   320 				return true;
   321 
   322 			prevHandler = signal(SIGSEGV, BadReadHandler);
   323 
   324 			volatile const char *p = reinterpret_cast<const char*>(addr);
   325 			char dummy;
   326 
   327 			for (size_t i = 0; i < len; i++)
   328 				dummy = p[i];
   329 
   330 			g_BadReadCalled = false;
   331 
   332 			signal(SIGSEGV, prevHandler);
   333 
   334 			return false;
   335 #elif SH_SYS == SH_SYS_APPLE
   336 			struct sigaction sa, osa;
   337 			sa.sa_sigaction = BadReadHandler;
   338 			sa.sa_flags = SA_SIGINFO | SA_RESTART;
   339 
   340 			g_BadReadCalled = true;
   341 
   342 			if (setjmp(g_BadReadJmpBuf))
   343 				return false;
   344 
   345 			if (sigaction(SIGBUS, &sa, &osa) == -1)
   346 				return false;
   347 
   348 			volatile const char *p = reinterpret_cast<const char *>(addr);
   349 			char dummy;
   350 
   351 			for (size_t i = 0; i < len; i++)
   352 				dummy = p[i];
   353 
   354 			g_BadReadCalled = false;
   355 
   356 			sigaction(SIGBUS, &osa, NULL);
   357 
   358 			return true;
   359 #elif SH_XP == SH_XP_WINAPI
   360 			// On Win32, simply use IsBadReadPtr
   361 			return !IsBadReadPtr(addr, len);
   362 #endif
   363 		}
   364 	}
   365 }
   366 
   367 #endif