1 在VS中使用模板“内核模式驱动程序,空(KMDF)”构建驱动工程。
2 项目属性, “驱动程序设置”>“常规” > “目标平台”默认为“通用”
3 项目中添加Driver.c (注意是.c而非.cpp)
#include <ntddk.h>
#include <wdf.h>
DRIVER_INITIALIZE DriverEntry;
EVT_WDF_DRIVER_DEVICE_ADD KmdfHelloWorldEvtDeviceAdd;
NTSTATUS
DriverEntry(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
{
// NTSTATUS variable to record success or failure
NTSTATUS status = STATUS_SUCCESS;
// Allocate the driver configuration object
WDF_DRIVER_CONFIG config;
// Print "Hello World" for DriverEntry
KdPrintEx(( DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "KmdfHelloWorld: DriverEntry\n" ));
// Initialize the driver configuration object to register the
// entry point for the EvtDeviceAdd callback, KmdfHelloWorldEvtDeviceAdd
WDF_DRIVER_CONFIG_INIT(&config,
KmdfHelloWorldEvtDeviceAdd
);
// Finally, create the driver object
status = WdfDriverCreate(DriverObject,
RegistryPath,
WDF_NO_OBJECT_ATTRIBUTES,
&config,
WDF_NO_HANDLE
);
return status;
}
NTSTATUS
KmdfHelloWorldEvtDeviceAdd(
_In_ WDFDRIVER Driver,
_Inout_ PWDFDEVICE_INIT DeviceInit
)
{
// We're not using the driver object,
// so we need to mark it as unreferenced
UNREFERENCED_PARAMETER(Driver);
NTSTATUS status;
// Allocate the device object
WDFDEVICE hDevice;
// Print "Hello World"
KdPrintEx(( DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "KmdfHelloWorld: KmdfHelloWorldEvtDeviceAdd\n" ));
// Create the device object
status = WdfDeviceCreate(&DeviceInit,
WDF_NO_OBJECT_ATTRIBUTES,
&hDevice
);
return status;
}
Ntddk.h 包含所有驱动程序的核心 Windows 内核定义,而 Wdf.h 包含基于 Windows 驱动程序框架 (WDF) 的驱动程序的定义。
如果无法添加 Ntddk.h
,请打开“配置”->“C/C++”>“常规”>“其他包含目录”并添加 C:\Program Files (x86)\Windows Kits\10\Include\<build#>\km
,将 <build#>
替换为 WDK 安装中的相应目录。
DriverEntry 是所有驱动程序的入口点 , DriverEntry 的任务是初始化驱动程序范围的结构和资源 。
系统在检测到你的设备已到达时,会调用 EvtDeviceAdd。 它的任务是初始化该设备的结构和资源 。
4 生成驱动程序
(1) 选择“属性” 。 在“Wpp 跟踪”>“所有选项”中,将“运行 Wpp 跟踪”设置为“否”
(2)编译成功后,在Debug目录中形成以下文件:
- KmdfHelloWorld.sys - 内核模式驱动程序文件
- KmdfHelloWorld.inf - 在安装驱动程序时 Windows 使用的信息文件
- KmdfHelloWorld.cat - 安装程序验证驱动程序的测试签名所使用的目录文件
(3)编译时出现error MSB8040: 此项目需要缓解了 Spectre 漏洞的库
原因:这是因为Visual Studio默认开启了缓解Spectre攻击的机制,所以就有两种解决方案,一种是生成解决方案时禁用Spectre缓解机制,另一种就是安装Spectre缓解机制。
a) 禁用Spectre机制: 右键解决方案,然后选择“属性”,然后选择“配置属性”——“C/C++”——“代码生成”,在最下方有一项Spectre缓解,下拉选择“禁用“就行了
b)安装Spectre缓解机制