-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathAsyncProfilerTests.cs
More file actions
2432 lines (2084 loc) · 117 KB
/
Copy pathAsyncProfilerTests.cs
File metadata and controls
2432 lines (2084 loc) · 117 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
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers.Binary;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Linq;
using Xunit;
namespace System.Threading.Tasks.Tests
{
// Mirrors AsyncProfiler.AsyncEventID from the runtime (which is internal and inaccessible from tests).
public enum AsyncEventID : byte
{
// Runtime (RuntimeAsync) events.
CreateRuntimeAsyncContext = 1,
ResumeRuntimeAsyncContext = 2,
SuspendRuntimeAsyncContext = 3,
CompleteRuntimeAsyncContext = 4,
UnwindRuntimeAsyncException = 5,
CreateRuntimeAsyncCallstack = 6,
ResumeRuntimeAsyncCallstack = 7,
SuspendRuntimeAsyncCallstack = 8,
ResumeRuntimeAsyncMethod = 9,
CompleteRuntimeAsyncMethod = 10,
// StateMachine (StateMachineAsync) events.
CreateStateMachineAsyncContext = 11,
ResumeStateMachineAsyncContext = 12,
SuspendStateMachineAsyncContext = 13,
CompleteStateMachineAsyncContext = 14,
UnwindStateMachineAsyncException = 15,
ResumeStateMachineAsyncCallstack = 16,
ResumeStateMachineAsyncMethod = 17,
CompleteStateMachineAsyncMethod = 18,
AppendStateMachineAsyncCallstack = 19,
// Neutral profiler events.
ResetAsyncThreadContext = 20,
ResetAsyncContinuationWrapperIndex = 21,
AsyncProfilerMetadata = 22,
AsyncProfilerSyncClock = 23,
}
public enum AsyncCallstackType : byte
{
StateMachine = 0x1,
Runtime = 0x2,
}
internal readonly record struct EventManifestEntry(AsyncEventID EventId, byte Version, byte FieldSize);
internal static class EventManifest
{
// Default manifest matching the current runtime emit; replaced when the parser
// observes an AsyncProfilerMetadata event carrying a per-event manifest.
// Dense, ordered by ascending (byte)AsyncEventID; lookups use (byte)id - 1.
public static readonly EventManifestEntry[] DefaultEntries = BuildDefaultEntries();
private static EventManifestEntry[] BuildDefaultEntries()
{
const byte NoPayload = 0;
const byte BytePayloadLength = 1;
const byte UShortPayloadLength = 2;
return
[
new EventManifestEntry(AsyncEventID.CreateRuntimeAsyncContext, 1, BytePayloadLength),
new EventManifestEntry(AsyncEventID.ResumeRuntimeAsyncContext, 1, BytePayloadLength),
new EventManifestEntry(AsyncEventID.SuspendRuntimeAsyncContext, 1, NoPayload),
new EventManifestEntry(AsyncEventID.CompleteRuntimeAsyncContext, 1, NoPayload),
new EventManifestEntry(AsyncEventID.UnwindRuntimeAsyncException, 1, BytePayloadLength),
new EventManifestEntry(AsyncEventID.CreateRuntimeAsyncCallstack, 1, UShortPayloadLength),
new EventManifestEntry(AsyncEventID.ResumeRuntimeAsyncCallstack, 1, UShortPayloadLength),
new EventManifestEntry(AsyncEventID.SuspendRuntimeAsyncCallstack, 1, UShortPayloadLength),
new EventManifestEntry(AsyncEventID.ResumeRuntimeAsyncMethod, 1, NoPayload),
new EventManifestEntry(AsyncEventID.CompleteRuntimeAsyncMethod, 1, NoPayload),
new EventManifestEntry(AsyncEventID.CreateStateMachineAsyncContext, 1, BytePayloadLength),
new EventManifestEntry(AsyncEventID.ResumeStateMachineAsyncContext, 1, BytePayloadLength),
new EventManifestEntry(AsyncEventID.SuspendStateMachineAsyncContext, 1, NoPayload),
new EventManifestEntry(AsyncEventID.CompleteStateMachineAsyncContext, 1, NoPayload),
new EventManifestEntry(AsyncEventID.UnwindStateMachineAsyncException, 1, BytePayloadLength),
new EventManifestEntry(AsyncEventID.ResumeStateMachineAsyncCallstack, 1, UShortPayloadLength),
new EventManifestEntry(AsyncEventID.ResumeStateMachineAsyncMethod, 1, NoPayload),
new EventManifestEntry(AsyncEventID.CompleteStateMachineAsyncMethod, 1, NoPayload),
new EventManifestEntry(AsyncEventID.AppendStateMachineAsyncCallstack, 1, UShortPayloadLength),
new EventManifestEntry(AsyncEventID.ResetAsyncThreadContext, 1, NoPayload),
new EventManifestEntry(AsyncEventID.ResetAsyncContinuationWrapperIndex, 1, NoPayload),
new EventManifestEntry(AsyncEventID.AsyncProfilerMetadata, 1, UShortPayloadLength),
new EventManifestEntry(AsyncEventID.AsyncProfilerSyncClock, 1, BytePayloadLength),
];
}
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/127951", TestPlatforms.Android | TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)]
public partial class AsyncProfilerTests
{
// The test scenarios drive async work via Task.Run(...).GetAwaiter().GetResult() (see
// RunScenarioAndFlush / RunScenario), which requires synchronous blocking waits. On
// single-threaded WASM this throws PlatformNotSupportedException from
// RuntimeFeature.ThrowIfMultithreadingIsNotSupported(), so gate the tests on both
// runtime async support and threading support.
public static bool IsRuntimeAsyncAndThreadingSupported =>
PlatformDetection.IsRuntimeAsyncSupported && PlatformDetection.IsMultithreadingSupported;
// Gate for tests that can run without threading (e.g., single-threaded WASM).
// These tests use async Task methods with await instead of Task.Run blocking.
public static bool IsRuntimeAsyncSupported => PlatformDetection.IsRuntimeAsyncSupported;
// StateMachine (StateMachineAsync_*) async-task instrumentation is the classic compiler-generated
// state machine (V1). It does not require runtime-async (V2), so it is supported on every runtime
// (CoreCLR and Mono) except NativeAOT, where it is opt-out to avoid ~100KB of per-state-machine
// generic instantiation overhead. Tests that depend on StateMachine events must be gated on these
// properties so they are skipped on NAOT.
public static bool IsStateMachineAsyncSupported =>
!PlatformDetection.IsNativeAot;
public static bool IsStateMachineAsyncAndThreadingSupported =>
IsStateMachineAsyncSupported && PlatformDetection.IsMultithreadingSupported;
// Gate for tests that exercise a mixed V1 (StateMachine) + V2 (RuntimeAsync) chain: they need both
// instrumentation paths, and V1 is disabled on NativeAOT, so require both conditions.
public static bool IsStateMachineAsyncAndRuntimeAsyncAndThreadingSupported =>
IsStateMachineAsyncAndThreadingSupported && IsRuntimeAsyncAndThreadingSupported;
// Alias so tests that additionally require CoreCLR can list the exclusion as an extra ConditionalFact
// condition alongside the shared gates.
public static bool IsNotMonoRuntime => PlatformDetection.IsNotMonoRuntime;
// Gate for the async dispatch-frame name-contract tests below: they reflect into CoreCLR-specific
// internal types, which is only reliable on the CoreCLR JIT (not Mono, and not NativeAOT where
// reflection is metadata-trimmed).
public static bool IsCoreClrJitRuntime =>
PlatformDetection.IsNotMonoRuntime && !PlatformDetection.IsNativeAot;
// Async dispatch-frame NAME contract (shared helpers; V1-specific tests live in AsyncProfilerV1Tests.cs
// and V2-specific tests in AsyncProfilerV2Tests.cs).
private const BindingFlags DeclaredInstanceMethod =
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
private static Type GetCoreLibType(string fullName)
{
Type? type = typeof(object).Assembly.GetType(fullName, throwOnError: false);
Assert.True(type is not null, $"Type '{fullName}' was not found in System.Private.CoreLib.");
return type!;
}
private static Type GetCoreLibNestedType(string declaringTypeFullName, string nestedTypeName)
{
Type? nested = GetCoreLibType(declaringTypeFullName).GetNestedType(nestedTypeName, BindingFlags.NonPublic);
Assert.True(nested is not null, $"Nested type '{nestedTypeName}' was not found on '{declaringTypeFullName}'.");
return nested!;
}
// AsyncProfiler.ContinuationWrapper - the V2 wrapper pool the stitcher keys off by name.
private static Type ContinuationWrapperType =>
GetCoreLibNestedType("System.Runtime.CompilerServices.AsyncProfiler", "ContinuationWrapper");
// Asserts the async dispatch method the stitcher recognizes by name still exists under that name.
// Keys mirror the string constants in the stitcher's AsyncStitchBoundary classifier.
private static MethodInfo AssertAsyncDispatchMethodExists(string key)
{
MethodInfo? method = key switch
{
"V1.MoveNextAsDispatcher" =>
GetCoreLibNestedType("System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1", "AsyncProfilerAsyncStateMachineBox`1")
.GetMethod("MoveNextAsDispatcher", DeclaredInstanceMethod),
"V1.AsyncStateMachineDispatcher.MoveNext" =>
GetCoreLibType("System.Runtime.CompilerServices.AsyncStateMachineDispatcher")
.GetMethod("MoveNext", DeclaredInstanceMethod),
"V2.DispatchContinuations" =>
GetCoreLibNestedType("System.Runtime.CompilerServices.AsyncHelpers", "RuntimeAsyncTask`1")
.GetMethod("DispatchContinuations", DeclaredInstanceMethod),
"V2.InstrumentedDispatchContinuations" =>
GetCoreLibNestedType("System.Runtime.CompilerServices.AsyncHelpers", "RuntimeAsyncTask`1")
.GetMethod("InstrumentedDispatchContinuations", DeclaredInstanceMethod),
_ => throw new ArgumentOutOfRangeException(nameof(key), key, "Unknown async dispatch method key."),
};
Assert.True(method is not null,
$"Async dispatch method for contract key '{key}' was not found; the CPU stitcher recognizes it by name.");
return method!;
}
private static void AssertMethodImplementationFlags(
MethodInfo method, MethodImplAttributes requiredFlags, string contractKey)
{
MethodImplAttributes actualFlags = method.GetMethodImplementationFlags();
Assert.True((actualFlags & requiredFlags) == requiredFlags,
$"Async dispatch method for contract key '{contractKey}' must have implementation flags " +
$"'{requiredFlags}' but had '{actualFlags}'.");
}
// ------------------------------------------------------------------------------------------------
// Real-callstack boundary layout.
//
// Beyond asserting the boundary methods exist (name contract above), these helpers capture the actual
// physical managed stack from inside a resumed async continuation and verify the stitcher-recognized
// boundary frames are present in the expected leaf->root order -- exactly what an unfiltered CPU sample
// would contain. StackTrace.GetFrames() does NOT drop [StackTraceHidden] frames on any runtime (only
// ToString filters them), so the boundary frames are visible even though they are hidden from managed
// stack traces.
// ------------------------------------------------------------------------------------------------
// Maps a captured frame's method identity to its stitcher boundary label, or null if not a boundary.
private static string? ClassifyAsyncBoundaryFrame(DiagnosticMethodInfo? info)
{
if (info is null)
{
return null;
}
string name = info.Name;
string typeName = info.DeclaringTypeName ?? string.Empty;
return name switch
{
_ when name.StartsWith("Continuation_Wrapper_", StringComparison.Ordinal) => "Wrapper",
"DispatchContinuations" => "V2.DispatchContinuations",
"InstrumentedDispatchContinuations" => "V2.InstrumentedDispatchContinuations",
"MoveNextAsDispatcher" => "V1.MoveNextAsDispatcher",
"MoveNext" when typeName.EndsWith("AsyncStateMachineDispatcher", StringComparison.Ordinal)
=> "V1.AsyncStateMachineDispatcher.MoveNext",
_ => null,
};
}
// Captures the current thread's physical managed stack UNFILTERED and returns the stitcher-recognized
// async boundary labels in leaf->root order. Must be called from inside a resumed async continuation
// (while the async profiler is active) so the dispatch machinery is on the stack.
private static (List<string> Boundaries, List<string> DiagnosticFrames) CaptureAsyncBoundarySequence()
{
var capture = CaptureAsyncStack();
return (capture.Boundaries, capture.DiagnosticFrames);
}
// Captures the physical stack once and returns, all leaf->root: the stitcher boundary labels, the
// per-frame declaring type names, and diagnostic frame names. The declaring type names let
// inline-completion tests locate a still-completing child's state-machine frame (its method name is the
// compiler-generated MoveNext, so it is identified by its declaring state-machine type name) relative
// to the resuming parent frame. The diagnostic names preserve every captured frame for failure output.
private static (List<string> Boundaries, List<string> DeclaringTypeNames, List<string> DiagnosticFrames) CaptureAsyncStack()
{
var boundaries = new List<string>();
var typeNames = new List<string>();
var diagnosticFrames = new List<string>();
foreach (StackFrame frame in new StackTrace(fNeedFileInfo: false).GetFrames())
{
DiagnosticMethodInfo? info = DiagnosticMethodInfo.Create(frame);
string typeName = info?.DeclaringTypeName ?? "<unknown-type>";
string methodName = info?.Name ?? "<unknown-method>";
typeNames.Add(typeName);
diagnosticFrames.Add($"{typeName}::{methodName}");
string? label = ClassifyAsyncBoundaryFrame(info);
if (label is not null)
{
boundaries.Add(label);
}
}
return (boundaries, typeNames, diagnosticFrames);
}
// Asserts that expectedLeafToRoot appears as an ordered subsequence of the captured boundary labels
// (leaf->root). Subsequence (not contiguous) matching tolerates unrelated frames between boundaries
// and repeated boundaries from nested resumes, while still enforcing the required relative order.
private static void AssertBoundarySubsequence(
List<string> capturedLeafToRoot,
List<string> diagnosticFramesLeafToRoot,
params string[] expectedLeafToRoot)
{
int matched = 0;
foreach (string label in capturedLeafToRoot)
{
if (matched < expectedLeafToRoot.Length && label == expectedLeafToRoot[matched])
{
matched++;
}
}
Assert.True(matched == expectedLeafToRoot.Length,
$"Expected async boundary frames [{string.Join(" -> ", expectedLeafToRoot)}] (leaf->root) were not all " +
$"present in order. Captured boundaries (leaf->root): [{string.Join(" -> ", capturedLeafToRoot)}]. " +
$"Captured diagnostic frames (leaf->root): [{string.Join(" -> ", diagnosticFramesLeafToRoot)}].");
}
// Asserts each expected fragment appears (as a substring of a declaring type name) as an ordered
// subsequence of the captured declaring type names (leaf->root), tolerating unrelated frames between.
// Used to locate specific user state-machine frames by the method name embedded in their generated type.
private static void AssertFrameOrder(
List<string> capturedLeafToRoot,
List<string> diagnosticFramesLeafToRoot,
params string[] expectedFragmentsLeafToRoot)
{
int matched = 0;
foreach (string typeName in capturedLeafToRoot)
{
if (matched < expectedFragmentsLeafToRoot.Length &&
typeName.Contains(expectedFragmentsLeafToRoot[matched], StringComparison.Ordinal))
{
matched++;
}
}
Assert.True(matched == expectedFragmentsLeafToRoot.Length,
$"Expected frames [{string.Join(" -> ", expectedFragmentsLeafToRoot)}] (leaf->root) were not all present " +
$"in order. Captured declaring types (leaf->root): [{string.Join(" -> ", capturedLeafToRoot)}]. " +
$"Captured diagnostic frames (leaf->root): [{string.Join(" -> ", diagnosticFramesLeafToRoot)}].");
}
private const string AsyncProfilerEventSourceName = "System.Runtime.CompilerServices.AsyncProfilerEventSource";
private const string WrapperNameTemplate = "Continuation_Wrapper_{0}";
private static readonly string WrapperNamePrefix = WrapperNameTemplate.Substring(0, WrapperNameTemplate.IndexOf("{0}", StringComparison.Ordinal));
private const int AsyncEventsId = 1;
private const int HeaderSize = 1 + sizeof(uint) + sizeof(uint) + sizeof(ulong) + sizeof(uint) + sizeof(ulong) + sizeof(ulong);
// AsyncProfilerEventSource Keywords matching the event source definition
private const EventKeywords CreateRuntimeAsyncContextKeyword = (EventKeywords)0x1;
private const EventKeywords ResumeRuntimeAsyncContextKeyword = (EventKeywords)0x2;
private const EventKeywords SuspendRuntimeAsyncContextKeyword = (EventKeywords)0x4;
private const EventKeywords CompleteRuntimeAsyncContextKeyword = (EventKeywords)0x8;
private const EventKeywords UnwindRuntimeAsyncExceptionKeyword = (EventKeywords)0x10;
private const EventKeywords CreateRuntimeAsyncCallstackKeyword = (EventKeywords)0x20;
private const EventKeywords ResumeRuntimeAsyncCallstackKeyword = (EventKeywords)0x40;
private const EventKeywords SuspendRuntimeAsyncCallstackKeyword = (EventKeywords)0x80;
private const EventKeywords ResumeRuntimeAsyncMethodKeyword = (EventKeywords)0x100;
private const EventKeywords CompleteRuntimeAsyncMethodKeyword = (EventKeywords)0x200;
private const EventKeywords CreateStateMachineAsyncContextKeyword = (EventKeywords)0x400;
private const EventKeywords ResumeStateMachineAsyncContextKeyword = (EventKeywords)0x800;
private const EventKeywords SuspendStateMachineAsyncContextKeyword = (EventKeywords)0x1000;
private const EventKeywords CompleteStateMachineAsyncContextKeyword = (EventKeywords)0x2000;
private const EventKeywords UnwindStateMachineAsyncExceptionKeyword = (EventKeywords)0x4000;
private const EventKeywords ResumeStateMachineAsyncCallstackKeyword = (EventKeywords)0x8000;
private const EventKeywords ResumeStateMachineAsyncMethodKeyword = (EventKeywords)0x10000;
private const EventKeywords CompleteStateMachineAsyncMethodKeyword = (EventKeywords)0x20000;
private const EventKeywords AllRuntimeAsyncKeywords =
CreateRuntimeAsyncContextKeyword |
ResumeRuntimeAsyncContextKeyword |
SuspendRuntimeAsyncContextKeyword |
CompleteRuntimeAsyncContextKeyword |
UnwindRuntimeAsyncExceptionKeyword |
CreateRuntimeAsyncCallstackKeyword |
ResumeRuntimeAsyncCallstackKeyword |
SuspendRuntimeAsyncCallstackKeyword |
ResumeRuntimeAsyncMethodKeyword |
CompleteRuntimeAsyncMethodKeyword;
private const EventKeywords AllStateMachineAsyncKeywords =
CreateStateMachineAsyncContextKeyword |
ResumeStateMachineAsyncContextKeyword |
SuspendStateMachineAsyncContextKeyword |
CompleteStateMachineAsyncContextKeyword |
UnwindStateMachineAsyncExceptionKeyword |
ResumeStateMachineAsyncCallstackKeyword |
ResumeStateMachineAsyncMethodKeyword |
CompleteStateMachineAsyncMethodKeyword;
private const EventKeywords AllKeywords =
AllRuntimeAsyncKeywords |
AllStateMachineAsyncKeywords;
private const EventKeywords RuntimeAsyncCoreKeywords =
CreateRuntimeAsyncContextKeyword |
ResumeRuntimeAsyncContextKeyword |
SuspendRuntimeAsyncContextKeyword |
CompleteRuntimeAsyncContextKeyword;
private const EventKeywords StateMachineAsyncCoreKeywords =
CreateStateMachineAsyncContextKeyword |
ResumeStateMachineAsyncContextKeyword |
SuspendStateMachineAsyncContextKeyword |
CompleteStateMachineAsyncContextKeyword;
private const EventKeywords RuntimeAsyncMethodKeywords =
ResumeRuntimeAsyncMethodKeyword |
CompleteRuntimeAsyncMethodKeyword;
private const EventKeywords StateMachineAsyncMethodKeywords =
ResumeStateMachineAsyncMethodKeyword |
CompleteStateMachineAsyncMethodKeyword;
private const EventKeywords RuntimeAsyncCallstackKeywords =
CreateRuntimeAsyncContextKeyword |
CreateRuntimeAsyncCallstackKeyword |
ResumeRuntimeAsyncContextKeyword |
ResumeRuntimeAsyncCallstackKeyword |
SuspendRuntimeAsyncContextKeyword |
SuspendRuntimeAsyncCallstackKeyword |
CompleteRuntimeAsyncContextKeyword |
CompleteRuntimeAsyncMethodKeyword |
UnwindRuntimeAsyncExceptionKeyword;
private const EventKeywords StateMachineAsyncCallstackKeywords =
CreateStateMachineAsyncContextKeyword |
ResumeStateMachineAsyncContextKeyword |
SuspendStateMachineAsyncContextKeyword |
ResumeStateMachineAsyncCallstackKeyword |
CompleteStateMachineAsyncContextKeyword |
CompleteStateMachineAsyncMethodKeyword |
UnwindStateMachineAsyncExceptionKeyword;
// CoreCLR has StackFrame.GetMethodFromNativeIP (static, non-public).
private static readonly MethodInfo? s_getMethodFromNativeIPMethod =
typeof(StackFrame).GetMethod("GetMethodFromNativeIP", BindingFlags.Static | BindingFlags.NonPublic);
// NativeAOT has DiagnosticMethodInfo.Create(StackFrame) (instance, non-public).
private static readonly ConstructorInfo? s_stackFrameFromIPCtor =
s_getMethodFromNativeIPMethod is null
? typeof(StackFrame).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(IntPtr), typeof(bool) }, null)
: null;
private static string? GetMethodNameFromMethodId(AsyncCallstackType callstackType, ulong methodId)
{
if (methodId != 0)
{
if (s_getMethodFromNativeIPMethod is not null)
{
MethodBase? method = (MethodBase?)s_getMethodFromNativeIPMethod.Invoke(null, new object[] { (IntPtr)methodId });
if (callstackType == AsyncCallstackType.Runtime)
{
return method?.Name;
}
else
{
return ExtractStateMachineMethodName(method?.DeclaringType?.Name);
}
}
if (s_stackFrameFromIPCtor is not null)
{
StackFrame frame = (StackFrame)s_stackFrameFromIPCtor.Invoke(new object[] { (IntPtr)methodId, false })!;
DiagnosticMethodInfo? diagInfo = DiagnosticMethodInfo.Create(frame);
if (callstackType == AsyncCallstackType.Runtime)
{
return diagInfo?.Name;
}
else
{
return ExtractStateMachineMethodName(diagInfo?.DeclaringTypeName);
}
}
// Mono fallback (no managed IP->method API): resolve via the reverse method-id map.
return ResolveStateMachineMethodNameFromId(methodId);
}
return null;
}
// Mono has no managed IP->method API, so the reflective resolvers above return null there and a
// frame's method id (a native code IP) can't be mapped back to a name. As a fallback we build a
// reverse map from method id -> async method name by scanning every compiler-generated async state
// machine reachable from the test class and computing the SAME id the runtime emits for a
// StateMachine frame, i.e. the native code of MoveNext (see AsyncStateMachineDiagnostics<T>.
// ResolveMethodId). This covers frame name resolution and the console dump uniformly on Mono.
//
// The IntPtr overload of GetNativeCodeInternal only exists on Mono (CoreCLR's takes an
// IRuntimeMethodInfo), so this reflection yields null on CoreCLR/NativeAOT and the fallback is a
// no-op there, leaving the robust IP->name resolution untouched.
private static readonly MethodInfo? s_getNativeCodeInternalMethod =
typeof(RuntimeMethodHandle).GetMethod(
"GetNativeCodeInternal",
BindingFlags.Static | BindingFlags.NonPublic,
null,
new[] { typeof(IntPtr) },
null);
// Set of (resolved name, state machine MoveNext handle) for every async state machine reachable
// from the test class, built once. This includes not just async methods declared on the test class
// but also async lambdas and local functions, whose compiler-generated state machines are nested
// types (under the test class or its display classes) implementing IAsyncStateMachine. Any of these
// can appear as a continuation frame, so all must be covered.
private static readonly Lazy<(string Name, IntPtr MoveNextHandle)[]> s_stateMachineMoveNextMethods =
new(BuildStateMachineMoveNextMethods);
// Resolved map: state machine frame method id (native code IP of MoveNext) -> async method name.
// Filled lazily on the first resolve miss, and eagerly by tests (SnapshotStateMachineMethodIdFor) that
// need to capture a method's tier-0 id before re-tiering; additive and keyed by address.
private static readonly ConcurrentDictionary<ulong, string> s_methodIdToName = new();
private static (string Name, IntPtr MoveNextHandle)[] BuildStateMachineMoveNextMethods()
{
var result = new List<(string, IntPtr)>();
CollectStateMachineMoveNextMethods(typeof(AsyncProfilerTests), result);
return result.ToArray();
}
// Recursively walks nested types looking for compiler-generated async state machines (types that
// implement IAsyncStateMachine) and records their MoveNext, named the same way IP->name resolution
// does on other runtimes (ExtractStateMachineMethodName over the state machine type name) so the
// fallback is indistinguishable from the primary resolver.
private static void CollectStateMachineMoveNextMethods(Type type, List<(string, IntPtr)> result)
{
foreach (Type nested in type.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic))
{
if (!nested.ContainsGenericParameters
&& typeof(System.Runtime.CompilerServices.IAsyncStateMachine).IsAssignableFrom(nested))
{
MethodInfo? moveNext = nested.GetMethod(
"MoveNext",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (moveNext is not null)
{
result.Add((ExtractStateMachineMethodName(nested.Name) ?? nested.Name, moveNext.MethodHandle.Value));
}
}
CollectStateMachineMoveNextMethods(nested, result);
}
}
// Records the CURRENT native code start of every known state machine MoveNext into the id->name map.
// Used by the resolve path, which only has a raw frame address and so must consider every method.
// A MoveNext has no native code start until it has actually run, and a resume frame's method id is the
// code start of whatever version was current when the runtime first froze that id. The map is additive
// and keyed by address. No-op except on Mono.
private static void SnapshotStateMachineMethodIds()
{
if (s_getNativeCodeInternalMethod is null)
{
return;
}
foreach ((string methodName, IntPtr moveNextHandle) in s_stateMachineMoveNextMethods.Value)
{
object? nativeCode = s_getNativeCodeInternalMethod.Invoke(null, new object[] { moveNextHandle });
if (nativeCode is IntPtr ip && ip != IntPtr.Zero)
{
s_methodIdToName.TryAdd((ulong)(nuint)ip, methodName);
}
}
}
// Records the CURRENT native code start of a single async method's compiler-generated state machine
// MoveNext (found via its [AsyncStateMachine] attribute) into the id->name map, keyed to the async
// method's name so it matches normal resolution. On Mono the interpreter re-tiers a method after
// enough calls, replacing its code start, while the resume frames keep the initial (tier-0) id frozen
// at first run; a test that calls a method enough to trigger re-tiering can snapshot its id up front,
// while the method is still at its tier-0 version, so the frozen id stays resolvable afterwards.
// No-op except on Mono.
private static void SnapshotStateMachineMethodIdFor(MethodInfo asyncMethod)
{
if (s_getNativeCodeInternalMethod is null)
{
return;
}
Type? stateMachineType = asyncMethod
.GetCustomAttribute<System.Runtime.CompilerServices.AsyncStateMachineAttribute>()?.StateMachineType;
MethodInfo? moveNext = stateMachineType?.GetMethod(
"MoveNext",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (moveNext is null)
{
return;
}
object? nativeCode = s_getNativeCodeInternalMethod.Invoke(null, new object[] { moveNext.MethodHandle.Value });
if (nativeCode is IntPtr ip && ip != IntPtr.Zero)
{
s_methodIdToName.TryAdd((ulong)(nuint)ip, asyncMethod.Name);
}
}
// Mono fallback: resolve a StateMachine frame's method id to the async method name via the reverse
// map. On a miss we snapshot the current native code starts and retry, filling the map lazily as
// methods run (a MoveNext has no code start until it has first run). No-op except on Mono.
private static string? ResolveStateMachineMethodNameFromId(ulong methodId)
{
if (s_getNativeCodeInternalMethod is null || methodId == 0)
{
return null;
}
if (s_methodIdToName.TryGetValue(methodId, out string? name))
{
return name;
}
SnapshotStateMachineMethodIds();
return s_methodIdToName.TryGetValue(methodId, out name) ? name : null;
}
// The compiler generates a state machine type named "<AsyncMethodName>d__N" (possibly nested
// and namespace-qualified). Extract the original async method name from between the angle
// brackets. Returns the input unchanged when it contains no angle brackets, or null when null.
private static string? ExtractStateMachineMethodName(string? declaringTypeName)
{
if (declaringTypeName is null)
{
return null;
}
int start = declaringTypeName.IndexOf('<');
int end = declaringTypeName.IndexOf('>');
start++;
if (start > 0 && end > start)
{
return declaringTypeName.Substring(start, end - start);
}
return declaringTypeName;
}
private static TestEventListener CreateListener(EventKeywords keywords)
{
var listener = new TestEventListener();
listener.AddSource(AsyncProfilerEventSourceName, EventLevel.Informational, keywords);
return listener;
}
private static void SendFlushCommand()
{
const int FlushCommand = 1;
foreach (EventSource source in EventSource.GetSources())
{
if (source.Name == AsyncProfilerEventSourceName)
{
EventSource.SendCommand(source, (EventCommand)FlushCommand, null);
return;
}
}
}
private static ulong GetCurrentOSThreadId()
{
return (ulong)typeof(Thread)
.GetProperty("CurrentOSThreadId", BindingFlags.Static | BindingFlags.NonPublic)!
.GetValue(null)!;
}
private static int GetCurrentWrapperSlot(string resumedMethodName)
{
var st = new StackTrace();
for (int i = 0; i < st.FrameCount - 1; i++)
{
string? name = GetFrameMethodName(st.GetFrame(i));
if (name is not null && name.Contains(resumedMethodName))
{
for (int j = i + 1; j < st.FrameCount; j++)
{
string? wrapperName = GetFrameMethodName(st.GetFrame(j));
if (wrapperName is null)
{
continue;
}
if (wrapperName.StartsWith(WrapperNamePrefix, StringComparison.Ordinal))
{
string wrapperSuffix = wrapperName.Substring(WrapperNamePrefix.Length);
return int.TryParse(wrapperSuffix, out int wrapperSlot) ? wrapperSlot : -1;
}
break;
}
return -1;
}
}
return -1;
}
private static string? GetFrameMethodName(StackFrame? frame)
{
if (frame is null)
{
return null;
}
string? name = frame.GetMethod()?.Name;
if (name is null)
{
name = DiagnosticMethodInfo.Create(frame)?.Name;
}
return name;
}
private delegate bool EventVisitor(AsyncEventID eventId, ReadOnlySpan<byte> buffer, ref int index);
private static void ParseEventBuffer(ReadOnlySpan<byte> buffer, EventVisitor visitor)
{
ParseEventBuffer(buffer, (AsyncEventID eventId, long _, ReadOnlySpan<byte> buf, ref int idx) =>
visitor(eventId, buf, ref idx));
}
private delegate bool EventVisitorWithTimestamp(AsyncEventID eventId, long timestamp, ReadOnlySpan<byte> buffer, ref int index);
// Reads the per-event payload length prefix (0, 1, or 2 bytes depending on the event manifest)
// and advances the index past it. Returns the declared payload length so callers can validate
// that downstream parsers consume exactly the indicated bytes.
private static int ReadPayloadLengthPrefix(ReadOnlySpan<byte> buffer, AsyncEventID eventId, ref int index)
{
int eventIdIndex = (byte)eventId - 1;
int payloadLengthFieldSize = (uint)eventIdIndex < (uint)EventManifest.DefaultEntries.Length
? EventManifest.DefaultEntries[eventIdIndex].FieldSize
: 0;
if (payloadLengthFieldSize == 0)
{
return 0;
}
if (payloadLengthFieldSize == 1)
{
return buffer[index++];
}
int payloadLength = BinaryPrimitives.ReadUInt16LittleEndian(buffer.Slice(index));
index += 2;
return payloadLength;
}
private static void ParseEventBuffer(ReadOnlySpan<byte> buffer, EventVisitorWithTimestamp visitor)
{
EventBufferHeader? header = ParseEventBufferHeader(buffer);
if (header is null)
{
return;
}
int index = HeaderSize;
long baseTimestamp = (long)header.Value.StartTimestamp;
while (index < buffer.Length)
{
if (index + 2 > buffer.Length)
{
break;
}
AsyncEventID eventId = (AsyncEventID)buffer[index++];
long delta = (long)ReadCompressedUInt64(buffer, ref index);
baseTimestamp += delta;
int payloadLength = ReadPayloadLengthPrefix(buffer, eventId, ref index);
int payloadStartIndex = index;
if (!visitor(eventId, baseTimestamp, buffer, ref index))
{
break;
}
Assert.Equal(payloadLength, index - payloadStartIndex);
}
}
private static bool SkipEventPayload(AsyncEventID eventId, ReadOnlySpan<byte> buffer, ref int index)
{
switch (eventId)
{
case AsyncEventID.CreateRuntimeAsyncContext:
case AsyncEventID.CreateStateMachineAsyncContext:
{
ReadCompressedUInt64(buffer, ref index); // parentDispatcherId
ReadCompressedUInt64(buffer, ref index); // dispatcherId
return true;
}
case AsyncEventID.ResumeRuntimeAsyncContext:
case AsyncEventID.ResumeStateMachineAsyncContext:
{
ReadCompressedUInt64(buffer, ref index); // dispatcherId
return true;
}
case AsyncEventID.SuspendRuntimeAsyncContext:
case AsyncEventID.CompleteRuntimeAsyncContext:
case AsyncEventID.ResumeRuntimeAsyncMethod:
case AsyncEventID.CompleteRuntimeAsyncMethod:
case AsyncEventID.SuspendStateMachineAsyncContext:
case AsyncEventID.CompleteStateMachineAsyncContext:
case AsyncEventID.ResumeStateMachineAsyncMethod:
case AsyncEventID.CompleteStateMachineAsyncMethod:
case AsyncEventID.ResetAsyncThreadContext:
case AsyncEventID.ResetAsyncContinuationWrapperIndex:
{
return true;
}
case AsyncEventID.UnwindRuntimeAsyncException:
case AsyncEventID.UnwindStateMachineAsyncException:
{
ReadCompressedUInt32(buffer, ref index);
return true;
}
case AsyncEventID.CreateRuntimeAsyncCallstack:
case AsyncEventID.ResumeRuntimeAsyncCallstack:
case AsyncEventID.SuspendRuntimeAsyncCallstack:
case AsyncEventID.ResumeStateMachineAsyncCallstack:
case AsyncEventID.AppendStateMachineAsyncCallstack:
{
SkipCallstackPayload(buffer, ref index, eventId, CallstackTypeFromEventId(eventId));
return true;
}
case AsyncEventID.AsyncProfilerMetadata:
{
SkipMetadataPayload(buffer, ref index);
return true;
}
case AsyncEventID.AsyncProfilerSyncClock:
{
ReadCompressedUInt64(buffer, ref index); // qpcSync
ReadCompressedUInt64(buffer, ref index); // utcSync
return true;
}
default:
{
return false;
}
}
}
private static uint ReadCompressedUInt32(ReadOnlySpan<byte> buffer, ref int index)
{
Deserializer.ReadCompressedUInt32(buffer, ref index, out uint value);
return value;
}
private static ulong ReadCompressedUInt64(ReadOnlySpan<byte> buffer, ref int index)
{
Deserializer.ReadCompressedUInt64(buffer, ref index, out ulong value);
return value;
}
private static void SkipCallstackPayload(ReadOnlySpan<byte> buffer, ref int index, AsyncEventID eventId, AsyncCallstackType callstackType)
{
ReadCallstackPayload(buffer, ref index, eventId, callstackType, out _, out _, out _, out _, out _);
}
private static void ReadCallstackPayload(ReadOnlySpan<byte> buffer, ref int index, AsyncEventID eventId,
out byte frameCount, out List<(ulong MethodId, int State)> frames)
{
ReadCallstackPayload(buffer, ref index, eventId, AsyncCallstackType.Runtime, out _, out _, out _, out frameCount, out frames);
}
private static void ReadCallstackPayload(ReadOnlySpan<byte> buffer, ref int index, AsyncEventID eventId, AsyncCallstackType callstackType,
out ulong parentDispatcherId, out ulong dispatcherId, out byte continuationIndex, out byte frameCount, out List<(ulong MethodId, int State)> frames)
{
index++; // Reserved callstack ID (for future callstack interning).
continuationIndex = buffer[index++];
frameCount = buffer[index++];
// parentDispatcherId is only present on CreateRuntimeAsyncCallstack.
parentDispatcherId = eventId == AsyncEventID.CreateRuntimeAsyncCallstack
? ReadCompressedUInt64(buffer, ref index)
: 0;
dispatcherId = ReadCompressedUInt64(buffer, ref index);
frames = new List<(ulong, int)>(frameCount);
if (frameCount == 0)
{
// Cached callstack reference (frame data resolved out-of-band by callstack id).
return;
}
bool readState = callstackType == AsyncCallstackType.StateMachine;
ulong currentMethodId = ReadCompressedUInt64(buffer, ref index);
int state = readState ? ReadCompressedInt32(buffer, ref index) : 0;
frames.Add((currentMethodId, state));
for (int i = 1; i < frameCount; i++)
{
long delta = ReadCompressedInt64(buffer, ref index);
state = readState ? ReadCompressedInt32(buffer, ref index) : 0;
currentMethodId = (ulong)((long)currentMethodId + delta);
frames.Add((currentMethodId, state));
}
}
// Derive callstack type from the event id:
// StateMachine (StateMachineAsync*) events carry compiler-built state machine frames;
// Runtime (RuntimeAsync_*) events carry runtime-async frames.
private static AsyncCallstackType CallstackTypeFromEventId(AsyncEventID eventId)
=> eventId is AsyncEventID.ResumeStateMachineAsyncCallstack
or AsyncEventID.AppendStateMachineAsyncCallstack
? AsyncCallstackType.StateMachine
: AsyncCallstackType.Runtime;
private static int ReadCompressedInt32(ReadOnlySpan<byte> buffer, ref int index)
{
Deserializer.ReadCompressedInt32(buffer, ref index, out int value);
return value;
}
private static long ReadCompressedInt64(ReadOnlySpan<byte> buffer, ref int index)
{
Deserializer.ReadCompressedInt64(buffer, ref index, out long value);
return value;
}
private static void SkipMetadataPayload(ReadOnlySpan<byte> buffer, ref int index)
{
ReadMetadataPayload(buffer, ref index, out _, out _, out _, out _, out _);
}
private static void ReadMetadataPayload(ReadOnlySpan<byte> buffer, ref int index,
out ulong qpcFrequency, out ulong qpcSync, out ulong utcSync, out uint eventBufferSize, out byte wrapperCount)
{
qpcFrequency = ReadCompressedUInt64(buffer, ref index);
qpcSync = ReadCompressedUInt64(buffer, ref index);
utcSync = ReadCompressedUInt64(buffer, ref index);
eventBufferSize = ReadCompressedUInt32(buffer, ref index);
wrapperCount = buffer[index++];
// Per-event manifest: [count: byte] followed by [id, version, payloadLengthFieldSize] triples.
byte manifestCount = buffer[index++];
index += manifestCount * 3;
}
private record struct MetadataFromBuffer(ulong QpcFrequency, ulong QpcSync, ulong UtcSync, uint EventBufferSize, byte WrapperCount);
private readonly record struct EventBufferHeader(byte Version, uint TotalSize, uint AsyncThreadContextId, ulong OsThreadId, uint EventCount, ulong StartTimestamp, ulong EndTimestamp);
private static EventBufferHeader? ParseEventBufferHeader(ReadOnlySpan<byte> buffer)
{
if (buffer.Length < HeaderSize || buffer[0] != 1)
{
return null;
}
int index = 1;
Deserializer.ReadUInt32(buffer, ref index, out uint totalSize);
Deserializer.ReadUInt32(buffer, ref index, out uint asyncThreadContextId);
Deserializer.ReadUInt64(buffer, ref index, out ulong threadId);
Deserializer.ReadUInt32(buffer, ref index, out uint eventCount);
Deserializer.ReadUInt64(buffer, ref index, out ulong startTs);
Deserializer.ReadUInt64(buffer, ref index, out ulong endTs);
return new EventBufferHeader(buffer[0], totalSize, asyncThreadContextId, threadId, eventCount, startTs, endTs);
}
private sealed class ParsedEvent
{
public AsyncEventID EventId { get; init; }
public long Timestamp { get; init; }
public ulong OsThreadId { get; init; }
public ulong ParentDispatcherId { get; init; }
public ulong DispatcherId { get; init; }
public AsyncCallstackType CallstackType { get; init; }
public byte ContinuationIndex { get; init; }
public byte FrameCount { get; init; }
public List<(ulong MethodId, int State)> Frames { get; init; } = [];
public uint UnwindFrameCount { get; init; }
public MetadataFromBuffer? Metadata { get; init; }
public ulong SyncClockQpc { get; init; }
public ulong SyncClockUtc { get; init; }
public bool HasMarkerFrame(string markerMethodName)
{
if (Frames.Count == 0)
{
return false;
}
foreach (var (methodId, _) in Frames)
{
string? methodName = GetMethodNameFromMethodId(CallstackType, methodId);
if (methodName is not null && methodName.Contains(markerMethodName, StringComparison.Ordinal))
{
return true;
}
}
return false;
}
}
private sealed class ParsedEventStream
{
private readonly List<ParsedEvent> _events;
private Dictionary<ulong, List<ParsedEvent>>? _byDispatcherId;
private Dictionary<ulong, ulong>? _parentOfDispatcher;
private Dictionary<ulong, List<ulong>>? _childrenOfDispatcher;
private Dictionary<ulong, DispatcherKind>? _dispatcherKind;
// StateMachine (StateMachineAsync_*) and Runtime (RuntimeAsync_*) dispatchers can coexist on the same logical
// thread (e.g., a StateMachine test runner hosting a Runtime test body). The runtime captures cross-kind
// parent links in that case, but a single test typically wants to walk only its own kind's
// subtree. Tracking the kind per dispatcher lets the chain walk stop at StateMachine<->Runtime boundaries
// by default.
internal enum DispatcherKind { Unknown, StateMachine, Runtime }
public ParsedEventStream(List<ParsedEvent> events)
{
// Stable sort by timestamp: events that share a Stopwatch tick keep their original
// parse (emission) order, which preserves each thread's relative event order. The