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緩解機制