Rise
The Vieneo Province
Loading...
Searching...
No Matches
Tests/NativeShaderCache11Tests.ps1

Source at documentation-generation time. See Test catalog for fixture associations.

1param(
2 [string]$MSBuild = 'MSBuild.exe',
3 [string]$Compiler = 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64\fxc.exe'
4)
5$ErrorActionPreference = 'Stop'
6$repo = Split-Path $PSScriptRoot
7$run = Join-Path $repo ('outputs\shader-cache-tests\' + [Guid]::NewGuid().ToString('N'))
8[IO.Directory]::CreateDirectory($run) | Out-Null
9$project = Join-Path $run 'cache.proj'
10$stage = Join-Path $run 'stage'
11$cache = Join-Path $run 'cache'
12$utf8 = New-Object Text.UTF8Encoding($false)
13function Write-Text($path, $text) { [IO.File]::WriteAllText($path, $text, $utf8) }
14function Assert($condition, $message) { if (!$condition) { throw $message } }
15function Digest($path) { (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash }
16
17$projectText = @'
18<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
19 <Import Project="IMPORT_TARGETS" />
20 <ItemGroup>
21 <NativeShader Remove="@(NativeShader)"/><NativeShaderSource Remove="@(NativeShaderSource)"/>
22 <NativeShader Include="A1"><Source>$(MSBuildThisFileDirectory)a.hlsl</Source><Entry>Main</Entry><Profile>ps_5_0</Profile><Samples>1</Samples><ResourceName>A1</ResourceName></NativeShader>
23 <NativeShader Include="A2"><Source>$(MSBuildThisFileDirectory)a.hlsl</Source><Entry>Main</Entry><Profile>ps_5_0</Profile><Samples>2</Samples><ResourceName>A2</ResourceName></NativeShader>
24 <NativeShader Include="B1"><Source>$(MSBuildThisFileDirectory)b.hlsl</Source><Entry>Main</Entry><Profile>ps_5_0</Profile><Samples>1</Samples><ResourceName>B1</ResourceName></NativeShader>
25 <NativeShader Include="B2"><Source>$(MSBuildThisFileDirectory)b.hlsl</Source><Entry>Main</Entry><Profile>ps_5_0</Profile><Samples>2</Samples><ResourceName>B2</ResourceName></NativeShader>
26 </ItemGroup>
27 <Target Name="Test" DependsOnTargets="PackageNativeShaders11;TrackNativeShaders11">
28 <WriteLinesToFile File="$([MSBuild]::EnsureTrailingSlash('$(NativeShaderIntermediate)'))result.txt" Overwrite="true" Lines="$(NativeShaderCacheHitCount),$(NativeShaderCompiledCount),$(NativeShaderPeakCompilerProcesses)"/>
29 <WriteLinesToFile File="$([MSBuild]::EnsureTrailingSlash('$(NativeShaderIntermediate)'))writes.txt" Overwrite="true" Lines="@(FileWrites)"/>
30 </Target>
31</Project>
32'@
33$projectText = $projectText.Replace('IMPORT_TARGETS', [Security.SecurityElement]::Escape((Join-Path $repo 'Rendering\NativeShaders11.targets')))
34Write-Text $project $projectText
35$originalA = @'
36#include "nested.hlsli"
37#if RISE_SCENE_SAMPLES == 1
38#include "one.hlsli"
39#else
40#include "two.hlsli"
41#endif
42float4 Main(float4 p : SV_POSITION) : SV_TARGET { return BASE + VALUE + p.x * 0.01; }
43'@
44$originalB = @'
45float4 Main(float4 p : SV_POSITION) : SV_TARGET { return p * RISE_SCENE_SAMPLES; }
46float4 Other(float4 p : SV_POSITION) : SV_TARGET { return p * 2; }
47float4 Vertex(float4 p : POSITION) : SV_POSITION { return p; }
48'@
49Write-Text (Join-Path $run 'a.hlsl') $originalA
50Write-Text (Join-Path $run 'b.hlsl') $originalB
51Write-Text (Join-Path $run 'nested.hlsli') '#include "base.hlsli"'
52Write-Text (Join-Path $run 'base.hlsli') '#define BASE 0.25'
53Write-Text (Join-Path $run 'one.hlsli') '#define VALUE 0.5'
54Write-Text (Join-Path $run 'two.hlsli') '#define VALUE 0.75'
55
56function Build-Arguments($destination, $cachePath, $compilerPath, $extra) {
57 @($project, '/t:Test', '/p:Configuration=Release', '/p:Platform=x64', '/nologo', '/v:minimal',
58 "/p:NativeShaderCompiler=$compilerPath", "/p:NativeShaderCacheDirectory=$cachePath",
59 "/p:NativeShaderIntermediate=$destination", '/p:NativeShaderMaxParallelism=2') + $extra
60}
61function Build($name, $hits, $compiled, $destination = $stage, $extra = @(), $compilerPath = $Compiler, $fails = $false) {
62 $arguments = Build-Arguments $destination $cache $compilerPath $extra
63 $output = & $MSBuild @arguments 2>&1
64 $code = $LASTEXITCODE
65 Write-Text (Join-Path $run "$name.log") ($output -join "`n")
66 if ($fails) {
67 Assert ($code -ne 0) "$name unexpectedly succeeded"
68 } else {
69 Assert ($code -eq 0) "$name failed: $output"
70 $values = ([IO.File]::ReadAllText((Join-Path $destination 'result.txt')).Trim()).Split(',')
71 Assert (([int]$values[0] -eq $hits) -and ([int]$values[1] -eq $compiled)) "$name expected $hits hits/$compiled compilations, got $values"
72 Assert ([int]$values[2] -le 2) "$name exceeded the worker limit"
73 }
74 Write-Output "PASS: $name"
75}
76
77Build 'cold' 0 4
78Assert (([IO.File]::ReadAllText((Join-Path $stage 'result.txt')).Trim().Split(',')[2]) -eq '2') 'Cold build did not overlap FXC workers'
79$times = @{}
80Get-ChildItem -LiteralPath $stage | Where-Object { $_.Extension -in '.cso', '.csz', '.rc' } | ForEach-Object { $times[$_.Name] = $_.LastWriteTimeUtc }
81Build 'warm' 4 0
82foreach ($name in $times.Keys) { Assert ((Get-Item -LiteralPath (Join-Path $stage $name)).LastWriteTimeUtc -eq $times[$name]) "Warm build touched $name" }
83$writes = [IO.File]::ReadAllText((Join-Path $stage 'writes.txt'))
84Assert (!$writes.Contains($cache)) 'Clean must not delete the shared cache'
85Assert ($writes.Contains('A1.deps') -and $writes.Contains('A1.csz')) 'Clean must track staged dependency and resource files'
86$deps = [IO.File]::ReadAllText((Join-Path $stage 'A1.deps'))
87Assert ($deps.Contains('base.hlsli') -and $deps.Contains('one.hlsli') -and !$deps.Contains('two.hlsli')) 'Wrong active transitive dependency graph'
88Build 'shared-output-directory' 4 0 (Join-Path $run 'another-stage')
89$noSlash = Join-Path $run 'stage with spaces'
90Build 'staging-path-spaces-no-trailing-slash' 4 0 $noSlash @("/p:NativeShaderIntermediate=$noSlash")
91Assert (Test-Path -LiteralPath (Join-Path $noSlash 'NativeShaders11.rc')) 'Resource file escaped the staging directory'
92
93# Compare real FXC compilation with compiling the cached preprocessed snapshot.
94& $Compiler /nologo /Ges /Zpr /O3 /T ps_5_0 /E Main /D RISE_SCENE_SAMPLES=1 /Fo (Join-Path $run 'direct.cso') (Join-Path $run 'a.hlsl') | Out-Null
95Assert ($LASTEXITCODE -eq 0) 'Direct FXC comparison failed'
96Assert ((Digest (Join-Path $run 'direct.cso')) -eq (Digest (Join-Path $stage 'A1.cso'))) 'Preprocessing changed bytecode'
97Write-Output 'PASS: direct FXC bytecode equivalence'
98
99$base = Join-Path $run 'base.hlsli'
100$oldTime = (Get-Item -LiteralPath $base).LastWriteTimeUtc
101[IO.File]::SetLastWriteTimeUtc($base, [DateTime]::UtcNow.AddMinutes(1))
102Build 'timestamp-only-edit' 4 0
103Write-Text $base '#define BASE 0.375'
104[IO.File]::SetLastWriteTimeUtc($base, $oldTime)
105Build 'transitive-edit-preserved-timestamp' 2 2
106Assert ((Get-Item -LiteralPath (Join-Path $stage 'B1.cso')).LastWriteTimeUtc -eq $times['B1.cso']) 'Unrelated shader was rewritten'
107Write-Text $base '#define BASE 0.25'
108Build 'revert-reuses-older-key' 4 0
109Write-Text (Join-Path $run 'one.hlsli') '#define VALUE 0.625'
110Build 'conditional-include-edit' 3 1
111Write-Text (Join-Path $run 'one.hlsli') '#define VALUE 0.5'
112Write-Text (Join-Path $run 'added.hlsli') '#define BASE 0.125'
113Write-Text (Join-Path $run 'nested.hlsli') '#include "added.hlsli"'
114Build 'new-transitive-include' 2 2
115Write-Text (Join-Path $run 'nested.hlsli') '#include "missing.hlsli"'
116Build 'missing-include-fails' 0 0 -fails $true
117Write-Text (Join-Path $run 'nested.hlsli') '#include "base.hlsli"'
118Write-Text (Join-Path $run 'a.hlsl') ($originalA.Replace('"one.hlsli"', '"added.hlsli"').Replace('BASE + VALUE', 'BASE'))
119Build 'changed-include-resolution' 2 2
120Assert ([IO.File]::ReadAllText((Join-Path $stage 'A1.deps')).Contains('added.hlsli')) 'Include resolution was not refreshed'
121Write-Text (Join-Path $run 'a.hlsl') $originalA
122Build 'restore-originals' 4 0
123
124$key = ([IO.File]::ReadAllLines((Join-Path $stage 'B1.deps'))[0]).Substring('cache-key: '.Length)
125$cached = Join-Path $cache ($key.Substring(0,2) + '\' + $key + '.cso')
126[IO.File]::WriteAllBytes($cached, [byte[]](1,2,3))
127Build 'corrupt-bytecode-rebuilt' 3 1
128Write-Text ($cached + '.sha256') 'corrupt checksum'
129Build 'corrupt-checksum-rebuilt' 3 1
130[IO.File]::Delete((Join-Path $stage 'A1.cso'))
131[IO.File]::Delete((Join-Path $stage 'A2.csz'))
132Build 'missing-staged-files-restored' 4 0
133Assert (Test-Path -LiteralPath (Join-Path $stage 'A2.csz')) 'Missing packed resource was not restored'
134Build 'different-options' 0 4 -extra @('/p:NativeShaderOptimization=O2')
135Build 'original-options-reused' 4 0
136Write-Text $project ($projectText.Replace('<Entry>Main</Entry><Profile>ps_5_0</Profile><Samples>2</Samples><ResourceName>B2', '<Entry>Other</Entry><Profile>ps_5_0</Profile><Samples>2</Samples><ResourceName>B2'))
137Build 'different-entry' 3 1
138Write-Text $project ($projectText.Replace('<Entry>Main</Entry><Profile>ps_5_0</Profile><Samples>2</Samples><ResourceName>B2', '<Entry>Vertex</Entry><Profile>vs_5_0</Profile><Samples>2</Samples><ResourceName>B2'))
139Build 'different-profile' 3 1
140Write-Text $project ($projectText.Replace('<Samples>2</Samples><ResourceName>B2', '<Samples>8</Samples><ResourceName>B2'))
141Build 'different-sample-count' 3 1
142Write-Text $project $projectText
143
144$undefSource = @'
145#undef RISE_SCENE_SAMPLES
146float RISE_SCENE_SAMPLES;
147float4 Main(float4 p : SV_POSITION) : SV_TARGET { return p * RISE_SCENE_SAMPLES; }
148'@
149Write-Text (Join-Path $run 'b.hlsl') $undefSource
150Build 'defines-expand-only-once' 2 2
151& $Compiler /nologo /Ges /Zpr /O3 /T ps_5_0 /E Main /D RISE_SCENE_SAMPLES=1 /Fo (Join-Path $run 'undef-direct.cso') (Join-Path $run 'b.hlsl') | Out-Null
152Assert ($LASTEXITCODE -eq 0) 'Direct FXC undef comparison failed'
153Assert ((Digest (Join-Path $run 'undef-direct.cso')) -eq (Digest (Join-Path $stage 'B1.cso'))) 'Snapshot compilation reapplied a removed define'
154Write-Text (Join-Path $run 'b.hlsl') $originalB
155
156$toolDirectory = Join-Path $run 'compiler'
157[IO.Directory]::CreateDirectory($toolDirectory) | Out-Null
158$copiedCompiler = Join-Path $toolDirectory 'fxc.exe'
159[IO.File]::Copy($Compiler, $copiedCompiler)
160Get-ChildItem -LiteralPath (Split-Path $Compiler) -Filter 'd3dcompiler_*.dll' | ForEach-Object { [IO.File]::Copy($_.FullName, (Join-Path $toolDirectory $_.Name)) }
161Build 'identical-compiler-at-another-path' 4 0 -compilerPath $copiedCompiler
162# PE overlays are not executable code. Only isolated test copies are modified.
163$stream = [IO.File]::OpenWrite($copiedCompiler)
164try { $stream.Seek(0, [IO.SeekOrigin]::End) | Out-Null; $stream.WriteByte(0) } finally { $stream.Dispose() }
165Build 'compiler-content-identity' 0 4 -compilerPath $copiedCompiler
166$dll = (Get-ChildItem -LiteralPath $toolDirectory -Filter 'd3dcompiler_*.dll' | Select-Object -First 1).FullName
167$stream = [IO.File]::OpenWrite($dll)
168try { $stream.Seek(0, [IO.SeekOrigin]::End) | Out-Null; $stream.WriteByte(0) } finally { $stream.Dispose() }
169Build 'compiler-dll-content-identity' 0 4 -compilerPath $copiedCompiler
170
171# Two independent MSBuild processes populate the same cold cache safely.
172$parallelCache = Join-Path $run 'parallel-cache'
173$processes = @()
174foreach ($number in 1,2) {
175 $destination = Join-Path $run "parallel-$number"
176 $arguments = Build-Arguments $destination $parallelCache $Compiler @()
177 $info = New-Object Diagnostics.ProcessStartInfo
178 $info.FileName = (Get-Command $MSBuild).Source
179 # Windows argv quoting: preserve the backslash before a closing quote.
180 $info.Arguments = (($arguments | ForEach-Object { '"' + ($_ -replace '(\\+)$', '$1$1') + '"' }) -join ' ')
181 $info.UseShellExecute = $false
182 $info.CreateNoWindow = $true
183 $info.RedirectStandardOutput = $true
184 $info.RedirectStandardError = $true
185 $process = [Diagnostics.Process]::Start($info)
186 $processes += @{ Process=$process; Out=$process.StandardOutput.ReadToEndAsync(); Err=$process.StandardError.ReadToEndAsync(); Destination=$destination }
187}
188$totalHits = 0; $totalCompiled = 0
189foreach ($entry in $processes) {
190 $entry.Process.WaitForExit()
191 $output = $entry.Out.GetAwaiter().GetResult() + $entry.Err.GetAwaiter().GetResult()
192 Write-Text ($entry.Destination + '.log') $output
193 Assert ($entry.Process.ExitCode -eq 0) "Concurrent build failed: $output"
194 $values = [IO.File]::ReadAllText((Join-Path $entry.Destination 'result.txt')).Trim().Split(',')
195 $totalHits += [int]$values[0]; $totalCompiled += [int]$values[1]
196 $entry.Process.Dispose()
197}
198Assert ($totalHits -eq 4 -and $totalCompiled -eq 4) 'Concurrent builds duplicated compilation or missed cache entries'
199Write-Output 'PASS: concurrent builds share cache locks'
200
201$beforeFailure = Digest (Join-Path $stage 'B1.cso')
202Write-Text (Join-Path $run 'b.hlsl') 'float4 Main() : SV_TARGET { return unknown_identifier; }'
203Build 'compiler-error-fails-no-stale-fallback' 0 0 -fails $true
204Assert ((Digest (Join-Path $stage 'B1.cso')) -eq $beforeFailure) 'Failed compiler overwrote good staged bytecode'
205Write-Text (Join-Path $run 'b.hlsl') $originalB
206Write-Text (Join-Path $run 'b.hlsl') ("#define SELECTED `"one.hlsli`"`n#include SELECTED`n" + $originalB)
207Build 'preprocess-error-with-zero-exit-fails' 0 0 -fails $true
208Assert ([IO.File]::ReadAllText((Join-Path $run 'preprocess-error-with-zero-exit-fails.log')).Contains('FXC failed (0)')) 'Expected FXC preprocessor zero-exit error was not exercised'
209Write-Text (Join-Path $run 'b.hlsl') $originalB
210Write-Text $project ($projectText.Replace('<Target Name="Test"', '<ItemGroup><NativeShaderSource Include="$(MSBuildThisFileDirectory)b.hlsl"><ExpectedHash>invalid</ExpectedHash></NativeShaderSource></ItemGroup><Target Name="Test"'))
211Build 'generated-source-validation-still-required' 0 0 -fails $true
212Assert (![IO.File]::ReadAllText((Join-Path $run 'generated-source-validation-still-required.log')).Contains('Native shaders: checking')) 'Cache ran before stale generated source rejection'
213Write-Text $project $projectText
214Build 'recover-after-errors' 4 0
215Write-Output "All shader cache tests passed (Release|x64). Logs: $run"