forked from microsoft/perfview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExtensibility.cs
More file actions
2199 lines (2029 loc) · 90.9 KB
/
Extensibility.cs
File metadata and controls
2199 lines (2029 loc) · 90.9 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.Symbols;
using Microsoft.Diagnostics.Tracing.Etlx;
using Microsoft.Diagnostics.Tracing.Stacks;
using Microsoft.Diagnostics.Utilities;
using PerfView;
using PerfViewModel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
using Utilities;
#if !PERFVIEW_COLLECT
using Graphs;
using EventSources;
using PerfView.Dialogs;
using PerfView.GuiUtilities;
#endif
namespace PerfViewExtensibility
{
/// <summary>
/// CommandEnvironment defines the 'primitive starting points' that a PerfView Extension uses
/// to start doing interesting things.
/// </summary>
public class CommandEnvironment
{
// logging
/// <summary>
/// The log file is a place to write verbose diagnostics. It is either the console or the GUI log, or
/// a file that use redirected logging to with the /logFile=XXX qualifier.
/// </summary>
public static TextWriter LogFile { get { return App.CommandProcessor.LogFile; } }
// File I/O
/// <summary>
/// Open an ETL file (same as new TraceLog(etlFileName))
/// </summary>
/// <param name="etlFileName"></param>
/// <returns></returns>
public static ETLDataFile OpenETLFile(string etlFileName) { return new ETLDataFile(etlFileName); }
/// <summary>
/// Opens a *.perfView.xml.zip or *.perfview.xml
/// </summary>
public static Stacks OpenPerfViewXmlFile(string perfViewXmlFileName)
{
var guiState = new StackWindowGuiState();
var source = new XmlStackSource(perfViewXmlFileName, delegate (XmlReader reader)
{
if (reader.Name == "StackWindowGuiState")
{
guiState.ReadFromXml(reader);
}
else
{
reader.Skip();
}
});
var ret = new Stacks(source, perfViewXmlFileName);
ret.GuiState = guiState;
ret.Name = perfViewXmlFileName;
return ret;
}
#if !PERFVIEW_COLLECT
/// <summary>
/// Opens a GCHeap dump (created with HeapSnapshot)
/// </summary>
public static Stacks OpenGCDumpFile(string gcDumpFileName)
{
var log = App.CommandProcessor.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 false // TODO FIX NOW remove
using (StreamWriter writer = File.CreateText(Path.ChangeExtension(this.FilePath, ".heapDump.xml")))
{
((MemoryGraph)graph).DumpNormalized(writer);
}
#endif
var retSource = new MemoryGraphStackSource(graph, log, gcDump.CountMultipliersByType);
// Set the sampling ratio so that the number of objects does not get too far out of control.
if (2000000 <= (int)graph.NodeIndexLimit)
{
retSource.SamplingRate = ((int)graph.NodeIndexLimit / 1000000);
log.WriteLine("Setting the sampling rate to {0} to keep processing under control.", retSource.SamplingRate);
}
// Figure out the multiplier
string extraTopStats = "";
if (gcDump.CountMultipliersByType != null)
{
extraTopStats += string.Format(" Heap Sampled: Mean Count Multiplier {0:f2} Mean Size Multiplier {1:f2}",
gcDump.AverageCountMultiplier, gcDump.AverageSizeMultiplier);
}
log.WriteLine("Type Histogram > 1% of heap size");
log.Write(graph.HistogramByTypeXml(graph.TotalSize / 100));
// TODO FIX NOW better name.
var retStacks = new Stacks(retSource, "GC Heap Dump of " + Path.GetFileName(gcDumpFileName));
retStacks.m_fileName = gcDumpFileName;
retStacks.ExtraTopStats = extraTopStats;
return retStacks;
}
#endif
// Data Collection
/// <summary>
/// Runs the command 'commandLine' with ETW enabled. Creates data file 'outputFileName'.
/// By default this is a Zipped ETL file.
/// </summary>
/// <param name="commandLine">The command line to run.</param>
/// <param name="dataFile">The data file to place the profile data. If omitted it is the parsedParams.DataFile</param>
/// <param name="parsedCommandLine">Any other arguments for the run command.
/// If omitted it is inherited from the CommandEnvironment.CommandLineArgs </param>
public static void Run(string commandLine, string dataFile = null, CommandLineArgs parsedCommandLine = null)
{
if (parsedCommandLine == null)
{
parsedCommandLine = App.CommandLineArgs;
}
parsedCommandLine.CommandLine = commandLine;
if (dataFile != null)
{
parsedCommandLine.DataFile = dataFile;
}
App.CommandProcessor.Run(parsedCommandLine);
}
/// <summary>
/// Run the 'Collect command creating the data file outputFileName. By default this is a Zipped ETL file.
/// </summary>
/// <param name="dataFile">The data file to place the profile data. If omitted it is the parsedParams.DataFile</param>
/// <param name="parsedCommandLine">Any other arguments for the run command.
/// If ommited it is inherited from the CommandEnvironment.CommandLineArgs </param>
public static void Collect(string dataFile = null, CommandLineArgs parsedCommandLine = null)
{
if (parsedCommandLine == null)
{
parsedCommandLine = App.CommandLineArgs;
}
if (dataFile != null)
{
parsedCommandLine.DataFile = dataFile;
}
App.CommandProcessor.Collect(parsedCommandLine);
}
/// <summary>
/// Collect a heap snapshot from 'process' placing the data in 'outputFileName' (a gcdump file)
/// </summary>
/// <param name="process">The name of the process or the process ID.
/// If there is more than one process with the same name, the one that was started LAST is chosen. </param>
/// <param name="outputFileName">The data file (.gcdump) to generate.</param>
public static void HeapSnapshot(string process, string outputFileName = null)
{
CommandLineArgs.Process = process;
if (outputFileName != null)
{
CommandLineArgs.DataFile = outputFileName;
}
App.CommandProcessor.HeapSnapshot(CommandLineArgs);
}
/// <summary>
/// Collect a heap snapshot from a process dump file 'dumpFile' placing the data in 'outputFileName' (a gcdump file)
/// </summary>
/// <param name="inputDumpFile">The dump file to extract the heap from.</param>
/// <param name="outputFileName">The data file (.gcdump) to generate. </param>
public static void HeapSnapshotFromProcessDump(string inputDumpFile, string outputFileName = null)
{
CommandLineArgs.ProcessDumpFile = inputDumpFile;
if (outputFileName != null)
{
CommandLineArgs.DataFile = outputFileName;
}
App.CommandProcessor.HeapSnapshot(CommandLineArgs);
}
#if !PERFVIEW_COLLECT
// gui operations
/// <summary>
/// Open a new stack viewer GUI window in the dat in 'stacks'
/// </summary>
/// <param name="stacks"></param>
/// <param name="OnOpened"></param>
public static void OpenStackViewer(Stacks stacks, Action<StackWindow> OnOpened = null)
{
GuiApp.MainWindow.Dispatcher.BeginInvoke((Action)delegate ()
{
// TODO FIX NOW Major hacks.
PerfViewStackSource perfViewStackSource;
string filePath;
if (stacks.m_EtlFile != null)
{
filePath = stacks.m_EtlFile.FilePath;
ETLPerfViewData file = (ETLPerfViewData)PerfViewFile.Get(filePath);
file.OpenWithoutWorker(GuiApp.MainWindow, GuiApp.MainWindow.StatusBar);
var stackSourceName = stacks.Name.Substring(0, stacks.Name.IndexOf(" file"));
perfViewStackSource = file.GetStackSource(stackSourceName);
if (perfViewStackSource == null)
perfViewStackSource = new PerfViewStackSource(file, "");
}
else
{
if (stacks.m_fileName != null)
filePath = stacks.m_fileName;
else
filePath = stacks.Name;
if (string.IsNullOrWhiteSpace(filePath))
filePath = "X.PERFVIEW.XML"; // MAJOR HACK.
var perfViewFile = PerfViewFile.Get(filePath);
var gcDumpFile = perfViewFile as HeapDumpPerfViewFile;
if (gcDumpFile != null)
{
gcDumpFile.OpenWithoutWorker(GuiApp.MainWindow, GuiApp.MainWindow.StatusBar);
var gcDump = gcDumpFile.GCDump;
if (gcDump.CreationTool != null && gcDump.CreationTool == "ILSize")
{
// Right now we set nothing.
stacks.GuiState = new StackWindowGuiState();
stacks.GuiState.Columns = new List<string> { "NameColumn",
"ExcPercentColumn", "ExcColumn", "ExcCountColumn",
"IncPercentColumn", "IncColumn", "IncCountColumn",
"FoldColumn", "FoldCountColumn" };
}
perfViewStackSource = gcDumpFile.GetStackSource();
}
else
{
var xmlFile = perfViewFile as XmlPerfViewFile;
if (xmlFile == null)
throw new ApplicationException("Currently only support ETL files and XML files");
perfViewStackSource = new PerfViewStackSource(xmlFile, "");
}
}
var stackWindow = new StackWindow(GuiApp.MainWindow, perfViewStackSource);
if (stacks.HasGuiState)
stackWindow.RestoreWindow(stacks.GuiState, filePath);
stackWindow.Filter = stacks.Filter;
stackWindow.SetStackSource(stacks.StackSource, delegate
{
if (stacks.HasGuiState)
stackWindow.GuiState = stacks.GuiState;
else
perfViewStackSource.ConfigureStackWindow(stackWindow);
LogFile.WriteLine("[Opened stack viewer {0}]", filePath);
OnOpened?.Invoke(stackWindow);
});
stackWindow.Show();
});
}
/// <summary>
/// Open a new EventViewer with the given set of events
/// </summary>
/// <param name="events"></param>
/// <param name="OnOpened">If non-null an action to perform after the window is opened (on the GUI thread)</param>
/// <returns></returns>
public static void OpenEventViewer(Events events, Action<EventWindow> OnOpened = null)
{
GuiApp.MainWindow.Dispatcher.BeginInvoke((Action)delegate ()
{
// TODO FIX NOW this is probably a hack?
var file = PerfViewFile.Get(events.m_EtlFile.FilePath);
var eventSource = new PerfViewEventSource(file);
eventSource.m_eventSource = events;
eventSource.Viewer = new EventWindow(GuiApp.MainWindow, eventSource);
eventSource.Viewer.Show();
if (OnOpened != null)
eventSource.Viewer.Loaded += delegate { OnOpened(eventSource.Viewer); };
});
}
/// <summary>
/// Displays an HTML file htmlFilePath, (typically created using CommandEnvironment.CreateUniqueCacheFileName())
/// in a new window.
/// </summary>
/// <param name="htmlFilePath">The path to the file containing the HTML.</param>
/// <param name="title">The title for the new window.</param>
/// <param name="DoCommand">Docommand(string command, TextWriter log), is a action that is called any time a URL of the
/// form <a href="command:XXXX"></a> is clicked on. The XXXX is passed as the command and a TextWriter that can display
/// messages to the windows log is given, and a handle to the web browser window itself. Messages surrounded by [] in
/// the log are also displayed on the windows one line status bar. Thus important messages should be surrounded by [].
/// This callback is NOT on the GUI thread, so you have to use the window.Dispatcher.BeginInvoke() to cause actions on
/// the GUI thread.</param>
/// <param name="OnOpened">If non-null an action to perform after the window is opened (on the GUI thread)</param>
public static void OpenHtmlReport(string htmlFilePath, string title,
Action<string, TextWriter, WebBrowserWindow> DoCommand = null, Action<WebBrowserWindow> OnOpened = null)
{
GuiApp.MainWindow.Dispatcher.BeginInvoke((Action)delegate ()
{
var viewer = new WebBrowserWindow(GuiApp.MainWindow);
viewer.Browser.Navigating += delegate (object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
{
if (e.Uri != null)
{
if (e.Uri.Scheme == "command")
{
e.Cancel = true;
if (viewer.StatusBar.Visibility != System.Windows.Visibility.Visible)
viewer.StatusBar.Visibility = System.Windows.Visibility.Visible;
viewer.StatusBar.StartWork("Following Hyperlink", delegate ()
{
if (DoCommand != null)
DoCommand(e.Uri.LocalPath, viewer.StatusBar.LogWriter, viewer);
else
viewer.StatusBar.Log("This view does not support command URLs.");
viewer.StatusBar.EndWork(null);
});
}
}
};
viewer.Width = 1000;
viewer.Height = 600;
viewer.Title = title;
WebBrowserWindow.Navigate(viewer.Browser, Path.GetFullPath(htmlFilePath));
viewer.Show();
if (OnOpened != null)
viewer.Loaded += delegate { OnOpened(viewer); };
});
}
#endif
/// <summary>
/// Open Excel on csvFilePath.
/// </summary>
public static void OpenExcel(string csvFilePath)
{
LogFile.WriteLine("[Opening CSV on {0}]", csvFilePath);
Command.Run(Command.Quote(csvFilePath), new CommandOptions().AddStart().AddTimeout(CommandOptions.Infinite));
}
#if !PERFVIEW_COLLECT
/// <summary>
/// Opens the log window if this is running under the GUI, otherwise does nothing.
/// </summary>
public static void OpenLog()
{
if (App.CommandLineArgs.NoGui)
return;
GuiApp.MainWindow.Dispatcher.BeginInvoke((Action)delegate ()
{
GuiApp.MainWindow.StatusBar.OpenLog();
});
}
#endif
// environment support
/// <summary>
/// The command lines passed to perfView itself. These are also populated by default values.
/// Setting these values in CommandLineArgs will cause the commands below to use the updated values.
/// </summary>
public static CommandLineArgs CommandLineArgs { get { return App.CommandLineArgs; } }
/// <summary>
/// ConfigData is a set of key-value dictionary that is persisted (as AppData\Roaming\PerfView\UserConfig.xml)
/// so it is remembered across invocations of the program.
/// </summary>
public static ConfigData ConfigData { get { return App.ConfigData; } }
/// <summary>
/// This is a directory where you can place temporary files. These files will be cleaned up
/// eventually if the number grows too large. (this is %TEMP%\PerfView)
/// </summary>
public static string CacheFileDirectory { get { return CacheFiles.CacheDir; } }
/// <summary>
/// Creates a file name that is in the CacheFileDirectory that will not collide with any other file.
/// You give it the base name (file name without extension), as well as the extension, and it returns
/// a full file path that is guaranteed to be unique.
/// </summary>
/// <param name="baseFilePath">The file name without extension (a suffix will be added to this)</param>
/// <param name="extension">optionally an extension to add to the file name (must have a . in front)</param>
/// <returns>The full path of a unique file in the CacheFileDirectory</returns>
public static string CreateUniqueCacheFileName(string baseFilePath, string extension = "")
{
return CacheFiles.FindFile(baseFilePath, extension);
}
/// <summary>
/// This is the directory that all extensions live in (e.g. PerfViewExtensibity next to PerfView.exe)
/// </summary>
public static string ExtensionsDirectory { get { return Extensions.ExtensionsDirectory; } }
/// <summary>
/// This is the directory where support files can go (.e.g AppData\Roaming\PerfView\VER.*)
/// </summary>
public static string SupportFilesDirectory { get { return SupportFiles.SupportFileDir; } }
}
public class DataFile : IDisposable
{ /// <summary>
/// The path of the data file
/// </summary>
public string FilePath { get { return m_FilePath; } }
public void Close() { Dispose(); }
public virtual void Dispose() { }
#region private
protected string m_FilePath;
#endregion
}
/// <summary>
/// ETL file is a simplified wrapper over the TraceLog class, which represents an ETL data file.
/// If you need 'advanced' features access the TraceLog property.
/// </summary>
public class ETLDataFile : DataFile
{
// We have the concept of a process to focus on. All STACK sampling will be filtered by this.
// If null, then no filtering is done. Do try to limit to one process if possible as it makes
// analysis and symbol lookup faster.
public void SetFilterProcess(TraceProcess process) { m_FilterProcess = process; }
public void SetFilterProcess(string name) { m_FilterProcess = Processes.LastProcessWithName(name); }
public void SetFilterProcess(int processId) { m_FilterProcess = Processes.LastProcessWithID(processId); }
public TraceProcess FilterProcess { get { return m_FilterProcess; } }
/// <summary>
/// ETL files collect machine wide, but it is good practice to focus on a particular process
/// as quickly as possible. TraceProcesses is a shortcut to TraceLog.Process that let you
/// find a process of interest quickly.
/// </summary>
public TraceProcesses Processes { get { return TraceLog.Processes; } }
/// <summary>
/// If the ETL file has stack samples, fetch them.
/// </summary>
public Stacks CPUStacks(bool loadAllCachedSymbols = false)
{
return new Stacks(TraceLog.CPUStacks(m_FilterProcess), "CPU", this, loadAllCachedSymbols);
}
/// <summary>
/// If the ETL file has stack samples, fetch them.
/// </summary>
public Stacks ThreadTimeStacks(bool loadAllCachedSymbols = false)
{
return new Stacks(TraceLog.ThreadTimeStacks(m_FilterProcess), "Thread Time", this, loadAllCachedSymbols);
}
/// <summary>
/// If the ETL file has stack samples, fetch them as an activity aware stack source.
/// </summary>
public Stacks ThreadTimeWithTasksStacks(bool loadAllCachedSymbols = false)
{
return new Stacks(TraceLog.ThreadTimeWithTasksStacks(m_FilterProcess), "Thread Time (with Tasks)", this, loadAllCachedSymbols);
}
#if !PERFVIEW_COLLECT
/// <summary>
/// Get the list of raw events.
/// </summary>
public Events Events { get { return new Events(this); } }
#endif
/// <summary>
/// Open an existing ETL file by name
/// </summary>
/// <param name="fileName">The name of the ETL file to open</param>
/// <param name="onLostEvents">If non-null, this method is called when there are lost events (with the count of lost events)</param>
public ETLDataFile(string fileName, Action<bool, int, int> onLostEvents = null)
{
var log = App.CommandProcessor.LogFile;
m_FilePath = fileName;
var etlOrEtlXFileName = FilePath;
UnZipIfNecessary(ref etlOrEtlXFileName, log);
for (; ; ) // RETRY Loop
{
var usedAnExistingEtlxFile = false;
var etlxFileName = etlOrEtlXFileName;
if (etlOrEtlXFileName.EndsWith(".etl", StringComparison.OrdinalIgnoreCase))
{
etlxFileName = CacheFiles.FindFile(etlOrEtlXFileName, ".etlx");
if (File.Exists(etlxFileName) && File.GetLastWriteTimeUtc(etlOrEtlXFileName) <= File.GetLastWriteTimeUtc(etlxFileName))
{
usedAnExistingEtlxFile = true;
log.WriteLine("Found a existing ETLX file in cache: {0}", etlxFileName);
}
else
{
var options = new TraceLogOptions();
options.ConversionLog = log;
if (App.CommandLineArgs.KeepAllEvents)
{
options.KeepAllEvents = true;
}
options.MaxEventCount = App.CommandLineArgs.MaxEventCount;
options.ContinueOnError = App.CommandLineArgs.ContinueOnError;
options.SkipMSec = App.CommandLineArgs.SkipMSec;
options.OnLostEvents = onLostEvents;
options.LocalSymbolsOnly = false;
options.ShouldResolveSymbols = delegate (string moduleFilePath) { return false; };
log.WriteLine("Creating ETLX file {0} from {1}", etlxFileName, etlOrEtlXFileName);
TraceLog.CreateFromEventTraceLogFile(etlOrEtlXFileName, etlxFileName, options);
var dataFileSize = "Unknown";
if (File.Exists(etlOrEtlXFileName))
{
dataFileSize = ((new System.IO.FileInfo(etlOrEtlXFileName)).Length / 1000000.0).ToString("n3") + " MB";
}
log.WriteLine("ETL Size {0} ETLX Size {1:n3} MB",
dataFileSize, (new System.IO.FileInfo(etlxFileName)).Length / 1000000.0);
}
}
// At this point we have an etlxFileName set, so we can open the TraceLog file.
try
{
m_TraceLog = new TraceLog(etlxFileName);
}
catch (Exception)
{
// Failure! If we used an existing ETLX file we should try to regenerate the file
if (usedAnExistingEtlxFile)
{
log.WriteLine("Could not open the ETLX file, regenerating...");
FileUtilities.ForceDelete(etlxFileName);
if (!File.Exists(etlxFileName))
{
continue; // Retry
}
}
throw;
}
break;
}
// Yeah we have opened the log file!
if (App.CommandLineArgs.UnsafePDBMatch)
{
m_TraceLog.CodeAddresses.UnsafePDBMatching = true;
}
}
/// <summary>
/// Lookup all symbols for any module with 'simpleFileName'. If processID==0 then all processes are searched.
/// </summary>
/// <param name="simpleModuleName">The name of the module without directory or extension</param>
/// <param name="symbolFlags">Options for symbol reading</param>
public void LookupSymbolsForModule(string simpleModuleName, SymbolReaderOptions symbolFlags = SymbolReaderOptions.None)
{
var symbolReader = GetSymbolReader(symbolFlags);
var log = App.CommandProcessor.LogFile;
// Remove any extensions.
simpleModuleName = Path.GetFileNameWithoutExtension(simpleModuleName);
// If we have a process, look the DLL up just there
var moduleFiles = new Dictionary<int, TraceModuleFile>();
if (m_FilterProcess != null)
{
foreach (var loadedModule in m_FilterProcess.LoadedModules)
{
var baseName = Path.GetFileNameWithoutExtension(loadedModule.Name);
if (string.Compare(baseName, simpleModuleName, StringComparison.OrdinalIgnoreCase) == 0)
{
moduleFiles[(int)loadedModule.ModuleFile.ModuleFileIndex] = loadedModule.ModuleFile;
}
}
}
// We did not find it, try system-wide
if (moduleFiles.Count == 0)
{
foreach (var moduleFile in TraceLog.ModuleFiles)
{
var baseName = Path.GetFileNameWithoutExtension(moduleFile.Name);
if (string.Compare(baseName, simpleModuleName, StringComparison.OrdinalIgnoreCase) == 0)
{
moduleFiles[(int)moduleFile.ModuleFileIndex] = moduleFile;
}
}
}
if (moduleFiles.Count == 0)
{
throw new ApplicationException("Could not find module " + simpleModuleName + " in trace.");
}
if (moduleFiles.Count > 1)
{
log.WriteLine("Found {0} modules with name {1}", moduleFiles.Count, simpleModuleName);
}
foreach (var moduleFile in moduleFiles.Values)
{
TraceLog.CodeAddresses.LookupSymbolsForModule(symbolReader, moduleFile);
}
}
/// <summary>
/// Access the underlying TraceLog class that actually represents the ETL data. You use
/// when the simplified wrappers are not sufficient.
/// </summary>
public TraceLog TraceLog { get { return m_TraceLog; } }
/// <summary>
/// Returns a SymbolReader which knows to look in local places associated with this file as well
/// as the user defined places.
/// </summary>
public SymbolReader GetSymbolReader(SymbolReaderOptions symbolFlags = SymbolReaderOptions.None)
{
return App.GetSymbolReader(m_FilePath, symbolFlags);
}
/// <summary>
/// Closes the file (so for example you could update it after this)
/// </summary>
public override void Dispose()
{
m_TraceLog.Dispose();
m_TraceLog = null;
}
#region private
private static void UnZipIfNecessary(ref string inputFileName, TextWriter log, bool unpackInCache = true)
{
if (string.Compare(Path.GetExtension(inputFileName), ".zip", StringComparison.OrdinalIgnoreCase) == 0)
{
string unzipedEtlFile;
if (unpackInCache)
{
unzipedEtlFile = CacheFiles.FindFile(inputFileName, ".etl");
if (File.Exists(unzipedEtlFile) && File.GetLastWriteTimeUtc(inputFileName) <= File.GetLastWriteTimeUtc(unzipedEtlFile))
{
log.WriteLine("Found a existing unzipped file {0}", unzipedEtlFile);
inputFileName = unzipedEtlFile;
return;
}
}
else
{
if (!inputFileName.EndsWith(".etl.zip", StringComparison.OrdinalIgnoreCase))
{
throw new ApplicationException("File does not end with the .etl.zip file extension");
}
unzipedEtlFile = inputFileName.Substring(0, inputFileName.Length - 4);
}
Stopwatch sw = Stopwatch.StartNew();
log.WriteLine("[Decompressing {0}]", inputFileName);
log.WriteLine("Generating output file {0}", unzipedEtlFile);
var zipArchive = ZipFile.OpenRead(inputFileName);
ZipArchiveEntry zippedEtlFile = null;
string dirForPdbs = null;
foreach (var entry in zipArchive.Entries)
{
if (entry.Length == 0) // Skip directories.
{
continue;
}
var fullName = entry.FullName;
if (fullName.EndsWith(".pdb", StringComparison.OrdinalIgnoreCase))
{
fullName = fullName.Replace('/', '\\'); // normalize separator convention
string pdbRelativePath = null;
if (fullName.StartsWith(@"symbols\", StringComparison.OrdinalIgnoreCase))
{
pdbRelativePath = fullName.Substring(8);
}
else if (fullName.StartsWith(@"ngenpdbs\", StringComparison.OrdinalIgnoreCase))
{
pdbRelativePath = fullName.Substring(9);
}
else
{
var m = Regex.Match(fullName, @"^[^\\]+\.ngenpdbs?\\(.*)", RegexOptions.IgnoreCase);
if (m.Success)
{
pdbRelativePath = m.Groups[1].Value;
}
else
{
log.WriteLine("WARNING: found PDB file that was not in a symbol server style directory, skipping extraction");
log.WriteLine(" Unzip this ETL and PDB by hand to use this PDB.");
continue;
}
}
if (dirForPdbs == null)
{
var inputDir = Path.GetDirectoryName(inputFileName);
if (inputDir.Length == 0)
{
inputDir = ".";
}
var symbolsDir = Path.Combine(inputDir, "symbols");
if (Directory.Exists(symbolsDir))
{
dirForPdbs = symbolsDir;
}
else
{
dirForPdbs = new SymbolPath(App.SymbolPath).DefaultSymbolCache();
}
log.WriteLine("Putting symbols in {0}", dirForPdbs);
}
var pdbTargetPath = Path.Combine(dirForPdbs, pdbRelativePath);
var pdbTargetName = Path.GetFileName(pdbTargetPath);
if (!File.Exists(pdbTargetPath) || (new System.IO.FileInfo(pdbTargetPath).Length != entry.Length))
{
var firstNameInRelativePath = pdbRelativePath;
var sepIdx = firstNameInRelativePath.IndexOf('\\');
if (sepIdx >= 0)
{
firstNameInRelativePath = firstNameInRelativePath.Substring(0, sepIdx);
}
var firstNamePath = Path.Combine(dirForPdbs, firstNameInRelativePath);
if (File.Exists(firstNamePath))
{
log.WriteLine("Deleting pdb file that is in the way {0}", firstNamePath);
FileUtilities.ForceDelete(firstNamePath);
}
log.WriteLine("Extracting PDB {0}", pdbRelativePath);
AtomicExtract(entry, pdbTargetPath);
}
else
{
log.WriteLine("PDB {0} exists, skipping", pdbRelativePath);
}
}
else if (fullName.EndsWith(".etl", StringComparison.OrdinalIgnoreCase))
{
if (zippedEtlFile != null)
{
throw new ApplicationException("The ZIP file does not have exactly 1 ETL file in it, can't auto-extract.");
}
zippedEtlFile = entry;
}
}
if (zippedEtlFile == null)
{
throw new ApplicationException("The ZIP file does not have any ETL files in it!");
}
AtomicExtract(zippedEtlFile, unzipedEtlFile);
log.WriteLine("Zipped size = {0:f3} MB Unzipped = {1:f3} MB",
zippedEtlFile.CompressedLength / 1000000.0, zippedEtlFile.Length / 1000000.0);
File.SetLastWriteTime(unzipedEtlFile, DateTime.Now); // Touch the file
inputFileName = unzipedEtlFile;
log.WriteLine("Finished decompression, took {0:f0} sec", sw.Elapsed.TotalSeconds);
}
}
// Extract to a temp file and move so we get atomic update. May leave trash behind
private static void AtomicExtract(ZipArchiveEntry zipEntry, string targetPath)
{
// Insure directory exists.
Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
var extractPath = targetPath + ".new";
try
{
zipEntry.ExtractToFile(extractPath, true);
FileUtilities.ForceMove(extractPath, targetPath);
}
finally
{
FileUtilities.ForceDelete(extractPath);
}
}
private TraceLog m_TraceLog;
private TraceProcess m_FilterProcess; // Only care about this process.
#endregion
}
#if !PERFVIEW_COLLECT
public class Events : ETWEventSource
{
void SaveAsCSV(string csvFileName)
{
string listSeparator = Thread.CurrentThread.CurrentCulture.TextInfo.ListSeparator;
using (var csvFile = File.CreateText(csvFileName))
{
// Write out column header
csvFile.Write("Event Name{0}Time MSec{0}Process Name", listSeparator);
// TODO get rid of ugly 4 column restriction
var maxField = 0;
var hasRest = true;
if (ColumnsToDisplay != null)
{
hasRest = false;
foreach (var columnName in ColumnsToDisplay)
{
Debug.Assert(!columnName.Contains(listSeparator));
if (maxField >= 4)
{
hasRest = true;
break;
}
maxField++;
csvFile.Write("{0}{1}", listSeparator, columnName);
}
}
if (hasRest)
csvFile.Write("{0}Rest", listSeparator);
csvFile.WriteLine();
// Write out events
this.ForEach(delegate (EventRecord _event)
{
// Have we exceeded MaxRet?
if (_event.EventName == null)
return false;
csvFile.Write("{0}{1}{2:f3}{1}{3}", _event.EventName, listSeparator, _event.TimeStampRelatveMSec, EscapeForCsv(_event.ProcessName, listSeparator));
var fields = _event.DisplayFields;
for (int i = 0; i < maxField; i++)
csvFile.Write("{0}{1}", listSeparator, EscapeForCsv(fields[i], listSeparator));
if (hasRest)
csvFile.Write("{0}{1}", listSeparator, EscapeForCsv(_event.Rest, listSeparator));
csvFile.WriteLine();
return true;
});
}
}
void OpenInExcel()
{
var log = App.CommandProcessor.LogFile;
var csvFile = CacheFiles.FindFile(m_EtlFile.FilePath, ".excel.csv");
if (File.Exists(csvFile))
{
FileUtilities.TryDelete(csvFile);
var baseFile = csvFile.Substring(0, csvFile.Length - 9);
for (int i = 1; ; i++)
{
csvFile = baseFile + i.ToString() + ".excel.csv";
if (!File.Exists(csvFile))
break;
}
}
log.WriteLine("Saving to CSV file {0}", csvFile);
SaveAsCSV(csvFile);
log.WriteLine("Opening CSV .");
Command.Run(Command.Quote(csvFile), new CommandOptions().AddStart().AddTimeout(CommandOptions.Infinite));
log.WriteLine("CSV file opened.");
throw new NotImplementedException();
}
public Events(ETLDataFile etlFile)
: base(etlFile.TraceLog)
{
m_EtlFile = etlFile;
}
#region private
/// <summary>
/// Returns a string that is will be exactly one field of a CSV file. Thus it escapes , and ""
/// </summary>
internal static string EscapeForCsv(string str, string listSeparator)
{
// TODO FIX NOW is this a hack?
if (str == null)
return "";
// If you don't have a comma, you are OK (we are losing leading and trailing whitespace but I don't care about that.
if (str.IndexOf(listSeparator) < 0)
return str;
// Escape all " by repeating them
str = str.Replace("\"", "\"\"");
return "\"" + str + "\""; // then quote the whole thing
}
internal ETLDataFile m_EtlFile;
#endregion
}
#endif
/// <summary>
/// A Stacks class represents what the PerfView 'stacks' view shows you. It has
/// a 'FilterParams' property which represents all the filter strings in that view.
/// It also has properties that represent the various tabs in that view (calltee, byname ...)
/// </summary>
public class Stacks
{
public FilterParams Filter { get { return m_Filter; } set { m_Filter = value; m_StackSource = null; } }
public void Update() { m_StackSource = null; }
public CallTree CallTree
{
get
{
if (m_CallTree == null || m_StackSource == null)
{
m_CallTree = new CallTree(ScalingPolicyKind.ScaleToData);
m_CallTree.StackSource = StackSource;
}
return m_CallTree;
}
}
private IEnumerable<CallTreeNodeBase> ByName
{
get
{
if (m_byName == null || m_CallTree == null || m_StackSource == null)
{
m_byName = CallTree.ByIDSortedExclusiveMetric();
}
return m_byName;
}
}
public CallTreeNodeBase FindNodeByName(string nodeNamePat)
{
var regEx = new Regex(nodeNamePat, RegexOptions.IgnoreCase);
foreach (var node in ByName)
{
if (regEx.IsMatch(node.Name))
{
return node;
}
}
return CallTree.Root;
}
public CallTreeNode GetCallers(string focusNodeName)
{
var focusNode = FindNodeByName(focusNodeName);
return AggregateCallTreeNode.CallerTree(focusNode);
}
public CallTreeNode GetCallees(string focusNodeName)
{
var focusNode = FindNodeByName(focusNodeName);
return AggregateCallTreeNode.CalleeTree(focusNode);
}
/// <summary>
/// Resolve the symbols of all modules that have at least 'minCount' INCLUSIVE samples.
/// symbolFlags indicate how aggressive you wish to be. By default it is aggressive as possible (do
/// whatever you need to get the PDB you need).
/// Setting 'minCount' to 0 will try to look up all symbols possible (which is relatively expensive).
///
/// By default all Warm symbols with a count > 50 AND in the machine local symbol cache are looked up.
/// If the cache is empty, or if you want even low count modules included, call this explicitly
/// </summary>
public void LookupWarmSymbols(int minCount, SymbolReaderOptions symbolFlags = SymbolReaderOptions.None)
{
TraceEventStackSource asTraceEventStackSource = GetTraceEventStackSource(m_rawStackSource);
if (asTraceEventStackSource == null)
{
App.CommandProcessor.LogFile.WriteLine("LookupWarmSymbols: Stack source does not support symbols.");
return;
}
string etlFilepath = null;
if (m_EtlFile != null)
{
etlFilepath = m_EtlFile.FilePath;
}
var reader = App.GetSymbolReader(etlFilepath, symbolFlags);
asTraceEventStackSource.LookupWarmSymbols(minCount, reader, StackSource);
m_StackSource = null;
}
/// <summary>
/// Lookup the symbols for a particular module (DLL).
/// </summary>
/// <param name="simpleModuleName">The simple name (dll name without path or file extension)</param>
/// <param name="symbolFlags">Optional flags that control symbol lookup</param>
public void LookupSymbolsForModule(string simpleModuleName, SymbolReaderOptions symbolFlags = SymbolReaderOptions.None)
{
if (m_EtlFile != null)
{
m_EtlFile.LookupSymbolsForModule(simpleModuleName, symbolFlags);
m_StackSource = null;
}
else
{
App.CommandProcessor.LogFile.WriteLine("LookupSymbolsForModule: Stack source does not support symbols.");
return;
}
}
/// <summary>
/// Saves the stacks as a XML file (or a ZIPed XML file). Only samples that pass the filter are saved.
/// Also all interesting symbolic names should be resolved first because it is impossible to resolve them
/// later. The saved samples CAN be regrouped later, however.