-
Notifications
You must be signed in to change notification settings - Fork 374
/
Copy pathDiagnosticsClient.cs
722 lines (631 loc) · 34 KB
/
DiagnosticsClient.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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
// 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.Buffers.Binary;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Diagnostics.NETCore.Client
{
/// <summary>
/// This is a top-level class that contains methods to send various diagnostics command to the runtime.
/// </summary>
public sealed class DiagnosticsClient
{
private const string DumpOperationName = "Write dump";
private readonly IpcEndpoint _endpoint;
public DiagnosticsClient(int processId) :
this(new PidIpcEndpoint(processId))
{
}
internal DiagnosticsClient(IpcEndpointConfig config) :
this(new DiagnosticPortIpcEndpoint(config))
{
}
internal DiagnosticsClient(IpcEndpoint endpoint)
{
_endpoint = endpoint;
}
/// <summary>
/// Wait for an available diagnostic endpoint to the runtime instance.
/// </summary>
/// <param name="timeout">The amount of time to wait before cancelling the wait for the connection.</param>
internal void WaitForConnection(TimeSpan timeout)
{
_endpoint.WaitForConnection(timeout);
}
/// <summary>
/// Wait for an available diagnostic endpoint to the runtime instance.
/// </summary>
/// <param name="token">The token to monitor for cancellation requests.</param>
/// <returns>
/// A task the completes when a diagnostic endpoint to the runtime instance becomes available.
/// </returns>
internal Task WaitForConnectionAsync(CancellationToken token)
{
return _endpoint.WaitForConnectionAsync(token);
}
/// <summary>
/// Start tracing the application and return an EventPipeSession object
/// </summary>
/// <param name="providers">An IEnumerable containing the list of Providers to turn on.</param>
/// <param name="requestRundown">If true, request rundown events from the runtime</param>
/// <param name="circularBufferMB">The size of the runtime's buffer for collecting events in MB</param>
/// <returns>
/// An EventPipeSession object representing the EventPipe session that just started.
/// </returns>
public EventPipeSession StartEventPipeSession(IEnumerable<EventPipeProvider> providers, bool requestRundown = true, int circularBufferMB = 256)
{
return EventPipeSession.Start(_endpoint, providers, requestRundown, circularBufferMB);
}
/// <summary>
/// Start tracing the application and return an EventPipeSession object
/// </summary>
/// <param name="provider">An EventPipeProvider to turn on.</param>
/// <param name="requestRundown">If true, request rundown events from the runtime</param>
/// <param name="circularBufferMB">The size of the runtime's buffer for collecting events in MB</param>
/// <returns>
/// An EventPipeSession object representing the EventPipe session that just started.
/// </returns>
public EventPipeSession StartEventPipeSession(EventPipeProvider provider, bool requestRundown = true, int circularBufferMB = 256)
{
return EventPipeSession.Start(_endpoint, new[] { provider }, requestRundown, circularBufferMB);
}
/// <summary>
/// Start tracing the application and return an EventPipeSession object
/// </summary>
/// <param name="providers">An IEnumerable containing the list of Providers to turn on.</param>
/// <param name="requestRundown">If true, request rundown events from the runtime</param>
/// <param name="circularBufferMB">The size of the runtime's buffer for collecting events in MB</param>
/// <param name="token">The token to monitor for cancellation requests.</param>
/// <returns>
/// An EventPipeSession object representing the EventPipe session that just started.
/// </returns>
internal Task<EventPipeSession> StartEventPipeSessionAsync(IEnumerable<EventPipeProvider> providers, bool requestRundown, int circularBufferMB, CancellationToken token)
{
return EventPipeSession.StartAsync(_endpoint, providers, requestRundown, circularBufferMB, token);
}
/// <summary>
/// Start tracing the application and return an EventPipeSession object
/// </summary>
/// <param name="provider">An EventPipeProvider to turn on.</param>
/// <param name="requestRundown">If true, request rundown events from the runtime</param>
/// <param name="circularBufferMB">The size of the runtime's buffer for collecting events in MB</param>
/// <param name="token">The token to monitor for cancellation requests.</param>
/// <returns>
/// An EventPipeSession object representing the EventPipe session that just started.
/// </returns>
internal Task<EventPipeSession> StartEventPipeSessionAsync(EventPipeProvider provider, bool requestRundown, int circularBufferMB, CancellationToken token)
{
return EventPipeSession.StartAsync(_endpoint, new[] { provider }, requestRundown, circularBufferMB, token);
}
/// <summary>
/// Trigger a core dump generation.
/// </summary>
/// <param name="dumpType">Type of the dump to be generated</param>
/// <param name="dumpPath">Full path to the dump to be generated. By default it is /tmp/coredump.{pid}</param>
/// <param name="logDumpGeneration">When set to true, display the dump generation debug log to the console.</param>
public void WriteDump(DumpType dumpType, string dumpPath, bool logDumpGeneration = false)
{
WriteDump(dumpType, dumpPath, logDumpGeneration ? WriteDumpFlags.LoggingEnabled : WriteDumpFlags.None);
}
/// <summary>
/// Trigger a core dump generation.
/// </summary>
/// <param name="dumpType">Type of the dump to be generated</param>
/// <param name="dumpPath">Full path to the dump to be generated.</param>
/// <param name="flags">logging and crash report flags. On runtimes less than 6.0, only LoggingEnabled is supported.</param>
public void WriteDump(DumpType dumpType, string dumpPath, WriteDumpFlags flags)
{
WriteDump(dumpType, dumpPath, flags, logPath: null);
}
/// <summary>
/// Trigger a core dump generation.
/// </summary>
/// <param name="dumpType">Type of the dump to be generated</param>
/// <param name="dumpPath">Full path to the dump to be generated.</param>
/// <param name="flags">logging and crash report flags. On runtimes less than 6.0, only LoggingEnabled is supported.</param>
/// <param name="logPath">Full path to the log to be generated. If null or empty and flags requests logging - the default behavior is... </param>
public void WriteDump(DumpType dumpType, string dumpPath, WriteDumpFlags flags, string logPath)
{
IpcMessage request = CreateWriteDumpMessageV4(dumpType, dumpPath, flags, logPath);
IpcMessage response = IpcClient.SendMessage(_endpoint, request);
if (ValidateResponseMessage(response, DumpOperationName, ValidateResponseOptions.UnknownCommandReturnsFalse | ValidateResponseOptions.ErrorMessageReturned))
{
return;
}
if ((flags & (WriteDumpFlags.LogToFile | WriteDumpFlags.VerboseLoggingEnabled)) != 0)
{
throw new ArgumentException($"{nameof(WriteDumpFlags.LogToFile)} and {nameof(WriteDumpFlags.VerboseLoggingEnabled)} flags are not supported by the current runtime.", nameof(flags));
}
request = CreateWriteDumpMessage(DumpCommandId.GenerateCoreDump3, dumpType, dumpPath, flags);
response = IpcClient.SendMessage(_endpoint, request);
if (ValidateResponseMessage(response, DumpOperationName, ValidateResponseOptions.UnknownCommandReturnsFalse | ValidateResponseOptions.ErrorMessageReturned))
{
return;
}
request = CreateWriteDumpMessage(DumpCommandId.GenerateCoreDump2, dumpType, dumpPath, flags);
response = IpcClient.SendMessage(_endpoint, request);
if (ValidateResponseMessage(response, DumpOperationName, ValidateResponseOptions.UnknownCommandReturnsFalse))
{
return;
}
if ((flags & ~WriteDumpFlags.LoggingEnabled) != 0)
{
throw new ArgumentException($"Only {nameof(WriteDumpFlags.LoggingEnabled)} flag is supported by this runtime version", nameof(flags));
}
request = CreateWriteDumpMessage(dumpType, dumpPath, logDumpGeneration: (flags & WriteDumpFlags.LoggingEnabled) != 0);
response = IpcClient.SendMessage(_endpoint, request);
ValidateResponseMessage(response, DumpOperationName);
}
/// <summary>
/// Trigger a core dump generation.
/// </summary>
/// <param name="dumpType">Type of the dump to be generated</param>
/// <param name="dumpPath">Full path to the dump to be generated. By default it is /tmp/coredump.{pid}</param>
/// <param name="logDumpGeneration">When set to true, display the dump generation debug log to the console.</param>
/// <param name="token">The token to monitor for cancellation requests.</param>
public Task WriteDumpAsync(DumpType dumpType, string dumpPath, bool logDumpGeneration, CancellationToken token)
{
return WriteDumpAsync(dumpType, dumpPath, logDumpGeneration ? WriteDumpFlags.LoggingEnabled : WriteDumpFlags.None, token);
}
/// <summary>
/// Trigger a core dump generation.
/// </summary>
/// <param name="dumpType">Type of the dump to be generated</param>
/// <param name="dumpPath">Full path to the dump to be generated. By default it is /tmp/coredump.{pid}</param>
/// <param name="flags">logging and crash report flags. On runtimes less than 6.0, only LoggingEnabled is supported.</param>
/// <param name="token">The token to monitor for cancellation requests.</param>
public Task WriteDumpAsync(DumpType dumpType, string dumpPath, WriteDumpFlags flags, CancellationToken token)
{
return WriteDumpAsync(dumpType, dumpPath, flags, logPath: null, token);
}
/// <summary>
/// Trigger a core dump generation.
/// </summary>
/// <param name="dumpType">Type of the dump to be generated</param>
/// <param name="dumpPath">Full path to the dump to be generated. By default it is /tmp/coredump.{pid}</param>
/// <param name="flags">logging and crash report flags. On runtimes less than 6.0, only LoggingEnabled is supported.</param>
/// <param name="logPath">Full path to the log to be generated. If null or empty and flags requests logging - the default behavior is... </param>
/// <param name="token">The token to monitor for cancellation requests.</param>
public async Task WriteDumpAsync(DumpType dumpType, string dumpPath, WriteDumpFlags flags, string logPath, CancellationToken token)
{
IpcMessage request = CreateWriteDumpMessageV4(dumpType, dumpPath, flags, logPath);
IpcMessage response = await IpcClient.SendMessageAsync(_endpoint, request, token).ConfigureAwait(false);
if (ValidateResponseMessage(response, DumpOperationName, ValidateResponseOptions.UnknownCommandReturnsFalse | ValidateResponseOptions.ErrorMessageReturned))
{
return;
}
if ((flags & (WriteDumpFlags.LogToFile | WriteDumpFlags.VerboseLoggingEnabled)) != 0)
{
throw new ArgumentException($"{nameof(WriteDumpFlags.LogToFile)} and {nameof(WriteDumpFlags.VerboseLoggingEnabled)} flags are not supported by the current runtime.", nameof(flags));
}
request = CreateWriteDumpMessage(DumpCommandId.GenerateCoreDump3, dumpType, dumpPath, flags);
response = await IpcClient.SendMessageAsync(_endpoint, request, token).ConfigureAwait(false);
if (ValidateResponseMessage(response, DumpOperationName, ValidateResponseOptions.UnknownCommandReturnsFalse | ValidateResponseOptions.ErrorMessageReturned))
{
return;
}
request = CreateWriteDumpMessage(DumpCommandId.GenerateCoreDump2, dumpType, dumpPath, flags);
response = await IpcClient.SendMessageAsync(_endpoint, request, token).ConfigureAwait(false);
if (ValidateResponseMessage(response, DumpOperationName, ValidateResponseOptions.UnknownCommandReturnsFalse))
{
return;
}
if ((flags & ~WriteDumpFlags.LoggingEnabled) != 0)
{
throw new ArgumentException($"Only {nameof(WriteDumpFlags.LoggingEnabled)} flag is supported by this runtime version", nameof(flags));
}
request = CreateWriteDumpMessage(dumpType, dumpPath, logDumpGeneration: (flags & WriteDumpFlags.LoggingEnabled) != 0);
response = await IpcClient.SendMessageAsync(_endpoint, request, token).ConfigureAwait(false);
ValidateResponseMessage(response, DumpOperationName);
}
/// <summary>
/// Attach a profiler.
/// </summary>
/// <param name="attachTimeout">Timeout for attaching the profiler</param>
/// <param name="profilerGuid">Guid for the profiler to be attached</param>
/// <param name="profilerPath">Path to the profiler to be attached</param>
/// <param name="additionalData">Additional data to be passed to the profiler</param>
public void AttachProfiler(TimeSpan attachTimeout, Guid profilerGuid, string profilerPath, byte[] additionalData = null)
{
IpcMessage request = CreateAttachProfilerMessage(attachTimeout, profilerGuid, profilerPath, additionalData);
IpcMessage response = IpcClient.SendMessage(_endpoint, request);
ValidateResponseMessage(response, nameof(AttachProfiler));
// The call to set up the pipe and send the message operates on a different timeout than attachTimeout, which is for the runtime.
// We should eventually have a configurable timeout for the message passing, potentially either separately from the
// runtime timeout or respect attachTimeout as one total duration.
}
internal async Task AttachProfilerAsync(TimeSpan attachTimeout, Guid profilerGuid, string profilerPath, byte[] additionalData, CancellationToken token)
{
IpcMessage request = CreateAttachProfilerMessage(attachTimeout, profilerGuid, profilerPath, additionalData);
IpcMessage response = await IpcClient.SendMessageAsync(_endpoint, request, token).ConfigureAwait(false);
ValidateResponseMessage(response, nameof(AttachProfilerAsync));
}
/// <summary>
/// Set a profiler as the startup profiler. It is only valid to issue this command
/// while the runtime is paused at startup.
/// </summary>
/// <param name="profilerGuid">Guid for the profiler to be attached</param>
/// <param name="profilerPath">Path to the profiler to be attached</param>
public void SetStartupProfiler(Guid profilerGuid, string profilerPath)
{
IpcMessage request = CreateSetStartupProfilerMessage(profilerGuid, profilerPath);
IpcMessage response = IpcClient.SendMessage(_endpoint, request);
ValidateResponseMessage(response, nameof(SetStartupProfiler), ValidateResponseOptions.InvalidArgumentIsRequiresSuspension);
}
internal async Task SetStartupProfilerAsync(Guid profilerGuid, string profilerPath, CancellationToken token)
{
IpcMessage request = CreateSetStartupProfilerMessage(profilerGuid, profilerPath);
IpcMessage response = await IpcClient.SendMessageAsync(_endpoint, request, token).ConfigureAwait(false);
ValidateResponseMessage(response, nameof(SetStartupProfilerAsync), ValidateResponseOptions.InvalidArgumentIsRequiresSuspension);
}
/// <summary>
/// Tell the runtime to resume execution after being paused at startup.
/// </summary>
public void ResumeRuntime()
{
IpcMessage request = CreateResumeRuntimeMessage();
IpcMessage response = IpcClient.SendMessage(_endpoint, request);
ValidateResponseMessage(response, nameof(ResumeRuntime));
}
internal async Task ResumeRuntimeAsync(CancellationToken token)
{
IpcMessage request = CreateResumeRuntimeMessage();
IpcMessage response = await IpcClient.SendMessageAsync(_endpoint, request, token).ConfigureAwait(false);
ValidateResponseMessage(response, nameof(ResumeRuntimeAsync));
}
/// <summary>
/// Set an environment variable in the target process.
/// </summary>
/// <param name="name">The name of the environment variable to set.</param>
/// <param name="value">The value of the environment variable to set.</param>
public void SetEnvironmentVariable(string name, string value)
{
IpcMessage request = CreateSetEnvironmentVariableMessage(name, value);
IpcMessage response = IpcClient.SendMessage(_endpoint, request);
ValidateResponseMessage(response, nameof(SetEnvironmentVariable));
}
internal async Task SetEnvironmentVariableAsync(string name, string value, CancellationToken token)
{
IpcMessage request = CreateSetEnvironmentVariableMessage(name, value);
IpcMessage response = await IpcClient.SendMessageAsync(_endpoint, request, token).ConfigureAwait(false);
ValidateResponseMessage(response, nameof(SetEnvironmentVariableAsync));
}
/// <summary>
/// Gets all environement variables and their values from the target process.
/// </summary>
/// <returns>A dictionary containing all of the environment variables defined in the target process.</returns>
public Dictionary<string, string> GetProcessEnvironment()
{
IpcMessage message = CreateProcessEnvironmentMessage();
using IpcResponse response = IpcClient.SendMessageGetContinuation(_endpoint, message);
ValidateResponseMessage(response.Message, nameof(GetProcessEnvironmentAsync));
ProcessEnvironmentHelper helper = ProcessEnvironmentHelper.Parse(response.Message.Payload);
return helper.ReadEnvironment(response.Continuation);
}
internal async Task<Dictionary<string, string>> GetProcessEnvironmentAsync(CancellationToken token)
{
IpcMessage message = CreateProcessEnvironmentMessage();
using IpcResponse response = await IpcClient.SendMessageGetContinuationAsync(_endpoint, message, token).ConfigureAwait(false);
ValidateResponseMessage(response.Message, nameof(GetProcessEnvironmentAsync));
ProcessEnvironmentHelper helper = ProcessEnvironmentHelper.Parse(response.Message.Payload);
return await helper.ReadEnvironmentAsync(response.Continuation, token).ConfigureAwait(false);
}
/// <summary>
/// Get all the active processes that can be attached to.
/// </summary>
/// <returns>
/// IEnumerable of all the active process IDs.
/// </returns>
public static IEnumerable<int> GetPublishedProcesses()
{
static IEnumerable<int> GetAllPublishedProcesses(string[] files)
{
foreach (string port in files)
{
string fileName = new FileInfo(port).Name;
Match match = Regex.Match(fileName, PidIpcEndpoint.DiagnosticsPortPattern);
if (!match.Success)
{
continue;
}
string group = match.Groups[1].Value;
if (!int.TryParse(group, NumberStyles.Integer, CultureInfo.InvariantCulture, out int processId))
{
continue;
}
yield return processId;
}
}
try
{
string[] files = Directory.GetFiles(PidIpcEndpoint.IpcRootPath);
return GetAllPublishedProcesses(files).Distinct();
}
catch (UnauthorizedAccessException ex)
{
if (PidIpcEndpoint.IpcRootPath.StartsWith(@"\\.\pipe"))
{
throw new DiagnosticsClientException($"Enumerating {PidIpcEndpoint.IpcRootPath} is not authorized", ex);
}
else
{
throw;
}
}
}
internal ProcessInfo GetProcessInfo()
{
// Attempt to get ProcessInfo v2
ProcessInfo processInfo = TryGetProcessInfo2();
if (null != processInfo)
{
return processInfo;
}
IpcMessage request = CreateProcessInfoMessage();
using IpcResponse response = IpcClient.SendMessageGetContinuation(_endpoint, request);
return GetProcessInfoFromResponse(response, nameof(GetProcessInfo));
}
internal async Task<ProcessInfo> GetProcessInfoAsync(CancellationToken token)
{
// Attempt to get ProcessInfo v2
ProcessInfo processInfo = await TryGetProcessInfo2Async(token).ConfigureAwait(false);
if (null != processInfo)
{
return processInfo;
}
IpcMessage request = CreateProcessInfoMessage();
using IpcResponse response = await IpcClient.SendMessageGetContinuationAsync(_endpoint, request, token).ConfigureAwait(false);
return GetProcessInfoFromResponse(response, nameof(GetProcessInfoAsync));
}
private ProcessInfo TryGetProcessInfo2()
{
IpcMessage request = CreateProcessInfo2Message();
using IpcResponse response2 = IpcClient.SendMessageGetContinuation(_endpoint, request);
return TryGetProcessInfo2FromResponse(response2, nameof(GetProcessInfo));
}
private async Task<ProcessInfo> TryGetProcessInfo2Async(CancellationToken token)
{
IpcMessage request = CreateProcessInfo2Message();
using IpcResponse response2 = await IpcClient.SendMessageGetContinuationAsync(_endpoint, request, token).ConfigureAwait(false);
return TryGetProcessInfo2FromResponse(response2, nameof(GetProcessInfoAsync));
}
private static byte[] SerializePayload<T>(T arg)
{
using (MemoryStream stream = new())
using (BinaryWriter writer = new(stream))
{
SerializePayloadArgument(arg, writer);
writer.Flush();
return stream.ToArray();
}
}
private static byte[] SerializePayload<T1, T2>(T1 arg1, T2 arg2)
{
using (MemoryStream stream = new())
using (BinaryWriter writer = new(stream))
{
SerializePayloadArgument(arg1, writer);
SerializePayloadArgument(arg2, writer);
writer.Flush();
return stream.ToArray();
}
}
private static byte[] SerializePayload<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)
{
using (MemoryStream stream = new())
using (BinaryWriter writer = new(stream))
{
SerializePayloadArgument(arg1, writer);
SerializePayloadArgument(arg2, writer);
SerializePayloadArgument(arg3, writer);
writer.Flush();
return stream.ToArray();
}
}
private static byte[] SerializePayload<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
using (MemoryStream stream = new())
using (BinaryWriter writer = new(stream))
{
SerializePayloadArgument(arg1, writer);
SerializePayloadArgument(arg2, writer);
SerializePayloadArgument(arg3, writer);
SerializePayloadArgument(arg4, writer);
writer.Flush();
return stream.ToArray();
}
}
private static void SerializePayloadArgument<T>(T obj, BinaryWriter writer)
{
if (typeof(T) == typeof(string))
{
writer.WriteString((string)((object)obj));
}
else if (typeof(T) == typeof(int))
{
writer.Write((int)((object)obj));
}
else if (typeof(T) == typeof(uint))
{
writer.Write((uint)((object)obj));
}
else if (typeof(T) == typeof(bool))
{
bool bValue = (bool)((object)obj);
uint uiValue = bValue ? (uint)1 : 0;
writer.Write(uiValue);
}
else if (typeof(T) == typeof(Guid))
{
Guid guidVal = (Guid)((object)obj);
writer.Write(guidVal.ToByteArray());
}
else if (typeof(T) == typeof(byte[]))
{
byte[] byteArray = (byte[])((object)obj);
uint length = byteArray == null ? 0U : (uint)byteArray.Length;
writer.Write(length);
if (length > 0)
{
writer.Write(byteArray);
}
}
else
{
throw new ArgumentException($"Type {obj.GetType()} is not supported in SerializePayloadArgument, please add it.");
}
}
private static IpcMessage CreateAttachProfilerMessage(TimeSpan attachTimeout, Guid profilerGuid, string profilerPath, byte[] additionalData)
{
if (profilerGuid == null || profilerGuid == Guid.Empty)
{
throw new ArgumentException($"{nameof(profilerGuid)} must be a valid Guid");
}
if (string.IsNullOrEmpty(profilerPath))
{
throw new ArgumentException($"{nameof(profilerPath)} must be non-null");
}
byte[] serializedConfiguration = SerializePayload((uint)attachTimeout.TotalSeconds, profilerGuid, profilerPath, additionalData);
return new IpcMessage(DiagnosticsServerCommandSet.Profiler, (byte)ProfilerCommandId.AttachProfiler, serializedConfiguration);
}
private static IpcMessage CreateProcessEnvironmentMessage()
{
return new IpcMessage(DiagnosticsServerCommandSet.Process, (byte)ProcessCommandId.GetProcessEnvironment);
}
private static IpcMessage CreateProcessInfoMessage()
{
return new IpcMessage(DiagnosticsServerCommandSet.Process, (byte)ProcessCommandId.GetProcessInfo);
}
private static IpcMessage CreateProcessInfo2Message()
{
return new IpcMessage(DiagnosticsServerCommandSet.Process, (byte)ProcessCommandId.GetProcessInfo2);
}
private static IpcMessage CreateResumeRuntimeMessage()
{
return new IpcMessage(DiagnosticsServerCommandSet.Process, (byte)ProcessCommandId.ResumeRuntime);
}
private static IpcMessage CreateSetEnvironmentVariableMessage(string name, string value)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException($"{nameof(name)} must be non-null.");
}
byte[] serializedConfiguration = SerializePayload(name, value);
return new IpcMessage(DiagnosticsServerCommandSet.Process, (byte)ProcessCommandId.SetEnvironmentVariable, serializedConfiguration);
}
private static IpcMessage CreateSetStartupProfilerMessage(Guid profilerGuid, string profilerPath)
{
if (profilerGuid == null || profilerGuid == Guid.Empty)
{
throw new ArgumentException($"{nameof(profilerGuid)} must be a valid Guid");
}
if (string.IsNullOrEmpty(profilerPath))
{
throw new ArgumentException($"{nameof(profilerPath)} must be non-null");
}
byte[] serializedConfiguration = SerializePayload(profilerGuid, profilerPath);
return new IpcMessage(DiagnosticsServerCommandSet.Profiler, (byte)ProfilerCommandId.StartupProfiler, serializedConfiguration);
}
private static IpcMessage CreateWriteDumpMessage(DumpType dumpType, string dumpPath, bool logDumpGeneration)
{
if (string.IsNullOrEmpty(dumpPath))
{
throw new ArgumentNullException($"{nameof(dumpPath)} required");
}
byte[] payload = SerializePayload(dumpPath, (uint)dumpType, logDumpGeneration);
return new IpcMessage(DiagnosticsServerCommandSet.Dump, (byte)DumpCommandId.GenerateCoreDump, payload);
}
private static IpcMessage CreateWriteDumpMessage(DumpCommandId command, DumpType dumpType, string dumpPath, WriteDumpFlags flags)
{
if (string.IsNullOrEmpty(dumpPath))
{
throw new ArgumentNullException($"{nameof(dumpPath)} required");
}
byte[] payload = SerializePayload(dumpPath, (uint)dumpType, (uint)flags);
return new IpcMessage(DiagnosticsServerCommandSet.Dump, (byte)command, payload);
}
private static IpcMessage CreateWriteDumpMessageV4(DumpType dumpType, string dumpPath, WriteDumpFlags flags, string logPath)
{
if (string.IsNullOrEmpty(dumpPath))
{
throw new ArgumentNullException($"{nameof(dumpPath)} required");
}
byte[] payload = SerializePayload(dumpPath, (uint)dumpType, (uint)flags, logPath);
return new IpcMessage(DiagnosticsServerCommandSet.Dump, (byte)DumpCommandId.GenerateCoreDump4, payload);
}
private static ProcessInfo GetProcessInfoFromResponse(IpcResponse response, string operationName)
{
ValidateResponseMessage(response.Message, operationName);
return ProcessInfo.ParseV1(response.Message.Payload);
}
private static ProcessInfo TryGetProcessInfo2FromResponse(IpcResponse response, string operationName)
{
if (!ValidateResponseMessage(response.Message, operationName, ValidateResponseOptions.UnknownCommandReturnsFalse))
{
return null;
}
return ProcessInfo.ParseV2(response.Message.Payload);
}
internal static bool ValidateResponseMessage(IpcMessage responseMessage, string operationName, ValidateResponseOptions options = ValidateResponseOptions.None)
{
switch ((DiagnosticsServerResponseId)responseMessage.Header.CommandId)
{
case DiagnosticsServerResponseId.OK:
return true;
case DiagnosticsServerResponseId.Error:
uint hr = BinaryPrimitives.ReadUInt32LittleEndian(new ReadOnlySpan<byte>(responseMessage.Payload, 0, 4));
int index = sizeof(uint);
string message = null;
switch (hr)
{
case (uint)DiagnosticsIpcError.UnknownCommand:
if (options.HasFlag(ValidateResponseOptions.UnknownCommandReturnsFalse))
{
return false;
}
throw new UnsupportedCommandException($"{operationName} failed - Command is not supported.");
case (uint)DiagnosticsIpcError.ProfilerAlreadyActive:
throw new ProfilerAlreadyActiveException($"{operationName} failed - A profiler is already loaded.");
case (uint)DiagnosticsIpcError.InvalidArgument:
if (options.HasFlag(ValidateResponseOptions.InvalidArgumentIsRequiresSuspension))
{
throw new ServerErrorException($"{operationName} failed - The runtime must be suspended for this command.");
}
throw new UnsupportedCommandException($"{operationName} failed - Invalid command argument.");
case (uint)DiagnosticsIpcError.NotSupported:
message = $"{operationName} - Not supported by this runtime.";
break;
default:
break;
}
// Check if the command can return an error message and if the payload is big enough to contain the
// error code (uint) and the string length (uint).
if (options.HasFlag(ValidateResponseOptions.ErrorMessageReturned) && responseMessage.Payload.Length >= (sizeof(uint) * 2))
{
message = IpcHelpers.ReadString(responseMessage.Payload, ref index);
}
if (string.IsNullOrWhiteSpace(message))
{
message = $"{operationName} failed - HRESULT: 0x{hr:X8}.";
}
throw new ServerErrorException(message);
default:
throw new ServerErrorException($"{operationName} failed - Server responded with unknown response.");
}
}
[Flags]
internal enum ValidateResponseOptions
{
None = 0x0,
UnknownCommandReturnsFalse = 0x1,
InvalidArgumentIsRequiresSuspension = 0x2,
ErrorMessageReturned = 0x4,
}
}
}