How KMDF converts handles to pointers


KMDF objects are data structures that are used internally by the framework. KMDF APIs don't allow drivers to access these objects directly via pointers, instead they are indirectly exposed via handles. Understanding how the object pointer to handle conversion happens internally helps during debugging, especially when it involves memory corruption issues. The debugger extension wdfkd.dll has commands to convert handles to object pointers and vice versa.

For instance the !wdfhandle command can be used to obtain the raw object pointer referred to by the handle, as shown below:

kd> !wdfkd.wdfhandle 0x00001ffef28eb788
Treating handle as a KMDF handle!

Dumping WDFHANDLE 0x00001ffef28eb788
=============================
Handle type is WDFDEVICE
Refcount: 4
Contexts:
    context:  dt 0xffffe0010d714b60 cdrom!CDROM_DEVICE_EXTENSION (size is 0x4a0 bytes)
    EvtCleanupCallback fffff801f65f1a9c cdrom!DeviceEvtCleanup

Parent: !wdfhandle 0x00001ffef386c3c8, type is WDFDRIVER
Owning device: !wdfdevice 0x00001ffef28eb788

!wdfobject 0xffffe0010d714870

The !wdfobject command converts a raw object pointer to a handle, as shown in the example below:

kd> !wdfobject 0xffffe0010d714870

The type for object 0xffffe0010d714870 is FxDevice
State: FxObjectStateCreated (0x1)
!wdfhandle 0x00001ffef28eb788

dt FxDevice 0xffffe0010d714870

Contexts:
    context:  dt 0xffffe0010d714b60 cdrom!CDROM_DEVICE_EXTENSION (size is 0x4a0 bytes)
    EvtCleanupCallback fffff801f65f1a9c cdrom!DeviceEvtCleanup

 Parent: !wdfobject  0xffffe0010c793c30, !wdfhandle 0x00001ffef386c3c8, type is WDFDRIVER
Owning device: !wdfdevice 0x00001ffef28eb788

The framework internally translates handles to object pointers using the following logic on X64 systems.

Object = ( (~Handle) & 0xfffffffffffffff8 )

The following debugger command illustrates the conversion.

kd> ??((unsigned int64)(~0x00001ffef28eb788) & 0xFFFFFFFFFFFFFFF8)
unsigned int64 0xffffe001`0d714870

The KMDF function Wdf01000!FxObject::_GetObjectFromHandle() performs this mapping.