// TEST.CPP
#include <windows.h>
#include <stdio.h>
#include <winioctl.h>
#include <setupapi.h>
#include "SimpleIoctl.h"
#include <initguid.h>
DEFINE_GUID(GUID_SIMPLE, 0x3d93c5c0, 0x0085, 0x11d1, 0x82, 0x1e, 0x00,
0x80, 0xc8, 0x83, 0x27, 0xab);
typedef struct _UNICODE_STRING {
WORD Length;
WORD MaximumLength;
LPWSTR Buffer;
} UNICODE_STRING;
#define Not_VxD
#include "myvxd.h"
void main(int argc, char* argv[])
{ // main
HMODULE hSetupapi = GetModuleHandle("SETUPAPI.DLL");
if (!hSetupapi)
{
puts("SETUPAPI.DLL not loaded!");
exit(1);
}
typedef BOOL (WINAPI* ENUM)(HDEVINFO, PSP_DEVINFO_DATA, LPGUID,
DWORD, PSP_INTERFACE_DEVICE_DATA);
typedef BOOL (WINAPI* GETDETAIL)(HDEVINFO,
PSP_INTERFACE_DEVICE_DATA, PSP_INTERFACE_DEVICE_DETAIL_DATA,
DWORD, PDWORD, PSP_DEVINFO_DATA);
ENUM SetupDiEnumDeviceInterfaces;
GETDETAIL SetupDiGetDeviceInterfaceDetail;
SetupDiEnumDeviceInterfaces = (ENUM) GetProcAddress(hSetupapi,
"SetupDiEnumDeviceInterfaces"); // NT 5.0 beta 1 name
if (!SetupDiEnumDeviceInterfaces)
SetupDiEnumDeviceInterfaces = (ENUM) GetProcAddress(hSetupapi,
"SetupDiEnumInterfaceDevice"); // Win98 beta 2 name
if (!SetupDiEnumDeviceInterfaces)
{
puts("Can't find SetupDiEnumDeviceInterfaces in SETUPAPI.DLL");
exit(1);
}
SetupDiGetDeviceInterfaceDetail = (GETDETAIL)
GetProcAddress(hSetupapi,
"SetupDiGetDeviceInterfaceDetailA"); // NT 5.0 beta 1 name
if (!SetupDiGetDeviceInterfaceDetail)
SetupDiGetDeviceInterfaceDetail = (GETDETAIL)
GetProcAddress(hSetupapi,
"SetupDiGetInterfaceDeviceDetailA"); // Win98 beta 2 name
if (!SetupDiGetDeviceInterfaceDetail)
{
printf("Can't find SetupDiGetDeviceInterfaceDetail in "
"SETUPAPI.DLL");
exit(1);
}
HDEVINFO info = SetupDiGetClassDevs((LPGUID) &GUID_SIMPLE, NULL,
NULL, DIGCF_PRESENT |
DIGCF_INTERFACEDEVICE);
if (info == INVALID_HANDLE_VALUE)
{
printf("Error %d trying to open enumeration handle for "
"GUID_SIMPLE\n", GetLastError());
exit(1);
}
SP_INTERFACE_DEVICE_DATA ifdata;
ifdata.cbSize = sizeof(ifdata);
if (!SetupDiEnumDeviceInterfaces(info, NULL, (LPGUID) &GUID_SIMPLE,
0, &ifdata))
{
printf("Error %d trying to enumerate interfaces\n",
GetLastError());
SetupDiDestroyDeviceInfoList(info);
exit(1);
}
DWORD needed;
SetupDiGetDeviceInterfaceDetail(info, &ifdata, NULL, 0, &needed,
NULL);
PSP_INTERFACE_DEVICE_DETAIL_DATA detail =
(PSP_INTERFACE_DEVICE_DETAIL_DATA) malloc(needed);
if (!detail)
{
printf("Error %d trying to get memory for interface detail\n",
GetLastError());
SetupDiDestroyDeviceInfoList(info);
exit(1);
}
detail->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
if (!SetupDiGetDeviceInterfaceDetail(info, &ifdata, detail, needed,
NULL, NULL))
{
printf("Error %d getting interface detail\n", GetLastError());
free((PVOID) detail);
SetupDiDestroyDeviceInfoList(info);
exit(1);
}
char name[MAX_PATH];
strncpy(name, detail->DevicePath, sizeof(name));
free((PVOID) detail);
SetupDiDestroyDeviceInfoList(info);
HANDLE hfile = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0,
NULL, OPEN_EXISTING, 0, NULL);
if (hfile == INVALID_HANDLE_VALUE)
{
printf("Error %d trying to open %s\n", GetLastError(), name);
exit(1);
}
DWORD version;
DWORD junk;
DWORD testval = 42;
BOOL dowrite = argc >= 2 && strcmpi(argv[1], "-dowrite") == 0;
if (DeviceIoControl(hfile, IOCTL_SIMPLE_GETVER_BUFFERED, &testval,
sizeof(testval), &version, sizeof(version), &junk, NULL))
printf("Buffered IOCTL reports version %d.%2.2d\n",
HIWORD(version), LOWORD(version));
else
printf("Buffered IOCTL failed with code %d\n", GetLastError());
if (DeviceIoControl(hfile, IOCTL_SIMPLE_GETVER_OUT_DIRECT,
&testval, sizeof(testval), &version, sizeof(version), &junk, NULL))
printf("Direct IOCTL reports version %d.%2.2d\n",
HIWORD(version), LOWORD(version));
else
printf("Direct IOCTL failed with code %d\n", GetLastError());
if (DeviceIoControl(hfile, IOCTL_SIMPLE_GETVER_NEITHER, &testval,
sizeof(testval), &version, sizeof(version), &junk, NULL))
printf("User-mode IOCTL reports version %d.%2.2d\n",
HIWORD(version), LOWORD(version));
else
printf("User-mode IOCTL failed with code %d\n", GetLastError());
if (dowrite)
{
DWORD nwritten;
if (WriteFile(hfile, "Hi!", 3, &nwritten, NULL))
printf("WriteFile succeeded, sent %d bytes\n", nwritten);
else
printf("WriteFile failed with code %d\n", GetLastError());
}
HANDLE hvxd = CreateFile("\\\\.\\MYVXD.VXD", 0, 0, 0, 0,
FILE_FLAG_DELETE_ON_CLOSE, NULL);
if (hvxd == INVALID_HANDLE_VALUE)
printf("Unable to dynamically load MYVXD\n");
else
{ // test VxD interface
WCHAR fname[MAX_PATH] = L"\\DosDevices\\";
int offset = wcslen(fname);
MultiByteToWideChar(CP_OEMCP, 0, name+4, -1, fname+offset,
MAX_PATH - offset);
OPENHANDLE_PARMS open = {
{wcslen(fname) * 2, sizeof(fname), fname},
GENERIC_READ | GENERIC_WRITE,
};
if (DeviceIoControl(hvxd, MYVXD_OPENHANDLE, &open,
sizeof(open), NULL, 0, NULL, NULL))
{ // opened handle okay
IOCTL_PARMS ioctl = {
open.hDevice,
IOCTL_SIMPLE_GETVER_BUFFERED,
NULL,
0,
&version,
sizeof(version),
};
if (DeviceIoControl(hvxd, MYVXD_IOCTL, &ioctl,
sizeof(ioctl), NULL, 0, NULL, NULL))
printf("IOCTL_SIMPLE_GETVER_BUFFERED via VxD reports "
"version number %d.%2.2d\n", HIWORD(version),
LOWORD(version));
else
printf("IOCTL_SIMPLE_GETVER_BUFFERED via VxD failed"
" with code %d\n", GetLastError());
CLOSEHANDLE_PARMS close = {open.hDevice};
if (DeviceIoControl(hvxd, MYVXD_CLOSEHANDLE, &close,
sizeof(close), NULL, 0, NULL, NULL))
printf("MYVXD_CLOSEHANDLE succeeded\n");
else
printf("MYVXD_CLOSEHANDLE failed with code %d\n",
GetLastError());
} // opened handle okay
else
printf("MYVXD_OPENHANDLE failed with code %d\n",
GetLastError());
CloseHandle(hvxd);
} // test VxD interface
CloseHandle(hfile);
} // main
Figure 2 A Simple WDM Driver
DRIVERENTRY.CPP
// DRIVERENTRY.CPP
#define INITGUID // define GUID_SIMPLE
#include "driver.h"
NTSTATUS AddDevice(IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT pdo);
VOID DriverUnload(IN PDRIVER_OBJECT fdo);
extern "C" NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject,
IN PUNICODE_STRING RegistryPath)
{ // DriverEntry
DriverObject->DriverUnload = DriverUnload;
DriverObject->DriverExtension->AddDevice = AddDevice;
DriverObject->MajorFunction[IRP_MJ_CREATE] = RequestCreate;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = RequestClose;
DriverObject->MajorFunction[IRP_MJ_WRITE] = RequestWrite;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = RequestControl;
DriverObject->MajorFunction[IRP_MJ_PNP] = RequestPnp;
DriverObject->MajorFunction[IRP_MJ_POWER] = RequestPower;
DriverObject->DriverStartIo = StartIo;
return STATUS_SUCCESS;
} // DriverEntry
VOID DriverUnload(IN PDRIVER_OBJECT DriverObject)
{ // DriverUnload
KdPrint(("simple - "
"Entering DriverUnload: DriverObject %8.8lX\n", DriverObject));
} // DriverUnload
NTSTATUS AddDevice(IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT pdo)
{ // AddDevice
NTSTATUS status;
PDEVICE_OBJECT fdo;
status = IoCreateDevice(DriverObject, sizeof(DEVICE_EXTENSION), NULL,
FILE_DEVICE_UNKNOWN, 0, FALSE, &fdo);
if (!NT_SUCCESS(status))
return status;
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fdo->DeviceExtension;
pdx->DeviceObject = fdo;
pdx->usage = 1; // locked until RemoveDevice
KeInitializeEvent(&pdx->evRemove, NotificationEvent, FALSE);
status = IoRegisterDeviceInterface(pdo, &GUID_SIMPLE, NULL,
&pdx->ifname);
if (!NT_SUCCESS(status))
{ // unable to register interface
IoDeleteDevice(fdo);
return status;
} // unable to register interface
IoSetDeviceInterfaceState(&pdx->ifname, TRUE);
pdx->LowerDeviceObject = IoAttachDeviceToDeviceStack(fdo, pdo);
fdo->Flags &= ~DO_DEVICE_INITIALIZING;
IoInitializeDpcRequest(fdo, DpcForIsr);
fdo->Flags |= DO_BUFFERED_IO;
pdx->power = PowerDeviceD0; // device starts in full power state
pdx->idle = PoRegisterDeviceForIdleDetection(pdo,
SIMPLE_IDLE_CONSERVATION, SIMPLE_IDLE_PERFORMANCE, PowerDeviceD3);
return STATUS_SUCCESS;
} // AddDevice
NTSTATUS CompleteRequest(IN PIRP Irp, IN NTSTATUS status, IN ULONG info)
{ // CompleteRequest
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = info;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return status;
} // CompleteRequest
NTSTATUS ForwardAndWait(IN PDEVICE_OBJECT fdo, IN PIRP Irp)
{ // ForwardAndWait
KEVENT event;
KeInitializeEvent(&event, NotificationEvent, FALSE);
IoCopyCurrentIrpStackLocationToNext(Irp);
IoSetCompletionRoutine(Irp, (PIO_COMPLETION_ROUTINE)
OnRequestComplete, (PVOID) &event, TRUE, TRUE, TRUE);
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fdo->DeviceExtension;
NTSTATUS status = IoCallDriver(pdx->LowerDeviceObject, Irp);
if (status == STATUS_PENDING)
{ // wait for completion
KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
status = Irp->IoStatus.Status;
} // wait for completion
return status;
} // ForwardAndWait
BOOLEAN LockDevice(PDEVICE_EXTENSION pdx)
{ // LockDevice
LONG usage = InterlockedIncrement(&pdx->usage);
if (pdx->removing)
{ // removing device
if (InterlockedDecrement(&pdx->usage) == 0)
KeSetEvent(&pdx->evRemove, 0, FALSE);
return FALSE;
} // removing device
return TRUE;
} // LockDevice
BOOLEAN LockDevice(IN PDEVICE_OBJECT fdo)
{
return LockDevice((PDEVICE_EXTENSION) fdo->DeviceExtension);
}
NTSTATUS OnRequestComplete(IN PDEVICE_OBJECT fdo, IN PIRP Irp,
IN PKEVENT pev)
{ // OnRequestComplete
KeSetEvent(pev, 0, FALSE);
return STATUS_MORE_PROCESSING_REQUIRED;
} // OnRequestComplete
VOID RemoveDevice(IN PDEVICE_OBJECT fdo)
{ // RemoveDevice
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fdo->DeviceExtension;
NTSTATUS status;
IoSetDeviceInterfaceState(&pdx->ifname, FALSE);
if (pdx->ifname.Buffer)
ExFreePool((PVOID) pdx->ifname.Buffer);
if (pdx->LowerDeviceObject)
IoDetachDevice(pdx->LowerDeviceObject);
IoDeleteDevice(fdo);
} // RemoveDevice
void UnlockDevice(PDEVICE_EXTENSION pdx)
{ // UnlockDevice
LONG usage = InterlockedDecrement(&pdx->usage);
if (usage == 0)
KeSetEvent(&pdx->evRemove, 0, FALSE);
} // UnlockDevice
void UnlockDevice(PDEVICE_OBJECT fdo)
{
UnlockDevice((PDEVICE_EXTENSION) fdo->DeviceExtension);
}
PLUGPLAY.CPP
// PLUGPLAY.CPP
#include "driver.h"
NTSTATUS DefaultPnpHandler(IN PDEVICE_OBJECT fdo, IN PIRP Irp);
NTSTATUS HandleRemoveDevice(IN PDEVICE_OBJECT fdo, IN PIRP Irp);
NTSTATUS HandleStartDevice(IN PDEVICE_OBJECT fdo, IN PIRP Irp);
NTSTATUS HandleStopDevice(IN PDEVICE_OBJECT fdo, IN PIRP Irp);
VOID ShowResources(IN PCM_PARTIAL_RESOURCE_LIST list);
NTSTATUS RequestPnp(IN PDEVICE_OBJECT fdo, IN PIRP Irp)
{ // RequestPnp
if (!LockDevice(fdo))
return CompleteRequest(Irp, STATUS_DELETE_PENDING, 0);
PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(Irp);
static NTSTATUS (*fcntab[])(IN PDEVICE_OBJECT fdo, IN PIRP Irp) = {
HandleStartDevice, // IRP_MN_START_DEVICE
DefaultPnpHandler, // IRP_MN_QUERY_REMOVE_DEVICE
HandleRemoveDevice, // IRP_MN_REMOVE_DEVICE
DefaultPnpHandler, // IRP_MN_CANCEL_REMOVE_DEVICE
HandleStopDevice, // IRP_MN_STOP_DEVICE
DefaultPnpHandler, // IRP_MN_QUERY_STOP_DEVICE
DefaultPnpHandler, // IRP_MN_CANCEL_STOP_DEVICE
DefaultPnpHandler, // IRP_MN_QUERY_DEVICE_RELATIONS
DefaultPnpHandler, // IRP_MN_QUERY_INTERFACE
DefaultPnpHandler, // IRP_MN_QUERY_CAPABILITIES
DefaultPnpHandler, // IRP_MN_QUERY_RESOURCES
DefaultPnpHandler, // IRP_MN_QUERY_RESOURCE_REQUIREMENTS
DefaultPnpHandler, // IRP_MN_QUERY_DEVICE_TEXT
DefaultPnpHandler, //
DefaultPnpHandler, //
DefaultPnpHandler, // IRP_MN_READ_CONFIG
DefaultPnpHandler, // IRP_MN_WRITE_CONFIG
DefaultPnpHandler, // IRP_MN_EJECT
DefaultPnpHandler, // IRP_MN_SET_LOCK
DefaultPnpHandler, // IRP_MN_QUERY_ID
DefaultPnpHandler, // IRP_MN_PNP_DEVICE_STATE
};
ULONG fcn = stack->MinorFunction;
NTSTATUS status;
if (fcn >= arraysize(fcntab))
{ // unknown function
status = DefaultPnpHandler(fdo, Irp);
UnlockDevice(fdo);
return status;
} // unknown function
status = (*fcntab[fcn])(fdo, Irp);
if (fcn != IRP_MN_REMOVE_DEVICE)
UnlockDevice(fdo);
return status;
} // RequestPnp
NTSTATUS DefaultPnpHandler(IN PDEVICE_OBJECT fdo, IN PIRP Irp)
{ // DefaultPnpHandler
IoSkipCurrentIrpStackLocation(Irp);
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fdo->DeviceExtension;
return IoCallDriver(pdx->LowerDeviceObject, Irp);
} // DefaultPnpHandler
NTSTATUS HandleRemoveDevice(IN PDEVICE_OBJECT fdo, IN PIRP Irp)
{ // HandleRemoveDevice
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fdo->DeviceExtension;
pdx->removing = TRUE;
UnlockDevice(pdx);
UnlockDevice(pdx);
KeWaitForSingleObject(&pdx->evRemove, Executive, KernelMode, FALSE,
NULL);
StopDevice(fdo);
NTSTATUS status = DefaultPnpHandler(fdo, Irp);
RemoveDevice(fdo);
return status;
} // HandleRemoveDevice
NTSTATUS HandleStartDevice(IN PDEVICE_OBJECT fdo, IN PIRP Irp)
{ // HandleStartDevice
NTSTATUS status = ForwardAndWait(fdo, Irp);
if (!NT_SUCCESS(status))
return CompleteRequest(Irp, status, Irp->IoStatus.Information);
PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(Irp);
status = StartDevice(fdo, &stack->Parameters.StartDevice.
AllocatedResourcesTranslated->List[0].PartialResourceList);
return CompleteRequest(Irp, status, 0);
} // HandleStartDevice
NTSTATUS HandleStopDevice(IN PDEVICE_OBJECT fdo, IN PIRP Irp)
{ // HandleStopDevice
NTSTATUS status = DefaultPnpHandler(fdo, Irp);
StopDevice(fdo);
return status;
} // HandleStopDevice
READWRITE.CPP
// READWRITE.CPP
#include "driver.h"
typedef struct POWER_STUFF {
PDEVICE_EXTENSION pdx;
DEVICE_POWER_STATE state;
} POWER_STUFF, *PPOWER_STUFF;
BOOLEAN DisableDevice(IN PDEVICE_EXTENSION pdx);
BOOLEAN EmpowerDevice(IN PPOWER_STUFF pps);
BOOLEAN EnableDevice(IN PDEVICE_EXTENSION pdx);
VOID OnCancel(IN PDEVICE_OBJECT fdo, IN PIRP Irp);
VOID OnCancelActiveIrp(IN PDEVICE_OBJECT fdo, IN PIRP Irp);
BOOLEAN OnInterrupt(IN PKINTERRUPT Interrupt, IN PDEVICE_EXTENSION fdo);
BOOLEAN TransferNext(IN PDEVICE_EXTENSION pdx);
BOOLEAN DisableDevice(IN PDEVICE_EXTENSION pdx)
{ // DisableDevice
pdx->enabled = FALSE;
return TRUE;
} // DisableDevice
VOID DpcForIsr(IN PKDPC Dpc, IN PDEVICE_OBJECT fdo, IN PIRP Irp,
IN PVOID Context)
{ // DpcForIsr
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fdo->DeviceExtension;
KIRQL irql;
IoAcquireCancelSpinLock(&irql);
BOOLEAN invalid = Irp != fdo->CurrentIrp;
if (!invalid)
IoSetCancelRoutine(Irp, NULL);
IoReleaseCancelSpinLock(irql);
if (invalid || Irp->Cancel)
return;
ULONG count = pdx->numxfer;
IoStartNextPacket(fdo, TRUE);
CompleteRequest(Irp, STATUS_SUCCESS, count);
UnlockDevice(pdx);
} // DpcForIsr
BOOLEAN EmpowerDevice(IN PPOWER_STUFF pps)
{ // EmpowerDevice
PDEVICE_EXTENSION pdx = pps->pdx;
DEVICE_POWER_STATE state = pps->state;
if (state == pdx->power)
return TRUE;
pdx->power = state;
if (state == PowerDeviceD0)
TransferNext(pdx);
return TRUE;
} // EmpowerDevice
BOOLEAN EnableDevice(IN PDEVICE_EXTENSION pdx)
{ // EnableDevice
pdx->enabled = TRUE;
return TRUE;
} // EnableDevice
VOID OnCancel(IN PDEVICE_OBJECT fdo, IN PIRP Irp)
{ // OnCancel
if (fdo->CurrentIrp == Irp)
{ // canceling current IRP
IoReleaseCancelSpinLock(Irp->CancelIrql);
IoStartNextPacket(fdo, TRUE);
} // canceling current IRP
else
{ // canceling queued IRP
KeRemoveEntryDeviceQueue(&fdo->DeviceQueue,
&Irp->Tail.Overlay.DeviceQueueEntry);
IoReleaseCancelSpinLock(Irp->CancelIrql);
} // canceling queued IRP
CompleteRequest(Irp, STATUS_CANCELLED, 0);
UnlockDevice(fdo);
} // OnCancel
VOID OnCancelActiveIrp(IN PDEVICE_OBJECT fdo, IN PIRP Irp)
{ // OnCancelActiveIrp
if (fdo->CurrentIrp == Irp)
{ // canceling active IRP
IoReleaseCancelSpinLock(Irp->CancelIrql);
IoStartNextPacket(fdo, TRUE);
CompleteRequest(Irp, STATUS_CANCELLED, 0);
UnlockDevice(fdo);
} // canceling active IRP
else
IoReleaseCancelSpinLock(Irp->CancelIrql);
} // OnCancelActiveIrp
BOOLEAN OnInterrupt(IN PKINTERRUPT Interrupt, IN PDEVICE_EXTENSION pdx)
{ // OnInterrupt
return TransferNext(pdx);
} // OnInterrupt
NTSTATUS RequestCreate(IN PDEVICE_OBJECT fdo, IN PIRP Irp)
{ // RequestCreate
return CompleteRequest(Irp, STATUS_SUCCESS, 0);
} // RequestCreate
NTSTATUS RequestClose(IN PDEVICE_OBJECT fdo, IN PIRP Irp)
{ // RequestClose
return CompleteRequest(Irp, STATUS_SUCCESS, 0);
} // RequestClose
NTSTATUS RequestWrite(IN PDEVICE_OBJECT fdo, IN PIRP Irp)
{ // RequestWrite
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fdo->DeviceExtension;
if (!LockDevice(pdx))
return CompleteRequest(Irp, STATUS_DELETE_PENDING, 0);
if (pdx->power > PowerDeviceD0)
{ // restore power to device
NTSTATUS status = SendDeviceSetPower(fdo, PowerDeviceD0, 0);
if (!NT_SUCCESS(status))
return CompleteRequest(Irp, status, 0);
} // restore power to device
if (pdx->idle)
PoSetDeviceBusy(pdx->idle);
IoMarkIrpPending(Irp);
IoStartPacket(fdo, Irp, NULL, OnCancel);
return STATUS_PENDING;
} // RequestWrite
VOID SetPowerState(IN PDEVICE_OBJECT fdo, IN DEVICE_POWER_STATE state)
{ // SetPowerState
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fdo->DeviceExtension;
POWER_STUFF ps = {pdx, state};
KeSynchronizeExecution(pdx->InterruptObject,
(PKSYNCHRONIZE_ROUTINE) EmpowerDevice, (PVOID) &ps);
} // SetPowerState
NTSTATUS StartDevice(PDEVICE_OBJECT fdo, PCM_PARTIAL_RESOURCE_LIST list)
{ // StartDevice
NTSTATUS status;
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fdo->DeviceExtension;
PCM_PARTIAL_RESOURCE_DESCRIPTOR resource = list->PartialDescriptors;
ULONG nres = list->Count;
BOOLEAN haveint = FALSE; // TRUE if we find our interrupt
ULONG vector; // interrupt vector
KIRQL irql; // interrupt level
KINTERRUPT_MODE mode; // interrupt mode
KAFFINITY affinity; // processor affinity for interrupt
BOOLEAN haveport = FALSE; // TRUE if we find our port
PHYSICAL_ADDRESS port; // port address
ULONG nports; // number of ports
BOOLEAN needmap = FALSE; // TRUE if we need to map port address
BOOLEAN error = FALSE; // TRUE if there's an error
for (ULONG i = 0; i < nres; ++i, ++resource)
{ // for each resource
switch (resource->Type)
{ // switch on resource type
case CmResourceTypePort:
{ // CmResourceTypePort
haveport = TRUE;
port = resource->u.Port.Start;
nports = resource->u.Port.Length;
needmap = (resource->Flags & CM_RESOURCE_PORT_IO) ==0;
break;
} // CmResourceTypePort
case CmResourceTypeInterrupt:
{ // CmResourceTypeInterrupt
haveint = TRUE;
irql = (KIRQL) resource->u.Interrupt.Level;
vector = resource->u.Interrupt.Vector;
affinity = resource->u.Interrupt.Affinity;
mode = (resource->Flags == CM_RESOURCE_INTERRUPT_LATCHED)
? Latched : LevelSensitive;
break;
} // CmResourceTypeInterrupt
case CmResourceTypeMemory:
{ // CmResourceTypeMemory
haveport = FALSE;
port = resource->u.Memory.Start;
nports = resource->u.Memory.Length;
needmap = TRUE;
break;
} // CmResourceTypeMemory
default:
error = TRUE;
break;
} // switch on resource type
} // for each resource
if (error || !haveport || !haveint)
return STATUS_DEVICE_CONFIGURATION_ERROR;
pdx->iospace = haveport;
pdx->nports = nports;
if (needmap)
{ // we have a memory-mapped register
pdx->base = (PUCHAR) MmMapIoSpace(port, nports, MmNonCached);
if (!pdx->base)
return STATUS_NO_MEMORY;
} // we have a memory-mapped register
else
pdx->base = (PUCHAR) port.LowPart;
pdx->mappedport = needmap;
pdx->iospace = haveport;
DisableDevice(pdx);
status = IoConnectInterrupt(&pdx->InterruptObject,
(PKSERVICE_ROUTINE) OnInterrupt, (PVOID) pdx, NULL, vector,
irql, irql, mode, FALSE, affinity, FALSE);
if (!NT_SUCCESS(status))
{ // unable to connect to interrupt
if (needmap)
MmUnmapIoSpace(pdx->base, nports);
return status;
} // unable to connect to interrupt
if (!KeSynchronizeExecution(pdx->InterruptObject,
(PKSYNCHRONIZE_ROUTINE) EnableDevice, (PVOID) pdx))
{ // can't enable device
IoDisconnectInterrupt(pdx->InterruptObject);
MmUnmapIoSpace(pdx->base, nports);
return STATUS_INVALID_DEVICE_STATE;
} // can't enable device
pdx->started = TRUE;
return STATUS_SUCCESS;
} // StartDevice
VOID StartIo(IN PDEVICE_OBJECT fdo, IN PIRP Irp)
{ // StartIo
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fdo->DeviceExtension;
KIRQL oldirql;
IoAcquireCancelSpinLock(&oldirql);
if (Irp != fdo->CurrentIrp || Irp->Cancel)
{ // request has been cancelled
IoReleaseCancelSpinLock(oldirql);
return;
} // request has been cancelled
else
{ // switch cancel routines
IoSetCancelRoutine(Irp, OnCancelActiveIrp);
IoReleaseCancelSpinLock(oldirql);
} // switch cancel routines
PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(Irp);
pdx->buffer = (PUCHAR) Irp->AssociatedIrp.SystemBuffer;
pdx->nbytes = stack->Parameters.Write.Length;
pdx->numxfer = 0;
KeSynchronizeExecution(pdx->InterruptObject,
(PKSYNCHRONIZE_ROUTINE) TransferNext, (PVOID) pdx);
} // StartIo
VOID StopDevice(IN PDEVICE_OBJECT fdo)
{ // StopDevice
PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fdo->DeviceExtension;
if (!pdx->started)
return;
pdx->started = FALSE;
KeSynchronizeExecution(pdx->InterruptObject,
(PKSYNCHRONIZE_ROUTINE) DisableDevice, (PVOID) pdx);
IoDisconnectInterrupt(pdx->InterruptObject);
pdx->InterruptObject = NULL;
if (pdx->mappedport)
MmUnmapIoSpace((PVOID) pdx->base, pdx->nports);
} // StopDevice
BOOLEAN TransferNext(IN PDEVICE_EXTENSION pdx)
{ // TransferNext
PIRP Irp = pdx->DeviceObject->CurrentIrp;
if (!Irp)
return FALSE; // no transfer pending
if (!pdx->nbytes)
{ // count exhausted
IoRequestDpc(pdx->DeviceObject, Irp, NULL);
return TRUE;
} // count exhausted
if (pdx->power > PowerDeviceD0)
return TRUE; // let IRP stall until power restored
if (pdx->iospace)
WRITE_PORT_UCHAR(pdx->base, *pdx->buffer);
else
WRITE_REGISTER_UCHAR(pdx->base, *pdx->buffer);
++pdx->buffer;
pdx->nbytes;
++pdx->numxfer;
return TRUE;
} // TransferNext
Figure 3 StartDevice Data Collection
NTSTATUS StartDevice(PDEVICE_OBJECT fdo,
PCM_PARTIAL_RESOURCE_LIST list)
{
PCM_PARTIAL_RESOURCE_DESCRIPTOR resource = list->PartialDescriptors;
ULONG nres = list->Count;
BOOLEAN error = FALSE;
for (ULONG i = 0; i < nres; ++i, ++resource)
switch (resource->type)
{
case CmResourceTypePort:
case CmResourceTypeInterrupt:
case CmResourceTypeMemory:
case CmResourceTypeDma:
}
}
Figure 4 Resource Descriptor Members
| Resource Type | Data to Extract | |
| CmResourceTypePort | u.Port.Start | Base address of group of ports |
| u.Port.Length | Number of ports at that address | |
| Flags | Various flags | |
| CmResourceTypeMemory | u.Memory.Start | Base address of memory window |
| u.Memory.Length | Number of bytes at that address | |
| Flags | Various flags | |
| CmResourceTypeInterrupt | u.Interrupt.Level | IRQL for this interrupt |
| u.Interrupt.Vector | Interrupt vector to hook | |
| u.Interrupt.Affinity | Processor affinity | |
| Flags | Various flags | |
| CmResourceTypeDma | u.Dma.Channel | Adapter channel number |
| u.Dma.Port | Port on adapter | |
| Flags | Various flags | |
Figure 7 Power Management Interfaces
|
Power Management Interface |
Brief Description |
|
PoCallDriver |
Send power management commands to a driver |
|
PoSetPowerState |
Used by a device driver during power state transitions to update information about its own device |
|
PoStartNextPowerIrp |
Indicate driver is ready for the next POWER request |
|
PoRegisterDeviceNotify |
Register notification function |
|
PoCancelDeviceNotify |
Undo a previous PoRegisterDeviceNotify |
|
PoRegisterDeviceForIdleDetection |
Request a power-change IRP if the device is idle for a specified period |
|
PoSetDeviceBusy |
Indicate that device is busy |
Figure 8 Minor Function Codes for IRP_MJ_POWER
|
Minor Function |
Brief Description |
|
IRP_MN_QUERY_POWER |
Determine if device can safely change to a specified power state |
|
IRP_MN_SET_POWER |
Direct device to change its power state |
|
IRP_MN_POWER_SEQUENCE |
Determine power sequence numbers |
|
IRP_MN_WAIT_WAKE |
Indicate that device will be needed to wake the computer |
Figure 9 NTKERN.VXD Services for I/O Operations
|
Service |
Brief Description |
|
NTKERN_Get_Version |
Get version number of NTKERN.VXD |
|
_NtKernCreateFile |
Open handle to WDM device |
|
_NtKernClose |
Close WDM device handle |
|
_NtKernReadFile |
Read from WDM device |
|
_NtKernWriteFile |
Write to WDM device |
|
_NtKernDeviceIoControl |
Perform control operation on WDM device |
Figure 10 MYVXD.VXD
MYVXD.C
// MYVXD.C
#include "stdvxd.h"
#pragma hdrstop
#include "myvxd.h"
DWORD OpenHandle(PUNICODE_STRING name, ACCESS_MASK DesiredAccess,
ULONG FileAttributes, ULONG ShareAccess, ULONG CreateDisposition,
ULONG CreateOptions, PHANDLE FileHandle);
DWORD Ioctl(DWORD hDevice, ULONG IoControlCode, PVOID pInbuf,
ULONG cbInbuf, PVOID pOutbuf, ULONG cbOutbuf);
DWORD CloseHandle(DWORD hDevice);
DWORD MapStatusToError(NTSTATUS status);
#pragma warning(disable:4035)
#undef _NtKernCreateFile
#undef _NtKernClose
#undef _NtKernDeviceIoControl
NTSTATUS __declspec(naked) __stdcall _NtKernCreateFile
(PHANDLE FileHandle,ACCESS_MASK DesiredAccess,
POBJECT_ATTRIBUTES ObjectAttributes,PIO_STATUS_BLOCK IoStatusBlock,
PLARGE_INTEGER AllocationSize,ULONG FileAttributes,ULONG ShareAccess,
ULONG CreateDisposition,ULONG CreateOptions,PVOID EaBuffer,
ULONG EaLength)
{
VxDJmp(_NtKernCreateFile)
}
NTSTATUS __declspec(naked) __stdcall _NtKernClose(HANDLE FileHandle)
{
VxDJmp(_NtKernClose)
}
NTSTATUS __declspec(naked) __stdcall _NtKernDeviceIoControl
(HANDLE FileHandle,HANDLE Event,PIO_APC_ROUTINE ApcRoutine,
PVOID ApcContext,PIO_STATUS_BLOCK IoStatusBlock,
ULONG IoControlCode,PVOID InputBuffer,ULONG InputBufferLength,
PVOID OutputBuffer,ULONG OutputBufferLength)
{
VxDJmp(_NtKernDeviceIoControl)
}
#pragma warning(default:4035)
#pragma VxD_INIT_CODE_SEG
SYSCTL BOOL OnSysDynamicDeviceInit(void)
{ // OnSysDynamicDeviceInit
if (NTKERN_Get_Version() < 0x40A)
return FALSE; // don't have Memphis level of NtKern
return TRUE;
} // OnSysDynamicDeviceInit
#pragma VxD_PAGEABLE_CODE_SEG
SYSCTL BOOL OnSysDynamicDeviceExit(void)
{ // OnSysDynamicDeviceExit
return TRUE;
} // OnSysDynamicDeviceExit
SYSCTL DWORD OnW32DeviceIoControl(PDIOCPARAMETERS p)
{ // OnW32DeviceIoControl
switch (p->dwIoControlCode)
{ // process control code
case DIOC_OPEN:
case DIOC_CLOSEHANDLE:
return 0;
case MYVXD_GETVERSION: // function 1
if (p->cbOutBuffer < sizeof(DWORD) || !p->lpvOutBuffer)
return ERROR_INVALID_PARAMETER;
*(PDWORD) p->lpvOutBuffer = 0x040A;
if (p->lpcbBytesReturned) // can be NULL!
*(PDWORD) p->lpcbBytesReturned = sizeof(DWORD);
return 0;
case MYVXD_OPENHANDLE: // function 2
{ // MYVXD_OPENHANDLE
OPENHANDLE_PARMS* parms = (OPENHANDLE_PARMS*) p->lpvInBuffer;
if (!parms || p->cbInBuffer < sizeof(OPENHANDLE_PARMS))
return ERROR_INVALID_PARAMETER;
return OpenHandle(&parms->name, parms->access,
parms->attributes, parms->share, parms->howcreate,
parms->options, (PHANDLE) &parms->hDevice);
} // MYVXD_OPENHANDLE
case MYVXD_IOCTL: // function 3
{ // MYVXD_IOCTL
IOCTL_PARMS* parms = (IOCTL_PARMS*) p->lpvInBuffer;
if (!parms || p->cbInBuffer < sizeof(IOCTL_PARMS))
return ERROR_INVALID_PARAMETER;
return Ioctl(parms->hDevice, parms->code, parms->inbuf,
parms->cbInbuf, parms->outbuf, parms->cbOutbuf);
} // MYVXD_IOCTL
case MYVXD_CLOSEHANDLE: // function 4
{ // MYVXD_CLOSEHANDLE
CLOSEHANDLE_PARMS* parms = (CLOSEHANDLE_PARMS*) p->lpvInBuffer;
if (!parms || p->cbInBuffer < sizeof(CLOSEHANDLE_PARMS))
return ERROR_INVALID_PARAMETER;
return CloseHandle(parms->hDevice);
} // MYVXD_CLOSEHANDLE
default:
ASSERT(FALSE);
return ERROR_INVALID_FUNCTION;
} // process control code
} // OnW32DeviceIoControl
DWORD OpenHandle(PUNICODE_STRING name, ACCESS_MASK DesiredAccess,
ULONG FileAttributes, ULONG ShareAccess, ULONG CreateDisposition,
ULONG CreateOptions, PHANDLE FileHandle)
{ // OpenHandle
OBJECT_ATTRIBUTES ObjectAttributes = {
sizeof(OBJECT_ATTRIBUTES), // Length
NULL, // RootDirectory
name, // ObjectName
0, // Attributes
NULL, // SecurityDescriptor
NULL, // SecurityQualityOfService
};
IO_STATUS_BLOCK IoStatusBlock;
return MapStatusToError(_NtKernCreateFile(FileHandle, DesiredAccess,
&ObjectAttributes, &IoStatusBlock, NULL, FileAttributes,
ShareAccess, CreateDisposition, CreateOptions, NULL, 0));
} // OpenHandle
DWORD Ioctl(DWORD hDevice, ULONG IoControlCode, PVOID pInbuf, ULONG cbInbuf,
PVOID pOutbuf, ULONG cbOutbuf)
{ // Ioctl
IO_STATUS_BLOCK IoStatusBlock;
return MapStatusToError(_NtKernDeviceIoControl((HANDLE) hDevice, NULL,
NULL, NULL, &IoStatusBlock, IoControlCode, pInbuf, cbInbuf,
pOutbuf, cbOutbuf));
} // Ioctl
DWORD CloseHandle(DWORD hDevice)
{ // CloseHandle
return MapStatusToError(_NtKernClose((HANDLE) hDevice));
} // CloseHandle
DWORD MapStatusToError(NTSTATUS status)
{ // MapStatusToError
// Status code mapping taken from KB article Q113996:
static struct {NTSTATUS s; DWORD e;} statmap[] = {
{STATUS_DATATYPE_MISALIGNMENT, ERROR_NOACCESS},
{STATUS_ACCESS_VIOLATION, ERROR_NOACCESS},
// etc.
{STATUS_VERIFY_REQUIRED, ERROR_MEDIA_CHANGED},
};
int i;
if (NT_SUCCESS(status))
return 0;
for (i = 0; i < arraysize(statmap); ++i)
if (status == statmap[i].s)
return statmap[i].e;
return ERROR_ACCESS_DENIED; // unknown error
} // MapStatusToError
STDVXD.H
// STDVXD.H
#ifndef STDVXD_H
#define STDVXD_H
#ifdef __cplusplus
extern "C" {
#define SYSCTL extern "C"
#else // not __cplusplus
#define SYSCTL
#endif // not __cplusplus
#include <wdm.h>
#define WANTVXDWRAPS
#include <basedef.h>
#undef NULL
#define NULL ((void*) 0)
#include <vmm.h>
#include <ntkern.h>
#include <debug.h>
#include <crs.h>
#include <vwin32.h>
#include <vxdwraps.h>
#include <winerror.h>
#ifdef __cplusplus
} // extern "C"
#endif
#include <string.h>
#pragma intrinsic(memcmp, memcpy, memset, strcat, strcmp, strcpy, strlen)
#ifdef DEBUG
#undef ASSERT
#define ASSERT(e) if(!(e)){Debug_Printf("Assertion failure in " \
__FILE__ ", line %d: " #e "\r\n", __LINE__);\
_asm int 1\
}
#else
#define ASSERT(e)
#endif
#ifndef MAKELONG
#define MAKELONG(low, high) ((LONG)(((WORD)(low)) | \
(((DWORD)((WORD)(high))) << 16)))
#endif
#ifndef FIELDOFFSET
#define FIELDOFFSET(type, field) ((DWORD)(&((type *)0)->field))
#endif
#ifndef arraysize
#define arraysize(p) (sizeof(p)/sizeof((p)[0]))
#endif
#ifndef NAKED
#define NAKED __declspec(NAKED)
#endif
#endif // STDVXD_H