// PatternFind.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <windows.h>
#include <tlhelp32.h>
#include "HijackTingMix.h"

struct GetProcessHandleAndModule
{
	std::wstring processName;
	std::wstring moduleName;
	HANDLE hProcess;
	HMODULE hModule;
};

bool GetProcessHandleAndModuleByName(PVOID lpParameter) {
	GetProcessHandleAndModule* pGetProcessHandleAndModule = (GetProcessHandleAndModule*)lpParameter;
	HANDLE handleSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (handleSnapshot) {
		PROCESSENTRY32 pe;
		pe.dwSize = sizeof(PROCESSENTRY32);
		if (Process32First(handleSnapshot, &pe)) {
			do {
				if (pe.szExeFile == pGetProcessHandleAndModule->processName)
				{
					pGetProcessHandleAndModule->hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
					CloseHandle(handleSnapshot);

					MODULEENTRY32 moduleEntry = { 0 };
					// 获取进程快照中包含在th32ProcessID中指定的进程的所有的模块。
					HANDLE hmoduleSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pe.th32ProcessID);
					/*ZeroMemory(&moduleEntry, sizeof(MODULEENTRY32));*/
					moduleEntry.dwSize = sizeof(MODULEENTRY32);
					do {
						if (moduleEntry.szModule == pGetProcessHandleAndModule->moduleName) {
							pGetProcessHandleAndModule->hModule = moduleEntry.hModule;
							return true; // 找到进程下的模块
						}
					} while (Module32Next(hmoduleSnapshot, &moduleEntry));
					CloseHandle(hmoduleSnapshot);
				}
			} while (Process32Next(handleSnapshot, &pe));
		}
		CloseHandle(handleSnapshot);
	}
	return false;
}
int main()
{
	std::string pattern = "0F 84 3?";
	GetProcessHandleAndModule* my = new GetProcessHandleAndModule();
	my->processName = my->moduleName = L"Test.exe";
	GetProcessHandleAndModuleByName((PVOID)my);
	clock_t nBeginTime = clock();
	// 0为进程全内存搜索，module为指定模块搜索
	std::vector<ULONG_PTR> retList;
	PatternFindEx(retList, my->hProcess, my->hModule, pattern, 0);
	std::cout << "共搜到：" << retList.size() << "个地址-->搜索时间：" << clock() - nBeginTime << " ms" << std::endl;
	for (int i = 0; i < retList.size(); i++)
	{
		std::cout << "第" << i + 1 << "个地址：" << (PVOID)retList[i] << std::endl;
	}

	//delete[] my; my = NULL;

	system("pause");
	return 0;
}