dlls/cstrike/cstrike/CstrikeHacks.cpp
author Scott Ehlert <ds@alliedmods.net>
Tue Sep 03 17:56:27 2013 -0500 (2013-09-03)
changeset 187 0b19788dcc03
parent 40 1a046181ff8b
child 188 83a0f433f014
permissions -rw-r--r--
Fixed cstrike module crash on OS X (r=dvander).

Valve now compiles OS X binaries with -fvisibility=hidden, so dlsym no longer works with non-exported symbols.
     1 #include <assert.h>
     2 #include <stdlib.h>
     3 #include "cstrike.h"
     4 
     5 #if defined(__linux__) || defined(__APPLE__)
     6 #include <sys/mman.h>
     7 #define	PAGE_EXECUTE_READWRITE	PROT_READ|PROT_WRITE|PROT_EXEC
     8 
     9 #if defined(__linux)
    10 #include <malloc.h>
    11 #endif
    12 #endif
    13 
    14 #if defined(__APPLE__)
    15 #include <mach-o/nlist.h>
    16 #endif
    17 
    18 /* Utils */
    19 unsigned char *UTIL_CodeAlloc(size_t size);
    20 void UTIL_CodeFree(unsigned char *addr);
    21 void UTIL_MemProtect(void *addr, int length, int prot);
    22 bool UTIL_GetLibraryOfAddress(void *memInBase, char *buffer, size_t maxlength, uintptr_t *base);
    23 
    24 /* Detours */
    25 void CtrlDetour_ClientCommand(bool set);
    26 int Detour_ClientCommand(edict_t *pEdict);
    27 
    28 int g_CSCliCmdFwd = -1;
    29 int *g_UseBotArgs = NULL;
    30 const char **g_BotArgs = NULL;
    31 
    32 /* Called on startup */
    33 void InitializeHacks()
    34 {
    35 	CtrlDetour_ClientCommand(true);
    36 }
    37 
    38 void OnPluginsLoaded()
    39 {
    40 	g_CSCliCmdFwd = MF_RegisterForward("CS_InternalCommand", ET_STOP, FP_CELL, FP_STRING, FP_DONE);
    41 }
    42 
    43 void ShutdownHacks()
    44 {
    45 	CtrlDetour_ClientCommand(false);
    46 }
    47 
    48 void CtrlDetour_ClientCommand(bool set)
    49 {
    50 #if defined AMD64
    51 #error UNSUPPORTED
    52 #endif
    53 	static unsigned char DetourOps[] = 
    54 	{
    55 		'\x50',									/* push eax         ; just for safety */
    56 		'\xff', '\x74', '\x24', '\x08',			/* push [esp+0x8]	; push the edict pointer */
    57 		'\xe8', '\x00', '\x00', '\x00', '\x00', /* call <gate>		; call our function */
    58 		'\x83', '\xc4', '\x08',					/* add esp, 8		; correct stack */
    59 		'\x85', '\xc0',							/* test eax, eax	; do != 0 test */
    60 		'\x74', '\x01',							/* je <cont>		; if == 0, jump to where old func is saved */
    61 		'\xc3'									/* ret				; return otherwise */
    62 	};
    63 	static unsigned char DetourJmp = '\xE9';
    64 
    65 	const unsigned int DetourBytes = 18;
    66 	const unsigned int DetourCallPos = 6;
    67 	const unsigned int DetourJmpPos = DetourBytes + CS_DETOURCOPYBYTES_CLIENTCOMMAND;
    68 	const unsigned int DetourJmpBytes = 5;
    69 	static unsigned char *FullDetour = NULL;
    70 
    71 	void *target = (void *)MDLL_ClientCommand;
    72 	unsigned char *paddr;
    73 
    74 	if (!g_UseBotArgs)
    75 	{
    76 #if defined(__linux__) || defined(__APPLE__)
    77 		/* Find the DLL */
    78 		char dll[256];
    79 		uintptr_t base;
    80 		if (!UTIL_GetLibraryOfAddress(target, dll, sizeof(dll), &base))
    81 		{
    82 			return;
    83 		}
    84 #if defined(__linux__)
    85 		void *handle = dlopen(dll, RTLD_NOW);
    86 		if (!handle)
    87 		{
    88 			return;
    89 		}
    90 		g_UseBotArgs = (int *)dlsym(handle, "UseBotArgs");
    91 		g_BotArgs = (const char **)dlsym(handle, "BotArgs");
    92 		dlclose(handle);
    93 #elif defined(__APPLE__)
    94 		/* Using dlsym on OS X won't work because the symbols are hidden */
    95 		struct nlist symbols[3];
    96 		memset(symbols, 0, sizeof(symbols));
    97 		symbols[0].n_un.n_name = (char *)"_UseBotArgs";
    98 		symbols[1].n_un.n_name = (char *)"_BotArgs";
    99 		if (nlist(dll, symbols) != 0)
   100 		{
   101 			return;
   102 		}
   103 		g_UseBotArgs = (int *)(base + symbols[0].n_value);
   104 		g_BotArgs = (const char **)(base + symbols[1].n_value);
   105 #endif
   106 #else /* Windows */
   107 		/* Find the bot args addresses */
   108 		paddr = (unsigned char *)target + CS_CLICMD_OFFS_USEBOTARGS;
   109 		g_UseBotArgs = *(int **)paddr;
   110 		paddr = (unsigned char *)target + CS_CLICMD_OFFS_BOTARGS;
   111 		g_BotArgs = (const char **)*(const char **)paddr;
   112 #endif
   113 	}
   114 
   115 	if (set)
   116 	{
   117 		assert(FullDetour == NULL);
   118 		FullDetour = UTIL_CodeAlloc(DetourBytes + CS_DETOURCOPYBYTES_CLIENTCOMMAND + DetourJmpBytes);
   119 	
   120 		/* Copy the main trampoline function */
   121 		memcpy(FullDetour, DetourOps, DetourBytes);
   122 	
   123 		/* Copy our detour call into the trampoline */
   124 		paddr = &FullDetour[DetourCallPos];
   125 		*(unsigned long *)paddr = (unsigned long)Detour_ClientCommand - (unsigned long)(paddr + 4);
   126 	
   127 		/* Copy original bytes onto the end of the function */
   128 	    	memcpy(&FullDetour[DetourBytes], target, CS_DETOURCOPYBYTES_CLIENTCOMMAND);
   129 		
   130 		/* Patch and copy the final jmp */
   131 		paddr = &FullDetour[DetourJmpPos];
   132 		*paddr++ = DetourJmp;
   133 		*(unsigned long *)paddr = ((unsigned long)target + CS_DETOURCOPYBYTES_CLIENTCOMMAND)
   134 									- (unsigned long)(paddr + 4);
   135 	
   136 		/* Now overwrite the target function with our trampoline */
   137 		UTIL_MemProtect(target, CS_DETOURCOPYBYTES_CLIENTCOMMAND + 10, PAGE_EXECUTE_READWRITE);
   138 		paddr = (unsigned char *)target;
   139 		*paddr++ = DetourJmp;
   140 		*(unsigned long *)paddr = (unsigned long)FullDetour - (unsigned long)(paddr + 4);
   141 	} else {
   142 		assert(FullDetour != NULL);
   143 
   144 		/* Copy back the original function bytes */
   145 		memcpy(target, &FullDetour[DetourBytes], CS_DETOURCOPYBYTES_CLIENTCOMMAND);
   146 
   147 		/* Free memory used */
   148 		UTIL_CodeFree(FullDetour);
   149 		FullDetour = NULL;
   150 	}
   151 }
   152 
   153 int Detour_ClientCommand(edict_t *pEdict)
   154 {
   155 	if (*g_UseBotArgs)
   156 	{
   157 		int client = ENTINDEX(pEdict);
   158 		const char *args = *g_BotArgs;
   159 		return MF_ExecuteForward(g_CSCliCmdFwd, (cell)client, args);
   160 	}
   161 	return 0;
   162 }
   163 
   164 unsigned char *UTIL_CodeAlloc(size_t size)
   165 {
   166 #if defined WIN32
   167 	return (unsigned char *)VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
   168 #elif defined __GNUC__
   169 #if defined __APPLE__
   170 	unsigned char *addr = (unsigned char *)valloc(size);
   171 #else
   172 	unsigned char *addr = (unsigned char *)memalign(sysconf(_SC_PAGESIZE), size);
   173 #endif
   174 	mprotect(addr, size, PROT_READ|PROT_WRITE|PROT_EXEC);
   175 	return addr;
   176 #endif
   177 }
   178 
   179 void UTIL_CodeFree(unsigned char *addr)
   180 {
   181 #if defined WIN32
   182 	VirtualFree(addr, 0, MEM_RELEASE);
   183 #else
   184 	free(addr);
   185 #endif
   186 }
   187 
   188 void UTIL_MemProtect(void *addr, int length, int prot)
   189 {
   190 #if defined(__linux__) || defined(__APPLE__)
   191 #define ALIGN(ar) ((long)ar & ~(sysconf(_SC_PAGESIZE)-1))
   192 	void *addr2 = (void *)ALIGN(addr);
   193 	mprotect(addr2, sysconf(_SC_PAGESIZE), prot);
   194 #else
   195 	DWORD old_prot;
   196 	VirtualProtect(addr, length, prot, &old_prot);
   197 #endif
   198 }
   199 
   200 bool UTIL_GetLibraryOfAddress(void *memInBase, char *buffer, size_t maxlength, uintptr_t *base)
   201 {
   202 #if defined(__linux__) || defined(__APPLE__)
   203 	Dl_info info;
   204 	if (!dladdr(memInBase, &info))
   205 	{
   206 		return false;
   207 	}
   208 	if (!info.dli_fbase || !info.dli_fname)
   209 	{
   210 		return false;
   211 	}
   212 	const char *dllpath = info.dli_fname;
   213 	snprintf(buffer, maxlength, "%s", dllpath);
   214 	if (base)
   215 	{
   216 		*base = (uintptr_t)info.dli_fbase;
   217 	}
   218 #else
   219 	MEMORY_BASIC_INFORMATION mem;
   220 	if (!VirtualQuery(memInBase, &mem, sizeof(mem)))
   221 	{
   222 		return false;
   223 	}
   224 	if (mem.AllocationBase == NULL)
   225 	{
   226 		return false;
   227 	}
   228 	HMODULE dll = (HMODULE)mem.AllocationBase;
   229 	GetModuleFileName(dll, (LPTSTR)buffer, maxlength);
   230 	if (base)
   231 	{
   232 		*base = (uintptr_t)mem.AllocationBase;
   233 	}
   234 #endif
   235 	return true;
   236 }
   237