FltReleaseContext() woes…

Reference counting is a _LOT_ easier when you can actually see the reference counts at some point. COM has this done wonderfully with IUnknown::AddRef()/Release() both returning a “not known to be accurate but potentially helpful for debugging” result. The documentation clearly states that the return values are intended solely for “diagnostic/testing purposes”. Now move on down to the kernel and things get darker. Too dark!

The handle/stream/file/etc contexts provided by FltMgr are damn handy, but they are reference counted objects and there’s no way to track the active number of references on one. I can understand that hiding this sort of thing is important because hosing things in kernel mode is hardly pleasant, but returning even a stale count is helpful to track down something that is going to end up hosing the system anyway.

So let’s say your mini-filter won’t unload because you probably have outstanding references which you introduced by failing to call FltReleaseContext() at some point. With a helpful return value on the number of outstanding references at the time of a call to FltReleaseContext(), tracking this down is _SO_ much easier. For stream contexts on x64 (XP/2K3), the reference count seems to be 8 bytes behind the opaque pointer the mini-filter gets after calling FltAllocateContext(). I’m not sure what it is for other context types, but it’s not difficult to find.

So, this is what I ended up using…

  #define _DumpStreamContextReferenceCount( Context ) \
  { \
    if ( NULL != Context ) { \
      DbgPrint("Context(%p)!ReferenceCount=%u!" __FUNCTION__ "\n", Context, ((ULONG*)Context)[-2]); \
    }
  }

Now you can litter these little babies all over the damn place, sort the output and end up with something that at least gives you a clue about where the leak is.

Advertisements
This entry was posted in Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s