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