Beware the shiny light that is MmIsAddressValid

This came up on NTDEV today and has come up in the past (both in the community and internally on the KMDF team).  MmIsAddressValid appears to be a great function given its name.  You pass in a kernel virtual address (VA from now on) and it returns TRUE is the pointer is valid and FALSE otherwise.  It appears that you can use to validate a pointer before accessing it, a function similar to the user mode APIs IsBadReadPtr and IsBadWritePtr.  Unfortunately, this function does nothing of the sort.

So what does it do?  It tells you if a dereference of the VA will result in a page fault or not.  It does not tell you if the VA is valid or not.  MmIsAddressValid will blindly dereference the VA when determining the return value, so the implementation itself does not validate the address (like all other kernel functions).  On some versions of Windows, PagedPool lie within a specific range of addresses, so MmIsAddressvalid can theoritically make a simple value comparison of the VA against that range and return TRUe (this is a drastic simplification, the actual implementation is much more complicated).

What if this function did return whether the VA was valid?  Woudl it still be useful?  The answer is no and for the same reasons that IsBadReadPtr and friends are not useful.  The answer is transitory.  As soon as it returns the result, another thread can execute and free the address (as MSDN states for the user mode APIs).

In conclusion, you need to know the validity of your pointers a priori.  Of course you must validate any user mode pointers you recieve in your driver, but you cannot take a random kernel address and test it for validity.  Like Raymond says, "programming is hard," and you must be 100% in your code or else BSOD the machine.