Repository navigation
Expand file tree
/
Copy pathDesktopBuildClient.cs
More file actions
457 lines (403 loc) · 18.7 KB
/
Copy pathDesktopBuildClient.cs
File metadata and controls
457 lines (403 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Microsoft.CodeAnalysis.CommandLine.CompilerServerLogger;
using static Microsoft.CodeAnalysis.CommandLine.NativeMethods;
namespace Microsoft.CodeAnalysis.CommandLine
{
internal class DesktopBuildClient : BuildClient
{
private const string ServerName = "VBCSCompiler.exe";
// Spend up to 1s connecting to existing process (existing processes should be always responsive).
private const int TimeOutMsExistingProcess = 1000;
// Spend up to 20s connecting to a new process, to allow time for it to start.
private const int TimeOutMsNewProcess = 20000;
private readonly RequestLanguage _language;
private readonly CompileFunc _compileFunc;
private readonly IAnalyzerAssemblyLoader _analyzerAssemblyLoader;
/// <summary>
/// When set it overrides all timeout values in milliseconds when communicating with the server.
/// </summary>
internal int? TimeoutOverride { get; set; }
internal DesktopBuildClient(RequestLanguage language, CompileFunc compileFunc, IAnalyzerAssemblyLoader analyzerAssemblyLoader)
{
_language = language;
_compileFunc = compileFunc;
_analyzerAssemblyLoader = analyzerAssemblyLoader;
}
internal static int Run(IEnumerable<string> arguments, IEnumerable<string> extraArguments, RequestLanguage language, CompileFunc compileFunc, IAnalyzerAssemblyLoader analyzerAssemblyLoader)
{
var client = new DesktopBuildClient(language, compileFunc, analyzerAssemblyLoader);
var clientDir = AppDomain.CurrentDomain.BaseDirectory;
var sdkDir = RuntimeEnvironment.GetRuntimeDirectory();
var workingDir = Directory.GetCurrentDirectory();
var buildPaths = new BuildPaths(clientDir: clientDir, workingDir: workingDir, sdkDir: sdkDir);
var originalArguments = BuildClient.GetCommandLineArgs(arguments).Concat(extraArguments).ToArray();
return client.RunCompilation(originalArguments, buildPaths).ExitCode;
}
protected override int RunLocalCompilation(string[] arguments, BuildPaths buildPaths, TextWriter textWriter)
{
return _compileFunc(arguments, buildPaths, textWriter, _analyzerAssemblyLoader);
}
protected override Task<BuildResponse> RunServerCompilation(
List<string> arguments,
BuildPaths buildPaths,
string sessionKey,
string keepAlive,
string libDirectory,
CancellationToken cancellationToken)
{
return RunServerCompilationCore(_language, arguments, buildPaths, sessionKey, keepAlive, libDirectory, TimeoutOverride, TryCreateServer, cancellationToken);
}
public static Task<BuildResponse> RunServerCompilation(
RequestLanguage language,
List<string> arguments,
BuildPaths buildPaths,
string keepAlive,
string libEnvVariable,
CancellationToken cancellationToken)
{
return RunServerCompilationCore(
language,
arguments,
buildPaths,
GetPipeNameForPath(buildPaths.ClientDirectory),
keepAlive,
libEnvVariable,
timeoutOverride: null,
tryCreateServerFunc: TryCreateServerCore,
cancellationToken: cancellationToken);
}
private static Task<BuildResponse> RunServerCompilationCore(
RequestLanguage language,
List<string> arguments,
BuildPaths buildPaths,
string pipeName,
string keepAlive,
string libEnvVariable,
int? timeoutOverride,
Func<string, string, bool> tryCreateServerFunc,
CancellationToken cancellationToken)
{
var clientDir = buildPaths.ClientDirectory;
var timeoutNewProcess = timeoutOverride ?? TimeOutMsNewProcess;
var timeoutExistingProcess = timeoutOverride ?? TimeOutMsExistingProcess;
var clientMutexName = BuildProtocolConstants.GetClientMutexName(pipeName);
bool holdsMutex;
using (var clientMutex = new Mutex(initiallyOwned: true,
name: clientMutexName,
createdNew: out holdsMutex))
{
try
{
if (!holdsMutex)
{
try
{
holdsMutex = clientMutex.WaitOne(timeoutNewProcess);
if (!holdsMutex)
{
return Task.FromResult<BuildResponse>(new RejectedBuildResponse());
}
}
catch (AbandonedMutexException)
{
holdsMutex = true;
}
}
// Check for an already running server
var serverMutexName = BuildProtocolConstants.GetServerMutexName(pipeName);
bool wasServerRunning = WasServerMutexOpen(serverMutexName);
var timeout = wasServerRunning ? timeoutExistingProcess : timeoutNewProcess;
NamedPipeClientStream pipe = null;
if (wasServerRunning || tryCreateServerFunc(clientDir, pipeName))
{
pipe = TryConnectToServer(pipeName,
timeout,
cancellationToken);
}
if (pipe != null)
{
var request = BuildRequest.Create(language,
buildPaths.WorkingDirectory,
arguments,
keepAlive,
libEnvVariable);
return TryCompile(pipe, request, cancellationToken);
}
}
finally
{
if (holdsMutex)
{
clientMutex.ReleaseMutex();
}
}
}
return Task.FromResult<BuildResponse>(new RejectedBuildResponse());
}
internal static bool WasServerMutexOpen(string mutexName)
{
Mutex mutex;
var open = Mutex.TryOpenExisting(mutexName, out mutex);
if (open)
{
mutex.Close();
return true;
}
return false;
}
/// <summary>
/// Try to compile using the server. Returns a null-containing Task if a response
/// from the server cannot be retrieved.
/// </summary>
private static async Task<BuildResponse> TryCompile(NamedPipeClientStream pipeStream,
BuildRequest request,
CancellationToken cancellationToken)
{
BuildResponse response;
using (pipeStream)
{
// Write the request
try
{
Log("Begin writing request");
await request.WriteAsync(pipeStream, cancellationToken).ConfigureAwait(false);
Log("End writing request");
}
catch (Exception e)
{
LogException(e, "Error writing build request.");
return new RejectedBuildResponse();
}
// Wait for the compilation and a monitor to detect if the server disconnects
var serverCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
Log("Begin reading response");
var responseTask = BuildResponse.ReadAsync(pipeStream, serverCts.Token);
var monitorTask = CreateMonitorDisconnectTask(pipeStream, serverCts.Token);
await Task.WhenAny(responseTask, monitorTask).ConfigureAwait(false);
Log("End reading response");
if (responseTask.IsCompleted)
{
// await the task to log any exceptions
try
{
response = await responseTask.ConfigureAwait(false);
}
catch (Exception e)
{
LogException(e, "Error reading response");
response = new RejectedBuildResponse();
}
}
else
{
Log("Server disconnect");
response = new RejectedBuildResponse();
}
// Cancel whatever task is still around
serverCts.Cancel();
Debug.Assert(response != null);
return response;
}
}
/// <summary>
/// The IsConnected property on named pipes does not detect when the client has disconnected
/// if we don't attempt any new I/O after the client disconnects. We start an async I/O here
/// which serves to check the pipe for disconnection.
///
/// This will return true if the pipe was disconnected.
/// </summary>
private static async Task CreateMonitorDisconnectTask(
NamedPipeClientStream pipeStream,
CancellationToken cancellationToken)
{
// Ignore this warning because the desktop projects don't target 4.6 yet
#pragma warning disable RS0007 // Avoid zero-length array allocations.
var buffer = new byte[0];
#pragma warning restore RS0007 // Avoid zero-length array allocations.
while (!cancellationToken.IsCancellationRequested && pipeStream.IsConnected)
{
// Wait a tenth of a second before trying again
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
try
{
Log("Before poking pipe.");
await pipeStream.ReadAsync(buffer, 0, 0, cancellationToken).ConfigureAwait(false);
Log("After poking pipe.");
}
// Ignore cancellation
catch (OperationCanceledException) { }
catch (Exception e)
{
// It is okay for this call to fail. Errors will be reflected in the
// IsConnected property which will be read on the next iteration of the
LogException(e, "Error poking pipe");
}
}
}
/// <summary>
/// Connect to the pipe for a given directory and return it.
/// Throws on cancellation.
/// </summary>
/// <param name="pipeName">Name of the named pipe to connect to.</param>
/// <param name="timeoutMs">Timeout to allow in connecting to process.</param>
/// <param name="cancellationToken">Cancellation token to cancel connection to server.</param>
/// <returns>
/// An open <see cref="NamedPipeClientStream"/> to the server process or null on failure.
/// </returns>
private static NamedPipeClientStream TryConnectToServer(
string pipeName,
int timeoutMs,
CancellationToken cancellationToken)
{
NamedPipeClientStream pipeStream;
try
{
// Machine-local named pipes are named "\\.\pipe\<pipename>".
// We use the SHA1 of the directory the compiler exes live in as the pipe name.
// The NamedPipeClientStream class handles the "\\.\pipe\" part for us.
Log("Attempt to open named pipe '{0}'", pipeName);
pipeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
cancellationToken.ThrowIfCancellationRequested();
Log("Attempt to connect named pipe '{0}'", pipeName);
pipeStream.Connect(timeoutMs);
Log("Named pipe '{0}' connected", pipeName);
cancellationToken.ThrowIfCancellationRequested();
// Verify that we own the pipe.
if (!CheckPipeConnectionOwnership(pipeStream))
{
Log("Owner of named pipe is incorrect");
return null;
}
return pipeStream;
}
catch (Exception e) when (!(e is TaskCanceledException))
{
LogException(e, "Exception while connecting to process");
return null;
}
}
/// <summary>
/// Create a new instance of the server process, returning true on success
/// and false otherwise.
/// </summary>
protected virtual bool TryCreateServer(string clientDir, string pipeName)
{
return TryCreateServerCore(clientDir, pipeName);
}
internal static bool TryCreateServerCore(string clientDir, string pipeName)
{
// The server should be in the same directory as the client
string expectedPath = Path.Combine(clientDir, ServerName);
if (!File.Exists(expectedPath))
return false;
// As far as I can tell, there isn't a way to use the Process class to
// create a process with no stdin/stdout/stderr, so we use P/Invoke.
// This code was taken from MSBuild task starting code.
STARTUPINFO startInfo = new STARTUPINFO();
startInfo.cb = Marshal.SizeOf(startInfo);
startInfo.hStdError = InvalidIntPtr;
startInfo.hStdInput = InvalidIntPtr;
startInfo.hStdOutput = InvalidIntPtr;
startInfo.dwFlags = STARTF_USESTDHANDLES;
uint dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW;
PROCESS_INFORMATION processInfo;
Log("Attempting to create process '{0}'", expectedPath);
var builder = new StringBuilder($@"""{expectedPath}"" ""-pipename:{pipeName}""");
bool success = CreateProcess(
lpApplicationName: null,
lpCommandLine: builder,
lpProcessAttributes: NullPtr,
lpThreadAttributes: NullPtr,
bInheritHandles: false,
dwCreationFlags: dwCreationFlags,
lpEnvironment: NullPtr, // Inherit environment
lpCurrentDirectory: clientDir,
lpStartupInfo: ref startInfo,
lpProcessInformation: out processInfo);
if (success)
{
Log("Successfully created process with process id {0}", processInfo.dwProcessId);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
else
{
Log("Failed to create process. GetLastError={0}", Marshal.GetLastWin32Error());
}
return success;
}
/// <summary>
/// Check to ensure that the named pipe server we connected to is owned by the same
/// user.
/// </summary>
/// <remarks>
/// The type is embedded in assemblies that need to run cross platform. While this particular
/// code will never be hit when running on non-Windows platforms it does need to work when
/// on Windows. To facilitate that we use reflection to make the check here to enable it to
/// compile into our cross plat assemblies.
/// </remarks>
private static bool CheckPipeConnectionOwnership(NamedPipeClientStream pipeStream)
{
try
{
var currentIdentity = WindowsIdentity.GetCurrent();
var currentOwner = currentIdentity.Owner;
var remotePipeSecurity = pipeStream.GetAccessControl();
var remoteOwner = remotePipeSecurity.GetOwner(typeof(SecurityIdentifier));
return currentOwner.Equals(remoteOwner);
}
catch (Exception ex)
{
Log("Exception checking pipe connection: {0}", ex.Message);
return false;
}
}
/// <summary>
/// Given the full path to the directory containing the compiler exes,
/// retrieves the name of the pipe for client/server communication on
/// that instance of the compiler.
/// </summary>
protected override string GetSessionKey(BuildPaths buildPaths)
{
return GetPipeNameForPath(buildPaths.ClientDirectory);
}
internal static string GetPipeNameForPath(string compilerExeDirectory)
{
var basePipeName = GetBasePipeName(compilerExeDirectory);
// Prefix with username and elevation
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
var isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
var userName = Environment.UserName;
return $"{userName}.{isAdmin}.{basePipeName}";
}
internal static string GetBasePipeName(string compilerExeDirectory)
{
// Normalize away trailing slashes. File APIs include / exclude this with no
// discernable pattern. Easiest to normalize it here vs. auditing every caller
// of this method.
compilerExeDirectory = compilerExeDirectory.TrimEnd(Path.DirectorySeparatorChar);
string basePipeName;
using (var sha = SHA256.Create())
{
var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(compilerExeDirectory));
basePipeName = Convert.ToBase64String(bytes)
.Replace("/", "_")
.Replace("=", string.Empty);
}
return basePipeName;
}
}
}