參考資訊:
https://wasm.in/
http://four-f.narod.ru/
https://github.com/steward-fu/ddk
main.c
#include <wdm.h> #define DEV_NAME L"\\Device\\MyDriver" #define SYM_NAME L"\\DosDevices\\MyDriver" KAPC stAPC = {0}; PDEVICE_OBJECT pNextDevice = NULL; typedef enum _KAPC_ENVIRONMENT { OriginalApcEnvironment, AttachedApcEnvironment, CurrentApcEnvironment, InsertApcEnvironment } KAPC_ENVIRONMENT; NTSYSAPI BOOLEAN _stdcall KeInsertQueueApc(PRKAPC, PVOID, PVOID, KPRIORITY); void KeInitializeApc(PKAPC, PETHREAD, KAPC_ENVIRONMENT, PKKERNEL_ROUTINE, PKRUNDOWN_ROUTINE, PKNORMAL_ROUTINE, KPROCESSOR_MODE, PVOID); void APC_Handler(PRKAPC Apc, PKNORMAL_ROUTINE *NormalRoutine, PVOID *NormalContext, PVOID *SystemArgument1, PVOID *SystemArgument2) { DbgPrint("APC_Handler\n"); } NTSTATUS AddDevice(PDRIVER_OBJECT pMyDriver, PDEVICE_OBJECT pPhyDevice) { PDEVICE_OBJECT pMyDevice = NULL; UNICODE_STRING usDeviceName = { 0 }; UNICODE_STRING usSymbolName = { 0 }; RtlInitUnicodeString(&usDeviceName, DEV_NAME); IoCreateDevice(pMyDriver, 0, &usDeviceName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pMyDevice); RtlInitUnicodeString(&usSymbolName, SYM_NAME); IoCreateSymbolicLink(&usSymbolName, &usDeviceName); pNextDevice = IoAttachDeviceToDeviceStack(pMyDevice, pPhyDevice); pMyDevice->Flags &= ~DO_DEVICE_INITIALIZING; pMyDevice->Flags |= DO_BUFFERED_IO; KeInitializeApc(&stAPC, PsGetCurrentThread(), 0, APC_Handler, 0, NULL, KernelMode, NULL); return STATUS_SUCCESS; } void Unload(PDRIVER_OBJECT pMyDriver) { pMyDriver = pMyDriver; } NTSTATUS IrpPnp(PDEVICE_OBJECT pMyDevice, PIRP pIrp) { UNICODE_STRING usSymbolName = { 0 }; PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp); if (pStack->MinorFunction == IRP_MN_START_DEVICE) { KeInsertQueueApc (&stAPC, NULL, NULL, 0); } else if (pStack->MinorFunction == IRP_MN_REMOVE_DEVICE) { RtlInitUnicodeString(&usSymbolName, SYM_NAME); IoDeleteSymbolicLink(&usSymbolName); IoDetachDevice(pNextDevice); IoDeleteDevice(pMyDevice); IoCompleteRequest(pIrp, IO_NO_INCREMENT); return STATUS_SUCCESS; } IoSkipCurrentIrpStackLocation(pIrp); return IoCallDriver(pNextDevice, pIrp); } NTSTATUS DriverEntry(PDRIVER_OBJECT pMyDriver, PUNICODE_STRING pMyRegistry) { pMyDriver->MajorFunction[IRP_MJ_PNP] = IrpPnp; pMyDriver->DriverExtension->AddDevice = AddDevice; pMyDriver->DriverUnload = Unload; return STATUS_SUCCESS; }
在收到IRP_MN_START_DEVICE時,插入一個新的APC Task,用來處理資源的移除
完成