PREfast for Drivers and IRQL Levels

IRQL levels can sometimes be a tricky thing to get right, especially if you’re new to drivers and coming from user mode. Playing with IRQL levels, memory, structures… Mix them the wrong way and you bugcheck the box. What can really be painful is the process of inheriting code and having to figure out what’s going on. Did the developer want this to come in at DISPATCH_LEVEL? With all the complexities of writing drivers using driver annotations is almost a necessity.

Let’s take this example:

NTSTATUSResetDevice( __in WDFDEVICE Device );

 

Off the top of your head without looking at the documentation you may or may not be able to determine what the IRQL level should be when you call this. Now can you be sure from all the different points in your code where this is called that you are at the correct IRQL?

Now let’s add one line of driver annotation to the same prototype:

__drv_requiresIRQL(PASSIVE_LEVEL)NTSTATUSResetDevice( __in WDFDEVICE Device );

 

You can see the obvious benefit in the code of the documentation. I could give this to my 9 yr old nephew and ask him what IRQL level this DDI requires. Here’s the other benefit: You can actually use PFD to check if this is valid in different areas of your code. Any place this is called PFD can detect it from one of two ways.

1. Annotation inference from another DDI call that either requires a certain IRQL level or raises/lowers the IRQL level. Looking at another DDI it can infer that the logic between the two DDI’s doesn’t make sense. (DDI-1 requires PASSIVE_LEVEL while DDI-2 four lines down requires APC_LEVEL)

2. It allows someone anyone who may have inherited the code to immediately understand the contract requirements and constraints on the DDI. Obviously, the code above has been shrunk down for simplicity, but you can see how this would be beneficial for a more complicated DDI.

This is something very easy that you can add to your code that will help with code portability and maintenance. If you’re all excited to jump into the next set of annotations you can feel free to read up more here: https://msdn2.microsoft.com/en-us/library/cc264089.aspx