MSDN Documentation

Windows Kernel I/O

File Objects

A file object is a kernel-transparent structure that represents an open instance of a file or device. It is the primary object used by the I/O Manager and drivers to manage and access files and devices.

The ROLE_FILE_OBJECT Structure

The core of a file object is the _FILE_OBJECT structure, defined in <wdm.h>. This structure contains a wealth of information about the open file, including:

typedef struct _FILE_OBJECT {
    CSHORT Type;
    CSHORT Size;
    PDEVICE_OBJECT DeviceObject;
    PINTERNAL_DEVICE_BUFFER_DATA SharedBuffer;
    NAMED_PIPE_INFORMATION PipeInformation;
    LARGE_INTEGER RemainingBytes;
    ULONG Flags;
    // ... many other fields
} FILE_OBJECT, *PFILE_OBJECT;

Creating and Managing File Objects

File objects are typically created by the I/O Manager in response to a user-mode application opening a file or device. The process involves:

  1. User-Mode Request: An application calls CreateFile.
  2. I/O Manager Intervention: The I/O Manager receives the request, determines the target device, and creates a _FILE_OBJECT structure.
  3. Driver Interaction: The I/O Manager dispatches the create request (as an IRP_MJ_CREATE IRP) to the appropriate device driver.
  4. Driver Initialization: The driver may perform its own initialization for the open request, potentially associating driver-specific data with the file object.

Drivers interact with file objects primarily through the PFILE_OBJECT pointer passed in IRPs. Key operations include:

Important Considerations:

Drivers should never directly allocate or deallocate _FILE_OBJECT structures. This is the sole responsibility of the I/O Manager.

Common File Object Flags

The Flags member of the _FILE_OBJECT structure is crucial for understanding the state of the file object. Some common flags include:

File Object Context

Drivers often need to store their own private data associated with a particular file object. The _FILE_OBJECT structure provides a mechanism for this through its context pointer. Drivers typically allocate a custom context structure and set the FileObject->FsContext (or FsContext2) field to point to it. This allows drivers to maintain state specific to each open instance of a file or device.

Relevant Structures and Functions

Structures:

  • _FILE_OBJECT
  • DEVICE_OBJECT
  • DRIVER_OBJECT

User-Mode APIs:

  • CreateFile
  • CloseHandle

Kernel Functions:

  • IoCreateFile (rarely called directly by drivers)
  • IoAllocateFileObject (internal I/O Manager function)
  • IoFreeFileObject (internal I/O Manager function)