sourcehook/sh_memory.h
author Pavol Marko <pavolmarko@gmail.com>
Fri Nov 02 20:15:19 2007 +0000 (2007-11-02)
branchhookman_autogen
changeset 442 07575ad47137
parent 435 35296642e147
child 445 4c2924c393ed
permissions -rw-r--r--
First step to gcc support: it compiles now
     1 /* ======== SourceHook ========
     2 * Copyright (C) 2004-2007 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 namespace LinuxSignal
    28 {
    29 #		include <signal.h>
    30 }
    31 #		include <setjmp.h>
    32 // http://www.die.net/doc/linux/man/man2/mprotect.2.html
    33 #		include <limits.h>
    34 #		ifndef PAGESIZE
    35 #			define PAGESIZE 4096
    36 #		endif
    37 #		define SH_MEM_READ PROT_READ
    38 #		define SH_MEM_WRITE PROT_WRITE
    39 #		define SH_MEM_EXEC PROT_EXEC
    40 
    41 // We need to align addr down to pagesize on linux
    42 // We assume PAGESIZE is a power of two
    43 #		define SH_LALIGN(x) (void*)((intptr_t)(x) & ~(PAGESIZE-1))
    44 #		define SH_LALDIF(x) ((intptr_t)(x) & (PAGESIZE-1))
    45 # else
    46 #		error Unsupported OS/Compiler
    47 # endif
    48 
    49 #include "sh_list.h"
    50 
    51 namespace SourceHook
    52 {
    53 	inline bool SetMemAccess(void *addr, size_t len, int access)
    54 	{
    55 # ifdef __linux__
    56 		return mprotect(SH_LALIGN(addr), len + SH_LALDIF(addr), access)==0 ? true : false;
    57 # else
    58 		DWORD tmp;
    59 		DWORD prot;
    60 		switch (access)
    61 		{
    62 		case SH_MEM_READ:
    63 			prot = PAGE_READONLY; break;
    64 		case SH_MEM_READ | SH_MEM_WRITE:
    65 			prot = PAGE_READWRITE; break;
    66 		case SH_MEM_READ | SH_MEM_EXEC:
    67 			prot = PAGE_EXECUTE_READ; break;
    68 		default:
    69 		case SH_MEM_READ | SH_MEM_WRITE | SH_MEM_EXEC:
    70 			prot = PAGE_EXECUTE_READWRITE; break;
    71 		}
    72 		return VirtualProtect(addr, len, prot, &tmp) ? true : false;
    73 # endif
    74 	}
    75 
    76 #ifdef __linux__
    77 	namespace
    78 	{
    79 		bool g_BadReadCalled;
    80 		jmp_buf g_BadReadJmpBuf;
    81 
    82 		static void BadReadHandler(int sig)
    83 		{
    84 			if (g_BadReadCalled)
    85 				longjmp(g_BadReadJmpBuf, 1);
    86 		}
    87 	}
    88 #endif
    89 
    90 	/**
    91 	*	@brief Checks whether the specified memory region is (still) accessible
    92 	*
    93 	*	@param addr The lower boundary
    94 	*	@param len Length of the region to be checked
    95 	*/
    96 	namespace
    97 	{
    98 		bool ModuleInMemory(char *addr, size_t len)
    99 		{
   100 #ifdef __linux__
   101 			// On linux, first check /proc/self/maps
   102 			long lower = reinterpret_cast<long>(addr);
   103 			long upper = lower + len;
   104 
   105 			FILE *pF = fopen("/proc/self/maps", "r");
   106 			if (pF)
   107 			{
   108 				// Linux /proc/self/maps -> parse
   109 				// Format:
   110 				// lower    upper    prot     stuff                 path
   111 				// 08048000-0804c000 r-xp 00000000 03:03 1010107    /bin/cat
   112 				long rlower, rupper;
   113 				while (fscanf(pF, "%lx-%lx", &rlower, &rupper) != EOF)
   114 				{
   115 					// Check whether we're IN THERE!
   116 					if (lower >= rlower && upper <= rupper)
   117 					{
   118 						fclose(pF);
   119 						return true;
   120 					}
   121 					// Read to end of line
   122 					int c;
   123 					while ((c = fgetc(pF)) != '\n')
   124 					{
   125 						if (c == EOF)
   126 							break;
   127 					}
   128 					if (c == EOF)
   129 						break;
   130 				}
   131 				fclose(pF);
   132 				return false;
   133 			}
   134 			pF = fopen("/proc/curproc/map", "r");
   135 			if (pF)
   136 			{
   137 				// FreeBSD /proc/curproc/map -> parse
   138 				// 0x804800 0x805500 13 15 0xc6e18960 r-x 21 0x0 COW NC vnode
   139 				long rlower, rupper;
   140 				while (fscanf(pF, "0x%lx 0x%lx", &rlower, &rupper) != EOF)
   141 				{
   142 					// Check whether we're IN THERE!
   143 					if (lower >= rlower && upper <= rupper)
   144 					{
   145 						fclose(pF);
   146 						return true;
   147 					}
   148 					// Read to end of line
   149 					int c;
   150 					while ((c = fgetc(pF)) != '\n')
   151 					{
   152 						if (c == EOF)
   153 							break;
   154 					}
   155 					if (c == EOF)
   156 						break;
   157 				}
   158 				fclose(pF);
   159 				return false;
   160 			}
   161 
   162 			// Both of the above failed, try to actually read and trap sigsegv (implemented by Damaged Soul)
   163 			void(*prevHandler)(int sig);
   164 			g_BadReadCalled = true;
   165 
   166 			if (setjmp(g_BadReadJmpBuf))
   167 				return true;
   168 
   169 			prevHandler = LinuxSignal::signal(SIGSEGV, BadReadHandler);
   170 
   171 			volatile const char *p = reinterpret_cast<const char*>(addr);
   172 			char dummy;
   173 
   174 			for (size_t i = 0; i < len; i++)
   175 				dummy = p[i];
   176 
   177 			g_BadReadCalled = false;
   178 
   179 			LinuxSignal::signal(SIGSEGV, prevHandler);
   180 
   181 			return false;
   182 #else
   183 			// On Win32, simply use IsBadReadPtr
   184 			return !IsBadReadPtr(addr, len);
   185 #endif
   186 		}
   187 	}
   188 
   189 	/*
   190 		Class which lets us allocate memory regions in special pages only meant for on the fly code generation.
   191 
   192 		If we alloc with malloc and then set the page access type to read/exec only, other regions returned by
   193 		malloc that are in the same page would lose their write access as well and the process could crash.
   194 
   195 		Allocating one page per code generation session is usually a waste of memory and on some plattforms also
   196 		a waste of virtual address space (Windows� VirtualAlloc has a granularity of 64K).
   197 
   198 
   199 		IMPORTANT: the memory that Alloc() returns is not a in a defined state!
   200 		It could be in read+exec OR read+write mode.
   201 		-> call SetRE() or SetRW() before using allocated memory!
   202 	*/
   203 	class CPageAlloc
   204 	{
   205 		struct AllocationUnit
   206 		{
   207 			size_t begin_offset;
   208 			size_t size;
   209 
   210 			AllocationUnit(size_t p_offs, size_t p_size) : begin_offset(p_offs), size(p_size)
   211 			{
   212 			}
   213 
   214 			bool operator < (const AllocationUnit &other) const
   215 			{
   216 				return begin_offset < other.begin_offset;
   217 			}
   218 		};
   219 		
   220 		typedef List<AllocationUnit> AUList;
   221 
   222 		struct AllocatedRegion
   223 		{
   224 			void *startPtr;
   225 			size_t size;
   226 			bool isolated;					// may contain only one AU
   227 			AUList allocUnits;
   228 
   229 			bool TryAlloc(size_t reqsize, void * &outAddr)
   230 			{
   231 				// Check for isolated
   232 				if (isolated && !allocUnits.empty())
   233 					return false;
   234 
   235 				// Find the smallest gap where req fits
   236 				size_t lastend = 0;
   237 				size_t smallestgap_pos = size + 1;
   238 				size_t smallestgap_size = size + 1;
   239 
   240 				for (AUList::iterator iter = allocUnits.begin(); iter != allocUnits.end(); ++iter)
   241 				{
   242 					if (iter->begin_offset - lastend >= reqsize)
   243 					{
   244 						if (iter->begin_offset - lastend < smallestgap_size)
   245 						{
   246 							smallestgap_size = iter->begin_offset - lastend;
   247 							smallestgap_pos = lastend;
   248 						}
   249 					}
   250 					lastend = iter->begin_offset + iter->size;
   251 				}
   252 
   253 				if (size - lastend >= reqsize)
   254 				{
   255 					if (size - lastend < smallestgap_size)
   256 					{
   257 						smallestgap_size = size - lastend;
   258 						smallestgap_pos = lastend;
   259 					}
   260 				}
   261 
   262 				if (smallestgap_pos < size)
   263 				{
   264 					outAddr = reinterpret_cast<void*>(reinterpret_cast<char*>(startPtr) + smallestgap_pos);
   265 					allocUnits.push_sorted( AllocationUnit(smallestgap_pos, reqsize) );
   266 					return true;
   267 				}
   268 				else
   269 				{
   270 					return false;
   271 				}
   272 			}
   273 
   274 			bool TryFree(void *addr)
   275 			{
   276 				if (addr < startPtr || addr >= reinterpret_cast<void*>(reinterpret_cast<char*>(startPtr) + size))
   277 					return false;
   278 
   279 				size_t offs = reinterpret_cast<char*>(addr) - reinterpret_cast<char*>(startPtr);
   280 
   281 				for (AUList::iterator iter = allocUnits.begin(); iter != allocUnits.end(); ++iter)
   282 				{
   283 					if (iter->begin_offset == offs)
   284 					{
   285 						allocUnits.erase(iter);
   286 						return true;
   287 					}
   288 				}
   289 
   290 				return false;
   291 			}
   292 
   293 			bool Contains(void *addr)
   294 			{
   295 				return addr >= startPtr && addr < reinterpret_cast<void*>(reinterpret_cast<char*>(startPtr) + size);
   296 			}
   297 
   298 			void FreeRegion()
   299 			{
   300 #ifdef __linux__
   301 				munmap(startPtr, size);
   302 #else
   303 				VirtualFree(startPtr, 0, MEM_RELEASE);
   304 #endif
   305 			}
   306 		};
   307 
   308 		typedef List<AllocatedRegion> ARList;
   309 
   310 		size_t m_PageSize;
   311 		ARList m_Regions;
   312 
   313 		bool AddRegion(size_t minSize, bool isolated)
   314 		{
   315 			AllocatedRegion newRegion;
   316 			newRegion.startPtr = 0;
   317 			newRegion.isolated = isolated;
   318 
   319 			// Compute real size -> align up to m_PageSize boundary
   320 
   321 			newRegion.size = minSize - (minSize % m_PageSize);
   322 			if (newRegion.size < minSize)
   323 				newRegion.size += m_PageSize;
   324 
   325 #ifdef __linux__
   326 			newRegion.startPtr = mmap(0, newRegion.size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
   327 #else
   328 			newRegion.startPtr = VirtualAlloc(NULL, newRegion.size, MEM_COMMIT, PAGE_READWRITE);
   329 #endif
   330 			
   331 			if (newRegion.startPtr)
   332 			{
   333 				m_Regions.push_back(newRegion);
   334 				return true;
   335 			}
   336 			else
   337 			{
   338 				return false;
   339 			}
   340 			
   341 		}
   342 
   343 		void *AllocPriv(size_t size, bool isolated)
   344 		{
   345 			void *addr;
   346 
   347 			if (!isolated)
   348 			{
   349 				for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   350 				{
   351 					if (iter->TryAlloc(size, addr))
   352 						return addr;
   353 				}
   354 			}
   355 
   356 			if (!AddRegion(size, isolated))
   357 				return NULL;
   358 			
   359 			bool tmp = m_Regions.back().TryAlloc(size, addr);
   360 			SH_ASSERT(tmp, ("TryAlloc fails after AddRegion"));
   361 			return addr;
   362 		}
   363 
   364 	public:
   365 		CPageAlloc()
   366 		{
   367 #ifdef __linux__
   368 			m_PageSize = sysconf(_SC_PAGESIZE);
   369 #else
   370 			SYSTEM_INFO sysInfo;
   371 			GetSystemInfo(&sysInfo);
   372 			m_PageSize = sysInfo.dwPageSize;
   373 #endif
   374 		}
   375 
   376 		~CPageAlloc()
   377 		{
   378 			// Free all regions
   379 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   380 			{
   381 				iter->FreeRegion();
   382 			}
   383 		}
   384 
   385 		void *Alloc(size_t size)
   386 		{
   387 			return AllocPriv(size, false);
   388 		}
   389 
   390 		void *AllocIsolated(size_t size)
   391 		{
   392 			return AllocPriv(size, true);
   393 		}
   394 
   395 		void Free(void *ptr)
   396 		{
   397 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   398 			{
   399 				if (iter->TryFree(ptr))
   400 				{
   401 					if (iter->allocUnits.empty())
   402 					{
   403 						iter->FreeRegion();
   404 						m_Regions.erase(iter);
   405 					}
   406 					break;
   407 				}
   408 			}
   409 		}
   410 
   411 		void SetRE(void *ptr)
   412 		{
   413 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   414 			{
   415 				if (iter->Contains(ptr))
   416 				{
   417 					SetMemAccess(iter->startPtr, iter->size, SH_MEM_READ | SH_MEM_EXEC);
   418 					break;
   419 				}
   420 			}
   421 		}
   422 
   423 		void SetRW(void *ptr)
   424 		{
   425 			for (ARList::iterator iter = m_Regions.begin(); iter != m_Regions.end(); ++iter)
   426 			{
   427 				if (iter->Contains(ptr))
   428 				{
   429 					SetMemAccess(iter->startPtr, iter->size, SH_MEM_READ | SH_MEM_WRITE);
   430 					break;
   431 				}
   432 			}
   433 		}
   434 
   435 		size_t GetPageSize()
   436 		{
   437 			return m_PageSize;
   438 		}
   439 	};
   440 }
   441 
   442 #endif