驱动管理类的封装

来源:互联网 发布:技校计算机专业软件 编辑:程序博客网 时间:2024/09/21 08:19

为了代码复用, 将NT驱动和MiniFilter的驱动操作(安装, 卸载, 启动, 停止)进行封装.

工程下载

srcDrvManager_2013_0609.rar 支持NT驱动和MiniFilter驱动的控制
srcDrvManager_2013_0610_1710.rar  增加了Sfilter驱动的控制

测试效果


用起来挺方便~

测试代码

// srcDrvManager.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "drvManagerNt.h"#include "drvManagerMiniFilter.h"void testNtDriver();void testMiniFilterDriver();int _tmain(int argc, _TCHAR* argv[]){    _tprintf(L">> _tmain\r\n");    testNtDriver();    testMiniFilterDriver();    _tprintf(L"END, press any key to quit\r\n");    getwchar();    return 0;}void testNtDriver(){    _tprintf(L">> testNtDriver\r\n");    DWORD           dwRc    =   DRV_MANAGER_OK;    CDrvManagerNt   Drv;    Drv.SetTargetName(L"HelloDrv");    Drv.SetDriverPathName(L".\\HelloDrv.sys");    _tprintf(L"press any key to Install\r\n");    getwchar();    dwRc = Drv.Install();    if (DRV_MANAGER_OK != dwRc)    {        _tprintf(L"err : dwRc = 0x%x\r\n", dwRc);        goto END_testNtDriver;    }    _tprintf(L"press any key to run\r\n");    getwchar();    dwRc = Drv.Run();    if (DRV_MANAGER_OK != dwRc)    {        _tprintf(L"err : dwRc = 0x%x\r\n", dwRc);        goto END_testNtDriver;    }    _tprintf(L"press any key to stop\r\n");    getwchar();    dwRc = Drv.Stop();    if (DRV_MANAGER_OK != dwRc)    {        _tprintf(L"err : dwRc = 0x%x\r\n", dwRc);        goto END_testNtDriver;    }    _tprintf(L"press any key to UnInstall\r\n");    getwchar();    dwRc = Drv.UnInstall();    if (DRV_MANAGER_OK != dwRc)        _tprintf(L"err : dwRc = 0x%x\r\n", dwRc);END_testNtDriver:    _tprintf(L"<< testNtDriver\r\n");}void testMiniFilterDriver(){    _tprintf(L">> testMiniFilterDriver\r\n");    DWORD                   dwRc    =   DRV_MANAGER_OK;    CDrvManagerMiniFilter   Drv;    Drv.SetTargetName(L"nullFilter");    Drv.SetDriverPathName(L".\\nullFilter.sys");    Drv.SetAltitude(L"370020");    _tprintf(L"press any key to Install\r\n");    getwchar();    dwRc = Drv.Install();    if (DRV_MANAGER_OK != dwRc)    {        _tprintf(L"err : dwRc = 0x%x\r\n", dwRc);        goto END_testMiniFilterDriver;    }    _tprintf(L"press any key to run\r\n");    getwchar();    dwRc = Drv.Run();    if (DRV_MANAGER_OK != dwRc)    {        _tprintf(L"err : dwRc = 0x%x\r\n", dwRc);        goto END_testMiniFilterDriver;    }    _tprintf(L"press any key to stop\r\n");    getwchar();    dwRc = Drv.Stop();    if (DRV_MANAGER_OK != dwRc)    {        _tprintf(L"err : dwRc = 0x%x\r\n", dwRc);        goto END_testMiniFilterDriver;    }    _tprintf(L"press any key to UnInstall\r\n");    getwchar();    dwRc = Drv.UnInstall();    if (DRV_MANAGER_OK != dwRc)        _tprintf(L"err : dwRc = 0x%x\r\n", dwRc);END_testMiniFilterDriver:    _tprintf(L"<< testMiniFilterDriver\r\n");}

驱动管理基类定义

