回顾驱动与用户层通信

环境:win10 64位
先关签名

bcdedit.exe /set nointegritychecks on

1。缓冲区方式读写
桥梁是用一个buf
将数据存储在AssociatedIrp.SystemBuffer
pDevObj->Flags |= DO_BUFFERED_IO
用户层
main.cpp

#include <windows.h>
#include <stdio.h>

#define GetFilePointer(hFile) SetFilePointer(hFile, 0, NULL, FILE_CURRENT)

int main()
{
    HANDLE hDevice =
        CreateFile("\\\\.\\HelloDDK",
            GENERIC_READ | GENERIC_WRITE,
            0,      // share mode none
            NULL,   // no security
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            NULL);      // no template

    if (hDevice == INVALID_HANDLE_VALUE)
    {
        printf("Failed to obtain file handle to device: "
            "%s with Win32 error code: %d\n",
            "MyWDMDevice", GetLastError());
        //return 1;
    }

    UCHAR buffer[10];
    memset(buffer, 0xBB, 10);
    ULONG ulRead;
    ULONG ulWrite;
    BOOL bRet;
    bRet = WriteFile(hDevice, buffer, 10, &ulWrite, NULL);
    if (bRet)
    {
        printf("Write %d bytes\n", ulWrite);
    }

    bRet = ReadFile(hDevice, buffer, 10, &ulRead, NULL);
    if (bRet)
    {
        printf("Read %d bytes:", ulRead);
        for (int i = 0; i<(int)ulRead; i++)
        {
            printf("%02X ", buffer[i]);
        }

        printf("\n");
    }

    printf("file length:%d\n", GetFileSize(hDevice, NULL));

    CloseHandle(hDevice);
    getchar();
    return 0;
}

驱动层
test.c

#include "Driver.h"

/************************************************************************
* 函数名称:DriverEntry
* 功能描述:初始化驱动程序,定位和申请硬件资源,创建内核对象
* 参数列表:
pDriverObject:从I/O管理器中传进来的驱动对象
pRegistryPath:驱动程序在注册表的中的路径
* 返回 值:返回初始化驱动状态
*************************************************************************/
#pragma INITCODE
 NTSTATUS DriverEntry(
    IN PDRIVER_OBJECT pDriverObject,
    IN PUNICODE_STRING pRegistryPath)
{
    NTSTATUS status;
    KdPrint(("Enter DriverEntry\n"));

    //设置卸载函数
    pDriverObject->DriverUnload = HelloDDKUnload;

    //设置派遣函数
    for (int i = 0; i < arraysize(pDriverObject->MajorFunction); ++i)
        pDriverObject->MajorFunction[i] = HelloDDKDispatchRoutin;
    pDriverObject->MajorFunction[IRP_MJ_WRITE] = HelloDDWrite;
    pDriverObject->MajorFunction[IRP_MJ_READ] = HelloDDKRead;
    //用户层获取文件长度时用产生这个irp
    pDriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION] = HelloDDKQueryInfomation;

    //创建驱动设备对象
    status = CreateDevice(pDriverObject);

    KdPrint(("Leave DriverEntry\n"));
    return status;
}

/************************************************************************
* 函数名称:CreateDevice
* 功能描述:初始化设备对象
* 参数列表:
pDriverObject:从I/O管理器中传进来的驱动对象
* 返回 值:返回初始化状态
*************************************************************************/
#pragma INITCODE
NTSTATUS CreateDevice(
    IN PDRIVER_OBJECT   pDriverObject)
{
    NTSTATUS status;
    PDEVICE_OBJECT pDevObj;
    PDEVICE_EXTENSION pDevExt;

    //创建设备名称
    UNICODE_STRING devName;
    RtlInitUnicodeString(&devName, L"\\Device\\MyDDKDevice");

    //创建设备
    status = IoCreateDevice(pDriverObject,
        sizeof(DEVICE_EXTENSION),
        &devName,
        FILE_DEVICE_UNKNOWN,
        0, TRUE,
        &pDevObj);
    if (!NT_SUCCESS(status))
        return status;

    pDevObj->Flags |= DO_BUFFERED_IO;
    pDevExt = (PDEVICE_EXTENSION)pDevObj->DeviceExtension;
    pDevExt->pDevice = pDevObj;
    pDevExt->ustrDeviceName = devName;

    //申请模拟文件的缓冲区
    pDevExt->buffer = (PUCHAR)ExAllocatePool(PagedPool, MAX_FILE_LENGTH);
    //设置模拟文件大小
    pDevExt->file_length = 0;

    //创建符号链接
    UNICODE_STRING symLinkName;
    RtlInitUnicodeString(&symLinkName, L"\\??\\HelloDDK");
    pDevExt->ustrSymLinkName = symLinkName;
    status = IoCreateSymbolicLink(&symLinkName, &devName);
    if (!NT_SUCCESS(status))
    {
        IoDeleteDevice(pDevObj);
        return status;
    }
    return STATUS_SUCCESS;
}

/************************************************************************
* 函数名称:HelloDDKUnload
* 功能描述:负责驱动程序的卸载操作
* 参数列表:
pDriverObject:驱动对象
* 返回 值:返回状态
*************************************************************************/
#pragma PAGEDCODE
VOID HelloDDKUnload(IN PDRIVER_OBJECT pDriverObject)
{
    PDEVICE_OBJECT  pNextObj;
    KdPrint(("Enter DriverUnload\n"));
    pNextObj = pDriverObject->DeviceObject;
    while (pNextObj != NULL)
    {
        PDEVICE_EXTENSION pDevExt = (PDEVICE_EXTENSION)
            pNextObj->DeviceExtension;
        if (pDevExt->buffer)
        {
            ExFreePool(pDevExt->buffer);
            pDevExt->buffer = NULL;
        }

        //删除符号链接
        UNICODE_STRING pLinkName = pDevExt->ustrSymLinkName;
        IoDeleteSymbolicLink(&pLinkName);
        pNextObj = pNextObj->NextDevice;
        IoDeleteDevice(pDevExt->pDevice);
    }
}

/************************************************************************
* 函数名称:HelloDDKDispatchRoutin
* 功能描述:对读IRP进行处理
* 参数列表:
pDevObj:功能设备对象
pIrp:从IO请求包
* 返回 值:返回状态
*************************************************************************/
#pragma PAGEDCODE
NTSTATUS HelloDDKDispatchRoutin(IN PDEVICE_OBJECT pDevObj,
    IN PIRP pIrp)
{
    KdPrint(("Enter HelloDDKDispatchRoutin\n"));

    PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(pIrp);
    //建立一个字符串数组与IRP类型对应起来
    static char* irpname[] =
    {
        "IRP_MJ_CREATE",
        "IRP_MJ_CREATE_NAMED_PIPE",
        "IRP_MJ_CLOSE",
        "IRP_MJ_READ",
        "IRP_MJ_WRITE",
        "IRP_MJ_QUERY_INFORMATION",
        "IRP_MJ_SET_INFORMATION",
        "IRP_MJ_QUERY_EA",
        "IRP_MJ_SET_EA",
        "IRP_MJ_FLUSH_BUFFERS",
        "IRP_MJ_QUERY_VOLUME_INFORMATION",
        "IRP_MJ_SET_VOLUME_INFORMATION",
        "IRP_MJ_DIRECTORY_CONTROL",
        "IRP_MJ_FILE_SYSTEM_CONTROL",
        "IRP_MJ_DEVICE_CONTROL",
        "IRP_MJ_INTERNAL_DEVICE_CONTROL",
        "IRP_MJ_SHUTDOWN",
        "IRP_MJ_LOCK_CONTROL",
        "IRP_MJ_CLEANUP",
        "IRP_MJ_CREATE_MAILSLOT",
        "IRP_MJ_QUERY_SECURITY",
        "IRP_MJ_SET_SECURITY",
        "IRP_MJ_POWER",
        "IRP_MJ_SYSTEM_CONTROL",
        "IRP_MJ_DEVICE_CHANGE",
        "IRP_MJ_QUERY_QUOTA",
        "IRP_MJ_SET_QUOTA",
        "IRP_MJ_PNP",
    };

    UCHAR type = stack->MajorFunction;
    if (type >= arraysize(irpname))
        KdPrint((" - Unknown IRP, major type %X\n", type));
    else
        KdPrint(("\t%s\n", irpname[type]));

    //对一般IRP的简单操作,后面会介绍对IRP更复杂的操作
    NTSTATUS status = STATUS_SUCCESS;
    // 完成IRP
    pIrp->IoStatus.Status = status;
    pIrp->IoStatus.Information = 0; // bytes xfered
    IoCompleteRequest(pIrp, IO_NO_INCREMENT);

    KdPrint(("Leave HelloDDKDispatchRoutin\n"));

    return status;
}

NTSTATUS HelloDDKRead(IN PDEVICE_OBJECT pDevObj,
    IN PIRP pIrp)
{
    KdPrint(("Enter HelloDDKRead\n"));
    //在 IoCreateDevice申请模拟文件的缓冲区
    //pDevExt->buffer = (PUCHAR)ExAllocatePool(PagedPool, MAX_FILE_LENGTH);
    PDEVICE_EXTENSION pDevExt = (PDEVICE_EXTENSION)pDevObj->DeviceExtension;
    NTSTATUS status = STATUS_SUCCESS;

    PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(pIrp);
    ULONG ulReadLength = stack->Parameters.Read.Length;
    ULONG ulReadOffset = (ULONG)stack->Parameters.Read.ByteOffset.QuadPart;

    if (ulReadOffset + ulReadLength>MAX_FILE_LENGTH)
    {
        status = STATUS_FILE_INVALID;
        ulReadLength = 0;
    }
    else
    {
        //将数据存储在AssociatedIrp.SystemBuffer,以便应用程序使用
        memcpy(pIrp->AssociatedIrp.SystemBuffer, pDevExt->buffer + ulReadOffset, ulReadLength);
        status = STATUS_SUCCESS;
    }

    pIrp->IoStatus.Status = status;
    pIrp->IoStatus.Information = ulReadLength;  // bytes xfered
    IoCompleteRequest(pIrp, IO_NO_INCREMENT);
    KdPrint(("Leave HelloDDKRead\n"));

    return status;
}

NTSTATUS HelloDDWrite(IN PDEVICE_OBJECT pDevObj,
    IN PIRP pIrp)
{
    KdPrint(("Enter HelloDDWrite\n"));

    NTSTATUS status = STATUS_SUCCESS;
    //在 IoCreateDevice申请模拟文件的缓冲区
    //pDevExt->buffer = (PUCHAR)ExAllocatePool(PagedPool, MAX_FILE_LENGTH);
    PDEVICE_EXTENSION pDevExt = (PDEVICE_EXTENSION)pDevObj->DeviceExtension;

    PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(pIrp);
    //获取存储的长度
    ULONG ulWriteLength = stack->Parameters.Write.Length;
    //获取存储的偏移量 就是buffer中从哪里开始
    ULONG ulWriteOffset = (ULONG)stack->Parameters.Write.ByteOffset.QuadPart;

    if (ulWriteOffset + ulWriteLength>MAX_FILE_LENGTH)
    {
        //如果存储长度+偏移量大于缓冲区长度,则返回无效
        status = STATUS_FILE_INVALID;
        ulWriteLength = 0;
    }
    else
    {
        //将写入的数据,存储在缓冲区内
        memcpy(pDevExt->buffer + ulWriteOffset, pIrp->AssociatedIrp.SystemBuffer, ulWriteLength);
        status = STATUS_SUCCESS;
        //设置新的文件长度
        if (ulWriteLength + ulWriteOffset>pDevExt->file_length)
        {
            pDevExt->file_length = ulWriteLength + ulWriteOffset;
        }
    }

    pIrp->IoStatus.Status = status;
    //用户的返回值是这个
    pIrp->IoStatus.Information = ulWriteLength; // bytes xfered
    IoCompleteRequest(pIrp, IO_NO_INCREMENT);
    KdPrint(("Leave HelloDDWrite\n"));
    return status;
}

