Private data associated with each File Object created

I'm a newbie Windows driver developer, and I'm working on a scenario where the driver needs to store specific private data, like the process ID, for each CreateFile request from user mode. I looked at the code in the Windows IOCTL driver sample, which sets up callbacks for NonPnpEvtDeviceFileCreate and FileClose functions.

From what I understand, each CreateFile call from user mode gives us a FileObject handle and calls NonPnpEvtDeviceFileCreate callback with WDFFILEOBJECT FileObject .

The sample code creates a DeviceExtension struct with a FileHandle and associates it with the wdfdevice object, meaning the memory is attached to the device itself and is shared across all applications interacting with the driver. This approach works fine if only one application interacts with the driver at a time but fails when multiple applications do because the DeviceExtension struct is global.

What I want to achieve is simple: if an application closes or crashes, I need to print its process ID in the kernel and perform some cleanup based on that process ID. How can I implement this?

Please correct me if my understanding is incorrect and provide guidance.

Are you actually writing a non-PnP driver? Why?

You can attach a context to the WDFFILEOBJECT object exactly like you can to the WDFDEVICE object. That's one of the most beautiful things about KMDF -- you can slap a context on any object.. You'll fetch that context in your EvtFileClose handler and do what you need.

Hey Tim,
Thanks for quick reply.

I'm writing this non-PnP driver to get hands-on experience with IOCTLs and user-kernel communication. This will be part of a more comprehensive driver later on.

Attaching private data and FileHandle to WDFFILEOBJECT context should solve the problem, right? And if multiple applications or other kernels are communicating with the driver, each context data structure would be a different instance for each application?

Yeah… don’t do that. Instead, start with something like our Nothing driver.. which is specifically designed for learning the stuff you’re looking at.

Feel free to look at the lab handout (same repro) that goes with our WDF seminar… it’ll walk you through some hands on exercises.

Allow me to second Peter's excellent advice. It's quiet possible and very useful to create PnP drivers that do not have devices.

... each context data structure would be a different instance for each application?

There is one file object, and hence one WDFFILEOBJECT, and hence one context structure, for each call to CreateFile. It's quite possible for one application (or driver) to open a file multiple times. You can't assume that the process is dying just because your file was closed, but you can be certain that your EvtFileClose callback will be triggered when the handle is closed, for whatever reason.