/// @file           \Helper\srcDrvManager\drvManager.h/// @brief          驱动管理类的基类定义#ifndef __HELPER_SRCDRVMANAGER_DRVMANAGER_H__#define __HELPER_SRCDRVMANAGER_DRVMANAGER_H__/// 错误码定义/// 如果没有API返回的错误码, 需要自定义#define DRV_MANAGER_ERR_BASE        0x80000000#define DRV_MANAGER_OK              S_OK#define DRV_MANAGER_NOT_IMP                 DRV_MANAGER_ERR_BASE + 1 ///< 未实现#define DRV_MANAGER_INVALID_PARAM           DRV_MANAGER_ERR_BASE + 2#define DRV_MANAGER_OPEN_SCM                DRV_MANAGER_ERR_BASE + 3#define DRV_MANAGER_CREATE_SERVICE          DRV_MANAGER_ERR_BASE + 4#define DRV_MANAGER_START_SERVICE           DRV_MANAGER_ERR_BASE + 5#define DRV_MANAGER_SERVICE_CONTROL_STOP    DRV_MANAGER_ERR_BASE + 6#define DRV_MANAGER_NOT_SERVICE_STOPPED     DRV_MANAGER_ERR_BASE + 7#define DRV_MANAGER_DELETE_SERVICE          DRV_MANAGER_ERR_BASE + 8/// 求一个宽字符串的字节数量#ifndef SIZEOF_WSTRING#define SIZEOF_WSTRING(x)   (_tcslen(x) * sizeof(wchar_t))#endif#pragma warning(disable : 4996)#include <string>class CDrvManager{public:    enum e_DrvType              ///< 驱动类型    {        e_DrvTypeNt =   0,      ///< NT驱动        e_DrvTypeMiniFilter,    ///< MiniFilter驱动        e_DrvTypeUnknown        ///< 未知驱动类型, 暂不支持    };public:    CDrvManager();    virtual ~CDrvManager();    //////////////////////////////////////////////////////////////////////////    /// 驱动的安装,卸载,启动,停止是由基类实现    /// 由基类决定操作流程(e.g. 安装驱动时, 操作完SCM, 在注册表中写点东西)    //////////////////////////////////////////////////////////////////////////    /// 安装驱动    DWORD   Install();    /// 启动驱动    DWORD   Run();    /// 停止驱动    DWORD   Stop();    /// 卸载驱动    DWORD   UnInstall();    //////////////////////////////////////////////////////////////////////////    /// 子类需要实现以下4个子操作的虚函数    //////////////////////////////////////////////////////////////////////////    /// 安装驱动的操作    virtual DWORD   InstallOpt() = 0;   ///< 安装装过程不一样, 必须由子类实现    /// 启动驱动的操作    virtual DWORD   RunOpt();           ///< 基类子类行为相同    /// 停止驱动的操作    virtual DWORD   StopOpt();          ///< 基类子类行为相同    /// 卸载驱动的操作    virtual DWORD   UnInstallOpt();     ///< 基类子类行为相同    //////////////////////////////////////////////////////////////////////////    /// 驱动操作过程中, 注册表操作可能没有    /// 如果子类有注册表操作, 需要重新实现以下2个虚函数    //////////////////////////////////////////////////////////////////////////    /// 安装驱动后的注册表操作    virtual DWORD   RegOpt_Install() {return DRV_MANAGER_OK;}    /// 卸载驱动后的注册表操作    virtual DWORD   RegOpt_UnInstall() {return DRV_MANAGER_OK;}    //////////////////////////////////////////////////////////////////////////    /// 参数设置    //////////////////////////////////////////////////////////////////////////    /// 设置驱动类型    void SetDriverType(const e_DrvType & eDriverType);    CDrvManager::e_DrvType GetDriverType();    /// 设置驱动目标名称    void SetTargetName(const wchar_t * pcTargetName);    const wchar_t * GetTargetName();    /// 设置驱动全路径或相对路径    void SetDriverPathName(const wchar_t * pcDriverPathName);    const wchar_t * GetDriverPathName();private:    //////////////////////////////////////////////////////////////////////////    /// 数据初始化, 反初始化不能是虚函数, 每个类必须重新定义    //////////////////////////////////////////////////////////////////////////    void DataInit();    ///< 数据初始化    void DataUnInit();  ///< 数据反初始化private:    e_DrvType       m_DrvType;          ///< 驱动类型    std::wstring    m_strTargetName;    ///< 驱动目标名称    /// 驱动全路径或相对路径(e.g. .\\NullFilter.sys)    std::wstring    m_strDriverPathName;};#endif  // #ifndef __HELPER_SRCDRVMANAGER_DRVMANAGER_H__

