#include <windows.h>
#include "NsHiJack.h"
#include "hookLib/detours.h"
#include "HijackTingMix.h"

#ifdef _WIN64
#pragma comment (lib,"hookLib/detours_x64.lib")
#else
#pragma comment(lib, "hookLib/detours_x86.lib")
#endif

ULONG_PTR bp1;
static int (WINAPI* pOrigGetWindowTextA)(HWND  hWnd, LPSTR lpString, int   nMaxCount) = GetWindowTextA;
int WINAPI NewGetWindowTextA(HWND  hWnd, LPSTR lpString, int   nMaxCount)
{
	// 不显示调试信息，注释掉HijackTingMix.h调试输出总开关
	MyPrintf(L"劫持GetWindowTextA\n");

	// hook api等待程序解码
	// 使用特征码搜索定位断点地址
	std::vector<ULONG_PTR> retAddr; 
	PatternFindEx(retAddr, (HANDLE)-1, GetModuleHandle(NULL), "75 23 45 33 C9 4C 8D 05", 0);
	bp1 = retAddr[0];
	SetHwBreakpoint(GetCurrentThreadId(), TYPE_EXECUTE, SIZE_1, bp1);  //设置硬件断点

	return pOrigGetWindowTextA(hWnd, lpString, nMaxCount);
}

void StartHook()
{
	DetourRestoreAfterWith();
	DetourTransactionBegin();
	DetourUpdateThread(GetCurrentThread());
	DetourAttach(&(PVOID&)pOrigGetWindowTextA, NewGetWindowTextA);
	DetourTransactionCommit();
}

LONG NTAPI ExceptionHandler(EXCEPTION_POINTERS* ExceptionInfo)
{
	if ((ULONG_PTR)ExceptionInfo->ExceptionRecord->ExceptionAddress == bp1)
	{
		// 不显示调试信息，注释掉HijackTingMix.h调试输出总开关
		MyPrintf(L"bp1异常\n");

		// ZF赋值
		((PEFLAGS)&ExceptionInfo->ContextRecord->EFlags)->ZF = ~((PEFLAGS)&ExceptionInfo->ContextRecord->EFlags)->ZF;
		ExceptionInfo->ContextRecord->EFlags |= 1 << 16; //0x10000
		return EXCEPTION_CONTINUE_EXECUTION;
	}

	return EXCEPTION_CONTINUE_SEARCH;
}
BOOL APIENTRY DllMain(HMODULE hModule,
	DWORD  ul_reason_for_call,
	LPVOID lpReserved
)
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
	{
		AddVectoredExceptionHandler(1, ExceptionHandler);
		StartHook();
		if (!NsInitDll())
			return false;
		//LOADPYG64
	}
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}