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