/*
* HL Loader
* Copyright (c) goldfinder (goldfinder@ifrance.com) 2002
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "RedirectFunction.h"
#include "mempatcher.h"

#define MakePtr( cast, ptr, addValue )( cast )( ( DWORD )( ptr ) + ( DWORD )( addValue ) )

void *RedirectFunction( char *pSource, int iNbBytesToCopy, DWORD pDestination ) 
{ 
	DWORD old_attributes; 

	char *pTrampoline = new char[ iNbBytesToCopy + 5 ]; 
	memcpy( pTrampoline, pSource, iNbBytesToCopy ); 

	*( ( char * )( pTrampoline + iNbBytesToCopy ) ) = '\xE9';
	*( ( DWORD * )( pTrampoline + iNbBytesToCopy + 1 ) ) = (DWORD)pSource - ( (DWORD)pTrampoline + 5 ); 

	VirtualProtect( pSource, 5, PAGE_READWRITE, &old_attributes ); 
	*pSource = '\xE9';
	*( ( DWORD * )( pSource + 1 ) ) = pDestination - ( (DWORD)pSource + 5 ); 
	VirtualProtect( pSource, 5, old_attributes, &old_attributes ); 

	return ( void * )pTrampoline; 
}
