mmoneyhome
mmoneyhome
采纳率25%
2020-06-07 21:54 阅读 236

【求助】 CreateFile打开驱动程序返回INVALID_HANDLE_NUMBER 但是GetLastError返回0 ?

80

我在WinDbg里面发现驱动是已经被正确加载了的。

而且驱动本身初始化的PASS 也通了。

从各个Dispath函数上来看这个阶段,没有触发任何的IRP 报文处理函数。

但就是返回INVALID_HANDLE_VALUE 我用GetLastError 返回值是0 ,

try exception 模块也没有捕获任何问题。

图片说明

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

using System.Threading;
using ProcessCreateNotifyTest;
using System.Runtime.ExceptionServices;

namespace TestDriver
{
    public partial class Form1 : Form
    {
        private const string EXE_DRIVER_NAME = "fastFatDemo";           //创建的驱动名
        private const string DISPLAY_NAME = "fastFatDemo Driver";   //显示的服务名
        private const string PROCESS_NOTIFY_NAME = "ProcessNotifyEvent";            //进程创建提示驱动名
        private const int IOCTL_GET_PROCESS_INFO = 2285572;    // IO控制码

        //关闭进程创建提示事件
        IntPtr g_hShutdownEvent;
        //加载返回的驱动句柄
        IntPtr hDriver;
        //全局进程创建提示事件
        IntPtr g_hProcessEvent;
        /// <summary>
        /// 进程事件
        /// </summary>
        public event Action<ProcessInfo> OnProcessEvent;
        void dumpErrorCode(string title, int error)
        {
            MessageBox.Show(title + error.ToString());

                if (error == 0)
                    MessageBox.Show(title + "〖0〗-操作成功完成。" + error.ToString());

        }


        private void OpenDriverEvent()
        {
            //打开驱动事件
            g_hProcessEvent = WinAPI.OpenEvent(WinAPI.SYNCHRONIZE, false, PROCESS_NOTIFY_NAME);

            if (g_hProcessEvent != IntPtr.Zero)
            {
                MessageBox.Show("成功打开驱动事件");
            }

        }


        private void MonitorThread()
        {

            uint dwRet;
            //创建关闭事件
            g_hShutdownEvent = WinAPI.CreateEvent(IntPtr.Zero, false, false, null);

            //创建等待事件数组
            IntPtr[] hHandleArray = { g_hShutdownEvent, g_hProcessEvent };

            while (true)
            {

                dwRet = WinAPI.WaitForMultipleObjects(
                 (uint)hHandleArray.Length,
                 hHandleArray, //事件数组
                 false, //只要有事件发生,就返回
                 0xFFFFFFFF //一直等 -1
                 );

                if (hHandleArray[dwRet] == g_hShutdownEvent)
                {
                    //关闭事件产生
                    break;
                }
                else
                {

                    //获取创建的进程信息
                    uint dwRet2 = 0;
                    ProcessInfo pProcInfo = new ProcessInfo();
                    bool bRet = WinAPI.DeviceIoControl(hDriver, IOCTL_GET_PROCESS_INFO, 0, 0, ref pProcInfo, (uint)Marshal.SizeOf(pProcInfo), ref dwRet2, IntPtr.Zero);
                    if (bRet)
                    {

                        if (this.OnProcessEvent != null)
                        {
                            this.OnProcessEvent(pProcInfo);
                        }

                    }
                }

            }
        }

        /// <summary>
        /// 卸载驱动
        /// </summary>
        /// <param name="hDriver"></param>
        public void UnloadDriver(IntPtr hDriver)
        {
            //关闭驱动句柄
            WinAPI.CloseHandle(hDriver);

            //打开服务管理器
            IntPtr hSCManager = WinAPI.OpenSCManager(null, null,
                WinAPI.SC_MANAGER_CREATE_SERVICE);

            if (IntPtr.Zero != hSCManager)
            {
                //打开服务
                IntPtr hService = WinAPI.OpenService(hSCManager, EXE_DRIVER_NAME, WinAPI.DELETE | WinAPI.SERVICE_STOP);

                if (IntPtr.Zero != hService)
                {
                    SERVICE_STATUS ss = new SERVICE_STATUS();
                    //停止服务
                    WinAPI.ControlService(hService, WinAPI.SERVICE_CONTROL_STOP, ref ss);
                    //删除服务
                    WinAPI.DeleteService(hService);
                    //关闭服务句柄
                    WinAPI.CloseServiceHandle(hService);
                }
                //关闭服务管理器句柄
                WinAPI.CloseServiceHandle(hSCManager);
            }
        }

        public IntPtr LoadDriver(string lpFileName)
        {
            int error = 0;

            string openName = string.Format("\\\\.\\{0}", EXE_DRIVER_NAME);
            IntPtr hSCManager = WinAPI.OpenSCManager(null, null,
            WinAPI.SC_MANAGER_CREATE_SERVICE);

            if (IntPtr.Zero != hSCManager)
            {

                //创建服务
                IntPtr hService = WinAPI.CreateService(hSCManager, EXE_DRIVER_NAME,
                    DISPLAY_NAME, WinAPI.SERVICE_START,
                    WinAPI.SERVICE_KERNEL_DRIVER, WinAPI.SERVICE_DEMAND_START,
                    WinAPI.SERVICE_ERROR_IGNORE, lpFileName, null, IntPtr.Zero, null, null, null);

                if (WinAPI.ERROR_SERVICE_EXISTS == WinAPI.GetLastError())
                {
                    hService = WinAPI.OpenService(hSCManager, EXE_DRIVER_NAME, WinAPI.SERVICE_START);
                }
                error = WinAPI.GetLastError();
                if(error!=0)
                {
                    dumpErrorCode("OpenService失败 ", error);

                }

                MessageBox.Show(openName);
                try
                {
                    hDriver = WinAPI.CreateFileA(openName,  
                        0,
                        WinAPI.FILE_SHARE_READ| WinAPI.FILE_SHARE_WRITE | WinAPI.FILE_SHARE_DELETE, 

                        IntPtr.Zero,
                        WinAPI.OPEN_EXISTING,
                        WinAPI.FILE_FLAG_OVERLAPPED,  
                        IntPtr.Zero);

                    if (hDriver == (IntPtr)(-1))
                    {
                        dumpErrorCode("获取文件句柄失败 ", error);
                    }
                    else
                    {
                        MessageBox.Show("成功创建驱动");
                        //his.OpenDriverEvent();
                    }
                }
                catch (Exception exp)
                {
                    int errorCode = WinAPI.GetLastError();
                    dumpErrorCode("打开设备失败", errorCode);
                    MessageBox.Show(exp.Message);
                }
                WinAPI.CloseServiceHandle(hService);
                WinAPI.CloseServiceHandle(hSCManager);
            }
            return hDriver;
        }



        public Form1()
        {
            InitializeComponent();



        }
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.InitialDirectory = "C:\\InstrSys\\";
            fileDialog.Filter = "系统文件|*.sys";
            fileDialog.ShowDialog();

            string sysPath = fileDialog.FileName;
            MessageBox.Show(sysPath);
            LoadDriver(sysPath);
        }
    }
}

驱动程序的EntryPoint 如下所示:

NTSTATUS
DriverEntry(
    _In_ PDRIVER_OBJECT DriverObject,
    _In_ PUNICODE_STRING RegistryPath
    )
{
    NTSTATUS Status;
    UNICODE_STRING UnicodeString;
    FS_FILTER_CALLBACKS FilterCallbacks;

    UNREFERENCED_PARAMETER( RegistryPath );
    DbgPrint("\nThis is HRFS Driver Entry\n");
    RtlInitUnicodeString(&UnicodeString, L"\\fastFatDemo");
    gSFilterDriverObject = DriverObject;

    Status = IoCreateDevice( DriverObject,
                             0,
                             &UnicodeString,
                             FILE_DEVICE_DISK_FILE_SYSTEM,
                             0,
                             FALSE,
                             &HrfsDiskFileSystemDeviceObject );

    if (!NT_SUCCESS( Status )) {
        return Status;
    }
    DbgPrint("HRFS device HRFS created\n ");
    DriverObject->DriverUnload = FatUnload;

    DriverObject->MajorFunction[IRP_MJ_CREATE]                   = (PDRIVER_DISPATCH)FatFsdCreate;
    DriverObject->MajorFunction[IRP_MJ_CLOSE]                    = (PDRIVER_DISPATCH)HrfsFsdClose;
    DriverObject->MajorFunction[IRP_MJ_READ]                     = (PDRIVER_DISPATCH)FatFsdRead;
    DriverObject->MajorFunction[IRP_MJ_WRITE]                    = (PDRIVER_DISPATCH)FatFsdWrite;
    DriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION]        = (PDRIVER_DISPATCH)FatFsdQueryInformation;
    DriverObject->MajorFunction[IRP_MJ_SET_INFORMATION]          = (PDRIVER_DISPATCH)FatFsdSetInformation;
    DriverObject->MajorFunction[IRP_MJ_QUERY_EA]                 = (PDRIVER_DISPATCH)FatFsdQueryEa;
    DriverObject->MajorFunction[IRP_MJ_SET_EA]                   = (PDRIVER_DISPATCH)FatFsdSetEa;
    DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS]            = (PDRIVER_DISPATCH)FatFsdFlushBuffers;
    DriverObject->MajorFunction[IRP_MJ_QUERY_VOLUME_INFORMATION] = (PDRIVER_DISPATCH)FatFsdQueryVolumeInformation;
    DriverObject->MajorFunction[IRP_MJ_SET_VOLUME_INFORMATION]   = (PDRIVER_DISPATCH)FatFsdSetVolumeInformation;
    DriverObject->MajorFunction[IRP_MJ_CLEANUP]                  = (PDRIVER_DISPATCH)FatFsdCleanup;
    DriverObject->MajorFunction[IRP_MJ_DIRECTORY_CONTROL]        = (PDRIVER_DISPATCH)FatFsdDirectoryControl;
    DriverObject->MajorFunction[IRP_MJ_FILE_SYSTEM_CONTROL]      = (PDRIVER_DISPATCH)FatFsdFileSystemControl;
    DriverObject->MajorFunction[IRP_MJ_LOCK_CONTROL]             = (PDRIVER_DISPATCH)FatFsdLockControl;
    DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL]           = (PDRIVER_DISPATCH)FatFsdDeviceControl;
    DriverObject->MajorFunction[IRP_MJ_SHUTDOWN]                 = (PDRIVER_DISPATCH)FatFsdShutdown;
    DriverObject->MajorFunction[IRP_MJ_PNP]                      = (PDRIVER_DISPATCH)FatFsdPnp;
    DbgPrint("HRFS device HRFS MajorFunction created\n ");
    DriverObject->FastIoDispatch = NULL;
    DbgPrint("HRFS device HRFS FatFastIoDispatch created\n ");
    RtlZeroMemory(&FatFastIoDispatch, sizeof(FatFastIoDispatch));

    FatFastIoDispatch.SizeOfFastIoDispatch =    sizeof(FAST_IO_DISPATCH);
    FatFastIoDispatch.FastIoCheckIfPossible =   FALSE;  //  CheckForFastIo
    FatFastIoDispatch.FastIoRead = FALSE;             //  Read
    FatFastIoDispatch.FastIoWrite = FALSE;            //  Write
    FatFastIoDispatch.FastIoQueryBasicInfo = FALSE;     //  QueryBasicInfo
    FatFastIoDispatch.FastIoQueryStandardInfo = FALSE;       //  QueryStandardInfo
    FatFastIoDispatch.FastIoLock = FALSE;               //  Lock
    FatFastIoDispatch.FastIoUnlockSingle = FALSE;       //  UnlockSingle
    FatFastIoDispatch.FastIoUnlockAll = FALSE;          //  UnlockAll
    FatFastIoDispatch.FastIoUnlockAllByKey = FALSE;     //  UnlockAllByKey
    FatFastIoDispatch.FastIoQueryNetworkOpenInfo = FALSE;
    FatFastIoDispatch.AcquireForCcFlush = FALSE;
    FatFastIoDispatch.ReleaseForCcFlush = FALSE;
    FatFastIoDispatch.MdlRead = FALSE;
    FatFastIoDispatch.MdlReadComplete = FALSE;
    FatFastIoDispatch.PrepareMdlWrite = FALSE;
    FatFastIoDispatch.MdlWriteComplete = FALSE;


    //FatFastIoDispatch.SizeOfFastIoDispatch = sizeof(FAST_IO_DISPATCH);
    //FatFastIoDispatch.FastIoCheckIfPossible = FatFastIoCheckIfPossible;  //  CheckForFastIo
    //FatFastIoDispatch.FastIoRead = FsRtlCopyRead;             //  Read
    //FatFastIoDispatch.FastIoWrite = FsRtlCopyWrite;            //  Write
    //FatFastIoDispatch.FastIoQueryBasicInfo = FatFastQueryBasicInfo;     //  QueryBasicInfo
    //FatFastIoDispatch.FastIoQueryStandardInfo = FatFastQueryStdInfo;       //  QueryStandardInfo
    //FatFastIoDispatch.FastIoLock = FatFastLock;               //  Lock
    //FatFastIoDispatch.FastIoUnlockSingle = FatFastUnlockSingle;       //  UnlockSingle
    //FatFastIoDispatch.FastIoUnlockAll = FatFastUnlockAll;          //  UnlockAll
    //FatFastIoDispatch.FastIoUnlockAllByKey = FatFastUnlockAllByKey;     //  UnlockAllByKey
    //FatFastIoDispatch.FastIoQueryNetworkOpenInfo = FatFastQueryNetworkOpenInfo;
    //FatFastIoDispatch.AcquireForCcFlush = HrfsAcquireForCcFlush;
    //FatFastIoDispatch.ReleaseForCcFlush = HrfsReleaseForCcFlush;
    //FatFastIoDispatch.MdlRead = FsRtlMdlReadDev;
    //FatFastIoDispatch.MdlReadComplete = FsRtlMdlReadCompleteDev;
    //FatFastIoDispatch.PrepareMdlWrite = FsRtlPrepareMdlWriteDev;
    //FatFastIoDispatch.MdlWriteComplete = FsRtlMdlWriteCompleteDev;





   /*  FsFilter通知回调例程在下层文件系统执行某些操作之前或之后调用。
       如果需要获取更多有关于FsFilter回调例程相关信息,可参见FsRtlRegisterFileSystemFilterCallbacks例程 
       为了注册FsFilter的通知回调例程必须分配并初始化FS_FILTER_CALLBACKS结构体,然后向该结构体中促出FsFilter回调例程,
       并将存储有Callbacks parameter到FsRtlRegisterFileSystemFilterCallbacks中。*/

    RtlZeroMemory( &FilterCallbacks,
                   sizeof(FS_FILTER_CALLBACKS) );

    FilterCallbacks.SizeOfFsFilterCallbacks = sizeof(FS_FILTER_CALLBACKS);
    FilterCallbacks.PreAcquireForSectionSynchronization = HrfsFilterCallbackAcquireForCreateSection;

    Status = FsRtlRegisterFileSystemFilterCallbacks( DriverObject,
                                                     &FilterCallbacks );

    if (!NT_SUCCESS( Status )) {

        IoDeleteDevice( HrfsDiskFileSystemDeviceObject );

        return Status;
    }
     DbgPrint("HRFS device HRFS FilterCallbacks registed\n ");


    RtlZeroMemory( &HrfsData, sizeof(FAT_DATA));

    HrfsData.NodeTypeCode = HRFS_NTC_DATA_HEADER;
    HrfsData.NodeByteSize = sizeof(FAT_DATA);

    InitializeListHead(&HrfsData.VcbQueue);

    pDriverObject = DriverObject;
    HrfsData.DiskFileSystemDeviceObject = HrfsDiskFileSystemDeviceObject;


    //
    //  This list head keeps track of closes yet to be done.
    //

    InitializeListHead( &HrfsData.AsyncCloseList );
    InitializeListHead( &HrfsData.DelayedCloseList );

    HrfsData.FatCloseItem = IoAllocateWorkItem( HrfsDiskFileSystemDeviceObject);

    if (HrfsData.FatCloseItem == NULL) {
        IoDeleteDevice (HrfsDiskFileSystemDeviceObject);

        return STATUS_INSUFFICIENT_RESOURCES;
    }
    DbgPrint("HRFS device HRFS workitem created\n ");
    //
    //  Allocate the zero page
    //

    HrfsData.ZeroPage = ExAllocatePoolWithTag( NonPagedPoolNx, PAGE_SIZE, 'ZtaF' );
    if (HrfsData.ZeroPage == NULL) {
        IoDeleteDevice (HrfsDiskFileSystemDeviceObject);

        return STATUS_INSUFFICIENT_RESOURCES;
    }
    RtlZeroMemory( HrfsData.ZeroPage, PAGE_SIZE );


    //
    //  Now initialize our general purpose spinlock (gag) and figure out how
    //  deep and wide we want our delayed lists (along with fooling ourselves
    //  about the lookaside depths).
    //

    KeInitializeSpinLock( &HrfsData.GeneralSpinLock );


    HrfsData.CacheManagerCallbacks.AcquireForLazyWrite  = &HrfsAcquireFcbForLazyWrite;
    HrfsData.CacheManagerCallbacks.ReleaseFromLazyWrite = &HrfsReleaseFcbFromLazyWrite;
    HrfsData.CacheManagerCallbacks.AcquireForReadAhead  = &HrfsAcquireFcbForReadAhead;
    HrfsData.CacheManagerCallbacks.ReleaseFromReadAhead = &HrfsReleaseFcbFromReadAhead;

    HrfsData.CacheManagerNoOpCallbacks.AcquireForLazyWrite  = &HrfsNoOpAcquire;
    HrfsData.CacheManagerNoOpCallbacks.ReleaseFromLazyWrite = &HrfsNoOpRelease;
    HrfsData.CacheManagerNoOpCallbacks.AcquireForReadAhead  = &HrfsNoOpAcquire;
    HrfsData.CacheManagerNoOpCallbacks.ReleaseFromReadAhead = &HrfsNoOpRelease;

    //
    //  Set up global pointer to our process.
    //

    HrfsData.OurProcess = PsGetCurrentProcess();
    DbgPrint("HRFS device HRFS our process getted\n ");
    // 
    //  Setup the number of processors we support for statistics as the current number 
    //  running.
    //

#if (NTDDI_VERSION >= NTDDI_VISTA)
    HrfsData.NumberProcessors = KeQueryActiveProcessorCount( NULL );
#else
    HrfsData.NumberProcessors = KeNumberProcessors;
#endif


    DbgPrint("HrfsData.NumberProcessors :%d", HrfsData.NumberProcessors);
    ExInitializeResourceLite( &HrfsData.Resource );
    IoRegisterFileSystem(HrfsDiskFileSystemDeviceObject);
    ObReferenceObject (HrfsDiskFileSystemDeviceObject);
    DbgPrint("Device HRFS HrfsDiskFileSystemDeviceObject registed\n ");


    return( STATUS_SUCCESS );
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • caozhy 从今以后生命中的每一秒都属于我爱的人 2020-06-08 08:16

    这个设备是你自己开发的还是怎么来的,你有没有一个程序可以证明你的驱动本身是正确的。
    或者说你有没有一个同类型的设备肯定是正确的,能验证你的C#程序是正确的。

    点赞 评论 复制链接分享

相关推荐