sourcehook/sourcehook_hookmangen.cpp
author Pavol Marko <pavolmarko@gmail.com>
Mon Nov 19 14:41:31 2007 +0000 (2007-11-19)
branchhookman_autogen
changeset 468 88027ecc83c4
parent 467 7b0d972632af
child 470 862a6376a785
permissions -rw-r--r--
Removed forgotten debug code
     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
     8 * Contributor(s): Borja "faluco" Ferav  (many thanks for assitance!)
     9 *				  David "BAILOPAN" Anderson
    10 * ============================
    11 */
    12 
    13 // recommended literature:
    14 // http://www.cs.umbc.edu/~chang/cs313.s02/stack.shtml
    15 // http://www.angelcode.com/dev/callconv/callconv.html
    16 // http://www.arl.wustl.edu/~lockwood/class/cs306/books/artofasm/Chapter_6/CH06-1.html
    17 
    18 #include "sourcehook_impl.h"
    19 #include "sourcehook_hookmangen.h"
    20 #include "sourcehook_hookmangen_x86.h"
    21 #include "sh_memory.h"
    22 #include <stdarg.h>							// we might need the address of vsnprintf
    23 #include <stdio.h>
    24 
    25 #if SH_COMP == SH_COMP_MSVC
    26 # define GCC_ONLY(x)
    27 # define MSVC_ONLY(x) x
    28 #elif SH_COMP == SH_COMP_GCC
    29 # define GCC_ONLY(x) x
    30 # define MSVC_ONLY(x)
    31 #endif
    32 
    33 // :TODO: test BIG vtable indices
    34 
    35 namespace SourceHook
    36 {
    37 	namespace Impl
    38 	{
    39 		CPageAlloc GenBuffer::ms_Allocator;
    40 
    41 		template <class T>
    42 		jit_int32_t DownCastPtr(T ptr)
    43 		{
    44 			return reinterpret_cast<jit_int32_t>(ptr);
    45 		}
    46 
    47 		jit_uint32_t DownCastSize(size_t size)
    48 		{
    49 			return static_cast<jit_uint32_t>(size);
    50 		}
    51 
    52 		GenContext::GenContext(const ProtoInfo *proto, int vtbl_offs, int vtbl_idx, ISourceHook *pSHPtr)
    53 			: m_GeneratedPubFunc(NULL), m_OrigProto(proto), m_Proto(proto), m_VtblOffs(vtbl_offs),
    54 			  m_VtblIdx(vtbl_idx), m_SHPtr(pSHPtr), m_pHI(NULL), m_HookfuncVfnptr(NULL), m_RegCounter(0)
    55 		{
    56 			m_pHI = new void*;
    57 			m_HookfuncVfnptr = new void*;
    58 			m_BuiltPI = new ProtoInfo;
    59 			m_BuiltPI_Params = NULL;
    60 			m_BuiltPI_Params2 = NULL;
    61 		}
    62 
    63 		GenContext::~GenContext()
    64 		{
    65 			Clear();
    66 			delete m_pHI;
    67 			delete m_HookfuncVfnptr;
    68 			delete m_BuiltPI;
    69 		}
    70 
    71 		void GenContext::Clear()
    72 		{
    73 			m_HookFunc.clear();
    74 			m_PubFunc.clear();
    75 			if (m_BuiltPI_Params)
    76 			{
    77 				delete m_BuiltPI_Params;
    78 				m_BuiltPI_Params = NULL;
    79 			}
    80 			if (m_BuiltPI_Params2)
    81 			{
    82 				delete m_BuiltPI_Params2;
    83 				m_BuiltPI_Params2 = NULL;
    84 			}
    85 		}
    86 
    87 		void GenContext::BuildProtoInfo()
    88 		{
    89 			m_BuiltPI->convention = m_Proto.GetConvention();
    90 			m_BuiltPI->numOfParams = m_Proto.GetNumOfParams();
    91 
    92 			m_BuiltPI->retPassInfo.size = m_Proto.GetRet().size;
    93 			m_BuiltPI->retPassInfo.type = m_Proto.GetRet().type;
    94 			m_BuiltPI->retPassInfo.flags = m_Proto.GetRet().flags;
    95 			m_BuiltPI->retPassInfo2.pNormalCtor = m_Proto.GetRet().pNormalCtor;
    96 			m_BuiltPI->retPassInfo2.pCopyCtor = m_Proto.GetRet().pCopyCtor;
    97 			m_BuiltPI->retPassInfo2.pDtor = m_Proto.GetRet().pDtor;
    98 			m_BuiltPI->retPassInfo2.pAssignOperator = m_Proto.GetRet().pAssignOperator;
    99 
   100 			if (m_BuiltPI_Params)
   101 				delete m_BuiltPI_Params;
   102 			m_BuiltPI_Params = new PassInfo[m_BuiltPI->numOfParams + 1];
   103 			if (m_BuiltPI_Params2)
   104 				delete m_BuiltPI_Params2;
   105 			m_BuiltPI_Params2 = new PassInfo::V2Info[m_BuiltPI->numOfParams + 1];
   106 
   107 			m_BuiltPI_Params[0].size = 1;			// Version 1
   108 			m_BuiltPI_Params[0].type = 0;
   109 			m_BuiltPI_Params[0].flags = 0;
   110 			
   111 			for (int i = 0; i < m_Proto.GetNumOfParams(); ++i)
   112 			{
   113 				m_BuiltPI_Params[i+1].size = m_Proto.GetParam(i).size;
   114 				m_BuiltPI_Params[i+1].type = m_Proto.GetParam(i).type;
   115 				m_BuiltPI_Params[i+1].flags = m_Proto.GetParam(i).flags;
   116 
   117 				m_BuiltPI_Params2[i+1].pNormalCtor = m_Proto.GetParam(i).pNormalCtor;
   118 				m_BuiltPI_Params2[i+1].pCopyCtor = m_Proto.GetParam(i).pCopyCtor;
   119 				m_BuiltPI_Params2[i+1].pDtor = m_Proto.GetParam(i).pDtor;
   120 				m_BuiltPI_Params2[i+1].pAssignOperator = m_Proto.GetParam(i).pAssignOperator;
   121 			}
   122 
   123 			m_BuiltPI->paramsPassInfo = m_BuiltPI_Params;
   124 			m_BuiltPI->paramsPassInfo2 = m_BuiltPI_Params2;
   125 		}
   126 
   127 		jit_int32_t GenContext::GetRealSize(const IntPassInfo &info)
   128 		{
   129 			if (info.flags & PassInfo::PassFlag_ByRef)
   130 			{
   131 				return SIZE_PTR;
   132 			}
   133 			return static_cast<jit_int32_t>(info.size);
   134 		}
   135 
   136 		// Computes size on the stack
   137 		jit_int32_t GenContext::GetStackSize(const IntPassInfo &info)
   138 		{
   139 			// Align up to 4 byte boundaries
   140 			jit_int32_t rs = GetRealSize(info);
   141 			if (rs % 4 != 0)
   142 				rs = (rs & ~(3)) + 4;
   143 			return rs;
   144 		}
   145 
   146 		jit_int8_t GenContext::NextRegEBX_ECX_EDX()
   147 		{
   148 			switch ((m_RegCounter++) % 3)
   149 			{
   150 			case 0:
   151 				return REG_EBX;
   152 			case 1:
   153 				return REG_ECX;
   154 			case 2:
   155 			default:
   156 				m_RegCounter = 0;
   157 				return REG_EDX;
   158 			}
   159 		}
   160 
   161 		void GenContext::BitwiseCopy_Setup()
   162 		{
   163 			//cld
   164 			//push edi
   165 			//push esi
   166 
   167 			IA32_Cld(&m_HookFunc);
   168 			IA32_Push_Reg(&m_HookFunc, REG_EDI);
   169 			IA32_Push_Reg(&m_HookFunc, REG_ESI);
   170 		}
   171 
   172 		void GenContext::BitwiseCopy_Do(size_t size)
   173 		{
   174 			jit_uint32_t dwords = DownCastSize(size) / 4;
   175 			jit_uint32_t bytes = DownCastSize(size) % 4;
   176 
   177 			//if dwords
   178 			// mov ecx, <dwords>
   179 			// rep movsd
   180 			//if bytes
   181 			// mov ecx, <bytes>
   182 			// rep movsb
   183 			//pop esi
   184 			//pop edi
   185 
   186 			if (dwords)
   187 			{
   188 				IA32_Mov_Reg_Imm32(&m_HookFunc, REG_ECX, dwords);
   189 				IA32_Rep(&m_HookFunc);
   190 				IA32_Movsd(&m_HookFunc);
   191 			}
   192 			if (bytes)
   193 			{
   194 				IA32_Mov_Reg_Imm32(&m_HookFunc, REG_ECX, bytes);
   195 				IA32_Rep(&m_HookFunc);
   196 				IA32_Movsb(&m_HookFunc);
   197 			}
   198 			IA32_Pop_Reg(&m_HookFunc, REG_ESI);
   199 			IA32_Pop_Reg(&m_HookFunc, REG_EDI);
   200 		}
   201 
   202 		short GenContext::GetParamsStackSize()
   203 		{
   204 			short acc = 0;
   205 			for (int i = 0; i < m_Proto.GetNumOfParams(); ++i)
   206 			{
   207 				acc += GetStackSize(m_Proto.GetParam(i));
   208 			}
   209 
   210 			return acc;
   211 		}
   212 
   213 		short GenContext::GetForcedByRefParamOffset(int p)
   214 		{
   215 			short off = 0;
   216 			for (int i = 0; i < p; ++i)
   217 			{
   218 				if (m_Proto.GetParam(i).flags & PassFlag_ForcedByRef)
   219 					off += GetStackSize(m_Proto.GetParam(i));
   220 			}
   221 			return off;
   222 		}
   223 
   224 		short GenContext::GetForcedByRefParamsSize()
   225 		{
   226 			return GetForcedByRefParamOffset(m_Proto.GetNumOfParams());
   227 		}
   228 
   229 		jit_int32_t GenContext::PushRef(jit_int32_t param_offset, const IntPassInfo &pi)
   230 		{
   231 			// push [ebp+<offset>]
   232 			IA32_Push_Rm_DispAuto(&m_HookFunc, REG_EBP, param_offset);
   233 
   234 			return SIZE_PTR;
   235 		}
   236 
   237 		jit_int32_t GenContext::PushBasic(jit_int32_t param_offset, const IntPassInfo &pi)
   238 		{
   239 			int reg;
   240 			int reg2;
   241 
   242 			switch (pi.size)
   243 			{
   244 			default:
   245 				SH_ASSERT(0, ("Unsupported!"));
   246 				return 0;
   247 			case 1:
   248 				reg = NextRegEBX_ECX_EDX();
   249 				//movzx reg, BYTE PTR [ebp+<offset>]
   250 				//push reg
   251 				IA32_Movzx_Reg32_Rm8_DispAuto(&m_HookFunc, reg, REG_EBP, param_offset);
   252 				IA32_Push_Reg(&m_HookFunc, reg);
   253 
   254 				return 4;
   255 			case 2:
   256 				reg = NextRegEBX_ECX_EDX();
   257 				//movzx reg, WORD PTR [ebp+<offset>]
   258 				//push reg
   259 				m_HookFunc.write_ubyte(IA32_16BIT_PREFIX);
   260 				IA32_Movzx_Reg32_Rm16_DispAuto(&m_HookFunc, reg, REG_EBP, param_offset);
   261 				IA32_Push_Reg(&m_HookFunc, reg);
   262 
   263 				return 4;
   264 			case 4:
   265 				reg = NextRegEBX_ECX_EDX();
   266 				//mov reg, DWORD PTR [ebp+<offset>]
   267 				//push reg
   268 				IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, reg, REG_EBP, param_offset);
   269 				IA32_Push_Reg(&m_HookFunc, reg);
   270 
   271 				return 4;
   272 			case 8:
   273 				reg = NextRegEBX_ECX_EDX();
   274 				reg2 = NextRegEBX_ECX_EDX();
   275 				//mov reg, DWORD PTR [ebp+<offset>+4]
   276 				//mov reg2, DWORD PTR [ebp+<offset>]
   277 				//push reg
   278 				//push reg2
   279 
   280 				IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, reg, REG_EBP, param_offset+4);
   281 				IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, reg2, REG_EBP, param_offset);
   282 				IA32_Push_Reg(&m_HookFunc, reg);
   283 				IA32_Push_Reg(&m_HookFunc, reg2);
   284 
   285 				return 8;
   286 			}
   287 		}
   288 
   289 		jit_int32_t GenContext::PushFloat(jit_int32_t param_offset, const IntPassInfo &pi)
   290 		{
   291 			switch (pi.size)
   292 			{
   293 			default:
   294 				SH_ASSERT(0, ("Unsupported!"));
   295 				return 0;
   296 			case 4:
   297 				//fld DWORD PTR [ebp+<offset>]
   298 				//push reg
   299 				//fstp DWORD PTR [esp]
   300 				IA32_Fld_Mem32_DispAuto(&m_HookFunc, REG_EBP, param_offset);
   301 				IA32_Push_Reg(&m_HookFunc, NextRegEBX_ECX_EDX());
   302 				IA32_Fstp_Mem32_ESP(&m_HookFunc);
   303 				return 4;
   304 			case 8:
   305 				//fld QWORD PTR [ebp+<offset>]
   306 				//sub esp, 8
   307 				//fstp QWORD PTR [esp]
   308 				IA32_Fld_Mem64_DispAuto(&m_HookFunc, REG_EBP, param_offset);
   309 				IA32_Sub_Rm_Imm8(&m_HookFunc, REG_ESP, 8, MOD_REG);
   310 				IA32_Fstp_Mem64_ESP(&m_HookFunc);
   311 				return 8;
   312 			}
   313 		}
   314 
   315 		jit_int32_t GenContext::PushObject(jit_int32_t param_offset, const IntPassInfo &pi, jit_int32_t place_fbrr)
   316 		{
   317 			if ((pi.flags & PassFlag_ForcedByRef) == 0)
   318 			{
   319 				// make room on the stack
   320 				// sub esp, <size>
   321 				IA32_Sub_Rm_ImmAuto(&m_HookFunc, REG_ESP, GetStackSize(pi), MOD_REG);
   322 			}
   323 
   324 			// if there is a copy constructor..
   325 			if (pi.pCopyCtor)
   326 			{
   327 				// save eax
   328 				// push src addr
   329 				// this= target addr = forcedbyref ? ebp+place_fbrr : esp+12
   330 				// call copy constructor
   331 				// restore eax
   332 			
   333 				IA32_Push_Reg(&m_HookFunc, REG_EAX);
   334 				
   335 				if (pi.flags & PassFlag_ForcedByRef)
   336 					IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, place_fbrr);
   337 				else
   338 					IA32_Lea_Reg_DispRegMultImm8(&m_HookFunc, REG_ECX, REG_NOIDX, REG_ESP, NOSCALE, 4);
   339 				
   340 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_EAX, REG_EBP, param_offset);
   341 				IA32_Push_Reg(&m_HookFunc, REG_EAX);
   342 				GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
   343 				IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EDX, DownCastPtr(pi.pCopyCtor));
   344 				IA32_Call_Reg(&m_HookFunc, REG_EDX);
   345 				GCC_ONLY(IA32_Add_Rm_ImmAuto(&m_HookFunc, REG_ESP, 2 * SIZE_PTR, MOD_REG));
   346 				IA32_Pop_Reg(&m_HookFunc, REG_EAX);
   347 			}
   348 			else
   349 			{
   350 				// bitwise copy
   351 
   352 				
   353 				BitwiseCopy_Setup();
   354 
   355 				//if forcedbyref:
   356 				//  lea edi, [ebp_place_fbrr]
   357 				//else
   358 				//  lea edi, [esp+8]			-  bc_setup pushed two regs onto the stack!
   359 				//lea esi, [ebp+<offs>]
   360 				if (pi.flags & PassFlag_ForcedByRef)
   361 					IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_EDI, REG_EBP, place_fbrr);
   362 				else
   363 					IA32_Lea_Reg_DispRegMultImm8(&m_HookFunc, REG_EDI, REG_NOIDX, REG_ESP, NOSCALE, 8);
   364 
   365 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ESI, REG_EBP, param_offset);
   366 
   367 				BitwiseCopy_Do(pi.size);
   368 			}
   369 
   370 			// forcedref: push reference to ebp+place_fbrr
   371 			if (pi.flags & PassFlag_ForcedByRef)
   372 			{
   373 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, place_fbrr);
   374 				IA32_Push_Reg(&m_HookFunc, REG_ECX);
   375 				return SIZE_PTR;
   376 			}
   377 			
   378 			return DownCastSize(pi.size);
   379 		}
   380 
   381 		void GenContext::DestroyParams(jit_int32_t fbrr_base)
   382 		{
   383 			for (int i = m_Proto.GetNumOfParams() - 1; i >= 0; --i)
   384 			{
   385 				const IntPassInfo &pi = m_Proto.GetParam(i);
   386 				if (pi.type == PassInfo::PassType_Object && (pi.flags & PassInfo::PassFlag_ODtor) &&
   387 					(pi.flags & PassInfo::PassFlag_ByVal) && (pi.flags & PassFlag_ForcedByRef))
   388 				{
   389 					IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, fbrr_base + GetForcedByRefParamOffset(i));
   390 					IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(pi.pDtor));
   391 					IA32_Call_Reg(&m_HookFunc, REG_EAX);
   392 				}
   393 			}
   394 		}
   395 		
   396 		// May not touch eax!
   397 		jit_int32_t GenContext::PushParams(jit_int32_t param_base_offset, jit_int32_t save_ret_to, int v_place_for_memret,
   398 				jit_int32_t v_place_fbrr_base)
   399 		{
   400 			jit_int32_t added_to_stack = 0;
   401 			jit_int32_t ret = 0;
   402 
   403 			// compute the offset _after_ the last parameter
   404 			jit_int32_t cur_offset = param_base_offset;
   405 			for (int i = 0; i < m_Proto.GetNumOfParams(); ++i)
   406 			{
   407 				cur_offset += GetStackSize(m_Proto.GetParam(i));
   408 			}
   409 
   410 			// push parameters in reverse order
   411 			for (int i = m_Proto.GetNumOfParams() - 1; i >= 0; --i)
   412 			{
   413 				const IntPassInfo &pi = m_Proto.GetParam(i);
   414 				cur_offset -= GetStackSize(pi);
   415 				if (pi.flags & PassInfo::PassFlag_ByVal)
   416 				{
   417 					switch (pi.type)
   418 					{
   419 					case PassInfo::PassType_Basic:
   420 						ret = PushBasic(cur_offset, pi);
   421 						break;
   422 					case PassInfo::PassType_Float:
   423 						ret = PushFloat(cur_offset, pi);
   424 						break;
   425 					case PassInfo::PassType_Object:
   426 						ret = PushObject(cur_offset, pi, v_place_fbrr_base + GetForcedByRefParamOffset(i));
   427 						break;
   428 					}
   429 				}
   430 				else if (pi.flags & PassInfo::PassFlag_ByRef)
   431 				{
   432 					PushRef(cur_offset, pi);
   433 				}
   434 				else
   435 				{
   436 					SH_ASSERT(0, ("Unsupported!"));
   437 				}
   438 				added_to_stack += ret;
   439 			}
   440 
   441 			return added_to_stack;
   442 		}
   443 
   444 		// It is IMPORTANT that PushMemRetPtr doesn't touch ecx and eax
   445 		jit_int32_t GenContext::PushMemRetPtr(jit_int32_t save_ret_to, jit_int32_t v_place_for_memret)
   446 		{
   447 			// Memory return support
   448 			if (m_Proto.GetRet().flags & PassInfo::PassFlag_RetMem)
   449 			{
   450 				// push address where to save it!
   451 				int reg = REG_EDX;
   452 				IA32_Lea_DispRegImmAuto(&m_HookFunc, reg, REG_EBP,
   453 					MemRetWithTempObj() ? v_place_for_memret : save_ret_to);
   454 				IA32_Push_Reg(&m_HookFunc, reg);
   455 
   456 				return (SH_COMP==SH_COMP_MSVC) ? 4 : 0;			// varargs funcs on msvc might need this.
   457 																// gcc doesn't: callee cleans the memret ptr, caller the other params :s
   458 			}
   459 			return 0;
   460 		}
   461 
   462 		void GenContext::SaveRetVal(int v_where, int v_place_for_memret)
   463 		{
   464 			size_t size = GetRealSize(m_Proto.GetRet());
   465 			if (size == 0)
   466 			{
   467 				// No return value -> nothing
   468 				return;
   469 			}
   470 
   471 			if (m_Proto.GetRet().flags & PassInfo::PassFlag_ByRef)
   472 			{
   473 				// mov [ebp + v_plugin_ret], eax
   474 				IA32_Mov_Rm_Reg_DispAuto(&m_HookFunc, REG_EBP, REG_EAX, v_where);
   475 				return;
   476 			}
   477 			// else: ByVal
   478 
   479 
   480 			// Memory return:
   481 			if (m_Proto.GetRet().flags & PassInfo::PassFlag_RetMem)
   482 			{
   483 				if (MemRetWithTempObj())
   484 				{
   485 					// *v_where = *v_place_for_memret
   486 
   487 					// if we have an assign operator, use that
   488 					if (m_Proto.GetRet().pAssignOperator)
   489 					{
   490 						// lea edx, [ebp + v_place_for_memret]  <-- src addr
   491 						// lea ecx, [ebp + v_where]				<-- dest addr
   492 						// push edx
   493 						// gcc: push ecx
   494 						// call it
   495 						// gcc: clean up
   496 
   497 						IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_EDX, REG_EBP, v_place_for_memret);
   498 						IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, v_where);
   499 						IA32_Push_Reg(&m_HookFunc, REG_EDX);
   500 						GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
   501 
   502 						IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(m_Proto.GetRet().pAssignOperator));
   503 						IA32_Call_Reg(&m_HookFunc, REG_EAX);
   504 						GCC_ONLY(IA32_Pop_Reg(&m_HookFunc, REG_ECX));
   505 					}
   506 					else
   507 					{
   508 						// bitwise copy
   509 						BitwiseCopy_Setup();
   510 
   511 						//lea edi, [evp+v_where]		<-- destination
   512 						//lea esi, [ebp+v_place_for_memret]	<-- src
   513 						IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_EDI, REG_EBP, v_where);
   514 						IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ESI, REG_EBP, v_place_for_memret);
   515 
   516 						BitwiseCopy_Do(m_Proto.GetRet().size);
   517 					}
   518 
   519 					// Then: destruct *v_place_for_memret if required
   520 					if (m_Proto.GetRet().pDtor)
   521 					{
   522 						//lea ecx, [ebp+v_place_for_memret]
   523 						//gcc: push ecx
   524 						//call it
   525 						//gcc: clean up
   526 
   527 						IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, v_place_for_memret);
   528 						GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
   529 						IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(m_Proto.GetRet().pDtor));
   530 						IA32_Call_Reg(&m_HookFunc, REG_EAX);
   531 						GCC_ONLY(IA32_Pop_Reg(&m_HookFunc, REG_ECX));
   532 					}
   533 				}
   534 				else
   535 				{
   536 					// Already copied to correct address -> we're done
   537 					return;
   538 				}
   539 			}
   540 
   541 			if (m_Proto.GetRet().type == PassInfo::PassType_Float)
   542 			{
   543 				if (size == 4)
   544 					IA32_Fstp_Mem32_DispAuto(&m_HookFunc, REG_EBP, v_where);
   545 				else if (size == 8)
   546 					IA32_Fstp_Mem64_DispAuto(&m_HookFunc, REG_EBP, v_where);
   547 			}
   548 			else if (m_Proto.GetRet().type == PassInfo::PassType_Basic)
   549 			{
   550 				if (size <= 4)
   551 				{
   552 					// size <= 4: return in EAX
   553 					//  We align <4 sizes up to 4
   554 
   555 
   556 					// mov [ebp + v_plugin_ret], eax
   557 					IA32_Mov_Rm_Reg_DispAuto(&m_HookFunc, REG_EBP, REG_EAX, v_where);
   558 				}
   559 				else if (size <= 8)
   560 				{
   561 					// size <= 4: return in EAX:EDX
   562 					//  We align 4<x<8 sizes up to 8
   563 
   564 					// mov [ebp + v_plugin_ret], eax
   565 					// mov [ebp + v_plugin_ret + 4], edx
   566 					IA32_Mov_Rm_Reg_DispAuto(&m_HookFunc, REG_EBP, REG_EAX, v_where);
   567 					IA32_Mov_Rm_Reg_DispAuto(&m_HookFunc, REG_EBP, REG_EDX, v_where + 4);
   568 				}
   569 			}
   570 			else if (m_Proto.GetRet().type == PassInfo::PassType_Object)
   571 			{
   572 				if (m_Proto.GetRet().flags & PassInfo::PassFlag_RetReg)
   573 				{
   574 					if (size <= 4)
   575 					{
   576 						// size <= 4: return in EAX
   577 						//  We align <4 sizes up to 4
   578 
   579 						// mov [ebp + v_plugin_ret], eax
   580 						IA32_Mov_Rm_Reg_DispAuto(&m_HookFunc, REG_EBP, REG_EAX, v_where);
   581 					}
   582 					else if (size <= 8)
   583 					{
   584 						// size <= 4: return in EAX:EDX
   585 						//  We align 4<x<8 sizes up to 8
   586 
   587 						// mov [ebp + v_plugin_ret], eax
   588 						// mov [ebp + v_plugin_ret + 4], edx
   589 						IA32_Mov_Rm_Reg_DispAuto(&m_HookFunc, REG_EBP, REG_EAX, v_where);
   590 						IA32_Mov_Rm_Reg_DispAuto(&m_HookFunc, REG_EBP, REG_EDX, v_where + 4);
   591 					}
   592 					else
   593 					{
   594 						SH_ASSERT(0, ("RetReg and size > 8 !"));
   595 					}
   596 				}
   597 			}
   598 		}
   599 
   600 		bool GenContext::MemRetWithTempObj()
   601 		{
   602 			// Memory return AND (has destructor OR has assign operator)
   603 			return ((m_Proto.GetRet().flags & PassInfo::PassFlag_RetMem)
   604 				&& (m_Proto.GetRet().flags & (PassInfo::PassFlag_ODtor | PassInfo::PassFlag_AssignOp)));
   605 		}
   606 
   607 		void GenContext::ProcessPluginRetVal(int v_cur_res, int v_pContext, int v_plugin_ret)
   608 		{
   609 			// only for non-void functions!
   610 			if (m_Proto.GetRet().size == 0)
   611 				return;
   612 
   613 			// if (cur_res >= MRES_OVERRIDE)
   614 			//   *reinterpret_cast<my_rettype*>(pContext->GetOverrideRetPtr()) = plugin_ret;
   615 
   616 			//  eax = cur_res
   617 			//  cmp eax,MRES_OVERRIDE
   618 			//  jnge thelabel
   619 			//    pContext->GetOverrideRetPtr()   -->  overrideretptr in eax
   620 			//    *eax = plugin_ret
   621 			//  thelabel:
   622 			//
   623 
   624 			jitoffs_t tmppos, counter;
   625 
   626 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_EAX, REG_EBP, v_cur_res);
   627 
   628 			IA32_Cmp_Rm_Imm32(&m_HookFunc, MOD_REG, REG_EAX, MRES_OVERRIDE);
   629 			tmppos = IA32_Jump_Cond_Imm8(&m_HookFunc, CC_NGE, 0);
   630 			m_HookFunc.start_count(counter);
   631 
   632 			// eax = pContext->GetOverrideRetPtr()
   633 			//   ECX = pContext
   634 			//   gcc: push ecx
   635 			//   eax = [ecx]
   636 			//   eax = [eax + 4]
   637 			//   call eax
   638 			//   gcc: clean up
   639 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_ECX, REG_EBP, v_pContext);
   640 			GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
   641 
   642 			// vtbloffs=0, vtblidx=1
   643 			IA32_Mov_Reg_Rm(&m_HookFunc, REG_EAX, REG_ECX, MOD_MEM_REG);
   644 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_EAX, REG_EAX, 4);
   645 			IA32_Call_Reg(&m_HookFunc, REG_EAX);
   646 			GCC_ONLY(IA32_Pop_Reg(&m_HookFunc, REG_ECX));
   647 
   648 
   649 			// *eax = plugin_ret
   650 			if (m_Proto.GetRet().flags & PassInfo::PassFlag_ByRef)
   651 			{
   652 				// mov ecx, [ebp+v_plugin_ret]
   653 				// mov [eax], ecx
   654 				IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_ECX, REG_EBP, v_plugin_ret);
   655 				IA32_Mov_Rm_Reg(&m_HookFunc, REG_EAX, REG_ECX, MOD_MEM_REG);
   656 			}
   657 			else
   658 			{
   659 				if (m_Proto.GetRet().pAssignOperator)
   660 				{
   661 					// lea edx, [ebp + v_plugin_ret]
   662 					// push edx					<-- src addr
   663 					// msvc: ecx = eax				<-- dest addr
   664 					// gcc: push eax				<-- dest addr
   665 					// call it
   666 					// gcc: clean up
   667 
   668 					IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_EDX, REG_EBP, v_plugin_ret);
   669 					IA32_Push_Reg(&m_HookFunc, REG_EDX);
   670 #if SH_COMP == SH_COMP_MSVC
   671 					IA32_Mov_Reg_Rm(&m_HookFunc, REG_ECX, REG_EAX, MOD_REG);
   672 #elif SH_COMP == SH_COMP_GCC
   673 					IA32_Push_Reg(&m_HookFunc, REG_EAX);
   674 #endif
   675 
   676 					IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(m_Proto.GetRet().pAssignOperator));
   677 					IA32_Call_Reg(&m_HookFunc, REG_EAX);
   678 					GCC_ONLY(IA32_Add_Rm_ImmAuto(&m_HookFunc, REG_ESP, 2 * SIZE_PTR, MOD_REG));
   679 				}
   680 				else
   681 				{
   682 					// bitwise copy
   683 					BitwiseCopy_Setup();
   684 
   685 					//mov edi, eax					<-- destination
   686 					//lea esi, [ebp+v_plugin_ret]	<-- src
   687 					IA32_Mov_Reg_Rm(&m_HookFunc, REG_EDI, REG_EAX, MOD_REG);
   688 					IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ESI, REG_EBP, v_plugin_ret);
   689 
   690 					BitwiseCopy_Do(m_Proto.GetRet().size);
   691 				}
   692 			}
   693 
   694 			m_HookFunc.end_count(counter);
   695 			m_HookFunc.rewrite(tmppos, static_cast<jit_uint8_t>(counter));
   696 		}
   697 
   698 		void GenContext::PrepareReturn(int v_status, int v_pContext, int v_retptr)
   699 		{
   700 			// only for non-void functions!
   701 			if (m_Proto.GetRet().size == 0)
   702 				return;
   703 
   704 			// retptr = status >= MRES_OVERRIDE ? pContext->GetOverrideRetPtr() : pContext->GetOrigRetPtr()
   705 
   706 			// OverrideRetPtr: vtblidx = 1
   707 			// OrigRetPtr: vtbldix = 2
   708 			//  vtblidx = (status >= MRES_OVERRIDE) ? 1 : 2
   709 
   710 			// 
   711 			// eax = pContext->GetOverrideRetPtr()
   712 			//   ECX = pContext
   713 			//   gcc: push ecx
   714 
   715 			// eax = (status < MRES_OVERRIDE) ? 1 : 0
   716 			//   xor eax, eax
   717 			//   cmp [ebp + v_status], MRES_OVERRIDE
   718 			//   setl al								<-- setcc optimization for ternary operators, 
   719 			
   720 
   721 			//   lea eax, [4*eax + 0x4]
   722 
   723 			//   edx = [ecx]
   724 			//   add edx, eax
   725 			//   mov edx, [edx]
   726 
   727 			//   call edx
   728 			// gcc: clean up
   729 
   730 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_ECX, REG_EBP, v_pContext);
   731 			GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
   732 			IA32_Xor_Reg_Rm(&m_HookFunc, REG_EAX, REG_EAX, MOD_REG);
   733 			IA32_Cmp_Rm_Disp8_Imm8(&m_HookFunc, REG_EBP, v_status, MRES_OVERRIDE);
   734 			IA32_SetCC_Rm8(&m_HookFunc, REG_EAX, CC_L);
   735 
   736 			IA32_Lea_Reg_RegMultImm32(&m_HookFunc, REG_EAX, REG_EAX, SCALE4, 4);
   737 
   738 			IA32_Mov_Reg_Rm(&m_HookFunc, REG_EDX, REG_ECX, MOD_MEM_REG);
   739 			IA32_Add_Reg_Rm(&m_HookFunc, REG_EDX, REG_EAX, MOD_REG);
   740 
   741 			IA32_Mov_Reg_Rm(&m_HookFunc, REG_EDX, REG_EDX, MOD_MEM_REG);
   742 			IA32_Call_Reg(&m_HookFunc, REG_EDX);
   743 			GCC_ONLY(IA32_Pop_Reg(&m_HookFunc, REG_ECX));
   744 
   745 			IA32_Mov_Rm_Reg_DispAuto(&m_HookFunc, REG_EBP, REG_EAX, v_retptr);
   746 		}
   747 
   748 		void GenContext::DoReturn(int v_retptr, int v_memret_outaddr)
   749 		{
   750 			size_t size = m_Proto.GetRet().size;
   751 			if (!size)
   752 				return;
   753 
   754 			// Get real ret pointer into ecx
   755 			// mov ecx, [ebp + v_ret_ptr]
   756 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_ECX, REG_EBP, v_retptr);
   757 
   758 			if (m_Proto.GetRet().flags & PassInfo::PassFlag_ByRef)
   759 			{
   760 				// mov eax, [ecx]
   761 				IA32_Mov_Reg_Rm(&m_HookFunc, REG_EAX, REG_ECX, MOD_MEM_REG);
   762 				return;
   763 			}
   764 			// else: byval
   765 
   766 			if (m_Proto.GetRet().type == PassInfo::PassType_Float)
   767 			{
   768 				if (size == 4)
   769 					IA32_Fld_Mem32(&m_HookFunc, REG_ECX);
   770 				else if (size == 8)
   771 					IA32_Fld_Mem64(&m_HookFunc, REG_ECX);
   772 			}
   773 			else if (m_Proto.GetRet().type == PassInfo::PassType_Basic || 
   774 				((m_Proto.GetRet().type == PassInfo::PassType_Object) && (m_Proto.GetRet().flags & PassInfo::PassFlag_RetReg)) )
   775 			{
   776 				if (size <= 4)
   777 				{
   778 					// size <= 4: return in EAX
   779 					//  We align <4 sizes up to 4
   780 
   781 					// mov eax, [ecx]
   782 					IA32_Mov_Reg_Rm(&m_HookFunc, REG_EAX, REG_ECX, MOD_MEM_REG);
   783 				}
   784 				else if (size <= 8)
   785 				{
   786 					// size <= 4: return in EAX:EDX
   787 					//  We align 4<x<8 sizes up to 8
   788 
   789 					// mov eax, [ecx]
   790 					// mov edx, [ecx+4]
   791 					IA32_Mov_Reg_Rm(&m_HookFunc, REG_EAX, REG_ECX, MOD_MEM_REG);
   792 					IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_EAX, REG_ECX, 4);
   793 				}
   794 				else
   795 				{
   796 					// size >8: return in memory
   797 					//  handled later
   798 				}
   799 			}
   800 
   801 			if (m_Proto.GetRet().flags & PassInfo::PassFlag_RetMem)
   802 			{
   803 				// *memret_outaddr = plugin_ret
   804 				if (m_Proto.GetRet().pCopyCtor)
   805 				{
   806 					// mov edx, ecx				<-- src	( we set ecx to [ebp+v_retptr] before )
   807 					// push edx					<-- src addr
   808 					// msvc: ecx = [ebp + v_memret_outaddr]				<-- dest addr
   809 					// gcc: push [ebp + v_memret_outaddr]				<-- dest addr
   810 					// call it
   811 					// gcc: clean up
   812 
   813 					IA32_Mov_Reg_Rm(&m_HookFunc, REG_EDX, REG_ECX, MOD_REG);
   814 					IA32_Push_Reg(&m_HookFunc, REG_EDX);
   815 
   816 #if SH_COMP == SH_COMP_MSVC
   817 					IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_ECX, REG_EBP, v_memret_outaddr);
   818 #elif SH_COMP == SH_COMP_GCC
   819 					IA32_Push_Rm_DispAuto(&m_HookFunc, REG_EBP, v_memret_outaddr);
   820 #endif
   821 
   822 					IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(m_Proto.GetRet().pCopyCtor));
   823 					IA32_Call_Reg(&m_HookFunc, REG_EAX);
   824 					GCC_ONLY(IA32_Add_Rm_ImmAuto(&m_HookFunc, REG_ESP, 2 * SIZE_PTR, MOD_REG));
   825 				}
   826 				else
   827 				{
   828 					// bitwise copy
   829 					BitwiseCopy_Setup();
   830 					
   831 					//mov edi, [ebp+v_memret_outaddr]		<-- destination
   832 					//mov esi, ecx						<-- src	( we set ecx to [ebp+v_retptr] before )
   833 					IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_EDI, REG_EBP, v_memret_outaddr);
   834 					IA32_Mov_Reg_Rm(&m_HookFunc, REG_ESI, REG_ECX, MOD_REG);
   835 
   836 					BitwiseCopy_Do(m_Proto.GetRet().size);
   837 				}
   838 
   839 				// In both cases: return the pointer in EAX
   840 				// mov eax, [ebp + v_memret_outaddr]
   841 				IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_EAX, REG_EBP, v_memret_outaddr);
   842 			}
   843 		}
   844 
   845 		void GenContext::GenerateCallHooks(int v_status, int v_prev_res, int v_cur_res, int v_iter,
   846 			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)
   847 		{
   848 			jitoffs_t counter, tmppos;
   849 			jitoffs_t counter2, tmppos2;
   850 
   851 			jitoffs_t loop_begin_counter;
   852 
   853 			// prev_res = MRES_IGNORED
   854 			IA32_Mov_Rm_Imm32_Disp8(&m_HookFunc, REG_EBP, MRES_IGNORED, v_prev_res);
   855 
   856 			m_HookFunc.start_count(loop_begin_counter);
   857 
   858 			// eax = pContext->GetNext()
   859 			//   ECX = pContext
   860 			//   gcc: push ecx
   861 			//   eax = [ecx]
   862 			//   eax = [eax]
   863 			//   call eax
   864 			// gcc: clean up
   865 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_ECX, REG_EBP, v_pContext);
   866 			GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
   867 
   868 			// vtbloffs=0, vtblidx=0
   869 			IA32_Mov_Reg_Rm(&m_HookFunc, REG_EAX, REG_ECX, MOD_MEM_REG);
   870 			IA32_Mov_Reg_Rm(&m_HookFunc, REG_EAX, REG_EAX, MOD_MEM_REG);
   871 			IA32_Call_Reg(&m_HookFunc, REG_EAX);
   872 			GCC_ONLY(IA32_Pop_Reg(&m_HookFunc, REG_ECX));
   873 
   874 			// quit on zero
   875 			//  test eax, eax
   876 			//  jz exit
   877 			IA32_Test_Rm_Reg(&m_HookFunc, REG_EAX, REG_EAX, MOD_REG);
   878 			tmppos = IA32_Jump_Cond_Imm32(&m_HookFunc, CC_Z, 0);
   879 			m_HookFunc.start_count(counter);
   880 
   881 			// prev_res = MRES_IGNORED
   882 			IA32_Mov_Rm_Imm32_Disp8(&m_HookFunc, REG_EBP, MRES_IGNORED, v_cur_res); 
   883 
   884 			// iter->call()
   885 			//  push params
   886 			//   ecx = eax
   887 			//   gcc: push ecx
   888 			//   eax = [ecx]
   889 			//   eax = [eax+2*SIZE_PTR]
   890 			//   call eax
   891 			//   gcc: clean up 
   892 			
   893 			jit_int32_t caller_clean_bytes = 0;			// gcc always, msvc never (hooks never have varargs!)
   894 			// vafmt: push va_buf
   895 			if (m_Proto.GetConvention() & ProtoInfo::CallConv_HasVafmt)
   896 			{
   897 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, v_va_buf);
   898 				IA32_Push_Reg(&m_HookFunc, REG_ECX);
   899 				caller_clean_bytes += SIZE_PTR;
   900 			}
   901 
   902 			caller_clean_bytes += PushParams(base_param_offset, v_plugin_ret, v_place_for_memret, v_place_fbrr_base);
   903 
   904 			IA32_Mov_Reg_Rm(&m_HookFunc, REG_ECX, REG_EAX, MOD_REG);
   905 			if (SH_COMP == SH_COMP_GCC)
   906 				IA32_Push_Reg(&m_HookFunc, REG_ECX);
   907 			caller_clean_bytes += PushMemRetPtr(v_plugin_ret, v_place_for_memret);
   908 			IA32_Mov_Reg_Rm(&m_HookFunc, REG_EAX, REG_ECX, MOD_MEM_REG);
   909 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_EAX, REG_EAX, 2*SIZE_PTR);
   910 			IA32_Call_Reg(&m_HookFunc, REG_EAX);
   911 
   912 			DestroyParams(v_place_fbrr_base);
   913 
   914 			SaveRetVal(v_plugin_ret, v_place_for_memret);
   915 
   916 			// cleanup (gcc only)
   917 			//   params + thisptr
   918 			if (SH_COMP == SH_COMP_GCC)
   919 				IA32_Add_Rm_ImmAuto(&m_HookFunc, REG_ESP, caller_clean_bytes + SIZE_PTR, MOD_REG);
   920 
   921 			// process meta return:
   922 			//  prev_res = cur_res
   923 			//  if (cur_res > status) status = cur_res;
   924 			//
   925 			//  eax = cur_res
   926 			//  edx = status
   927 			//  prev_res = eax
   928 			//  cmp eax,edx
   929 			//  jng thelabel
   930 			//  status = eax
   931 			//  thelabel:
   932 			//
   933 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_EAX, REG_EBP, v_cur_res);
   934 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_EDX, REG_EBP, v_status);
   935 			IA32_Mov_Rm_Reg_Disp8(&m_HookFunc, REG_EBP, REG_EAX, v_prev_res);
   936 
   937 			IA32_Cmp_Reg_Rm(&m_HookFunc, REG_EAX, REG_EDX, MOD_REG);
   938 			tmppos2 = IA32_Jump_Cond_Imm8(&m_HookFunc, CC_NG, 0);
   939 			m_HookFunc.start_count(counter2);
   940 
   941 			IA32_Mov_Rm_Reg_Disp8(&m_HookFunc, REG_EBP, REG_EAX, v_status);
   942 
   943 			m_HookFunc.end_count(counter2);
   944 			m_HookFunc.rewrite(tmppos2, static_cast<jit_uint8_t>(counter2));
   945 
   946 			// process retval for non-void functions
   947 			ProcessPluginRetVal(v_cur_res, v_pContext, v_plugin_ret);
   948 
   949 			// jump back to loop begin
   950 			tmppos2 = IA32_Jump_Imm32(&m_HookFunc, 0);
   951 			m_HookFunc.end_count(loop_begin_counter);
   952 			m_HookFunc.rewrite(tmppos2, -static_cast<jit_int32_t>(loop_begin_counter));
   953 
   954 			m_HookFunc.end_count(counter);
   955 			m_HookFunc.rewrite(tmppos, static_cast<jit_int32_t>(counter));
   956 		}
   957 
   958 		void GenContext::GenerateCallOrig(int v_status, int v_pContext, int param_base_offs, int v_this,
   959 			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)
   960 		{
   961 			jitoffs_t counter, tmppos;
   962 			jitoffs_t counter2, tmppos2;
   963 			jitoffs_t counter3, tmppos3;
   964 
   965 			// if (status != MRES_SUPERCEDE && pConteext->ShouldCallOrig())
   966 			//   *v_orig_ret = orig_call()
   967 			// else
   968 			//   *v_orig_ret = *v_override_ret
   969 
   970 			// mov eax, status
   971 			// cmp eax, MRES_SUPERCEDE
   972 			// je dont_call
   973 			// call pContext->ShouldCallOrig()
   974 			// test al, al						!! important: al, not eax! bool is only stored in the LSbyte
   975 			// jz dont_call
   976 			//
   977 			//  orig_call()
   978 			//  SaveRet(v_orig_ret)
   979 			//  jmp skip_dont_call:
   980 			//
   981 			// dont_call:
   982 			//  *v_orig_ret = *v_override_ret
   983 			// skip_dont_call:
   984 
   985 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_EAX, REG_EBP, v_status);
   986 			IA32_Cmp_Rm_Imm32(&m_HookFunc, MOD_REG, REG_EAX, MRES_SUPERCEDE);
   987 
   988 			tmppos = IA32_Jump_Cond_Imm32(&m_HookFunc, CC_E, 0);
   989 			m_HookFunc.start_count(counter);
   990 
   991 			// eax = pContext->ShouldCallOrig()
   992 			//   ECX = pContext
   993 			//   gcc: push ecx
   994 			//   eax = [ecx]
   995 			//   eax = [eax + 3*SIZE_PTR]
   996 			//   call eax
   997 			// gcc: clean up
   998 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_ECX, REG_EBP, v_pContext);
   999 			GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
  1000 
  1001 			// vtbloffs=0, vtblidx=3
  1002 			IA32_Mov_Reg_Rm(&m_HookFunc, REG_EAX, REG_ECX, MOD_MEM_REG);
  1003 			IA32_Mov_Reg_Rm_Disp8(&m_HookFunc, REG_EAX, REG_EAX, 3*SIZE_PTR);
  1004 			IA32_Call_Reg(&m_HookFunc, REG_EAX);
  1005 			GCC_ONLY(IA32_Pop_Reg(&m_HookFunc, REG_ECX));
  1006 
  1007 			IA32_Test_Rm_Reg8(&m_HookFunc, REG_EAX, REG_EAX, MOD_REG);
  1008 			tmppos2 = IA32_Jump_Cond_Imm32(&m_HookFunc, CC_Z, 0);
  1009 			m_HookFunc.start_count(counter2);
  1010 
  1011 			jit_int32_t caller_clean_bytes = 0;			// gcc always, msvc when cdecl-like (varargs)
  1012 			
  1013 			// vafmt: push va_buf, then "%s"
  1014 			if (m_Proto.GetConvention() & ProtoInfo::CallConv_HasVafmt)
  1015 			{
  1016 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, v_va_buf);
  1017 				IA32_Push_Reg(&m_HookFunc, REG_ECX);
  1018 				IA32_Push_Imm32(&m_HookFunc, DownCastPtr("%s"));
  1019 				caller_clean_bytes += 2*SIZE_PTR;
  1020 			}
  1021 
  1022 			// push params
  1023 			caller_clean_bytes += PushParams(param_base_offs, v_orig_ret, v_place_for_memret, v_place_fbrr_base);
  1024 
  1025 			// thisptr
  1026 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_ECX, REG_EBP, v_this);
  1027 			if (SH_COMP == SH_COMP_GCC)
  1028 			{
  1029 				//  on gcc/mingw, this is the first parameter
  1030 				IA32_Push_Reg(&m_HookFunc, REG_ECX);
  1031 				//  on msvc without varargs, simply leave it in ecx
  1032 
  1033 				// actually, if we're returning in memory, this pointer is the second param
  1034 				// and the memret pointer is the real first parameter
  1035 				caller_clean_bytes += PushMemRetPtr(v_orig_ret, v_place_for_memret);
  1036 			}
  1037 			else
  1038 			{
  1039 				// On msvc, if we're returning in memory, the memret pointer is the first parameter
  1040 				caller_clean_bytes += PushMemRetPtr(v_orig_ret, v_place_for_memret);
  1041 
  1042 				// actually, with varargs, the this pointer is the first param and the memret ptr
  1043 				// is the second one
  1044 				if (m_Proto.GetConvention() & ProtoInfo::CallConv_HasVarArgs)
  1045 				{
  1046 					IA32_Push_Reg(&m_HookFunc, REG_ECX);
  1047 				}
  1048 			}
  1049 
  1050 			// call
  1051 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_EAX, REG_EBP, v_vfnptr_origentry);
  1052 			IA32_Call_Reg(&m_HookFunc, REG_EAX);
  1053 
  1054 			// cleanup
  1055 			if (SH_COMP == SH_COMP_GCC || (m_Proto.GetConvention() & ProtoInfo::CallConv_HasVarArgs))
  1056 				IA32_Add_Rm_ImmAuto(&m_HookFunc, REG_ESP, caller_clean_bytes + SIZE_PTR, MOD_REG);
  1057 
  1058 			DestroyParams(v_place_fbrr_base);
  1059 
  1060 			// save retval
  1061 			SaveRetVal(v_orig_ret, v_place_for_memret);
  1062 
  1063 			// Skip don't call variant
  1064 			tmppos3 = IA32_Jump_Imm32(&m_HookFunc, 0);
  1065 			m_HookFunc.start_count(counter3);
  1066 
  1067 
  1068 			// don't call:
  1069 			m_HookFunc.end_count(counter);
  1070 			m_HookFunc.rewrite(tmppos, static_cast<jit_uint32_t>(counter));
  1071 
  1072 			m_HookFunc.end_count(counter2);
  1073 			m_HookFunc.rewrite(tmppos2, static_cast<jit_uint32_t>(counter2));
  1074 
  1075 			// *v_orig_ret = *v_override_ret
  1076 			if (m_Proto.GetRet().flags & PassInfo::PassFlag_ByRef)
  1077 			{
  1078 				// mov ecx, [ebp + v_override_ret]
  1079 				// mov [ebp + v_orig_ret], ecx
  1080 
  1081 				IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_ECX, REG_EBP, v_override_ret);
  1082 				IA32_Mov_Rm_Reg_DispAuto(&m_HookFunc, REG_EBP, REG_ECX, v_orig_ret);
  1083 			}
  1084 			else
  1085 			{
  1086 				if (m_Proto.GetRet().pAssignOperator)
  1087 				{
  1088 					// lea edx, [ebp + v_override_ret]			<-- src addr
  1089 					// lea ecx, [ebp + v_orig_ret]				<-- dest addr
  1090 					// push edx					<-- src addr
  1091 					// gcc: push ecx
  1092 					// call it
  1093 					// gcc: clean up
  1094 
  1095 					IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_EDX, REG_EBP, v_override_ret);
  1096 					IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, v_orig_ret);
  1097 					IA32_Push_Reg(&m_HookFunc, REG_EDX);
  1098 					GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
  1099 
  1100 					IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(m_Proto.GetRet().pAssignOperator));
  1101 					IA32_Call_Reg(&m_HookFunc, REG_EAX);
  1102 					GCC_ONLY(IA32_Add_Rm_ImmAuto(&m_HookFunc, REG_ESP, 2*SIZE_PTR, MOD_REG));
  1103 				}
  1104 				else
  1105 				{
  1106 					// bitwise copy
  1107 					BitwiseCopy_Setup();
  1108 
  1109 					//lea edi, [ebp+v_orig_ret]			<-- destination
  1110 					//lea esi, [ebp+v_override_ret]		<-- src
  1111 					IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_EDI, REG_EBP, v_orig_ret);
  1112 					IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ESI, REG_EBP, v_override_ret);
  1113 
  1114 					BitwiseCopy_Do(m_Proto.GetRet().size);
  1115 				}
  1116 			}
  1117 
  1118 			// skip don't call label target:
  1119 			m_HookFunc.end_count(counter3);
  1120 			m_HookFunc.rewrite(tmppos3, static_cast<jit_uint32_t>(counter3));
  1121 		}
  1122 
  1123 		// Sets *v_pContext to return value
  1124 		void GenContext::CallSetupHookLoop(int v_orig_ret, int v_override_ret, 
  1125 			int v_cur_res, int v_prev_res, int v_status, int v_vfnptr_origentry,
  1126 			int v_this, int v_pContext)
  1127 		{
  1128 			// call shptr->SetupHookLoop(ms_HI, ourvfnptr, reinterpret_cast<void*>(this),
  1129 			//  &vfnptr_origentry, &status, &prev_res, &cur_res, &orig_ret, &override_ret);
  1130 			// The last two params are null for void funcs.
  1131 
  1132 			if (m_Proto.GetRet().size == 0)
  1133 			{
  1134 				// void
  1135 				IA32_Push_Imm8(&m_HookFunc, 0);		// orig_ret
  1136 				IA32_Push_Imm8(&m_HookFunc, 0);		// override_ret
  1137 			}
  1138 			else
  1139 			{
  1140 				// orig_ret and override_ret
  1141 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_EAX, REG_EBP, v_override_ret);
  1142 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_EDX, REG_EBP, v_orig_ret);
  1143 				IA32_Push_Reg(&m_HookFunc, REG_EAX);
  1144 				IA32_Push_Reg(&m_HookFunc, REG_EDX);
  1145 			}
  1146 
  1147 			// cur_res and prev_res
  1148 			IA32_Lea_DispRegImm8(&m_HookFunc, REG_EAX, REG_EBP, v_cur_res);
  1149 			IA32_Lea_DispRegImm8(&m_HookFunc, REG_EDX, REG_EBP, v_prev_res);
  1150 			IA32_Push_Reg(&m_HookFunc, REG_EAX);
  1151 			IA32_Push_Reg(&m_HookFunc, REG_EDX);
  1152 
  1153 			// status and vfnptr_origentry
  1154 			IA32_Lea_DispRegImm8(&m_HookFunc, REG_EAX, REG_EBP, v_status);
  1155 			IA32_Lea_DispRegImm8(&m_HookFunc, REG_EDX, REG_EBP, v_vfnptr_origentry);
  1156 			IA32_Push_Reg(&m_HookFunc, REG_EAX);
  1157 			IA32_Push_Reg(&m_HookFunc, REG_EDX);
  1158 
  1159 			// this
  1160 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_EAX, REG_EBP, v_this);
  1161 			IA32_Push_Reg(&m_HookFunc, REG_EAX);
  1162 
  1163 			// our vfn ptr
  1164 			//  *(this + vtbloffs) + SIZE_PTR*vtblidx
  1165 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_ECX, REG_EBP, v_this);			// get this into ecx (gcc!)
  1166 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_EAX, REG_ECX, m_VtblOffs);
  1167 			IA32_Add_Rm_ImmAuto(&m_HookFunc, REG_EAX, m_VtblIdx * SIZE_PTR, MOD_REG);
  1168 			IA32_Push_Reg(&m_HookFunc, REG_EAX);
  1169 
  1170 			// *m_pHI
  1171 			IA32_Mov_Rm_Imm32(&m_HookFunc, REG_EDX, DownCastPtr(m_pHI), MOD_REG);
  1172 			IA32_Mov_Reg_Rm(&m_HookFunc, REG_EAX, REG_EDX, MOD_MEM_REG);
  1173 			IA32_Push_Reg(&m_HookFunc, REG_EAX);
  1174 
  1175 			// set up thisptr
  1176 #if SH_COMP == SH_COMP_GCC
  1177 			//  on gcc/mingw, this is the first parameter
  1178 			GCC_ONLY(IA32_Push_Imm32(&m_HookFunc, DownCastPtr(m_SHPtr)));
  1179 #elif SH_COMP == SH_COMP_MSVC
  1180 			//  on msvc, it's ecx
  1181 			IA32_Mov_Reg_Imm32(&m_HookFunc, REG_ECX, DownCastPtr(m_SHPtr));
  1182 #endif
  1183 
  1184 			// call the function. vtbloffs = 0, vtblidx = 19
  1185 			// get vtptr into edx  --  we know shptr on jit time -> dereference it here!
  1186 			IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, 
  1187 				(*reinterpret_cast<jit_uint32_t**>(m_SHPtr))[19]);
  1188 
  1189 			IA32_Call_Reg(&m_HookFunc, REG_EAX);
  1190 
  1191 			// on gcc/mingw, we have to clean up after the call
  1192 			// 9 params + hidden thisptr param
  1193 			GCC_ONLY(IA32_Add_Rm_Imm8(&m_HookFunc, REG_ESP, 10*SIZE_PTR, MOD_REG));
  1194 
  1195 			// store return value
  1196 			IA32_Mov_Rm_Reg_Disp8(&m_HookFunc, REG_EBP, REG_EAX, v_pContext);
  1197 		}
  1198 
  1199 		void GenContext::CallEndContext(int v_pContext)
  1200 		{
  1201 			// call endcontext:
  1202 			// shptr->EndContext(pContex)
  1203 			IA32_Mov_Reg_Rm_DispAuto(&m_HookFunc, REG_EAX, REG_EBP, v_pContext);
  1204 			IA32_Push_Reg(&m_HookFunc, REG_EAX);
  1205 
  1206 			// thisptr
  1207 #if SH_COMP == SH_COMP_GCC
  1208 			//  on gcc/mingw, this is the first parameter
  1209 			IA32_Push_Imm32(&m_HookFunc, DownCastPtr(m_SHPtr));
  1210 #elif SH_COMP == SH_COMP_MSVC
  1211 			//  on msvc, it's ecx
  1212 			IA32_Mov_Reg_Imm32(&m_HookFunc, REG_ECX, DownCastPtr(m_SHPtr));
  1213 #endif
  1214 
  1215 			// get vtptr into edx  --  we know shptr on jit time -> dereference it here!
  1216 			IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, 
  1217 				(*reinterpret_cast<jit_uint32_t**>(m_SHPtr))[20]);
  1218 
  1219 			IA32_Call_Reg(&m_HookFunc, REG_EAX);
  1220 
  1221 			// on gcc/mingw, we have to clean up after the call
  1222 			// 1 param + hidden thisptr param
  1223 			GCC_ONLY(IA32_Add_Rm_Imm8(&m_HookFunc, REG_ESP, 2*SIZE_PTR, MOD_REG));
  1224 		}
  1225 
  1226 		void GenContext::ResetFrame(jit_int32_t startOffset)
  1227 		{
  1228 			m_HookFunc_FrameOffset = startOffset;
  1229 			m_HookFunc_FrameVarsSize = 0;
  1230 		}
  1231 		
  1232 		jit_int32_t GenContext::AddVarToFrame(jit_int32_t size)
  1233 		{
  1234 			m_HookFunc_FrameOffset -= size;
  1235 			m_HookFunc_FrameVarsSize += size;
  1236 			return m_HookFunc_FrameOffset;
  1237 		}
  1238 
  1239 		jit_int32_t GenContext::ComputeVarsSize()
  1240 		{
  1241 			return m_HookFunc_FrameVarsSize;
  1242 		}
  1243 		
  1244 		void * GenContext::GenerateHookFunc()
  1245 		{
  1246 			// prologue
  1247 			IA32_Push_Reg(&m_HookFunc, REG_EBP);
  1248 			IA32_Push_Reg(&m_HookFunc, REG_EBX);
  1249 			IA32_Mov_Reg_Rm(&m_HookFunc, REG_EBP, REG_ESP, MOD_REG);
  1250 
  1251 			jit_int32_t v_this = 0;
  1252 			jit_int32_t param_base_offs = 0;
  1253 			if (SH_COMP == SH_COMP_GCC || (m_Proto.GetConvention() & ProtoInfo::CallConv_HasVarArgs))
  1254 			{
  1255 				// gcc or msvc with varargs:
  1256 				v_this = 12;		// first param
  1257 				param_base_offs = 16;
  1258 				ResetFrame(0);
  1259 			}
  1260 			else
  1261 			{
  1262 				// on msvc without varargs, save thisptr
  1263 				v_this = -4;
  1264 				param_base_offs = 12;
  1265 				IA32_Push_Reg(&m_HookFunc, REG_ECX);
  1266 				ResetFrame(-4);			// start placing local vars on offset -4
  1267 										// because there already is the thisptr variable
  1268 			}
  1269 
  1270 			// ********************** stack frame **********************
  1271 			//															MSVC without varargs
  1272 			//   second param (gcc: first real param)	ebp + 16
  1273 			//   first param (gcc: thisptr)				ebp + 12
  1274 			//   ret address:							ebp + 8
  1275 			//   caller's ebp							ebp + 4
  1276 			//   saved ebx								ebp
  1277 			//   MSVC ONLY:	current this				ebp - 4
  1278 			//   void *vfnptr_origentry					ebp - 4			-4
  1279 			//   META_RES status = MRES_IGNORED			ebp - 8			-4
  1280 			//   META_RES prev_res						ebp - 12		-4
  1281 			//   META_RES cur_res						ebp - 16		-4
  1282 			//   IMyDelegate *iter						ebp - 20		-4
  1283 			//   IHookContext *pContext					ebp - 24		-4
  1284 			//  == 3 ptrs + 3 enums = 24 bytes
  1285 			//
  1286 			// non-void: add:
  1287 			//   my_rettype *ret_ptr					ebp - 28 		-4
  1288 			//   my_rettype orig_ret					ebp - 28 - sizeof(my_rettype)			-4
  1289 			//   my_rettype override_ret				ebp - 28 - sizeof(my_rettype)*2			-4
  1290 			//   my_rettype plugin_ret					ebp - 28 - sizeof(my_rettype)*3			-4
  1291 			//  == + 3 * sizeof(my_rettype) bytes
  1292 
  1293 			// if required:
  1294 			//   my_rettype place_for_memret			ebp - 28 - sizeof(my_rettype)*4			-4
  1295 
  1296 			// gcc only: if required:
  1297 			//   place forced byref params              ebp - 28 - sizeof(my_rettype)*{4 or 5}
  1298 			//
  1299 			// varargs:
  1300 			//   va_list argptr
  1301 			//   char va_buf[something];
  1302 			
  1303 
  1304 			const jit_int8_t v_vfnptr_origentry =	AddVarToFrame(SIZE_PTR);
  1305 			const jit_int8_t v_status =				AddVarToFrame(sizeof(META_RES));
  1306 			const jit_int8_t v_prev_res =			AddVarToFrame(sizeof(META_RES));
  1307 			const jit_int8_t v_cur_res =			AddVarToFrame(sizeof(META_RES));
  1308 			const jit_int8_t v_iter =				AddVarToFrame(SIZE_PTR);
  1309 			const jit_int8_t v_pContext =			AddVarToFrame(SIZE_PTR);
  1310 
  1311 			// Memory return: first param is the address
  1312 			jit_int32_t v_memret_addr = 0;
  1313 			if (m_Proto.GetRet().flags & PassInfo::PassFlag_RetMem)
  1314 			{
  1315 				if (SH_COMP == SH_COMP_GCC)
  1316 				{
  1317 					// gcc: now:	first param = mem ret addr
  1318 					//				second param = this pointer
  1319 					//				third param = actual first param
  1320 					v_memret_addr = 12;
  1321 					v_this += 4;
  1322 					param_base_offs += SIZE_PTR;
  1323 				}
  1324 				else   // MSVC
  1325 				{
  1326 					if (m_Proto.GetConvention() & ProtoInfo::CallConv_HasVarArgs)
  1327 					{
  1328 						// varargs -> cdecl
  1329 						// msvc: now:
  1330 						//     first param = this pointer
  1331 						//     second param = mem ret addr
  1332 						//     third param = actual first param
  1333 
  1334 						// params_base_offs is already updated to point to after the this pointer
  1335 						v_memret_addr = param_base_offs;
  1336 						param_base_offs += SIZE_PTR;
  1337 					}
  1338 					else
  1339 					{
  1340 						v_memret_addr = param_base_offs;
  1341 						param_base_offs += SIZE_PTR;
  1342 					}
  1343 				}
  1344 			}
  1345 
  1346 			jit_int32_t v_ret_ptr = 0;
  1347 			jit_int32_t v_orig_ret = 0;
  1348 			jit_int32_t v_override_ret = 0;
  1349 			jit_int32_t v_plugin_ret = 0;
  1350 			
  1351 			if (m_Proto.GetRet().size != 0)
  1352 			{
  1353 				v_ret_ptr =				AddVarToFrame(SIZE_PTR);
  1354 				v_orig_ret =			AddVarToFrame(GetStackSize(m_Proto.GetRet()));
  1355 				v_override_ret =		AddVarToFrame(GetStackSize(m_Proto.GetRet()));
  1356 				v_plugin_ret =			AddVarToFrame(GetStackSize(m_Proto.GetRet()));
  1357 			}
  1358 
  1359 			jit_int32_t v_place_for_memret = 0;
  1360 			if (MemRetWithTempObj())
  1361 			{
  1362 				v_place_for_memret = 	AddVarToFrame(GetStackSize(m_Proto.GetRet()));
  1363 			}
  1364 
  1365 			jit_int32_t v_place_fbrr_base  = 0;
  1366 			if (SH_COMP == SH_COMP_GCC && GetForcedByRefParamsSize())
  1367 			{
  1368 				v_place_fbrr_base =		AddVarToFrame(GetForcedByRefParamsSize());
  1369 			}
  1370 
  1371 			// Only exists for varargs functions
  1372 			jit_int32_t v_va_argptr = 0;
  1373 			if (m_Proto.GetConvention() & ProtoInfo::CallConv_HasVarArgs)
  1374 			{
  1375 				v_va_argptr = AddVarToFrame(SIZE_PTR);
  1376 			}
  1377 			
  1378 			jit_int32_t v_va_buf = 0;
  1379 			if (m_Proto.GetConvention() & ProtoInfo::CallConv_HasVafmt)
  1380 			{
  1381 				v_va_buf = AddVarToFrame(SourceHook::STRBUF_LEN);
  1382 			}
  1383 			
  1384 			IA32_Sub_Rm_Imm32(&m_HookFunc, REG_ESP, ComputeVarsSize(), MOD_REG);
  1385 
  1386 			// init status localvar
  1387 			IA32_Mov_Rm_Imm32_Disp8(&m_HookFunc, REG_EBP, MRES_IGNORED, v_status);
  1388 
  1389 			// VarArgs: init argptr & format
  1390 			if (m_Proto.GetConvention() & ProtoInfo::CallConv_HasVarArgs)
  1391 			{
  1392 				// argptr = first vararg param
  1393 				// lea eax, [ebp + param_base_offs + paramssize]
  1394 				// mov argptr, eax
  1395 
  1396 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_EAX, REG_EBP, param_base_offs + GetParamsStackSize() + SIZE_PTR);	// +SIZE_PTR: last const char * is not in protoinfo
  1397 				IA32_Mov_Rm_Reg_DispAuto(&m_HookFunc, REG_EBP, REG_EAX, v_va_argptr);
  1398 			}
  1399 			if (m_Proto.GetConvention() & ProtoInfo::CallConv_HasVafmt)
  1400 			{
  1401 				// vsnprintf
  1402 				
  1403 				// push valist, fmt param, maxsize, buffer
  1404 				IA32_Push_Reg(&m_HookFunc, REG_EAX);
  1405 				IA32_Push_Rm_DispAuto(&m_HookFunc, REG_EBP, param_base_offs + GetParamsStackSize());		// last given param (+4-4, see above)
  1406 				IA32_Push_Imm32(&m_HookFunc, SourceHook::STRBUF_LEN - 1);
  1407 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, v_va_buf);
  1408 				IA32_Push_Reg(&m_HookFunc, REG_ECX);
  1409 				
  1410 				// call
  1411 				IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(&vsnprintf));
  1412 				IA32_Call_Reg(&m_HookFunc, REG_EAX);
  1413 
  1414 				// Clean up (cdecl)
  1415 				IA32_Add_Rm_Imm32(&m_HookFunc, REG_ESP, 0x10, MOD_REG);
  1416 
  1417 				// Set trailing zero
  1418 				IA32_Xor_Reg_Rm(&m_HookFunc, REG_EDX, REG_EDX, MOD_REG);
  1419 				IA32_Mov_Rm8_Reg8_DispAuto(&m_HookFunc, REG_EBP, REG_EDX, v_va_buf + SourceHook::STRBUF_LEN - 1);
  1420 			}
  1421 			
  1422 			// Call constructors for ret vars if required
  1423 			if((m_Proto.GetRet().flags & PassInfo::PassFlag_ByVal) &&
  1424 				m_Proto.GetRet().pNormalCtor)
  1425 			{
  1426 				// orig_reg
  1427 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, v_orig_ret);
  1428 				GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
  1429 				IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(m_Proto.GetRet().pNormalCtor));
  1430 				IA32_Call_Reg(&m_HookFunc, REG_EAX);
  1431 				GCC_ONLY(IA32_Pop_Reg(&m_HookFunc, REG_ECX));
  1432 
  1433 				// override_reg
  1434 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, v_override_ret);
  1435 				GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
  1436 				IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(m_Proto.GetRet().pNormalCtor));
  1437 				IA32_Call_Reg(&m_HookFunc, REG_EAX);
  1438 				GCC_ONLY(IA32_Pop_Reg(&m_HookFunc, REG_ECX));
  1439 
  1440 				// plugin_ret
  1441 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, v_plugin_ret);
  1442 				GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
  1443 				IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(m_Proto.GetRet().pNormalCtor));
  1444 				IA32_Call_Reg(&m_HookFunc, REG_EAX);
  1445 				GCC_ONLY(IA32_Pop_Reg(&m_HookFunc, REG_ECX));
  1446 
  1447 				// _don't_ call a constructor for v_place_for_memret !
  1448 			}
  1449 
  1450 			// ********************** SetupHookLoop **********************
  1451 			CallSetupHookLoop(v_orig_ret, v_override_ret, v_cur_res, v_prev_res, v_status, v_vfnptr_origentry,
  1452 				v_this, v_pContext);
  1453 
  1454 			// ********************** call pre hooks **********************
  1455 			GenerateCallHooks(v_status, v_prev_res, v_cur_res, v_iter, v_pContext, param_base_offs,
  1456 				v_plugin_ret, v_place_for_memret, v_place_fbrr_base, v_va_buf);
  1457 
  1458 			// ********************** call orig func **********************
  1459 			GenerateCallOrig(v_status, v_pContext, param_base_offs, v_this, v_vfnptr_origentry, v_orig_ret,
  1460 				v_override_ret, v_place_for_memret, v_place_fbrr_base, v_va_buf);
  1461 
  1462 			// ********************** call post hooks **********************
  1463 			GenerateCallHooks(v_status, v_prev_res, v_cur_res, v_iter, v_pContext, param_base_offs,
  1464 				v_plugin_ret, v_place_for_memret, v_place_fbrr_base, v_va_buf);
  1465 
  1466 			// ********************** end context and return **********************
  1467 
  1468 			PrepareReturn(v_status, v_pContext, v_ret_ptr);
  1469 
  1470 			CallEndContext(v_pContext);
  1471 
  1472 			// Call destructors of byval object params which have a destructor
  1473 			jit_int32_t cur_param_pos = param_base_offs;
  1474 			for (int i = 0; i < m_Proto.GetNumOfParams(); ++i)
  1475 			{
  1476 				const IntPassInfo &pi = m_Proto.GetParam(i);
  1477 				// GCC: NOT of forced byref params. the caller destructs those.
  1478 				if (pi.type == PassInfo::PassType_Object && (pi.flags & PassInfo::PassFlag_ODtor) &&
  1479 					(pi.flags & PassInfo::PassFlag_ByVal) && !(pi.flags & PassFlag_ForcedByRef))
  1480 				{
  1481 					IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, cur_param_pos);
  1482 					IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(pi.pDtor));
  1483 					IA32_Call_Reg(&m_HookFunc, REG_EAX);
  1484 				}
  1485 				cur_param_pos += GetStackSize(pi);
  1486 			}
  1487 
  1488 			DoReturn(v_ret_ptr, v_memret_addr);
  1489 
  1490 			// Call destructors of orig_ret/ ...
  1491 			if((m_Proto.GetRet().flags & PassInfo::PassFlag_ByVal) &&
  1492 				m_Proto.GetRet().pDtor)
  1493 			{
  1494 				// Preserve return value in EAX(:EDX)
  1495 				IA32_Push_Reg(&m_HookFunc, REG_EAX);
  1496 				IA32_Push_Reg(&m_HookFunc, REG_EDX);
  1497 
  1498 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, v_plugin_ret);
  1499 				GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
  1500 				IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(m_Proto.GetRet().pDtor));
  1501 				IA32_Call_Reg(&m_HookFunc, REG_EAX);
  1502 				GCC_ONLY(IA32_Pop_Reg(&m_HookFunc, REG_ECX));
  1503 
  1504 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, v_override_ret);
  1505 				GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
  1506 				IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(m_Proto.GetRet().pDtor));
  1507 				IA32_Call_Reg(&m_HookFunc, REG_EAX);
  1508 				GCC_ONLY(IA32_Pop_Reg(&m_HookFunc, REG_ECX));
  1509 
  1510 				IA32_Lea_DispRegImmAuto(&m_HookFunc, REG_ECX, REG_EBP, v_orig_ret);
  1511 				GCC_ONLY(IA32_Push_Reg(&m_HookFunc, REG_ECX));
  1512 				IA32_Mov_Reg_Imm32(&m_HookFunc, REG_EAX, DownCastPtr(m_Proto.GetRet().pDtor));
  1513 				IA32_Call_Reg(&m_HookFunc, REG_EAX);
  1514 				GCC_ONLY(IA32_Pop_Reg(&m_HookFunc, REG_ECX));
  1515 
  1516 				IA32_Pop_Reg(&m_HookFunc, REG_EDX);
  1517 				IA32_Pop_Reg(&m_HookFunc, REG_EAX);
  1518 			}
  1519 
  1520 			// epilogue
  1521 			IA32_Mov_Reg_Rm(&m_HookFunc, REG_ESP, REG_EBP, MOD_REG);
  1522 			IA32_Pop_Reg(&m_HookFunc, REG_EBX);
  1523 			IA32_Pop_Reg(&m_HookFunc, REG_EBP);
  1524 
  1525 			if (SH_COMP == SH_COMP_MSVC && !(m_Proto.GetConvention() & ProtoInfo::CallConv_HasVarArgs))
  1526 			{
  1527 				// msvc without varargs:
  1528 				//  callee cleans the stack
  1529 
  1530 				short cleansize = GetParamsStackSize();
  1531 				// Memory return: address is first param
  1532 				if (m_Proto.GetRet().flags & PassInfo::PassFlag_RetMem)
  1533 					cleansize += SIZE_PTR;
  1534 				
  1535 				IA32_Return_Popstack(&m_HookFunc, cleansize);
  1536 			}
  1537 			else
  1538 			{
  1539 				// gcc or msvc with varargs: caller cleans the stack
  1540 				//  exception: gcc removes the memret addr on memret: 
  1541 				if (SH_COMP == SH_COMP_GCC && (m_Proto.GetRet().flags & PassInfo::PassFlag_RetMem))
  1542 					IA32_Return_Popstack(&m_HookFunc, SIZE_PTR);
  1543 				else
  1544 					IA32_Return(&m_HookFunc);
  1545 			}
  1546 			
  1547 			
  1548 			// Store pointer for later use
  1549 			// m_HookfuncVfnPtr is a pointer to a void* because SH expects a pointer
  1550 			// into the hookman's vtable
  1551 			*m_HookfuncVfnptr = reinterpret_cast<void*>(m_HookFunc.GetData());
  1552 
  1553 			m_HookFunc.SetRE();
  1554 
  1555 			return m_HookFunc.GetData();
  1556 		}
  1557 
  1558 		// Pre-condition: GenerateHookFunc() has been called!
  1559 		void * GenContext::GeneratePubFunc()
  1560 		{
  1561 			jitoffs_t counter, tmppos;
  1562 
  1563 			// The pubfunc is a static cdecl function.
  1564 			// C Code:
  1565 			//  int HookManPubFunc(
  1566 			//     bool store,				ebp + 8
  1567 			//     IHookManagerInfo *hi		ebp + 12
  1568 			//     )
  1569 			//  {
  1570 			//    if (store)
  1571 			//      *m_pHI = hi;
  1572 			//    if (hi)
  1573 			//      hi->SetInfo(HOOKMAN_VERSION, m_VtblOffs, m_VtblIdx, m_Proto.GetProto(), m_HookfuncVfnptr)
  1574 			//  }
  1575 
  1576 			// prologue
  1577 			IA32_Push_Reg(&m_PubFunc, REG_EBP);
  1578 			IA32_Mov_Reg_Rm(&m_PubFunc, REG_EBP, REG_ESP, MOD_REG);
  1579 
  1580 			
  1581 			// save store in eax, hi in ecx
  1582 			IA32_Movzx_Reg32_Rm8_Disp8(&m_PubFunc, REG_EAX, REG_EBP, 8);
  1583 			IA32_Mov_Reg_Rm_DispAuto(&m_PubFunc, REG_ECX, REG_EBP, 12);
  1584 
  1585 			// Check for store == 0
  1586 			IA32_Test_Rm_Reg8(&m_PubFunc, REG_EAX, REG_EAX, MOD_REG);
  1587 			tmppos = IA32_Jump_Cond_Imm8(&m_PubFunc, CC_Z, 0);
  1588 			m_PubFunc.start_count(counter);
  1589 
  1590 			// nonzero -> store hi
  1591 			IA32_Mov_Rm_Imm32(&m_PubFunc, REG_EDX, DownCastPtr(m_pHI), MOD_REG);
  1592 			IA32_Mov_Rm_Reg(&m_PubFunc, REG_EDX, REG_ECX, MOD_MEM_REG);
  1593 
  1594 			// zero
  1595 			m_PubFunc.end_count(counter);
  1596 			m_PubFunc.rewrite(tmppos, static_cast<jit_uint8_t>(counter));
  1597 
  1598 			// check for hi == 0
  1599 			IA32_Test_Rm_Reg(&m_PubFunc, REG_ECX, REG_ECX, MOD_REG);
  1600 			tmppos = IA32_Jump_Cond_Imm8(&m_PubFunc, CC_Z, 0);
  1601 			m_PubFunc.start_count(counter);
  1602 
  1603 			// nonzero -> call vfunc
  1604 			//  push params in reverse order
  1605 			IA32_Push_Imm32(&m_PubFunc, DownCastPtr(m_HookfuncVfnptr));
  1606 			IA32_Push_Imm32(&m_PubFunc, DownCastPtr(m_BuiltPI));
  1607 			IA32_Push_Imm32(&m_PubFunc, m_VtblIdx);
  1608 			IA32_Push_Imm32(&m_PubFunc, m_VtblOffs);
  1609 			IA32_Push_Imm32(&m_PubFunc, SH_HOOKMAN_VERSION);
  1610 
  1611 			//  hi == this is in ecx
  1612 			//  on gcc/mingw, ecx is the first parameter
  1613 #if SH_COMP == SH_COMP_GCC
  1614 			IA32_Push_Reg(&m_PubFunc, REG_ECX);
  1615 #endif
  1616 			
  1617 			// call the function. vtbloffs = 0, vtblidx = 0
  1618 			// get vtptr into edx
  1619 			IA32_Mov_Reg_Rm(&m_PubFunc, REG_EDX, REG_ECX, MOD_MEM_REG);
  1620 			// get funcptr into eax
  1621 			IA32_Mov_Reg_Rm(&m_PubFunc, REG_EAX, REG_EDX, MOD_MEM_REG);
  1622 
  1623 			IA32_Call_Reg(&m_PubFunc, REG_EAX);
  1624 
  1625 			// on gcc/mingw, we have to clean up after the call
  1626 #if SH_COMP == SH_COMP_GCC
  1627 			// 5 params + hidden thisptr param
  1628 			IA32_Add_Rm_Imm8(&m_PubFunc, REG_ESP, 6*SIZE_MWORD, MOD_REG);
  1629 #endif
  1630 
  1631 			// zero
  1632 			m_PubFunc.end_count(counter);
  1633 			m_PubFunc.rewrite(tmppos, static_cast<jit_uint8_t>(counter));
  1634 
  1635 			// return value
  1636 			IA32_Xor_Reg_Rm(&m_PubFunc, REG_EAX, REG_EAX, MOD_REG);
  1637 
  1638 			// epilogue
  1639 			IA32_Mov_Reg_Rm(&m_PubFunc, REG_ESP, REG_EBP, MOD_REG);
  1640 			IA32_Pop_Reg(&m_PubFunc, REG_EBP);
  1641 			IA32_Return(&m_PubFunc);
  1642 
  1643 			m_PubFunc.SetRE();
  1644 
  1645 			return m_PubFunc;
  1646 		}
  1647 
  1648 		bool GenContext::PassInfoSupported(const IntPassInfo &pi, bool is_ret)
  1649 		{
  1650 			// :TODO: Error returns
  1651 			if (pi.type != PassInfo::PassType_Basic &&
  1652 				pi.type != PassInfo::PassType_Float &&
  1653 				pi.type != PassInfo::PassType_Object)
  1654 			{
  1655 				return false;
  1656 			}
  1657 
  1658 			if (pi.type == PassInfo::PassType_Object &&
  1659 				(pi.flags & PassInfo::PassFlag_ByVal))
  1660 			{
  1661 				if ((pi.flags & PassInfo::PassFlag_CCtor) && !pi.pCopyCtor)
  1662 				{
  1663 					return false;
  1664 				}
  1665 
  1666 				if ((pi.flags & PassInfo::PassFlag_ODtor) && !pi.pDtor)
  1667 				{
  1668 					return false;
  1669 				}
  1670 				
  1671 				if ((pi.flags & PassInfo::PassFlag_AssignOp) && !pi.pAssignOperator)
  1672 				{
  1673 					return false;
  1674 				}
  1675 
  1676 				if ((pi.flags & PassInfo::PassFlag_OCtor) && !pi.pNormalCtor)
  1677 				{
  1678 					return false;
  1679 				}
  1680 			}
  1681 
  1682 			if ((pi.flags & (PassInfo::PassFlag_ByVal | PassInfo::PassFlag_ByRef)) == 0)
  1683 			{
  1684 				return false;			 // Neither byval nor byref!
  1685 			}
  1686 			return true;
  1687 		}
  1688 
  1689 		void GenContext::AutoDetectRetType()
  1690 		{
  1691 			IntPassInfo &pi = m_Proto.GetRet();
  1692 
  1693 			// Only relevant for byval types
  1694 			if (pi.flags & PassInfo::PassFlag_ByVal)
  1695 			{
  1696 				// Basic + float: 
  1697 				if (pi.type == PassInfo::PassType_Basic ||
  1698 					pi.type == PassInfo::PassType_Float)
  1699 				{
  1700 					// <= 8 bytes:
  1701 					//    _always_ in registers, no matter what the user says
  1702 					if (pi.size <= 8)
  1703 					{
  1704 						pi.flags &= ~PassInfo::PassFlag_RetMem;
  1705 						pi.flags |= PassInfo::PassFlag_RetReg;
  1706 					}
  1707 					else
  1708 					{
  1709 						// Does this even exist? No idea, if it does: in memory!
  1710 						pi.flags &= ~PassInfo::PassFlag_RetReg;
  1711 						pi.flags |= PassInfo::PassFlag_RetMem;
  1712 					}
  1713 				}
  1714 				// Object: 
  1715 				else if (pi.type == PassInfo::PassType_Object)
  1716 				{
  1717 					// If the user says nothing, auto-detect
  1718 					if ((pi.flags & (PassInfo::PassFlag_RetMem | PassInfo::PassFlag_RetReg)) == 0)
  1719 					{
  1720 #if SH_COMP == SH_COMP_MSVC
  1721 						// MSVC seems to return _all_ structs, classes, unions in memory
  1722 						pi.flags |= PassInfo::PassFlag_RetMem;
  1723 #elif SH_COMP == SH_COMP_GCC
  1724 						// Same goes for GCC :)
  1725 						pi.flags |= PassInfo::PassFlag_RetMem;
  1726 #endif
  1727 					}
  1728 				}
  1729 			}
  1730 			else
  1731 			{
  1732 				// byref: make sure that the flag is _not_ set
  1733 				pi.flags &= ~PassInfo::PassFlag_RetMem;
  1734 				pi.flags |= PassInfo::PassFlag_RetReg;
  1735 			}
  1736 		}
  1737 
  1738 		void GenContext::AutoDetectParamFlags()
  1739 		{
  1740 #if SH_COMP == SH_COMP_GCC
  1741 			// On GCC, all objects are passed by reference if they have a destructor
  1742 			for (int i = 0; i < m_Proto.GetNumOfParams(); ++i)
  1743 			{
  1744 				IntPassInfo &pi = m_Proto.GetParam(i);
  1745 				if (pi.type == PassInfo::PassType_Object &&
  1746 					(pi.flags & PassInfo::PassFlag_ODtor))
  1747 				{
  1748 					pi.flags |= PassFlag_ForcedByRef;
  1749 				}
  1750 			}
  1751 #endif
  1752 		}
  1753 
  1754 		HookManagerPubFunc GenContext::Generate()
  1755 		{
  1756 			Clear();
  1757 
  1758 			// Check conditions:
  1759 			// -1) good proto version
  1760 			//  0) we don't support unknown passtypes, convention, ...
  1761 			//  1) we don't support functions which return objects by value or take parameters by value
  1762 			//     that have a constructor, a destructor or an overloaded assignment op
  1763 			//     (we wouldn't know how to call it!)
  1764 
  1765 			if (m_Proto.GetVersion() < 1)
  1766 			{
  1767 				return NULL;
  1768 			}
  1769 
  1770 			AutoDetectRetType();
  1771 			AutoDetectParamFlags();
  1772 
  1773 			// Basically, we only support ThisCall/thiscall with varargs
  1774 			if ((m_Proto.GetConvention() & (~ProtoInfo::CallConv_HasVafmt)) != ProtoInfo::CallConv_ThisCall)
  1775 			{
  1776 				return NULL;
  1777 			}
  1778 
  1779 
  1780 			if (m_Proto.GetRet().size != 0 && !PassInfoSupported(m_Proto.GetRet(), true))
  1781 			{
  1782 				return NULL;
  1783 			}
  1784 
  1785 			for (int i = 0; i < m_Proto.GetNumOfParams(); ++i)
  1786 			{
  1787 				if (!PassInfoSupported(m_Proto.GetParam(i), false))
  1788 					return NULL;
  1789 			}
  1790 
  1791 			BuildProtoInfo();
  1792 			GenerateHookFunc();
  1793 			return fastdelegate::detail::horrible_cast<HookManagerPubFunc>(GeneratePubFunc());
  1794 		}
  1795 
  1796 		HookManagerPubFunc GenContext::GetPubFunc()
  1797 		{
  1798 			if (m_GeneratedPubFunc == 0)
  1799 				m_GeneratedPubFunc = Generate();
  1800 
  1801 			return m_GeneratedPubFunc;
  1802 		}
  1803 
  1804 		bool GenContext::Equal(const CProto &proto, int vtbl_offs, int vtbl_idx)
  1805 		{
  1806 			return (m_OrigProto.ExactlyEqual(proto) && m_VtblOffs == vtbl_offs && m_VtblIdx == vtbl_idx);
  1807 		}
  1808 
  1809 		bool GenContext::Equal(HookManagerPubFunc other)
  1810 		{
  1811 			return m_GeneratedPubFunc == other;
  1812 		}
  1813 
  1814 		// *********************************** class GenContextContainer
  1815 		CHookManagerAutoGen::CHookManagerAutoGen(ISourceHook *pSHPtr) : m_pSHPtr(pSHPtr)
  1816 		{
  1817 		}
  1818 
  1819 		CHookManagerAutoGen::~CHookManagerAutoGen()
  1820 		{
  1821 			for (List<StoredContext>::iterator iter = m_Contexts.begin(); iter != m_Contexts.end(); ++iter)
  1822 			{
  1823 				delete iter->m_GenContext;
  1824 			}
  1825 		}
  1826 
  1827 		int CHookManagerAutoGen::GetIfaceVersion()
  1828 		{
  1829 			return SH_HOOKMANAUTOGEN_IFACE_VERSION;
  1830 		}
  1831 
  1832 		int CHookManagerAutoGen::GetImplVersion()
  1833 		{
  1834 			return SH_HOOKMANAUTOGEN_IMPL_VERSION;
  1835 		}
  1836 
  1837 		HookManagerPubFunc CHookManagerAutoGen::MakeHookMan(const ProtoInfo *proto, int vtbl_offs, int vtbl_idx)
  1838 		{
  1839 			CProto mproto(proto);
  1840 			for (List<StoredContext>::iterator iter = m_Contexts.begin(); iter != m_Contexts.end(); ++iter)
  1841 			{
  1842 				if (iter->m_GenContext->Equal(mproto, vtbl_offs, vtbl_idx))
  1843 				{
  1844 					iter->m_RefCnt++;
  1845 					return iter->m_GenContext->GetPubFunc();
  1846 				}
  1847 			}
  1848 
  1849 			// Not found yet -> new one
  1850 			StoredContext sctx;
  1851 			sctx.m_RefCnt = 1;
  1852 			sctx.m_GenContext = new GenContext(proto, vtbl_offs, vtbl_idx, m_pSHPtr);
  1853 
  1854 			if (sctx.m_GenContext->GetPubFunc() == NULL)
  1855 			{
  1856 				return NULL;
  1857 			}
  1858 			else
  1859 			{
  1860 				m_Contexts.push_back(sctx);
  1861 				return sctx.m_GenContext->GetPubFunc();
  1862 			}
  1863 		}
  1864 
  1865 		void CHookManagerAutoGen::ReleaseHookMan(HookManagerPubFunc pubFunc)
  1866 		{
  1867 			for (List<StoredContext>::iterator iter = m_Contexts.begin(); iter != m_Contexts.end(); ++iter)
  1868 			{
  1869 				if (iter->m_GenContext->Equal(pubFunc))
  1870 				{
  1871 					iter->m_RefCnt--;
  1872 					if (iter->m_RefCnt == 0)
  1873 					{
  1874 						delete iter->m_GenContext;
  1875 						m_Contexts.erase(iter);
  1876 					}
  1877 					break;
  1878 				}
  1879 			}
  1880 		}
  1881 	}
  1882 }