KMDF驱动如何获取底层硬盘驱动对象,并向其发送IRP_MJ_READ请求?请给出示例
时间: 2024-03-19 18:44:39 浏览: 156
获取底层硬盘驱动对象并向其发送IRP_MJ_READ请求,可以通过以下步骤实现:
1. 获取磁盘设备对象
可以使用 WdfDeviceGetIoTarget 函数获取磁盘设备的 WDFIOTARGET 对象,如下所示:
```
WDFIOTARGET target;
target = WdfDeviceGetIoTarget(Device);
```
2. 构建读请求
可以使用 WdfIoTargetSendReadSynchronously 函数向磁盘设备发送 IRP_MJ_READ 请求,如下所示:
```
WDF_REQUEST_REUSE_PARAMS reuseParams;
WDF_REQUEST_REUSE_PARAMS_INIT(&reuseParams, WDF_REQUEST_REUSE_NO_FLAGS, STATUS_SUCCESS);
WdfRequestReuse(Request, &reuseParams);
LARGE_INTEGER byteOffset;
byteOffset.QuadPart = offset;
NTSTATUS status = WdfIoTargetSendReadSynchronously(target, NULL, Request, &byteOffset, &length, NULL, NULL);
```
其中,Request 是 WDFREQUEST 对象,offset 是要读取的起始字节偏移量,length 是要读取的字节数。
完整示例代码如下:
```
NTSTATUS ReadDisk(
_In_ WDFDEVICE Device,
_In_ LONGLONG offset,
_In_ ULONG length,
_Out_ PVOID buffer)
{
NTSTATUS status = STATUS_SUCCESS;
WDF_REQUEST_REUSE_PARAMS reuseParams;
WDF_REQUEST_REUSE_PARAMS_INIT(&reuseParams, WDF_REQUEST_REUSE_NO_FLAGS, STATUS_SUCCESS);
WDFIOTARGET target;
target = WdfDeviceGetIoTarget(Device);
WDFREQUEST Request;
WDF_OBJECT_ATTRIBUTES attributes;
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ParentObject = Device;
status = WdfRequestCreate(&attributes, target, &Request);
if (!NT_SUCCESS(status)) {
return status;
}
LARGE_INTEGER byteOffset;
byteOffset.QuadPart = offset;
WdfRequestSetCompletionRoutine(Request, ReadDiskCompletionRoutine, buffer);
status = WdfIoTargetFormatRequestForRead(target, Request, NULL, NULL, &byteOffset, NULL);
if (!NT_SUCCESS(status)) {
WdfObjectDelete(Request);
return status;
}
status = WdfIoTargetSendRequestSynchronously(target, Request, NULL);
if (!NT_SUCCESS(status)) {
WdfObjectDelete(Request);
return status;
}
status = WdfRequestUnmarkCancelable(Request);
if (!NT_SUCCESS(status)) {
WdfObjectDelete(Request);
return status;
}
status = WdfRequestReuse(Request, &reuseParams);
if (!NT_SUCCESS(status)) {
WdfObjectDelete(Request);
return status;
}
return STATUS_SUCCESS;
}
VOID ReadDiskCompletionRoutine(
_In_ WDFREQUEST Request,
_In_ WDFIOTARGET Target,
_In_ PWDF_REQUEST_COMPLETION_PARAMS Params,
_In_ WDFCONTEXT Context)
{
PVOID buffer = Context;
ULONG_PTR length = Params->IoStatus.Information;
if (NT_SUCCESS(Params->IoStatus.Status)) {
RtlCopyMemory(buffer, WdfMemoryGetBuffer(Params->Parameters.Read.Buffer, NULL), length);
}
WdfObjectDelete(Request);
}
```
注意,以上代码仅为示例,具体实现可能需要根据实际情况进行调整。
阅读全文