Nt驱动管理类定义

/// @file           \Helper\srcDrvManager\drvManagerNt.h/// @brief          Nt驱动管理类定义#ifndef __HELPER_SRCDRVMANAGER_DRVMANAGER_DRV_MANAGER_NT_H__#define __HELPER_SRCDRVMANAGER_DRVMANAGER_DRV_MANAGER_NT_H__#include "drvManager.h"class CDrvManagerNt : public CDrvManager{public:    CDrvManagerNt();    virtual ~CDrvManagerNt();    /// 需要实现的纯虚函数    virtual DWORD   InstallOpt();private:    /// 数据初始化, 反初始化不能是虚函数, 每个类必须重新定义    void DataInit();    ///< 数据初始化    void DataUnInit();  ///< 数据反初始化};// #ifndef __HELPER_SRCDRVMANAGER_DRVMANAGER_DRV_MANAGER_NT_H__#endif

MiniFilter驱动管理类定义

/// @file           \Helper\srcDrvManager\drvManagerMiniFilter.h/// @brief          MiniFilter驱动管理类定义#ifndef __HELPER_SRCDRVMANAGER_DRVMANAGER_DRV_MANAGER_MINI_FILTER_H__#define __HELPER_SRCDRVMANAGER_DRVMANAGER_DRV_MANAGER_MINI_FILTER_H__#include "drvManager.h"class CDrvManagerMiniFilter : public CDrvManager{public:    CDrvManagerMiniFilter();    virtual ~CDrvManagerMiniFilter();    /// 需要实现的纯虚函数    virtual DWORD   InstallOpt();    /// 需要实现的普通虚函数    virtual DWORD   RegOpt_Install();    virtual DWORD   RegOpt_UnInstall();    /// 设置MiniFilter's Altitude    void SetAltitude(const wchar_t * pcAltitude);    const wchar_t * GetAltitude();private:    /// 数据初始化, 反初始化不能是虚函数, 每个类必须重新定义    void DataInit();    ///< 数据初始化    void DataUnInit();  ///< 数据反初始化private:    std::wstring    m_strAltitude;  ///< minifilter's pcAltitude};// #ifndef __HELPER_SRCDRVMANAGER_DRVMANAGER_DRV_MANAGER_MINI_FILTER_H__#endif

驱动管理类具体实现

驱动管理基类实现

