BOOL ProcessGetPIDFromName()

in PPLGuard/utils.cpp [301:368]


BOOL ProcessGetPIDFromName(LPWSTR pwszProcessName, PDWORD pdwProcessId)
{
	BOOL bReturnValue = FALSE;

	HANDLE hProcessSnap = NULL;
	PROCESSENTRY32 pe32 = { 0 };
	DWORD dwProcessId = 0;
	DWORD dwMatchCount = 0;
	BOOL bMatch = FALSE;

	if ((hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) == INVALID_HANDLE_VALUE)
	{
		PrintLastError(L"CreateToolhelp32Snapshot");
		goto end;
	}

	pe32.dwSize = sizeof(PROCESSENTRY32);

	if (!Process32First(hProcessSnap, &pe32))
	{
		PrintLastError(L"Process32First");
		goto end;
	}

	do
	{
		bMatch = FALSE;

		if (_wcsicmp(pe32.szExeFile, pwszProcessName) == 0)
			bMatch = TRUE;
		else
		{
			if (PathCchRemoveExtension(pe32.szExeFile, wcslen(pe32.szExeFile) + 1) == S_OK)
			{
				if (_wcsicmp(pe32.szExeFile, pwszProcessName) == 0)
					bMatch = TRUE;
			}
		}

		if (bMatch)
		{
			dwProcessId = pe32.th32ProcessID;
			dwMatchCount++;
		}

	} while (Process32Next(hProcessSnap, &pe32));

	if (dwMatchCount == 0)
	{
		wprintf(L"[-] Failed to find a process that matches the provided name.\n");
		goto end;
	}

	if (dwMatchCount > 1)
	{
		wprintf(L"[-] Found more than one process that matches the provided name. Please provide a PID instead.\n");
		goto end;
	}

	*pdwProcessId = dwProcessId;
	bReturnValue = TRUE;

end:
	if (hProcessSnap)
		CloseHandle(hProcessSnap);

	return bReturnValue;
}