forked from microsoft/perfview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserCommands.cs
More file actions
1928 lines (1706 loc) · 91.6 KB
/
UserCommands.cs
File metadata and controls
1928 lines (1706 loc) · 91.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Diagnostics.Tracing.StackSources;
using Microsoft.Diagnostics.Tracing.StackSources;
using Microsoft.Diagnostics.Symbols;
using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Etlx;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
using Microsoft.Diagnostics.Tracing.Parsers.Kernel;
using Microsoft.Diagnostics.Tracing.Session;
using Microsoft.Diagnostics.Tracing.Stacks;
using Microsoft.Diagnostics.Tracing.Stacks.Formats;
using Microsoft.Diagnostics.Utilities;
using PerfView;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Utilities;
using Address = System.UInt64;
#if !PERFVIEW_COLLECT
using Graphs;
using EventSources;
using PerfView.Dialogs;
using PerfView.GuiUtilities;
#endif
// This is an example use of the extensibility features.
namespace PerfViewExtensibility
{
/// <summary>
/// Commands is an actual use of the extensibility functionality. Normally a 'Commands'
/// class is compiled into a user defined DLL.
/// </summary>
public class Commands : CommandEnvironment
{
// If you add new build-in commands you need to add lines to src\PerfView\SupportFiles\PerfVIew.xml.
// This is the file that contains the help for the user commands. If you don't update this
// file, your new command will not have help.
//
// This can be as simple as coping the PerfView.xml file from output directory to src\PerfView\SupportFiles.
// HOwever you can do better than this by removing all 'method' entries that are not user commands
// That is members of this class. THis makes the file (and therefore PerfView.exe) smaller.
/// <summary>
/// Save Thread stacks from a NetPerf file into a *.speedscope.json file.
/// </summary>
/// <param name="netPerfFileName">The ETL file to convert</param>
public void NetperfToSpeedScope(string netPerfFileName)
{
string outputName = Path.ChangeExtension(netPerfFileName, ".speedscope.json");
string etlxFileName = TraceLog.CreateFromEventPipeDataFile(netPerfFileName);
using (var eventLog = new TraceLog(etlxFileName))
{
var startStopSource = new MutableTraceEventStackSource(eventLog);
// EventPipe currently only has managed code stacks.
startStopSource.OnlyManagedCodeStacks = true;
var computer = new SampleProfilerThreadTimeComputer(eventLog, App.GetSymbolReader(eventLog.FilePath));
computer.GenerateThreadTimeStacks(startStopSource);
SpeedScopeStackSourceWriter.WriteStackViewAsJson(startStopSource, outputName);
LogFile.WriteLine("[Converted {0} to {1} Use https://www.speedscope.app/ to view.]", netPerfFileName, outputName);
}
}
#if false // TODO Ideally you don't need Linux Specific versions, and it should be based
// on eventPipe. You can delete after 1/2018
public void LinuxGCStats(string traceFileName)
{
var options = new TraceLogOptions();
options.ConversionLog = LogFile;
if (App.CommandLineArgs.KeepAllEvents)
{
options.KeepAllEvents = true;
}
options.MaxEventCount = App.CommandLineArgs.MaxEventCount;
options.ContinueOnError = App.CommandLineArgs.ContinueOnError;
options.SkipMSec = App.CommandLineArgs.SkipMSec;
options.LocalSymbolsOnly = false;
options.ShouldResolveSymbols = delegate (string moduleFilePath) { return false; }; // Don't resolve any symbols
string etlxFilePath = traceFileName + ".etlx";
etlxFilePath = TraceLog.CreateFromLttngTextDataFile(traceFileName, etlxFilePath, options);
TraceLog traceLog = new TraceLog(etlxFilePath);
List<Microsoft.Diagnostics.Tracing.Analysis.TraceProcess> processes = new List<Microsoft.Diagnostics.Tracing.Analysis.TraceProcess>();
using (var source = traceLog.Events.GetSource())
{
Microsoft.Diagnostics.Tracing.Analysis.TraceLoadedDotNetRuntimeExtensions.NeedLoadedDotNetRuntimes(source);
source.Process();
foreach (var proc in Microsoft.Diagnostics.Tracing.Analysis.TraceProcessesExtensions.Processes(source))
{
if (Microsoft.Diagnostics.Tracing.Analysis.TraceLoadedDotNetRuntimeExtensions.LoadedDotNetRuntime(proc) != null)
{
processes.Add(proc);
}
}
}
string outputFileName = traceFileName + ".gcStats.html";
using (StreamWriter output = File.CreateText(outputFileName))
{
Stats.ClrStats.ToHtml(output, processes, outputFileName, "GCStats", Stats.ClrStats.ReportType.GC);
}
}
public void LinuxJITStats(string traceFileName)
{
var options = new TraceLogOptions();
options.ConversionLog = LogFile;
if (App.CommandLineArgs.KeepAllEvents)
{
options.KeepAllEvents = true;
}
options.MaxEventCount = App.CommandLineArgs.MaxEventCount;
options.ContinueOnError = App.CommandLineArgs.ContinueOnError;
options.SkipMSec = App.CommandLineArgs.SkipMSec;
options.LocalSymbolsOnly = false;
options.ShouldResolveSymbols = delegate (string moduleFilePath) { return false; }; // Don't resolve any symbols
string outputFileName = traceFileName + ".jitStats.html";
string etlxFilePath = traceFileName + ".etlx";
etlxFilePath = TraceLog.CreateFromLttngTextDataFile(traceFileName, etlxFilePath, options);
TraceLog traceLog = new TraceLog(etlxFilePath);
var source = traceLog.Events.GetSource();
Dictionary<int, Microsoft.Diagnostics.Tracing.Analysis.TraceProcess> jitStats = new Dictionary<int, Microsoft.Diagnostics.Tracing.Analysis.TraceProcess>();
Dictionary<int, List<object>> bgJitEvents = new Dictionary<int, List<object>>();
// attach callbacks to grab background JIT events
var clrPrivate = new ClrPrivateTraceEventParser(source);
clrPrivate.ClrMulticoreJitCommon += delegate (Microsoft.Diagnostics.Tracing.Parsers.ClrPrivate.MulticoreJitPrivateTraceData data)
{
if (!bgJitEvents.ContainsKey(data.ProcessID))
{
bgJitEvents.Add(data.ProcessID, new List<object>());
}
bgJitEvents[data.ProcessID].Add(data.Clone());
};
source.Clr.LoaderModuleLoad += delegate (ModuleLoadUnloadTraceData data)
{
if (!bgJitEvents.ContainsKey(data.ProcessID))
{
bgJitEvents.Add(data.ProcessID, new List<object>());
}
bgJitEvents[data.ProcessID].Add(data.Clone());
};
// process the model
Microsoft.Diagnostics.Tracing.Analysis.TraceLoadedDotNetRuntimeExtensions.NeedLoadedDotNetRuntimes(source);
source.Process();
foreach (var proc in Microsoft.Diagnostics.Tracing.Analysis.TraceProcessesExtensions.Processes(source))
{
if (Microsoft.Diagnostics.Tracing.Analysis.TraceLoadedDotNetRuntimeExtensions.LoadedDotNetRuntime(proc) != null && !jitStats.ContainsKey(proc.ProcessID))
{
jitStats.Add(proc.ProcessID, proc);
}
}
using (TextWriter output = File.CreateText(outputFileName))
{
Stats.ClrStats.ToHtml(output, jitStats.Values.ToList(), outputFileName, "JITStats", Stats.ClrStats.ReportType.JIT, true);
}
}
#endif
#if !PERFVIEW_COLLECT
/// <summary>
/// Dump every event in 'etlFileName' (which can be a ETL file or an ETL.ZIP file), as an XML file 'xmlOutputFileName'
/// If the output file name is not given, the input filename's extension is changed to '.etl.xml' and that is used.
///
/// This command is particularly useful for EventSources, where you want to post-process the data in some other tool.
/// </summary>
public void DumpEventsAsXml(string etlFileName, string xmlOutputFileName = null)
{
if (xmlOutputFileName == null)
xmlOutputFileName = PerfViewFile.ChangeExtension(etlFileName, ".etl.xml");
var eventCount = 0;
using (var outputFile = File.CreateText(xmlOutputFileName))
{
using (var etlFile = OpenETLFile(etlFileName))
{
var events = GetTraceEventsWithProcessFilter(etlFile);
var sb = new StringBuilder();
outputFile.WriteLine("<Events>");
foreach (TraceEvent _event in events)
{
sb.Clear();
_event.ToXml(sb);
outputFile.WriteLine(sb.ToString());
eventCount++;
}
outputFile.WriteLine("</Events>");
}
}
LogFile.WriteLine("[Wrote {0} events to {1}]", eventCount, xmlOutputFileName);
}
/// <summary>
/// Save the CPU stacks from 'etlFileName'. If the /process qualifier is present use it to narrow what
/// is put into the file to a single process.
/// </summary>
public void SaveCPUStacks(string etlFileName, string processName = null)
{
using (var etlFile = OpenETLFile(etlFileName))
{
TraceProcess process = null;
if (processName != null)
{
process = etlFile.Processes.LastProcessWithName(processName);
if (process == null)
throw new ApplicationException("Could not find process named " + processName);
}
SaveCPUStacksForProcess(etlFile, process);
}
}
/// <summary>
/// Save the CPU stacks for a set of traces.
///
/// If 'scenario' is an XML file, it will be used as a configuration file.
///
/// Otherwise, 'scenario' must refer to a directory. All ETL files in that directory and
/// any subdirectories will be processed according to the default rules.
///
/// Summary of config XML: ([] used instead of brackets)
/// [ScenarioConfig]
/// [Scenarios files="*.etl" process="$1.exe" name="scenario $1" /]
/// [/ScenarioConfig]
/// </summary>
public void SaveScenarioCPUStacks(string scenario)
{
var startTime = DateTime.Now;
int skipped = 0, updated = 0;
Dictionary<string, ScenarioConfig> configs;
var outputBuilder = new StringBuilder();
string outputName = null;
DateTime scenarioUpdateTime = DateTime.MinValue;
var writerSettings = new XmlWriterSettings()
{
Indent = true,
Encoding = Encoding.UTF8,
OmitXmlDeclaration = true
};
using (var outputWriter = XmlWriter.Create(outputBuilder, writerSettings))
{
if (scenario.EndsWith(".xml"))
{
using (var reader = XmlReader.Create(scenario))
{
configs = DeserializeScenarioConfig(reader, outputWriter, LogFile, Path.GetDirectoryName(scenario));
}
outputName = Path.ChangeExtension(scenario, ".scenarioSet.xml");
scenarioUpdateTime = File.GetLastWriteTimeUtc(scenario);
}
else
{
configs = new Dictionary<string, ScenarioConfig>();
var dirent = new DirectoryInfo(scenario);
foreach (var etl in dirent.EnumerateFiles("*.etl").Concat(dirent.EnumerateFiles("*.etl.zip")))
{
configs[PerfViewFile.ChangeExtension(etl.FullName, ".perfView.xml.zip")] = new ScenarioConfig(etl.FullName);
}
// Write default ScenarioSet.
outputWriter.WriteStartDocument();
outputWriter.WriteStartElement("ScenarioSet");
outputWriter.WriteStartElement("Scenarios");
outputWriter.WriteAttributeString("files", "*.perfView.xml.zip");
outputWriter.WriteEndElement();
outputWriter.WriteEndElement();
outputName = Path.Combine(scenario, "Default.scenarioSet.xml");
}
}
if (configs.Count == 0)
{
throw new ApplicationException("No ETL files specified");
}
foreach (var configPair in configs)
{
var destFile = configPair.Key;
var config = configPair.Value;
var filename = config.InputFile;
// Update if we've been written to since updateTime (max of file and scenario config write time).
var updateTime = File.GetLastWriteTimeUtc(filename);
if (scenarioUpdateTime > updateTime)
updateTime = scenarioUpdateTime;
if (File.Exists(destFile) &&
File.GetLastWriteTimeUtc(destFile) >= scenarioUpdateTime)
{
LogFile.WriteLine("[Skipping file {0}: up to date]", filename);
skipped++;
continue;
}
var etl = OpenETLFile(filename);
TraceProcess processOfInterest;
bool wildCard = false;
if (config.ProcessFilter == null)
{
processOfInterest = FindProcessOfInterest(etl);
}
else if (config.ProcessFilter == "*")
{
processOfInterest = null;
wildCard = true;
}
else
{
processOfInterest = null;
foreach (var process in etl.Processes)
{
if (config.StartTime <= process.StartTimeRelativeMsec &&
string.Compare(process.Name, config.ProcessFilter, StringComparison.OrdinalIgnoreCase) == 0)
{
processOfInterest = process;
break;
}
}
}
if (processOfInterest == null & !wildCard)
throw new ApplicationException("Process of interest could not be located for " + filename);
FilterParams filter = new FilterParams();
filter.StartTimeRelativeMSec = config.StartTime.ToString("R");
filter.EndTimeRelativeMSec = config.EndTime.ToString("R");
SaveCPUStacksForProcess(etl, processOfInterest, filter, destFile);
LogFile.WriteLine("[File {0} updated]", filename);
updated++;
}
// Regenerate scenario set if out-of-date.
if (!scenario.EndsWith(".xml") || !File.Exists(outputName) ||
File.GetLastWriteTimeUtc(outputName) < File.GetLastWriteTimeUtc(scenario))
{
LogFile.WriteLine("[Writing ScenarioSet file {0}]", outputName);
File.WriteAllText(outputName, outputBuilder.ToString(), Encoding.UTF8);
}
var endTime = DateTime.Now;
LogFile.WriteLine("[Scenario {3}: {0} generated, {1} up-to-date [{2:F3} s]]",
updated, skipped, (endTime - startTime).TotalSeconds,
Path.GetFileName(PerfViewFile.ChangeExtension(outputName, "")));
}
/// <summary>
/// If there are System.Diagnostics.Tracing.EventSources that are logging data to the ETL file
/// then there are manifests for each of these EventSources in event stream. This method
/// dumps these to 'outputDirectory' (each manifest file is 'ProviderName'.manifest.xml)
///
/// If outputDirectory is not present, then the directory 'EtwManifests' in the same directory
/// as the 'etlFileName' is used as the output directory.
/// If 'pattern' is present this is a .NET regular expression and only EventSources that match
/// the pattern will be output.
/// </summary>
public void DumpEventSourceManifests(string etlFileName, string outputDirectory = null, string pattern = null)
{
if (outputDirectory == null)
outputDirectory = Path.Combine(Path.GetDirectoryName(etlFileName), "ETWManifests");
var etlFile = OpenETLFile(etlFileName);
Directory.CreateDirectory(outputDirectory);
int manifestCount = 0;
foreach (var parser in etlFile.TraceLog.Parsers)
{
var asDynamic = parser as DynamicTraceEventParser;
if (asDynamic != null)
{
foreach (var provider in asDynamic.DynamicProviders)
{
if (pattern == null || Regex.IsMatch(provider.Name, pattern))
{
var filePath = Path.Combine(outputDirectory, provider.Name + ".manifest.xml");
LogFile.WriteLine("Creating manifest file {0}", filePath);
File.WriteAllText(filePath, provider.Manifest);
manifestCount++;
}
}
}
}
LogFile.WriteLine("[Created {0} manifest files in {1}]", manifestCount, outputDirectory);
}
/// <summary>
/// Generate a GCDumpFile of a JavaScript heap from ETW data in 'etlFileName'
/// </summary>
public void JSGCDumpFromETLFile(string etlFileName, string gcDumpOutputFileName = null)
{
if (gcDumpOutputFileName == null)
gcDumpOutputFileName = Path.ChangeExtension(etlFileName, ".gcdump");
// TODO FIX NOW retrieve the process name, ID etc.
var reader = new JavaScriptDumpGraphReader(LogFile);
var memoryGraph = reader.Read(etlFileName);
GCHeapDump.WriteMemoryGraph(memoryGraph, gcDumpOutputFileName);
LogFile.WriteLine("[Wrote gcDump file {0}]", gcDumpOutputFileName);
}
/// <summary>
/// Generate a GCDumpFile of a DotNet heap from ETW data in 'etlFileName',
/// need to have a V4.5.1 runtime (preferably V4.5.2) to have the proper events.
/// </summary>
public void DotNetGCDumpFromETLFile(string etlFileName, string processNameOrId = null, string gcDumpOutputFileName = null)
{
if (gcDumpOutputFileName == null)
gcDumpOutputFileName = PerfViewFile.ChangeExtension(etlFileName, ".gcdump");
CommandProcessor.UnZipIfNecessary(ref etlFileName, LogFile);
// TODO FIX NOW retrieve the process name, ID etc.
var reader = new DotNetHeapDumpGraphReader(LogFile);
var memoryGraph = reader.Read(etlFileName, processNameOrId);
GCHeapDump.WriteMemoryGraph(memoryGraph, gcDumpOutputFileName);
LogFile.WriteLine("[Wrote gcDump file {0}]", gcDumpOutputFileName);
}
/// <summary>
/// Pretty prints the raw .NET GC dump events (GCBulk*) with minimal processing as XML. This is mostly
/// useful for debugging, to see if the raw data sane if there is a question on why something is not showing
/// up properly in a more user-friendly view.
/// </summary>
/// <param name="etlFileName">The input ETW file containing the GC dump events</param>
/// <param name="processId">The process to focus on. 0 (the default) says to pick the first process with Bulk GC events.</param>
/// <param name="outputFileName">The output XML file.</param>
public void DumpRawDotNetGCHeapEvents(string etlFileName, string processId = null, string outputFileName = null)
{
if (outputFileName == null)
outputFileName = Path.ChangeExtension(etlFileName, ".rawEtwGCDump.xml");
int proccessIdInt = 0;
if (processId != null)
proccessIdInt = int.Parse(processId);
CommandProcessor.UnZipIfNecessary(ref etlFileName, LogFile);
var typeLookup = new Dictionary<Address, string>(500);
var events = new List<TraceEvent>();
var edges = new List<GCBulkEdgeTraceData>();
using (var source = new ETWTraceEventSource(etlFileName, TraceEventSourceType.MergeAll))
using (TextWriter output = File.CreateText(outputFileName))
{
source.Clr.TypeBulkType += delegate (GCBulkTypeTraceData data)
{
if (proccessIdInt == 0)
proccessIdInt = data.ProcessID;
if (proccessIdInt != data.ProcessID)
return;
output.WriteLine(" <TypeBulkType Proc=\"{0}\" TimeMSec=\"{1:f3}\" Count=\"{2}\"/>",
data.ProcessID, data.TimeStampRelativeMSec, data.Count);
for (int i = 0; i < data.Count; i++)
{
var typeData = data.Values(i);
typeLookup[typeData.TypeID] = typeData.TypeName;
}
};
source.Clr.GCBulkEdge += delegate (GCBulkEdgeTraceData data)
{
if (proccessIdInt != data.ProcessID)
return;
output.WriteLine(" <GCBulkEdge Proc=\"{0}\" TimeMSec=\"{1:f3}\" Count=\"{2}\"/>",
data.ProcessID, data.TimeStampRelativeMSec, data.Count);
edges.Add((GCBulkEdgeTraceData)data.Clone());
};
source.Clr.GCBulkNode += delegate (GCBulkNodeTraceData data)
{
if (proccessIdInt != data.ProcessID)
return;
events.Add(data.Clone());
};
source.Clr.GCBulkRootStaticVar += delegate (GCBulkRootStaticVarTraceData data)
{
if (proccessIdInt != data.ProcessID)
return;
events.Add(data.Clone());
};
source.Clr.GCBulkRootEdge += delegate (GCBulkRootEdgeTraceData data)
{
if (proccessIdInt != data.ProcessID)
return;
events.Add(data.Clone());
};
source.Clr.GCBulkRootConditionalWeakTableElementEdge += delegate (GCBulkRootConditionalWeakTableElementEdgeTraceData data)
{
if (proccessIdInt != data.ProcessID)
return;
events.Add(data.Clone());
};
source.Clr.GCBulkRootCCW += delegate (GCBulkRootCCWTraceData data)
{
if (proccessIdInt != data.ProcessID)
return;
events.Add(data.Clone());
};
source.Clr.GCBulkRCW += delegate (GCBulkRCWTraceData data)
{
if (proccessIdInt != data.ProcessID)
return;
events.Add(data.Clone());
};
output.WriteLine("<HeapDumpEvents>");
// Pass one process types and gather up interesting events.
source.Process();
// Need to do these things after all the type events are processed.
foreach (var data in events)
{
var node = data as GCBulkNodeTraceData;
if (node != null)
{
output.WriteLine(" <GCBulkNode Proc=\"{0}\" TimeMSec=\"{1:f3}\" Count=\"{2}\">",
data.ProcessID, data.TimeStampRelativeMSec, node.Count);
for (int i = 0; i < node.Count; i++)
{
var value = node.Values(i);
output.WriteLine(" <Node Type=\"{0}\" ObjectID=\"0x{1:x}\" Size=\"{2}\" EdgeCount=\"{3}\"/>",
typeName(typeLookup, value.TypeID), value.Address, value.Size, value.EdgeCount);
// TODO can show edges.
}
output.WriteLine(" </GCBulkNode>");
continue;
}
var rootEdge = data as GCBulkRootEdgeTraceData;
if (rootEdge != null)
{
output.WriteLine(" <GCBulkRootEdge Proc=\"{0}\" TimeMSec=\"{1:f3}\" Count=\"{2}\">",
rootEdge.ProcessID, rootEdge.TimeStampRelativeMSec, rootEdge.Count);
for (int i = 0; i < rootEdge.Count; i++)
{
var value = rootEdge.Values(i);
output.WriteLine(" <RootEdge GCRootID=\"0x{0:x}\" ObjectID=\"0x{1:x}\" GCRootKind=\"{2}\" GCRootFlag=\"{3}\"/>",
value.GCRootID, value.RootedNodeAddress, value.GCRootKind, value.GCRootFlag);
}
output.WriteLine(" </GCBulkRootEdge>");
continue;
}
var staticVar = data as GCBulkRootStaticVarTraceData;
if (staticVar != null)
{
output.WriteLine(" <GCBulkRootStaticVar Proc=\"{0}\" TimeMSec=\"{1:f3}\" Count=\"{2}\">",
staticVar.ProcessID, staticVar.TimeStampRelativeMSec, staticVar.Count);
for (int i = 0; i < staticVar.Count; i++)
{
var value = staticVar.Values(i);
output.WriteLine(" <StaticVar Type=\"{0}\" Name=\"{1}\" GCRootID=\"0x{2:x}\" ObjectID=\"0x{3:x}\"/>",
typeName(typeLookup, value.TypeID), XmlUtilities.XmlEscape(value.FieldName), value.GCRootID, value.ObjectID);
}
output.WriteLine(" </GCBulkRootStaticVar>");
continue;
}
var rcw = data as GCBulkRCWTraceData;
if (rcw != null)
{
output.WriteLine(" <GCBulkRCW Proc=\"{0}\" TimeMSec=\"{1:f3}\" Count=\"{2}\">",
rcw.ProcessID, rcw.TimeStampRelativeMSec, rcw.Count);
for (int i = 0; i < rcw.Count; i++)
{
var value = rcw.Values(i);
output.WriteLine(" <RCW Type=\"{0}\" ObjectID=\"0x{1:x}\" IUnknown=\"0x{2:x}\"/>",
typeName(typeLookup, value.TypeID), value.ObjectID, value.IUnknown);
}
output.WriteLine(" </GCBulkRCW>");
continue;
}
var ccw = data as GCBulkRootCCWTraceData;
if (ccw != null)
{
output.WriteLine(" <GCBulkRootCCW Proc=\"{0}\" TimeMSec=\"{1:f3}\" Count=\"{2}\">",
ccw.ProcessID, ccw.TimeStampRelativeMSec, ccw.Count);
for (int i = 0; i < ccw.Count; i++)
{
var value = ccw.Values(i);
output.WriteLine(" <RootCCW Type=\"{0}\" ObjectID=\"0x{1:x}\" IUnknown=\"0x{2:x}\"/>",
typeName(typeLookup, value.TypeID), value.ObjectID, value.IUnknown);
}
output.WriteLine(" </GCBulkRootCCW>");
continue;
}
var condWeakTable = data as GCBulkRootConditionalWeakTableElementEdgeTraceData;
if (condWeakTable != null)
{
output.WriteLine(" <GCBulkRootConditionalWeakTableElementEdge Proc=\"{0}\" TimeMSec=\"{1:f3}\" Count=\"{2}\">",
condWeakTable.ProcessID, condWeakTable.TimeStampRelativeMSec, condWeakTable.Count);
for (int i = 0; i < condWeakTable.Count; i++)
{
var value = condWeakTable.Values(i);
output.WriteLine(" <ConditionalWeakTableElementEdge GCRootID=\"0x{0:x}\" GCKeyID=\"0x{1:x}\" GCValueID=\"0x{2:x}\"/>",
value.GCRootID, value.GCKeyNodeID, value.GCValueNodeID);
}
output.WriteLine(" </GCBulkRootConditionalWeakTableElementEdge>");
continue;
}
}
output.WriteLine("</HeapDumpEvents>");
}
LogFile.WriteLine("[Wrote XML output for process {0} to file {1}]", processId, outputFileName);
}
private static string typeName(Dictionary<Address, string> types, Address typeId)
{
string ret;
if (types.TryGetValue(typeId, out ret))
return XmlUtilities.XmlEscape(ret);
return "TypeID(0x" + typeId.ToString("x") + ")";
}
/// <summary>
/// Dumps a GCDump file as XML. Useful for debugging heap dumping issues. It is easier to read than
/// what is produced by 'WriteGCDumpAsXml' but can't be read in with as a '.gcdump.xml' file.
/// </summary>
/// <param name="gcDumpFileName"></param>
public void DumpGCDumpFile(string gcDumpFileName)
{
var log = LogFile;
var gcDump = new GCHeapDump(gcDumpFileName);
Graph graph = gcDump.MemoryGraph;
log.WriteLine(
"Opened Graph {0} Bytes: {1:f3}M NumObjects: {2:f3}K NumRefs: {3:f3}K Types: {4:f3}K RepresentationSize: {5:f1}M",
gcDumpFileName, graph.TotalSize / 1000000.0, (int)graph.NodeIndexLimit / 1000.0,
graph.TotalNumberOfReferences / 1000.0, (int)graph.NodeTypeIndexLimit / 1000.0,
graph.SizeOfGraphDescription() / 1000000.0);
var outputFileName = Path.ChangeExtension(gcDumpFileName, ".heapDump.xml");
using (StreamWriter writer = File.CreateText(outputFileName))
((MemoryGraph)graph).DumpNormalized(writer);
log.WriteLine("[File {0} dumped as {1}.]", gcDumpFileName, outputFileName);
}
/// <summary>
/// Dumps a GCDump file as gcdump.xml file. THese files can be read back by PerfView.
/// </summary>
/// <param name="gcDumpFileName">The input file (.gcdump)</param>
/// <param name="outputFileName">The output file name (defaults to input file with .gcdump.xml suffix)</param>
public void WriteGCDumpAsXml(string gcDumpFileName, string outputFileName = null)
{
var log = LogFile;
var gcDump = new GCHeapDump(gcDumpFileName);
Graph graph = gcDump.MemoryGraph;
log.WriteLine(
"Opened Graph {0} Bytes: {1:f3}M NumObjects: {2:f3}K NumRefs: {3:f3}K Types: {4:f3}K RepresentationSize: {5:f1}M",
gcDumpFileName, graph.TotalSize / 1000000.0, (int)graph.NodeIndexLimit / 1000.0,
graph.TotalNumberOfReferences / 1000.0, (int)graph.NodeTypeIndexLimit / 1000.0,
graph.SizeOfGraphDescription() / 1000000.0);
if (outputFileName == null)
outputFileName = Path.ChangeExtension(gcDumpFileName, ".gcDump.xml");
using (StreamWriter writer = File.CreateText(outputFileName))
XmlGcHeapDump.WriteGCDumpToXml(gcDump, writer);
log.WriteLine("[File {0} written as {1}.]", gcDumpFileName, outputFileName);
}
/// <summary>
/// Given a name (or guid) of a provider registered on the system, generate a '.manifest.xml' file that
/// represents the manifest for that provider.
/// </summary>
public void DumpRegisteredManifest(string providerName, string outputFileName = null)
{
if (outputFileName == null)
outputFileName = providerName + ".manifest.xml";
var str = RegisteredTraceEventParser.GetManifestForRegisteredProvider(providerName);
LogFile.WriteLine("[Output written to {0}]", outputFileName);
File.WriteAllText(outputFileName, str);
}
/// <summary>
/// Opens a text window that displays events from the given set of event source names
/// By default the output goes to a GUI window but you can use the /LogFile option to
/// redirect it elsewhere.
/// </summary>
/// <param name="etwProviderNames"> a comma separated list of providers specs (just like /Providers value)</param>
public void Listen(string etwProviderNames)
{
var sessionName = "PerfViewListen";
LogFile.WriteLine("Creating Session {0}", sessionName);
using (var session = new TraceEventSession(sessionName))
{
TextWriter listenTextEditorWriter = null;
if (!App.CommandLineArgs.NoGui)
{
GuiApp.MainWindow.Dispatcher.BeginInvoke((Action)delegate ()
{
var logTextWindow = new Controls.TextEditorWindow(GuiApp.MainWindow);
// Destroy the session when the widow is closed.
logTextWindow.Closed += delegate (object sender, EventArgs e) { session.Dispose(); };
listenTextEditorWriter = new Controls.TextEditorWriter(logTextWindow.m_TextEditor);
logTextWindow.TextEditor.IsReadOnly = true;
logTextWindow.Title = "Listening to " + etwProviderNames;
logTextWindow.Show();
});
}
// Add callbacks for any EventSource Events to print them to the Text window
Action<TraceEvent> onAnyEvent = delegate (TraceEvent data)
{
try
{
String str = data.TimeStamp.ToString("HH:mm:ss.fff ");
str += data.EventName;
str += "\\" + data.ProviderName + " ";
for (int i = 0; i < data.PayloadNames.Length; i++)
{
var payload = data.PayloadNames[i];
if (i != 0)
str += ",";
str += String.Format("{0}=\"{1}\"", payload, data.PayloadByName(payload));
}
if (App.CommandLineArgs.NoGui)
App.CommandProcessor.LogFile.WriteLine("{0}", str);
else
{
GuiApp.MainWindow.Dispatcher.BeginInvoke((Action)delegate ()
{
// This should be null because the BeginInvoke above came before this
// and both are constrained to run in the same thread, so this has to
// be after it (and thus it is initialized).
Debug.Assert(listenTextEditorWriter != null);
listenTextEditorWriter.WriteLine("{0}", str);
});
}
}
catch (Exception e)
{
App.CommandProcessor.LogFile.WriteLine("Error: Exception during event processing of event {0}: {1}", data.EventName, e.Message);
}
};
session.Source.Dynamic.All += onAnyEvent;
// Add support for EventWriteStrings (which are not otherwise parsable).
session.Source.UnhandledEvents += delegate (TraceEvent data)
{
string formattedMessage = data.FormattedMessage;
if (formattedMessage != null)
listenTextEditorWriter.WriteLine("{0} {1} Message=\"{2}\"",
data.TimeStamp.ToString("HH:mm:ss.fff"), data.EventName, formattedMessage);
};
// Enable all the providers the users asked for
var parsedProviders = ProviderParser.ParseProviderSpecs(etwProviderNames.Split(','), null, LogFile);
foreach (var parsedProvider in parsedProviders)
{
LogFile.WriteLine("Enabling provider {0}:{1:x}:{2}", parsedProvider.Name, (ulong)parsedProvider.MatchAnyKeywords, parsedProvider.Level);
session.EnableProvider(parsedProvider.Name, parsedProvider.Level, (ulong)parsedProvider.MatchAnyKeywords, parsedProvider.Options);
}
// Start listening for events.
session.Source.Process();
}
}
/// <summary>
/// Creates perfView.xml file that represents the directory size of 'directoryPath' and places
/// it in 'outputFileName'.
/// </summary>
/// <param name="directoryPath">The directory whose size is being computed (default to the current dir)</param>
/// <param name="outputFileName">The output fileName (defaults to NAME.dirSize.PerfView.xml.zip) where NAME is
/// the simple name of the directory.</param>
public void DirectorySize(string directoryPath = null, string outputFileName = null)
{
if (string.IsNullOrWhiteSpace(directoryPath))
{
// Hop to the GUI thread and get the arguments from a dialog box and then call myself again.
GuiApp.MainWindow.Dispatcher.BeginInvoke((Action)delegate ()
{
var dialog = new FileInputAndOutput(GuiApp.MainWindow, delegate (string dirPath, string outFileName)
{
App.CommandLineArgs.CommandAndArgs = new string[] { "DirectorySize", dirPath, outFileName };
App.CommandLineArgs.DoCommand = App.CommandProcessor.UserCommand;
GuiApp.MainWindow.ExecuteCommand("Computing directory size", App.CommandLineArgs.DoCommand);
});
dialog.SelectingDirectories = true;
dialog.OutputExtension = ".dirSize.perfView.xml.zip";
dialog.CurrentDirectory = GuiApp.MainWindow.CurrentDirectory.FilePath;
dialog.HelpAnchor = "DirectorySize";
dialog.Instructions = "Please enter the name of the directory on which to do a disk size analysis " +
"and optionally the output file where place the resulting data.";
dialog.Title = "Disk Size Analysis";
dialog.Show();
});
return;
}
if (string.IsNullOrWhiteSpace(outputFileName))
{
if (char.IsLetterOrDigit(directoryPath[0]))
outputFileName = Path.GetFileNameWithoutExtension(Path.GetFullPath(directoryPath)) + ".dirSize.PerfView.xml.zip";
else
outputFileName = "dirSize.PerfView.xml.zip";
}
LogFile.WriteLine("[Computing the file size of the directory {0}...]", directoryPath);
// Open and close the output file to make sure we can write to it, that way we fail early if we can't
File.OpenWrite(outputFileName).Close();
File.Delete(outputFileName);
FileSizeStackSource fileSizeStackSource = new FileSizeStackSource(directoryPath, LogFile);
XmlStackSourceWriter.WriteStackViewAsZippedXml(fileSizeStackSource, outputFileName);
LogFile.WriteLine("[Wrote file {0}]", outputFileName);
if (!App.CommandLineArgs.NoGui && App.CommandLineArgs.LogFile == null)
{
if (outputFileName.EndsWith(".perfView.xml.zip", StringComparison.OrdinalIgnoreCase) && File.Exists(outputFileName))
GuiApp.MainWindow.OpenNext(outputFileName);
}
}
/// <summary>
/// Creates a .perfView.xml.zip that represents the profiling data from a perf script output dump. Adding a
/// --threadtime tag enables blocked time investigations on the perf script dump.
/// </summary>
/// <param name="path">The path to the perf script dump, right now, either a file with suffix perf.data.dump,
/// .trace.zip or .data.txt will be accepted.</param>
/// <param name="threadTime">Option to turn on thread time on the perf script dump.</param>
public void PerfScript(string path, string threadTime = null)
{
bool doThreadTime = threadTime != null && threadTime == "--threadtime";
var perfScriptStackSource = new ParallelLinuxPerfScriptStackSource(path, doThreadTime);
string outputFileName = Path.ChangeExtension(path, ".perfView.xml.zip");
XmlStackSourceWriter.WriteStackViewAsZippedXml(perfScriptStackSource, outputFileName);
if (!App.CommandLineArgs.NoGui && App.CommandLineArgs.LogFile == null)
{
if (outputFileName.EndsWith(".perfView.xml.zip", StringComparison.OrdinalIgnoreCase) && File.Exists(outputFileName))
{
GuiApp.MainWindow.OpenNext(outputFileName);
}
}
}
/// <summary>
/// Creates a stack source out of the textFileName where each line is a frame (which is directly rooted)
/// and every such line has a metric of 1. Thus it allows you to form histograms for these lines nicely
/// in perfView.
/// </summary>
/// <param name="textFilePath"></param>
public void TextHistogram(string textFilePath)
{
LogFile.WriteLine("[Opening {0} as a Histogram]");
var stackSource = new PerfView.OtherSources.TextStackSource();
stackSource.Read(textFilePath);
var stacks = new Stacks(stackSource);
OpenStackViewer(stacks);
}
/// <summary>
/// Reads a project N metaData.csv file (From ILC.exe) and converts it to a .GCDump file (a heap)
/// </summary>
public void ProjectNMetaData(string projectNMetadataDataCsv)
{
var metaDataReader = new ProjectNMetaDataLogReader();
var memoryGraph = metaDataReader.Read(projectNMetadataDataCsv);
var outputName = Path.ChangeExtension(projectNMetadataDataCsv, ".gcdump");
GCHeapDump.WriteMemoryGraph(memoryGraph, outputName);
LogFile.WriteLine("[Writing the GCDump to {0}]", outputName);
}
/// <summary>
/// This is used to visualize the Project N ILTransformed\*.reflectionlog.csv file so it can viewed
/// in PerfVIew.
/// </summary>
/// <param name="reflectionLogFile">The name of the file to view</param>
public void ReflectionUse(string reflectionLogFile)
{
LogFile.WriteLine("[Opening {0} as a Histogram]");
var stackSource = new PerfView.OtherSources.TextStackSource();
var lineNum = 0;
stackSource.StackForLine = delegate (StackSourceInterner interner, string line)
{
lineNum++;
StackSourceCallStackIndex ret = StackSourceCallStackIndex.Invalid;
Match m = Regex.Match(line, "^(.*?),(.*?),\"(.*)\"");
if (m.Success)
{
string reflectionType = m.Groups[1].Value;
string entityKind = m.Groups[2].Value;
string symbol = m.Groups[3].Value;
if (entityKind == "Method" || entityKind == "Field")
symbol = Regex.Replace(symbol, "^.*?[^,] +", "");
ret = interner.CallStackIntern(interner.FrameIntern("REFLECTION " + reflectionType), ret);
ret = interner.CallStackIntern(interner.FrameIntern("KIND " + entityKind), ret);
ret = interner.CallStackIntern(interner.FrameIntern("SYM " + symbol), ret);
}
else
LogFile.WriteLine("Warning {0}: Could not parse {1}", lineNum, line);
return ret;
};
stackSource.Read(reflectionLogFile);
var stacks = new Stacks(stackSource);
OpenStackViewer(stacks);
}
/// <summary>
/// ImageSize generates a XML report (by default inputExeName.imageSize.xml) that
/// breaks down the executable file 'inputExeName' by the symbols in it (fetched from
/// its PDB. The PDB needs to be locatable (either on the _NT_SYMBOL_PATH, or next to
/// the file, or in its original build location). This report can be viewed with
/// PerfView (it looks like a GC heap).
/// </summary>
/// <param name="inputExeName">The name of the EXE (or DLL) that you wish to analyze. If blank it will prompt for one.</param>
/// <param name="outputFileName">The name of the report file. Defaults to the inputExeName
/// with a .imageSize.xml suffix.</param>
public void ImageSize(string inputExeName = null, string outputFileName = null)
{
if (outputFileName == null)
outputFileName = Path.ChangeExtension(inputExeName, ".imageSize.xml");
if (string.IsNullOrWhiteSpace(inputExeName))
{
if (App.CommandLineArgs.NoGui)
throw new ApplicationException("Must specify an input EXE name");
// Hop to the GUI thread and get the arguments from a dialog box and then call myself again.
GuiApp.MainWindow.Dispatcher.BeginInvoke((Action)delegate ()
{
var dialog = new FileInputAndOutput(GuiApp.MainWindow, delegate (string inExeName, string outFileName)
{
App.CommandLineArgs.CommandAndArgs = new string[] { "ImageSize", inExeName, outFileName };
App.CommandLineArgs.DoCommand = App.CommandProcessor.UserCommand;
GuiApp.MainWindow.ExecuteCommand("Computing directory size", App.CommandLineArgs.DoCommand);
});
dialog.InputExtentions = new string[] { ".dll", ".exe" };
dialog.OutputExtension = ".imageSize.xml";
dialog.CurrentDirectory = GuiApp.MainWindow.CurrentDirectory.FilePath;
dialog.HelpAnchor = "ImageSize";
dialog.Instructions = "Please enter the name of the EXE or DLL on which you wish to do a size analysis " +
"and optionally the output file where place the resulting data.";
dialog.Title = "Image Size Analysis";
dialog.Show();
});
return;
}
string pdbScopeExe = Path.Combine(ExtensionsDirectory, "PdbScope.exe");
if (!File.Exists(pdbScopeExe))
throw new ApplicationException(@"The PerfViewExtensions\PdbScope.exe file does not exit. ImageSize report not possible");
// Currently we need to find the DLL again to unmangle names completely, and this DLL name is emedded in the output file.
// Remove relative paths and try to make it universal so that you stand the best chance of finding this DLL.
inputExeName = App.MakeUniversalIfPossible(Path.GetFullPath(inputExeName));
string commandLine = string.Format("{0} /x /f /s {1}", pdbScopeExe, Command.Quote(inputExeName));
LogFile.WriteLine("Running command {0}", commandLine);
FileUtilities.ForceDelete(outputFileName);
Command.Run(commandLine, new CommandOptions().AddOutputStream(LogFile).AddTimeout(3600000));
if (!File.Exists(outputFileName) || File.GetLastWriteTimeUtc(outputFileName) <= File.GetLastWriteTimeUtc(inputExeName))
{
// TODO can remove after pdbScope gets a proper outputFileName parameter
string pdbScopeOutputFile = Path.ChangeExtension(Path.GetFullPath(Path.GetFileName(inputExeName)), ".pdb.xml");
if (!File.Exists(pdbScopeOutputFile))
throw new ApplicationException("Error PdbScope did not create a file " + pdbScopeOutputFile);
LogFile.WriteLine("Moving {0} to {1}", pdbScopeOutputFile, outputFileName);
FileUtilities.ForceMove(pdbScopeOutputFile, outputFileName);
}
// TODO This is pretty ugly. If the main window is working we can't launch it.
if (!App.CommandLineArgs.NoGui && App.CommandLineArgs.LogFile == null)