core/sourcehook/sh_memory.h
author David Anderson <dvander@alliedmods.net>
Mon Feb 16 15:52:46 2009 -0500 (2009-02-16)
changeset 633 153e2d943cc3
parent 539 db914129ae01
child 684 8015336442cb
permissions -rw-r--r--
Fixed mprotect() being called with invalid length values (bug 3642, r=ds).
     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	/********/ 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 #		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 # ifdef __linux__
    54 		return mprotect(SH_LALIGN(addr), len + SH_LALDIF(addr), access)==0 ? true : false;
    55 # else
    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 #ifdef __linux__
    75 	namespace
    76 	{
    77 		bool g_BadReadCalled;
    78 		jmp_buf g_BadReadJmpBuf;
    79 
    80 		static void BadReadHandler(int sig)
    81 		{
    82 			if (g_BadReadCalled)
    83 				longjmp(g_BadReadJmpBuf, 1);
    84 		}
    85 	}
    86 #endif
    87 
    88 	/**
    89 	*	@brief Checks whether the specified memory region is (still) accessible
    90 	*
    91 	*	@param addr The lower boundary
    92 	*	@param len Length of the region to be checked
    93 	*/
    94 	namespace
    95 	{
    96 		bool ModuleInMemory(char *addr, size_t len)
    97 		{
    98 #ifdef __linux__
    99 			// On linux, first check /proc/self/maps
   100 			long lower = reinterpret_cast<long>(addr);
   101 			long upper = lower + len;
   102 
   103 			FILE *pF = fopen("/proc/self/maps", "r");
   104 			if (pF)
   105 			{
   106 				// Linux /proc/self/maps -> parse
   107 				// Format:
   108 				// lower    upper    prot     stuff                 path
   109 				// 08048000-0804c000 r-xp 00000000 03:03 1010107    /bin/cat
   110 				long rlower, rupper;
   111 				while (fscanf(pF, "%lx-%lx", &rlower, &rupper) != EOF)
   112 				{
   113 					// Check whether we're IN THERE!
   114 					if (lower >= rlower && upper <= rupper)
   115 					{
   116 						fclose(pF);
   117 						return true;
   118 					}
   119 					// Read to end of line
   120 					int c;
   121 					while ((c = fgetc(pF)) != '\n')
   122 					{
   123 						if (c == EOF)
   124 							break;
   125 					}
   126 					if (c == EOF)
   127 						break;
   128 				}
   129 				fclose(pF);
   130 				return false;
   131 			}
   132 			pF = fopen("/proc/curproc/map", "r");
   133 			if (pF)
   134 			{
   135 				// FreeBSD /proc/curproc/map -> parse
   136 				// 0x804800 0x805500 13 15 0xc6e18960 r-x 21 0x0 COW NC vnode
   137 				long rlower, rupper;
   138 				while (fscanf(pF, "0x%lx 0x%lx", &rlower, &rupper) != EOF)
   139 				{
   140 					// Check whether we're IN THERE!
   141 					if (lower >= rlower && upper <= rupper)
   142 					{
   143 						fclose(pF);
   144 						return true;
   145 					}
   146 					// Read to end of line
   147 					int c;
   148 					while ((c = fgetc(pF)) != '\n')
   149 					{
   150 						if (c == EOF)
   151 							break;
   152 					}
   153 					if (c == EOF)
   154 						break;
   155 				}
   156 				fclose(pF);
   157 				return false;
   158 			}
   159 
   160 			// Both of the above failed, try to actually read and trap sigsegv (implemented by Damaged Soul)
   161 			void(*prevHandler)(int sig);
   162 			g_BadReadCalled = true;
   163 
   164 			if (setjmp(g_BadReadJmpBuf))
   165 				return true;
   166 
   167 			prevHandler = signal(SIGSEGV, BadReadHandler);
   168 
   169 			volatile const char *p = reinterpret_cast<const char*>(addr);
   170 			char dummy;
   171 
   172 			for (size_t i = 0; i < len; i++)
   173 				dummy = p[i];
   174 
   175 			g_BadReadCalled = false;
   176 
   177 			signal(SIGSEGV, prevHandler);
   178 
   179 			return false;
   180 #else
   181 			// On Win32, simply use IsBadReadPtr
   182 			return !IsBadReadPtr(addr, len);
   183 #endif
   184 		}
   185 	}
   186 }
   187 
   188 #endif