⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 driverloader.cpp

📁 PCI驱动程序,对于想要开发WDM驱动程序的人有非常好的应用价值
💻 CPP
📖 第 1 页 / 共 2 页
字号:
	return	ret;
}


/****************************************************************************
*
*    FUNCTION: LoadDeviceDriver( const TCHAR, const TCHAR, HANDLE *)
*
*    PURPOSE: Registers a driver with the SCM and then loads it.
*	Argument:
*		Name	:	symbolic link name of driver
*		Path	:	the system path of driver,such as \winnt\system32\drivers\*.sys
*		HANDLE	:	out handle of opened device
*
****************************************************************************/
BOOL DriverLoader::LoadDeviceDriver( const TCHAR * Name,const TCHAR * Path, HANDLE * lphDevice )
{
	CheckRight();

	SC_HANDLE	schSCManager;
	BOOL		okay;

	schSCManager = OpenSCManager(	NULL,	//lpComputer name
									NULL,	//SCM lpDatabase
									SC_MANAGER_ALL_ACCESS );//access type
	if( !schSCManager )
	{
		ERROR_DUMP( _T("DriverLoader::LoadDeviceDriver"), _T("OpenSCManager error") );
		return	FALSE;
	}

	//
	//	Remove previous instance
	//	Is it alreay in Registry ?
	//
	RemoveDriver( schSCManager, Name );

	//
	// Ignore success of installation: it may already be installed.
	//	Make a key in the registry(ERROR_SERVICE_EXISTS)
	//
	InstallDriver( schSCManager, Name, Path );
	
	//
	//	Ignore success of start: it may already be started.
	//	DriverEntry call ( if any )
	//
	StartDriver( schSCManager, Name );

	//
	// Do make sure we can open it.can't be ignored
	//
	okay = OpenDevice( Name, lphDevice );

 	CloseServiceHandle( schSCManager );

	return okay;
}


//
//
//	FUNCTION: InstallDriver( IN SC_HANDLE, IN LPCTSTR, IN LPCTSTR)
//
//	PURPOSE: Creates a driver service.That is ,create a Key in registry
//	Arguments	:	
//		SchSCManager	:	SCM handle
//		DriverLinkName		:	executive name of driver
//		ServiceExe		:	executive name of device driver			
//
//
BOOL	DriverLoader::InstallDriver(IN SC_HANDLE SchSCManager, 
									IN LPCTSTR DriverLinkName, IN LPCTSTR DrvSysPath)
{
	CheckRight();

    SC_HANDLE	schService;
	TCHAR		keyPath[MAX_PATH];	//total path of registry
	HKEY		key;
	BOOL		openStatus;

    //
    // NOTE: This creates an entry for a standalone driver. If this
    //       is modified for use with a driver that requires a Tag,
    //       Group, and/or Dependencies, it may be necessary to
    //       query the registry for existing driver information
    //       (in order to determine a unique Tag, etc.).
    //
    schService = CreateService( SchSCManager,			// SCManager database
                                DriverLinkName,			// name of service
                                _T("KMDDriver"),			// name to display
                                SERVICE_ALL_ACCESS,		// desired access
                                SERVICE_KERNEL_DRIVER,	// service type
                                SERVICE_DEMAND_START,	// start type
                                SERVICE_ERROR_NORMAL,	// error control type
                                DrvSysPath,				// service's binary
                                NULL,					// no load ordering group
                                NULL,					// no tag identifier
                                NULL,					// no dependencies
                                NULL,					// LocalSystem account
                                NULL );					// no password
    if ( schService == NULL )	//create failed
	{
		ERROR_DUMP( _T("DriverLoader::InstallDriver"), _T("Write registry error") );
	}
	//
	//	Open the registry key created just now to test if we are successed !
	//
	ZeroMemory(keyPath,sizeof(keyPath));

	if( !CopyFile( CurDir, driverPath, FALSE ) )	//copy driver executive file to the system dir
	{
		ERROR_DUMP( _T("DriverLoader::InstallDriver"), _T("CopyFile error") );
	}

	//
	// Get a handle to the key for driver so that it can be altered in the
	// next step.
	//
	_stprintf( keyPath,_T("%s\\%s"), _T("SYSTEM\\CurrentControlSet\\Services"), DriverLinkName );
	openStatus = RegOpenKeyEx (	HKEY_LOCAL_MACHINE,	//
								keyPath,			//sub key
								0,
								KEY_ALL_ACCESS,
								&key ) ;				//out key handle
	//
	// Check the return to make sure that the application could get a
	// handle to the key.
	//
	if (openStatus != ERROR_SUCCESS) 
	{
		//
		//	A problem has occured. Delete the service so that it is not
		//	installed.
		//
		DeleteService (schService) ;
		ERROR_DUMP( _T("DriverLoader::InstallDriver"), _T("Query registry error") );
		return	FALSE;
	}

	//
	// Delete the ImagePath value in the newly created key so that the
	// system looks for the driver in the normal location.
	//
	openStatus = RegDeleteValue( key, _T("ImagePath") );

	//
	// Make sure that the application could delete the value.
	//
	if( openStatus != ERROR_SUCCESS ) 
	{
		//
		// A problem has occurred. Delete the service so that it is not
		// installed and will not try to start.
		//
		RegCloseKey (key) ;
		DeleteService (schService) ;
		ERROR_DUMP( _T("DriverLoader::InstallDriver"), _T("Delete ImagePath error") );
		return	FALSE;
	}

	//
	// Close the key handle as it is no longer needed.
	//
	RegCloseKey (key) ;
    CloseServiceHandle( schService );
    return TRUE;
}


