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