Setting Contexts

After creating a new context, a minifilter driver can attach it to an object by calling FltSetXxxContext, where Xxx is the context type.

If the Operation parameter of the FltSetXxxContext routine is set to FLT_SET_CONTEXT_KEEP_IF_EXISTS, FltSetXxxContext attaches the newly allocated context to the object only if the minifilter driver has not already set a context for the object. If the minifilter driver has already set a context, FltSetXxxContext returns STATUS_FLT_CONTEXT_ALREADY_DEFINED, which is an NTSTATUS error code, and does not replace the existing context. If the OldContext parameter of the FltSetXxxContext routine is non-NULL, it receives a pointer to the existing context. When this pointer is no longer needed, the minifilter driver must release it by calling FltReleaseContext.

If the Operation parameter is set to FLT_SET_CONTEXT_REPLACE_IF_EXISTS, FltSetXxxContext always attaches the new context to the object. If the minifilter driver has already set a context, FltSetXxxContext deletes the existing context, sets the new context, and increments the reference count on the new context. If the OldContext parameter is non-NULL, it receives a pointer to the deleted context. When this pointer is no longer needed, the minifilter driver must release it by calling FltReleaseContext.

In the following code example, taken from the CTX sample minifilter driver, the CtxInstanceSetup routine creates and sets an instance context:

status = FltAllocateContext(
           FltObjects->Filter,           //Filter
           FLT_INSTANCE_CONTEXT,         //ContextType
           CTX_INSTANCE_CONTEXT_SIZE,    //ContextSize
           NonPagedPool,                 //PoolType
           &instanceContext);            //ReturnedContext
...
status = FltSetInstanceContext(
           FltObjects->Instance,              //Instance
           FLT_SET_CONTEXT_KEEP_IF_EXISTS,    //Operation
           instanceContext,                   //NewContext
           NULL);                             //OldContext

if (instanceContext != NULL) {
  FltReleaseContext(instanceContext);
}
return status;

Note that after the call to FltSetInstanceContext, there is a call to FltReleaseContext to release the reference count that was set by FltAllocateContext (not FltSetInstanceContext). This is explained in Releasing Contexts.