Attaching the Filter Device Object to the Target Device Object

Call IoAttachDeviceToDeviceStackSafe to attach the filter device object to the filter driver stack for the target file system or volume.

devExt = myLegacyFilterDeviceObject->DeviceExtension;

status = IoAttachDeviceToDeviceStackSafe(
           myLegacyFilterDeviceObject,        //SourceDevice
           DeviceObject,                      //TargetDevice
           &devext->AttachedToDeviceObject);  //AttachedToDeviceObject

Note that the device object pointer received by the AttachedToDeviceObject output parameter can differ from TargetDevice if any other filters were already chained above the device object that is pointed to by TargetDevice.

Attaching to a File System by Name

Every file system is required to create one or more named control device objects. To attach to a particular file system directly, a file system filter driver passes the name of the appropriate file system control device object to IoGetDeviceObjectPointer to get a device object pointer. The following code snippet shows how to get such a pointer to one of the two control device objects for the RAW file system:

RtlInitUnicodeString(&nameString, L"\\Device\\RawDisk");

status = IoGetDeviceObjectPointer(
            &nameString,                    //ObjectName
            FILE_READ_ATTRIBUTES,           //DesiredAccess
            &fileObject,                    //FileObject
            &rawDeviceObject);              //DeviceObject

if (NT_SUCCESS(status)) {
            ObDereferenceObject(fileObject);
}

If the call to IoGetDeviceObjectPointer succeeds, the file system filter driver can then call IoAttachDeviceToDeviceStackSafe to attach to the returned control device object.

Note In addition to the control device object pointer (rawDeviceObject), IoGetDeviceObjectPointer returns a pointer to a file object (fileObject) that represents the device object in user mode. In the code snippet above, the file object is not needed, so it is closed by calling ObDereferenceObject. It is important to note that decrementing the reference count on the file object returned by IoGetDeviceObjectPointer causes the reference count on the device object to be decremented as well. Thus the fileObject and rawDeviceObject pointers should both be considered invalid after the above call to ObDereferenceObject, unless the reference count on the device object is incremented by an additional call to ObReferenceObject before ObDereferenceObject is called for the file object.