/****************************************************************************
*
*    FUNCTION: StartDriver( IN SC_HANDLE, IN LPCTSTR)
*
*    PURPOSE: Starts the driver service.
*	Argument:
*		SchSCManager	:	SCM handle
*		DrivreName		:	symbolink name
*
****************************************************************************/
BOOL	DriverLoader::StartDriver( IN SC_HANDLE SchSCManager, IN LPCTSTR DriverLinkName )
{
	CheckRight();

    SC_HANDLE  schService;
    BOOL       ret;

    schService = OpenService( SchSCManager,
                              DriverLinkName,
                              SERVICE_ALL_ACCESS);
    if ( schService == NULL )
	{
		ERROR_DUMP( _T("DriverLoader::StartDriver"), _T("Open Service error") );
        return FALSE;
	}

	//
	//	It will Make DriverEntry be called
	//
    ret = StartService( schService, 0, NULL )
       || GetLastError() == ERROR_SERVICE_ALREADY_RUNNING 
	   || GetLastError() == ERROR_SERVICE_DISABLED;
	
    if( !ret )
		ERROR_DUMP( _T("DriverLoader::StartDriver"), _T("StartService error") );
	CloseServiceHandle( schService );

    return ret;
}


/****************************************************************************
*
*    FUNCTION: OpenDevice( IN LPCTSTR, HANDLE *)
*
*    PURPOSE: Opens the device and returns a handle if desired.
*	Argument:
*		Drivername	:	symbolink name
*		lphDevice	:	device handle
****************************************************************************/

BOOL	DriverLoader::OpenDevice( IN LPCTSTR DriverLinkName, HANDLE * hDevice )
{
    CheckRight();

	TCHAR    completeDeviceName[64];
    HANDLE   hDriver;

    //------------------------------------------------------------------------
    // Create a \\.\XXX device name that CreateFile can use
    //
    // NOTE: We're making an assumption here that the driver
    //       has created a symbolic link using it's own name
    //       (i.e. if the driver has the name "XXX" we assume
    //       that it used IoCreateSymbolicLink to create a
    //       symbolic link "\DosDevices\XXX". Usually, there
    //       is this understanding between related apps/drivers.
    //
    //       An application might also peruse the DEVICEMAP
    //       section of the registry, or use the QueryDosDevice
    //       API to enumerate the existing symbolic links in the
    //       system.
    //------------------------------------------------------------------------

	/*	if( (GetVersion() & 0xFF) >= 5 ) */
	if(OsType>=WIN2KP)		//win2000 professional edition or higher editon
	{
		//------------------------------------------------------------------------
		// We reference the global name so that the application can
		// be executed in Terminal Services sessions on Win2K
		//------------------------------------------------------------------------
		_stprintf( completeDeviceName, _T("\\\\.\\Global\\%s"), DriverLinkName );

	} else {

		_stprintf( completeDeviceName, _T("\\\\.\\%s"), DriverLinkName );
	}

    hDriver = CreateFile( completeDeviceName,
                          GENERIC_READ | GENERIC_WRITE,
                          0,
                          NULL,
                          OPEN_EXISTING,
                          FILE_ATTRIBUTE_NORMAL,
                          NULL );
    if ( hDriver == INVALID_HANDLE_VALUE )
	{
		ERROR_DUMP( _T("DriverLoader::OpenDevice"), _T("CreateFile error") );
        return FALSE;
	}
	//
	// If user wants handle, give it to them.  Otherwise, just close it.
	//
	if ( hDevice )
		*hDevice = hDriver;
	else
	    CloseHandle( hDriver );
    return TRUE;
}



