-
Notifications
You must be signed in to change notification settings - Fork 718
/
Copy pathPerfViewData.cs
9652 lines (8470 loc) · 449 KB
/
PerfViewData.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Diagnostics.Tracing.StackSources;
using global::DiagnosticsHub.Packaging.Interop;
using Graphs;
using Microsoft.Diagnostics.Symbols;
using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Etlx;
using Microsoft.Diagnostics.Tracing.EventPipe;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Parsers.AspNet;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
using Microsoft.Diagnostics.Tracing.Parsers.ClrPrivate;
using Microsoft.Diagnostics.Tracing.Parsers.ETWClrProfiler;
using Microsoft.Diagnostics.Tracing.Parsers.IIS_Trace;
using Microsoft.Diagnostics.Tracing.Parsers.InteropEventProvider;
using Microsoft.Diagnostics.Tracing.Parsers.JSDumpHeap;
using Microsoft.Diagnostics.Tracing.Parsers.Kernel;
using Microsoft.Diagnostics.Tracing.Stacks;
using Microsoft.Diagnostics.Utilities;
using Microsoft.DiagnosticsHub.Packaging.InteropEx;
using PerfView.GuiUtilities;
using PerfViewExtensibility;
using PerfViewModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Media;
using System.Xml;
using Utilities;
using Address = System.UInt64;
using EventSource = EventSources.EventSource;
namespace PerfView
{
/// <summary>
/// PerfViewTreeItem is a common base class for something that can be represented in the
/// TreeView GUI. in particular it has a name, and children. This includes both
/// file directories as well as data file (that might have multiple sources inside them)
/// </summary>
public abstract class PerfViewTreeItem : INotifyPropertyChanged
{
/// <summary>
/// The name to place in the treeview (should be short).
/// </summary>
public string Name { get; protected internal set; }
/// <summary>
/// If the entry should have children in the TreeView, this is them.
/// </summary>
public virtual IList<PerfViewTreeItem> Children { get { return m_Children; } }
/// <summary>
/// All items have some sort of file path that is associated with them.
/// </summary>
public virtual string FilePath { get { return m_filePath; } }
public virtual string HelpAnchor { get { return GetType().Name; } }
public bool IsExpanded { get { return m_isExpanded; } set { m_isExpanded = value; FirePropertyChanged("IsExpanded"); } }
public bool IsSelected { get { return m_isSelected; } set { m_isSelected = value; FirePropertyChanged("IsSelected"); } }
/// <summary>
/// Open the file (This might be expensive (but maybe not). It should not be run on
/// the GUI thread. This should populate the Children property if that is appropriate.
///
/// if 'doAfter' is present, it will be run after the window has been opened. It is always
/// executed on the GUI thread.
/// </summary>
public abstract void Open(Window parentWindow, StatusBar worker, Action doAfter = null);
/// <summary>
/// Once something is opened, it should be closed.
/// </summary>
public abstract void Close();
// Support so that we can update children and the view will update
public event PropertyChangedEventHandler PropertyChanged;
protected void FirePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// The Icon to show next to the entry.
/// </summary>
public virtual ImageSource Icon { get { return GuiApp.MainWindow.Resources["StackSourceBitmapImage"] as ImageSource; } }
#region private
public override string ToString() { if (FilePath != null) { return FilePath; } return Name; }
protected List<PerfViewTreeItem> m_Children;
protected List<PerfViewReport> m_UserDeclaredChildren;
protected string m_filePath;
private bool m_isExpanded;
private bool m_isSelected;
#endregion
}
public class PerfViewDirectory : PerfViewTreeItem
{
// Only names that match this filter are displayed.
public Regex Filter
{
get { return m_filter; }
set
{
if (m_filter != value)
{
m_filter = value;
m_Children = null;
FirePropertyChanged("Children");
}
}
}
public PerfViewDirectory(string path)
{
m_filePath = path;
Name = System.IO.Path.GetFileName(path);
}
public override IList<PerfViewTreeItem> Children
{
get
{
if (m_Children == null)
{
m_Children = new List<PerfViewTreeItem>();
if (Name != "..")
{
try
{
foreach (var filePath in FilesInDirectory(m_filePath))
{
var template = PerfViewFile.TryGet(filePath);
if (template != null)
{
// Filter out kernel, rundown files etc, if the base file exists.
Match m = Regex.Match(filePath, @"^(.*)\.(kernel|clr|user)[^.]*\.etl$", RegexOptions.IgnoreCase);
if (m.Success && File.Exists(m.Groups[1].Value + ".etl"))
continue;
// Filter out any items we were asked to filter out.
if (m_filter != null && !m_filter.IsMatch(Path.GetFileName(filePath)))
continue;
m_Children.Add(PerfViewFile.Get(filePath, template));
}
}
foreach (var dir in DirsInDirectory(m_filePath))
{
// Filter out any items we were asked to filter out.
if (m_filter != null && !m_filter.IsMatch(Path.GetFileName(dir)))
{
continue;
}
// We know that .NGENPDB directories are uninteresting, filter them out.
if (dir.EndsWith(".NENPDB", StringComparison.OrdinalIgnoreCase))
{
continue;
}
m_Children.Add(new PerfViewDirectory(dir));
}
// We always have the parent directory.
m_Children.Add(new PerfViewDirectory(System.IO.Path.Combine(m_filePath, "..")));
}
// FIX NOW review
catch (Exception) { }
}
}
return m_Children;
}
}
public override string HelpAnchor { get { return null; } } // Don't bother with help for this.
/// <summary>
/// Open the file (This might be expensive (but maybe not). This should populate the Children property
/// too.
/// </summary>
public override void Open(Window parentWindow, StatusBar worker, Action doAfter)
{
var mainWindow = parentWindow as MainWindow;
if (mainWindow != null)
{
mainWindow.OpenPath(FilePath);
}
doAfter?.Invoke();
}
/// <summary>
/// Close the file
/// </summary>
public override void Close() { }
public override ImageSource Icon { get { return GuiApp.MainWindow.Resources["FolderOpenBitmapImage"] as ImageSource; } }
#region private
private class DirCacheEntry
{
public string[] FilesInDirectory;
public string[] DirsInDirectory;
public DateTime LastWriteTimeUtc;
}
// To speed things up we remember the list list of directory items we fetched from disk
private static Dictionary<string, DirCacheEntry> s_dirCache = new Dictionary<string, DirCacheEntry>();
private static string[] FilesInDirectory(string directoryPath)
{
var entry = GetDirEntry(directoryPath);
if (entry.FilesInDirectory == null)
{
entry.FilesInDirectory = Directory.GetFiles(directoryPath);
}
return entry.FilesInDirectory;
}
private static string[] DirsInDirectory(string directoryPath)
{
var entry = GetDirEntry(directoryPath);
if (entry.DirsInDirectory == null)
{
entry.DirsInDirectory = Directory.GetDirectories(directoryPath);
}
return entry.DirsInDirectory;
}
/// <summary>
/// Gets a cache entry, nulls it out if it is out of date.
/// </summary>
private static DirCacheEntry GetDirEntry(string directoryPath)
{
DateTime lastWrite = Directory.GetLastWriteTimeUtc(directoryPath);
DirCacheEntry entry;
if (!s_dirCache.TryGetValue(directoryPath, out entry))
{
s_dirCache[directoryPath] = entry = new DirCacheEntry();
}
if (lastWrite != entry.LastWriteTimeUtc)
{
entry.DirsInDirectory = null;
entry.FilesInDirectory = null;
}
entry.LastWriteTimeUtc = lastWrite;
return entry;
}
private Regex m_filter;
#endregion
}
/// <summary>
/// A PerfViewTreeGroup simply groups other Items. Thus it has a name, and you use the Children
/// to add Child nodes to the group.
/// </summary>
public class PerfViewTreeGroup : PerfViewTreeItem
{
public PerfViewTreeGroup(string name)
{
Name = name;
m_Children = new List<PerfViewTreeItem>();
}
public PerfViewTreeGroup AddChild(PerfViewTreeItem child)
{
m_Children.Add(child);
return this;
}
// Groups do no semantic action. All the work is in the visual GUI part.
public override void Open(Window parentWindow, StatusBar worker, Action doAfter = null)
{
doAfter?.Invoke();
}
public override void Close() { }
public override IList<PerfViewTreeItem> Children { get { return m_Children; } }
public override string HelpAnchor { get { return Name.Replace(" ", ""); } }
public override ImageSource Icon { get { return GuiApp.MainWindow.Resources["FolderOpenBitmapImage"] as ImageSource; } }
}
/// <summary>
/// PerfViewData is an abstraction of something that PerfViewGui knows how to display. It is
/// </summary>
public abstract class PerfViewFile : PerfViewTreeItem
{
public bool IsOpened { get { return m_opened; } }
public bool IsUpToDate { get { return m_utcLastWriteAtOpen == File.GetLastWriteTimeUtc(FilePath); } }
/// <summary>
/// Get does not actually open the file (which might be expensive). It also does not
/// populate the children for the node (which again might be expensive). Instead it
/// just looks at the file name). It DOES however determine how this data will be
/// treated from here on (based on file extension or an explicitly passed template parameter.
///
/// Get implements interning, so if you Get the same full file path, then you will get the
/// same PerfViewDataFile structure.
///
/// After you have gotten a PerfViewData, you use instance methods to manipulate it
///
/// This routine throws if the path name does not have a suffix we understand.
/// </summary>
public static PerfViewFile Get(string filePath, PerfViewFile format = null)
{
var ret = TryGet(filePath, format);
if (ret == null)
{
throw new ApplicationException("Could not determine data Template from the file extension for " + filePath + ".");
}
return ret;
}
/// <summary>
/// Tries to to a 'Get' operation on filePath. If format == null (indicating
/// that we should try to determine the type of the file from the file suffix) and
/// it does not have a suffix we understand, then we return null.
/// </summary>
public static PerfViewFile TryGet(string filePath, PerfViewFile format = null)
{
if (format == null)
{
// See if it is any format we recognize.
foreach (PerfViewFile potentalFormat in Formats)
{
if (potentalFormat.IsMyFormat(filePath))
{
format = potentalFormat;
break;
};
}
if (format == null)
{
return null;
}
}
string fullPath = Path.GetFullPath(filePath);
PerfViewFile ret;
if (!s_internTable.TryGetValue(fullPath, out ret))
{
ret = (PerfViewFile)format.MemberwiseClone();
ret.m_filePath = filePath;
s_internTable[fullPath] = ret;
}
ret.Name = Path.GetFileName(ret.FilePath);
if (ret.Name.EndsWith(".etl", StringComparison.OrdinalIgnoreCase))
{
var dir = Path.GetDirectoryName(ret.FilePath);
if (dir.Length == 0)
{
dir = ".";
}
var wildCard = ret.Name.Insert(ret.Name.Length - 4, ".*");
if (Directory.GetFiles(dir, wildCard).Length > 0)
{
ret.Name += " (unmerged)";
}
}
return ret;
}
/// <summary>
/// Logs the fact that the GUI should call a user defined method when a file is opened.
/// </summary>
public static PerfViewFile GetTemplateForExtension(string extension)
{
foreach (PerfViewFile potentalFormat in Formats)
{
if (potentalFormat.IsMyFormat(extension))
{
return potentalFormat;
}
}
var ret = new PerfViewUserFile(extension + " file", new string[] { extension });
Formats.Add(ret);
return ret;
}
/// <summary>
/// Declares that the user command 'userCommand' (that takes one string argument)
/// should be called when the file is opened.
/// </summary>
public void OnOpenFile(string userCommand)
{
if (userCommands == null)
{
userCommands = new List<string>();
}
userCommands.Add(userCommand);
}
/// <summary>
/// Declares that the file should have a view called 'viewName' and the user command
/// 'userCommand' (that takes two string arguments (file, viewName)) should be called
/// when that view is opened
/// </summary>
public void DeclareFileView(string viewName, string userCommand)
{
if (m_UserDeclaredChildren == null)
{
m_UserDeclaredChildren = new List<PerfViewReport>();
}
m_UserDeclaredChildren.Add(new PerfViewReport(viewName, delegate (string reportFileName, string reportViewName)
{
PerfViewExtensibility.Extensions.ExecuteUserCommand(userCommand, new string[] { reportFileName, reportViewName });
}));
}
internal void ExecuteOnOpenCommand(StatusBar worker)
{
if (m_UserDeclaredChildren != null)
{
// The m_UserDeclaredChildren are templates. We need to instantiate them to this file before adding them as children.
foreach (var userDeclaredChild in m_UserDeclaredChildren)
{
m_Children.Add(new PerfViewReport(userDeclaredChild, this));
}
m_UserDeclaredChildren = null;
}
// Add the command to the list
if (userCommands == null)
{
return;
}
var args = new string[] { FilePath };
foreach (string command in userCommands)
{
worker.LogWriter.WriteLine("Running User defined OnFileOpen command " + command);
try
{
PerfViewExtensibility.Extensions.ExecuteUserCommand(command, args);
}
catch (Exception e)
{
worker.LogError(@"Error executing OnOpenFile command " + command + "\r\n" + e.ToString());
}
}
return;
}
// A list of user commands to be executed when a file is opened
private List<string> userCommands;
/// <summary>
/// Retrieves the base file name from a PerfView data source's name.
/// </summary>
/// <example>
/// GetBaseName(@"C:\data\foo.bar.perfView.xml.zip") == "foo.bar"
/// </example>
/// <param name="filePath">The path to the data source.</param>
/// <returns>The base name, without extensions or path, of <paramref name="filePath"/>.</returns>
public static string GetFileNameWithoutExtension(string filePath)
{
string fileName = Path.GetFileName(filePath);
foreach (var fmt in Formats)
{
foreach (string ext in fmt.FileExtensions)
{
if (fileName.EndsWith(ext))
{
return fileName.Substring(0, fileName.Length - ext.Length);
}
}
}
return fileName;
}
/// <summary>
/// Change the extension of a PerfView data source path.
/// </summary>
/// <param name="filePath">The path to change.</param>
/// <param name="newExtension">The new extension to add.</param>
/// <returns>The path to a file with the same directory and base name of <paramref name="filePath"/>,
/// but with extension <paramref name="newExtension"/>.</returns>
public static string ChangeExtension(string filePath, string newExtension)
{
string dirName = Path.GetDirectoryName(filePath);
string fileName = GetFileNameWithoutExtension(filePath) + newExtension;
return Path.Combine(dirName, fileName);
}
public override void Open(Window parentWindow, StatusBar worker, Action doAfter = null)
{
if (!m_opened)
{
worker.StartWork("Opening " + Name, delegate ()
{
Action<Action> continuation = OpenImpl(parentWindow, worker);
ExecuteOnOpenCommand(worker);
worker.EndWork(delegate ()
{
m_opened = true;
FirePropertyChanged("Children");
IsExpanded = true;
var defaultSource = GetStackSource();
if (defaultSource != null)
{
defaultSource.IsSelected = true;
}
if (continuation != null)
{
continuation(doAfter);
}
else
{
doAfter?.Invoke();
}
});
});
}
else
{
if (m_singletonStackSource != null && m_singletonStackSource.Viewer != null)
{
m_singletonStackSource.Viewer.Focus();
}
}
}
public override void Close()
{
if (m_opened)
{
m_opened = false;
s_internTable.Remove(FilePath);
}
if (m_Children != null)
{
m_Children.Clear();
FirePropertyChanged("Children");
}
}
public virtual PerfViewStackSource GetStackSource(string sourceName = null)
{
if (sourceName == null)
{
sourceName = DefaultStackSourceName;
if (sourceName == null)
{
return null;
}
}
Debug.Assert(m_opened);
if (m_Children != null)
{
foreach (var child in m_Children)
{
var asStackSource = child as PerfViewStackSource;
if (asStackSource != null && asStackSource.SourceName == sourceName)
{
return asStackSource;
}
var asGroup = child as PerfViewTreeGroup;
if (asGroup != null && asGroup.Children != null)
{
foreach (var groupChild in asGroup.Children)
{
asStackSource = groupChild as PerfViewStackSource;
if (asStackSource != null && asStackSource.SourceName == sourceName)
{
return asStackSource;
}
}
}
}
}
else if (m_singletonStackSource != null)
{
var asStackSource = m_singletonStackSource as PerfViewStackSource;
if (asStackSource != null)
{
return asStackSource;
}
}
return null;
}
public virtual string DefaultStackSourceName { get { return "CPU"; } }
/// <summary>
/// Gets or sets the processes to be initially included in stack views. The default value is null.
/// The names are not case sensitive.
/// </summary>
/// <remarks>
/// If this is null, a dialog will prompt the user to choose the initially included processes
/// from a list that contains all processes from the trace.
/// If this is NOT null, the 'Choose Process' dialog will never show and the initially included
/// processes will be all processes with a name in InitiallyIncludedProcesses.
/// </remarks>
/// <example>
/// Let's say these are the processes in the trace: devenv (104), PerfWatson2, (67) devenv (56)
/// and InitiallyIncludedProcesses = ["devenv", "vswinexpress"].
/// When the user opens a stack window, the included filter will be set to "^Process32% devenv (104)|^Process32% devenv (56)"
/// </example>
public string[] InitiallyIncludedProcesses { get; set; }
/// <summary>
/// If the stack sources have their first tier being the Process, then SupportsProcesses should be true.
/// </summary>
public virtual bool SupportsProcesses { get { return false; } }
/// <summary>
/// If the source logs data from multiple processes, this gives a list
/// of those processes. Returning null means you don't support this.
///
/// This can take a while. Don't call on the GUI thread.
/// </summary>
public virtual List<IProcess> GetProcesses(TextWriter log)
{
// This can take a while, should not be on GUI thread.
Debug.Assert(GuiApp.MainWindow.Dispatcher.Thread != System.Threading.Thread.CurrentThread);
var dataSource = GetStackSource(DefaultStackSourceName);
if (dataSource == null)
{
return null;
}
StackSource stackSource = dataSource.GetStackSource(log);
// maps call stack indexes to callStack closest to the root.
var rootMostFrameCache = new Dictionary<StackSourceCallStackIndex, IProcessForStackSource>();
var processes = new List<IProcess>();
DateTime start = DateTime.Now;
stackSource.ForEach(delegate (StackSourceSample sample)
{
if (sample.StackIndex != StackSourceCallStackIndex.Invalid)
{
var process = GetProcessFromStack(sample.StackIndex, stackSource, rootMostFrameCache, processes);
if (process != null)
{
process.CPUTimeMSec += sample.Metric;
long sampleTicks = start.Ticks + (long)(sample.TimeRelativeMSec * 10000);
if (sampleTicks < process.StartTime.Ticks)
{
process.StartTime = new DateTime(sampleTicks);
}
if (sampleTicks > process.EndTime.Ticks)
{
process.EndTime = new DateTime(sampleTicks);
}
Debug.Assert(process.EndTime >= process.StartTime);
}
}
});
processes.Sort();
if (processes.Count == 0)
{
processes = null;
}
return processes;
}
public virtual string Title
{
get
{
// Arrange the title putting most descriptive inTemplateion first.
var fullName = m_filePath;
Match m = Regex.Match(fullName, @"(([^\\]+)\\)?([^\\]+)$");
return m.Groups[3].Value + " in " + m.Groups[2].Value + " (" + fullName + ")";
}
}
public SymbolReader GetSymbolReader(TextWriter log, SymbolReaderOptions symbolFlags = SymbolReaderOptions.None)
{
return App.GetSymbolReader(FilePath, symbolFlags);
}
public virtual void LookupSymbolsForModule(string simpleModuleName, TextWriter log, int processId = 0)
{
throw new ApplicationException("This file type does not support lazy symbol resolution.");
}
// Things a subclass should be overriding
/// <summary>
/// The name of the file format.
/// </summary>
public abstract string FormatName { get; }
/// <summary>
/// The file extensions that this format knows how to read.
/// </summary>
public abstract string[] FileExtensions { get; }
/// <summary>
/// Implements the open operation. Executed NOT on the GUI thread. Typically returns null
/// which means the open is complete. If some operation has to be done on the GUI thread afterward
/// then action(doAfter) continuation is returned. This function is given an addition action
/// that must be done at the every end.
/// </summary>
protected virtual Action<Action> OpenImpl(Window parentWindow, StatusBar worker)
{
return delegate (Action doAfter)
{
// By default we have a singleton source (which we don't show on the GUI) and we immediately open it
m_singletonStackSource = new PerfViewStackSource(this, "");
m_singletonStackSource.Open(parentWindow, worker);
doAfter?.Invoke();
};
}
protected internal virtual void ConfigureStackWindow(string stackSourceName, StackWindow stackWindow) { }
/// <summary>
/// Allows you to do a firt action after everything is done.
/// </summary>
protected internal virtual void FirstAction(StackWindow stackWindow) { }
protected internal virtual StackSource OpenStackSourceImpl(
string streamName, TextWriter log, double startRelativeMSec = 0, double endRelativeMSec = double.PositiveInfinity, Predicate<TraceEvent> predicate = null)
{
return null;
}
/// <summary>
/// Simplified form, you should implement one overload or the other.
/// </summary>
/// <returns></returns>
protected internal virtual StackSource OpenStackSourceImpl(TextWriter log) { return null; }
protected internal virtual EventSource OpenEventSourceImpl(TextWriter log) { return null; }
// Helper functions for ConfigStackWindowImpl (we often configure windows the same way)
internal static void ConfigureAsMemoryWindow(string stackSourceName, StackWindow stackWindow)
{
bool walkableObjectView = HeapDumpPerfViewFile.Gen0WalkableObjectsViewName.Equals(stackSourceName) || HeapDumpPerfViewFile.Gen1WalkableObjectsViewName.Equals(stackSourceName);
// stackWindow.ScalingPolicy = ScalingPolicyKind.TimeMetric;
stackWindow.IsMemoryWindow = true;
stackWindow.FoldPercentTextBox.Text = stackWindow.GetDefaultFoldPercentage();
var defaultFold = "[];mscorlib!String";
if (!walkableObjectView)
{
stackWindow.FoldRegExTextBox.Text = defaultFold;
}
stackWindow.FoldRegExTextBox.Items.Insert(0, defaultFold);
var defaultExclusions = "[not reachable from roots]";
stackWindow.ExcludeRegExTextBox.Text = defaultExclusions;
stackWindow.ExcludeRegExTextBox.Items.Insert(0, defaultExclusions);
stackWindow.GroupRegExTextBox.Items.Insert(0, "[group modules] {%}!->module $1");
stackWindow.GroupRegExTextBox.Items.Insert(0, "[group full path module entries] {*}!=>module $1");
stackWindow.GroupRegExTextBox.Items.Insert(0, "[group module entries] {%}!=>module $1");
var defaultGroup = @"[group Framework] mscorlib!=>LIB;System%!=>LIB;";
if (!walkableObjectView)
{
stackWindow.GroupRegExTextBox.Text = defaultGroup;
}
stackWindow.GroupRegExTextBox.Items.Insert(0, defaultGroup);
stackWindow.PriorityTextBox.Text = Graphs.MemoryGraphStackSource.DefaultPriorities;
stackWindow.RemoveColumn("WhenColumn");
stackWindow.RemoveColumn("WhichColumn");
stackWindow.RemoveColumn("FirstColumn");
stackWindow.RemoveColumn("LastColumn");
stackWindow.RemoveColumn("IncAvgColumn");
}
internal static void ConfigureAsEtwStackWindow(StackWindow stackWindow, bool removeCounts = true, bool removeScenarios = true, bool removeIncAvg = true, bool windows = true)
{
if (removeCounts)
{
stackWindow.RemoveColumn("IncCountColumn");
stackWindow.RemoveColumn("ExcCountColumn");
stackWindow.RemoveColumn("FoldCountColumn");
}
if (removeScenarios)
{
stackWindow.RemoveColumn("WhichColumn");
}
if (removeIncAvg)
{
stackWindow.RemoveColumn("IncAvgColumn");
}
var defaultEntry = stackWindow.GetDefaultFoldPat();
stackWindow.FoldRegExTextBox.Text = defaultEntry;
stackWindow.FoldRegExTextBox.Items.Clear();
if (!string.IsNullOrWhiteSpace(defaultEntry))
{
stackWindow.FoldRegExTextBox.Items.Add(defaultEntry);
}
if (windows && defaultEntry != "ntoskrnl!%ServiceCopyEnd")
{
stackWindow.FoldRegExTextBox.Items.Add("ntoskrnl!%ServiceCopyEnd");
}
stackWindow.GroupRegExTextBox.Text = stackWindow.GetDefaultGroupPat();
stackWindow.GroupRegExTextBox.Items.Clear();
stackWindow.GroupRegExTextBox.Items.Add(@"[no grouping]");
if (windows)
{
stackWindow.GroupRegExTextBox.Items.Add(@"[group CLR/OS entries] \Temporary ASP.NET Files\->;v4.0.30319\%!=>CLR;v2.0.50727\%!=>CLR;mscoree=>CLR;\mscorlib.*!=>LIB;\System.Xaml.*!=>WPF;\System.*!=>LIB;Presentation%=>WPF;WindowsBase%=>WPF;system32\*!=>OS;syswow64\*!=>OS;{%}!=> module $1");
}
stackWindow.GroupRegExTextBox.Items.Add(@"[group modules] {%}!->module $1");
stackWindow.GroupRegExTextBox.Items.Add(@"[group module entries] {%}!=>module $1");
stackWindow.GroupRegExTextBox.Items.Add(@"[group full path module entries] {*}!=>module $1");
stackWindow.GroupRegExTextBox.Items.Add(@"[group class entries] {%!*}.%(=>class $1;{%!*}::=>class $1");
stackWindow.GroupRegExTextBox.Items.Add(@"[group classes] {%!*}.%(->class $1;{%!*}::->class $1");
}
// ideally this function would not exist. Does the open logic on the current thread (likely GUI thread)
// public is consumed by external extensions
public void OpenWithoutWorker()
{
OpenWithoutWorker(GuiApp.MainWindow, GuiApp.MainWindow.StatusBar);
}
internal void OpenWithoutWorker(Window parentWindow, StatusBar worker)
{
OpenImpl(parentWindow, worker);
}
// This is the global list of all known file types.
private static List<PerfViewFile> Formats = new List<PerfViewFile>()
{
new CSVPerfViewData(),
new ETLPerfViewData(),
new WTPerfViewFile(),
new ClrProfilerCodeSizePerfViewFile(),
new ClrProfilerAllocStacksPerfViewFile(),
new XmlPerfViewFile(),
new ClrProfilerHeapPerfViewFile(),
new PdbScopePerfViewFile(),
new VmmapPerfViewFile(),
new DebuggerStackPerfViewFile(),
new HeapDumpPerfViewFile(),
new ProcessDumpPerfViewFile(),
new ScenarioSetPerfViewFile(),
new OffProfPerfViewFile(),
new DiagSessionPerfViewFile(),
new LinuxPerfViewData(),
new XmlTreeFile(),
new EventPipePerfViewData()
};
#region private
internal void StackSourceClosing(PerfViewStackSource dataSource)
{
// TODO FIX NOW. WE need reference counting
if (m_singletonStackSource != null)
{
m_opened = false;
}
}
protected PerfViewFile() { } // Don't allow public default constructor
/// <summary>
/// Gets the process from the stack. It assumes that the stack frame closest to the root is the process
/// name and returns an IProcess representing it.
/// </summary>
private IProcessForStackSource GetProcessFromStack(StackSourceCallStackIndex callStack, StackSource stackSource,
Dictionary<StackSourceCallStackIndex, IProcessForStackSource> rootMostFrameCache, List<IProcess> processes)
{
Debug.Assert(callStack != StackSourceCallStackIndex.Invalid);
IProcessForStackSource ret;
if (rootMostFrameCache.TryGetValue(callStack, out ret))
{
return ret;
}
var caller = stackSource.GetCallerIndex(callStack);
if (caller == StackSourceCallStackIndex.Invalid)
{
string topCallStackStr = stackSource.GetFrameName(stackSource.GetFrameIndex(callStack), true);
Match m = Regex.Match(topCallStackStr, @"^Process\d*\s+([^()]*?)\s*(\(\s*(\d+)\s*\))?\s*$");
if (m.Success)
{
var processIDStr = m.Groups[3].Value;
var processName = m.Groups[1].Value;
if (processName.Length == 0)
{
processName = "(" + processIDStr + ")";
}
ret = new IProcessForStackSource(processName);
int processID;
if (int.TryParse(processIDStr, out processID))
{
ret.ProcessID = processID;
}
processes.Add(ret);
}
}
else
{
ret = GetProcessFromStack(caller, stackSource, rootMostFrameCache, processes);
}
rootMostFrameCache.Add(callStack, ret);
return ret;
}
protected bool IsMyFormat(string fileName)
{
foreach (var extension in FileExtensions)
{
if (fileName.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
protected bool m_opened;
protected internal DateTime m_utcLastWriteAtOpen;
// If we have only one stack source put it here
protected PerfViewStackSource m_singletonStackSource;
private static Dictionary<string, PerfViewFile> s_internTable = new Dictionary<string, PerfViewFile>();
#endregion
}
// Used for new user defined file formats.
internal class PerfViewUserFile : PerfViewFile
{
public PerfViewUserFile(string formatName, string[] fileExtensions)
{
m_formatName = formatName;
m_fileExtensions = fileExtensions;
}
public override string FormatName { get { return m_formatName; } }
public override string[] FileExtensions { get { return m_fileExtensions; } }
protected override Action<Action> OpenImpl(Window parentWindow, StatusBar worker) { return null; }
#region private
private string m_formatName;
private string[] m_fileExtensions;
#endregion
}
public class PerfViewReport : PerfViewTreeItem
{
// Used to create a template for all PerfViewFiles
public PerfViewReport(string name, Action<string, string> onOpen)
{
Name = name;
m_onOpen = onOpen;
}
// Used to clone a PerfViewReport and specialize it to a particular data file.
internal PerfViewReport(PerfViewReport template, PerfViewFile dataFile)
{
Name = template.Name;
m_onOpen = template.m_onOpen;
DataFile = dataFile;
}
#region overrides
public virtual string Title { get { return Name + " for " + DataFile.Title; } }
public PerfViewFile DataFile { get; private set; }
public override string FilePath { get { return DataFile.FilePath; } }
public override void Open(Window parentWindow, StatusBar worker, Action doAfter)
{
m_onOpen(DataFile.FilePath, Name);
}
public override void Close() { }
public override ImageSource Icon { get { return GuiApp.MainWindow.Resources["HtmlReportBitmapImage"] as ImageSource; } }
#endregion
#region private
private Action<string, string> m_onOpen;
#endregion
}
/// <summary>
/// Represents a report from an ETL file that can be viewed in a web browsers. Subclasses need
/// to override OpenImpl().
/// </summary>
public abstract class PerfViewHtmlReport : PerfViewTreeItem
{
public PerfViewHtmlReport(PerfViewFile dataFile, string name)
{