NTSTATUS HelloDDKQueryInfomation(IN PDEVICE_OBJECT pDevObj,
    IN PIRP pIrp)
{
    KdPrint(("Enter HelloDDKQueryInfomation\n"));

    PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(pIrp);

    PDEVICE_EXTENSION pDevExt = (PDEVICE_EXTENSION)pDevObj->DeviceExtension;

    FILE_INFORMATION_CLASS info = stack->Parameters.QueryFile.FileInformationClass;
    if (info == FileStandardInformation)
    {
        KdPrint(("FileStandardInformation\n"));
        PFILE_STANDARD_INFORMATION file_info =
            (PFILE_STANDARD_INFORMATION)pIrp->AssociatedIrp.SystemBuffer;
        file_info->EndOfFile = RtlConvertLongToLargeInteger(pDevExt->file_length);
    }

    NTSTATUS status = STATUS_SUCCESS;
    // 完成IRP
    pIrp->IoStatus.Status = status;
    pIrp->IoStatus.Information = stack->Parameters.QueryFile.Length;    // bytes xfered
    IoCompleteRequest(pIrp, IO_NO_INCREMENT);

    KdPrint(("Leave HelloDDKQueryInfomation\n"));

    return status;
}

//Driver.h

#pragma once

#ifdef __cplusplus
extern "C"
{
#endif
#include <NTDDK.h>
#ifdef __cplusplus
}
#endif 

#define PAGEDCODE code_seg("PAGE")
#define LOCKEDCODE code_seg()
#define INITCODE code_seg("INIT")

#define PAGEDDATA data_seg("PAGE")
#define LOCKEDDATA data_seg()
#define INITDATA data_seg("INIT")

#define arraysize(p) (sizeof(p)/sizeof((p)[0]))

#define MAX_FILE_LENGTH 1024

typedef struct _DEVICE_EXTENSION {
    PDEVICE_OBJECT pDevice;
    UNICODE_STRING ustrDeviceName;  //设备名称
    UNICODE_STRING ustrSymLinkName; //符号链接名

    PUCHAR buffer;//缓冲区
    ULONG file_length;//模拟的文件长度,必须小于MAX_FILE_LENGTH
} DEVICE_EXTENSION, *PDEVICE_EXTENSION;

// 函数声明

NTSTATUS CreateDevice(IN PDRIVER_OBJECT pDriverObject);
VOID HelloDDKUnload(IN PDRIVER_OBJECT pDriverObject);
NTSTATUS HelloDDKDispatchRoutin(IN PDEVICE_OBJECT pDevObj,
    IN PIRP pIrp);
NTSTATUS HelloDDKRead(IN PDEVICE_OBJECT pDevObj,
    IN PIRP pIrp);
NTSTATUS HelloDDWrite(IN PDEVICE_OBJECT pDevObj,
    IN PIRP pIrp);
NTSTATUS HelloDDKQueryInfomation(IN PDEVICE_OBJECT pDevObj,
    IN PIRP pIrp);

原文地址:http://blog.51cto.com/haidragon/2315222

时间: 2024-10-08 03:25:32

回顾驱动与用户层通信的相关文章

向Windows内核驱动传递用户层定义的事件Event,并响应内核层的通知

完整的程序在下载:http://download.csdn.net/detail/dijkstar/7913249 用户层创建的事件Event是一个Handle句柄,和内核中的创建的内核模式下的KEVENT是一个东西.因此,在应用层创建的事件,可以在内核层获得并使用.这一部分的原理,见张帆编著的<Windows驱动技术详解>章节8.5.4,P237页: 程序是来自于<Windows驱动技术详解>章节8.5.4(驱动程序和应用程序交互事件对象)和章节10.2.1(DPC定时器). 首

DeviceIoControl 应用层如何和驱动层通信?