/****************************************************************************
*
*    FUNCTION: StopDriver( IN SC_HANDLE, IN LPCTSTR)
*
*    PURPOSE: Has the configuration manager stop the driver (unload it)
*
****************************************************************************/
BOOL	DriverLoader::StopDriver( IN SC_HANDLE SchSCManager, IN LPCTSTR DriverLinkName )
{
    SC_HANDLE       schService;
    BOOL            ret;
    SERVICE_STATUS  serviceStatus;

    schService = OpenService(	SchSCManager, 
								DriverLinkName, 
								SERVICE_ALL_ACCESS );
    if ( schService == NULL )
	{
		ERROR_DUMP( _T("DriverLoader::StopDriver"), _T("OpenService error") );
        return FALSE;
	}

    ret = ControlService(	schService, 
							SERVICE_CONTROL_STOP, 
							&serviceStatus 	);

    CloseServiceHandle( schService );
    return ret;
}


/****************************************************************************
*
*    FUNCTION: UnloadDeviceDriver( const TCHAR *)
*
*    PURPOSE: Stops the driver and has the configuration manager unload it.
*
****************************************************************************/
BOOL	DriverLoader::UnloadDeviceDriver( const TCHAR * Name )
{
	SC_HANDLE	schSCManager;

	schSCManager = OpenSCManager(	NULL,                 // machine (NULL == local)
                              		NULL,                 // database (NULL == default)
									SC_MANAGER_ALL_ACCESS); // access required
	StopDriver( schSCManager, Name );

	RemoveDriver( schSCManager, Name );	
	 
	CloseServiceHandle( schSCManager );

	return TRUE;
}

//--------------------------------------------------------------------
//
//	This is the first routine that user will call,it will call
//	LoadDeviceDriver routine at first
//	Argument:
//		None
//	Return	:
//		TRUE on success
//		FALSE on failure
//
//--------------------------------------------------------------------

BOOL	DriverLoader::RunDriver()
{
	CheckRight();

	BOOL	LoadOk	=	FALSE;

	LoadOk	=	LoadDeviceDriver(	DriverLinkName,
									driverPath,
									&DrvHandle );
	if( !LoadOk )
	{ 
		if( !(LoadOk = CopyFile(CurDir, driverPath, FALSE)) ) 
		{
			ERROR_DUMP( _T("DriverLoader::RunDriver"), _T("CopyFile error") );
			return	FALSE;						
		}
		SetFileAttributes( driverPath, FILE_ATTRIBUTE_NORMAL );
		LoadOk	=	LoadDeviceDriver(	DriverLinkName, 
										driverPath, 
										&DrvHandle );

		if( !LoadOk )
		{
			UnloadDeviceDriver( DriverLinkName );
			LoadOk	=	LoadDeviceDriver(	DriverLinkName,
											driverPath,
											&DrvHandle );
			if( !LoadOk )
			{
				ERROR_DUMP( _T("DriverLoader::RunDriver"), _T("LoadDeviceDriver error") );
				DeleteFile(driverPath);
				return	FALSE;
			}
		}
		DeleteFile( driverPath );
	}

	m_nDriverState	=	STARTED;
	return	LoadOk;
}


DWORD	DriverLoader::GetErrorCode()
{
#ifdef	_DEBUG
	return	dwErrorCode;
#else	
	return	0;
#endif
}

TCHAR *	DriverLoader::GetErrorString( )
{
#ifdef	_DEBUG
	return ErrorBuf;
#else	
	return	"Error";
#endif
}




⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -