commit 0ee5f83f778b90ccfa4af86c59ce2b01e23998b1 Author: nefarius Date: Thu Mar 23 13:48:13 2023 +0100 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ca1c7a3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,400 @@ +# ---> VisualStudio +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + diff --git a/DmfBusFilterExtension.sln b/DmfBusFilterExtension.sln new file mode 100644 index 0000000..0ddc8c7 --- /dev/null +++ b/DmfBusFilterExtension.sln @@ -0,0 +1,49 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.33328.57 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DmfBusFilterExtension", "src\DmfBusFilterExtension.vcxproj", "{D384918D-A356-4325-B8DD-A2A10E4592A0}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{93279664-7E33-4C94-8014-E754C9D0A831}" + ProjectSection(SolutionItems) = preProject + LICENSE = LICENSE + README.md = README.md + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM64 = Debug|ARM64 + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|ARM64 = Release|ARM64 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Debug|ARM64.Build.0 = Debug|ARM64 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Debug|x64.ActiveCfg = Debug|x64 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Debug|x64.Build.0 = Debug|x64 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Debug|x64.Deploy.0 = Debug|x64 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Debug|x86.ActiveCfg = Debug|Win32 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Debug|x86.Build.0 = Debug|Win32 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Debug|x86.Deploy.0 = Debug|Win32 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Release|ARM64.ActiveCfg = Release|ARM64 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Release|ARM64.Build.0 = Release|ARM64 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Release|ARM64.Deploy.0 = Release|ARM64 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Release|x64.ActiveCfg = Release|x64 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Release|x64.Build.0 = Release|x64 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Release|x64.Deploy.0 = Release|x64 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Release|x86.ActiveCfg = Release|Win32 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Release|x86.Build.0 = Release|Win32 + {D384918D-A356-4325-B8DD-A2A10E4592A0}.Release|x86.Deploy.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {97A0BC17-320C-4B2C-B748-738029614E0E} + EndGlobalSection +EndGlobal diff --git a/DmfBusFilterExtension.sln.DotSettings b/DmfBusFilterExtension.sln.DotSettings new file mode 100644 index 0000000..9931cc6 --- /dev/null +++ b/DmfBusFilterExtension.sln.DotSettings @@ -0,0 +1,8 @@ + + True + True + True + True + True + True + True \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2071b23 --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0e96734 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# DMF Extension Library for Bus Filter Support + +## 🚨 DISCLAIMER 🚨 + +**Provided for education purposes only!** diff --git a/src/Dmf.props b/src/Dmf.props new file mode 100644 index 0000000..e010b1d --- /dev/null +++ b/src/Dmf.props @@ -0,0 +1,20 @@ + + + + + + <_PropertySheetDisplayName>Driver Module Framework + + $(SolutionDir)..\ + + + + $(DmfRootPath)\DMF\Modules.Library;$(DmfRootPath)\DMF\Modules.Template;$(DmfRootPath)\DMF\Modules.Library.Tests;$(DmfRootPath)\DMF\Framework;$(IntDir);%(AdditionalIncludeDirectories) + + + $(DmfRootPath)\$(Configuration)\$(PlatformName)\lib\DmfK\DmfK.lib;$(DmfRootPath)\$(Configuration)\$(PlatformName)\individual_libs\DmfKModules.Template\DmfKModules.Template.lib;%(AdditionalDependencies); + $(DmfRootPath)\$(Configuration)\$(PlatformName)\lib\DmfU\DmfU.lib;$(DmfRootPath)\$(Configuration)\$(PlatformName)\individual_libs\DmfUModules.Template\DmfUModules.Template.lib;%(AdditionalDependencies); + + + + diff --git a/src/DmfBusFilterExtension.vcxproj b/src/DmfBusFilterExtension.vcxproj new file mode 100644 index 0000000..8a6b64f --- /dev/null +++ b/src/DmfBusFilterExtension.vcxproj @@ -0,0 +1,155 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + Debug + ARM64 + + + Release + ARM64 + + + + {D384918D-A356-4325-B8DD-A2A10E4592A0} + {1bc93793-694f-48fe-9372-81e2b05556fd} + v4.5 + 12.0 + Debug + Win32 + DmfBusFilterExtension + $(LatestTargetPlatformVersion) + + + + true + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + + + false + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + + + true + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + + + false + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + + + true + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + + + false + WindowsKernelModeDriver10.0 + StaticLibrary + KMDF + + + + + + + + + + + + DbgengKernelDebugger + + + DbgengKernelDebugger + true + + + DbgengKernelDebugger + + + DbgengKernelDebugger + true + + + DbgengKernelDebugger + + + DbgengKernelDebugger + true + + + + true + Trace.h + + + + + true + Trace.h + + + + + true + Trace.h + + + + + true + Trace.h + + + + + true + Trace.h + + + + + true + Trace.h + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/DmfBusFilterExtension.vcxproj.filters b/src/DmfBusFilterExtension.vcxproj.filters new file mode 100644 index 0000000..adfd945 --- /dev/null +++ b/src/DmfBusFilterExtension.vcxproj.filters @@ -0,0 +1,34 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {8E41214B-6785-4CFE-B992-037D68949A14} + inf;inv;inx;mof;mc; + + + + + Header Files + + + Header Files + + + + + Source Files + + + \ No newline at end of file diff --git a/src/Dmf_BusFilter.c b/src/Dmf_BusFilter.c new file mode 100644 index 0000000..3971900 --- /dev/null +++ b/src/Dmf_BusFilter.c @@ -0,0 +1,1211 @@ +/*++ + + Copyright (c) Nefarius Software Solutions e.U. All rights reserved. + Licensed under the MIT license. + +Module Name: + + Dmf_BusFilter.c + +Abstract: + + Creates the supporting plumbing for a Bus Filter Driver. + +Environment: + + Kernel-mode Driver Framework + +--*/ + +#include "DmfDefinitions.h" +#include "Dmf_BusFilter.h" +#include "DmfModules.Library.Trace.h" + +#if defined(DMF_INCLUDE_TMH) +#include "Dmf_BusFilter.tmh" +#endif + +/////////////////////////////////////////////////////////////////////////////////////////////////////// +// Bus Filter +/////////////////////////////////////////////////////////////////////////////////////////////////////// +// + +#if defined(DMF_KERNEL_MODE) + +// WDM child device context +// +typedef struct _WDM_CHILD_DEVICE_EXTENSION +{ + // GUID to identify WDM child device. + // + GUID Signature; + + // Target Device Object + // + PDEVICE_OBJECT TargetDeviceObject; + + // Physical Device Object + // + PDEVICE_OBJECT PhysicalDeviceObject; + + // Parent ChildList entry + // + LIST_ENTRY ListEntry; + + // Parent WDF device object + // + WDFDEVICE Parent; + + // Child WDF wrapper object + // + DMFBUSCHILDDEVICE Child; + + // TRUE if PDO is attached, FALSE otherwise + // + BOOLEAN IsExisting; +} WDM_CHILD_DEVICE_EXTENSION; + +// Parent bus device context +// +typedef struct _PARENT_BUS_DEVICE_CONTEXT +{ + // + // List of child device (relations) + // + LIST_ENTRY ChildList; + + // + // Spin lock protecting child list access + // + KSPIN_LOCK ChildListLock; +} PARENT_BUS_DEVICE_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(PARENT_BUS_DEVICE_CONTEXT, DMF_BusFilter_GetParentContext) + +// Bus child device context +// +typedef struct _BUS_CHILD_DEVICE_CONTEXT +{ + // WDM device object + // + PDEVICE_OBJECT DeviceObject; +} BUS_CHILD_DEVICE_CONTEXT; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(BUS_CHILD_DEVICE_CONTEXT, DMF_BusFilter_GetChildContext) + +typedef +_Function_class_(EVT_DMF_BusFilter_DispatchPnp) +_IRQL_requires_same_ +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSTATUS +EVT_DMF_BusFilter_DispatchPnp( + _In_ DMFBUSCHILDDEVICE ChildDevice, + _In_ PIRP Irp + ); + +// Module-internal context data +// +typedef struct _DMF_CONTEXT_BusFilter +{ + // Copy of the module configuration + // + DMF_BusFilter_CONFIG Configuration; + + // Hooked dispatch table + // + PDRIVER_DISPATCH MajorDispatchFunctions[IRP_MJ_MAXIMUM_FUNCTION + 1]; + + // PNP minor functions dispatch routines + // + EVT_DMF_BusFilter_DispatchPnp* PnPMinorDispatchFunctions[IRP_MN_DEVICE_ENUMERATED + 1]; +} BusFilter_Context; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(BusFilter_Context, + BusFilterContextGet); + +// {678CBB8D-019F-4D07-912A-73E2E568B148} +DEFINE_GUID(GUID_DMF_BUSFILTER_SIGNATURE, + 0x678cbb8d, 0x19f, 0x4d07, 0x91, 0x2a, 0x73, 0xe2, 0xe5, 0x68, 0xb1, 0x48); + +#pragma code_seg("PAGE") +_IRQL_requires_max_(PASSIVE_LEVEL) +static +void +DMF_BusFilter_Relations_RemoveDevice( + _In_ PDEVICE_OBJECT DeviceObject + ) +/*++ + +Routine Description: + + Processes child device removal. + +Arguments: + + DeviceObject - Parent device object. + +Return Value: + + None + +--*/ +{ + KLOCK_QUEUE_HANDLE handle; + WDM_CHILD_DEVICE_EXTENSION* extension = (WDM_CHILD_DEVICE_EXTENSION*)DeviceObject->DeviceExtension; + PARENT_BUS_DEVICE_CONTEXT* parentContext = DMF_BusFilter_GetParentContext(extension->Parent); + const BusFilter_Context* context = BusFilterContextGet(WdfGetDriver()); + const DMF_BusFilter_CONFIG* config = &context->Configuration; + + FuncEntry(DMF_TRACE); + + PAGED_CODE(); + + if (extension->IsExisting) + { + goto Exit; + } + +#pragma warning(disable: 28150) + KeAcquireInStackQueuedSpinLock(&parentContext->ChildListLock, + &handle); + RemoveEntryList(&extension->ListEntry); + KeReleaseInStackQueuedSpinLock(&handle); +#pragma warning(default: 28150) + + TraceVerbose(DMF_TRACE, "%!FUNC! called at %!irql!", KeGetCurrentIrql()); + + if (config->EvtDeviceRemove) + { + config->EvtDeviceRemove(extension->Parent, extension->Child); + } + + WdfObjectDelete(extension->Child); + IoDetachDevice(extension->TargetDeviceObject); + IoDeleteDevice(DeviceObject); + +Exit: + + FuncExitNoReturn(DMF_TRACE); +} +#pragma code_seg() + +_IRQL_requires_max_(DISPATCH_LEVEL) +static +NTSTATUS +DMF_BusFilter_DispatchPnp( + _In_ PDEVICE_OBJECT DeviceObject, + _In_ PIRP Irp, + _In_ UCHAR MinorCode + ) +/*++ + +Routine Description: + + Handles PnP requests. + +Arguments: + + DeviceObject - Parent device object. + Irp - Irp with PnP request. + MinorCode - Request minor code. + +Return Value: + + NTSTATUS + +--*/ +{ + const WDM_CHILD_DEVICE_EXTENSION* extension = (WDM_CHILD_DEVICE_EXTENSION*)DeviceObject->DeviceExtension; + const BusFilter_Context* context = BusFilterContextGet(WdfGetDriver()); + + if (MinorCode == IRP_MN_REMOVE_DEVICE) + { + // Handle child device removal + // + DMF_BusFilter_Relations_RemoveDevice(DeviceObject); + } + else if (MinorCode <= IRP_MN_DEVICE_ENUMERATED) + { + if (context->PnPMinorDispatchFunctions[MinorCode] != NULL) + { + // + // Forward to PnP minor code dispatch routines + // + return context->PnPMinorDispatchFunctions[MinorCode](extension->Child, Irp); + } + } + + // Forward to lower driver + // + IoSkipCurrentIrpStackLocation(Irp); + return IoCallDriver(extension->TargetDeviceObject, + Irp); +} + +_IRQL_requires_max_(DISPATCH_LEVEL) +static +NTSTATUS +DMF_BusFilter_DispatchHandler( + _In_ PDEVICE_OBJECT DeviceObject, + _In_ PIRP Irp + ) +/*++ + +Routine Description: + + Dispatch routine handler for all IRPs + +Arguments: + + DeviceObject - Parent device object. + Irp - Irp with request. + +Return Value: + + NTSTATUS + +--*/ +{ + const WDM_CHILD_DEVICE_EXTENSION* extension = (WDM_CHILD_DEVICE_EXTENSION*)DeviceObject->DeviceExtension; + const PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(Irp); + const BusFilter_Context* context = BusFilterContextGet(WdfGetDriver()); + + if (!IsEqualGUID(&extension->Signature, + &GUID_DMF_BUSFILTER_SIGNATURE)) + { + return context->MajorDispatchFunctions[stack->MajorFunction](DeviceObject, Irp); + } + + // Handle PNP requests + // + if (stack->MajorFunction == IRP_MJ_PNP) + { + return DMF_BusFilter_DispatchPnp(DeviceObject, Irp, stack->MinorFunction); + } + + // Forward to lower driver + // + IoSkipCurrentIrpStackLocation(Irp); + return IoCallDriver(extension->TargetDeviceObject, Irp); +} + +_IRQL_requires_max_(APC_LEVEL) +static +NTSTATUS +DMF_BusFilter_Relations_AddDevice( + _In_ WDFDEVICE Device, + _In_ PDEVICE_OBJECT PhysicalDeviceObject + ) +/*++ + +Routine Description: + + Creates proxy child device for bus PDO. + +Arguments: + + Device - Child device to add. + PhysicalDeviceObject - Parent device object. + +Return Value: + + NTSTATUS + +--*/ +{ + NTSTATUS ntStatus = STATUS_NOT_IMPLEMENTED; + WDF_OBJECT_ATTRIBUTES attributes; + PLIST_ENTRY entry = NULL; + KLOCK_QUEUE_HANDLE handle; + WDM_CHILD_DEVICE_EXTENSION* childExtension = NULL; + PDEVICE_OBJECT filterDeviceObject = NULL; + BOOLEAN preexisting = FALSE; + DMFBUSCHILDDEVICE child = NULL; + BUS_CHILD_DEVICE_CONTEXT* childContext = NULL; + PARENT_BUS_DEVICE_CONTEXT* parentContext = DMF_BusFilter_GetParentContext(Device); + const PDEVICE_OBJECT deviceObject = WdfDeviceWdmGetDeviceObject(Device); + const BusFilter_Context* context = BusFilterContextGet(WdfGetDriver()); + const DMF_BusFilter_CONFIG* config = &context->Configuration; + + FuncEntry(DMF_TRACE); + + if (parentContext == NULL) + { + ntStatus = STATUS_INVALID_DEVICE_STATE; + goto Exit; + } + + KeAcquireInStackQueuedSpinLock(&parentContext->ChildListLock, + &handle); + + // Find and update PDO status + // + for ( + entry = parentContext->ChildList.Flink; + entry != &parentContext->ChildList; + entry = entry->Flink + ) + { + childExtension = CONTAINING_RECORD(entry, + WDM_CHILD_DEVICE_EXTENSION, + ListEntry); + + if (childExtension->PhysicalDeviceObject == PhysicalDeviceObject) + { + preexisting = TRUE; + childExtension->IsExisting = TRUE; + break; + } + } + + KeReleaseInStackQueuedSpinLock(&handle); + + if (preexisting) + { + ntStatus = STATUS_SUCCESS; + goto Exit; + } + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, + BUS_CHILD_DEVICE_CONTEXT); + attributes.ParentObject = Device; + + // Create piggyback framework object for WDM child device object + // + ntStatus = WdfObjectCreate(&attributes, (WDFOBJECT*)&child); + if (!NT_SUCCESS(ntStatus)) + { + TraceError(DMF_TRACE, "WdfObjectCreate fails: ntStatus=%!STATUS!", ntStatus); + goto Exit; + } + + // Create WDM device + // + ntStatus = IoCreateDevice(deviceObject->DriverObject, + sizeof(WDM_CHILD_DEVICE_EXTENSION), + NULL, + config->DeviceType, + FILE_DEVICE_SECURE_OPEN | config->DeviceCharacteristics, + FALSE, + &filterDeviceObject); + if (!NT_SUCCESS(ntStatus)) + { + TraceError(DMF_TRACE, "IoCreateDevice fails: ntStatus=%!STATUS!", ntStatus); + goto Exit; + } + + // Link WDM and WDF device together. + // + childContext = DMF_BusFilter_GetChildContext(child); + childContext->DeviceObject = filterDeviceObject; + + childExtension = (WDM_CHILD_DEVICE_EXTENSION*)filterDeviceObject->DeviceExtension; + RtlZeroMemory(childExtension, + sizeof(WDM_CHILD_DEVICE_EXTENSION)); + RtlCopyMemory(&childExtension->Signature, + &GUID_DMF_BUSFILTER_SIGNATURE, + sizeof(GUID)); + childExtension->Parent = Device; + childExtension->Child = child; + + childExtension->PhysicalDeviceObject = PhysicalDeviceObject; + + childExtension->TargetDeviceObject = IoAttachDeviceToDeviceStack(filterDeviceObject, + PhysicalDeviceObject); + if (childExtension->TargetDeviceObject == NULL) + { + IoDeleteDevice(filterDeviceObject); + ntStatus = STATUS_NO_SUCH_DEVICE; + goto Exit; + } + + filterDeviceObject->Flags |= childExtension->TargetDeviceObject->Flags & + (DO_BUFFERED_IO | DO_DIRECT_IO | DO_POWER_INRUSH | DO_POWER_PAGABLE); + + if (config->EvtDeviceAdd) + { + ntStatus = config->EvtDeviceAdd(Device, child); + + if (!NT_SUCCESS(ntStatus)) + { + TraceError(DMF_TRACE, "EvtDeviceAdd fails: ntStatus=%!STATUS!", ntStatus); + + IoDetachDevice(childExtension->TargetDeviceObject); + IoDeleteDevice(filterDeviceObject); + goto Exit; + } + } + + KeAcquireInStackQueuedSpinLock(&parentContext->ChildListLock, + &handle); + childExtension->IsExisting = TRUE; + InsertTailList(&parentContext->ChildList, + &childExtension->ListEntry); + KeReleaseInStackQueuedSpinLock(&handle); + + filterDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; + + ntStatus = STATUS_SUCCESS; + +Exit: + + if (!NT_SUCCESS(ntStatus) && child != NULL) + { + WdfObjectDelete(child); + } + + FuncExit(DMF_TRACE, "status=%!STATUS!", ntStatus); + + return ntStatus; +} + +#pragma code_seg("PAGE") +_IRQL_requires_max_(PASSIVE_LEVEL) +static +NTSTATUS +DMF_BusFilter_QueryBusRelationsCompleted( + _In_ PDEVICE_OBJECT DeviceObject, + _In_ PIRP Irp, + _In_ WDFDEVICE Device + ) +/*++ + +Routine Description: + + Bus relations query completed routine. + +Arguments: + + DeviceObject - Parent device object. + Irp - Query Bus Relations IRP. + Device - Target WDFDEVICE. + +Return Value: + + NTSTATUS + +--*/ +{ + NTSTATUS ntStatus = STATUS_NOT_IMPLEMENTED; + PARENT_BUS_DEVICE_CONTEXT* parentContext = DMF_BusFilter_GetParentContext(Device); + PDEVICE_RELATIONS deviceRelations = NULL; + KLOCK_QUEUE_HANDLE handle; + WDM_CHILD_DEVICE_EXTENSION* childExtension = NULL; + + UNREFERENCED_PARAMETER(DeviceObject); + + FuncEntry(DMF_TRACE); + + PAGED_CODE(); + + if (Irp->PendingReturned) + { + IoMarkIrpPending(Irp); + } + + if (!NT_SUCCESS(Irp->IoStatus.Status)) + { + goto Exit; + } + + if (parentContext == NULL) + { + goto Exit; + } + +#pragma warning(disable: 28150) + KeAcquireInStackQueuedSpinLock(&parentContext->ChildListLock, + &handle); + + // Reset child states + // + for ( + LIST_ENTRY* entry = parentContext->ChildList.Flink; + entry != &parentContext->ChildList; + entry = entry->Flink + ) + { + childExtension = CONTAINING_RECORD(entry, + WDM_CHILD_DEVICE_EXTENSION, + ListEntry); + childExtension->IsExisting = FALSE; + } + + KeReleaseInStackQueuedSpinLock(&handle); +#pragma warning(default: 28150) + + deviceRelations = (PDEVICE_RELATIONS)Irp->IoStatus.Information; + + if (deviceRelations == NULL) + { + goto Exit; + } + + // Walk through device relations. + // + for (ULONG index = 0; index < deviceRelations->Count; index++) + { + TraceVerbose(DMF_TRACE, "%!FUNC! called at %!irql!", KeGetCurrentIrql()); + + ntStatus = DMF_BusFilter_Relations_AddDevice(Device, + deviceRelations->Objects[index]); + if (!NT_SUCCESS(ntStatus)) + { + TraceError(DMF_TRACE, "DMF_BusFilter_Relations_AddDevice fails: ntStatus=%!STATUS!", ntStatus); + } + } + +Exit: + + FuncExitNoReturn(DMF_TRACE); + + return STATUS_CONTINUE_COMPLETION; +} +#pragma code_seg() + +_IRQL_requires_max_(DISPATCH_LEVEL) +static +NTSTATUS +DMF_BusFilter_PreprocessQueryBusRelations( + _In_ WDFDEVICE Device, + _In_ PIRP Irp + ) +/*++ + +Routine Description: + + Pre-processes IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS. + +Arguments: + + DeviceObject - Parent device object. + Irp - IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS request. + +Return Value: + + NTSTATUS + +--*/ +{ + const PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(Irp); + + if ( + stack->MajorFunction != IRP_MJ_PNP || + stack->MinorFunction != IRP_MN_QUERY_DEVICE_RELATIONS || + stack->Parameters.QueryDeviceRelations.Type != BusRelations + ) + { + IoSkipCurrentIrpStackLocation(Irp); + } + else + { + IoCopyCurrentIrpStackLocationToNext(Irp); + IoSetCompletionRoutine(Irp, + (PIO_COMPLETION_ROUTINE)DMF_BusFilter_QueryBusRelationsCompleted, + Device, + TRUE, + TRUE, + TRUE); + } + + return WdfDeviceWdmDispatchPreprocessedIrp(Device, + Irp); +} + +#pragma code_seg("PAGE") +static +NTSTATUS +DMF_BusFilter_PnP_StartDevice( + _In_ DMFBUSCHILDDEVICE ChildDevice, + _In_ PIRP Irp + ) +/*++ + +Routine Description: + + Handles IRP_MN_START_DEVICE + +Arguments: + + ChildDevice - Associated child device. + Irp - IRP_MJ_PNP / IRP_MN_START_DEVICE request. + +Return Value: + + NTSTATUS + +--*/ +{ + NTSTATUS ntStatus; + const BusFilter_Context* context = BusFilterContextGet(WdfGetDriver()); + const DMF_BusFilter_CONFIG* config = &context->Configuration; + + FuncEntry(DMF_TRACE); + + PAGED_CODE(); + + if (!IoForwardIrpSynchronously(DMF_BusFilter_WdmAttachedDeviceGet(ChildDevice), + Irp)) + { + TraceError(DMF_TRACE, "IoForwardIrpSynchronously fails: Irp=0x%p", Irp); + + Irp->IoStatus.Status = STATUS_NO_SUCH_DEVICE; + } + else if (NT_SUCCESS(Irp->IoStatus.Status) && config->EvtDeviceStarted) + { + config->EvtDeviceStarted(ChildDevice, + Irp); + } + + ntStatus = Irp->IoStatus.Status; + IoCompleteRequest(Irp, IO_NO_INCREMENT); + + FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus); + + return ntStatus; +} +#pragma code_seg() + +static +NTSTATUS +DMF_BusFilter_PnP_DeviceEnumerated( + _In_ DMFBUSCHILDDEVICE ChildDevice, + _In_ PIRP Irp + ) +/*++ + +Routine Description: + + Handles IRP_MN_DEVICE_ENUMERATED. + +Arguments: + + ChildDevice - Associated child device. + Irp - IRP_MJ_PNP / IRP_MN_DEVICE_ENUMERATED request. + +Return Value: + + NTSTATUS + +--*/ +{ + NTSTATUS ntStatus; + const BusFilter_Context* context = BusFilterContextGet(WdfGetDriver()); + const DMF_BusFilter_CONFIG* config = &context->Configuration; + + FuncEntry(DMF_TRACE); + + if (config->EvtDeviceEnumerated) + { + config->EvtDeviceEnumerated(ChildDevice, + Irp); + } + + // Forward to the parent bus driver + // + IoSkipCurrentIrpStackLocation(Irp); + ntStatus = IoCallDriver(DMF_BusFilter_WdmAttachedDeviceGet(ChildDevice), + Irp); + + FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus); + + return ntStatus; +} + +static +NTSTATUS +DMF_BusFilter_PnP_QueryId( + _In_ DMFBUSCHILDDEVICE ChildDevice, + _In_ PIRP Irp + ) +/*++ + +Routine Description: + + Handles IRP_MN_QUERY_ID. + +Arguments: + + ChildDevice - Associated child device. + Irp - IRP_MJ_PNP / IRP_MN_QUERY_ID request. + +Return Value: + + NTSTATUS + +--*/ +{ + NTSTATUS ntStatus; + const BusFilter_Context* context = BusFilterContextGet(WdfGetDriver()); + const DMF_BusFilter_CONFIG* config = &context->Configuration; + + FuncEntry(DMF_TRACE); + + // Forward immediately if client driver has no handler + // + if (config->EvtDeviceQueryId == NULL) + { + IoSkipCurrentIrpStackLocation(Irp); + ntStatus = IoCallDriver(DMF_BusFilter_WdmAttachedDeviceGet(ChildDevice), + Irp); + + FuncExit(DMF_TRACE, "status=%!STATUS!", ntStatus); + return ntStatus; + } + + // If client driver didn't do anything with the IRP... + // + if (!config->EvtDeviceQueryId(ChildDevice, Irp)) + { + // ...forward it prior to completion + // + if (!IoForwardIrpSynchronously(DMF_BusFilter_WdmAttachedDeviceGet(ChildDevice), + Irp)) + { + TraceError(DMF_TRACE, "IoForwardIrpSynchronously fails: Irp=0x%p", Irp); + + Irp->IoStatus.Status = STATUS_NO_SUCH_DEVICE; + } + } + + // Complete the Irp. + // + ntStatus = Irp->IoStatus.Status; + IoCompleteRequest(Irp, IO_NO_INCREMENT); + + FuncExit(DMF_TRACE, "status=%!STATUS!", ntStatus); + + return ntStatus; +} + +static +NTSTATUS +DMF_BusFilter_PnP_QueryInterface( + _In_ DMFBUSCHILDDEVICE ChildDevice, + _In_ PIRP Irp + ) +/*++ + +Routine Description: + + Handles IRP_MN_QUERY_INTERFACE. + +Arguments: + + ChildDevice - Associated child device. + Irp - IRP_MJ_PNP / IRP_MN_QUERY_INTERFACE request. + +Return Value: + + NTSTATUS + +--*/ +{ + NTSTATUS ntStatus; + const BusFilter_Context* context = BusFilterContextGet(WdfGetDriver()); + const DMF_BusFilter_CONFIG* config = &context->Configuration; + + FuncEntry(DMF_TRACE); + + // Forward immediately if client driver has no handler + // + if (config->EvtDeviceQueryInterface == NULL) + { + IoSkipCurrentIrpStackLocation(Irp); + ntStatus = IoCallDriver(DMF_BusFilter_WdmAttachedDeviceGet(ChildDevice), + Irp); + + FuncExit(DMF_TRACE, "status=%!STATUS!", ntStatus); + return ntStatus; + } + + // If client driver didn't do anything with the IRP... + // + if (!config->EvtDeviceQueryInterface(ChildDevice, Irp)) + { + // ...forward it prior to completion + // + if (!IoForwardIrpSynchronously(DMF_BusFilter_WdmAttachedDeviceGet(ChildDevice), + Irp)) + { + TraceError(DMF_TRACE, "IoForwardIrpSynchronously fails: Irp=0x%p", Irp); + + Irp->IoStatus.Status = STATUS_NO_SUCH_DEVICE; + } + } + + // Complete the Irp + // + ntStatus = Irp->IoStatus.Status; + IoCompleteRequest(Irp, IO_NO_INCREMENT); + + FuncExit(DMF_TRACE, "status=%!STATUS!", ntStatus); + + return ntStatus; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////// +// BusFilter Public Calls by Client +// + +#pragma warning(disable:4995) +#pragma code_seg("PAGE") +_IRQL_requires_max_(PASSIVE_LEVEL) +_Must_inspect_result_ +NTSTATUS +DMF_BusFilter_Initialize( + _In_ DMF_BusFilter_CONFIG* BusFilterConfig + ) +/*++ + +Routine Description: + + Called by Client Driver to initialize DMF BusFilter operations from DriverEntry(). + +Arguments: + + BusFilterConfig - Client Driver configuration parameters. + +Return Value: + + NTSTATUS + +--*/ +{ + NTSTATUS ntStatus; + WDF_OBJECT_ATTRIBUTES attributes; + BusFilter_Context* contextBusFilter; + + FuncEntry(DMF_TRACE); + + PAGED_CODE(); + + contextBusFilter = NULL; + + // Config is required + // + if (BusFilterConfig == NULL) + { + ntStatus = STATUS_INVALID_PARAMETER; + goto Exit; + } + + // Driver object must be already created + // + if (!WdfGetDriver()) + { + ntStatus = STATUS_NOT_SUPPORTED; + goto Exit; + } + + if (!BusFilterConfig->DriverObject) + { + ntStatus = STATUS_INVALID_PARAMETER; + goto Exit; + } + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, + BusFilter_Context); + + // Attach context to driver object. + // + ntStatus = WdfObjectAllocateContext(WdfGetDriver(), + &attributes, + (void**)&contextBusFilter); + if (!NT_SUCCESS(ntStatus)) + { + TraceError(DMF_TRACE, "WdfObjectAllocateContext fails: ntStatus=%!STATUS!",ntStatus); + goto Exit; + } + + // Save copy of config in context to invoke callback routines later. + // + RtlCopyMemory(&contextBusFilter->Configuration, + BusFilterConfig, + sizeof(DMF_BusFilter_CONFIG)); + + ULONG index; + PDRIVER_DISPATCH* pDispatch; + + // Store original dispatch routine pointers and overwrite with our own + // + #pragma warning(disable:28175) + for ( + index = 0, + pDispatch = BusFilterConfig->DriverObject->MajorFunction; + index <= IRP_MJ_MAXIMUM_FUNCTION; + index++, pDispatch++ + ) + { + contextBusFilter->MajorDispatchFunctions[index] = *pDispatch; + *pDispatch = DMF_BusFilter_DispatchHandler; + } + #pragma warning(default:28175) + + // PnP minor code dispatch routines + // + contextBusFilter->PnPMinorDispatchFunctions[IRP_MN_START_DEVICE] = DMF_BusFilter_PnP_StartDevice; + contextBusFilter->PnPMinorDispatchFunctions[IRP_MN_DEVICE_ENUMERATED] = DMF_BusFilter_PnP_DeviceEnumerated; + contextBusFilter->PnPMinorDispatchFunctions[IRP_MN_QUERY_ID] = DMF_BusFilter_PnP_QueryId; + contextBusFilter->PnPMinorDispatchFunctions[IRP_MN_QUERY_INTERFACE] = DMF_BusFilter_PnP_QueryInterface; + + // Clear invalid characteristics (see MS docs) + // + BusFilterConfig->DeviceCharacteristics &= ~(FILE_AUTOGENERATED_DEVICE_NAME | + FILE_CHARACTERISTIC_TS_DEVICE | + FILE_CHARACTERISTIC_WEBDAV_DEVICE | + FILE_DEVICE_IS_MOUNTED | + FILE_VIRTUAL_VOLUME); + + ntStatus = STATUS_SUCCESS; + +Exit: + + FuncExit(DMF_TRACE, "status=%!STATUS!", ntStatus); + + return ntStatus; +} +#pragma code_seg() +#pragma warning(default:4995) + +#pragma code_seg("PAGE") +NTSTATUS +DMF_BusFilter_DeviceAdd( + _In_ WDFDRIVER Driver, + _Inout_ PWDFDEVICE_INIT DeviceInit + ) +/*++ + +Routine Description: + + Creates bus WDF device. + +Arguments: + + Driver - Associated WDFDRIVER. + DeviceInit - WDF PWDFDEVICE_INIT. + +Return Value: + + NTSTATUS + +--*/ +{ + NTSTATUS ntStatus = STATUS_NOT_IMPLEMENTED; + WDF_OBJECT_ATTRIBUTES attributes; + WDFDEVICE device = NULL; + UCHAR minorPnP = IRP_MN_QUERY_DEVICE_RELATIONS; + PDMFDEVICE_INIT dmfDeviceInit = NULL; + + FuncEntry(DMF_TRACE); + + PAGED_CODE(); + + const BusFilter_Context* context = BusFilterContextGet(Driver); + const DMF_BusFilter_CONFIG* config = &context->Configuration; + + WdfFdoInitSetFilter(DeviceInit); + + // Attach IRP preprocessor. + // + ntStatus = WdfDeviceInitAssignWdmIrpPreprocessCallback(DeviceInit, + DMF_BusFilter_PreprocessQueryBusRelations, + IRP_MJ_PNP, + &minorPnP, + 1); + if (!NT_SUCCESS(ntStatus)) + { + TraceError(DMF_TRACE, "WdfDeviceInitAssignWdmIrpPreprocessCallback fails: ntStatus=%!STATUS!", ntStatus); + goto Exit; + } + + // Don't initialize with context here as client driver might decide + // to set their own context memory in EvtPreBusDeviceAdd + // + WDF_OBJECT_ATTRIBUTES_INIT(&attributes); + + // Call pre-device-creation callback, if set. + // + if (config->EvtPreBusDeviceAdd) + { + ntStatus = config->EvtPreBusDeviceAdd(Driver, + DeviceInit, + &attributes, + &dmfDeviceInit); + if (!NT_SUCCESS(ntStatus)) + { + TraceError(DMF_TRACE, "EvtPreBusDeviceAdd fails: ntStatus=%!STATUS!", ntStatus); + goto Exit; + } + } + + // Client driver is using DMF modules. + // + if (dmfDeviceInit != NULL) + { + DMF_DmfFdoSetFilter(dmfDeviceInit); + } + + // Create device object + // + ntStatus = WdfDeviceCreate(&DeviceInit, + &attributes, + &device); + if (!NT_SUCCESS(ntStatus)) + { + TraceError(DMF_TRACE, "WdfDeviceCreate fails: ntStatus=%!STATUS!", ntStatus); + goto Exit; + } + + PARENT_BUS_DEVICE_CONTEXT* parentContext = NULL; + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, + PARENT_BUS_DEVICE_CONTEXT); + + // Add bus device context. + // + ntStatus = WdfObjectAllocateContext(device, + &attributes, + (void**)&parentContext); + if (!NT_SUCCESS(ntStatus)) + { + TraceError(DMF_TRACE, "WdfObjectAllocateContext fails: ntStatus=%!STATUS!", ntStatus); + goto Exit; + } + + InitializeListHead(&parentContext->ChildList); + KeInitializeSpinLock(&parentContext->ChildListLock); + + // Call post-device-creation callback, if set. + // + if (config->EvtPostBusDeviceAdd) + { + ntStatus = config->EvtPostBusDeviceAdd(device, + dmfDeviceInit); + if (!NT_SUCCESS(ntStatus)) + { + TraceError(DMF_TRACE, "EvtPostBusDeviceAdd fails: ntStatus=%!STATUS!", ntStatus); + goto Exit; + } + } + +Exit: + + if (!NT_SUCCESS(ntStatus) && dmfDeviceInit != NULL) + { + DMF_DmfDeviceInitFree(&dmfDeviceInit); + } + + if (!NT_SUCCESS(ntStatus) && device != NULL) + { + WdfObjectDelete(device); + } + + FuncExit(DMF_TRACE, "status=%!STATUS!", ntStatus); + + return ntStatus; +} +#pragma code_seg() + +PDEVICE_OBJECT +DMF_BusFilter_WdmDeviceObjectGet( + _In_ DMFBUSCHILDDEVICE ChildDevice + ) +/*++ + +Routine Description: + + Returns DEVICE_OBJECT associated with a given DMFBUSCHILDDEVICE. + +Arguments: + + ChildDevice - The given DMFBUSCHILDDEVICE. + +Return Value: + + The associated DEVICE_OBJECT. + +--*/ +{ + const BUS_CHILD_DEVICE_CONTEXT* childContext = DMF_BusFilter_GetChildContext(ChildDevice); + + if (childContext) + { + return childContext->DeviceObject; + } + + return NULL; +} + +PDEVICE_OBJECT +DMF_BusFilter_WdmAttachedDeviceGet( + _In_ DMFBUSCHILDDEVICE ChildDevice + ) +/*++ + +Routine Description: + + Returns the attached DEVICE_OBJECT associated with a given DMFBUSCHILDDEVICE. + +Arguments: + + ChildDevice - The given DMFBUSCHILDDEVICE. + +Return Value: + + The attached DEVICE_OBJECT. + +--*/ +{ + const BUS_CHILD_DEVICE_CONTEXT* childContext = DMF_BusFilter_GetChildContext(ChildDevice); + + if (childContext) + { + const WDM_CHILD_DEVICE_EXTENSION* childExtension = (WDM_CHILD_DEVICE_EXTENSION*)childContext->DeviceObject->DeviceExtension; + + if (IsEqualGUID(&childExtension->Signature, + &GUID_DMF_BUSFILTER_SIGNATURE)) + { + return childExtension->TargetDeviceObject; + } + } + + return NULL; +} + +PDEVICE_OBJECT +DMF_BusFilter_WdmPhysicalDeviceGet( + _In_ DMFBUSCHILDDEVICE ChildDevice + ) +/*++ + +Routine Description: + + Returns the associated physical DEVICE_OBJECT associated with a given DMFBUSCHILDDEVICE. + +Arguments: + + ChildDevice - The given DMFBUSCHILDDEVICE. + +Return Value: + + The associated physical (parent) DEVICE_OBJECT. + +--*/ +{ + const BUS_CHILD_DEVICE_CONTEXT* childContext = DMF_BusFilter_GetChildContext(ChildDevice); + + if (childContext) + { + const WDM_CHILD_DEVICE_EXTENSION* childExtension = (WDM_CHILD_DEVICE_EXTENSION*)childContext->DeviceObject->DeviceExtension; + + if (IsEqualGUID(&childExtension->Signature, + &GUID_DMF_BUSFILTER_SIGNATURE)) + { + return childExtension->PhysicalDeviceObject; + } + } + + return NULL; +} + +#endif // defined(DMF_KERNEL_MODE) diff --git a/src/Dmf_BusFilter.h b/src/Dmf_BusFilter.h new file mode 100644 index 0000000..37d4981 --- /dev/null +++ b/src/Dmf_BusFilter.h @@ -0,0 +1,198 @@ +/*++ + + Copyright (c) Nefarius Software Solutions e.U. All rights reserved. + Licensed under the MIT license. + +Module Name: + + Dmf_BusFilter.h + +Abstract: + + Companion file to Dmf_BusFilter.c. + +Environment: + + Kernel-mode Driver Framework + +--*/ + +#pragma once + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Bus Filter support +///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// + +#if defined(DMF_KERNEL_MODE) + +// Declare an opaque handle representing a filtered PDO. +// +DECLARE_HANDLE(DMFBUSCHILDDEVICE); + +typedef +_Function_class_(EVT_DMF_BusFilter_PreBusDeviceAdd) +_IRQL_requires_same_ +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSTATUS +EVT_DMF_BusFilter_PreBusDeviceAdd( + _In_ WDFDRIVER Driver, + _Inout_ PWDFDEVICE_INIT DeviceInit, + _Out_ WDF_OBJECT_ATTRIBUTES* Attributes, + _Outptr_result_maybenull_ PDMFDEVICE_INIT* DmfDeviceInit + ); + +typedef +_Function_class_(EVT_DMF_BusFilter_PostBusDeviceAdd) +_IRQL_requires_same_ +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSTATUS +EVT_DMF_BusFilter_PostBusDeviceAdd( + _In_ WDFDEVICE Device, + _In_opt_ PDMFDEVICE_INIT DmfDeviceInit + ); + +typedef +_Function_class_(EVT_DMF_BusFilter_DeviceAdd) +_IRQL_requires_max_(APC_LEVEL) +_IRQL_requires_same_ +NTSTATUS +EVT_DMF_BusFilter_DeviceAdd( + _In_ WDFDEVICE Device, + _In_ DMFBUSCHILDDEVICE ChildDevice + ); + +typedef +_Function_class_(EVT_DMF_BusFilter_DeviceRemove) +_IRQL_requires_max_(PASSIVE_LEVEL) +_IRQL_requires_same_ +VOID +EVT_DMF_BusFilter_DeviceRemove( + _In_ WDFDEVICE Device, + _In_ DMFBUSCHILDDEVICE ChildDevice + ); + +typedef +_Function_class_(EVT_DMF_BusFilter_DeviceStarted) +_IRQL_requires_max_(PASSIVE_LEVEL) +_IRQL_requires_same_ +VOID +EVT_DMF_BusFilter_DeviceStarted( + _In_ DMFBUSCHILDDEVICE ChildDevice, + _In_ IRP* Irp + ); + +typedef +_Function_class_(EVT_DMF_BusFilter_DeviceEnumerated) +_IRQL_requires_max_(PASSIVE_LEVEL) +_IRQL_requires_same_ +VOID +EVT_DMF_BusFilter_DeviceEnumerated( + _In_ DMFBUSCHILDDEVICE ChildDevice, + _In_ IRP* Irp + ); + +typedef +_Function_class_(EVT_DMF_BusFilter_DeviceQueryId) +_IRQL_requires_max_(PASSIVE_LEVEL) +_IRQL_requires_same_ +BOOLEAN +EVT_DMF_BusFilter_DeviceQueryId( + _In_ DMFBUSCHILDDEVICE ChildDevice, + _In_ IRP* Irp + ); + +typedef +_Function_class_(EVT_DMF_BusFilter_DeviceQueryInterface) +_IRQL_requires_max_(PASSIVE_LEVEL) +_IRQL_requires_same_ +BOOLEAN +EVT_DMF_BusFilter_DeviceQueryInterface( + _In_ DMFBUSCHILDDEVICE ChildDevice, + _In_ IRP* Irp + ); + +typedef struct +{ + // The driver object. + // + _In_ DRIVER_OBJECT* DriverObject; + + // The device type. + // + _In_ DEVICE_TYPE DeviceType; + + // The device characteristics. + // + _In_ ULONG DeviceCharacteristics; + + // Called before bus device object is created. + // + _In_opt_ EVT_DMF_BusFilter_PreBusDeviceAdd* EvtPreBusDeviceAdd; + + // Called after bus device object was created. + // + _In_opt_ EVT_DMF_BusFilter_PostBusDeviceAdd* EvtPostBusDeviceAdd; + + // Called when child proxy device was created. + // + _In_opt_ EVT_DMF_BusFilter_DeviceAdd* EvtDeviceAdd; + + // Called when child proxy device gets removed. + // + _In_opt_ EVT_DMF_BusFilter_DeviceRemove* EvtDeviceRemove; + + // Called when IRP_MN_START_DEVICE is set to child device. + // + _In_opt_ EVT_DMF_BusFilter_DeviceStarted* EvtDeviceStarted; + + // Called when IRP_MN_DEVICE_ENUMERATED is sent to child device. + // + _In_opt_ EVT_DMF_BusFilter_DeviceEnumerated* EvtDeviceEnumerated; + + // Called when IRP_MN_QUERY_ID is sent to child device. + // + _In_opt_ EVT_DMF_BusFilter_DeviceQueryId* EvtDeviceQueryId; + + // Called when IRP_MN_QUERY_INTERFACE is sent to child device. + // + _In_opt_ EVT_DMF_BusFilter_DeviceQueryInterface* EvtDeviceQueryInterface; +} DMF_BusFilter_CONFIG; + +__forceinline +VOID +DMF_BusFilter_CONFIG_INIT( + _Out_ DMF_BusFilter_CONFIG* BusFilterConfig, + _In_ PDRIVER_OBJECT DriverObject + ) +{ + RtlZeroMemory(BusFilterConfig, + sizeof(DMF_BusFilter_CONFIG)); + BusFilterConfig->DriverObject = DriverObject; +} + +_IRQL_requires_max_(PASSIVE_LEVEL) +_Must_inspect_result_ +NTSTATUS +DMF_BusFilter_Initialize( + _In_ DMF_BusFilter_CONFIG* BusFilterConfig + ); + +EVT_WDF_DRIVER_DEVICE_ADD DMF_BusFilter_DeviceAdd; + +PDEVICE_OBJECT +DMF_BusFilter_WdmDeviceObjectGet( + _In_ DMFBUSCHILDDEVICE ChildDevice + ); + +PDEVICE_OBJECT +DMF_BusFilter_WdmAttachedDeviceGet( + _In_ DMFBUSCHILDDEVICE ChildDevice + ); + +PDEVICE_OBJECT +DMF_BusFilter_WdmPhysicalDeviceGet( + _In_ DMFBUSCHILDDEVICE ChildDevice + ); + +#endif // defined(DMF_KERNEL_MODE) diff --git a/src/Trace.h b/src/Trace.h new file mode 100644 index 0000000..50af168 --- /dev/null +++ b/src/Trace.h @@ -0,0 +1,54 @@ +#pragma once + +// From DmfTrace.h. +// ---------------- +// + +#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ + WPP_LEVEL_LOGGER(flag) + +#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ + (WPP_LEVEL_ENABLED(flag) && \ + WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) + +#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) \ + WPP_LEVEL_LOGGER(flags) + +#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) \ + (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) + +// +// This comment block is scanned by the trace preprocessor to define our +// Trace function. +// +// USEPREFIX and USESUFFIX strip all trailing whitespace, so we need to surround +// FuncExit messages with brackets +// +// begin_wpp config +// FUNC Trace{FLAG=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); +// FUNC TraceEvents(LEVEL, FLAGS, MSG, ...); +// FUNC FuncEntry{LEVEL=TRACE_LEVEL_VERBOSE}(FLAGS); +// FUNC FuncEntryArguments{LEVEL=TRACE_LEVEL_VERBOSE}(FLAGS, MSG, ...); +// FUNC FuncExit{LEVEL=TRACE_LEVEL_VERBOSE}(FLAGS, MSG, ...); +// FUNC FuncExitVoid{LEVEL=TRACE_LEVEL_VERBOSE}(FLAGS); +// FUNC TraceError{LEVEL=TRACE_LEVEL_ERROR}(FLAGS, MSG, ...); +// FUNC TraceWarning{LEVEL=TRACE_LEVEL_WARNING}(FLAGS, MSG, ...); +// FUNC TraceInformation{LEVEL=TRACE_LEVEL_INFORMATION}(FLAGS, MSG, ...); +// FUNC TraceVerbose{LEVEL=TRACE_LEVEL_VERBOSE}(FLAGS, MSG, ...); +// FUNC FuncExitNoReturn{LEVEL=TRACE_LEVEL_VERBOSE}(FLAGS); +// USEPREFIX(FuncEntry, "%!STDPREFIX! [%!FUNC!] --> Entry"); +// USEPREFIX(FuncEntryArguments, "%!STDPREFIX! [%!FUNC!] --> Entry <"); +// USEPREFIX(FuncExit, "%!STDPREFIX! [%!FUNC!] <-- Exit <"); +// USESUFFIX(FuncExit, ">"); +// USEPREFIX(FuncExitVoid, "%!STDPREFIX! [%!FUNC!] <-- Exit"); +// USEPREFIX(TraceError, "%!STDPREFIX! [%!FUNC!] ERROR:"); +// USEPREFIX(TraceWarning, "%!STDPREFIX! [%!FUNC!] WARNING:"); +// USEPREFIX(TraceEvents, "%!STDPREFIX! [%!FUNC!] "); +// USEPREFIX(TraceInformation, "%!STDPREFIX! [%!FUNC!] "); +// USEPREFIX(TraceVerbose, "%!STDPREFIX! [%!FUNC!] "); +// USEPREFIX(FuncExitNoReturn, "%!STDPREFIX! [%!FUNC!] <--"); +// CUSTOM_TYPE(SMFX_MACHINE_EXCEPTION, ItemEnum(StateMachine_MachineException)); +// CUSTOM_TYPE(SMFX_TRANSITION_TYPE, ItemEnum(StateMachine_TransitionType)); +// CUSTOM_TYPE(COMPONENT_FIRMWARE_UPDATE_V2_EVENT, ItemEnum(ComponentFirmwareUpdateV2EventId)); +// CUSTOM_TYPE(COMPONENT_FIRMWARE_UPDATE_V2_STATE, ItemEnum(ComponentFirmwareUpdateV2StateId)); +// end_wpp