首页 > 代码库 > 基本NT式驱动代码结构

基本NT式驱动代码结构

#include <ntddk.h>

void DriverUnload(IN PDRIVER_OBJECT DriverObject);
NTSTATUS MyCreateClose(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp);
NTSTATUS MyDefaultHandler(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp);

NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegPath)
{
UNICODE_STRING ustrDevName, ustrLinkName;
PDEVICE_OBJECT pDeviceObj = NULL;
NTSTATUS status;
unsigned int i;

KdPrint(("DriverEntry ...\n"));

RtlInitUnicodeString(&ustrDevName, L"\\Device\\demo0");
RtlInitUnicodeString(&ustrLinkName, L"\\DosDevices\\demo0");

for (i=0; i<IRP_MJ_MAXIMUM_FUNCTION; i++)
{
DriverObject->MajorFunction[i] = MyDefaultHandler;
}

DriverObject->MajorFunction[IRP_MJ_CREATE] = MyCreateClose;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = MyCreateClose;

DriverObject->DriverUnload = DriverUnload;

status = IoCreateDevice(DriverObject,
0,
&ustrDevName,
FILE_DEVICE_UNKNOWN,
0,
FALSE,
&pDeviceObj);

if (!NT_SUCCESS(status))
{
KdPrint(("IoCreateDevice failed ...\n"));
return status;
}

if (!pDeviceObj)
{
KdPrint(("pDeviceObj == NULL\n"));
return STATUS_UNEXPECTED_IO_ERROR;
}

pDeviceObj->Flags |= DO_DIRECT_IO;

status = IoCreateSymbolicLink(&ustrLinkName, &ustrDevName);

pDeviceObj->Flags &= ~DO_DEVICE_INITIALIZING;

return STATUS_SUCCESS;
}

VOID DriverUnload(IN PDRIVER_OBJECT DriverObject)
{
UNICODE_STRING ustrLinkName;

KdPrint(("DriverUnload ...\n"));

RtlInitUnicodeString(&ustrLinkName, L"\\DosDevices\\demo0");

IoDeleteSymbolicLink(&ustrLinkName);
IoDeleteDevice(DriverObject->DeviceObject);
}

NTSTATUS MyCreateClose(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}

NTSTATUS MyDefaultHandler(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
Irp->IoStatus.Status = STATUS_NOT_SUPPORTED;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return Irp->IoStatus.Status;
}

基本NT式驱动代码结构