diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..8a41ad9
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,72 @@
+name: ci
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+jobs:
+ logic:
+ name: Build, test, pack (ubuntu)
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: 8.0.x
+
+ - name: Restore
+ run: dotnet restore
+
+ - name: Build
+ run: dotnet build --no-restore -c Release
+
+ - name: Test
+ run: dotnet test --no-build -c Release
+
+ - name: Pack
+ run: dotnet pack --no-build -c Release -o artifacts/
+
+ - name: InfGen smoke test
+ run: |
+ dotnet tool install --prerelease --tool-path ./tools-out --add-source ./artifacts WindowsDriver.InfGen
+ ./tools-out/infgen generate --manifest samples/VirtualAudio/manifest.json --out /tmp/virtualaudio.inf
+ ./tools-out/infgen validate --inf /tmp/virtualaudio.inf
+
+ - name: Template smoke test
+ run: |
+ dotnet new install ./artifacts/WindowsDriver.Templates.*.nupkg
+ mkdir -p /tmp/tpl && pushd /tmp/tpl
+ dotnet new driver-solution -n SmokeDriver
+ cd SmokeDriver && dotnet new sln -n SmokeDriver
+ dotnet sln add SmokeDriver/SmokeDriver.csproj SmokeDriver.Tests/SmokeDriver.Tests.csproj
+ dotnet restore --source "${{ github.workspace }}/artifacts" --source https://api.nuget.org/v3/index.json
+ dotnet test
+ popd
+
+ - name: Upload packages
+ uses: actions/upload-artifact@v4
+ with:
+ name: nuget-packages
+ path: artifacts/*.nupkg
+
+ windows:
+ name: Build samples (windows)
+ runs-on: windows-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: 8.0.x
+
+ - name: Build + test
+ run: |
+ dotnet build -c Release
+ dotnet test --no-build -c Release
+
+ # NOTE: GitHub-hosted Windows runners do not ship the WDK, so the native
+ # KMDF shim and real INF signing cannot run here. Compile shim/WdsKmdfShim
+ # and run InfVerif/SignTool on a machine (or private runner) with the WDK.
+ # See docs/inf-and-signing.md for the full pipeline.
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..3d354e1
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,30 @@
+# Build artifacts
+bin/
+obj/
+artifacts/
+out/
+publish/
+*.user
+*.suo
+.vs/
+
+# NuGet
+*.nupkg
+*.snupkg
+packages/
+nuget/
+
+# Test results
+TestResults/
+*.trx
+*.coverage
+test-results/
+
+# Generated INF output
+*.inf.bak
+
+# IDE
+.idea/
+*.swp
+.DS_Store
+Thumbs.db
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..e07c7ad
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,59 @@
+# Changelog
+
+All notable changes to the Windows Driver SDK are documented in this file.
+The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
+
+## [0.1.0-preview.1] - 2026-11-18
+
+First public preview of the SDK. Everything below ships in this bundle.
+
+### Added
+
+- `WindowsDriver.Sdk` core runtime:
+ - Driver lifecycle model (`IDriver`: `OnDriverEntryAsync` / `OnDeviceAddAsync` / `OnDriverUnloadAsync`)
+ and device lifecycle model (`DeviceBase`: prepare/release hardware, D0 entry/exit,
+ query-remove, surprise-removal) mirroring the WDF callback order.
+ - IO model: `IoQueue` with Sequential / Parallel / Manual dispatch modes (the WDF
+ `WdfIoQueueDispatch*` equivalents), `IoRequest` with buffered completion,
+ `IoResult` for request outcomes.
+ - `NtStatus` enum with the common NTSTATUS values plus severity helpers.
+ - `WinIoctl.CtlCode` implementing the exact `CTL_CODE` C macro bit layout, and the
+ common `FILE_DEVICE_*` / method / access constants.
+ - `DriverContext`, `DeviceContext`, `PropertyStore`, `IDriverRegistry` (+ in-memory
+ implementation), `IDriverLog` (+ console / file / composite loggers).
+ - `ByteRingBuffer`: thread-safe byte ring buffer used by audio and serial.
+- Device-class modules:
+ - **Audio**: `PcmFormat` + `AudioFormatNegotiator`, `AudioDeviceStateMachine`,
+ `VolumeState` (dB/mute/ramp), `AudioIoctlCodes` contract, `VirtualAudioDevice`,
+ `SineSource` generator and `PcmWavWriter` capture.
+ - **HID**: `HidReportDescriptorBuilder` emitting real USB HID report descriptors
+ (main/global/local items, report IDs, automatic bit padding), a descriptor parser
+ for validation, the 9-byte HID class descriptor builder, `GamepadInputReport`
+ pack/unpack, and a `HidDevice` wired for descriptor + input-report IOCTLs.
+ - **Sensor**: `AccelerometerSimulator` (gravity + deterministic noise + impulses),
+ `AmbientLightSimulator` (day-cycle lux curve), `SensorDevice` publishing readings
+ over IOCTL and an event queue.
+ - **Serial**: `SerialLineConfig` (baud/data bits/parity/stop bits/flow control),
+ `VirtualSerialPort` loopback pair, `SerialDevice` with line-control IOCTLs and
+ TX/RX statistics.
+- `WindowsDriver.Interop`:
+ - UMDF layer: C# contract mirrors of the key `IWDF*` interfaces (documented, without
+ invented COM IIDs), the C-shim export contract, and `ManagedDriverBootstrap` —
+ the entry point a native UMDF shim calls after hosting the .NET runtime via
+ `hostfxr`.
+ - KMDF layer: control-plane IOCTL contract (`KmdfIoctlCodes`), `KmdfControlPlane`
+ (real `CreateFileW` / `DeviceIoControl` P/Invoke client for talking to a KMDF
+ shim driver), and the request/event wire structs shared with the C shim.
+ - `Win32Native` P/Invoke declarations (CreateFile, DeviceIoControl, CloseHandle).
+- `WindowsDriver.Testing`: `TestDriverHost` / `TestDevice` (in-memory device bus that
+ runs driver logic without Windows), `FakeTimeProvider` (advanceable .NET 8
+ `TimeProvider`), `CapturedLog`, `FakeRegistry`, and check helpers.
+- `WindowsDriver.InfGen`: `dotnet` tool that generates a spec-compliant driver INF
+ from a JSON manifest (`infgen generate`) and lints an existing INF
+ (`infgen validate`).
+- Four sample drivers with unit tests and INF manifests: **VirtualAudio**,
+ **HidGamepad**, **VirtualSensor**, **VirtualSerial**.
+- `dotnet new` templates (`driver-umdf`, `driver-tests`, `driver-solution`).
+- Install/uninstall/test-signing PowerShell scripts (`tools/`), a ready-to-build
+ KMDF shim driver skeleton in C (`shim/WdsKmdfShim/`), a GitHub Actions CI workflow,
+ and the full documentation set under `docs/`.
diff --git a/Directory.Build.props b/Directory.Build.props
new file mode 100644
index 0000000..f435789
--- /dev/null
+++ b/Directory.Build.props
@@ -0,0 +1,20 @@
+
+
+
+
+ net8.0
+ 12.0
+ enable
+ enable
+ 0.1.0-preview.1
+ Windows Driver SDK contributors
+ Windows Driver SDK contributors
+ en-US
+ true
+
+ $(NoWarn);CS1591
+ true
+ false
+
+
+
diff --git a/Directory.Packages.props b/Directory.Packages.props
new file mode 100644
index 0000000..9c46357
--- /dev/null
+++ b/Directory.Packages.props
@@ -0,0 +1,14 @@
+
+
+
+
+ true
+
+
+
+
+
+
+
+
+
diff --git a/LICENSE b/LICENSE
index b7e1c5b..9bf676c 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,6 +1,6 @@
MIT License
-Copyright (c) 2026 Full Dive Research Society
+Copyright (c) 2026 Windows Driver SDK contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..02100d8
--- /dev/null
+++ b/README.md
@@ -0,0 +1,130 @@
+# Windows Driver SDK for .NET
+
+Write Windows device drivers in C#. The SDK gives you a managed driver runtime
+with the WDF programming model — driver/device lifecycle, IO queues, IOCTL
+dispatch, NTSTATUS semantics — plus ready-made device-class modules for
+**audio**, **HID**, **sensor** and **serial** devices, an INF generator, a
+test host that runs your driver without Windows, and the native shim contracts
+that take the same code to production.
+
+```
+┌────────────────────────────────────────────────────────────┐
+│ Your driver: IDriver + DeviceBase subclass in pure C# │
+├────────────────────────────────────────────────────────────┤
+│ WindowsDriver.Sdk │
+│ • runtime: lifecycle, IoQueue, IOCTL, NTSTATUS, logging │
+│ • modules: Audio · HID · Sensor · Serial │
+├────────────────────────────────────────────────────────────┤
+│ Hosting (choose one) │
+│ • WindowsDriver.Testing.TestDriverHost (unit tests) │
+│ • UMDF shim (user-mode, WUDFHost) │
+│ • KMDF control plane over the C shim (kernel reach) │
+└────────────────────────────────────────────────────────────┘
+```
+
+## Why
+
+Microsoft's Windows Driver Kit supports C/C++ for driver code (UMDF drivers are
+C++/COM; kernel drivers are C). Managed code has never been officially
+supported in kernel mode, and UMDF is C++-only in the box. This SDK fills the
+gap the practical way:
+
+- **Driver logic in C#** — the parts that iterate quickly (device logic, state
+ machines, protocol handling, policy) run in .NET 8.
+- **Native where required** — the parts that must be native (COM activation in
+ WUDFHost, kernel-mode DDIs) are thin, frozen-ABI shims documented and
+ scaffolded in this repository (`shim/`).
+- **Testable without Windows** — `TestDriverHost` runs your driver with a fake
+ clock and in-memory bus on any OS. The full sample suite (62 tests) runs on
+ Linux CI in under a second.
+
+This is the same architecture commercial products (e.g. Jungo WinDriver's
+user-mode .NET offering) and many in-house drivers use — but open, and with the
+WDF-shaped API surface you already know.
+
+## Packages
+
+| Package | What it gives you |
+| --- | --- |
+| `WindowsDriver.Sdk` | Core runtime + Audio/HID/Sensor/Serial modules |
+| `WindowsDriver.Interop` | UMDF shim contracts, KMDF control plane, Win32 P/Invoke |
+| `WindowsDriver.Testing` | `TestDriverHost`, `FakeTimeProvider`, captured logging |
+| `WindowsDriver.InfGen` | `infgen` dotnet tool: manifest → INF, INF lint |
+| `WindowsDriver.Templates` | `dotnet new driver-umdf` / `driver-tests` / `driver-solution` |
+
+## Quickstart
+
+Prerequisites: [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0).
+Building/deploying a real driver additionally needs the
+[WDK](https://learn.microsoft.com/windows-hardware/drivers/download-the-wdk)
+on a Windows machine.
+
+```bash
+# 1. Create a driver project from the template
+dotnet new install WindowsDriver.Templates --prerelease
+dotnet new driver-solution -n ContosoButton
+cd ContosoButton && dotnet new sln -n ContosoButton
+dotnet sln add ContosoButton/ContosoButton.csproj ContosoButton.Tests/ContosoButton.Tests.csproj
+
+# 2. Test it — no Windows, no device, no VM
+dotnet test
+
+# 3. Generate the INF for deployment
+dotnet tool install --prerelease --tool-path ./.tools WindowsDriver.InfGen
+./.tools/infgen generate --manifest ContosoButton/ContosoButton.manifest.json
+```
+
+That is a complete driver: a `DeviceBase` subclass with IOCTL handlers, a
+passing test, and an INF you can sign and deploy.
+
+## Sample drivers (all with tests + INF manifests)
+
+| Sample | Class | Highlights |
+| --- | --- | --- |
+| [VirtualAudio](samples/VirtualAudio/) | Media | PCM ring buffer, 44.1/48/96 kHz format negotiation, volume ramps, tone generator |
+| [HidGamepad](samples/HidGamepad/) | HIDClass | Real USB HID report descriptor builder (6-axis + 12 buttons), report pack/unpack |
+| [VirtualSensor](samples/VirtualSensor/) | Sensor | Accelerometer + ambient light simulators, IOCTL + event-queue publishing |
+| [VirtualSerial](samples/VirtualSerial/) | Ports | Line config validation, loopback, null-modem pairs, break/framing faults |
+
+## Documentation
+
+| Doc | Content |
+| --- | --- |
+| [Getting started](docs/getting-started.md) | Install, first driver end-to-end, deploy |
+| [Architecture](docs/architecture.md) | The managed-host model, layering, hosting paths |
+| [UMDF guide](docs/umdf-guide.md) | Hosting C# drivers in WUDFHost, shim ABI, lifecycle mapping |
+| [KMDF interop guide](docs/kmdf-interop-guide.md) | Kernel constraints, control plane, the C shim protocol |
+| [Audio guide](docs/audio-guide.md) | Ring buffer, negotiation, the audio IOCTL contract |
+| [HID guide](docs/hid-guide.md) | HID item encoding, descriptor building, report layout |
+| [Sensor guide](docs/sensor-guide.md) | Simulators, sampling loop, SensorCx mapping |
+| [Serial guide](docs/serial-guide.md) | Line config, loopback pairs, Windows serial stack |
+| [INF and signing](docs/inf-and-signing.md) | Manifest schema, INF anatomy, test-signing, attestation |
+| [Testing guide](docs/testing-guide.md) | TestDriverHost, fake clock, patterns |
+| [CI/CD](docs/ci-cd.md) | GitHub Actions setup, WDK limitations on runners |
+| [API reference](docs/api-reference.md) | Type-by-type summary of the SDK surface |
+
+## Repository layout
+
+```
+src/WindowsDriver.Sdk core runtime + device-class modules
+src/WindowsDriver.Interop UMDF/KMDF interop, Win32 P/Invoke
+src/WindowsDriver.Testing test host helpers
+src/WindowsDriver.InfGen infgen tool
+src/WindowsDriver.Templates dotnet new templates
+samples/ VirtualAudio, HidGamepad, VirtualSensor, VirtualSerial
+tests/ SDK unit tests
+shim/WdsKmdfShim KMDF shim driver skeleton (C, build with the WDK)
+shim/UmdfShim UMDF COM shim design notes + ABI
+tools/ Install-Driver.ps1, Uninstall-Driver.ps1, Enable-TestSigning.ps1
+docs/ the documentation set
+.github/workflows/ci.yml build + test + pack + smoke tests
+```
+
+## Status and support
+
+Version 0.1.0-preview.1. The managed SDK surface is complete and tested (62
+tests, all green). The KMDF C shim compiles as a WDK skeleton and implements
+the full IOCTL contract; the UMDF C++/COM shim is specified and ABIs frozen,
+with implementation notes in `shim/UmdfShim/README.md`.
+
+License: MIT (see [LICENSE](LICENSE)).
diff --git a/WindowsDriverSdk.sln b/WindowsDriverSdk.sln
new file mode 100644
index 0000000..d81d799
--- /dev/null
+++ b/WindowsDriverSdk.sln
@@ -0,0 +1,134 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.0.31903.59
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A810073A-39A0-452D-8019-63158FB238FE}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsDriver.Sdk", "src\WindowsDriver.Sdk\WindowsDriver.Sdk.csproj", "{969E6C50-38A0-449F-8D68-B62BBE75DF37}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsDriver.Interop", "src\WindowsDriver.Interop\WindowsDriver.Interop.csproj", "{FC733A26-63E8-4952-BFBA-8356C1121575}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsDriver.Testing", "src\WindowsDriver.Testing\WindowsDriver.Testing.csproj", "{893DF398-AEFB-42F1-84B9-78A6844ED4CA}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsDriver.InfGen", "src\WindowsDriver.InfGen\WindowsDriver.InfGen.csproj", "{57D34D4C-124D-4953-9614-1DFABF119D42}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsDriver.Templates", "src\WindowsDriver.Templates\WindowsDriver.Templates.csproj", "{F613BF5F-49CE-45A2-B231-E3BD3B170501}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{4E302CDA-8E52-4518-A334-0CBCD04554A1}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "VirtualAudio", "VirtualAudio", "{77CA5C77-3C76-43E0-9662-223C45A070E4}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VirtualAudio.Driver", "samples\VirtualAudio\Driver\VirtualAudio.Driver.csproj", "{674118DC-D57D-4EFF-BA1B-747531F17E3B}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VirtualAudio.Tests", "samples\VirtualAudio\Tests\VirtualAudio.Tests.csproj", "{308FEC2B-DF63-4AE7-9867-FB306D1EA775}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "HidGamepad", "HidGamepad", "{70431D5B-9E18-4E7C-8C9B-59CDBDC3FED6}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HidGamepad.Driver", "samples\HidGamepad\Driver\HidGamepad.Driver.csproj", "{299CBE98-C80A-47C1-AFA4-A91D42DCB466}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HidGamepad.Tests", "samples\HidGamepad\Tests\HidGamepad.Tests.csproj", "{0B4D3B1B-D55B-47E5-AFC9-B0366CB1ED46}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "VirtualSensor", "VirtualSensor", "{49E10DAF-450E-446B-9194-14515EE03E68}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VirtualSensor.Driver", "samples\VirtualSensor\Driver\VirtualSensor.Driver.csproj", "{ECD8F6E9-6155-4A62-B603-D0DA48E8F576}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VirtualSensor.Tests", "samples\VirtualSensor\Tests\VirtualSensor.Tests.csproj", "{9663B2A4-843F-4FED-8510-391CECA0CF8D}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "VirtualSerial", "VirtualSerial", "{9B930C30-F307-4709-B8FD-44611F346039}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VirtualSerial.Driver", "samples\VirtualSerial\Driver\VirtualSerial.Driver.csproj", "{A328D3B7-4FC2-4B59-AAA1-80159976F28C}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VirtualSerial.Tests", "samples\VirtualSerial\Tests\VirtualSerial.Tests.csproj", "{FE1C8833-749B-4B5F-8F39-BD0231462150}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{2B57AFF7-A86B-4B0E-9AFD-5ECDEF967628}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsDriver.Sdk.Tests", "tests\WindowsDriver.Sdk.Tests\WindowsDriver.Sdk.Tests.csproj", "{E026A82C-A4B1-40E9-96BB-223050295864}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {969E6C50-38A0-449F-8D68-B62BBE75DF37}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {969E6C50-38A0-449F-8D68-B62BBE75DF37}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {969E6C50-38A0-449F-8D68-B62BBE75DF37}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {969E6C50-38A0-449F-8D68-B62BBE75DF37}.Release|Any CPU.Build.0 = Release|Any CPU
+ {FC733A26-63E8-4952-BFBA-8356C1121575}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {FC733A26-63E8-4952-BFBA-8356C1121575}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {FC733A26-63E8-4952-BFBA-8356C1121575}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {FC733A26-63E8-4952-BFBA-8356C1121575}.Release|Any CPU.Build.0 = Release|Any CPU
+ {893DF398-AEFB-42F1-84B9-78A6844ED4CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {893DF398-AEFB-42F1-84B9-78A6844ED4CA}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {893DF398-AEFB-42F1-84B9-78A6844ED4CA}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {893DF398-AEFB-42F1-84B9-78A6844ED4CA}.Release|Any CPU.Build.0 = Release|Any CPU
+ {57D34D4C-124D-4953-9614-1DFABF119D42}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {57D34D4C-124D-4953-9614-1DFABF119D42}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {57D34D4C-124D-4953-9614-1DFABF119D42}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {57D34D4C-124D-4953-9614-1DFABF119D42}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F613BF5F-49CE-45A2-B231-E3BD3B170501}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F613BF5F-49CE-45A2-B231-E3BD3B170501}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F613BF5F-49CE-45A2-B231-E3BD3B170501}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F613BF5F-49CE-45A2-B231-E3BD3B170501}.Release|Any CPU.Build.0 = Release|Any CPU
+ {674118DC-D57D-4EFF-BA1B-747531F17E3B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {674118DC-D57D-4EFF-BA1B-747531F17E3B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {674118DC-D57D-4EFF-BA1B-747531F17E3B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {674118DC-D57D-4EFF-BA1B-747531F17E3B}.Release|Any CPU.Build.0 = Release|Any CPU
+ {308FEC2B-DF63-4AE7-9867-FB306D1EA775}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {308FEC2B-DF63-4AE7-9867-FB306D1EA775}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {308FEC2B-DF63-4AE7-9867-FB306D1EA775}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {308FEC2B-DF63-4AE7-9867-FB306D1EA775}.Release|Any CPU.Build.0 = Release|Any CPU
+ {299CBE98-C80A-47C1-AFA4-A91D42DCB466}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {299CBE98-C80A-47C1-AFA4-A91D42DCB466}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {299CBE98-C80A-47C1-AFA4-A91D42DCB466}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {299CBE98-C80A-47C1-AFA4-A91D42DCB466}.Release|Any CPU.Build.0 = Release|Any CPU
+ {0B4D3B1B-D55B-47E5-AFC9-B0366CB1ED46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {0B4D3B1B-D55B-47E5-AFC9-B0366CB1ED46}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {0B4D3B1B-D55B-47E5-AFC9-B0366CB1ED46}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {0B4D3B1B-D55B-47E5-AFC9-B0366CB1ED46}.Release|Any CPU.Build.0 = Release|Any CPU
+ {ECD8F6E9-6155-4A62-B603-D0DA48E8F576}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {ECD8F6E9-6155-4A62-B603-D0DA48E8F576}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {ECD8F6E9-6155-4A62-B603-D0DA48E8F576}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {ECD8F6E9-6155-4A62-B603-D0DA48E8F576}.Release|Any CPU.Build.0 = Release|Any CPU
+ {9663B2A4-843F-4FED-8510-391CECA0CF8D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {9663B2A4-843F-4FED-8510-391CECA0CF8D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {9663B2A4-843F-4FED-8510-391CECA0CF8D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {9663B2A4-843F-4FED-8510-391CECA0CF8D}.Release|Any CPU.Build.0 = Release|Any CPU
+ {A328D3B7-4FC2-4B59-AAA1-80159976F28C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {A328D3B7-4FC2-4B59-AAA1-80159976F28C}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {A328D3B7-4FC2-4B59-AAA1-80159976F28C}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {A328D3B7-4FC2-4B59-AAA1-80159976F28C}.Release|Any CPU.Build.0 = Release|Any CPU
+ {FE1C8833-749B-4B5F-8F39-BD0231462150}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {FE1C8833-749B-4B5F-8F39-BD0231462150}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {FE1C8833-749B-4B5F-8F39-BD0231462150}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {FE1C8833-749B-4B5F-8F39-BD0231462150}.Release|Any CPU.Build.0 = Release|Any CPU
+ {E026A82C-A4B1-40E9-96BB-223050295864}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {E026A82C-A4B1-40E9-96BB-223050295864}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {E026A82C-A4B1-40E9-96BB-223050295864}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {E026A82C-A4B1-40E9-96BB-223050295864}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(NestedProjects) = preSolution
+ {969E6C50-38A0-449F-8D68-B62BBE75DF37} = {A810073A-39A0-452D-8019-63158FB238FE}
+ {FC733A26-63E8-4952-BFBA-8356C1121575} = {A810073A-39A0-452D-8019-63158FB238FE}
+ {893DF398-AEFB-42F1-84B9-78A6844ED4CA} = {A810073A-39A0-452D-8019-63158FB238FE}
+ {57D34D4C-124D-4953-9614-1DFABF119D42} = {A810073A-39A0-452D-8019-63158FB238FE}
+ {F613BF5F-49CE-45A2-B231-E3BD3B170501} = {A810073A-39A0-452D-8019-63158FB238FE}
+ {77CA5C77-3C76-43E0-9662-223C45A070E4} = {4E302CDA-8E52-4518-A334-0CBCD04554A1}
+ {674118DC-D57D-4EFF-BA1B-747531F17E3B} = {77CA5C77-3C76-43E0-9662-223C45A070E4}
+ {308FEC2B-DF63-4AE7-9867-FB306D1EA775} = {77CA5C77-3C76-43E0-9662-223C45A070E4}
+ {70431D5B-9E18-4E7C-8C9B-59CDBDC3FED6} = {4E302CDA-8E52-4518-A334-0CBCD04554A1}
+ {299CBE98-C80A-47C1-AFA4-A91D42DCB466} = {70431D5B-9E18-4E7C-8C9B-59CDBDC3FED6}
+ {0B4D3B1B-D55B-47E5-AFC9-B0366CB1ED46} = {70431D5B-9E18-4E7C-8C9B-59CDBDC3FED6}
+ {49E10DAF-450E-446B-9194-14515EE03E68} = {4E302CDA-8E52-4518-A334-0CBCD04554A1}
+ {ECD8F6E9-6155-4A62-B603-D0DA48E8F576} = {49E10DAF-450E-446B-9194-14515EE03E68}
+ {9663B2A4-843F-4FED-8510-391CECA0CF8D} = {49E10DAF-450E-446B-9194-14515EE03E68}
+ {9B930C30-F307-4709-B8FD-44611F346039} = {4E302CDA-8E52-4518-A334-0CBCD04554A1}
+ {A328D3B7-4FC2-4B59-AAA1-80159976F28C} = {9B930C30-F307-4709-B8FD-44611F346039}
+ {FE1C8833-749B-4B5F-8F39-BD0231462150} = {9B930C30-F307-4709-B8FD-44611F346039}
+ {E026A82C-A4B1-40E9-96BB-223050295864} = {2B57AFF7-A86B-4B0E-9AFD-5ECDEF967628}
+ EndGlobalSection
+EndGlobal
diff --git a/build.ps1 b/build.ps1
new file mode 100644
index 0000000..60d3bc4
--- /dev/null
+++ b/build.ps1
@@ -0,0 +1,28 @@
+# Build, test and pack the Windows Driver SDK.
+# Usage: .\build.ps1 [-Configuration Release]
+[CmdletBinding()]
+param(
+ [string]$Configuration = "Debug"
+)
+
+$ErrorActionPreference = 'Stop'
+Set-Location $PSScriptRoot
+
+Write-Host "== restore ==" -ForegroundColor Cyan
+dotnet restore
+
+Write-Host "== build ($Configuration) ==" -ForegroundColor Cyan
+dotnet build --no-restore -c $Configuration
+
+Write-Host "== test ==" -ForegroundColor Cyan
+dotnet test --no-build -c $Configuration
+
+Write-Host "== pack ==" -ForegroundColor Cyan
+dotnet pack --no-build -c $Configuration -o artifacts/
+
+Write-Host "== infgen smoke test ==" -ForegroundColor Cyan
+dotnet tool install --prerelease --tool-path ./tools-out --add-source ./artifacts WindowsDriver.InfGen 2>$null
+./tools-out/infgen generate --manifest samples/VirtualAudio/manifest.json --out $env:TEMP\virtualaudio.inf
+./tools-out/infgen validate --inf $env:TEMP\virtualaudio.inf
+
+Write-Host "Done. Packages are in ./artifacts/" -ForegroundColor Green
diff --git a/build.sh b/build.sh
new file mode 100644
index 0000000..8e520df
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+# Build, test and pack the Windows Driver SDK (cross-platform parts).
+# Usage: ./build.sh [Debug|Release]
+set -euo pipefail
+
+CONFIG="${1:-Debug}"
+cd "$(dirname "$0")"
+
+echo "== restore =="
+dotnet restore
+
+echo "== build ($CONFIG) =="
+dotnet build --no-restore -c "$CONFIG"
+
+echo "== test =="
+dotnet test --no-build -c "$CONFIG"
+
+echo "== pack =="
+dotnet pack --no-build -c "$CONFIG" -o artifacts/
+
+echo "== infgen smoke test =="
+dotnet tool install --prerelease --tool-path ./tools-out --add-source ./artifacts WindowsDriver.InfGen >/dev/null || true
+./tools-out/infgen generate --manifest samples/VirtualAudio/manifest.json --out /tmp/virtualaudio.inf
+./tools-out/infgen validate --inf /tmp/virtualaudio.inf
+
+echo "Done. Packages are in ./artifacts/"
diff --git a/docs/api-reference.md b/docs/api-reference.md
new file mode 100644
index 0000000..f86e210
--- /dev/null
+++ b/docs/api-reference.md
@@ -0,0 +1,146 @@
+# API reference
+
+A type-by-type map of the SDK surface. Namespaces: `WindowsDriver.Sdk` (core),
+`WindowsDriver.Sdk.Audio/Hid/Sensor/Serial` (modules),
+`WindowsDriver.Interop.Umdf/Kmdf/Win32`, `WindowsDriver.Testing`,
+`WindowsDriver.InfGen` (tool).
+
+## Core runtime (`WindowsDriver.Sdk`)
+
+### Lifecycle
+
+| Type | Member | Notes |
+| --- | --- | --- |
+| `IDriver` | `OnDriverEntryAsync(DriverContext, ct)` | first callback |
+| | `OnDeviceAddAsync(DeviceAddContext, DeviceContext, ct) → DeviceBase` | per device |
+| | `OnDriverUnloadAsync()` | last callback |
+| `DriverBase` | abstract base, `CreateDevice(deviceContext)` helper | no-op entry/unload |
+| `DriverContext` | `Log`, `Registry`, `TimeProvider`, `DriverServiceName`, `DriverProperties` | created by the host |
+| `DeviceBase` | `Context`, `DefaultQueue`, `CreateQueue(options)`, `IsD0`, `IsHardwarePrepared` | override `OnPrepareHardwareAsync`, `OnD0EntryAsync/OnD0ExitAsync`, `OnReleaseHardwareAsync`, `OnQueryRemoveAsync`, `OnSurpriseRemovalAsync` |
+| `DriverHost` | `StartAsync()`, `AddDeviceAsync(addContext)`, `RemoveDeviceAsync`, `SurpriseRemoveDeviceAsync`, `ShutdownAsync` | the WDF order, with rollback |
+| `DeviceAddContext` | `DeviceInstanceId`, `HardwareIds`, `CompatibleIds`, `Properties`, `IsRawDevice` | bus-reported identity |
+| `DeviceContext` | `DeviceInstanceId`, `HardwareIds`, `Properties`, `Log`, `CreateDeviceInterface(guid, ref?)` | per device, host-created |
+| `DevicePowerState` | `Unspecified, D0..D3` | WDM values |
+
+### IO
+
+| Type | Member | Notes |
+| --- | --- | --- |
+| `IoRequest` | `Kind`, `IoControlCode`, `InputBuffer`, `OutputBuffer`, `Complete(status, bytes)`, `Fail(status)` | complete exactly once; write counts = input bytes |
+| `IoResult` | `Status`, `BytesTransferred`, `Output`, `IsSuccess` | snapshot from the test host |
+| `IoQueue` | `OnDeviceControl/OnRead/OnWrite(handler)`, `Submit`, `ManualRequests`, `DrainAsync`, `StopAsync` | dispatch via options |
+| `IoQueueOptions` | `Dispatch` (Sequential/Parallel/Manual), `Name` | |
+| `QueueHandlers` | `DeviceControl`, `Read`, `Write` — `Func` | unregistered → `InvalidDeviceRequest` |
+
+### Status and encoding
+
+| Type | Notes |
+| --- | --- |
+| `NtStatus` | Success, Pending, Timeout, BufferOverflow, Unsuccessful, NoSuchDevice, InvalidParameter, EndOfFile, InvalidDeviceRequest, AccessDenied, BufferTooSmall, ObjectNameNotFound, Cancelled, DeviceNotReady, IoTimeout, NotSupported, InvalidDeviceState |
+| `NtStatusExtensions` | `IsSuccess` (NT_SUCCESS semantics: < 0x80000000), `IsInformational`, `IsWarning`, `IsError`, `Severity`, `ToHexString` |
+| `WinIoctl` | `CtlCode` (exact C-macro layout), `VendorControlCode` (enforces ≥ 0x800), `DeviceType/Function/Method/AccessFromControl`, `FileDevice*` constants, `Method*`, `FileAccess*` |
+| `WireFormat` | little-endian `Read/Write` for i16/u16/i32/u32/i64/u64/f32/f64 with `BufferTooSmall` bounds checks |
+| `DriverException` | carries `Status`; `InvalidRequestException` = InvalidDeviceRequest |
+
+### Environment
+
+| Type | Notes |
+| --- | --- |
+| `IDriverLog` | `IsEnabled(level)`, `Log(level, message)`; extensions `Trace/Info/Warning/Error(fmt, args)` |
+| implementations | `ConsoleDriverLog`, `FileDriverLog`, `CompositeDriverLog`, `ScopedDriverLog` (prefix), `NullDriverLog` |
+| `IDriverRegistry` | `ReadString/ReadDword/WriteString/WriteDword/DeleteValue` — the service `Parameters` key |
+| `MemoryRegistry` | in-memory implementation (extendable) |
+| `PropertyStore` | typed string-keyed store (`GetString/GetDword/GetBool/GetGuid/Set/Remove`) |
+| `KnownDeviceProperties` | FriendlyName, Manufacturer, DeviceDescription, DriverVersion, InterfaceClassGuid |
+| `ByteRingBuffer` | `Write`, `Read`, `Skip`, `Clear`, `Count`, `FreeSpace`, `DroppedBytes`, `TotalBytesWritten/Read` |
+
+## Audio (`WindowsDriver.Sdk.Audio`)
+
+| Type | Notes |
+| --- | --- |
+| `PcmFormat` | record (rate, bits, channels); `BytesPerFrame`, `BytesPerSecond` |
+| `AudioFormatNegotiator` | `Negotiate(requested) → AudioNegotiationResult` (accepted format or InvalidParameter) |
+| `AudioDeviceStateMachine` | `Start/Pause/Stop`, `Snapshot`, `Transitioned` event; invalid → InvalidDeviceState |
+| `VolumeState` | `SetMasterGain(target, ramp)`, `SetMute`, `SetChannelGain`, `CurrentGain`, `CurrentGainDecibels`, `RampRemaining` |
+| `AudioIoctlCodes` | GetSupportedFormats, SetFormat, GetFormat, Start, Stop, Pause, GetPosition, SetVolume, GetVolume, SkipOutput |
+| `VirtualAudioDevice` | composes all of it; options: `Mode` (Capture/Render/Loopback), `Source`, `Sink`, `RingBufferBytes`, `SupportedFormats`, `ApplyVolumeToOutput` |
+| `SineSource` | frequency/amplitude generator (mutable frequency) |
+| `IAudioSource` / `IAudioSink` | `FillFrames(span, format)` / `WriteFrames(span, format)` |
+| `PcmVolume` | `ApplyMasterGain16(span, gain)` — 16-bit in-place scaling |
+| `PcmWavWriter` | `IAudioSink` writing a RIFF/WAVE stream; `WriteTrailer()` patches sizes |
+
+## HID (`WindowsDriver.Sdk.Hid`)
+
+| Type | Notes |
+| --- | --- |
+| `HidReportDescriptorBuilder` | fluent items (UsagePage, Usage, Logical*, ReportId/Size/Count, Input/Output/Feature, Collection), conveniences `Buttons`, `Axis`, `PaddingInput`, `ToBytes` |
+| `HidReportDescriptorParser` | `Parse(bytes) → HidDescriptorSummary` (reports, fields, depth, UsesReportIds) |
+| `HidDescriptor` | `Build(reportDescriptor, bcdHid, country)` — 9-byte class descriptor |
+| `HidDescriptors` | `GamepadSixAxisTwelveButtons()` — canonical descriptor |
+| `GamepadState` | buttons 1..12 (indexer), X/Y/Z/Rx/Ry/Rz int16 |
+| `GamepadInputReport` | `Pack/Unpack`, `ReportId = 1`, `ReportSizeBytes = 15` |
+| `HidDevice` | IOCTL contract (`HidIoctlCodes`), `InputReportFactory`, feature echo |
+| enums | `HidUsagePage`, `GenericDesktopUsage`, `HidCollectionType`, `HidMainItemFlags` |
+
+## Sensor (`WindowsDriver.Sdk.Sensor`)
+
+| Type | Notes |
+| --- | --- |
+| `ISensorSource` | `Kind`, `Unit`, `ValueCount`, `SampleRateHz`, `Sample(timestamp)` |
+| `AccelerometerSimulator` | gravity + seeded noise + `AddImpulse(at, duration, accel)` |
+| `AmbientLightSimulator` | day curve + flicker + `OverrideLux` |
+| `SensorReading` | (kind, timestamp, values, unit) |
+| `SensorDevice` | `SampleOnce`, `LatestReading(i)`, `Readings` channel, background loop on D0 |
+| `SensorIoctlCodes` | GetSensorCount, GetSensorInfo, GetLatestReading, SetSampleRate |
+
+## Serial (`WindowsDriver.Sdk.Serial`)
+
+| Type | Notes |
+| --- | --- |
+| `SerialLineConfig` | record + `Validate()` (UART rules) + `ReadFrom/WriteTo` (8-byte wire) |
+| `SerialDevice` | queues (`RxQueue/TxQueue`), `ApplyConfig`, `InjectReceive`, `Transmit`, `AssertBreak`, `InjectFramingError`, `Cts/Dsr/BreakActive` |
+| `SerialLoopbackPair` | cross-connects two non-loopback ports |
+| `SerialIoctlCodes` | GetLineConfig, SetLineConfig, Transmit, Purge, GetStatus, GetRxCount |
+| enums | `SerialParity`, `SerialStopBits`, `SerialFlowControl` |
+
+## Interop (`WindowsDriver.Interop.*`)
+
+| Type | Notes |
+| --- | --- |
+| `Umdf.ShimHeader` (`UmdfShimContract.ShimHeader`) | the C ABI header (single source of truth) |
+| `Umdf.ManagedDriverBootstrap` | `WdsInitialize/WdsDeviceAdd/WdsQueueRequest/WdsDeviceD0Entry/WdsDeviceD0Exit/WdsDeviceRelease/WdsDriverUnload` — `[UnmanagedCallersOnly]` |
+| `Umdf.UmdfShimSettings` | function pointers + names (5 pointers, `WireSize = 5 × IntPtr.Size`) |
+| `Umdf.IWdf*` interfaces | documentation contracts mirroring wudfddi.h callbacks (no fake COM IIDs) |
+| `Kmdf.KmdfShimProtocol` | Ping/GetVersion/SendCommand/ReadEvents/AcknowledgeEvents + `Magic` ("WSHI") |
+| `Kmdf.KmdfCommandHeader/KmdfResultHeader/KmdfEventRecord` | packed wire structs (8/8/16 bytes) |
+| `Kmdf.KmdfControlPlane` | `Open`, `Ping`, `GetVersion`, `SendCommand`, `ReadEvents` over real Win32 IOCTLs |
+| `Win32.Win32Native` | `CreateFileW`, `DeviceIoControl`, `SendIoctl` helper |
+
+## Testing (`WindowsDriver.Testing`)
+
+| Type | Notes |
+| --- | --- |
+| `TestDriverHost` | wraps `DriverHost` + captured log + fake registry + fake clock; `StartAsync`, `AddDeviceAsync`, `ShutdownAsync` |
+| `TestDriverHostBuilder` | `UseFakeTime(start?)`, `UseRealTime()`, `WithRegistry`, `WithLogMinimum` |
+| `TestDevice` | `SendIoctlAsync(code, input?, outputSize?)`, `ReadAsync`, `WriteAsync` (5 s timeout default), exposes `Device`/`Context`/`DefaultQueue` |
+| `FakeTimeProvider` | `Advance(delta)`, `AdvanceTo(when)`; timers fire synchronously, no backwards time |
+| `CapturedLog` | `Messages`, `Entries`, `Contains`, `ContainsError`, `Clear` |
+| `FakeRegistry` | seedable in-memory registry |
+| `Check` | `Status`, `Success`, `Bytes` — framework-agnostic asserts |
+| `TestSync` | `WaitUntilAsync(condition, timeout)` polling helper |
+
+## InfGen (`WindowsDriver.InfGen`)
+
+| Type | Notes |
+| --- | --- |
+| `Program` (`infgen`) | `generate --manifest x.json [--out] [--arch]`, `validate --inf f.inf`, `schema` |
+| `DriverManifest` | JSON manifest record + `Validate`; camelCase + comments tolerated |
+| `InfGenerator` | `Generate(manifest, archs?)`; `NormalizeGuid`; `SdkVersion` |
+| `InfValidator` | `Validate(text) → InfIssue[]`; required sections, GUIDs, DriverVer, duplicates, model refs, string keys |
+| `DriverFile` / `DriverModel` | manifest sub-records |
+
+## Versioning
+
+`Directory.Build.props` holds the single `` (currently
+`0.1.0-preview.1`) applied to all packages; `global.json` pins the .NET SDK
+(8.0.x, latestFeature).
diff --git a/docs/architecture.md b/docs/architecture.md
new file mode 100644
index 0000000..17a8b8e
--- /dev/null
+++ b/docs/architecture.md
@@ -0,0 +1,141 @@
+# Architecture
+
+## The problem being solved
+
+Windows drivers must ultimately be native code: kernel-mode drivers are C (the
+CLR cannot run at IRQL), and UMDF drivers are COM classes created by
+`WUDFHost.exe`. At the same time, most of what a modern device driver *does* —
+protocol parsing, state machines, buffering, throttling, configuration — is
+plain application logic that iterates fastest in a managed language with
+modern tooling and tests.
+
+The Windows Driver SDK resolves this with a **managed-host architecture**: all
+device logic lives in .NET 8 behind framework-shaped abstractions, and thin
+native components exist only where the OS requires them.
+
+## Layering
+
+```
+┌─────────────────────────────────────────────────────────────────────┐
+│ Driver project (yours) │
+│ IDriver / DriverBase + DeviceBase subclass │
+├─────────────────────────────────────────────────────────────────────┤
+│ WindowsDriver.Sdk (managed) │
+│ Runtime DriverHost · DeviceBase · IoQueue · IoRequest │
+│ NtStatus · WinIoctl · WireFormat · logging/registry │
+│ Modules Audio (VirtualAudioDevice) · HID (HidDevice) │
+│ Sensor (SensorDevice) · Serial (SerialDevice) │
+├─────────────────────────────────────────────────────────────────────┤
+│ Hosting (one of three, same lifecycle) │
+│ 1. WindowsDriver.Testing.TestDriverHost — in-memory, any OS │
+│ 2. UMDF shim (C++/COM in WUDFHost) — user-mode, Windows │
+│ 3. KMDF control plane over C shim (.sys) — kernel reach │
+├─────────────────────────────────────────────────────────────────────┤
+│ WindowsDriver.Interop (managed) │
+│ UmdfShimContract + ManagedDriverBootstrap (hostfxr entry points) │
+│ KmdfControlPlane (CreateFile/DeviceIoControl client) │
+│ Win32Native P/Invoke declarations │
+└─────────────────────────────────────────────────────────────────────┘
+```
+
+The layering rule is strict: the SDK core has **no** dependency on Windows —
+`WindowsDriver.Sdk.dll` runs on Linux, which is why the entire test suite does.
+Only `WindowsDriver.Interop` touches Win32, and only its KMDF client actually
+calls it at runtime.
+
+## One lifecycle, three hosts
+
+The WDF callback order is encoded once, in `DriverHost`:
+
+```
+DriverEntry → (AddDevice → PrepareHardware → D0Entry)* → DriverUnload
+```
+
+`DriverHost.StartAsync` loads your `IDriver` type; `DriverHost.AddDeviceAsync`
+runs add + power-up and rolls back cleanly on failure
+(D0Exit → StopQueues → ReleaseHardware); `DriverHost.ShutdownAsync` runs the
+mirror image. All three hosting paths call exactly this class:
+
+| Host | What it provides | Call-site |
+| --- | --- | --- |
+| `TestDriverHost` (Testing) | fake clock, fake registry, captured log, in-memory device bus | tests, CI on any OS |
+| UMDF shim | the real `IWDF*` COM objects, real buffers from `WdfRequest*`, ETW logging | production, user-mode |
+| KMDF shim + control plane | kernel device object, event ring, buffered IOCTLs | production, kernel reach |
+
+This is the central testing guarantee: **the orchestration you test is the
+orchestration you deploy.** Only the leaf calls (where bytes come from and
+where they go) differ per host.
+
+## IO model
+
+`IoQueue` mirrors the WDF queue dispatch modes:
+
+| SDK | WDF equivalent | Semantics |
+| --- | --- | --- |
+| `QueueDispatchMode.Sequential` | `WdfIoQueueDispatchSequential` | one request at a time, in order |
+| `QueueDispatchMode.Parallel` | `WdfIoQueueDispatchParallel` | concurrent handlers |
+| `QueueDispatchMode.Manual` | `WdfIoQueueDispatchManual` | driver pulls from `ManualRequests` channel |
+
+`IoRequest` carries kind (DeviceControl/Read/Write), the IOCTL code, input and
+output buffers, and is completed exactly once with an NTSTATUS and an
+information count. Completion semantics match
+`WdfRequestCompleteWithInformation` — for writes the count is input bytes, for
+everything else output bytes.
+
+Handlers are plain `Func`; the queue
+translates `DriverException.Status` and unhandled exceptions into completion
+statuses, so a driver bug degrades to a clean request failure instead of a
+crashed host.
+
+## Time is an abstraction
+
+Every time-dependent behavior (audio positions, sensor sampling loops, volume
+ramps) takes the host's `System.TimeProvider` (introduced as a first-class API
+in .NET 8). Production hosts inject `TimeProvider.System`; tests inject
+`FakeTimeProvider` and *advance* time, which fires timers synchronously and
+deterministically. This removes the largest source of flaky driver tests —
+wall-clock races.
+
+## IOCTL conventions
+
+- Custom IOCTLs use `WinIoctl.VendorControlCode(function, access, deviceType)`
+ which enforces the vendor function range (≥ 0x800) and produces the exact
+ `CTL_CODE` C-macro bit layout — the same value a C driver would emit and a
+ Win32 `DeviceIoControl` caller would pass.
+- Payloads are little-endian and written with `WireFormat`, which bounds-checks
+ every access and throws `STATUS_BUFFER_TOO_SMALL` on short buffers.
+- Every module ships a documented contract (`AudioIoctlCodes`,
+ `HidIoctlCodes`, `SensorIoctlCodes`, `SerialIoctlCodes`) — stable, testable,
+ and shared verbatim with the KMDF shim headers.
+
+## What stays native, and why
+
+| Component | Language | Reason |
+| --- | --- | --- |
+| UMDF COM activation (`WUDFHost` calls your driver's `DllGetClassObject`) | C++ | OS contract is COM |
+| Kernel-mode driver objects (`WdfDeviceCreate`, IRQL, DMA) | C | CLR cannot run in kernel |
+| Everything else | C# | testability, iteration speed, tooling |
+
+The shims are deliberately small: the UMDF shim is callback forwarding plus a
+`hostfxr` bootstrap (~a few hundred lines); the KMDF shim implements one IOCTL
+protocol (`shim/WdsKmdfShim/`, compiling skeleton included). Both ABIs are
+frozen in `WindowsDriver.Interop` so the two sides cannot drift apart silently.
+
+## Comparison with other approaches
+
+| Approach | Managed logic | Kernel reach | Testability | Notes |
+| --- | --- | --- | --- | --- |
+| **This SDK** | full | via control-plane shim | in-memory, deterministic | open source |
+| WDK C/C++ directly | none | full | HLK-based | the Microsoft-supported path |
+| Commercial driver kits (e.g. Jungo WinDriver .NET) | partial | via proprietary kernel agent | proprietary | commercial licensing |
+| .NET NativeAOT driver experiments | full | none today | — | no kernel CLR story |
+
+## Known limits (design honesty)
+
+- The UMDF C++/COM shim is specified but not shipped compiled — it needs a WDK
+ environment and your CLSIDs (see `shim/UmdfShim/README.md`).
+- Kernel callbacks that must run at device IRQ levels stay in C; the C# control
+ plane talks to them over the shim protocol.
+- Buffered IOCTLs only (`METHOD_BUFFERED`) in the SDK contracts; direct/
+ neither methods are reachable through `WinIoctl.CtlCode` but the shims do not
+ map them yet.
diff --git a/docs/audio-guide.md b/docs/audio-guide.md
new file mode 100644
index 0000000..9b017de
--- /dev/null
+++ b/docs/audio-guide.md
@@ -0,0 +1,114 @@
+# Audio guide
+
+The audio module (`WindowsDriver.Sdk.Audio`) gives you everything a virtual
+audio device needs minus the OS glue: PCM format negotiation, a hardware-like
+ring buffer, a start/pause/stop state machine, volume with ramps, a position
+clock, and the IOCTL contract. `VirtualAudioDevice` composes all of it; the
+VirtualAudio sample adds one custom IOCTL pair on top.
+
+## Core types
+
+| Type | Role |
+| --- | --- |
+| `PcmFormat(SampleRateHz, BitsPerSample, Channels)` | interleaved little-endian PCM format |
+| `AudioFormatNegotiator` | picks the closest supported format for a request |
+| `AudioDeviceStateMachine` | Stopped/Paused/Running with WDF-style transitions |
+| `VolumeState` | master + per-channel gains, mute, linear ramps, dB conversion |
+| `ByteRingBuffer` | thread-safe FIFO with drop counting (the "DMA buffer") |
+| `SineSource` / `IAudioSource` | produces frames while running |
+| `IAudioSink` / `PcmWavWriter` | consumes frames (WAV capture for tests/demos) |
+| `VirtualAudioDevice : DeviceBase` | the composed device |
+
+## The IOCTL contract
+
+`AudioIoctlCodes` defines ten vendor IOCTLs on `FILE_DEVICE_SOUND`
+(functions ≥ 0x800, all METHOD_BUFFERED). The documented payload layouts:
+
+- **GetSupportedFormats** — out: u32 count, then count × (u32 rate, u32 bits, u32 channels).
+- **SetFormat** — in: the same triple. Accepted only while Stopped
+ (`STATUS_INVALID_DEVICE_STATE` otherwise). If the request is not exactly
+ supported, the negotiator picks the closest format and *succeeds* with the
+ accepted format in the output — the caller reads it back rather than
+ guessing. (Returning a warning status here would make the Win32 call fail;
+ warnings are not success from `DeviceIoControl`'s perspective.)
+- **Start / Pause / Stop** — state machine transitions; invalid transitions
+ fail with `STATUS_INVALID_DEVICE_STATE`, transitions are idempotent.
+- **GetPosition** — out: (u64 bytePosition, u64 framePosition, u32 state).
+- **SetVolume** — in: (f32 master 0..1, u8 mute, u32 rampMs, u32 channelCount,
+ channelCount × f32). Channel 0 means master-only.
+- **GetVolume** — out: target, current (post-ramp), mute, remaining ramp ms,
+ channel count, per-channel gains.
+- **SkipOutput** — in: u32 bytes to drop from the ring (clients that fall
+ behind use this instead of reading stale audio).
+
+## How the clock works
+
+A real audio device advances its position with hardware time. The SDK's
+`VirtualAudioDevice` advances *logically*: while `Running`, the number of
+frames owed equals `(now − startTime − pausedTime) × sampleRate`, computed
+from the host's `TimeProvider` and lazily materialized into the ring buffer on
+the next Read/Write/GetPosition call. Consequences:
+
+- Time is exact — advance the fake clock 1 s in a test and `GetPosition`
+ reports exactly `sampleRate` frames.
+- No background thread needed in tests; in production the UMDF/KMDF host can
+ drive the pump from a real timer or interrupt-equivalent.
+- Overrun drops are counted (`ByteRingBuffer.DroppedBytes`) rather than
+ silently corrupting the stream, mirroring real DMA underrun/overrun
+ behavior.
+
+## Writing your own device
+
+```csharp
+public sealed class MyAudioDevice : VirtualAudioDevice
+{
+ public MyAudioDevice(DeviceContext context)
+ : base(context, new AudioVirtualOptions
+ {
+ Mode = AudioVirtualMode.Capture, // or Render / Loopback
+ Source = new SineSource(1000.0, 0.3),
+ RingBufferBytes = 1_000_000, // ~5 s of 48 kHz stereo
+ SupportedFormats = [ new(48000, 16, 2), new(48000, 24, 2) ],
+ })
+ {
+ }
+
+ protected override Task HandleDeviceControlAsync(IoRequest request, CancellationToken ct)
+ {
+ // handle your IOCTLs, then:
+ return base.HandleDeviceControlAsync(request, ct);
+ }
+}
+```
+
+Modes:
+
+- **Capture** — the `IAudioSource` fills the ring; clients `Read` frames
+ (microphone-style).
+- **Render** — clients `Write` frames; the `IAudioSink` consumes them
+ (speaker-style; `PcmWavWriter` is a convenient sink).
+- **Loopback** — writes come back on the next read (test harness).
+
+## Applying volume
+
+`PcmVolume.ApplyMasterGain16` scales interleaved 16-bit samples in place with
+clamping; `VirtualAudioDevice` applies the current gain (ramp included, mute
+forces zero) on the device's output path when `AudioVirtualOptions.ApplyVolumeToOutput`
+is true (the default). The volume test in the sample asserts the halved peak
+and the silent mute case numerically.
+
+## Integration with the Windows audio stack
+
+Where does this plug in on a real system?
+
+| Path | What it is | Use when |
+| --- | --- | --- |
+| UMDF driver + your client | the SDK contract as-is; your client app opens the device interface and exchanges PCM | custom audio pipelines, virtual devices for your own app |
+| UMDF HID-style mini-driver | n/a for audio | — |
+| KMDF/AVStream miniport | native; the kernel side implements a miniport (PortCls) and can call the shim protocol for policy | real audio endpoints other apps must see (WaveOut/WASAPI) |
+| Audio Processing Object (APO) | user-mode COM in the audio engine; conceptually C#-hostable through the same COM-shim approach | DSP effects in the system pipeline |
+
+The most practical first step is a virtual endpoint paired with a client
+service; moving to system-visible endpoints means the AVStream/PortCls
+miniport in C with the SDK's control plane handling everything above the
+DDI boundary.
diff --git a/docs/ci-cd.md b/docs/ci-cd.md
new file mode 100644
index 0000000..271bd29
--- /dev/null
+++ b/docs/ci-cd.md
@@ -0,0 +1,78 @@
+# CI/CD guide
+
+The repository ships a working GitHub Actions workflow (`.github/workflows/ci.yml`)
+with two jobs, plus `build.sh` / `build.ps1` for local use.
+
+## What runs on every push/PR
+
+**Job 1 — `logic` (ubuntu-latest)**
+
+1. `actions/setup-dotnet@v4` with .NET 8.0.x.
+2. `dotnet restore` → `dotnet build -c Release` → `dotnet test -c Release`
+ — all 62 tests (SDK core, interop contracts, InfGen, four samples) pass on
+ Linux in under a second; no Windows or WDK needed.
+3. `dotnet pack -c Release -o artifacts/` — the five SDK packages plus the
+ four sample packages.
+4. **InfGen smoke test** — install the packed tool from the local artifacts
+ feed (`--prerelease --add-source ./artifacts`), generate the VirtualAudio
+ INF from its manifest, and lint it. This proves the tool package and the
+ manifest→INF pipeline in one step.
+5. **Template smoke test** — `dotnet new install` the packed templates
+ package, instantiate `driver-solution` as a new project, wire the sln,
+ restore against the artifacts feed + nuget.org, and run the generated
+ project's tests. This is an end-to-end proof that the published packages
+ are consumable by a fresh project.
+6. Upload `artifacts/*.nupkg` as a workflow artifact.
+
+**Job 2 — `windows` (windows-latest)**
+
+Build + test on Windows to catch any OS-specific compile issue. It stops
+there, on purpose:
+
+> GitHub-hosted Windows runners do not ship the WDK, so the native KMDF shim,
+> InfVerif, Inf2Cat and signtool cannot run in public CI. Run those steps on a
+> private runner with the WDK installed, or locally (see below).
+
+## Local pipeline (the parts CI can't do)
+
+```powershell
+# On a machine with VS + WDK:
+.\build.ps1 -Configuration Release # managed: build, test, pack
+
+# Native shim (KMDF):
+# open shim/WdsKmdfShim in VS → build x64/arm64
+
+# Package validation:
+InfVerif /drive: . # INF rule check
+Inf2Cat /driver:. /os:10_X64 # catalog
+signtool sign /fd SHA256 /a /f test.pfx .\WdsKmdfShim.cat
+
+# Deploy into a VM and drive it:
+.\tools\Install-Driver.ps1 -InfPath .\WdsKmdfShim.inf -CertPath .\test.cer
+```
+
+## Suggested repo setup for teams
+
+1. **Branch protection** — require the `logic` job to pass; it gates every
+ behavioral change in the driver logic.
+2. **Private WDK runner** — one machine or VM with VS + WDK + HLK for the
+ native/signing stages; trigger it with `workflow_dispatch` or
+ `repository_dispatch` from the same pipeline.
+3. **Package feed** — push `artifacts/*.nupkg` to a private Azure Artifacts /
+ GitHub Packages feed; drivers consume `WindowsDriver.Sdk` etc. with
+ `--prerelease` until you ship a stable version.
+4. **Versioning** — the SDK version lives in `Directory.Build.props` (single
+ source); bump it and the template's default `sdkVersion` symbol together
+ when packaging.
+5. **Determinism** — the tests never touch wall-clock time (the fake clock
+ starts at a fixed date); do not add real-time waits, or CI becomes flaky.
+
+## Security notes
+
+- CI uses no secrets; signing happens on the private runner (or never, for
+ test-signed development).
+- The InfGen/template smoke tests download only from your artifacts folder and
+ nuget.org; add package pinning (`global.json` pins the SDK already) if your
+ threat model needs it.
+- Kernel packages are machine-impacting: test them in VMs with snapshots, not
+ on the build host.
diff --git a/docs/getting-started.md b/docs/getting-started.md
new file mode 100644
index 0000000..11eb492
--- /dev/null
+++ b/docs/getting-started.md
@@ -0,0 +1,182 @@
+# Getting started
+
+This guide takes you from an empty folder to a running, tested, deployable
+driver. Everything except the final deployment steps works on any OS — Linux
+and macOS are fine for development because the test host runs the driver logic
+in memory.
+
+## 1. Prerequisites
+
+| Component | Needed for | Where |
+| --- | --- | --- |
+| .NET 8 SDK (8.0.4xx+) | everything | [dotnet.microsoft.com](https://dotnet.microsoft.com/download/dotnet/8.0) |
+| Windows 10/11 x64 or ARM64 | deploying drivers | — |
+| WDK (matching your VS version) | building the native shims, InfVerif, signing | [learn.microsoft.com/windows-hardware/drivers/download-the-wdk](https://learn.microsoft.com/windows-hardware/drivers/download-the-wdk) |
+| Visual Studio 2022/2026 (or the EWDK) | building `shim/WdsKmdfShim` | — |
+
+You do **not** need Windows for development: the `TestDriverHost` runs driver
+logic in-process with a controllable clock, which is where you will spend most
+of your iteration time.
+
+## 2. Get the packages
+
+The SDK is distributed as five NuGet packages (see the repository `artifacts/`
+folder, or your private feed):
+
+```bash
+dotnet new install WindowsDriver.Templates --prerelease
+dotnet tool install --prerelease --tool-path ./.tools WindowsDriver.InfGen
+```
+
+When building from this repository, point `--add-source` at the local
+`artifacts/` folder:
+
+```bash
+./build.sh # restores, builds, tests and packs everything
+dotnet new install ./artifacts/WindowsDriver.Templates.0.1.0-preview.1.nupkg
+```
+
+## 3. Create your first driver
+
+```bash
+dotnet new driver-solution -n ContosoButton
+cd ContosoButton
+dotnet new sln -n ContosoButton
+dotnet sln add ContosoButton/ContosoButton.csproj ContosoButton.Tests/ContosoButton.Tests.csproj
+dotnet test
+```
+
+The template produces:
+
+- `ContosoButton/ContosoButton.cs` — the driver: an `IDriver` implementation
+ (`DriverBase` base class) and a `DeviceBase` subclass with an IOCTL
+ dispatcher.
+- `ContosoButton.Tests/ContosoButtonTests.cs` — an xUnit test that boots the
+ driver in `TestDriverHost`, adds a device, and asserts behavior.
+- `ContosoButton.manifest.json` — the InfGen manifest that generates the INF.
+
+## 4. Understand the two entry points
+
+A driver implements `IDriver` (usually via `DriverBase`):
+
+```csharp
+public sealed class ContosoButtonDriver : DriverBase
+{
+ public override Task OnDriverEntryAsync(DriverContext context, CancellationToken ct)
+ {
+ context.Log.Info("entering, service '{0}'", context.DriverServiceName);
+ return Task.CompletedTask;
+ }
+
+ public override Task OnDeviceAddAsync(
+ DeviceAddContext addContext, DeviceContext deviceContext, CancellationToken ct)
+ {
+ var device = new ContosoButtonDevice(deviceContext);
+ deviceContext.CreateDeviceInterface(new Guid("…")); // apps open this
+ return Task.FromResult(device);
+ }
+}
+```
+
+`OnDriverEntryAsync` runs once (allocate driver-wide state, read the service
+`Parameters` registry key via `context.Registry`). `OnDeviceAddAsync` runs per
+device the PnP manager enumerates — create your `DeviceBase` subclass and
+return it. The host then runs the WDF power-up sequence:
+`PrepareHardware` → `D0Entry`.
+
+## 5. Handle IOCTLs
+
+Device-specific work happens in queue handlers. The default queue is created
+for you (parallel dispatch); create more with `CreateQueue`:
+
+```csharp
+public sealed class ContosoButtonDevice : DeviceBase
+{
+ public ContosoButtonDevice(DeviceContext context) : base(context)
+ {
+ DefaultQueue.OnDeviceControl(HandleDeviceControlAsync);
+ }
+
+ private Task HandleDeviceControlAsync(IoRequest request, CancellationToken ct)
+ {
+ var code = request.IoControlCode;
+ if (code == ContosoIoctlCodes.GetButtonState) // VendorControlCode(0x800, FileAccessRead)
+ {
+ WireFormat.WriteUInt32(request.OutputBuffer.Span, 0, _state);
+ request.Complete(NtStatus.Success, sizeof(uint));
+ }
+ else
+ {
+ request.Fail(NtStatus.InvalidDeviceRequest); // unknown IOCTL
+ }
+ return Task.CompletedTask;
+ }
+}
+```
+
+Rules that match WDF semantics:
+
+- Complete every request **exactly once** — double completion throws (in real
+ WDF it bugchecks).
+- For writes, `Complete(status, bytes)` counts bytes taken from the *input*
+ buffer; for reads/IOCTLs, bytes placed in the *output* buffer.
+- Throw `DriverException(NtStatus.…)` to fail a request with a specific
+ status; uncaught exceptions complete with `STATUS_UNSUCCESSFUL`.
+
+## 6. Test it
+
+```csharp
+[Fact]
+public async Task Button_state_roundtrips()
+{
+ var host = TestDriverHost.Builder().UseFakeTime().Build();
+ await host.StartAsync("ContosoButtonService");
+ var device = await host.AddDeviceAsync("ROOT\\CONTOSOBUTTON\\0000", "Root\\ContosoButton");
+
+ var result = await device.SendIoctlAsync(ContosoIoctlCodes.GetButtonState);
+ Check.Status(result, NtStatus.Success);
+
+ await host.ShutdownAsync();
+}
+```
+
+`TestDriverHost` runs the exact lifecycle the production shims run, so behavior
+you verify here is the behavior you get on Windows. See
+[testing-guide.md](testing-guide.md) for the fake clock, fake registry and
+log assertions.
+
+## 7. Generate the INF and deploy
+
+```bash
+./.tools/infgen generate --manifest ContosoButton/ContosoButton.manifest.json
+# ContosoButton.inf
+
+infgen validate --inf ContosoButton.inf # lint before signing
+```
+
+On a Windows machine (with the package signed — see
+[inf-and-signing.md](inf-and-signing.md)):
+
+```powershell
+.\tools\Enable-TestSigning.ps1 # once, for test-signed packages (reboot)
+.\tools\Install-Driver.ps1 -InfPath .\ContosoButton.inf -CertPath .\test.cer
+.\tools\Uninstall-Driver.ps1 -InfName ContosoButton.inf
+```
+
+## 8. Debugging
+
+- **In tests** — pass a `CapturedLog` to the host builder and assert on its
+ entries; every device logs with its instance-id prefix.
+- **On Windows (UMDF)** — enable WUDFHost tracing with
+ `Wudfhost.exe` debug settings; the shim forwards your `IDriverLog` lines to
+ ETW. `!wdfkd.wdflogdump` shows the framework logs in WinDbg.
+- **On Windows (KMDF control plane)** — `KmdfControlPlane.ReadEvents()` drains
+ the kernel ring; post events from the shim's `WdsPostEvent` for tracing.
+
+## Next steps
+
+- Pick the hosting path: [umdf-guide.md](umdf-guide.md) (user-mode, first
+ choice) or [kmdf-interop-guide.md](kmdf-interop-guide.md) (kernel reach).
+- Look at the sample closest to your device class: [audio](../samples/VirtualAudio/),
+ [HID](../samples/HidGamepad/), [sensor](../samples/VirtualSensor/),
+ [serial](../samples/VirtualSerial/).
diff --git a/docs/hid-guide.md b/docs/hid-guide.md
new file mode 100644
index 0000000..50e6119
--- /dev/null
+++ b/docs/hid-guide.md
@@ -0,0 +1,128 @@
+# HID guide
+
+The HID module (`WindowsDriver.Sdk.Hid`) can emit real USB HID report
+descriptors byte-by-byte, parse them back for validation, and pack/unpack
+input reports against a device state object. The HidGamepad sample uses all of
+it.
+
+## HID item encoding (what the builder emits)
+
+HID report descriptors are sequences of *items*. Each short item is:
+
+```
+byte = (tag << 4) | (type << 2) | sizeCode
+ type: 0 = Main, 1 = Global, 2 = Local
+ sizeCode: 0 → 0 data bytes, 1 → 1, 2 → 2, 3 → 4
+```
+
+Item values are signed, little-endian, encoded in the smallest size that
+holds them (with one exception: zero-valued Main items use the 0-byte form).
+The tags the builder uses:
+
+| Main | tag | Global | tag | Local | tag |
+| --- | --- | --- | --- | --- | --- |
+| Input | 0x8 | Usage Page | 0x0 | Usage | 0x0 |
+| Output | 0x9 | Logical Min/Max | 0x1/0x2 | Usage Min/Max | 0x1/0x2 |
+| Feature | 0xB | Report Size | 0x7 | | |
+| Collection | 0xA | Report Count | 0x9 | | |
+| End Collection | 0xC | Report ID | 0x8 | | |
+
+You can see these in the canonical gamepad descriptor bytes: `05 01` (Usage
+Page Generic Desktop), `09 05` (Usage Game Pad), `A1 01` (Collection
+Application), `85 01` (Report ID 1), `05 09` (Usage Page Button)…
+
+## Building a descriptor
+
+```csharp
+byte[] descriptor = HidReportDescriptorBuilder.Create()
+ .UsagePage(HidUsagePage.GenericDesktop)
+ .Usage(GenericDesktopUsage.GamePad)
+ .BeginCollection(HidCollectionType.Application)
+ .ReportId(1)
+ .Buttons(12) // 12 bits + auto pad to byte
+ .Axis(GenericDesktopUsage.X, 16, short.MinValue, short.MaxValue)
+ .Axis(GenericDesktopUsage.Y, 16, short.MinValue, short.MaxValue)
+ .Axis(GenericDesktopUsage.Z, 16, short.MinValue, short.MaxValue)
+ .Axis(GenericDesktopUsage.Rx, 16, short.MinValue, short.MaxValue)
+ .Axis(GenericDesktopUsage.Ry, 16, short.MinValue, short.MaxValue)
+ .Axis(GenericDesktopUsage.Rz, 16, short.MinValue, short.MaxValue)
+ .EndCollection()
+ .ToBytes();
+```
+
+Convenience blocks:
+
+- `Buttons(count)` — Usage Page Button, Usage Min/Max 1..count, Logical 0..1,
+ one-bit fields, **automatic Const padding to a byte boundary**, and restores
+ the previous usage page afterwards.
+- `Axis(usage, bits, min, max)` — single Data,Variable,Absolute field.
+- `PaddingInput(bits)` — explicit padding without consuming a usage.
+
+Rules the builder enforces: report IDs must be 1–255 (0 is reserved), report
+sizes 1–32 bits, unit exponents −8..7, and `ToBytes()` throws if the descriptor
+does not end with an End Collection.
+
+## Validating what you built
+
+`HidReportDescriptorParser.Parse(descriptor)` walks the items, maintains the
+global state stack (Push/Pop included), and returns a summary: per-report-ID
+bit totals for Input/Output/Feature, every non-const field with its usage
+page/min/max and logical range, collection depth, and whether report IDs are
+used. The sample's test asserts exactly the layout you expect:
+
+```
+ReportId 1 → 112 input bits = 12 buttons + 4 pad + 6 × 16-bit axes
+Wire size = 1 (report ID) + 14 bytes = 15
+```
+
+A parser that re-derives the layout is the cheapest way to catch descriptor
+bugs before Windows does.
+
+## The input report on the wire
+
+For the canonical gamepad (`GamepadInputReport`):
+
+```
+byte 0 report ID (1)
+bytes 1..2 buttons 1..12 in bits 0..11 (LSB first), bits 12..15 zero
+bytes 3..14 X, Y, Z, Rx, Ry, Rz as int16 little-endian
+```
+
+`GamepadState` is the driver-side object; `GamepadInputReport.Pack(state)` →
+15 bytes, `Unpack(bytes)` → state. Round-trip is tested, including the
+button-bit mapping (button N = bit N−1).
+
+## The HID device
+
+`HidDevice : DeviceBase` serves the descriptors and the current input report:
+
+| IOCTL | Behavior |
+| --- | --- |
+| `GetReportDescriptor` | out: the raw descriptor bytes |
+| `GetDeviceDescriptor` | out: the 9-byte class descriptor (bLength 9, type 0x21, bcdHID 1.11, country, 1 descriptor, type 0x22, length) |
+| `GetInputReportSize` | out: u16 wire size |
+| `GetInputReport` | out: current report (from `InputReportFactory`) |
+| `SetFeatureReport` / `GetFeatureReport` | feature storage + echo |
+
+Read requests return the current input report — `HidDeviceOptions.
+InputReportFactory` is a `Func`, so the owning driver decides how
+state becomes wire data (the gamepack sample packs its `GamepadState` under a
+lock). Subclass `HidDevice` to add IOCTLs (the sample adds `UpdateState` and
+`SetInputState`).
+
+## Integration with the Windows HID stack
+
+Two realistic paths:
+
+1. **UMDF + HID class extension (HidCx)** — the supported user-mode route.
+ Your driver registers with HidCx and fills the standard hidclass
+ IOCTL/DTM contract (`IOCTL_HID_GET_DEVICE_DESCRIPTOR`,
+ `IOCTL_HID_READ_REPORT`, …). The SDK's descriptor bytes are the payload —
+ what you plug in is *your* descriptor into HidCx's descriptor DDI, and the
+ input report bytes into the report DDI. The class extension then exposes
+ the device as a HID device to the system (gamepad in games, etc.).
+2. **KMDF shim** — for kernel-only stacks; the report bytes flow over the
+ shim protocol and a native HID miniport presents them to hidclass.
+
+Either way, building and validating the descriptor in C# with the parser is
+the time-saver: the descriptor you tested is the descriptor you ship.
diff --git a/docs/inf-and-signing.md b/docs/inf-and-signing.md
new file mode 100644
index 0000000..6e4562d
--- /dev/null
+++ b/docs/inf-and-signing.md
@@ -0,0 +1,143 @@
+# INF and signing
+
+Every driver package needs an INF. The SDK generates it from a JSON manifest
+with `infgen`, and this guide covers the manifest schema, what the generated
+INF contains, and how to get the package signed and installed.
+
+## The manifest
+
+```json
+{
+ "name": "VirtualAudio",
+ "provider": "Contoso Devices",
+ "manufacturer": "Contoso Devices LLC",
+ "version": "0.1.0",
+ "driverVerDate": "11/18/2026",
+ "class": "Media",
+ "classGuid": "{4d36e96c-e325-11ce-bfc1-08002be10318}",
+ "framework": "umdf",
+ "serviceName": "WdsVirtualAudio",
+ "catalogFile": "VirtualAudio.cat",
+ "files": [
+ { "source": "VirtualAudio.Driver.dll" }
+ ],
+ "models": [
+ {
+ "name": "Contoso Virtual Audio Device (SDK sample)",
+ "hardwareIds": ["Root\\ContosoVirtualAudio"],
+ "compatibleIds": ["*WdsVirtualAudio"]
+ }
+ ],
+ "wdfLibraryVersion": "2.15.0"
+}
+```
+
+Field notes:
+
+- `class`/`classGuid` — the **setup class**. Common values: Media
+ `{4d36e96c-e325-11ce-bfc1-08002be10318}` (sound/game controllers), HIDClass
+ `{745a17a0-74d3-11d0-b6fe-00a0c90e91ab}`, Ports
+ `{4d36e978-e325-11ce-bfc1-08002be10318}`, Sensor
+ `{5175d334-c371-4806-b3ba-71fd53c9258d}`. The full list lives in Microsoft's
+ "system-defined device setup classes" documentation.
+- `framework` — `umdf` or `kmdf`; picks the `[.Wdf]` wiring
+ (`UmdfService` + `UmdfLibraryVersion` + `ServiceBinary` vs. `KmdfService` +
+ `KmdfLibraryVersion`).
+- `hardwareIds` — most specific first. Root-enumerated virtual devices
+ typically use `Root\YourDevice`.
+- `driverVerDate` — MM/DD/YYYY; defaults to the generation date.
+
+`infgen validate --inf file.inf` lints the result: required sections,
+parseable GUIDs, DriverVer format, duplicate sections, model→install-section
+references, and unresolved string keys (comments stripped first). Run InfVerif
+from the WDK before submission — it knows rules this linter does not.
+
+## What the generated INF contains
+
+```
+[Version] Signature, Class, ClassGuid, Provider,
+ CatalogFile, DriverVer, PnpLockdown=1
+[Manufacturer] %Manufacturer%=Standard,NTamd64,NTarm64
+[Standard.NTamd64] %Model0%=Install.NTamd64,
+[Install.NTamd64] CopyFiles=DriverFiles
+[Install.NTamd64.Wdf] UmdfService=, _Install
+ UmdfServiceOrder=
+[_Install] UmdfLibraryVersion=2.15.0
+ ServiceBinary=%12%\
+[DriverFiles] the file list
+[SourceDisksNames/Files] package media mapping
+[DestinationDirs] DriverFiles = 12
+[Strings] Provider, Manufacturer, Model0, DiskName
+```
+
+Everything is deterministic from the manifest, so you can regenerate instead
+of hand-editing (the header comment says exactly that).
+
+## Signing: test signing
+
+For development:
+
+1. Create a test certificate (elevated PowerShell):
+
+```powershell
+$cert = New-SelfSignedCertificate -Type CodeSigningCert -Subject "CN=WDS Test" `
+ -KeyUsage DigitalSignature -KeyExportPolicy Exportable `
+ -Provider "Microsoft Enhanced Cryptographic Provider v1.0" `
+ -CertStoreLocation Cert:\CurrentUser\My
+Export-PfxCertificate -Cert $cert -FilePath .\test.pfx
+Export-Certificate -Cert $cert -FilePath .\test.cer
+```
+
+2. Sign the binaries and package with `signtool` (from the WDK):
+
+```powershell
+signtool sign /fd SHA256 /a /f .\test.pfx .\YourDriver.dll
+Inf2Cat /driver:. /os:10_X64 # builds the .cat from the INF + files
+signtool sign /fd SHA256 /a /f .\test.pfx .\YourDriver.cat
+```
+
+3. Trust the certificate and enable test signing (reboot required):
+
+```powershell
+Import-Certificate -FilePath .\test.cer -CertStoreLocation Cert:\LocalMachine\TrustedPublisher
+.\tools\Enable-TestSigning.ps1 # bcdedit /set testsigning on
+```
+
+4. Install:
+
+```powershell
+.\tools\Install-Driver.ps1 -InfPath .\YourDriver.inf -CertPath .\test.cer
+```
+
+## Signing: production (attestation / WHQL)
+
+- **Attestation signing** — sign with an EV code-signing certificate, submit
+ the package to the Windows hardware Dev Center, and Microsoft countersigns
+ it; the countersigned package installs everywhere without test signing.
+ Kernel drivers require Microsoft's signature (attestation or full WHQL) —
+ a self-signed kernel package will not load on retail.
+- **WHQL** — full certification via HLK (Windows Hardware Lab Kit) tests;
+ required for some driver types and wanted for Windows Update distribution.
+- Regardless of path: `InfVerif`, `SDV` (static driver verifier, KMDF only),
+ and `Driver Verifier` at runtime are your pre-submission gates.
+
+## Install/uninstall scripts
+
+`tools/Install-Driver.ps1` wraps `pnputil /add-driver /install` with admin and
+test-signing prechecks and optional certificate import.
+`tools/Uninstall-Driver.ps1` maps your INF name to its published `oemXX.inf`
+name, removes matching devices, and deletes the package
+(`pnputil /delete-driver /uninstall /force`).
+
+## Common pitfalls
+
+- **GUID braces** — the manifest accepts `{guid}` or bare `guid`; `infgen`
+ normalizes to lowercase braced form.
+- **Class mismatch** — the Class/ClassGuid pair must be consistent (e.g. HID
+ drivers install into HIDClass; putting a sensor driver in Ports will confuse
+ the stack).
+- **Files must exist at install time** — `CopyFiles` sections reference files
+ that must ship in the same package directory; the catalog covers exactly the
+ files the INF lists.
+- **Kernel + test signing** — a test-signed kernel driver loads only while
+ test signing is enabled; plan the attestation submission early.
diff --git a/docs/kmdf-interop-guide.md b/docs/kmdf-interop-guide.md
new file mode 100644
index 0000000..c3775c0
--- /dev/null
+++ b/docs/kmdf-interop-guide.md
@@ -0,0 +1,121 @@
+# KMDF interop guide — C# control plane over a kernel shim
+
+Kernel-mode drivers are C territory: the CLR cannot run at IRQL, and KMDF DDIs
+take kernel object handles. Any claim of "kernel drivers in C#" is false
+advertising. What *is* achievable — and what this SDK provides — is the split
+that production teams actually use:
+
+- **Kernel side (C, small, frozen)**: device objects, queues, DMA, interrupts —
+ the hot path and whatever must touch hardware.
+- **Managed side (C#, everything else)**: policy, configuration, state
+ aggregation, telemetry, UI, testing — running in a normal .NET process and
+ talking to the kernel driver through a documented IOCTL protocol.
+
+This guide covers the second half: the `WindowsDriver.Interop.Kmdf` control
+plane and the shim driver skeleton in `shim/WdsKmdfShim/`.
+
+## The shim protocol
+
+The shim driver (`WdsKmdfShim.sys`, KMDF) exposes a device interface and
+implements five buffered IOCTLs — the same contract as
+`WindowsDriver.Interop.Kmdf.KmdfShimProtocol`:
+
+| IOCTL | Function | In | Out |
+| --- | --- | --- | --- |
+| `Ping` | 0x800 | — | u32 magic `WSHI` (0x49485357) |
+| `GetVersion` | 0x801 | — | (u32 major, u32 minor) = 1.0 |
+| `SendCommand` | 0x802 | `KmdfCommandHeader` + data | `KmdfResultHeader` + data |
+| `ReadEvents` | 0x803 | — | (u32 count) + `KmdfEventRecord`s |
+| `AcknowledgeEvents` | 0x804 | u32 eventMask | — |
+
+Wire structs are `#pragma pack(1)` and mirrored byte-for-byte on both sides
+(`KmdfEventRecord` ↔ `WDS_EVENT_RECORD`, etc. — verified by unit tests that
+assert `Marshal.SizeOf` against the C `C_ASSERT` values: 16-byte event record,
+8-byte command and result headers).
+
+Vendor commands start at `KmdfCommandIds.FirstVendorCommand` (0x100); IDs
+below are reserved for the shim itself. `SendCommand` is synchronous: the
+kernel runs your command and returns a status plus payload. Asynchronous
+results flow back as events: kernel code calls `WdsPostEvent(device, eventId,
+size, data)`, the ring holds up to 256 records, and the control plane drains
+them with `ReadEvents`.
+
+## Using the control plane from C#
+
+```csharp
+using WindowsDriver.Interop.Kmdf;
+
+var control = new KmdfControlPlane(@"\\.\WdsKmdfShim0");
+control.Open(); // CreateFileW on the device interface
+
+control.Ping(); // verifies the WSHI magic
+var (major, minor) = control.GetVersion();
+
+// Send a vendor command defined on the kernel side.
+var (status, data) = control.SendCommand(0x100, new byte[] { 0x01, 0x02 });
+if (status.IsSuccess())
+{
+ // parse `data`
+}
+
+// Drain the kernel event ring (e.g. on a timer).
+foreach (KmdfEvent evt in control.ReadEvents(maxEvents: 64))
+{
+ Console.WriteLine($"seq={evt.Sequence} id={evt.EventId} bytes={evt.Data.Length}");
+}
+
+control.Dispose();
+```
+
+`Open()` uses the real `CreateFileW`/`DeviceIoControl` P/Invoke declarations in
+`Win32Native` — on a machine without the driver installed it throws the actual
+Win32 error (`ERROR_FILE_NOT_FOUND`), which is your cue that the package is
+not deployed.
+
+## Building the kernel shim
+
+`shim/WdsKmdfShim/` is a compiling-against-WDK skeleton:
+
+- `wds_shim.h` — protocol constants, packed wire structs (`C_ASSERT`s pin the
+ sizes), the device-interface GUID, and the ring capacity.
+- `wds_shim.c` — `DriverEntry`, `EvtDeviceAdd` (device + sequential queue +
+ interface creation), `EvtIoDeviceControl` implementing all five IOCTLs, an
+ event ring with a spin lock, and `WdsHandleCommand` — a stub where your
+ kernel work goes.
+- Build in Visual Studio with the WDK (KMDF, Windows 10+, x64/arm64), sign, and
+ install with `tools/Install-Driver.ps1` using an INF generated with
+ `"framework": "kmdf"` (InfGen emits the `KmdfService` wiring).
+
+The skeleton is deliberately not built by CI — GitHub runners have no WDK.
+Compile it on a machine with the WDK before deployment (see
+[ci-cd.md](ci-cd.md) for the pipeline shape).
+
+## What belongs on each side
+
+| Put in the kernel (C) | Put in C# (control plane) |
+| --- | --- |
+| register access, DMA, ISR/DPC work | configuration and policy |
+| IRQL-sensitive sequencing | state aggregation and interpretation |
+| small fixed command handlers | all business logic and protocol parsing |
+| event emission (`WdsPostEvent`) | event interpretation, UI, storage |
+
+The SDK's device-class modules (audio/HID/sensor/serial) are control-plane
+friendly: their IOCTL contracts run unmodified over the shim protocol, so you
+can develop the full logic with `TestDriverHost` and later connect the same
+client code to the kernel device.
+
+## Testing without a kernel
+
+The control plane's wire layer is testable without a device: the unit tests
+assert IOCTL code uniqueness and vendor-range discipline, struct sizes, and
+the magic value. `KmdfControlPlane` itself guards every call with "open first"
+failures. For end-to-end behavior, run the shim in a Windows VM and point the
+control plane at it — the protocol is versioned via `GetVersion`, so both
+sides can negotiate.
+
+## When to skip the shim entirely
+
+If your "driver" is really a virtual device (no hardware), prefer UMDF — the
+UMDF path runs entirely in user mode and `TestDriverHost` covers more of it.
+The KMDF story earns its complexity only when you must touch actual hardware
+or kernel APIs.
diff --git a/docs/sensor-guide.md b/docs/sensor-guide.md
new file mode 100644
index 0000000..0b19151
--- /dev/null
+++ b/docs/sensor-guide.md
@@ -0,0 +1,110 @@
+# Sensor guide
+
+The sensor module (`WindowsDriver.Sdk.Sensor`) models a multi-sensor device:
+deterministic simulators produce readings, a device class publishes them over
+an IOCTL contract and an event queue, and a background sampling loop runs
+while the device is powered.
+
+## Core types
+
+| Type | Role |
+| --- | --- |
+| `ISensorSource` | a sampled data source: kind, unit, value count, sample rate |
+| `AccelerometerSimulator` | gravity on +Z, smooth seeded sine-noise, transient impulses |
+| `AmbientLightSimulator` | indoor baseline + day-cycle daylight + flicker, manual override |
+| `SensorReading` | (kind, timestamp, values[], unit) |
+| `SensorDevice : DeviceBase` | hosts sources, IOCTL contract, event queue, sampling loop |
+
+## Deterministic simulation
+
+Both simulators are **pure functions of the timestamp** — no hidden state, no
+random walks. The same timestamp always produces the same values, which makes
+tests exact: the VirtualSensor sample asserts gravity ≈ 9.8 m/s² on Z, the
+3-minute-past-midnight lux level (indoor baseline, no daylight), and byte-level
+round-trips through the IOCTL payloads.
+
+The accelerometer adds *impulses* — transient accelerations with a triangular
+envelope over a duration (`AddImpulse(at, duration, (dx, dy, dz))`). A shake
+is then a testable event: sample mid-impulse and assert X > 5 m/s².
+
+The ambient light simulator models indoor baseline (400 lx default) with a
+daylight sine curve peaking at 12:00 (12,000 lx default) plus slow flicker,
+and a manual `OverrideLux` for "the lamp is on" scenarios.
+
+## The IOCTL contract
+
+`SensorIoctlCodes` (vendor functions on `FILE_DEVICE_UNKNOWN`, METHOD_BUFFERED):
+
+- **GetSensorCount** — out: u32.
+- **GetSensorInfo(index)** — out: (u32 kind, u32 valueCount, u32 sampleRateMilliHz, char[16] unit). Out-of-range index → `STATUS_INVALID_PARAMETER`.
+- **GetLatestReading(index)** — out: (u64 timestamp ticks, u32 valueCount, valueCount × f64). Before the first sample → `STATUS_DEVICE_NOT_READY`.
+- **SetSampleRate(index, milliHz)** — adjusts the poll rate of one sensor.
+
+Timestamps are `DateTimeOffset.UtcTicks` — reproducible under the fake clock.
+
+## Polling and push
+
+Clients choose:
+
+- **Poll** — `GetLatestReading` whenever convenient.
+- **Subscribe** — `SensorDevice.Readings` is a bounded `Channel`
+ (drop-oldest at 256 by default): every `SampleOnce()` writes one reading per
+ sensor. Drop-oldest matches how real sensor stacks behave under load — you
+ lose old samples, never block the device.
+
+## The sampling loop
+
+On `D0Entry` the device starts a loop that wakes at the fastest configured
+sensor rate (`Task.Delay(interval, TimeProvider, ct)`) and samples everything;
+on `D0Exit` it stops and waits (bounded by 2 s). Under the fake clock the loop
+advances when you advance time — no real waiting in tests. Tests that need
+deterministic single steps call `SampleOnce()` directly (also public), so the
+loop is exercised by exactly one test and the rest stay rock solid.
+
+## Writing your device
+
+```csharp
+public sealed class MySensorDevice : SensorDevice
+{
+ public MySensorDevice(DeviceContext context)
+ : base(context, new SensorDeviceOptions
+ {
+ Sources =
+ [
+ new AccelerometerSimulator(seed: 42, sampleRateHz: 50),
+ new AmbientLightSimulator(seed: 7, sampleRateHz: 4),
+ ],
+ })
+ {
+ }
+
+ protected override Task HandleDeviceControlAsync(IoRequest request, CancellationToken ct)
+ {
+ // custom IOCTLs (overrides, calibration), then:
+ return base.HandleDeviceControlAsync(request, ct);
+ }
+}
+```
+
+Custom sources implement `ISensorSource` (kind, unit, value count, rate,
+`Sample(timestamp)`) — a barometer, humidity, or a derived value computed from
+other sensors.
+
+## Integration with the Windows sensor stack
+
+Real Windows sensor drivers register with the **sensor class extension
+(SensorCx)** on UMDF: the class extension owns the Windows Sensor API surface
+(/categories, report intervals, properties) and your driver fills readings.
+The mapping from the SDK model:
+
+- `ISensorSource` ↔ one SensorCx sensor (each has a type GUID and a driver-
+ provided friendly name/category).
+- `SampleOnce` ↔ SensorCx data notifications (`SensorCx` DDI to publish a
+ report after collection).
+- `SetSampleRate` ↔ report-interval property (`SENSOR_PROPERTY_REPORT_INTERVAL`,
+ milliseconds).
+- The event queue ↔ SensorCx's notification model (it also batches/rate-limits).
+
+The simulators stay exactly as they are — you swap only the publishing layer.
+The Sensor class GUID used by the sample's manifest is the system-defined one
+from Microsoft's "system-defined device setup classes" documentation.
diff --git a/docs/serial-guide.md b/docs/serial-guide.md
new file mode 100644
index 0000000..a191326
--- /dev/null
+++ b/docs/serial-guide.md
@@ -0,0 +1,84 @@
+# Serial guide
+
+The serial module (`WindowsDriver.Sdk.Serial`) implements a complete virtual
+COM port: line configuration with classic UART validation, TX/RX queues,
+loopback and null-modem wiring, modem status, break conditions, and counters.
+
+## Core types
+
+| Type | Role |
+| --- | --- |
+| `SerialLineConfig` | baud / data bits / parity / stop bits / flow control, with wire helpers |
+| `SerialDevice : DeviceBase` | the port: queues, IOCTL contract, status |
+| `SerialLoopbackPair` | cross-connects two ports like a null-modem cable |
+| `TxSink` delegate | receives every transmitted byte (used by the pair) |
+
+## Line configuration and validation
+
+`SerialLineConfig` follows the rules a real 8250-family UART enforces:
+
+- baud 50 .. 1,000,000;
+- data bits 5–8;
+- **1.5 stop bits only with 5 data bits**; **2 stop bits never with 5 data
+ bits**;
+- parity None/Odd/Even/Mark/Space; flow None/XonXoff/RtsCts.
+
+`Validate()` throws `DriverException(InvalidParameter)` with a specific
+message; `SerialDevice.ApplyConfig` calls it before switching, and the
+`SetLineConfig` IOCTL surfaces the failure to the client. The wire format is
+8 bytes: (u32 baud, u8 dataBits, u8 parity, u8 stopBits, u8 flow, pad).
+
+## Data paths
+
+Three ways bytes move:
+
+1. **Loopback plug** (`Loopback = true`, the default) — everything transmitted
+ (via `Write` requests, the `Transmit` IOCTL, or `SerialDevice.Transmit`)
+ comes back on the RX queue immediately. Perfect for self-tests.
+2. **Null-modem pair** — create two devices with `Loopback = false` and join
+ them: `new SerialLoopbackPair(portA, portB)`. A's TX → B's RX and B's TX →
+ A's RX, through the `TxSink` hook. The sample's test sends in both
+ directions and asserts nothing loops back to the sender.
+3. **Remote simulation** — `InjectReceive(bytes)` writes directly into the RX
+ queue, as if the peer sent them; the sample exposes it via a custom IOCTL
+ (`SimulateRemoteData`).
+
+Queues are `ByteRingBuffer`s (4096 bytes each by default) with full counters:
+`TotalBytesWritten/Read` feed the `GetStatus` IOCTL, and `Purge` clears RX
+and/or TX by flags.
+
+## Status and faults
+
+`GetStatus` returns (u64 txBytes, u64 rxBytes, u32 framingErrors, u8 cts,
+u8 dsr, u8 breakActive, u8 loopback). Fault injection for tests:
+
+- `InjectFramingError()` — bumps the error counter.
+- `AssertBreak(true)` — sets the break flag and injects a framing error, like
+ a real break condition on the line.
+
+CTS/DSR are asserted by default; expose setters if your scenario needs
+handshake failures.
+
+## The IOCTL contract
+
+`SerialIoctlCodes` (vendor functions on `FILE_DEVICE_SERIAL_PORT`,
+METHOD_BUFFERED): `GetLineConfig`, `SetLineConfig`, `Transmit`, `Purge`
+(bit 0 RX, bit 1 TX), `GetStatus`, `GetRxCount`. Empty `Transmit` payloads are
+rejected with `STATUS_INVALID_PARAMETER`, short buffers with
+`STATUS_BUFFER_TOO_SMALL`.
+
+## Integration with the Windows serial stack
+
+- **Presenting a COM port to applications** — a driver for the *Ports* class
+ that creates a serial device interface gets a COM number from Windows
+ (serenum/serial enumeration). A UMDF serial driver implements the serial
+ controller contract; the byte paths here map onto its read/write requests.
+- **USB CDC-ACM** — a very common real-world shape: the driver is a CDC host
+ function driver and the "line" is a USB bulk pair; the config/validation
+ logic and the loopback/pair model are directly reusable for testing.
+- **Virtual pairs for applications** — many products ship virtual COM pairs
+ (com0com-style); `SerialLoopbackPair` is exactly that, in-process for tests
+ or across the shim protocol for two real processes.
+
+The sample manifest uses the Ports class GUID
+(`{4d36e978-e325-11ce-bfc1-08002be10318}`).
diff --git a/docs/testing-guide.md b/docs/testing-guide.md
new file mode 100644
index 0000000..b037eb9
--- /dev/null
+++ b/docs/testing-guide.md
@@ -0,0 +1,109 @@
+# Testing guide
+
+The SDK's testing story rests on one idea: the same `DriverHost` that the
+production shims drive also runs inside `TestDriverHost` — so tests exercise
+the real lifecycle (add → prepare → D0 → IO → exit), just with in-memory
+inputs and a controllable clock.
+
+## Setting up a host
+
+```csharp
+var host = TestDriverHost.Builder()
+ .UseFakeTime() // FakeTimeProvider starting 2026-01-01
+ .WithRegistry(new FakeRegistry(("LogLevel", 3u)))
+ .Build();
+
+await host.StartAsync("ContosoButtonService");
+var device = await host.AddDeviceAsync("ROOT\\CONTOSOBUTTON\\0000", "Root\\ContosoButton");
+// … interact …
+await host.ShutdownAsync();
+```
+
+The builder gives you:
+
+- `FakeTime` — the `FakeTimeProvider` (null when you chose real time).
+- `Log` — a `CapturedLog` recording every entry (level, message, time).
+- `Registry` — the `FakeRegistry` the driver reads its `Parameters` from.
+- `Devices` — the `TestDevice` list.
+
+## Interacting with a device
+
+`TestDevice` mirrors what an application (or the WDF stack) would do:
+
+```csharp
+// IOCTLs — input bytes + output buffer size, returns an IoResult snapshot
+var result = await device.SendIoctlAsync(ContosoIoctlCodes.GetState, outputSize: 4);
+Check.Status(result, NtStatus.Success);
+Check.Bytes(result, 4);
+var state = BinaryPrimitives.ReadUInt32LittleEndian(result.Output);
+
+// Reads and writes
+var data = await device.ReadAsync(256);
+await device.WriteAsync(new byte[] { 1, 2, 3 });
+```
+
+Every call runs through the device's real queue — dispatch mode, handler
+registration, completion semantics and exception mapping all apply. A test
+that hangs more than 5 s throws a `TimeoutException` naming the IOCTL, which
+is almost always a driver that forgot to complete a request (a genuine bug you
+want surfaced).
+
+`Check` helpers (`Status`, `Success`, `Bytes`) throw `TestCheckException`
+with a formatted message — they work with xUnit, NUnit and MSTest alike, which
+is why `WindowsDriver.Testing` has no framework dependency.
+
+## The fake clock
+
+`FakeTimeProvider` derives from .NET 8's `System.TimeProvider`. Timers created
+through it fire inside `Advance()`:
+
+```csharp
+host.FakeTime!.Advance(TimeSpan.FromSeconds(1)); // timers + Task.Delay fire now
+host.FakeTime.AdvanceTo(new DateTimeOffset(2026, 6, 1, 12, 0, 0, TimeSpan.Zero));
+```
+
+Rules: time never moves backwards (throws), re-entrant `AdvanceTo` from a
+timer callback throws, and periodic timers re-arm per period. Because the SDK's
+audio position clock, sensor sampling loop and volume ramps all read
+`TimeProvider`, a one-second audio position test is exact:
+
+```csharp
+await device.SendIoctlAsync(AudioIoctlCodes.Start);
+host.FakeTime!.Advance(TimeSpan.FromSeconds(1));
+// GetPosition → exactly 48000 frames at 48 kHz
+```
+
+## Log assertions
+
+```csharp
+host.Log.Contains("device ROOT\\CONTOSOBUTTON\\0000 added"); // substring, case-insensitive
+Assert.False(host.Log.ContainsError()); // no [ERROR] entries
+host.Log.Entries.First(e => e.Level == DriverLogLevel.Info).Message
+```
+
+Every device logs with an `[instanceId]` prefix via `ScopedDriverLog`, so
+multi-device tests can attribute messages.
+
+## Testing device classes
+
+- **Lifecycle order** — assert on the log or on a trace list: entry → add →
+ prepare → D0entry (…→ d0exit → release → unload). The SDK test suite does
+ exactly this against a tracing driver.
+- **Queue semantics** — a Sequential queue handler that sleeps proves
+ one-at-a-time dispatch (`maxConcurrent == 1`); unknown IOCTLs prove the
+ `InvalidDeviceRequest` default.
+- **Failure paths** — throw `DriverException(NtStatus.X)` from a handler and
+ assert the request completes with X; incomplete requests surface as the
+ SubmitAsync timeout.
+- **Devices that need peers** — `SerialLoopbackPair` composes two devices;
+ build them directly with a `DeviceContext` like the serial sample's test.
+- **INFs** — each sample test generates its INF from the manifest and runs the
+ linter, so a broken manifest fails CI on Linux.
+
+## What tests can't cover
+
+Real OS interaction — actual `WUDFHost` activation, hardware registers, IRQL —
+stays outside the unit harness by design. Cover it with: the KMDF shim running
+in a VM (the control plane protocol is versioned), HLK for certification, and
+Driver Verifier before submission. The unit suite's job is to make the 95% of
+driver logic that is plain code fast and deterministic to verify.
diff --git a/docs/umdf-guide.md b/docs/umdf-guide.md
new file mode 100644
index 0000000..1b1acac
--- /dev/null
+++ b/docs/umdf-guide.md
@@ -0,0 +1,112 @@
+# UMDF guide — hosting C# drivers in WUDFHost
+
+UMDF (User-Mode Driver Framework) is the right first target for a C# driver:
+it runs in a user-mode host process (`WUDFHost.exe`), a driver bug produces an
+error instead of a blue screen, and most device classes (HID via HidCx,
+sensors via SensorCx, custom buses) have user-mode paths.
+
+## What Microsoft supports vs. what this SDK adds
+
+As of the WDK available in November 2026, Microsoft's supported languages for
+UMDF driver code are C++ and C++/COM. There is no official C# story. This SDK
+adds one with a **managed-host architecture**: a small C++/COM shim gets loaded
+by `WUDFHost`, hosts the .NET runtime via `hostfxr`, and forwards every UMDF
+callback to your C# driver through a frozen ABI.
+
+You write only the C# part. The shim is mechanical forwarding code — this guide
+is its implementation spec, and the managed side of the ABI is already shipped.
+
+## The two sides of the ABI
+
+### Managed side (shipped: `WindowsDriver.Interop.Umdf`)
+
+- `ManagedDriverBootstrap` — seven `[UnmanagedCallersOnly]` entry points the
+ shim resolves with `hostfxr`'s `load_assembly_and_get_function_pointer`:
+
+ | Entry point | Called when | Bridges to |
+ | --- | --- | --- |
+ | `WdsInitialize` | `IDriverEntry::OnInitialize` | `DriverHost.StartAsync(driverType)` |
+ | `WdsDeviceAdd` | `EvtDriverDeviceAdd` | `DriverHost.AddDeviceAsync` |
+ | `WdsQueueRequest` | every request in a queue | `IoQueue.Submit(IoRequest)` |
+ | `WdsDeviceD0Entry` / `WdsDeviceD0Exit` | power transitions | `DeviceBase.D0EntryAsync` / `D0ExitAsync` |
+ | `WdsDeviceRelease` | `EvtDeviceReleaseHardware` | `DeviceBase.ReleaseHardwareAsync` |
+ | `WdsDriverUnload` | `IDriverEntry::OnDeinitialize` | `DriverHost.ShutdownAsync` |
+
+- `UmdfShimSettings` — the struct the shim passes to `WdsInitialize`: function
+ pointers for `CompleteRequest` (managed → shim), `Log` (managed → shim, UTF-8
+ lines) and `ArmQueue`, plus the UTF-8 service name and the fully-qualified
+ managed driver type name (e.g. `VirtualAudio.Driver.SampleAudioDriver, VirtualAudio.Driver`).
+- `UmdfShimContract.ShimHeader` — the C header text, the single source of truth
+ for both sides.
+
+### Native side (your shim project)
+
+Implement in C++/COM inside a UMDF driver DLL (call it `WdsShimU.dll`):
+
+1. Standard COM scaffolding (`DllGetClassObject` + class factory) so
+ `WUDFHost` can create the driver object from the CLSID your INF registers
+ (see the `[.Wdf]` `UmdfService` wiring that `infgen` emits).
+2. `IDriverEntry::OnInitialize` → prepare `WDS_SHIM_SETTINGS`, locate
+ `hostfxr.dll`, initialize with your assembly's `.runtimeconfig.json`, get
+ function pointers for the seven `Wds*` entry points, call `WdsInitialize`.
+3. `OnDeviceAdd` → read the hardware IDs from the device property store and
+ call `WdsDeviceAdd(instanceId, hardwareIds[], count)`.
+4. Queue plumbing — create an `IWDFIoQueue` per managed `IoQueue`; on each
+ request: `WdfRequestRetrieveInputBuffer`/`OutputBuffer` → `WdsQueueRequest`
+ with `(requestId, kind, ioctl, input, inputLen, output, outputLen)`. When
+ the managed side later calls your `CompleteRequest(requestId, status,
+ bytes)` callback, finish with `WdfRequestCompleteWithInformation` — for
+ write requests the information is input bytes, matching the SDK contract.
+5. Power/PnP callbacks → `WdsDeviceD0Entry(previousState)` /
+ `WdsDeviceD0Exit(newState)` / `WdsDeviceRelease()`.
+6. `Log` callback → forward UTF-8 lines to WPP/ETW tracing.
+
+## Lifecycle mapping
+
+| UMDF/WDF callback | SDK callback | Notes |
+| --- | --- | --- |
+| `IDriverEntry::OnInitialize` | `IDriver.OnDriverEntryAsync(DriverContext)` | read `Parameters` key via `DriverContext.Registry` |
+| `EvtDriverDeviceAdd` | `IDriver.OnDeviceAddAsync(addContext, deviceContext)` | return your `DeviceBase`; host runs PrepareHardware + D0Entry |
+| `EvtDevicePrepareHardware` | `DeviceBase.OnPrepareHardwareAsync` | map resources |
+| `EvtDeviceD0Entry` | `DeviceBase.OnD0EntryAsync(previousState)` | start streams/timers |
+| `EvtDeviceD0Exit` | `DeviceBase.OnD0ExitAsync(newState)` | stop streams |
+| `EvtDeviceReleaseHardware` | `DeviceBase.OnReleaseHardwareAsync` | free resources |
+| `EvtDeviceQueryRemove` | `DeviceBase.OnQueryRemoveAsync` | return normally to approve; throw `DriverException` to deny |
+| `EvtDeviceSurpriseRemoval` | `DeviceBase.OnSurpriseRemovalAsync` | unplug — stop touching hardware |
+| `IDriverEntry::OnDeinitialize` | `IDriver.OnDriverUnloadAsync` | last callback |
+
+`IoQueue` dispatch modes map 1:1 to `WdfIoQueueDispatch*`:
+Sequential / Parallel / Manual.
+
+## Buffers and copying
+
+All SDK contracts use `METHOD_BUFFERED` IOCTLs, so the shim can simply copy
+`SystemBuffer` in and out — no MDL plumbing. The managed side validates every
+access with `WireFormat` (throws `STATUS_BUFFER_TOO_SMALL`, which the shim
+maps straight back to the request).
+
+## Practical notes
+
+- **Threading**: UMDF delivers callbacks on host threads; the SDK queues
+ serialize or parallelize exactly like WDF. Handlers may run concurrently in
+ Parallel mode — guard device state (the samples use small `lock` blocks or
+ concurrent structures).
+- **Startup cost**: hosting the CLR adds tens of milliseconds to driver load.
+ Irrelevant for most drivers; if your device must respond within microseconds
+ of arrival, pre-warm in `OnDriverEntryAsync`.
+- **Crash semantics**: an unhandled managed exception completes the request
+ with `STATUS_UNSUCCESSFUL`; it cannot take down the machine. `WUDFHost`
+ restarts the driver host on repeated failure, same as native UMDF drivers.
+- **Testing**: `TestDriverHost` runs the identical lifecycle — CI on Linux
+ gates the same code that ships in `WUDFHost`.
+
+## Checklist to go from repo to deployed UMDF driver
+
+1. `dotnet new driver-umdf` → write the driver + tests (any OS).
+2. `infgen generate --manifest .manifest.json` → INF (UMDF wiring
+ included: `UmdfService`, `UmdfLibraryVersion`, `ServiceBinary`).
+3. Build the C++/COM shim per the checklist above; register it as the
+ `UmdfService` binary in the INF.
+4. Sign the package (test cert locally, attestation for distribution) — see
+ [inf-and-signing.md](inf-and-signing.md).
+5. `tools/Install-Driver.ps1 -InfPath ` on an admin prompt.
diff --git a/global.json b/global.json
new file mode 100644
index 0000000..4c4c3ae
--- /dev/null
+++ b/global.json
@@ -0,0 +1,7 @@
+{
+ "sdk": {
+ "version": "8.0.100",
+ "rollForward": "latestFeature",
+ "allowPrerelease": false
+ }
+}
diff --git a/samples/HidGamepad/Driver/HidGamepad.Driver.csproj b/samples/HidGamepad/Driver/HidGamepad.Driver.csproj
new file mode 100644
index 0000000..6fcac7b
--- /dev/null
+++ b/samples/HidGamepad/Driver/HidGamepad.Driver.csproj
@@ -0,0 +1,13 @@
+
+
+
+ HidGamepad.Driver
+ Sample: virtual HID gamepad (6-axis + 12-button report descriptor, input report packing) built on WindowsDriver.Sdk.
+
+
+
+
+
+
+
+
diff --git a/samples/HidGamepad/Driver/SampleGamepadDriver.cs b/samples/HidGamepad/Driver/SampleGamepadDriver.cs
new file mode 100644
index 0000000..6c7bf97
--- /dev/null
+++ b/samples/HidGamepad/Driver/SampleGamepadDriver.cs
@@ -0,0 +1,136 @@
+using WindowsDriver.Sdk;
+using WindowsDriver.Sdk.Hid;
+
+namespace HidGamepad.Driver;
+
+/// Sample-specific IOCTLs for the gamepad.
+public static class GamepadIoctlCodes
+{
+ /// In: a full 15-byte gamepad input report — replaces the device state.
+ public static readonly uint SetInputState = WinIoctl.VendorControlCode(0x900, WinIoctl.FileAccessWrite);
+
+ /// In: (u16 buttonMask, s16 x, s16 y, s16 z, s16 rx, s16 ry, s16 rz) — 14 bytes, merges into state.
+ public static readonly uint UpdateState = WinIoctl.VendorControlCode(0x901, WinIoctl.FileAccessWrite);
+}
+
+///
+/// Sample driver: enumerates one virtual 6-axis / 12-button gamepad per devnode.
+/// The HID report descriptor is built with the SDK's real item encoder, so the
+/// bytes that ship to the Windows HID stack are spec-compliant.
+///
+public sealed class SampleGamepadDriver : DriverBase
+{
+ public override Task OnDeviceAddAsync(DeviceAddContext addContext, DeviceContext deviceContext, CancellationToken cancellationToken)
+ {
+ deviceContext.Properties.Set(KnownDeviceProperties.FriendlyName, "Contoso Virtual Gamepad (SDK sample)");
+ deviceContext.Properties.Set(KnownDeviceProperties.Manufacturer, "Contoso Devices");
+
+ var device = new SampleGamepadDevice(deviceContext);
+ deviceContext.CreateDeviceInterface(new Guid("9E573ADB-6D6A-4E37-8FB6-71C1A2E4D67B"));
+ return Task.FromResult(device);
+ }
+}
+
+///
+/// Virtual gamepad device: extends with state-update
+/// IOCTLs that simulate the physical controls (buttons, accelerometers, gyros).
+///
+public sealed class SampleGamepadDevice : HidDevice
+{
+ private readonly object _gate = new();
+ private GamepadState _state = new();
+
+ public SampleGamepadDevice(DeviceContext context, HidDeviceOptions? options = null)
+ : base(context, options ?? new HidDeviceOptions
+ {
+ ReportDescriptor = HidDescriptors.GamepadSixAxisTwelveButtons(),
+ })
+ {
+ InputReportFactory = PackCurrent;
+ }
+
+ /// Current device state (thread-safe snapshot).
+ public GamepadState State
+ {
+ get { lock (_gate) { return Snapshot(_state); } }
+ }
+
+ /// Merges axis/button changes into the current state.
+ public void Update(Action mutator)
+ {
+ lock (_gate)
+ {
+ mutator(_state);
+ }
+ }
+
+ private byte[] PackCurrent()
+ {
+ lock (_gate)
+ {
+ return GamepadInputReport.Pack(_state);
+ }
+ }
+
+ private static GamepadState Snapshot(GamepadState source)
+ {
+ var copy = new GamepadState { X = source.X, Y = source.Y, Z = source.Z, Rx = source.Rx, Ry = source.Ry, Rz = source.Rz };
+ for (var b = 1; b <= GamepadState.ButtonCount; b++)
+ {
+ copy[b] = source[b];
+ }
+ return copy;
+ }
+
+ protected override Task HandleDeviceControlAsync(IoRequest request, CancellationToken ct)
+ {
+ var code = request.IoControlCode;
+ if (code == GamepadIoctlCodes.SetInputState)
+ {
+ if (request.InputBuffer.Length != GamepadInputReport.ReportSizeBytes)
+ {
+ request.Fail(NtStatus.InvalidParameter);
+ }
+ else
+ {
+ lock (_gate)
+ {
+ _state = GamepadInputReport.Unpack(request.InputBuffer.Span);
+ }
+ Context.Log.Info("gamepad state replaced via IOCTL");
+ request.Complete(NtStatus.Success, GamepadInputReport.ReportSizeBytes);
+ }
+ }
+ else if (code == GamepadIoctlCodes.UpdateState)
+ {
+ var size = 2 + 6 * sizeof(short);
+ if (request.InputBuffer.Length < size)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ lock (_gate)
+ {
+ var buttons = System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian(request.InputBuffer.Span);
+ for (var b = 1; b <= GamepadState.ButtonCount; b++)
+ {
+ _state[b] = (buttons & (1 << (b - 1))) != 0;
+ }
+ _state.X = System.Buffers.Binary.BinaryPrimitives.ReadInt16LittleEndian(request.InputBuffer.Span.Slice(2));
+ _state.Y = System.Buffers.Binary.BinaryPrimitives.ReadInt16LittleEndian(request.InputBuffer.Span.Slice(4));
+ _state.Z = System.Buffers.Binary.BinaryPrimitives.ReadInt16LittleEndian(request.InputBuffer.Span.Slice(6));
+ _state.Rx = System.Buffers.Binary.BinaryPrimitives.ReadInt16LittleEndian(request.InputBuffer.Span.Slice(8));
+ _state.Ry = System.Buffers.Binary.BinaryPrimitives.ReadInt16LittleEndian(request.InputBuffer.Span.Slice(10));
+ _state.Rz = System.Buffers.Binary.BinaryPrimitives.ReadInt16LittleEndian(request.InputBuffer.Span.Slice(12));
+ }
+ request.Complete(NtStatus.Success, size);
+ }
+ }
+ else
+ {
+ return base.HandleDeviceControlAsync(request, ct);
+ }
+ return Task.CompletedTask;
+ }
+}
diff --git a/samples/HidGamepad/README.md b/samples/HidGamepad/README.md
new file mode 100644
index 0000000..ecd5919
--- /dev/null
+++ b/samples/HidGamepad/README.md
@@ -0,0 +1,42 @@
+# HidGamepad sample
+
+A virtual 6-axis + 12-button HID gamepad. The report descriptor is emitted by
+the SDK's real USB HID item encoder (`HidReportDescriptorBuilder`), so the
+bytes are spec-compliant and can be validated by parsing them back — the tests
+do exactly that.
+
+## What it demonstrates
+
+- **Descriptor engineering** — `HidDescriptors.GamepadSixAxisTwelveButtons()`
+ builds the descriptor: report ID 1, 12 button bits + 4 padding bits, then
+ X/Y/Z/Rx/Ry/Rz as 16-bit logical axes. 15-byte input reports on the wire.
+- **Report packing** — `GamepadState` → `GamepadInputReport.Pack()` /
+ `Unpack()` round-trips, button-bit mapping included.
+- **Class descriptor** — the 9-byte HID class descriptor announces the report
+ descriptor length (bDescriptorType 0x21/0x22).
+- **State injection** — `GamepadIoctlCodes.UpdateState` (mask + six int16
+ axes) and `SetInputState` (full 15-byte report) simulate the physical
+ controls from the client side.
+- **Feature reports** — SetFeatureReport/GetFeatureReport echo, like real HID
+ devices.
+
+## Layout
+
+```
+Driver/SampleGamepadDriver.cs driver + device (extends HidDevice)
+manifest.json InfGen manifest → INF (HIDClass, UMDF)
+Tests/HidGamepadSampleTests.cs 7 tests: descriptor parse, reports, IOCTLs, INF
+```
+
+## Try it
+
+```bash
+dotnet test samples/HidGamepad/Tests
+infgen generate --manifest samples/HidGamepad/manifest.json
+```
+
+## Going further
+
+Read `docs/hid-guide.md` for the item encoding, the byte layout of the input
+report, and the two integration paths with the Windows HID stack (HidCx via a
+UMDF HID mini-driver, or the KMDF shim path).
diff --git a/samples/HidGamepad/Tests/HidGamepad.Tests.csproj b/samples/HidGamepad/Tests/HidGamepad.Tests.csproj
new file mode 100644
index 0000000..9804ea1
--- /dev/null
+++ b/samples/HidGamepad/Tests/HidGamepad.Tests.csproj
@@ -0,0 +1,20 @@
+
+
+
+ false
+ Unit tests for the HidGamepad sample driver — run anywhere with `dotnet test` (no Windows needed).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/HidGamepad/Tests/HidGamepadSampleTests.cs b/samples/HidGamepad/Tests/HidGamepadSampleTests.cs
new file mode 100644
index 0000000..424b60a
--- /dev/null
+++ b/samples/HidGamepad/Tests/HidGamepadSampleTests.cs
@@ -0,0 +1,176 @@
+using System.Buffers.Binary;
+using HidGamepad.Driver;
+using WindowsDriver.Sdk;
+using WindowsDriver.Sdk.Hid;
+using WindowsDriver.Testing;
+using WindowsDriver.InfGen;
+using Xunit;
+
+namespace HidGamepad.Tests;
+
+public class HidGamepadSampleTests
+{
+ private static async Task<(TestDriverHost Host, TestDevice Device)> StartHostAsync()
+ {
+ var host = TestDriverHost.Builder().UseFakeTime().Build();
+ await host.StartAsync("WdsHidGamepad");
+ var device = await host.AddDeviceAsync("ROOT\\CONTOSOVIRTUALGAMEPAD\\0000", "Root\\ContosoVirtualGamepad");
+ return (host, device);
+ }
+
+ [Fact]
+ public async Task Report_descriptor_is_valid_and_matches_the_report_layout()
+ {
+ var (host, device) = await StartHostAsync();
+
+ var descriptor = await device.SendIoctlAsync(HidIoctlCodes.GetReportDescriptor, outputSize: 512);
+ Check.Success(descriptor);
+ Assert.True(descriptor.BytesTransferred > 20, "descriptor looks too small");
+
+ var summary = HidReportDescriptorParser.Parse(descriptor.Output.AsSpan(0, descriptor.BytesTransferred));
+ Assert.True(summary.UsesReportIds);
+ var report = summary.Find(GamepadInputReport.ReportId);
+ Assert.NotNull(report);
+ Assert.Equal(12 + 4 + 6 * 16, report!.InputBits); // buttons + pad + 6 axes
+ Assert.Equal(GamepadInputReport.ReportSizeBytes, report.WireBytes(hasReportId: true));
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Class_descriptor_announces_report_descriptor_length()
+ {
+ var (host, device) = await StartHostAsync();
+
+ var classDescriptor = await device.SendIoctlAsync(HidIoctlCodes.GetDeviceDescriptor, outputSize: 64);
+ Check.Success(classDescriptor);
+ Check.Bytes(classDescriptor, HidDescriptor.HidDescriptorLength);
+ Assert.Equal(HidDescriptor.HidDescriptorType, classDescriptor.Output[1]);
+ Assert.Equal(0x11, classDescriptor.Output[2]); // bcdHID 1.11 = 0x0111 (LSB)
+ Assert.Equal(0x01, classDescriptor.Output[3]); // ...MSB
+
+ var size = await device.SendIoctlAsync(HidIoctlCodes.GetInputReportSize, outputSize: 2);
+ Check.Success(size);
+ Assert.Equal(GamepadInputReport.ReportSizeBytes, BinaryPrimitives.ReadUInt16LittleEndian(size.Output));
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Read_returns_the_current_input_report()
+ {
+ var (host, device) = await StartHostAsync();
+
+ var state = new GamepadState();
+ state.SetButtons(1, 4, 12);
+ state.X = -1234;
+ state.Rz = 32100;
+
+ var update = BuildUpdatePayload(state);
+ Check.Success(await device.SendIoctlAsync(GamepadIoctlCodes.UpdateState, update));
+
+ var report = await device.ReadAsync(GamepadInputReport.ReportSizeBytes);
+ Check.Success(report);
+ Check.Bytes(report, GamepadInputReport.ReportSizeBytes);
+ Assert.Equal(GamepadInputReport.ReportId, report.Output[0]);
+
+ var unpacked = GamepadInputReport.Unpack(report.Output.AsSpan(0, report.BytesTransferred));
+ Assert.True(unpacked[1]);
+ Assert.True(unpacked[4]);
+ Assert.True(unpacked[12]);
+ Assert.False(unpacked[2]);
+ Assert.Equal(-1234, unpacked.X);
+ Assert.Equal(32100, unpacked.Rz);
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task SetInputState_ioctl_replaces_the_whole_state()
+ {
+ var (host, device) = await StartHostAsync();
+
+ var raw = new byte[GamepadInputReport.ReportSizeBytes];
+ raw[0] = GamepadInputReport.ReportId;
+ BinaryPrimitives.WriteUInt16LittleEndian(raw.AsSpan(1), 0b0000_1100_0000_0011); // buttons 1,2,11,12
+ BinaryPrimitives.WriteInt16LittleEndian(raw.AsSpan(3), 500);
+
+ Check.Success(await device.SendIoctlAsync(GamepadIoctlCodes.SetInputState, raw));
+
+ var snapshot = ((SampleGamepadDevice)device.Device).State;
+ Assert.True(snapshot[1] && snapshot[2] && snapshot[11] && snapshot[12]);
+ Assert.False(snapshot[5]);
+ Assert.Equal(500, snapshot.X);
+
+ // Wrong-size input is rejected.
+ var bad = await device.SendIoctlAsync(GamepadIoctlCodes.SetInputState, new byte[7]);
+ Check.Status(bad, NtStatus.InvalidParameter);
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Feature_reports_echo_back()
+ {
+ var (host, device) = await StartHostAsync();
+
+ var feature = new byte[] { 0x05, 0x7F, 0x00, 0x99 };
+ Check.Success(await device.SendIoctlAsync(HidIoctlCodes.SetFeatureReport, feature));
+
+ var echoed = await device.SendIoctlAsync(HidIoctlCodes.GetFeatureReport, outputSize: feature.Length);
+ Check.Success(echoed);
+ Check.Bytes(echoed, feature.Length);
+ Assert.Equal(feature, echoed.Output.Take(feature.Length).ToArray());
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Short_output_buffers_get_buffer_too_small()
+ {
+ var (host, device) = await StartHostAsync();
+ var report = await device.ReadAsync(4); // needs 15 bytes
+ Check.Status(report, NtStatus.BufferTooSmall);
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public void Manifest_generates_a_valid_hid_inf()
+ {
+ var manifest = DriverManifest.FromJson(File.ReadAllText(FindManifest()));
+ var inf = new WindowsDriver.InfGen.InfGenerator(new DateOnly(2026, 11, 18)).Generate(manifest);
+
+ Assert.Contains("Class=HIDClass", inf);
+ Assert.Contains("{745a17a0-74d3-11d0-b6fe-00a0c90e91ab}", inf);
+
+ var issues = new WindowsDriver.InfGen.InfValidator().Validate(inf);
+ Assert.True(issues.Count == 0, "INF issues: " + string.Join("; ", issues.Select(i => $"[{i.Section}] {i.Message}")));
+ }
+
+ private static byte[] BuildUpdatePayload(GamepadState state)
+ {
+ var payload = new byte[2 + 6 * sizeof(short)];
+ ushort buttons = 0;
+ for (var b = 1; b <= GamepadState.ButtonCount; b++)
+ {
+ if (state[b])
+ {
+ buttons |= (ushort)(1 << (b - 1));
+ }
+ }
+ BinaryPrimitives.WriteUInt16LittleEndian(payload, buttons);
+ BinaryPrimitives.WriteInt16LittleEndian(payload.AsSpan(2), state.X);
+ BinaryPrimitives.WriteInt16LittleEndian(payload.AsSpan(4), state.Y);
+ BinaryPrimitives.WriteInt16LittleEndian(payload.AsSpan(6), state.Z);
+ BinaryPrimitives.WriteInt16LittleEndian(payload.AsSpan(8), state.Rx);
+ BinaryPrimitives.WriteInt16LittleEndian(payload.AsSpan(10), state.Ry);
+ BinaryPrimitives.WriteInt16LittleEndian(payload.AsSpan(12), state.Rz);
+ return payload;
+ }
+
+ private static string FindManifest()
+ {
+ var path = Path.Combine(AppContext.BaseDirectory, "../../../../manifest.json");
+ return File.Exists(path) ? path : Path.Combine(Directory.GetCurrentDirectory(), "manifest.json");
+ }
+}
diff --git a/samples/HidGamepad/manifest.json b/samples/HidGamepad/manifest.json
new file mode 100644
index 0000000..342a8ec
--- /dev/null
+++ b/samples/HidGamepad/manifest.json
@@ -0,0 +1,22 @@
+{
+ "name": "HidGamepad",
+ "provider": "Contoso Devices",
+ "manufacturer": "Contoso Devices LLC",
+ "version": "0.1.0",
+ "class": "HIDClass",
+ "classGuid": "{745a17a0-74d3-11d0-b6fe-00a0c90e91ab}",
+ "framework": "umdf",
+ "serviceName": "WdsHidGamepad",
+ "catalogFile": "HidGamepad.cat",
+ "files": [
+ { "source": "HidGamepad.Driver.dll" }
+ ],
+ "models": [
+ {
+ "name": "Contoso Virtual Gamepad (SDK sample)",
+ "hardwareIds": ["Root\\ContosoVirtualGamepad"],
+ "compatibleIds": ["*WdsHidGamepad"]
+ }
+ ],
+ "wdfLibraryVersion": "2.15.0"
+}
diff --git a/samples/VirtualAudio/Driver/SampleAudioDriver.cs b/samples/VirtualAudio/Driver/SampleAudioDriver.cs
new file mode 100644
index 0000000..12b6ca5
--- /dev/null
+++ b/samples/VirtualAudio/Driver/SampleAudioDriver.cs
@@ -0,0 +1,122 @@
+using WindowsDriver.Sdk;
+using WindowsDriver.Sdk.Audio;
+
+namespace VirtualAudio.Driver;
+
+/// Sample-specific IOCTLs layered on top of the audio contract.
+public static class SampleAudioIoctlCodes
+{
+ /// Out: f32 tone frequency (Hz).
+ public static readonly uint GetToneFrequency = WinIoctl.VendorControlCode(0x900, WinIoctl.FileAccessRead);
+
+ /// In: f32 tone frequency (Hz), 20..20000.
+ public static readonly uint SetToneFrequency = WinIoctl.VendorControlCode(0x901, WinIoctl.FileAccessWrite);
+}
+
+///
+/// Sample driver: installs one virtual audio device per enumerated devnode.
+/// The device is a with a sine source plus one
+/// extra IOCTL pair (tone frequency) demonstrating how to extend the SDK contract.
+///
+public sealed class SampleAudioDriver : DriverBase
+{
+ public override Task OnDriverEntryAsync(DriverContext context, CancellationToken cancellationToken)
+ {
+ context.Log.Info("sample audio driver entering (service '{0}')", context.DriverServiceName);
+ context.DriverProperties.Set(KnownDeviceProperties.Manufacturer, "Contoso Devices");
+ return Task.CompletedTask;
+ }
+
+ public override Task OnDeviceAddAsync(DeviceAddContext addContext, DeviceContext deviceContext, CancellationToken cancellationToken)
+ {
+ deviceContext.Log.Info("device add: {0} (hardware ids: {1})",
+ addContext.DeviceInstanceId, string.Join(", ", addContext.HardwareIds));
+
+ var device = new SampleAudioDevice(deviceContext, new AudioVirtualOptions
+ {
+ Mode = AudioVirtualMode.Capture,
+ Source = new SineSource(frequencyHz: 440.0, amplitude: 0.25),
+ // ~5 s of 48 kHz stereo 16-bit — enough to buffer a full second without drops.
+ RingBufferBytes = 1_000_000,
+ SupportedFormats =
+ [
+ new PcmFormat(44100, 16, 2),
+ new PcmFormat(48000, 16, 2),
+ new PcmFormat(96000, 16, 2),
+ ],
+ });
+
+ // A device interface lets applications find and open the device.
+ deviceContext.CreateDeviceInterface(new Guid("C4B9E4AF-E85A-4F03-B3B4-EB2E6BCF862B"));
+ return Task.FromResult(device);
+ }
+
+ public override Task OnDriverUnloadAsync()
+ {
+ Context?.Log.Info("sample audio driver unloading");
+ return Task.CompletedTask;
+ }
+}
+
+/// Virtual audio device with a sample-specific tone-frequency IOCTL.
+public sealed class SampleAudioDevice : VirtualAudioDevice
+{
+ private SineSource ToneSource { get; }
+
+ public SampleAudioDevice(DeviceContext context, AudioVirtualOptions options)
+ : base(context, options)
+ {
+ if (options.Source is not SineSource sine)
+ {
+ throw new ArgumentException("SampleAudioDevice requires a SineSource.", nameof(options));
+ }
+ ToneSource = sine;
+ Context.Properties.Set(KnownDeviceProperties.FriendlyName, "Contoso Virtual Audio (SDK sample)");
+ }
+
+ /// Frequency the device's sine source is currently generating.
+ public double ToneFrequency => ToneSource.FrequencyHz;
+
+ protected override Task HandleDeviceControlAsync(IoRequest request, CancellationToken ct)
+ {
+ var code = request.IoControlCode;
+ if (code == SampleAudioIoctlCodes.GetToneFrequency)
+ {
+ if (request.OutputBuffer.Length < sizeof(float))
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ WireFormat.WriteFloat(request.OutputBuffer.Span, 0, (float)ToneSource.FrequencyHz);
+ request.Complete(NtStatus.Success, sizeof(float));
+ }
+ }
+ else if (code == SampleAudioIoctlCodes.SetToneFrequency)
+ {
+ if (request.InputBuffer.Length < sizeof(float))
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ var frequency = WireFormat.ReadFloat(request.InputBuffer.Span, 0);
+ if (frequency is < 20f or > 20000f)
+ {
+ request.Fail(NtStatus.InvalidParameter);
+ }
+ else
+ {
+ ToneSource.FrequencyHz = frequency;
+ Context.Log.Info("tone frequency set to {0} Hz", frequency);
+ request.Complete(NtStatus.Success);
+ }
+ }
+ }
+ else
+ {
+ return base.HandleDeviceControlAsync(request, ct);
+ }
+ return Task.CompletedTask;
+ }
+}
diff --git a/samples/VirtualAudio/Driver/VirtualAudio.Driver.csproj b/samples/VirtualAudio/Driver/VirtualAudio.Driver.csproj
new file mode 100644
index 0000000..a4af034
--- /dev/null
+++ b/samples/VirtualAudio/Driver/VirtualAudio.Driver.csproj
@@ -0,0 +1,13 @@
+
+
+
+ VirtualAudio.Driver
+ Sample: virtual audio device (PCM ring buffer, format negotiation, volume, IOCTL contract) built on WindowsDriver.Sdk.
+
+
+
+
+
+
+
+
diff --git a/samples/VirtualAudio/README.md b/samples/VirtualAudio/README.md
new file mode 100644
index 0000000..1892da6
--- /dev/null
+++ b/samples/VirtualAudio/README.md
@@ -0,0 +1,46 @@
+# VirtualAudio sample
+
+A complete virtual audio device in C#: PCM format negotiation, a ring buffer
+standing in for the hardware DMA engine, a start/pause/stop state machine,
+volume with ramps and mute, and the `AudioIoctlCodes` IOCTL contract — plus one
+sample-specific IOCTL pair (tone frequency) showing how to extend the contract.
+
+## What it demonstrates
+
+- **Driver entry** — `SampleAudioDriver : DriverBase` creates one
+ `SampleAudioDevice : VirtualAudioDevice` per enumerated devnode and registers
+ a device interface.
+- **Format negotiation** — `AudioFormatNegotiator` picks the closest supported
+ format for a client request (48 kHz requested while running 44.1 kHz? →
+ 44.1 kHz).
+- **Time-driven audio** — the device's byte position advances with the host
+ `TimeProvider` while Running, exactly like a real render/capture clock. The
+ `SineSource` fills the ring buffer on demand; the tests advance the fake
+ clock and read deterministic PCM.
+- **Volume** — master gain, per-channel gains, mute, and linear ramps; gain is
+ applied to 16-bit samples on the output path.
+- **Extensibility** — `SampleAudioDevice` overrides
+ `HandleDeviceControlAsync`, handles its own IOCTLs and delegates the rest to
+ the base contract.
+
+## Layout
+
+```
+Driver/SampleAudioDriver.cs driver + device (extends VirtualAudioDevice)
+manifest.json InfGen manifest → INF (Media class, UMDF)
+Tests/AudioSampleTests.cs 9 tests: negotiation, position, volume, IOCTLs, INF
+```
+
+## Try it
+
+```bash
+dotnet test samples/VirtualAudio/Tests # runs everywhere, no Windows needed
+infgen generate --manifest samples/VirtualAudio/manifest.json
+```
+
+## Going further
+
+- Read `docs/audio-guide.md` for the Windows audio stack mapping (PortCls /
+ AVStream / AudioGraph loopback) and what changes in production.
+- Swap `SineSource` for a custom `IAudioSource` (microphone emulation, network
+ stream) — the device, contract and tests stay the same.
diff --git a/samples/VirtualAudio/Tests/AudioSampleTests.cs b/samples/VirtualAudio/Tests/AudioSampleTests.cs
new file mode 100644
index 0000000..edf86f7
--- /dev/null
+++ b/samples/VirtualAudio/Tests/AudioSampleTests.cs
@@ -0,0 +1,234 @@
+using System.Buffers.Binary;
+using VirtualAudio.Driver;
+using WindowsDriver.Sdk;
+using WindowsDriver.Sdk.Audio;
+using WindowsDriver.Testing;
+using WindowsDriver.InfGen;
+using Xunit;
+
+namespace VirtualAudio.Tests;
+
+public class VirtualAudioSampleTests
+{
+ private static async Task<(TestDriverHost Host, TestDevice Device)> StartHostAsync()
+ {
+ var host = TestDriverHost.Builder().UseFakeTime().Build();
+ await host.StartAsync("WdsVirtualAudio");
+ var device = await host.AddDeviceAsync(
+ "ROOT\\CONTOSOVIRTUALAUDIO\\0000",
+ "Root\\ContosoVirtualAudio");
+ return (host, device);
+ }
+
+ private static byte[] PackFormat(PcmFormat format)
+ {
+ var data = new byte[12];
+ BinaryPrimitives.WriteUInt32LittleEndian(data, (uint)format.SampleRateHz);
+ BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(4), (uint)format.BitsPerSample);
+ BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(8), (uint)format.Channels);
+ return data;
+ }
+
+ private static PcmFormat ReadFormat(byte[] data) => new(
+ (int)BinaryPrimitives.ReadUInt32LittleEndian(data),
+ (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(4)),
+ (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8)));
+
+ [Fact]
+ public async Task Device_boots_and_reports_default_format()
+ {
+ var (host, device) = await StartHostAsync();
+
+ var result = await device.SendIoctlAsync(AudioIoctlCodes.GetFormat, outputSize: 12);
+ Check.Success(result);
+ Check.Bytes(result, 12);
+ Assert.Equal(new PcmFormat(44100, 16, 2), ReadFormat(result.Output));
+
+ Assert.Single(device.Context.DeviceInterfaces);
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Format_negotiation_adjusts_unsupported_requests()
+ {
+ var (host, device) = await StartHostAsync();
+
+ // 48000 is supported exactly.
+ var exact = await device.SendIoctlAsync(AudioIoctlCodes.SetFormat, PackFormat(new PcmFormat(48000, 16, 2)), 12);
+ Check.Success(exact);
+
+ // 22050 is not supported: the negotiator picks 44100 and reports the adjusted format.
+ var adjusted = await device.SendIoctlAsync(AudioIoctlCodes.SetFormat, PackFormat(new PcmFormat(22050, 16, 2)), 12);
+ Check.Success(adjusted);
+ Assert.Equal(44100, ReadFormat(adjusted.Output).SampleRateHz);
+
+ // Zero rate is invalid.
+ var invalid = await device.SendIoctlAsync(AudioIoctlCodes.SetFormat, PackFormat(new PcmFormat(0, 16, 2)));
+ Check.Status(invalid, NtStatus.InvalidParameter);
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Format_cannot_change_while_running()
+ {
+ var (host, device) = await StartHostAsync();
+ await device.SendIoctlAsync(AudioIoctlCodes.Start);
+
+ var result = await device.SendIoctlAsync(AudioIoctlCodes.SetFormat, PackFormat(new PcmFormat(96000, 16, 2)));
+ Check.Status(result, NtStatus.InvalidDeviceState);
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Position_advances_with_the_fake_clock_and_reads_produce_sine()
+ {
+ var (host, device) = await StartHostAsync();
+
+ // Switch to 48000 Hz then start.
+ await device.SendIoctlAsync(AudioIoctlCodes.SetFormat, PackFormat(new PcmFormat(48000, 16, 2)));
+ await device.SendIoctlAsync(AudioIoctlCodes.Start);
+
+ host.FakeTime!.Advance(TimeSpan.FromSeconds(1));
+
+ var position = await device.SendIoctlAsync(AudioIoctlCodes.GetPosition, outputSize: 20);
+ Check.Success(position);
+ Check.Bytes(position, 20);
+ var bytePosition = BinaryPrimitives.ReadUInt64LittleEndian(position.Output);
+ var framePosition = BinaryPrimitives.ReadUInt64LittleEndian(position.Output.AsSpan(8));
+ Assert.Equal(48000ul, framePosition);
+ Assert.Equal(48000ul * 2ul * (ulong)sizeof(short), bytePosition);
+
+ // Read 0.5 seconds of audio: 24000 frames × 4 bytes = 96000 bytes.
+ var audio = await device.ReadAsync(96000);
+ Check.Success(audio);
+ Check.Bytes(audio, 96000);
+
+ // Signal is a real sine: some peaks well above zero, nothing clipping, channels equal (stereo dupe).
+ short peak = 0;
+ for (var i = 0; i + 2 <= audio.BytesTransferred; i += 2)
+ {
+ var sample = BinaryPrimitives.ReadInt16LittleEndian(audio.Output.AsSpan(i));
+ peak = Math.Max(peak, Math.Abs(sample));
+ }
+ Assert.InRange(peak, 5000, (short)(0.25 * short.MaxValue + 2)); // amp 0.25
+
+ // Stopping must not change the position, and reads still work (buffer content).
+ await device.SendIoctlAsync(AudioIoctlCodes.Stop);
+ var afterStop = await device.SendIoctlAsync(AudioIoctlCodes.GetPosition, outputSize: 20);
+ Assert.Equal(framePosition, BinaryPrimitives.ReadUInt64LittleEndian(afterStop.Output.AsSpan(8)));
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Volume_gain_applies_to_output()
+ {
+ var (host, device) = await StartHostAsync();
+ await device.SendIoctlAsync(AudioIoctlCodes.SetFormat, PackFormat(new PcmFormat(48000, 16, 2)));
+ await device.SendIoctlAsync(AudioIoctlCodes.Start);
+ host.FakeTime!.Advance(TimeSpan.FromMilliseconds(500));
+
+ var full = await ReadPeak(device);
+ Assert.True(full > 5000, $"expected audible signal, peak={full}");
+
+ // Set master gain to 0.5, mute off, no ramp, master-only.
+ var volume = new byte[17];
+ BinaryPrimitives.WriteSingleLittleEndian(volume.AsSpan(0), 0.5f);
+ volume[8] = 0; // not muted
+ BinaryPrimitives.WriteUInt32LittleEndian(volume.AsSpan(9), 0); // rampMs
+ BinaryPrimitives.WriteUInt32LittleEndian(volume.AsSpan(13), 0); // channelCount
+ await device.SendIoctlAsync(AudioIoctlCodes.SetVolume, volume);
+
+ host.FakeTime.Advance(TimeSpan.FromMilliseconds(500));
+ var halved = await ReadPeak(device);
+ Assert.InRange(halved, full * 4 / 10, full * 6 / 10);
+
+ // Mute produces silence.
+ volume[8] = 1;
+ await device.SendIoctlAsync(AudioIoctlCodes.SetVolume, volume);
+ host.FakeTime.Advance(TimeSpan.FromMilliseconds(500));
+ Assert.Equal(0, await ReadPeak(device));
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Supported_formats_ioctl_lists_the_catalog()
+ {
+ var (host, device) = await StartHostAsync();
+ var result = await device.SendIoctlAsync(AudioIoctlCodes.GetSupportedFormats, outputSize: 4 + 3 * 12);
+ Check.Success(result);
+ Check.Bytes(result, 4 + 3 * 12);
+ Assert.Equal(3u, BinaryPrimitives.ReadUInt32LittleEndian(result.Output));
+ Assert.Equal(44100u, BinaryPrimitives.ReadUInt32LittleEndian(result.Output.AsSpan(4)));
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Sample_specific_ioctl_extends_the_contract()
+ {
+ var (host, device) = await StartHostAsync();
+
+ var get = await device.SendIoctlAsync(SampleAudioIoctlCodes.GetToneFrequency, outputSize: sizeof(float));
+ Check.Success(get);
+ Assert.Equal(440f, BinaryPrimitives.ReadSingleLittleEndian(get.Output));
+
+ var set = new byte[4];
+ BinaryPrimitives.WriteSingleLittleEndian(set, 1000f);
+ Check.Success(await device.SendIoctlAsync(SampleAudioIoctlCodes.SetToneFrequency, set));
+
+ var after = await device.SendIoctlAsync(SampleAudioIoctlCodes.GetToneFrequency, outputSize: sizeof(float));
+ Assert.Equal(1000f, BinaryPrimitives.ReadSingleLittleEndian(after.Output));
+
+ BinaryPrimitives.WriteSingleLittleEndian(set, 0f); // below 20 Hz
+ var bad = await device.SendIoctlAsync(SampleAudioIoctlCodes.SetToneFrequency, set);
+ Check.Status(bad, NtStatus.InvalidParameter);
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Unknown_ioctl_rejects_with_invalid_device_request()
+ {
+ var (host, device) = await StartHostAsync();
+ var result = await device.SendIoctlAsync(WinIoctl.CtlCode(WinIoctl.FileDeviceSound, 0x799, WinIoctl.MethodBuffered, WinIoctl.FileAccessAny));
+ Check.Status(result, NtStatus.InvalidDeviceRequest);
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public void Manifest_generates_a_valid_inf()
+ {
+ var manifestPath = FindManifest();
+ var manifest = DriverManifest.FromJson(File.ReadAllText(manifestPath));
+ var inf = new WindowsDriver.InfGen.InfGenerator(new DateOnly(2026, 11, 18)).Generate(manifest);
+
+ Assert.Contains("Class=Media", inf);
+ Assert.Contains("UmdfService=WdsVirtualAudio", inf);
+ Assert.Contains(@"Root\ContosoVirtualAudio", inf);
+
+ var issues = new WindowsDriver.InfGen.InfValidator().Validate(inf);
+ Assert.True(issues.Count == 0, "INF issues: " + string.Join("; ", issues.Select(i => $"[{i.Section}] {i.Message}")));
+ }
+
+ private static async Task ReadPeak(TestDevice device)
+ {
+ var audio = await device.ReadAsync(9600);
+ Check.Success(audio);
+ short peak = 0;
+ for (var i = 0; i + 2 <= audio.BytesTransferred; i += 2)
+ {
+ var sample = BinaryPrimitives.ReadInt16LittleEndian(audio.Output.AsSpan(i));
+ peak = Math.Max(peak, Math.Abs(sample));
+ }
+ return peak;
+ }
+
+ private static string FindManifest()
+ {
+ var path = Path.Combine(AppContext.BaseDirectory, "../../../../manifest.json");
+ return File.Exists(path) ? path : Path.Combine(Directory.GetCurrentDirectory(), "manifest.json");
+ }
+}
diff --git a/samples/VirtualAudio/Tests/VirtualAudio.Tests.csproj b/samples/VirtualAudio/Tests/VirtualAudio.Tests.csproj
new file mode 100644
index 0000000..d063336
--- /dev/null
+++ b/samples/VirtualAudio/Tests/VirtualAudio.Tests.csproj
@@ -0,0 +1,20 @@
+
+
+
+ false
+ Unit tests for the VirtualAudio sample driver — run anywhere with `dotnet test` (no Windows needed).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/VirtualAudio/manifest.json b/samples/VirtualAudio/manifest.json
new file mode 100644
index 0000000..b8c9a7e
--- /dev/null
+++ b/samples/VirtualAudio/manifest.json
@@ -0,0 +1,22 @@
+{
+ "name": "VirtualAudio",
+ "provider": "Contoso Devices",
+ "manufacturer": "Contoso Devices LLC",
+ "version": "0.1.0",
+ "class": "Media",
+ "classGuid": "{4d36e96c-e325-11ce-bfc1-08002be10318}",
+ "framework": "umdf",
+ "serviceName": "WdsVirtualAudio",
+ "catalogFile": "VirtualAudio.cat",
+ "files": [
+ { "source": "VirtualAudio.Driver.dll" }
+ ],
+ "models": [
+ {
+ "name": "Contoso Virtual Audio Device (SDK sample)",
+ "hardwareIds": ["Root\\ContosoVirtualAudio"],
+ "compatibleIds": ["*WdsVirtualAudio"]
+ }
+ ],
+ "wdfLibraryVersion": "2.15.0"
+}
diff --git a/samples/VirtualSensor/Driver/SampleSensorDriver.cs b/samples/VirtualSensor/Driver/SampleSensorDriver.cs
new file mode 100644
index 0000000..a0be00b
--- /dev/null
+++ b/samples/VirtualSensor/Driver/SampleSensorDriver.cs
@@ -0,0 +1,105 @@
+using System.Buffers.Binary;
+using WindowsDriver.Sdk;
+using WindowsDriver.Sdk.Sensor;
+
+namespace VirtualSensor.Driver;
+
+/// Sample-specific IOCTLs.
+public static class SensorSampleIoctlCodes
+{
+ /// In: (u8 enable, f64 lux) — overrides the ambient-light simulation.
+ public static readonly uint SetAmbientOverride = WinIoctl.VendorControlCode(0x900, WinIoctl.FileAccessWrite);
+
+ /// In: (f64 dx, f64 dy, f64 dz, u32 durationMs) — injects a shake impulse.
+ public static readonly uint InjectImpulse = WinIoctl.VendorControlCode(0x901, WinIoctl.FileAccessWrite);
+}
+
+///
+/// Sample driver: one device hosting a 3-axis accelerometer and an ambient
+/// light sensor, both deterministic simulators from the SDK.
+///
+public sealed class SampleSensorDriver : DriverBase
+{
+ public override Task OnDeviceAddAsync(DeviceAddContext addContext, DeviceContext deviceContext, CancellationToken cancellationToken)
+ {
+ deviceContext.Properties.Set(KnownDeviceProperties.FriendlyName, "Contoso Virtual Sensor Suite (SDK sample)");
+ deviceContext.Properties.Set(KnownDeviceProperties.Manufacturer, "Contoso Devices");
+
+ var accelerometer = new AccelerometerSimulator(seed: 42, sampleRateHz: 50);
+ var ambientLight = new AmbientLightSimulator(seed: 7, sampleRateHz: 4);
+
+ var device = new SampleSensorDevice(deviceContext, new SensorDeviceOptions
+ {
+ Sources = [accelerometer, ambientLight],
+ });
+ deviceContext.CreateDeviceInterface(new Guid("7B1E3D6C-9E30-4A5E-9A6B-2D8C7F5A0B41"));
+ return Task.FromResult(device);
+ }
+}
+
+/// Sensor device extended with sample-specific simulation IOCTLs.
+public sealed class SampleSensorDevice : SensorDevice
+{
+ public SampleSensorDevice(DeviceContext context, SensorDeviceOptions options)
+ : base(context, options)
+ {
+ }
+
+ protected override Task HandleDeviceControlAsync(IoRequest request, CancellationToken ct)
+ {
+ var code = request.IoControlCode;
+ if (code == SensorSampleIoctlCodes.SetAmbientOverride)
+ {
+ var size = sizeof(byte) + sizeof(double);
+ if (request.InputBuffer.Length < size)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ var enable = request.InputBuffer.Span[0] != 0;
+ var lux = BinaryPrimitives.ReadDoubleLittleEndian(request.InputBuffer.Span.Slice(1));
+ if (enable && (lux < 0 || lux > 200_000))
+ {
+ request.Fail(NtStatus.InvalidParameter);
+ }
+ else
+ {
+ if (GetSource(1) is AmbientLightSimulator als)
+ {
+ als.OverrideLux = enable ? lux : null;
+ Context.Log.Info("ambient override {0} ({1} lux)", enable ? "on" : "off", enable ? lux : 0);
+ }
+ request.Complete(NtStatus.Success, size);
+ }
+ }
+ }
+ else if (code == SensorSampleIoctlCodes.InjectImpulse)
+ {
+ var size = 3 * sizeof(double) + sizeof(uint);
+ if (request.InputBuffer.Length < size)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else if (GetSource(0) is not AccelerometerSimulator accelerometer)
+ {
+ request.Fail(NtStatus.DeviceNotReady);
+ }
+ else
+ {
+ var dx = BinaryPrimitives.ReadDoubleLittleEndian(request.InputBuffer.Span);
+ var dy = BinaryPrimitives.ReadDoubleLittleEndian(request.InputBuffer.Span.Slice(8));
+ var dz = BinaryPrimitives.ReadDoubleLittleEndian(request.InputBuffer.Span.Slice(16));
+ var durationMs = BinaryPrimitives.ReadUInt32LittleEndian(request.InputBuffer.Span.Slice(24));
+ accelerometer.AddImpulse(Driver.TimeProvider.GetUtcNow().TimeOfDay, TimeSpan.FromMilliseconds(durationMs), (dx, dy, dz));
+ Context.Log.Info("impulse injected: ({0}, {1}, {2}) m/s^2 for {3} ms", dx, dy, dz, durationMs);
+ request.Complete(NtStatus.Success, size);
+ }
+ }
+ else
+ {
+ return base.HandleDeviceControlAsync(request, ct);
+ }
+ return Task.CompletedTask;
+ }
+}
diff --git a/samples/VirtualSensor/Driver/VirtualSensor.Driver.csproj b/samples/VirtualSensor/Driver/VirtualSensor.Driver.csproj
new file mode 100644
index 0000000..2a52a0d
--- /dev/null
+++ b/samples/VirtualSensor/Driver/VirtualSensor.Driver.csproj
@@ -0,0 +1,13 @@
+
+
+
+ VirtualSensor.Driver
+ Sample: virtual sensor device (3-axis accelerometer + ambient light simulator, IOCTL + event queue) built on WindowsDriver.Sdk.
+
+
+
+
+
+
+
+
diff --git a/samples/VirtualSensor/README.md b/samples/VirtualSensor/README.md
new file mode 100644
index 0000000..c8e0920
--- /dev/null
+++ b/samples/VirtualSensor/README.md
@@ -0,0 +1,42 @@
+# VirtualSensor sample
+
+A sensor suite device: a 3-axis accelerometer and an ambient light sensor, both
+driven by deterministic simulators from the SDK, published over an IOCTL
+contract and an event queue.
+
+## What it demonstrates
+
+- **Pure-function simulation** — `AccelerometerSimulator` (gravity on +Z,
+ smooth seeded noise, transient impulses) and `AmbientLightSimulator` (indoor
+ baseline + day cycle + flicker) are functions of the timestamp, so tests are
+ fully reproducible.
+- **Polling and push** — clients poll `SensorIoctlCodes.GetLatestReading`, or
+ subscribe to `SensorDevice.Readings` (a bounded channel with drop-oldest
+ semantics, like a real sensor event queue).
+- **Background sampling** — while in D0 the device samples at the fastest
+ sensor rate using `Task.Delay(interval, TimeProvider)`, so a fake clock can
+ drive it in tests.
+- **Extensibility** — `SampleSensorDevice` adds `SetAmbientOverride` (force a
+ lux value, e.g. simulating a lamp) and `InjectImpulse` (a shake) on top of
+ the sensor contract.
+
+## Layout
+
+```
+Driver/SampleSensorDriver.cs driver + device (extends SensorDevice)
+manifest.json InfGen manifest → INF (Sensor class, UMDF)
+Tests/SensorSampleTests.cs 6 tests: sensors, determinism, IOCTLs, events, INF
+```
+
+## Try it
+
+```bash
+dotnet test samples/VirtualSensor/Tests
+infgen generate --manifest samples/VirtualSensor/manifest.json
+```
+
+## Going further
+
+Read `docs/sensor-guide.md` for the SensorCx (sensor class extension) mapping —
+real Windows sensor drivers register with SensorCx and report through the
+Windows Sensor API; the simulators and the IOCTL contract stay the same.
diff --git a/samples/VirtualSensor/Tests/SensorSampleTests.cs b/samples/VirtualSensor/Tests/SensorSampleTests.cs
new file mode 100644
index 0000000..3f5e8c3
--- /dev/null
+++ b/samples/VirtualSensor/Tests/SensorSampleTests.cs
@@ -0,0 +1,179 @@
+using System.Buffers.Binary;
+using VirtualSensor.Driver;
+using WindowsDriver.Sdk;
+using WindowsDriver.Sdk.Sensor;
+using WindowsDriver.Testing;
+using WindowsDriver.InfGen;
+using Xunit;
+
+namespace VirtualSensor.Tests;
+
+public class VirtualSensorSampleTests
+{
+ private static async Task<(TestDriverHost Host, TestDevice Device)> StartHostAsync()
+ {
+ var host = TestDriverHost.Builder().UseFakeTime().Build();
+ await host.StartAsync("WdsVirtualSensor");
+ var device = await host.AddDeviceAsync("ROOT\\CONTOSOVIRTUALSENSOR\\0000", "Root\\ContosoVirtualSensor");
+ return (host, device);
+ }
+
+ [Fact]
+ public async Task Device_reports_two_sensors()
+ {
+ var (host, device) = await StartHostAsync();
+
+ var count = await device.SendIoctlAsync(SensorIoctlCodes.GetSensorCount, outputSize: sizeof(uint));
+ Check.Success(count);
+ Assert.Equal(2u, BinaryPrimitives.ReadUInt32LittleEndian(count.Output));
+
+ var info = await device.SendIoctlAsync(SensorIoctlCodes.GetSensorInfo, PackUInt(0), outputSize: 28);
+ Check.Success(info);
+ Assert.Equal((uint)SensorKind.Accelerometer3D, BinaryPrimitives.ReadUInt32LittleEndian(info.Output));
+ Assert.Equal(3u, BinaryPrimitives.ReadUInt32LittleEndian(info.Output.AsSpan(4)));
+ Assert.Equal(50000u, BinaryPrimitives.ReadUInt32LittleEndian(info.Output.AsSpan(8))); // 50 Hz in milliHz
+
+ var als = await device.SendIoctlAsync(SensorIoctlCodes.GetSensorInfo, PackUInt(1), outputSize: 28);
+ Assert.Equal((uint)SensorKind.AmbientLight, BinaryPrimitives.ReadUInt32LittleEndian(als.Output));
+
+ var outOfRange = await device.SendIoctlAsync(SensorIoctlCodes.GetSensorInfo, PackUInt(5), outputSize: 28);
+ Check.Status(outOfRange, NtStatus.InvalidParameter);
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Readings_are_deterministic_and_gravity_is_present()
+ {
+ var (host, device) = await StartHostAsync();
+ var sensorDevice = (SampleSensorDevice)device.Device;
+
+ // Before sampling, latest readings are absent.
+ var none = await device.SendIoctlAsync(SensorIoctlCodes.GetLatestReading, PackUInt(0));
+ Check.Status(none, NtStatus.DeviceNotReady);
+
+ sensorDevice.SampleOnce();
+ var reading = sensorDevice.LatestReading(0)!;
+ Assert.Equal(3, reading.Values.Count);
+ Assert.Equal("m/s^2", reading.Unit);
+ // Device lies flat: Z ≈ +9.8, X/Y near zero.
+ Assert.InRange(reading.Values[2], 9.0, 10.6);
+ Assert.InRange(reading.Values[0], -0.5, 0.5);
+ Assert.InRange(reading.Values[1], -0.5, 0.5);
+
+ // Same timestamp → identical values (pure function of time).
+ var again = ((AccelerometerSimulator)sensorDevice.GetSource(0)).Sample(reading.Timestamp);
+ Assert.Equal(reading.Values, again.Values);
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task GetLatestReading_ioctl_returns_the_sampled_values()
+ {
+ var (host, device) = await StartHostAsync();
+ var sensorDevice = (SampleSensorDevice)device.Device;
+
+ host.FakeTime!.Advance(TimeSpan.FromMinutes(3));
+ sensorDevice.SampleOnce();
+
+ var result = await device.SendIoctlAsync(SensorIoctlCodes.GetLatestReading, PackUInt(1), outputSize: 8 + 4 + 8);
+ Check.Success(result);
+ Check.Bytes(result, 20);
+ var valueCount = BinaryPrimitives.ReadUInt32LittleEndian(result.Output.AsSpan(8));
+ Assert.Equal(1u, valueCount);
+ var lux = BinaryPrimitives.ReadDoubleLittleEndian(result.Output.AsSpan(12));
+ // 3 minutes past fake midnight → no daylight, indoor baseline.
+ Assert.InRange(lux, 300, 500);
+
+ // Timestamp is the fake clock's.
+ var ticks = BinaryPrimitives.ReadUInt64LittleEndian(result.Output);
+ var timestamp = new DateTimeOffset((long)ticks, TimeSpan.Zero);
+ Assert.Equal(host.FakeTime.GetUtcNow().UtcTicks, timestamp.UtcTicks);
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Sample_specific_ioctls_control_the_simulation()
+ {
+ var (host, device) = await StartHostAsync();
+ var sensorDevice = (SampleSensorDevice)device.Device;
+
+ // ALS override: force 12345 lux.
+ var overridePayload = new byte[1 + sizeof(double)];
+ overridePayload[0] = 1;
+ BinaryPrimitives.WriteDoubleLittleEndian(overridePayload.AsSpan(1), 12345);
+ Check.Success(await device.SendIoctlAsync(SensorSampleIoctlCodes.SetAmbientOverride, overridePayload));
+
+ sensorDevice.SampleOnce();
+ Assert.Equal(12345, sensorDevice.LatestReading(1)!.Values[0], precision: 3);
+
+ // Disable override → back to simulation.
+ overridePayload[0] = 0;
+ await device.SendIoctlAsync(SensorSampleIoctlCodes.SetAmbientOverride, overridePayload);
+ sensorDevice.SampleOnce();
+ Assert.True(sensorDevice.LatestReading(1)!.Values[0] < 1000, "override did not clear");
+
+ // Invalid override value.
+ overridePayload[0] = 1;
+ BinaryPrimitives.WriteDoubleLittleEndian(overridePayload.AsSpan(1), -5);
+ var bad = await device.SendIoctlAsync(SensorSampleIoctlCodes.SetAmbientOverride, overridePayload);
+ Check.Status(bad, NtStatus.InvalidParameter);
+
+ // Impulse on the accelerometer.
+ var impulse = new byte[3 * sizeof(double) + sizeof(uint)];
+ BinaryPrimitives.WriteDoubleLittleEndian(impulse.AsSpan(0), 30);
+ BinaryPrimitives.WriteUInt32LittleEndian(impulse.AsSpan(24), 400);
+ Check.Success(await device.SendIoctlAsync(SensorSampleIoctlCodes.InjectImpulse, impulse));
+
+ // The impulse ramps up linearly — sample mid-way through the 400 ms window.
+ host.FakeTime!.Advance(TimeSpan.FromMilliseconds(200));
+ sensorDevice.SampleOnce();
+ var shaken = sensorDevice.LatestReading(0)!.Values;
+ Assert.True(shaken[0] > 5, $"impulse not visible: X={shaken[0]}");
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Event_queue_receives_sampled_readings()
+ {
+ var (host, device) = await StartHostAsync();
+ var sensorDevice = (SampleSensorDevice)device.Device;
+
+ sensorDevice.SampleOnce();
+ sensorDevice.SampleOnce();
+
+ var first = await sensorDevice.Readings.ReadAsync(new CancellationTokenSource(TimeSpan.FromSeconds(1)).Token);
+ var second = await sensorDevice.Readings.ReadAsync(new CancellationTokenSource(TimeSpan.FromSeconds(1)).Token);
+ Assert.Equal(SensorKind.Accelerometer3D, first.Kind);
+ Assert.Equal(SensorKind.AmbientLight, second.Kind);
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public void Manifest_generates_a_valid_sensor_inf()
+ {
+ var manifest = DriverManifest.FromJson(File.ReadAllText(FindManifest()));
+ var inf = new WindowsDriver.InfGen.InfGenerator(new DateOnly(2026, 11, 18)).Generate(manifest);
+
+ Assert.Contains("Class=Sensor", inf);
+ var issues = new WindowsDriver.InfGen.InfValidator().Validate(inf);
+ Assert.True(issues.Count == 0, "INF issues: " + string.Join("; ", issues.Select(i => $"[{i.Section}] {i.Message}")));
+ }
+
+ private static byte[] PackUInt(uint value)
+ {
+ var data = new byte[4];
+ BinaryPrimitives.WriteUInt32LittleEndian(data, value);
+ return data;
+ }
+
+ private static string FindManifest()
+ {
+ var path = Path.Combine(AppContext.BaseDirectory, "../../../../manifest.json");
+ return File.Exists(path) ? path : Path.Combine(Directory.GetCurrentDirectory(), "manifest.json");
+ }
+}
diff --git a/samples/VirtualSensor/Tests/VirtualSensor.Tests.csproj b/samples/VirtualSensor/Tests/VirtualSensor.Tests.csproj
new file mode 100644
index 0000000..203c1b6
--- /dev/null
+++ b/samples/VirtualSensor/Tests/VirtualSensor.Tests.csproj
@@ -0,0 +1,20 @@
+
+
+
+ false
+ Unit tests for the VirtualSensor sample driver — run anywhere with `dotnet test` (no Windows needed).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/VirtualSensor/manifest.json b/samples/VirtualSensor/manifest.json
new file mode 100644
index 0000000..2708ac0
--- /dev/null
+++ b/samples/VirtualSensor/manifest.json
@@ -0,0 +1,22 @@
+{
+ "name": "VirtualSensor",
+ "provider": "Contoso Devices",
+ "manufacturer": "Contoso Devices LLC",
+ "version": "0.1.0",
+ "class": "Sensor",
+ "classGuid": "{5175d334-c371-4806-b3ba-71fd53c9258d}",
+ "framework": "umdf",
+ "serviceName": "WdsVirtualSensor",
+ "catalogFile": "VirtualSensor.cat",
+ "files": [
+ { "source": "VirtualSensor.Driver.dll" }
+ ],
+ "models": [
+ {
+ "name": "Contoso Virtual Sensor Suite (SDK sample)",
+ "hardwareIds": ["Root\\ContosoVirtualSensor"],
+ "compatibleIds": ["*WdsVirtualSensor"]
+ }
+ ],
+ "wdfLibraryVersion": "2.15.0"
+}
diff --git a/samples/VirtualSerial/Driver/SampleSerialDriver.cs b/samples/VirtualSerial/Driver/SampleSerialDriver.cs
new file mode 100644
index 0000000..e230d09
--- /dev/null
+++ b/samples/VirtualSerial/Driver/SampleSerialDriver.cs
@@ -0,0 +1,65 @@
+using System.Buffers.Binary;
+using WindowsDriver.Sdk;
+using WindowsDriver.Sdk.Serial;
+
+namespace VirtualSerial.Driver;
+
+/// Sample-specific IOCTLs.
+public static class SerialSampleIoctlCodes
+{
+ /// In: bytes to inject into the RX queue (simulates a remote peer sending data).
+ public static readonly uint SimulateRemoteData = WinIoctl.VendorControlCode(0x900, WinIoctl.FileAccessWrite);
+}
+
+///
+/// Sample driver: enumerates one virtual COM port per devnode. The default
+/// instance is a loopback port; two instances can be cross-connected with
+/// to model a cable between them.
+///
+public sealed class SampleSerialDriver : DriverBase
+{
+ public override Task OnDeviceAddAsync(DeviceAddContext addContext, DeviceContext deviceContext, CancellationToken cancellationToken)
+ {
+ deviceContext.Properties.Set(KnownDeviceProperties.FriendlyName, "Contoso Virtual COM Port (SDK sample)");
+ deviceContext.Properties.Set(KnownDeviceProperties.Manufacturer, "Contoso Devices");
+
+ var device = new SampleSerialDevice(deviceContext, new SerialDeviceOptions
+ {
+ InitialConfig = new SerialLineConfig(BaudRate: 115_200, DataBits: 8, Parity: SerialParity.None, StopBits: SerialStopBits.One),
+ Loopback = true,
+ });
+ deviceContext.CreateDeviceInterface(new Guid("86E0D1E0-8089-4A62-9A0E-3B7C4D9E2F18"));
+ return Task.FromResult(device);
+ }
+}
+
+/// Virtual COM port extended with a remote-peer simulation IOCTL.
+public sealed class SampleSerialDevice : SerialDevice
+{
+ public SampleSerialDevice(DeviceContext context, SerialDeviceOptions options)
+ : base(context, options)
+ {
+ }
+
+ protected override Task HandleDeviceControlAsync(IoRequest request, CancellationToken ct)
+ {
+ var code = request.IoControlCode;
+ if (code == SerialSampleIoctlCodes.SimulateRemoteData)
+ {
+ if (request.InputBuffer.Length == 0)
+ {
+ request.Fail(NtStatus.InvalidParameter);
+ }
+ else
+ {
+ var injected = InjectReceive(request.InputBuffer.Span);
+ request.Complete(NtStatus.Success, injected);
+ }
+ }
+ else
+ {
+ return base.HandleDeviceControlAsync(request, ct);
+ }
+ return Task.CompletedTask;
+ }
+}
diff --git a/samples/VirtualSerial/Driver/VirtualSerial.Driver.csproj b/samples/VirtualSerial/Driver/VirtualSerial.Driver.csproj
new file mode 100644
index 0000000..e895062
--- /dev/null
+++ b/samples/VirtualSerial/Driver/VirtualSerial.Driver.csproj
@@ -0,0 +1,13 @@
+
+
+
+ VirtualSerial.Driver
+ Sample: virtual serial/COM port device (line config, TX/RX queues, loopback and null-modem pairs) built on WindowsDriver.Sdk.
+
+
+
+
+
+
+
+
diff --git a/samples/VirtualSerial/README.md b/samples/VirtualSerial/README.md
new file mode 100644
index 0000000..3475f37
--- /dev/null
+++ b/samples/VirtualSerial/README.md
@@ -0,0 +1,40 @@
+# VirtualSerial sample
+
+A virtual COM port: line configuration with classic UART validation, TX/RX
+queues, loopback, modem status (CTS/DSR), break detection, counters — and a
+null-modem pair that cross-connects two ports like a cable.
+
+## What it demonstrates
+
+- **Line config** — `SerialLineConfig` validates baud (50–1,000,000), data
+ bits (5–8), parity, stop bits (the 1.5-stop-bits-only-with-5-data-bits rule)
+ and flow control before applying, exactly like a real UART would.
+- **Data paths** — `Write`/`Transmit` into the TX queue; loopback mode echoes
+ back on RX; `SerialLoopbackPair` wires device A's TX to device B's RX and
+ vice versa (both created with `Loopback = false`).
+- **Status** — `GetStatus` reports TX/RX counters, framing errors, CTS/DSR,
+ break-active and loopback state; `AssertBreak`/`InjectFramingError` simulate
+ line faults for tests.
+- **Extensibility** — `SampleSerialDevice` adds `SimulateRemoteData` (inject
+ bytes into RX as if a remote peer sent them).
+
+## Layout
+
+```
+Driver/SampleSerialDriver.cs driver + device (extends SerialDevice)
+manifest.json InfGen manifest → INF (Ports class, UMDF)
+Tests/VirtualSerialSampleTests.cs 7 tests: loopback, config, purge, pair, INF
+```
+
+## Try it
+
+```bash
+dotnet test samples/VirtualSerial/Tests
+infgen generate --manifest samples/VirtualSerial/manifest.json
+```
+
+## Going further
+
+Read `docs/serial-guide.md` for the Windows serial stack (serenum, serial.h
+IOCTLs, CDC-ACM over USB) and how to expose the port to applications as a real
+COM device.
diff --git a/samples/VirtualSerial/Tests/VirtualSerial.Tests.csproj b/samples/VirtualSerial/Tests/VirtualSerial.Tests.csproj
new file mode 100644
index 0000000..583d71c
--- /dev/null
+++ b/samples/VirtualSerial/Tests/VirtualSerial.Tests.csproj
@@ -0,0 +1,20 @@
+
+
+
+ false
+ Unit tests for the VirtualSerial sample driver — run anywhere with `dotnet test` (no Windows needed).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/VirtualSerial/Tests/VirtualSerialSampleTests.cs b/samples/VirtualSerial/Tests/VirtualSerialSampleTests.cs
new file mode 100644
index 0000000..93431c3
--- /dev/null
+++ b/samples/VirtualSerial/Tests/VirtualSerialSampleTests.cs
@@ -0,0 +1,182 @@
+using System.Text;
+using VirtualSerial.Driver;
+using WindowsDriver.Sdk;
+using WindowsDriver.Sdk.Serial;
+using WindowsDriver.Testing;
+using WindowsDriver.InfGen;
+using Xunit;
+
+namespace VirtualSerial.Tests;
+
+public class VirtualSerialSampleTests
+{
+ private static async Task<(TestDriverHost Host, TestDevice Device)> StartHostAsync()
+ {
+ var host = TestDriverHost.Builder().UseFakeTime().Build();
+ await host.StartAsync("WdsVirtualSerial");
+ var device = await host.AddDeviceAsync("ROOT\\CONTOSOVIRTUALSERIAL\\0000", "Root\\ContosoVirtualSerial");
+ return (host, device);
+ }
+
+ [Fact]
+ public async Task Loopback_write_comes_back_on_read()
+ {
+ var (host, device) = await StartHostAsync();
+
+ var payload = Encoding.ASCII.GetBytes("PING from the control plane\r\n");
+ var written = await device.WriteAsync(payload);
+ Check.Success(written);
+ Check.Bytes(written, payload.Length);
+
+ var read = await device.ReadAsync(payload.Length);
+ Check.Success(read);
+ Check.Bytes(read, payload.Length);
+ Assert.Equal(payload, read.Output.Take(payload.Length).ToArray());
+
+ // Queue is drained now.
+ var count = await device.SendIoctlAsync(SerialIoctlCodes.GetRxCount, outputSize: sizeof(uint));
+ Assert.Equal(0u, System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(count.Output));
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Transmit_ioctl_also_loops_back()
+ {
+ var (host, device) = await StartHostAsync();
+
+ var result = await device.SendIoctlAsync(SerialIoctlCodes.Transmit, Encoding.ASCII.GetBytes("OK"));
+ Check.Success(result);
+ Check.Bytes(result, 2);
+
+ var read = await device.ReadAsync(2);
+ Assert.Equal("OK", Encoding.ASCII.GetString(read.Output, 0, read.BytesTransferred));
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Line_config_roundtrip_and_validation()
+ {
+ var (host, device) = await StartHostAsync();
+
+ // Default config from the sample driver.
+ var config = await device.SendIoctlAsync(SerialIoctlCodes.GetLineConfig, outputSize: SerialLineConfig.WireSize);
+ Check.Success(config);
+ Check.Bytes(config, SerialLineConfig.WireSize);
+ Assert.Equal(115200u, System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(config.Output));
+
+ // Change to 9600 7E2 with RTS/CTS.
+ var newConfig = new SerialLineConfig(9600, 7, SerialParity.Even, SerialStopBits.Two, SerialFlowControl.RtsCts);
+ var payload = new byte[SerialLineConfig.WireSize];
+ newConfig.WriteTo(payload);
+ Check.Success(await device.SendIoctlAsync(SerialIoctlCodes.SetLineConfig, payload, SerialLineConfig.WireSize));
+
+ var after = await device.SendIoctlAsync(SerialIoctlCodes.GetLineConfig, outputSize: SerialLineConfig.WireSize);
+ Assert.Equal(newConfig, SerialLineConfig.ReadFrom(after.Output.AsSpan(0, SerialLineConfig.WireSize)));
+
+ // 1.5 stop bits with 8 data bits is invalid.
+ new SerialLineConfig(9600, 8, SerialParity.None, SerialStopBits.OnePointFive).WriteTo(payload);
+ var rejected = await device.SendIoctlAsync(SerialIoctlCodes.SetLineConfig, payload);
+ Check.Status(rejected, NtStatus.InvalidParameter);
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Purge_clears_selected_queues()
+ {
+ var (host, device) = await StartHostAsync();
+
+ await device.WriteAsync(Encoding.ASCII.GetBytes("stale"));
+ await device.SendIoctlAsync(SerialSampleIoctlCodes.SimulateRemoteData, Encoding.ASCII.GetBytes("remote"));
+
+ var purge = new byte[4];
+ System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(purge, 0x3); // RX + TX
+ Check.Success(await device.SendIoctlAsync(SerialIoctlCodes.Purge, purge));
+
+ var count = await device.SendIoctlAsync(SerialIoctlCodes.GetRxCount, outputSize: sizeof(uint));
+ Assert.Equal(0u, System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(count.Output));
+
+ var read = await device.ReadAsync(16);
+ Check.Bytes(read, 0);
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public async Task Status_counters_and_remote_simulation()
+ {
+ var (host, device) = await StartHostAsync();
+
+ Check.Success(await device.SendIoctlAsync(SerialSampleIoctlCodes.SimulateRemoteData, "hello"u8.ToArray()));
+ var read = await device.ReadAsync(5);
+ Assert.Equal("hello", Encoding.ASCII.GetString(read.Output, 0, read.BytesTransferred));
+
+ var status = await device.SendIoctlAsync(SerialIoctlCodes.GetStatus, outputSize: 24);
+ Check.Success(status);
+ Check.Bytes(status, 24);
+ Assert.Equal(5ul, System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(status.Output.AsSpan(8))); // rx bytes read
+ Assert.Equal(1u, status.Output[20]); // CTS asserted
+ Assert.Equal(1u, status.Output[21]); // DSR asserted
+ Assert.Equal(1u, status.Output[23]); // loopback enabled
+
+ // Break condition bumps the framing-error counter.
+ ((SampleSerialDevice)device.Device).AssertBreak(true);
+ var status2 = await device.SendIoctlAsync(SerialIoctlCodes.GetStatus, outputSize: 24);
+ Assert.Equal(1u, System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(status2.Output.AsSpan(16)));
+ Assert.Equal(1u, status2.Output[22]); // break active
+
+ await host.ShutdownAsync();
+ }
+
+ [Fact]
+ public void Null_modem_pair_routes_data_across_devices()
+ {
+ var host = TestDriverHost.Builder().UseFakeTime().Build();
+
+ var portA = new SampleSerialDevice(
+ new DeviceContext(CreateDriverContext(host), new DeviceAddContext { DeviceInstanceId = "ROOT\\CONTOSOVIRTUALSERIAL\\000A" }),
+ new SerialDeviceOptions { Loopback = false });
+ var portB = new SampleSerialDevice(
+ new DeviceContext(CreateDriverContext(host), new DeviceAddContext { DeviceInstanceId = "ROOT\\CONTOSOVIRTUALSERIAL\\000B" }),
+ new SerialDeviceOptions { Loopback = false });
+ _ = new SerialLoopbackPair(portA, portB);
+
+ // A transmits → B receives (and nothing loops back to A).
+ Assert.Equal(6, portA.Transmit("from A"u8.ToArray()));
+ var buffer = new byte[16];
+ Assert.Equal(0, portA.RxQueue.Count);
+ Assert.Equal(6, portB.RxQueue.Read(buffer));
+ Assert.Equal("from A", Encoding.ASCII.GetString(buffer, 0, 6));
+
+ // And the other direction.
+ Assert.Equal(6, portB.Transmit("from B"u8.ToArray()));
+ Assert.Equal(6, portA.RxQueue.Read(buffer));
+ Assert.Equal("from B", Encoding.ASCII.GetString(buffer, 0, 6));
+ }
+
+ [Fact]
+ public void Manifest_generates_a_valid_serial_inf()
+ {
+ var manifest = DriverManifest.FromJson(File.ReadAllText(FindManifest()));
+ var inf = new WindowsDriver.InfGen.InfGenerator(new DateOnly(2026, 11, 18)).Generate(manifest);
+
+ Assert.Contains("Class=Ports", inf);
+ var issues = new WindowsDriver.InfGen.InfValidator().Validate(inf);
+ Assert.True(issues.Count == 0, "INF issues: " + string.Join("; ", issues.Select(i => $"[{i.Section}] {i.Message}")));
+ }
+
+ private static DriverContext CreateDriverContext(TestDriverHost host) => new()
+ {
+ Log = host.Log,
+ Registry = host.Registry,
+ TimeProvider = host.FakeTime ?? TimeProvider.System,
+ };
+
+ private static string FindManifest()
+ {
+ var path = Path.Combine(AppContext.BaseDirectory, "../../../../manifest.json");
+ return File.Exists(path) ? path : Path.Combine(Directory.GetCurrentDirectory(), "manifest.json");
+ }
+}
diff --git a/samples/VirtualSerial/manifest.json b/samples/VirtualSerial/manifest.json
new file mode 100644
index 0000000..e4d3b69
--- /dev/null
+++ b/samples/VirtualSerial/manifest.json
@@ -0,0 +1,22 @@
+{
+ "name": "VirtualSerial",
+ "provider": "Contoso Devices",
+ "manufacturer": "Contoso Devices LLC",
+ "version": "0.1.0",
+ "class": "Ports",
+ "classGuid": "{4d36e978-e325-11ce-bfc1-08002be10318}",
+ "framework": "umdf",
+ "serviceName": "WdsVirtualSerial",
+ "catalogFile": "VirtualSerial.cat",
+ "files": [
+ { "source": "VirtualSerial.Driver.dll" }
+ ],
+ "models": [
+ {
+ "name": "Contoso Virtual COM Port (SDK sample)",
+ "hardwareIds": ["Root\\ContosoVirtualSerial"],
+ "compatibleIds": ["*WdsVirtualSerial"]
+ }
+ ],
+ "wdfLibraryVersion": "2.15.0"
+}
diff --git a/shim/UmdfShim/README.md b/shim/UmdfShim/README.md
new file mode 100644
index 0000000..cb65af7
--- /dev/null
+++ b/shim/UmdfShim/README.md
@@ -0,0 +1,65 @@
+# UmdfShim — native UMDF host shim (design notes)
+
+UMDF drivers are COM objects running inside `WUDFHost.exe`. Microsoft's WDK
+expects C++/COM implementations; the SDK runs your C# driver logic inside that
+host through a thin native shim.
+
+## Architecture
+
+```
+WUDFHost.exe
+ └── WdsShimU.dll (C++/COM — you build this with the WDK)
+ ├─ implements IDriverEntry (IWDFDriver/IWDFDevice callbacks, real IIDs from wudfddi.h)
+ ├─ hosts the .NET runtime via hostfxr (hostfxr_initialize_for_runtime_config,
+ │ hostfxr_get_runtime_delegate → load_assembly_and_get_function_pointer)
+ └─ forwards every callback to WindowsDriver.Interop.Umdf.ManagedDriverBootstrap
+ (WdsInitialize / WdsDeviceAdd / WdsQueueRequest / WdsDeviceD0Entry /
+ WdsDeviceD0Exit / WdsDeviceRelease / WdsDriverUnload)
+
+Your driver (C#)
+ └─ implements WindowsDriver.Sdk.IDriver / DeviceBase — the same code you tested
+ with TestDriverHost.
+```
+
+The ABI between the two sides is frozen in two places that must stay in sync:
+
+- `WindowsDriver.Interop.Umdf.UmdfShimContract.ShimHeader` (C header text)
+- `WindowsDriver.Interop.Umdf.ManagedDriverBootstrap` (`[UnmanagedCallersOnly]` entry points)
+
+## Implementation checklist for the C++ shim
+
+1. **DllGetClassObject / class factory** — standard COM scaffolding so
+ `WUDFHost` can create the driver object (CLSID from your INF
+ `UmdfService` registration).
+2. **IDriverEntry** — `OnInitialize` passes service name + registry path into
+ `WDS_SHIM_SETTINGS`; `OnDeviceAdd` collects hardware IDs (via
+ `IWDFPropertyStore`/`WdfDevice` properties) and calls `WdsDeviceAdd`;
+ `OnDeinitialize` calls `WdsDriverUnload`.
+3. **Runtime hosting** — locate `hostfxr.dll` next to your shim, resolve
+ `hostfxr_initialize_for_runtime_config` and
+ `hostfxr_get_runtime_delegate`, load the managed assembly's
+ `.runtimeconfig.json`, get a function pointer to each `Wds*` entry point.
+ Microsoft documents this flow as "Write a custom .NET host".
+4. **Queue plumbing** — create `IWDFIoQueue` per device; on each request,
+ marshal `WdfRequestRetrieveInputBuffer`/`OutputBuffer` into
+ `WdsQueueRequest`; complete with the shim's `CompleteRequest` callback
+ (which the managed side invokes with `WdfRequestCompleteWithInformation`
+ semantics — for writes the information is input bytes).
+5. **Power/PnP** — map `IWDFDriverCreatedDevice` callbacks to
+ `WdsDeviceD0Entry` / `WdsDeviceD0Exit` / `WdsDeviceRelease`.
+6. **Logging** — the shim's `Log` callback receives UTF-8 lines from the
+ managed host and should forward them to `WUDF` tracing / `WPP`.
+
+## Files
+
+- `wds_shim_abi.h` — copy of the contract header (source of truth lives in
+ `WindowsDriver.Interop`, so the SDK can keep both sides aligned).
+
+## Status
+
+The SDK ships the full managed side and the exact ABI; the C++/COM shim above
+is intentionally left as an implementation task for your driver project — it is
+mechanical forwarding code, but it needs a WDK build environment and your
+product's COM CLSIDs/INF to be meaningful. The KMDF path
+(`shim/WdsKmdfShim/`) has a compilable C skeleton today if you need kernel
+reach sooner.
diff --git a/shim/WdsKmdfShim/README.md b/shim/WdsKmdfShim/README.md
new file mode 100644
index 0000000..b5e11be
--- /dev/null
+++ b/shim/WdsKmdfShim/README.md
@@ -0,0 +1,55 @@
+# WdsKmdfShim — KMDF shim driver skeleton
+
+The kernel-side half of the SDK's KMDF interop story. It owns the real KMDF
+device/queue objects (where managed code cannot run) and exposes the buffered
+IOCTL protocol implemented by `WindowsDriver.Interop.Kmdf.KmdfControlPlane`.
+
+## What the shim provides
+
+| IOCTL (managed constant) | Function | Behavior |
+| -------------------------------------- | -------- | -------- |
+| `KmdfShimProtocol.Ping` | 0x800 | Returns the `WSHI` magic |
+| `KmdfShimProtocol.GetVersion` | 0x801 | Returns major/minor (1.0) |
+| `KmdfShimProtocol.SendCommand` | 0x802 | Runs a vendor command (stub — fill in `WdsHandleCommand`) |
+| `KmdfShimProtocol.ReadEvents` | 0x803 | Drains the kernel event ring (records: 16-byte header + payload) |
+| `KmdfShimProtocol.AcknowledgeEvents` | 0x804 | Marks consumed events (extend for your retention policy) |
+
+The wire structs in `wds_shim.h` mirror `WindowsDriver.Interop.Kmdf` byte-for-byte
+(`KmdfEventRecord` = `WDS_EVENT_RECORD`, `KmdfCommandHeader` = `WDS_COMMAND_HEADER`,
+`KmdfResultHeader` = `WDS_RESULT_HEADER`).
+
+## Building
+
+1. Visual Studio 2022/2026 + the matching WDK.
+2. New Project → **Kernel Mode Driver, KMDF** → name it `WdsKmdfShim`.
+3. Replace the generated sources with `wds_shim.c` and `wds_shim.h`.
+4. Build for x64/arm64 (Windows 10 1903+ target platform).
+5. Sign the .sys + generate a catalog (see `docs/inf-and-signing.md`), then
+ install with `tools/Install-Driver.ps1` and a root-enumerated INF produced by
+ `infgen` with `"framework": "kmdf"`.
+
+## Talking to it from C#
+
+```csharp
+using WindowsDriver.Interop.Kmdf;
+
+var control = new KmdfControlPlane(@"\\.\WdsKmdfShim0");
+control.Open();
+control.Ping();
+var (major, minor) = control.GetVersion();
+var (status, data) = control.SendCommand(0x100 /* your command */, new byte[] { 1, 2, 3 });
+foreach (var evt in control.ReadEvents())
+{
+ Console.WriteLine($"seq={evt.Sequence} id={evt.EventId} bytes={evt.Data.Length}");
+}
+```
+
+## Extension points
+
+- `WdsHandleCommand` in `wds_shim.c` — vendor commands (IDs ≥ `WDS_COMMAND_FIRST_VENDOR`).
+- `WdsPostEvent` — post async completions into the ring; the control plane
+ drains them from any .NET process.
+- The event ring holds 256 records; tune `WDS_EVENT_RING_CAPACITY`.
+
+This file is a reference implementation — it is not compiled by the SDK's CI
+(no WDK on CI runners). Compile it on a machine with the WDK before deploying.
diff --git a/shim/WdsKmdfShim/wds_shim.c b/shim/WdsKmdfShim/wds_shim.c
new file mode 100644
index 0000000..3133608
--- /dev/null
+++ b/shim/WdsKmdfShim/wds_shim.c
@@ -0,0 +1,327 @@
+// wds_shim.c — KMDF shim driver skeleton for the Windows Driver SDK.
+//
+// ROLE
+// The shim is the kernel-side half of the SDK's KMDF interop story. It owns
+// the real KMDF device/queue objects (where C# cannot run) and exposes a
+// small buffered-IOCTL protocol that the managed control plane
+// (WindowsDriver.Interop.Kmdf.KmdfControlPlane) talks to from any .NET
+// process. Hot-path kernel work stays in C; everything else (policy, state
+// machines, telemetry, UI) lives in C#.
+//
+// STATUS
+// Skeleton: compiles against the WDK and implements the full IOCTL contract,
+// but the vendor command dispatch is a stub for you to fill in. Build it in
+// Visual Studio with the Windows Driver Kit (KMDF, Windows 10+, x64/arm64).
+// This file is NOT built by the SDK's CI — it is a reference implementation.
+//
+// BUILD
+// 1. Visual Studio → New Project → "Kernel Mode Driver, KMDF" → name WdsKmdfShim.
+// 2. Replace the generated driver.c/h with this file + wds_shim.h.
+// 3. Add a pre-build step or project reference so wds_shim.h is on the include path.
+// 4. Build, sign (see docs/inf-and-signing.md), install with tools/Install-Driver.ps1.
+
+#include "wds_shim.h"
+
+// ---------------------------------------------------------------------------
+// Per-device context: the event ring and sequence counter.
+typedef struct _WDS_DEVICE_CONTEXT {
+ UINT8 Ring[WDS_EVENT_RING_CAPACITY][sizeof(WDS_EVENT_RECORD) + 256];
+ UINT32 RingUsed[WDS_EVENT_RING_CAPACITY];
+ UINT32 Head; // next slot to write
+ UINT64 NextSequence;
+ WDFSPINLOCK RingLock;
+} WDS_DEVICE_CONTEXT, *PWDS_DEVICE_CONTEXT;
+
+WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(WDS_DEVICE_CONTEXT, WdsDeviceGetContext)
+
+// Forward declarations.
+EVT_WDF_DRIVER_DEVICE_ADD WdsEvtDeviceAdd;
+EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL WdsEvtIoDeviceControl;
+EVT_WDF_OBJECT_CONTEXT_CLEANUP WdsEvtDriverContextCleanup;
+
+static NTSTATUS WdsPostEvent(_In_ WDFDEVICE device, _In_ UINT32 eventId, _In_ UINT32 dataSize, _In_reads_bytes_opt_(dataSize) const UINT8* data);
+static NTSTATUS WdsHandleCommand(_In_ WDFDEVICE device, _In_ const WDS_COMMAND_HEADER* command, _In_ UINT32 availableBytes, _Out_ UINT32* resultStatus, _Out_writes_bytes_(256) UINT8* resultData, _Out_ UINT32* resultSize);
+
+// ---------------------------------------------------------------------------
+// Driver entry — WDF does all the heavy lifting.
+NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT driverObject, _In_ PUNICODE_STRING registryPath)
+{
+ WDF_OBJECT_ATTRIBUTES attributes;
+ WDF_DRIVER_CONFIG config;
+
+ WDF_DRIVER_CONFIG_INIT(&config, WdsEvtDeviceAdd);
+
+ WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
+ attributes.EvtCleanupCallback = WdsEvtDriverContextCleanup;
+
+ return WdfDriverCreate(driverObject, registryPath, &attributes, &config, WDF_NO_HANDLE);
+}
+
+// ---------------------------------------------------------------------------
+// Device add: create the shim device, a sequential IO queue, and the interface.
+NTSTATUS WdsEvtDeviceAdd(_In_ WDFDRIVER driver, _Inout_ PWDFDEVICE_INIT deviceInit)
+{
+ UNREFERENCED_PARAMETER(driver);
+
+ NTSTATUS status;
+ WDFDEVICE device = WDF_NO_HANDLE;
+ WDF_OBJECT_ATTRIBUTES attributes;
+ WDF_IO_QUEUE_CONFIG queueConfig;
+ WDF_IO_QUEUE queue;
+
+ WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, WDS_DEVICE_CONTEXT);
+
+ status = WdfDeviceCreate(&deviceInit, &attributes, &device);
+ if (!NT_SUCCESS(status))
+ {
+ return status;
+ }
+
+ // Initialize the event ring.
+ PWDS_DEVICE_CONTEXT ctx = WdsDeviceGetContext(device);
+ RtlZeroMemory(ctx, sizeof(*ctx));
+ ctx->NextSequence = 1;
+ WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
+ attributes.ParentObject = device;
+ status = WdfSpinLockCreate(&attributes, &ctx->RingLock);
+ if (!NT_SUCCESS(status))
+ {
+ return status;
+ }
+
+ // Sequential queue: IOCTLs are processed one at a time (same semantics as
+ // the SDK's QueueDispatchMode.Sequential).
+ WDF_IO_QUEUE_CONFIG_INIT(&queueConfig, WdfIoQueueDispatchSequential);
+ queueConfig.EvtIoDeviceControl = WdsEvtIoDeviceControl;
+ WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
+ attributes.ParentObject = device;
+
+ status = WdfIoQueueCreate(device, &queueConfig, &attributes, &queue);
+ if (!NT_SUCCESS(status))
+ {
+ return status;
+ }
+ status = WdfDeviceConfigureRequestDispatching(device, queue, WdfRequestTypeDeviceControl);
+ if (!NT_SUCCESS(status))
+ {
+ return status;
+ }
+
+ // Expose the interface the managed control plane opens.
+ status = WdfDeviceCreateDeviceInterface(device, &WDS_SHIM_DEVICE_INTERFACE, NULL);
+ if (!NT_SUCCESS(status))
+ {
+ return status;
+ }
+
+ // Boot event: the control plane sees this as soon as it drains the ring.
+ return WdsPostEvent(device, 0x0001 /* WDS_EVENT_DEVICE_STARTED */, 0, NULL);
+}
+
+// ---------------------------------------------------------------------------
+// IOCTL dispatch — the whole managed/kernel contract lives here.
+VOID WdsEvtIoDeviceControl(_In_ WDFQUEUE queue, _In_ WDFREQUEST request, _In_ size_t outputBufferLength,
+ _In_ size_t inputBufferLength, _In_ ULONG ioControlCode)
+{
+ WDFDEVICE device = WdfIoQueueGetDevice(queue);
+ PWDS_DEVICE_CONTEXT ctx = WdsDeviceGetContext(device);
+ NTSTATUS status = STATUS_SUCCESS;
+ PVOID input = NULL;
+ PVOID output = NULL;
+ size_t actualInput = 0;
+ size_t actualOutput = 0;
+ ULONG information = 0;
+
+ switch (ioControlCode)
+ {
+ case WDS_IOCTL_PING:
+ {
+ if (outputBufferLength < sizeof(UINT32))
+ {
+ status = STATUS_BUFFER_TOO_SMALL;
+ break;
+ }
+ status = WdfRequestRetrieveOutputBuffer(request, sizeof(UINT32), &output, &actualOutput);
+ if (!NT_SUCCESS(status))
+ {
+ break;
+ }
+ *(UINT32*)output = WDS_SHIM_MAGIC;
+ information = sizeof(UINT32);
+ break;
+ }
+
+ case WDS_IOCTL_GET_VERSION:
+ {
+ if (outputBufferLength < 2 * sizeof(UINT32))
+ {
+ status = STATUS_BUFFER_TOO_SMALL;
+ break;
+ }
+ status = WdfRequestRetrieveOutputBuffer(request, 2 * sizeof(UINT32), &output, &actualOutput);
+ if (!NT_SUCCESS(status))
+ {
+ break;
+ }
+ ((UINT32*)output)[0] = WDS_SHIM_VERSION_MAJOR;
+ ((UINT32*)output)[1] = WDS_SHIM_VERSION_MINOR;
+ information = 2 * sizeof(UINT32);
+ break;
+ }
+
+ case WDS_IOCTL_SEND_COMMAND:
+ {
+ if (inputBufferLength < sizeof(WDS_COMMAND_HEADER) || outputBufferLength < sizeof(WDS_RESULT_HEADER))
+ {
+ status = STATUS_BUFFER_TOO_SMALL;
+ break;
+ }
+ status = WdfRequestRetrieveInputBuffer(request, sizeof(WDS_COMMAND_HEADER), &input, &actualInput);
+ if (!NT_SUCCESS(status))
+ {
+ break;
+ }
+ status = WdfRequestRetrieveOutputBuffer(request, sizeof(WDS_RESULT_HEADER), &output, &actualOutput);
+ if (!NT_SUCCESS(status))
+ {
+ break;
+ }
+
+ const WDS_COMMAND_HEADER* command = (const WDS_COMMAND_HEADER*)input;
+ if (command->DataSize > actualInput - sizeof(WDS_COMMAND_HEADER))
+ {
+ status = STATUS_INVALID_PARAMETER;
+ break;
+ }
+
+ UINT32 resultSize = 0;
+ UINT32 resultStatus = STATUS_SUCCESS;
+ UINT8* resultData = ((UINT8*)output) + sizeof(WDS_RESULT_HEADER);
+ UINT32 resultCapacity = (UINT32)(actualOutput - sizeof(WDS_RESULT_HEADER));
+ if (resultCapacity > 256)
+ {
+ resultCapacity = 256;
+ }
+
+ status = WdsHandleCommand(device, command, command->DataSize, &resultStatus, resultData, &resultSize);
+
+ PWDS_RESULT_HEADER result = (PWDS_RESULT_HEADER)output;
+ result->Status = resultStatus;
+ result->DataSize = resultSize;
+ information = sizeof(WDS_RESULT_HEADER) + resultSize;
+ break;
+ }
+
+ case WDS_IOCTL_READ_EVENTS:
+ {
+ // Drain up to N events into the output buffer: (u32 count) + records.
+ status = WdfRequestRetrieveOutputBuffer(request, sizeof(UINT32), &output, &actualOutput);
+ if (!NT_SUCCESS(status))
+ {
+ break;
+ }
+
+ UINT32* countOut = (UINT32*)output;
+ UINT8* cursor = ((UINT8*)output) + sizeof(UINT32);
+ UINT8* end = ((UINT8*)output) + actualOutput;
+ UINT32 drained = 0;
+
+ WdfSpinLockAcquire(ctx->RingLock);
+ for (UINT32 i = 0; i < WDS_EVENT_RING_CAPACITY; i++)
+ {
+ UINT32 used = ctx->RingUsed[(ctx->Head + i) % WDS_EVENT_RING_CAPACITY];
+ if (used == 0)
+ {
+ continue;
+ }
+ UINT32 total = (UINT32)(sizeof(WDS_EVENT_RECORD) + used);
+ if ((size_t)(end - cursor) < sizeof(WDS_EVENT_RECORD) + used)
+ {
+ break; // output buffer full
+ }
+ WDS_EVENT_RECORD* record = (WDS_EVENT_RECORD*)cursor;
+ const UINT8* slot = ctx->Ring[(ctx->Head + i) % WDS_EVENT_RING_CAPACITY];
+ RtlCopyMemory(record, slot, total);
+ cursor += total;
+ drained++;
+ }
+ // Consumed events are removed by ACKNOWLEDGE_EVENTS; here they stay so
+ // a crash does not lose telemetry. For the skeleton, drain-and-keep.
+ WdfSpinLockRelease(ctx->RingLock);
+
+ *countOut = drained;
+ information = (ULONG)(sizeof(UINT32) + (cursor - ((UINT8*)output) - sizeof(UINT32)));
+ break;
+ }
+
+ case WDS_IOCTL_ACKNOWLEDGE_EVENTS:
+ // Skeleton: clearing the ring is left to the integrator (drop consumed
+ // records below the acknowledged sequence).
+ status = STATUS_SUCCESS;
+ break;
+
+ default:
+ status = STATUS_INVALID_DEVICE_REQUEST;
+ break;
+ }
+
+ WdfRequestCompleteWithInformation(request, status, information);
+}
+
+// ---------------------------------------------------------------------------
+// Vendor command dispatch — replace the stub with your kernel-side work.
+NTSTATUS WdsHandleCommand(_In_ WDFDEVICE device, _In_ const WDS_COMMAND_HEADER* command,
+ _In_ UINT32 availableBytes, _Out_ UINT32* resultStatus,
+ _Out_writes_bytes_(256) UINT8* resultData, _Out_ UINT32* resultSize)
+{
+ UNREFERENCED_PARAMETER(device);
+ UNREFERENCED_PARAMETER(availableBytes);
+ UNREFERENCED_PARAMETER(resultData);
+
+ *resultSize = 0;
+
+ if (command->CommandId < WDS_COMMAND_FIRST_VENDOR)
+ {
+ *resultStatus = STATUS_INVALID_DEVICE_REQUEST;
+ return STATUS_SUCCESS; // the IOCTL itself succeeded; the command failed
+ }
+
+ // TODO: vendor commands — read command->Data (command->DataSize bytes),
+ // perform the kernel operation, write results into resultData, post events
+ // with WdsPostEvent for asynchronous completions.
+ *resultStatus = STATUS_NOT_IMPLEMENTED;
+ return STATUS_SUCCESS;
+}
+
+// ---------------------------------------------------------------------------
+// Ring post helper.
+NTSTATUS WdsPostEvent(_In_ WDFDEVICE device, _In_ UINT32 eventId, _In_ UINT32 dataSize,
+ _In_reads_bytes_opt_(dataSize) const UINT8* data)
+{
+ PWDS_DEVICE_CONTEXT ctx = WdsDeviceGetContext(device);
+ if (dataSize > 256)
+ {
+ return STATUS_INVALID_PARAMETER;
+ }
+
+ NTSTATUS status = STATUS_SUCCESS;
+ WdfSpinLockAcquire(ctx->RingLock);
+ UINT32 slot = ctx->Head % WDS_EVENT_RING_CAPACITY;
+ WDS_EVENT_RECORD* record = (WDS_EVENT_RECORD*)ctx->Ring[slot];
+ record->Sequence = ctx->NextSequence++;
+ record->EventId = eventId;
+ record->DataSize = dataSize;
+ if (data != NULL && dataSize > 0)
+ {
+ RtlCopyMemory((UINT8*)record + sizeof(WDS_EVENT_RECORD), data, dataSize);
+ }
+ ctx->RingUsed[slot] = dataSize;
+ ctx->Head = (ctx->Head + 1) % WDS_EVENT_RING_CAPACITY;
+ WdfSpinLockRelease(ctx->RingLock);
+ return status;
+}
+
+VOID WdsEvtDriverContextCleanup(_In_ WDFOBJECT driverObject)
+{
+ UNREFERENCED_PARAMETER(driverObject);
+}
diff --git a/shim/WdsKmdfShim/wds_shim.h b/shim/WdsKmdfShim/wds_shim.h
new file mode 100644
index 0000000..ec4ceff
--- /dev/null
+++ b/shim/WdsKmdfShim/wds_shim.h
@@ -0,0 +1,54 @@
+// wds_shim.h — wire contract for the WDS KMDF shim driver.
+// Mirrors WindowsDriver.Interop.Kmdf (KmdfShimProtocol) — keep both in sync.
+#pragma once
+
+#include
+#include
+
+// The shim answers PING with this magic (ASCII "WSHI", little-endian).
+#define WDS_SHIM_MAGIC 0x49485357u
+#define WDS_SHIM_VERSION_MAJOR 1u
+#define WDS_SHIM_VERSION_MINOR 0u
+
+// IOCTL function codes (CTL_CODE(FILE_DEVICE_UNKNOWN, function, METHOD_BUFFERED, access)).
+#define WDS_IOCTL_PING CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_BUFFERED, FILE_READ_ACCESS)
+#define WDS_IOCTL_GET_VERSION CTL_CODE(FILE_DEVICE_UNKNOWN, 0x801, METHOD_BUFFERED, FILE_READ_ACCESS)
+#define WDS_IOCTL_SEND_COMMAND CTL_CODE(FILE_DEVICE_UNKNOWN, 0x802, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
+#define WDS_IOCTL_READ_EVENTS CTL_CODE(FILE_DEVICE_UNKNOWN, 0x803, METHOD_BUFFERED, FILE_READ_ACCESS)
+#define WDS_IOCTL_ACKNOWLEDGE_EVENTS CTL_CODE(FILE_DEVICE_UNKNOWN, 0x804, METHOD_BUFFERED, FILE_WRITE_ACCESS)
+
+// Vendor commands start at 0x100 (0x00-0xFF are reserved for the shim itself).
+#define WDS_COMMAND_FIRST_VENDOR 0x100u
+
+// Device interface GUID of the shim — applications/control planes open this.
+// {D9C2A2E5-6F71-4E1B-9C3A-58B7F0D6E412}
+DEFINE_GUID(WDS_SHIM_DEVICE_INTERFACE,
+ 0xD9C2A2E5, 0x6F71, 0x4E1B, 0x9C, 0x3A, 0x58, 0xB7, 0xF0, 0xD6, 0xE4, 0x12);
+
+// One event record in the kernel ring buffer: fixed 16-byte header + DataSize payload bytes.
+#pragma pack(push, 1)
+typedef struct _WDS_EVENT_RECORD {
+ UINT64 Sequence;
+ UINT32 EventId;
+ UINT32 DataSize;
+ // UINT8 Data[DataSize]; — follows the header
+} WDS_EVENT_RECORD, *PWDS_EVENT_RECORD;
+C_ASSERT(sizeof(WDS_EVENT_RECORD) == 16);
+
+typedef struct _WDS_COMMAND_HEADER {
+ UINT32 CommandId;
+ UINT32 DataSize;
+ // UINT8 Data[DataSize]; — follows the header
+} WDS_COMMAND_HEADER, *PWDS_COMMAND_HEADER;
+C_ASSERT(sizeof(WDS_COMMAND_HEADER) == 8);
+
+typedef struct _WDS_RESULT_HEADER {
+ UINT32 Status; // NTSTATUS of the command
+ UINT32 DataSize;
+ // UINT8 Data[DataSize]; — follows the header
+} WDS_RESULT_HEADER, *PWDS_RESULT_HEADER;
+C_ASSERT(sizeof(WDS_RESULT_HEADER) == 8);
+#pragma pack(pop)
+
+// Ring capacity: number of event records retained for user-mode readers.
+#define WDS_EVENT_RING_CAPACITY 256
diff --git a/src/WindowsDriver.InfGen/DriverManifest.cs b/src/WindowsDriver.InfGen/DriverManifest.cs
new file mode 100644
index 0000000..f0275d2
--- /dev/null
+++ b/src/WindowsDriver.InfGen/DriverManifest.cs
@@ -0,0 +1,143 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace WindowsDriver.InfGen;
+
+/// WDF flavor the driver package targets.
+public enum DriverFramework
+{
+ Umdf,
+ Kmdf,
+}
+
+/// One driver file to copy during install.
+public sealed record DriverFile(string Source, string? Destination = null);
+
+/// One hardware model supported by the package.
+public sealed record DriverModel
+{
+ /// Display name (the %Model% string).
+ public required string Name { get; init; }
+
+ /// Hardware IDs, most specific first.
+ public IReadOnlyList HardwareIds { get; init; } = [];
+
+ /// Optional compatible IDs.
+ public IReadOnlyList CompatibleIds { get; init; } = [];
+}
+
+///
+/// The manifest InfGen turns into a driver INF. All fields are required except
+/// where noted; see docs/inf-and-signing.md for the full schema reference.
+///
+public sealed record DriverManifest
+{
+ /// Base name for the INF, catalog and service (no extension).
+ public required string Name { get; init; }
+
+ /// Publishing provider (the %Provider% string).
+ public required string Provider { get; init; }
+
+ /// Manufacturer display name; defaults to Provider.
+ public string? Manufacturer { get; init; }
+
+ /// Driver version, e.g. "0.1.0".
+ public required string Version { get; init; }
+
+ /// DriverVer date (MM/DD/YYYY). Defaults to the generation date.
+ public string? DriverVerDate { get; init; }
+
+ public required string Class { get; init; }
+
+ /// Setup class GUID in {xxxxxxxx-...} form (with braces).
+ public required string ClassGuid { get; init; }
+
+ public required DriverFramework Framework { get; init; }
+
+ /// Service name for the WDF section; defaults to Name.
+ public string? ServiceName { get; init; }
+
+ /// Catalog file name; defaults to <Name>.cat.
+ public string? CatalogFile { get; init; }
+
+ /// Files copied by the driver package. The first entry must be the driver binary.
+ public IReadOnlyList Files { get; init; } = [];
+
+ public IReadOnlyList Models { get; init; } = [];
+
+ /// WDF library versions: "2.15.0" for UMDF, "1.15" for KMDF.
+ public string? WdfLibraryVersion { get; init; }
+
+ public static DriverManifest FromJson(string json)
+ {
+ var options = new JsonSerializerOptions
+ {
+ PropertyNameCaseInsensitive = true,
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
+ ReadCommentHandling = JsonCommentHandling.Skip,
+ AllowTrailingCommas = true,
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) },
+ };
+ DriverManifest manifest;
+ try
+ {
+ manifest = JsonSerializer.Deserialize(json, options)
+ ?? throw new InfGenException("Manifest parsed to null — is the JSON valid?");
+ }
+ catch (JsonException ex)
+ {
+ throw new InfGenException($"Manifest JSON is invalid: {ex.Message}");
+ }
+ Validate(manifest);
+ return manifest;
+ }
+
+ public static void Validate(DriverManifest manifest)
+ {
+ var problems = new List();
+
+ if (string.IsNullOrWhiteSpace(manifest.Name))
+ {
+ problems.Add("name is required.");
+ }
+ if (string.IsNullOrWhiteSpace(manifest.Provider))
+ {
+ problems.Add("provider is required.");
+ }
+ if (string.IsNullOrWhiteSpace(manifest.Version))
+ {
+ problems.Add("version is required.");
+ }
+ if (string.IsNullOrWhiteSpace(manifest.Class))
+ {
+ problems.Add("class is required.");
+ }
+ if (string.IsNullOrWhiteSpace(manifest.ClassGuid) || !Guid.TryParse(manifest.ClassGuid.Trim('{', '}'), out _))
+ {
+ problems.Add($"classGuid '{manifest.ClassGuid}' is not a parseable GUID.");
+ }
+ if (manifest.Files.Count == 0)
+ {
+ problems.Add("files must contain at least the driver binary.");
+ }
+ if (manifest.Models.Count == 0)
+ {
+ problems.Add("at least one model is required.");
+ }
+ foreach (var model in manifest.Models)
+ {
+ if (model.HardwareIds.Count == 0 && model.CompatibleIds.Count == 0)
+ {
+ problems.Add($"model '{model.Name}' needs at least one hardware ID or compatible ID.");
+ }
+ }
+
+ if (problems.Count > 0)
+ {
+ throw new InfGenException("Manifest invalid:\n - " + string.Join("\n - ", problems));
+ }
+ }
+}
+
+/// Tool error with a friendly message (exit code 1).
+public sealed class InfGenException(string message) : Exception(message);
diff --git a/src/WindowsDriver.InfGen/InfGenerator.cs b/src/WindowsDriver.InfGen/InfGenerator.cs
new file mode 100644
index 0000000..cc42c89
--- /dev/null
+++ b/src/WindowsDriver.InfGen/InfGenerator.cs
@@ -0,0 +1,132 @@
+using WindowsDriver.InfGen;
+
+namespace WindowsDriver.InfGen;
+
+///
+/// Generates a driver INF from a . The output
+/// follows the Windows INF grammar: Version block, per-architecture manufacturer
+/// and DDInstall sections, source disks, destination dirs, the WDF install
+/// section (UmdfService or KmdfService) and the strings table.
+///
+public sealed class InfGenerator
+{
+ private readonly string _generationDate;
+
+ public InfGenerator(DateOnly? generationDate = null)
+ {
+ _generationDate = generationDate?.ToString("MM/dd/yyyy")
+ ?? DateOnly.FromDateTime(DateTime.UtcNow).ToString("MM/dd/yyyy");
+ }
+
+ /// Generates the INF text for the given architectures (default amd64 + arm64).
+ public string Generate(DriverManifest manifest, IReadOnlyList? architectures = null)
+ {
+ DriverManifest.Validate(manifest);
+ var arches = architectures ?? ["NTamd64", "NTarm64"];
+ var serviceName = manifest.ServiceName ?? manifest.Name;
+ var manufacturer = manifest.Manufacturer ?? manifest.Provider;
+ var catalog = manifest.CatalogFile ?? $"{manifest.Name}.cat";
+ var driverBinary = manifest.Files[0].Source;
+ var date = manifest.DriverVerDate ?? _generationDate;
+
+ var lines = new List
+ {
+ $"; Generated by infgen {SdkVersion} — do not edit by hand.",
+ $"; Source manifest: {manifest.Name} ({manifest.Framework} driver, v{manifest.Version}).",
+ string.Empty,
+ "[Version]",
+ "Signature=\"$WINDOWS NT$\"",
+ $"Class={manifest.Class}",
+ $"ClassGuid={NormalizeGuid(manifest.ClassGuid)}",
+ "Provider=%Provider%",
+ $"CatalogFile={catalog}",
+ $"DriverVer={date},{manifest.Version}",
+ "PnpLockdown=1",
+ string.Empty,
+ "[Manufacturer]",
+ "%Manufacturer%=Standard," + string.Join(",", arches),
+ string.Empty,
+ };
+
+ foreach (var arch in arches)
+ {
+ var install = $"Install.{arch}";
+ lines.Add($"[Standard.{arch}]");
+ for (var m = 0; m < manifest.Models.Count; m++)
+ {
+ var model = manifest.Models[m];
+ var ids = string.Join(",", model.HardwareIds.Concat(model.CompatibleIds).Select(EscapeHwId));
+ lines.Add($"%Model{m}%={install},{ids}");
+ }
+ lines.Add(string.Empty);
+ lines.Add($"[{install}]");
+ lines.Add("CopyFiles=DriverFiles");
+ lines.Add(string.Empty);
+ lines.Add($"[{install}.Wdf]");
+ if (manifest.Framework == DriverFramework.Umdf)
+ {
+ lines.Add($"UmdfService={serviceName}, {serviceName}_Install");
+ lines.Add($"UmdfServiceOrder={serviceName}");
+ lines.Add(string.Empty);
+ lines.Add($"[{serviceName}_Install]");
+ lines.Add($"UmdfLibraryVersion={manifest.WdfLibraryVersion ?? "2.15.0"}");
+ lines.Add($"ServiceBinary=%12%\\{driverBinary}");
+ }
+ else
+ {
+ lines.Add($"KmdfService={serviceName}, {serviceName}_Install");
+ lines.Add(string.Empty);
+ lines.Add($"[{serviceName}_Install]");
+ lines.Add($"KmdfLibraryVersion={manifest.WdfLibraryVersion ?? "1.15"}");
+ }
+ lines.Add(string.Empty);
+ }
+
+ lines.Add("[DriverFiles]");
+ foreach (var file in manifest.Files)
+ {
+ lines.Add(file.Source);
+ }
+ lines.Add(string.Empty);
+ lines.Add("[SourceDisksNames]");
+ lines.Add("1 = %DiskName%");
+ lines.Add(string.Empty);
+ lines.Add("[SourceDisksFiles]");
+ foreach (var file in manifest.Files)
+ {
+ lines.Add($"{file.Source} = 1");
+ }
+ lines.Add(string.Empty);
+ lines.Add("[DestinationDirs]");
+ lines.Add("DriverFiles = 12 ; %windir%\\system32\\drivers");
+ lines.Add(string.Empty);
+ lines.Add("[Strings]");
+ lines.Add($"Provider = \"{manifest.Provider}\"");
+ lines.Add($"Manufacturer = \"{manufacturer}\"");
+ for (var m = 0; m < manifest.Models.Count; m++)
+ {
+ lines.Add($"Model{m} = \"{manifest.Models[m].Name}\"");
+ }
+ lines.Add("DiskName = \"Windows Driver SDK installation media\"");
+
+ return string.Join(Environment.NewLine, lines) + Environment.NewLine;
+ }
+
+ public static string NormalizeGuid(string guid)
+ {
+ guid = guid.Trim();
+ if (!guid.StartsWith('{'))
+ {
+ guid = "{" + guid;
+ }
+ if (!guid.EndsWith('}'))
+ {
+ guid += "}";
+ }
+ return guid.ToLowerInvariant();
+ }
+
+ private static string EscapeHwId(string id) => id.Replace('"', '\'');
+
+ public const string SdkVersion = "0.1.0-preview.1";
+}
diff --git a/src/WindowsDriver.InfGen/InfValidator.cs b/src/WindowsDriver.InfGen/InfValidator.cs
new file mode 100644
index 0000000..103d62e
--- /dev/null
+++ b/src/WindowsDriver.InfGen/InfValidator.cs
@@ -0,0 +1,152 @@
+using System.Text.RegularExpressions;
+
+namespace WindowsDriver.InfGen;
+
+/// One lint finding for an INF file.
+public sealed record InfIssue(string Section, string Message);
+
+///
+/// Lightweight INF linter: verifies required sections exist, GUIDs parse, model
+/// references resolve, and no section is duplicated. It does not replace the
+/// full ChkINF / InfVerif tooling shipped with the WDK — run those before
+/// submission (see docs/inf-and-signing.md).
+///
+public sealed partial class InfValidator
+{
+ private static readonly string[] RequiredSections = ["Version", "Manufacturer", "Strings"];
+
+ public IReadOnlyList Validate(string infText)
+ {
+ var issues = new List();
+ var sections = ParseSections(infText);
+ var sectionNames = sections.Keys.ToArray();
+
+ foreach (var required in RequiredSections)
+ {
+ if (!sectionNames.Any(n => n.Equals(required, StringComparison.OrdinalIgnoreCase)))
+ {
+ issues.Add(new InfIssue(required, "required section is missing."));
+ }
+ }
+
+ // Version block
+ if (sections.TryGetValue("Version", out var version))
+ {
+ var keys = ParseKeys(version);
+ foreach (var key in new[] { "Signature", "Class", "ClassGuid", "Provider", "DriverVer" })
+ {
+ if (!keys.ContainsKey(key))
+ {
+ issues.Add(new InfIssue("Version", $"missing '{key}'."));
+ }
+ }
+ if (keys.TryGetValue("ClassGuid", out var guid) && !Guid.TryParse(guid.Trim('{', '}'), out _))
+ {
+ issues.Add(new InfIssue("Version", $"ClassGuid '{guid}' is not a parseable GUID."));
+ }
+ if (keys.TryGetValue("DriverVer", out var ver) && !DriverVerRegex().IsMatch(ver))
+ {
+ issues.Add(new InfIssue("Version", $"DriverVer '{ver}' must be 'MM/DD/YYYY,version'."));
+ }
+ }
+
+ // Duplicate sections
+ var duplicates = sectionNames
+ .GroupBy(n => n, StringComparer.OrdinalIgnoreCase)
+ .Where(g => g.Count() > 1)
+ .Select(g => g.Key);
+ foreach (var duplicate in duplicates)
+ {
+ issues.Add(new InfIssue(duplicate, "section defined more than once."));
+ }
+
+ // Manufacturer model references
+ foreach (var (name, lines) in sections.Where(kvp => kvp.Key.StartsWith("Standard.", StringComparison.OrdinalIgnoreCase)))
+ {
+ foreach (var line in lines.Where(l => l.TrimStart().StartsWith('%')))
+ {
+ // %ModelX%=Install.NTamd64,
+ var match = ModelLine().Match(line);
+ if (!match.Success)
+ {
+ issues.Add(new InfIssue(name, $"cannot parse model line '{line.Trim()}'."));
+ continue;
+ }
+ var installSection = match.Groups["install"].Value;
+ if (!sections.ContainsKey(installSection))
+ {
+ issues.Add(new InfIssue(name, $"model references missing install section [{installSection}]."));
+ }
+ }
+ }
+
+ // String references resolve (comments are stripped first: ';' starts a comment)
+ var withoutComments = string.Join('\n', infText.Split(['\r', '\n'])
+ .Select(line => line.Contains(';') ? line[..line.IndexOf(';')] : line));
+ var strings = sections.TryGetValue("Strings", out var s) ? ParseKeys(s) : new Dictionary();
+ foreach (var reference in StringRefs().Matches(withoutComments).Select(m => m.Groups["key"].Value))
+ {
+ if (reference.All(char.IsDigit))
+ {
+ continue; // dirids like %12% are not string keys
+ }
+ if (!strings.ContainsKey(reference))
+ {
+ issues.Add(new InfIssue("Strings", $"string key '%{reference}%' is used but not defined."));
+ }
+ }
+
+ return issues;
+ }
+
+ private static Dictionary> ParseSections(string infText)
+ {
+ var result = new Dictionary>(StringComparer.OrdinalIgnoreCase);
+ string? current = null;
+ foreach (var raw in infText.Split(['\r', '\n']))
+ {
+ var line = raw.Trim();
+ if (line.Length == 0 || line.StartsWith(';'))
+ {
+ continue;
+ }
+ if (line.StartsWith('[') && line.EndsWith(']'))
+ {
+ current = line[1..^1].Trim();
+ if (!result.ContainsKey(current))
+ {
+ result[current] = [];
+ }
+ continue;
+ }
+ if (current is not null)
+ {
+ result[current].Add(line);
+ }
+ }
+ return result;
+ }
+
+ private static Dictionary ParseKeys(List lines)
+ {
+ var result = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (var line in lines)
+ {
+ var eq = line.IndexOf('=');
+ if (eq > 0)
+ {
+ result[line[..eq].Trim()] = line[(eq + 1)..].Trim();
+ }
+ }
+ return result;
+ }
+
+ [GeneratedRegex(@"^(?\d{2}/\d{2}/\d{4}),(?.+)$")]
+ private static partial Regex DriverVerRegex();
+
+ [GeneratedRegex(@"^%(?[^%]+)%\s*=\s*(?[^,]+),")]
+ private static partial Regex ModelLine();
+
+ [GeneratedRegex(@"%(?[A-Za-z0-9_.\-]+)%")]
+ private static partial Regex StringRefs();
+}
diff --git a/src/WindowsDriver.InfGen/Program.cs b/src/WindowsDriver.InfGen/Program.cs
new file mode 100644
index 0000000..502a80d
--- /dev/null
+++ b/src/WindowsDriver.InfGen/Program.cs
@@ -0,0 +1,175 @@
+using WindowsDriver.InfGen;
+
+namespace WindowsDriver.InfGen;
+
+///
+/// infgen — driver INF generator and linter.
+///
+/// infgen generate --manifest <driver.json> [--out <file.inf>] [--arch NTamd64,NTarm64]
+/// infgen validate --inf <file.inf>
+/// infgen schema
+///
+/// Exit codes: 0 = success, 1 = failure (message printed to stderr).
+///
+public static class Program
+{
+ public static int Main(string[] args)
+ {
+ try
+ {
+ if (args.Length == 0)
+ {
+ PrintUsage();
+ return 1;
+ }
+
+ switch (args[0].ToLowerInvariant())
+ {
+ case "generate":
+ return RunGenerate(args.Skip(1).ToArray());
+ case "validate":
+ return RunValidate(args.Skip(1).ToArray());
+ case "schema":
+ Console.WriteLine(ExampleManifest);
+ return 0;
+ case "--help" or "-h" or "help":
+ PrintUsage();
+ return 0;
+ default:
+ Console.Error.WriteLine($"Unknown command '{args[0]}'.");
+ PrintUsage();
+ return 1;
+ }
+ }
+ catch (InfGenException ex)
+ {
+ Console.Error.WriteLine($"error: {ex.Message}");
+ return 1;
+ }
+ catch (FileNotFoundException ex)
+ {
+ Console.Error.WriteLine($"error: {ex.FileName ?? ex.Message} not found.");
+ return 1;
+ }
+ catch (Exception ex)
+ {
+ Console.Error.WriteLine($"error: {ex.GetType().Name}: {ex.Message}");
+ return 1;
+ }
+ }
+
+ private static int RunGenerate(string[] args)
+ {
+ string? manifestPath = null;
+ string? outPath = null;
+ string[]? arches = null;
+
+ for (var i = 0; i < args.Length; i++)
+ {
+ switch (args[i])
+ {
+ case "--manifest" or "-m" when i + 1 < args.Length:
+ manifestPath = args[++i];
+ break;
+ case "--out" or "-o" when i + 1 < args.Length:
+ outPath = args[++i];
+ break;
+ case "--arch" when i + 1 < args.Length:
+ arches = args[++i].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
+ break;
+ default:
+ throw new InfGenException($"Unknown option '{args[i]}' for generate.");
+ }
+ }
+
+ if (manifestPath is null)
+ {
+ throw new InfGenException("generate requires --manifest .");
+ }
+
+ var manifest = DriverManifest.FromJson(File.ReadAllText(manifestPath));
+ var inf = new InfGenerator().Generate(manifest, arches);
+ outPath ??= Path.ChangeExtension(manifestPath, ".inf");
+ File.WriteAllText(outPath, inf);
+ Console.WriteLine($"wrote {outPath} ({inf.Length} bytes, {manifest.Framework} driver '{manifest.Name}' v{manifest.Version})");
+ return 0;
+ }
+
+ private static int RunValidate(string[] args)
+ {
+ string? infPath = null;
+ for (var i = 0; i < args.Length; i++)
+ {
+ switch (args[i])
+ {
+ case "--inf" or "-f" when i + 1 < args.Length:
+ infPath = args[++i];
+ break;
+ default:
+ throw new InfGenException($"Unknown option '{args[i]}' for validate.");
+ }
+ }
+ if (infPath is null)
+ {
+ throw new InfGenException("validate requires --inf .");
+ }
+
+ var issues = new InfValidator().Validate(File.ReadAllText(infPath));
+ if (issues.Count == 0)
+ {
+ Console.WriteLine($"{infPath}: OK (no issues found)");
+ return 0;
+ }
+ foreach (var issue in issues)
+ {
+ Console.WriteLine($"{infPath}: [{issue.Section}] {issue.Message}");
+ }
+ Console.Error.WriteLine($"{infPath}: {issues.Count} issue(s) found.");
+ return 1;
+ }
+
+ private static void PrintUsage()
+ {
+ Console.WriteLine("""
+ infgen — Windows Driver SDK INF tool (v0.1.0-preview.1)
+
+ infgen generate --manifest [--out ] [--arch NTamd64,NTarm64]
+ Generates a driver INF from a JSON manifest.
+
+ infgen validate --inf
+ Lints an INF: required sections, GUIDs, model refs, string refs.
+
+ infgen schema
+ Prints an example manifest.
+
+ """);
+ }
+
+ private const string ExampleManifest = """
+ {
+ // Windows Driver SDK manifest → driver INF
+ "name": "MyDevice",
+ "provider": "Contoso Devices",
+ "manufacturer": "Contoso Devices LLC",
+ "version": "1.0.0",
+ "driverVerDate": "11/18/2026",
+ "class": "Media",
+ "classGuid": "{4d36e96c-e325-11ce-bfc1-08002be10318}",
+ "framework": "umdf",
+ "serviceName": "WdsMyDevice",
+ "catalogFile": "MyDevice.cat",
+ "files": [
+ { "source": "MyDevice.dll", "destination": "drivers" },
+ { "source": "MyDevice.json" }
+ ],
+ "models": [
+ {
+ "name": "Contoso Virtual MyDevice",
+ "hardwareIds": ["Root\\ContosoMyDevice"],
+ "compatibleIds": ["*WdsMyDevice"]
+ }
+ ],
+ "wdfLibraryVersion": "2.15.0"
+ }
+ """;
+}
diff --git a/src/WindowsDriver.InfGen/WindowsDriver.InfGen.csproj b/src/WindowsDriver.InfGen/WindowsDriver.InfGen.csproj
new file mode 100644
index 0000000..195fb17
--- /dev/null
+++ b/src/WindowsDriver.InfGen/WindowsDriver.InfGen.csproj
@@ -0,0 +1,18 @@
+
+
+
+ Exe
+ infgen — generates driver INF files from a JSON manifest and validates existing INF files. Ships as a dotnet tool (`dotnet tool install WindowsDriver.InfGen`).
+ true
+ infgen
+ ../../artifacts/
+ WindowsDriver.InfGen
+ windows;driver;inf;wdk;installer;codegen
+ LICENSE
+
+
+
+
+
+
+
diff --git a/src/WindowsDriver.Interop/Kmdf/KmdfControlPlane.cs b/src/WindowsDriver.Interop/Kmdf/KmdfControlPlane.cs
new file mode 100644
index 0000000..5649d84
--- /dev/null
+++ b/src/WindowsDriver.Interop/Kmdf/KmdfControlPlane.cs
@@ -0,0 +1,134 @@
+using System.Buffers.Binary;
+using Microsoft.Win32.SafeHandles;
+using WindowsDriver.Interop.Win32;
+using WindowsDriver.Sdk;
+
+namespace WindowsDriver.Interop.Kmdf;
+
+///
+/// Managed control plane for a KMDF shim driver. Opens the device interface,
+/// sends buffered IOCTLs (ping/version/commands) and drains the shim's event
+/// ring. Runs in any .NET process — a service, a tray app, or tests.
+///
+/// On a machine without the shim device installed, Open() fails with the real
+/// Win32 error (ERROR_FILE_NOT_FOUND = 2); unit tests exercise the wire
+/// structures and IOCTL math without a device.
+///
+public sealed class KmdfControlPlane : IDisposable
+{
+ private SafeFileHandle? _device;
+
+ ///
+ /// Creates a control plane for the device at
+ /// (e.g. "\\\\?\\WdsKmdfShim#..." from the shim's CreateDeviceInterface, or
+ /// "\\\\.\\WdsKmdfShim0" for a named device object).
+ ///
+ public KmdfControlPlane(string devicePath)
+ {
+ DevicePath = devicePath;
+ }
+
+ public string DevicePath { get; }
+
+ public bool IsOpen => _device is { IsInvalid: false, IsClosed: false };
+
+ /// Opens the device handle. Throws System.ComponentModel.Win32Exception on failure.
+ public void Open()
+ {
+ var handle = Win32Native.CreateFileW(
+ DevicePath,
+ Win32Native.GenericRead | Win32Native.GenericWrite,
+ Win32Native.FileShareRead | Win32Native.FileShareWrite,
+ lpSecurityAttributes: IntPtr.Zero,
+ Win32Native.OpenExisting,
+ dwFlagsAndAttributes: 0,
+ hTemplateFile: IntPtr.Zero);
+ if (handle.IsInvalid)
+ {
+ throw new System.ComponentModel.Win32Exception(
+ System.Runtime.InteropServices.Marshal.GetLastWin32Error(),
+ $"Cannot open device '{DevicePath}'. Is the shim driver installed?");
+ }
+ _device = handle;
+ }
+
+ /// Sends PING and verifies the shim magic.
+ public void Ping()
+ {
+ var device = RequireOpen();
+ var buffer = new byte[sizeof(uint)];
+ var written = Win32Native.SendIoctl(device, KmdfShimProtocol.Ping, ReadOnlySpan.Empty, buffer);
+ var magic = BinaryPrimitives.ReadUInt32LittleEndian(buffer);
+ if (written < sizeof(uint) || magic != KmdfShimProtocol.Magic)
+ {
+ throw new InvalidOperationException($"Shim responded with unexpected magic 0x{magic:X8}.");
+ }
+ }
+
+ /// Returns the shim protocol version.
+ public (uint Major, uint Minor) GetVersion()
+ {
+ var device = RequireOpen();
+ var buffer = new byte[2 * sizeof(uint)];
+ Win32Native.SendIoctl(device, KmdfShimProtocol.GetVersion, ReadOnlySpan.Empty, buffer);
+ return (BinaryPrimitives.ReadUInt32LittleEndian(buffer), BinaryPrimitives.ReadUInt32LittleEndian(buffer.AsSpan(4)));
+ }
+
+ /// Sends a command; returns the result status and payload.
+ public (NtStatus Status, byte[] Data) SendCommand(uint commandId, ReadOnlySpan commandData)
+ {
+ var device = RequireOpen();
+ var input = new byte[KmdfCommandHeader.WireSize + commandData.Length];
+ BinaryPrimitives.WriteUInt32LittleEndian(input, commandId);
+ BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(4), (uint)commandData.Length);
+ commandData.CopyTo(input.AsSpan(KmdfCommandHeader.WireSize));
+
+ var output = new byte[KmdfResultHeader.WireSize + 4096];
+ var written = Win32Native.SendIoctl(device, KmdfShimProtocol.SendCommand, input, output);
+ if (written < KmdfResultHeader.WireSize)
+ {
+ throw new InvalidOperationException("SendCommand returned a truncated result header.");
+ }
+ var status = (NtStatus)BinaryPrimitives.ReadUInt32LittleEndian(output);
+ var dataSize = BinaryPrimitives.ReadUInt32LittleEndian(output.AsSpan(4));
+ var data = new byte[Math.Min((int)dataSize, written - KmdfResultHeader.WireSize)];
+ output.AsSpan(KmdfResultHeader.WireSize, data.Length).CopyTo(data);
+ return (status, data);
+ }
+
+ /// Drains up to events from the shim ring.
+ public IReadOnlyList ReadEvents(int maxEvents = 64)
+ {
+ var device = RequireOpen();
+ var buffer = new byte[sizeof(uint) + maxEvents * KmdfEventRecord.WireSize + 4096];
+ var written = Win32Native.SendIoctl(device, KmdfShimProtocol.ReadEvents, ReadOnlySpan.Empty, buffer);
+ if (written < sizeof(uint))
+ {
+ return Array.Empty();
+ }
+ var count = BinaryPrimitives.ReadUInt32LittleEndian(buffer);
+ var events = new List((int)count);
+ var offset = sizeof(uint);
+ for (var i = 0; i < count && offset + KmdfEventRecord.WireSize <= written; i++)
+ {
+ var sequence = BinaryPrimitives.ReadUInt64LittleEndian(buffer.AsSpan(offset));
+ var eventId = BinaryPrimitives.ReadUInt32LittleEndian(buffer.AsSpan(offset + 8));
+ var dataSize = BinaryPrimitives.ReadUInt32LittleEndian(buffer.AsSpan(offset + 12));
+ offset += KmdfEventRecord.WireSize;
+ var data = new byte[Math.Min((int)dataSize, Math.Max(0, written - offset))];
+ buffer.AsSpan(offset, data.Length).CopyTo(data);
+ offset += data.Length;
+ events.Add(new KmdfEvent(sequence, eventId, data));
+ }
+ return events;
+ }
+
+ private SafeFileHandle RequireOpen() =>
+ _device ?? throw new InvalidOperationException("Call Open() first.");
+
+ public void Dispose()
+ {
+ _device?.Dispose();
+ _device = null;
+ }
+}
diff --git a/src/WindowsDriver.Interop/Kmdf/KmdfShimProtocol.cs b/src/WindowsDriver.Interop/Kmdf/KmdfShimProtocol.cs
new file mode 100644
index 0000000..6cfb26b
--- /dev/null
+++ b/src/WindowsDriver.Interop/Kmdf/KmdfShimProtocol.cs
@@ -0,0 +1,81 @@
+using System.Runtime.InteropServices;
+using WindowsDriver.Sdk;
+
+namespace WindowsDriver.Interop.Kmdf;
+
+///
+/// Wire contract between the managed KMDF control plane
+/// () and the KMDF shim driver (shim/WdsKmdfShim).
+/// All payloads are METHOD_BUFFERED little-endian; the C side mirrors every
+/// struct in wds_shim_protocol.h.
+///
+public static class KmdfShimProtocol
+{
+ /// Response magic for PING: the ASCII bytes "WSHI" read little-endian.
+ public const uint Magic = 0x49485357; // 'W','S','H','I'
+
+ public const uint ShimVersionMajor = 1;
+ public const uint ShimVersionMinor = 0;
+
+ private static uint Ctl(uint function, uint access) =>
+ WinIoctl.VendorControlCode(function, access);
+
+ /// Out: u32 magic — liveness check.
+ public static readonly uint Ping = Ctl(0x800, WinIoctl.FileAccessRead);
+
+ /// Out: (u32 major, u32 minor).
+ public static readonly uint GetVersion = Ctl(0x801, WinIoctl.FileAccessRead);
+
+ ///
+ /// In: KmdfCommandHeader + command data.
+ /// Out: KmdfResultHeader + result data.
+ ///
+ public static readonly uint SendCommand = Ctl(0x802, WinIoctl.FileAccessReadWrite);
+
+ /// Out: (u32 count) + count × KmdfEventRecord. Empty when the ring has no events.
+ public static readonly uint ReadEvents = Ctl(0x803, WinIoctl.FileAccessRead);
+
+ /// In: u32 eventMask (0 = all). Marks events consumed by the caller.
+ public static readonly uint AcknowledgeEvents = Ctl(0x804, WinIoctl.FileAccessWrite);
+}
+
+/// Header of a command sent to the shim via SendCommand (data follows).
+[StructLayout(LayoutKind.Sequential, Pack = 1)]
+public struct KmdfCommandHeader
+{
+ public uint CommandId;
+ public uint DataSize;
+ public const int WireSize = sizeof(uint) + sizeof(uint);
+}
+
+/// Header of the result returned by SendCommand (data follows).
+[StructLayout(LayoutKind.Sequential, Pack = 1)]
+public struct KmdfResultHeader
+{
+ public uint Status; // NTSTATUS
+ public uint DataSize;
+ public const int WireSize = sizeof(uint) + sizeof(uint);
+}
+
+/// Header of one event record returned by ReadEvents (data follows).
+[StructLayout(LayoutKind.Sequential, Pack = 1)]
+public struct KmdfEventRecord
+{
+ public ulong Sequence;
+ public uint EventId;
+ public uint DataSize;
+ public const int WireSize = sizeof(ulong) + sizeof(uint) + sizeof(uint);
+
+ /// Total wire size of a record with the given data length.
+ public static int TotalSize(int dataSize) => WireSize + dataSize;
+}
+
+/// One parsed event from the shim's ring buffer.
+public sealed record KmdfEvent(ulong Sequence, uint EventId, byte[] Data);
+
+/// Standard command IDs the shim understands (extend for your device).
+public static class KmdfCommandIds
+{
+ /// Vendor-defined commands start here (0..0xFF are reserved for the shim itself).
+ public const uint FirstVendorCommand = 0x100;
+}
diff --git a/src/WindowsDriver.Interop/Umdf/ManagedDriverBootstrap.cs b/src/WindowsDriver.Interop/Umdf/ManagedDriverBootstrap.cs
new file mode 100644
index 0000000..7eacdf6
--- /dev/null
+++ b/src/WindowsDriver.Interop/Umdf/ManagedDriverBootstrap.cs
@@ -0,0 +1,259 @@
+using System.Runtime.InteropServices;
+using WindowsDriver.Sdk;
+
+namespace WindowsDriver.Interop.Umdf;
+
+///
+/// Settings passed from the native UMDF shim into the managed bootstrap. The
+/// layout is mirrored byte-for-byte by the shim (see shim/ and docs/umdf-guide.md).
+///
+[StructLayout(LayoutKind.Sequential, Pack = 1)]
+public struct UmdfShimSettings
+{
+ /// Function pointer the shim provides for completing requests: int CompleteRequest(ulong id, int status, int bytes).
+ public nint CompleteRequest;
+
+ /// Function pointer for host-side logging: void Log(int level, void* utf8Message, int length).
+ public nint Log;
+
+ /// Function pointer the managed side calls when a queue must be armed again (manual dispatch).
+ public nint ArmQueue;
+
+ /// UTF-8 service name pointer (null-terminated), owned by the shim.
+ public nint DriverServiceNameUtf8;
+
+ /// UTF-8 fully-qualified managed driver type name, e.g. "VirtualAudio.Driver.SampleAudioDriver, VirtualAudio.Driver".
+ public nint DriverTypeNameUtf8;
+
+ /// 5 pointers — 8 bytes each on 64-bit Windows.
+ public static readonly int WireSize = 5 * IntPtr.Size;
+}
+
+///
+/// Entry points the native UMDF shim calls after hosting the .NET runtime with
+/// hostfxr (load_assembly_and_get_function_pointer). All callbacks are
+/// [UnmanagedCallersOnly] so the shim receives plain function pointers.
+///
+/// Marshaling rules: requests are pushed with WdsQueueRequest;
+/// the managed side completes them via the shim's CompleteRequest callback.
+/// NTSTATUS conventions match .
+///
+public static unsafe class ManagedDriverBootstrap
+{
+ private static DriverHost? _host;
+ private static nint _completeRequestPtr;
+ private static nint _logPtr;
+
+ /// hostfxr delegates here; returns an NTSTATUS (0 = success).
+ [UnmanagedCallersOnly(EntryPoint = "WdsInitialize")]
+ public static int Initialize(UmdfShimSettings* settings)
+ {
+ try
+ {
+ if (settings is null)
+ {
+ return AsInt(NtStatus.InvalidParameter);
+ }
+ _completeRequestPtr = settings->CompleteRequest;
+ _logPtr = settings->Log;
+
+ var serviceName = ReadUtf8(settings->DriverServiceNameUtf8) ?? "WdsDriver";
+ var driverTypeName = ReadUtf8(settings->DriverTypeNameUtf8)
+ ?? throw new DriverException(NtStatus.InvalidParameter, "DriverTypeNameUtf8 missing from shim settings.");
+
+ var log = new NativeShimLog(_logPtr);
+ _host = new DriverHost(log, registry: null, timeProvider: TimeProvider.System);
+
+ var driverType = Type.GetType(driverTypeName, throwOnError: true)!;
+ _host.StartAsync(driverType, serviceName).GetAwaiter().GetResult();
+ return AsInt(NtStatus.Success);
+ }
+ catch (DriverException ex)
+ {
+ return AsInt(ex.Status);
+ }
+ catch (Exception ex)
+ {
+ System.Console.Error.WriteLine($"WdsInitialize failed: {ex}");
+ return AsInt(NtStatus.Unsuccessful);
+ }
+ }
+
+ /// PnP: a device instance was reported. hardwareIds is an array of pointers to null-terminated UTF-16 strings.
+ [UnmanagedCallersOnly(EntryPoint = "WdsDeviceAdd")]
+ public static int DeviceAdd(byte* deviceInstanceIdUtf16, byte** hardwareIdsUtf16, int hardwareIdCount)
+ {
+ try
+ {
+ var host = _host ?? throw new DriverException(NtStatus.InvalidDeviceState, "Shim not initialized.");
+ var instanceId = Marshal.PtrToStringUni((nint)deviceInstanceIdUtf16) ?? string.Empty;
+ var hardwareIds = new List(hardwareIdCount);
+ for (var i = 0; i < hardwareIdCount; i++)
+ {
+ hardwareIds.Add(Marshal.PtrToStringUni((nint)hardwareIdsUtf16[i]) ?? string.Empty);
+ }
+ var addContext = new DeviceAddContext
+ {
+ DeviceInstanceId = instanceId,
+ HardwareIds = hardwareIds,
+ };
+ _ = host.AddDeviceAsync(addContext).GetAwaiter().GetResult();
+ return AsInt(NtStatus.Success);
+ }
+ catch (DriverException ex)
+ {
+ return AsInt(ex.Status);
+ }
+ catch (Exception ex)
+ {
+ ReportCrash("WdsDeviceAdd", ex);
+ return AsInt(NtStatus.Unsuccessful);
+ }
+ }
+
+ /// Pushes an IO request from the UMDF shim into the managed driver. kind: 0=DeviceControl, 1=Read, 2=Write.
+ [UnmanagedCallersOnly(EntryPoint = "WdsQueueRequest")]
+ public static int QueueRequest(
+ ulong requestId,
+ int kind,
+ uint ioControlCode,
+ byte* input,
+ int inputLength,
+ byte* output,
+ int outputLength)
+ {
+ try
+ {
+ var host = _host ?? throw new DriverException(NtStatus.InvalidDeviceState, "Shim not initialized.");
+ var device = host.Devices.FirstOrDefault() ?? throw new DriverException(NtStatus.NoSuchDevice, "No device instances.");
+ var managedKind = kind switch
+ {
+ 0 => IoRequestKind.DeviceControl,
+ 1 => IoRequestKind.Read,
+ 2 => IoRequestKind.Write,
+ _ => throw new DriverException(NtStatus.InvalidParameter, $"Unknown request kind {kind}."),
+ };
+ var inputCopy = inputLength > 0 ? new ReadOnlySpan(input, inputLength).ToArray() : Array.Empty();
+ var outputCopy = outputLength > 0 ? new byte[outputLength] : Array.Empty();
+
+ var request = new IoRequest(managedKind, ioControlCode, inputCopy, outputCopy, requestId);
+ request.Completed += completed =>
+ {
+ if (_completeRequestPtr != nint.Zero)
+ {
+ var complete = (delegate* unmanaged)_completeRequestPtr;
+ _ = complete(completed.Id, (int)completed.Status, completed.BytesTransferred);
+ }
+ if (outputLength > 0 && completed.BytesTransferred > 0 && output != null)
+ {
+ completed.OutputBuffer.Span.Slice(0, completed.BytesTransferred)
+ .CopyTo(new Span(output, outputLength));
+ }
+ };
+ device.DefaultQueue.Submit(request);
+ return AsInt(NtStatus.Success);
+ }
+ catch (DriverException ex)
+ {
+ return AsInt(ex.Status);
+ }
+ catch (Exception ex)
+ {
+ ReportCrash("WdsQueueRequest", ex);
+ return AsInt(NtStatus.Unsuccessful);
+ }
+ }
+
+ /// Power: device entered D0 (previousState: 0 unspecified, 1 D0, 2 D1, 3 D2, 4 D3).
+ [UnmanagedCallersOnly(EntryPoint = "WdsDeviceD0Entry")]
+ public static int DeviceD0Entry(int previousState) => RunLifecycle((device, ct) => device.D0EntryAsync((DevicePowerState)previousState, ct));
+
+ /// Power: device is leaving D0 (newState as above).
+ [UnmanagedCallersOnly(EntryPoint = "WdsDeviceD0Exit")]
+ public static int DeviceD0Exit(int newState) => RunLifecycle((device, ct) => device.D0ExitAsync((DevicePowerState)newState, ct));
+
+ /// PnP release: free hardware resources.
+ [UnmanagedCallersOnly(EntryPoint = "WdsDeviceRelease")]
+ public static int DeviceRelease() => RunLifecycle((device, ct) => device.ReleaseHardwareAsync(ct));
+
+ /// Final unload.
+ [UnmanagedCallersOnly(EntryPoint = "WdsDriverUnload")]
+ public static int DriverUnload()
+ {
+ try
+ {
+ var host = _host;
+ _host = null;
+ if (host is not null)
+ {
+ host.ShutdownAsync().GetAwaiter().GetResult();
+ }
+ return AsInt(NtStatus.Success);
+ }
+ catch (Exception ex)
+ {
+ ReportCrash("WdsDriverUnload", ex);
+ return AsInt(NtStatus.Unsuccessful);
+ }
+ }
+
+ private static int RunLifecycle(Func action)
+ {
+ try
+ {
+ var host = _host ?? throw new DriverException(NtStatus.InvalidDeviceState, "Shim not initialized.");
+ foreach (var device in host.Devices)
+ {
+ action(device.Device, CancellationToken.None).GetAwaiter().GetResult();
+ }
+ return AsInt(NtStatus.Success);
+ }
+ catch (DriverException ex)
+ {
+ return AsInt(ex.Status);
+ }
+ catch (Exception ex)
+ {
+ ReportCrash("lifecycle", ex);
+ return AsInt(NtStatus.Unsuccessful);
+ }
+ }
+
+ /// NTSTATUS values above int.MaxValue (0xC0000000+) need an unchecked widening.
+ private static int AsInt(NtStatus status) => unchecked((int)(uint)status);
+
+ private static string? ReadUtf8(nint pointer)
+ {
+ if (pointer == nint.Zero)
+ {
+ return null;
+ }
+ var length = 0;
+ while (((byte*)pointer)[length] != 0)
+ {
+ length++;
+ }
+ return System.Text.Encoding.UTF8.GetString((byte*)pointer, length);
+ }
+
+ private static void ReportCrash(string where, Exception ex) =>
+ System.Console.Error.WriteLine($"[{where}] {ex.GetType().Name}: {ex.Message}");
+
+ private sealed class NativeShimLog(nint sink) : IDriverLog
+ {
+ public bool IsEnabled(DriverLogLevel level) => sink != nint.Zero;
+
+ public unsafe void Log(DriverLogLevel level, string message)
+ {
+ if (sink == nint.Zero)
+ {
+ return;
+ }
+ var bytes = System.Text.Encoding.UTF8.GetBytes(message);
+ fixed (byte* p = bytes)
+ {
+ ((delegate* unmanaged)sink)((int)level, p, bytes.Length);
+ }
+ }
+ }
+}
diff --git a/src/WindowsDriver.Interop/Umdf/UmdfContracts.cs b/src/WindowsDriver.Interop/Umdf/UmdfContracts.cs
new file mode 100644
index 0000000..f37ad25
--- /dev/null
+++ b/src/WindowsDriver.Interop/Umdf/UmdfContracts.cs
@@ -0,0 +1,67 @@
+namespace WindowsDriver.Interop.Umdf;
+
+///
+/// C# mirrors of the key UMDF COM interfaces. These are *documentation
+/// contracts*: they describe which callbacks the native shim implements on the
+/// managed driver's behalf, with the same names and semantics as the real
+/// interfaces from wudfddi.h.
+///
+/// The shim (C++) implements the real COM interfaces (IWDFDriver, IWDFDevice,
+/// IWDFIoQueue, IWDFIoRequest, ...) with their genuine IIDs from the WDK and is
+/// registered in the INF as the UMDF service; it then forwards every callback
+/// into the managed host via . This layer
+/// deliberately avoids fake [ComImport] GUIDs — wrong IIDs would produce
+/// binaries that silently fail at runtime. When adding a new forwarded
+/// callback, mirror the vtable order from the WDK header.
+///
+public interface IWdfDriver
+{
+ /// IWDFDriver::CreateDevice — the shim creates a framework device.
+ void CreateDevice(IWdfDeviceInitialize init, ILifeTime lifetime);
+}
+
+public interface ILifeTime
+{
+ void OnDriverEntry();
+ void OnDeviceAdd(string deviceInstanceId, string[] hardwareIds);
+ void OnDriverUnload();
+}
+
+public interface IWdfDeviceInitialize
+{
+ void SetPnpPowerCallbacks();
+ void SetFileObjectConfig();
+}
+
+public interface IWdfDevice
+{
+ void CreateDeviceInterface(Guid interfaceClassGuid, string? referenceString);
+ IWdfIoQueue CreateIoQueue();
+ void ConfigureRequestHandling();
+}
+
+public interface IWdfIoQueue
+{
+ void DispatchSequential();
+ void DispatchParallel();
+ void DispatchManual();
+}
+
+public interface IWdfIoRequest
+{
+ uint IoControlCode { get; }
+ nint InputBuffer { get; }
+ int InputBufferLength { get; }
+ nint OutputBuffer { get; }
+ int OutputBufferLength { get; }
+ void Complete(int ntStatus);
+ void CompleteWithInformation(int ntStatus, int information);
+}
+
+public interface IWdfFile
+{
+ IWdfDevice GetDevice();
+}
+
+/// The subset of UMDF version information the shim reports to the managed host.
+public sealed record UmdfHostInfo(string DriverServiceName, string RegistryPath, int UmdfVersionMajor, int UmdfVersionMinor);
diff --git a/src/WindowsDriver.Interop/Umdf/UmdfShimContract.cs b/src/WindowsDriver.Interop/Umdf/UmdfShimContract.cs
new file mode 100644
index 0000000..37474f4
--- /dev/null
+++ b/src/WindowsDriver.Interop/Umdf/UmdfShimContract.cs
@@ -0,0 +1,67 @@
+namespace WindowsDriver.Interop.Umdf;
+
+///
+/// The exact C declarations the native UMDF shim exposes (exports of the shim
+/// DLL, e.g. WdsShimU.dll) and the managed function pointers it resolves via
+/// hostfxr. Keep this in sync with shim/ and docs/umdf-guide.md.
+///
+public static class UmdfShimContract
+{
+ /// Exported function names of the native shim.
+ public static class ShimExports
+ {
+ public const string DllGetClassObject = "DllGetClassObject"; // standard COM entry the WUDFHost uses
+ public const string DriverEntry = "DriverEntry"; // UMDF module entry
+ }
+
+ /// Managed entry points (resolved via hostfxr load_assembly_and_get_function_pointer).
+ public static class ManagedEntryPoints
+ {
+ public const string Initialize = "WdsInitialize";
+ public const string DeviceAdd = "WdsDeviceAdd";
+ public const string QueueRequest = "WdsQueueRequest";
+ public const string DeviceD0Entry = "WdsDeviceD0Entry";
+ public const string DeviceD0Exit = "WdsDeviceD0Exit";
+ public const string DeviceRelease = "WdsDeviceRelease";
+ public const string DriverUnload = "WdsDriverUnload";
+ }
+
+ ///
+ /// C header the shim compiles against (mirror of the managed struct + entry
+ /// points above). Included here as the single source of truth for the ABI.
+ ///
+ public const string ShimHeader = """
+// wds_shim_abi.h — ABI between the native UMDF shim and the managed driver host.
+// Include from the shim project; the managed side mirrors it in UmdfShimSettings.
+#pragma once
+#include
+
+typedef int (*PFN_WdsCompleteRequest)(unsigned long long requestId, int ntStatus, int bytesTransferred);
+typedef void (*PFN_WdsLog)(int level, const unsigned char* utf8Message, int length);
+typedef void (*PFN_WdsArmQueue)(int queueIndex);
+
+typedef struct WDS_SHIM_SETTINGS {
+ PFN_WdsCompleteRequest CompleteRequest;
+ PFN_WdsLog Log;
+ PFN_WdsArmQueue ArmQueue;
+ const unsigned char* DriverServiceNameUtf8; // null-terminated
+ const unsigned char* DriverTypeNameUtf8; // null-terminated
+} WDS_SHIM_SETTINGS;
+
+// Managed entry points, resolved with hostfxr's
+// load_assembly_and_get_function_pointer:
+typedef int (*PFN_WdsInitialize)(WDS_SHIM_SETTINGS* settings);
+typedef int (*PFN_WdsDeviceAdd)(const wchar_t* deviceInstanceId,
+ const wchar_t** hardwareIds,
+ int hardwareIdCount);
+typedef int (*PFN_WdsQueueRequest)(unsigned long long requestId,
+ int kind, // 0=DeviceControl, 1=Read, 2=Write
+ unsigned long ioControlCode,
+ const unsigned char* input, int inputLength,
+ unsigned char* output, int outputLength);
+typedef int (*PFN_WdsDeviceD0Entry)(int previousState);
+typedef int (*PFN_WdsDeviceD0Exit)(int newState);
+typedef int (*PFN_WdsDeviceRelease)(void);
+typedef int (*PFN_WdsDriverUnload)(void);
+""";
+}
diff --git a/src/WindowsDriver.Interop/Win32/Win32Native.cs b/src/WindowsDriver.Interop/Win32/Win32Native.cs
new file mode 100644
index 0000000..c55018f
--- /dev/null
+++ b/src/WindowsDriver.Interop/Win32/Win32Native.cs
@@ -0,0 +1,85 @@
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+namespace WindowsDriver.Interop.Win32;
+
+///
+/// The Win32 P/Invoke surface used by the KMDF control plane. Real declarations
+/// (kernel32.dll), safe-handle based, usable from any .NET process.
+///
+public static class Win32Native
+{
+ // CreateFile access/share/disposition flags (winbase.h)
+ public const uint GenericRead = 0x80000000;
+ public const uint GenericWrite = 0x40000000;
+ public const uint FileShareRead = 0x00000001;
+ public const uint FileShareWrite = 0x00000002;
+ public const uint OpenExisting = 3;
+ public const uint FileFlagOverlapped = 0x40000000;
+
+ /// Opens a device (\\.\Name or the symbolic link from CreateDeviceInterface).
+ [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
+ public static extern SafeFileHandle CreateFileW(
+ string lpFileName,
+ uint dwDesiredAccess,
+ uint dwShareMode,
+ IntPtr lpSecurityAttributes,
+ uint dwCreationDisposition,
+ uint dwFlagsAndAttributes,
+ IntPtr hTemplateFile);
+
+ /// Sends a buffered IOCTL to an opened device handle.
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool DeviceIoControl(
+ SafeFileHandle hDevice,
+ uint dwIoControlCode,
+ IntPtr lpInBuffer,
+ uint nInBufferSize,
+ IntPtr lpOutBuffer,
+ uint nOutBufferSize,
+ out uint lpBytesReturned,
+ IntPtr lpOverlapped);
+
+ ///
+ /// Sends a buffered IOCTL and throws on failure;
+ /// returns the bytes written to the output buffer.
+ ///
+ public static int SendIoctl(SafeFileHandle device, uint controlCode, ReadOnlySpan input, Span output)
+ {
+ var inPtr = IntPtr.Zero;
+ var outPtr = IntPtr.Zero;
+ try
+ {
+ if (input.Length > 0)
+ {
+ inPtr = Marshal.AllocHGlobal(input.Length);
+ Marshal.Copy(input.ToArray(), 0, inPtr, input.Length);
+ }
+ if (output.Length > 0)
+ {
+ outPtr = Marshal.AllocHGlobal(output.Length);
+ }
+ var ok = DeviceIoControl(device, controlCode, inPtr, (uint)input.Length, outPtr, (uint)output.Length, out var returned, IntPtr.Zero);
+ if (!ok)
+ {
+ throw new Win32Exception(Marshal.GetLastWin32Error(),
+ $"DeviceIoControl(0x{controlCode:X8}) failed.");
+ }
+ var copied = Math.Min((int)returned, output.Length);
+ if (copied > 0)
+ {
+ var managed = new byte[copied];
+ Marshal.Copy(outPtr, managed, 0, copied);
+ managed.CopyTo(output);
+ }
+ return copied;
+ }
+ finally
+ {
+ if (inPtr != IntPtr.Zero) Marshal.FreeHGlobal(inPtr);
+ if (outPtr != IntPtr.Zero) Marshal.FreeHGlobal(outPtr);
+ }
+ }
+}
diff --git a/src/WindowsDriver.Interop/WindowsDriver.Interop.csproj b/src/WindowsDriver.Interop/WindowsDriver.Interop.csproj
new file mode 100644
index 0000000..dcd1346
--- /dev/null
+++ b/src/WindowsDriver.Interop/WindowsDriver.Interop.csproj
@@ -0,0 +1,20 @@
+
+
+
+ Native interop layer of the Windows Driver SDK: UMDF shim contracts (C header + managed bootstrap), KMDF control-plane client (CreateFile/DeviceIoControl P/Invoke and wire structs), and the Win32 P/Invoke declarations used by both.
+ WindowsDriver.Interop
+ windows;driver;umdf;kmdf;interop;hostfxr;ioctl
+ LICENSE
+
+ true
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/WindowsDriver.Sdk/Audio/AudioIoctlCodes.cs b/src/WindowsDriver.Sdk/Audio/AudioIoctlCodes.cs
new file mode 100644
index 0000000..8f65755
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Audio/AudioIoctlCodes.cs
@@ -0,0 +1,45 @@
+namespace WindowsDriver.Sdk.Audio;
+
+///
+/// IOCTL contract implemented by (and any audio
+/// driver built on the SDK's audio module). All IOCTLs use METHOD_BUFFERED.
+/// Payload layouts are documented per field and implemented with
+/// — the same layouts the KMDF/UMDF shims forward.
+///
+public static class AudioIoctlCodes
+{
+ private const uint DeviceType = WinIoctl.FileDeviceSound;
+
+ // Vendor function codes start at WinIoctl.FirstVendorFunction (0x800).
+ private static uint Ctl(uint function, uint access) => WinIoctl.VendorControlCode(function, access, DeviceType);
+
+ /// Out: u32 count, then count × (u32 rate, u32 bits, u32 channels).
+ public static readonly uint GetSupportedFormats = Ctl(0x800, WinIoctl.FileAccessRead);
+
+ /// In: (u32 rate, u32 bits, u32 channels). Accepted only while Stopped; out-of-range rates are adjusted by the negotiator.
+ public static readonly uint SetFormat = Ctl(0x801, WinIoctl.FileAccessWrite);
+
+ /// Out: (u32 rate, u32 bits, u32 channels) — the active format.
+ public static readonly uint GetFormat = Ctl(0x802, WinIoctl.FileAccessRead);
+
+ /// No payload. Stopped/Paused → Running.
+ public static readonly uint Start = Ctl(0x803, WinIoctl.FileAccessAny);
+
+ /// No payload. Any → Stopped (position retained).
+ public static readonly uint Stop = Ctl(0x804, WinIoctl.FileAccessAny);
+
+ /// No payload. Running → Paused.
+ public static readonly uint Pause = Ctl(0x805, WinIoctl.FileAccessAny);
+
+ /// Out: (u64 bytePosition, u64 framePosition, u32 state).
+ public static readonly uint GetPosition = Ctl(0x806, WinIoctl.FileAccessRead);
+
+ /// In: (f32 masterGain 0..1, u8 mute, u32 rampMs, u32 channelCount, then channelCount × f32). channelCount 0 = master only.
+ public static readonly uint SetVolume = Ctl(0x807, WinIoctl.FileAccessWrite);
+
+ /// Out: (f32 masterGain target, f32 currentGain, u8 mute, u32 rampRemainingMs, u32 channelCount, channelCount × f32).
+ public static readonly uint GetVolume = Ctl(0x808, WinIoctl.FileAccessRead);
+
+ /// In: (u32 bytesToSkip). Skips playback/output bytes; used by clients that drop stale data.
+ public static readonly uint SkipOutput = Ctl(0x809, WinIoctl.FileAccessWrite);
+}
diff --git a/src/WindowsDriver.Sdk/Audio/AudioState.cs b/src/WindowsDriver.Sdk/Audio/AudioState.cs
new file mode 100644
index 0000000..4816625
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Audio/AudioState.cs
@@ -0,0 +1,179 @@
+namespace WindowsDriver.Sdk.Audio;
+
+/// Playback state machine states (mirrors KSSTATE: stop/pause/run).
+public enum AudioDeviceState
+{
+ Stopped,
+ Paused,
+ Running,
+}
+
+///
+/// Small explicit state machine for audio start/stop/pause transitions.
+/// Invalid transitions throw with
+/// so IOCTL handlers can simply let
+/// it bubble to request completion.
+///
+public sealed class AudioDeviceStateMachine
+{
+ private readonly object _gate = new();
+
+ public AudioDeviceState State { get; private set; } = AudioDeviceState.Stopped;
+
+ public event Action? Transitioned;
+
+ /// Stopped/Paused → Running. Starting while already running is invalid.
+ public void Start()
+ {
+ Transition(AudioDeviceState.Running, allowedFrom: [AudioDeviceState.Stopped, AudioDeviceState.Paused]);
+ }
+
+ /// Running → Paused.
+ public void Pause()
+ {
+ Transition(AudioDeviceState.Paused, allowedFrom: [AudioDeviceState.Running]);
+ }
+
+ /// Any → Stopped.
+ public void Stop()
+ {
+ Transition(AudioDeviceState.Stopped, allowedFrom: [AudioDeviceState.Running, AudioDeviceState.Paused, AudioDeviceState.Stopped]);
+ }
+
+ public AudioDeviceState Snapshot() { lock (_gate) { return State; } }
+
+ private void Transition(AudioDeviceState target, AudioDeviceState[] allowedFrom)
+ {
+ AudioDeviceState previous;
+ lock (_gate)
+ {
+ previous = State;
+ if (previous == target)
+ {
+ return; // idempotent
+ }
+ if (!allowedFrom.Contains(previous))
+ {
+ throw new DriverException(NtStatus.InvalidDeviceState, $"Cannot transition {previous} → {target}.");
+ }
+ State = target;
+ }
+ Transitioned?.Invoke(previous, target);
+ }
+}
+
+///
+/// Master/channel volume with dB conversion and a linear ramp, kept separate
+/// from the device so tests can drive it directly.
+///
+public sealed class VolumeState
+{
+ private readonly object _gate = new();
+ private float[] _channelGains;
+ private float _rampStartGain;
+ private float _rampTargetGain;
+ private TimeSpan _rampDuration;
+ private long _rampStartTimestampTicks;
+
+ public VolumeState(int channels, TimeProvider? timeProvider = null)
+ {
+ Channels = channels;
+ TimeProvider = timeProvider ?? TimeProvider.System;
+ _channelGains = new float[channels];
+ Array.Fill(_channelGains, 1f);
+ _rampTargetGain = 1f;
+ _rampStartGain = 1f;
+ }
+
+ public TimeProvider TimeProvider { get; }
+ public int Channels { get; }
+
+ public bool Mute { get; private set; }
+
+ /// Linear ramp target (0..1). Reaches the target after .
+ public float TargetGain { get; private set; } = 1f;
+
+ /// Current gain including the in-progress ramp and mute (0..1).
+ public float CurrentGain
+ {
+ get
+ {
+ lock (_gate)
+ {
+ var gain = _rampDuration <= TimeSpan.Zero
+ ? _rampTargetGain
+ : Lerp(_rampStartGain, _rampTargetGain, Progress());
+ return Mute ? 0f : Clamp(gain);
+ }
+ }
+ }
+
+ /// Remaining ramp time; zero when no ramp is in progress.
+ public TimeSpan RampRemaining
+ {
+ get
+ {
+ lock (_gate)
+ {
+ if (_rampDuration <= TimeSpan.Zero)
+ {
+ return TimeSpan.Zero;
+ }
+ var remaining = _rampDuration - (TimeProvider.GetUtcNow() - new DateTimeOffset(_rampStartTimestampTicks, TimeSpan.Zero));
+ return remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero;
+ }
+ }
+ }
+
+ /// Sets the master target gain (clamped to 0..1) and starts a ramp.
+ public void SetMasterGain(float target, TimeSpan ramp = default)
+ {
+ lock (_gate)
+ {
+ _rampStartGain = CurrentGain;
+ _rampTargetGain = Clamp(target);
+ _rampDuration = ramp;
+ _rampStartTimestampTicks = TimeProvider.GetUtcNow().UtcTicks;
+ TargetGain = _rampTargetGain;
+ }
+ }
+
+ public void SetMute(bool mute)
+ {
+ lock (_gate)
+ {
+ Mute = mute;
+ }
+ }
+
+ public float GetChannelGain(int channel) { lock (_gate) { return Clamp(_channelGains[channel]); } }
+
+ public void SetChannelGain(int channel, float gain)
+ {
+ lock (_gate)
+ {
+ _channelGains[channel] = Clamp(gain);
+ }
+ }
+
+ /// 20·log10(gain) dB, or negative infinity for silence.
+ public double CurrentGainDecibels
+ {
+ get
+ {
+ var g = CurrentGain;
+ return g <= 0f ? double.NegativeInfinity : 20 * Math.Log10(g);
+ }
+ }
+
+ private double Progress()
+ {
+ var elapsedTicks = TimeProvider.GetUtcNow().UtcTicks - _rampStartTimestampTicks;
+ var progress = elapsedTicks / (double)_rampDuration.Ticks;
+ return Math.Clamp(progress, 0.0, 1.0);
+ }
+
+ private static float Clamp(float gain) => Math.Clamp(gain, 0f, 1f);
+
+ private static float Lerp(float a, float b, double t) => (float)(a + (b - a) * t);
+}
diff --git a/src/WindowsDriver.Sdk/Audio/PcmFormat.cs b/src/WindowsDriver.Sdk/Audio/PcmFormat.cs
new file mode 100644
index 0000000..0f1d002
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Audio/PcmFormat.cs
@@ -0,0 +1,87 @@
+namespace WindowsDriver.Sdk.Audio;
+
+///
+/// An uncompressed PCM format. Byte order is little-endian (native on Windows);
+/// multi-channel data is interleaved.
+///
+public sealed record PcmFormat(int SampleRateHz, int BitsPerSample, int Channels)
+{
+ public int BytesPerFrame => (BitsPerSample + 7) / 8 * Channels;
+
+ public long BytesPerSecond => (long)SampleRateHz * BytesPerFrame;
+
+ public override string ToString() => $"{SampleRateHz} Hz / {BitsPerSample}-bit / {Channels}ch";
+}
+
+/// Result of a format negotiation attempt.
+public sealed record AudioNegotiationResult
+{
+ public PcmFormat? Accepted { get; init; }
+ public NtStatus Status { get; init; } = NtStatus.Success;
+ public string? Reason { get; init; }
+
+ public bool IsAccepted => Status.IsSuccess();
+}
+
+///
+/// Chooses the best supported PCM format for a requested one — the same job
+/// IMiniport's DataRangeIntersection does for real audio drivers. Preference
+/// order: exact match, then sample rate, then bit depth, then channel count.
+///
+public sealed class AudioFormatNegotiator
+{
+ private readonly List _supported;
+
+ public AudioFormatNegotiator(IEnumerable supported)
+ {
+ _supported = supported.ToList();
+ if (_supported.Count == 0)
+ {
+ throw new ArgumentException("At least one supported format is required.", nameof(supported));
+ }
+ }
+
+ public IReadOnlyList SupportedFormats => _supported;
+
+ public PcmFormat Default => _supported[0];
+
+ /// Negotiates a concrete format from the request.
+ public AudioNegotiationResult Negotiate(PcmFormat requested)
+ {
+ if (requested.SampleRateHz <= 0 || requested.BitsPerSample <= 0 || requested.Channels <= 0)
+ {
+ return new AudioNegotiationResult
+ {
+ Status = NtStatus.InvalidParameter,
+ Reason = $"Format {requested} has non-positive fields.",
+ };
+ }
+
+ var exact = _supported.FirstOrDefault(f => f == requested);
+ if (exact is not null)
+ {
+ return new AudioNegotiationResult { Accepted = exact };
+ }
+
+ // Nothing exact: pick the supported format with the lowest "distance",
+ // weighting sample rate heaviest (listeners notice pitch shifts most).
+ var best = _supported
+ .Select(f => (
+ Format: f,
+ Score: Math.Abs(f.SampleRateHz - requested.SampleRateHz) * 1.0
+ + Math.Abs(f.BitsPerSample - requested.BitsPerSample) * 100.0
+ + Math.Abs(f.Channels - requested.Channels) * 1000.0))
+ .OrderBy(x => x.Score)
+ .First();
+
+ return new AudioNegotiationResult
+ {
+ Accepted = best.Format,
+ Status = NtStatus.Success,
+ Reason = $"Requested {requested}; closest supported is {best.Format}.",
+ };
+ }
+
+ /// True when the exact format is supported (no adjustment needed).
+ public bool IsSupported(PcmFormat format) => _supported.Contains(format);
+}
diff --git a/src/WindowsDriver.Sdk/Audio/PcmSources.cs b/src/WindowsDriver.Sdk/Audio/PcmSources.cs
new file mode 100644
index 0000000..52967ba
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Audio/PcmSources.cs
@@ -0,0 +1,166 @@
+using System.Buffers.Binary;
+
+namespace WindowsDriver.Sdk.Audio;
+
+/// Produces PCM frames into the device ring buffer while running (Capture/Loopback mode).
+public interface IAudioSource
+{
+ /// Fills the destination with complete frames; returns the number of frames written.
+ int FillFrames(Span destination, PcmFormat format);
+}
+
+/// Consumes PCM frames from the device ring buffer (Render mode).
+public interface IAudioSink
+{
+ void WriteFrames(ReadOnlySpan frames, PcmFormat format);
+}
+
+///
+/// Continuous sine generator — the virtual "hardware" tone for demos and tests.
+/// Phase is accumulated across calls so long captures stay seamless. 16-bit
+/// signed little-endian only (the common test format).
+///
+public sealed class SineSource : IAudioSource
+{
+ private long _framesGenerated;
+ private double _phase;
+
+ public SineSource(double frequencyHz = 440.0, double amplitude = 0.25)
+ {
+ if (amplitude <= 0 || amplitude > 1)
+ {
+ throw new ArgumentOutOfRangeException(nameof(amplitude), "Amplitude must be in (0, 1].");
+ }
+ FrequencyHz = frequencyHz;
+ Amplitude = amplitude;
+ }
+
+ public double FrequencyHz { get; set; }
+ public double Amplitude { get; }
+ public long FramesGenerated => Interlocked.Read(ref _framesGenerated);
+
+ public int FillFrames(Span destination, PcmFormat format)
+ {
+ if (format.BitsPerSample != 16)
+ {
+ throw new NotSupportedException("SineSource supports 16-bit PCM only; extend FillFrames for other depths.");
+ }
+ var bytesPerFrame = format.BytesPerFrame;
+ var frames = destination.Length / bytesPerFrame;
+ var step = 2 * Math.PI * FrequencyHz / format.SampleRateHz;
+ for (var f = 0; f < frames; f++)
+ {
+ var sample = (short)Math.Round(Amplitude * short.MaxValue * Math.Sin(_phase + step * f));
+ var offset = f * bytesPerFrame;
+ for (var c = 0; c < format.Channels; c++)
+ {
+ BinaryPrimitives.WriteInt16LittleEndian(destination.Slice(offset + c * sizeof(short)), sample);
+ }
+ }
+ _phase += step * frames;
+ _phase %= 2 * Math.PI;
+ Interlocked.Add(ref _framesGenerated, frames);
+ return frames;
+ }
+}
+
+///
+/// Applies a linear gain to interleaved 16-bit PCM samples in place, clamping
+/// to the 16-bit range. Channel gains can be applied per channel position.
+///
+public static class PcmVolume
+{
+ public static void ApplyMasterGain16(Span interleaved16, float gain)
+ {
+ if (gain >= 0.999f && gain <= 1.001f)
+ {
+ return;
+ }
+ for (var i = 0; i + sizeof(short) <= interleaved16.Length; i += sizeof(short))
+ {
+ var sample = BinaryPrimitives.ReadInt16LittleEndian(interleaved16.Slice(i));
+ var scaled = Math.Round(sample * gain);
+ BinaryPrimitives.WriteInt16LittleEndian(interleaved16.Slice(i), (short)Math.Clamp(scaled, short.MinValue, short.MaxValue));
+ }
+ }
+}
+
+///
+/// Writes received PCM into a standard 44-byte-header RIFF/WAVE stream — used
+/// by the sample and tests to capture the virtual device's render output.
+///
+public sealed class PcmWavWriter : IAudioSink, IDisposable
+{
+ private readonly Stream _stream;
+ private readonly PcmFormat _format;
+ private readonly bool _leaveOpen;
+ private long _dataBytes;
+ private bool _finalized;
+
+ public PcmWavWriter(Stream stream, PcmFormat format, bool leaveOpen = false)
+ {
+ _stream = stream ?? throw new ArgumentNullException(nameof(stream));
+ _format = format;
+ _leaveOpen = leaveOpen;
+ WriteHeader(_stream, format, dataBytes: 0);
+ }
+
+ /// Bytes of PCM data written so far (excludes the 44-byte header).
+ public long DataBytes => _dataBytes;
+
+ public void WriteFrames(ReadOnlySpan frames, PcmFormat format)
+ {
+ if (format != _format)
+ {
+ throw new InvalidOperationException($"WAV writer was created for {_format} but received {format}.");
+ }
+ _stream.Write(frames);
+ _dataBytes += frames.Length;
+ }
+
+ /// Patches the RIFF chunk sizes so the file is valid. Also called by Dispose.
+ public void WriteTrailer()
+ {
+ if (_finalized || !_stream.CanSeek)
+ {
+ return;
+ }
+ Span size = stackalloc byte[4];
+ BinaryPrimitives.WriteInt32LittleEndian(size, (int)(36 + _dataBytes));
+ _stream.Seek(4, SeekOrigin.Begin);
+ _stream.Write(size);
+ BinaryPrimitives.WriteInt32LittleEndian(size, (int)_dataBytes);
+ _stream.Seek(40, SeekOrigin.Begin);
+ _stream.Write(size);
+ _stream.Flush();
+ _finalized = true;
+ }
+
+ public void Dispose()
+ {
+ WriteTrailer();
+ if (!_leaveOpen)
+ {
+ _stream.Dispose();
+ }
+ }
+
+ private static void WriteHeader(Stream stream, PcmFormat format, long dataBytes)
+ {
+ Span header = stackalloc byte[44];
+ "RIFF"u8.CopyTo(header.Slice(0));
+ BinaryPrimitives.WriteInt32LittleEndian(header.Slice(4), (int)(36 + dataBytes));
+ "WAVE"u8.CopyTo(header.Slice(8));
+ "fmt "u8.CopyTo(header.Slice(12));
+ BinaryPrimitives.WriteInt32LittleEndian(header.Slice(16), 16); // fmt chunk size
+ BinaryPrimitives.WriteInt16LittleEndian(header.Slice(20), 1); // PCM
+ BinaryPrimitives.WriteInt16LittleEndian(header.Slice(22), (short)format.Channels);
+ BinaryPrimitives.WriteInt32LittleEndian(header.Slice(24), format.SampleRateHz);
+ BinaryPrimitives.WriteInt32LittleEndian(header.Slice(28), (int)format.BytesPerSecond);
+ BinaryPrimitives.WriteInt16LittleEndian(header.Slice(32), (short)format.BytesPerFrame);
+ BinaryPrimitives.WriteInt16LittleEndian(header.Slice(34), (short)format.BitsPerSample);
+ "data"u8.CopyTo(header.Slice(36));
+ BinaryPrimitives.WriteInt32LittleEndian(header.Slice(40), (int)dataBytes);
+ stream.Write(header);
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Audio/VirtualAudioDevice.cs b/src/WindowsDriver.Sdk/Audio/VirtualAudioDevice.cs
new file mode 100644
index 0000000..2bd666d
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Audio/VirtualAudioDevice.cs
@@ -0,0 +1,444 @@
+namespace WindowsDriver.Sdk.Audio;
+
+/// Direction of the virtual audio device.
+public enum AudioVirtualMode
+{
+ /// The source produces audio; clients read frames (capture/loopback-style).
+ Capture,
+
+ /// Clients write frames; the sink consumes them (render-style).
+ Render,
+
+ /// Clients write frames that come back on Read — a full loopback.
+ Loopback,
+}
+
+/// Configuration for .
+public sealed class AudioVirtualOptions
+{
+ public IReadOnlyList SupportedFormats { get; init; } =
+ [
+ new PcmFormat(44100, 16, 2),
+ new PcmFormat(48000, 16, 2),
+ new PcmFormat(96000, 16, 2),
+ ];
+
+ public AudioVirtualMode Mode { get; init; } = AudioVirtualMode.Capture;
+
+ public int RingBufferBytes { get; init; } = 65536;
+
+ /// Required for Capture/Loopback.
+ public IAudioSource? Source { get; init; }
+
+ /// Required for Render.
+ public IAudioSink? Sink { get; init; }
+
+ /// Applies the current master/channel gain on the device output path.
+ public bool ApplyVolumeToOutput { get; init; } = true;
+}
+
+///
+/// A complete virtual audio device built on the SDK: format negotiation, a PCM
+/// ring buffer standing in for hardware DMA, a start/stop/pause state machine,
+/// volume with ramps, and the IOCTL contract.
+///
+/// Time is taken from the host's — production
+/// hosts pass a real-time provider, tests pass a controllable fake. Byte position
+/// advances with wall time while Running, exactly like a real render/capture
+/// clock, and the ring buffer is lazily filled on demand.
+///
+public class VirtualAudioDevice : DeviceBase
+{
+ private readonly AudioVirtualOptions _options;
+ private readonly AudioFormatNegotiator _negotiator;
+ private readonly ByteRingBuffer _ring;
+ private readonly object _gate = new();
+ private long _startTicks;
+ private long _pausedAccumTicks;
+ private long _pausedAtTicks;
+ private long _producedFrames;
+
+ public VirtualAudioDevice(DeviceContext context, AudioVirtualOptions? options = null)
+ : base(context)
+ {
+ _options = options ?? new AudioVirtualOptions();
+ _negotiator = new AudioFormatNegotiator(_options.SupportedFormats);
+ _ring = new ByteRingBuffer(_options.RingBufferBytes);
+ CurrentFormat = _negotiator.Default;
+ Volume = new VolumeState(CurrentFormat.Channels, Driver.TimeProvider);
+
+ DefaultQueue
+ .OnDeviceControl(HandleDeviceControlAsync)
+ .OnRead(HandleReadAsync)
+ .OnWrite(HandleWriteAsync);
+ }
+
+ public PcmFormat CurrentFormat { get; private set; }
+
+ public AudioDeviceStateMachine State { get; } = new();
+
+ public VolumeState Volume { get; private set; }
+
+ public ByteRingBuffer Ring => _ring;
+
+ public AudioFormatNegotiator Negotiator => _negotiator;
+
+ /// Bytes the device has produced/consumed while running (the audio position).
+ public long ProducedFrames
+ {
+ get { lock (_gate) { return _producedFrames; } }
+ }
+
+ // ----- Lifecycle -----
+
+ public override Task OnPrepareHardwareAsync(CancellationToken cancellationToken)
+ {
+ Context.Log.Info("audio device: preparing hardware, {0} supported formats", _negotiator.SupportedFormats.Count);
+ return Task.CompletedTask;
+ }
+
+ public override Task OnD0EntryAsync(DevicePowerState previousState, CancellationToken cancellationToken)
+ {
+ Context.Log.Info("audio device: D0 entry from {0}", previousState);
+ return Task.CompletedTask;
+ }
+
+ public override Task OnD0ExitAsync(DevicePowerState newState, CancellationToken cancellationToken)
+ {
+ State.Stop();
+ Context.Log.Info("audio device: D0 exit to {0}", newState);
+ return Task.CompletedTask;
+ }
+
+ // ----- IO handlers -----
+
+ private Task HandleReadAsync(IoRequest request, CancellationToken ct)
+ {
+ if (_options.Mode == AudioVirtualMode.Render)
+ {
+ request.Fail(NtStatus.InvalidDeviceRequest);
+ return Task.CompletedTask;
+ }
+ PumpTo(now());
+ var bytesPerFrame = CurrentFormat.BytesPerFrame;
+ var requestedFrames = request.OutputBuffer.Length / bytesPerFrame;
+ var destination = request.OutputBuffer.Slice(0, requestedFrames * bytesPerFrame);
+ var read = _ring.Read(destination.Span);
+ if (_options.ApplyVolumeToOutput)
+ {
+ PcmVolume.ApplyMasterGain16(destination.Span.Slice(0, read), Volume.CurrentGain);
+ }
+ request.Complete(NtStatus.Success, read);
+ return Task.CompletedTask;
+ }
+
+ private Task HandleWriteAsync(IoRequest request, CancellationToken ct)
+ {
+ if (_options.Mode == AudioVirtualMode.Capture)
+ {
+ request.Fail(NtStatus.InvalidDeviceRequest);
+ return Task.CompletedTask;
+ }
+ var bytesPerFrame = CurrentFormat.BytesPerFrame;
+ var frames = request.InputBuffer.Length / bytesPerFrame;
+ var data = request.InputBuffer.Slice(0, frames * bytesPerFrame);
+ var accepted = _ring.Write(data.Span);
+ PumpTo(now()); // drain toward the sink; dropped frames are counted by the ring
+ request.Complete(NtStatus.Success, accepted);
+ return Task.CompletedTask;
+ }
+
+ ///
+ /// Handles the contract. Subclasses override
+ /// this to add device-specific IOCTLs and fall back to base for the rest.
+ ///
+ protected virtual Task HandleDeviceControlAsync(IoRequest request, CancellationToken ct)
+ {
+ var code = request.IoControlCode;
+ if (code == AudioIoctlCodes.GetSupportedFormats)
+ {
+ HandleGetSupportedFormats(request);
+ }
+ else if (code == AudioIoctlCodes.SetFormat)
+ {
+ HandleSetFormat(request);
+ }
+ else if (code == AudioIoctlCodes.GetFormat)
+ {
+ HandleGetFormat(request);
+ }
+ else if (code == AudioIoctlCodes.Start)
+ {
+ State.Start();
+ StartClock();
+ request.Complete(NtStatus.Success);
+ }
+ else if (code == AudioIoctlCodes.Stop)
+ {
+ State.Stop();
+ request.Complete(NtStatus.Success);
+ }
+ else if (code == AudioIoctlCodes.Pause)
+ {
+ PauseClock();
+ State.Pause();
+ request.Complete(NtStatus.Success);
+ }
+ else if (code == AudioIoctlCodes.GetPosition)
+ {
+ HandleGetPosition(request);
+ }
+ else if (code == AudioIoctlCodes.SetVolume)
+ {
+ HandleSetVolume(request);
+ }
+ else if (code == AudioIoctlCodes.GetVolume)
+ {
+ HandleGetVolume(request);
+ }
+ else if (code == AudioIoctlCodes.SkipOutput)
+ {
+ var bytes = WireFormat.ReadUInt32(request.InputBuffer.Span, 0);
+ var skipped = _ring.Skip((int)Math.Min(bytes, int.MaxValue));
+ request.Complete(NtStatus.Success, sizeof(uint));
+ Context.Log.Trace("skipped {0} output bytes", skipped);
+ }
+ else
+ {
+ request.Fail(NtStatus.InvalidDeviceRequest);
+ }
+ return Task.CompletedTask;
+ }
+
+ private void HandleGetSupportedFormats(IoRequest request)
+ {
+ var formats = _negotiator.SupportedFormats;
+ var needed = sizeof(uint) + formats.Count * 12;
+ if (request.OutputBuffer.Length < needed)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ return;
+ }
+ var span = request.OutputBuffer.Span;
+ WireFormat.WriteUInt32(span, 0, (uint)formats.Count);
+ for (var i = 0; i < formats.Count; i++)
+ {
+ var baseOffset = sizeof(uint) + i * 12;
+ WireFormat.WriteUInt32(span, baseOffset, (uint)formats[i].SampleRateHz);
+ WireFormat.WriteUInt32(span, baseOffset + 4, (uint)formats[i].BitsPerSample);
+ WireFormat.WriteUInt32(span, baseOffset + 8, (uint)formats[i].Channels);
+ }
+ request.Complete(NtStatus.Success, needed);
+ }
+
+ private void HandleSetFormat(IoRequest request)
+ {
+ if (request.InputBuffer.Length < 12)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ return;
+ }
+ if (State.Snapshot() != AudioDeviceState.Stopped)
+ {
+ request.Fail(NtStatus.InvalidDeviceState);
+ return;
+ }
+ var requested = new PcmFormat(
+ (int)WireFormat.ReadUInt32(request.InputBuffer.Span, 0),
+ (int)WireFormat.ReadUInt32(request.InputBuffer.Span, 4),
+ (int)WireFormat.ReadUInt32(request.InputBuffer.Span, 8));
+
+ var result = _negotiator.Negotiate(requested);
+ if (!result.IsAccepted || result.Accepted is null)
+ {
+ request.Fail(result.Status);
+ return;
+ }
+ CurrentFormat = result.Accepted;
+ Volume = new VolumeState(CurrentFormat.Channels, Driver.TimeProvider);
+ var span = request.OutputBuffer.Span;
+ if (span.Length >= 12)
+ {
+ WireFormat.WriteUInt32(span, 0, (uint)CurrentFormat.SampleRateHz);
+ WireFormat.WriteUInt32(span, 4, (uint)CurrentFormat.BitsPerSample);
+ WireFormat.WriteUInt32(span, 8, (uint)CurrentFormat.Channels);
+ request.Complete(result.Status, 12); // BufferOverflow signals "adjusted"
+ }
+ else
+ {
+ request.Complete(result.Status);
+ }
+ }
+
+ private void HandleGetFormat(IoRequest request)
+ {
+ if (request.OutputBuffer.Length < 12)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ return;
+ }
+ var span = request.OutputBuffer.Span;
+ WireFormat.WriteUInt32(span, 0, (uint)CurrentFormat.SampleRateHz);
+ WireFormat.WriteUInt32(span, 4, (uint)CurrentFormat.BitsPerSample);
+ WireFormat.WriteUInt32(span, 8, (uint)CurrentFormat.Channels);
+ request.Complete(NtStatus.Success, 12);
+ }
+
+ private void HandleGetPosition(IoRequest request)
+ {
+ if (request.OutputBuffer.Length < 20)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ return;
+ }
+ PumpTo(now());
+ long produced;
+ lock (_gate)
+ {
+ produced = _producedFrames;
+ }
+ var span = request.OutputBuffer.Span;
+ WireFormat.WriteUInt64(span, 0, (ulong)(produced * CurrentFormat.BytesPerFrame));
+ WireFormat.WriteUInt64(span, 8, (ulong)produced);
+ WireFormat.WriteUInt32(span, 16, (uint)State.Snapshot());
+ request.Complete(NtStatus.Success, 20);
+ }
+
+ private void HandleSetVolume(IoRequest request)
+ {
+ var min = 2 * sizeof(float) + sizeof(byte) + sizeof(uint) + sizeof(uint);
+ if (request.InputBuffer.Length < min)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ return;
+ }
+ var span = request.InputBuffer.Span;
+ var masterGain = WireFormat.ReadFloat(span, 0);
+ var mute = span[8] != 0;
+ var rampMs = WireFormat.ReadUInt32(span, 9);
+ var channelCount = (int)WireFormat.ReadUInt32(span, 13);
+ var needed = min + channelCount * sizeof(float);
+ if (request.InputBuffer.Length < needed)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ return;
+ }
+ if (channelCount > Volume.Channels)
+ {
+ request.Fail(NtStatus.InvalidParameter);
+ return;
+ }
+ Volume.SetMasterGain(masterGain, TimeSpan.FromMilliseconds(rampMs));
+ Volume.SetMute(mute);
+ for (var c = 0; c < channelCount; c++)
+ {
+ Volume.SetChannelGain(c, WireFormat.ReadFloat(span, min + c * sizeof(float)));
+ }
+ request.Complete(NtStatus.Success);
+ }
+
+ private void HandleGetVolume(IoRequest request)
+ {
+ var needed = 2 * sizeof(float) + sizeof(byte) + sizeof(uint) + sizeof(uint) + Volume.Channels * sizeof(float);
+ if (request.OutputBuffer.Length < needed)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ return;
+ }
+ var span = request.OutputBuffer.Span;
+ WireFormat.WriteFloat(span, 0, Volume.TargetGain);
+ WireFormat.WriteFloat(span, 4, Volume.CurrentGain);
+ span[8] = Volume.Mute ? (byte)1 : (byte)0;
+ WireFormat.WriteUInt32(span, 9, (uint)Volume.RampRemaining.TotalMilliseconds);
+ WireFormat.WriteUInt32(span, 13, (uint)Volume.Channels);
+ for (var c = 0; c < Volume.Channels; c++)
+ {
+ WireFormat.WriteFloat(span, 17 + c * sizeof(float), Volume.GetChannelGain(c));
+ }
+ request.Complete(NtStatus.Success, needed);
+ }
+
+ // ----- Clock / ring filling -----
+
+ private DateTimeOffset now() => Driver.TimeProvider.GetUtcNow();
+
+ private void StartClock()
+ {
+ lock (_gate)
+ {
+ _startTicks = now().UtcTicks;
+ _pausedAccumTicks = 0;
+ }
+ }
+
+ private void PauseClock()
+ {
+ lock (_gate)
+ {
+ _pausedAtTicks = now().UtcTicks;
+ }
+ }
+
+ ///
+ /// Advances the virtual hardware clock: produces frames up to "now" into (or
+ /// out of) the ring buffer. Called lazily from Read/Write/GetPosition.
+ ///
+ private void PumpTo(DateTimeOffset timestamp)
+ {
+ if (State.Snapshot() != AudioDeviceState.Running)
+ {
+ return;
+ }
+ long elapsedTicks;
+ lock (_gate)
+ {
+ var start = _startTicks + _pausedAccumTicks;
+ elapsedTicks = timestamp.UtcTicks - start;
+ if (elapsedTicks <= 0)
+ {
+ return;
+ }
+ }
+
+ var bytesPerSecond = CurrentFormat.BytesPerSecond;
+ var targetFrames = (long)(elapsedTicks * bytesPerSecond / TimeSpan.TicksPerSecond / CurrentFormat.BytesPerFrame);
+ long produced;
+ lock (_gate)
+ {
+ produced = targetFrames - _producedFrames;
+ if (produced <= 0)
+ {
+ return;
+ }
+ }
+
+ var bytesNeeded = checked((int)Math.Min(produced * CurrentFormat.BytesPerFrame, int.MaxValue));
+ var buffer = new byte[bytesNeeded];
+
+ switch (_options.Mode)
+ {
+ case AudioVirtualMode.Capture or AudioVirtualMode.Loopback:
+ {
+ var source = _options.Source ?? throw new InvalidOperationException("Capture/Loopback requires a source.");
+ var framesFilled = source.FillFrames(buffer, CurrentFormat);
+ _ring.Write(buffer.AsSpan(0, framesFilled * CurrentFormat.BytesPerFrame));
+ lock (_gate)
+ {
+ _producedFrames += framesFilled;
+ }
+ break;
+ }
+ case AudioVirtualMode.Render:
+ {
+ var sink = _options.Sink ?? throw new InvalidOperationException("Render requires a sink.");
+ var consumed = _ring.Read(buffer);
+ sink.WriteFrames(buffer.AsSpan(0, consumed), CurrentFormat);
+ lock (_gate)
+ {
+ _producedFrames += consumed / CurrentFormat.BytesPerFrame;
+ }
+ break;
+ }
+ }
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Hid/GamepadReport.cs b/src/WindowsDriver.Sdk/Hid/GamepadReport.cs
new file mode 100644
index 0000000..297d3d3
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Hid/GamepadReport.cs
@@ -0,0 +1,115 @@
+using System.Buffers.Binary;
+
+namespace WindowsDriver.Sdk.Hid;
+
+///
+/// Driver-side gamepad state; converted to a wire report via
+/// . Buttons are 1-based (physical button
+/// numbers 1..12) matching the descriptor's Usage Min/Max.
+///
+public sealed class GamepadState
+{
+ public const int ButtonCount = 12;
+
+ private readonly bool[] _buttons = new bool[ButtonCount + 1];
+
+ /// 16-bit accelerometers/gyros in device units.
+ public short X { get; set; }
+ public short Y { get; set; }
+ public short Z { get; set; }
+ public short Rx { get; set; }
+ public short Ry { get; set; }
+ public short Rz { get; set; }
+
+ public bool this[int button]
+ {
+ get
+ {
+ if (button < 1 || button > ButtonCount) throw new ArgumentOutOfRangeException(nameof(button), "Buttons are numbered 1..12.");
+ return _buttons[button];
+ }
+ set
+ {
+ if (button < 1 || button > ButtonCount) throw new ArgumentOutOfRangeException(nameof(button), "Buttons are numbered 1..12.");
+ _buttons[button] = value;
+ }
+ }
+
+ public void SetButtons(params int[] buttons)
+ {
+ Array.Clear(_buttons);
+ foreach (var b in buttons)
+ {
+ this[b] = true;
+ }
+ }
+}
+
+///
+/// Packs/unpacks the gamepad input report (report ID 1) against the canonical
+/// descriptor:
+///
+/// byte 0 report ID (1)
+/// bytes 1..2 12 button bits (LSB first) + 4 padding bits
+/// bytes 3..14 X, Y, Z, Rx, Ry, Rz as int16 little-endian
+///
+///
+public static class GamepadInputReport
+{
+ public const byte ReportId = 1;
+ public const int ReportSizeBytes = 15; // 1 + 2 + 12
+
+ public static byte[] Pack(GamepadState state)
+ {
+ var report = new byte[ReportSizeBytes];
+ report[0] = ReportId;
+
+ ushort buttons = 0;
+ for (var b = 1; b <= GamepadState.ButtonCount; b++)
+ {
+ if (state[b])
+ {
+ buttons |= (ushort)(1 << (b - 1));
+ }
+ }
+ BinaryPrimitives.WriteUInt16LittleEndian(report.AsSpan(1), buttons);
+
+ WriteAxis(report, 3, state.X);
+ WriteAxis(report, 5, state.Y);
+ WriteAxis(report, 7, state.Z);
+ WriteAxis(report, 9, state.Rx);
+ WriteAxis(report, 11, state.Ry);
+ WriteAxis(report, 13, state.Rz);
+ return report;
+ }
+
+ public static GamepadState Unpack(ReadOnlySpan report)
+ {
+ if (report.Length != ReportSizeBytes)
+ {
+ throw new ArgumentException($"Gamepad input report must be exactly {ReportSizeBytes} bytes.", nameof(report));
+ }
+ if (report[0] != ReportId)
+ {
+ throw new ArgumentException($"Report ID must be {ReportId}, got {report[0]}.", nameof(report));
+ }
+ var state = new GamepadState
+ {
+ X = BinaryPrimitives.ReadInt16LittleEndian(report.Slice(3)),
+ Y = BinaryPrimitives.ReadInt16LittleEndian(report.Slice(5)),
+ Z = BinaryPrimitives.ReadInt16LittleEndian(report.Slice(7)),
+ Rx = BinaryPrimitives.ReadInt16LittleEndian(report.Slice(9)),
+ Ry = BinaryPrimitives.ReadInt16LittleEndian(report.Slice(11)),
+ Rz = BinaryPrimitives.ReadInt16LittleEndian(report.Slice(13)),
+ };
+ var buttons = BinaryPrimitives.ReadUInt16LittleEndian(report.Slice(1));
+ for (var b = 1; b <= GamepadState.ButtonCount; b++)
+ {
+ state[b] = (buttons & (1 << (b - 1))) != 0;
+ }
+ return state;
+ }
+
+ private static void WriteAxis(byte[] report, int offset, short value) =>
+ BinaryPrimitives.WriteInt16LittleEndian(report.AsSpan(offset), value);
+}
diff --git a/src/WindowsDriver.Sdk/Hid/HidDescriptor.cs b/src/WindowsDriver.Sdk/Hid/HidDescriptor.cs
new file mode 100644
index 0000000..954ef62
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Hid/HidDescriptor.cs
@@ -0,0 +1,284 @@
+using System.Buffers.Binary;
+
+namespace WindowsDriver.Sdk.Hid;
+
+///
+/// Standard HID class descriptors. The 9-byte HID descriptor announces the spec
+/// version and the report descriptor length; descriptor type 0x21 = HID,
+/// 0x22 = Report.
+///
+public static class HidDescriptor
+{
+ public const byte HidDescriptorType = 0x21;
+ public const byte ReportDescriptorType = 0x22;
+ public const int HidDescriptorLength = 9;
+
+ /// Builds the 9-byte HID class descriptor for the given report descriptor.
+ public static byte[] Build(ReadOnlySpan reportDescriptor, ushort bcdHid = 0x0111, byte countryCode = 0)
+ {
+ // Layout (USB HID class descriptor): bLength, bDescriptorType, bcdHID[2],
+ // bCountryCode, bNumDescriptors, bDescriptorType2, wDescriptorLength[2].
+ var descriptor = new byte[HidDescriptorLength];
+ descriptor[0] = HidDescriptorLength;
+ descriptor[1] = HidDescriptorType;
+ BinaryPrimitives.WriteUInt16LittleEndian(descriptor.AsSpan(2), bcdHid);
+ descriptor[4] = countryCode;
+ descriptor[5] = 1; // bNumDescriptors
+ descriptor[6] = ReportDescriptorType;
+ BinaryPrimitives.WriteUInt16LittleEndian(descriptor.AsSpan(7), (ushort)reportDescriptor.Length);
+ return descriptor;
+ }
+}
+
+/// One Input/Output/Feature field decoded from a descriptor.
+public sealed record HidFieldSummary(
+ HidMainItemKind Kind,
+ byte ReportId,
+ int BitWidth,
+ int LogicalMinimum,
+ int LogicalMaximum,
+ int UsagePage,
+ int? UsageMinimum,
+ int? UsageMaximum);
+
+public enum HidMainItemKind
+{
+ Input,
+ Output,
+ Feature,
+}
+
+/// Aggregated per-report-ID sizes.
+public sealed record HidReportLayout(byte ReportId, int InputBits, int OutputBits, int FeatureBits)
+{
+ /// Full report size as exchanged on the wire (report-ID byte included when present).
+ public int WireBytes(bool hasReportId) => (hasReportId ? 1 : 0) + (Math.Max(InputBits, Math.Max(OutputBits, FeatureBits)) + 7) / 8;
+}
+
+/// Result of .
+public sealed record HidDescriptorSummary
+{
+ public required IReadOnlyList Reports { get; init; }
+ public required IReadOnlyList Fields { get; init; }
+ public int MaxCollectionDepth { get; init; }
+ public bool UsesReportIds { get; init; }
+
+ public HidReportLayout? Find(byte reportId) => Reports.FirstOrDefault(r => r.ReportId == reportId);
+}
+
+///
+/// Parses a HID report descriptor back into a structural summary. Used to
+/// validate generated descriptors (and for tests). Implements the short-item
+/// encoding exactly as emits it.
+///
+public static class HidReportDescriptorParser
+{
+ public static HidDescriptorSummary Parse(ReadOnlySpan descriptor)
+ {
+ var fields = new List();
+ var reportBits = new Dictionary();
+ var globalStack = new Stack();
+ var globals = new GlobalState();
+ var locals = new LocalState();
+ var depth = 0;
+ var maxDepth = 0;
+ var i = 0;
+
+ while (i < descriptor.Length)
+ {
+ var prefix = descriptor[i++];
+ var tag = (prefix >> 4) & 0xF;
+ var type = (prefix >> 2) & 0x3;
+ var sizeCode = prefix & 0x3;
+
+ if (tag == 0xF)
+ {
+ throw new InvalidDataException("Long items are not supported by this parser (offset " + (i - 1) + ").");
+ }
+ var dataSize = sizeCode switch { 0 => 0, 1 => 1, 2 => 2, 3 => 4, _ => throw new InvalidDataException("bad size") };
+ if (i + dataSize > descriptor.Length)
+ {
+ throw new InvalidDataException("Truncated descriptor: item at offset " + (i - 1) + " needs " + dataSize + " bytes.");
+ }
+ var value = ReadValue(descriptor.Slice(i, dataSize));
+ i += dataSize;
+
+ switch (type)
+ {
+ case 0: // Main
+ switch (tag)
+ {
+ case 0x8: // Input
+ Accumulate(HidMainItemKind.Input, globals, locals, value, fields, reportBits);
+ locals.Reset();
+ break;
+ case 0x9: // Output
+ Accumulate(HidMainItemKind.Output, globals, locals, value, fields, reportBits);
+ locals.Reset();
+ break;
+ case 0xB: // Feature
+ Accumulate(HidMainItemKind.Feature, globals, locals, value, fields, reportBits);
+ locals.Reset();
+ break;
+ case 0xA: // Collection
+ depth++;
+ maxDepth = Math.Max(maxDepth, depth);
+ locals.Reset();
+ break;
+ case 0xC: // End collection
+ depth--;
+ if (depth < 0)
+ {
+ throw new InvalidDataException("Unmatched EndCollection in descriptor.");
+ }
+ break;
+ }
+ break;
+
+ case 1: // Global
+ switch (tag)
+ {
+ case 0x0: globals.UsagePage = value; break;
+ case 0x1: globals.LogicalMin = value; break;
+ case 0x2: globals.LogicalMax = value; break;
+ case 0x3: globals.PhysicalMin = value; break;
+ case 0x4: globals.PhysicalMax = value; break;
+ case 0x5: break; // unit exponent — not tracked
+ case 0x6: break; // unit — not tracked
+ case 0x7: globals.ReportSize = (int)value; break;
+ case 0x8: globals.ReportId = (byte)value; break;
+ case 0x9: globals.ReportCount = (int)value; break;
+ case 0xA: globalStack.Push(globals.Clone()); break; // Push
+ case 0xB: globals = globalStack.Count > 0 ? globalStack.Pop() : throw new InvalidDataException("Pop without Push."); break;
+ }
+ break;
+
+ case 2: // Local
+ switch (tag)
+ {
+ case 0x0: locals.Usages.Add((int)value); break;
+ case 0x1: locals.UsageMin = (int)value; break;
+ case 0x2: locals.UsageMax = (int)value; break;
+ }
+ break;
+ }
+ }
+
+ if (depth != 0)
+ {
+ throw new InvalidDataException($"{depth} collection(s) left open at end of descriptor.");
+ }
+ if (globalStack.Count != 0)
+ {
+ throw new InvalidDataException("Push without matching Pop at end of descriptor.");
+ }
+
+ return new HidDescriptorSummary
+ {
+ Fields = fields,
+ Reports = reportBits.Select(kvp => new HidReportLayout(kvp.Key, kvp.Value.Input, kvp.Value.Output, kvp.Value.Feature)).ToList(),
+ MaxCollectionDepth = maxDepth,
+ UsesReportIds = reportBits.Keys.Any(id => id != 0),
+ };
+ }
+
+ private static void Accumulate(
+ HidMainItemKind kind,
+ GlobalState globals,
+ LocalState locals,
+ int flags,
+ List fields,
+ Dictionary reportBits)
+ {
+ var bitWidth = globals.ReportSize * globals.ReportCount;
+ var isConst = (flags & 0x1) != 0;
+ if (!isConst)
+ {
+ fields.Add(new HidFieldSummary(
+ kind,
+ globals.ReportId,
+ bitWidth,
+ globals.LogicalMin,
+ globals.LogicalMax,
+ globals.UsagePage,
+ locals.UsageMin,
+ locals.UsageMax));
+ }
+ var entry = reportBits.TryGetValue(globals.ReportId, out var bits) ? bits : (0, 0, 0);
+ var updated = kind switch
+ {
+ HidMainItemKind.Input => (entry.Item1 + bitWidth, entry.Item2, entry.Item3),
+ HidMainItemKind.Output => (entry.Item1, entry.Item2 + bitWidth, entry.Item3),
+ _ => (entry.Item1, entry.Item2, entry.Item3 + bitWidth),
+ };
+ reportBits[globals.ReportId] = updated;
+ }
+
+ private static int ReadValue(ReadOnlySpan data)
+ {
+ // Signed, little-endian.
+ return data.Length switch
+ {
+ 0 => 0,
+ 1 => (sbyte)data[0],
+ 2 => (short)(data[0] | (data[1] << 8)),
+ 4 => data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24),
+ _ => throw new InvalidDataException("Invalid item data size."),
+ };
+ }
+
+ private sealed class GlobalState
+ {
+ public int UsagePage;
+ public int LogicalMin;
+ public int LogicalMax;
+ public int PhysicalMin;
+ public int PhysicalMax;
+ public int ReportSize;
+ public int ReportCount = 1;
+ public byte ReportId;
+
+ public GlobalState Clone() => (GlobalState)MemberwiseClone();
+ }
+
+ private sealed class LocalState
+ {
+ public List Usages { get; } = [];
+ public int? UsageMin;
+ public int? UsageMax;
+
+ public void Reset()
+ {
+ Usages.Clear();
+ UsageMin = null;
+ UsageMax = null;
+ }
+ }
+}
+
+/// Canonical descriptors shipped with the SDK.
+public static class HidDescriptors
+{
+ ///
+ /// 6-axis + 12-button gamepad: X/Y/Z + Rx/Ry/Rz as 16-bit axes, 12 buttons,
+ /// input report 1. Produces a 15-byte input report (ID + 2 buttons/pad bytes
+ /// + 12 axis bytes).
+ ///
+ public static byte[] GamepadSixAxisTwelveButtons()
+ {
+ return HidReportDescriptorBuilder.Create()
+ .UsagePage(HidUsagePage.GenericDesktop)
+ .Usage(GenericDesktopUsage.GamePad)
+ .BeginCollection(HidCollectionType.Application)
+ .ReportId(1)
+ .Buttons(12)
+ .Axis(GenericDesktopUsage.X, 16, short.MinValue, short.MaxValue)
+ .Axis(GenericDesktopUsage.Y, 16, short.MinValue, short.MaxValue)
+ .Axis(GenericDesktopUsage.Z, 16, short.MinValue, short.MaxValue)
+ .Axis(GenericDesktopUsage.Rx, 16, short.MinValue, short.MaxValue)
+ .Axis(GenericDesktopUsage.Ry, 16, short.MinValue, short.MaxValue)
+ .Axis(GenericDesktopUsage.Rz, 16, short.MinValue, short.MaxValue)
+ .EndCollection()
+ .ToBytes();
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Hid/HidDevice.cs b/src/WindowsDriver.Sdk/Hid/HidDevice.cs
new file mode 100644
index 0000000..d9c16e4
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Hid/HidDevice.cs
@@ -0,0 +1,166 @@
+using System.Buffers.Binary;
+
+namespace WindowsDriver.Sdk.Hid;
+
+///
+/// SDK-level IOCTL contract for HID devices. These are the codes handled by
+/// ; when a device is integrated with the Windows HID
+/// stack through HidCx, the class extension maps this traffic onto the standard
+/// hidclass IOCTLs (see docs/hid-guide.md).
+///
+public static class HidIoctlCodes
+{
+ private static uint Ctl(uint function, uint access) => WinIoctl.VendorControlCode(function, access);
+
+ /// Out: the raw report descriptor bytes.
+ public static readonly uint GetReportDescriptor = Ctl(0x800, WinIoctl.FileAccessRead);
+
+ /// Out: the 9-byte HID class descriptor.
+ public static readonly uint GetDeviceDescriptor = Ctl(0x801, WinIoctl.FileAccessRead);
+
+ /// Out: u16 wire size of the largest input report (ID byte included).
+ public static readonly uint GetInputReportSize = Ctl(0x802, WinIoctl.FileAccessRead);
+
+ /// Out: the current input report (ID byte first).
+ public static readonly uint GetInputReport = Ctl(0x803, WinIoctl.FileAccessRead);
+
+ /// In: feature report bytes; the device stores and echoes them.
+ public static readonly uint SetFeatureReport = Ctl(0x804, WinIoctl.FileAccessWrite);
+
+ /// Out: the last feature report set via .
+ public static readonly uint GetFeatureReport = Ctl(0x805, WinIoctl.FileAccessRead);
+}
+
+/// Configuration for .
+public sealed class HidDeviceOptions
+{
+ /// Raw report descriptor. Defaults to the canonical 6-axis/12-button gamepad.
+ public byte[]? ReportDescriptor { get; init; }
+
+ /// Produces the current packed input report (report-ID byte first). Defaults to a neutral gamepad state.
+ public Func? InputReportFactory { get; init; }
+
+ public ushort BcdHid { get; init; } = 0x0111;
+ public byte CountryCode { get; init; }
+
+ public static HidDeviceOptions Default => new();
+}
+
+///
+/// A complete virtual HID device: serves the report and class descriptors over
+/// IOCTL and delivers the current input report on Read requests. The input
+/// report content is produced by ,
+/// so the owning driver decides how state (buttons, axes) becomes wire data.
+///
+public class HidDevice : DeviceBase
+{
+ private readonly HidDeviceOptions _options;
+ private readonly byte[] _reportDescriptor;
+ private readonly byte[] _classDescriptor;
+ private byte[] _featureReport = [];
+
+ public HidDevice(DeviceContext context, HidDeviceOptions? options = null)
+ : base(context)
+ {
+ _options = options ?? HidDeviceOptions.Default;
+ _reportDescriptor = _options.ReportDescriptor ?? HidDescriptors.GamepadSixAxisTwelveButtons();
+ _classDescriptor = HidDescriptor.Build(_reportDescriptor, _options.BcdHid, _options.CountryCode);
+ InputReportFactory = _options.InputReportFactory ?? (() => GamepadInputReport.Pack(new GamepadState()));
+
+ DefaultQueue
+ .OnDeviceControl(HandleDeviceControlAsync)
+ .OnRead(HandleReadAsync);
+ }
+
+ public Func InputReportFactory { get; set; }
+
+ /// Last feature report written by a client (SetFeatureReport).
+ public byte[] FeatureReport => _featureReport;
+
+ public int InputReportSize
+ {
+ get
+ {
+ var factory = InputReportFactory();
+ return factory.Length;
+ }
+ }
+
+ public override Task OnPrepareHardwareAsync(CancellationToken cancellationToken)
+ {
+ Context.Log.Info("HID device ready: {0}-byte report descriptor", _reportDescriptor.Length);
+ return Task.CompletedTask;
+ }
+
+ private Task HandleReadAsync(IoRequest request, CancellationToken ct)
+ {
+ var report = InputReportFactory();
+ if (request.OutputBuffer.Length < report.Length)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ return Task.CompletedTask;
+ }
+ report.CopyTo(request.OutputBuffer);
+ request.Complete(NtStatus.Success, report.Length);
+ return Task.CompletedTask;
+ }
+
+ ///
+ /// Handles the contract. Subclasses override
+ /// this to add device-specific IOCTLs and fall back to base for the rest.
+ ///
+ protected virtual Task HandleDeviceControlAsync(IoRequest request, CancellationToken ct)
+ {
+ var code = request.IoControlCode;
+ if (code == HidIoctlCodes.GetReportDescriptor)
+ {
+ CopyTo(request, _reportDescriptor);
+ }
+ else if (code == HidIoctlCodes.GetDeviceDescriptor)
+ {
+ CopyTo(request, _classDescriptor);
+ }
+ else if (code == HidIoctlCodes.GetInputReportSize)
+ {
+ if (request.OutputBuffer.Length < sizeof(ushort))
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ BinaryPrimitives.WriteUInt16LittleEndian(request.OutputBuffer.Span, (ushort)InputReportSize);
+ request.Complete(NtStatus.Success, sizeof(ushort));
+ }
+ }
+ else if (code == HidIoctlCodes.GetInputReport)
+ {
+ var report = InputReportFactory();
+ CopyTo(request, report);
+ }
+ else if (code == HidIoctlCodes.SetFeatureReport)
+ {
+ _featureReport = request.InputBuffer.ToArray();
+ request.Complete(NtStatus.Success, _featureReport.Length);
+ }
+ else if (code == HidIoctlCodes.GetFeatureReport)
+ {
+ CopyTo(request, _featureReport);
+ }
+ else
+ {
+ request.Fail(NtStatus.InvalidDeviceRequest);
+ }
+ return Task.CompletedTask;
+ }
+
+ private static void CopyTo(IoRequest request, byte[] payload)
+ {
+ if (request.OutputBuffer.Length < payload.Length)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ return;
+ }
+ payload.CopyTo(request.OutputBuffer);
+ request.Complete(NtStatus.Success, payload.Length);
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Hid/HidReportDescriptorBuilder.cs b/src/WindowsDriver.Sdk/Hid/HidReportDescriptorBuilder.cs
new file mode 100644
index 0000000..0626390
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Hid/HidReportDescriptorBuilder.cs
@@ -0,0 +1,204 @@
+using System.Buffers.Binary;
+
+namespace WindowsDriver.Sdk.Hid;
+
+///
+/// Builds real USB HID report descriptors by encoding HID short items. Every
+/// emitted byte follows the HID 1.11 item encoding:
+///
+/// byte = (tag << 4) | (type << 2) | sizeCode // sizeCode: 0=0B, 1=1B, 2=2B, 3=4B
+/// type: 0 = Main, 1 = Global, 2 = Local
+///
+/// The descriptor can be parsed back with
+/// and fed straight to the Windows HID stack (HidCx) via a UMDF HID mini-driver.
+///
+public sealed class HidReportDescriptorBuilder
+{
+ private readonly List _bytes = [];
+
+ /// Static global state tracked so convenience helpers can restore context.
+ private ushort _currentPage;
+
+ public static HidReportDescriptorBuilder Create() => new();
+
+ // ----- Global items -----
+
+ public HidReportDescriptorBuilder UsagePage(HidUsagePage page)
+ {
+ _currentPage = (ushort)page;
+ return Item(tag: 0x0, type: GlobalType, (int)page);
+ }
+
+ public HidReportDescriptorBuilder LogicalMinimum(int value) => Item(0x1, GlobalType, value);
+ public HidReportDescriptorBuilder LogicalMaximum(int value) => Item(0x2, GlobalType, value);
+ public HidReportDescriptorBuilder PhysicalMinimum(int value) => Item(0x3, GlobalType, value);
+ public HidReportDescriptorBuilder PhysicalMaximum(int value) => Item(0x4, GlobalType, value);
+
+ /// Unit exponent (signed nibble: −8..7, encoded as 4-bit two's complement).
+ public HidReportDescriptorBuilder UnitExponent(int exponent)
+ {
+ if (exponent < -8 || exponent > 7)
+ {
+ throw new ArgumentOutOfRangeException(nameof(exponent), "Unit exponent must be in [-8, 7].");
+ }
+ return Item(0x5, GlobalType, exponent);
+ }
+
+ public HidReportDescriptorBuilder Unit(int value) => Item(0x6, GlobalType, value);
+ public HidReportDescriptorBuilder ReportSize(int bits)
+ {
+ if (bits <= 0 || bits > 32) throw new ArgumentOutOfRangeException(nameof(bits), "Report size must be 1..32 bits.");
+ return Item(0x7, GlobalType, bits);
+ }
+ public HidReportDescriptorBuilder ReportId(byte id)
+ {
+ if (id == 0) throw new ArgumentOutOfRangeException(nameof(id), "Report ID 0 is reserved (no-ID reports).");
+ return Item(0x8, GlobalType, id);
+ }
+ public HidReportDescriptorBuilder ReportCount(int count)
+ {
+ if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count), "Report count must be positive.");
+ return Item(0x9, GlobalType, count);
+ }
+
+ // ----- Local items -----
+
+ public HidReportDescriptorBuilder Usage(ushort usage) => Item(0x0, LocalType, usage);
+ public HidReportDescriptorBuilder Usage(GenericDesktopUsage usage) => Usage((ushort)usage);
+ public HidReportDescriptorBuilder UsageMinimum(ushort usage) => Item(0x1, LocalType, usage);
+ public HidReportDescriptorBuilder UsageMaximum(ushort usage) => Item(0x2, LocalType, usage);
+
+ // ----- Main items -----
+
+ public HidReportDescriptorBuilder Input(HidMainItemFlags flags = HidMainItemFlags.Data | HidMainItemFlags.Variable)
+ => MainItem(0x8, (int)flags);
+
+ public HidReportDescriptorBuilder Output(HidMainItemFlags flags = HidMainItemFlags.Data | HidMainItemFlags.Variable)
+ => MainItem(0x9, (int)flags);
+
+ public HidReportDescriptorBuilder Feature(HidMainItemFlags flags = HidMainItemFlags.Data | HidMainItemFlags.Variable)
+ => MainItem(0xB, (int)flags);
+
+ public HidReportDescriptorBuilder BeginCollection(HidCollectionType type) => MainItem(0xA, (int)type);
+
+ public HidReportDescriptorBuilder EndCollection() => MainItem(0xC, 0);
+
+ // ----- Convenience blocks -----
+
+ ///
+ /// Emits the standard button block: switches to the Button usage page, declares
+ /// single-bit Data,Variable,Absolute fields with usages
+ /// 1..count, pads to a byte boundary, and restores the previous usage page.
+ ///
+ public HidReportDescriptorBuilder Buttons(int count, HidMainItemFlags? kind = null)
+ {
+ var previousPage = _currentPage;
+ UsagePage(HidUsagePage.Button);
+ UsageMinimum(1);
+ UsageMaximum((ushort)count);
+ LogicalMinimum(0);
+ LogicalMaximum(1);
+ ReportSize(1);
+ ReportCount(count);
+ Input(kind ?? (HidMainItemFlags.Data | HidMainItemFlags.Variable));
+ var paddingBits = (8 - (count % 8)) % 8;
+ if (paddingBits > 0)
+ {
+ ReportSize(paddingBits);
+ ReportCount(1);
+ Input(HidMainItemFlags.Const | HidMainItemFlags.Absolute);
+ }
+ return UsagePage((HidUsagePage)previousPage);
+ }
+
+ /// Emits a single Data,Variable,Absolute axis field with explicit width and range.
+ public HidReportDescriptorBuilder Axis(GenericDesktopUsage usage, int bits, int logicalMinimum, int logicalMaximum)
+ {
+ Usage(usage);
+ LogicalMinimum(logicalMinimum);
+ LogicalMaximum(logicalMaximum);
+ ReportSize(bits);
+ ReportCount(1);
+ return Input();
+ }
+
+ /// Emits Const,Absolute padding bits (keeps report byte-aligned without consuming a usage).
+ public HidReportDescriptorBuilder PaddingInput(int bits)
+ {
+ ReportSize(bits);
+ ReportCount(1);
+ return Input(HidMainItemFlags.Const | HidMainItemFlags.Absolute);
+ }
+
+ /// Returns the encoded descriptor bytes.
+ public byte[] ToBytes()
+ {
+ if (_bytes.Count == 0 || _bytes[^1] != 0xC0)
+ {
+ throw new InvalidOperationException("Descriptor must end with an EndCollection item.");
+ }
+ return [.. _bytes];
+ }
+
+ public int ByteCount => _bytes.Count;
+
+ // ----- Item encoding -----
+
+ private const int MainType = 0, GlobalType = 1, LocalType = 2;
+
+ private HidReportDescriptorBuilder Item(int tag, int type, int value)
+ {
+ var (sizeCode, encoded) = EncodeValue(value);
+ _bytes.Add((byte)((tag << 4) | (type << 2) | sizeCode));
+ _bytes.AddRange(encoded);
+ return this;
+ }
+
+ private HidReportDescriptorBuilder MainItem(int tag, int value)
+ {
+ // Main item flags are unsigned bit fields; encode in the smallest unsigned size.
+ var (sizeCode, encoded) = EncodeUnsigned((uint)value);
+ _bytes.Add((byte)((tag << 4) | (MainType << 2) | sizeCode));
+ _bytes.AddRange(encoded);
+ return this;
+ }
+
+ private static (int SizeCode, byte[] Bytes) EncodeValue(int value)
+ {
+ // Signed, little-endian, smallest size that holds the value with sign extension.
+ if (value >= sbyte.MinValue && value <= sbyte.MaxValue)
+ {
+ return (1, [(byte)value]);
+ }
+ if (value >= short.MinValue && value <= short.MaxValue)
+ {
+ var buf = new byte[2];
+ BinaryPrimitives.WriteInt16LittleEndian(buf, (short)value);
+ return (2, buf);
+ }
+ var buf4 = new byte[4];
+ BinaryPrimitives.WriteInt32LittleEndian(buf4, value);
+ return (3, buf4);
+ }
+
+ private static (int SizeCode, byte[] Bytes) EncodeUnsigned(uint value)
+ {
+ if (value == 0)
+ {
+ return (0, Array.Empty()); // zero-value main items encode with no data bytes
+ }
+ if (value <= byte.MaxValue)
+ {
+ return (1, [(byte)value]);
+ }
+ if (value <= ushort.MaxValue)
+ {
+ var buf = new byte[2];
+ BinaryPrimitives.WriteUInt16LittleEndian(buf, (ushort)value);
+ return (2, buf);
+ }
+ var buf4 = new byte[4];
+ BinaryPrimitives.WriteUInt32LittleEndian(buf4, value);
+ return (3, buf4);
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Hid/HidUsagePages.cs b/src/WindowsDriver.Sdk/Hid/HidUsagePages.cs
new file mode 100644
index 0000000..ac9b2f7
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Hid/HidUsagePages.cs
@@ -0,0 +1,71 @@
+namespace WindowsDriver.Sdk.Hid;
+
+/// USB HID usage page IDs (HID 1.11 spec, table of major usage pages).
+public enum HidUsagePage : ushort
+{
+ GenericDesktop = 0x01,
+ Simulation = 0x02,
+ Button = 0x09,
+ Ordinal = 0x0A,
+ Telephony = 0x0B,
+ Consumer = 0x0C,
+ Digitizer = 0x0D,
+ Sensor = 0x20,
+ VendorDefinedStart = 0xFF00,
+}
+
+/// Generic Desktop page usages used by joysticks/gamepads and mouse-like devices.
+public enum GenericDesktopUsage : ushort
+{
+ Pointer = 0x01,
+ Mouse = 0x02,
+ Joystick = 0x04,
+ GamePad = 0x05,
+ Keyboard = 0x06,
+ Keypad = 0x07,
+ SystemControl = 0x80,
+ X = 0x30,
+ Y = 0x31,
+ Z = 0x32,
+ Rx = 0x33,
+ Ry = 0x34,
+ Rz = 0x35,
+ Slider = 0x36,
+ Dial = 0x37,
+ Wheel = 0x38,
+ HatSwitch = 0x39,
+}
+
+/// HID collection types.
+public enum HidCollectionType : byte
+{
+ Physical = 0x00,
+ Application = 0x01,
+ Logical = 0x02,
+ Report = 0x03,
+ NamedArray = 0x04,
+ UsageSwitch = 0x05,
+ UsageModifier = 0x06,
+}
+
+/// Input/Output/Feature main item flags ([Data/Const][Array/Variable][Absolute/Relative]...).
+[Flags]
+public enum HidMainItemFlags
+{
+ Data = 0x0000,
+ Const = 0x0001,
+ Array = 0x0000,
+ Variable = 0x0002,
+ Absolute = 0x0000,
+ Relative = 0x0004,
+ NoWrap = 0x0000,
+ Wrap = 0x0008,
+ Linear = 0x0000,
+ NonLinear = 0x0010,
+ PreferredState = 0x0000,
+ NoPreferredState = 0x0020,
+ NoNullPosition = 0x0000,
+ NullState = 0x0040,
+ NonVolatile = 0x0000,
+ Volatile = 0x0080,
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/ByteRingBuffer.cs b/src/WindowsDriver.Sdk/Runtime/ByteRingBuffer.cs
new file mode 100644
index 0000000..1678ea7
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/ByteRingBuffer.cs
@@ -0,0 +1,108 @@
+using System.Collections.Concurrent;
+
+namespace WindowsDriver.Sdk;
+
+///
+/// Thread-safe byte ring buffer used by the audio and serial modules. Writers
+/// drop bytes when the buffer is full (counted in );
+/// readers get whatever is available. This models a hardware FIFO between the
+/// device and the host.
+///
+public sealed class ByteRingBuffer
+{
+ private readonly object _gate = new();
+ private readonly byte[] _buffer;
+ private int _head; // next write position
+ private int _tail; // next read position
+ private int _count;
+
+ public ByteRingBuffer(int capacity)
+ {
+ if (capacity <= 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity must be positive.");
+ }
+ Capacity = capacity;
+ _buffer = new byte[capacity];
+ }
+
+ public int Capacity { get; }
+ public int Count { get { lock (_gate) { return _count; } } }
+ public int FreeSpace { get { lock (_gate) { return Capacity - _count; } } }
+ public long DroppedBytes { get; private set; }
+ public long TotalBytesWritten { get; private set; }
+ public long TotalBytesRead { get; private set; }
+
+ ///
+ /// Writes as much of the data as fits. Returns the number of bytes accepted;
+ /// the remainder is dropped and counted.
+ ///
+ public int Write(ReadOnlySpan data)
+ {
+ lock (_gate)
+ {
+ var accepted = Math.Min(data.Length, Capacity - _count);
+ if (accepted == data.Length)
+ {
+ data.CopyTo(_buffer.AsSpan(_head));
+ }
+ else
+ {
+ data.Slice(0, accepted).CopyTo(_buffer.AsSpan(_head));
+ }
+ _head = (_head + accepted) % Capacity;
+ _count += accepted;
+ TotalBytesWritten += accepted;
+ DroppedBytes += data.Length - accepted;
+ return accepted;
+ }
+ }
+
+ /// Reads up to the destination length. Returns the number of bytes read.
+ public int Read(Span destination)
+ {
+ lock (_gate)
+ {
+ var available = Math.Min(destination.Length, _count);
+ if (available == 0)
+ {
+ return 0;
+ }
+
+ var firstChunk = Math.Min(available, Capacity - _tail);
+ _buffer.AsSpan(_tail, firstChunk).CopyTo(destination);
+ if (available > firstChunk)
+ {
+ _buffer.AsSpan(0, available - firstChunk).CopyTo(destination.Slice(firstChunk));
+ }
+ _tail = (_tail + available) % Capacity;
+ _count -= available;
+ TotalBytesRead += available;
+ return available;
+ }
+ }
+
+ /// Removes up to from the buffer without copying (drain).
+ public int Skip(int bytes)
+ {
+ lock (_gate)
+ {
+ var skipped = Math.Min(bytes, _count);
+ _tail = (_tail + skipped) % Capacity;
+ _count -= skipped;
+ TotalBytesRead += skipped;
+ return skipped;
+ }
+ }
+
+ /// Empties the buffer. Counters ( etc.) are preserved.
+ public void Clear()
+ {
+ lock (_gate)
+ {
+ _head = 0;
+ _tail = 0;
+ _count = 0;
+ }
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/DeviceBase.cs b/src/WindowsDriver.Sdk/Runtime/DeviceBase.cs
new file mode 100644
index 0000000..3757115
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/DeviceBase.cs
@@ -0,0 +1,107 @@
+namespace WindowsDriver.Sdk;
+
+///
+/// Base class for a device instance implemented by a driver. Subclass it and
+/// override the callbacks you need — the order and semantics mirror the WDF
+/// device callbacks:
+///
+///
+/// - — EvtDevicePrepareHardware: map resources, allocate HW-visible state.
+/// - — EvtDeviceD0Entry: start the hardware (streams, timers).
+/// - — EvtDeviceD0Exit: stop the hardware.
+/// - — EvtDeviceReleaseHardware: free HW resources.
+///
+///
+/// Queues are created with during OnDeviceAdd; the
+/// default queue is already created for you.
+///
+public abstract class DeviceBase
+{
+ private readonly List _queues = [];
+
+ protected DeviceBase(DeviceContext context)
+ {
+ Context = context;
+ DefaultQueue = CreateQueue(new IoQueueOptions { Name = "default", Dispatch = QueueDispatchMode.Parallel });
+ }
+
+ /// Context for this device instance (ids, properties, interface creation).
+ public DeviceContext Context { get; }
+
+ /// Convenience accessor for the driver context.
+ public DriverContext Driver => Context.Driver;
+
+ /// The automatically created default queue (parallel dispatch).
+ public IoQueue DefaultQueue { get; }
+
+ public IReadOnlyList Queues => _queues;
+
+ /// True once OnD0EntryAsync completed successfully (running = powered).
+ public bool IsD0 { get; private set; }
+
+ /// True once OnPrepareHardwareAsync completed successfully.
+ public bool IsHardwarePrepared { get; private set; }
+
+ /// Creates an additional queue (WdfIoQueueCreate).
+ protected IoQueue CreateQueue(IoQueueOptions options)
+ {
+ var queue = new IoQueue(Context.Driver.Log, options);
+ _queues.Add(queue);
+ return queue;
+ }
+
+ // ----- Power/PnP lifecycle -----
+
+ public virtual Task OnPrepareHardwareAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+ public virtual Task OnReleaseHardwareAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+ public virtual Task OnD0EntryAsync(DevicePowerState previousState, CancellationToken cancellationToken) => Task.CompletedTask;
+ public virtual Task OnD0ExitAsync(DevicePowerState newState, CancellationToken cancellationToken) => Task.CompletedTask;
+
+ ///
+ /// Approve removal by returning normally; deny it by throwing
+ /// with a failure status (EvtDeviceQueryRemove).
+ ///
+ public virtual Task OnQueryRemoveAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+
+ /// Device vanished without warning (unplug). Stop touching the hardware.
+ public virtual Task OnSurpriseRemovalAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+
+ // ----- Internals (hosts call these wrappers so IsD0/IsHardwarePrepared stay accurate) -----
+
+ /// Host entry point: runs and marks hardware prepared.
+ public async Task PrepareHardwareAsync(CancellationToken ct)
+ {
+ await OnPrepareHardwareAsync(ct).ConfigureAwait(false);
+ IsHardwarePrepared = true;
+ }
+
+ /// Host entry point: runs and clears the prepared flag.
+ public async Task ReleaseHardwareAsync(CancellationToken ct)
+ {
+ await OnReleaseHardwareAsync(ct).ConfigureAwait(false);
+ IsHardwarePrepared = false;
+ }
+
+ /// Host entry point: runs and marks the device powered.
+ public async Task D0EntryAsync(DevicePowerState previous, CancellationToken ct)
+ {
+ await OnD0EntryAsync(previous, ct).ConfigureAwait(false);
+ IsD0 = true;
+ }
+
+ /// Host entry point: runs and clears the powered flag.
+ public async Task D0ExitAsync(DevicePowerState next, CancellationToken ct)
+ {
+ await OnD0ExitAsync(next, ct).ConfigureAwait(false);
+ IsD0 = false;
+ }
+
+ /// Stops all queues; pending requests are cancelled (queue purge semantics).
+ public async Task StopQueuesAsync()
+ {
+ foreach (var queue in _queues)
+ {
+ await queue.StopAsync().ConfigureAwait(false);
+ }
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/DeviceContext.cs b/src/WindowsDriver.Sdk/Runtime/DeviceContext.cs
new file mode 100644
index 0000000..83b257a
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/DeviceContext.cs
@@ -0,0 +1,57 @@
+namespace WindowsDriver.Sdk;
+
+///
+/// Per-device environment handed to the driver when a device instance is added.
+/// Created by the host; the driver passes it into its
+/// subclass constructor.
+///
+public sealed class DeviceContext
+{
+ private readonly List _deviceInterfaces = [];
+
+ ///
+ /// Created by a host (DriverHost, the UMDF shim, the test host, or a test)
+ /// and handed to . Tests and samples
+ /// may construct one directly for unit-level device tests.
+ ///
+ public DeviceContext(DriverContext driver, DeviceAddContext add)
+ {
+ Driver = driver;
+ AddContext = add;
+ Log = new ScopedDriverLog(driver.Log, add.DeviceInstanceId);
+ }
+
+ public DriverContext Driver { get; }
+
+ internal DeviceAddContext AddContext { get; }
+
+ /// Bus-reported device instance id.
+ public string DeviceInstanceId => AddContext.DeviceInstanceId;
+
+ public IReadOnlyList HardwareIds => AddContext.HardwareIds;
+ public IReadOnlyList CompatibleIds => AddContext.CompatibleIds;
+
+ /// Devnode property store (per-device).
+ public PropertyStore Properties { get; } = new();
+
+ /// Device-scoped log with the instance id prefixed.
+ public IDriverLog Log { get; }
+
+ /// Device interfaces created so far (symbolic link names).
+ public IReadOnlyList DeviceInterfaces => _deviceInterfaces;
+
+ ///
+ /// Registers a device interface (WdfDeviceCreateDeviceInterface). Returns the
+ /// symbolic link name that applications open. The generated name is host-specific:
+ /// the test host fabricates a stable pseudo-path; a UMDF shim returns the real
+ /// "\\?\..." path.
+ ///
+ public string CreateDeviceInterface(Guid interfaceClass, string? referenceString = null)
+ {
+ var symlink = $"\\\\?\\{interfaceClass:B}#{referenceString ?? string.Empty}".ToUpperInvariant();
+ _deviceInterfaces.Add(symlink);
+ Properties.Set(KnownDeviceProperties.InterfaceClassGuid, interfaceClass);
+ Log.Info("created device interface {0}", symlink);
+ return symlink;
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/DevicePowerState.cs b/src/WindowsDriver.Sdk/Runtime/DevicePowerState.cs
new file mode 100644
index 0000000..f7272e1
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/DevicePowerState.cs
@@ -0,0 +1,14 @@
+namespace WindowsDriver.Sdk;
+
+///
+/// Device power states — values match the WDM DEVICE_POWER_STATE enum
+/// (PowerDeviceUnspecified / D0 / D1 / D2 / D3).
+///
+public enum DevicePowerState
+{
+ Unspecified = 0,
+ D0 = 1,
+ D1 = 2,
+ D2 = 3,
+ D3 = 4,
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/DriverException.cs b/src/WindowsDriver.Sdk/Runtime/DriverException.cs
new file mode 100644
index 0000000..3157723
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/DriverException.cs
@@ -0,0 +1,24 @@
+namespace WindowsDriver.Sdk;
+
+///
+/// Thrown by driver callbacks to fail the surrounding request or lifecycle step
+/// with a specific NTSTATUS. Uncaught generic exceptions complete with
+/// ; an
+/// completes with .
+///
+public class DriverException : Exception
+{
+ public NtStatus Status { get; }
+
+ public DriverException(NtStatus status, string message, Exception? innerException = null)
+ : base($"{status.ToHexString()}: {message}", innerException)
+ {
+ Status = status;
+ }
+}
+
+/// Convenience for rejecting unsupported or malformed requests.
+public sealed class InvalidRequestException : DriverException
+{
+ public InvalidRequestException(string message) : base(NtStatus.InvalidDeviceRequest, message) { }
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/DriverHost.cs b/src/WindowsDriver.Sdk/Runtime/DriverHost.cs
new file mode 100644
index 0000000..ee3f194
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/DriverHost.cs
@@ -0,0 +1,198 @@
+namespace WindowsDriver.Sdk;
+
+/// A device instance managed by .
+public sealed class DeviceInstance
+{
+ internal DeviceInstance(DeviceBase device, DeviceContext context)
+ {
+ Device = device;
+ Context = context;
+ }
+
+ public DeviceBase Device { get; }
+ public DeviceContext Context { get; }
+
+ public string DeviceInstanceId => Context.DeviceInstanceId;
+ public IoQueue DefaultQueue => Device.DefaultQueue;
+}
+
+///
+/// Orchestrates the driver and device lifecycle exactly like the WDF framework
+/// would: DriverEntry → AddDevice → PrepareHardware → D0Entry, and the mirror
+/// image on shutdown. The UMDF shim, the KMDF control plane and the test host
+/// all drive this class — so behavior you verify in tests is the behavior you
+/// get in production.
+///
+public sealed class DriverHost
+{
+ private readonly List _devices = [];
+ private readonly object _gate = new();
+ private IDriver? _driver;
+ private DriverContext? _driverContext;
+
+ public DriverHost(IDriverLog? log = null, IDriverRegistry? registry = null, TimeProvider? timeProvider = null)
+ {
+ Log = log ?? ConsoleDriverLog.Instance;
+ Registry = registry ?? new MemoryRegistry();
+ TimeProvider = timeProvider ?? TimeProvider.System;
+ }
+
+ public IDriverLog Log { get; }
+ public IDriverRegistry Registry { get; }
+ public TimeProvider TimeProvider { get; }
+ public bool IsStarted { get; private set; }
+
+ public IReadOnlyList Devices
+ {
+ get { lock (_gate) { return _devices.ToArray(); } }
+ }
+
+ /// Loads the driver type (must implement , parameterless ctor) and runs DriverEntry.
+ public async Task StartAsync(Type driverType, string? serviceName = null, CancellationToken cancellationToken = default)
+ {
+ if (IsStarted)
+ {
+ throw new InvalidOperationException("DriverHost is already started.");
+ }
+ var driver = (IDriver)Activator.CreateInstance(driverType)!;
+ var context = new DriverContext
+ {
+ Log = Log,
+ Registry = Registry,
+ TimeProvider = TimeProvider,
+ DriverServiceName = serviceName ?? driverType.Name,
+ };
+ await driver.OnDriverEntryAsync(context, cancellationToken).ConfigureAwait(false);
+ _driver = driver;
+ _driverContext = context;
+ IsStarted = true;
+ Log.Info("driver {0} loaded (service '{1}')", driverType.Name, context.DriverServiceName);
+ }
+
+ public Task StartAsync(string? serviceName = null, CancellationToken cancellationToken = default) where TDriver : IDriver, new()
+ => StartAsync(typeof(TDriver), serviceName, cancellationToken);
+
+ ///
+ /// Adds a device instance and powers it up: AddDevice → PrepareHardware → D0Entry.
+ /// Throws on failure (after rolling back partially completed steps).
+ ///
+ public async Task AddDeviceAsync(DeviceAddContext addContext, CancellationToken cancellationToken = default)
+ {
+ if (!IsStarted || _driver is null)
+ {
+ throw new InvalidOperationException("Call StartAsync before AddDeviceAsync.");
+ }
+
+ var context = new DeviceContext(_driverContext!, addContext);
+
+ var device = await _driver.OnDeviceAddAsync(addContext, context, cancellationToken).ConfigureAwait(false)
+ ?? throw new DriverException(NtStatus.Unsuccessful, "OnDeviceAddAsync returned null.");
+
+ try
+ {
+ await device.PrepareHardwareAsync(cancellationToken).ConfigureAwait(false);
+ await device.D0EntryAsync(DevicePowerState.D3, cancellationToken).ConfigureAwait(false);
+ }
+ catch (DriverException)
+ {
+ await RollbackAsync(device, cancellationToken).ConfigureAwait(false);
+ throw;
+ }
+ catch (OperationCanceledException)
+ {
+ await RollbackAsync(device, cancellationToken).ConfigureAwait(false);
+ throw;
+ }
+ catch (Exception ex)
+ {
+ Log.Error("device add failed unexpectedly: {0}", ex);
+ await RollbackAsync(device, cancellationToken).ConfigureAwait(false);
+ throw new DriverException(NtStatus.Unsuccessful, "Device add failed.", ex);
+ }
+
+ var instance = new DeviceInstance(device, context);
+ lock (_gate)
+ {
+ _devices.Add(instance);
+ }
+ Log.Info("device {0} added and started (interfaces: {1})", addContext.DeviceInstanceId, context.DeviceInterfaces.Count);
+ return instance;
+ }
+
+ private async Task RollbackAsync(DeviceBase device, CancellationToken ct)
+ {
+ try
+ {
+ await device.StopQueuesAsync().ConfigureAwait(false);
+ if (device.IsD0)
+ {
+ await device.D0ExitAsync(DevicePowerState.D3, ct).ConfigureAwait(false);
+ }
+ if (device.IsHardwarePrepared)
+ {
+ await device.ReleaseHardwareAsync(ct).ConfigureAwait(false);
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Warning("rollback during failed device add also failed: {0}", ex.Message);
+ }
+ }
+
+ /// Powers down and releases one device (QueryRemove honored by the device callbacks).
+ public async Task RemoveDeviceAsync(DeviceInstance instance, CancellationToken cancellationToken = default)
+ {
+ await instance.Device.OnQueryRemoveAsync(cancellationToken).ConfigureAwait(false);
+ await instance.Device.D0ExitAsync(DevicePowerState.D3, cancellationToken).ConfigureAwait(false);
+ await instance.Device.StopQueuesAsync().ConfigureAwait(false);
+ await instance.Device.ReleaseHardwareAsync(cancellationToken).ConfigureAwait(false);
+ lock (_gate)
+ {
+ _devices.Remove(instance);
+ }
+ Log.Info("device {0} removed", instance.DeviceInstanceId);
+ }
+
+ /// Notifies the device of an unannounced removal (unplug).
+ public async Task SurpriseRemoveDeviceAsync(DeviceInstance instance, CancellationToken cancellationToken = default)
+ {
+ await instance.Device.OnSurpriseRemovalAsync(cancellationToken).ConfigureAwait(false);
+ await instance.Device.StopQueuesAsync().ConfigureAwait(false);
+ lock (_gate)
+ {
+ _devices.Remove(instance);
+ }
+ }
+
+ /// Powers down all devices and calls DriverUnload.
+ public async Task ShutdownAsync(CancellationToken cancellationToken = default)
+ {
+ if (_driver is null)
+ {
+ return;
+ }
+ DeviceInstance[] devices;
+ lock (_gate)
+ {
+ devices = _devices.ToArray();
+ _devices.Clear();
+ }
+ foreach (var device in devices)
+ {
+ try
+ {
+ await device.Device.D0ExitAsync(DevicePowerState.D3, cancellationToken).ConfigureAwait(false);
+ await device.Device.StopQueuesAsync().ConfigureAwait(false);
+ await device.Device.ReleaseHardwareAsync(cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ Log.Warning("error during shutdown of {0}: {1}", device.DeviceInstanceId, ex.Message);
+ }
+ }
+ await _driver.OnDriverUnloadAsync().ConfigureAwait(false);
+ IsStarted = false;
+ _driver = null;
+ Log.Info("driver unloaded");
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/DriverLog.cs b/src/WindowsDriver.Sdk/Runtime/DriverLog.cs
new file mode 100644
index 0000000..e2bc5c1
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/DriverLog.cs
@@ -0,0 +1,124 @@
+using System.Globalization;
+using System.Text;
+
+namespace WindowsDriver.Sdk;
+
+/// Log levels a driver can emit (maps onto ETW verbosity levels).
+public enum DriverLogLevel
+{
+ Trace = 0,
+ Info = 1,
+ Warning = 2,
+ Error = 3,
+}
+
+///
+/// Logging facade for drivers. In a real deployment this is backed by ETW (or
+/// WPP-style tracing); in the test host it is backed by CapturedLog.
+///
+public interface IDriverLog
+{
+ bool IsEnabled(DriverLogLevel level);
+
+ /// Writes a pre-formatted message. Use the extension methods for formatting.
+ void Log(DriverLogLevel level, string message);
+}
+
+public static class DriverLogExtensions
+{
+ public static void Trace(this IDriverLog log, string format, params object?[] args) => log.WriteAt(DriverLogLevel.Trace, format, args);
+ public static void Info(this IDriverLog log, string format, params object?[] args) => log.WriteAt(DriverLogLevel.Info, format, args);
+ public static void Warning(this IDriverLog log, string format, params object?[] args) => log.WriteAt(DriverLogLevel.Warning, format, args);
+ public static void Error(this IDriverLog log, string format, params object?[] args) => log.WriteAt(DriverLogLevel.Error, format, args);
+
+ private static void WriteAt(this IDriverLog log, DriverLogLevel level, string format, object?[] args)
+ {
+ if (!log.IsEnabled(level))
+ {
+ return;
+ }
+ log.Log(level, args.Length == 0 ? format : string.Format(CultureInfo.InvariantCulture, format, args));
+ }
+}
+
+/// A logger that discards everything.
+public sealed class NullDriverLog : IDriverLog
+{
+ public static readonly NullDriverLog Instance = new();
+ public bool IsEnabled(DriverLogLevel level) => false;
+ public void Log(DriverLogLevel level, string message) { }
+}
+
+/// Writes formatted lines to the console: "12:00:00.000 [Info] message".
+public sealed class ConsoleDriverLog : IDriverLog
+{
+ public static readonly ConsoleDriverLog Instance = new();
+
+ private readonly DriverLogLevel _minimum;
+
+ public ConsoleDriverLog(DriverLogLevel minimum = DriverLogLevel.Trace) => _minimum = minimum;
+
+ public bool IsEnabled(DriverLogLevel level) => level >= _minimum;
+
+ public void Log(DriverLogLevel level, string message)
+ {
+ var line = $"{DateTime.UtcNow:HH:mm:ss.fff} [{level.ToString().ToUpperInvariant()}] {message}";
+ Console.WriteLine(line);
+ }
+}
+
+/// Thread-safe file logger (UTF-8, append or overwrite).
+public sealed class FileDriverLog : IDriverLog, IDisposable
+{
+ private readonly object _gate = new();
+ private readonly StreamWriter _writer;
+ private readonly DriverLogLevel _minimum;
+
+ public FileDriverLog(string path, bool append = false, DriverLogLevel minimum = DriverLogLevel.Trace)
+ {
+ _minimum = minimum;
+ _writer = new StreamWriter(new FileStream(path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read), Encoding.UTF8);
+ }
+
+ public bool IsEnabled(DriverLogLevel level) => level >= _minimum;
+
+ public void Log(DriverLogLevel level, string message)
+ {
+ lock (_gate)
+ {
+ _writer.WriteLine($"{DateTime.UtcNow:HH:mm:ss.fff} [{level.ToString().ToUpperInvariant()}] {message}");
+ _writer.Flush();
+ }
+ }
+
+ public void Dispose()
+ {
+ lock (_gate)
+ {
+ _writer.Dispose();
+ }
+ }
+}
+
+/// Fans messages out to multiple sinks.
+public sealed class CompositeDriverLog(params IDriverLog[] sinks) : IDriverLog
+{
+ public bool IsEnabled(DriverLogLevel level) => sinks.Any(s => s.IsEnabled(level));
+ public void Log(DriverLogLevel level, string message)
+ {
+ foreach (var sink in sinks)
+ {
+ if (sink.IsEnabled(level))
+ {
+ sink.Log(level, message);
+ }
+ }
+ }
+}
+
+/// Prefixes every message with a scope tag, e.g. the device instance id.
+public sealed class ScopedDriverLog(IDriverLog inner, string scope) : IDriverLog
+{
+ public bool IsEnabled(DriverLogLevel level) => inner.IsEnabled(level);
+ public void Log(DriverLogLevel level, string message) => inner.Log(level, $"[{scope}] {message}");
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/DriverModel.cs b/src/WindowsDriver.Sdk/Runtime/DriverModel.cs
new file mode 100644
index 0000000..c7ce6f0
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/DriverModel.cs
@@ -0,0 +1,90 @@
+namespace WindowsDriver.Sdk;
+
+///
+/// Bus-reported identity of a device instance being added — the managed
+/// equivalent of the information WDF hands to EvtDriverDeviceAdd.
+///
+public sealed record DeviceAddContext
+{
+ /// PnP device instance id, e.g. "ROOT\SAMPLEAUDIO\0000".
+ public required string DeviceInstanceId { get; init; }
+
+ /// Hardware IDs in best-match order (most specific first).
+ public IReadOnlyList HardwareIds { get; init; } = Array.Empty();
+
+ /// Compatible IDs, used when no hardware ID matches.
+ public IReadOnlyList CompatibleIds { get; init; } = Array.Empty();
+
+ /// Initial devnode property store.
+ public PropertyStore Properties { get; init; } = new();
+
+ /// True when the device was enumerated by the PnP manager as "raw" (no INF match yet).
+ public bool IsRawDevice { get; init; }
+}
+
+///
+/// The driver entry point set. Write a class implementing this interface and
+/// host it with , the UMDF shim, or the test host.
+/// Callback order matches WDF: DriverEntry → (AddDevice → PrepareHardware →
+/// D0Entry)* → DriverUnload.
+///
+public interface IDriver
+{
+ /// First callback; allocate driver-wide resources here (WDF: EvtDriverContextCreate/WdfDriverCreate).
+ Task OnDriverEntryAsync(DriverContext context, CancellationToken cancellationToken);
+
+ ///
+ /// Called once per device instance. Create your subclass
+ /// wrapping and return it; the host then runs the
+ /// power-up sequence. Returning null/throwing fails device start.
+ ///
+ Task OnDeviceAddAsync(DeviceAddContext addContext, DeviceContext deviceContext, CancellationToken cancellationToken);
+
+ /// Last callback before unload; release driver-wide resources here.
+ Task OnDriverUnloadAsync();
+}
+
+/// Optional base class providing no-op lifecycle callbacks and a CreateDevice helper.
+public abstract class DriverBase : IDriver
+{
+ protected DriverContext? Context { get; private set; }
+
+ public virtual Task OnDriverEntryAsync(DriverContext context, CancellationToken cancellationToken)
+ {
+ Context = context;
+ return Task.CompletedTask;
+ }
+
+ public abstract Task OnDeviceAddAsync(DeviceAddContext addContext, DeviceContext deviceContext, CancellationToken cancellationToken);
+
+ public virtual Task OnDriverUnloadAsync() => Task.CompletedTask;
+
+ /// Helper so subclasses can simply `return CreateDevice<MyDevice>(deviceContext);`.
+ protected TDevice CreateDevice(DeviceContext deviceContext) where TDevice : DeviceBase
+ {
+ return (TDevice)Activator.CreateInstance(typeof(TDevice), deviceContext)!;
+ }
+}
+
+///
+/// Per-driver environment handed to .
+///
+public sealed class DriverContext
+{
+ public required IDriverLog Log { get; init; }
+
+ /// Driver service Parameters-key access. Real deployments read the registry; tests use MemoryRegistry.
+ public required IDriverRegistry Registry { get; init; }
+
+ ///
+ /// Clock abstraction for all time-dependent behavior (audio positions, sensor
+ /// sampling). Hosts inject TimeProvider.System; tests inject a controllable fake.
+ ///
+ public TimeProvider TimeProvider { get; init; } = TimeProvider.System;
+
+ /// Service name from the INF (matches the [Services] section).
+ public string DriverServiceName { get; init; } = string.Empty;
+
+ /// Driver-global properties.
+ public PropertyStore DriverProperties { get; } = new();
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/IDriverRegistry.cs b/src/WindowsDriver.Sdk/Runtime/IDriverRegistry.cs
new file mode 100644
index 0000000..31b64ea
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/IDriverRegistry.cs
@@ -0,0 +1,62 @@
+namespace WindowsDriver.Sdk;
+
+///
+/// Read/write access to the driver's service Parameters key
+/// (HKLM\SYSTEM\CurrentControlSet\Services\<ServiceName>\Parameters). The real
+/// deployment is backed by Win32 registry APIs; tests use .
+///
+public interface IDriverRegistry
+{
+ string? ReadString(string valueName);
+ uint? ReadDword(string valueName);
+ void WriteString(string valueName, string value);
+ void WriteDword(string valueName, uint value);
+ bool DeleteValue(string valueName);
+}
+
+/// In-memory used by the test host and as a default.
+public class MemoryRegistry : IDriverRegistry
+{
+ private readonly object _gate = new();
+ private readonly Dictionary _values = new(StringComparer.OrdinalIgnoreCase);
+
+ public string? ReadString(string valueName)
+ {
+ lock (_gate)
+ {
+ return _values.TryGetValue(valueName, out var entry) && !entry.IsDword ? (string)entry.Value : null;
+ }
+ }
+
+ public uint? ReadDword(string valueName)
+ {
+ lock (_gate)
+ {
+ return _values.TryGetValue(valueName, out var entry) && entry.IsDword ? (uint)entry.Value : null;
+ }
+ }
+
+ public void WriteString(string valueName, string value)
+ {
+ lock (_gate)
+ {
+ _values[valueName] = (value, false);
+ }
+ }
+
+ public void WriteDword(string valueName, uint value)
+ {
+ lock (_gate)
+ {
+ _values[valueName] = (value, true);
+ }
+ }
+
+ public bool DeleteValue(string valueName)
+ {
+ lock (_gate)
+ {
+ return _values.Remove(valueName);
+ }
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/IoQueue.cs b/src/WindowsDriver.Sdk/Runtime/IoQueue.cs
new file mode 100644
index 0000000..e08429e
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/IoQueue.cs
@@ -0,0 +1,223 @@
+using System.Collections.Concurrent;
+using System.Threading.Channels;
+
+namespace WindowsDriver.Sdk;
+
+///
+/// Dispatch mode for an IO queue — the managed equivalent of the
+/// WdfIoQueueDispatch* settings.
+///
+public enum QueueDispatchMode
+{
+ /// Requests are handed to the driver one at a time, in order.
+ Sequential,
+
+ /// Requests are handed to the driver concurrently (default).
+ Parallel,
+
+ /// Requests wait in the queue until the driver pulls them — for polling-style drivers.
+ Manual,
+}
+
+/// Optional tuning knobs for .
+public sealed class IoQueueOptions
+{
+ public QueueDispatchMode Dispatch { get; init; } = QueueDispatchMode.Parallel;
+ public string? Name { get; init; }
+
+ public static IoQueueOptions Default => new();
+}
+
+///
+/// The set of request handlers a driver registers on a queue. Unregistered
+/// kinds complete with — the same
+/// behavior as a WDF queue without a corresponding EvtIo* callback.
+///
+public sealed class QueueHandlers
+{
+ public Func? DeviceControl { get; set; }
+ public Func? Read { get; set; }
+ public Func? Write { get; set; }
+}
+
+///
+/// An IO queue owned by a device. Requests arrive via and
+/// are dispatched to the registered handlers according to the dispatch mode.
+///
+public sealed class IoQueue
+{
+ private readonly QueueHandlers _handlers = new();
+ private readonly CancellationTokenSource _stopping = new();
+ private readonly object _gate = new();
+ private readonly List _outstanding = new();
+ private readonly SemaphoreSlim _sequentialGate = new(1, 1);
+ private readonly Channel _manualChannel;
+ private readonly IDriverLog _log;
+ private int _running;
+
+ public IoQueue(IDriverLog log, IoQueueOptions? options = null)
+ {
+ _log = log;
+ Options = options ?? IoQueueOptions.Default;
+ _manualChannel = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = false });
+ }
+
+ public string Name => Options.Name ?? "queue";
+ public IoQueueOptions Options { get; }
+ public QueueDispatchMode Dispatch => Options.Dispatch;
+ public QueueHandlers Handlers => _handlers;
+ public bool IsStopped { get; private set; }
+
+ // ----- Handler registration (fluent) -----
+
+ public IoQueue OnDeviceControl(Func handler) { _handlers.DeviceControl = handler; return this; }
+ public IoQueue OnRead(Func handler) { _handlers.Read = handler; return this; }
+ public IoQueue OnWrite(Func handler) { _handlers.Write = handler; return this; }
+
+ /// Manual-mode readers pull requests from this channel.
+ public ChannelReader ManualRequests => _manualChannel.Reader;
+
+ /// Submits a request. The host calls this; drivers do not.
+ public void Submit(IoRequest request)
+ {
+ if (IsStopped)
+ {
+ request.Fail(NtStatus.Cancelled);
+ return;
+ }
+
+ switch (Dispatch)
+ {
+ case QueueDispatchMode.Manual:
+ _manualChannel.Writer.TryWrite(request);
+ break;
+
+ case QueueDispatchMode.Sequential:
+ Track(DispatchSequentialAsync(request));
+ break;
+
+ default:
+ _ = DispatchParallelAsync(request);
+ break;
+ }
+ }
+
+ private async Task DispatchSequentialAsync(IoRequest request)
+ {
+ try
+ {
+ await _sequentialGate.WaitAsync(_stopping.Token).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ request.Fail(NtStatus.Cancelled);
+ return;
+ }
+ try
+ {
+ // The gate is held for the whole handler duration, so requests run
+ // strictly one at a time, in submission order.
+ await InvokeHandlerAsync(request).ConfigureAwait(false);
+ }
+ finally
+ {
+ _sequentialGate.Release();
+ }
+ }
+
+ private async Task DispatchParallelAsync(IoRequest request)
+ {
+ Track(InvokeHandlerAsync(request));
+ await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding);
+ }
+
+ private void Track(Task handlerTask)
+ {
+ lock (_gate)
+ {
+ _outstanding.Add(handlerTask);
+ _running++;
+ }
+ _ = handlerTask.ContinueWith(t =>
+ {
+ lock (_gate)
+ {
+ _outstanding.Remove(t);
+ _running--;
+ }
+ }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
+ }
+
+ private async Task InvokeHandlerAsync(IoRequest request)
+ {
+ var handler = request.Kind switch
+ {
+ IoRequestKind.DeviceControl => _handlers.DeviceControl,
+ IoRequestKind.Read => _handlers.Read,
+ IoRequestKind.Write => _handlers.Write,
+ _ => null,
+ };
+
+ try
+ {
+ if (handler is null)
+ {
+ request.Fail(NtStatus.InvalidDeviceRequest);
+ return;
+ }
+ await handler(request, _stopping.Token).ConfigureAwait(false);
+ }
+ catch (DriverException ex)
+ {
+ _log.Error($"[{Name}] handler for {request.Kind} failed: {ex.Message}");
+ request.Fail(ex.Status);
+ }
+ catch (OperationCanceledException)
+ {
+ request.Fail(NtStatus.Cancelled);
+ }
+ catch (Exception ex)
+ {
+ _log.Error($"[{Name}] unhandled exception in {request.Kind} handler: {ex}");
+ request.Fail(NtStatus.Unsuccessful);
+ }
+ }
+
+ /// Waits until all in-flight handler invocations have finished.
+ public async Task DrainAsync()
+ {
+ while (true)
+ {
+ Task[] snapshot;
+ lock (_gate)
+ {
+ snapshot = _outstanding.ToArray();
+ }
+ if (snapshot.Length == 0)
+ {
+ return;
+ }
+ await Task.WhenAll(snapshot).ConfigureAwait(false);
+ }
+ }
+
+ ///
+ /// Stops the queue: pending manual requests are cancelled, and new
+ /// submissions complete immediately with .
+ ///
+ public async Task StopAsync()
+ {
+ if (IsStopped)
+ {
+ return;
+ }
+ IsStopped = true;
+ _stopping.Cancel();
+ _manualChannel.Writer.TryComplete();
+ while (_manualChannel.Reader.TryRead(out var pending))
+ {
+ pending.Fail(NtStatus.Cancelled);
+ }
+ await DrainAsync().ConfigureAwait(false);
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/IoRequest.cs b/src/WindowsDriver.Sdk/Runtime/IoRequest.cs
new file mode 100644
index 0000000..2e0b950
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/IoRequest.cs
@@ -0,0 +1,101 @@
+namespace WindowsDriver.Sdk;
+
+/// The kind of IO operation a request represents (maps to WDF request types).
+public enum IoRequestKind
+{
+ DeviceControl,
+ Read,
+ Write,
+ Create,
+ Close,
+}
+
+///
+/// A single IO request flowing from the host (test host, UMDF shim or KMDF
+/// control plane) into a driver queue. The driver inspects the buffers and
+/// finishes the request exactly once with — the same
+/// contract as WdfRequestComplete.
+///
+public sealed class IoRequest
+{
+ private bool _completed;
+
+ public IoRequest(IoRequestKind kind, uint ioControlCode, ReadOnlyMemory input, Memory output, ulong id = 0)
+ {
+ Kind = kind;
+ IoControlCode = ioControlCode;
+ InputBuffer = input;
+ OutputBuffer = output;
+ Id = id;
+ }
+
+ /// Host-assigned identifier, useful for tracing a request across layers.
+ public ulong Id { get; }
+
+ public IoRequestKind Kind { get; }
+
+ /// The IOCTL code — meaningful only for .
+ public uint IoControlCode { get; }
+
+ /// SystemBuffer input side (IRP SystemBuffer with METHOD_BUFFERED).
+ public ReadOnlyMemory InputBuffer { get; }
+
+ /// Output side: the driver fills it and reports transferred bytes.
+ public Memory OutputBuffer { get; }
+
+ public bool IsCompleted => _completed;
+
+ public NtStatus Status { get; private set; } = NtStatus.Pending;
+
+ public int BytesTransferred { get; private set; }
+
+ /// Raised exactly once when the request is completed (host-side observation).
+ public event Action? Completed;
+
+ ///
+ /// Completes the request. Completing twice throws — in WDF a double-complete
+ /// bugchecks the machine, so treat this as a driver bug.
+ ///
+ public void Complete(NtStatus status, int bytesTransferred = 0)
+ {
+ if (_completed)
+ {
+ throw new InvalidOperationException($"Request {Id} was already completed with {Status.ToHexString()} — double completion is a driver bug.");
+ }
+ // Information semantics follow WdfRequestCompleteWithInformation: for
+ // writes the count refers to bytes taken from the input buffer, for
+ // everything else to bytes placed in the output buffer.
+ var maxInformation = Kind == IoRequestKind.Write ? InputBuffer.Length : OutputBuffer.Length;
+ if (bytesTransferred < 0 || bytesTransferred > maxInformation)
+ {
+ throw new ArgumentOutOfRangeException(nameof(bytesTransferred),
+ $"Transferred {bytesTransferred} bytes but the buffer only allows {maxInformation}.");
+ }
+ _completed = true;
+ Status = status;
+ BytesTransferred = bytesTransferred;
+ Completed?.Invoke(this);
+ }
+
+ /// Completes with the given failure status and zero bytes.
+ public void Fail(NtStatus status) => Complete(status, 0);
+}
+
+///
+/// An immutable snapshot of a completed request, as returned by the test host's
+/// SendIoctl/Read/Write helpers.
+///
+public sealed record IoResult(NtStatus Status, int BytesTransferred, byte[] Output)
+{
+ public bool IsSuccess => Status.IsSuccess();
+
+ public static IoResult From(IoRequest request)
+ {
+ // For writes, report the transmitted bytes; for reads and IOCTLs, the output data.
+ var source = request.Kind == IoRequestKind.Write ? request.InputBuffer.Span : request.OutputBuffer.Span;
+ var count = Math.Min(request.BytesTransferred, source.Length);
+ var output = new byte[count];
+ source.Slice(0, count).CopyTo(output);
+ return new IoResult(request.Status, request.BytesTransferred, output);
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/NtStatus.cs b/src/WindowsDriver.Sdk/Runtime/NtStatus.cs
new file mode 100644
index 0000000..66c048c
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/NtStatus.cs
@@ -0,0 +1,60 @@
+using System.Text;
+
+namespace WindowsDriver.Sdk;
+
+///
+/// NTSTATUS values used by the Windows kernel and returned from IOCTLs.
+/// Only the values a driver author regularly needs are listed here; extend as
+/// required. The numeric values match winnt.h / ntstatus.h exactly.
+///
+public enum NtStatus : uint
+{
+ Success = 0x00000000,
+ Timeout = 0x00000102, // informational
+ Pending = 0x00000103, // informational
+ BufferOverflow = 0x80000005, // warning
+ Unsuccessful = 0xC0000001,
+ NoSuchDevice = 0xC000000E,
+ InvalidParameter = 0xC000000D,
+ EndOfFile = 0xC0000011,
+ InvalidDeviceRequest = 0xC0000010,
+ AccessDenied = 0xC0000022,
+ BufferTooSmall = 0xC0000023,
+ ObjectNameNotFound = 0xC0000034,
+ Cancelled = 0xC0000120,
+ DeviceNotReady = 0xC00000A3,
+ IoTimeout = 0xC00000B5,
+ NotSupported = 0xC00000BB,
+ InvalidDeviceState = 0xC0000184,
+}
+
+/// Severity and convenience checks for .
+public static class NtStatusExtensions
+{
+ /// NT_SUCCESS: matches the C macro ((NTSTATUS)s >= 0) — success and informational severities.
+ public static bool IsSuccess(this NtStatus status) => (uint)status < 0x80000000u;
+
+ /// NT_INFORMATION: severity 1.
+ public static bool IsInformational(this NtStatus status) => ((uint)status >> 30) == 1;
+
+ /// NT_WARNING: severity 2 (includes ).
+ public static bool IsWarning(this NtStatus status) => ((uint)status >> 30) == 2;
+
+ /// NT_ERROR: severity 3.
+ public static bool IsError(this NtStatus status) => ((uint)status >> 30) == 3;
+
+ /// The two-bit NTSTATUS severity field (bits 30–31).
+ public static uint Severity(this NtStatus status) => (uint)status >> 30;
+
+ /// "0xC0000010 (InvalidDeviceRequest)" style rendering for logs.
+ public static string ToHexString(this NtStatus status)
+ {
+ var sb = new StringBuilder(20);
+ sb.Append("0x").Append(((uint)status).ToString("X8"));
+ if (((uint)status & 0xC0000000u) != 0 || status == NtStatus.Success)
+ {
+ sb.Append(" (").Append(status.ToString()).Append(')');
+ }
+ return sb.ToString();
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/PropertyStore.cs b/src/WindowsDriver.Sdk/Runtime/PropertyStore.cs
new file mode 100644
index 0000000..431e5bc
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/PropertyStore.cs
@@ -0,0 +1,160 @@
+using System.Globalization;
+
+namespace WindowsDriver.Sdk;
+
+///
+/// A typed, string-keyed store for device and driver properties — the managed
+/// stand-in for DEVPKEY properties and registry blobs attached to a devnode.
+///
+public sealed class PropertyStore
+{
+ private readonly object _gate = new();
+ private readonly Dictionary _values = new(StringComparer.OrdinalIgnoreCase);
+
+ public IReadOnlyCollection Keys
+ {
+ get { lock (_gate) { return _values.Keys.ToArray(); } }
+ }
+
+ public int Count
+ {
+ get { lock (_gate) { return _values.Count; } }
+ }
+
+ public bool Contains(string key)
+ {
+ lock (_gate)
+ {
+ return _values.ContainsKey(key);
+ }
+ }
+
+ public string? GetString(string key, string? defaultValue = null)
+ {
+ lock (_gate)
+ {
+ return _values.TryGetValue(key, out var value) && value is string s ? s : defaultValue;
+ }
+ }
+
+ public uint? GetDword(string key, uint? defaultValue = null)
+ {
+ lock (_gate)
+ {
+ return _values.TryGetValue(key, out var value)
+ ? value switch
+ {
+ uint u => u,
+ int i when i >= 0 => (uint)i,
+ string s when uint.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsed) => parsed,
+ _ => defaultValue,
+ }
+ : defaultValue;
+ }
+ }
+
+ public long? GetLong(string key, long? defaultValue = null)
+ {
+ lock (_gate)
+ {
+ return _values.TryGetValue(key, out var value)
+ ? value switch
+ {
+ long l => l,
+ int i => i,
+ uint u => u,
+ _ => defaultValue,
+ }
+ : defaultValue;
+ }
+ }
+
+ public bool GetBool(string key, bool defaultValue = false)
+ {
+ lock (_gate)
+ {
+ return _values.TryGetValue(key, out var value)
+ ? value switch
+ {
+ bool b => b,
+ uint u => u != 0,
+ string s => s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1",
+ _ => defaultValue,
+ }
+ : defaultValue;
+ }
+ }
+
+ public Guid? GetGuid(string key)
+ {
+ lock (_gate)
+ {
+ return _values.TryGetValue(key, out var value)
+ ? value switch
+ {
+ Guid g => g,
+ string s when Guid.TryParse(s, out var parsed) => parsed,
+ _ => null,
+ }
+ : null;
+ }
+ }
+
+ public object? GetRaw(string key)
+ {
+ lock (_gate)
+ {
+ return _values.TryGetValue(key, out var value) ? value : null;
+ }
+ }
+
+ public void Set(string key, string value) => SetRaw(key, value);
+ public void Set(string key, uint value) => SetRaw(key, value);
+ public void Set(string key, int value) => SetRaw(key, value);
+ public void Set(string key, long value) => SetRaw(key, value);
+ public void Set(string key, bool value) => SetRaw(key, value);
+ public void Set(string key, Guid value) => SetRaw(key, value);
+
+ public void SetRaw(string key, object value)
+ {
+ ArgumentNullException.ThrowIfNull(value);
+ lock (_gate)
+ {
+ _values[key] = value;
+ }
+ }
+
+ public bool Remove(string key)
+ {
+ lock (_gate)
+ {
+ return _values.Remove(key);
+ }
+ }
+
+ public void Clear()
+ {
+ lock (_gate)
+ {
+ _values.Clear();
+ }
+ }
+
+ public override string ToString()
+ {
+ lock (_gate)
+ {
+ return $"PropertyStore[{_values.Count}]: " + string.Join(", ", _values.Select(kvp => $"{kvp.Key}={kvp.Value}"));
+ }
+ }
+}
+
+/// Well-known property key names used by samples and tooling.
+public static class KnownDeviceProperties
+{
+ public const string FriendlyName = "Device_FriendlyName";
+ public const string Manufacturer = "Device_Manufacturer";
+ public const string DeviceDescription = "Device_DeviceDesc";
+ public const string DriverVersion = "Device_DriverVersion";
+ public const string InterfaceClassGuid = "Device_InterfaceClassGuid";
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/WinIoctl.cs b/src/WindowsDriver.Sdk/Runtime/WinIoctl.cs
new file mode 100644
index 0000000..1221e2b
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/WinIoctl.cs
@@ -0,0 +1,74 @@
+namespace WindowsDriver.Sdk;
+
+///
+/// Device types, transfer methods and access rights used to build IOCTL codes,
+/// plus , the managed equivalent of the C macro
+/// CTL_CODE(DeviceType, Function, Method, Access) from winioctl.h:
+///
+/// #define CTL_CODE(DeviceType, Function, Method, Access) \
+/// (((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
+///
+///
+public static class WinIoctl
+{
+ // ----- Common FILE_DEVICE_* device types (winioctl.h) -----
+ public const uint FileDeviceKeyboard = 0x00000009;
+ public const uint FileDeviceNetwork = 0x00000012;
+ public const uint FileDeviceSerialPort = 0x0000001B;
+ public const uint FileDeviceUnknown = 0x00000022;
+ public const uint FileDeviceSound = 0x00000023;
+
+ /// Recommended device type for SDK drivers that define custom IOCTLs.
+ public const uint FileDeviceVendorDefault = FileDeviceUnknown;
+
+ // ----- Transfer methods -----
+ public const uint MethodBuffered = 0;
+ public const uint MethodInDirect = 1;
+ public const uint MethodOutDirect = 2;
+ public const uint MethodNeither = 3;
+
+ // ----- Access requirements -----
+ public const uint FileAccessAny = 0x0000; // FILE_ANY_ACCESS
+ public const uint FileAccessRead = 0x0001; // FILE_READ_ACCESS
+ public const uint FileAccessWrite = 0x0002; // FILE_WRITE_ACCESS
+ public const uint FileAccessReadWrite = FileAccessRead | FileAccessWrite;
+
+ ///
+ /// IOCTL function codes below this value are reserved for Microsoft system
+ /// use; vendor drivers must start their function codes here.
+ ///
+ public const uint FirstVendorFunction = 0x800;
+
+ /// Managed CTL_CODE. Bit layout matches the C macro exactly.
+ public static uint CtlCode(uint deviceType, uint function, uint method, uint access) =>
+ (deviceType << 16) | ((access & 0x3) << 14) | (function << 2) | method;
+
+ /// Extracts the device-type field from an IOCTL code (bits 16–31).
+ public static uint DeviceTypeFromControl(uint controlCode) => controlCode >> 16;
+
+ /// Extracts the function field from an IOCTL code (bits 2–13, a 12-bit field).
+ public static uint FunctionFromControl(uint controlCode) => (controlCode >> 2) & 0xFFF;
+
+ /// Extracts the method field from an IOCTL code (bits 0–1).
+ public static uint MethodFromControl(uint controlCode) => controlCode & 0x3;
+
+ /// Extracts the access field from an IOCTL code (bits 14–15).
+ public static uint AccessFromControl(uint controlCode) => (controlCode >> 14) & 0x3;
+
+ ///
+ /// Builds a vendor-defined IOCTL with METHOD_BUFFERED — the default choice for
+ /// SDK drivers because the host copies buffers in and out for you.
+ ///
+ /// Function code, must be or higher.
+ /// Access requirement (, , or both).
+ /// FILE_DEVICE_* device type; defaults to .
+ public static uint VendorControlCode(uint function, uint access = FileAccessReadWrite, uint deviceType = FileDeviceVendorDefault)
+ {
+ if (function < FirstVendorFunction)
+ {
+ throw new ArgumentOutOfRangeException(nameof(function),
+ $"Vendor function codes must be >= {FirstVendorFunction}; codes below that are reserved for Microsoft.");
+ }
+ return CtlCode(deviceType, function, MethodBuffered, access);
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Runtime/WireFormat.cs b/src/WindowsDriver.Sdk/Runtime/WireFormat.cs
new file mode 100644
index 0000000..0cc58db
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Runtime/WireFormat.cs
@@ -0,0 +1,41 @@
+using System.Buffers.Binary;
+
+namespace WindowsDriver.Sdk;
+
+///
+/// Explicit little-endian read/write helpers for IOCTL payloads. Windows runs on
+/// little-endian hardware, so every wire struct in the SDK is little-endian.
+/// These helpers throw with
+/// when the destination is too short —
+/// the same status a real driver returns for undersized output buffers.
+///
+public static class WireFormat
+{
+ public static void WriteInt16(Span dest, int offset, short value) { ThrowIfTooSmall(dest.Length, offset, sizeof(short)); BinaryPrimitives.WriteInt16LittleEndian(dest.Slice(offset), value); }
+ public static void WriteUInt16(Span dest, int offset, ushort value) { ThrowIfTooSmall(dest.Length, offset, sizeof(ushort)); BinaryPrimitives.WriteUInt16LittleEndian(dest.Slice(offset), value); }
+ public static void WriteInt32(Span dest, int offset, int value) { ThrowIfTooSmall(dest.Length, offset, sizeof(int)); BinaryPrimitives.WriteInt32LittleEndian(dest.Slice(offset), value); }
+ public static void WriteUInt32(Span dest, int offset, uint value) { ThrowIfTooSmall(dest.Length, offset, sizeof(uint)); BinaryPrimitives.WriteUInt32LittleEndian(dest.Slice(offset), value); }
+ public static void WriteInt64(Span dest, int offset, long value) { ThrowIfTooSmall(dest.Length, offset, sizeof(long)); BinaryPrimitives.WriteInt64LittleEndian(dest.Slice(offset), value); }
+ public static void WriteUInt64(Span dest, int offset, ulong value) { ThrowIfTooSmall(dest.Length, offset, sizeof(ulong)); BinaryPrimitives.WriteUInt64LittleEndian(dest.Slice(offset), value); }
+ public static void WriteFloat(Span dest, int offset, float value) { ThrowIfTooSmall(dest.Length, offset, sizeof(float)); BinaryPrimitives.WriteSingleLittleEndian(dest.Slice(offset), value); }
+ public static void WriteDouble(Span dest, int offset, double value) { ThrowIfTooSmall(dest.Length, offset, sizeof(double)); BinaryPrimitives.WriteDoubleLittleEndian(dest.Slice(offset), value); }
+
+ public static short ReadInt16(ReadOnlySpan src, int offset) { ThrowIfTooSmall(src.Length, offset, sizeof(short)); return BinaryPrimitives.ReadInt16LittleEndian(src.Slice(offset)); }
+ public static ushort ReadUInt16(ReadOnlySpan src, int offset) { ThrowIfTooSmall(src.Length, offset, sizeof(ushort)); return BinaryPrimitives.ReadUInt16LittleEndian(src.Slice(offset)); }
+ public static int ReadInt32(ReadOnlySpan src, int offset) { ThrowIfTooSmall(src.Length, offset, sizeof(int)); return BinaryPrimitives.ReadInt32LittleEndian(src.Slice(offset)); }
+ public static uint ReadUInt32(ReadOnlySpan src, int offset) { ThrowIfTooSmall(src.Length, offset, sizeof(uint)); return BinaryPrimitives.ReadUInt32LittleEndian(src.Slice(offset)); }
+ public static long ReadInt64(ReadOnlySpan src, int offset) { ThrowIfTooSmall(src.Length, offset, sizeof(long)); return BinaryPrimitives.ReadInt64LittleEndian(src.Slice(offset)); }
+ public static ulong ReadUInt64(ReadOnlySpan src, int offset) { ThrowIfTooSmall(src.Length, offset, sizeof(ulong)); return BinaryPrimitives.ReadUInt64LittleEndian(src.Slice(offset)); }
+ public static float ReadFloat(ReadOnlySpan src, int offset) { ThrowIfTooSmall(src.Length, offset, sizeof(float)); return BinaryPrimitives.ReadSingleLittleEndian(src.Slice(offset)); }
+ public static double ReadDouble(ReadOnlySpan src, int offset) { ThrowIfTooSmall(src.Length, offset, sizeof(double)); return BinaryPrimitives.ReadDoubleLittleEndian(src.Slice(offset)); }
+
+ /// Throws BufferTooSmall when [offset, offset + size) falls outside the buffer.
+ public static void ThrowIfTooSmall(int bufferLength, int offset, int size)
+ {
+ if (offset < 0 || size < 0 || (long)offset + size > bufferLength)
+ {
+ throw new DriverException(NtStatus.BufferTooSmall,
+ $"Need {size} bytes at offset {offset} but the buffer is {bufferLength} bytes.");
+ }
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Sensor/SensorDevice.cs b/src/WindowsDriver.Sdk/Sensor/SensorDevice.cs
new file mode 100644
index 0000000..f677be4
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Sensor/SensorDevice.cs
@@ -0,0 +1,282 @@
+using System.Text;
+using System.Threading.Channels;
+
+namespace WindowsDriver.Sdk.Sensor;
+
+///
+/// SDK-level IOCTL contract for sensor devices handled by .
+/// Payload layouts are implemented with ; see
+/// docs/sensor-guide.md for the SensorCx mapping.
+///
+public static class SensorIoctlCodes
+{
+ private static uint Ctl(uint function, uint access) => WinIoctl.VendorControlCode(function, access);
+
+ /// Out: u32 sensor count.
+ public static readonly uint GetSensorCount = Ctl(0x800, WinIoctl.FileAccessRead);
+
+ /// In: u32 index. Out: (u32 kind, u32 valueCount, u32 sampleRateMilliHz, char[16] unit).
+ public static readonly uint GetSensorInfo = Ctl(0x801, WinIoctl.FileAccessRead);
+
+ /// In: u32 index. Out: (u64 timestampTicks100ns, u32 valueCount, valueCount × f64).
+ public static readonly uint GetLatestReading = Ctl(0x802, WinIoctl.FileAccessRead);
+
+ /// In: (u32 index, u32 sampleRateMilliHz). Sets the poll rate.
+ public static readonly uint SetSampleRate = Ctl(0x803, WinIoctl.FileAccessWrite);
+}
+
+/// Configuration for .
+public sealed class SensorDeviceOptions
+{
+ /// The sensors this device publishes (order defines indices).
+ public IReadOnlyList Sources { get; init; } = [];
+
+ /// Background sampling interval cap: real drivers sample on hardware interrupts; the loop uses at most this many ticks/second.
+ public bool RunBackgroundSamplingLoop { get; init; } = true;
+
+ /// Maximum readings buffered in the event queue before old ones are dropped.
+ public int EventQueueCapacity { get; init; } = 256;
+}
+
+///
+/// A virtual sensor device hosting one or more s.
+/// Clients poll or subscribe via
+/// the event queue (). A background loop samples at each
+/// sensor's rate while the device is in D0; also works
+/// synchronously for tests.
+///
+public class SensorDevice : DeviceBase
+{
+ private readonly SensorDeviceOptions _options;
+ private readonly ISensorSource[] _sources;
+ private readonly SensorReading?[] _latest;
+ private readonly Channel _readings;
+ private Task? _samplingLoop;
+ private CancellationTokenSource? _loopCancellation;
+
+ public SensorDevice(DeviceContext context, SensorDeviceOptions? options = null)
+ : base(context)
+ {
+ _options = options ?? new SensorDeviceOptions();
+ _sources = _options.Sources.ToArray();
+ if (_sources.Length == 0)
+ {
+ throw new ArgumentException("At least one sensor source is required.", nameof(options));
+ }
+ _latest = new SensorReading?[_sources.Length];
+ _readings = Channel.CreateBounded(new BoundedChannelOptions(_options.EventQueueCapacity)
+ {
+ FullMode = BoundedChannelFullMode.DropOldest,
+ });
+
+ DefaultQueue
+ .OnDeviceControl(HandleDeviceControlAsync)
+ .OnRead(HandleReadAsync);
+ }
+
+ /// Event queue of sampled readings (dropped-oldest when full).
+ public ChannelReader Readings => _readings.Reader;
+
+ public int SensorCount => _sources.Length;
+
+ public ISensorSource GetSource(int index) => _sources[index];
+
+ /// Samples every sensor once (background loop calls this too).
+ public void SampleOnce()
+ {
+ var now = Driver.TimeProvider.GetUtcNow();
+ for (var i = 0; i < _sources.Length; i++)
+ {
+ var reading = _sources[i].Sample(now);
+ _latest[i] = reading;
+ _readings.Writer.TryWrite(reading);
+ }
+ }
+
+ public SensorReading? LatestReading(int index) => _latest[index];
+
+ public override Task OnD0EntryAsync(DevicePowerState previousState, CancellationToken cancellationToken)
+ {
+ if (_options.RunBackgroundSamplingLoop)
+ {
+ _loopCancellation = new CancellationTokenSource();
+ _samplingLoop = Task.Run(() => SamplingLoopAsync(_loopCancellation.Token));
+ }
+ return Task.CompletedTask;
+ }
+
+ public override async Task OnD0ExitAsync(DevicePowerState newState, CancellationToken cancellationToken)
+ {
+ if (_loopCancellation is not null)
+ {
+ _loopCancellation.Cancel();
+ try
+ {
+ if (_samplingLoop is not null)
+ {
+ await _samplingLoop.WaitAsync(TimeSpan.FromSeconds(2), cancellationToken).ConfigureAwait(false);
+ }
+ }
+ catch (TimeoutException)
+ {
+ Context.Log.Warning("sensor sampling loop did not stop within 2s");
+ }
+ _loopCancellation.Dispose();
+ _loopCancellation = null;
+ _samplingLoop = null;
+ }
+ }
+
+ private async Task SamplingLoopAsync(CancellationToken ct)
+ {
+ // Interleave sensors: the loop wakes at the fastest configured rate and
+ // samples everything (cheap for simulated sources).
+ var fastestHz = _sources.Max(s => s.SampleRateHz);
+ var interval = TimeSpan.FromMilliseconds(Math.Max(1, 1000.0 / fastestHz));
+ while (!ct.IsCancellationRequested)
+ {
+ try
+ {
+ await Task.Delay(interval, Driver.TimeProvider, ct).ConfigureAwait(false);
+ SampleOnce();
+ }
+ catch (OperationCanceledException)
+ {
+ return;
+ }
+ }
+ }
+
+ private Task HandleReadAsync(IoRequest request, CancellationToken ct)
+ {
+ // Read = latest accelerometer values, if present (convenience for stream-style clients).
+ var accel = Array.FindIndex(_sources, s => s.Kind == SensorKind.Accelerometer3D);
+ if (accel < 0 || _latest[accel] is not { } reading)
+ {
+ request.Fail(NtStatus.DeviceNotReady);
+ return Task.CompletedTask;
+ }
+ var needed = sizeof(ulong) + sizeof(uint) + reading.Values.Count * sizeof(double);
+ if (request.OutputBuffer.Length < needed)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ return Task.CompletedTask;
+ }
+ WriteReading(request.OutputBuffer.Span, reading);
+ request.Complete(NtStatus.Success, needed);
+ return Task.CompletedTask;
+ }
+
+ ///
+ /// Handles the contract. Subclasses override
+ /// this to add device-specific IOCTLs and fall back to base for the rest.
+ ///
+ protected virtual Task HandleDeviceControlAsync(IoRequest request, CancellationToken ct)
+ {
+ var code = request.IoControlCode;
+ if (code == SensorIoctlCodes.GetSensorCount)
+ {
+ if (request.OutputBuffer.Length < sizeof(uint))
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ WireFormat.WriteUInt32(request.OutputBuffer.Span, 0, (uint)_sources.Length);
+ request.Complete(NtStatus.Success, sizeof(uint));
+ }
+ }
+ else if (code == SensorIoctlCodes.GetSensorInfo)
+ {
+ var index = ReadIndex(request, _sources.Length);
+ var source = _sources[index];
+ var needed = 3 * sizeof(uint) + 16;
+ if (request.OutputBuffer.Length < needed)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ var span = request.OutputBuffer.Span;
+ WireFormat.WriteUInt32(span, 0, (uint)source.Kind);
+ WireFormat.WriteUInt32(span, 4, (uint)source.ValueCount);
+ WireFormat.WriteUInt32(span, 8, (uint)(source.SampleRateHz * 1000));
+ var unit = Encoding.ASCII.GetBytes(source.Unit);
+ span.Slice(12, 16).Fill(0);
+ unit.AsSpan(0, Math.Min(unit.Length, 16)).CopyTo(span.Slice(12));
+ request.Complete(NtStatus.Success, needed);
+ }
+ }
+ else if (code == SensorIoctlCodes.GetLatestReading)
+ {
+ var index = ReadIndex(request, _sources.Length);
+ if (_latest[index] is not { } reading)
+ {
+ request.Fail(NtStatus.DeviceNotReady);
+ }
+ else
+ {
+ var needed = sizeof(ulong) + sizeof(uint) + reading.Values.Count * sizeof(double);
+ if (request.OutputBuffer.Length < needed)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ WriteReading(request.OutputBuffer.Span, reading);
+ request.Complete(NtStatus.Success, needed);
+ }
+ }
+ }
+ else if (code == SensorIoctlCodes.SetSampleRate)
+ {
+ if (request.InputBuffer.Length < 2 * sizeof(uint))
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ var index = (int)WireFormat.ReadUInt32(request.InputBuffer.Span, 0);
+ if (index < 0 || index >= _sources.Length)
+ {
+ request.Fail(NtStatus.InvalidParameter);
+ }
+ else
+ {
+ var milliHz = WireFormat.ReadUInt32(request.InputBuffer.Span, 4);
+ _sources[index].SampleRateHz = milliHz / 1000.0;
+ request.Complete(NtStatus.Success);
+ }
+ }
+ }
+ else
+ {
+ request.Fail(NtStatus.InvalidDeviceRequest);
+ }
+ return Task.CompletedTask;
+ }
+
+ private static int ReadIndex(IoRequest request, int sensorCount)
+ {
+ if (request.InputBuffer.Length < sizeof(uint))
+ {
+ throw new DriverException(NtStatus.BufferTooSmall, "Sensor index buffer too small.");
+ }
+ var index = (int)WireFormat.ReadUInt32(request.InputBuffer.Span, 0);
+ if (index < 0 || index >= sensorCount)
+ {
+ throw new DriverException(NtStatus.InvalidParameter, $"Sensor index {index} is out of range (0..{sensorCount - 1}).");
+ }
+ return index;
+ }
+
+ private static void WriteReading(Span dest, SensorReading reading)
+ {
+ WireFormat.WriteUInt64(dest, 0, (ulong)reading.Timestamp.UtcTicks);
+ WireFormat.WriteUInt32(dest, 8, (uint)reading.Values.Count);
+ for (var i = 0; i < reading.Values.Count; i++)
+ {
+ WireFormat.WriteDouble(dest, 12 + i * sizeof(double), reading.Values[i]);
+ }
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Sensor/SensorModel.cs b/src/WindowsDriver.Sdk/Sensor/SensorModel.cs
new file mode 100644
index 0000000..7b9e824
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Sensor/SensorModel.cs
@@ -0,0 +1,32 @@
+namespace WindowsDriver.Sdk.Sensor;
+
+/// Categories of sensors the SDK models (map onto Windows sensor categories/types when integrating with SensorCx).
+public enum SensorKind
+{
+ Accelerometer3D,
+ AmbientLight,
+ Custom,
+}
+
+/// A single sampled reading from a sensor.
+public sealed record SensorReading(
+ SensorKind Kind,
+ DateTimeOffset Timestamp,
+ IReadOnlyList Values,
+ string Unit);
+
+///
+/// A sampled data source for . Implementations are
+/// pure functions of the timestamp, so tests are fully deterministic.
+///
+public interface ISensorSource
+{
+ SensorKind Kind { get; }
+ string Unit { get; }
+ int ValueCount { get; }
+
+ /// Samples-per-second the device should poll at.
+ double SampleRateHz { get; set; }
+
+ SensorReading Sample(DateTimeOffset timestamp);
+}
diff --git a/src/WindowsDriver.Sdk/Sensor/SensorSimulators.cs b/src/WindowsDriver.Sdk/Sensor/SensorSimulators.cs
new file mode 100644
index 0000000..4db1e9d
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Sensor/SensorSimulators.cs
@@ -0,0 +1,132 @@
+namespace WindowsDriver.Sdk.Sensor;
+
+///
+/// Deterministic 3-axis accelerometer simulator. Gravity is applied on +Z
+/// (device lying flat), with smooth seeded sine-noise and optional transient
+/// impulses (taps, shakes). Sampling is a pure function of the timestamp:
+/// the same timestamp always yields the same values.
+///
+public sealed class AccelerometerSimulator : ISensorSource
+{
+ private readonly double[] _frequencies;
+ private readonly double[] _phases;
+ private readonly List _impulses = [];
+
+ public AccelerometerSimulator(int seed = 42, double sampleRateHz = 50)
+ {
+ var random = new Random(seed);
+ _frequencies = new double[3];
+ _phases = new double[3];
+ for (var i = 0; i < 3; i++)
+ {
+ // 0.5–4 Hz wobble components per axis
+ _frequencies[i] = 0.5 + random.NextDouble() * 3.5;
+ _phases[i] = random.NextDouble() * 2 * Math.PI;
+ }
+ SampleRateHz = sampleRateHz;
+ }
+
+ public double SampleRateHz { get; set; }
+
+ /// Amplitude of the smooth noise in m/s² per axis.
+ public double NoiseLevel { get; set; } = 0.05;
+
+ /// Gravity magnitude in m/s² (standard gravity).
+ public double GravityMagnitude { get; set; } = 9.80665;
+
+ /// Adds a transient acceleration impulse starting at with linear attack/release.
+ public void AddImpulse(TimeSpan at, TimeSpan duration, (double X, double Y, double Z) acceleration)
+ {
+ _impulses.Add(new Impulse(at, duration, acceleration));
+ }
+
+ public SensorKind Kind => SensorKind.Accelerometer3D;
+ public string Unit => "m/s^2";
+ public int ValueCount => 3;
+
+ public SensorReading Sample(DateTimeOffset timestamp)
+ {
+ var t = timestamp.TimeOfDay.TotalSeconds;
+ var x = Noise(t, 0);
+ var y = Noise(t, 1);
+ var z = Noise(t, 2) + GravityMagnitude;
+ foreach (var impulse in _impulses)
+ {
+ var contribution = impulse.ValueAt(timestamp.TimeOfDay);
+ x += contribution.X;
+ y += contribution.Y;
+ z += contribution.Z;
+ }
+ return new SensorReading(Kind, timestamp, [x, y, z], Unit);
+ }
+
+ private double Noise(double tSeconds, int axis) =>
+ NoiseLevel * Math.Sin(2 * Math.PI * _frequencies[axis] * tSeconds + _phases[axis]);
+
+ private sealed record Impulse(TimeSpan Start, TimeSpan Duration, (double X, double Y, double Z) Accel)
+ {
+ public (double X, double Y, double Z) ValueAt(TimeSpan time)
+ {
+ if (time < Start || time > Start + Duration)
+ {
+ return (0, 0, 0);
+ }
+ // Triangular envelope: linear rise to peak at the midpoint.
+ var p = (time - Start) / Duration;
+ var envelope = 2 * (p <= 0.5 ? p : 1 - p);
+ return (Accel.X * envelope, Accel.Y * envelope, Accel.Z * envelope);
+ }
+ }
+}
+
+///
+/// Deterministic ambient light simulator: an indoor baseline with a smooth
+/// daylight sine curve (peak at 12:00) plus seeded noise. A manual override
+/// wins over the curve — used to simulate a lamp being switched.
+///
+public sealed class AmbientLightSimulator : ISensorSource
+{
+ private readonly double _frequency;
+ private readonly double _phase;
+
+ public AmbientLightSimulator(int seed = 7, double sampleRateHz = 4)
+ {
+ var random = new Random(seed);
+ _frequency = 0.05 + random.NextDouble() * 0.1; // slow flicker
+ _phase = random.NextDouble() * 2 * Math.PI;
+ SampleRateHz = sampleRateHz;
+ }
+
+ public double SampleRateHz { get; set; }
+
+ /// Indoor baseline illuminance in lux.
+ public double IndoorBaseLux { get; set; } = 400;
+
+ /// Peak outdoor contribution at solar noon in lux.
+ public double PeakDaylightLux { get; set; } = 12000;
+
+ /// Manual illuminance override; null follows the day curve.
+ public double? OverrideLux { get; set; }
+
+ public SensorKind Kind => SensorKind.AmbientLight;
+ public string Unit => "lx";
+ public int ValueCount => 1;
+
+ public SensorReading Sample(DateTimeOffset timestamp)
+ {
+ if (OverrideLux is { } manual)
+ {
+ return new SensorReading(Kind, timestamp, [manual], Unit);
+ }
+
+ var timeOfDay = timestamp.TimeOfDay;
+ // Sun above horizon from ~06:00 to ~18:00, peaking at noon.
+ var dayFraction = (timeOfDay - TimeSpan.FromHours(6)) / TimeSpan.FromHours(12);
+ var daylight = dayFraction > 0 && dayFraction < 1
+ ? Math.Sin(dayFraction * Math.PI) * PeakDaylightLux
+ : 0;
+ var flicker = IndoorBaseLux * 0.05 * Math.Sin(2 * Math.PI * _frequency * timeOfDay.TotalSeconds + _phase);
+ var lux = Math.Max(0, IndoorBaseLux + daylight + flicker);
+ return new SensorReading(Kind, timestamp, [lux], Unit);
+ }
+}
diff --git a/src/WindowsDriver.Sdk/Serial/SerialDevice.cs b/src/WindowsDriver.Sdk/Serial/SerialDevice.cs
new file mode 100644
index 0000000..32cc290
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Serial/SerialDevice.cs
@@ -0,0 +1,282 @@
+namespace WindowsDriver.Sdk.Serial;
+
+/// Receives every byte transmitted by a serial device (used to cross-connect two ports).
+public delegate void TxSink(ReadOnlySpan data);
+
+///
+/// SDK-level IOCTL contract for serial devices handled by .
+/// When a serial driver is integrated with Windows, serenum/the serial class maps
+/// device traffic onto the standard serial IOCTLs (serial.h); see docs/serial-guide.md.
+///
+public static class SerialIoctlCodes
+{
+ private static uint Ctl(uint function, uint access) => WinIoctl.VendorControlCode(function, access, WinIoctl.FileDeviceSerialPort);
+
+ /// Out: wire struct.
+ public static readonly uint GetLineConfig = Ctl(0x800, WinIoctl.FileAccessRead);
+
+ /// In: wire struct (8 bytes).
+ public static readonly uint SetLineConfig = Ctl(0x801, WinIoctl.FileAccessWrite);
+
+ /// In: bytes to transmit (any length ≥ 1).
+ public static readonly uint Transmit = Ctl(0x802, WinIoctl.FileAccessWrite);
+
+ /// In: u32 flags — bit 0 purge RX, bit 1 purge TX.
+ public static readonly uint Purge = Ctl(0x803, WinIoctl.FileAccessWrite);
+
+ /// Out: (u64 txBytes, u64 rxBytes, u32 framingErrors, u8 cts, u8 dsr, u8 breakActive, u8 loopback).
+ public static readonly uint GetStatus = Ctl(0x804, WinIoctl.FileAccessRead);
+
+ /// Out: u32 receive queue depth (bytes waiting).
+ public static readonly uint GetRxCount = Ctl(0x805, WinIoctl.FileAccessRead);
+}
+
+/// Configuration for .
+public sealed class SerialDeviceOptions
+{
+ public SerialLineConfig InitialConfig { get; init; } = new();
+
+ /// When true, transmitted bytes echo into the RX queue (loopback plug).
+ public bool Loopback { get; init; } = true;
+
+ public int RxQueueBytes { get; init; } = 4096;
+ public int TxQueueBytes { get; init; } = 4096;
+}
+
+///
+/// A complete virtual serial port: line config with UART validation, TX/RX
+/// queues, loopback, modem status (CTS/DSR), break detection and counters.
+/// Two instances can be cross-connected with
+/// to form a virtual null-modem cable.
+///
+public class SerialDevice : DeviceBase
+{
+ private readonly ByteRingBuffer _rx;
+ private readonly ByteRingBuffer _tx;
+ private readonly object _gate = new();
+
+ public SerialDevice(DeviceContext context, SerialDeviceOptions? options = null)
+ : base(context)
+ {
+ Options = options ?? new SerialDeviceOptions();
+ Options.InitialConfig.Validate();
+ Config = Options.InitialConfig;
+ _rx = new ByteRingBuffer(Options.RxQueueBytes);
+ _tx = new ByteRingBuffer(Options.TxQueueBytes);
+
+ DefaultQueue
+ .OnDeviceControl(HandleDeviceControlAsync)
+ .OnRead(HandleReadAsync)
+ .OnWrite(HandleWriteAsync);
+ }
+
+ public SerialDeviceOptions Options { get; }
+ public SerialLineConfig Config { get; private set; }
+ public ByteRingBuffer RxQueue => _rx;
+ public ByteRingBuffer TxQueue => _tx;
+
+ public bool Cts { get; private set; } = true;
+ public bool Dsr { get; private set; } = true;
+ public bool BreakActive { get; private set; }
+
+ public long FramingErrors { get; private set; }
+
+ /// Set by to receive every transmitted byte.
+ internal TxSink? TxSubscription { get; set; }
+
+ public override Task OnPrepareHardwareAsync(CancellationToken cancellationToken)
+ {
+ Context.Log.Info("serial port ready: {0} baud / {1}{2}{3} / loopback={4}",
+ Config.BaudRate, Config.DataBits, Config.Parity, Config.StopBits, Options.Loopback);
+ return Task.CompletedTask;
+ }
+
+ /// Applies and validates a new line configuration.
+ public void ApplyConfig(SerialLineConfig config)
+ {
+ config.Validate();
+ Config = config;
+ Context.Log.Info("serial config applied: {0}", config);
+ }
+
+ /// Injects bytes directly into the RX queue (simulates a remote peer).
+ public int InjectReceive(ReadOnlySpan data) => _rx.Write(data);
+
+ ///
+ /// Transmits bytes immediately: into the TX queue, back on RX when loopback
+ /// is enabled, and to the paired device when cross-connected.
+ ///
+ public int Transmit(ReadOnlySpan data)
+ {
+ var accepted = _tx.Write(data);
+ if (Options.Loopback)
+ {
+ _rx.Write(data.Slice(0, accepted));
+ }
+ TxSubscription?.Invoke(data.Slice(0, accepted));
+ return accepted;
+ }
+
+ /// Simulates a framing error on the next received byte(s).
+ public void InjectFramingError() { lock (_gate) { FramingErrors++; } }
+
+ /// Simulates a break condition (line held at space).
+ public void AssertBreak(bool active)
+ {
+ BreakActive = active;
+ if (active)
+ {
+ InjectFramingError();
+ }
+ }
+
+ private Task HandleReadAsync(IoRequest request, CancellationToken ct)
+ {
+ var read = _rx.Read(request.OutputBuffer.Span);
+ request.Complete(NtStatus.Success, read);
+ return Task.CompletedTask;
+ }
+
+ private Task HandleWriteAsync(IoRequest request, CancellationToken ct)
+ {
+ var accepted = _tx.Write(request.InputBuffer.Span);
+ if (Options.Loopback)
+ {
+ // Loopback plug: whatever we transmitted comes back on RX.
+ _rx.Write(request.InputBuffer.Span.Slice(0, accepted));
+ }
+ TxSubscription?.Invoke(request.InputBuffer.Span.Slice(0, accepted));
+ request.Complete(NtStatus.Success, accepted);
+ return Task.CompletedTask;
+ }
+
+ ///
+ /// Handles the contract. Subclasses override
+ /// this to add device-specific IOCTLs and fall back to base for the rest.
+ ///
+ protected virtual Task HandleDeviceControlAsync(IoRequest request, CancellationToken ct)
+ {
+ var code = request.IoControlCode;
+ if (code == SerialIoctlCodes.GetLineConfig)
+ {
+ if (request.OutputBuffer.Length < SerialLineConfig.WireSize)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ Config.WriteTo(request.OutputBuffer.Span);
+ request.Complete(NtStatus.Success, SerialLineConfig.WireSize);
+ }
+ }
+ else if (code == SerialIoctlCodes.SetLineConfig)
+ {
+ if (request.InputBuffer.Length < SerialLineConfig.WireSize)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ ApplyConfig(SerialLineConfig.ReadFrom(request.InputBuffer.Span));
+ request.Complete(NtStatus.Success, SerialLineConfig.WireSize);
+ }
+ }
+ else if (code == SerialIoctlCodes.Transmit)
+ {
+ if (request.InputBuffer.Length == 0)
+ {
+ request.Fail(NtStatus.InvalidParameter);
+ }
+ else
+ {
+ Transmit(request.InputBuffer.Span);
+ request.Complete(NtStatus.Success, request.InputBuffer.Length);
+ }
+ }
+ else if (code == SerialIoctlCodes.Purge)
+ {
+ if (request.InputBuffer.Length < sizeof(uint))
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ var flags = WireFormat.ReadUInt32(request.InputBuffer.Span, 0);
+ if ((flags & 0x1) != 0)
+ {
+ _rx.Clear();
+ }
+ if ((flags & 0x2) != 0)
+ {
+ _tx.Clear();
+ }
+ request.Complete(NtStatus.Success, sizeof(uint));
+ }
+ }
+ else if (code == SerialIoctlCodes.GetStatus)
+ {
+ var needed = 2 * sizeof(ulong) + sizeof(uint) + 4 * sizeof(byte);
+ if (request.OutputBuffer.Length < needed)
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ var span = request.OutputBuffer.Span;
+ long framing;
+ lock (_gate)
+ {
+ framing = FramingErrors;
+ }
+ WireFormat.WriteUInt64(span, 0, (ulong)_tx.TotalBytesWritten);
+ WireFormat.WriteUInt64(span, 8, (ulong)_rx.TotalBytesRead);
+ WireFormat.WriteUInt32(span, 16, (uint)framing);
+ span[20] = Cts ? (byte)1 : (byte)0;
+ span[21] = Dsr ? (byte)1 : (byte)0;
+ span[22] = BreakActive ? (byte)1 : (byte)0;
+ span[23] = Options.Loopback ? (byte)1 : (byte)0;
+ request.Complete(NtStatus.Success, needed);
+ }
+ }
+ else if (code == SerialIoctlCodes.GetRxCount)
+ {
+ if (request.OutputBuffer.Length < sizeof(uint))
+ {
+ request.Fail(NtStatus.BufferTooSmall);
+ }
+ else
+ {
+ WireFormat.WriteUInt32(request.OutputBuffer.Span, 0, (uint)_rx.Count);
+ request.Complete(NtStatus.Success, sizeof(uint));
+ }
+ }
+ else
+ {
+ request.Fail(NtStatus.InvalidDeviceRequest);
+ }
+ return Task.CompletedTask;
+ }
+}
+
+///
+/// Cross-connects two s like a null-modem cable:
+/// A's transmit goes to B's receive and vice versa. Both devices must be
+/// created with = false.
+///
+public sealed class SerialLoopbackPair
+{
+ public SerialLoopbackPair(SerialDevice a, SerialDevice b)
+ {
+ if (a.Options.Loopback || b.Options.Loopback)
+ {
+ throw new InvalidOperationException("Loopback must be disabled on both devices to form a pair.");
+ }
+ A = a;
+ B = b;
+ a.TxSubscription = data => b.RxQueue.Write(data);
+ b.TxSubscription = data => a.RxQueue.Write(data);
+ }
+
+ public SerialDevice A { get; }
+ public SerialDevice B { get; }
+}
diff --git a/src/WindowsDriver.Sdk/Serial/SerialModel.cs b/src/WindowsDriver.Sdk/Serial/SerialModel.cs
new file mode 100644
index 0000000..e521355
--- /dev/null
+++ b/src/WindowsDriver.Sdk/Serial/SerialModel.cs
@@ -0,0 +1,96 @@
+namespace WindowsDriver.Sdk.Serial;
+
+/// Parity modes (matches SERIAL parity settings).
+public enum SerialParity : byte
+{
+ None = 0,
+ Odd = 1,
+ Even = 2,
+ Mark = 3,
+ Space = 4,
+}
+
+/// Stop bits. OnePointFive is only valid with 5 data bits (classic 8250 rule).
+public enum SerialStopBits : byte
+{
+ One = 0,
+ OnePointFive = 1,
+ Two = 2,
+}
+
+/// Flow control modes.
+public enum SerialFlowControl : byte
+{
+ None = 0,
+ XonXoff = 1,
+ RtsCts = 2,
+}
+
+///
+/// The serial line configuration. Validation follows the classic UART rules:
+/// 5–8 data bits, baud 50..1,000,000, and 1.5 stop bits only with 5 data bits.
+///
+public sealed record SerialLineConfig(
+ uint BaudRate = 115_200,
+ byte DataBits = 8,
+ SerialParity Parity = SerialParity.None,
+ SerialStopBits StopBits = SerialStopBits.One,
+ SerialFlowControl FlowControl = SerialFlowControl.None)
+{
+ public const uint MinBaudRate = 50;
+ public const uint MaxBaudRate = 1_000_000;
+
+ /// Wired size of the config struct in IOCTL payloads.
+ public const int WireSize = 8;
+
+ /// Writes this config as (u32 baud, u8 dataBits, u8 parity, u8 stopBits, u8 flow, pad).
+ public void WriteTo(Span dest)
+ {
+ WireFormat.ThrowIfTooSmall(dest.Length, 0, WireSize);
+ WireFormat.WriteUInt32(dest, 0, BaudRate);
+ dest[4] = DataBits;
+ dest[5] = (byte)Parity;
+ dest[6] = (byte)StopBits;
+ dest[7] = (byte)FlowControl;
+ }
+
+ public static SerialLineConfig ReadFrom(ReadOnlySpan src)
+ {
+ WireFormat.ThrowIfTooSmall(src.Length, 0, WireSize);
+ return new SerialLineConfig(
+ WireFormat.ReadUInt32(src, 0),
+ src[4],
+ (SerialParity)src[5],
+ (SerialStopBits)src[6],
+ (SerialFlowControl)src[7]);
+ }
+
+ /// Throws (InvalidParameter) when the combination is invalid.
+ public void Validate()
+ {
+ if (BaudRate < MinBaudRate || BaudRate > MaxBaudRate)
+ {
+ throw new DriverException(NtStatus.InvalidParameter, $"Baud rate {BaudRate} is outside [{MinBaudRate}, {MaxBaudRate}].");
+ }
+ if (DataBits is < 5 or > 8)
+ {
+ throw new DriverException(NtStatus.InvalidParameter, $"Data bits must be 5..8, got {DataBits}.");
+ }
+ if (StopBits == SerialStopBits.OnePointFive && DataBits != 5)
+ {
+ throw new DriverException(NtStatus.InvalidParameter, "1.5 stop bits are only valid with 5 data bits.");
+ }
+ if (StopBits == SerialStopBits.Two && DataBits == 5)
+ {
+ throw new DriverException(NtStatus.InvalidParameter, "5 data bits cannot be combined with 2 stop bits.");
+ }
+ if (!Enum.IsDefined(Parity))
+ {
+ throw new DriverException(NtStatus.InvalidParameter, $"Unknown parity value {(byte)Parity}.");
+ }
+ if (!Enum.IsDefined(FlowControl))
+ {
+ throw new DriverException(NtStatus.InvalidParameter, $"Unknown flow control value {(byte)FlowControl}.");
+ }
+ }
+}
diff --git a/src/WindowsDriver.Sdk/WindowsDriver.Sdk.csproj b/src/WindowsDriver.Sdk/WindowsDriver.Sdk.csproj
new file mode 100644
index 0000000..6aa52f0
--- /dev/null
+++ b/src/WindowsDriver.Sdk/WindowsDriver.Sdk.csproj
@@ -0,0 +1,14 @@
+
+
+
+ Core runtime of the Windows Driver SDK for .NET: driver/device lifecycle, IO queues, IOCTL handling, NTSTATUS, logging, plus the Audio, HID, Sensor and Serial device-class modules. Driver logic is written in C# and hosted either by the bundled test host, a UMDF shim, or the KMDF control plane.
+ WindowsDriver.Sdk
+ windows;driver;umdf;kmdf;wdm;audio;hid;sensor;serial;ioctl;wdf
+ LICENSE
+
+
+
+
+
+
+
diff --git a/src/WindowsDriver.Templates/WindowsDriver.Templates.csproj b/src/WindowsDriver.Templates/WindowsDriver.Templates.csproj
new file mode 100644
index 0000000..c9b6bd6
--- /dev/null
+++ b/src/WindowsDriver.Templates/WindowsDriver.Templates.csproj
@@ -0,0 +1,19 @@
+
+
+
+ dotnet new templates for the Windows Driver SDK: a UMDF-style driver project, an xUnit test project wired to the test host, and a complete driver solution.
+ WindowsDriver.Templates
+ windows;driver;templates;dotnet-new;umdf
+ false
+
+ false
+ $(NoWarn);NU5128;NU5119
+ LICENSE
+
+
+
+
+
+
+
+
diff --git a/src/WindowsDriver.Templates/templates/driver-solution/.template.config/template.json b/src/WindowsDriver.Templates/templates/driver-solution/.template.config/template.json
new file mode 100644
index 0000000..fb3ca96
--- /dev/null
+++ b/src/WindowsDriver.Templates/templates/driver-solution/.template.config/template.json
@@ -0,0 +1,35 @@
+{
+ "$schema": "https://json.schemastore.org/template",
+ "author": "Windows Driver SDK contributors",
+ "classifications": ["Windows", "Driver", "UMDF", "Solution"],
+ "description": "A complete driver solution skeleton: driver project, test project, InfGen manifest and build script.",
+ "name": "Windows Driver Solution (Windows Driver SDK)",
+ "identity": "WindowsDriver.Sdk.Driver.Solution",
+ "groupIdentity": "WindowsDriver.Sdk.Driver.Solution",
+ "shortName": "driver-solution",
+ "sourceName": "DriverTemplate",
+ "preferNameDirectory": true,
+ "tags": {
+ "language": "C#",
+ "type": "item"
+ },
+ "symbols": {
+ "sdkVersion": {
+ "type": "parameter",
+ "datatype": "string",
+ "defaultValue": "0.1.0-preview.1",
+ "replaces": "SDK_VERSION"
+ }
+ },
+ "sources": [
+ {
+ "modifiers": [
+ {
+ "exclude": [
+ "**/*.sln"
+ ]
+ }
+ ]
+ }
+ ]
+}
diff --git a/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate.Tests/DriverTemplate.Tests.csproj b/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate.Tests/DriverTemplate.Tests.csproj
new file mode 100644
index 0000000..8c4c415
--- /dev/null
+++ b/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate.Tests/DriverTemplate.Tests.csproj
@@ -0,0 +1,26 @@
+
+
+
+ net8.0
+ 12.0
+ enable
+ enable
+ DriverTemplate.Tests
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate.Tests/DriverTemplateTests.cs b/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate.Tests/DriverTemplateTests.cs
new file mode 100644
index 0000000..ec6480f
--- /dev/null
+++ b/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate.Tests/DriverTemplateTests.cs
@@ -0,0 +1,23 @@
+using WindowsDriver.Sdk;
+using WindowsDriver.Testing;
+using Xunit;
+
+namespace DriverTemplate.Tests;
+
+public class DriverTemplateTests
+{
+ [Fact]
+ public async Task Device_boots_and_rejects_unknown_ioctls()
+ {
+ var host = TestDriverHost.Builder().UseFakeTime().Build();
+ await host.StartAsync("DriverTemplateService");
+ var device = await host.AddDeviceAsync("ROOT\\DRIVERTEMPLATE\\0000", "Root\\DriverTemplate");
+
+ Assert.True(device.Device.IsD0, "device should be powered after AddDevice");
+
+ var unknown = await device.SendIoctlAsync(0xDEAD);
+ Check.Status(unknown, NtStatus.InvalidDeviceRequest);
+
+ await host.ShutdownAsync();
+ }
+}
diff --git a/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate.manifest.json b/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate.manifest.json
new file mode 100644
index 0000000..1b2a141
--- /dev/null
+++ b/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate.manifest.json
@@ -0,0 +1,21 @@
+{
+ // InfGen manifest — generate the INF with:
+ // dotnet tool install WindowsDriver.InfGen
+ // infgen generate --manifest DriverTemplate.manifest.json
+ "name": "DriverTemplate",
+ "provider": "Your Company",
+ "version": "0.1.0",
+ "class": "Unknown",
+ "classGuid": "{4d36e97b-e325-11ce-bfc1-08002be10318}",
+ "framework": "umdf",
+ "serviceName": "DriverTemplateService",
+ "files": [
+ { "source": "DriverTemplate.dll" }
+ ],
+ "models": [
+ {
+ "name": "DriverTemplate Device",
+ "hardwareIds": ["Root\\DriverTemplate"]
+ }
+ ]
+}
diff --git a/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate/DriverTemplate.cs b/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate/DriverTemplate.cs
new file mode 100644
index 0000000..1866abe
--- /dev/null
+++ b/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate/DriverTemplate.cs
@@ -0,0 +1,58 @@
+using WindowsDriver.Sdk;
+
+namespace DriverTemplate;
+
+///
+/// Driver entry point. The host (test host during development, the UMDF shim in
+/// production) calls OnDriverEntryAsync once, then OnDeviceAddAsync per device.
+///
+public sealed class DriverTemplateDriver : DriverBase
+{
+ public override Task OnDriverEntryAsync(DriverContext context, CancellationToken cancellationToken)
+ {
+ context.Log.Info("DriverTemplate driver entering (service '{0}')", context.DriverServiceName);
+ return Task.CompletedTask;
+ }
+
+ public override Task OnDeviceAddAsync(DeviceAddContext addContext, DeviceContext deviceContext, CancellationToken cancellationToken)
+ {
+ deviceContext.Log.Info("device add: {0}", addContext.DeviceInstanceId);
+ deviceContext.Properties.Set(KnownDeviceProperties.FriendlyName, "DriverTemplate Device");
+
+ var device = new DriverTemplateDevice(deviceContext);
+ // Applications discover the device through its interface GUID.
+ deviceContext.CreateDeviceInterface(new Guid("00000000-0000-0000-0000-000000000000"));
+ return Task.FromResult(device);
+ }
+}
+
+///
+/// The device instance. Register IOCTL handlers on the default queue and
+/// override lifecycle callbacks (PrepareHardware/D0Entry/…) as needed.
+///
+public sealed class DriverTemplateDevice : DeviceBase
+{
+ public DriverTemplateDevice(DeviceContext context) : base(context)
+ {
+ DefaultQueue.OnDeviceControl(HandleDeviceControlAsync);
+ }
+
+ public override Task OnPrepareHardwareAsync(CancellationToken cancellationToken)
+ {
+ Context.Log.Info("hardware prepared");
+ return Task.CompletedTask;
+ }
+
+ private Task HandleDeviceControlAsync(IoRequest request, CancellationToken ct)
+ {
+ switch (request.IoControlCode)
+ {
+ // Vendor IOCTL codes start at 0x800:
+ // var code = WinIoctl.VendorControlCode(0x800, WinIoctl.FileAccessRead);
+ default:
+ request.Fail(NtStatus.InvalidDeviceRequest);
+ break;
+ }
+ return Task.CompletedTask;
+ }
+}
diff --git a/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate/DriverTemplate.csproj b/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate/DriverTemplate.csproj
new file mode 100644
index 0000000..84b5520
--- /dev/null
+++ b/src/WindowsDriver.Templates/templates/driver-solution/DriverTemplate/DriverTemplate.csproj
@@ -0,0 +1,17 @@
+
+
+
+ net8.0
+ 12.0
+ enable
+ enable
+ DriverTemplate
+ DriverTemplate — a Windows Driver SDK driver.
+
+
+
+
+
+
+
+
diff --git a/src/WindowsDriver.Templates/templates/driver-tests/.template.config/template.json b/src/WindowsDriver.Templates/templates/driver-tests/.template.config/template.json
new file mode 100644
index 0000000..33cebea
--- /dev/null
+++ b/src/WindowsDriver.Templates/templates/driver-tests/.template.config/template.json
@@ -0,0 +1,24 @@
+{
+ "$schema": "https://json.schemastore.org/template",
+ "author": "Windows Driver SDK contributors",
+ "classifications": ["Windows", "Driver", "Testing"],
+ "description": "An xUnit test project wired to the Windows Driver SDK test host — runs driver logic without Windows or a device.",
+ "name": "Windows Driver Tests (Windows Driver SDK)",
+ "identity": "WindowsDriver.Sdk.Driver.Tests",
+ "groupIdentity": "WindowsDriver.Sdk.Driver.Tests",
+ "shortName": "driver-tests",
+ "sourceName": "DriverTemplate.Tests",
+ "preferNameDirectory": true,
+ "tags": {
+ "language": "C#",
+ "type": "project"
+ },
+ "symbols": {
+ "sdkVersion": {
+ "type": "parameter",
+ "datatype": "string",
+ "defaultValue": "0.1.0-preview.1",
+ "replaces": "SDK_VERSION"
+ }
+ }
+}
diff --git a/src/WindowsDriver.Templates/templates/driver-tests/DriverTemplate.Tests.csproj b/src/WindowsDriver.Templates/templates/driver-tests/DriverTemplate.Tests.csproj
new file mode 100644
index 0000000..dd4ace6
--- /dev/null
+++ b/src/WindowsDriver.Templates/templates/driver-tests/DriverTemplate.Tests.csproj
@@ -0,0 +1,23 @@
+
+
+
+ net8.0
+ 12.0
+ enable
+ enable
+ DriverTemplate.Tests
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/WindowsDriver.Templates/templates/driver-tests/DriverTemplateTests.cs b/src/WindowsDriver.Templates/templates/driver-tests/DriverTemplateTests.cs
new file mode 100644
index 0000000..ec6480f
--- /dev/null
+++ b/src/WindowsDriver.Templates/templates/driver-tests/DriverTemplateTests.cs
@@ -0,0 +1,23 @@
+using WindowsDriver.Sdk;
+using WindowsDriver.Testing;
+using Xunit;
+
+namespace DriverTemplate.Tests;
+
+public class DriverTemplateTests
+{
+ [Fact]
+ public async Task Device_boots_and_rejects_unknown_ioctls()
+ {
+ var host = TestDriverHost.Builder().UseFakeTime().Build();
+ await host.StartAsync("DriverTemplateService");
+ var device = await host.AddDeviceAsync("ROOT\\DRIVERTEMPLATE\\0000", "Root\\DriverTemplate");
+
+ Assert.True(device.Device.IsD0, "device should be powered after AddDevice");
+
+ var unknown = await device.SendIoctlAsync(0xDEAD);
+ Check.Status(unknown, NtStatus.InvalidDeviceRequest);
+
+ await host.ShutdownAsync();
+ }
+}
diff --git a/src/WindowsDriver.Templates/templates/driver-umdf/.template.config/template.json b/src/WindowsDriver.Templates/templates/driver-umdf/.template.config/template.json
new file mode 100644
index 0000000..d51eb07
--- /dev/null
+++ b/src/WindowsDriver.Templates/templates/driver-umdf/.template.config/template.json
@@ -0,0 +1,24 @@
+{
+ "$schema": "https://json.schemastore.org/template",
+ "author": "Windows Driver SDK contributors",
+ "classifications": ["Windows", "Driver", "UMDF"],
+ "description": "A driver project for the Windows Driver SDK: an IDriver entry point, a DeviceBase subclass with IOCTL handling, and an InfGen manifest.",
+ "name": "Windows Driver (Windows Driver SDK)",
+ "identity": "WindowsDriver.Sdk.Driver.Project",
+ "groupIdentity": "WindowsDriver.Sdk.Driver.Umdf",
+ "shortName": "driver-umdf",
+ "sourceName": "DriverTemplate",
+ "preferNameDirectory": true,
+ "tags": {
+ "language": "C#",
+ "type": "project"
+ },
+ "symbols": {
+ "sdkVersion": {
+ "type": "parameter",
+ "datatype": "string",
+ "defaultValue": "0.1.0-preview.1",
+ "replaces": "SDK_VERSION"
+ }
+ }
+}
diff --git a/src/WindowsDriver.Templates/templates/driver-umdf/DriverTemplate.cs b/src/WindowsDriver.Templates/templates/driver-umdf/DriverTemplate.cs
new file mode 100644
index 0000000..1866abe
--- /dev/null
+++ b/src/WindowsDriver.Templates/templates/driver-umdf/DriverTemplate.cs
@@ -0,0 +1,58 @@
+using WindowsDriver.Sdk;
+
+namespace DriverTemplate;
+
+///
+/// Driver entry point. The host (test host during development, the UMDF shim in
+/// production) calls OnDriverEntryAsync once, then OnDeviceAddAsync per device.
+///
+public sealed class DriverTemplateDriver : DriverBase
+{
+ public override Task OnDriverEntryAsync(DriverContext context, CancellationToken cancellationToken)
+ {
+ context.Log.Info("DriverTemplate driver entering (service '{0}')", context.DriverServiceName);
+ return Task.CompletedTask;
+ }
+
+ public override Task OnDeviceAddAsync(DeviceAddContext addContext, DeviceContext deviceContext, CancellationToken cancellationToken)
+ {
+ deviceContext.Log.Info("device add: {0}", addContext.DeviceInstanceId);
+ deviceContext.Properties.Set(KnownDeviceProperties.FriendlyName, "DriverTemplate Device");
+
+ var device = new DriverTemplateDevice(deviceContext);
+ // Applications discover the device through its interface GUID.
+ deviceContext.CreateDeviceInterface(new Guid("00000000-0000-0000-0000-000000000000"));
+ return Task.FromResult(device);
+ }
+}
+
+///
+/// The device instance. Register IOCTL handlers on the default queue and
+/// override lifecycle callbacks (PrepareHardware/D0Entry/…) as needed.
+///
+public sealed class DriverTemplateDevice : DeviceBase
+{
+ public DriverTemplateDevice(DeviceContext context) : base(context)
+ {
+ DefaultQueue.OnDeviceControl(HandleDeviceControlAsync);
+ }
+
+ public override Task OnPrepareHardwareAsync(CancellationToken cancellationToken)
+ {
+ Context.Log.Info("hardware prepared");
+ return Task.CompletedTask;
+ }
+
+ private Task HandleDeviceControlAsync(IoRequest request, CancellationToken ct)
+ {
+ switch (request.IoControlCode)
+ {
+ // Vendor IOCTL codes start at 0x800:
+ // var code = WinIoctl.VendorControlCode(0x800, WinIoctl.FileAccessRead);
+ default:
+ request.Fail(NtStatus.InvalidDeviceRequest);
+ break;
+ }
+ return Task.CompletedTask;
+ }
+}
diff --git a/src/WindowsDriver.Templates/templates/driver-umdf/DriverTemplate.csproj b/src/WindowsDriver.Templates/templates/driver-umdf/DriverTemplate.csproj
new file mode 100644
index 0000000..84b5520
--- /dev/null
+++ b/src/WindowsDriver.Templates/templates/driver-umdf/DriverTemplate.csproj
@@ -0,0 +1,17 @@
+
+
+
+ net8.0
+ 12.0
+ enable
+ enable
+ DriverTemplate
+ DriverTemplate — a Windows Driver SDK driver.
+
+
+
+
+
+
+
+
diff --git a/src/WindowsDriver.Testing/CapturedLog.cs b/src/WindowsDriver.Testing/CapturedLog.cs
new file mode 100644
index 0000000..c1aff1a
--- /dev/null
+++ b/src/WindowsDriver.Testing/CapturedLog.cs
@@ -0,0 +1,113 @@
+using WindowsDriver.Sdk;
+
+namespace WindowsDriver.Testing;
+
+/// An in-memory registry with seed values (wraps the core MemoryRegistry).
+public sealed class FakeRegistry : MemoryRegistry
+{
+ public FakeRegistry(params (string Key, object Value)[] seed)
+ {
+ foreach (var (key, value) in seed)
+ {
+ switch (value)
+ {
+ case string s: WriteString(key, s); break;
+ case uint u: WriteDword(key, u); break;
+ case int i when i >= 0: WriteDword(key, (uint)i); break;
+ case bool b: WriteDword(key, b ? 1u : 0u); break;
+ default:
+ throw new ArgumentException($"Unsupported seed value type {value.GetType().Name} for '{key}'.");
+ }
+ }
+ }
+}
+
+/// Records every log entry for assertions.
+public sealed class CapturedLog(DriverLogLevel minimum = DriverLogLevel.Trace) : IDriverLog
+{
+ private readonly object _gate = new();
+ private readonly List<(DriverLogLevel Level, string Message, DateTimeOffset At)> _entries = [];
+
+ public bool IsEnabled(DriverLogLevel level) => level >= minimum;
+
+ public void Log(DriverLogLevel level, string message)
+ {
+ lock (_gate)
+ {
+ _entries.Add((level, message, DateTimeOffset.UtcNow));
+ }
+ }
+
+ public IReadOnlyList Messages
+ {
+ get { lock (_gate) { return _entries.Select(e => e.Message).ToArray(); } }
+ }
+
+ public IReadOnlyList<(DriverLogLevel Level, string Message, DateTimeOffset At)> Entries
+ {
+ get { lock (_gate) { return _entries.ToArray(); } }
+ }
+
+ public bool Contains(string substring)
+ {
+ lock (_gate)
+ {
+ return _entries.Any(e => e.Message.Contains(substring, StringComparison.OrdinalIgnoreCase));
+ }
+ }
+
+ public bool ContainsError() => Entries.Any(e => e.Level == DriverLogLevel.Error);
+
+ public void Clear()
+ {
+ lock (_gate)
+ {
+ _entries.Clear();
+ }
+ }
+}
+
+/// Framework-agnostic assertion helpers for driver tests.
+public static class Check
+{
+ /// Throws with a detailed message when the result status differs.
+ public static void Status(IoResult result, NtStatus expected, string? because = null)
+ {
+ if (result.Status != expected)
+ {
+ throw new TestCheckException(
+ $"{because}: expected status {expected.ToHexString()} but got {result.Status.ToHexString()} " +
+ $"({result.BytesTransferred} bytes).");
+ }
+ }
+
+ public static void Success(IoResult result, string? because = null) => Status(result, NtStatus.Success, because);
+
+ public static void Bytes(IoResult result, int expectedBytes, string? because = null)
+ {
+ if (result.BytesTransferred != expectedBytes)
+ {
+ throw new TestCheckException($"{because}: expected {expectedBytes} bytes, got {result.BytesTransferred}.");
+ }
+ }
+}
+
+/// Thrown by helpers — any test framework treats it as a failure.
+public sealed class TestCheckException(string message) : Exception(message);
+
+/// Small async polling helper for deterministic waits (real-time, used only where fake-time callbacks cross threads).
+public static class TestSync
+{
+ public static async Task WaitUntilAsync(Func condition, TimeSpan? timeout = null, string? what = null)
+ {
+ var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromSeconds(5));
+ while (!condition())
+ {
+ if (DateTime.UtcNow > deadline)
+ {
+ throw new TimeoutException($"Condition not met within {(timeout ?? TimeSpan.FromSeconds(5)).TotalSeconds}s: {what ?? "unnamed"}.");
+ }
+ await Task.Delay(10);
+ }
+ }
+}
diff --git a/src/WindowsDriver.Testing/FakeTimeProvider.cs b/src/WindowsDriver.Testing/FakeTimeProvider.cs
new file mode 100644
index 0000000..92e1693
--- /dev/null
+++ b/src/WindowsDriver.Testing/FakeTimeProvider.cs
@@ -0,0 +1,155 @@
+namespace WindowsDriver.Testing;
+
+///
+/// A controllable for deterministic tests.
+/// Timers created through it only fire when /
+/// crosses their due time — callbacks run synchronously
+/// inside the advance call, so tests never wait on real wall-clock time.
+///
+public sealed class FakeTimeProvider(DateTimeOffset? start = null) : TimeProvider
+{
+ private readonly object _gate = new();
+ private readonly List _timers = [];
+ private DateTimeOffset _utcNow = start ?? new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
+ private bool _advancing;
+
+ public override DateTimeOffset GetUtcNow() { lock (_gate) { return _utcNow; } }
+
+ /// Number of timers currently scheduled (periodic timers count once).
+ public int ActiveTimers { get { lock (_gate) { return _timers.Count; } } }
+
+ /// Advances time; fires all timers that become due, in due-time order.
+ public void Advance(TimeSpan delta) => AdvanceTo(_utcNow + delta);
+
+ /// Moves the clock to an absolute timestamp, firing due timers along the way.
+ public void AdvanceTo(DateTimeOffset target)
+ {
+ lock (_gate)
+ {
+ if (_advancing)
+ {
+ throw new InvalidOperationException("AdvanceTo called re-entrantly from a timer callback.");
+ }
+ if (target < _utcNow)
+ {
+ throw new ArgumentOutOfRangeException(nameof(target), "Cannot advance time backwards.");
+ }
+ _advancing = true;
+ }
+
+ try
+ {
+ // Fire timers until none is due before the target.
+ while (true)
+ {
+ FakeTimer? due;
+ DateTimeOffset dueTime;
+ lock (_gate)
+ {
+ due = _timers
+ .Where(t => t.NextDue.HasValue && t.NextDue.Value <= target)
+ .OrderBy(t => t.NextDue!.Value)
+ .FirstOrDefault();
+ if (due is null)
+ {
+ _utcNow = target;
+ return;
+ }
+ dueTime = due.NextDue!.Value;
+ _utcNow = dueTime;
+ }
+ due.Fire(); // callback runs synchronously; may re-arm itself
+ }
+ }
+ finally
+ {
+ lock (_gate)
+ {
+ _advancing = false;
+ }
+ }
+ }
+
+ public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
+ {
+ var timer = new FakeTimer(this, callback, state, period);
+ lock (_gate)
+ {
+ if (dueTime != Timeout.InfiniteTimeSpan)
+ {
+ timer.NextDue = _utcNow + dueTime;
+ _timers.Add(timer);
+ }
+ }
+ return timer;
+ }
+
+ private void RemoveTimer(FakeTimer timer)
+ {
+ lock (_gate)
+ {
+ _timers.Remove(timer);
+ }
+ }
+
+ private sealed class FakeTimer(FakeTimeProvider owner, TimerCallback callback, object? state, TimeSpan period) : ITimer
+ {
+ private bool _disposed;
+
+ public DateTimeOffset? NextDue { get; set; }
+
+ public bool Change(TimeSpan dueTime, TimeSpan period)
+ {
+ lock (owner._gate)
+ {
+ if (_disposed)
+ {
+ return false;
+ }
+ if (dueTime == Timeout.InfiniteTimeSpan)
+ {
+ NextDue = null;
+ return true;
+ }
+ NextDue = owner._utcNow + dueTime;
+ return true;
+ }
+ }
+
+ public void Fire()
+ {
+ if (_disposed)
+ {
+ return;
+ }
+ callback(state);
+ lock (owner._gate)
+ {
+ if (period == Timeout.InfiniteTimeSpan || period <= TimeSpan.Zero)
+ {
+ NextDue = null;
+ owner._timers.Remove(this);
+ }
+ else
+ {
+ NextDue = owner._utcNow + period;
+ }
+ }
+ }
+
+ public void Dispose()
+ {
+ lock (owner._gate)
+ {
+ _disposed = true;
+ owner._timers.Remove(this);
+ }
+ }
+
+ public ValueTask DisposeAsync()
+ {
+ Dispose();
+ return ValueTask.CompletedTask;
+ }
+ }
+}
diff --git a/src/WindowsDriver.Testing/TestDriverHost.cs b/src/WindowsDriver.Testing/TestDriverHost.cs
new file mode 100644
index 0000000..b6aa683
--- /dev/null
+++ b/src/WindowsDriver.Testing/TestDriverHost.cs
@@ -0,0 +1,161 @@
+using WindowsDriver.Sdk;
+
+namespace WindowsDriver.Testing;
+
+///
+/// A complete in-memory environment for running driver code without Windows:
+/// fake clock, captured log, fake registry and a virtual device bus. The same
+/// orchestration used by the production shims drives
+/// lifecycle, so verified behavior transfers to deployment.
+///
+public sealed class TestDriverHost
+{
+ internal TestDriverHost(DriverHost host, CapturedLog log, FakeRegistry registry, FakeTimeProvider? time)
+ {
+ Host = host;
+ Log = log;
+ Registry = registry;
+ FakeTime = time;
+ }
+
+ public DriverHost Host { get; }
+ public CapturedLog Log { get; }
+ public FakeRegistry Registry { get; }
+
+ /// The fake clock, when the builder was configured with one; null with real time.
+ public FakeTimeProvider? FakeTime { get; }
+
+ public IReadOnlyList Devices =>
+ Host.Devices.Select(d => new TestDevice(d)).ToArray();
+
+ public bool IsStarted => Host.IsStarted;
+
+ public Task StartAsync(string? serviceName = null, CancellationToken ct = default) where TDriver : IDriver, new()
+ => Host.StartAsync(typeof(TDriver), serviceName, ct);
+
+ public Task StartAsync(Type driverType, string? serviceName = null, CancellationToken ct = default)
+ => Host.StartAsync(driverType, serviceName, ct);
+
+ public Task AddDeviceAsync(DeviceAddContext addContext, CancellationToken ct = default)
+ => Host.AddDeviceAsync(addContext, ct).ContinueWith(t => new TestDevice(t.Result), ct);
+
+ /// Adds a device with just an instance id (hardware ids inferred).
+ public async Task AddDeviceAsync(string deviceInstanceId, params string[] hardwareIds)
+ {
+ var instance = await Host.AddDeviceAsync(new DeviceAddContext
+ {
+ DeviceInstanceId = deviceInstanceId,
+ HardwareIds = hardwareIds,
+ });
+ return new TestDevice(instance);
+ }
+
+ public Task ShutdownAsync(CancellationToken ct = default) => Host.ShutdownAsync(ct);
+
+ public static TestDriverHostBuilder Builder() => new();
+}
+
+/// Fluent configuration for .
+public sealed class TestDriverHostBuilder
+{
+ private CapturedLog? _log;
+ private FakeRegistry? _registry;
+ private FakeTimeProvider? _timeProvider;
+
+ /// Sets a fake clock starting at the given time.
+ public TestDriverHostBuilder UseFakeTime(DateTimeOffset? start = null)
+ {
+ _timeProvider = new FakeTimeProvider(start);
+ return this;
+ }
+
+ /// Uses real wall-clock time (rarely wanted in tests).
+ public TestDriverHostBuilder UseRealTime()
+ {
+ _timeProvider = null;
+ return this;
+ }
+
+ public TestDriverHostBuilder WithRegistry(FakeRegistry registry)
+ {
+ _registry = registry;
+ return this;
+ }
+
+ /// Sets the minimum level for the captured log (default Trace).
+ public TestDriverHostBuilder WithLogMinimum(DriverLogLevel minimum)
+ {
+ _log = new CapturedLog(minimum);
+ return this;
+ }
+
+ public TestDriverHost Build()
+ {
+ var log = _log ?? new CapturedLog();
+ var registry = _registry ?? new FakeRegistry();
+ var host = new DriverHost(log, registry, _timeProvider);
+ return new TestDriverHost(host, log, registry, _timeProvider);
+ }
+}
+
+///
+/// A device under test: wraps the and offers typed
+/// helpers for sending IOCTLs, reading and writing — as an application or the
+/// WDF queue would.
+///
+public sealed class TestDevice
+{
+ private int _nextRequestId = 1;
+
+ internal TestDevice(DeviceInstance instance) => Instance = instance;
+
+ public DeviceInstance Instance { get; }
+ public DeviceBase Device => Instance.Device;
+ public DeviceContext Context => Instance.Context;
+ public string DeviceInstanceId => Instance.DeviceInstanceId;
+ public IoQueue DefaultQueue => Instance.DefaultQueue;
+
+ /// Sends an IOCTL and awaits its completion. Output buffer defaults to 256 bytes.
+ public Task SendIoctlAsync(uint controlCode, byte[]? input = null, int outputSize = 256, TimeSpan? timeout = null)
+ {
+ var request = new IoRequest(
+ IoRequestKind.DeviceControl,
+ controlCode,
+ input ?? Array.Empty(),
+ new byte[outputSize],
+ (ulong)Interlocked.Increment(ref _nextRequestId));
+ return SubmitAsync(request, timeout);
+ }
+
+ /// Serializes the request payload (little-endian) and sends it as an IOCTL input.
+ public Task SendIoctlAsync(uint controlCode, TPayload payload, Func serializer, int outputSize = 256)
+ => SendIoctlAsync(controlCode, serializer(payload), outputSize);
+
+ public Task ReadAsync(int bytes = 256, TimeSpan? timeout = null)
+ {
+ var request = new IoRequest(IoRequestKind.Read, 0, Array.Empty(), new byte[bytes],
+ (ulong)Interlocked.Increment(ref _nextRequestId));
+ return SubmitAsync(request, timeout);
+ }
+
+ public Task WriteAsync(byte[] data, TimeSpan? timeout = null)
+ {
+ var request = new IoRequest(IoRequestKind.Write, 0, data, Array.Empty(),
+ (ulong)Interlocked.Increment(ref _nextRequestId));
+ return SubmitAsync(request, timeout);
+ }
+
+ private async Task SubmitAsync(IoRequest request, TimeSpan? timeout)
+ {
+ var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ request.Completed += completion.SetResult;
+ DefaultQueue.Submit(request);
+ var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(5);
+ var finished = await Task.WhenAny(completion.Task, Task.Delay(effectiveTimeout));
+ if (finished != completion.Task)
+ {
+ throw new TimeoutException($"Request {request.Kind} (ioctl 0x{request.IoControlCode:X8}) did not complete within {effectiveTimeout.TotalSeconds}s.");
+ }
+ return IoResult.From(request);
+ }
+}
diff --git a/src/WindowsDriver.Testing/WindowsDriver.Testing.csproj b/src/WindowsDriver.Testing/WindowsDriver.Testing.csproj
new file mode 100644
index 0000000..efbc9a6
--- /dev/null
+++ b/src/WindowsDriver.Testing/WindowsDriver.Testing.csproj
@@ -0,0 +1,18 @@
+
+
+
+ Test-time helpers for the Windows Driver SDK: an in-memory TestDriverHost that runs driver logic without Windows or a device, a controllable FakeTimeProvider, captured logging and a fake registry. Framework-agnostic (works with xUnit, NUnit, MSTest).
+ WindowsDriver.Testing
+ windows;driver;testing;unit-test;mock;umdf;kmdf
+ LICENSE
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/WindowsDriver.Sdk.Tests/InfGenTests.cs b/tests/WindowsDriver.Sdk.Tests/InfGenTests.cs
new file mode 100644
index 0000000..26e66ca
--- /dev/null
+++ b/tests/WindowsDriver.Sdk.Tests/InfGenTests.cs
@@ -0,0 +1,139 @@
+using WindowsDriver.InfGen;
+using Xunit;
+
+namespace WindowsDriver.Sdk.Tests;
+
+public class InfGenTests
+{
+ private static DriverManifest SampleManifest => new()
+ {
+ Name = "TestDevice",
+ Provider = "Contoso Devices",
+ Version = "1.2.3",
+ Class = "Media",
+ ClassGuid = "{4d36e96c-e325-11ce-bfc1-08002be10318}",
+ Framework = DriverFramework.Umdf,
+ Files = [new DriverFile("TestDevice.dll")],
+ Models = [new DriverModel { Name = "Contoso Virtual Test Device", HardwareIds = ["Root\\ContosoTest"] }],
+ };
+
+ [Fact]
+ public void Generator_produces_all_required_grammar_blocks()
+ {
+ var inf = new InfGenerator(new DateOnly(2026, 11, 18)).Generate(SampleManifest);
+
+ Assert.Contains("Signature=\"$WINDOWS NT$\"", inf);
+ Assert.Contains("Class=Media", inf);
+ Assert.Contains("ClassGuid={4d36e96c-e325-11ce-bfc1-08002be10318}", inf);
+ Assert.Contains("CatalogFile=TestDevice.cat", inf);
+ Assert.Contains("DriverVer=11/18/2026,1.2.3", inf);
+ Assert.Contains("PnpLockdown=1", inf);
+ Assert.Contains("[Manufacturer]", inf);
+ Assert.Contains("%Manufacturer%=Standard,NTamd64,NTarm64", inf);
+ Assert.Contains("[Standard.NTamd64]", inf);
+ Assert.Contains("%Model0%=Install.NTamd64,Root\\ContosoTest", inf);
+ Assert.Contains("[Install.NTamd64.Wdf]", inf);
+ Assert.Contains("UmdfService=TestDevice, TestDevice_Install", inf);
+ Assert.Contains("UmdfLibraryVersion=2.15.0", inf);
+ Assert.Contains("ServiceBinary=%12%\\TestDevice.dll", inf);
+ Assert.Contains("DriverFiles = 12", inf);
+ Assert.Contains("Model0 = \"Contoso Virtual Test Device\"", inf);
+ }
+
+ [Fact]
+ public void Generator_switches_to_kmdf_sections()
+ {
+ var manifest = SampleManifest with { Framework = DriverFramework.Kmdf };
+ var inf = new InfGenerator(new DateOnly(2026, 11, 18)).Generate(manifest);
+
+ Assert.Contains("KmdfService=TestDevice, TestDevice_Install", inf);
+ Assert.Contains("KmdfLibraryVersion=1.15", inf);
+ Assert.DoesNotContain("UmdfService", inf);
+ }
+
+ [Fact]
+ public void Generated_inf_passes_the_validator()
+ {
+ var inf = new InfGenerator(new DateOnly(2026, 11, 18)).Generate(SampleManifest);
+ var issues = new InfValidator().Validate(inf);
+ Assert.True(issues.Count == 0, string.Join("; ", issues.Select(i => $"[{i.Section}] {i.Message}")));
+ }
+
+ [Fact]
+ public void Validator_flags_broken_infs()
+ {
+ var broken = """
+ [Version]
+ Signature="$WINDOWS NT$"
+ ClassGuid={not-a-guid}
+ DriverVer=2026.11.18,1.0
+
+ [Strings]
+ Unused = "x"
+
+ [Standard.NTamd64]
+ %Model0%=Install,Root\Broken
+ """;
+ var issues = new InfValidator().Validate(broken);
+ Assert.Contains(issues, i => i.Section == "Version" && i.Message.Contains("Class"));
+ Assert.Contains(issues, i => i.Section == "Version" && i.Message.Contains("Provider"));
+ Assert.Contains(issues, i => i.Section == "Version" && i.Message.Contains("DriverVer"));
+ Assert.Contains(issues, i => i.Section == "Version" && i.Message.Contains("ClassGuid"));
+ Assert.Contains(issues, i => i.Section == "Manufacturer" && i.Message.Contains("missing"));
+ Assert.Contains(issues, i => i.Section == "Standard.NTamd64" && i.Message.Contains("missing install section"));
+ Assert.Contains(issues, i => i.Section == "Strings" && i.Message.Contains("Model0"));
+ }
+
+ [Fact]
+ public void Manifest_validation_catches_missing_fields()
+ {
+ // Missing required JSON properties are reported by the deserializer.
+ var problems = Assert.Throws(() => DriverManifest.FromJson("""
+ { "name": "", "classGuid": "nope", "framework": "umdf" }
+ """));
+ Assert.Contains("provider", problems.Message);
+ Assert.Contains("version", problems.Message);
+
+ // Present but invalid values are caught by manifest validation.
+ var invalid = Assert.Throws(() => DriverManifest.FromJson("""
+ {
+ "name": "X",
+ "provider": "P",
+ "version": "1",
+ "class": "Media",
+ "classGuid": "nope",
+ "framework": "umdf",
+ "files": [{ "source": "x.sys" }],
+ "models": [{ "name": "m", "hardwareIds": ["Root\\X"] }]
+ }
+ """));
+ Assert.Contains("classGuid", invalid.Message);
+ Assert.Contains("parseable GUID", invalid.Message);
+ }
+
+ [Fact]
+ public void Manifest_parses_camel_case_json()
+ {
+ var manifest = DriverManifest.FromJson("""
+ {
+ "name": "P",
+ "provider": "Contoso",
+ "version": "0.1",
+ "class": "Ports",
+ "classGuid": "{4d36e978-e325-11ce-bfc1-08002be10318}",
+ "framework": "kmdf",
+ "files": [{ "source": "p.sys" }],
+ "models": [{ "name": "P device", "hardwareIds": ["Root\\P"] }]
+ }
+ """);
+ Assert.Equal(DriverFramework.Kmdf, manifest.Framework);
+ Assert.Equal("Ports", manifest.Class);
+ }
+
+ [Fact]
+ public void Guid_normalization_adds_braces_and_lowercases()
+ {
+ Assert.Equal("{4d36e96c-e325-11ce-bfc1-08002be10318}",
+ InfGenerator.NormalizeGuid("4D36E96C-E325-11CE-BFC1-08002BE10318"));
+ }
+}
diff --git a/tests/WindowsDriver.Sdk.Tests/InteropTests.cs b/tests/WindowsDriver.Sdk.Tests/InteropTests.cs
new file mode 100644
index 0000000..9221a60
--- /dev/null
+++ b/tests/WindowsDriver.Sdk.Tests/InteropTests.cs
@@ -0,0 +1,82 @@
+using System.Runtime.InteropServices;
+using WindowsDriver.Interop.Kmdf;
+using WindowsDriver.Interop.Umdf;
+using WindowsDriver.Sdk;
+using Xunit;
+
+namespace WindowsDriver.Sdk.Tests;
+
+public class InteropTests
+{
+ // ----- KMDF shim protocol -----
+
+ [Fact]
+ public void Shim_ioctl_codes_are_unique_and_vendor_scoped()
+ {
+ var codes = new[]
+ {
+ KmdfShimProtocol.Ping,
+ KmdfShimProtocol.GetVersion,
+ KmdfShimProtocol.SendCommand,
+ KmdfShimProtocol.ReadEvents,
+ KmdfShimProtocol.AcknowledgeEvents,
+ };
+ Assert.Equal(codes.Length, codes.Distinct().Count());
+ Assert.All(codes, c =>
+ {
+ Assert.True(WinIoctl.FunctionFromControl(c) >= WinIoctl.FirstVendorFunction, $"0x{c:X8} must use a vendor function code");
+ Assert.Equal(WinIoctl.MethodBuffered, WinIoctl.MethodFromControl(c));
+ });
+ }
+
+ [Fact]
+ public void Wire_struct_sizes_are_stable()
+ {
+ Assert.Equal(8, KmdfCommandHeader.WireSize);
+ Assert.Equal(8, KmdfResultHeader.WireSize);
+ Assert.Equal(16, KmdfEventRecord.WireSize);
+ Assert.Equal(8, Marshal.SizeOf());
+ Assert.Equal(16, Marshal.SizeOf());
+ Assert.Equal(16, KmdfEventRecord.TotalSize(0));
+ Assert.Equal(17, KmdfEventRecord.TotalSize(1));
+ }
+
+ [Fact]
+ public void Magic_reads_as_ascii()
+ {
+ var bytes = BitConverter.GetBytes(KmdfShimProtocol.Magic);
+ Assert.Equal("WSHI", System.Text.Encoding.ASCII.GetString(bytes));
+ }
+
+ // ----- UMDF shim contract -----
+
+ [Fact]
+ public void Shim_header_declares_the_managed_entry_points()
+ {
+ var header = UmdfShimContract.ShimHeader;
+ Assert.Contains("PFN_WdsInitialize", header);
+ Assert.Contains("PFN_WdsQueueRequest", header);
+ Assert.Contains("WDS_SHIM_SETTINGS", header);
+
+ Assert.Equal("WdsInitialize", UmdfShimContract.ManagedEntryPoints.Initialize);
+ Assert.Equal("WdsQueueRequest", UmdfShimContract.ManagedEntryPoints.QueueRequest);
+ }
+
+ [Fact]
+ public void Umdf_settings_struct_matches_wire_size()
+ {
+ // 5 pointers on 64-bit.
+ Assert.Equal(5 * IntPtr.Size, Marshal.SizeOf());
+ Assert.Equal(UmdfShimSettings.WireSize, Marshal.SizeOf());
+ }
+
+ // ----- KMDF control plane (no device: error paths) -----
+
+ [Fact]
+ public void Control_plane_requires_open_before_use()
+ {
+ var plane = new KmdfControlPlane(@"\\.\WdsKmdfShim0");
+ Assert.Throws(() => plane.Ping());
+ Assert.Throws(() => plane.ReadEvents());
+ }
+}
diff --git a/tests/WindowsDriver.Sdk.Tests/RuntimeTests.cs b/tests/WindowsDriver.Sdk.Tests/RuntimeTests.cs
new file mode 100644
index 0000000..1593b85
--- /dev/null
+++ b/tests/WindowsDriver.Sdk.Tests/RuntimeTests.cs
@@ -0,0 +1,297 @@
+using System.Buffers.Binary;
+using WindowsDriver.Sdk;
+using WindowsDriver.Sdk.Audio;
+using WindowsDriver.Testing;
+using Xunit;
+
+namespace WindowsDriver.Sdk.Tests;
+
+public class RuntimeTests
+{
+ // ----- NtStatus -----
+
+ [Theory]
+ [InlineData(NtStatus.Success, true, false, false, false)]
+ [InlineData(NtStatus.Pending, true, false, false, false)]
+ [InlineData(NtStatus.BufferOverflow, false, false, true, false)]
+ [InlineData(NtStatus.InvalidDeviceRequest, false, false, false, true)]
+ [InlineData(NtStatus.AccessDenied, false, false, false, true)]
+ public void Severity_fields_are_derived_from_bit_30(NtStatus status, bool success, bool info, bool warning, bool error)
+ {
+ Assert.Equal(success, status.IsSuccess());
+ Assert.Equal(info, status.IsInformational());
+ Assert.Equal(warning, status.IsWarning());
+ Assert.Equal(error, status.IsError());
+ }
+
+ // ----- CTL_CODE bit math (matches the C macro) -----
+
+ [Fact]
+ public void CtlCode_matches_the_C_macro()
+ {
+ // #define CTL_CODE( DeviceType, Function, Method, Access ) (
+ // ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) )
+ Assert.Equal(0x00226004u, WinIoctl.CtlCode(0x22, 0x801, WinIoctl.MethodBuffered, WinIoctl.FileAccessRead));
+ Assert.Equal(0x22u, WinIoctl.DeviceTypeFromControl(0x00226004u));
+ Assert.Equal(0x801u, WinIoctl.FunctionFromControl(0x00226004u));
+ Assert.Equal(WinIoctl.MethodBuffered, WinIoctl.MethodFromControl(0x00226004u));
+ Assert.Equal(WinIoctl.FileAccessRead, WinIoctl.AccessFromControl(0x00226004u));
+
+ // Sound-device example from the audio contract.
+ var audio = AudioIoctlCodes.GetFormat;
+ Assert.Equal(WinIoctl.FileDeviceSound, WinIoctl.DeviceTypeFromControl(audio));
+ Assert.Equal(0x802u, WinIoctl.FunctionFromControl(audio));
+ }
+
+ [Fact]
+ public void VendorControlCode_rejects_reserved_functions()
+ {
+ Assert.Throws(() => WinIoctl.VendorControlCode(0x100));
+ _ = WinIoctl.VendorControlCode(0x800); // lowest allowed
+ }
+
+ // ----- WireFormat -----
+
+ [Fact]
+ public void WireFormat_roundtrips_little_endian_values()
+ {
+ var buffer = new byte[24];
+ WireFormat.WriteInt16(buffer, 0, -12345);
+ WireFormat.WriteUInt32(buffer, 2, 0xDEADBEEF);
+ WireFormat.WriteInt64(buffer, 6, long.MinValue);
+ WireFormat.WriteDouble(buffer, 14, Math.PI);
+
+ Assert.Equal(-12345, WireFormat.ReadInt16(buffer, 0));
+ Assert.Equal(0xDEADBEEFu, WireFormat.ReadUInt32(buffer, 2));
+ Assert.Equal(long.MinValue, WireFormat.ReadInt64(buffer, 6));
+ Assert.Equal(Math.PI, WireFormat.ReadDouble(buffer, 14));
+
+ // Bytes are explicitly little-endian: 0xDEADBEEF reads as EF BE AD DE.
+ Assert.Equal([0xEF, 0xBE, 0xAD, 0xDE], buffer.AsSpan(2, 4).ToArray());
+ }
+
+ [Fact]
+ public void WireFormat_throws_buffer_too_small()
+ {
+ var ex = Assert.Throws(() =>
+ {
+ Span tiny = stackalloc byte[3];
+ WireFormat.WriteInt32(tiny, 0, 1);
+ });
+ Assert.Equal(NtStatus.BufferTooSmall, ex.Status);
+ }
+
+ // ----- PropertyStore -----
+
+ [Fact]
+ public void PropertyStore_handles_typed_values()
+ {
+ var store = new PropertyStore();
+ store.Set("name", "device");
+ store.Set("count", 42u);
+ store.Set("enabled", true);
+ store.Set("id", new Guid("12345678-1234-1234-1234-123456789ABC"));
+
+ Assert.Equal("device", store.GetString("name"));
+ Assert.Equal(42u, store.GetDword("count"));
+ Assert.True(store.GetBool("enabled"));
+ Assert.Equal(new Guid("12345678-1234-1234-1234-123456789ABC"), store.GetGuid("id"));
+ Assert.Equal("123", store.GetDword("missing-does-not-exist", defaultValue: 123).ToString());
+ }
+
+ // ----- ByteRingBuffer -----
+
+ [Fact]
+ public void RingBuffer_wraps_and_counts_drops()
+ {
+ var ring = new ByteRingBuffer(8);
+ Assert.Equal(3, ring.Write([1, 2, 3]));
+ Assert.Equal(5, ring.Write(Enumerable.Range(4, 10).Select(i => (byte)i).ToArray())); // 5 accepted, 5 dropped
+ Assert.Equal(5, ring.DroppedBytes);
+ Assert.Equal(8, ring.Count);
+
+ var output = new byte[8];
+ Assert.Equal(8, ring.Read(output));
+ Assert.Equal([1, 2, 3, 4, 5, 6, 7, 8], output);
+
+ Assert.Equal(0, ring.Read(output));
+ Assert.Equal(8, ring.TotalBytesWritten); // accepted bytes only (5 were dropped)
+ Assert.Equal(8, ring.TotalBytesRead);
+ }
+
+ [Fact]
+ public void RingBuffer_skip_and_clear_work_across_the_wrap()
+ {
+ var ring = new ByteRingBuffer(4);
+ ring.Write([1, 2, 3, 4]);
+ Assert.Equal(2, ring.Skip(2));
+ var one = new byte[1];
+ Assert.Equal(1, ring.Read(one));
+ Assert.Equal(3, one[0]);
+ ring.Clear();
+ Assert.Equal(0, ring.Count);
+ }
+
+ // ----- IoQueue -----
+
+ private static async Task<(IoRequest Request, IoResult Result)> SendAsync(IoQueue queue, uint ioctl, byte[]? input = null, int outputSize = 64)
+ {
+ var request = new IoRequest(IoRequestKind.DeviceControl, ioctl, input ?? Array.Empty(), new byte[outputSize], 42);
+ var completion = new TaskCompletionSource();
+ request.Completed += completion.SetResult;
+ queue.Submit(request);
+ await completion.Task;
+ return (request, IoResult.From(request));
+ }
+
+ [Fact]
+ public async Task Queue_without_handler_rejects_the_request()
+ {
+ var queue = new IoQueue(NullDriverLog.Instance);
+ var (_, result) = await SendAsync(queue, 0xDEAD);
+ Assert.Equal(NtStatus.InvalidDeviceRequest, result.Status);
+ }
+
+ [Fact]
+ public async Task Sequential_queue_runs_requests_one_at_a_time()
+ {
+ var queue = new IoQueue(NullDriverLog.Instance, new IoQueueOptions { Dispatch = QueueDispatchMode.Sequential });
+ var concurrent = 0;
+ var maxConcurrent = 0;
+ var delay = TimeSpan.FromMilliseconds(20);
+
+ queue.OnDeviceControl((request, ct) =>
+ {
+ Interlocked.Increment(ref concurrent);
+ maxConcurrent = Math.Max(maxConcurrent, concurrent);
+ return Task.Delay(delay).ContinueWith(_ =>
+ {
+ Interlocked.Decrement(ref concurrent);
+ request.Complete(NtStatus.Success);
+ });
+ });
+
+ var tasks = Enumerable.Range(0, 5).Select(_ => SendAsync(queue, 1)).ToArray();
+ await Task.WhenAll(tasks);
+ Assert.All(tasks, t => Assert.Equal(NtStatus.Success, t.Result.Result.Status));
+ Assert.Equal(1, maxConcurrent);
+ }
+
+ [Fact]
+ public async Task DriverException_status_flows_to_the_request()
+ {
+ var queue = new IoQueue(NullDriverLog.Instance);
+ queue.OnDeviceControl((request, ct) => throw new DriverException(NtStatus.DeviceNotReady, "not ready"));
+ var (_, result) = await SendAsync(queue, 1);
+ Assert.Equal(NtStatus.DeviceNotReady, result.Status);
+ }
+
+ [Fact]
+ public void Double_completion_is_a_bug()
+ {
+ var request = new IoRequest(IoRequestKind.DeviceControl, 1, Array.Empty(), new byte[4]);
+ request.Complete(NtStatus.Success, 0);
+ Assert.Throws(() => request.Complete(NtStatus.Success, 0));
+ }
+
+ [Fact]
+ public void Byte_overflow_is_rejected()
+ {
+ var request = new IoRequest(IoRequestKind.Read, 0, Array.Empty(), new byte[4]);
+ Assert.Throws(() => request.Complete(NtStatus.Success, 5));
+ }
+
+ // ----- Manual queue -----
+
+ [Fact]
+ public async Task Manual_queue_holds_requests_until_pulled()
+ {
+ var queue = new IoQueue(NullDriverLog.Instance, new IoQueueOptions { Dispatch = QueueDispatchMode.Manual });
+ var request = new IoRequest(IoRequestKind.DeviceControl, 7, Array.Empty(), new byte[4]);
+ queue.Submit(request);
+ Assert.False(request.IsCompleted);
+
+ var pulled = await queue.ManualRequests.ReadAsync();
+ Assert.Same(request, pulled);
+ pulled.Complete(NtStatus.Success);
+ Assert.True(request.IsCompleted);
+ }
+
+ // ----- DriverHost lifecycle -----
+
+ private sealed class LifecycleDriver : DriverBase
+ {
+ public static readonly List Trace = [];
+
+ public override Task OnDriverEntryAsync(DriverContext context, CancellationToken ct)
+ {
+ Trace.Add("entry");
+ return Task.CompletedTask;
+ }
+
+ public override Task OnDeviceAddAsync(DeviceAddContext addContext, DeviceContext deviceContext, CancellationToken ct)
+ {
+ Trace.Add("add");
+ var device = new LifecycleDevice(deviceContext);
+ return Task.FromResult(device);
+ }
+
+ public override Task OnDriverUnloadAsync()
+ {
+ Trace.Add("unload");
+ return Task.CompletedTask;
+ }
+ }
+
+ private sealed class LifecycleDevice(DeviceContext context) : DeviceBase(context)
+ {
+ public override Task OnPrepareHardwareAsync(CancellationToken ct)
+ {
+ LifecycleDriver.Trace.Add("prepare");
+ return Task.CompletedTask;
+ }
+
+ public override Task OnD0EntryAsync(DevicePowerState previous, CancellationToken ct)
+ {
+ LifecycleDriver.Trace.Add("d0entry");
+ return Task.CompletedTask;
+ }
+
+ public override Task OnD0ExitAsync(DevicePowerState next, CancellationToken ct)
+ {
+ LifecycleDriver.Trace.Add("d0exit");
+ return Task.CompletedTask;
+ }
+
+ public override Task OnReleaseHardwareAsync(CancellationToken ct)
+ {
+ LifecycleDriver.Trace.Add("release");
+ return Task.CompletedTask;
+ }
+ }
+
+ [Fact]
+ public async Task Lifecycle_runs_in_WDF_order()
+ {
+ LifecycleDriver.Trace.Clear();
+ var host = TestDriverHost.Builder().UseFakeTime().Build();
+ await host.StartAsync();
+ await host.AddDeviceAsync("ROOT\\TEST\\0000", "Root\\TestDevice");
+
+ Assert.Equal(["entry", "add", "prepare", "d0entry"], LifecycleDriver.Trace);
+
+ await host.ShutdownAsync();
+ Assert.Equal(["entry", "add", "prepare", "d0entry", "d0exit", "release", "unload"], LifecycleDriver.Trace);
+ Assert.False(host.IsStarted);
+ }
+
+ [Fact]
+ public async Task DeviceContext_shares_the_driver_context()
+ {
+ var host = TestDriverHost.Builder().UseFakeTime().Build();
+ await host.StartAsync();
+ var device = await host.AddDeviceAsync("ROOT\\TEST\\0001", "Root\\TestDevice");
+ Assert.Same(host.Log, device.Context.Driver.Log);
+ await host.ShutdownAsync();
+ }
+}
diff --git a/tests/WindowsDriver.Sdk.Tests/WindowsDriver.Sdk.Tests.csproj b/tests/WindowsDriver.Sdk.Tests/WindowsDriver.Sdk.Tests.csproj
new file mode 100644
index 0000000..4e65bdc
--- /dev/null
+++ b/tests/WindowsDriver.Sdk.Tests/WindowsDriver.Sdk.Tests.csproj
@@ -0,0 +1,21 @@
+
+
+
+ false
+ Unit tests for the Windows Driver SDK core runtime, interop contracts and InfGen.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tools/Enable-TestSigning.ps1 b/tools/Enable-TestSigning.ps1
new file mode 100644
index 0000000..68b0f80
--- /dev/null
+++ b/tools/Enable-TestSigning.ps1
@@ -0,0 +1,37 @@
+<#
+.SYNOPSIS
+ Enables Windows test signing so test-signed driver packages load.
+
+.DESCRIPTION
+ Runs `bcdedit /set testsigning on`. Requires admin rights and a reboot to
+ take effect. A watermark appears on the desktop while test signing is on.
+
+.EXAMPLE
+ .\Enable-TestSigning.ps1
+#>
+[CmdletBinding()]
+param(
+ [switch]$Off
+)
+
+$ErrorActionPreference = 'Stop'
+
+$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
+$principal = New-Object Security.Principal.WindowsPrincipal($identity)
+if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
+ throw "Administrator rights are required. Run from an elevated prompt."
+}
+
+if ($Off) {
+ bcdedit /set testsigning off
+ Write-Host "Test signing disabled. Reboot to apply." -ForegroundColor Yellow
+ return
+}
+
+bcdedit /set testsigning on
+if ($LASTEXITCODE -ne 0) {
+ throw "bcdedit failed with exit code $LASTEXITCODE (is this an elevated, UEFI/BIOS-compatible environment?)."
+}
+Write-Host "Test signing ENABLED. Reboot to apply." -ForegroundColor Green
+Write-Host "Remember to import your test certificate:" -ForegroundColor Cyan
+Write-Host " Import-Certificate -FilePath .\test.cer -CertStoreLocation Cert:\LocalMachine\TrustedPublisher"
diff --git a/tools/Install-Driver.ps1 b/tools/Install-Driver.ps1
new file mode 100644
index 0000000..ac0b179
--- /dev/null
+++ b/tools/Install-Driver.ps1
@@ -0,0 +1,72 @@
+<#
+.SYNOPSIS
+ Installs a driver package (INF + binaries) with pnputil and starts the device.
+
+.DESCRIPTION
+ Wraps `pnputil /add-driver /install` with prechecks: admin rights, INF
+ presence, and (optionally) test-signing detection. Works for UMDF and KMDF
+ driver packages produced by the Windows Driver SDK.
+
+.PARAMETER InfPath
+ Path to the .inf file to install.
+
+.PARAMETER CertPath
+ Optional path to a .cer certificate to add to the machine TrustedPublishers
+ store first (useful for test-signed packages).
+
+.EXAMPLE
+ .\Install-Driver.ps1 -InfPath .\VirtualAudio.inf
+
+.EXAMPLE
+ .\Install-Driver.ps1 -InfPath .\WdsKmdfShim.inf -CertPath .\test.cer
+#>
+[CmdletBinding()]
+param(
+ [Parameter(Mandatory = $true)]
+ [string]$InfPath,
+
+ [string]$CertPath
+)
+
+$ErrorActionPreference = 'Stop'
+
+function Assert-Admin {
+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
+ $principal = New-Object Security.Principal.WindowsPrincipal($identity)
+ if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
+ throw "Administrator rights are required to install drivers. Run from an elevated prompt."
+ }
+}
+
+Assert-Admin
+
+$InfPath = (Resolve-Path $InfPath).Path
+if (-not (Test-Path $InfPath)) {
+ throw "INF not found: $InfPath"
+}
+
+if ($CertPath) {
+ $CertPath = (Resolve-Path $CertPath).Path
+ Write-Host "Importing certificate $CertPath into TrustedPublishers..." -ForegroundColor Cyan
+ Import-Certificate -FilePath $CertPath -CertStoreLocation Cert:\LocalMachine\TrustedPublisher | Out-Null
+}
+
+# Detect test-signed packages and warn about the requirement.
+$testSigning = (bcdedit /enum '{current}' | Select-String -Pattern 'testsigning\s+Yes') -ne $null
+if (-not $testSigning) {
+ Write-Warning "Test signing is not enabled. If this package is test-signed, enable it first:"
+ Write-Warning " .\Enable-TestSigning.ps1 (then reboot)"
+}
+
+Write-Host "Installing $InfPath ..." -ForegroundColor Cyan
+pnputil /add-driver $InfPath /install
+if ($LASTEXITCODE -ne 0) {
+ throw "pnputil failed with exit code $LASTEXITCODE."
+}
+
+$infName = Split-Path $InfPath -Leaf
+Write-Host ""
+Write-Host "Installed. Device status:" -ForegroundColor Green
+Get-PnpDevice -Class '*' | Where-Object { $_.InstanceId -like "*$infName*" -or $_.FriendlyName -like "*$infName*" } |
+ Format-Table Status, Class, FriendlyName, InstanceId -AutoSize
+Write-Host "To remove it again: .\Uninstall-Driver.ps1 -InfName $infName"
diff --git a/tools/Uninstall-Driver.ps1 b/tools/Uninstall-Driver.ps1
new file mode 100644
index 0000000..446f9dc
--- /dev/null
+++ b/tools/Uninstall-Driver.ps1
@@ -0,0 +1,77 @@
+<#
+.SYNOPSIS
+ Uninstalls a previously installed driver package and removes its devices.
+
+.PARAMETER InfName
+ The published INF name (oemXX.inf) or the original file name. When omitted,
+ the script lists matching packages instead of removing anything.
+
+.PARAMETER HardwareId
+ Optional hardware ID to find the devices that use the driver.
+
+.EXAMPLE
+ .\Uninstall-Driver.ps1 # list installed SDK driver packages
+ .\Uninstall-Driver.ps1 -InfName VirtualAudio.inf
+#>
+[CmdletBinding()]
+param(
+ [string]$InfName,
+ [string]$HardwareId
+)
+
+$ErrorActionPreference = 'Stop'
+
+function Assert-Admin {
+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
+ $principal = New-Object Security.Principal.WindowsPrincipal($identity)
+ if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
+ throw "Administrator rights are required to uninstall drivers. Run from an elevated prompt."
+ }
+}
+
+Assert-Admin
+
+# Map the original INF name to its published oemXX.inf name.
+$published = pnputil /enum-drivers | Out-String
+$blocks = $published -split "`r?`n`r?`n" | Where-Object { $_ -match 'Original Name' }
+
+$target = $null
+foreach ($block in $blocks) {
+ $original = [regex]::Match($block, 'Original Name:\s*(.+)$').Groups[1].Value.Trim()
+ if ($original -eq $InfName -or ($InfName -and $original -ieq $InfName)) {
+ $target = [regex]::Match($block, 'Published Name:\s*(.+)$').Groups[1].Value.Trim()
+ break
+ }
+ if ($HardwareId -and $block -match [regex]::Escape($HardwareId)) {
+ $target = [regex]::Match($block, 'Published Name:\s*(.+)$').Groups[1].Value.Trim()
+ break
+ }
+}
+
+if (-not $target) {
+ Write-Host "Installed driver packages (Original Name / Published Name):" -ForegroundColor Cyan
+ foreach ($block in $blocks) {
+ $o = [regex]::Match($block, 'Original Name:\s*(.+)$').Groups[1].Value.Trim()
+ $p = [regex]::Match($block, 'Published Name:\s*(.+)$').Groups[1].Value.Trim()
+ "$o → $p"
+ }
+ if ($InfName) {
+ Write-Warning "No package matched '$InfName'."
+ }
+ return
+}
+
+Write-Host "Removing devices that use $target..." -ForegroundColor Cyan
+if ($HardwareId) {
+ Get-PnpDevice | Where-Object { $_.InstanceId -like "*$HardwareId*" } | ForEach-Object {
+ Write-Host " removing device $($_.InstanceId)"
+ pnputil /remove-device $_.InstanceId | Out-Null
+ }
+}
+
+Write-Host "Deleting driver package $target ..." -ForegroundColor Cyan
+pnputil /delete-driver $target /uninstall /force
+if ($LASTEXITCODE -ne 0) {
+ throw "pnputil failed with exit code $LASTEXITCODE."
+}
+Write-Host "Uninstalled." -ForegroundColor Green