Introduction
This tutorial will attempt to describe how to write a simple device driver for Windows NT. There are various resources and tutorials on the internet for writing device drivers, however, they are somewhat scarce as compared to writing a "hello world" GUI program for Windows . This makes the search for information on starting to write device drivers a bit harder. you may think that if there's already one tutorial, why do you need more? The answer is that more information is always better especially when you are first beginning to understand a concept. It is always good to see information from different perspectives. People write differently and describe certain pieces of information in a different light depending on how familiar they are with a certain aspect or how they think it should be explained. This being the case I would recommend anyone Who Wants to Write Device Drivers Not to Stop Here or Somewhere Else. ALWAYS FIND A Variety of Samples and Code Snippets and research the Differe Nces. Sometimes There Are Bugs and things omitted. Sometimes There..........................
This Tutorial Will Describe How To create a Simple Device Driver, Dynamical Load and unload it, and finally talk to it from user mode.
Creating a Simple Device Driver Driver
What is a subsystem?
I need to define a starting ground before we begin to explain how to write a device driver. The starting point for this article will be the compiler. The compiler and linker generate a binary in a format that the Operating System understands. In Windows, this format is "PE" for "Portable Executable" format. in this format, there is an idea called a subsystem. A subsystem, along with other options specified in the PE header information, describes how to load an executable which also includes the entry point into the binary.Many people use the VC IDE to simply create a project with some default pre-set options for the compiler's (and linker) command line. This is why a lot of people may not be familiar with this concept even though they are most likely already using it if they have ever written Windows applications. Have you ever written a console application? Have you ever written a GUI application for Windows? These are different subsystems in Windows. Both of these will generate a P E binary with the appropriate subsystem information This is also why a console application uses "main" where a WINDOWS application uses "WinMain" When you choose these projects, VC simply creates a project with / SUBSYSTEM:.. CONSOLE or / SUBSYSTEM: WINDOWS. IF you Accidentally Choose The Wrong Project, You CAN SIMPLY CHANU Rather THAN NEEDING TO CREATE A New Project.
There's a point to all of this? A Driver is Simply Linked Using A Different Subsystem Called "Native". MSDN Subsystem Compiler Options.
The Driver's "main"
After the compiler is setup with the appropriate options, it's probably good to start thinking about the entry point to a driver. The first section lied a little bit about the subsystem. "NATIVE" can also be used to run user-mode applications which define an entry point called "NtProcessStartup". This is the "default" type of executable that is made when specifying "NATIVE" in the same way "WinMain" and "main" are found when the linker is creating an application. You can override the default entry point with your own, simply by using the "-entry:
Remember, DLLs actually are also compiled specifying "WINDOWS" as the subsystem, but they also have an additional switch called / DLL There is a switch which can also be used for drivers:. / DRIVER: WDM (which also sets NATIVE behind the scenes ) as well as a / DRIVER: UP which means this driver can not be loaded on a multi-processor system.The linker builds the final binary, and based on what the options are in the PE header and how the binary is attempting to be loaded (run as an EXE through the loader, loaded by LoadLibrary, or attempting to be loaded as a driver) will define how the loading system behaves. The loading system attempts to perform some level of verification, that the image being loaded is indeed supposed to be loaded in this manner, for example. There is even, in some cases, startup code added to the binary that executes before your entry point is reached (WinMainCRTStartup calling WinMain, for example, to initialize the CRT). your job is to simply Write the application base d on how you want it to be loaded and then set the correct options in the linker so it knows how to properly create the binary. There are various resources on the details of the PE format which you should be able to find if you are interested IN further investigation info this area.
The Options We Will Set for the Linker Will End Up Being The FOLLOWING:
/ Subsystem: Native / Driver: WDM -ENTRY: DRIVERENTRY
Before CREANTING THE
There are some things we need to go over before we simply sit down and write the "DriverEntry". I know that a lot of people simply want to jump right into writing the driver and seeing it work. This is generally the case in most programming scenarios as you usually just take the code, change it around, compile it, and test it out. If you remember back to when you were first learning Windows development, it was probably the same way. Your application probably did not work right away , probably crashed, or just disappeared. This was a lot of fun and you probably learned a lot, but you know that with a driver, the adventure is a little different. Not knowing what to do can end up in blue screening the system, and if your driver is loaded on boot and executes that code, you now have a problem. Hopefully, you can boot in safe mode or restore to a previous hardware configuration. that being the case, we have a few things to go over before you Write the driver in order to help educate you on wh At you are doing before you actually do it.
The first rule of thumb is do not just take a driver and compile it with some of your changes. If you do not understand how the driver is working or how to program correctly in the environment, you are likely to cause problems. Drivers can corrupt the integrity of the whole system, they can have bugs that do not always occur but in some rare circumstances. Application programs can have the same type of bugs in behavior but not in root cause. As an example, there are times when you can not access memory that is pagable. If you know how Virtual Memory works, you know that the Operating System will remove pages from memory to pull in pages that are needed, and this is how more applications can run than would have been physically possible given the memory limitations of the machine. There are places, however, when pages can not be read into memory from disk. At these times, those "drivers" who work with memory can only access memory that can not be paged out.Where am I going with this? Well, i f you allow a driver which runs under these constraints to access memory that is "pagable", it may not crash as the Operating System usually tries to keep all pages in memory as long as possible. If you close an application that was running, it may still be in memory, for example! This is why a bug like this may go undetected (unless you try doing things like driver verifier) and eventually may trap. When it does, if you do not understand the basic concepts like this, you Would Be Lost As to What The Problem is and how to fix it.
There are a lot of concepts behind everything that will be described in this document. On IRQL alone, there is a twenty page document you can find on MSDN. There's an equally large document on IRP. I will not attempt to duplicate this information nor point out every single little detail. What I will attempt to do is give a basic summary and point you in the direction of where to find more information. It's important to at least know that these concepts exist and understand some basic idea behind them, before writing THE DRIVER.WHAT IS IRQL?
The IRQL is known as the "Interrupt ReQuest Level". The processor will be executing code in a thread at a particular IRQL. The IRQL of the processor essentially helps determine how that thread is allowed to be interrupted. The thread can only be interrupted by code which needs to run at a higher IRQL on the same processor. interrupts requiring the same IRQL or lower are masked off so only interrupts requiring a higher IRQL are available for processing. In a multi-processor system, each processor operates independently at its own IRQL.
There are four IRQL levels which you generally will be dealing with, which are "Passive", "APC", "Dispatch" and "DIRQL". Kernel APIs documented in MSDN generally have a note which specifies the IRQL level at which you need to be running in order to use the API. The higher the IRQL you go, the less APIs that are available for use. The documentation on MSDN defines what IRQL the processor will be running at when the particular entry point of the driver is called. " Driverence, for example, will be called at passive_level.
Passive_level
This is The Lowest Irql. No Interrupts Are Masked Off and this Is The Level In Which A Thread Executing In User Mode Is Running. Pagable Memory IS AccessIble.Apc_level
In a processor running at this level, only APC level interrupts are masked. This is the level in which Asynchronous Procedure Calls occur. Pagable memory is still accessible. When an APC occurs, the processor is raised to APC level. This, in turn, also disables other APCs from occurring. A driver can manually raise its IRQL to APC (or any other level) in order to perform some synchronization with APCs, for example, since APCs can not be invoked if you are already at APC level. There .
Dispatch_level
The processor running at this level has DPC level interrupts and lower masked off. Pagable memory can not be accessed, so all memory being accessed must be non-paged. If you are running at Dispatch Level, the APIs that you can use greatly decrease since you Can Only Deal with non-paged memory.
DIRQL (Device IRQL)
Generally, higher level drivers do not deal with a method to determine which devices have priority over IRQLs at this level, but all interrupts at this level or less are masked off and do not occur. This is actually a range of IRQLs, and this is Other Devices.
In this driver, we will basically only be working at PASSIVE_LEVEL, so we will not have to worry about the gotchas. However, it is necessary for you to be aware of what IRQL is, if you intend to continue writing device drivers.
For More Information On Irqls and Thread Scheduling, Refer to The Following Documentation, And Another Good Source of Information Is Here.What is an Irp?
The "IRP" is called the "I / O Request Packet", and it is passed down from driver to driver in the driver stack. This is a data structure that allows drivers to communicate with each other and to request work to be done by The Driver. The I / O Manager OR Another Driver May Create An Irp and Pass It Down To your Driver. The IRP INCLUDES INFORMATION About The Operation That Being Requested.
A Description of the IRP Data Structure Can Be Found He.
The description and usage of an IRP can go from simple to complex very easily, so we will only be describing, in general, what an IRP will mean to you. There is an article on MSDN which describes in a lot more detail (about twenty . '
The IRP will also contain a list of "sub-requests" also known as the "IRP Stack Location". Each driver in the device stack will generally have its own "sub request" of how to interpret the IRP. This data structure is the "IO_STACK_LOCATION" and is described ON MSDN.
To create an analogy of the IRP and IO_STACK_LOCATION, perhaps you have three people who do different jobs such as carpentry, plumbing and welding. If they were going to build a house, they could have a common overall design and perhaps a common set of tools like their tool box. This includes things like power drills, etc. All of these common tools and overall design of building a house would be the IRP. Each of them has an individual piece they need to work on to make this happen, for example , the plumber needs the plans on where to put the pipe, how much pipe he has, etc. These could be interpreted as the IO_STACK_LOCATION as his specific job is to do the piping. The carpenter could be building the framework for the house and the details of that would be in his IO_STACK_LOCATION. So, while the entire IRP is a request to build a house, each person in the stack of people has their own job as defined by the IO_STACK_LOCATION to make this happen. Once everyone has completed their job , TH Ey Then Complete The Irp.The Device Driver We Will Be Building Will Not Be That Complex and Will Basical BE The Only Driver In The Stack.
Things to avoid
There are a lot of pitfalls that you will need to avoid but they are mostly unrelated to our simple driver. To be more informed, however, here is a list of items called "things to avoid" when it comes to driver development.
Create the Driverentry Routine
There is so much to explain, however, I think it's time we simply started to develop the driver and explain as we go. It is hard to digest theory or even how code is supposed to work, without actually doing anything. You need some hands ON Experience So You CAN Bring these Ideas Out of space and into reality.
The Prototype for the Driverentry Is The Following.ntstatus Driverentry (PDRiver_Object PDRIVEROBJECT, PUNICODE_STRING PregistryPath);
The DRIVER_OBJECT is a data structure used to represent this driver. The DriverEntry routine will use it to populate it with other entry points to the driver for handling specific I / O requests. This object also has a pointer to a DEVICE_OBJECT which is a data structure which represents a particular device. A single driver may actually advertise itself as handling multiple devices, and as such, the DRIVER_OBJECT maintains a linked list pointer to all the devices this particular driver services request for. We will simply be creating one device.
............................ ...CRIPLILE, TELEGEMENT OF. 1.
The next part is to actually put things in the DriverEntry routine. The first thing we will do is create the device. You may be wondering how we are going to create a device and what type of device we should create. This is generally because a driver is usually associated with hardware but this is not the case. There are a variety of different types of drivers which operate at different levels, not all drivers work or interface directly with hardware. Generally, you maintain a stack of drivers each with a specific job to do. The highest level driver is the one that communicates with user mode, and the lowest level drivers generally just talk to other drivers and hardware. There are network drivers, display drivers, file system drivers, etc., and each has their own stack of drivers. Each place in the stack breaks up a request into a more generic or simpler request for the lower level driver to service. The highest level drivers are the ones which communicate themselves to user mode, and Unless They Are A Special Device With A Particular Framework (Like Display Drivers), They Can Behave Generally The Same As Other Drivers Just As The IMPLEMENT DIFFERENT TYPES OF Operations.
As an example, take the hard disk drive. The driver which communicates to user mode does not talk directly to hardware. The high level driver simply manages the file system itself and where to put things. It then communicates where it wants to read or write from the disk to the lower level driver which may or may not talk directly to hardware. There may be another layer which then communicates that request to the actual hardware driver which then physically reads or writes a particular sector off a disk and then returns it to the higher level. The highest level may interpret them as file data, but the lowest level driver may simply be stupid and only manage requests as far as when to read a sector based off where the read / write head is located on the disk. It COULD THEN DETERMINE What Sector Read Requests To Service, However, It Has No IDEA What The Data IS AND DOS NOT ITEA What THETA IS TAKE A LOOK AT The First Part of Our "DriveREntry".
NTSTATUS DRIVERENTRY (PDRIVER_OBJECT PDRIVEROBJECT, PUNICODE_STRING PregistryPath)
{
NTSTATUS NTSTATUS = status_success;
Uint uiindex = 0;
PDEvice_Object PDeviceObject = NULL;
Unicode_string ustername, USDOSDEVICENAME;
DBGPRINT ("DriveREntry Called / R / N);
RTLinitunicodeString (& USDRIVERNAME, L "// device // example");
RTLINITUNICODESTRING (& USDosDeviceName, L "// dosdevices // eXample");
Ntstatus = IocreateDevice (PDRIVEROBJECT, 0,
& usdrivername,
File_Device_unknown,
FILE_DEVICE_SECURE_OPEN,
False, & pdeviceObject;
The first thing you will notice is the DbgPrint function. This works just like "printf" and it prints messages out to the debugger or debug output window. You can get a tool called "DBGVIEW" from www.sysinternals.com and all of the information in those messages will be displayed.You will then notice that we use a function called "RtlInitUnicodeString" which basically initializes a UNICODE_STRING data structure. This data structure contains basically three entries. The first is the size of the current Unicode string, the second is the maximum size that the Unicode string can be, and the third is a pointer to the Unicode string. This is used to describe a Unicode string and used commonly in drivers. The one thing to remember with UNICODE_STRING is that they are not required to be NULL terminated since there is a size parameter in the structure! This causes problems for people new to driver development as they assume a UNICODE_STRING is NULL terminated, and they blue-screen the driver. Mo St UNIDE STRINGS PASSING INTO YOUR Driver Will Not Be Null Terminated, so this is something you need to be aware of.
Devices have names just like anything else. They are generally named / Device /
The second parameter we passed 0, and it says to specify the number of bytes to create for the device extension. This is basically a data structure that the driver writer can define which is unique to that device. This is how you can extend the information being passed into a device and create device contexts, etc. in which to store instance data. We will not be using this for this example.Now that we have successfully created our / Device / Example device driver, we need to setup the Driver Object to call into our driver when certain requests are made. These requests are called IRP Major requests. There are also Minor requests which are sub-requests of these and can be found in the stack location of the IRP.
The Following Code Populates Certain Requests:
For (uiindex = 0; uiindex PDRIVEROBJECT-> Majorfunction [uiindex] = example_unsupportedfunction; PDRIVEROBJECT-> Majorfunction [IRP_MJ_CLOSE] = Example_Close; PDRIVEROBJECT-> Majorfunction [IRP_MJ_CREATE] = Example_create; PDRIVEROBJECT-> Majorfunction [IRP_MJ_DEVICE_CONTROL] = example_iocontrol; PDRIVEROBJECT-> Majorfunction [IRP_MJ_READ] = Example_Read; PDRIVEROBJECT-> Majorfunction [IRP_MJ_WRITE] = USE_WRITE_FUNCTION; We populate the create, close, ocontrol, read and write. What do these Refer to? When Communicating with the user-mode application, Certain Apis call directly to the driver and pass in parameters! CreateFile -> IRP_MJ_CREATE CLOSEHANDLE -> IRP_MJ_CLEANUP & IRP_MJ_CLOSE WRITEFILE -> IRP_MJ_WRITE READFILE-> IRP_MJ_READ Deviceiocontrol -> IRP_MJ_DEVICE_CONTROL To explain, one difference is IRP_MJ_CLOSE is not called in the context of the process which created the handle. If you need to perform process related clean up, then you need to handle IRP_MJ_CLEANUP as well.So as you can see, when a user mode application uses these functions, it calls into your driver. You may be wondering why the user mode API says "file" when it does not really mean "file". That is true, these APIs can talk to any device which exposes itself to user mode, they are not only for accessing files. In the last piece of this article, we will be writing a user mode application to talk to our driver and it will simply do CreateFile, WriteFile, CloseHandle. That's how simple it is. USE_WRITE_FUNCTION Is a constant i will explain later. The Next Piece of Code Is Pretty Simple, It's The Driver Unload function. PDRIVEROBJECT-> DRIVERUNLOAD = EXAMPLE_UNLOAD; You can technically omit this function but if you want to unload your driver dynamically, then it must be specified. If you do not specify this function once your driver is loaded, the system will not allow it to be unloaded. The code after this is actually using the DEVICE_OBJECT, not the DRIVER_OBJECT. These two data structures may get a little confusing since they both start with "D" and end with "_OBJECT", so it's easy to confuse which one we're using. PDEviceObject-> flags | = IO_TYPE; PDEviceObject-> flags & = (~ do_device_initializing); We are simply setting the flags. "IO_TYPE" is actually a constant which defines the type of I / O we want to do (I defined it in example.h). I will explain this in the section on handling user-mode write requests . The "DO_DEVICE_INITIALIZING" tells the I / O Manager that the device is being initialized and not to send any I / O requests to the driver. For devices created in the context of the "DriverEntry", this is not needed since the I / O Manager will clear this flag once the "DriverEntry" is done. However, if you create a device in any function outside of the DriverEntry, you need to manually clear this flag for any device you create with IoCreateDevice. This flag is actually set by the IoCreateDevice function. We cleared it here just for fun even though we were not required to.The last piece of our driver is using both of the Unicode strings we defined above. "/ Device / Example" and "/ DosDevices / Example". IOCREATESYMBOLICLINK (& USDOSDEVICENAME, & USDRIVERNAME); "IoCreateSymbolicLink" does just that, it creates a "Symbolic Link" in the object manager. To view the object manager, you may download my tool "QuickView", or go to www.sysinternals.com and download "WINOBJ". A Symbolic LINK SIMPLY MAPS A "DOS Device Name" to an "Nt Device Name". In this Example, "Example" is Our dos device name and "/ device / example" is Our NT device name. To put this into perspective, different vendors have different drivers and each driver is required to have its own name. You can not have two drivers with the same NT Device name. Say, you have a memory stick which can display itself to the system as a New Drive Drive Letter Such As E :. If You Remove This Memory Stick and Say You Map A Network Drive To E: The Same Way, They Do Not Care IF E: Is A CD ROM, Floppy Disk, memory stick or network drive. How is this possible? Well, the driver needs to be able to interpret the requests and either handle them within themselves such as the case of a network redirector or pass them down to the appropriate hardware driver This is done through symbolic links E:.. is a symbolic link The network mapped drive may map E:. to / Device / NetworkRedirector and the memory stick may map E: to / Device / FujiMemoryStick, for example.This is how Applications Can Be Written Using A Commonly Defined Name Which can be abstracted to point to any device driver which would be able to handle requests. There are no rules here, we could actually map / Device / Example to E :. We can do whatever we wish to do, but in the end, however , the application attempts to use the device as how the device driver needs to respond and act. This means supporting IOCTLs commonly used by those devices as applications will try to use them. COM1, COM2, etc. are all examples of this. COM1 is A DOS Name Which is mapped to an Nt Device Name of a Driver Which Handles Serial Requests. This Doesn't Even Need To Be a real physical serial port! So we have defined "Example" AS A DOS Device Which Points To "/ device / Example". In the "Communicating with Usermode" Portion, We Will Learn More About How To Use this mapping.create the unload routine The Next Piece of Code We Will Look at Is The Unload Routine. This is required in Order Driver Dynamical. This section will be a bit smaller as there is not much to excel. Void Example_unload (PDRIVER_Object DriverObject) { Unicode_string usdosdevicename; DBGPRINT ("eXample_unload caled / r / n"); RTLINITUNICODESTRING (& USDosDeviceName, L "// dosdevices // eXample"); IodeleteSymbolicLink (& USDOSDEVICENAME); IodeleteDevice (driverObject-> deviceObject); } You can do wherever you wish you unload routine. This Unload Routine is Very Simple, IT Just deletes the symbolic link we create and then deletes the Only Device That We create Which Was / Device / Example. CREANG THE IRP_MJ_WRITE The rest of the functions should be self explanatory as they do not do anything. This is why I am only choosing to explain the "Write" routine. If this article is liked, I may write a second tutorial on implementing the IO Control function . If you have used WriteFile and ReadFile, you know that you simply pass a buffer of data to write data to a device or read data from a device. These parameters are sent to the device in the IRP as we explained previously. There is more to the story though as there are actually three different methods that the I / O Manager will use to marshal this data before giving the IRP to the driver. that also means that how the data is marshaled is how the driver's Read and Write functions need to interpret The data. The Three Methods Are "Direct I / O", "Buffered I / O" and "neither". # I idef __Use_direct__ #define IO_TYPE DO_DIRECT_IO #define us_write_function example_writedirectio #ENDIF #ifdef __Use_buffered__ #define IO_TYPE DO_BUFFERED_IO #define us_write_function example_writebufferedio #ENDIF #ifndef IO_TYPE #define IO_TYPE 0 #define us_write_function example_writeneither #ENDIF The code was written so if you define "__USE_DIRECT__" in the header, then IO_TYPE is now DO_DIRECT_IO and USE_WRITE_FUNCTION is now Example_WriteDirectIO. If you define "__USE_BUFFERED__" in the header, then IO_TYPE is now DO_BUFFERED_IO and USE_WRITE_FUNCTION is now Example_WriteBufferedIO. If you don 't define __Use_direct__ or __use_buffered___ ip_type is defined as 0 (neither) and the write function is example_writeneither. WE WILL NOW Go over Each Type OF I / O. Direct I / O THE FIRST Thing I Will Do Is Simply Show You The Code for Handling Direct I / O. NTSTATUS EXAMPLE_WRITEDIRECTIO (PDEvice_Object DeviceObject, PIRP IRP) { NTSTATUS NTSTATUS = status_success; PIO_STACK_LOCATION PIOSTACKIRP = NULL; Pchar PWRITEDATABUFFER; DBGPRINT ("EXAMPLE_WRITEDIRECTIO CALLED / R / N"); / * * Each Time The IRP IS Passed Down * The Driver Stack A New Stack Location is Added * Specifying cemeters for the igp to the driver. * / PiostackirP = IOGETCURRENTIRPSTACKLOCATION (IRP); IF (Piostackir) { PWRITEDATABUFFER = MmgetsystemAddressFormdlsafe (IRP-> MDLADDRESS, NORMALPAGEPRIORIRIRITY); IF (PWRITEDATABUFER) { / * * WE NEED TO VERIFY That The String * Is Null Terminated. Bad Things Can Happen * if We access Memory Not Valid While In The Kernel. * / IF (Example_IsStringterminated (PWRITEDATABUFFER, PiostackirP-> parameters.write.length) { DBGPRINT (PWRITEDATABUFFER); } } } Return NTSTATUS; } The entry point simply provides the device object for the device for which this request is being sent for. If you recall, a single driver can create multiple devices even though we have only created one. The other parameter is as was mentioned before which is an IRP! The first thing we do is call "IoGetCurrentIrpStackLocation", and this simply provides us with our IO_STACK_LOCATION. In our example, the only parameter we need from this is the length of the buffer provided to the driver, which is at Parameters.Write.Length . The way buffered I / O works is that it provides you with a "MdlAddress" which is a "Memory Descriptor List". This is a description of the user mode addresses and how they map to physical addresses. The function we call then is " MmgetsystemAddressFormdlsafe "and we use the Irp-> mdladdress to do this. This Operation will the game US a system virtual address Which we can the use to read the memory. The reasoning behind this is that some drivers do not always process a user mode request in the context of the thread or even the process in which it was issued. If you process a request in a different thread which is running in another process context, you . SO, this Simply Maps The Physical Pages Used by The User Mode Process INTO System Memory. We can the Buffer Passed Down from User Mode. This method is generally used for larger buffers since it does not require memory to be copied. The user mode buffers are locked in memory until the IRP is completed which is the downside of using direct I / O. This is the only downfall and is why It's generally more useful for larger buffers.buffered I / O THE FIRST Thing I Will Do Is Simply Show You The Code for Handling Buffered I / O. NTSTATUS EXAMPLE_WRITEBUFFEREDIO (PDEvice_Object DeviceObject, PIRP IRP) { NTSTATUS NTSTATUS = status_success; PIO_STACK_LOCATION PIOSTACKIRP = NULL; Pchar PWRITEDATABUFFER; DBGPRINT ("eXample_writebufferedio caled / r / n"); / * * Each Time The IRP IS Passed Down * The Driver Stack A New Stack Location is Added * Specifying cemeters for the igp to the driver. * / PiostackirP = IOGETCURRENTIRPSTACKLOCATION (IRP); IF (Piostackir) { PWRITEDATABUFFER = (PCHAR) IRP-> AssociatedIrp.systemBuffer; IF (PWRITEDATABUFER) { / * * WE NEED TO VERIFY That The String * Is Null Terminated. Bad Things Can Happen * if We access Memory Not Valid While In The Kernel. * / IF (Example_IsStringterminated (PWRITEDATABUFFER, Piostackirp-> parameters.write.length))) { DBGPRINT (PWRITEDATABUFFER); } } } Return NTSTATUS; } As mentioned above, the idea is to pass data down to the driver that can be accessed from any context such as another thread in another process. The other reason would be to map the memory to be non-paged so the driver can also read it At raised Irql level. The reason you may need to access memory outside the current process context is that some drivers create threads in the SYSTEM process. They then defer work to this process either asynchronously or synchronously. A driver at a higher level than your driver may do this or your driver itself may do it.The downfall of using "Buffered I / O" is that it allocates non-paged memory and performs a copy. This is now overhead in processing every read and write into the driver. This is one of the reasons this is best used on smaller buffers. The whole user mode page does not need to be locked in memory as with Direct I / O, which is the plus side of this. The other problem with using this for larger buffers is that since it allocates Non-Paged Memory, IT Would Need To Allocate A Large Block of Sequential Non-Paged Memory. Neither Buffered Nor Direct THE FIRST Thing I Will Do Is Show You The Code for Handling Neither Buffered Nor Direct I / O. NTSTATUS EXAMPLE_WRITENEITEER (PDEvice_Object DeviceObject, PIRP IRP) { NTSTATUS NTSTATUS = status_success; PIO_STACK_LOCATION PIOSTACKIRP = NULL; Pchar PWRITEDATABUFFER; DBGPrint ("eXample_writeneither caled / r / n"); / * * Each Time The IRP IS Passed Down * The Driver Stack A New Stack Location is Added * Specifying cemeters for the igp to the driver. * / PiostackirP = IOGETCURRENTIRPSTACKLOCATION (IRP); IF (Piostackir) { / * * WE NEED THIS IN EXEPTION HANDLER OR ELSE We Could Trap. * / __Try { ProbeForread (IRP-> Userbuffer, Piostackirp-> parameters.write.length, TYPE_ALIGNMENT (CHAR); PWRITEDATABUFFER = IRP-> UserBuffer; IF (PWRITEDATABUFER) { / * * WE NEED TO VERIFY That The String * Is Null Terminated. Bad Things Can Happen * if We access Memory Not Valid While In The Kernel. * / IF (Example_IsStringterminated (PWRITEDATABUFFER, Piostackirp-> parameters.write.length))) { DBGPRINT (PWRITEDATABUFFER); } } } __except (exception_execute_handler) { Ntstatus = getExceptioncode (); } } Return NTSTATUS; } In this method, the driver accesses the user mode address directly. The I / O manager does not copy the data, it does not lock the user mode pages in memory, it simply gives the driver the user mode address buffer. The upside of this is that no data is copied, no memory is allocated, and no pages are locked into memory. The downside of this is that you must process this request in the context of the calling thread so you will be able to access the user mode address space of the correct process. The other downside of this is that the process itself can attempt to change access to the pages, free the memory, etc., on another thread. This is why you generally want to use "ProbeForRead" and "ProbeForWrite" functions and surround all the code in an exception handler. There's no guarantee that at any time the pages could be invalid, you can simply attempt to make sure they are, before you attempt to read or write. This buffer is stored AT IRP-> UserBuffer. What's twis #pragma stuff? These directives you see simply let the linker know what segment to put the code and what options to set on the pages. The "DriverEntry", for example, is set as "INIT" which is a discardable page. This is because you only need That function during initialization. Homework! YOUR HOMEWORK IS To Create The Read Routines for Each Type of I / O Processing. You can use the write routines as reference to figure out what you need to do. Dynamically Loading and Unloading the DriverA lot of tutorials will go and explain the registry, however, I have chosen not to at this time. There is a simple user mode API that you can use to load and unload the driver without having to do anything else This is what we will use for now. INT _CDECL Main (Void) { Handle hscmanager; Handle HService; Service_status ss; Hscmanager = OpenScManager (NULL, NULL, SC_MANAGER_CREATE_SERVICE); Printf ("Load Driver / N"); IF (HScManager) { Printf ("CREATE Service / N"); HService = CreateService (HScManager, "Example", "EXample driver", Service_start | Delete | Service_Stop, Service_kernel_driver, Service_demand_start, Service_ERROR_IGNORE, "C: //example.sys", NULL, NULL, NULL, NULL, NULL; IF (! hservice) { HService = OpenService (HScManager, "Example", Service_start | delete | service_stop; } IF (HService) { Printf ("Start Service / N"); StartService (Hservice, 0, NULL); Printf ("Press Enter to Close Service / R / N"); GetChar (); ControlService (hservice, service_control_stop, & ss); DeleteService (HService); ClosESERVICEHANDE (HSERVICE); } CloseServiceHandle (HSCManager); } Return 0; } This code will load the driver and start it. We load the driver with "SERVICE_DEMAND_START" which means this driver must be physically started. It will not start automatically on boot, that way we can test it, and if we blue-screen, we Can FIX The Issue without Having to Boot To Safe Mode. . This program will simply pause You can then run the application that talks to the service, in another window The code above should be pretty easy to understand that you need to copy the driver to C:. /Example.sys in order to use it . If the service fails to create, it This is knows it has already been created and opens it. We then start the service and pause. Once you press Enter, we stop the service, delete it from the list of services, and exit. Very Simple Code and You CAN Modify It To Serve Your Purposes.communicating to the Device Driver The Following Is The Code That Communicates To The Driver. INT _CDECL Main (Void) { Handle hfile; DWORD dwreturn; Hfile = CREATEFILE (".// EXAMPLE", Generic_read | generic_Write, 0, NULL, Open_EXISTING, 0, NULL IF (HFile) { Writefile (HFILE, "Hello from User Mode!", SIZEOF ("Hello from User Mode!"), & dwreturn, NULL; CloseHandle (HFILE); } Return 0; } This is probably simpler than you thought. If you compile the driver three times using the three different methods of I / O, the message sent down from user mode should be printed in DBGVIEW. As you notice, you simply need to open the DOS Device name using //./ Conclusion