KMDF驱动如何获取底层硬盘驱动对象,并向其发送IRP_MJ_WRITE请求?请给出示例
时间: 2024-03-19 07:44:42 浏览: 111
Porting-WDM-Drvs-to-KMDF.rar_WDF_WDM WDF_kmdf_wdm_驱动开发
获取底层硬盘驱动对象并向其发送IRP_MJ_WRITE请求,可以通过以下步骤实现:
1. 获取磁盘设备对象
可以使用 WdfDeviceGetIoTarget 函数获取磁盘设备的 WDFIOTARGET 对象,如下所示:
```
WDFIOTARGET target;
target = WdfDeviceGetIoTarget(Device);
```
2. 构建写请求
可以使用 WdfIoTargetSendWriteSynchronously 函数向磁盘设备发送 IRP_MJ_WRITE 请求,如下所示:
```
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 = WdfIoTargetSendWriteSynchronously(target, NULL, Request, &byteOffset, &length, NULL, NULL);
```
其中,Request 是 WDFREQUEST 对象,offset 是要写入的起始字节偏移量,length 是要写入的字节数。
完整示例代码如下:
```
NTSTATUS WriteDisk(
_In_ WDFDEVICE Device,
_In_ LONGLONG offset,
_In_ ULONG length,
_In_ 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, WriteDiskCompletionRoutine, buffer);
status = WdfIoTargetFormatRequestForWrite(target, Request, NULL, NULL, &byteOffset, NULL);
if (!NT_SUCCESS(status)) {
WdfObjectDelete(Request);
return status;
}
PVOID dataBuffer;
status = WdfRequestRetrieveOutputBuffer(Request, length, &dataBuffer, NULL);
if (!NT_SUCCESS(status)) {
WdfObjectDelete(Request);
return status;
}
RtlCopyMemory(dataBuffer, buffer, length);
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 WriteDiskCompletionRoutine(
_In_ WDFREQUEST Request,
_In_ WDFIOTARGET Target,
_In_ PWDF_REQUEST_COMPLETION_PARAMS Params,
_In_ WDFCONTEXT Context)
{
WdfObjectDelete(Request);
}
```
注意,以上代码仅为示例,具体实现可能需要根据实际情况进行调整。
阅读全文