/// @file           \Helper\srcDrvManager\drvManager.cpp/// @brief          ...#include "stdafx.h"#include "drvManager.h"/// @warning 不能在构造,析构函数中调用虚函数!CDrvManager::CDrvManager(){    DataInit();}CDrvManager::~CDrvManager(){    DataUnInit();}void CDrvManager::SetDriverType(const e_DrvType & eDriverType){    m_DrvType = eDriverType;}void CDrvManager::SetTargetName(const wchar_t * pcTargetName){    m_strTargetName = pcTargetName;}void CDrvManager::SetDriverPathName(const wchar_t * pcDriverPathName){    m_strDriverPathName = pcDriverPathName;}void CDrvManager::DataInit(){    m_DrvType = CDrvManager::e_DrvTypeUnknown;    m_strTargetName = L"";    m_strDriverPathName = L"";}void CDrvManager::DataUnInit(){}CDrvManager::e_DrvType CDrvManager::GetDriverType(){    return m_DrvType;}const wchar_t * CDrvManager::GetTargetName(){    return m_strTargetName.c_str();}const wchar_t * CDrvManager::GetDriverPathName(){    if (0 == m_strDriverPathName.length())    {        m_strDriverPathName = L".\\";        m_strDriverPathName += m_strTargetName.c_str();        m_strDriverPathName += L".sys";    }    return m_strDriverPathName.c_str();}DWORD   CDrvManager::Install(){    DWORD   dwRc    =   DRV_MANAGER_OK;    dwRc = InstallOpt();    if (DRV_MANAGER_OK != dwRc)        return dwRc;    return RegOpt_Install();}DWORD   CDrvManager::Run(){    return RunOpt();}DWORD   CDrvManager::Stop(){    return StopOpt();}DWORD   CDrvManager::UnInstall(){    DWORD   dwRc    =   DRV_MANAGER_OK;    dwRc = UnInstallOpt();    if (DRV_MANAGER_OK != dwRc)        return dwRc;    return RegOpt_UnInstall();}DWORD   CDrvManager::RunOpt(){    DWORD       dwRc        =   DRV_MANAGER_OK;    SC_HANDLE   schManager  =   NULL;    SC_HANDLE   schService  =   NULL;    __try    {        if (NULL == GetTargetName())        {            dwRc = DRV_MANAGER_INVALID_PARAM;            __leave;        }        schManager=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);        if (NULL == schManager)            __leave;        schService = OpenService(   schManager,            GetTargetName(),            SERVICE_ALL_ACCESS);        if (NULL == schService)            __leave;        if (!StartService(schService, 0, NULL))        {            if( GetLastError() == ERROR_SERVICE_ALREADY_RUNNING )                 __leave; ///< 服务已经开启            dwRc = DRV_MANAGER_START_SERVICE;        }    }    __finally    {        if (NULL != schService)            CloseServiceHandle(schService);        if (NULL != schManager)            CloseServiceHandle(schManager);    }    return dwRc;}DWORD   CDrvManager::StopOpt(){    DWORD           dwRc        =   DRV_MANAGER_OK;    SC_HANDLE       schManager  =   NULL;    SC_HANDLE       schService  =   NULL;    SERVICE_STATUS  svcStatus;    __try    {        schManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);        if (NULL == schManager)            __leave;        schService = OpenService(   schManager,            GetTargetName(),            SERVICE_ALL_ACCESS);        if (NULL == schService)            __leave;        if (!ControlService(schService,SERVICE_CONTROL_STOP,&svcStatus))        {            dwRc = DRV_MANAGER_SERVICE_CONTROL_STOP;            __leave;        }        if (SERVICE_STOPPED != svcStatus.dwCurrentState)        {            dwRc = DRV_MANAGER_NOT_SERVICE_STOPPED;            __leave;        }    }    __finally    {        if (NULL != schService)            CloseServiceHandle(schService);        if (NULL != schManager)            CloseServiceHandle(schManager);    }    return dwRc;}DWORD   CDrvManager::UnInstallOpt(){    DWORD           dwRc        =   DRV_MANAGER_OK;    SC_HANDLE       schManager  =   NULL;    SC_HANDLE       schService  =   NULL;    __try    {        schManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);        if(NULL==schManager)            __leave;        schService = OpenService(   schManager,            GetTargetName(),            SERVICE_ALL_ACCESS);        if (NULL == schService)            __leave;        if (!DeleteService(schService))        {            dwRc = DRV_MANAGER_DELETE_SERVICE;            __leave;            return FALSE;        }    }    __finally    {        if (NULL != schService)            CloseServiceHandle(schService);        if (NULL != schManager)            CloseServiceHandle(schManager);    }    return dwRc;}



Nt驱动管理类实现

