Rise
The Vieneo Province
Loading...
Searching...
No Matches
CompileNativeShaders11.cs
Go to the documentation of this file.
1using System;
2using System.Collections.Concurrent;
3using System.Collections.Generic;
4using System.Diagnostics;
5using System.IO;
6using System.Linq;
7using System.Security.Cryptography;
8using System.Text;
9using System.Text.RegularExpressions;
10using System.Threading;
11using System.Threading.Tasks;
12using Microsoft.Build.Framework;
13using Microsoft.Build.Utilities;
14
15// FXC resolves the dependency graph on every build, including conditional and
16// macro-controlled includes. Compile that exact preprocessed snapshot so the key always
17// describes the compiler input, even if an include changes during compilation.
18public sealed class CompileNativeShaders11 : Microsoft.Build.Utilities.Task, ICancelableTask
19{
20 [Required] public ITaskItem[] Shaders { get; set; }
21 [Required] public string Compiler { get; set; }
22 [Required] public string CacheDirectory { get; set; }
23 [Required] public string OutputDirectory { get; set; }
24 public string Optimization { get; set; } = "O3";
25 public int MaxParallelism { get; set; } = Math.Min(8, Environment.ProcessorCount);
26 [Output] public int CompiledCount { get; set; }
27 [Output] public int CacheHitCount { get; set; }
28 [Output] public int PeakCompilerProcesses { get; set; }
29 readonly CancellationTokenSource cancellation = new CancellationTokenSource();
31 readonly object processCountLock = new object();
32
33 sealed class Snapshot
34 {
35 public string Path, Hash, Dependencies;
36 }
37
38 public void Cancel() { cancellation.Cancel(); }
39
40 static string Hash(byte[] bytes)
41 {
42 using (var sha = SHA256.Create())
43 return BitConverter.ToString(sha.ComputeHash(bytes)).Replace("-", "").ToLowerInvariant();
44 }
45
46 static string Quote(string value)
47 {
48 // Paths supplied to FXC are files (no trailing slash). Metadata is
49 // validated below; never pass shell text or user supplied FXC switches.
50 if (value.IndexOf('"') >= 0 || value.IndexOf('\n') >= 0 || value.IndexOf('\r') >= 0)
51 throw new ArgumentException("Invalid shader argument: " + value);
52 return "\"" + value + "\"";
53 }
54
55 void RunCompiler(string arguments)
56 {
57 cancellation.Token.ThrowIfCancellationRequested();
58 using (var process = new Process())
59 {
60 process.StartInfo = new ProcessStartInfo(Compiler, arguments) {
61 UseShellExecute = false, CreateNoWindow = true,
62 RedirectStandardOutput = true, RedirectStandardError = true
63 };
64 process.Start();
65 lock (processCountLock)
67 try
68 {
69 // Drain both streams while FXC runs, including very large diagnostics.
70 var stdout = process.StandardOutput.ReadToEndAsync();
71 var stderr = process.StandardError.ReadToEndAsync();
72 while (!process.WaitForExit(100)) cancellation.Token.ThrowIfCancellationRequested();
73 var diagnostics = stdout.GetAwaiter().GetResult() + stderr.GetAwaiter().GetResult();
74 // FXC /P can report X1500/X1507 yet exit with code zero and
75 // leave partial output. Never cache that partial translation.
76 if (process.ExitCode != 0 || Regex.IsMatch(diagnostics, @"\berror(\s+[A-Z][0-9]+)?\s*:", RegexOptions.IgnoreCase))
77 throw new InvalidOperationException("FXC failed (" + process.ExitCode + "): " + arguments + "\n" + diagnostics);
78 if (!String.IsNullOrWhiteSpace(diagnostics))
79 {
80 if (Regex.IsMatch(diagnostics, @"\bwarning\s+[A-Z][0-9]+\s*:", RegexOptions.IgnoreCase))
81 Log.LogWarning("{0}", diagnostics.Trim());
82 else Log.LogMessage(MessageImportance.Low, "{0}", diagnostics.Trim());
83 }
84 }
85 finally
86 {
87 // Cancellation only terminates this task's own child process.
88 if (!process.HasExited) { process.Kill(); process.WaitForExit(); }
90 }
91 }
92 }
93
94 FileStream LockEntry(string path)
95 {
96 while (true)
97 {
98 cancellation.Token.ThrowIfCancellationRequested();
99 try { return new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); }
100 catch (IOException error)
101 {
102 // Only sharing/lock violations mean another build owns this key.
103 int code = error.HResult & 0xffff;
104 if (code != 32 && code != 33) throw;
105 cancellation.Token.WaitHandle.WaitOne(100);
106 }
107 }
108 }
109
110 static bool ValidBytecode(byte[] bytes)
111 {
112 return bytes.Length >= 32 && bytes.Length <= 16 * 1024 * 1024 &&
113 bytes[0] == 'D' && bytes[1] == 'X' && bytes[2] == 'B' && bytes[3] == 'C' &&
114 BitConverter.ToUInt32(bytes, 24) == bytes.Length;
115 }
116
117 static byte[] ReadCache(string path)
118 {
119 if (!File.Exists(path) || !File.Exists(path + ".sha256")) return null;
120 long length = new FileInfo(path).Length;
121 if (length < 32 || length > 16 * 1024 * 1024 || new FileInfo(path + ".sha256").Length > 128) return null;
122 var bytes = File.ReadAllBytes(path);
123 return ValidBytecode(bytes) && String.Equals(Hash(bytes), File.ReadAllText(path + ".sha256").Trim(), StringComparison.Ordinal)
124 ? bytes : null;
125 }
126
127 static void WriteIfDifferent(string path, byte[] bytes)
128 {
129 if (File.Exists(path) && new FileInfo(path).Length == bytes.Length && File.ReadAllBytes(path).SequenceEqual(bytes)) return;
130 var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
131 try
132 {
133 File.WriteAllBytes(temporary, bytes);
134 if (File.Exists(path)) File.Replace(temporary, path, null);
135 else File.Move(temporary, path);
136 }
137 finally { if (File.Exists(temporary)) File.Delete(temporary); }
138 }
139
140 string GroupKey(ITaskItem item)
141 {
142 return Path.GetFullPath(item.GetMetadata("Source")) + "\n" + item.GetMetadata("Samples");
143 }
144
145 void ParallelWork<T>(IEnumerable<T> items, Action<T> action)
146 {
147 var failures = new ConcurrentQueue<Exception>();
148 try
149 {
150 // Shader costs differ by orders of magnitude. Array partitioning
151 // reserves growing batches, stranding expensive jobs behind one
152 // worker while others go idle. Claim exactly one item at a time.
153 Parallel.ForEach(Partitioner.Create(items, EnumerablePartitionerOptions.NoBuffering),
154 new ParallelOptions { MaxDegreeOfParallelism = MaxParallelism, CancellationToken = cancellation.Token }, item => {
155 try { action(item); }
156 catch (OperationCanceledException) { throw; }
157 catch (Exception error) { failures.Enqueue(error); cancellation.Cancel(); throw; }
158 });
159 }
160 catch
161 {
162 // Preserve the original compiler diagnostic when sibling workers
163 // are cancelled, and avoid waiting for expensive unrelated shaders.
164 if (!failures.IsEmpty) throw new AggregateException(failures);
165 throw;
166 }
167 }
168
169 public override bool Execute()
170 {
171 var timer = Stopwatch.StartNew();
172 string temporaryDirectory = null;
173 try
174 {
175 if (MaxParallelism < 1 || MaxParallelism > 64) throw new ArgumentException("NativeShaderMaxParallelism must be between 1 and 64.");
176 if (!Regex.IsMatch(Optimization ?? "", "^O[0-3]$")) throw new ArgumentException("NativeShaderOptimization must be O0, O1, O2 or O3.");
177 Compiler = Path.GetFullPath(Compiler);
178 CacheDirectory = Path.GetFullPath(CacheDirectory);
179 OutputDirectory = Path.GetFullPath(OutputDirectory);
180 var compilerDirectory = Path.GetDirectoryName(Compiler);
181 var compilerLibraries = Directory.GetFiles(compilerDirectory, "d3dcompiler_*.dll").OrderBy(p => p, StringComparer.OrdinalIgnoreCase).ToArray();
182 if (compilerLibraries.Length == 0)
183 throw new FileNotFoundException("Use Windows SDK FXC with its adjacent d3dcompiler DLL so the compiler identity can be verified.");
184 var compilerIdentity = Hash(File.ReadAllBytes(Compiler)) + "\n" + String.Join("\n",
185 compilerLibraries.Select(p => Path.GetFileName(p) + ":" + Hash(File.ReadAllBytes(p))));
186 var identities = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
187 foreach (var item in Shaders)
188 {
189 if (!Regex.IsMatch(item.ItemSpec, "^[A-Za-z0-9_-]+$") || !identities.Add(item.ItemSpec) ||
190 !Regex.IsMatch(item.GetMetadata("Entry"), "^[A-Za-z_][A-Za-z0-9_]*$") ||
191 !Regex.IsMatch(item.GetMetadata("Profile"), "^(vs|ps|gs|hs|ds|cs)_5_0$") ||
192 !Regex.IsMatch(item.GetMetadata("Samples"), "^[1248]$"))
193 throw new ArgumentException("Invalid or duplicate native shader item: " + item.ItemSpec);
194 }
195 Directory.CreateDirectory(CacheDirectory);
196 Directory.CreateDirectory(OutputDirectory);
197 temporaryDirectory = Path.Combine(CacheDirectory, "tmp", Guid.NewGuid().ToString("N"));
198 Directory.CreateDirectory(temporaryDirectory);
199 var snapshots = new ConcurrentDictionary<string, Snapshot>();
200 Log.LogMessage(MessageImportance.High, "Native shaders: checking {0} variants; up to {1} FXC workers; cache {2}", Shaders.Length, MaxParallelism, CacheDirectory);
201 ParallelWork(Shaders.GroupBy(GroupKey), group => {
202 var item = group.First();
203 var path = Path.Combine(temporaryDirectory, Guid.NewGuid().ToString("N") + ".hlsl");
204 RunCompiler("/nologo /P " + Quote(path) + " /D RISE_SCENE_SAMPLES=" + item.GetMetadata("Samples") + " " + Quote(Path.GetFullPath(item.GetMetadata("Source"))));
205 var bytes = File.ReadAllBytes(path);
206 // Keep FXC's active include paths for inspection. The cache key
207 // uses the full expanded text, not mtimes or a hand-written include parser.
208 var dependencies = Regex.Matches(Encoding.UTF8.GetString(bytes), "(?m)^#line [0-9]+ \"([^\"]+)\"")
209 .Cast<Match>().Select(m => m.Groups[1].Value.Replace("\\\\", "\\")).Distinct(StringComparer.OrdinalIgnoreCase);
210 snapshots[group.Key] = new Snapshot { Path = path, Hash = Hash(bytes), Dependencies = String.Join("\n", dependencies) };
211 });
212 int hits = 0, compiled = 0;
213 ParallelWork(Shaders, item => {
214 var snapshot = snapshots[GroupKey(item)];
215 var compileFlags = "/nologo /Ges /Zpr /" + Optimization + " /T " + item.GetMetadata("Profile") + " /E " + item.GetMetadata("Entry");
216 var flags = compileFlags + " /D RISE_SCENE_SAMPLES=" + item.GetMetadata("Samples");
217 var key = Hash(Encoding.UTF8.GetBytes("RiseNativeShaderCache-v1\n" + compilerIdentity + "\n" + flags + "\n" + snapshot.Hash));
218 var directory = Path.Combine(CacheDirectory, key.Substring(0, 2));
219 Directory.CreateDirectory(directory);
220 var cached = Path.Combine(directory, key + ".cso");
221 byte[] bytes;
222 using (LockEntry(cached + ".lock"))
223 {
224 bytes = ReadCache(cached);
225 if (bytes != null) Interlocked.Increment(ref hits);
226 else
227 {
228 Log.LogMessage(MessageImportance.Normal, "Compiling shader {0}", item.ItemSpec);
229 var output = Path.Combine(temporaryDirectory, item.ItemSpec + ".cso");
230 // Defines have already been expanded. Applying /D again
231 // would incorrectly undo a source-level #undef.
232 RunCompiler(compileFlags + " /Fo " + Quote(output) + " " + Quote(snapshot.Path));
233 bytes = File.ReadAllBytes(output);
234 if (!ValidBytecode(bytes)) throw new InvalidDataException("Invalid DXBC output for " + item.ItemSpec);
235 WriteIfDifferent(cached, bytes);
236 WriteIfDifferent(cached + ".sha256", Encoding.ASCII.GetBytes(Hash(bytes)));
237 Interlocked.Increment(ref compiled);
238 }
239 }
240 WriteIfDifferent(Path.Combine(OutputDirectory, item.ItemSpec + ".cso"), bytes);
241 WriteIfDifferent(Path.Combine(OutputDirectory, item.ItemSpec + ".deps"), Encoding.UTF8.GetBytes(
242 "cache-key: " + key + "\nbytecode-sha256: " + Hash(bytes) + "\nflags: " + flags + "\n" + snapshot.Dependencies + "\n"));
243 });
244 CacheHitCount = hits;
245 CompiledCount = compiled;
246 Log.LogMessage(MessageImportance.High, "Native shaders: {0} cache hits, {1} compiled, {2} variants; {3:F2}s; peak {4} FXC processes.", hits, compiled, Shaders.Length, timer.Elapsed.TotalSeconds, PeakCompilerProcesses);
247 return true;
248 }
249 catch (OperationCanceledException) { Log.LogError("Native shader build cancelled."); return false; }
250 catch (Exception error) { Log.LogErrorFromException(error, true); return false; }
251 finally
252 {
253 if (temporaryDirectory != null && Directory.Exists(temporaryDirectory))
254 Directory.Delete(temporaryDirectory, true);
255 }
256 }
257}
static byte[] ReadCache(string path)
string GroupKey(ITaskItem item)
void RunCompiler(string arguments)
static void WriteIfDifferent(string path, byte[] bytes)
void ParallelWork< T >(IEnumerable< T > items, Action< T > action)
static string Hash(byte[] bytes)
FileStream LockEntry(string path)
static bool ValidBytecode(byte[] bytes)
readonly CancellationTokenSource cancellation
static string Quote(string value)
std::function< void(const char *, bool warning)> Log