-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
IpcUtils.cs
481 lines (422 loc) · 17.2 KB
/
IpcUtils.cs
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Diagnostics.Tools.RuntimeClient;
using System.Threading;
using System.Linq;
using System.Reflection;
using System.Security.Principal;
// modified version of same code in dotnet/diagnostics for testing
namespace Tracing.Tests.Common
{
public static class Utils
{
public static readonly string DiagnosticPortsEnvKey = "DOTNET_DiagnosticPorts";
public static readonly string DiagnosticPortSuspend = "DOTNET_DefaultDiagnosticPortSuspend";
public static async Task<T> WaitTillTimeout<T>(Task<T> task, TimeSpan timeout)
{
using var cts = new CancellationTokenSource();
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, cts.Token));
if (completedTask == task)
{
cts.Cancel();
return await task;
}
else
{
throw new TimeoutException("Task timed out");
}
}
public static async Task WaitTillTimeout(Task task, TimeSpan timeout)
{
using var cts = new CancellationTokenSource();
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, cts.Token));
if (completedTask == task)
{
cts.Cancel();
return;
}
else
{
throw new TimeoutException("Task timed out");
}
}
public static async Task<bool> RunSubprocess(Assembly currentAssembly, Dictionary<string,string> environment, Func<Task> beforeExecution = null, Func<int, Task> duringExecution = null, Func<Task> afterExecution = null)
{
bool fSuccess = true;
using (var process = new Process())
{
if (beforeExecution != null)
await beforeExecution();
var stdoutSb = new StringBuilder();
var stderrSb = new StringBuilder();
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.Environment.Add("DOTNET_StressLog", "1"); // Turn on stresslog for subprocess
process.StartInfo.Environment.Add("DOTNET_LogFacility", "1000"); // Diagnostics Server Log Facility
process.StartInfo.Environment.Add("DOTNET_LogLevel", "10"); // Log everything
foreach ((string key, string value) in environment)
process.StartInfo.Environment.Add(key, value);
process.StartInfo.FileName = Process.GetCurrentProcess().MainModule.FileName;
process.StartInfo.Arguments = TestLibrary.Utilities.IsNativeAot ? "0" : $"{new Uri(currentAssembly.Location).LocalPath} 0";
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardError = true;
Logger.logger.Log($"running sub-process: {process.StartInfo.FileName} {process.StartInfo.Arguments}");
DateTime startTime = DateTime.Now;
process.OutputDataReceived += new DataReceivedEventHandler((s,e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
stdoutSb.Append($"\n\t{(DateTime.Now - startTime).TotalSeconds,5:f1}s: {e.Data}");
}
});
process.ErrorDataReceived += new DataReceivedEventHandler((s,e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
stderrSb.Append($"\n\t{(DateTime.Now - startTime).TotalSeconds,5:f1}s: {e.Data}");
}
});
process.EnableRaisingEvents = true;
fSuccess &= process.Start();
if (!fSuccess)
throw new Exception("Failed to start subprocess");
StreamWriter subprocessStdIn = process.StandardInput;
process.BeginOutputReadLine();
process.BeginErrorReadLine();
Logger.logger.Log($"subprocess started: {fSuccess}");
Logger.logger.Log($"subprocess PID: {process.Id}");
bool fGotToEnd = false;
process.Exited += (s, e) =>
{
Logger.logger.Log("================= Subprocess Exited =================");
if (!fGotToEnd)
{
Logger.logger.Log($"- Exit code: {process.ExitCode}");
Logger.logger.Log($"Subprocess stdout: {stdoutSb.ToString()}");
Logger.logger.Log($"Subprocess stderr: {stderrSb.ToString()}");
}
};
while (!EventPipeClient.ListAvailablePorts().Contains(process.Id))
{
Logger.logger.Log($"Standard Diagnostics Server connection not created yet -> try again in 100 ms");
await Task.Delay(100);
}
try
{
if (duringExecution != null)
await duringExecution(process.Id);
fGotToEnd = true;
Logger.logger.Log($"Sending 'exit' to subprocess stdin");
subprocessStdIn.WriteLine("exit");
subprocessStdIn.Close();
while (!process.WaitForExit(5000))
{
Logger.logger.Log("Subprocess didn't exit in 5 seconds!");
}
Logger.logger.Log($"SubProcess exited - Exit code: {process.ExitCode}");
fSuccess &= process.ExitCode == 0;
}
catch (Exception e)
{
Logger.logger.Log(e.ToString());
Logger.logger.Log($"Calling process.Kill()");
process.Kill();
fSuccess=false;
}
finally
{
Logger.logger.Log($"----------------------------------------");
Logger.logger.Log($"Subprocess stdout: {stdoutSb.ToString()}");
Logger.logger.Log($"Subprocess stderr: {stderrSb.ToString()}");
Logger.logger.Log($"----------------------------------------");
}
if (afterExecution != null)
await afterExecution();
}
return fSuccess;
}
public static void Assert(bool predicate, string message = "")
{
if (!predicate)
throw new Exception(message);
}
}
public class IpcHeader
{
IpcHeader() { }
public IpcHeader(byte commandSet, byte commandId)
{
CommandSet = (byte)commandSet;
CommandId = commandId;
}
// the number of bytes for the DiagnosticsIpc::IpcHeader type in native code
public static readonly UInt16 HeaderSizeInBytes = 20;
private static readonly UInt16 MagicSizeInBytes = 14;
public byte[] Magic = DotnetIpcV1; // byte[14] in native code
public UInt16 Size = HeaderSizeInBytes;
public byte CommandSet;
public byte CommandId;
public UInt16 Reserved = 0x0000;
// Helper expression to quickly get V1 magic string for comparison
// should be 14 bytes long
public static byte[] DotnetIpcV1 => Encoding.ASCII.GetBytes("DOTNET_IPC_V1" + '\0');
public byte[] Serialize()
{
using (var stream = new MemoryStream())
using (var writer = new BinaryWriter(stream))
{
writer.Write(Magic);
Debug.Assert(Magic.Length == MagicSizeInBytes);
writer.Write(Size);
writer.Write(CommandSet);
writer.Write(CommandId);
writer.Write((UInt16)0x0000);
writer.Flush();
return stream.ToArray();
}
}
public static IpcHeader TryParse(BinaryReader reader)
{
IpcHeader header = new IpcHeader
{
Magic = reader.ReadBytes(MagicSizeInBytes),
Size = reader.ReadUInt16(),
CommandSet = reader.ReadByte(),
CommandId = reader.ReadByte(),
Reserved = reader.ReadUInt16()
};
return header;
}
override public string ToString()
{
return $"{{ Magic={Magic}; Size={Size}; CommandSet={CommandSet}; CommandId={CommandId}; Reserved={Reserved} }}";
}
}
public class IpcMessage
{
public IpcMessage()
{ }
public IpcMessage(IpcHeader header, byte[] payload)
{
Payload = payload;
Header = header;
}
public IpcMessage(byte commandSet, byte commandId, byte[] payload = null)
: this(new IpcHeader(commandSet, commandId), payload)
{
}
public byte[] Payload { get; private set; } = null;
public IpcHeader Header { get; private set; } = default;
public byte[] Serialize()
{
byte[] serializedData = null;
// Verify things will fit in the size capacity
Header.Size = checked((UInt16)(IpcHeader.HeaderSizeInBytes + (Payload?.Length ?? 0)));
byte[] headerBytes = Header.Serialize();
using (var stream = new MemoryStream())
using (var writer = new BinaryWriter(stream))
{
writer.Write(headerBytes);
if (Payload != null)
writer.Write(Payload);
writer.Flush();
serializedData = stream.ToArray();
}
return serializedData;
}
public static IpcMessage Parse(Stream stream)
{
IpcMessage message = new IpcMessage();
using (var reader = new BinaryReader(stream, Encoding.UTF8, true))
{
message.Header = IpcHeader.TryParse(reader);
message.Payload = reader.ReadBytes(message.Header.Size - IpcHeader.HeaderSizeInBytes);
return message;
}
}
override public string ToString()
{
var sb = new StringBuilder();
sb.Append($"{{ Header={Header.ToString()}; ");
if (Payload != null)
{
sb.Append("Payload=[ ");
foreach (byte b in Payload)
sb.Append($"0x{b:X2} ");
sb.Append(" ]");
}
sb.Append("}");
return sb.ToString();
}
}
public class ProcessInfo
{
// uint64_t ProcessId;
// GUID RuntimeCookie;
// LPCWSTR CommandLine;
// LPCWSTR OS;
// LPCWSTR Arch;
public UInt64 ProcessId;
public Guid RuntimeCookie;
public string Commandline;
public string OS;
public string Arch;
public static ProcessInfo TryParse(byte[] buf)
{
var info = new ProcessInfo();
int start = 0;
int end = 8; /* sizeof(uint64_t) */
info.ProcessId = BitConverter.ToUInt64(buf[start..end]);
start = end;
end = start + 16; /* sizeof(guid) */
info.RuntimeCookie = new Guid(buf[start..end]);
string ParseString(ref int start, ref int end)
{
start = end;
end = start + 4; /* sizeof(uint32_t) */
uint nChars = BitConverter.ToUInt32(buf[start..end]);
start = end;
end = start + ((int)nChars * sizeof(char));
return System.Text.Encoding.Unicode.GetString(buf[start..end]).TrimEnd('\0');
}
info.Commandline = ParseString(ref start, ref end);
info.OS = ParseString(ref start, ref end);
info.Arch = ParseString(ref start, ref end);
return info;
}
}
public class ProcessInfo2
{
// uint64_t ProcessId;
// GUID RuntimeCookie;
// LPCWSTR CommandLine;
// LPCWSTR OS;
// LPCWSTR Arch;
public UInt64 ProcessId;
public Guid RuntimeCookie;
public string Commandline;
public string OS;
public string Arch;
public string ManagedEntrypointAssemblyName;
public string ClrProductVersion;
public static ProcessInfo2 TryParse(byte[] buf)
{
var info = new ProcessInfo2();
int start = 0;
int end = 8; /* sizeof(uint64_t) */
info.ProcessId = BitConverter.ToUInt64(buf[start..end]);
start = end;
end = start + 16; /* sizeof(guid) */
info.RuntimeCookie = new Guid(buf[start..end]);
string ParseString(ref int start, ref int end)
{
start = end;
end = start + 4; /* sizeof(uint32_t) */
uint nChars = BitConverter.ToUInt32(buf[start..end]);
start = end;
end = start + ((int)nChars * sizeof(char));
return System.Text.Encoding.Unicode.GetString(buf[start..end]).TrimEnd('\0');
}
info.Commandline = ParseString(ref start, ref end);
info.OS = ParseString(ref start, ref end);
info.Arch = ParseString(ref start, ref end);
info.ManagedEntrypointAssemblyName = ParseString(ref start, ref end);
info.ClrProductVersion = ParseString(ref start, ref end);
return info;
}
}
public class IpcClient
{
public static IpcMessage SendMessage(Stream stream, IpcMessage message)
{
using (stream)
{
Write(stream, message);
return Read(stream);
}
}
public static Stream SendMessage(Stream stream, IpcMessage message, out IpcMessage response)
{
Write(stream, message);
response = Read(stream);
return stream;
}
private static void Write(Stream stream, byte[] buffer)
{
stream.Write(buffer, 0, buffer.Length);
}
private static void Write(Stream stream, IpcMessage message)
{
Write(stream, message.Serialize());
}
private static IpcMessage Read(Stream stream)
{
return IpcMessage.Parse(stream);
}
}
public class ConnectionHelper
{
private static string IpcRootPath { get; } = OperatingSystem.IsWindows() ? @"\\.\pipe\" : Path.GetTempPath();
public static Stream GetStandardTransport(int processId)
{
try
{
var process = Process.GetProcessById(processId);
}
catch (System.ArgumentException)
{
throw new Exception($"Process {processId} is not running.");
}
catch (System.InvalidOperationException)
{
throw new Exception($"Process {processId} seems to be elevated.");
}
if (OperatingSystem.IsWindows())
{
string pipeName = $"dotnet-diagnostic-{processId}";
var namedPipe = new NamedPipeClientStream(
".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);
namedPipe.Connect(3);
return namedPipe;
}
else if (OperatingSystem.IsAndroid() || OperatingSystem.IsIOS() || OperatingSystem.IsTvOS())
{
TcpClient client = new TcpClient("127.0.0.1", 9000);
return client.GetStream();
}
else
{
string ipcPort;
try
{
ipcPort = Directory.GetFiles(IpcRootPath, $"dotnet-diagnostic-{processId}-*-socket") // Try best match.
.OrderByDescending(f => new FileInfo(f).LastWriteTime)
.FirstOrDefault();
if (ipcPort == null)
{
throw new Exception($"Process {processId} not running compatible .NET Core runtime.");
}
}
catch (InvalidOperationException)
{
throw new Exception($"Process {processId} not running compatible .NET Core runtime.");
}
string path = Path.Combine(IpcRootPath, ipcPort);
var remoteEP = new UnixDomainSocketEndPoint(path);
var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
socket.Connect(remoteEP);
return new NetworkStream(socket, ownsSocket: true);
}
}
}
}