/// @file           \Helper\srcDrvManager\drvManagerNt.cpp/// @brief          ...#include "stdafx.h"#include "drvManagerNt.h"CDrvManagerNt::CDrvManagerNt(){    DataInit();}CDrvManagerNt::~CDrvManagerNt(){    DataUnInit();}DWORD   CDrvManagerNt::InstallOpt(){    wchar_t         szDriverImagePath[MAX_PATH] = {0};        DWORD       dwRc        =   DRV_MANAGER_OK;    SC_HANDLE   hServiceMgr =   NULL; ///< SCM管理器的句柄    SC_HANDLE   hService    =   NULL; ///< 驱动程序的服务句柄    __try    {        if ((NULL == GetTargetName()) || (NULL == GetDriverPathName()))        {            dwRc = DRV_MANAGER_INVALID_PARAM;            __leave;        }        /// 得到完整的驱动路径        GetFullPathName(GetDriverPathName(), MAX_PATH, szDriverImagePath, NULL);        /// 打开服务控制管理器        hServiceMgr = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );        if (NULL == hServiceMgr)         {            /// OpenSCManager失败            dwRc = DRV_MANAGER_OPEN_SCM;            __leave;        }        /// 创建驱动所对应的服务        hService = CreateService( hServiceMgr,            GetTargetName(),            // 注册表中驱动的名字            GetTargetName(),            // 注册表驱动的DisplayName            SERVICE_ALL_ACCESS,         // 加载驱动的访问权限            SERVICE_KERNEL_DRIVER,      // 表示加载的服务是驱动程序              SERVICE_DEMAND_START,       // 驱动的Start值            SERVICE_ERROR_IGNORE,       // 驱动的ErrorControl值            szDriverImagePath,          // 驱动的ImagePath值            NULL,                       // 驱动的Group值            NULL,             NULL,                       // 驱动的DependOnService值            NULL,             NULL);        if (NULL == hService)         {                    if (ERROR_SERVICE_EXISTS != GetLastError())                dwRc =  DRV_MANAGER_CREATE_SERVICE;        }    }    __finally    {        if (NULL != hService)            CloseServiceHandle(hService);        if (NULL != hServiceMgr)            CloseServiceHandle(hServiceMgr);    }    return dwRc;}void CDrvManagerNt::DataInit(){    SetDriverType(CDrvManager::e_DrvTypeNt);}void CDrvManagerNt::DataUnInit(){}


MiniFilter驱动管理类实现