调用的方法之一的DeviceIoControl 驱动层提供设备名 例如filedisk 在驱动层 首先先是注册列表 用winObj查看 filedisk的驱动对象 但是 这八个对象时怎么生成的呢? 我们在加载filedisk.sys驱动时进行中断 查看过程 具体的双击调试 看我的另一篇文章 http://www.cnblogs.com/UnMovedMover/p/3690369.html 在下载的源码filedisk中sys下面的filedisk-17\filedisk-17\sys\src

OVS中对于用户层和datapath层的多个通道利用epoll进行控制

这里先暂时记录下代码流程,有待完善. static int construct(struct ofproto *ofproto_) { struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_); const char *name = ofproto->up.name; int max_ports; int error; int i; error = dpif_create_and_open(name, ofproto->up.type

[原创]用户层关闭瑞星2009杀毒软件安全保护

原文链接:用户层关闭瑞星2009杀毒软件安全保护 我写这个纯粹是hacker精神,如果被滥用做病毒木马一类的邋遢东东,可跟偶没关系哦. 原理very简单,我发现瑞星监控主要在RavMonD进程中,如果打破其与内核的联系,则瑞星监控功能就无法正常工作了,怎么打破联系呢?如果是进内核的话当然有很多的办法,从而没有挑战性了,况且RavMonD会阻止用户进程去加载驱动或者动注册表的关键地方,比如run子键.下面上测试代码: 1 int main(int argc,char *argv[]) 2 { 3

Kernel与用户进程通信

测试IPv6 ready logo   rfc 3315的时候,遇到一个问题,要求在收到ICMPv6 RA的时候,DHCPv6  Client要发Solicit消息.在平常的应用中,都是启动DHCPv6  Client后,client每隔一段时间就会发送Solicit,而并不是要在收到RA的时候发送.于是就修改了下kernel和client的代码,使得在kernel收到RA消息时,发送消息给DHCPv6  Client,使client发送Solicit. 思路为:使用netlink_kernel

Android4.0(Phone)拨号启动过程分析(三)与Framework层通信

由于Android几乎所有的代码都是公开的,如果要对Framework层分析就必需先拿到Framework层的代码,我在前面已经搭建好了ubuntu14.04的环境,下载好了Android4.0的源码,其中也包括了Framework层和Package的代码,导出到宿主机Windows XP中用Source Insight 3.5工具来查看源码,Package中的代码可以导入到Eclipse下查看,我是把frameworks\base整个目录都导入到Source Insight 3.5工程中,可以

Linux 内核层和 用户层 配置 GPIO 引脚

Linux BSP 开发的基础就是和GPIO打交道, 下面总结下这几天对某家开发板的GPIO控制的知识. 公司的开发板用的是 DTB  模式 ,首先,进入 dts,dtsi文件查看关于GPIO 的模块. soc { . . . gpio0: [email protected]****addr { compatible = "**********"; reg = <0 0x****addr 0 0x50>; interrupts = <SPI 4 IRQ_TYPE_LE

自定义用户层的灵活性串口通信协议

想不到第一次接触串口就要去写一个自定义的灵活性串口通信协议,所以在这里记录一下自己的心得,有什么不合理的地方还请大佬们指出. 先说明这里提到的灵活性其实也是相对来说的,并不是说明数据包都可以定义. 一.用户层串口通信协议 简单的来说用户层的串口通信协议就是如何定义一个数据包格式,发送端按照规定的数据包格式发送出去,接收端按照规定的数据包格式解析出正确的数据. 那为什么又要在用户层定义呢,其一是因为底层的通信协议不是随随便便就可以写出来的,二是因为我们在市面上买到的串口模块本身就已经有了底层通信协

Linux用户层直接操作GPIO

Linux用户层直接操作GPIO 在一个老手的指导下,应用层可以直接操作GPIO,具体指设置GPIO的输入输出以及输出电平高或者低.这个大大地提高了灵活性,官方的文档有GPIO Sysfs Interface for Userspace,GPIO Sysfs. 这里我记录一下使用过例子: # RK30_PIN0_PD4 # A0-7 -> 0-7 / B0-7 -> 8-15 / C0-7 -> 16-23 / D0-7 -> 24-31 echo 28 > /sys/cla