-
Notifications
You must be signed in to change notification settings - Fork 720
/
Copy pathRegisteredTraceEventParser.cs
1470 lines (1304 loc) · 66.5 KB
/
RegisteredTraceEventParser.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.Session;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace Microsoft.Diagnostics.Tracing.Parsers
{
/// <summary>
/// RegisteredTraceEventParser uses the standard windows provider database (TDH, what gets registered with wevtutil)
/// to find the names of events and fields of the events).
/// </summary>
public sealed unsafe class RegisteredTraceEventParser : ExternalTraceEventParser
{
/// <summary>
/// Create a new RegisteredTraceEventParser and attach it to the given TraceEventSource
/// </summary>
public RegisteredTraceEventParser(TraceEventSource source, bool dontRegister = false)
: base(source, dontRegister)
{
#if !DOTNET_V35
var symbolSource = new SymbolTraceEventParser(source);
symbolSource.MetaDataEventInfo += delegate (EmptyTraceData data)
{
DynamicTraceEventData template = (new RegisteredTraceEventParser.TdhEventParser((byte*)data.userData, null, MapTable)).ParseEventMetaData();
// Uncomment this if you want to see the template in the debugger at this point
// template.source = data.source;
// template.eventRecord = data.eventRecord;
// template.userData = data.userData;
m_state.m_templates[template] = template;
};
// Try to parse bitmap and value map information.
symbolSource.MetaDataEventMapInfo += delegate (EmptyTraceData data)
{
try
{
Guid providerID = *((Guid*)data.userData);
byte* eventInfoBuffer = (byte*)(data.userData + sizeof(Guid));
RegisteredTraceEventParser.EVENT_MAP_INFO* eventInfo = (RegisteredTraceEventParser.EVENT_MAP_INFO*)eventInfoBuffer;
IDictionary<long, string> map = RegisteredTraceEventParser.TdhEventParser.ParseMap(eventInfo, eventInfoBuffer);
if (eventInfo->NameOffset < data.EventDataLength - 16)
{
string mapName = new string((char*)(&eventInfoBuffer[eventInfo->NameOffset]));
MapTable.Add(new MapKey(providerID, mapName), map);
}
}
catch (Exception) { };
};
#endif
}
/// <summary>
/// Given a provider name that has been registered with the operating system, get
/// a string representing the ETW manifest for that provider. Note that this
/// manifest is not as rich as the original source manifest because some information
/// is not actually compiled into the binary manifest that is registered with the OS.
/// </summary>
public static string GetManifestForRegisteredProvider(string providerName)
{
var providerGuid = TraceEventProviders.GetProviderGuidByName(providerName);
if (providerGuid == Guid.Empty)
{
throw new ApplicationException("Could not find provider with name " + providerName);
}
return GetManifestForRegisteredProvider(providerGuid);
}
/// <summary>
/// Given a provider GUID that has been registered with the operating system, get
/// a string representing the ETW manifest for that provider. Note that this
/// manifest is not as rich as the original source manifest because some information
/// is not actually compiled into the binary manifest that is registered with the OS.
/// </summary>
public static string GetManifestForRegisteredProvider(Guid providerGuid)
{
int buffSize = 84000; // Still in the small object heap.
var buffer = new byte[buffSize]; // Still in the small object heap.
byte* enumBuffer = null;
TraceEventNativeMethods.EVENT_RECORD eventRecord = new TraceEventNativeMethods.EVENT_RECORD();
eventRecord.EventHeader.ProviderId = providerGuid;
// We keep events of a given event number together in the output
string providerName = null;
SortedDictionary<int, StringWriter> events = new SortedDictionary<int, StringWriter>();
// We keep tasks separated by task ID
SortedDictionary<int, TaskInfo> tasks = new SortedDictionary<int, TaskInfo>();
// Templates where the KEY is the template string and the VALUE is the template name (backwards)
Dictionary<string, string> templateIntern = new Dictionary<string, string>(8);
// Remember any enum types we have. Value is XML for the enum (normal)
Dictionary<string, string> enumIntern = new Dictionary<string, string>();
StringWriter enumLocalizations = new StringWriter();
// Any task names used so far
Dictionary<string, int> taskNames = new Dictionary<string, int>();
// Any es used so far
Dictionary<string, int> opcodeNames = new Dictionary<string, int>();
// This ensures that we have unique event names.
Dictionary<string, int> eventNames = new Dictionary<string, int>();
SortedDictionary<ulong, string> keywords = new SortedDictionary<ulong, string>();
List<ProviderDataItem> keywordsItems = TraceEventProviders.GetProviderKeywords(providerGuid);
if (keywordsItems != null)
{
foreach (var keywordItem in keywordsItems)
{
// Skip the reserved keywords.
if (keywordItem.Value >= 1000000000000UL)
{
continue;
}
keywords[keywordItem.Value] = MakeLegalIdentifier(keywordItem.Name);
}
}
int status;
for (; ; )
{
int size = buffer.Length;
status = TdhEnumerateManifestProviderEvents(eventRecord.EventHeader.ProviderId, buffer, ref size);
if (status != 122 || 20000000 < size) // 122 == Insufficient buffer keep it under 2Meg
{
break;
}
buffer = new byte[size];
}
if (status == 0)
{
const int NumberOfEventsOffset = 0;
const int FirstDescriptorOffset = 8;
int eventCount = BitConverter.ToInt32(buffer, NumberOfEventsOffset);
var descriptors = new EVENT_DESCRIPTOR[eventCount];
fixed (EVENT_DESCRIPTOR* pDescriptors = descriptors)
{
Marshal.Copy(buffer, FirstDescriptorOffset, (IntPtr)pDescriptors, descriptors.Length * sizeof(EVENT_DESCRIPTOR));
}
foreach (var descriptor in descriptors)
{
for (; ; )
{
int size = buffer.Length;
status = TdhGetManifestEventInformation(eventRecord.EventHeader.ProviderId, descriptor, buffer, ref size);
if (status != 122 || 20000000 < size) // 122 == Insufficient buffer keep it under 2Meg
{
break;
}
buffer = new byte[size];
}
if (status != 0)
{
continue;
}
fixed (byte* eventInfoBuff = buffer)
{
var eventInfo = (TRACE_EVENT_INFO*)eventInfoBuff;
EVENT_PROPERTY_INFO* propertyInfos = &eventInfo->EventPropertyInfoArray;
if (providerName == null)
{
if (eventInfo->ProviderNameOffset != 0)
{
providerName = new string((char*)(&eventInfoBuff[eventInfo->ProviderNameOffset]));
}
else
{
providerName = "provider(" + eventInfo->ProviderGuid.ToString() + ")";
}
}
// Compute task name
string taskName = null;
if (eventInfo->TaskNameOffset != 0)
{
taskName = MakeLegalIdentifier((new string((char*)(&eventInfoBuff[eventInfo->TaskNameOffset]))));
}
if (taskName == null)
{
taskName = "task_" + eventInfo->EventDescriptor.Task.ToString();
}
// Ensure task name is unique.
int taskNumForName;
if (taskNames.TryGetValue(taskName, out taskNumForName) && taskNumForName != eventInfo->EventDescriptor.Task)
{
taskName = taskName + "_" + eventInfo->EventDescriptor.Task.ToString();
}
taskNames[taskName] = eventInfo->EventDescriptor.Task;
// Compute opcode name
string opcodeName = "";
if (eventInfo->EventDescriptor.Opcode != 0)
{
if (eventInfo->OpcodeNameOffset != 0)
{
opcodeName = MakeLegalIdentifier((new string((char*)(&eventInfoBuff[eventInfo->OpcodeNameOffset]))));
}
else
{
opcodeName = "opcode_" + eventInfo->EventDescriptor.Opcode.ToString();
}
}
// Ensure opcode name is unique.
int opcodeNumForName;
if (opcodeNames.TryGetValue(opcodeName, out opcodeNumForName) && opcodeNumForName != eventInfo->EventDescriptor.Opcode)
{
// If we did not find a name, use 'opcode and the disambiguator
if (eventInfo->OpcodeNameOffset == 0)
{
opcodeName = "opcode";
}
opcodeName = opcodeName + "_" + eventInfo->EventDescriptor.Task.ToString() + "_" + eventInfo->EventDescriptor.Opcode.ToString();
}
opcodeNames[opcodeName] = eventInfo->EventDescriptor.Opcode;
// And event name
string eventName = taskName;
if (!taskName.EndsWith(opcodeName, StringComparison.OrdinalIgnoreCase))
{
eventName += Capitalize(opcodeName);
}
// Ensure uniqueness of the event name
int eventNumForName;
if (eventNames.TryGetValue(eventName, out eventNumForName) && eventNumForName != eventInfo->EventDescriptor.Id)
{
eventName = eventName + eventInfo->EventDescriptor.Id.ToString();
}
eventNames[eventName] = eventInfo->EventDescriptor.Id;
// Get task information
TaskInfo taskInfo;
if (!tasks.TryGetValue(eventInfo->EventDescriptor.Task, out taskInfo))
{
tasks[eventInfo->EventDescriptor.Task] = taskInfo = new TaskInfo() { Name = taskName };
}
var symbolName = eventName;
if (eventInfo->EventDescriptor.Version > 0)
{
symbolName += "_V" + eventInfo->EventDescriptor.Version;
}
StringWriter eventWriter;
if (!events.TryGetValue(eventInfo->EventDescriptor.Id, out eventWriter))
{
events[eventInfo->EventDescriptor.Id] = eventWriter = new StringWriter();
}
eventWriter.Write(" <event value=\"{0}\" symbol=\"{1}\" version=\"{2}\" task=\"{3}\"",
eventInfo->EventDescriptor.Id,
symbolName,
eventInfo->EventDescriptor.Version,
taskName);
if (eventInfo->EventDescriptor.Opcode != 0)
{
string opcodeId;
if (eventInfo->EventDescriptor.Opcode < 10) // It is a reserved opcode.
{
// For some reason opcodeName does not have the underscore, which we need.
if (eventInfo->EventDescriptor.Opcode == (byte)TraceEventOpcode.DataCollectionStart)
{
opcodeId = "win:DC_Start";
}
else if (eventInfo->EventDescriptor.Opcode == (byte)TraceEventOpcode.DataCollectionStop)
{
opcodeId = "win:DC_Stop";
}
else
{
opcodeId = "win:" + opcodeName;
}
}
else
{
opcodeId = opcodeName;
if (taskInfo.Opcodes == null)
{
taskInfo.Opcodes = new SortedDictionary<int, string>();
}
if (!taskInfo.Opcodes.ContainsKey(eventInfo->EventDescriptor.Opcode))
{
taskInfo.Opcodes[eventInfo->EventDescriptor.Opcode] = opcodeId;
}
}
eventWriter.Write(" opcode=\"{0}\"", opcodeId);
}
// TODO handle cases outside standard levels
if ((int)TraceEventLevel.Always <= eventInfo->EventDescriptor.Level && eventInfo->EventDescriptor.Level <= (int)TraceEventLevel.Verbose)
{
var asLevel = (TraceEventLevel)eventInfo->EventDescriptor.Level;
var levelName = "win:" + asLevel;
eventWriter.Write(" level=\"{0}\"", levelName);
}
var keywordStr = GetKeywordStr(keywords, (ulong)eventInfo->EventDescriptor.Keyword);
if (keywordStr.Length > 0)
{
eventWriter.Write(" keywords=\"" + keywordStr + "\"", eventInfo->EventDescriptor.Keyword);
}
if (eventInfo->TopLevelPropertyCount != 0)
{
var templateWriter = new StringWriter();
string[] propertyNames = new string[eventInfo->TopLevelPropertyCount];
for (int j = 0; j < eventInfo->TopLevelPropertyCount; j++)
{
EVENT_PROPERTY_INFO* propertyInfo = &propertyInfos[j];
var propertyName = new string((char*)(&eventInfoBuff[propertyInfo->NameOffset]));
propertyNames[j] = propertyName;
var enumAttrib = "";
// Deal with any maps (bit fields or enumerations)
if (propertyInfo->MapNameOffset != 0)
{
string mapName = new string((char*)(&eventInfoBuff[propertyInfo->MapNameOffset]));
if (enumBuffer == null)
{
enumBuffer = (byte*)System.Runtime.InteropServices.Marshal.AllocHGlobal(buffSize);
}
if (!enumIntern.ContainsKey(mapName))
{
EVENT_MAP_INFO* enumInfo = (EVENT_MAP_INFO*)enumBuffer;
var hr = TdhGetEventMapInformation(&eventRecord, mapName, enumInfo, ref buffSize);
if (hr == 0)
{
// We only support manifest enums for now.
if (enumInfo->Flag == MAP_FLAGS.EVENTMAP_INFO_FLAG_MANIFEST_VALUEMAP ||
enumInfo->Flag == MAP_FLAGS.EVENTMAP_INFO_FLAG_MANIFEST_BITMAP)
{
StringWriter enumWriter = new StringWriter();
string enumName = new string((char*)(&enumBuffer[enumInfo->NameOffset]));
enumAttrib = " map=\"" + enumName + "\"";
if (enumInfo->Flag == MAP_FLAGS.EVENTMAP_INFO_FLAG_MANIFEST_VALUEMAP)
{
enumWriter.WriteLine(" <valueMap name=\"{0}\">", enumName);
}
else
{
enumWriter.WriteLine(" <bitMap name=\"{0}\">", enumName);
}
EVENT_MAP_ENTRY* mapEntries = &enumInfo->MapEntryArray;
for (int k = 0; k < enumInfo->EntryCount; k++)
{
int value = mapEntries[k].Value;
string valueName = new string((char*)(&enumBuffer[mapEntries[k].NameOffset])).Trim();
enumWriter.WriteLine(" <map value=\"0x{0:x}\" message=\"$(string.map_{1}{2})\"/>", value, enumName, valueName);
enumLocalizations.WriteLine(" <string id=\"map_{0}{1}\" value=\"{2}\"/>", enumName, valueName, valueName);
}
if (enumInfo->Flag == MAP_FLAGS.EVENTMAP_INFO_FLAG_MANIFEST_VALUEMAP)
{
enumWriter.WriteLine(" </valueMap>", enumName);
}
else
{
enumWriter.WriteLine(" </bitMap>", enumName);
}
enumIntern[mapName] = enumWriter.ToString();
}
}
}
}
// Remove anything that does not look like an ID (.e.g space)
propertyName = Regex.Replace(propertyName, "[^A-Za-z0-9_]", "");
TdhInputType propertyType = propertyInfo->InType;
string countOrLengthAttrib = "";
if ((propertyInfo->Flags & PROPERTY_FLAGS.ParamCount) != 0)
{
countOrLengthAttrib = " count=\"" + propertyNames[propertyInfo->CountOrCountIndex] + "\"";
}
else if ((propertyInfo->Flags & PROPERTY_FLAGS.ParamLength) != 0)
{
countOrLengthAttrib = " length=\"" + propertyNames[propertyInfo->LengthOrLengthIndex] + "\"";
}
templateWriter.WriteLine(" <data name=\"{0}\" inType=\"win:{1}\"{2}{3}/>", propertyName, propertyType.ToString(), enumAttrib, countOrLengthAttrib);
}
var templateStr = templateWriter.ToString();
// See if this template already exists, and if not make it
string templateName;
if (!templateIntern.TryGetValue(templateStr, out templateName))
{
templateName = eventName + "Args";
if (eventInfo->EventDescriptor.Version > 0)
{
templateName += "_V" + eventInfo->EventDescriptor.Version;
}
templateIntern[templateStr] = templateName;
}
eventWriter.Write(" template=\"{0}\"", templateName);
}
eventWriter.WriteLine("/>");
}
}
}
if (enumBuffer != null)
{
System.Runtime.InteropServices.Marshal.FreeHGlobal((IntPtr)enumBuffer);
}
if (providerName == null)
{
throw new ApplicationException("Could not find provider with at GUID of " + providerGuid.ToString());
}
StringWriter manifest = new StringWriter();
manifest.WriteLine("<instrumentationManifest xmlns=\"http://schemas.microsoft.com/win/2004/08/events\">");
manifest.WriteLine(" <instrumentation xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:win=\"http://manifests.microsoft.com/win/2004/08/windows/events\">");
manifest.WriteLine(" <events>");
manifest.WriteLine(" <provider name=\"{0}\" guid=\"{{{1}}}\" resourceFileName=\"{0}\" messageFileName=\"{0}\" symbol=\"{2}\" source=\"Xml\" >",
providerName, providerGuid, Regex.Replace(providerName, @"[^\w]", ""));
StringWriter localizedStrings = new StringWriter();
if (keywords != null)
{
manifest.WriteLine(" <keywords>");
foreach (var keyValue in keywords)
{
manifest.WriteLine(" <keyword name=\"{0}\" message=\"$(string.keyword_{1})\" mask=\"0x{2:x}\"/>",
keyValue.Value, keyValue.Value, keyValue.Key);
localizedStrings.WriteLine(" <string id=\"keyword_{0}\" value=\"{1}\"/>", keyValue.Value, keyValue.Value);
}
manifest.WriteLine(" </keywords>");
}
manifest.WriteLine(" <tasks>");
foreach (var taskValue in tasks.Keys)
{
var task = tasks[taskValue];
manifest.WriteLine(" <task name=\"{0}\" message=\"$(string.task_{1})\" value=\"{2}\"{3}>", task.Name, task.Name, taskValue,
task.Opcodes == null ? "/" : ""); // If no opcodes, terminate immediately.
localizedStrings.WriteLine(" <string id=\"task_{0}\" value=\"{1}\"/>", task.Name, task.Name);
if (task.Opcodes != null)
{
manifest.WriteLine(">");
manifest.WriteLine(" <opcodes>");
foreach (var keyValue in task.Opcodes)
{
manifest.WriteLine(" <opcode name=\"{0}\" message=\"$(string.opcode_{1}{2})\" value=\"{3}\"/>",
keyValue.Value, task.Name, keyValue.Value, keyValue.Key);
localizedStrings.WriteLine(" <string id=\"opcode_{0}{1}\" value=\"{2}\"/>", task.Name, keyValue.Value, keyValue.Value);
}
manifest.WriteLine(" </opcodes>");
manifest.WriteLine(" </task>");
}
}
manifest.WriteLine(" </tasks>");
if (enumIntern.Count > 0)
{
manifest.WriteLine(" <maps>");
foreach (var map in enumIntern.Values)
{
manifest.Write(map);
}
manifest.WriteLine(" </maps>");
localizedStrings.Write(enumLocalizations.ToString());
}
manifest.WriteLine(" <events>");
foreach (StringWriter eventStr in events.Values)
{
manifest.Write(eventStr.ToString());
}
manifest.WriteLine(" </events>");
manifest.WriteLine(" <templates>");
foreach (var keyValue in templateIntern)
{
manifest.WriteLine(" <template tid=\"{0}\">", keyValue.Value);
manifest.Write(keyValue.Key);
manifest.WriteLine(" </template>");
}
manifest.WriteLine(" </templates>");
manifest.WriteLine(" </provider>");
manifest.WriteLine(" </events>");
manifest.WriteLine(" </instrumentation>");
string strings = localizedStrings.ToString();
if (strings.Length > 0)
{
manifest.WriteLine(" <localization>");
manifest.WriteLine(" <resources culture=\"{0}\">", IetfLanguageTag(CultureInfo.CurrentCulture));
manifest.WriteLine(" <stringTable>");
manifest.Write(strings);
manifest.WriteLine(" </stringTable>");
manifest.WriteLine(" </resources>");
manifest.WriteLine(" </localization>");
}
manifest.WriteLine("</instrumentationManifest>");
return manifest.ToString(); ;
}
#region private
// Borrowed from Core CLR System.Globalization.CultureInfo
private static string IetfLanguageTag(CultureInfo culture)
{
// special case the compatibility cultures
switch (culture.Name)
{
case "zh-CHT":
return "zh-Hant";
case "zh-CHS":
return "zh-Hans";
default:
return culture.Name;
}
}
private static string MakeLegalIdentifier(string name)
{
// TODO FIX NOW beef this up.
name = name.Replace(" ", "");
name = name.Replace("-", "_");
return name;
}
/// <summary>
/// Generates a space separated list of set of keywords 'keywordSet' using the table 'keywords'
/// It will generate new keyword names if needed and add them to 'keywords' if they are not present.
/// </summary>
private static string GetKeywordStr(SortedDictionary<ulong, string> keywords, ulong keywordSet)
{
var ret = "";
// TODO FIX NOW what should we be doing here? I do want pass along channel information
// We skip the reserved keywords (48 and above)
for (int i = 0; i < 48; i++)
{
ulong keyword = 1UL << i;
if ((keyword & keywordSet) != 0)
{
string keywordStr;
if (!keywords.TryGetValue(keyword, out keywordStr))
{
keywordStr = "keyword_" + keyword.ToString("x");
keywords[keyword] = keywordStr;
}
if (ret.Length != 0)
{
ret += " ";
}
ret += keywordStr;
}
}
return ret;
}
/// <summary>
/// Class used to accumulate information about Tasks in the implementation of GetManifestForRegisteredProvider
/// </summary>
private class TaskInfo
{
public string Name;
public SortedDictionary<int, string> Opcodes;
}
private static string Capitalize(string str)
{
if (str.Length == 0)
{
return str;
}
char c = str[0];
if (Char.IsUpper(c))
{
return str;
}
return (str.Substring(1).ToUpper() + str.Substring(1));
}
internal override DynamicTraceEventData TryLookup(TraceEvent unknownEvent)
{
return TryLookupWorker(unknownEvent, MapTable);
}
/// <summary>
/// Try to look up 'unknonwEvent using TDH or the TraceLogging mechanism. if 'mapTable' is non-null it will be used
/// look up the string names for fields that have bitsets or enumerated values. This is only need for the KernelTraceControl
/// case where the map information is logged as special events and can't be looked up with TDH APIs.
/// </summary>
internal static DynamicTraceEventData TryLookupWorker(TraceEvent unknownEvent, Dictionary<MapKey, IDictionary<long, string>> mapTable = null)
{
// We are not able to handle WPP events in this parser.
if (unknownEvent.lookupAsWPP)
{
return null;
}
// Is this a TraceLogging style
DynamicTraceEventData ret = null;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// Trace logging events are not guaranteed to be on channel 11.
// Trace logging events will have one of these headers.
bool hasETWEventInformation = false;
for (int i = 0; i != unknownEvent.eventRecord->ExtendedDataCount; i++)
{
var extType = unknownEvent.eventRecord->ExtendedData[i].ExtType;
if (extType == TraceEventNativeMethods.EVENT_HEADER_EXT_TYPE_EVENT_KEY ||
extType == TraceEventNativeMethods.EVENT_HEADER_EXT_TYPE_EVENT_SCHEMA_TL)
{
hasETWEventInformation = true;
break;
}
}
// TODO cache the buffer?, handle more types, handle structs...
int buffSize = 9000;
byte* buffer = (byte*)System.Runtime.InteropServices.Marshal.AllocHGlobal(buffSize);
int status = TdhGetEventInformation(unknownEvent.eventRecord, 0, null, buffer, &buffSize);
if (status == 122) // Buffer too small
{
System.Runtime.InteropServices.Marshal.FreeHGlobal((IntPtr)buffer);
buffer = (byte*)System.Runtime.InteropServices.Marshal.AllocHGlobal(buffSize);
status = TdhGetEventInformation(unknownEvent.eventRecord, 0, null, buffer, &buffSize);
}
if (status == 0)
{
ret = (new TdhEventParser(buffer, unknownEvent.eventRecord, mapTable)).ParseEventMetaData();
ret.containsSelfDescribingMetadata = hasETWEventInformation;
}
System.Runtime.InteropServices.Marshal.FreeHGlobal((IntPtr)buffer);
}
return ret;
}
/// <summary>
/// TdhEventParser takes the Trace Diagnostics Helper (TDH) TRACE_EVENT_INFO structure and
/// (passed as a byte*) and converts it to a DynamicTraceEventData which which
/// can be used to parse events of that type. You first create TdhEventParser and then
/// call ParseEventMetaData to do the parsing.
/// </summary>
internal class TdhEventParser
{
/// <summary>
/// Creates a new parser from the TRACE_EVENT_INFO held in 'buffer'. Use
/// ParseEventMetaData to then parse it into a DynamicTraceEventData structure.
/// EventRecord can be null and mapTable if present allow the parser to resolve maps (enums), and can be null.
/// </summary>
public TdhEventParser(byte* eventInfo, TraceEventNativeMethods.EVENT_RECORD* eventRecord, Dictionary<MapKey, IDictionary<long, string>> mapTable)
{
eventBuffer = eventInfo;
this.eventInfo = (TRACE_EVENT_INFO*)eventInfo;
propertyInfos = &this.eventInfo->EventPropertyInfoArray;
this.eventRecord = eventRecord;
this.mapTable = mapTable;
}
/// <summary>
/// Actually performs the parsing of the TRACE_EVENT_INFO passed in the constructor
/// </summary>
/// <returns></returns>
public DynamicTraceEventData ParseEventMetaData()
{
EVENT_PROPERTY_INFO* propertyInfos = &eventInfo->EventPropertyInfoArray;
string taskName = null;
if (eventInfo->TaskNameOffset != 0)
{
taskName = MakeLegalIdentifier(new string((char*)(&eventBuffer[eventInfo->TaskNameOffset])));
}
string opcodeName = null;
if (eventInfo->OpcodeNameOffset != 0)
{
opcodeName = new string((char*)(&eventBuffer[eventInfo->OpcodeNameOffset]));
if (opcodeName.StartsWith("win:"))
{
opcodeName = opcodeName.Substring(4);
}
opcodeName = MakeLegalIdentifier(opcodeName);
}
string providerName = "UnknownProvider";
if (eventInfo->ProviderNameOffset != 0)
{
providerName = new string((char*)(&eventBuffer[eventInfo->ProviderNameOffset]));
}
var eventID = eventInfo->EventDescriptor.Id;
// Mark it as a classic event if necessary.
if (eventInfo->DecodingSource == 1) // means it is from MOF (Classic)
{
eventID = (int)TraceEventID.Illegal;
}
var newTemplate = new DynamicTraceEventData(null, eventID,
eventInfo->EventDescriptor.Task, taskName,
eventInfo->EventGuid,
eventInfo->EventDescriptor.Opcode, opcodeName,
eventInfo->ProviderGuid, providerName);
if (eventID == (int)TraceEventID.Illegal)
{
newTemplate.lookupAsClassic = true;
}
if (eventInfo->EventMessageOffset != 0)
{
newTemplate.MessageFormat = new string((char*)(&eventBuffer[eventInfo->EventMessageOffset]));
}
Debug.WriteLine("In TdhEventParser for event" + providerName + "/" + taskName + "/" + opcodeName + " with " + eventInfo->TopLevelPropertyCount + " fields");
DynamicTraceEventData.PayloadFetchClassInfo fields = ParseFields(0, eventInfo->TopLevelPropertyCount);
newTemplate.payloadNames = fields.FieldNames;
newTemplate.payloadFetches = fields.FieldFetches;
return newTemplate; // return this as the event template for this lookup.
}
/// <summary>
/// Parses at most 'maxFields' fields starting at the current position.
/// Will return the parse fields in 'payloadNamesRet' and 'payloadFetchesRet'
/// Will return true if successful, false means an error occurred.
/// </summary>
private DynamicTraceEventData.PayloadFetchClassInfo ParseFields(int startField, int numFields)
{
ushort fieldOffset = 0;
var fieldNames = new List<string>(numFields);
var fieldFetches = new List<DynamicTraceEventData.PayloadFetch>(numFields);
for (int curField = 0; curField < numFields; curField++)
{
DynamicTraceEventData.PayloadFetch propertyFetch = new DynamicTraceEventData.PayloadFetch();
var propertyInfo = &propertyInfos[curField + startField];
var propertyName = new string((char*)(&eventBuffer[propertyInfo->NameOffset]));
// Remove anything that does not look like an ID (.e.g space)
propertyName = Regex.Replace(propertyName, "[^A-Za-z0-9_]", "");
// If it is an array, the field offset starts over at 0 because they are
// describing the ELMEMENT not the array and thus each element starts at 0
// Strings do NOT describe the element and thus don't get this treatment.
var arrayFieldOffset = fieldOffset;
if ((propertyInfo->Flags & (PROPERTY_FLAGS.ParamCount | PROPERTY_FLAGS.ParamLength)) != 0 &&
propertyInfo->InType != TdhInputType.UnicodeString && propertyInfo->InType != TdhInputType.AnsiString)
{
fieldOffset = 0;
}
// Is this a nested struct?
if ((propertyInfo->Flags & PROPERTY_FLAGS.Struct) != 0)
{
int numStructFields = propertyInfo->NumOfStructMembers;
Debug.WriteLine(" " + propertyName + " Is a nested type with " + numStructFields + " fields {");
DynamicTraceEventData.PayloadFetchClassInfo classInfo = ParseFields(propertyInfo->StructStartIndex, numStructFields);
if (classInfo == null)
{
Debug.WriteLine(" Failure parsing nested struct.");
goto Exit;
}
Debug.WriteLine(" } " + propertyName + " Nested struct completes.");
propertyFetch = DynamicTraceEventData.PayloadFetch.StructPayloadFetch(fieldOffset, classInfo);
}
else // A normal type
{
propertyFetch = new DynamicTraceEventData.PayloadFetch(fieldOffset, propertyInfo->InType, propertyInfo->OutType);
if (propertyFetch.Size == DynamicTraceEventData.UNKNOWN_SIZE)
{
Trace.WriteLine(" Unknown type for " + propertyName + " " + propertyInfo->InType.ToString() + " fields from here will be missing.");
goto Exit;
}
// Deal with any maps (bit fields or enumerations)
if (propertyInfo->MapNameOffset != 0)
{
string mapName = new string((char*)(&eventBuffer[propertyInfo->MapNameOffset]));
// Normal case, you can look up the enum information immediately.
if (eventRecord != null)
{
int buffSize = 84000; // TODO this is inefficient (and incorrect for very large enums).
byte* enumBuffer = (byte*)System.Runtime.InteropServices.Marshal.AllocHGlobal(buffSize);
EVENT_MAP_INFO* enumInfo = (EVENT_MAP_INFO*)enumBuffer;
var hr = TdhGetEventMapInformation(eventRecord, mapName, enumInfo, ref buffSize);
if (hr == 0)
{
propertyFetch.Map = ParseMap(enumInfo, enumBuffer);
}
System.Runtime.InteropServices.Marshal.FreeHGlobal((IntPtr)enumBuffer);
}
else
{
// This is the kernelTraceControl case, the map information will be provided
// later, so we have to set up a LAZY map which will be evaluated when we need the
// enum (giving time for the enum definition to be processed.
var mapKey = new MapKey(eventInfo->ProviderGuid, mapName);
// Set the map to be a lazyMap, which is a Func that returns a map.
Func<IDictionary<long, string>> lazyMap = delegate ()
{
IDictionary<long, string> map = null;
if (mapTable != null)
{
mapTable.TryGetValue(mapKey, out map);
}
return map;
};
propertyFetch.LazyMap = lazyMap;
}
}
}
// is this dynamically sized with another field specifying the length?
// Is it an array (binary and not a struct) (seems InType is not valid if property is a struct, so need to test for both.
if ((propertyInfo->Flags & (PROPERTY_FLAGS.ParamCount | PROPERTY_FLAGS.ParamLength | PROPERTY_FLAGS.ParamFixedCount)) != 0 || propertyInfo->CountOrCountIndex > 1 || (propertyInfo->InType == TdhInputType.Binary && (propertyInfo->Flags & PROPERTY_FLAGS.Struct) == 0))
{
// silliness where if it is a byte[] they use Length otherwise they use count. Normalize it.
var countOrCountIndex = propertyInfo->CountOrCountIndex;
if ((propertyInfo->Flags & PROPERTY_FLAGS.ParamLength) != 0 || propertyInfo->InType == TdhInputType.Binary)
{
countOrCountIndex = propertyInfo->LengthOrLengthIndex;
}
ushort fixedCount = 0;
ushort arraySize;
if ((propertyInfo->Flags & (PROPERTY_FLAGS.ParamFixedLength | PROPERTY_FLAGS.ParamFixedCount)) != 0)
{
fixedCount = countOrCountIndex;
arraySize = fixedCount;
}
else
{
// We only support the case where the length/count is right before the array. We remove this field
// and use the PREFIX size to indicate that the size of the array is determined by the 32 or 16 bit number before
// the array data.
if (countOrCountIndex == startField + curField - 1)
{
var lastFieldIdx = fieldFetches.Count - 1;
arraySize = DynamicTraceEventData.COUNTED_SIZE + DynamicTraceEventData.CONSUMES_FIELD + DynamicTraceEventData.ELEM_COUNT;
if (fieldFetches[lastFieldIdx].Size == 4)
{
arraySize += DynamicTraceEventData.BIT_32;
}
else if (fieldFetches[lastFieldIdx].Size != 2)
{
Trace.WriteLine("WARNING: Unexpected dynamic length size, giving up");
goto Exit;
}
// remove the previous field (so we have to adjust our offset)
if (arrayFieldOffset != ushort.MaxValue)
{
arrayFieldOffset -= fieldFetches[lastFieldIdx].Size;
}
fieldNames.RemoveAt(lastFieldIdx);
fieldFetches.RemoveAt(lastFieldIdx);
}
else
{
Trace.WriteLine(" Error: Array is variable sized and does not follow prefix convention.");
goto Exit;
}
}
// Strings are treated specially (we don't treat them as an array of chars).
// They don't need an arrayFetch but DO need set the size and offset appropriately
if (propertyFetch.Type == typeof(string))
{
// This is a string with its size determined by another field. Set the size
// based on 'arraySize' but preserver the IS_ANSI that we got from looking at the tdhInType.
propertyFetch.Size = (ushort)(arraySize | (propertyFetch.Size & DynamicTraceEventData.IS_ANSI));
propertyFetch.Offset = arrayFieldOffset;
}
else
{
Debug.WriteLine(" Field is an array of size " + ((fixedCount != 0) ? fixedCount.ToString() : "VARIABLE") + " of type " + ((propertyFetch.Type ?? typeof(void))) + " at offset " + arrayFieldOffset.ToString("x"));
propertyFetch = DynamicTraceEventData.PayloadFetch.ArrayPayloadFetch(arrayFieldOffset, propertyFetch, arraySize, fixedCount);
}
fieldOffset = ushort.MaxValue; // Indicate that the next offset must be computed at run time.
}
fieldFetches.Add(propertyFetch);
fieldNames.Add(propertyName);
var size = propertyFetch.Size;
Debug.WriteLine(" Got TraceLogging Field " + propertyName + " " + (propertyFetch.Type ?? typeof(void)) + " size " + size.ToString("x") + " offset " + fieldOffset.ToString("x") + " (void probably means array)");
Debug.Assert(0 < size);
if (size >= DynamicTraceEventData.SPECIAL_SIZES)
{
fieldOffset = ushort.MaxValue; // Indicate that the offset must be computed at run time.
}
else if (fieldOffset != ushort.MaxValue)
{
Debug.Assert(fieldOffset + size < ushort.MaxValue);
fieldOffset += size;
}
}
Exit:
var ret = new DynamicTraceEventData.PayloadFetchClassInfo() { FieldNames = fieldNames.ToArray(), FieldFetches = fieldFetches.ToArray() };
return ret; ;
}
// Parses a EVENT_MAP_INFO into a Dictionary for a Value map or a SortedDictionary for a Bitmap
// returns null if it does not know how to parse it.
internal static unsafe IDictionary<long, string> ParseMap(EVENT_MAP_INFO* enumInfo, byte* enumBuffer)
{
IDictionary<long, string> map = null;
// We only support manifest enums for now.
if (enumInfo->Flag == MAP_FLAGS.EVENTMAP_INFO_FLAG_MANIFEST_VALUEMAP ||
enumInfo->Flag == MAP_FLAGS.EVENTMAP_INFO_FLAG_MANIFEST_BITMAP)
{
StringWriter enumWriter = new StringWriter();
string enumName = new string((char*)(&enumBuffer[enumInfo->NameOffset]));
if (enumInfo->Flag == MAP_FLAGS.EVENTMAP_INFO_FLAG_MANIFEST_VALUEMAP)
{
map = new Dictionary<long, string>();
}
else
{
map = new SortedDictionary<long, string>();
}
EVENT_MAP_ENTRY* mapEntries = &enumInfo->MapEntryArray;
for (int k = 0; k < enumInfo->EntryCount; k++)
{
int value = mapEntries[k].Value;
string valueName = new string((char*)(&enumBuffer[mapEntries[k].NameOffset])).Trim();
map[value] = valueName;
}
}
return map;
}
#region private
private TRACE_EVENT_INFO* eventInfo;
private TraceEventNativeMethods.EVENT_RECORD* eventRecord;
private Dictionary<MapKey, IDictionary<long, string>> mapTable; // table of enums that have defined.
private EVENT_PROPERTY_INFO* propertyInfos;
private byte* eventBuffer; // points at the eventInfo, but in increments of bytes
#endregion // private
}
[DllImport("tdh.dll")]
internal static extern int TdhGetEventInformation(
TraceEventNativeMethods.EVENT_RECORD* pEvent,
uint TdhContextCount,
void* pTdhContext,
byte* pBuffer,
int* pBufferSize);
[DllImport("tdh.dll", CharSet = CharSet.Unicode)]
internal static extern int TdhGetEventMapInformation(
TraceEventNativeMethods.EVENT_RECORD* pEvent,
string pMapName,
EVENT_MAP_INFO* info,
ref int infoSize