/****************************************************************************
**
** Copyright (C) 2019 BlackINT3
** Contact: https://github.com/BlackINT3/OpenArk
**
** GNU Lesser General Public License Usage (LGPL)
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "api-process.h"
#ifdef _ARKDRV_
#else
namespace ArkDrvApi {
namespace Process {
HANDLE WINAPI OpenProcessR0(DWORD access, BOOL inherit, DWORD pid)
{
	std::string outdata;
	PROCESS_OPEN_INFO info; 
	info.access = access;
	info.inherit = inherit;
	info.pid = pid;
	bool ret = IoControlDriver(IOCTL_ARK_PROCESS, PROCESS_OPEN, TO_STREAM(info), outdata);
	if (!ret) return NULL;
	HANDLE phd = (HANDLE)*(DWORD*)outdata.c_str();
	return phd;
}

HANDLE WINAPI OpenProcess(DWORD access, BOOL inherit, DWORD pid)
{
	if (pid == -1) return NULL;

	HANDLE phd = ::OpenProcess(access, inherit, pid);
	if (phd) return phd;

	if (GetLastError() != ERROR_ACCESS_DENIED) {
		ERR(L"OpenProcess pid:%d err:%d", pid, GetLastError());
		return NULL;
	}

	phd = OpenProcessR0(access, inherit, pid);
	if (!phd) {
		ERR(L"OpenProcess by Kernel pid:%d err:%d", pid, GetLastError());
		return NULL;
	}

	return phd;
}

HANDLE WINAPI OpenThreadR0(DWORD access, BOOL inherit, DWORD tid)
{
	std::string outdata;
	THREAD_OPEN_INFO info;
	info.access = access;
	info.inherit = inherit;
	info.tid = tid;
	bool ret = IoControlDriver(IOCTL_ARK_PROCESS, THREAD_OPEN, TO_STREAM(info), outdata);
	if (!ret) return NULL;
	HANDLE thd = (HANDLE)*(DWORD*)outdata.c_str();
	return thd;
}

HANDLE WINAPI OpenThread(DWORD access, BOOL inherit, DWORD tid)
{
	HANDLE thd = ::OpenThread(access, inherit, tid);
	if (!thd && GetLastError() == ERROR_ACCESS_DENIED) {
		thd = OpenThreadR0(access, inherit, tid);
		if (!thd) return 0;
	}
	return thd;
}
} // namespace Process
} // namespace ArkDrvApi
#endif