diff options
| author | Jakob Lichtenberg (170957) <[email protected]> | 2024-06-28 11:39:18 -0700 |
|---|---|---|
| committer | Jakob Lichtenberg (170957) <[email protected]> | 2024-06-28 11:39:18 -0700 |
| commit | 1971c7bfc27f90764155ef96df64db4b4cfb93df (patch) | |
| tree | 9193a001a463219d073ce9ea5f1e3408a0ba3d56 | |
| parent | 3c4d58d08b74cf2925ec632ed1fe81e0d81df8a1 (diff) | |
| parent | b3af8c8f9bd508f54075da2f2516b31d05cd52c8 (diff) | |
Merge branch 'main' into user/jakobl/nuget_packagereference_instead_of_packages_configuser/jakobl/nuget_packagereference_instead_of_packages_config
51 files changed, 3883 insertions, 422 deletions
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 5faaec7b..be83c18d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -7,6 +7,9 @@ # Root files /* @microsoft/driver-samples-maintainers +# Windows Implementation Library submodule +/wil/ @microsoft/driver-samples-maintainers + # Audio /audio/ @microsoft/windowsaudio @@ -37,6 +40,7 @@ /pofx/PEP/ @microsoft/device-enumeration-and-interconnect /prm/ @microsoft/device-enumeration-and-interconnect /wmi/wmiacpi/ @microsoft/device-enumeration-and-interconnect +/general/SystemDma/ @microsoft/device-enumeration-and-interconnect # Display Kernel /video/ @microsoft/display-kernel-devs @@ -46,6 +50,7 @@ # Energy Efficiency /pofx/WDF/ @microsoft/ee-devs +/powerlimit/ @microsoft/ee-devs /simbatt/ @microsoft/ee-devs /thermal/ @microsoft/ee-devs @@ -61,8 +66,15 @@ /filesys/miniFilter/ @microsoft/filter-manager # Kernel Core +/general/cancel/ @microsoft/kernel-core +/general/event/ @microsoft/kernel-core /general/registry/ @microsoft/kernel-core +# Network Driver Platform +/network/config/ @microsoft/network-driver-platform +/network/modem/ @microsoft/network-driver-platform +/network/ndis/ @microsoft/network-driver-platform + # Network Security /network/trans/ @microsoft/netsec @@ -70,11 +82,36 @@ /security/ @microsoft/platform-integrity /TrEE/ @microsoft/platform-integrity +# PnP +/general/DCHU/ @microsoft/pnp +/setup/ @microsoft/pnp + +# Print +/print/ @microsoft/core-print +/wia/ @microsoft/core-print + # Sensors Platform /sensors/ @microsoft/sensors-platform # Storage /storage/ @microsoft/storage-core +# Windows Driver Framework (WDF) samples +/general/echo/ @microsoft/coreos-buses-and-wdf +/general/ioctl/ @microsoft/coreos-buses-and-wdf +/general/pcidrv/ @microsoft/coreos-buses-and-wdf +/general/PLX9x5x/ @microsoft/coreos-buses-and-wdf +/general/toaster/ @microsoft/coreos-buses-and-wdf +/hid/ @microsoft/coreos-buses-and-wdf +/input/ @microsoft/coreos-buses-and-wdf +/pofx/UMDF2/ @microsoft/coreos-buses-and-wdf +/serial/ @microsoft/coreos-buses-and-wdf +/spb/ @microsoft/coreos-buses-and-wdf +/usb/ @microsoft/coreos-buses-and-wdf +/wmi/wmisamp/ @microsoft/coreos-buses-and-wdf + # Windows Internet of Things /pos/ @microsoft/winiotdev + +# Wi-Fi Core +/network/wlan/ @microsoft/wi-fi-core diff --git a/.github/scripts/Install-Vsix.ps1 b/.github/scripts/Install-Vsix.ps1 new file mode 100644 index 00000000..50ef088b --- /dev/null +++ b/.github/scripts/Install-Vsix.ps1 @@ -0,0 +1,38 @@ +<#
+
+.SYNOPSIS
+Download and install the latest WDK VSIX.
+
+#>
+
+# set uri by resolving amd64 vsix
+$uri = "https://marketplace.visualstudio.com$((Invoke-WebRequest -Uri "https://marketplace.visualstudio.com/items?itemName=DriverDeveloperKits-WDK.WDKVsix").Links | Where-Object outerHTML -like '*(amd64)*' | select -expand href)"
+
+# set download version
+$uri_version = ([regex]'(\d+\.)(\d+\.)(\d+\.)(\d+)').Matches($uri).Value
+
+# set msbuild path
+$msbuild_path = (Resolve-Path "$env:ProgramFiles\Microsoft Visual Studio\2022\*\MSBuild\")
+
+# download vsix, expand, and store the downloaded version extracted from the extension manifest
+"Downloading WDK VSIX version: $uri_version..."
+Invoke-WebRequest -Uri "$uri" -OutFile wdk.zip
+"Expanding WDK VSIX archive..."
+Expand-Archive ".\wdk.zip" .\
+"Extracting version from manifest..."
+$downloaded_version = ([xml](Get-Content .\extension.vsixmanifest)).PackageManifest.Metadata.Identity.Version
+"Downloaded WDK VSIX version: $downloaded_version"
+
+# copy msbuild files, extension manifest, and check installed version from the extension manifest
+"Copying WDK extension files to build path..."
+cp (".\`$MSBuild\*", ".\extension.vsixmanifest") "$msbuild_path" -Recurse -Force
+"Extracting version from copied manifest..."
+$installed_version = ([xml](Get-Content ${msbuild_path}\extension.vsixmanifest)).PackageManifest.Metadata.Identity.Version
+"Installed WDK VSIX Version: $installed_version"
+if (-not ("$downloaded_version" -eq "$installed_version")) {
+ "WDK VSIX installation failed due to version mismatch"
+ exit 1
+}
+
+# set github environment variable for vsix version
+"SAMPLES_VSIX_VERSION=$installed_version" | Out-File -FilePath "$env:GITHUB_ENV" -Append
diff --git a/.github/workflows/Code-Scanning.yml b/.github/workflows/Code-Scanning.yml index 6915addf..cd0d8abf 100644 --- a/.github/workflows/Code-Scanning.yml +++ b/.github/workflows/Code-Scanning.yml @@ -32,31 +32,31 @@ jobs: language: [ 'cpp' ] steps: - - name: Checkout repository - uses: actions/checkout@v3 - with: - submodules: 'recursive' + - name: Checkout repository + uses: actions/checkout@v4 + with: + submodules: 'recursive' - - name: Initialize CodeQL - uses: github/codeql-action/init@v3 - with: - languages: ${{ matrix.language }} - packs: microsoft/windows-drivers - - name: Add MSBuild to PATH - uses: microsoft/[email protected] + - name: Install WDK VSIX + run: .\.github\scripts\Install-Vsix.ps1 - - name: Retrieve and build all available solutions - run: | - .\Build-AllSamples.ps1 -Verbose -ThrottleLimit 1 - env: - WDS_Configuration: Debug - WDS_Platform: x64 - WDS_WipeOutputs: ${{ true }} + - name: Install Nuget Packages + run: nuget restore .\packages.config -PackagesDirectory .\packages\ - - name: Perform CodeQL analysis - uses: github/codeql-action/analyze@v3 - with: - category: "/language:${{matrix.language}}" - - - + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + packs: microsoft/windows-drivers + + - name: Retrieve and build all available solutions + run: .\Build-AllSamples.ps1 -Verbose -ThrottleLimit 1 + env: + WDS_Configuration: Debug + WDS_Platform: x64 + WDS_WipeOutputs: ${{ true }} + + - name: Perform CodeQL analysis + uses: github/codeql-action/analyze@v3 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/ci-pr.yml b/.github/workflows/ci-pr.yml index fd2b78a6..c04f4adb 100644 --- a/.github/workflows/ci-pr.yml +++ b/.github/workflows/ci-pr.yml @@ -18,12 +18,15 @@ jobs: runs-on: windows-2022 steps: - name: Check out repository code - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: submodules: 'recursive' - - name: Add MSBuild to PATH - uses: microsoft/[email protected] + - name: Install WDK VSIX + run: .\.github\scripts\Install-Vsix.ps1 + + - name: Install Nuget Packages + run: nuget restore .\packages.config -PackagesDirectory .\packages\ - name: Get changed files id: get-changed-files @@ -54,7 +57,7 @@ jobs: if: always() steps: - name: Check out repository code - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Retrieve overview reports uses: actions/download-artifact@v3 @@ -63,8 +66,7 @@ jobs: path: _logs - name: Join and generate global reports - run: | - .\.github\scripts\Join-CsvReports.ps1 + run: .\.github\scripts\Join-CsvReports.ps1 - name: Archive global overview build reports uses: actions/upload-artifact@v3 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c4fd1a2a..c35a81ec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,16 +18,18 @@ jobs: runs-on: windows-2022 steps: - name: Check out repository code - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: submodules: 'recursive' - - name: Add MSBuild to PATH - uses: microsoft/[email protected] + - name: Install WDK VSIX + run: .\.github\scripts\Install-Vsix.ps1 + + - name: Install Nuget Packages + run: nuget restore .\packages.config -PackagesDirectory .\packages\ - name: Retrieve and build all available solutions - run: | - .\Build-AllSamples.ps1 -Verbose + run: .\Build-AllSamples.ps1 -Verbose env: WDS_Configuration: ${{ matrix.configuration }} WDS_Platform: ${{ matrix.platform }} @@ -47,7 +49,7 @@ jobs: if: always() steps: - name: Check out repository code - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Retrieve overview reports uses: actions/download-artifact@v3 @@ -56,8 +58,7 @@ jobs: path: _logs - name: Join and generate global reports - run: | - .\.github\scripts\Join-CsvReports.ps1 + run: .\.github\scripts\Join-CsvReports.ps1 - name: Archive global overview build reports uses: actions/upload-artifact@v3 diff --git a/Build-SampleSet.ps1 b/Build-SampleSet.ps1 index 8c3f6deb..9d1cc014 100644 --- a/Build-SampleSet.ps1 +++ b/Build-SampleSet.ps1 @@ -9,6 +9,14 @@ param( ) $root = Get-Location + +# launch developer powershell (if necessary to prevent multiple developer sessions) +if (-not $env:VSCMD_VER) { + Import-Module (Resolve-Path "$env:ProgramFiles\Microsoft Visual Studio\2022\*\Common7\Tools\Microsoft.VisualStudio.DevShell.dll") + Enter-VsDevShell -VsInstallPath (Resolve-Path "$env:ProgramFiles\Microsoft Visual Studio\2022\*") + cd $root +} + $ThrottleFactor = 5 $LogicalProcessors = (Get-CIMInstance -Class 'CIM_Processor' -Verbose:$false).NumberOfLogicalProcessors @@ -45,27 +53,31 @@ finally { } # -# Determine build environment: 'GitHub', 'NuGet', 'EWDK', or 'WDK'. Only used to determine build number. +# Determine build environment: 'GitHub', 'NuGet', 'EWDK', or 'WDK'. # Determine build number (used for exclusions based on build number). Five digits. Say, '22621'. +# Determine NuGet package version (if applicable). +# Determine WDK vsix version. # $build_environment="" $build_number=0 +$nuget_package_version=0 +$vsix_version="" # -# WDK NuGet will require presence of a folder 'packages' +# In Github we build using NuGet and get the version from packages and vsix version from env var set from the install vsix step. # -# -# Hack: In GitHub we do not have an environment variable where we can see WDK build number, so we have it hard coded. -# -if (-not $env:GITHUB_REPOSITORY -eq '') { +if ($env:GITHUB_REPOSITORY) { $build_environment="GitHub" - $build_number=22621 + $nuget_package_version=([regex]'(?<=x64\.)(\d+\.)(\d+\.)(\d+\.)(\d+)').Matches((Get-Childitem .\packages\*WDK.x64* -Name)).Value + $build_number=$nuget_package_version.split('.')[2] + $vsix_version = $env:SAMPLES_VSIX_VERSION } # -# Hack: If user has hydrated nuget packages, then use those. That will be indicated by presence of a folder named .\packages. +# WDK NuGet will require presence of a folder 'packages'. The version is sourced from repo .\Env-Vars.ps1. # elseif(Test-Path(".\Directory.Build.props")) { $build_environment=("NuGet") - $build_number=26074 + $nuget_package_version=([regex]'(?<=x64\.)(\d+\.)(\d+\.)(\d+\.)(\d+)').Matches((Get-Childitem .\packages\*WDK.x64* -Name)).Value + $build_number=$nuget_package_version.split('.')[2] } # # EWDK sets environment variable BuildLab. For example 'ni_release_svc_prod1.22621.2428'. @@ -91,7 +103,19 @@ else { Write-Error "Could not determine build environment." exit 1 } - +# +# Get the vsix version from packages if not set +if (-not $vsix_version) { + $vsix_version = ls "${env:ProgramData}\Microsoft\VisualStudio\Packages\Microsoft.Windows.DriverKit,version=*" | Select -ExpandProperty Name + if ($vsix_version) { + $vsix_version = $vsix_version.split('=')[1] + } + else { + Write-Error "No version of the WDK VSIX could be found. The WDK VSIX is not installed." + exit 1 + } +} +# # # InfVerif_AdditionalOptions # @@ -155,6 +179,8 @@ $SolutionsTotal = $sampleSet.Count * $Configurations.Count * $Platforms.Count Write-Output ("Build Environment: " + $build_environment) Write-Output ("Build Number: " + $build_number) +if (($build_environment -eq "GitHub") -or ($build_environment -eq "NuGet")) { Write-Output ("Nuget Package Version: " + $nuget_package_version) } +Write-Output ("WDK VSIX Version: " + $vsix_version) Write-Output ("Samples: " + $sampleSet.Count) Write-Output ("Configurations: " + $Configurations.Count + " (" + $Configurations + ")") Write-Output ("Platforms: " + $Platforms.Count + " (" + $Platforms + ")") diff --git a/Building-Locally.md b/Building-Locally.md index 77f747a0..e3db8dde 100644 --- a/Building-Locally.md +++ b/Building-Locally.md @@ -1,23 +1,58 @@ # How to build locally -## Step 1: Install Git and PowerShell 7 +## Step 1: Install Tools ``` winget install --id Microsoft.Powershell --source winget winget install --id Git.Git --source winget ``` -## Step 2: Create a "driver build environment" +For using WDK NuGet feed based build additionally: +``` +winget install --id Microsoft.NuGet --source winget +``` + +## Step 2: Optional: Disable Strong Name Validation + +When: This step is only required if you will be using pre-release versions of the WDK. + +As per https://learn.microsoft.com/en-us/windows-hardware/drivers/installing-preview-versions-wdk : + +Run the following commands from an elevated command prompt to disable strong name validation: + +``` +reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\StrongName\Verification\*,31bf3856ad364e35 /v TestPublicKey /t REG_SZ /d 00240000048000009400000006020000002400005253413100040000010001003f8c902c8fe7ac83af7401b14c1bd103973b26dfafb2b77eda478a2539b979b56ce47f36336741b4ec52bbc51fecd51ba23810cec47070f3e29a2261a2d1d08e4b2b4b457beaa91460055f78cc89f21cd028377af0cc5e6c04699b6856a1e49d5fad3ef16d3c3d6010f40df0a7d6cc2ee11744b5cfb42e0f19a52b8a29dc31b0 /f + +reg add HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\StrongName\Verification\*,31bf3856ad364e35 /v TestPublicKey /t REG_SZ /d 00240000048000009400000006020000002400005253413100040000010001003f8c902c8fe7ac83af7401b14c1bd103973b26dfafb2b77eda478a2539b979b56ce47f36336741b4ec52bbc51fecd51ba23810cec47070f3e29a2261a2d1d08e4b2b4b457beaa91460055f78cc89f21cd028377af0cc5e6c04699b6856a1e49d5fad3ef16d3c3d6010f40df0a7d6cc2ee11744b5cfb42e0f19a52b8a29dc31b0 /f +``` + +## Step 3: Optional: Install Microsoft .NET Framework 4.7.2 Targeting Pack and Microsoft .NET Framework 4.8.1 SDK + +When: This step is only required to build sample usb\usbview . + +### Option A: Install VS Components +Easy: If you will install Visual Studio (see later) you may at that point select to add both of following individual components: +* .NET Framework 4.7.2 targeting pack +* .NET Framework 4.8.1 SDK -There are multiple ways to achieve this. For example, [install Visual Studio and the Windows Driver Kit](https://learn.microsoft.com/en-us/windows-hardware/drivers/download-the-wdk#download-and-install-the-windows-11-version-22h2-wdk). +### Option B: Use EWDK +Easy: If you use EWDK, then all necessary prequisites are included. -You can also use the Enterprise WDK (EWDK), a standalone, self-contained command-line environment for building drivers: - * Download the Windows 11, version 22H2 EWDK ISO image from the [official site](https://learn.microsoft.com/en-us/legal/windows/hardware/enterprise-wdk-license-2022) - * Mount ISO image - * Open a terminal - * `.\LaunchBuildEnv` - -## Step 3: Clone Windows Driver Samples and checkout main branch +### Option C: Install Developer Pack + +Hardest: Install from https://aka.ms/msbuild/developerpacks -> '.NET Framework' -> 'Supported versions' both of following packages: +* .NET Framework 4.7.2 -> Developer Pack +* .NET Framework 4.8.1 -> Developer Pack + +This will install following Apps: +* Microsoft .NET Framework 4.7.2 SDK +* Microsoft .NET Framework 4.7.2 Targeting Pack +* Microsoft .NET Framework 4.7.2 Targeting Pack (ENU) +* Microsoft .NET Framework 4.8.1 SDK +* Microsoft .NET Framework 4.8.1 Targeting Pack +* Microsoft .NET Framework 4.8.1 Targeting Pack (ENU) + +## Step 4: Clone Windows Driver Samples and checkout relevant branch ``` cd path\to\your\repos @@ -25,7 +60,62 @@ git clone --recurse-submodules https://github.com/microsoft/Windows-driver-sampl cd Windows-driver-samples ``` -## Step 4: Check all samples builds with expected results for all flavors +If you are planning to use in-market WDK, then you would typically want to use the 'main' branch: +``` +git checkout main +``` + +If you are planning to use a WDK Preview or WDK EEAP release, then you would typically want to use the 'develop' branch: +``` +git checkout develop +``` + +## Step 5: Create a "driver build environment" + +To build the Windows Driver Samples you need a "driver build environment". In essence an environment that consist of following prerequisites: +* Visual Studio Build Tools including tools such as for example cl.exe and link.exe . +* The Windows Software Development Kit. +* The Windows Driver Kit. + +### Option A: Use WDK NuGet Packages +* See [Download the Windows Driver Kit (WDK)](https://learn.microsoft.com/en-us/windows-hardware/drivers/download-the-wdk) for instructions on how to install Visual Studio, but only complete "Step 1". You do not need to install the SDK or the WDK. +* Install the Visual Studio Windows Driver Kit Extension (WDK.vsix). + * Open Visual Studio -> Extensions -> Manage Extensions... -> Browse. + * In the search bar type: `Windows Driver Kit`. + * Find the `Microsoft` signed extension. + * Click the Install button. +* Launch a "Developer Command Prompt for VS 2022". +* Restore WDK packages from feed : + +``` +>cd path\to\your\repos\Windows-driver-samples +>nuget restore -PackagesDirectory .\packages +``` + +* When this is done you should have a .\packages folder that looks exactly as follows: +``` +>cd path\to\your\repos\Windows-driver-samples +>dir /b packages +Microsoft.Windows.SDK.CPP.10.0.26000.1 +Microsoft.Windows.SDK.CPP.x64.10.0.26000.1 +Microsoft.Windows.SDK.CPP.arm64.10.0.26000.1 +Microsoft.Windows.WDK.x64.10.0.26000.1 +Microsoft.Windows.WDK.arm64.10.0.26000.1 +``` +### Option B: Use the Windows Driver Kit +* Here you will install each of above prerequisites one at a time. +* See [Download the Windows Driver Kit (WDK)](https://learn.microsoft.com/en-us/windows-hardware/drivers/download-the-wdk) for instructions on how to install Visual Studio, SDK, and WDK. +* Launch a "Developer Command Prompt for VS 2022". + +### Option C: Use an Enterprise WDK +* You can also simply use the Enterprise WDK (EWDK), a standalone, self-contained command-line environment for building drivers that contains all prerequisites in one combined ISO. +* See [Download the Windows Driver Kit (WDK)](https://learn.microsoft.com/en-us/windows-hardware/drivers/download-the-wdk) for instructions on how to download the EWDK. +* Mount ISO image +* Open a terminal +* `.\LaunchBuildEnv` + + +## Step 6: Check all samples builds with expected results for all flavors ``` pwsh @@ -33,21 +123,42 @@ pwsh ``` Above builds all samples for all configurations and platforms. -You can refine, for example as follows: +You can refine what exact samples to build, what configurations, and platforms to build. build Here are a few examples: ``` -pwsh +# Get Help: +Get-Help .\Build-AllSamples + +# Build all solutions for all flavors with builds running in parallel: +.\Build-AllSamples + +# Build with Verbose output (print start and finish of each sample): +.\Build-AllSamples -Verbose + +# Build without massive parallism (slow, but good debugging): +.\Build-AllSamples -ThrottleLimit 1 + +# Build the solutions in the tools folder for all flavors: .\Build-AllSamples -Samples '^tools.' -Configurations 'Debug','Release' -Platforms 'x64','arm64' + +# Build the solutions in the tools folder for only 'Debug|x64': +.\Build-AllSamples -Samples '^tools.' -Configurations 'Debug' -Platforms 'x64' ``` Expected output: ``` -Samples: 153 -Configurations: 2 (Debug Release) -Platforms: 2 (x64 arm64) -Combinations: 612 -Logical Processors: 12 -Throttle factor: 5 -Throttle limit: 60 +PS > .\build-AllSamples.ps1 +Build Environment: NuGet +Build Number: 26100 +Samples: 132 +Configurations: 2 (Debug Release) +Platforms: 2 (x64 arm64) +InfVerif_AdditionalOptions: /samples +Combinations: 528 +LogicalProcessors: 12 +ThrottleFactor: 5 +ThrottleLimit: 60 +WDS_WipeOutputs: +Disk Remaining (GB): ... T: Combinations B: Built @@ -58,20 +169,51 @@ S: Built and result was 'Succeeded' E: Built and result was 'Excluded' U: Built and result was 'Unsupported' (Platform and Configuration combination) F: Built and result was 'Failed' +O: Built and result was 'Sporadic' Building all combinations... Built all combinations. -Elapsed time: 12 minutes, 34 seconds. -Samples: 153 +Elapsed time: 12 minutes, 42 seconds. +Disk Remaining (GB): ... +Samples: 132 Configurations: 2 (Debug Release) Platforms: 2 (x64 arm64) -Combinations: 612 -Succeeded: 326 -Excluded: 56 -Unsupported: 230 +Combinations: 528 +Succeeded: 526 +Excluded: 0 +Unsupported: 2 Failed: 0 +Sporadic: 0 Log files directory: .\_logs -Overview report: .\_logs\_overview.htm +Overview report: .\_overview.htm +``` + +## 7: NuGet - Additional Notes + +To restore a specific version of our WDK NuGet packages: + +Follow these steps before running "nuget restore" command: +* Open the .\packages.config file and update the full version (including the branch if required) in all three entries. +* Open the .\Directory.build.props file and update the version and build of the package with the same values as in previous step. +* Open .\Build-SampleSet and change the NuGet build number (used by .\exclusions.csv and for determining infverif flags) +* Now you can run "nuget restore" + +A few examples of how to interact with nuget: +``` +# To add an alternative online NuGet source: +nuget sources add -Name "MyNuGetFeed" -Source https://nugetserver.com/_packaging/feedname/nuget/v3/index.json + +# To add an alternative local NuGet source: +nuget sources add -Name "MyNuGetFeed" -Source \\path\to\mylocalrepo + +# To remove an alternative NuGet source: +nuget sources remove -Name "MyNuGetFeed" + +# To enumerate NuGet locals: +nuget locals all -list + +# To clear NuGet locals: +nuget locals all -clear ``` diff --git a/Directory.Build.props b/Directory.Build.props index 83d6a797..8c123e76 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,10 +1,10 @@ <Project> <ItemGroup> - <PackageReference Include="Microsoft.Windows.WDK.x64" Version="10.0.26074.1000-preview.ge-release-sigma" Condition="'$(Platform)' == 'x64'"/> - <PackageReference Include="Microsoft.Windows.WDK.arm64" Version="10.0.26074.1000-preview.ge-release-sigma" Condition="'$(Platform)' == 'ARM64'"/> - <PackageReference Include="Microsoft.Windows.SDK.CPP.x64" Version="10.0.26074.1000-preview.ge-release-sigma" Condition="'$(Platform)' == 'x64'"/> - <PackageReference Include="Microsoft.Windows.SDK.CPP.arm64" Version="10.0.26074.1000-preview.ge-release-sigma" Condition="'$(Platform)' == 'ARM64'"/> - <PackageReference Include="Microsoft.Windows.SDK.CPP" Version="10.0.26074.1000-preview.ge-release-sigma" /> + <PackageReference Include="Microsoft.Windows.WDK.x64" Version="10.0.26100.1" Condition="'$(Platform)' == 'x64'"/> + <PackageReference Include="Microsoft.Windows.WDK.arm64" Version="10.0.26100.1" Condition="'$(Platform)' == 'ARM64'"/> + <PackageReference Include="Microsoft.Windows.SDK.CPP.x64" Version="10.0.26100.1" Condition="'$(Platform)' == 'x64'"/> + <PackageReference Include="Microsoft.Windows.SDK.CPP.arm64" Version="10.0.26100.1" Condition="'$(Platform)' == 'ARM64'"/> + <PackageReference Include="Microsoft.Windows.SDK.CPP" Version="10.0.26100.1" /> </ItemGroup> <!-- https://github.com/dotnet/NuGet.BuildTasks/issues/154 --> diff --git a/configuration.dsc.yaml b/configuration.dsc.yaml index d259db24..f8245c08 100644 --- a/configuration.dsc.yaml +++ b/configuration.dsc.yaml @@ -4,19 +4,18 @@ properties: - resource: Microsoft.WinGet.DSC/WinGetPackage id: vsPackage directives: - description: Install Visual Studio Community 2022 + description: Install Visual Studio 2022 Community allowPrerelease: true settings: id: Microsoft.VisualStudio.2022.Community source: winget + useLatest: true - resource: Microsoft.VisualStudio.DSC/VSComponents id: vsComponents dependsOn: - vsPackage directives: - description: Install required VS workloads - maxVersion: "1.0.15" - allowPrerelease: true + description: Install required VS workloads and components settings: productId: Microsoft.VisualStudio.Product.Community channelId: VisualStudio.17.Release @@ -43,17 +42,26 @@ properties: - Microsoft.VisualStudio.Component.VC.MFC.ARM64 - Microsoft.VisualStudio.Component.VC.MFC.ARM64.Spectre - Microsoft.VisualStudio.Workload.NativeDesktop - - Microsoft.VisualStudio.Component.Windows11SDK.22621 + - resource: Microsoft.WinGet.DSC/WinGetPackage + id: sdkPackage + directives: + description: Install Windows SDK version 26100 + allowPrerelease: true + settings: + id: Microsoft.WindowsSDK.10.0.26100 + source: winget + useLatest: true - resource: Microsoft.WinGet.DSC/WinGetPackage id: wdkPackage dependsOn: - - vsComponents + - sdkPackage directives: - description: Install Windows Driver Kit + description: Install Windows Driver Kit version 26100 allowPrerelease: true settings: - id: Microsoft.WindowsWDK.10.0.22621 + id: Microsoft.WindowsWDK.10.0.26100 source: winget + useLatest: true - resource: PSDscResources/Script id: wdkVsix dependsOn: @@ -63,14 +71,11 @@ properties: description: Install Windows Driver Kit VSIX settings: GetScript: | - return & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -nologo -latest -products Microsoft.VisualStudio.Product.Community -requires Microsoft.Windows.DriverKit -property installationVersion + return & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -nologo -version '[17.0,18.0)' -requires Microsoft.Windows.DriverKit -property installationVersion SetScript: | - $path = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -nologo -latest -products * -property enginePath | Join-Path -ChildPath 'VSIXInstaller.exe' - if (Test-Path $path) { & $path /q "${env:ProgramFiles(x86)}\Windows Kits\10\Vsix\VS2022\10.0.22621.0\WDK.vsix" } + $installerPath = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -nologo -latest -products * -property enginePath | Join-Path -ChildPath 'VSIXInstaller.exe' + if (Test-Path $installerPath) { & $installerPath /q "${env:ProgramFiles(x86)}\Windows Kits\10\Vsix\VS2022\10.0.26100.0\${env:PROCESSOR_ARCHITECTURE}\WDK.vsix" } TestScript: | - $versionString = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -nologo -latest -products Microsoft.VisualStudio.Product.Community -requires Microsoft.Windows.DriverKit -Property installationVersion - if (-not $versionString) { return $false } - $versionArray = $versionString.Split('.') - if ($versionArray[0] -le 17) { return $false } - return $true + $versionString = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -nologo -version '[17.0,18.0)' -requires Microsoft.Windows.DriverKit -property installationVersion + return $versionString -match "^17\." configurationVersion: 0.2.0 diff --git a/configuration_vsonly.dsc.yaml b/configuration_vsonly.dsc.yaml index a46f410e..6ce4fc83 100644 --- a/configuration_vsonly.dsc.yaml +++ b/configuration_vsonly.dsc.yaml @@ -4,19 +4,18 @@ properties: - resource: Microsoft.WinGet.DSC/WinGetPackage id: vsPackage directives: - description: Install Visual Studio Community 2022 + description: Install Visual Studio 2022 Community allowPrerelease: true settings: id: Microsoft.VisualStudio.2022.Community source: winget + useLatest: true - resource: Microsoft.VisualStudio.DSC/VSComponents id: vsComponents dependsOn: - vsPackage directives: - description: Install required VS workloads - maxVersion: "1.0.15" - allowPrerelease: true + description: Install required VS workloads and components settings: productId: Microsoft.VisualStudio.Product.Community channelId: VisualStudio.17.Release diff --git a/exclusions.csv b/exclusions.csv index 6694a853..5352e0d1 100644 --- a/exclusions.csv +++ b/exclusions.csv @@ -2,4 +2,7 @@ Path,Configurations,MinBuild,MaxBuild,Reason audio\acx\samples\audiocodec\driver,*,,22621,Only NI: error C1083: Cannot open include file: 'acx.h': No such file or directory general\dchu\osrfx2_dchu_extension_loose,*|x64,,22621,Only NI: Only x64: Fails to build general\dchu\osrfx2_dchu_extension_tight,*|x64,,22621,Only NI: Only x64: Fails to build +network\trans\WFPSampler,Debug|ARM64,,22621,Only NI: Only ARM: Fails to build on EWDK 22621 with VS 17.1.5 - CallingConvention=StdCall not supported prm,*,,22621,Only NI: Not supported on NI. +powerlimit\plclient,*,,22621,Only NI: Not supported on NI. +powerlimit\plpolicy,*,,22621,Only NI: Not supported on NI. diff --git a/filesys/miniFilter/scanner/user/scanUser.c b/filesys/miniFilter/scanner/user/scanUser.c index e766261c..08b948b3 100644 --- a/filesys/miniFilter/scanner/user/scanUser.c +++ b/filesys/miniFilter/scanner/user/scanUser.c @@ -254,8 +254,6 @@ Return Value } } - free( message ); - return hr; } @@ -268,13 +266,12 @@ main ( { DWORD requestCount = SCANNER_DEFAULT_REQUEST_COUNT; DWORD threadCount = SCANNER_DEFAULT_THREAD_COUNT; - HANDLE threads[SCANNER_MAX_THREAD_COUNT]; + HANDLE threads[SCANNER_MAX_THREAD_COUNT] = { NULL }; SCANNER_THREAD_CONTEXT context; HANDLE port, completion; - PSCANNER_MESSAGE msg; + PSCANNER_MESSAGE messages; DWORD threadId; HRESULT hr; - DWORD i, j; // // Check how many threads and per thread requests are desired. @@ -343,11 +340,23 @@ main ( context.Completion = completion; // - // Create specified number of threads. + // Allocate messages. // - for (i = 0; i < threadCount; i++) { + messages = calloc(((size_t) threadCount) * requestCount, sizeof(SCANNER_MESSAGE)); + + if (messages == NULL) { + hr = ERROR_NOT_ENOUGH_MEMORY; + goto main_cleanup; + } + + // + // Create specified number of threads. + // + + for (DWORD i = 0; i < threadCount; i++) { + threads[i] = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE) ScannerWorker, @@ -366,20 +375,9 @@ main ( goto main_cleanup; } - for (j = 0; j < requestCount; j++) { - - // - // Allocate the message. - // - -#pragma prefast(suppress:__WARNING_MEMORY_LEAK, "msg will not be leaked because it is freed in ScannerWorker") - msg = malloc( sizeof( SCANNER_MESSAGE ) ); - - if (msg == NULL) { - - hr = ERROR_NOT_ENOUGH_MEMORY; - goto main_cleanup; - } + for (DWORD j = 0; j < requestCount; j++) { + + PSCANNER_MESSAGE msg = &(messages[i * requestCount + j]); memset( &msg->Ovlp, 0, sizeof( OVERLAPPED ) ); @@ -393,24 +391,26 @@ main ( &msg->Ovlp ); if (hr != HRESULT_FROM_WIN32( ERROR_IO_PENDING )) { - - free( msg ); goto main_cleanup; } } } hr = S_OK; - - WaitForMultipleObjectsEx( i, threads, TRUE, INFINITE, FALSE ); - + main_cleanup: + for (INT i = 0; threads[i] != NULL; ++i) { + WaitForSingleObjectEx(threads[i], INFINITE, FALSE); + } + printf( "Scanner: All done. Result = 0x%08x\n", hr ); CloseHandle( port ); CloseHandle( completion ); + free(messages); + return hr; } diff --git a/hid/firefly/sauron/Sauron.cpp b/hid/firefly/sauron/Sauron.cpp index 16cb12d4..36ef367b 100644 --- a/hid/firefly/sauron/Sauron.cpp +++ b/hid/firefly/sauron/Sauron.cpp @@ -445,7 +445,7 @@ HRESULT CSauron::WzToColor(const WCHAR *pwszColor, COLORREF *pcrColor) return E_POINTER; } - if (0 == lstrlenW(pwszColor)) + if (0 == wcslen(pwszColor)) { //Empty color string passed in return E_INVALIDARG; @@ -457,7 +457,7 @@ HRESULT CSauron::WzToColor(const WCHAR *pwszColor, COLORREF *pcrColor) return E_POINTER; } - if (lstrlenW(pwszColor) != 7) + if (wcslen(pwszColor) != 7) { //hex color string is not of the correct length return E_INVALIDARG; @@ -534,5 +534,3 @@ inline DWORD CSauron::SwapBytes(DWORD dwRet) { return ((dwRet & 0x0000FF00) | ((dwRet & 0x00FF0000) >> 16) | ((dwRet & 0x000000FF) << 16)); } - - diff --git a/hid/hclient/ecdisp.c b/hid/hclient/ecdisp.c index 0d15774f..28433aea 100644 --- a/hid/hclient/ecdisp.c +++ b/hid/hclient/ecdisp.c @@ -3588,8 +3588,7 @@ bSetDataDlgProc( break; } - #pragma prefast(suppress: 28750, "Banned API check.") - CharUpperBuff(DataString, lstrlen(DataString)); + CharUpperBuff(DataString, (DWORD)strlen(DataString)); if (0 == lstrcmp(DataString, "TRUE")) { diff --git a/input/kbfiltr/README.md b/input/kbfiltr/README.md index a40b084e..d7ea125b 100644 --- a/input/kbfiltr/README.md +++ b/input/kbfiltr/README.md @@ -107,4 +107,4 @@ On the target computer, in a Command Prompt window, enter **devmgmt** to open De To use the test application provided with the sample, it must be copied to the target computer manually. Save the kbftest.exe file from the folder where the build result is placed (for example, exe\\Debug). This file is copied somewhere on the target, possibly where the driver package files are located. The test application is the executed on the target computer in a Command Prompt using **kbftest** as the command. > [!TIP] -> Optional information to help a user be more successfulTo avoid DLL dependencies for kbftext.exe, and the need to copy additional files, select the statically linked run-time library when building. +> To avoid DLL dependencies for kbftext.exe, and the need to copy additional files, select the statically linked run-time library when building. diff --git a/network/trans/WFPSampler/WFPSampler.sln b/network/trans/WFPSampler/WFPSampler.sln index 1e71e3d1..4f4851d9 100644 --- a/network/trans/WFPSampler/WFPSampler.sln +++ b/network/trans/WFPSampler/WFPSampler.sln @@ -1,7 +1,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0 +# Visual Studio Version 17 +VisualStudioVersion = 17.9.34701.34 MinimumVisualStudioVersion = 12.0 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Lib", "Lib", "{7DD950F3-D068-438B-808A-EE9BE2D1F34D}" EndProject diff --git a/network/trans/WFPSampler/exe/WFPSampler.vcxproj b/network/trans/WFPSampler/exe/WFPSampler.vcxproj index 86fae1b7..3a80bd7c 100644 --- a/network/trans/WFPSampler/exe/WFPSampler.vcxproj +++ b/network/trans/WFPSampler/exe/WFPSampler.vcxproj @@ -29,18 +29,20 @@ <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <TargetVersion>Windows10</TargetVersion> <UseDebugLibraries>False</UseDebugLibraries> - <DriverTargetPlatform>Desktop</DriverTargetPlatform> + <DriverTargetPlatform>Universal</DriverTargetPlatform> <DriverType /> <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> <ConfigurationType>Application</ConfigurationType> + <Driver_SpectreMitigation>Spectre</Driver_SpectreMitigation> </PropertyGroup> <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> <TargetVersion>Windows10</TargetVersion> <UseDebugLibraries>False</UseDebugLibraries> - <DriverTargetPlatform>Desktop</DriverTargetPlatform> + <DriverTargetPlatform>Universal</DriverTargetPlatform> <DriverType /> <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> <ConfigurationType>Application</ConfigurationType> + <Driver_SpectreMitigation>Spectre</Driver_SpectreMitigation> </PropertyGroup> <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <TargetVersion>Windows10</TargetVersion> @@ -49,6 +51,7 @@ <DriverType /> <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> <ConfigurationType>Application</ConfigurationType> + <Driver_SpectreMitigation>Spectre</Driver_SpectreMitigation> </PropertyGroup> <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> <TargetVersion>Windows10</TargetVersion> @@ -57,6 +60,7 @@ <DriverType /> <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> <ConfigurationType>Application</ConfigurationType> + <Driver_SpectreMitigation>Spectre</Driver_SpectreMitigation> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <PropertyGroup> @@ -106,7 +110,6 @@ <Link> <AdditionalOptions>%(AdditionalOptions) /integritycheck</AdditionalOptions> <AdditionalDependencies>%(AdditionalDependencies);advapi32.lib;comctl32.lib;kernel32.lib;netapi32.lib;ole32.lib;oleaut32.lib;user32.lib;uuid.lib;ntdll.lib;kernel32.lib;setupapi.lib;rpcrt4.lib;fwpuclnt.lib;ws2_32.lib;.\..\lib\$(IntDir)\WFPSampler.lib</AdditionalDependencies> - <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> @@ -128,7 +131,6 @@ <Link> <AdditionalOptions>%(AdditionalOptions) /integritycheck</AdditionalOptions> <AdditionalDependencies>%(AdditionalDependencies);advapi32.lib;comctl32.lib;kernel32.lib;netapi32.lib;ole32.lib;oleaut32.lib;user32.lib;uuid.lib;ntdll.lib;kernel32.lib;setupapi.lib;rpcrt4.lib;fwpuclnt.lib;ws2_32.lib;.\..\lib\$(IntDir)\WFPSampler.lib</AdditionalDependencies> - <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> @@ -150,7 +152,6 @@ <Link> <AdditionalOptions>%(AdditionalOptions) /integritycheck</AdditionalOptions> <AdditionalDependencies>%(AdditionalDependencies);advapi32.lib;comctl32.lib;kernel32.lib;netapi32.lib;ole32.lib;oleaut32.lib;user32.lib;uuid.lib;ntdll.lib;kernel32.lib;setupapi.lib;rpcrt4.lib;fwpuclnt.lib;ws2_32.lib;.\..\lib\$(IntDir)\WFPSampler.lib</AdditionalDependencies> - <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> @@ -172,7 +173,6 @@ <Link> <AdditionalOptions>%(AdditionalOptions) /integritycheck</AdditionalOptions> <AdditionalDependencies>%(AdditionalDependencies);advapi32.lib;comctl32.lib;kernel32.lib;netapi32.lib;ole32.lib;oleaut32.lib;user32.lib;uuid.lib;ntdll.lib;kernel32.lib;setupapi.lib;rpcrt4.lib;fwpuclnt.lib;ws2_32.lib;.\..\lib\$(IntDir)\WFPSampler.lib</AdditionalDependencies> - <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries> </Link> </ItemDefinitionGroup> <ItemGroup> diff --git a/network/trans/WFPSampler/lib/WFPSampler.vcxproj b/network/trans/WFPSampler/lib/WFPSampler.vcxproj index d7889fb8..a905e396 100644 --- a/network/trans/WFPSampler/lib/WFPSampler.vcxproj +++ b/network/trans/WFPSampler/lib/WFPSampler.vcxproj @@ -30,18 +30,20 @@ <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <TargetVersion>Windows10</TargetVersion> <UseDebugLibraries>False</UseDebugLibraries> - <DriverTargetPlatform>Desktop</DriverTargetPlatform> + <DriverTargetPlatform>Universal</DriverTargetPlatform> <DriverType /> <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> <ConfigurationType>StaticLibrary</ConfigurationType> + <Driver_SpectreMitigation>Spectre</Driver_SpectreMitigation> </PropertyGroup> <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> <TargetVersion>Windows10</TargetVersion> <UseDebugLibraries>False</UseDebugLibraries> - <DriverTargetPlatform>Desktop</DriverTargetPlatform> + <DriverTargetPlatform>Universal</DriverTargetPlatform> <DriverType /> <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> <ConfigurationType>StaticLibrary</ConfigurationType> + <Driver_SpectreMitigation>Spectre</Driver_SpectreMitigation> </PropertyGroup> <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <TargetVersion>Windows10</TargetVersion> @@ -50,6 +52,7 @@ <DriverType /> <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> <ConfigurationType>StaticLibrary</ConfigurationType> + <Driver_SpectreMitigation>Spectre</Driver_SpectreMitigation> </PropertyGroup> <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> <TargetVersion>Windows10</TargetVersion> @@ -58,6 +61,7 @@ <DriverType /> <PlatformToolset>WindowsApplicationForDrivers10.0</PlatformToolset> <ConfigurationType>StaticLibrary</ConfigurationType> + <Driver_SpectreMitigation>Spectre</Driver_SpectreMitigation> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <PropertyGroup> @@ -105,8 +109,6 @@ <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;..\idl;$(SDK_INC_PATH);.\$(IntDir)</AdditionalIncludeDirectories> </ResourceCompile> <Link> - <AdditionalOptions>%(AdditionalOptions) /integritycheck</AdditionalOptions> - <AdditionalDependencies>%(AdditionalDependencies);advapi32.lib;comctl32.lib;kernel32.lib;netapi32.lib;ole32.lib;oleaut32.lib;user32.lib;uuid.lib;ntdll.lib;kernel32.lib;setupapi.lib;rpcrt4.lib;fwpuclnt.lib;ws2_32.lib</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> @@ -126,8 +128,6 @@ <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;..\idl;$(SDK_INC_PATH);.\$(IntDir)</AdditionalIncludeDirectories> </ResourceCompile> <Link> - <AdditionalOptions>%(AdditionalOptions) /integritycheck</AdditionalOptions> - <AdditionalDependencies>%(AdditionalDependencies);advapi32.lib;comctl32.lib;kernel32.lib;netapi32.lib;ole32.lib;oleaut32.lib;user32.lib;uuid.lib;ntdll.lib;kernel32.lib;setupapi.lib;rpcrt4.lib;fwpuclnt.lib;ws2_32.lib</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> @@ -147,8 +147,6 @@ <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;..\idl;$(SDK_INC_PATH);.\$(IntDir)</AdditionalIncludeDirectories> </ResourceCompile> <Link> - <AdditionalOptions>%(AdditionalOptions) /integritycheck</AdditionalOptions> - <AdditionalDependencies>%(AdditionalDependencies);advapi32.lib;comctl32.lib;kernel32.lib;netapi32.lib;ole32.lib;oleaut32.lib;user32.lib;uuid.lib;ntdll.lib;kernel32.lib;setupapi.lib;rpcrt4.lib;fwpuclnt.lib;ws2_32.lib</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> @@ -168,8 +166,6 @@ <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;..\idl;$(SDK_INC_PATH);.\$(IntDir)</AdditionalIncludeDirectories> </ResourceCompile> <Link> - <AdditionalOptions>%(AdditionalOptions) /integritycheck</AdditionalOptions> - <AdditionalDependencies>%(AdditionalDependencies);advapi32.lib;comctl32.lib;kernel32.lib;netapi32.lib;ole32.lib;oleaut32.lib;user32.lib;uuid.lib;ntdll.lib;kernel32.lib;setupapi.lib;rpcrt4.lib;fwpuclnt.lib;ws2_32.lib</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemGroup> diff --git a/network/trans/WFPSampler/svc/WFPSamplerService.vcxproj b/network/trans/WFPSampler/svc/WFPSamplerService.vcxproj index af6f39f6..1e3c0eac 100644 --- a/network/trans/WFPSampler/svc/WFPSamplerService.vcxproj +++ b/network/trans/WFPSampler/svc/WFPSamplerService.vcxproj @@ -99,6 +99,9 @@ <PreprocessorDefinitions>%(PreprocessorDefinitions);WIN32_LEAN_AND_MEAN;UNICODE;_UNICODE</PreprocessorDefinitions> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;..\lib;$(SDK_INC_PATH);.\$(IntDir);.\..\lib\$(IntDir)</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + <RuntimeTypeInfo>false</RuntimeTypeInfo> + <SDLCheck>true</SDLCheck> + <WholeProgramOptimization>true</WholeProgramOptimization> </ClCompile> <Midl> <PreprocessorDefinitions>%(PreprocessorDefinitions);WIN32_LEAN_AND_MEAN;UNICODE;_UNICODE</PreprocessorDefinitions> @@ -111,7 +114,6 @@ <Link> <AdditionalOptions>%(AdditionalOptions) /integritycheck</AdditionalOptions> <AdditionalDependencies>%(AdditionalDependencies);advapi32.lib;comctl32.lib;kernel32.lib;netapi32.lib;ole32.lib;oleaut32.lib;user32.lib;uuid.lib;ntdll.lib;setupapi.lib;rpcrt4.lib;rpcns4.lib;fwpuclnt.lib;ws2_32.lib;oneCoreUap.lib;.\..\lib\$(IntDir)\WFPSampler.lib</AdditionalDependencies> - <IgnoreSpecificDefaultLibraries>libcmt.lib;libcmtd.lib;msvcrtd.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> @@ -122,6 +124,7 @@ <PreprocessorDefinitions>%(PreprocessorDefinitions);WIN32_LEAN_AND_MEAN;UNICODE;_UNICODE</PreprocessorDefinitions> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;..\lib;$(SDK_INC_PATH);.\$(IntDir);.\..\lib\$(IntDir)</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + <SDLCheck>true</SDLCheck> </ClCompile> <Midl> <PreprocessorDefinitions>%(PreprocessorDefinitions);WIN32_LEAN_AND_MEAN;UNICODE;_UNICODE</PreprocessorDefinitions> @@ -134,7 +137,6 @@ <Link> <AdditionalOptions>%(AdditionalOptions) /integritycheck</AdditionalOptions> <AdditionalDependencies>%(AdditionalDependencies);advapi32.lib;comctl32.lib;kernel32.lib;netapi32.lib;ole32.lib;oleaut32.lib;user32.lib;uuid.lib;ntdll.lib;setupapi.lib;rpcrt4.lib;rpcns4.lib;fwpuclnt.lib;ws2_32.lib;oneCoreUap.lib;.\..\lib\$(IntDir)\WFPSampler.lib</AdditionalDependencies> - <IgnoreSpecificDefaultLibraries>libcmt.lib;libcmtd.lib;msvcrtd.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> @@ -145,6 +147,8 @@ <PreprocessorDefinitions>%(PreprocessorDefinitions);WIN32_LEAN_AND_MEAN;UNICODE;_UNICODE</PreprocessorDefinitions> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;..\lib;$(SDK_INC_PATH);.\$(IntDir);.\..\lib\$(IntDir)</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> + <RuntimeTypeInfo>false</RuntimeTypeInfo> + <SDLCheck>true</SDLCheck> </ClCompile> <Midl> <PreprocessorDefinitions>%(PreprocessorDefinitions);WIN32_LEAN_AND_MEAN;UNICODE;_UNICODE</PreprocessorDefinitions> @@ -157,7 +161,6 @@ <Link> <AdditionalOptions>%(AdditionalOptions) /integritycheck /VERBOSE:LIB</AdditionalOptions> <AdditionalDependencies>%(AdditionalDependencies);advapi32.lib;comctl32.lib;kernel32.lib;netapi32.lib;ole32.lib;oleaut32.lib;user32.lib;uuid.lib;ntdll.lib;setupapi.lib;rpcrt4.lib;rpcns4.lib;fwpuclnt.lib;ws2_32.lib;oneCoreUap.lib;.\..\lib\$(IntDir)\WFPSampler.lib</AdditionalDependencies> - <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries> <IgnoreSpecificDefaultLibraries>libcmt.lib;msvcrt.lib;msvcrtd.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries> </Link> </ItemDefinitionGroup> @@ -169,6 +172,8 @@ <PreprocessorDefinitions>%(PreprocessorDefinitions);WIN32_LEAN_AND_MEAN;UNICODE;_UNICODE</PreprocessorDefinitions> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;..\lib;$(SDK_INC_PATH);.\$(IntDir);.\..\lib\$(IntDir)</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> + <CallingConvention>StdCall</CallingConvention> + <SDLCheck>true</SDLCheck> </ClCompile> <Midl> <PreprocessorDefinitions>%(PreprocessorDefinitions);WIN32_LEAN_AND_MEAN;UNICODE;_UNICODE</PreprocessorDefinitions> @@ -181,7 +186,6 @@ <Link> <AdditionalOptions>%(AdditionalOptions) /integritycheck /VERBOSE:LIB</AdditionalOptions> <AdditionalDependencies>%(AdditionalDependencies);advapi32.lib;comctl32.lib;kernel32.lib;netapi32.lib;ole32.lib;oleaut32.lib;user32.lib;uuid.lib;ntdll.lib;setupapi.lib;rpcrt4.lib;rpcns4.lib;fwpuclnt.lib;ws2_32.lib;oneCoreUap.lib;.\..\lib\$(IntDir)\WFPSampler.lib</AdditionalDependencies> - <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries> <IgnoreSpecificDefaultLibraries>libcmt.lib;msvcrt.lib;msvcrtd.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries> </Link> </ItemDefinitionGroup> diff --git a/network/trans/WFPSampler/sys/ClassifyFunctions_BasicPacketExaminationCallouts.cpp b/network/trans/WFPSampler/sys/ClassifyFunctions_BasicPacketExaminationCallouts.cpp index 0c42a94e..cef0b6df 100644 --- a/network/trans/WFPSampler/sys/ClassifyFunctions_BasicPacketExaminationCallouts.cpp +++ b/network/trans/WFPSampler/sys/ClassifyFunctions_BasicPacketExaminationCallouts.cpp @@ -4199,6 +4199,12 @@ VOID PerformBasicPacketExaminationAtDiscard(_In_ CLASSIFY_DATA* pClassifyData) break; } + case IpDiscardIpsnpiClientDrop: + { + pDiscardReason = "IPSNPI Drop"; + + break; + } } break; diff --git a/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.InX b/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.InX index bb55b7ad..c6aad050 100644 --- a/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.InX +++ b/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.InX @@ -37,15 +37,24 @@ AddReg = WFPCalloutsClassReg [DestinationDirs] - WFPSamplerCalloutDriver.DriverFiles = 13 ;/// %WinDir%\System32\Drivers + WFPSamplerCalloutDriver.CopyFiles = 12 ;/// %WinDir%\System32\Drivers + WFPSamplerCalloutDriver.DelFiles = 12 ;/// %WinDir%\System32\Drivers [DefaultInstall.nt$ARCH$] OptionDesc = %WFPSamplerCalloutDriverDescription% - CopyFiles = WFPSamplerCalloutDriver.DriverFiles + CopyFiles = WFPSamplerCalloutDriver.CopyFiles [DefaultInstall.nt$ARCH$.Services] AddService = %WFPSamplerCalloutDriverServiceName%,,WFPSamplerCalloutDriver.Service +[DefaultUninstall.nt$ARCH$] + LegacyUninstall = 1 + DelFiles = WFPSamplerCalloutDriver.DelFiles + DelReg = WFPCalloutsClassReg + +[DefaultUninstall.nt$ARCH$.Services] + DelService = %WFPSamplerCalloutDriverServiceName%,0x200 ;/// SPSVCINST_STOPSERVICE + [WFPCalloutsClassReg] HKR,,,0 HKR,,Icon,, @@ -53,16 +62,19 @@ HKR,,DeviceCharacteristics,0x10001,0x100 ;/// FLG_ADDREG_BINVALUETYPE | FLG_ADDREG_TYPE_MULTI_SZ, FILE_DEVICE_SECURE_OPEN HKR,,Security,, ;/// Permit Generic All access to SYstem, Built-in Admin, and Local System. -[WFPSamplerCalloutDriver.DriverFiles] +[WFPSamplerCalloutDriver.CopyFiles] WFPSamplerCalloutDriver.sys,,,0x00000040 ;/// COPYFLG_OVERWRITE_OLDER_ONLY +[WFPSamplerCalloutDriver.DelFiles] + WFPSamplerCalloutDriver.sys + [WFPSamplerCalloutDriver.Service] DisplayName = %WFPSamplerCalloutDriverServiceName% Description = %WFPSamplerCalloutDriverServiceDescription% ServiceType = 1 ;/// SERVICE_KERNEL_DRIVER StartType = 0 ;/// SERVICE_BOOT_START ErrorControl = 1 ;/// SERVICE_ERROR_NORMAL - ServiceBinary = %13%\WFPSamplerCalloutDriver.sys ;/// %WinDir%\System32\Drivers\WFPSamplerCalloutDriver.sys + ServiceBinary = %12%\WFPSamplerCalloutDriver.sys ;/// %WinDir%\System32\Drivers\WFPSamplerCalloutDriver.sys LoadOrderGroup = NDIS ;/// Load immediately after TCPIP.sys Dependencies = TCPIP diff --git a/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.vcxproj b/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.vcxproj index 09bfdeba..af141891 100644 --- a/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.vcxproj +++ b/network/trans/WFPSampler/sys/WFPSamplerCalloutDriver.vcxproj @@ -47,7 +47,7 @@ <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <TargetVersion>Windows10</TargetVersion> <UseDebugLibraries>True</UseDebugLibraries> - <DriverTargetPlatform>Windows Driver</DriverTargetPlatform> + <DriverTargetPlatform>Universal</DriverTargetPlatform> <DriverType>KMDF</DriverType> <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> <ConfigurationType>Driver</ConfigurationType> @@ -55,7 +55,7 @@ <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> <TargetVersion>Windows10</TargetVersion> <UseDebugLibraries>True</UseDebugLibraries> - <DriverTargetPlatform>Windows Driver</DriverTargetPlatform> + <DriverTargetPlatform>Universal</DriverTargetPlatform> <DriverType>KMDF</DriverType> <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> <ConfigurationType>Driver</ConfigurationType> @@ -171,7 +171,7 @@ <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;.\..\syslib;$(DDK_INC_PATH)</AdditionalIncludeDirectories> </ResourceCompile> <Link> - <AdditionalDependencies>%(AdditionalDependencies);$(DDK_LIB_PATH)\NTOSKrnl.lib;$(DDK_LIB_PATH)\FwpKClnt.lib;$(DDK_LIB_PATH)\NetIO.lib;$(DDK_LIB_PATH)\NDIS.lib;$(DDK_LIB_PATH)\WDMSec.lib;UUID.lib;.\..\syslib\$(IntDir)WFPSampler.lib</AdditionalDependencies> + <AdditionalDependencies>%(AdditionalDependencies);$(DDK_LIB_PATH)\NTOSKrnl.lib;$(DDK_LIB_PATH)\FwpKClnt.lib;$(DDK_LIB_PATH)\NetIO.lib;$(DDK_LIB_PATH)\NDIS.lib;$(DDK_LIB_PATH)\WDMSec.lib;UUID.lib;.\..\syslib\$(IntDir)\WFPSampler.lib</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> @@ -190,7 +190,7 @@ <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;.\..\syslib;$(DDK_INC_PATH)</AdditionalIncludeDirectories> </ResourceCompile> <Link> - <AdditionalDependencies>%(AdditionalDependencies);$(DDK_LIB_PATH)\NTOSKrnl.lib;$(DDK_LIB_PATH)\FwpKClnt.lib;$(DDK_LIB_PATH)\NetIO.lib;$(DDK_LIB_PATH)\NDIS.lib;$(DDK_LIB_PATH)\WDMSec.lib;UUID.lib;.\..\syslib\$(IntDir)WFPSampler.lib</AdditionalDependencies> + <AdditionalDependencies>%(AdditionalDependencies);$(DDK_LIB_PATH)\NTOSKrnl.lib;$(DDK_LIB_PATH)\FwpKClnt.lib;$(DDK_LIB_PATH)\NetIO.lib;$(DDK_LIB_PATH)\NDIS.lib;$(DDK_LIB_PATH)\WDMSec.lib;UUID.lib;.\..\syslib\$(IntDir)\WFPSampler.lib</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemGroup> diff --git a/network/trans/WFPSampler/syslib/WFPSampler.vcxproj b/network/trans/WFPSampler/syslib/WFPSampler.vcxproj index 9ec9b254..cc19afc6 100644 --- a/network/trans/WFPSampler/syslib/WFPSampler.vcxproj +++ b/network/trans/WFPSampler/syslib/WFPSampler.vcxproj @@ -32,18 +32,20 @@ <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <TargetVersion>Windows10</TargetVersion> <UseDebugLibraries>False</UseDebugLibraries> - <DriverTargetPlatform>Desktop</DriverTargetPlatform> + <DriverTargetPlatform>Universal</DriverTargetPlatform> <DriverType>KMDF</DriverType> <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> <ConfigurationType>StaticLibrary</ConfigurationType> + <Driver_SpectreMitigation>Spectre</Driver_SpectreMitigation> </PropertyGroup> <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> <TargetVersion>Windows10</TargetVersion> <UseDebugLibraries>False</UseDebugLibraries> - <DriverTargetPlatform>Desktop</DriverTargetPlatform> + <DriverTargetPlatform>Universal</DriverTargetPlatform> <DriverType>KMDF</DriverType> <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> <ConfigurationType>StaticLibrary</ConfigurationType> + <Driver_SpectreMitigation>Spectre</Driver_SpectreMitigation> </PropertyGroup> <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <TargetVersion>Windows10</TargetVersion> @@ -52,6 +54,7 @@ <DriverType>KMDF</DriverType> <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> <ConfigurationType>StaticLibrary</ConfigurationType> + <Driver_SpectreMitigation>Spectre</Driver_SpectreMitigation> </PropertyGroup> <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> <TargetVersion>Windows10</TargetVersion> @@ -60,6 +63,7 @@ <DriverType>KMDF</DriverType> <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> <ConfigurationType>StaticLibrary</ConfigurationType> + <Driver_SpectreMitigation>Spectre</Driver_SpectreMitigation> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <PropertyGroup> @@ -119,7 +123,6 @@ <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;$(DDK_INC_PATH);$(IFSKIT_INC_PATH)</AdditionalIncludeDirectories> </ResourceCompile> <Link> - <AdditionalDependencies>%(AdditionalDependencies);$(DDK_LIB_PATH)\NTOSKrnl.lib;$(DDK_LIB_PATH)\FwpKClnt.lib;$(DDK_LIB_PATH)\NetIO.lib;$(DDK_LIB_PATH)\NDIS.lib;$(SDK_LIB_PATH)\UUID.lib</AdditionalDependencies> </Link> <DriverSign> <FileDigestAlgorithm>sha256</FileDigestAlgorithm> @@ -143,7 +146,6 @@ <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;$(DDK_INC_PATH);$(IFSKIT_INC_PATH)</AdditionalIncludeDirectories> </ResourceCompile> <Link> - <AdditionalDependencies>%(AdditionalDependencies);$(DDK_LIB_PATH)\NTOSKrnl.lib;$(DDK_LIB_PATH)\FwpKClnt.lib;$(DDK_LIB_PATH)\NetIO.lib;$(DDK_LIB_PATH)\NDIS.lib;$(SDK_LIB_PATH)\UUID.lib</AdditionalDependencies> </Link> <DriverSign> <FileDigestAlgorithm>sha256</FileDigestAlgorithm> @@ -167,7 +169,6 @@ <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;$(DDK_INC_PATH);$(IFSKIT_INC_PATH)</AdditionalIncludeDirectories> </ResourceCompile> <Link> - <AdditionalDependencies>%(AdditionalDependencies);$(DDK_LIB_PATH)\NTOSKrnl.lib;$(DDK_LIB_PATH)\FwpKClnt.lib;$(DDK_LIB_PATH)\NetIO.lib;$(DDK_LIB_PATH)\NDIS.lib;$(SDK_LIB_PATH)\UUID.lib</AdditionalDependencies> </Link> <DriverSign> <FileDigestAlgorithm>sha256</FileDigestAlgorithm> @@ -191,7 +192,6 @@ <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);..\inc;$(DDK_INC_PATH);$(IFSKIT_INC_PATH)</AdditionalIncludeDirectories> </ResourceCompile> <Link> - <AdditionalDependencies>%(AdditionalDependencies);$(DDK_LIB_PATH)\NTOSKrnl.lib;$(DDK_LIB_PATH)\FwpKClnt.lib;$(DDK_LIB_PATH)\NetIO.lib;$(DDK_LIB_PATH)\NDIS.lib;$(SDK_LIB_PATH)\UUID.lib</AdditionalDependencies> </Link> <DriverSign> <FileDigestAlgorithm>sha256</FileDigestAlgorithm> diff --git a/network/trans/stmedit/sys/InlineEdit.c b/network/trans/stmedit/sys/InlineEdit.c index b21cc429..2586072e 100644 --- a/network/trans/stmedit/sys/InlineEdit.c +++ b/network/trans/stmedit/sys/InlineEdit.c @@ -316,8 +316,8 @@ InlineEditClassify( // If a FIN/RST has been classified, flush any data and permit the FIN/RST. // if ((!FlowContext->bFlowActive) || - (streamData->flags & FWPS_STREAM_FLAG_SEND_DISCONNECT) || - (streamData->flags & FWPS_STREAM_FLAG_RECEIVE_DISCONNECT)) + (streamData->flags & FWPS_STREAM_FLAG_SEND_DISCONNECT) || // must also handle FWPS_STREAM_FLAG_SEND_ABORT + (streamData->flags & FWPS_STREAM_FLAG_RECEIVE_DISCONNECT)) // must also handle FWPS_STREAM_FLAG_RECEIVE_ABORT { DoTraceLevelMessage(TRACE_LEVEL_INFORMATION, CO_GENERAL, "FlowCtx %p, FIN/RST classified (Flow Active %d)!", FlowContext, FlowContext->bFlowActive); diff --git a/network/trans/stmedit/sys/stmedit.vcxproj b/network/trans/stmedit/sys/stmedit.vcxproj index aeb8cca6..acd6c422 100644 --- a/network/trans/stmedit/sys/stmedit.vcxproj +++ b/network/trans/stmedit/sys/stmedit.vcxproj @@ -22,6 +22,7 @@ <ProjectGuid>{9CE912A5-6210-4EF8-B22D-611D13254D4C}</ProjectGuid> <RootNamespace>$(MSBuildProjectName)</RootNamespace> <KMDF_VERSION_MAJOR>1</KMDF_VERSION_MAJOR> + <KMDF_VERSION_MINOR>15</KMDF_VERSION_MINOR> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">x64</Platform> <SampleGuid>{8FEDC4BC-EFA4-4BF4-91B6-E33FA555EB15}</SampleGuid> @@ -44,22 +45,19 @@ <ConfigurationType>Driver</ConfigurationType> </PropertyGroup> <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> - <TargetVersion> - </TargetVersion> + <TargetVersion>Windows10</TargetVersion> <UseDebugLibraries>True</UseDebugLibraries> - <DriverTargetPlatform> - </DriverTargetPlatform> + <DriverTargetPlatform>Universal</DriverTargetPlatform> <DriverType>KMDF</DriverType> <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> <ConfigurationType>Driver</ConfigurationType> <SupportsPackaging>false</SupportsPackaging> + <Driver_SpectreMitigation>Spectre</Driver_SpectreMitigation> </PropertyGroup> <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> - <TargetVersion> - </TargetVersion> + <TargetVersion>Windows10</TargetVersion> <UseDebugLibraries>True</UseDebugLibraries> - <DriverTargetPlatform> - </DriverTargetPlatform> + <DriverTargetPlatform>Universal</DriverTargetPlatform> <DriverType>KMDF</DriverType> <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> <ConfigurationType>Driver</ConfigurationType> @@ -97,21 +95,22 @@ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ResourceCompile> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH)</AdditionalIncludeDirectories> - <PreprocessorDefinitions>%(PreprocessorDefinitions);BINARY_COMPATIBLE=0;NT;UNICODE;_UNICODE;NDIS60;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE;NDIS60;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> </ResourceCompile> <ClCompile> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH)</AdditionalIncludeDirectories> - <PreprocessorDefinitions>%(PreprocessorDefinitions);BINARY_COMPATIBLE=0;NT;UNICODE;_UNICODE;NDIS60;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE;NDIS630;POOL_NX_OPTIN</PreprocessorDefinitions> <ExceptionHandling> </ExceptionHandling> <WppEnabled>true</WppEnabled> <WppTraceFunction>DoTraceLevelMessage(LEVEL,FLAGS,MSG,...)</WppTraceFunction> <WppModuleName>StmEdit</WppModuleName> <WppScanConfigurationData>Trace.h</WppScanConfigurationData> + <Optimization>MaxSpeed</Optimization> </ClCompile> <Midl> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH)</AdditionalIncludeDirectories> - <PreprocessorDefinitions>%(PreprocessorDefinitions);BINARY_COMPATIBLE=0;NT;UNICODE;_UNICODE;NDIS60;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE;NDIS60;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> </Midl> <Link> <AdditionalDependencies>%(AdditionalDependencies);$(DDK_LIB_PATH)\ntoskrnl.lib;$(DDK_LIB_PATH)\ndis.lib;$(DDK_LIB_PATH)\wdmsec.lib;$(DDK_LIB_PATH)\fwpkclnt.lib;uuid.lib</AdditionalDependencies> @@ -123,11 +122,11 @@ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> <ResourceCompile> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH)</AdditionalIncludeDirectories> - <PreprocessorDefinitions>%(PreprocessorDefinitions);BINARY_COMPATIBLE=0;NT;UNICODE;_UNICODE;NDIS630;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE;NDIS630;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> </ResourceCompile> <ClCompile> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH)</AdditionalIncludeDirectories> - <PreprocessorDefinitions>%(PreprocessorDefinitions);BINARY_COMPATIBLE=0;NT;UNICODE;_UNICODE;NDIS630;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE;NDIS630;POOL_NX_OPTIN</PreprocessorDefinitions> <ExceptionHandling> </ExceptionHandling> <WppEnabled>true</WppEnabled> @@ -137,7 +136,7 @@ </ClCompile> <Midl> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH)</AdditionalIncludeDirectories> - <PreprocessorDefinitions>%(PreprocessorDefinitions);BINARY_COMPATIBLE=0;NT;UNICODE;_UNICODE;NDIS630;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE;NDIS630;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> </Midl> <Link> <AdditionalDependencies>%(AdditionalDependencies);$(DDK_LIB_PATH)\ntoskrnl.lib;$(DDK_LIB_PATH)\ndis.lib;$(DDK_LIB_PATH)\wdmsec.lib;$(DDK_LIB_PATH)\fwpkclnt.lib;uuid.lib</AdditionalDependencies> @@ -149,11 +148,11 @@ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ResourceCompile> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH)</AdditionalIncludeDirectories> - <PreprocessorDefinitions>%(PreprocessorDefinitions);BINARY_COMPATIBLE=0;NT;UNICODE;_UNICODE;NDIS60;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE;NDIS60;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> </ResourceCompile> <ClCompile> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH)</AdditionalIncludeDirectories> - <PreprocessorDefinitions>%(PreprocessorDefinitions);BINARY_COMPATIBLE=0;NT;UNICODE;_UNICODE;NDIS60;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE;NDIS630;NDIS60;POOL_NX_OPTIN</PreprocessorDefinitions> <ExceptionHandling> </ExceptionHandling> <WppEnabled>true</WppEnabled> @@ -163,7 +162,7 @@ </ClCompile> <Midl> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH)</AdditionalIncludeDirectories> - <PreprocessorDefinitions>%(PreprocessorDefinitions);BINARY_COMPATIBLE=0;NT;UNICODE;_UNICODE;NDIS60;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE;NDIS60;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> </Midl> <Link> <AdditionalDependencies>%(AdditionalDependencies);$(DDK_LIB_PATH)\ntoskrnl.lib;$(DDK_LIB_PATH)\ndis.lib;$(DDK_LIB_PATH)\wdmsec.lib;$(DDK_LIB_PATH)\fwpkclnt.lib;uuid.lib</AdditionalDependencies> @@ -175,11 +174,11 @@ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> <ResourceCompile> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH)</AdditionalIncludeDirectories> - <PreprocessorDefinitions>%(PreprocessorDefinitions);BINARY_COMPATIBLE=0;NT;UNICODE;_UNICODE;NDIS630;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE;NDIS630;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> </ResourceCompile> <ClCompile> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH)</AdditionalIncludeDirectories> - <PreprocessorDefinitions>%(PreprocessorDefinitions);BINARY_COMPATIBLE=0;NT;UNICODE;_UNICODE;NDIS630;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> + <PreprocessorDefinitions>%(PreprocessorDefinitions);UNICODE;_UNICODE;NDIS630;POOL_NX_OPTIN</PreprocessorDefinitions> <ExceptionHandling> </ExceptionHandling> <WppEnabled>true</WppEnabled> @@ -189,7 +188,7 @@ </ClCompile> <Midl> <AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DDK_INC_PATH)</AdditionalIncludeDirectories> - <PreprocessorDefinitions>%(PreprocessorDefinitions);BINARY_COMPATIBLE=0;NT;UNICODE;_UNICODE;NDIS630;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> + <PreprocessorDefinitions>%(PreprocessorDefinitions)NT;UNICODE;_UNICODE;NDIS630;POOL_NX_OPTIN_AUTO</PreprocessorDefinitions> </Midl> <Link> <AdditionalDependencies>%(AdditionalDependencies);$(DDK_LIB_PATH)\ntoskrnl.lib;$(DDK_LIB_PATH)\ndis.lib;$(DDK_LIB_PATH)\wdmsec.lib;$(DDK_LIB_PATH)\fwpkclnt.lib;uuid.lib</AdditionalDependencies> diff --git a/network/trans/stmedit/sys/stmedit.vcxproj.Filters b/network/trans/stmedit/sys/stmedit.vcxproj.Filters index 662fe098..8286c235 100644 --- a/network/trans/stmedit/sys/stmedit.vcxproj.Filters +++ b/network/trans/stmedit/sys/stmedit.vcxproj.Filters @@ -33,16 +33,18 @@ </ClCompile> </ItemGroup> <ItemGroup> - <ClInclude Include="LwQueue.h"> + <ClInclude Include="*.h;*.hpp;*.hxx;*.hm;*.inl;*.xsd"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="*.h;*.hpp;*.hxx;*.hm;*.inl;*.xsd"> <Filter>Header Files</Filter> </ClInclude> - <ClInclude Include="StreamEdit.h" /> - <ClInclude Include="Trace.h" /> - <ClInclude Include="LwQueue.h"> + <ClInclude Include="*.h;*.hpp;*.hxx;*.hm;*.inl;*.xsd"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="*.h;*.hpp;*.hxx;*.hm;*.inl;*.xsd"> <Filter>Header Files</Filter> </ClInclude> - <ClInclude Include="StreamEdit.h" /> - <ClInclude Include="Trace.h" /> <ClInclude Include="*.h;*.hpp;*.hxx;*.hm;*.inl;*.xsd"> <Filter>Header Files</Filter> </ClInclude> diff --git a/network/wlan/WDI/HEADER/PlatformDef.h b/network/wlan/WDI/HEADER/PlatformDef.h index cad6fb7a..a8f4fb55 100644 --- a/network/wlan/WDI/HEADER/PlatformDef.h +++ b/network/wlan/WDI/HEADER/PlatformDef.h @@ -813,42 +813,42 @@ PlatformRequestPreAuthentication( RT_STATUS PlatformReadFile( - IN PVOID Adapter, - IN ps1Byte szFileName, - IN OUT pu1Byte pBufOfLines, - IN s4Byte nMaxNumLine, - IN s4Byte nMaxByteCntLine, - OUT ps4Byte pnNumLines + IN PVOID Adapter, + IN UNICODE_STRING* fileName, + IN OUT pu1Byte pBufOfLines, + IN s4Byte nMaxNumLine, + IN s4Byte nMaxByteCntLine, + OUT ps4Byte pnNumLinesRead ); RT_STATUS PlatformOpenFile( - IN PVOID Adapter, - IN ps1Byte szFileName, - IN OUT PRT_FILE_HANDLER pFileHandler + IN UNICODE_STRING* fileName, + IN OUT HANDLE* fileHandle ); RT_STATUS PlatformMapFile( - IN OUT PRT_FILE_HANDLER pFileHandler + IN OUT HANDLE* fileHandle, + OUT u1Byte* contentBuffer, + OUT s4Byte* contentBufferLength ); VOID PlatformUnMapFile( - IN OUT PRT_FILE_HANDLER pFileHandler + IN OUT u1Byte* contentBuffer ); VOID PlatformCloseFile( - IN OUT PRT_FILE_HANDLER pFileHandler + IN OUT HANDLE* fileHandle ); RT_STATUS PlatformReadAndMapFile( - IN PVOID Adapter, - IN ps1Byte szFileName, - IN OUT pu1Byte pOutFile, - IN OUT pu4Byte UNALIGNED pFileSize + IN UNICODE_STRING* fileName, + OUT u1Byte* outFileBuffer, + OUT u4Byte* outFileBufferLength ); BOOLEAN diff --git a/network/wlan/WDI/PLATFORM/NDIS6/Ndis6Common.c b/network/wlan/WDI/PLATFORM/NDIS6/Ndis6Common.c index d122f0c0..a8eb835d 100644 --- a/network/wlan/WDI/PLATFORM/NDIS6/Ndis6Common.c +++ b/network/wlan/WDI/PLATFORM/NDIS6/Ndis6Common.c @@ -207,85 +207,105 @@ ParseFileBufToLines( // which is a 2-dimention array, for example, // u1Byte pBufOfLines[nMaxNumLine][nMaxByteCntLine]. // -// Note: -// In NDIS5, the file to open shall be placed at the directory the same as -// driver binary. -// RT_STATUS PlatformReadFile( - IN PVOID Adapter, - IN ps1Byte szFileName, - IN OUT pu1Byte pBufOfLines, - IN s4Byte nMaxNumLine, - IN s4Byte nMaxByteCntLine, - OUT ps4Byte pnNumLinesRead + IN PVOID Adapter, + IN UNICODE_STRING* fileName, + IN OUT pu1Byte pBufOfLines, + IN s4Byte nMaxNumLine, + IN s4Byte nMaxByteCntLine, + OUT ps4Byte pnNumLinesRead ) { - RT_STATUS rtStatus = RT_STATUS_FAILURE; - NDIS_STRING NdisStrFileName; - NDIS_PHYSICAL_ADDRESS ndisPhyAddr; - NDIS_STATUS ndisStatus; - NDIS_HANDLE hFileHandle; - UINT ulFileLength; - pu1Byte pMappedFile = NULL; + RT_STATUS rtStatus = RT_STATUS_FAILURE; + OBJECT_ATTRIBUTES objectAttributes; + HANDLE fileHandle; + IO_STATUS_BLOCK iostatBlock; + NTSTATUS ntStatus; - // Check input parameters. - if(szFileName == NULL) - { - RT_TRACE(COMP_INIT, DBG_WARNING, ("PlatformReadFile(): szFileName should not be NULL!\n")); - return rtStatus; - } + // Check Input parameters. if(pBufOfLines == NULL) { RT_TRACE(COMP_INIT, DBG_WARNING, ("PlatformReadFile(): pBufOfLines should not be NULL!\n")); return rtStatus; } - // Convert szFileName to NDIS_STRING. - NdisInitializeString(&NdisStrFileName, (PUCHAR)szFileName); - if(NdisStrFileName.Buffer != NULL && NdisStrFileName.Length > 0) - { - // Open the file specified. - ndisPhyAddr.LowPart = ndisPhyAddr.HighPart = -1; - NdisOpenFile(&ndisStatus, - &hFileHandle, - &ulFileLength, - &NdisStrFileName, - ndisPhyAddr); - if(ndisStatus == NDIS_STATUS_SUCCESS) - { - // Map the file into memory. - NdisMapFile(&ndisStatus, (PVOID *)(&pMappedFile), hFileHandle); - if(ndisStatus == NDIS_STATUS_SUCCESS) - { - // Read the file into pBufOfLines. - ParseFileBufToLines(Adapter, pMappedFile, ulFileLength, pBufOfLines, nMaxNumLine, nMaxByteCntLine, pnNumLinesRead); - - // Return Success only when Config Success - rtStatus = RT_STATUS_SUCCESS; - - // Relase the memory for mapping the file. - NdisUnmapFile(hFileHandle); + // Initialize the object attributes of the file we want to open + InitializeObjectAttributes( + &objectAttributes, + fileName, + OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, + NULL, // RootDirectory + NULL // Default Security + ); + + // Open the file using the object attributes to get a Handle + ntStatus = ZwOpenFile( + &fileHandle, + GENERIC_READ, + &objectAttributes, + &iostatBlock, + 0, // Do not share the file + FILE_NON_DIRECTORY_FILE + ); + + if (NT_SUCCESS(ntStatus)) { + FILE_STANDARD_INFORMATION fileInformation = { 0 }; + + // Get the file information to know the size we need to alloc + ntStatus = ZwQueryInformationFile( + fileHandle, + &iostatBlock, + &fileInformation, + sizeof(fileInformation), + FileStandardInformation + ); + + if (NT_SUCCESS(ntStatus)) { + u1Byte* buffer = NULL; + s4Byte bufferLength = (s4Byte)fileInformation.EndOfFile.QuadPart; + + // Try to allocate space to read the file + buffer = ExAllocatePool2(POOL_FLAG_NON_PAGED, bufferLength, 'frP'); + if (buffer) { + + // If alloc was successful, then read the file + ntStatus = ZwReadFile( + fileHandle, + NULL, + NULL, + NULL, + &iostatBlock, + buffer, + bufferLength, + 0, // No offset + NULL + ); + + if (NT_SUCCESS(ntStatus)) { + // Read the buffer into pBufOfLines. + ParseFileBufToLines(Adapter, buffer, bufferLength, pBufOfLines, nMaxNumLine, nMaxByteCntLine, pnNumLinesRead); + rtStatus = RT_STATUS_SUCCESS; + } + else { + RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadFile(): failed to read file, ntStatus: %#X\n", ntStatus)); + } + + ExFreePool(buffer); + } - else - { - RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadFile(): failed to map the file, %s!, ndisStatus: %#X\n", szFileName, ndisStatus)); + else { + RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadFile(): failed to allocate space for file!\n")); } - - // Close the file. - NdisCloseFile(hFileHandle); } - else - { - RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadFile(): failed to open the file, %s!, ndisStatus: %#X\n", szFileName, ndisStatus)); + else { + RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadFile(): failed to read file attributes!, ntStatus: %#X\n", ntStatus)); } - - // Release the NDIS_STRING allocated via NdisInitializeString(). - NdisFreeString(NdisStrFileName); + + ZwClose(fileHandle); } - else - { - RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadFile(): NdisInitializeString() failed! szFileName: %s\n", szFileName)); + else { + RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadFile(): failed to open the file!, ntStatus: %#X\n", ntStatus)); } return rtStatus; @@ -293,51 +313,39 @@ PlatformReadFile( RT_STATUS PlatformOpenFile( - IN PVOID Adapter, - IN ps1Byte szFileName, - IN OUT PRT_FILE_HANDLER pFileHandler + IN UNICODE_STRING* fileName, + IN OUT HANDLE* fileHandle ) { - RT_STATUS rtStatus = RT_STATUS_FAILURE; - NDIS_STRING NdisStrFileName; - NDIS_PHYSICAL_ADDRESS ndisPhyAddr; - NDIS_STATUS ndisStatus; - pu1Byte pMappedFile = NULL; + RT_STATUS rtStatus = RT_STATUS_FAILURE; + OBJECT_ATTRIBUTES objectAttributes; + IO_STATUS_BLOCK iostatBlock; + NTSTATUS ntStatus; - - // Check input parameters. - if(szFileName == NULL) - { - RT_TRACE(COMP_INIT, DBG_LOUD, ("PlatformOpenFile(): szFileName should not be NULL!\n")); - return rtStatus; - } + // Initialize the object attributes of the file we want to open + InitializeObjectAttributes( + &objectAttributes, + fileName, + OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, + NULL, // RootDirectory + NULL // Default Security + ); - // Convert szFileName to NDIS_STRING. - NdisInitializeString(&NdisStrFileName, (PUCHAR)szFileName); - if(NdisStrFileName.Buffer != NULL && NdisStrFileName.Length > 0) - { - // Open the file specified. - ndisPhyAddr.LowPart = ndisPhyAddr.HighPart = -1; - NdisOpenFile(&ndisStatus, - &(pFileHandler->FileHandler), - &(pFileHandler->FileLength), - &NdisStrFileName, - ndisPhyAddr); - - NdisFreeString(NdisStrFileName); - if(ndisStatus == NDIS_STATUS_SUCCESS) - { - rtStatus = RT_STATUS_SUCCESS; - } - else - { - RT_TRACE(COMP_INIT, DBG_LOUD, ("PlatformOpenFile(): failed to open the file, %s!, ndisStatus: %#X\n", szFileName, ndisStatus)); - } - + // Open the file using the object attributes to get a Handle + ntStatus = ZwOpenFile( + fileHandle, + GENERIC_READ, + &objectAttributes, + &iostatBlock, + 0, // Do not share the file + FILE_NON_DIRECTORY_FILE + ); + + if (NT_SUCCESS(ntStatus)) { + rtStatus = RT_STATUS_SUCCESS; } - else - { - RT_TRACE(COMP_INIT, DBG_LOUD, ("PlatformOpenFile(): NdisInitializeString() failed! szFileName: %s\n", szFileName)); + else { + RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadFile(): failed to open the file!, ntStatus: %#X, fileName: %wZ\n", ntStatus, fileName)); } return rtStatus; @@ -345,20 +353,66 @@ PlatformOpenFile( RT_STATUS PlatformMapFile( - IN OUT PRT_FILE_HANDLER pFileHandler + IN OUT HANDLE* fileHandle, + OUT u1Byte* contentBuffer, + OUT s4Byte* contentBufferLength ) { - RT_STATUS rtStatus = RT_STATUS_FAILURE; - NDIS_STATUS ndisStatus; - - // Map the file into memory. - NdisMapFile(&ndisStatus, (PVOID *)(&(pFileHandler->MappedFile)), pFileHandler->FileHandler); - if(ndisStatus == NDIS_STATUS_SUCCESS) { - rtStatus = RT_STATUS_SUCCESS; + RT_STATUS rtStatus = RT_STATUS_FAILURE; + OBJECT_ATTRIBUTES objectAttributes; + IO_STATUS_BLOCK iostatBlock; + NTSTATUS ntStatus; + + + FILE_STANDARD_INFORMATION fileInformation = { 0 }; + + // Get the file information to know the size we need to alloc + ntStatus = ZwQueryInformationFile( + *fileHandle, + &iostatBlock, + &fileInformation, + sizeof(fileInformation), + FileStandardInformation + ); + + if (NT_SUCCESS(ntStatus)) { + u1Byte* buffer = NULL; + s4Byte bufferLength = (s4Byte)fileInformation.EndOfFile.QuadPart; + + // Try to allocate space to read the file + buffer = ExAllocatePool2(POOL_FLAG_NON_PAGED, bufferLength, 'frP'); + if (buffer) { + + // If alloc was successful, then read the file + ntStatus = ZwReadFile( + fileHandle, + NULL, + NULL, + NULL, + &iostatBlock, + buffer, + bufferLength, + 0, // No offset + NULL + ); + + if (NT_SUCCESS(ntStatus)) { + contentBuffer = buffer; + *contentBufferLength = bufferLength; + rtStatus = RT_STATUS_SUCCESS; + } + else { + ExFreePool(buffer); + RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadFile(): failed to read file, ntStatus: %#X\n", ntStatus)); + } + } + else { + RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadFile(): failed to allocate space for file!\n")); + } } else { - RT_TRACE(COMP_INIT, DBG_LOUD, ("PlatformMapFile(): failed to map the file!, ndisStatus: %#X\n", ndisStatus)); + RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadFile(): failed to read file attributes!, ntStatus: %#X\n", ntStatus)); } return rtStatus; @@ -366,22 +420,65 @@ PlatformMapFile( VOID PlatformUnMapFile( - IN OUT PRT_FILE_HANDLER pFileHandler + IN OUT u1Byte* contentBuffer ) { // Relase the memory for mapping the file. - NdisUnmapFile(pFileHandler->FileHandler); + ExFreePool(contentBuffer); } + VOID PlatformCloseFile( - IN OUT PRT_FILE_HANDLER pFileHandler + IN OUT HANDLE* fileHandle ) { // Relase the memory for mapping the file. - NdisCloseFile(pFileHandler->FileHandler); + ZwClose(fileHandle); +} + +// +// Description: +// Open the file specifed and copy the file into an byte buffer, +// +RT_STATUS +PlatformReadAndMapFile( + IN UNICODE_STRING* fileName, + OUT u1Byte* outFileBuffer, + OUT u4Byte* outFileBufferLength +) +{ + RT_STATUS rtStatus = RT_STATUS_FAILURE; + HANDLE fileHandle; + RT_STATUS callStatus; + + callStatus = PlatformOpenFile(fileName, &fileHandle); + + if (callStatus == RT_STATUS_SUCCESS) { + u1Byte* fileBuffer = NULL; + u4Byte* fileBufferLength = NULL; + + callStatus = PlatformMapFile(&fileHandle, fileBuffer, fileBufferLength); + + if (callStatus == RT_STATUS_SUCCESS) { + outFileBuffer = fileBuffer; + outFileBufferLength = fileBufferLength; + rtStatus = RT_STATUS_SUCCESS; + } + else { + RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadAndMapFile(): failed to map file!, rtStatus: %#X\n", callStatus)); + } + + PlatformCloseFile(fileHandle); + } + else { + RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadAndMapFile(): failed to open the file!, rtStatus: %#X\n", callStatus)); + } + + return rtStatus; } + // // Description: // Indication for PHY power state changed. @@ -2722,85 +2819,6 @@ N6InitializeNative80211MIBs( Adapter->pNdisCommon->PrivacyExemptionEntrieNum = 0; } -// -// Description: -// Open the file specifed and copy the file into an array, -// -RT_STATUS -PlatformReadAndMapFile( - IN PVOID Adapter, - IN ps1Byte szFileName, - IN OUT pu1Byte pOutFile, - IN OUT pu4Byte UNALIGNED pFileSize - ) -{ - RT_STATUS rtStatus = RT_STATUS_FAILURE; - NDIS_STRING NdisStrFileName; - NDIS_PHYSICAL_ADDRESS ndisPhyAddr; - NDIS_STATUS ndisStatus; - NDIS_HANDLE hFileHandle; - UINT ulFileLength; - pu1Byte pMappedFile = NULL; - - // Check input parameters. - if(szFileName == NULL) - { - RT_TRACE(COMP_INIT, DBG_WARNING, ("PlatformReadAndMapFile(): szFileName should not be NULL!\n")); - return rtStatus; - } - - - // Convert szFileName to NDIS_STRING. - NdisInitializeString(&NdisStrFileName, (PUCHAR)szFileName); - if(NdisStrFileName.Buffer != NULL && NdisStrFileName.Length > 0) - { - // Open the file specified. - ndisPhyAddr.LowPart = ndisPhyAddr.HighPart = -1; - NdisOpenFile(&ndisStatus, - &hFileHandle, - &ulFileLength, - &NdisStrFileName, - ndisPhyAddr); - if(ndisStatus == NDIS_STATUS_SUCCESS) - { - // Map the file into memory. - NdisMapFile(&ndisStatus, (PVOID *)(&pMappedFile), hFileHandle); - if(ndisStatus == NDIS_STATUS_SUCCESS) - { - // Copy File into array - PlatformMoveMemory(pOutFile, pMappedFile, ulFileLength); - *pFileSize = ulFileLength; - - // Return Success only when Config Success - rtStatus = RT_STATUS_SUCCESS; - - // Relase the memory for mapping the file. - NdisUnmapFile(hFileHandle); - } - else - { - RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadAndMapFile(): failed to map the file, %s!, ndisStatus: %#X\n", szFileName, ndisStatus)); - } - - // Close the file. - NdisCloseFile(hFileHandle); - } - else - { - RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadAndMapFile(): failed to open the file, %s!, ndisStatus: %#X\n", szFileName, ndisStatus)); - } - - // Release the NDIS_STRING allocated via NdisInitializeString(). - NdisFreeString(NdisStrFileName); - } - else - { - RT_TRACE(COMP_INIT, DBG_SERIOUS, ("PlatformReadAndMapFile(): NdisInitializeString() failed! szFileName: %s\n", szFileName)); - } - - return rtStatus; -} - // // Description: diff --git a/network/wwan/cxwmbclass/sources.inc b/network/wwan/cxwmbclass/sources.inc deleted file mode 100644 index 7b1e526c..00000000 --- a/network/wwan/cxwmbclass/sources.inc +++ /dev/null @@ -1,12 +0,0 @@ -MBBCX_MAJOR_VERSION=1 -MBBCX_MINOR_VERSION=0 - -MBBCX_VERSION=$(MBBCX_MAJOR_VERSION).$(MBBCX_MINOR_VERSION) - -MBBCX_DDK_INC_PATH=$(ONECORE_EXTERNAL_DDK_INC_PATH)\mbbcx\$(MBBCX_VERSION) -MBBCX_DDK_LIB_PATH=$(ONECORE_EXTERNAL_DDK_LIB_PATH)\mbbcx\$(MBBCX_VERSION) - -KMDF_VERSION_MAJOR=1 -KMDF_VERSION_MINOR=31 -KMDF_VERSION=$(KMDF_VERSION_MAJOR).$(KMDF_VERSION_MINOR) -KMDF_DDK_INC_PATH=$(ONECORE_INTERNAL_DDK_INC_PATH)\wdf\kmdf\$(KMDF_VERSION); diff --git a/powerlimit/plclient/README.md b/powerlimit/plclient/README.md new file mode 100644 index 00000000..8ee71011 --- /dev/null +++ b/powerlimit/plclient/README.md @@ -0,0 +1,17 @@ +--- +page_type: sample +description: "Demonstrates a simulated power limit device." +languages: +- cpp +products: +- windows +- windows-wdk +--- + +# plclient - Simulated Power Limit Client Driver + +This sample is a driver for a simulated power limit client device. + +## Universal Windows Driver Compliant + +The plclient sample provides the source code for a power limit device that supports power limit management by the operating system. diff --git a/powerlimit/plclient/plclient.asl b/powerlimit/plclient/plclient.asl new file mode 100644 index 00000000..ce0458df --- /dev/null +++ b/powerlimit/plclient/plclient.asl @@ -0,0 +1,10 @@ +DefinitionBlock ("ACPITABL.DAT", "SSDT", 0x02, "MSFT", "simulatr", 0x1) { + Device (\_SB.SOC0) { + Name (_HID, "PLCL0001") + Name (_UID, 1) + } + Device (\_SB.GPU1) { + Name (_HID, "PLCL0001") + Name (_UID, 2) + } +}
\ No newline at end of file diff --git a/powerlimit/plclient/plclient.c b/powerlimit/plclient/plclient.c new file mode 100644 index 00000000..41676590 --- /dev/null +++ b/powerlimit/plclient/plclient.c @@ -0,0 +1,451 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + +Module Name: + + plclient.c + +Abstract: + + This module implements power limit related operations for the simulated power + limit client driver. + +--*/ + +//-------------------------------------------------------------------- Includes + +#include "plclient.h" + +//--------------------------------------------------------------------- Pragmas + +#pragma alloc_text(PAGE, InitPowerLimitValues) +#pragma alloc_text(PAGE, CleanupPowerLimitValues) +#pragma alloc_text(PAGE, PLCQueryAttributes) +#pragma alloc_text(PAGE, PLCSetLimits) +#pragma alloc_text(PAGE, PLCQueryLimitValues) + +//------------------------------------------------------------------- Functions + +_Use_decl_annotations_ +NTSTATUS +InitPowerLimitValues ( + PFDO_DATA DevExt + ) + +/*++ + +Routine Description: + + This routine initializes simulated limit values and attributes for the supplied + device extension. + +Parameters Description: + + DevExt - Supplies a pointer to the device extension to be udpated. + +Return Value: + + NTSTATUS. + +--*/ + +{ + + ULONG DomainId; + ULONG Index; + PPOWER_LIMIT_ATTRIBUTES LimitAttributes; + ULONG LimitCount; + PPOWER_LIMIT_VALUE LimitValues; + NTSTATUS Status; + ULONG Type; + + PAGED_CODE(); + + LimitAttributes = NULL; + LimitValues = NULL; + LimitCount = PLCLIENT_DEFAULT_DOMAIN_COUNT * PLCLIENT_DEFAULT_LIMIT_COUNT_PER_DOMAIN; + LimitAttributes = ExAllocatePool2(POOL_FLAG_PAGED, + LimitCount * sizeof(POWER_LIMIT_ATTRIBUTES), + PLCLIENT_TAG); + + LimitValues = ExAllocatePool2(POOL_FLAG_PAGED, + LimitCount * sizeof(POWER_LIMIT_VALUE), + PLCLIENT_TAG); + + if ((LimitAttributes == NULL) || (LimitValues == NULL)) { + Status = STATUS_INSUFFICIENT_RESOURCES; + goto InitPowerLimitValuesEnd; + } + + for (DomainId = 0; DomainId < PLCLIENT_DEFAULT_DOMAIN_COUNT; DomainId += 1) { + for (Type = 0; Type < PLCLIENT_DEFAULT_LIMIT_COUNT_PER_DOMAIN; Type += 1) { + Index = (PLCLIENT_DEFAULT_LIMIT_COUNT_PER_DOMAIN * DomainId) + Type; + + // + // Set init attributes. + // + + LimitAttributes[Index].Type = Type; + LimitAttributes[Index].DomainId = DomainId; + LimitAttributes[Index].MaxValue = PLCLIENT_DEFAULT_MAX_VALUE; + LimitAttributes[Index].MinValue = PLCLIENT_DEFAULT_MIN_VALUE; + LimitAttributes[Index].DefaultACValue = POWER_LIMIT_VALUE_NO_CONTROL; + LimitAttributes[Index].DefaultDCValue = POWER_LIMIT_VALUE_NO_CONTROL; + + if (Type == PowerLimitContinuous) { + LimitAttributes[Index].MinTimeParameter = PLCLIENT_DEFAULT_MIN_VALUE; + LimitAttributes[Index].MaxTimeParameter = PLCLIENT_DEFAULT_MAX_VALUE; + LimitAttributes[Index].Flags.SupportTimeParameter = 1; + } + + // + // Set init values. + // + + LimitValues[Index].Type = Type; + LimitValues[Index].DomainId = DomainId; + LimitValues[Index].TargetValue = POWER_LIMIT_VALUE_NO_CONTROL; + LimitValues[Index].TimeParameter = POWER_LIMIT_VALUE_NO_CONTROL; + } + } + + DevExt->LimitCount = LimitCount; + DevExt->LimitAttributes = LimitAttributes; + DevExt->LimitValues = LimitValues; + LimitAttributes = NULL; + LimitValues = NULL; + Status = STATUS_SUCCESS; + +InitPowerLimitValuesEnd: + if (LimitAttributes != NULL) { + ExFreePoolWithTag(LimitAttributes, PLCLIENT_TAG); + LimitAttributes = NULL; + } + + if (LimitValues != NULL) { + ExFreePoolWithTag(LimitValues, PLCLIENT_TAG); + LimitValues = NULL; + } + + return Status; +} + +_Use_decl_annotations_ +VOID +CleanupPowerLimitValues ( + PFDO_DATA DevExt + ) + +/*++ + +Routine Description: + + This routine cleans up simulated limit values and attributes for the supplied + device extension. + +Parameters Description: + + DevExt - Supplies a pointer to the device extension to be udpated. + +Return Value: + + NTSTATUS. + +--*/ + +{ + + PAGED_CODE(); + + if (DevExt == NULL) { + goto CleanupPowerLimitValuesEnd; + } + + if (DevExt->LimitAttributes != NULL) { + ExFreePoolWithTag(DevExt->LimitAttributes, PLCLIENT_TAG); + DevExt->LimitAttributes = NULL; + } + + if (DevExt->LimitValues != NULL) { + ExFreePoolWithTag(DevExt->LimitValues, PLCLIENT_TAG); + DevExt->LimitValues = NULL; + } + + DevExt->LimitCount = 0; + +CleanupPowerLimitValuesEnd: + return; +} + +_Use_decl_annotations_ +NTSTATUS +PLCQueryAttributes ( + PVOID Context, + ULONG BufferCount, + PVOID Buffer, + PULONG AttributeCount + ) + +/*++ + +Routine Description: + + This is the callback function which returns power limit attributes. + +Parameters Description: + + Context - Supplies a pointer to the device handle. + + BufferCount - Supplies count of Buffer entries. + + Buffer - Supplies a pointer to the buffer to store power limit attributes. + + AttributeCount - Supplies a pointer to save the number of attributes. + +Return Value: + + Returns STATUS_BUFFER_TOO_SMALL if the supplied buffer is not big enough, otherwise + other NTSTATUS values. + +--*/ + +{ + + PFDO_DATA DevExt; + WDFDEVICE DeviceHandle; + BOOLEAN ReleaseLock; + NTSTATUS Status; + + PAGED_CODE(); + + ReleaseLock = FALSE; + if (Context == NULL) { + Status = STATUS_INVALID_PARAMETER; + goto QueryAttributesEnd; + } + + DeviceHandle = (WDFDEVICE)Context; + DevExt = GetDeviceExtension(DeviceHandle); + AcquireGlobalMutex(); + ReleaseLock = TRUE; + if (BufferCount < DevExt->LimitCount) { + if (AttributeCount != NULL) { + *AttributeCount = DevExt->LimitCount; + } + + Status = STATUS_BUFFER_TOO_SMALL; + goto QueryAttributesEnd; + } + + RtlCopyMemory(Buffer, + DevExt->LimitAttributes, + sizeof(POWER_LIMIT_ATTRIBUTES) * DevExt->LimitCount); + + Status = STATUS_SUCCESS; + +QueryAttributesEnd: + if (ReleaseLock != FALSE) { + ReleaseGlobalMutex(); + } + + return Status; +} + +_Use_decl_annotations_ +NTSTATUS +PLCSetLimits ( + PVOID Context, + ULONG ValueCount, + PVOID Values + ) + +/*++ + +Routine Description: + + This is the callback function which takes requests to set power limit values. + +Parameters Description: + + Context - Supplies a pointer to the device handle. + + ValueCount - Supplies count of Value entries. + + Values - Supplies a pointer to the buffer contains values to be updated. + +Return Value: + + NTSTATUS. + +--*/ + +{ + + PPOWER_LIMIT_ATTRIBUTES Attributes; + PFDO_DATA DevExt; + WDFDEVICE DeviceHandle; + ULONG Index; + BOOLEAN ReleaseLock; + NTSTATUS Status; + BOOLEAN Valid; + PPOWER_LIMIT_VALUE ValueBuffer; + ULONG ValueIndex; + + PAGED_CODE(); + + ReleaseLock = FALSE; + if ((Context == NULL) || (ValueCount == 0) || (Values == NULL)) { + Status = STATUS_INVALID_PARAMETER; + goto SetLimitsEnd; + } + + ValueBuffer = (PPOWER_LIMIT_VALUE)Values; + DeviceHandle = (WDFDEVICE)Context; + DevExt = GetDeviceExtension(DeviceHandle); + AcquireGlobalMutex(); + ReleaseLock = TRUE; + + // + // Sanity check on proposed values before update. + // + + if (DevExt->LimitCount < ValueCount) { + Status = STATUS_INVALID_PARAMETER; + goto SetLimitsEnd; + } + + // + // N.B. On a production driver, those values should be used as power limit targets + // for the hardware. + // + + for (Index = 0; Index < ValueCount; Index += 1) { + Valid = FALSE; + for (ValueIndex = 0; ValueIndex < DevExt->LimitCount; ValueIndex += 1) { + if ((ValueBuffer[Index].Type != DevExt->LimitAttributes[ValueIndex].Type) || + (ValueBuffer[Index].DomainId != DevExt->LimitAttributes[ValueIndex].DomainId)) { + + continue; + } + + Attributes = &DevExt->LimitAttributes[ValueIndex]; + if ((ValueBuffer[Index].TargetValue == POWER_LIMIT_VALUE_NO_CONTROL) || + ((ValueBuffer[Index].TargetValue >= Attributes->MinValue) && + (ValueBuffer[Index].TargetValue <= Attributes->MaxValue))) { + + Valid = TRUE; + } + + if (ValueBuffer[Index].TimeParameter != POWER_LIMIT_VALUE_NO_CONTROL) { + if ((Attributes->Flags.SupportTimeParameter != 0) && + (ValueBuffer[Index].TimeParameter >= Attributes->MinTimeParameter) && + (ValueBuffer[Index].TimeParameter <= Attributes->MaxTimeParameter)) { + + Valid = TRUE; + } + } + + break; + } + + // + // N.B. Bail out if this proposed value is not valid. + // + + if (Valid == FALSE) { + Status = STATUS_INVALID_PARAMETER; + goto SetLimitsEnd; + } + } + + for (Index = 0; Index < ValueCount; Index += 1) { + for (ValueIndex = 0; ValueIndex < DevExt->LimitCount; ValueIndex += 1) { + if ((ValueBuffer[Index].Type != DevExt->LimitValues[ValueIndex].Type) || + (ValueBuffer[Index].DomainId != DevExt->LimitValues[ValueIndex].DomainId)) { + + continue; + } + + DevExt->LimitValues[ValueIndex].TargetValue = ValueBuffer[Index].TargetValue; + DevExt->LimitValues[ValueIndex].TimeParameter = ValueBuffer[Index].TimeParameter; + break; + } + } + + Status = STATUS_SUCCESS; + +SetLimitsEnd: + if (ReleaseLock != FALSE) { + ReleaseGlobalMutex(); + } + + return Status; +} + +_Use_decl_annotations_ +NTSTATUS +PLCQueryLimitValues ( + PVOID Context, + ULONG ValueCount, + PVOID Values + ) + +/*++ + +Routine Description: + + This is the callback function which returns power limit values. + +Parameters Description: + + Context - Supplies a pointer to the device handle. + + ValueCount - Supplies count of Value entries. + + Values - Supplies a pointer to the buffer to store power limit values. + +Return Value: + + Returns STATUS_BUFFER_TOO_SMALL if the supplied buffer is not big enough, otherwise + other NTSTATUS values. + +--*/ + +{ + + PFDO_DATA DevExt; + WDFDEVICE DeviceHandle; + BOOLEAN ReleaseLock; + NTSTATUS Status; + + PAGED_CODE(); + + ReleaseLock = FALSE; + if ((Context == NULL) || (ValueCount == 0) || (Values == NULL)){ + Status = STATUS_INVALID_PARAMETER; + goto QueryLimitsEnd; + } + + DeviceHandle = (WDFDEVICE)Context; + DevExt = GetDeviceExtension(DeviceHandle); + AcquireGlobalMutex(); + ReleaseLock = TRUE; + if (ValueCount < DevExt->LimitCount) { + Status = STATUS_BUFFER_TOO_SMALL; + goto QueryLimitsEnd; + } + + RtlCopyMemory(Values, + DevExt->LimitValues, + sizeof(POWER_LIMIT_VALUE) * DevExt->LimitCount); + + Status = STATUS_SUCCESS; + +QueryLimitsEnd: + if (ReleaseLock != FALSE) { + ReleaseGlobalMutex(); + } + + return Status; +} diff --git a/powerlimit/plclient/plclient.h b/powerlimit/plclient/plclient.h new file mode 100644 index 00000000..6e9a7f3f --- /dev/null +++ b/powerlimit/plclient/plclient.h @@ -0,0 +1,95 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + +Module Name: + + plclient.h + +Abstract: + + This is the header file for the simulated power limit client driver. + +--*/ + +#pragma once + +//-------------------------------------------------------------------- Includes + +#include <ntddk.h> +#include <wdf.h> +#include <ntstrsafe.h> +#include <initguid.h> +#include <wdmguid.h> +#include <poclass.h> +#include <limits.h> +#include "powerlimitclient_drvinterface.h" + +//----------------------------------------------------------------------- Types + +typedef struct { + ULONG LimitCount; + PPOWER_LIMIT_ATTRIBUTES LimitAttributes; + PPOWER_LIMIT_VALUE LimitValues; +} FDO_DATA, *PFDO_DATA; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(FDO_DATA, GetDeviceExtension); + +//----------------------------------------------------------------------- Debug + +#define DebugPrint(l, m, ...) DbgPrintEx(DPFLTR_POWER_ID, l, "[plclient]: "m, __VA_ARGS__) +#define DebugEnter() DebugPrint(PLCLIENT_PRINT_TRACE, "Entering %s", __FUNCTION__) +#define DebugExit() DebugPrint(PLCLIENT_PRINT_TRACE, "Leaving " __FUNCTION__ "\n") +#define DebugExitStatus(_status_) DebugPrint(PLCLIENT_PRINT_TRACE, "Leaving " __FUNCTION__ ": Status=0x%08x\n", _status_) + +#define PLCLIENT_PRINT_ERROR DPFLTR_ERROR_LEVEL +#define PLCLIENT_PRINT_TRACE DPFLTR_TRACE_LEVEL +#define PLCLIENT_PRINT_INFO DPFLTR_INFO_LEVEL + +#define PLCLIENT_TAG 'PLCL' + +//--------------------------------------------------------------------- Globals + +extern WDFWAITLOCK GlobalMutex; + +//------------------------------------------------------------------ Prototypes + +FORCEINLINE +VOID +AcquireGlobalMutex ( + VOID + ) +{ + + WdfWaitLockAcquire(GlobalMutex, 0); + return; +} + +FORCEINLINE +VOID +ReleaseGlobalMutex ( + VOID + ) +{ + + WdfWaitLockRelease(GlobalMutex); + return; +} + +// +// plclient.c +// + +QUERY_POWER_LIMIT_ATTRIBUTES PLCQueryAttributes; +SET_POWER_LIMIT PLCSetLimits; +QUERY_POWER_LIMIT PLCQueryLimitValues; + +NTSTATUS +InitPowerLimitValues ( + _Inout_ PFDO_DATA DevExt + ); + +VOID +CleanupPowerLimitValues ( + _Inout_opt_ PFDO_DATA DevExt + ); diff --git a/powerlimit/plclient/plclient.inf b/powerlimit/plclient/plclient.inf new file mode 100644 index 00000000..136b6761 --- /dev/null +++ b/powerlimit/plclient/plclient.inf @@ -0,0 +1,83 @@ +;/*++ +; +;Copyright (c) Microsoft Corporation All rights Reserved +; +;Module Name: +; +; plclient.inf +; +;Abstract: +; +; INF file for installing simulate power limit client driver. +; +;--*/ + +[Version] +Signature="$WINDOWS NT$" +Class=System +ClassGuid={4D36E97D-E325-11CE-BFC1-08002BE10318} +Provider=%ProviderString% +DriverVer=08/29/2023, 1.00.0000 +CatalogFile=plclient.cat +PnpLockdown=1 + +[DestinationDirs] +DefaultDestDir = 12 + +[SourceDisksNames] +1 = %DiskId1%,,,"" + +[SourceDisksFiles] +plclient.sys = 1,, + +;******************************************** +; Simulated Power Limit Client Install Section +;******************************************** + +[Manufacturer] +%StdMfg%=Standard,NTamd64 +%StdMfg%=Standard,NTarm64 + +[Standard.NTamd64] +%PlCl.DeviceDesc% = PlCl_Device, ACPI\PLCL0001 +%PlCl.DeviceDesc% = PlCl_Device, root\PLCL0001 + +[Standard.NTarm64] +%PlCl.DeviceDesc% = PlCl_Device, ACPI\PLCL0001 +%PlCl.DeviceDesc% = PlCl_Device, root\PLCL0001 + +[PlCl_Device.NT] +CopyFiles=PlCl_Device_Drivers + +[PlCl_Device.NT.HW] +AddReg=PlCl_Device.NT.AddReg + +[PlCl_Device.NT.AddReg] +HKR,,DeviceCharacteristics,0x10001,0x0100 ; Use same security checks on relative opens +HKR,,Security,,"D:P(A;;GA;;;BA)(A;;GA;;;SY)" ; Allow generic-all access to Built-in administrators and Local system + +[PlCl_Device_Drivers] +plclient.sys + +;-------------- Service installation + +[PlCl_Device.NT.Services] +AddService = plclient,%SPSVCINST_ASSOCSERVICE%,PlCl_Service_Inst + +; -------------- plclient driver install sections + +[PlCl_Service_Inst] +DisplayName = %PlCl.SVCDESC% +ServiceType = 1 ; SERVICE_KERNEL_DRIVER +StartType = 3 ; SERVICE_DEMAND_START +ErrorControl = 1 ; SERVICE_ERROR_NORMAL +ServiceBinary = %12%\plclient.sys +LoadOrderGroup = Extended Base + +[Strings] +SPSVCINST_ASSOCSERVICE= 0x00000002 +ProviderString = "TODO-Set-Provider" +StdMfg = "(Standard system devices)" +DiskId1 = "Simulate Power Limit Client Installation Disk #1" +PlCl.DeviceDesc = "Simulate Power Limit Client Device" +PlCl.SVCDESC = "Simulate Power Limit Client Driver" diff --git a/powerlimit/plclient/plclient.rc b/powerlimit/plclient/plclient.rc new file mode 100644 index 00000000..326c61c2 --- /dev/null +++ b/powerlimit/plclient/plclient.rc @@ -0,0 +1,11 @@ +#include <windows.h> + +#include <ntverp.h> + +#define VER_FILETYPE VFT_DRV +#define VER_FILESUBTYPE VFT2_DRV_SYSTEM +#define VER_FILEDESCRIPTION_STR "Simulate Power Limit Client Driver" +#define VER_INTERNALNAME_STR "plclient.sys" +#define VER_ORIGINALFILENAME_STR "plclient.sys" + +#include "common.ver" diff --git a/powerlimit/plclient/plclient.sln b/powerlimit/plclient/plclient.sln new file mode 100644 index 00000000..0401b799 --- /dev/null +++ b/powerlimit/plclient/plclient.sln @@ -0,0 +1,35 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.9.34701.34 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "plclient", "plclient.vcxproj", "{D6B30052-9124-44DB-A421-4DEE110B91E2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM64 = Debug|ARM64 + Debug|x64 = Debug|x64 + Release|ARM64 = Release|ARM64 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D6B30052-9124-44DB-A421-4DEE110B91E2}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {D6B30052-9124-44DB-A421-4DEE110B91E2}.Debug|ARM64.Build.0 = Debug|ARM64 + {D6B30052-9124-44DB-A421-4DEE110B91E2}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {D6B30052-9124-44DB-A421-4DEE110B91E2}.Debug|x64.ActiveCfg = Debug|x64 + {D6B30052-9124-44DB-A421-4DEE110B91E2}.Debug|x64.Build.0 = Debug|x64 + {D6B30052-9124-44DB-A421-4DEE110B91E2}.Debug|x64.Deploy.0 = Debug|x64 + {D6B30052-9124-44DB-A421-4DEE110B91E2}.Release|ARM64.ActiveCfg = Release|ARM64 + {D6B30052-9124-44DB-A421-4DEE110B91E2}.Release|ARM64.Build.0 = Release|ARM64 + {D6B30052-9124-44DB-A421-4DEE110B91E2}.Release|ARM64.Deploy.0 = Release|ARM64 + {D6B30052-9124-44DB-A421-4DEE110B91E2}.Release|x64.ActiveCfg = Release|x64 + {D6B30052-9124-44DB-A421-4DEE110B91E2}.Release|x64.Build.0 = Release|x64 + {D6B30052-9124-44DB-A421-4DEE110B91E2}.Release|x64.Deploy.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {810BCAEA-5B6F-43EC-AF83-6B849DF63425} + EndGlobalSection +EndGlobal diff --git a/powerlimit/plclient/plclient.vcxproj b/powerlimit/plclient/plclient.vcxproj new file mode 100644 index 00000000..b1ecc40d --- /dev/null +++ b/powerlimit/plclient/plclient.vcxproj @@ -0,0 +1,123 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|ARM64"> + <Configuration>Debug</Configuration> + <Platform>ARM64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|ARM64"> + <Configuration>Release</Configuration> + <Platform>ARM64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{D6B30052-9124-44DB-A421-4DEE110B91E2}</ProjectGuid> + <TemplateGuid>{1bc93793-694f-48fe-9372-81e2b05556fd}</TemplateGuid> + <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion> + <Configuration>Debug</Configuration> + <Platform Condition="'$(Platform)' == ''">x64</Platform> + <RootNamespace>plclient</RootNamespace> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <PropertyGroup Label="UserMacros" /> + <PropertyGroup /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <DriverSign> + <FileDigestAlgorithm>sha256</FileDigestAlgorithm> + </DriverSign> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <DriverSign> + <FileDigestAlgorithm>sha256</FileDigestAlgorithm> + </DriverSign> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> + <DriverSign> + <FileDigestAlgorithm>sha256</FileDigestAlgorithm> + </DriverSign> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> + <DriverSign> + <FileDigestAlgorithm>sha256</FileDigestAlgorithm> + </DriverSign> + </ItemDefinitionGroup> + <ItemGroup> + <Inf Include="plclient.inf" /> + </ItemGroup> + <ItemGroup> + <FilesToPackage Include="$(TargetPath)" /> + </ItemGroup> + <ItemGroup> + <ClInclude Include="plclient.h" /> + <ClInclude Include="powerlimitclient_drvinterface.h" /> + </ItemGroup> + <ItemGroup> + <ClCompile Include="plclient.c" /> + <ClCompile Include="wdf.c" /> + </ItemGroup> + <ItemGroup> + <ResourceCompile Include="plclient.rc" /> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets"> + </ImportGroup> +</Project>
\ No newline at end of file diff --git a/powerlimit/plclient/plclient.vcxproj.filters b/powerlimit/plclient/plclient.vcxproj.filters new file mode 100644 index 00000000..391468bc --- /dev/null +++ b/powerlimit/plclient/plclient.vcxproj.filters @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Source Files"> + <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> + <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> + </Filter> + <Filter Include="Header Files"> + <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> + <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> + </Filter> + <Filter Include="Resource Files"> + <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> + <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> + </Filter> + <Filter Include="Driver Files"> + <UniqueIdentifier>{8E41214B-6785-4CFE-B992-037D68949A14}</UniqueIdentifier> + <Extensions>inf;inv;inx;mof;mc;</Extensions> + </Filter> + </ItemGroup> + <ItemGroup> + <Inf Include="plclient.inf"> + <Filter>Driver Files</Filter> + </Inf> + </ItemGroup> + <ItemGroup> + <ClInclude Include="plclient.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="powerlimitclient_drvinterface.h"> + <Filter>Header Files</Filter> + </ClInclude> + </ItemGroup> + <ItemGroup> + <ClCompile Include="plclient.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="wdf.c"> + <Filter>Source Files</Filter> + </ClCompile> + </ItemGroup> + <ItemGroup> + <ResourceCompile Include="plclient.rc"> + <Filter>Resource Files</Filter> + </ResourceCompile> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/powerlimit/plclient/powerlimitclient_drvinterface.h b/powerlimit/plclient/powerlimitclient_drvinterface.h new file mode 100644 index 00000000..d4c71bda --- /dev/null +++ b/powerlimit/plclient/powerlimitclient_drvinterface.h @@ -0,0 +1,58 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + +Module Name: + + powerlimitclient_drvinterface.h + +Abstract: + + This module contains the interfaces used to communicate with the simulate + power limit client driver stack. + +--*/ + +//--------------------------------------------------------------------- Pragmas + +#pragma once + +//--------------------------------------------------------------------- Defines + +// +// IOCTLs to control the client driver +// + +#define POWERLIMITCLIENT_IOCTL(_index_) \ + CTL_CODE(FILE_DEVICE_UNKNOWN, _index_, METHOD_BUFFERED, FILE_WRITE_DATA) + +// +// IOCTL_POWERLIMIT_CLIENT_QUERY_LIMIT_COUNT +// - Output: ULONG, number of supported power limit parameters. +// + +#define IOCTL_POWERLIMIT_CLIENT_QUERY_LIMIT_COUNT POWERLIMITCLIENT_IOCTL(0x800) + +// +// IOCTL_POWERLIMIT_CLIENT_QUERY_ATTRIBUTES +// - Output: POWER_LIMIT_ATTRIBUTES[], attributes of supported power limit parameters. +// + +#define IOCTL_POWERLIMIT_CLIENT_QUERY_ATTRIBUTES POWERLIMITCLIENT_IOCTL(0x801) + +// +// IOCTL_POWERLIMIT_CLIENT_QUERY_LIMITS +// - Output: POWER_LIMIT_VALUE[], values of supported power limit parameters. +// + +#define IOCTL_POWERLIMIT_CLIENT_QUERY_LIMITS POWERLIMITCLIENT_IOCTL(0x802) + +// +// Each domain supports PowerLimitContinuous/Burst/BurstTimeParameter. +// + +#define PLCLIENT_DEFAULT_LIMIT_COUNT_PER_DOMAIN 3UL +#define PLCLIENT_DEFAULT_DOMAIN_COUNT 2UL +#define PLCLIENT_DEFAULT_LIMIT_COUNT PLCLIENT_DEFAULT_LIMIT_COUNT_PER_DOMAIN * PLCLIENT_DEFAULT_DOMAIN_COUNT +#define PLCLIENT_DEFAULT_MAX_VALUE 50000UL +#define PLCLIENT_DEFAULT_MIN_VALUE 1000UL diff --git a/powerlimit/plclient/wdf.c b/powerlimit/plclient/wdf.c new file mode 100644 index 00000000..f5d0eb9b --- /dev/null +++ b/powerlimit/plclient/wdf.c @@ -0,0 +1,477 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + +Module Name: + + wdf.c + +Abstract: + + The module implements WDF boilerplate for the simulate power limit client. + +--*/ + +//-------------------------------------------------------------------- Includes + +#include "plclient.h" + +//--------------------------------------------------------------------- Globals + +WDFWAITLOCK GlobalMutex; + +//------------------------------------------------------------------ Prototypes + +DRIVER_INITIALIZE DriverEntry; +EVT_WDF_DRIVER_DEVICE_ADD EvtDriverDeviceAdd; +EVT_WDF_DRIVER_UNLOAD EvtDriverUnload; +EVT_WDF_OBJECT_CONTEXT_DESTROY EvtDeviceDestroy; +EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL EvtIoDeviceControl; + +//--------------------------------------------------------------------- Pragmas + +#pragma alloc_text(INIT, DriverEntry) +#pragma alloc_text(PAGE, EvtDriverDeviceAdd) +#pragma alloc_text(PAGE, EvtDriverUnload) +#pragma alloc_text(PAGE, EvtIoDeviceControl) +#pragma alloc_text(PAGE, EvtDeviceDestroy) + +//------------------------------------------------------------------- Functions + +_Use_decl_annotations_ +NTSTATUS +DriverEntry ( + _In_ PDRIVER_OBJECT DriverObject, + _In_ PUNICODE_STRING RegistryPath + ) + +/*++ + +Routine Description: + + DriverEntry initializes the driver and is the first routine called by the + system after the driver is loaded. DriverEntry configures and creates a WDF + driver object. + +Parameters Description: + + DriverObject - Supplies a pointer to the driver object. + + RegistryPath - Supplies a pointer to a unicode string representing the path + to the driver-specific key in the registry. + +Return Value: + + NTSTATUS. + +--*/ + +{ + + WDF_DRIVER_CONFIG DriverConfig; + NTSTATUS Status; + + UNREFERENCED_PARAMETER(RegistryPath); + + // + // Initiialize the DriverConfig data that controls the attributes that are + // global to this driver. + // + + DebugEnter(); + WDF_DRIVER_CONFIG_INIT(&DriverConfig, EvtDriverDeviceAdd); + DriverConfig.EvtDriverUnload = EvtDriverUnload; + + // + // Create the driver object + // + + Status = WdfDriverCreate(DriverObject, + RegistryPath, + WDF_NO_OBJECT_ATTRIBUTES, + &DriverConfig, + WDF_NO_HANDLE); + + if (!NT_SUCCESS(Status)) { + DebugPrint(PLCLIENT_PRINT_ERROR, + "WdfDriverCreate() Failed. Status 0x%x\n", + Status); + + goto DriverEntryEnd; + } + + // + // Initialize global mutex. + // + + Status = WdfWaitLockCreate(WDF_NO_OBJECT_ATTRIBUTES, &GlobalMutex); + if (!NT_SUCCESS(Status)) { + DebugPrint(PLCLIENT_PRINT_ERROR, + "WdfWaitLockCreate() Failed! 0x%x\n", + Status); + + goto DriverEntryEnd; + } + +DriverEntryEnd: + DebugExitStatus(Status); + return Status; +} + +_Use_decl_annotations_ +NTSTATUS +EvtDriverDeviceAdd ( + WDFDRIVER Driver, + PWDFDEVICE_INIT DeviceInit + ) + +/*++ + +Routine Description: + + This routine is called by the framework in response to AddDevice call from + the PnP manager. A WDF device object is created and initialized to represent + a new instance of the power limit client device. + +Arguments: + + Driver - Supplies a handle to the WDF Driver object. + + DeviceInit - Supplies a pointer to a framework-allocated WDFDEVICE_INIT structure. + +Return Value: + + NTSTATUS + +--*/ + +{ + + PFDO_DATA DevExt; + WDF_OBJECT_ATTRIBUTES DeviceAttributes; + WDFDEVICE DeviceHandle; + POWER_LIMIT_INTERFACE PowerLimitInterface; + WDFQUEUE Queue; + WDF_IO_QUEUE_CONFIG QueueConfig; + WDF_QUERY_INTERFACE_CONFIG QueryInterfaceConfig; + NTSTATUS Status; + + UNREFERENCED_PARAMETER(Driver); + + PAGED_CODE(); + + DevExt = NULL; + + DebugEnter(); + + // + // Initialize attributes and a context area for the device object. + // + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&DeviceAttributes, FDO_DATA); + DeviceAttributes.EvtDestroyCallback = &EvtDeviceDestroy; + + // + // Create a framework device object. This call will in turn create + // a WDM device object, attach to the lower stack, and set the + // appropriate flags and attributes. + // + + Status = WdfDeviceCreate(&DeviceInit, &DeviceAttributes, &DeviceHandle); + if (!NT_SUCCESS(Status)) { + DebugPrint(PLCLIENT_PRINT_ERROR, + "WdfDeviceCreate() Failed. 0x%x\n", + Status); + + goto DriverDeviceAddEnd; + } + + // + // Configure a default queue for IO requests. This queue processes requests + // to read the simulated state. + // + // N.B. Those IOCTLs supplies another approach to validate device driver + // interface, which are not needed by production code. + // + + WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&QueueConfig, + WdfIoQueueDispatchSequential); + + QueueConfig.EvtIoDeviceControl = EvtIoDeviceControl; + Status = WdfIoQueueCreate(DeviceHandle, + &QueueConfig, + WDF_NO_OBJECT_ATTRIBUTES, + &Queue); + + if (!NT_SUCCESS(Status)) { + DebugPrint(PLCLIENT_PRINT_ERROR, + "WdfIoQueueCreate() Failed. 0x%x\n", + Status); + + goto DriverDeviceAddEnd; + } + + // + // Initialize the device extension. + // + + DevExt = GetDeviceExtension(DeviceHandle); + Status = InitPowerLimitValues(DevExt); + if (!NT_SUCCESS(Status)) { + DebugPrint(PLCLIENT_PRINT_ERROR, + "InitPowerLimitValues() Failed. 0x%x\n", + Status); + + goto DriverDeviceAddEnd; + } + + // + // Create a device interface for this device to advertise the simulated + // power limit client IO interface. + // + + Status = WdfDeviceCreateDeviceInterface( + DeviceHandle, + &GUID_DEVINTERFACE_POWER_LIMIT, + NULL); + + if (!NT_SUCCESS(Status)) { + goto DriverDeviceAddEnd; + } + + // + // Create a driver interface for this device to advertise the power limit + // interface. + // + + RtlZeroMemory(&PowerLimitInterface, sizeof(PowerLimitInterface)); + PowerLimitInterface.Version = 1; + PowerLimitInterface.Size = sizeof(PowerLimitInterface); + PowerLimitInterface.Context = DeviceHandle; + PowerLimitInterface.InterfaceReference = WdfDeviceInterfaceReferenceNoOp; + PowerLimitInterface.InterfaceDereference = WdfDeviceInterfaceDereferenceNoOp; + PowerLimitInterface.DomainCount = PLCLIENT_DEFAULT_DOMAIN_COUNT; + PowerLimitInterface.QueryAttributes = PLCQueryAttributes; + PowerLimitInterface.SetPowerLimit = PLCSetLimits; + PowerLimitInterface.QueryPowerLimit = PLCQueryLimitValues; + WDF_QUERY_INTERFACE_CONFIG_INIT(&QueryInterfaceConfig, + (PINTERFACE)&PowerLimitInterface, + &GUID_POWER_LIMIT_INTERFACE, + NULL); + + Status = WdfDeviceAddQueryInterface(DeviceHandle, &QueryInterfaceConfig); + if (!NT_SUCCESS(Status)) { + DebugPrint(PLCLIENT_PRINT_ERROR, + "WdfDeviceAddQueryInterface() Failed. 0x%x\n", + Status); + + goto DriverDeviceAddEnd; + } + +DriverDeviceAddEnd: + if (!NT_SUCCESS(Status)) { + CleanupPowerLimitValues(DevExt); + } + + DebugExitStatus(Status); + return Status; +} + +_Use_decl_annotations_ +VOID +EvtDeviceDestroy ( + WDFOBJECT Object + ) + +/*++ + +Routine Description: + + This routine destroys the device's data. + +Arguments: + + Object - Supplies the WDF reference to the device that is being removed. + +Return Value: + + None. + +--*/ + +{ + + PFDO_DATA DevExt; + + PAGED_CODE(); + + DebugEnter(); + DevExt = GetDeviceExtension(Object); + CleanupPowerLimitValues(DevExt); + DebugExit(); + return; +} + +_Use_decl_annotations_ +VOID +EvtIoDeviceControl ( + WDFQUEUE Queue, + WDFREQUEST Request, + size_t OutputBufferLength, + size_t InputBufferLength, + ULONG IoControlCode + ) + +/*++ + +Routine Description: + + Handles requests to read the simulated device state. + +Arguments: + + Queue - Supplies a handle to the framework queue object that is associated + with the I/O request. + + Request - Supplies a handle to a framework request object. This one + represents the IRP_MJ_DEVICE_CONTROL IRP received by the framework. + + OutputBufferLength - Supplies the length, in bytes, of the request's output + buffer, if an output buffer is available. + + InputBufferLength - Supplies the length, in bytes, of the request's input + buffer, if an input buffer is available. + + IoControlCode - Supplies the Driver-defined or system-defined I/O control + code (IOCTL) that is associated with the request. + +Return Value: + + VOID + +--*/ + +{ + + ULONG BytesReturned; + WDFDEVICE Device; + PFDO_DATA DevExt; + PVOID OutputBuffer; + NTSTATUS Status; + + UNREFERENCED_PARAMETER(InputBufferLength); + + PAGED_CODE(); + + Device = WdfIoQueueGetDevice(Queue); + DevExt = GetDeviceExtension(Device); + DebugPrint(PLCLIENT_PRINT_TRACE, + "EvtIoDeviceControl: 0x%08x\n", + IoControlCode); + + BytesReturned = 0; + OutputBuffer = NULL; + if (OutputBufferLength > 0) { + Status = WdfRequestRetrieveOutputBuffer(Request, + OutputBufferLength, + &OutputBuffer, + NULL); + + if (!NT_SUCCESS(Status)) { + goto DeviceIoControlEnd; + } + } + + Status = STATUS_NOT_SUPPORTED; + switch(IoControlCode) { + case IOCTL_POWERLIMIT_CLIENT_QUERY_LIMIT_COUNT: + if (OutputBufferLength == sizeof(ULONG)) { + AcquireGlobalMutex(); + *((PULONG)OutputBuffer) = DevExt->LimitCount; + BytesReturned = sizeof(ULONG); + ReleaseGlobalMutex(); + Status = STATUS_SUCCESS; + + } else { + Status = STATUS_BUFFER_OVERFLOW; + } + + break; + + case IOCTL_POWERLIMIT_CLIENT_QUERY_ATTRIBUTES: + if (OutputBufferLength == sizeof(POWER_LIMIT_ATTRIBUTES) * DevExt->LimitCount) { + AcquireGlobalMutex(); + RtlCopyMemory(OutputBuffer, DevExt->LimitAttributes, OutputBufferLength); + ReleaseGlobalMutex(); + BytesReturned = (ULONG)OutputBufferLength; + Status = STATUS_SUCCESS; + + } else { + Status = STATUS_BUFFER_OVERFLOW; + } + + break; + + case IOCTL_POWERLIMIT_CLIENT_QUERY_LIMITS: + if (OutputBufferLength == sizeof(POWER_LIMIT_VALUE) * DevExt->LimitCount) { + AcquireGlobalMutex(); + RtlCopyMemory(OutputBuffer, DevExt->LimitValues, OutputBufferLength); + ReleaseGlobalMutex(); + BytesReturned = (ULONG)OutputBufferLength; + Status = STATUS_SUCCESS; + + } else { + Status = STATUS_BUFFER_OVERFLOW; + } + + break; + + default: + break; + } + +DeviceIoControlEnd: + WdfRequestCompleteWithInformation(Request, Status, BytesReturned); + DebugExitStatus(Status); + return; +} + +_Use_decl_annotations_ +VOID +EvtDriverUnload ( + WDFDRIVER Driver + ) + +/*++ + +Routine Description: + + EvtDriverUnload is called when the driver is being unloaded to clean up + driver state. + +Arguments: + + Driver - Supplies a handle to the WDF Driver object. + +Return Value: + + None + +--*/ + +{ + + UNREFERENCED_PARAMETER(Driver); + + PAGED_CODE(); + + DebugEnter(); + + // + // N.B. Does nothing since we don't have anything to clean up, just print + // some debug info. + // + + DebugExit(); + return; +} diff --git a/powerlimit/plpolicy/README.md b/powerlimit/plpolicy/README.md new file mode 100644 index 00000000..f23c22e3 --- /dev/null +++ b/powerlimit/plpolicy/README.md @@ -0,0 +1,38 @@ +--- +page_type: sample +description: "Demonstrates a simulated power policy device." +languages: +- cpp +products: +- windows +- windows-wdk +--- + +# plpolicy - Simulated Power Limit Policy Driver + +This sample is a driver for a simulated power limit policy device. + +## Universal Windows Driver Compliant + +The plpolicy sample provides the source code for a power limit controller that supplies power limit management to the operating system. + +This driver supplies IOCTLs to receive commands from other modules and plumb cooresponding information to the hardware through OS kernel +space APIs. + +IOCTL_POWERLIMIT_POLICY_REGISTER: Other module supplies the BIOS name of the target device to control the power limit. + +IOCTL_POWERLIMIT_POLICY_QUERY_ATTRIBUTES: Query the target device for supported power limits and attributes. + +IOCTL_POWERLIMIT_POLICY_QUERY_VALUES: Query the target device for active power limit values. + +IOCTL_POWERLIMIT_POLICY_SET_VALUES: Set power limit values to the target device. + +For a production driver, those IOCTLs are not needed. Instead, the policy driver should: +1. During the init phase, subscribes to GUID_DEVINTERFACE_POWER_LIMIT notifications. Then query client's BIOS name in the callback, and + compares it with the target client device. Then create power limit request through PoCreatePowerLimitRequest, query attributes through + PoQueryPowerLimitAttributes. + +2. At runtime, the policy driver should collect input signals and calcualte power limit target(s), then send targets to the client through + PoSetPowerLimitValue. If necessary, the policy driver can query the current power limit of client through PoQueryPowerLimitValue. + +3. If the power limit control is no longer needed, delete the power limit request through PoDeletePowerLimitRequest. diff --git a/powerlimit/plpolicy/plpolicy.c b/powerlimit/plpolicy/plpolicy.c new file mode 100644 index 00000000..e5db18cd --- /dev/null +++ b/powerlimit/plpolicy/plpolicy.c @@ -0,0 +1,611 @@ +/*++ + +Copyright (c) Microsoft Corporation + +Module Name: + + plpolicy.c + +Abstract: + + This module implements power limit related operations for the simulated power + limit policy driver. + +--*/ + +//-------------------------------------------------------------------- Includes + +#include "plpolicy.h" + +//------------------------------------------------------------------ Prototypes + +NTSTATUS +GetDeviceObjectFromInterfaceName ( + _In_ PUNICODE_STRING Name, + _Outptr_ PFILE_OBJECT *File, + _Outptr_ PDEVICE_OBJECT *Device + ); + +PDEVICE_REGISTRATION +FindRegistrationByName ( + _In_ PUNICODE_STRING TargetDeviceName, + _In_ PFDO_DATA DevExt + ); + +PDEVICE_REGISTRATION +FindRegistrationById ( + _In_ PFDO_DATA DevExt, + _In_ ULONG RequestId + ); + +//--------------------------------------------------------------------- Globals + +WDFWAITLOCK GlobalMutex; + +//--------------------------------------------------------------------- Pragmas + +#pragma alloc_text(PAGE, RegisterRequest) +#pragma alloc_text(PAGE, UnregisterRequest) +#pragma alloc_text(PAGE, QueryAttributes) +#pragma alloc_text(PAGE, QueryLimitValues) +#pragma alloc_text(PAGE, SetLimitValues) +#pragma alloc_text(PAGE, GetDeviceObjectFromInterfaceName) +#pragma alloc_text(PAGE, FindRegistrationByName) +#pragma alloc_text(PAGE, FindRegistrationById) + +//------------------------------------------------------------------- Functions + +_Use_decl_annotations_ +NTSTATUS +RegisterRequest ( + PFDO_DATA DevExt, + PUNICODE_STRING TargetDeviceName, + PDEVICE_OBJECT PolicyDeviceObject, + PULONG RequestId + ) + +/*++ + +Routine Description: + + This routine registers a power limit request for the specified device. + +Arguments: + + DevExt - Supplies a pointer to the device extension. + + TargetDeviceName - Supplies the name of the target device. + + PolicyDeviceObject - Supplies a pointer to the policy driver's device object. + + RequestId - Supplies a pointer to the registered request. + +Return Value: + + NTSTATUS. + +--*/ + +{ + + PFILE_OBJECT FileObject; + COUNTED_REASON_CONTEXT ReasContext; + PDEVICE_REGISTRATION Registration; + ULONG SizeNeeded; + NTSTATUS Status; + PDEVICE_OBJECT TargetDeviceObject; + + PAGED_CODE(); + + FileObject = NULL; + TargetDeviceObject = NULL; + Registration = NULL; + AcquireGlobalMutex(); + if (FindRegistrationByName(TargetDeviceName, DevExt) != NULL) { + Status = STATUS_SUCCESS; + goto RegisterEnd; + } + + Status = GetDeviceObjectFromInterfaceName(TargetDeviceName, + &FileObject, + &TargetDeviceObject); + + if (!NT_SUCCESS(Status)) { + goto RegisterEnd; + } + + SizeNeeded = sizeof(DEVICE_REGISTRATION) + TargetDeviceName->MaximumLength; + Registration = ExAllocatePool2(POOL_FLAG_PAGED, SizeNeeded, PLPOLICY_TAG); + if (Registration == NULL) { + Status = STATUS_INSUFFICIENT_RESOURCES; + goto RegisterEnd; + } + + RtlZeroMemory(Registration, SizeNeeded); + Registration->TargetDeviceName.Length = TargetDeviceName->Length; + Registration->TargetDeviceName.MaximumLength = TargetDeviceName->MaximumLength; + Registration->TargetDeviceName.Buffer = OffsetToPtr(Registration, + sizeof(DEVICE_REGISTRATION)); + + RtlCopyMemory(Registration->TargetDeviceName.Buffer, + TargetDeviceName->Buffer, + TargetDeviceName->MaximumLength); + + ReasContext.Version = DIAGNOSTIC_REASON_VERSION; + ReasContext.Flags = DIAGNOSTIC_REASON_SIMPLE_STRING; + RtlInitUnicodeString(&ReasContext.SimpleString, L"Simulated Power Limit Policy Device"); + Status = PoCreatePowerLimitRequest(&Registration->PowerLimitRequest, + TargetDeviceObject, + PolicyDeviceObject, + &ReasContext); + + if (!NT_SUCCESS(Status)) { + goto RegisterEnd; + } + + Registration->Initialized = TRUE; + Registration->RequestId = DevExt->RequestCount; + *RequestId = DevExt->RequestCount; + InsertTailList(&DevExt->RequestHeader, &Registration->Link); + DevExt->RequestCount += 1; + Registration = NULL; + Status = STATUS_SUCCESS; + +RegisterEnd: + ReleaseGlobalMutex(); + if (FileObject != NULL) { + ObDereferenceObject(FileObject); + } + + if (TargetDeviceObject != NULL) { + ObDereferenceObject(TargetDeviceObject); + } + + if (Registration != NULL) { + ExFreePoolWithTag(Registration, PLPOLICY_TAG); + } + + return Status; +} + +_Use_decl_annotations_ +NTSTATUS +UnregisterRequest ( + PFDO_DATA DevExt, + ULONG RequestId + ) + +/*++ + +Routine Description: + + This routine unregisters a power limit request for the specified device. + +Arguments: + + DevExt - Supplies a pointer to the device extension. + + RequestId - Supplies the Id of the request. + +Return Value: + + NTSTATUS. + +--*/ + +{ + + PDEVICE_REGISTRATION Registration; + NTSTATUS Status; + + PAGED_CODE(); + + AcquireGlobalMutex(); + Registration = FindRegistrationById(DevExt, RequestId); + if (Registration == NULL) { + Status = STATUS_OBJECT_NAME_NOT_FOUND; + goto UnregisterEnd; + } + + RemoveEntryList(&Registration->Link); + PoDeletePowerLimitRequest(Registration->PowerLimitRequest); + ExFreePoolWithTag(Registration, PLPOLICY_TAG); + Status = STATUS_SUCCESS; + +UnregisterEnd: + ReleaseGlobalMutex(); + return Status; +} + +_Use_decl_annotations_ +NTSTATUS +QueryAttributes ( + PPOWER_LIMIT_ATTRIBUTES Buffer, + PFDO_DATA DevExt, + ULONG RequestId, + ULONG BufferCount + ) + +/*++ + +Routine Description: + + This routine returns supported power limit parameter's attributes. + +Arguments: + + Buffer - Supplies a pointer to save attributes. + + DevExt - Supplies a pointer to the device extension. + + RequestId - Supplies the Id of the request. + + BufferCount - Supplies the count of buffer. + +Return Value: + + NTSTATUS. + +--*/ + +{ + + ULONG AttributeCount; + PDEVICE_REGISTRATION Registration; + NTSTATUS Status; + + PAGED_CODE(); + + AcquireGlobalMutex(); + Registration = FindRegistrationById(DevExt, RequestId); + if (Registration == NULL) { + Status = STATUS_OBJECT_NAME_NOT_FOUND; + goto QueryAttributesEnd; + } + + Status = PoQueryPowerLimitAttributes(Registration->PowerLimitRequest, + BufferCount, + Buffer, + &AttributeCount); + +QueryAttributesEnd: + ReleaseGlobalMutex(); + return Status; +} + +_Use_decl_annotations_ +NTSTATUS +QueryLimitValues ( + PPOWER_LIMIT_VALUE Buffer, + PFDO_DATA DevExt, + ULONG RequestId, + ULONG BufferCount + ) + +/*++ + +Routine Description: + + This routine checks values of power limits. + +Arguments: + + Buffer - Supplies a pointer to save values. + + DevExt - Supplies a pointer to the device extension. + + RequestId - Supplies the Id of the request. + + BufferCount - Supplies the count of buffer. + +Return Value: + + NTSTATUS. + +--*/ + +{ + + PDEVICE_REGISTRATION Registration; + NTSTATUS Status; + + PAGED_CODE(); + + AcquireGlobalMutex(); + Registration = FindRegistrationById(DevExt, RequestId); + if (Registration == NULL) { + Status = STATUS_OBJECT_NAME_NOT_FOUND; + goto QueryLimitValuesEnd; + } + + Status = PoQueryPowerLimitValue(Registration->PowerLimitRequest, + BufferCount, + Buffer); + +QueryLimitValuesEnd: + ReleaseGlobalMutex(); + return Status; +} + +_Use_decl_annotations_ +NTSTATUS +SetLimitValues ( + PFDO_DATA DevExt, + ULONG RequestId, + ULONG BufferCount, + PPOWER_LIMIT_VALUE Buffer + ) + +/*++ + +Routine Description: + + This routine sets values of power limits. + +Arguments: + + DevExt - Supplies a pointer to the device extension. + + RequestId - Supplies the Id of the request. + + BufferCount - Supplies the count of buffer. + + Buffer - Supplies a pointer to proposed control values. + +Return Value: + + NTSTATUS. + +--*/ + +{ + + COUNTED_REASON_CONTEXT ReasContext; + PDEVICE_REGISTRATION Registration; + NTSTATUS Status; + + PAGED_CODE(); + + AcquireGlobalMutex(); + Registration = FindRegistrationById(DevExt, RequestId); + if (Registration == NULL) { + Status = STATUS_OBJECT_NAME_NOT_FOUND; + goto QueryLimitValuesEnd; + } + + ReasContext.Version = DIAGNOSTIC_REASON_VERSION; + ReasContext.Flags = DIAGNOSTIC_REASON_SIMPLE_STRING; + RtlInitUnicodeString(&ReasContext.SimpleString, L"Sim PL Policy"); + Status = PoSetPowerLimitValue(Registration->PowerLimitRequest, + &ReasContext, + BufferCount, + Buffer); + +QueryLimitValuesEnd: + ReleaseGlobalMutex(); + return Status; +} + +NTSTATUS +GetDeviceObjectFromInterfaceName ( + _In_ PUNICODE_STRING Name, + _Outptr_ PFILE_OBJECT *File, + _Outptr_ PDEVICE_OBJECT *Device + ) + +/*++ + +Routine Description: + + This routine retrieves the device object for the named interface. + +Arguments: + + Name - Supplies a pointer to the name of the device interface. + + File - Supplies a pointer to a location to receive the file object. + + Device - Supplies a pointer to a location to receive the device object. + +Return Value: + + NTSTATUS. + +--*/ + +{ + + OBJECT_ATTRIBUTES Attributes; + PDEVICE_OBJECT DeviceObject; + PFILE_OBJECT FileObject; + HANDLE Handle; + IO_STATUS_BLOCK IoStatus; + NTSTATUS Status; + + PAGED_CODE(); + + DeviceObject = NULL; + FileObject = NULL; + Handle = NULL; + InitializeObjectAttributes(&Attributes, + Name, + OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, + NULL, + NULL); + + // + // Open a handle to the device. + // + + Status = ZwCreateFile(&Handle, + FILE_ALL_ACCESS, + &Attributes, + &IoStatus, + NULL, + 0, + FILE_SHARE_READ | FILE_SHARE_WRITE, + FILE_OPEN, + 0, + NULL, + 0); + + if (!NT_SUCCESS(Status)) { + Handle = NULL; + goto GetInterfaceDeviceObjectEnd; + } + + // + // Retrieve the file object associated with the device handle. + // + + Status = ObReferenceObjectByHandle(Handle, + 0, + *IoFileObjectType, + KernelMode, + &FileObject, + NULL); + + if (!NT_SUCCESS(Status)) { + FileObject = NULL; + goto GetInterfaceDeviceObjectEnd; + } + + // + // Get the device object associated with the file object. + // + // N.B. The device object must be referenced before dereferencing the file + // object. + // + + DeviceObject = IoGetRelatedDeviceObject(FileObject); + if (DeviceObject == NULL) { + Status = STATUS_UNSUCCESSFUL; + goto GetInterfaceDeviceObjectEnd; + } + + ObReferenceObject(DeviceObject); + *File = FileObject; + *Device = DeviceObject; + FileObject = NULL; + Status = STATUS_SUCCESS; + +GetInterfaceDeviceObjectEnd: + if (FileObject != NULL) { + ObDereferenceObject(FileObject); + } + + if (Handle != NULL) { + ZwClose(Handle); + } + + return Status; +} + +_Use_decl_annotations_ +PDEVICE_REGISTRATION +FindRegistrationByName ( + PUNICODE_STRING TargetDeviceName, + PFDO_DATA DevExt + ) + +/*++ + +Routine Description: + + This routine searches for an existing registration matching the given + device name. + +Arguments: + + TargetDeviceName - Supplies the PDO name of the device. + + DevExt - Supplies a pointer to the device extension. + +Return Value: + + A pointer to the device registration, if it is found. Otherwise, NULL. + +--*/ + +{ + + LONG Comparison; + PLIST_ENTRY Link; + PDEVICE_REGISTRATION Registration; + + Registration = NULL; + if (DevExt->RequestCount == 0) { + goto FindRegistrationByNameEnd; + } + + for (Link = DevExt->RequestHeader.Flink; + Link != &DevExt->RequestHeader; + Link = Link->Flink) { + + Registration = CONTAINING_RECORD(Link, DEVICE_REGISTRATION, Link); + Comparison = RtlCompareUnicodeString(TargetDeviceName, + &Registration->TargetDeviceName, + FALSE); + + if (Comparison == 0) { + break; + } + + Registration = NULL; + } + +FindRegistrationByNameEnd: + return Registration; +} + +_Use_decl_annotations_ +PDEVICE_REGISTRATION +FindRegistrationById ( + PFDO_DATA DevExt, + ULONG RequestId + ) + +/*++ + +Routine Description: + + This routine searches for an existing registration matching the given + device name. + +Arguments: + + TargetDeviceName - Supplies the PDO name of the device. + + RequestId - Supplies the ID of the power limit request. + +Return Value: + + A pointer to the device registration, if it is found. Otherwise, NULL. + +--*/ + +{ + + PLIST_ENTRY Link; + PDEVICE_REGISTRATION Registration; + + Registration = NULL; + if (DevExt->RequestCount == 0) { + goto FindRegistrationByIdEnd; + } + + for (Link = DevExt->RequestHeader.Flink; + Link != &DevExt->RequestHeader; + Link = Link->Flink) { + + Registration = CONTAINING_RECORD(Link, DEVICE_REGISTRATION, Link); + if (Registration->RequestId == RequestId) { + break; + } + + Registration = NULL; + } + +FindRegistrationByIdEnd: + return Registration; +}
\ No newline at end of file diff --git a/powerlimit/plpolicy/plpolicy.h b/powerlimit/plpolicy/plpolicy.h new file mode 100644 index 00000000..ae767b63 --- /dev/null +++ b/powerlimit/plpolicy/plpolicy.h @@ -0,0 +1,128 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + +Module Name: + + plpolicy.h + +Abstract: + + This is the header file for the simulated power limit policy driver. + +--*/ + +#pragma once + +//-------------------------------------------------------------------- Includes + +#include <ntddk.h> +#include <wdf.h> +#include <ntstrsafe.h> +#include <initguid.h> +#include <wdmguid.h> +#include <poclass.h> +#include <limits.h> +#include "powerlimitpolicy_drvinterface.h" + +//----------------------------------------------------------------------- Types + +typedef struct _DEVICE_REGISTRATION { + LIST_ENTRY Link; + BOOLEAN Initialized; + ULONG RequestId; + PVOID PowerLimitRequest; + UNICODE_STRING TargetDeviceName; +} DEVICE_REGISTRATION, *PDEVICE_REGISTRATION; + +typedef struct _FDO_DATA { + ULONG RequestCount; + LIST_ENTRY RequestHeader; +} FDO_DATA, *PFDO_DATA; + +WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(FDO_DATA, GetDeviceExtension); + +//----------------------------------------------------------------------- Debug + +#define DebugPrint(l, m, ...) DbgPrintEx(DPFLTR_POWER_ID, l, "[plpolicy]: "m, __VA_ARGS__) +#define DebugEnter() DebugPrint(PLPOLICY_PRINT_TRACE, "Entering " __FUNCTION__ "\n") +#define DebugExit() DebugPrint(PLPOLICY_PRINT_TRACE, "Leaving " __FUNCTION__ "\n") +#define DebugExitStatus(_status_) DebugPrint(PLPOLICY_PRINT_TRACE, "Leaving " __FUNCTION__ ": Status=0x%x\n", _status_) + +#define PLPOLICY_PRINT_ERROR DPFLTR_ERROR_LEVEL +#define PLPOLICY_PRINT_TRACE DPFLTR_TRACE_LEVEL +#define PLPOLICY_PRINT_INFO DPFLTR_INFO_LEVEL + +#define PLPOLICY_TAG 'PLPO' + +#define OffsetToPtr(Base, Offset) ((PVOID)((PUCHAR)(Base) + (Offset))) + +//--------------------------------------------------------------------- Globals + +extern WDFWAITLOCK GlobalMutex; + +//------------------------------------------------------------------ Prototypes + +FORCEINLINE +VOID +AcquireGlobalMutex ( + VOID + ) +{ + + WdfWaitLockAcquire(GlobalMutex, 0); + return; +} + +FORCEINLINE +VOID +ReleaseGlobalMutex ( + VOID + ) +{ + + WdfWaitLockRelease(GlobalMutex); + return; +} + +// +// plpolicy.c +// + +NTSTATUS +RegisterRequest ( + _Inout_ PFDO_DATA DevExt, + _In_ PUNICODE_STRING TargetDeviceName, + _In_ PDEVICE_OBJECT PolicyDeviceObject, + _Out_ PULONG RequestId + ); + +NTSTATUS +UnregisterRequest ( + _Inout_ PFDO_DATA DevExt, + _In_ ULONG RequestId + ); + +NTSTATUS +QueryAttributes ( + _Out_ PPOWER_LIMIT_ATTRIBUTES Buffer, + _Inout_ PFDO_DATA DevExt, + _In_ ULONG RequestId, + _In_ ULONG BufferCount + ); + +NTSTATUS +QueryLimitValues ( + _Out_ PPOWER_LIMIT_VALUE Buffer, + _Inout_ PFDO_DATA DevExt, + _In_ ULONG RequestId, + _In_ ULONG BufferCount + ); + +NTSTATUS +SetLimitValues ( + _Inout_ PFDO_DATA DevExt, + _In_ ULONG RequestId, + _In_ ULONG BufferCount, + _In_ PPOWER_LIMIT_VALUE Buffer + ); diff --git a/powerlimit/plpolicy/plpolicy.inf b/powerlimit/plpolicy/plpolicy.inf new file mode 100644 index 00000000..ac5dc127 --- /dev/null +++ b/powerlimit/plpolicy/plpolicy.inf @@ -0,0 +1,82 @@ +;/*++ +; +;Copyright (c) Microsoft Corporation All rights Reserved +; +;Module Name: +; +; plpolicy.inf +; +;Abstract: +; +; INF file for installing simulate power limit policy driver. +; +;--*/ + +[Version] +Signature="$WINDOWS NT$" +Class=System +ClassGuid={4D36E97D-E325-11CE-BFC1-08002BE10318} +Provider=%ProviderString% +DriverVer=08/29/2023,1.00.0000 +CatalogFile=plpolicy.cat +PnpLockdown=1 + +[DestinationDirs] +DefaultDestDir = 12 + +[SourceDisksNames] +1 = %DiskId1%,,,"" + +[SourceDisksFiles] +plpolicy.sys = 1,, + +;***************************************** +; Thermal Request Proxy Install Section +;***************************************** + +[Manufacturer] +%StdMfg%=Standard,NTamd64 +%StdMfg%=Standard,NTarm64 + +[Standard.NTamd64] +%plpolicy.DeviceDesc%=PLPolicy_Device,ACPI\PLPO0001 +%plpolicy.DeviceDesc%=PLPolicy_Device,root\PLPO0001 + +[Standard.NTarm64] +%plpolicy.DeviceDesc%=PLPolicy_Device,ACPI\PLPO0001 +%plpolicy.DeviceDesc%=PLPolicy_Device,root\PLPO0001 + +[PLPolicy_Device.NT] +CopyFiles=PLPolicy_Device.NT.Copy + +[PLPolicy_Device.NT.HW] +AddReg=PLPolicy_Device.NT.AddReg + +[PLPolicy_Device.NT.AddReg] +HKR,,DeviceCharacteristics,0x10001,0x0100 ; Use same security checks on relative opens +HKR,,Security,,"D:P(A;;GA;;;BA)(A;;GA;;;SY)" ; Allow generic-all access to Built-in administrators and Local system + +[PLPolicy_Device.NT.Copy] +plpolicy.sys + +;-------------- Service installation + +[PLPolicy_Device.NT.Services] +AddService = plpolicy,%SPSVCINST_ASSOCSERVICE%,PLPolicy_Service_Inst + +[PLPolicy_Service_Inst] +DisplayName = %plpolicy.SVCDESC% +ServiceType = 1 ; SERVICE_KERNEL_DRIVER +StartType = 3 ; SERVICE_DEMAND_START +ErrorControl = 1 ; SERVICE_ERROR_NORMAL +ServiceBinary = %12%\plpolicy.sys +LoadOrderGroup = System Reserved + +[Strings] +SPSVCINST_ASSOCSERVICE= 0x00000002 +ProviderString = "TODO-Set-Provider" +StdMfg = "(Standard system devices)" +ClassName = "System devices" +DiskId1 = "Simulate Power Limit Policy Installation Disk #1" +plpolicy.DeviceDesc = "Simulate Power Limit Policy Device" +plpolicy.SVCDESC = "Simulate Power Limit Policy Driver" diff --git a/powerlimit/plpolicy/plpolicy.rc b/powerlimit/plpolicy/plpolicy.rc new file mode 100644 index 00000000..0dbbb5ff --- /dev/null +++ b/powerlimit/plpolicy/plpolicy.rc @@ -0,0 +1,10 @@ +#include <verrsrc.h> +#include <ntverp.h> + +#define VER_FILETYPE VFT_DRV +#define VER_FILESUBTYPE VFT2_DRV_SYSTEM +#define VER_FILEDESCRIPTION_STR "Simulate Power Limit Policy Driver" +#define VER_INTERNALNAME_STR "plpolicy.sys" +#define VER_ORIGINALFILENAME_STR "plpolicy.sys" + +#include "common.ver" diff --git a/powerlimit/plpolicy/plpolicy.sln b/powerlimit/plpolicy/plpolicy.sln new file mode 100644 index 00000000..65827082 --- /dev/null +++ b/powerlimit/plpolicy/plpolicy.sln @@ -0,0 +1,35 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.9.34701.34 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "plpolicy", "plpolicy.vcxproj", "{F69B9212-A156-4EF1-8478-11228DE91DD3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM64 = Debug|ARM64 + Debug|x64 = Debug|x64 + Release|ARM64 = Release|ARM64 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F69B9212-A156-4EF1-8478-11228DE91DD3}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {F69B9212-A156-4EF1-8478-11228DE91DD3}.Debug|ARM64.Build.0 = Debug|ARM64 + {F69B9212-A156-4EF1-8478-11228DE91DD3}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {F69B9212-A156-4EF1-8478-11228DE91DD3}.Debug|x64.ActiveCfg = Debug|x64 + {F69B9212-A156-4EF1-8478-11228DE91DD3}.Debug|x64.Build.0 = Debug|x64 + {F69B9212-A156-4EF1-8478-11228DE91DD3}.Debug|x64.Deploy.0 = Debug|x64 + {F69B9212-A156-4EF1-8478-11228DE91DD3}.Release|ARM64.ActiveCfg = Release|ARM64 + {F69B9212-A156-4EF1-8478-11228DE91DD3}.Release|ARM64.Build.0 = Release|ARM64 + {F69B9212-A156-4EF1-8478-11228DE91DD3}.Release|ARM64.Deploy.0 = Release|ARM64 + {F69B9212-A156-4EF1-8478-11228DE91DD3}.Release|x64.ActiveCfg = Release|x64 + {F69B9212-A156-4EF1-8478-11228DE91DD3}.Release|x64.Build.0 = Release|x64 + {F69B9212-A156-4EF1-8478-11228DE91DD3}.Release|x64.Deploy.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {ED084CB6-1513-41AF-9AF9-545395180D32} + EndGlobalSection +EndGlobal diff --git a/powerlimit/plpolicy/plpolicy.vcxproj b/powerlimit/plpolicy/plpolicy.vcxproj new file mode 100644 index 00000000..bb0b948a --- /dev/null +++ b/powerlimit/plpolicy/plpolicy.vcxproj @@ -0,0 +1,123 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|ARM64"> + <Configuration>Debug</Configuration> + <Platform>ARM64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|ARM64"> + <Configuration>Release</Configuration> + <Platform>ARM64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectGuid>{F69B9212-A156-4EF1-8478-11228DE91DD3}</ProjectGuid> + <TemplateGuid>{1bc93793-694f-48fe-9372-81e2b05556fd}</TemplateGuid> + <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion> + <Configuration>Debug</Configuration> + <Platform Condition="'$(Platform)' == ''">x64</Platform> + <RootNamespace>plpolicy</RootNamespace> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>true</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="Configuration"> + <TargetVersion>Windows10</TargetVersion> + <UseDebugLibraries>false</UseDebugLibraries> + <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset> + <ConfigurationType>Driver</ConfigurationType> + <DriverType>KMDF</DriverType> + <DriverTargetPlatform>Universal</DriverTargetPlatform> + </PropertyGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> + <ImportGroup Label="ExtensionSettings"> + </ImportGroup> + <ImportGroup Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + </ImportGroup> + <PropertyGroup Label="UserMacros" /> + <PropertyGroup /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> + <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor> + </PropertyGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <DriverSign> + <FileDigestAlgorithm>sha256</FileDigestAlgorithm> + </DriverSign> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <DriverSign> + <FileDigestAlgorithm>sha256</FileDigestAlgorithm> + </DriverSign> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> + <DriverSign> + <FileDigestAlgorithm>sha256</FileDigestAlgorithm> + </DriverSign> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> + <DriverSign> + <FileDigestAlgorithm>sha256</FileDigestAlgorithm> + </DriverSign> + </ItemDefinitionGroup> + <ItemGroup> + <Inf Include="plpolicy.inf" /> + </ItemGroup> + <ItemGroup> + <FilesToPackage Include="$(TargetPath)" /> + </ItemGroup> + <ItemGroup> + <ClInclude Include="plpolicy.h" /> + <ClInclude Include="powerlimitpolicy_drvinterface.h" /> + </ItemGroup> + <ItemGroup> + <ClCompile Include="plpolicy.c" /> + <ClCompile Include="wdf.c" /> + </ItemGroup> + <ItemGroup> + <ResourceCompile Include="plpolicy.rc" /> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> + <ImportGroup Label="ExtensionTargets"> + </ImportGroup> +</Project>
\ No newline at end of file diff --git a/powerlimit/plpolicy/plpolicy.vcxproj.filters b/powerlimit/plpolicy/plpolicy.vcxproj.filters new file mode 100644 index 00000000..b2317860 --- /dev/null +++ b/powerlimit/plpolicy/plpolicy.vcxproj.filters @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <Filter Include="Source Files"> + <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> + <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> + </Filter> + <Filter Include="Header Files"> + <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> + <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> + </Filter> + <Filter Include="Resource Files"> + <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> + <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> + </Filter> + <Filter Include="Driver Files"> + <UniqueIdentifier>{8E41214B-6785-4CFE-B992-037D68949A14}</UniqueIdentifier> + <Extensions>inf;inv;inx;mof;mc;</Extensions> + </Filter> + </ItemGroup> + <ItemGroup> + <Inf Include="plpolicy.inf"> + <Filter>Driver Files</Filter> + </Inf> + </ItemGroup> + <ItemGroup> + <ClInclude Include="plpolicy.h"> + <Filter>Header Files</Filter> + </ClInclude> + <ClInclude Include="powerlimitpolicy_drvinterface.h"> + <Filter>Header Files</Filter> + </ClInclude> + </ItemGroup> + <ItemGroup> + <ClCompile Include="plpolicy.c"> + <Filter>Source Files</Filter> + </ClCompile> + <ClCompile Include="wdf.c"> + <Filter>Source Files</Filter> + </ClCompile> + </ItemGroup> + <ItemGroup> + <ResourceCompile Include="plpolicy.rc"> + <Filter>Resource Files</Filter> + </ResourceCompile> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/powerlimit/plpolicy/powerlimitpolicy_drvinterface.h b/powerlimit/plpolicy/powerlimitpolicy_drvinterface.h new file mode 100644 index 00000000..cd630ef6 --- /dev/null +++ b/powerlimit/plpolicy/powerlimitpolicy_drvinterface.h @@ -0,0 +1,85 @@ +/*++ + +Copyright (c) Microsoft Corporation + +Module Name: + + powerlimitpolicy_drvinterface.h + +Abstract: + + This module contains the interfaces used to communicate with the simulate + power limit policy driver stack. + +--*/ + +//--------------------------------------------------------------------- Pragmas + +#pragma once + +//--------------------------------------------------------------------- Defines + +// +// Simulated power limit policy interface +// + +// {dbdc0da1-563c-4e20-8408-d4e3c1069ea3} +DEFINE_GUID(GUID_DEVINTERFACE_POWERLIMIT_POLICY, +0xdbdc0da1, 0x563c, 0x4e20, 0x84, 0x08, 0xd4, 0xe3, 0xc1, 0x06, 0x9e, 0xa3); + +// +// IOCTLs to control the policy driver +// + +#define POWERLIMIT_POLICY_IOCTL(_index_) \ + CTL_CODE(FILE_DEVICE_UNKNOWN, _index_, METHOD_BUFFERED, FILE_WRITE_DATA) + +// +// IOCTL_POWERLIMIT_POLICY_REGISTER +// - Input: WCHAR[], contains interface name of the target device +// - Output: ULONG, Id of the created power limit +// + +#define IOCTL_POWERLIMIT_POLICY_REGISTER POWERLIMIT_POLICY_IOCTL(0x800) + +// +// IOCTL_POWERLIMIT_POLICY_UNREGISTER +// - Input: ULONG, Id of the power limit to unregister +// + +#define IOCTL_POWERLIMIT_POLICY_UNREGISTER POWERLIMIT_POLICY_IOCTL(0x801) + +// +// IOCTL_POWERLIMIT_POLICY_QUERY_ATTRIBUTES +// - Input: POWERLIMIT_POLICY_ATTRIBUTES +// - Output: POWERLIMIT_POLICY_ATTRIBUTES +// + +#define IOCTL_POWERLIMIT_POLICY_QUERY_ATTRIBUTES POWERLIMIT_POLICY_IOCTL(0x802) + +// +// IOCTL_POWERLIMIT_POLICY_QUERY_VALUES +// - Input: POWERLIMIT_POLICY_VALUES +// - Output: POWERLIMIT_POLICY_VALUES +// + +#define IOCTL_POWERLIMIT_POLICY_QUERY_VALUES POWERLIMIT_POLICY_IOCTL(0x803) + +// +// IOCTL_POWERLIMIT_POLICY_SET_VALUES +// - Input: POWERLIMIT_POLICY_VALUES, values to be updated for target power limit request +// + +#define IOCTL_POWERLIMIT_POLICY_SET_VALUES POWERLIMIT_POLICY_IOCTL(0x804) + +typedef struct _POWERLIMIT_POLICY_ATTRIBUTES { + ULONG RequestId; + ULONG BufferCount; + POWER_LIMIT_ATTRIBUTES Buffer[ANYSIZE_ARRAY]; +} POWERLIMIT_POLICY_ATTRIBUTES, *PPOWERLIMIT_POLICY_ATTRIBUTES; + +typedef struct _POWERLIMIT_POLICY_VALUES { + ULONG RequestId; + ULONG BufferCount; + POWER_LIMIT_VALUE Buffer[ANYSIZE_ARRAY]; +} POWERLIMIT_POLICY_VALUES, *PPOWERLIMIT_POLICY_VALUES; diff --git a/powerlimit/plpolicy/wdf.c b/powerlimit/plpolicy/wdf.c new file mode 100644 index 00000000..14760ac7 --- /dev/null +++ b/powerlimit/plpolicy/wdf.c @@ -0,0 +1,620 @@ +/*++ + +Copyright (c) Microsoft Corporation. All rights reserved. + +Module Name: + + wdf.c + +Abstract: + + The module implements WDF boilerplate for the simulate power limit policy. + +--*/ + +//-------------------------------------------------------------------- Includes + +#include "plpolicy.h" + +//------------------------------------------------------------------ Prototypes + +DRIVER_INITIALIZE DriverEntry; +EVT_WDF_DRIVER_DEVICE_ADD EvtDriverDeviceAdd; +EVT_WDF_DRIVER_UNLOAD EvtDriverUnload; +EVT_WDF_OBJECT_CONTEXT_DESTROY EvtDeviceDestroy; +EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL EvtIoDeviceControl; + +NTSTATUS +GetDeviceName ( + _Out_ PUNICODE_STRING DeviceName, + _In_reads_bytes_(BufferLength) PWCHAR Buffer, + _In_ SIZE_T BufferLength + ); + +//--------------------------------------------------------------------- Pragmas + +#pragma alloc_text(INIT, DriverEntry) +#pragma alloc_text(PAGE, EvtDriverDeviceAdd) +#pragma alloc_text(PAGE, EvtDriverUnload) +#pragma alloc_text(PAGE, EvtIoDeviceControl) +#pragma alloc_text(PAGE, EvtDeviceDestroy) +#pragma alloc_text(PAGE, GetDeviceName) + +//------------------------------------------------------------------- Functions + +_Use_decl_annotations_ +NTSTATUS +DriverEntry ( + PDRIVER_OBJECT DriverObject, + PUNICODE_STRING RegistryPath + ) + +/*++ + +Routine Description: + + DriverEntry initializes the driver and is the first routine called by the + system after the driver is loaded. DriverEntry configures and creates a WDF + driver object. + +Parameters Description: + + DriverObject - Supplies a pointer to the driver object. + + RegistryPath - Supplies a pointer to a unicode string representing the + path to the driver-specific key in the registry. + +Return Value: + + NTSTATUS. + +--*/ + +{ + + WDF_DRIVER_CONFIG DriverConfig; + NTSTATUS Status; + + UNREFERENCED_PARAMETER(RegistryPath); + + // + // Initiialize the DriverConfig data that controls the attributes that are + // global to this driver. + // + + DebugEnter(); + WDF_DRIVER_CONFIG_INIT(&DriverConfig, EvtDriverDeviceAdd); + DriverConfig.EvtDriverUnload = EvtDriverUnload; + + // + // Create a framework driver object to represent this driver. + // + + Status = WdfDriverCreate(DriverObject, + RegistryPath, + WDF_NO_OBJECT_ATTRIBUTES, + &DriverConfig, + WDF_NO_HANDLE); + + if (!NT_SUCCESS(Status)) { + DebugPrint(PLPOLICY_PRINT_ERROR, + "WdfDriverCreate() Failed! 0x%x\n", + Status); + + goto DriverEntryEnd; + } + + // + // Initialize global mutex. + // + + Status = WdfWaitLockCreate(WDF_NO_OBJECT_ATTRIBUTES, &GlobalMutex); + if (!NT_SUCCESS(Status)) { + DebugPrint(PLPOLICY_PRINT_ERROR, + "WdfSpinLockCreate() Failed! 0x%x\n", + Status); + + goto DriverEntryEnd; + } + + Status = STATUS_SUCCESS; + +DriverEntryEnd: + DebugExitStatus(Status); + return Status; +} + +_Use_decl_annotations_ +NTSTATUS +EvtDriverDeviceAdd ( + WDFDRIVER Driver, + PWDFDEVICE_INIT DeviceInit + ) + +/*++ + +Routine Description: + + EvtDriverDeviceAdd is called by the framework in response to AddDevice + call from the PnP manager. A WDF device object is created and initailized to + represent the simulation control interface. + +Arguments: + + Driver - Supplies a handle to a framework driver object created in + DriverEntry + + DeviceInit - Supplies a pointer to a framework-allocated WDFDEVICE_INIT + structure. + +Return Value: + + NTSTATUS + +--*/ + +{ + + PFDO_DATA DevExt; + WDF_OBJECT_ATTRIBUTES DeviceAttributes; + WDFDEVICE DeviceHandle; + WDF_IO_QUEUE_CONFIG IoQueueConfig; + WDFQUEUE Queue; + NTSTATUS Status; + + UNREFERENCED_PARAMETER(Driver); + + PAGED_CODE(); + + DebugEnter(); + + // + // Initialize attributes and a context area for the device object. + // + + WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&DeviceAttributes, FDO_DATA); + DeviceAttributes.EvtDestroyCallback = &EvtDeviceDestroy; + + + // + // Create a framework device object. This call will in turn create + // a WDM device object, attach to the lower stack, and set the + // appropriate flags and attributes. + // + + Status = WdfDeviceCreate(&DeviceInit, &DeviceAttributes, &DeviceHandle); + if (!NT_SUCCESS(Status)) { + DebugPrint(PLPOLICY_PRINT_ERROR, + "WdfDeviceCreate() Failed! 0x%x\n", + Status); + + goto EvtDriverDeviceAddEnd; + } + + // + // Configure a default queue for IO requests. This queue processes requests + // to read/write the simulated state. + // + + WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&IoQueueConfig, + WdfIoQueueDispatchSequential); + + IoQueueConfig.EvtIoDeviceControl = EvtIoDeviceControl; + Status = WdfIoQueueCreate(DeviceHandle, + &IoQueueConfig, + WDF_NO_OBJECT_ATTRIBUTES, + &Queue); + + if (!NT_SUCCESS(Status)) { + DebugPrint(PLPOLICY_PRINT_ERROR, + "WdfIoQueueCreate() Failed! 0x%x\n", + Status); + + goto EvtDriverDeviceAddEnd; + } + + // + // Create device interface for this device. The interface will be + // enabled by the framework when StartDevice returns successfully. + // Clients of this driver will open this interface and send ioctls. + // + + Status = WdfDeviceCreateDeviceInterface(DeviceHandle, + &GUID_DEVINTERFACE_POWERLIMIT_POLICY, + NULL); + + if (!NT_SUCCESS(Status)) { + DebugPrint(PLPOLICY_PRINT_ERROR, + "WdfDeviceCreateDeviceInterface() Failed! 0x%x\n", + Status); + + goto EvtDriverDeviceAddEnd; + } + + // + // Ignore failures to initialize the device; the test cases will fail in + // this case. + // + + DevExt = GetDeviceExtension(DeviceHandle); + InitializeListHead(&DevExt->RequestHeader); + DevExt->RequestCount = 0; + Status = STATUS_SUCCESS; + +EvtDriverDeviceAddEnd: + DebugExitStatus(Status); + return Status; +} + +_Use_decl_annotations_ +VOID +EvtDeviceDestroy ( + WDFOBJECT Object + ) + +/*++ + +Routine Description: + + This routine destroys the device's data. + +Arguments: + + Object - Supplies the WDF reference to the device that is being removed. + +Return Value: + + None. + +--*/ + +{ + + PFDO_DATA DevExt; + PLIST_ENTRY Link; + PDEVICE_REGISTRATION Registration; + + PAGED_CODE(); + + DebugEnter(); + DevExt = GetDeviceExtension(Object); + while (IsListEmpty(&DevExt->RequestHeader) == FALSE) { + Link = DevExt->RequestHeader.Flink; + Registration = CONTAINING_RECORD(Link, DEVICE_REGISTRATION, Link); + RemoveEntryList(&Registration->Link); + PoDeletePowerLimitRequest(Registration->PowerLimitRequest); + ExFreePoolWithTag(Registration, PLPOLICY_TAG); + } + + DebugExit(); + return; +} + +_Use_decl_annotations_ +VOID +EvtIoDeviceControl ( + WDFQUEUE Queue, + WDFREQUEST Request, + size_t OutputBufferLength, + size_t InputBufferLength, + ULONG IoControlCode + ) + +/*++ + +Routine Description: + + This routine processes an IOCTL sent to the PEP. + +Arguments: + + Queue - Supplies a handle to the WDF queue object. + + Request - Supplies a handle to the WDF request object for this request. + + OuputBufferLength - Supplies the length of the output buffer, in bytes. + + InputBufferLength - Supplies the length of the input buffer, in bytes. + + IoControlCode - Supplies the IOCTL code being processes. + +Return Value: + + None. + +--*/ + +{ + + PPOWERLIMIT_POLICY_ATTRIBUTES Attributes; + ULONG BytesWritten; + PFDO_DATA DevExt; + WDFDEVICE Device; + UNICODE_STRING DeviceName; + PVOID InputBuffer; + PVOID OutputBuffer; + PPOWERLIMIT_POLICY_ATTRIBUTES QueryAttributeInput; + PPOWERLIMIT_POLICY_VALUES QueryValueInput; + ULONG RequestId; + PPOWERLIMIT_POLICY_VALUES SetInput; + ULONG SizeNeeded; + NTSTATUS Status; + PPOWERLIMIT_POLICY_VALUES Values; + + DebugPrint(PLPOLICY_PRINT_TRACE, + "EvtIoDeviceControl: 0x%08x\n", + IoControlCode); + + BytesWritten = 0; + OutputBuffer = NULL; + InputBuffer = NULL; + if (InputBufferLength > 0) { + Status = WdfRequestRetrieveInputBuffer(Request, + InputBufferLength, + &InputBuffer, + NULL); + + if (!NT_SUCCESS(Status)) { + goto DeviceControlEnd; + } + } + + if (OutputBufferLength > 0) { + Status = WdfRequestRetrieveOutputBuffer(Request, + OutputBufferLength, + &OutputBuffer, + NULL); + + if (!NT_SUCCESS(Status)) { + goto DeviceControlEnd; + } + } + + Device = WdfIoQueueGetDevice(Queue); + DevExt = GetDeviceExtension(Device); + switch (IoControlCode) { + case IOCTL_POWERLIMIT_POLICY_REGISTER: + if ((InputBufferLength == 0) || (InputBuffer == NULL)) { + Status = STATUS_INVALID_PARAMETER; + goto DeviceControlEnd; + } + + if ((OutputBufferLength != sizeof(ULONG)) || (OutputBuffer == NULL)) { + Status = STATUS_INVALID_PARAMETER; + goto DeviceControlEnd; + } + + Status = GetDeviceName(&DeviceName, + (PWCHAR)InputBuffer, + InputBufferLength); + + if (!NT_SUCCESS(Status)) { + goto DeviceControlEnd; + } + + Status = RegisterRequest(DevExt, + &DeviceName, + WdfDeviceWdmGetDeviceObject(Device), + &RequestId); + + if (NT_SUCCESS(Status)) { + *(PULONG)OutputBuffer = RequestId; + BytesWritten = sizeof(ULONG); + } + + break; + + case IOCTL_POWERLIMIT_POLICY_UNREGISTER: + if (InputBufferLength < sizeof(ULONG)) { + Status = STATUS_INVALID_PARAMETER; + goto DeviceControlEnd; + } + + RequestId = *(PULONG)InputBuffer; + Status = UnregisterRequest(DevExt, RequestId); + + break; + + case IOCTL_POWERLIMIT_POLICY_QUERY_ATTRIBUTES: + if (InputBufferLength < sizeof(POWERLIMIT_POLICY_ATTRIBUTES)) { + Status = STATUS_INVALID_PARAMETER; + goto DeviceControlEnd; + } + + QueryAttributeInput = (PPOWERLIMIT_POLICY_ATTRIBUTES)InputBuffer; + SizeNeeded = FIELD_OFFSET(POWERLIMIT_POLICY_ATTRIBUTES, + Buffer[QueryAttributeInput->BufferCount]); + + if ((OutputBufferLength < SizeNeeded) || (InputBufferLength < SizeNeeded)) { + Status = STATUS_INVALID_PARAMETER; + goto DeviceControlEnd; + } + + Attributes = ExAllocatePool2(POOL_FLAG_PAGED, SizeNeeded, PLPOLICY_TAG); + if (Attributes == NULL) { + Status = STATUS_INSUFFICIENT_RESOURCES; + goto DeviceControlEnd; + } + + Attributes->RequestId = QueryAttributeInput->RequestId; + Attributes->BufferCount = QueryAttributeInput->BufferCount; + Status = QueryAttributes(Attributes->Buffer, + DevExt, + QueryAttributeInput->RequestId, + QueryAttributeInput->BufferCount); + + if (NT_SUCCESS(Status)) { + RtlCopyMemory(OutputBuffer, Attributes, SizeNeeded); + BytesWritten = SizeNeeded; + } + + ExFreePoolWithTag(Attributes, PLPOLICY_TAG); + + break; + + case IOCTL_POWERLIMIT_POLICY_QUERY_VALUES: + if (InputBufferLength < sizeof(POWERLIMIT_POLICY_VALUES)) { + Status = STATUS_INVALID_PARAMETER; + goto DeviceControlEnd; + } + + QueryValueInput = (PPOWERLIMIT_POLICY_VALUES)InputBuffer; + SizeNeeded = FIELD_OFFSET(POWERLIMIT_POLICY_VALUES, + Buffer[QueryValueInput->BufferCount]); + + if ((OutputBufferLength < SizeNeeded) || (InputBufferLength < SizeNeeded)) { + Status = STATUS_INVALID_PARAMETER; + goto DeviceControlEnd; + } + + Values = ExAllocatePool2(POOL_FLAG_PAGED, SizeNeeded, PLPOLICY_TAG); + if (Values == NULL) { + Status = STATUS_INSUFFICIENT_RESOURCES; + goto DeviceControlEnd; + } + + // + // The input buffer contains which limits to read, copy them over before + // calling kernel API. + // + + RtlCopyMemory(Values, QueryValueInput, SizeNeeded); + Status = QueryLimitValues(Values->Buffer, + DevExt, + QueryValueInput->RequestId, + QueryValueInput->BufferCount); + + if (NT_SUCCESS(Status)) { + RtlCopyMemory(OutputBuffer, Values, SizeNeeded); + BytesWritten = SizeNeeded; + } + + ExFreePoolWithTag(Values, PLPOLICY_TAG); + + break; + + case IOCTL_POWERLIMIT_POLICY_SET_VALUES: + if (InputBufferLength < sizeof(POWERLIMIT_POLICY_VALUES)) { + Status = STATUS_INVALID_PARAMETER; + goto DeviceControlEnd; + } + + SetInput = (PPOWERLIMIT_POLICY_VALUES)InputBuffer; + SizeNeeded = FIELD_OFFSET(POWERLIMIT_POLICY_VALUES, + Buffer[SetInput->BufferCount]); + + if (InputBufferLength < SizeNeeded) { + Status = STATUS_INVALID_PARAMETER; + goto DeviceControlEnd; + } + + Status = SetLimitValues(DevExt, + SetInput->RequestId, + SetInput->BufferCount, + SetInput->Buffer); + + break; + + default: + Status = STATUS_NOT_SUPPORTED; + break; + } + +DeviceControlEnd: + WdfRequestCompleteWithInformation(Request, Status, BytesWritten); + DebugExitStatus(Status); + return; +} + +VOID +EvtDriverUnload ( + WDFDRIVER Driver + ) + +/*++ + +Routine Description: + + This routine is called at driver unload to clean up any lingering thermal + requests. + +Arguments: + + Driver - Supplies a pointer to the WDF driver object. + +Return Value: + + None. + +--*/ + +{ + + UNREFERENCED_PARAMETER(Driver); + + PAGED_CODE(); + + DebugEnter(); + + // + // N.B. Does nothing since we don't have anything to clean up, just print + // some debug info. + // + + DebugExit(); + return; +} + +_Use_decl_annotations_ +NTSTATUS +GetDeviceName ( + PUNICODE_STRING DeviceName, + PWCHAR Buffer, + SIZE_T BufferLength + ) + +/*++ + +Routine Description: + + This routine extracts a device name from an IOCTL input buffer, being + careful to validate the name is well formed. + +Arguments: + + DeviceName - Supplies a UNICODE_STRING to initialize with the device name. + + Buffer - Supplies the buffer containing the device name. + + BufferLength - Supplies the length of the buffer containing the device name, + in bytes. + +Return Value: + + NTSTATUS. + +--*/ + +{ + + size_t Length; + NTSTATUS Status; + + Status = RtlStringCchLengthW(Buffer, BufferLength / sizeof(WCHAR), &Length); + if (!NT_SUCCESS(Status)) { + goto GetDeviceNameEnd; + } + + if (Length > NTSTRSAFE_UNICODE_STRING_MAX_CCH) { + Status = STATUS_INVALID_PARAMETER; + goto GetDeviceNameEnd; + } + + DeviceName->Buffer = Buffer; + DeviceName->Length = (USHORT)(Length * sizeof(WCHAR)); + DeviceName->MaximumLength = (USHORT)(Length * sizeof(WCHAR)); + Status = STATUS_SUCCESS; + +GetDeviceNameEnd: + return Status; +} diff --git a/simbatt/func/miniclass.c b/simbatt/func/miniclass.c index ba2df340..612b4c66 100644 --- a/simbatt/func/miniclass.c +++ b/simbatt/func/miniclass.c @@ -202,7 +202,7 @@ Return Value: } Status = GetSimBattStateFromRegistry(Device, RegState); - if (!NT_SUCCESS(Status)) { + if (NT_SUCCESS(Status)) { RtlZeroMemory(RegState, sizeof(SIMBATT_STATE)); WdfWaitLockAcquire(DevExt->StateLock, NULL); |
