Loading

学习自建调试体系(三)

这部分是讲释放在OD插件中的资源文件,也就是一个驱动,然后安装驱动、卸载驱动的过程。主要关注点放在安装、卸载者部分代码上。

安装、启动服务

总结大致步骤如下:

  1. 获得服务控制管理器句柄(OpenSCManager)
  2. 获得服务句柄(CreateService)
  3. 如果CreateService失败,使用OpenService再次获得服务句柄
  4. StartService
//
// 安装服务
//
BOOL DbgObjInstallService(
	const wchar_t *SzPath,		//驱动路径
	const wchar_t *SzName)		//服务名称
{
	BOOL bRet = FALSE;
	DWORD dwLastError;
	SC_HANDLE hSCManager;
	SC_HANDLE hService = NULL;
	
  	// 获得服务控制管理器句柄
	if (hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS))
	{
        //获得服务句柄
		hService = CreateService(
			hSCManager, SzName,
			SzName, SERVICE_ALL_ACCESS,
			SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START,
			SERVICE_ERROR_IGNORE, SzPath,
			NULL, NULL, NULL, NULL, NULL
			);

		if (hService == NULL)
		{
          	//再次获得服务句柄
			hService = OpenService(hSCManager, SzName, SERVICE_ALL_ACCESS);

			if (!hService)
			{
				CloseServiceHandle(hSCManager);
				return FALSE;
			}

		}
		//开启服务
		bRet = StartService(hService, 0, NULL);
		if (!bRet)
		{
			dwLastError = GetLastError();
		}
	}

	if (hService)
	{
		CloseServiceHandle(hService);
	}

	if (hSCManager)
	{
		CloseServiceHandle(hSCManager);
	}

	return bRet;
}

卸载服务

//
// 卸载服务 参数:服务名称
//
BOOL DbgObjUnInstallService(wchar_t* SzServiceName)
{
	BOOL bRet = FALSE;
	SC_HANDLE hServiceMgr = NULL;
	SC_HANDLE hServiceDDK = NULL;
	SERVICE_STATUS SvrSta;

	do
	{
		//
		// 打开SCM管理器
		//
		hServiceMgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);

		if (hServiceMgr == NULL)
		{
			break;
		}

		//
		// 打开驱动所对应的服务
		//
		hServiceDDK = OpenService(hServiceMgr, SzServiceName, SERVICE_ALL_ACCESS);

		if (hServiceDDK == NULL)
		{
			break;
		}
		//
		// 关闭驱动所对应的服务
		//
		ControlService(hServiceDDK, SERVICE_CONTROL_STOP, &SvrSta);


		if (DeleteService(hServiceDDK))
		{
			bRet = TRUE;
		}

	} while (FALSE);		//while FALSE 是个什么鬼?

	if (hServiceDDK)
	{
		CloseServiceHandle(hServiceDDK);
	}

	if (hServiceMgr)
	{
		CloseServiceHandle(hServiceMgr);
	}

	return bRet;
}
posted @ 2016-04-20 19:27  Lnju  阅读(720)  评论(0编辑  收藏  举报