Steward
分享是一種喜悅、更是一種幸福
驅動程式 - Windows Driver Model (WDM) - 使用範例 - C/C++ (DDK) - Unload Driver
參考資訊:
https://wasm.in/
http://four-f.narod.ru/
https://github.com/steward-fu/wadk
當驅動程式準備要被系統移除時,I/O Manager會呼叫Unload Callback,做最後的資源清除動作,如果沒有將驅動程式的資源清除乾淨,系統會提示需要重新開機的訊息,由於我們並沒有在其它地方配置資源,因此,我們的Unload Callback就只是簡單列印字串而已
main.c
#include <wdm.h>
static PDEVICE_OBJECT pNextDevice = NULL;
static NTSTATUS AddDevice(PDRIVER_OBJECT pMyDriver, PDEVICE_OBJECT pPhyDevice)
{
PDEVICE_OBJECT pMyDevice = NULL;
UNICODE_STRING usDeviceName = { 0 };
UNICODE_STRING usSymbolName = { 0 };
RtlInitUnicodeString(&usDeviceName, L"\\Device\\MyDriver");
IoCreateDevice(pMyDriver, 0, &usDeviceName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pMyDevice);
DbgPrint("%s, pMyDevice = %p\n", __FUNCTION__, pMyDevice);
RtlInitUnicodeString(&usSymbolName, L"\\DosDevices\\MyDriver");
IoCreateSymbolicLink(&usSymbolName, &usDeviceName);
pNextDevice = IoAttachDeviceToDeviceStack(pMyDevice, pPhyDevice);
DbgPrint("%s, pNextDevice = %p\n", __FUNCTION__, pNextDevice);
pMyDevice->Flags &= ~DO_DEVICE_INITIALIZING;
pMyDevice->Flags |= DO_BUFFERED_IO;
return STATUS_SUCCESS;
}
static NTSTATUS IrpDispatch(PDEVICE_OBJECT pMyDevice, PIRP pIrp)
{
UNICODE_STRING usSymbolName = { 0 };
PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
DbgPrint("%s, Major = 0x%x\n", __FUNCTION__, pStack->MajorFunction);
if (pStack->MinorFunction == IRP_MN_REMOVE_DEVICE) {
DbgPrint("%s, Delete symbolic link\n", __FUNCTION__);
RtlInitUnicodeString(&usSymbolName, L"\\DosDevices\\MyDriver");
IoDeleteSymbolicLink(&usSymbolName);
DbgPrint("%s, Delete device\n", __FUNCTION__);
IoDetachDevice(pNextDevice);
IoDeleteDevice(pMyDevice);
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
IoSkipCurrentIrpStackLocation(pIrp);
return IoCallDriver(pNextDevice, pIrp);
}
static VOID Unload(PDRIVER_OBJECT pMyDriver)
{
DbgPrint("%s, pMyDriver = %p\n", __FUNCTION__, pMyDriver);
}
NTSTATUS DriverEntry(PDRIVER_OBJECT pMyDriver, PUNICODE_STRING pMyRegistry)
{
DbgPrint("%s, pMyDriver = %p\n", __FUNCTION__, pMyDriver);
pMyDriver->MajorFunction[IRP_MJ_PNP] = IrpDispatch;
pMyDriver->DriverExtension->AddDevice = AddDevice;
pMyDriver->DriverUnload = Unload;
return STATUS_SUCCESS;
}
完成