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