/// @file           \Helper\srcDrvManager\drvManagerMiniFilter.cpp/// @brief          ...#include "stdafx.h"#include "drvManagerMiniFilter.h"CDrvManagerMiniFilter::CDrvManagerMiniFilter(){    DataInit();}CDrvManagerMiniFilter::~CDrvManagerMiniFilter(){    DataUnInit();}DWORD   CDrvManagerMiniFilter::InstallOpt(){    /// @ref    /// <<File System Minifilter Load Order Groups and Altitude Ranges>>    /// http://msdn.microsoft.com/en-us/library/windows/hardware/gg462963.aspx    const wchar_t * lpLoadOrderGroup    =   L"FSFilter Activity Monitor";    const wchar_t * lpDependencies      =   L"FltMgr";    wchar_t         szDriverImagePath[MAX_PATH] = {0};    DWORD       dwRc        =   DRV_MANAGER_OK;    SC_HANDLE   hServiceMgr =   NULL; ///< SCM管理器的句柄    SC_HANDLE   hService    =   NULL; ///< 驱动程序的服务句柄    __try    {        if ((NULL == GetTargetName()) || (NULL == GetDriverPathName()))        {            dwRc = DRV_MANAGER_INVALID_PARAM;            __leave;        }        /// 得到完整的驱动路径        GetFullPathName(GetDriverPathName(), MAX_PATH, szDriverImagePath, NULL);        /// 打开服务控制管理器        hServiceMgr = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );        if (NULL == hServiceMgr)         {            /// OpenSCManager失败            dwRc = DRV_MANAGER_OPEN_SCM;            __leave;        }        /// 创建驱动所对应的服务        hService = CreateService( hServiceMgr,            GetTargetName(),            // 注册表中驱动的名字            GetTargetName(),            // 注册表驱动的DisplayName            SERVICE_ALL_ACCESS,         // 加载驱动的访问权限            SERVICE_FILE_SYSTEM_DRIVER, // 加载的驱动是文件系统驱动程序            SERVICE_DEMAND_START,       // 驱动的Start值            SERVICE_ERROR_IGNORE,       // 驱动的ErrorControl值            szDriverImagePath,          // 驱动的ImagePath值            lpLoadOrderGroup,           // 驱动的Group值            NULL,             lpDependencies,             // 驱动的DependOnService值            NULL,             NULL);        if (NULL == hService)         {                    if (ERROR_SERVICE_EXISTS != GetLastError())                dwRc =  DRV_MANAGER_CREATE_SERVICE;        }    }    __finally    {        if (NULL != hService)            CloseServiceHandle(hService);        if (NULL != hServiceMgr)            CloseServiceHandle(hServiceMgr);    }    return dwRc;}DWORD   CDrvManagerMiniFilter::RegOpt_Install(){    DWORD   dwRc    =   DRV_MANAGER_OK;    DWORD   dwData  =   0;    HKEY    hKey;    wchar_t szTemp[MAX_PATH] = {0};    __try    {        /// SYSTEM\\CurrentControlSet\\Services\\DriverName\\Instances        /// 子健下的键值项         _tcscpy(szTemp, L"SYSTEM\\CurrentControlSet\\Services\\");        _tcscat(szTemp, GetTargetName());        _tcscat(szTemp, L"\\Instances");        dwRc = RegCreateKeyEx(  HKEY_LOCAL_MACHINE,            szTemp,            0,            L"",            TRUE,            KEY_ALL_ACCESS,            NULL,            &hKey,            (LPDWORD)&dwData);        if (ERROR_SUCCESS != dwRc)            __leave;        /// 注册表驱动程序的DefaultInstance值         _tcscpy(szTemp,GetTargetName());        _tcscat(szTemp,L" Instance");        dwRc = RegSetValueEx(   hKey,            L"DefaultInstance",            0,            REG_SZ,            (CONST BYTE *)szTemp,            (DWORD)(SIZEOF_WSTRING(szTemp)));        if (ERROR_SUCCESS != dwRc)            __leave;        RegFlushKey(hKey); ///< 刷新注册表        RegCloseKey(hKey);        /// SYSTEM\\CurrentControlSet\\Services\\DriverName\\Instances\\        /// DriverName Instance子健下的键值项         _tcscpy(szTemp, L"SYSTEM\\CurrentControlSet\\Services\\");        _tcscat(szTemp, GetTargetName());        _tcscat(szTemp, L"\\Instances\\");        _tcscat(szTemp, GetTargetName());        _tcscat(szTemp, L" Instance");        dwRc = RegCreateKeyEx(  HKEY_LOCAL_MACHINE,            szTemp,            0,            L"",            TRUE,KEY_ALL_ACCESS,            NULL,            &hKey,            (LPDWORD)&dwData);        if (ERROR_SUCCESS != dwRc)            __leave;        // 注册表驱动程序的Altitude 值        _tcscpy(szTemp, GetAltitude());        dwRc = RegSetValueEx(   hKey,            L"Altitude",            0,            REG_SZ,            (CONST BYTE*)szTemp,            (DWORD)(SIZEOF_WSTRING(szTemp)));        if (ERROR_SUCCESS != dwRc)            __leave;        // 注册表驱动程序的Flags 值        dwData = 0;        dwRc = RegSetValueEx(   hKey,            L"Flags",            0,            REG_DWORD,            (CONST BYTE*)&dwData,            sizeof(DWORD));        if (ERROR_SUCCESS != dwRc)            __leave;    }    __finally    {        RegFlushKey(hKey); ///< 刷新注册表        RegCloseKey(hKey);    }    return dwRc;}DWORD   CDrvManagerMiniFilter::RegOpt_UnInstall(){    /// 如果卸载后, 注册表如果有残留信息, 应该清理一下    return DRV_MANAGER_OK;  ///< 卸载后, 当作没有注册表清理操作~}void CDrvManagerMiniFilter::DataInit(){    m_strAltitude = L"";    SetDriverType(CDrvManager::e_DrvTypeMiniFilter);}void CDrvManagerMiniFilter::DataUnInit(){}void CDrvManagerMiniFilter::SetAltitude(const wchar_t * pcAltitude){    m_strAltitude = pcAltitude;}const wchar_t * CDrvManagerMiniFilter::GetAltitude(){    _ASSERT(0 != m_strAltitude.length());    return m_strAltitude.c_str();}

原创粉丝点击