Friday, September 27, 2013

Kernel Mode Driver

KMD layers between I/O manager (Io*) and hal.dll. KMD uses API exposed by hal.dll to interact with the hardware.

KMD process IRP (I/O Request Packets) handed down from I/O manager on behalf of user applications. Microsoft introduced device framework to ease devlopment of KMD. WDM (Windows Driver Model) was released to support Win98 and W2K. WDF (Windows Driver Framework) encapsulates WDM with another layer of abstraction.

The DriverEntry() routine is executed when KMD is first loaded into kernel space. DriverEntry() returns the status in NTSTATUS type. DriverEntry() takes 2 parameters. The first IN parameter is of type DRIVER_OBJECT which contains information of the driver, including a list of function pointers:

DriverInit - by default, I/O manager set this to the address of DriverEntry()

DriverUnload - to be set by KMD for the routine to execute when KMD is to be unload

DriverDispatch - an array of MajorFunction which define the routines to be executed in response to the major function codes (e.g.IRP_MJ_READ, IRP_MJ_WRITE, IRP_MJ_DEVICE_CONTROL etc) in the IRP passed down Dispatch routines carry the following signature: NTSTATUS DispatchRoutine(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp); For device control, IRP contains a 32-bit field, IoControlCode, which provide further information on the IRP. IocontrolCode comprises four sub-fields:

(1) DeviceType - Microsoft reserves type value 0x0000 to 0x7FFF e.g.FILE_DEVICE_DISK, FILE_DEVICE_KEYBOARD. User can define its own type using 0x8000 to 0xFFFF (32K)

(2) Function - program specific integer value defines action to be performed. MS reserves 0x0000 to 0x7FFF. User defined function span 0x8000 to 0xFFFF

(3) Method - defines how data are to be passed between user and kernel mode code. e.g. METHOD_BUFFER means OS to create a non-paged system buffer

(4) Access - READ or WRITE access to be declared before opening the file object representing the device.
To use the KMD, it must firstly be registered to the OS via RegisterDriverDeviceName(). Then use RegisterDriverDeviceLink() call to create a symbolic link for user mode program to communicate with the KMD. User mode program first use CreateFile() to open the device. It then can use Windows API DeviceIoControl() to communicate with the KMD

No comments: