Writing a device driver for Windows

Source: Internet
Author: User
Tags unique id

Writing a device driver for Windows

In order to write a device driver for Windows, one needs the device Driver Development Kit (DDK) and a C compiler.
According to the article, a device driver ' s maximum size is 960MB on Windows XP (100MB on NT4, 220MB on Win2K).
Setting up the environment
A proper environment must be setup. Use Setenv (which ships with the DDK) to set the environment variables (and what isn't) to build a driver:
C:\>programme\ntddk\bin\setenv \PROGRAMME\NTDDK.
The argument that's given to setenv must point to the directory under which, the DDK is installed.
Makefile
The directory that contains the sources for the device driver must has a file called Makefile and another file called Sou RCEs. For a simple device driver, it was sufficient to one of the makefile:

! INCLUDE $ (ntmakeenv) \makefile.def

Sources
This file actually contains the names of the files to be compiled:

Targetname=kamel
Targetpath=obj
Targettype=driver

SOURCES=KAMEL.C writeevent.c kamelmsg.rc

C_defines=-dunicode-dstrict

KAMEL.C is the code for the driver itself, WRITEEVENT.C contains a function so can be called to write messages to the SY Stem Event log (see below) and Kamelmsg.rc contains the strings that is written
Writing the driver
I call the driver we ' re going to write Kamel. In German, the This would then was called Kameltreiber which is a pun German speaking people would understand. So, we ' re creating (according to the sources file) a file called KAMEL.C. The first lines contain the includes we need:

#include "Ntddk.h"
#include "WriteEvent.h"
#include "KamelMsg.h"

Ntddk.h must always be included, WriteEvent.h contains the declaration of writeEvent (which are a function to write events, Of course) and KamelMsg.h (being created by the message compiler) contains the identifiers of the strings we want to writ E using WriteEvent.
Each driver needs a driverentry function which are called when the driver is loaded:
Now, we use the write the forward declarations together with the Pragmas alloc_text. They indicate wheather or not, the function is pageable.

#define BUFFERSIZE 1024
#define Buffertag ' kmlb '

typedef struct _KAMEL_DRIVER_EXTENSION {
Char Buffer[buffersize];
} kamel_driver_extension, *pkamel_driver_extension;

kamel_driver_extension* driverextension=0;


NTSTATUS DriverEntry (in Pdriver_object driverobject, in punicode_string Registrypath);
NTSTATUS Createcamel (in Pdevice_object deviceobject, in Pirp IRP);
NTSTATUS Readcamel (in Pdevice_object deviceobject, in Pirp IRP);
NTSTATUS Writecamel (in Pdevice_object deviceobject, in Pirp IRP);
NTSTATUS Shutdowncamel (in Pdevice_object deviceobject, in Pirp IRP);
NTSTATUS Cleanupcamel (in Pdevice_object deviceobject, in Pirp IRP);
NTSTATUS Ioctlcamel (in Pdevice_object deviceobject, in Pirp IRP);
VOID cmlunload (in Pdriver_object driverobject);


#ifdef ALLOC_PRAGMA
#pragma alloc_text (INIT, DriverEntry)
#pragma alloc_text (PAGE, Createcamel)
#pragma alloc_text (PAGE, Readcamel)
#pragma alloc_text (PAGE, Writecamel)
#pragma alloc_text (PAGE, Shutdowncamel)
#pragma alloc_text (PAGE, Ioctlcamel)
#pragma alloc_text (PAGE, Cmlunload)
#endif

NTSTATUS DriverEntry (in Pdriver_object driverobject, in punicode_string Registrypath) {

Unicode_string namestring, linkstring;
Pdevice_object DeviceObject;
NTSTATUS status;

WriteEvent (Msg_driver_entry,driverobject,null);

Rtlinitunicodestring (&namestring, L "\\Device\\Kamel");

Status = IoCreateDevice (
DriverObject,
sizeof (65533),
&namestring,
0,//file_device_unknown,
0,
FALSE,
&deviceobject);

if (! Nt_success (status))
return status;


Deviceobject->flags |= Do_direct_io;
Deviceobject->flags &= ~do_device_initializing;


Rtlinitunicodestring (&linkstring, L "\\DosDevices\\Kamel");
Status = Iocreatesymboliclink (&linkstring, &namestring);

if (! Nt_success (status)) {
Iodeletedevice (Driverobject->deviceobject);
return status;
}


Driverobject->majorfunction[irp_mj_create] = Createcamel;
Driverobject->majorfunction[irp_mj_read] = Readcamel;
Driverobject->majorfunction[irp_mj_write] = Writecamel;
Driverobject->majorfunction[irp_mj_shutdown] = Shutdowncamel;
Driverobject->majorfunction[irp_mj_device_control] = Ioctlcamel;

driverobject->driverunload=cmlunload;

ExAllocatePool is obsolete and exallocatepoolwithtag should be used.
Driverextension = ExAllocatePool (NonPagedPool, sizeof (kamel_driver_extension));

if (!driverextension) {
WriteEvent (Msg_no_ioallocatedriverobjectextension, DriverObject, NULL);
return status_insufficient_resources;
}

RtlZeroMemory (Driverextension->buffer, buffersize);

Rtlcopybytes (Driverextension->buffer, "123456789012345", 16);

return status_success;
}

DriverEntry First writes an Event (using WriteEvent, explained later) so it can is verified that DriverEntry indeed is CA Lled. Then, the actual device is created using IoCreateDevice and initialized.
Setting up Major Functions
An application communicates with a driver with the driver ' s Major Functions. These is set in the drivers array of function pointers majorfunction.
User Visible Name for the driver
In order to create a user-visible name for the device just created, Iocreatesymboliclink is called.
Allocating Pool Memory
The driver allocates some Pool Memory with ExAllocatePool.
By the To, Paged and non-paged Pool Memory sized can be adjusted with the registry keys Hkey_local_machine\system\current Controlset\control\session manager\memory management\ (Non) pagedpoolsize. The Value specified is the size in bytes.
Programming the Major Functions
In DriverEntry, the Major Functions irp_mj_create, Irp_mj_read, Irp_mj_write, Irp_mj_shutdown, Irp_mj_device_control were set. Here is the actual functions they point to:
Irp_mj_create
This function was called when a file using the this deivce is created. In Win32API, Devices is opened using CreateFile which then routes in the function associated with irp_mj_create.

NTSTATUS Createcamel (in Pdevice_object deviceobject, in Pirp Irp) {
WriteEvent (Msg_create, (PVOID) deviceobject,null);

IoCompleteRequest (irp,io_no_increment);
return status_success;
}

Irp_mj_read

NTSTATUS Readcamel (in Pdevice_object deviceobject, in Pirp Irp) {
Puchar currentaddress;
Pio_stack_location irpstack;

WriteEvent (Msg_read,deviceobject,null);

if (!driverextension) {
WriteEvent (Msg_driverextisnullinread,deviceobject,null);
IoCompleteRequest (IRP, io_no_increment);
return status_insufficient_resources;
}
Irpstack = Iogetcurrentirpstacklocation (IRP);

if (irpstack->majorfunction = = Irp_mj_read) {
currentaddress = Mmgetsystemaddressformdlsafe (irp->mdladdress, normalpagepriority);

if (!currentaddress) {
WriteEvent (Msg_mmgetsystemaddress,deviceobject,null);
IoCompleteRequest (IRP, io_no_increment);
return status_success;
}
RtlMoveMemory (Currentaddress,
Driverextension->buffer+irpstack->parameters.read.byteoffset.lowpart,
Irpstack->parameters.read.length);
}
else {
WriteEvent (Msg_majorfunc_not_read,deviceobject,null);
}

IoCompleteRequest (IRP, io_no_increment);
return status_success;
}

A driver should call iogetcurrentirpstacklocation in it IRP function to receive a pointer to a io_stack_location Structur E.
Mmgetsystemaddressformdlsafe is a macro. It returns a virtual address to non system-space for the buffer described by the MDL.
RtlMoveMemory
Irp_mj_write

NTSTATUS Writecamel (in Pdevice_object deviceobject, in Pirp Irp) {
Puchar currentaddress;
Pio_stack_location irpstack;

if (!driverextension) {
IoCompleteRequest (IRP, io_no_increment);
return status_insufficient_resources;
}

Irpstack = Iogetcurrentirpstacklocation (IRP);

if (irpstack->majorfunction = = Irp_mj_write) {
currentaddress = Mmgetsystemaddressformdlsafe (irp->mdladdress, normalpagepriority);

if (!currentaddress) {
IoCompleteRequest (IRP, io_no_increment);
return status_success;
}

RtlMoveMemory (Driverextension->buffer+irpstack->parameters.write.byteoffset.lowpart,
Currentaddress, irpstack->parameters.write.length);
}
else {
WriteEvent (Msg_majorfunc_not_read,deviceobject,null);
}

IoCompleteRequest (IRP, io_no_increment);
return status_success;
}

Irp_mj_shutdown

NTSTATUS Shutdowncamel (in Pdevice_object deviceobject, in Pirp Irp) {
WriteEvent (Msg_shutdown,deviceobject,null);
IoCompleteRequest (IRP, io_no_increment);
return status_success;
}

Irp_mj_device_control

NTSTATUS Ioctlcamel (in Pdevice_object deviceobject, in Pirp Irp) {
WriteEvent (Msg_ioctl,deviceobject,null);
IoCompleteRequest (IRP, io_no_increment);
return status_success;
}

The Unload function

VOID cmlunload (in Pdriver_object driverobject) {
Unicode_string linkstring;

WriteEvent (Msg_driverunload, DriverObject, NULL);
Exfreepool (driverextension);
Rtlinitunicodestring (&linkstring, L "\\DosDevices\\Kamel");
Iodeletesymboliclink (&linkstring);
Iodeletedevice (Driverobject->deviceobject);
}

Writing Events from a Device Driver
It is possible to write strings from the driver into the System event box (which and can be viewed with the Event Viewer (Eventvwr.exe). It isn't straight forward however and the following steps must each are done.
The Message File
First, a message file must is created, having the suffix. MC, which contains each possible string you want to output and Al So assignes a unique ID to these strings. A sample is given here:

MessageID = 1
Severity = Informational
SymbolicName = Msg_driver_entry
Language = 中文版
Driver Entry
.
MessageID = 2
Severity = Informational
SymbolicName = Msg_create
Language = 中文版
Create
.

Each Entry must is followed by a and a single dot on its own line. In this sample, the unique Id was associated with the symbolic name Msg_driver_entry and the String "DRIVER ENTRY". If you take a look at driverentry above, you'll see this I call WriteEvent with the symbolic name Msg_driver_entry.
The message File then was to being compiled with the message compiler MC:MC KAMELMSG.MC in the command line. This produces a file called messagefile.rc. Kamelmsg.rc must is included in the sources file. It also creates the file KamelMsg.h which must is included to the constants.
This is still not sufficient. Also A string entry must be created in the Registry under Hklm\system\currentcontrolset\services\eventlog\system\<driv Ername>\eventmessagefile. The string must point to the. dll or. sys into which the messages were compiled, with our case:%systemroot%\system32\driver S\kamel.sys
WriteEvent

BOOLEAN WriteEvent (in NTSTATUS ErrorCode, in PVOID ioobject,in pirp Irp) {
Pio_error_log_packet PACKET;
Pio_stack_location irpstack;
Pwchar pinsertionstring;
STRING ansiinsertstring;
Unicode_string uniinsertstring;

UCHAR PacketSize;

packetsize = sizeof (Io_error_log_packet);

Packet = Ioallocateerrorlogentry (ioobject,packetsize);
if (Packet = = NULL) return FALSE;

Packet->errorcode = ErrorCode;
Packet->uniqueerrorvalue = 0,
Packet->retrycount = 0;
Packet->sequencenumber = 0;
Packet->iocontrolcode = 0;
packet->dumpdatasize = 0;

if (irp!=null) {
Irpstack=iogetcurrentirpstacklocation (IRP);
Packet->majorfunctioncode = irpstack->majorfunction;
Packet->finalstatus = irp->iostatus.status;
}
else {
Packet->majorfunctioncode = 0;
Packet->finalstatus = 0;
}

IoWriteErrorLogEntry (Packet);
return TRUE;
}

WriteEvent.h

BOOLEAN WriteEvent (in NTSTATUS ErrorCode, in PVOID ioobject,in pirp IRP);
#pragma alloc_text (PAGE, WriteEvent)

Entries in the registry
The driver must is registred with the registry:create a This key hklm\system\currentcontrolset\services\<drivername&gt ; and add the following Keys:errorcontrol, Group, Start, Tag and Type.

Writing a device driver for Windows

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.