-
Notifications
You must be signed in to change notification settings - Fork 720
/
Copy pathDynamicTraceEventParser.cs
2653 lines (2421 loc) · 108 KB
/
DynamicTraceEventParser.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
// Copyright (c) Microsoft Corporation. All rights reserved.
using FastSerialization;
using Microsoft.Diagnostics.Tracing.Compatibility;
using Microsoft.Diagnostics.Tracing.EventPipe;
using Microsoft.Diagnostics.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Address = System.UInt64;
namespace Microsoft.Diagnostics.Tracing.Parsers
{
/// <summary>
/// A DynamicTraceEventParser is a parser that understands how to read the embedded manifests that occur in the
/// dataStream (System.Diagnostics.Tracing.EventSources do this).
///
/// See also TDHDynamicTraceEventParser which knows how to read the manifest that are registered globally with
/// the machine.
/// </summary>
public class DynamicTraceEventParser : TraceEventParser
{
/// <summary>
/// The event ID for the EventSource manifest emission event.
/// </summary>
public const TraceEventID ManifestEventID = (TraceEventID)0xFFFE;
/// <summary>
/// Create a new DynamicTraceEventParser (which can parse ETW providers that dump their manifests
/// to the ETW data stream) an attach it to the ETW data stream 'source'.
/// </summary>
public DynamicTraceEventParser(TraceEventSource source)
: base(source)
{
// Try to retrieve persisted state
state = (DynamicTraceEventParserState)StateObject;
if (state == null)
{
StateObject = state = new DynamicTraceEventParserState();
partialManifests = new Dictionary<Guid, List<PartialManifestInfo>>();
this.source.RegisterUnhandledEvent(CheckForDynamicManifest);
}
// make a registeredParser to resolve self-describing events (and more).
registeredParser = new RegisteredTraceEventParser(source, true);
// But cause any of its new definitions to work on my subscriptions.
registeredParser.NewEventDefinition = OnNewEventDefintion;
// make an eventPipeTraceEventParser to resolve EventPipe events
eventPipeTraceEventParser = new EventPipeTraceEventParser(source, dontRegister: true);
eventPipeTraceEventParser.NewEventDefinition = OnNewEventDefintion;
}
/// <summary>
/// Returns a list of providers (their manifest) that this TraceParser knows about.
/// </summary>
public IEnumerable<ProviderManifest> DynamicProviders
{
get
{
return state.providers.Values;
}
}
/// <summary>
/// Given a manifest describing the provider add its information to the parser.
/// </summary>
public void AddDynamicProvider(ProviderManifest providerManifest, bool noThrowOnError = false)
{
// Debug.WriteLine("callback count = " + ((source is ETWTraceEventSource) ? ((ETWTraceEventSource)source).CallbackCount() : -1));
// Trace.WriteLine("Dynamic: Found provider " + providerManifest.Name + " Guid " + providerManifest.Guid);
ProviderManifest prevManifest = null;
if (state.providers.TryGetValue(providerManifest.Guid, out prevManifest))
{
// If the new manifest is not strictly better than the one we already have, ignore it.
if (!providerManifest.BetterThan(prevManifest))
{
// Trace.WriteLine("Dynamic: existing manifest just as good, returning");
return;
}
}
// Register the new definitions.
providerManifest.ParseProviderEvents(delegate (DynamicTraceEventData template)
{
return OnNewEventDefintion(template, prevManifest != null);
}, noThrowOnError);
// Remember this serialized information.(do it afterward so ContainKey call above is accurate)
state.providers[providerManifest.Guid] = providerManifest;
// Register the manifest event with myself so that I continue to get updated manifests.
// TODO we are 'leaking' these today. Clean them up on Dispose.
var callback = new DynamicManifestTraceEventData(delegate (TraceEvent data) { CheckForDynamicManifest(data); }, providerManifest);
source.RegisterEventTemplate(callback);
// Raise the event that says we found a new provider.
var newProviderCallback = DynamicProviderAdded;
if (newProviderCallback != null)
{
newProviderCallback(providerManifest);
}
// Debug.WriteLine("callback count = " + ((source is ETWTraceEventSource) ? ((ETWTraceEventSource)source).CallbackCount() : -1));
// Trace.WriteLine("Dynamic finished registering " + providerManifest.Name);
}
/// <summary>
/// Utility method that stores all the manifests known to the DynamicTraceEventParser to the directory 'directoryPath'
/// </summary>
public void WriteAllManifests(string directoryPath)
{
Directory.CreateDirectory(directoryPath);
foreach (var providerManifest in DynamicProviders)
{
var filePath = Path.Combine(directoryPath, providerManifest.Name + ".manifest.xml");
providerManifest.WriteToFile(filePath);
}
}
/// <summary>
/// Utility method that read all the manifests the directory 'directoryPath' into the parser.
/// Manifests must end in a .man or .manifest.xml suffix. It will throw an error if
/// the manifest is incorrect or using unsupported options.
/// </summary>
public void ReadAllManifests(string directoryPath)
{
foreach (var fileName in Directory.GetFiles(directoryPath, "*.manifest.xml"))
{
AddDynamicProvider(new ProviderManifest(fileName));
}
foreach (var fileName in Directory.GetFiles(directoryPath, "*.man"))
{
AddDynamicProvider(new ProviderManifest(fileName));
}
}
/// <summary>
/// Override.
/// </summary>
public override bool IsStatic { get { return false; } }
/// <summary>
/// This event, will be fired any time a new Provider is added to the table
/// of ETW providers known to this DynamicTraceEventParser. This includes
/// when the EventSource manifest events are encountered as well as any
/// explicit calls to AddDynamicProvider. (including ReadAllManifests).
///
/// The Parser will filter out duplicate manifest events, however if an
/// old version of a provider's manifest is encountered, and later a newer
/// version is encountered, you can receive this event more than once for
/// a single provider.
/// </summary>
public event Action<ProviderManifest> DynamicProviderAdded;
#if false
public event Action<EventCounterTraceData> EventCounter
{
add
{
// action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
// RegisterTemplate(new EventCounterTraceData(value, 0xFFFD, 0xFFFE, "EventSource", Guid.Empty, 253, "EventCounter", ProviderGuid, ProviderName));
}
remove
{
// source.UnregisterEventTemplate(value, 15, ProviderGuid);
}
}
#endif
#region private
/// <summary>
/// override
/// </summary>
protected override string GetProviderName()
{
// This parser covers more than one provider, so the convention is that you return null for the provider name.
return null;
}
/// <summary>
/// Called on unhandled events to look for manifests. Returns true if we added a new manifest (which may have updated the lookup table)
/// </summary>
private bool CheckForDynamicManifest(TraceEvent data)
{
if (data.ID != ManifestEventID)
{
return false;
}
// We also are expecting only these tasks and opcodes.
if (data.Opcode != (TraceEventOpcode)0xFE || data.Task != (TraceEventTask)0xFFFE)
{
return false;
}
// Starting with .NET 6, the manifest is written into the event stream, which results in
// duplicate event dispatch. To avoid this, filter out the Microsoft-Windows-DotNETRuntime provider
// if it is present in the event stream.
if (data.ProviderGuid == ClrTraceEventParser.ProviderGuid)
{
return false;
}
// Look up our information.
List<PartialManifestInfo> partialManifestsForGuid;
if (!partialManifests.TryGetValue(data.ProviderGuid, out partialManifestsForGuid))
{
partialManifestsForGuid = new List<PartialManifestInfo>();
partialManifests.Add(data.ProviderGuid, partialManifestsForGuid);
}
PartialManifestInfo partialManifest = null;
// PERF: Expansion of
// partialManifest = partialManifestsForGuid.Find(e => data.ProcessID == e.ProcessID && data.ThreadID == e.ThreadID);
// that avoids the delegate allocation.
foreach (var p in partialManifestsForGuid)
{
if (p.ProcessID == data.ProcessID && p.ThreadID == data.ThreadID)
{
partialManifest = p;
break;
}
}
if (partialManifest == null)
{
partialManifest = new PartialManifestInfo() { ProcessID = data.ProcessID, ThreadID = data.ThreadID };
partialManifestsForGuid.Add(partialManifest);
}
ProviderManifest provider = partialManifest.AddChunk(data);
// We have a completed manifest, add it to our list.
if (provider != null)
{
partialManifestsForGuid.Remove(partialManifest);
// Throw away empty lists or lists that are old
var nowUtc = DateTime.UtcNow;
if (partialManifestsForGuid.Count == 0 || partialManifestsForGuid.TrueForAll(e => (nowUtc - e.StartedUtc).TotalSeconds > 10))
{
partialManifests.Remove(data.ProviderGuid);
}
AddDynamicProvider(provider, true);
return true; // I should have added a manifest event, so re-lookup the event
}
return false;
}
/// <summary>
/// Override
/// </summary>
protected internal override void EnumerateTemplates(Func<string, string, EventFilterResponse> eventsToObserve, Action<TraceEvent> callback)
{
// Normally state is setup in the constructor, but call can be invoked before the constructor has finished,
if (state == null)
{
state = (DynamicTraceEventParserState)StateObject;
}
foreach (var provider in state.providers.Values)
{
provider.ParseProviderEvents(delegate (DynamicTraceEventData template)
{
if (eventsToObserve != null)
{
var response = eventsToObserve(template.ProviderName, template.EventName);
if (response != EventFilterResponse.AcceptEvent)
{
return response;
}
}
// We should only return a particular template at most once.
// However registredParser can overlap with dynamicParser
// (this can happen if the ETL was merged and has KernelTraceControler events for the provider
// or someone registers an EventSource with the OS).
// Since we will Enumerate all the events the registeredParser knows
// about below, we filter out any duplicates here.
if (!registeredParser.HasDefinitionForTemplate(template))
{
callback(template);
}
return EventFilterResponse.AcceptEvent;
}, true);
}
// also enumerate any events from the registeredParser.
registeredParser.EnumerateTemplates(eventsToObserve, callback);
// also enumerate any events from the eventPipeTraceEventParser
eventPipeTraceEventParser.EnumerateTemplates(eventsToObserve, callback);
}
private class PartialManifestInfo
{
internal PartialManifestInfo() { StartedUtc = DateTime.UtcNow; }
internal DateTime StartedUtc; // When we started
private byte[][] Chunks;
private int ChunksLeft;
internal int ProcessID; // The process and thread ID that is emitting this manifest (acts as a stream ID)
internal int ThreadID; // The process and thread ID that is emitting this manifest (acts as a stream ID)
private ProviderManifest provider;
private byte majorVersion;
private byte minorVersion;
private ManifestEnvelope.ManifestFormats format;
internal unsafe ProviderManifest AddChunk(TraceEvent data)
{
if (provider != null)
{
goto Fail;
}
if (data.EventDataLength <= sizeof(ManifestEnvelope) || data.GetByteAt(3) != 0x5B) // magic number
{
goto Fail;
}
ushort totalChunks = (ushort)data.GetInt16At(4);
ushort chunkNum = (ushort)data.GetInt16At(6);
if (chunkNum >= totalChunks || totalChunks == 0)
{
goto Fail;
}
if (Chunks == null)
{
// To allow for resyncing at 0, otherwise we fail aggressively.
if (chunkNum != 0)
{
goto Fail;
}
format = (ManifestEnvelope.ManifestFormats)data.GetByteAt(0);
majorVersion = (byte)data.GetByteAt(1);
minorVersion = (byte)data.GetByteAt(2);
ChunksLeft = totalChunks;
Chunks = new byte[ChunksLeft][];
}
else
{
// Chunks have to agree with the format and version information.
if (format != (ManifestEnvelope.ManifestFormats)data.GetByteAt(0) ||
majorVersion != data.GetByteAt(1) || minorVersion != data.GetByteAt(2))
{
goto Fail;
}
}
if (Chunks.Length <= chunkNum || Chunks[chunkNum] != null)
{
goto Fail;
}
byte[] chunk = new byte[data.EventDataLength - 8];
Chunks[chunkNum] = data.EventData(chunk, 0, 8, chunk.Length);
--ChunksLeft;
if (ChunksLeft > 0)
{
return null;
}
// OK we have a complete set of chunks
byte[] serializedData = Chunks[0];
if (Chunks.Length > 1)
{
int totalLength = 0;
for (int i = 0; i < Chunks.Length; i++)
{
totalLength += Chunks[i].Length;
}
// Concatenate all the arrays.
serializedData = new byte[totalLength];
int pos = 0;
for (int i = 0; i < Chunks.Length; i++)
{
Array.Copy(Chunks[i], 0, serializedData, pos, Chunks[i].Length);
pos += Chunks[i].Length;
}
}
Chunks = null;
// string str = Encoding.UTF8.GetString(serializedData);
provider = new ProviderManifest(serializedData, format, majorVersion, minorVersion,
"Event at " + data.TimeStampRelativeMSec.ToString("f3") + " MSec");
provider.ISDynamic = true;
return provider;
Fail:
Chunks = null;
return null;
}
}
private DynamicTraceEventParserState state;
private Dictionary<Guid, List<PartialManifestInfo>> partialManifests;
// It is not intuitive that self-describing events (which are arguably 'dynamic') are resolved by
// the RegisteredTraceEventParser. This is even more wacky in a mixed EventSource where some events
// are resolved by dynamic manifest and some are self-describing. To avoid these issues DynamicTraceEventParsers
// be able to handle both (it can resolve anything a RegisteredTraceEventParser can). This
// RegisteredTraceEventParser is how this gets accomplished.
private RegisteredTraceEventParser registeredParser;
// It is enabling DynamicTraceEventParsers to handle the EventSource events from EventPipe.
private EventPipeTraceEventParser eventPipeTraceEventParser;
#endregion
}
#if false
public sealed class EventCounterTraceData : TraceEvent
{
public int DataCount { get { return GetInt32At(0); } }
public double Data(int index) { return GetDoubleAt(4 + index * 8); }
public int NamesCount { get { return GetInt32At(4 + 8 * DataCount); } }
public string Names(int index) { return GetUnicodeStringAt(OffsetForIndexInNamesArray(index)); }
#region Private
internal EventCounterTraceData(Action<EventCounterTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName)
: base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName)
{
this.Action = action;
m_lastIdx = 0xFFFF; // Invalidate the cache
}
protected internal override void Dispatch()
{
m_lastIdx = 0xFFFF; // Invalidate the cache
Action(this);
}
protected internal override Delegate Target
{
get { return Action; }
set { Action = (Action<EventCounterTraceData>)value; }
}
protected internal override void Validate()
{
m_lastIdx = 0xFFFF; // Invalidate the cache
Debug.Assert(!(Version == 0 && EventDataLength != OffsetForIndexInNamesArray(NamesCount)));
}
public override StringBuilder ToXml(StringBuilder sb)
{
Prefix(sb);
XmlAttrib(sb, "DataCount", DataCount);
XmlAttrib(sb, "NamesCount", NamesCount);
sb.AppendLine(">");
for (int i = 0; i < DataCount; i++)
{
string name = "";
if (i < NamesCount)
name = Names(i);
sb.Append(" ").AppendLine(name).Append("=").Append(Data(i)).AppendLine();
}
sb.Append("</Event>");
return sb;
}
public override string[] PayloadNames
{
get
{
if (payloadNames == null)
payloadNames = new string[] { "DataCount", "NamesCount" };
return payloadNames;
}
}
public override object PayloadValue(int index)
{
switch (index)
{
case 0:
return DataCount;
case 1:
return NamesCount;
default:
Debug.Assert(false, "Bad field index");
return null;
}
}
private int OffsetForIndexInNamesArray(int targetIdx)
{
Debug.Assert(targetIdx <= NamesCount);
int idx = m_lastIdx;
int offset = m_lastOffset;
if (targetIdx < idx)
{
idx = 0;
offset = 8 + 8 * DataCount;
}
while (idx < targetIdx)
{
offset = SkipUnicodeString(offset);
idx++;
}
Debug.Assert(offset <= EventDataLength);
m_lastIdx = (ushort)idx;
m_lastOffset = (ushort)offset;
Debug.Assert(idx == targetIdx);
Debug.Assert(m_lastIdx == targetIdx && m_lastOffset == offset); // No truncation
return offset;
}
private ushort m_lastIdx;
private ushort m_lastOffset;
private event Action<EventCounterTraceData> Action;
#endregion
}
#endif
#region internal classes
/// <summary>
/// DynamicTraceEventData is an event that knows how to take runtime information to parse event fields (and payload)
///
/// This meta-data is distilled down to a array of field names and an array of PayloadFetches which contain enough
/// information to find the field data in the payload blob. This meta-data is used in the
/// DynamicTraceEventData.PayloadNames and DynamicTraceEventData.PayloadValue methods.
/// </summary>
internal class DynamicTraceEventData : TraceEvent, IFastSerializable
{
internal DynamicTraceEventData(Action<TraceEvent> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName)
: base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName)
{
m_target = target;
}
internal event Action<TraceEvent> m_target;
#region overrides
/// <summary>
/// Implements TraceEvent interface
/// </summary>
protected internal override void Dispatch()
{
if (m_target != null)
{
m_target(this);
}
}
/// <summary>
/// Implements TraceEvent interface
/// </summary>
public override string[] PayloadNames
{
get { Debug.Assert(payloadNames != null); return payloadNames; }
}
/// <summary>
/// Implements TraceEvent interface
/// </summary>
public override object PayloadValue(int index)
{
try
{
#if DEBUG
// Confirm that the serialization 'adds up'
var computedSize = SkipToField(payloadFetches, payloadFetches.Length, 0, EventDataLength, false);
Debug.Assert(computedSize <= this.EventDataLength);
if ((int)ID != 0xFFFE) // If it is not a manifest event
{
// TODO FIX NOW the || condition is a hack because PerfVIew.ClrEnableParameters fails.
Debug.Assert(computedSize <= this.EventDataLength || this.ProviderName == "PerfView");
}
#endif
int offset = payloadFetches[index].Offset;
if (offset == ushort.MaxValue)
{
offset = SkipToField(payloadFetches, index, 0, EventDataLength, true);
}
// Fields that are simply not present, (perfectly) we simply return null for.
if (offset == EventDataLength)
{
return null;
}
return GetPayloadValueAt(ref payloadFetches[index], offset, EventDataLength);
}
catch (Exception e)
{
return "<<<EXCEPTION_DURING_VALUE_LOOKUP " + e.GetType().Name + ">>>";
}
}
private object GetPayloadValueAt(ref PayloadFetch payloadFetch, int offset, int payloadLength)
{
if (payloadLength <= offset)
{
throw new ArgumentOutOfRangeException("Payload size exceeds buffer size.");
}
// Is this a struct field?
PayloadFetchClassInfo classInfo = payloadFetch.Class;
if (classInfo != null)
{
var ret = new StructValue();
for (int i = 0; i < classInfo.FieldFetches.Length; i++)
{
ret.Add(classInfo.FieldNames[i], GetPayloadValueAt(ref classInfo.FieldFetches[i], offset, payloadLength));
offset = OffsetOfNextField(ref classInfo.FieldFetches[i], offset, payloadLength);
}
return ret;
}
PayloadFetchArrayInfo arrayInfo = payloadFetch.Array;
if (arrayInfo != null)
{
var arrayCount = GetCountForArray(payloadFetch, arrayInfo, ref offset);
// TODO this is very inefficient for blitable types. Optimize that.
var elementType = arrayInfo.Element.Type;
// Byte array short-circuit.
if (elementType == typeof(byte))
{
return GetByteArrayAt(offset, arrayCount);
}
var ret = Array.CreateInstance(elementType, arrayCount);
for (int i = 0; i < arrayCount; i++)
{
object value = GetPayloadValueAt(ref arrayInfo.Element, offset, payloadLength);
if (value.GetType() != elementType)
{
value = ((IConvertible)value).ToType(elementType, null);
}
ret.SetValue(value, i);
offset = OffsetOfNextField(ref arrayInfo.Element, offset, payloadLength);
}
return ret;
}
Type type = payloadFetch.Type;
if (type == null)
{
return "[CANT PARSE]";
}
if ((uint)ushort.MaxValue < (uint)offset)
{
return "[CANT PARSE OFFSET]";
}
// CONSIDER: The code below ensures that if you have fields that are
// 'off the end' of a data that you return the default value. That
// allows the parser to gracefully handle old events that have fewer
// fields but does NOT guarantee we don't read past the end of the
// buffer in all cases (if you have corrupt/mismatched data). The
// code below does ensure this but is more expensive. For now I have
// chosen the cheaper solution.
//
// if ((uint)EventDataLength < OffsetOfNextField(offset, index))
// return GetDefaultValueByType(payloadFetches[index].type);
if ((uint)EventDataLength <= (uint)offset)
{
return GetDefaultValueByType(type);
}
switch (Type.GetTypeCode(type))
{
case TypeCode.String:
{
var size = payloadFetch.Size;
var isAnsi = false;
if (size >= SPECIAL_SIZES)
{
isAnsi = ((size & IS_ANSI) != 0);
if (IsNullTerminated(size))
{
if (isAnsi)
{
return GetUTF8StringAt(offset);
}
else
{
return GetUnicodeStringAt(offset);
}
}
else if (IsCountedSize(size))
{
bool unicodeByteCountString = !isAnsi && (size & ELEM_COUNT) == 0;
if (((size & BIT_32) != 0))
{
size = (ushort)GetInt32At(offset);
offset += 4; // skip size;
}
else
{
size = (ushort)GetInt16At(offset);
offset += 2; // skip size;
}
if (unicodeByteCountString)
{
size /= 2; // Unicode string with BYTE count. Element count is half that.
}
}
else
{
return "[CANT PARSE STRING]";
}
}
else if (size > 0x8000) // What is this? looks like a hack.
{
size -= 0x8000;
isAnsi = true;
}
if (isAnsi)
{
return GetFixedAnsiStringAt(size, offset);
}
else
{
return GetFixedUnicodeStringAt(size, offset);
}
}
case TypeCode.Boolean:
return GetByteAt(offset) != 0;
case TypeCode.Char:
return (Char)GetInt16At(offset);
case TypeCode.Byte:
return (byte)GetByteAt(offset);
case TypeCode.SByte:
return (SByte)GetByteAt(offset);
case TypeCode.Int16:
return GetInt16At(offset);
case TypeCode.UInt16:
return (UInt16)GetInt16At(offset);
case TypeCode.Int32:
return GetInt32At(offset);
case TypeCode.UInt32:
return (UInt32)GetInt32At(offset);
case TypeCode.Int64:
return GetInt64At(offset);
case TypeCode.UInt64:
return (UInt64)GetInt64At(offset);
case TypeCode.Single:
return GetSingleAt(offset);
case TypeCode.Double:
return GetDoubleAt(offset);
default:
if (type == typeof(IntPtr))
{
if (PointerSize == 4)
{
return (Address)GetInt32At(offset);
}
else
{
return (Address)GetInt64At(offset);
}
}
else if (type == typeof(Guid))
{
return GetGuidAt(offset);
}
else if (type == typeof(DateTime))
{
if (payloadFetch.Size == 16)
{
int currentOffset = offset;
int year = GetInt16At(currentOffset);
int month = GetInt16At(currentOffset += 2);
int dayOfWeek = GetInt16At(currentOffset += 2);
int day = GetInt16At(currentOffset += 2);
int hour = GetInt16At(currentOffset += 2);
int minute = GetInt16At(currentOffset += 2);
int second = GetInt16At(currentOffset += 2);
int milliseconds = GetInt16At(currentOffset);
return new DateTime(year, month, day, hour, minute, second, milliseconds, DateTimeKind.Utc);
}
return DateTime.FromFileTime(GetInt64At(offset));
}
else
{
return "[UNSUPPORTED TYPE]";
}
}
}
/// <summary>
/// Used by PayloadValue to represent a structure. It is basically a IDictionary with a ToString() that
/// returns the value as JSON.
/// </summary>
internal class StructValue : IDictionary<string, object>
{
public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { return m_values.GetEnumerator(); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return m_values.GetEnumerator(); }
public bool IsReadOnly { get { return true; } }
public object this[string key]
{
get
{
foreach (var keyValue in m_values)
{
if (key == keyValue.Key)
{
return keyValue.Value;
}
}
return null;
}
set { throw new NotImplementedException(); }
}
public bool TryGetValue(string key, out object value)
{
foreach (var keyValue in m_values)
{
if (key == keyValue.Key)
{
value = keyValue.Value;
return true;
}
}
value = null;
return false;
}
public void Add(string key, object value) { m_values.Add(new KeyValuePair<string, object>(key, value)); }
public void Add(KeyValuePair<string, object> item) { m_values.Add(item); }
public void Clear() { m_values.Clear(); }
public int Count { get { return m_values.Count; } }
public override string ToString()
{
return WriteAsJSon(new StringBuilder(), this).ToString();
}
private static StringBuilder WriteAsJSon(StringBuilder sb, object value)
{
var asStructValue = value as StructValue;
if (asStructValue != null)
{
sb.Append("{ ");
bool first = true;
foreach (var keyvalue in asStructValue)
{
if (!first)
{
sb.Append(", ");
}
else
{
first = false;
}
sb.Append("\"");
Quote(sb, keyvalue.Key);
sb.Append("\":");
WriteAsJSon(sb, keyvalue.Value);
}
sb.Append(" }");
return sb;
}
var asArray = value as System.Array;
if (asArray != null && asArray.Rank == 1)
{
sb.Append("[ ");
bool first = true;
for (int i = 0; i < asArray.Length; i++)
{
if (!first)
{
sb.Append(", ");
}
else
{
first = false;
}
WriteAsJSon(sb, asArray.GetValue(i));
}
sb.Append(" ]");
return sb;
}
if (value is int || value is bool || value is double || value is float)
{
sb.Append(value);
return sb;
}
else if (value == null)
{
sb.Append("null");
}
else
{
sb.Append("\"");
Quote(sb, value.ToString());
sb.Append("\"");
}
return sb;
}
#region private
/// <summary>
/// Uses C style conventions to quote a string 'value' and append to the string builder 'sb'.
/// Thus all \ are turned into \\ and all " into \"
/// </summary>
private static void Quote(StringBuilder output, string value)
{
for (int i = 0; i < value.Length; i++)
{
var c = value[i];
if (c == '\\' || c == '"')
{
output.Append('\\');
}
output.Append(c);
}
}
public bool ContainsKey(string key)
{
object value;
return TryGetValue(key, out value);
}
public ICollection<string> Keys { get { throw new NotImplementedException(); } }
public bool Remove(string key) { throw new NotImplementedException(); }
public ICollection<object> Values { get { throw new NotImplementedException(); } }
public bool Contains(KeyValuePair<string, object> item) { throw new NotImplementedException(); }
public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) { throw new NotImplementedException(); }
public bool Remove(KeyValuePair<string, object> item) { throw new NotImplementedException(); }
private List<KeyValuePair<string, object>> m_values = new List<KeyValuePair<string, object>>();
#endregion
}
// Return the default value for a given type
private object GetDefaultValueByType(Type type)
{
if (type == typeof(string)) // Activator.CreateInstance does not work on strings.
{
return String.Empty;
}
else
{
return Activator.CreateInstance(type);
}
}
/// <summary>
/// Implements TraceEvent interface
/// </summary>
public override string PayloadString(int index, IFormatProvider formatProvider = null)
{
// See if you can do enumeration mapping.
var map = payloadFetches[index].Map;
if (map != null)
{
object value = PayloadValue(index);
if (value == null)
{
return "";
}
long asLong = (long)((IConvertible)value).ToInt64(formatProvider);
if (map is SortedDictionary<long, string>)
{
StringBuilder sb = new StringBuilder();
// It is a bitmap, compute the bits from the bitmap.
foreach (var keyValue in map)
{
if (asLong == 0)
{
break;
}
if ((keyValue.Key & asLong) != 0)
{
if (sb.Length != 0)
{
sb.Append('|');
}
sb.Append(keyValue.Value);
asLong &= ~keyValue.Key;
}
}
if (asLong != 0)
{
if (sb.Length != 0)
{
sb.Append('|');
}