core/sourcehook/sourcehook_hookmangen.h
author David Anderson <dvander@alliedmods.net>
Tue Nov 18 04:57:10 2008 -0600 (2008-11-18)
changeset 574 edb3ced430ac
parent 539 db914129ae01
child 733 2365240861a2
permissions -rw-r--r--
Another version.rc bug.
     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
     8 * ============================
     9 */
    10 
    11 #ifndef __SOURCEHOOK_HOOKMANGEN_H__
    12 #define __SOURCEHOOK_HOOKMANGEN_H__
    13 
    14 #include "sh_pagealloc.h"
    15 
    16 namespace SourceHook
    17 {
    18 	namespace Impl
    19 	{
    20 
    21 		// Code gen stuff
    22 #if SH_COMP == SH_COMP_GCC
    23 #include <stdint.h>
    24 		typedef int8_t jit_int8_t;
    25 		typedef uint8_t jit_uint8_t;
    26 		typedef int32_t jit_int32_t;
    27 		typedef uint32_t jit_uint32_t;
    28 		typedef int64_t jit_int64_t;
    29 		typedef uint64_t jit_uint64_t;
    30 #elif SH_COMP == SH_COMP_MSVC
    31 		typedef __int8 jit_int8_t;
    32 		typedef unsigned __int8 jit_uint8_t;
    33 		typedef __int32 jit_int32_t;
    34 		typedef unsigned __int32 jit_uint32_t;
    35 		typedef __int64 jit_int64_t;
    36 		typedef unsigned __int64 jit_uint64_t;
    37 #endif
    38 		typedef unsigned int jitoffs_t;
    39 		typedef signed int jitrel_t;
    40 
    41 
    42 		class GenBuffer
    43 		{
    44 			static CPageAlloc ms_Allocator;
    45 
    46 			unsigned char *m_pData;
    47 			jitoffs_t m_Size;
    48 			jitoffs_t m_AllocatedSize;
    49 
    50 		public:
    51 			GenBuffer() : m_pData(NULL), m_Size(0), m_AllocatedSize(0)
    52 			{
    53 			}
    54 			~GenBuffer()
    55 			{
    56 				clear();
    57 			}
    58 			jitoffs_t GetSize()
    59 			{
    60 				return m_Size;
    61 			}
    62 			unsigned char *GetData()
    63 			{
    64 				return m_pData;
    65 			}
    66 
    67 			template <class PT> void push(PT what)
    68 			{
    69 				push((const unsigned char *)&what, sizeof(PT));
    70 			}
    71 
    72 			void push(const unsigned char *data, jitoffs_t size)
    73 			{
    74 				jitoffs_t newSize = m_Size + size;
    75 				if (newSize > m_AllocatedSize)
    76 				{
    77 					m_AllocatedSize = newSize > m_AllocatedSize*2 ? newSize : m_AllocatedSize*2;
    78 					if (m_AllocatedSize < 64)
    79 						m_AllocatedSize = 64;
    80 
    81 					unsigned char *newBuf;
    82 					newBuf = reinterpret_cast<unsigned char*>(ms_Allocator.Alloc(m_AllocatedSize));
    83 					ms_Allocator.SetRW(newBuf);
    84 					if (!newBuf)
    85 					{
    86 						SH_ASSERT(0, ("bad_alloc: couldn't allocate 0x%08X bytes of memory\n", m_AllocatedSize));
    87 						return;
    88 					}
    89 					memset((void*)newBuf, 0xCC, m_AllocatedSize);			// :TODO: remove this !
    90 					memcpy((void*)newBuf, (const void*)m_pData, m_Size);
    91 					if (m_pData)
    92 					{
    93 						ms_Allocator.SetRE(reinterpret_cast<void*>(m_pData));
    94 						ms_Allocator.SetRW(newBuf);
    95 						ms_Allocator.Free(reinterpret_cast<void*>(m_pData));
    96 					}
    97 					m_pData = newBuf;
    98 				}
    99 				memcpy((void*)(m_pData + m_Size), (const void*)data, size);
   100 				m_Size = newSize;
   101 			}
   102 
   103 			template <class PT> void rewrite(jitoffs_t offset, PT what)
   104 			{
   105 				rewrite(offset, (const unsigned char *)&what, sizeof(PT));
   106 			}
   107 
   108 			void rewrite(jitoffs_t offset, const unsigned char *data, jitoffs_t size)
   109 			{
   110 				SH_ASSERT(offset + size <= m_AllocatedSize, ("rewrite too far"));
   111 
   112 				memcpy((void*)(m_pData + offset), (const void*)data, size);
   113 			}
   114 
   115 			void clear()
   116 			{
   117 				if (m_pData)
   118 					ms_Allocator.Free(reinterpret_cast<void*>(m_pData));
   119 				m_pData = NULL;
   120 				m_Size = 0;
   121 				m_AllocatedSize = 0;
   122 			}
   123 
   124 			void SetRE()
   125 			{
   126 				ms_Allocator.SetRE(reinterpret_cast<void*>(m_pData));
   127 			}
   128 
   129 			operator void *()
   130 			{
   131 				return reinterpret_cast<void*>(GetData());
   132 			}
   133 
   134 			void write_ubyte(jit_uint8_t x)			{ push(x); }
   135 			void write_byte(jit_uint8_t x)			{ push(x); }
   136 			
   137 			void write_ushort(unsigned short x)		{ push(x); }
   138 			void write_short(signed short x)		{ push(x); }
   139 
   140 			void write_uint32(jit_uint32_t x)		{ push(x); }
   141 			void write_int32(jit_uint32_t x)		{ push(x); }
   142 
   143 			jitoffs_t get_outputpos()
   144 			{
   145 				return m_Size;
   146 			}
   147 
   148 			void start_count(jitoffs_t &offs)
   149 			{
   150 				offs = get_outputpos();
   151 			}
   152 			void end_count(jitoffs_t &offs)
   153 			{
   154 				offs = get_outputpos() - offs;
   155 			}
   156 		};
   157 
   158 		class GenContext
   159 		{
   160 			const static int SIZE_MWORD = 4;
   161 			const static int SIZE_PTR = sizeof(void*);
   162 			const static int PassFlag_ForcedByRef = (1<<30);   // ByVal in source, but actually passed by reference (GCC) -> private pass, destruct
   163 
   164 			HookManagerPubFunc m_GeneratedPubFunc;
   165 
   166 			CProto m_OrigProto;			// original passed-in prototype
   167 			CProto m_Proto;
   168 			int m_VtblOffs;
   169 			int m_VtblIdx;
   170 			ISourceHook *m_SHPtr;
   171 
   172 			GenBuffer m_HookFunc;
   173 			GenBuffer m_PubFunc;
   174 
   175 			ProtoInfo *m_BuiltPI;
   176 			PassInfo *m_BuiltPI_Params;
   177 			PassInfo::V2Info *m_BuiltPI_Params2;
   178 
   179 			// For hookfunc
   180 			void **m_pHI;
   181 			void **m_HookfuncVfnptr;
   182 
   183 			// Level 3 - Helpers
   184 			int m_RegCounter;
   185 			jit_int8_t NextRegEBX_ECX_EDX();
   186 
   187 			int m_BytesPushedAfterInitialAlignment;
   188 			enum AlignStackFlags
   189 			{
   190 				AlignStack_GCC_ThisOnStack = 1,
   191 				AlignStack_MSVC_ThisOnStack = 2,
   192 				AlignStack_MemRet = 4
   193 			};
   194 			jit_int32_t AlignStackBeforeCall(int paramsize, int flags);
   195 			void AlignStackAfterCall(jit_int32_t numofbytes);
   196 			void CheckAlignmentBeforeCall();
   197 
   198 			// size info
   199 			jit_int32_t GetRealSize(const IntPassInfo &info);			// checks for reference
   200 			jit_int32_t AlignSize(jit_int32_t x, jit_int32_t boundary);	// align a size
   201 			jit_int32_t GetParamStackSize(const IntPassInfo &info);		// get the size of a param in the param stack
   202 			short GetParamsTotalStackSize();		// sum(GetParamStackSize(param[i]), 0 <= i < numOfParams)
   203 
   204 			// Helpers
   205 			void BitwiseCopy_Setup();
   206 			void BitwiseCopy_Do(size_t size);
   207 
   208 
   209 			// HookFunc frame
   210 			jit_int32_t m_HookFunc_FrameOffset;
   211 			jit_int32_t m_HookFunc_FrameVarsSize;
   212 
   213 			void ResetFrame(jit_int32_t startOffset);
   214 			jit_int32_t AddVarToFrame(jit_int32_t size);
   215 			jit_int32_t ComputeVarsSize();
   216 
   217 			// Param push
   218 			short GetForcedByRefParamsSize();		// sum(param[i] is forcedbyref ? GetStackSize(param[i]) : 0, 0 <= i < numOfParams)
   219 			short GetForcedByRefParamOffset(int p);		// sum(param[i] is forcedbyref ? GetStackSize(param[i]) : 0, 0 <= i < p)
   220 			jit_int32_t PushParams(jit_int32_t param_base_offset, jit_int32_t save_ret_to, 
   221 				jit_int32_t v_place_for_memret, jit_int32_t v_place_fbrr_base);		// save_ret_to and v_place_for_memret only used for memory returns
   222 			jit_int32_t PushRef(jit_int32_t param_offset, const IntPassInfo &pi);
   223 			jit_int32_t PushBasic(jit_int32_t param_offset, const IntPassInfo &pi);
   224 			jit_int32_t PushFloat(jit_int32_t param_offset, const IntPassInfo &pi);
   225 			jit_int32_t PushObject(jit_int32_t param_offset, const IntPassInfo &pi, jit_int32_t v_place_fbrr);
   226 			jit_int32_t PushMemRetPtr(jit_int32_t save_ret_to, jit_int32_t v_place_for_memret);
   227 			void DestroyParams(jit_int32_t fbrr_base);
   228 
   229 			// Ret val processing
   230 			void SaveRetVal(jit_int32_t v_where, jit_int32_t v_place_for_memret);
   231 			void ProcessPluginRetVal(jit_int32_t v_cur_res, jit_int32_t v_pContext, jit_int32_t v_plugin_ret);
   232 
   233 			void PrepareReturn(jit_int32_t v_status, jit_int32_t v_pContext, jit_int32_t v_retptr);
   234 			void DoReturn(jit_int32_t v_retptr, jit_int32_t v_memret_outaddr);
   235 
   236 			bool MemRetWithTempObj();			// do we do a memory return AND need a temporary place for it?
   237 
   238 			// Call hooks
   239 			void GenerateCallHooks(int v_status, int v_prev_res, int v_cur_res, int v_iter,
   240 				int v_pContext, int base_param_offset, int v_plugin_ret, int v_place_for_memret, jit_int32_t v_place_fbrr_base, jit_int32_t v_va_buf);
   241 
   242 			// Call orig
   243 			void GenerateCallOrig(int v_status, int v_pContext, int param_base_offs, int v_this,
   244 				int v_vfnptr_origentry, int v_orig_ret, int v_override_ret, int v_place_for_memret, jit_int32_t v_place_fbrr_base, jit_int32_t v_va_buf);
   245 
   246 			// Hook loop
   247 			void CallSetupHookLoop(int v_orig_ret, int v_override_ret, 
   248 				int v_cur_res, int v_prev_res, int v_status, int v_vnfptr_origentry,
   249 				int v_this, int v_pContext);
   250 
   251 			void CallEndContext(int v_pContext);
   252 
   253 			// Level 2 -> called from Generate()
   254 			void AutoDetectRetType();
   255 			void AutoDetectParamFlags();
   256 			bool PassInfoSupported(const IntPassInfo &pi, bool is_ret);
   257 			void Clear();
   258 			void BuildProtoInfo();
   259 			void *GenerateHookFunc();
   260 			void *GeneratePubFunc();
   261 			
   262 			HookManagerPubFunc Generate();
   263 		public:
   264 			// Level 1 -> Public interface
   265 			GenContext(const ProtoInfo *proto, int vtbl_offs, int vtbl_idx, ISourceHook *pSHPtr);
   266 			~GenContext();
   267 
   268 			bool Equal(const CProto &proto, int vtbl_offs, int vtbl_idx);
   269 			bool Equal(HookManagerPubFunc other);
   270 
   271 			HookManagerPubFunc GetPubFunc();
   272 		};
   273 
   274 		class CHookManagerAutoGen : public IHookManagerAutoGen 
   275 		{
   276 			struct StoredContext
   277 			{
   278 				int m_RefCnt;
   279 				GenContext *m_GenContext;
   280 			};
   281 			List<StoredContext> m_Contexts;
   282 			ISourceHook *m_pSHPtr;
   283 
   284 		public:
   285 			CHookManagerAutoGen(ISourceHook *pSHPtr);
   286 			~CHookManagerAutoGen();
   287 
   288 			int GetIfaceVersion();
   289 			int GetImplVersion();
   290 
   291 			HookManagerPubFunc MakeHookMan(const ProtoInfo *proto, int vtbl_offs, int vtbl_idx);
   292 			void ReleaseHookMan(HookManagerPubFunc pubFunc);
   293 		};
   294 
   295 	}
   296 }
   297 
   298 
   299 #endif