forked from microsoft/perfview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventPipeEventSource.cs
1607 lines (1434 loc) · 71.9 KB
/
EventPipeEventSource.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
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
using FastSerialization;
using Microsoft.Diagnostics.Tracing.EventPipe;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
using Microsoft.Diagnostics.Tracing.Session;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace Microsoft.Diagnostics.Tracing
{
/// <summary>
/// EventPipeEventSource knows how to decode EventPipe (generated by the .NET core runtime).
/// Please see <see href="https://github.com/Microsoft/perfview/blob/main/src/TraceEvent/EventPipe/EventPipeFormat.md" />for details on the file format.
///
/// By conventions files of such a format are given the .netperf suffix and are logically
/// very much like a ETL file in that they have a header that indicate things about
/// the trace as a whole, and a list of events. Like more modern ETL files the
/// file as a whole is self-describing. Some of the events are 'MetaData' events
/// that indicate the provider name, event name, and payload field names and types.
/// Ordinary events then point at these meta-data event so that logically all
/// events have a name some basic information (process, thread, timestamp, activity
/// ID) and user defined field names and values of various types.
/// </summary>
public unsafe class EventPipeEventSource : TraceEventDispatcher, IFastSerializable, IFastSerializableVersion
{
public EventPipeEventSource(string fileName) : this(new PinnedStreamReader(fileName, 0x20000, new SerializationConfiguration() { StreamLabelWidth = StreamLabelWidth.FourBytes }), fileName, false)
{
}
public EventPipeEventSource(Stream stream)
: this(new PinnedStreamReader(stream, alignment: StreamReaderAlignment.OneByte, config: new SerializationConfiguration() { StreamLabelWidth = StreamLabelWidth.FourBytes }), "stream", true)
{
}
private EventPipeEventSource(PinnedStreamReader streamReader, string name, bool isStreaming)
{
_deserializerIntializer = () =>
{
StreamLabel start = streamReader.Current;
byte[] netTraceMagic = new byte[8];
streamReader.Read(netTraceMagic, 0, netTraceMagic.Length);
byte[] expectedMagic = Encoding.UTF8.GetBytes("Nettrace");
bool isNetTrace = true;
if (!netTraceMagic.SequenceEqual(expectedMagic))
{
// The older netperf format didn't have this 'Nettrace' magic on it.
streamReader.Goto(start);
isNetTrace = false;
}
var deserializer = new Deserializer(streamReader, name);
#if SUPPORT_V1_V2
// This is only here for V2 and V1. V3+ should use the name EventTrace, it can be removed when we drop support.
deserializer.RegisterFactory("Microsoft.DotNet.Runtime.EventPipeFile", delegate { return this; });
#endif
deserializer.RegisterFactory("Trace", delegate { return this; });
deserializer.RegisterFactory("EventBlock", delegate { return new EventPipeEventBlock(this); });
deserializer.RegisterFactory("MetadataBlock", delegate { return new EventPipeMetadataBlock(this); });
deserializer.RegisterFactory("SPBlock", delegate { return new EventPipeSequencePointBlock(this); });
deserializer.RegisterFactory("StackBlock", delegate { return new EventPipeStackBlock(this); });
var entryObj = deserializer.GetEntryObject(); // this call invokes FromStream and reads header data
if ((FileFormatVersionNumber >= 4) != isNetTrace)
{
//NetTrace header should be present iff the version is >= 4
throw new SerializationException("Invalid NetTrace file format version");
}
// Because we told the deserialize to use 'this' when creating a EventPipeFile, we
// expect the entry object to be 'this'.
Debug.Assert(entryObj == this);
return deserializer;
};
osVersion = new Version("0.0.0.0");
cpuSpeedMHz = 10;
if (!isStreaming)
_deserializer = _deserializerIntializer();
EventCache = new EventCache();
EventCache.OnEvent += EventCache_OnEvent;
EventCache.OnEventsDropped += EventCache_OnEventsDropped;
StackCache = new StackCache();
}
public DateTime QPCTimeToTimeStamp(long QPCTime)
{
return base.QPCTimeToDateTimeUTC(QPCTime).ToLocalTime();
}
#region private
// I put these in the private section because they are overrides, and thus don't ADD to the API.
public override int EventsLost => _eventsLost;
/// <summary>
/// This is the version number reader and writer (although we don't don't have a writer at the moment)
/// It MUST be updated (as well as MinimumReaderVersion), if breaking changes have been made.
/// If your changes are forward compatible (old readers can still read the new format) you
/// don't have to update the version number but it is useful to do so (while keeping MinimumReaderVersion unchanged)
/// so that readers can quickly determine what new content is available.
/// </summary>
public int Version => 5;
/// <summary>
/// This field is only used for writers, and this code does not have writers so it is not used.
/// It should be set to Version unless changes since the last version are forward compatible
/// (old readers can still read this format), in which case this should be unchanged.
/// </summary>
public int MinimumReaderVersion => Version;
/// <summary>
/// This is the smallest version that the deserializer here can read. Currently
/// we are careful about backward compat so our deserializer can read anything that
/// has ever been produced. We may change this when we believe old writers basically
/// no longer exist (and we can remove that support code).
/// </summary>
public int MinimumVersionCanRead => 0;
/// <summary>
/// Called after headers are deserialized. This is especially useful in a streaming scenario
/// because the headers are only read after Process() is called.
/// </summary>
internal Action HeadersDeserialized;
protected override void Dispose(bool disposing)
{
if (_deserializer != null)
{
_deserializer.Dispose();
}
base.Dispose(disposing);
}
public override bool Process()
{
if (_deserializer is null)
{
Debug.Assert(_deserializerIntializer != null);
_deserializer = _deserializerIntializer?.Invoke();
Debug.Assert(_deserializer != null);
}
HeadersDeserialized?.Invoke();
if (FileFormatVersionNumber >= 3)
{
// loop through the stream until we hit a null object. Deserialization of
// EventPipeEventBlocks will cause dispatch to happen.
// ReadObject uses registered factories and recognizes types by names, then derserializes them with FromStream
while (_deserializer.ReadObject() != null)
{ }
if(FileFormatVersionNumber >= 4)
{
// Ensure all events have been sorted and dispatched
EventCache.Flush();
}
}
#if SUPPORT_V1_V2
else
{
PinnedStreamReader deserializerReader = (PinnedStreamReader)_deserializer.Reader;
while (deserializerReader.Current < _endOfEventStream)
{
TraceEventNativeMethods.EVENT_RECORD* eventRecord = ReadEvent(deserializerReader, false);
if (eventRecord != null)
{
// in the code below we set sessionEndTimeQPC to be the timestamp of the last event.
// Thus the new timestamp should be later, and not more than 1 day later.
Debug.Assert(sessionEndTimeQPC <= eventRecord->EventHeader.TimeStamp);
Debug.Assert(sessionEndTimeQPC == 0 || eventRecord->EventHeader.TimeStamp - sessionEndTimeQPC < _QPCFreq * 24 * 3600);
var traceEvent = Lookup(eventRecord);
Dispatch(traceEvent);
sessionEndTimeQPC = eventRecord->EventHeader.TimeStamp;
}
}
}
#endif
return true;
}
internal int FileFormatVersionNumber { get; private set; }
internal EventCache EventCache { get; private set; }
internal StackCache StackCache { get; private set; }
internal override string ProcessName(int processID, long timeQPC) => string.Format("Process({0})", processID);
internal void ReadAndDispatchEvent(PinnedStreamReader reader, bool useHeaderCompression)
{
DispatchEventRecord(ReadEvent(reader, useHeaderCompression));
}
internal void DispatchEventRecord(TraceEventNativeMethods.EVENT_RECORD* eventRecord)
{
if (eventRecord != null)
{
// in the code below we set sessionEndTimeQPC to be the timestamp of the last event.
// Thus the new timestamp should be later, and not more than 1 day later.
Debug.Assert(sessionEndTimeQPC <= eventRecord->EventHeader.TimeStamp);
Debug.Assert(sessionEndTimeQPC == 0 || eventRecord->EventHeader.TimeStamp - sessionEndTimeQPC < _QPCFreq * 24 * 3600);
var traceEvent = Lookup(eventRecord);
if (traceEvent.NeedsFixup)
{
traceEvent.FixupData();
}
Dispatch(traceEvent);
sessionEndTimeQPC = eventRecord->EventHeader.TimeStamp;
}
}
internal void ResetCompressedHeader()
{
_compressedHeader = new EventPipeEventHeader();
}
internal TraceEventNativeMethods.EVENT_RECORD* ReadEvent(PinnedStreamReader reader, bool useHeaderCompression)
{
byte* headerPtr = null;
if (useHeaderCompression)
{
// The header uses a variable size encoding, but it is certainly smaller than 100 bytes
const int maxHeaderSize = 100;
headerPtr = reader.GetPointer(maxHeaderSize);
ReadEventHeader(headerPtr, useHeaderCompression, ref _compressedHeader);
return ReadEvent(_compressedHeader, reader);
}
else
{
headerPtr = reader.GetPointer(EventPipeEventHeader.GetHeaderSize(FileFormatVersionNumber));
int totalSize = EventPipeEventHeader.GetTotalEventSize(headerPtr, FileFormatVersionNumber);
headerPtr = reader.GetPointer(totalSize); // now we now the real size and get read entire event
EventPipeEventHeader eventData = new EventPipeEventHeader();
ReadEventHeader(headerPtr, useHeaderCompression, ref eventData);
return ReadEvent(eventData, reader);
}
}
void ReadEventHeader(byte* headerPtr, bool useHeaderCompression, ref EventPipeEventHeader eventData)
{
if (FileFormatVersionNumber <= 3)
{
EventPipeEventHeader.ReadFromFormatV3(headerPtr, ref eventData);
}
else // if (FileFormatVersionNumber == 4)
{
EventPipeEventHeader.ReadFromFormatV4(headerPtr, useHeaderCompression, ref eventData);
if(eventData.MetaDataId != 0 && StackCache.TryGetStack(eventData.StackId, out int stackBytesSize, out IntPtr stackBytes))
{
eventData.StackBytesSize = stackBytesSize;
eventData.StackBytes = stackBytes;
}
}
// Basic sanity checks. Are the timestamps and sizes sane.
Debug.Assert(sessionEndTimeQPC <= eventData.TimeStamp);
Debug.Assert(sessionEndTimeQPC == 0 || eventData.TimeStamp - sessionEndTimeQPC < _QPCFreq * 24 * 3600);
Debug.Assert(0 <= eventData.PayloadSize && eventData.PayloadSize <= eventData.TotalNonHeaderSize);
Debug.Assert(0 <= eventData.TotalNonHeaderSize && eventData.TotalNonHeaderSize < 0x20000); // TODO really should be 64K but BulkSurvivingObjectRanges needs fixing.
Debug.Assert(FileFormatVersionNumber != 3 ||
((long)eventData.Payload % 4 == 0 && eventData.TotalNonHeaderSize % 4 == 0)); // ensure 4 byte alignment
Debug.Assert(0 <= eventData.StackBytesSize && eventData.StackBytesSize <= 800);
}
private TraceEventNativeMethods.EVENT_RECORD* ReadEvent(EventPipeEventHeader eventData, PinnedStreamReader reader)
{
StreamLabel headerStart = reader.Current;
StreamLabel eventDataEnd = headerStart.Add(eventData.HeaderSize + eventData.TotalNonHeaderSize);
TraceEventNativeMethods.EVENT_RECORD* ret = null;
if (eventData.IsMetadata())
{
int payloadSize = eventData.PayloadSize;
// Note that this skip invalidates the eventData pointer, so it is important to pull any fields out we need first.
reader.Skip(eventData.HeaderSize);
StreamLabel metadataV1Start = reader.Current;
StreamLabel metaDataEnd = reader.Current.Add(payloadSize);
// Read in the header (The header does not include payload parameter information)
var metaDataHeader = new EventPipeEventMetaDataHeader(reader, payloadSize,
GetMetaDataVersion(FileFormatVersionNumber), PointerSize, _processId);
DynamicTraceEventData eventTemplate = CreateTemplate(metaDataHeader);
// If the metadata contains no parameter metadata, don't attempt to read it.
if (!metaDataHeader.ContainsParameterMetadata)
{
CreateDefaultParameters(eventTemplate);
}
else
{
ParseEventParameters(eventTemplate, metaDataHeader, reader, metaDataEnd, NetTraceFieldLayoutVersion.V1);
}
while (reader.Current < metaDataEnd)
{
// If we've already parsed the V1 metadata and there's more left to decode,
// then we have some tags to read
int tagLength = reader.ReadInt32();
EventPipeMetadataTag tag = (EventPipeMetadataTag)reader.ReadByte();
StreamLabel tagEndLabel = reader.Current.Add(tagLength);
if (tag == EventPipeMetadataTag.ParameterPayloadV2)
{
ParseEventParameters(eventTemplate, metaDataHeader, reader, tagEndLabel, NetTraceFieldLayoutVersion.V2);
}
else if (tag == EventPipeMetadataTag.Opcode)
{
Debug.Assert(tagLength == 1);
metaDataHeader.Opcode = reader.ReadByte();
SetOpcode(eventTemplate, metaDataHeader.Opcode);
}
// Skip any remaining bytes or unknown tags
reader.Goto(tagEndLabel);
}
Debug.Assert(reader.Current == metaDataEnd);
_eventMetadataDictionary.Add(metaDataHeader.MetaDataId, metaDataHeader);
_metadataTemplates[eventTemplate] = eventTemplate;
Debug.Assert(eventData.StackBytesSize == 0, "Meta-data events should always have a empty stack");
}
else
{
ret = ConvertEventHeaderToRecord(ref eventData);
}
reader.Goto(eventDataEnd);
return ret;
}
private static EventPipeMetaDataVersion GetMetaDataVersion(int fileFormatVersion)
{
switch(fileFormatVersion)
{
case 1:
return EventPipeMetaDataVersion.LegacyV1;
case 2:
return EventPipeMetaDataVersion.LegacyV2;
default:
return EventPipeMetaDataVersion.NetTrace;
}
}
private TraceEventNativeMethods.EVENT_RECORD* ConvertEventHeaderToRecord(ref EventPipeEventHeader eventData)
{
if (_eventMetadataDictionary.TryGetValue(eventData.MetaDataId, out var metaData))
{
return metaData.GetEventRecordForEventData(eventData);
}
else
{
Debug.Assert(false, "Warning can't find metaData for ID " + eventData.MetaDataId.ToString("x"));
return null;
}
}
internal override unsafe Guid GetRelatedActivityID(TraceEventNativeMethods.EVENT_RECORD* eventRecord)
{
if(FileFormatVersionNumber >= 4)
{
return _relatedActivityId;
}
else
{
// Recover the EventPipeEventHeader from the payload pointer and then fetch from the header.
return EventPipeEventHeader.GetRelatedActivityID((byte*)eventRecord->UserData);
}
}
public void ToStream(Serializer serializer) => throw new InvalidOperationException("We dont ever serialize one of these in managed code so we don't need to implement ToSTream");
public void FromStream(Deserializer deserializer)
{
FileFormatVersionNumber = deserializer.VersionBeingRead;
#if SUPPORT_V1_V2
if (deserializer.VersionBeingRead < 3)
{
ForwardReference reference = deserializer.ReadForwardReference();
_endOfEventStream = deserializer.ResolveForwardReference(reference, preserveCurrent: true);
}
#endif
// The start time is stored as a SystemTime which is a bunch of shorts, convert to DateTime.
short year = deserializer.ReadInt16();
short month = deserializer.ReadInt16();
short dayOfWeek = deserializer.ReadInt16();
short day = deserializer.ReadInt16();
short hour = deserializer.ReadInt16();
short minute = deserializer.ReadInt16();
short second = deserializer.ReadInt16();
short milliseconds = deserializer.ReadInt16();
_syncTimeUTC = new DateTime(year, month, day, hour, minute, second, milliseconds, DateTimeKind.Utc);
deserializer.Read(out _syncTimeQPC);
deserializer.Read(out _QPCFreq);
sessionStartTimeQPC = _syncTimeQPC;
if (3 <= deserializer.VersionBeingRead)
{
deserializer.Read(out pointerSize);
deserializer.Read(out _processId);
deserializer.Read(out numberOfProcessors);
deserializer.Read(out _expectedCPUSamplingRate);
}
#if SUPPORT_V1_V2
else
{
_processId = 0; // V1 && V2 tests expect 0 for process Id
pointerSize = 8; // V1 EventPipe only supports Linux which is x64 only.
numberOfProcessors = 1;
}
#endif
}
private void EventCache_OnEvent(ref EventPipeEventHeader header)
{
if (header.MetaDataId != 0 && StackCache.TryGetStack(header.StackId, out int stackBytesSize, out IntPtr stackBytes))
{
header.StackBytesSize = stackBytesSize;
header.StackBytes = stackBytes;
}
_relatedActivityId = header.RelatedActivityID;
DispatchEventRecord(ConvertEventHeaderToRecord(ref header));
}
private void EventCache_OnEventsDropped(int droppedEventCount)
{
long totalLostEvents = _eventsLost + droppedEventCount;
_eventsLost = (int)Math.Min(totalLostEvents, int.MaxValue);
}
internal bool TryGetTemplateFromMetadata(TraceEvent unhandledEvent, out DynamicTraceEventData template)
{
return _metadataTemplates.TryGetValue(unhandledEvent, out template);
}
private static void CreateDefaultParameters(DynamicTraceEventData eventTemplate)
{
eventTemplate.payloadNames = new string[0];
eventTemplate.payloadFetches = new DynamicTraceEventData.PayloadFetch[0];
}
/// <summary>
/// Given the EventPipe metaData header and a stream pointing at the serialized meta-data for the parameters for the
/// event, create a new DynamicTraceEventData that knows how to parse that event.
/// ReaderForParameters.Current is advanced past the parameter information.
/// </summary>
private void ParseEventParameters(DynamicTraceEventData template, EventPipeEventMetaDataHeader eventMetaDataHeader, PinnedStreamReader readerForParameters,
StreamLabel metadataBlobEnd, NetTraceFieldLayoutVersion fieldLayoutVersion)
{
DynamicTraceEventData.PayloadFetchClassInfo classInfo = null;
// Read the count of event payload fields.
int fieldCount = readerForParameters.ReadInt32();
Debug.Assert(0 <= fieldCount && fieldCount < 0x4000);
if (fieldCount > 0)
{
try
{
// Recursively parse the metadata, building up a list of payload names and payload field fetch objects.
classInfo = ParseFields(readerForParameters, fieldCount, metadataBlobEnd, fieldLayoutVersion);
}
catch (FormatException)
{
// If we encounter unparsable metadata, ignore the payloads of this event type but don't fail to parse the entire
// trace. This gives us more flexibility in the future to introduce new descriptive information.
classInfo = null;
}
}
if (classInfo == null)
{
classInfo = CheckForWellKnownEventFields(eventMetaDataHeader);
if (classInfo == null)
{
classInfo = new DynamicTraceEventData.PayloadFetchClassInfo()
{
FieldNames = new string[0],
FieldFetches = new DynamicTraceEventData.PayloadFetch[0]
};
}
}
template.payloadNames = classInfo.FieldNames;
template.payloadFetches = classInfo.FieldFetches;
return;
}
private void SetOpcode(DynamicTraceEventData template, int opcode)
{
template.opcode = (TraceEventOpcode)opcode;
template.opcodeName = template.opcode.ToString();
}
private DynamicTraceEventData CreateTemplate(EventPipeEventMetaDataHeader eventMetaDataHeader)
{
string opcodeName = ((TraceEventOpcode)eventMetaDataHeader.Opcode).ToString();
int opcode = eventMetaDataHeader.Opcode;
if (opcode == 0)
{
GetOpcodeFromEventName(eventMetaDataHeader.EventName, out opcode, out opcodeName);
}
string eventName = FilterOpcodeNameFromEventName(eventMetaDataHeader.EventName, opcode);
DynamicTraceEventData template = new DynamicTraceEventData(null, eventMetaDataHeader.EventId, 0, eventName, Guid.Empty, opcode, null, eventMetaDataHeader.ProviderId, eventMetaDataHeader.ProviderName);
SetOpcode(template, eventMetaDataHeader.Opcode);
return template;
}
private string FilterOpcodeNameFromEventName(string eventName, int opcode)
{
// If the event has an opcode associated and the opcode name is also specified, we should
// remove the opcode name from the event's name. Otherwise the events will show up with
// duplicate opcode names (i.e. RequestStart/Start)
if (opcode == (int)TraceEventOpcode.Start && eventName.EndsWith("Start", StringComparison.OrdinalIgnoreCase))
{
return eventName.Remove(eventName.Length - 5, 5);
}
else if (opcode == (int)TraceEventOpcode.Stop && eventName.EndsWith("Stop", StringComparison.OrdinalIgnoreCase))
{
return eventName.Remove(eventName.Length - 4, 4);
}
return eventName;
}
// The NetPerf and NetTrace V1 file formats were incapable of representing some event parameter types that EventSource and ETW support.
// This works around that issue without requiring a runtime or format update for well-known EventSources that used the indescribable types.
private DynamicTraceEventData.PayloadFetchClassInfo CheckForWellKnownEventFields(EventPipeEventMetaDataHeader eventMetaDataHeader)
{
if (eventMetaDataHeader.ProviderName == "Microsoft-Diagnostics-DiagnosticSource")
{
string eventName = eventMetaDataHeader.EventName;
if (eventName == "Event" ||
eventName == "Activity1Start" ||
eventName == "Activity1Stop" ||
eventName == "Activity2Start" ||
eventName == "Activity2Stop" ||
eventName == "RecursiveActivity1Start" ||
eventName == "RecursiveActivity1Stop")
{
DynamicTraceEventData.PayloadFetch[] fieldFetches = new DynamicTraceEventData.PayloadFetch[3];
string[] fieldNames = new string[3];
fieldFetches[0].Type = typeof(string);
fieldFetches[0].Size = DynamicTraceEventData.NULL_TERMINATED;
fieldFetches[0].Offset = 0;
fieldNames[0] = "SourceName";
fieldFetches[1].Type = typeof(string);
fieldFetches[1].Size = DynamicTraceEventData.NULL_TERMINATED;
fieldFetches[1].Offset = ushort.MaxValue;
fieldNames[1] = "EventName";
DynamicTraceEventData.PayloadFetch[] keyValuePairFieldFetches = new DynamicTraceEventData.PayloadFetch[2];
string[] keyValuePairFieldNames = new string[2];
keyValuePairFieldFetches[0].Type = typeof(string);
keyValuePairFieldFetches[0].Size = DynamicTraceEventData.NULL_TERMINATED;
keyValuePairFieldFetches[0].Offset = 0;
keyValuePairFieldNames[0] = "Key";
keyValuePairFieldFetches[1].Type = typeof(string);
keyValuePairFieldFetches[1].Size = DynamicTraceEventData.NULL_TERMINATED;
keyValuePairFieldFetches[1].Offset = ushort.MaxValue;
keyValuePairFieldNames[1] = "Value";
DynamicTraceEventData.PayloadFetchClassInfo keyValuePairClassInfo = new DynamicTraceEventData.PayloadFetchClassInfo()
{
FieldFetches = keyValuePairFieldFetches,
FieldNames = keyValuePairFieldNames
};
DynamicTraceEventData.PayloadFetch argumentElementFetch = DynamicTraceEventData.PayloadFetch.StructPayloadFetch(0, keyValuePairClassInfo);
ushort fetchSize = DynamicTraceEventData.COUNTED_SIZE + DynamicTraceEventData.ELEM_COUNT;
fieldFetches[2] = DynamicTraceEventData.PayloadFetch.ArrayPayloadFetch(ushort.MaxValue, argumentElementFetch, fetchSize);
fieldNames[2] = "Arguments";
return new DynamicTraceEventData.PayloadFetchClassInfo()
{
FieldFetches = fieldFetches,
FieldNames = fieldNames
};
}
}
return null;
}
private DynamicTraceEventData.PayloadFetchClassInfo ParseFields(PinnedStreamReader reader, int numFields, StreamLabel metadataBlobEnd,
NetTraceFieldLayoutVersion fieldLayoutVersion)
{
string[] fieldNames = new string[numFields];
DynamicTraceEventData.PayloadFetch[] fieldFetches = new DynamicTraceEventData.PayloadFetch[numFields];
ushort offset = 0;
for (int fieldIndex = 0; fieldIndex < numFields; fieldIndex++)
{
StreamLabel fieldEnd = metadataBlobEnd;
string fieldName = "<unknown_field>";
if (fieldLayoutVersion >= NetTraceFieldLayoutVersion.V2)
{
StreamLabel fieldStart = reader.Current;
int fieldLength = reader.ReadInt32();
fieldEnd = fieldStart.Add(fieldLength);
Debug.Assert(fieldEnd <= metadataBlobEnd);
fieldName = reader.ReadNullTerminatedUnicodeString();
}
DynamicTraceEventData.PayloadFetch payloadFetch = ParseType(reader, offset, fieldEnd, fieldName, fieldLayoutVersion);
if (fieldLayoutVersion <= NetTraceFieldLayoutVersion.V1)
{
// Read the string name of the event payload field.
// The older format put the name after the type signature rather
// than before it. This is a bit worse for diagnostics because
// we won't have the name available to associate with any failure
// reading the type signature above.
fieldName = reader.ReadNullTerminatedUnicodeString();
}
fieldNames[fieldIndex] = fieldName;
// Update the offset into the event for the next payload fetch.
if (payloadFetch.Size >= DynamicTraceEventData.SPECIAL_SIZES || offset == ushort.MaxValue)
{
offset = ushort.MaxValue; // Indicate that the offset must be computed at run time.
}
else
{
offset += payloadFetch.Size;
}
// Save the current payload fetch.
fieldFetches[fieldIndex] = payloadFetch;
if (fieldLayoutVersion >= NetTraceFieldLayoutVersion.V2)
{
// skip over any data that a later version of the format may append
Debug.Assert(reader.Current <= fieldEnd);
reader.Goto(fieldEnd);
}
}
return new DynamicTraceEventData.PayloadFetchClassInfo()
{
FieldNames = fieldNames,
FieldFetches = fieldFetches
};
}
private DynamicTraceEventData.PayloadFetch ParseType(
PinnedStreamReader reader,
ushort offset,
StreamLabel fieldEnd,
string fieldName,
NetTraceFieldLayoutVersion fieldLayoutVersion)
{
Debug.Assert(reader.Current < fieldEnd);
DynamicTraceEventData.PayloadFetch payloadFetch = new DynamicTraceEventData.PayloadFetch();
// Read the TypeCode for the current field.
TypeCode typeCode = (TypeCode)reader.ReadInt32();
// Fill out the payload fetch object based on the TypeCode.
switch (typeCode)
{
case TypeCode.Boolean:
{
payloadFetch.Type = typeof(bool);
payloadFetch.Size = 4; // We follow windows conventions and use 4 bytes for bool.
payloadFetch.Offset = offset;
break;
}
case TypeCode.Char:
{
payloadFetch.Type = typeof(char);
payloadFetch.Size = sizeof(char);
payloadFetch.Offset = offset;
break;
}
case TypeCode.SByte:
{
payloadFetch.Type = typeof(SByte);
payloadFetch.Size = sizeof(SByte);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Byte:
{
payloadFetch.Type = typeof(byte);
payloadFetch.Size = sizeof(byte);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Int16:
{
payloadFetch.Type = typeof(Int16);
payloadFetch.Size = sizeof(Int16);
payloadFetch.Offset = offset;
break;
}
case TypeCode.UInt16:
{
payloadFetch.Type = typeof(UInt16);
payloadFetch.Size = sizeof(UInt16);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Int32:
{
payloadFetch.Type = typeof(Int32);
payloadFetch.Size = sizeof(Int32);
payloadFetch.Offset = offset;
break;
}
case TypeCode.UInt32:
{
payloadFetch.Type = typeof(UInt32);
payloadFetch.Size = sizeof(UInt32);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Int64:
{
payloadFetch.Type = typeof(Int64);
payloadFetch.Size = sizeof(Int64);
payloadFetch.Offset = offset;
break;
}
case TypeCode.UInt64:
{
payloadFetch.Type = typeof(UInt64);
payloadFetch.Size = sizeof(UInt64);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Single:
{
payloadFetch.Type = typeof(Single);
payloadFetch.Size = sizeof(Single);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Double:
{
payloadFetch.Type = typeof(Double);
payloadFetch.Size = sizeof(Double);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Decimal:
{
payloadFetch.Type = typeof(Decimal);
payloadFetch.Size = sizeof(Decimal);
payloadFetch.Offset = offset;
break;
}
case TypeCode.DateTime:
{
payloadFetch.Type = typeof(DateTime);
payloadFetch.Size = 8;
payloadFetch.Offset = offset;
break;
}
case EventPipeEventSource.GuidTypeCode:
{
payloadFetch.Type = typeof(Guid);
payloadFetch.Size = 16;
payloadFetch.Offset = offset;
break;
}
case TypeCode.String:
{
payloadFetch.Type = typeof(String);
payloadFetch.Size = DynamicTraceEventData.NULL_TERMINATED;
payloadFetch.Offset = offset;
break;
}
case TypeCode.Object:
{
// TypeCode.Object represents an embedded struct.
// Read the number of fields in the struct. Each of these fields could be an embedded struct,
// but these embedded structs are still counted as single fields. They will be expanded when they are handled.
int structFieldCount = reader.ReadInt32();
DynamicTraceEventData.PayloadFetchClassInfo embeddedStructClassInfo = ParseFields(reader, structFieldCount, fieldEnd, fieldLayoutVersion);
if (embeddedStructClassInfo == null)
{
throw new FormatException($"Field {fieldName}: Unable to parse metadata for embedded struct");
}
payloadFetch = DynamicTraceEventData.PayloadFetch.StructPayloadFetch(offset, embeddedStructClassInfo);
break;
}
case EventPipeEventSource.ArrayTypeCode:
{
if (fieldLayoutVersion == NetTraceFieldLayoutVersion.V1)
{
throw new FormatException($"EventPipeEventSource.ArrayTypeCode is not a valid type code in V1 field metadata.");
}
DynamicTraceEventData.PayloadFetch elementType = ParseType(reader, 0, fieldEnd, fieldName, fieldLayoutVersion);
// This fetchSize marks the array as being prefixed with an unsigned 16 bit count of elements
ushort fetchSize = DynamicTraceEventData.COUNTED_SIZE + DynamicTraceEventData.ELEM_COUNT;
payloadFetch = DynamicTraceEventData.PayloadFetch.ArrayPayloadFetch(offset, elementType, fetchSize);
break;
}
default:
{
throw new FormatException($"Field {fieldName}: Typecode {typeCode} is not supported.");
}
}
return payloadFetch;
}
private static void GetOpcodeFromEventName(string eventName, out int opcode, out string opcodeName)
{
opcode = 0;
opcodeName = null;
// If this EventName suggests that it has an Opcode, then we must remove the opcode name from its name
// Otherwise the events will show up with duplicate opcode names (i.e. RequestStart/Start)
if (eventName != null)
{
if (eventName.EndsWith("Start", StringComparison.OrdinalIgnoreCase))
{
opcode = (int)TraceEventOpcode.Start;
opcodeName = nameof(TraceEventOpcode.Start);
}
else if (eventName.EndsWith("Stop", StringComparison.OrdinalIgnoreCase))
{
opcode = (int)TraceEventOpcode.Stop;
opcodeName = nameof(TraceEventOpcode.Stop);
}
}
}
// Guid is not part of TypeCode (yet), we decided to use 17 to represent it, as it's the "free slot"
// see https://github.com/dotnet/coreclr/issues/16105#issuecomment-361749750 for more
internal const TypeCode GuidTypeCode = (TypeCode)17;
// Array isn't part of TypeCode either
internal const TypeCode ArrayTypeCode = (TypeCode)19;
#if SUPPORT_V1_V2
private StreamLabel _endOfEventStream;
#endif
private Dictionary<int, EventPipeEventMetaDataHeader> _eventMetadataDictionary = new Dictionary<int, EventPipeEventMetaDataHeader>();
private Deserializer _deserializer;
private Dictionary<TraceEvent, DynamicTraceEventData> _metadataTemplates =
new Dictionary<TraceEvent, DynamicTraceEventData>(new ExternalTraceEventParserState.TraceEventComparer());
private EventPipeEventHeader _compressedHeader;
private int _eventsLost;
private Guid _relatedActivityId;
internal int _processId;
internal int _expectedCPUSamplingRate;
private Func<Deserializer> _deserializerIntializer;
#endregion
}
#region private classes
/// <summary>
/// The Nettrace format is divided up into various blocks - this is a base class that handles the common
/// aspects for all of them.
/// </summary>
internal abstract class EventPipeBlock : IFastSerializable, IFastSerializableVersion
{
public EventPipeBlock(EventPipeEventSource source) => _source = source;
// _startEventData and _endEventData have already been initialized before this is invoked
// to help identify the bounds. The reader is positioned at _startEventData
protected abstract void ReadBlockContents(PinnedStreamReader reader);
public unsafe void FromStream(Deserializer deserializer)
{
// blockSizeInBytes does not include padding bytes to ensure alignment.
var blockSizeInBytes = deserializer.ReadInt();
// after the block size comes eventual padding, we just need to skip it by jumping to the nearest aligned address
if ((long)deserializer.Current % 4 != 0)
{
var nearestAlignedAddress = deserializer.Current.Add((int)(4 - ((long)deserializer.Current % 4)));
deserializer.Goto(nearestAlignedAddress);
}
_startEventData = deserializer.Current;
_endEventData = _startEventData.Add(blockSizeInBytes);
PinnedStreamReader deserializerReader = (PinnedStreamReader)deserializer.Reader;
ReadBlockContents(deserializerReader);
deserializerReader.Goto(_endEventData); // go to the end of block, in case some padding was not skipped yet
}
public void ToStream(Serializer serializer) => throw new InvalidOperationException();
protected StreamLabel _startEventData;
protected StreamLabel _endEventData;
protected EventPipeEventSource _source;
public int Version => 2;
public int MinimumVersionCanRead => Version;
public int MinimumReaderVersion => 0;
}
internal enum EventBlockFlags : short
{
Uncompressed = 0,
HeaderCompression = 1
}
/// <summary>
/// An EVentPipeEventBlock represents a block of events. It basically only has
/// one field, which is the size in bytes of the block. But when its FromStream
/// is called, it will perform the callbacks for the events (thus deserializing
/// it performs dispatch).
/// </summary>
internal class EventPipeEventBlock : EventPipeBlock
{
public EventPipeEventBlock(EventPipeEventSource source) : base(source) { }
protected unsafe override void ReadBlockContents(PinnedStreamReader reader)
{
if(_source.FileFormatVersionNumber >= 4)
{
_source.ResetCompressedHeader();
byte[] eventBlockBytes = new byte[_endEventData.Sub(_startEventData)];
reader.Read(eventBlockBytes, 0, eventBlockBytes.Length);
_source.EventCache.ProcessEventBlock(eventBlockBytes);
}
else
{
//NetPerf file had the events fully sorted so we can dispatch directly
while (reader.Current < _endEventData)
{
_source.ReadAndDispatchEvent(reader, false);
}
}
}
}
/// <summary>
/// A block of metadata carrying events. These 'events' aren't dispatched by EventPipeEventSource - they carry
/// the metadata that allows the payloads of non-metadata events to be decoded.
/// </summary>
internal class EventPipeMetadataBlock : EventPipeBlock
{
public EventPipeMetadataBlock(EventPipeEventSource source) : base(source) { }
protected unsafe override void ReadBlockContents(PinnedStreamReader reader)
{
_source.ResetCompressedHeader();
short headerSize = reader.ReadInt16();
Debug.Assert(headerSize >= 20);
short flags = reader.ReadInt16();
long minTimeStamp = reader.ReadInt64();
long maxTimeStamp = reader.ReadInt64();
reader.Goto(_startEventData.Add(headerSize));
while (reader.Current < _endEventData)
{
_source.ReadAndDispatchEvent(reader, (flags & (short)EventBlockFlags.HeaderCompression) != 0);
}
}
}
/// <summary>
/// An EventPipeSequencePointBlock represents a stream divider that contains
/// updates for all thread event sequence numbers, indicates that all queued
/// events can be sorted and dispatched, and that all cached events/stacks can
/// be flushed.
/// </summary>
internal class EventPipeSequencePointBlock : EventPipeBlock
{
public EventPipeSequencePointBlock(EventPipeEventSource source) : base(source) { }
protected unsafe override void ReadBlockContents(PinnedStreamReader reader)
{
byte[] blockBytes = new byte[_endEventData.Sub(_startEventData)];
reader.Read(blockBytes, 0, blockBytes.Length);
_source.EventCache.ProcessSequencePointBlock(blockBytes);
_source.StackCache.Flush();