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