-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
3374 lines (3018 loc) · 166 KB
/
Program.cs
File metadata and controls
3374 lines (3018 loc) · 166 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 Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Etlx;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Parsers.Kernel;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DiagSessionAnalyzer;
class Program {
static void Main ( string[] args )
{
if ( args.Length == 0 )
{
Console.WriteLine ( "Usage: DiagSessionAnalyzer <path_to_etl_file> [--top N] [--pid PID] [--symbols PATH] [--verbose] [--timeout SECONDS] [--skip-size MB]" );
Console.WriteLine ( "Example: DiagSessionAnalyzer sc.user_aux.etl --top 50 --pid 4036" );
Console.WriteLine ( " DiagSessionAnalyzer sc.user_aux.etl --symbols \"srv*c:\\symbols*https://msdl.microsoft.com/download/symbols\"" );
Console.WriteLine ( " DiagSessionAnalyzer sc.user_aux.etl --verbose" );
Console.WriteLine ( " DiagSessionAnalyzer sc.user_aux.etl --timeout 30 (skip modules that take longer than 30 seconds)" );
Console.WriteLine ( " DiagSessionAnalyzer sc.user_aux.etl --skip-size 100 (skip modules if symbols exceed 100 MB)" );
return;
}
string etlPath = args[0];
int topCount = 50;
uint? filterPid = null;
string? symbolPath = null;
bool verbose = false;
int timeoutSeconds = 30; // Default timeout: 30 seconds
double? maxSizeMB = null; // Maximum size per module in MB (null = no limit)
// Parse arguments
for ( int i = 1; i < args.Length; i++ )
{
if ( args[i] == "--top" && i + 1 < args.Length )
{
if ( int.TryParse ( args[i + 1], out int top ) )
{
topCount = top;
i++;
}
}
else if ( ( args[i] == "--pid" || args[i] == "-p" ) && i + 1 < args.Length )
{
if ( uint.TryParse ( args[i + 1], out uint pid ) )
{
filterPid = pid;
i++;
}
}
else if ( ( args[i] == "--symbols" || args[i] == "-s" ) && i + 1 < args.Length )
{
symbolPath = args[i + 1];
i++;
}
else if ( args[i] == "--verbose" || args[i] == "-v" )
{
verbose = true;
}
else if ( ( args[i] == "--timeout" || args[i] == "-t" ) && i + 1 < args.Length )
{
if ( int.TryParse ( args[i + 1], out int timeout ) )
{
timeoutSeconds = timeout;
i++;
}
}
else if ( ( args[i] == "--skip-size" || args[i] == "--max-size" ) && i + 1 < args.Length )
{
if ( double.TryParse ( args[i + 1], out double maxSize ) )
{
maxSizeMB = maxSize;
i++;
}
}
}
if ( !File.Exists ( etlPath ) )
{
Console.WriteLine ( $"Error: File not found: {etlPath}" );
return;
}
Console.WriteLine ( $"=== DiagSession Analyzer ===\n" );
Console.WriteLine ( $"File: {etlPath}" );
Console.WriteLine ( $"Size: {new FileInfo(etlPath).Length / 1024 / 1024} MB\n" );
try
{
AnalyzeEtlFile ( etlPath, topCount, filterPid, symbolPath, verbose, timeoutSeconds, maxSizeMB );
}
catch ( Exception ex )
{
Console.WriteLine ( $"Error: {ex.Message}" );
Console.WriteLine ( $"Stack trace: {ex.StackTrace}" );
}
}
static void AnalyzeEtlFile ( string etlPath, int topCount, uint? filterPid, string? symbolPath, bool verbose, int timeoutSeconds = 30, double? maxSizeMB = null )
{
// Configure symbol path via environment variable BEFORE creating TraceLog
string? originalSymbolPath = null;
bool symbolPathSet = false;
if ( !string.IsNullOrEmpty ( symbolPath ) )
{
// Save original value
originalSymbolPath = Environment.GetEnvironmentVariable ( "_NT_SYMBOL_PATH" );
// Format symbol path correctly - if it's a directory, use it as cache
// Format: "srv*cache*server" for symbol server with cache
string formattedSymbolPath = symbolPath;
if ( Directory.Exists ( symbolPath ) )
{
// If it's a directory, use it as cache with Microsoft symbol server
// Format: srv*cache*server means: use cache directory, and download from server if not found
// Also add the directory itself as a direct path for local PDB files
formattedSymbolPath = $"{symbolPath};srv*{symbolPath}*https://msdl.microsoft.com/download/symbols";
}
// Set new symbol path for both _NT_SYMBOL_PATH and _NT_ALT_SYMBOL_PATH
Environment.SetEnvironmentVariable ( "_NT_SYMBOL_PATH", formattedSymbolPath );
Environment.SetEnvironmentVariable ( "_NT_ALT_SYMBOL_PATH", formattedSymbolPath );
symbolPathSet = true;
if ( verbose )
{
Console.WriteLine ( $"Symbol path set to: {formattedSymbolPath}" );
Console.WriteLine ( "Loading symbols (this may take a while on first run)...\n" );
}
else
{
Console.WriteLine ( $"Symbol path configured. Loading symbols...\n" );
}
}
else
{
// Check if environment variable is already set
string? envSymbolPath = Environment.GetEnvironmentVariable ( "_NT_SYMBOL_PATH" );
if ( !string.IsNullOrEmpty ( envSymbolPath ) )
{
if ( verbose )
{
Console.WriteLine ( $"Using symbol path from _NT_SYMBOL_PATH: {envSymbolPath}" );
Console.WriteLine ( "Loading symbols (this may take a while on first run)...\n" );
}
else
{
Console.WriteLine ( $"Using symbol path from _NT_SYMBOL_PATH. Loading symbols...\n" );
}
}
else
{
if ( verbose )
{
Console.WriteLine ( "No symbol path specified. Use --symbols to specify symbol path or set _NT_SYMBOL_PATH environment variable.\n" );
}
}
}
// Dictionary to store function call counts
var functionStats = new Dictionary<string, FunctionStats>();
var processNames = new Dictionary<uint, string>();
var callTrees = new Dictionary<uint, CallTreeNode>(); // Root nodes for each process
long totalStacks = 0;
Console.WriteLine ( "Converting ETL to ETLX for symbol resolution (this may take a while)...\n" );
// Convert ETL to ETLX for symbol resolution
// Note: If symbol path was set, we may need to delete existing ETLX to force symbol loading
string etlxPath = Path.ChangeExtension ( etlPath, ".etlx" );
// If symbol path was set and ETLX exists, delete it to force symbol reload
if ( symbolPathSet && File.Exists ( etlxPath ) )
{
if ( verbose )
{
Console.WriteLine ( "Deleting existing ETLX file to force symbol reload..." );
}
try
{
File.Delete ( etlxPath );
}
catch ( Exception ex )
{
if ( verbose )
{
Console.WriteLine ( $" Warning: Could not delete ETLX file: {ex.Message}" );
}
}
}
if ( !File.Exists ( etlxPath ) )
{
Console.WriteLine ( "Creating ETLX file for symbol resolution..." );
// Try to use TraceLogOptions if available
try
{
var createMethod = typeof ( TraceLog ).GetMethod ( "CreateFromEventTraceLogFile",
new[] { typeof ( string ), typeof ( string ), typeof ( TraceLogOptions ) } );
if ( createMethod != null )
{
if ( verbose )
{
Console.WriteLine ( " Using TraceLogOptions for symbol loading..." );
}
// Try to create TraceLogOptions with symbol loading enabled
var optionsType = typeof ( TraceLogOptions );
var options = Activator.CreateInstance ( optionsType )
?? throw new InvalidOperationException ( "Failed to create TraceLogOptions instance." );
// Get SymbolReaderOptions property
var symbolReaderOptionsProp = optionsType.GetProperty ( "SymbolReaderOptions",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );
if ( symbolReaderOptionsProp != null )
{
var symbolReaderOptionsType = symbolReaderOptionsProp.PropertyType;
var symbolReaderOptions = Activator.CreateInstance ( symbolReaderOptionsType );
if ( symbolReaderOptions != null && symbolPathSet )
{
var envSymbolPath = Environment.GetEnvironmentVariable ( "_NT_SYMBOL_PATH" );
if ( verbose )
{
Console.WriteLine ( $" Configuring SymbolReaderOptions with path: {envSymbolPath}" );
}
// Try to set SymbolPath property
var symbolPathProp = symbolReaderOptionsType.GetProperty ( "SymbolPath",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );
if ( symbolPathProp != null && envSymbolPath != null )
{
symbolPathProp.SetValue ( symbolReaderOptions, envSymbolPath );
if ( verbose )
{
Console.WriteLine ( $" Set SymbolPath property" );
}
}
else if ( envSymbolPath != null )
{
// Try alternative property names
var altPropNames = new[] { "Path", "SymbolServerPath", "CachePath", "SymbolCachePath" };
foreach ( var propName in altPropNames )
{
var prop = symbolReaderOptionsType.GetProperty ( propName,
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );
if ( prop != null )
{
prop.SetValue ( symbolReaderOptions, envSymbolPath );
if ( verbose )
{
Console.WriteLine ( $" Set {propName} property" );
}
break;
}
}
}
// Try to set other symbol-related properties that might help
var propertiesToSet = new Dictionary<string, object>();
if ( envSymbolPath != null )
{
propertiesToSet.Add ( "SymbolPath", envSymbolPath );
var cachePath = envSymbolPath.Split ( ';' ) [0];
if ( !string.IsNullOrEmpty ( cachePath ) )
{
propertiesToSet.Add ( "LocalSymbolCache", cachePath );
}
}
propertiesToSet.Add ( "SymbolServer", "https://msdl.microsoft.com/download/symbols" );
foreach ( var kvp in propertiesToSet )
{
var prop = symbolReaderOptionsType.GetProperty ( kvp.Key,
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );
if ( prop != null && prop.CanWrite )
{
try
{
prop.SetValue ( symbolReaderOptions, kvp.Value );
if ( verbose )
{
Console.WriteLine ( $" Set {kvp.Key} = {kvp.Value}" );
}
}
catch
{
// Ignore if can't set
}
}
}
// List all available properties for debugging
if ( verbose )
{
var allProps = symbolReaderOptionsType.GetProperties (
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );
Console.WriteLine ( $" Available SymbolReaderOptions properties: {string.Join(", ", allProps.Select(p => p.Name))}" );
}
symbolReaderOptionsProp.SetValue ( options, symbolReaderOptions );
}
}
else if ( verbose )
{
Console.WriteLine ( " Warning: SymbolReaderOptions property not found in TraceLogOptions" );
}
if ( verbose )
{
Console.WriteLine ( " Calling CreateFromEventTraceLogFile with options..." );
}
createMethod.Invoke ( null, new object[] { etlPath, etlxPath, options } );
if ( verbose )
{
Console.WriteLine ( " ✓ ETLX file created with TraceLogOptions" );
}
}
else
{
if ( verbose )
{
Console.WriteLine ( " TraceLogOptions method not available, using standard method" );
}
TraceLog.CreateFromEventTraceLogFile ( etlPath, etlxPath );
}
}
catch ( Exception ex )
{
if ( verbose )
{
Console.WriteLine ( $" Error creating ETLX with options: {ex.Message}" );
Console.WriteLine ( $" Stack trace: {ex.StackTrace}" );
}
// Fallback to standard method
Console.WriteLine ( " Falling back to standard ETLX creation (symbols may not load)..." );
TraceLog.CreateFromEventTraceLogFile ( etlPath, etlxPath );
}
}
else
{
Console.WriteLine ( "Using existing ETLX file..." );
if ( symbolPathSet && verbose )
{
Console.WriteLine ( "Note: Existing ETLX file may not have symbols. Delete .etlx file to force symbol reload." );
}
}
Console.WriteLine ( "Processing ETL file (this may take a while)...\n" );
// Create a custom TextWriter that filters symbol messages
// NOTE: For debugging symbol loading issues, it's better to see all messages
// So we only filter when NOT in verbose mode AND user hasn't explicitly requested symbol info
TextWriter? originalOut = null;
SymbolFilterWriter? symbolFilter = null;
// Only filter if not verbose - this allows seeing symbol loading messages during debugging
if ( !verbose )
{
originalOut = Console.Out;
symbolFilter = new SymbolFilterWriter ( originalOut );
Console.SetOut ( symbolFilter );
}
try
{
// Try to use OpenOrConvert with options if available
TraceLog? traceLog = null;
try
{
var openMethod = typeof ( TraceLog ).GetMethod ( "OpenOrConvert",
new[] { typeof ( string ), typeof ( TraceLogOptions ) } );
if ( openMethod != null && symbolPathSet )
{
if ( verbose )
{
Console.WriteLine ( "Attempting to use OpenOrConvert with TraceLogOptions..." );
}
// Create TraceLogOptions with symbol path
var optionsType = typeof ( TraceLogOptions );
var options = Activator.CreateInstance ( optionsType )
?? throw new InvalidOperationException ( "Failed to create TraceLogOptions instance." );
var symbolReaderOptionsProp = optionsType.GetProperty ( "SymbolReaderOptions",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );
if ( symbolReaderOptionsProp != null )
{
var symbolReaderOptionsType = symbolReaderOptionsProp.PropertyType;
var symbolReaderOptions = Activator.CreateInstance ( symbolReaderOptionsType );
if ( symbolReaderOptions != null )
{
var envSymbolPath = Environment.GetEnvironmentVariable ( "_NT_SYMBOL_PATH" );
var symbolPathProp = symbolReaderOptionsType.GetProperty ( "SymbolPath",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );
if ( symbolPathProp != null && envSymbolPath != null )
{
symbolPathProp.SetValue ( symbolReaderOptions, envSymbolPath );
}
symbolReaderOptionsProp.SetValue ( options, symbolReaderOptions );
}
}
traceLog = ( TraceLog? ) openMethod.Invoke ( null, new object[] { etlPath, options } );
if ( verbose && traceLog != null )
{
Console.WriteLine ( " ✓ Opened TraceLog with TraceLogOptions" );
}
}
}
catch ( Exception ex )
{
if ( verbose )
{
Console.WriteLine ( $" Could not use OpenOrConvert with options: {ex.Message}" );
}
}
// Fallback to standard OpenOrConvert
if ( traceLog == null )
{
traceLog = TraceLog.OpenOrConvert ( etlPath );
}
using ( traceLog )
{
// Implement PerfView's "Warm Symbol Lookup" algorithm
// Step 1: Analyze modules by iterating through call stacks to find "hot" modules
if ( verbose )
{
Console.WriteLine ( "\n=== Starting Warm Symbol Lookup (PerfView algorithm) ===" );
}
try
{
// Step 1: Collect module metrics from call stacks
var moduleMetrics = new Dictionary<string, long>();
long totalSamples = 0;
if ( verbose )
{
Console.WriteLine ( "Step 1: Analyzing call stacks to find hot modules..." );
}
// Iterate through all call stacks to count module usage
int stackCount = 0;
foreach ( var callStack in traceLog.CallStacks )
{
if ( callStack == null )
{
continue;
}
stackCount++;
totalSamples++;
// Walk up the call stack
var frame = callStack;
var modulesSeenOnStack = new HashSet<string>();
while ( frame != null )
{
if ( frame.CodeAddress != null )
{
var module = frame.CodeAddress.ModuleFile;
if ( module != null )
{
string moduleName = Path.GetFileNameWithoutExtension ( module.Name ?? "" );
if ( !string.IsNullOrEmpty ( moduleName ) && !modulesSeenOnStack.Contains ( moduleName ) )
{
modulesSeenOnStack.Add ( moduleName );
if ( !moduleMetrics.ContainsKey ( moduleName ) )
{
moduleMetrics[moduleName] = 0;
}
moduleMetrics[moduleName]++;
}
}
}
frame = frame.Caller;
}
if ( stackCount > 10000 )
{
break; // Limit for performance
}
}
if ( verbose )
{
Console.WriteLine ( $" Analyzed {stackCount} call stacks, found {moduleMetrics.Count} unique modules" );
}
// Step 2: Filter modules with >2% metric (PerfView threshold)
var modulesToLookup = new List< ( string name, double percent ) >();
foreach ( var kvp in moduleMetrics )
{
double percent = totalSamples > 0
? ( kvp.Value * 100.0 ) / totalSamples
: 0;
if ( percent > 2.0 ) // PerfView uses 2% threshold
{
modulesToLookup.Add ( ( kvp.Key, percent ) );
}
}
modulesToLookup = modulesToLookup.OrderByDescending ( m => m.percent ).ToList();
if ( verbose )
{
Console.WriteLine ( $"\nStep 2: Found {modulesToLookup.Count} modules with >2% metric:" );
foreach ( var ( name, percent ) in modulesToLookup.Take ( 10 ) )
{
// Try to get module file size
TraceModuleFile? moduleFile = null;
foreach ( var mf in traceLog.ModuleFiles )
{
if ( Path.GetFileNameWithoutExtension ( mf.Name ?? "" ) == name )
{
moduleFile = mf;
break;
}
}
string sizeInfo = "";
if ( moduleFile != null )
{
try
{
// Try to get PDB size
double pdbSizeMB = GetModulePdbSizeMB ( moduleFile, null );
if ( pdbSizeMB > 0.01 )
{
sizeInfo = $" (~{pdbSizeMB:F1} MB)";
}
}
catch
{
// Ignore
}
}
Console.WriteLine ( $" {name}: {percent:F1}%{sizeInfo}" );
}
}
// Step 3: Call LookupSymbolsForModule for each hot module
if ( modulesToLookup.Count > 0 )
{
if ( verbose )
{
Console.WriteLine ( "\nStep 3: Loading symbols for hot modules..." );
}
// Create SymbolReader (as shown in PerfView source code)
// SymbolReader constructor: SymbolReader(TextWriter log, string nt_symbol_path = null)
// Try to create SymbolReader using reflection since it might not be directly accessible
object? symbolReader = null;
try
{
var envSymbolPath = Environment.GetEnvironmentVariable ( "_NT_SYMBOL_PATH" );
if ( verbose )
{
Console.WriteLine ( $" Creating SymbolReader with path: {envSymbolPath}" );
}
// Try to find SymbolReader type
Type? symbolReaderType = null;
// Method 1: Try to load from fully qualified name
try
{
symbolReaderType = Type.GetType ( "Microsoft.Diagnostics.Symbols.SymbolReader, Microsoft.Diagnostics.Tracing.TraceEvent" );
if ( verbose && symbolReaderType != null )
{
Console.WriteLine ( $" Found SymbolReader via Type.GetType: {symbolReaderType.FullName}" );
}
}
catch ( Exception ex )
{
if ( verbose )
{
Console.WriteLine ( $" Type.GetType failed: {ex.Message}" );
}
}
// Method 2: Search in all loaded assemblies
if ( symbolReaderType == null )
{
foreach ( var assembly in AppDomain.CurrentDomain.GetAssemblies() )
{
try
{
symbolReaderType = assembly.GetType ( "Microsoft.Diagnostics.Symbols.SymbolReader" );
if ( symbolReaderType != null )
{
if ( verbose )
{
Console.WriteLine ( $" Found SymbolReader in assembly: {assembly.FullName}" );
}
break;
}
}
catch
{
// Ignore
}
}
}
// Method 3: Try to load TraceEvent assembly explicitly
if ( symbolReaderType == null )
{
try
{
var traceEventAssembly = System.Reflection.Assembly.LoadFrom (
Path.Combine ( AppDomain.CurrentDomain.BaseDirectory, "Microsoft.Diagnostics.Tracing.TraceEvent.dll" ) );
symbolReaderType = traceEventAssembly.GetType ( "Microsoft.Diagnostics.Symbols.SymbolReader" );
if ( verbose && symbolReaderType != null )
{
Console.WriteLine ( $" Found SymbolReader by loading assembly explicitly" );
}
}
catch ( Exception ex )
{
if ( verbose )
{
Console.WriteLine ( $" Failed to load assembly explicitly: {ex.Message}" );
}
}
}
if ( symbolReaderType != null )
{
// Create a StringWriter to capture symbol loading messages
var symbolLog = new StringWriter();
// List all available constructors
var constructors = symbolReaderType.GetConstructors();
if ( verbose )
{
Console.WriteLine ( $" Found {constructors.Length} constructors:" );
foreach ( var ctor in constructors )
{
var paramTypes = ctor.GetParameters().Select ( p => $"{p.ParameterType.Name} {p.Name}" ).ToArray();
Console.WriteLine ( $" - SymbolReader({string.Join(", ", paramTypes)})" );
}
}
// Try constructor: SymbolReader(TextWriter log, string nt_symbol_path = null, DelegatingHandler httpClientDelegatingHandler = null)
// First try with TextWriter and string
var constructor = symbolReaderType.GetConstructor (
new[] { typeof ( TextWriter ), typeof ( string ) } );
if ( constructor != null )
{
try
{
symbolReader = constructor.Invoke ( new object[] { symbolLog, envSymbolPath ?? "" } );
if ( verbose )
{
Console.WriteLine ( $" ✓ SymbolReader created: {symbolReader.GetType().FullName}" );
}
}
catch ( Exception ex )
{
if ( verbose )
{
Console.WriteLine ( $" ✗ Constructor failed: {ex.Message}" );
Console.WriteLine ( $" Inner exception: {ex.InnerException?.Message}" );
}
}
}
// If that failed, try with just TextWriter
if ( symbolReader == null )
{
constructor = symbolReaderType.GetConstructor ( new[] { typeof ( TextWriter ) } );
if ( constructor != null )
{
try
{
symbolReader = constructor.Invoke ( new object[] { symbolLog } );
// Try to set SymbolPath property
var symbolPathProp = symbolReaderType.GetProperty ( "SymbolPath" );
if ( symbolPathProp != null && envSymbolPath != null )
{
symbolPathProp.SetValue ( symbolReader, envSymbolPath );
}
if ( verbose )
{
Console.WriteLine ( $" ✓ SymbolReader created (with TextWriter only)" );
}
}
catch ( Exception ex )
{
if ( verbose )
{
Console.WriteLine ( $" ✗ Constructor with TextWriter only failed: {ex.Message}" );
Console.WriteLine ( $" Inner exception: {ex.InnerException?.Message}" );
}
}
}
}
// If still failed, try with all three parameters (passing null for DelegatingHandler)
if ( symbolReader == null )
{
constructor = symbolReaderType.GetConstructor (
new[] { typeof ( TextWriter ), typeof ( string ), typeof ( System.Net.Http.DelegatingHandler ) } );
if ( constructor != null )
{
try
{
System.Net.Http.DelegatingHandler? httpHandler = null;
symbolReader = constructor.Invoke ( new object?[] { symbolLog, envSymbolPath ?? "", httpHandler } );
if ( verbose )
{
Console.WriteLine ( $" ✓ SymbolReader created (with all parameters)" );
}
}
catch ( Exception ex )
{
if ( verbose )
{
Console.WriteLine ( $" ✗ Constructor with all parameters failed: {ex.Message}" );
Console.WriteLine ( $" Inner exception: {ex.InnerException?.Message}" );
}
}
}
}
}
else
{
if ( verbose )
{
Console.WriteLine ( " ⚠ SymbolReader type not found" );
Console.WriteLine ( " Searching for alternative symbol loading methods..." );
// List all types in TraceEvent assembly that contain "Symbol"
try
{
var traceEventAssembly = System.Reflection.Assembly.LoadFrom (
Path.Combine ( AppDomain.CurrentDomain.BaseDirectory, "Microsoft.Diagnostics.Tracing.TraceEvent.dll" ) );
var symbolTypes = traceEventAssembly.GetTypes()
.Where ( t => t.Name.Contains ( "Symbol" ) && t.IsPublic )
.Take ( 10 )
.ToList();
if ( symbolTypes.Count > 0 )
{
Console.WriteLine ( $" Found {symbolTypes.Count} symbol-related types:" );
foreach ( var t in symbolTypes )
{
Console.WriteLine ( $" - {t.FullName}" );
}
}
}
catch ( Exception ex )
{
Console.WriteLine ( $" Could not list types: {ex.Message}" );
}
}
}
}
catch ( Exception ex )
{
if ( verbose )
{
Console.WriteLine ( $" ✗ Failed to create SymbolReader: {ex.Message}" );
}
}
if ( symbolReader != null )
{
// Get CodeAddresses collection
var codeAddressesType = traceLog.CodeAddresses.GetType();
// Get all LookupSymbolsForModule methods (there might be multiple overloads)
var allLookupMethods = codeAddressesType.GetMethods (
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance )
.Where ( m => m.Name == "LookupSymbolsForModule" )
.ToList();
if ( verbose )
{
Console.WriteLine ( $" Found {allLookupMethods.Count} LookupSymbolsForModule overloads:" );
foreach ( var m in allLookupMethods )
{
var paramTypes = m.GetParameters().Select ( p => p.ParameterType.Name ).ToArray();
Console.WriteLine ( $" - LookupSymbolsForModule({string.Join(", ", paramTypes)})" );
}
}
if ( allLookupMethods.Count > 0 )
{
// Try method with string parameter first (simpler)
var lookupByNameMethod = allLookupMethods.FirstOrDefault ( m =>
{
var parameters = m.GetParameters();
return parameters.Length == 1 && parameters[0].ParameterType == typeof ( string );
} );
if ( lookupByNameMethod != null )
{
if ( verbose )
{
Console.WriteLine ( " Using LookupSymbolsForModule(string) method" );
}
foreach ( var ( moduleName, percent ) in modulesToLookup )
{
if ( verbose )
{
Console.Write ( $" Loading symbols for {moduleName} ({percent:F1}%)... " );
}
// Get initial cache size
double initialSizeMB = GetSymbolCacheSizeMB ( Environment.GetEnvironmentVariable ( "_NT_SYMBOL_PATH" ) );
// Start progress indicator in background with size tracking
var progressToken = new CancellationTokenSource();
var progressTask = Task.Run ( () =>
{
ShowProgressBarWithUpdate ( progressToken.Token, () =>
{
double currentMB = GetSymbolCacheSizeMB ( Environment.GetEnvironmentVariable ( "_NT_SYMBOL_PATH" ) );
return Math.Max ( 0, currentMB - initialSizeMB );
} );
} );
try
{
// Wrap the symbol lookup in a task
var lookupTask = Task.Run ( () =>
{
lookupByNameMethod.Invoke ( traceLog.CodeAddresses, new object[] { moduleName } );
} );
// Wait for completion with smart timeout (skip only if MB not growing)
bool completed = WaitWithProgressCheck ( lookupTask, timeoutSeconds, initialSizeMB, progressToken, maxSizeMB, moduleName, out string? skipReason );
// Stop progress indicator
progressToken.Cancel();
progressTask.Wait ( 1000 );
if ( !completed )
{
// Module was skipped - show reason
Console.Write ( "\r" + new string ( ' ', Console.WindowWidth - 1 ) + "\r" );
Console.WriteLine ( $" ⏱ Skipped {moduleName} ({skipReason ?? "unknown reason"})" );
continue; // Skip to next module
}
// Get final cache size
double finalSizeMB = GetSymbolCacheSizeMB ( Environment.GetEnvironmentVariable ( "_NT_SYMBOL_PATH" ) );
double loadedMB = Math.Max ( 0, finalSizeMB - initialSizeMB );
if ( verbose )
{
// Clear progress bar and show success
Console.Write ( "\r" + new string ( ' ', Console.WindowWidth - 1 ) + "\r" );
if ( loadedMB > 0.01 )
{
Console.WriteLine ( $" ✓ Symbols loaded for {moduleName} ({loadedMB:F2} MB)" );
}
else
{
Console.WriteLine ( $" ✓ Symbols loaded for {moduleName}" );
}
}
}
catch ( Exception ex )
{
progressToken.Cancel();
progressTask.Wait ( 1000 );
if ( verbose )
{
Console.Write ( "\r" + new string ( ' ', Console.WindowWidth - 1 ) + "\r" );
Console.WriteLine ( $" ✗ Failed to load symbols for {moduleName}: {ex.Message}" );
}
}
}
}
// Try method with SymbolReader and TraceModuleFile
else
{
var lookupWithSymbolReaderMethod = allLookupMethods.FirstOrDefault ( m =>
{
var parameters = m.GetParameters();
if ( parameters.Length == 2 )
{
// Check if first parameter is SymbolReader or compatible type
var firstParamType = parameters[0].ParameterType;
var symbolReaderType = symbolReader.GetType();
return ( firstParamType == symbolReaderType ||
firstParamType.IsAssignableFrom ( symbolReaderType ) ||
symbolReaderType.IsAssignableFrom ( firstParamType ) ) &&
parameters[1].ParameterType == typeof ( TraceModuleFile );
}
return false;
} );
if ( lookupWithSymbolReaderMethod != null )
{
if ( verbose )
{
Console.WriteLine ( " Using LookupSymbolsForModule(SymbolReader, TraceModuleFile) method" );
}
foreach ( var ( moduleName, percent ) in modulesToLookup )
{
try
{
// Find module file
TraceModuleFile? moduleFile = null;
foreach ( var mf in traceLog.ModuleFiles )
{
if ( Path.GetFileNameWithoutExtension ( mf.Name ?? "" ) == moduleName )
{
moduleFile = mf;
break;
}
}
if ( moduleFile != null )
{
if ( verbose )
{
Console.Write ( $" Loading symbols for {moduleName} ({percent:F1}%)... " );
}
// Get initial cache size and PDB size
double initialSizeMB = GetSymbolCacheSizeMB ( Environment.GetEnvironmentVariable ( "_NT_SYMBOL_PATH" ) );
double modulePdbSizeMB = GetModulePdbSizeMB ( moduleFile, symbolReader );
// Start progress indicator in background with size tracking
var progressToken = new System.Threading.CancellationTokenSource();
var progressTask = Task.Run ( () =>
{
ShowProgressBarWithUpdate ( progressToken.Token, () =>
{
double currentMB = GetSymbolCacheSizeMB ( Environment.GetEnvironmentVariable ( "_NT_SYMBOL_PATH" ) );
double loadedMB = Math.Max ( 0, currentMB - initialSizeMB );
// Если знаем размер PDB, показываем прогресс
return modulePdbSizeMB > 0 ? Math.Min ( loadedMB, modulePdbSizeMB ) : loadedMB;
} );
} );
try
{
// Wrap the symbol lookup in a task
var lookupTask = Task.Run ( () =>
{
lookupWithSymbolReaderMethod.Invoke ( traceLog.CodeAddresses, new object[] { symbolReader, moduleFile } );
} );
// Wait for completion with smart timeout (skip only if MB not growing)
bool completed = WaitWithProgressCheck ( lookupTask, timeoutSeconds, initialSizeMB, progressToken, maxSizeMB, moduleName, out string? skipReason );
// Stop progress indicator
progressToken.Cancel();
progressTask.Wait ( 1000 );
if ( !completed )
{
// Module was skipped - show reason
Console.Write ( "\r" + new string ( ' ', Console.WindowWidth - 1 ) + "\r" );
Console.WriteLine ( $" ⏱ Skipped {moduleName} ({skipReason ?? "unknown reason"})" );
continue; // Skip to next module
}
// Get final cache size
double finalSizeMB = GetSymbolCacheSizeMB ( Environment.GetEnvironmentVariable ( "_NT_SYMBOL_PATH" ) );
double loadedMB = Math.Max ( 0, finalSizeMB - initialSizeMB );
if ( verbose )
{
// Clear progress bar and show success
Console.Write ( "\r" + new string ( ' ', Console.WindowWidth - 1 ) + "\r" );
if ( loadedMB > 0.01 )
{
Console.WriteLine ( $" ✓ Symbols loaded for {moduleName} ({loadedMB:F2} MB)" );
}
else
{