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