-
Notifications
You must be signed in to change notification settings - Fork 394
Expand file tree
/
Copy pathSOSRunner.cs
More file actions
1859 lines (1691 loc) · 73.6 KB
/
SOSRunner.cs
File metadata and controls
1859 lines (1691 loc) · 73.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Diagnostics.TestHelpers;
using Xunit.Abstractions;
using Xunit.Extensions;
public class SOSRunner : IDisposable
{
/// <summary>
/// What to use to generate the dump
/// </summary>
public enum DumpGenerator
{
NativeDebugger,
CreateDump,
DotNetDump,
}
/// <summary>
/// Dump type
/// </summary>
public enum DumpType
{
Triage,
Mini,
Heap,
Full
}
/// <summary>
/// What action should the debugger do
/// </summary>
public enum DebuggerAction
{
Live,
GenerateDump,
LoadDump,
LoadDumpWithDotNetDump,
}
/// <summary>
/// Which debugger to use
/// </summary>
public enum NativeDebugger
{
Unknown,
Cdb,
Lldb,
Gdb,
DotNetDump,
}
/// <summary>
/// SOS test runner config information
/// </summary>
public class TestInformation
{
private string _testName;
private bool _testLive = true;
private bool _testDump = true;
private bool _testCrashReport = true;
private DumpGenerator _dumpGenerator = DumpGenerator.CreateDump;
private DumpType _dumpType = DumpType.Heap;
private string _debuggeeDumpOutputRootDir;
private string _debuggeeDumpInputRootDir;
public TestConfiguration TestConfiguration { get; set; }
public ITestOutputHelper OutputHelper { get; set; }
public bool TestLive
{
// Don't test single file on Alpine. lldb 10.0 can't launch them.
get { return _testLive && !(TestConfiguration.PublishSingleFile && OS.IsAlpine); }
set { _testLive = value; }
}
public bool TestDump
{
get
{
return _testDump &&
// Only single file dumps on Windows
(!TestConfiguration.PublishSingleFile || OS.Kind == OSKind.Windows) &&
// Generate and test dumps if on OSX or Alpine only if the runtime is 6.0 or greater
(!(OS.Kind == OSKind.OSX || OS.IsAlpine) || TestConfiguration.RuntimeFrameworkVersionMajor > 5);
}
set { _testDump = value; }
}
public string TestName
{
get { return _testName ?? "SOS." + DebuggeeName; }
set { _testName = value; }
}
public string DebuggeeName { get; set; }
public string DebuggeeArguments { get; set; }
public DumpGenerator DumpGenerator
{
get
{
DumpGenerator dumpGeneration = _dumpGenerator;
if (dumpGeneration == DumpGenerator.CreateDump)
{
if (!TestConfiguration.CreateDumpExists ||
TestConfiguration.PublishSingleFile ||
TestConfiguration.GenerateDumpWithLLDB() ||
TestConfiguration.GenerateDumpWithGDB())
{
dumpGeneration = DumpGenerator.NativeDebugger;
}
}
return dumpGeneration;
}
set { _dumpGenerator = value; }
}
public DumpType DumpType
{
get
{
// Currently neither cdb or dotnet-dump collect generates valid dumps on Windows for an single file app
// Issue: https://github.com/dotnet/diagnostics/issues/2515
return TestConfiguration.PublishSingleFile ? SOSRunner.DumpType.Full : _dumpType;
}
set { _dumpType = value; }
}
public bool UsePipeSync { get; set; }
public bool DumpDiagnostics { get; set; } = true;
public string DumpNameSuffix { get; set; }
public bool EnableSOSLogging { get; set; } = true;
public bool TestCrashReport
{
get { return _testCrashReport && DumpGenerator == DumpGenerator.CreateDump && OS.Kind != OSKind.Windows && TestConfiguration.RuntimeFrameworkVersionMajor >= 6; }
set { _testCrashReport = value; }
}
public string DebuggeeDumpOutputRootDir
{
get { return _debuggeeDumpOutputRootDir ?? TestConfiguration.DebuggeeDumpOutputRootDir(); }
set { _debuggeeDumpOutputRootDir = value; }
}
public string DebuggeeDumpInputRootDir
{
get { return _debuggeeDumpInputRootDir ?? TestConfiguration.DebuggeeDumpInputRootDir(); }
set { _debuggeeDumpInputRootDir = value; }
}
public bool IsValid()
{
return TestConfiguration != null && OutputHelper != null && DebuggeeName != null;
}
}
public const string HexValueRegEx = "[A-Fa-f0-9]+(`[A-Fa-f0-9]+)?";
public const string DecValueRegEx = "[,0-9]+(`[,0-9]+)?";
public NativeDebugger Debugger { get; private set; }
public string DebuggerToString
{
get { return Debugger.ToString().ToUpperInvariant(); }
}
private readonly TestConfiguration _config;
private readonly TestRunner.OutputHelper _outputHelper;
private readonly Dictionary<string, string> _variables;
private readonly ScriptLogger _scriptLogger;
private readonly ProcessRunner _processRunner;
private readonly DumpType? _dumpType;
private string _lastCommandOutput;
private string _previousCommandCapture;
private SOSRunner(NativeDebugger debugger, TestConfiguration config, TestRunner.OutputHelper outputHelper, Dictionary<string, string> variables,
ScriptLogger scriptLogger, ProcessRunner processRunner, DumpType? dumpType)
{
Debugger = debugger;
_config = config;
_outputHelper = outputHelper;
_variables = variables;
_scriptLogger = scriptLogger;
_processRunner = processRunner;
_dumpType = dumpType;
}
/// <summary>
/// Run a debuggee and create a dump.
/// </summary>
/// <param name="information">test info</param>
/// <returns>full dump name</returns>
public static async Task<string> CreateDump(TestInformation information)
{
if (!information.IsValid())
{
throw new ArgumentException("Invalid TestInformation");
}
TestConfiguration config = information.TestConfiguration;
DumpGenerator dumpGeneration = information.DumpGenerator;
string dumpName = null;
Directory.CreateDirectory(information.DebuggeeDumpOutputRootDir);
if (dumpGeneration == DumpGenerator.NativeDebugger)
{
using SOSRunner runner = await SOSRunner.StartDebugger(information, DebuggerAction.GenerateDump);
dumpName = runner.ReplaceVariables("%DUMP_NAME%");
try
{
await runner.LoadSosExtension();
string command = null;
switch (runner.Debugger)
{
case SOSRunner.NativeDebugger.Cdb:
await runner.ContinueExecution();
switch (information.DumpType)
{
case DumpType.Mini:
command = ".dump /o /m %DUMP_NAME%";
break;
case DumpType.Heap:
command = ".dump /o /mw %DUMP_NAME%";
break;
case DumpType.Triage:
command = ".dump /o /mshuRp %DUMP_NAME%";
break;
case DumpType.Full:
command = ".dump /o /ma %DUMP_NAME%";
break;
}
break;
case SOSRunner.NativeDebugger.Gdb:
command = "generate-core-file %DUMP_NAME%";
break;
default:
throw new Exception(runner.Debugger.ToString() + " does not support creating dumps");
}
await runner.RunCommand(command);
}
catch (Exception ex)
{
runner.WriteLine(ex.ToString());
throw;
}
finally
{
await runner.QuitDebugger();
}
}
else
{
TestRunner.OutputHelper outputHelper = null;
NamedPipeServerStream pipeServer = null;
string pipeName = null;
try
{
// Setup the logging from the options in the config file
outputHelper = TestRunner.ConfigureLogging(config, information.OutputHelper, information.TestName);
// Restore and build the debuggee. The debuggee name is lower cased because the
// source directory name has been lowercased by the build system.
DebuggeeConfiguration debuggeeConfig = await DebuggeeCompiler.Execute(config, information.DebuggeeName, outputHelper);
Dictionary<string, string> variables = GenerateVariables(information, debuggeeConfig, DebuggerAction.GenerateDump);
dumpName = ReplaceVariables(variables, "%DUMP_NAME%");
outputHelper.WriteLine("Starting {0}", information.TestName);
outputHelper.WriteLine("{");
// Get the full debuggee launch command line (includes the host if required)
string exePath = debuggeeConfig.BinaryExePath;
StringBuilder arguments = new();
if (!string.IsNullOrWhiteSpace(config.HostExe))
{
exePath = config.HostExe;
if (!string.IsNullOrWhiteSpace(config.HostArgs))
{
arguments.Append(config.HostArgs);
arguments.Append(' ');
}
arguments.Append(debuggeeConfig.BinaryExePath);
}
// Setup a pipe server for the debuggee to connect to sync when to take a dump
if (information.UsePipeSync)
{
int runnerId = Process.GetCurrentProcess().Id;
pipeName = $"SOSRunner.{runnerId}.{information.DebuggeeName}";
pipeServer = new NamedPipeServerStream(pipeName);
arguments.Append(' ');
arguments.Append(pipeName);
}
// Add any additional test specific arguments after the pipe name (if one).
if (!string.IsNullOrWhiteSpace(information.DebuggeeArguments))
{
arguments.Append(' ');
arguments.Append(information.DebuggeeArguments);
}
// Create the debuggee process runner
ProcessRunner processRunner = new ProcessRunner(exePath, ReplaceVariables(variables, arguments.ToString())).
WithEnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0").
WithEnvironmentVariable("DOTNET_ROOT", config.DotNetRoot).
WithRuntimeConfiguration("DbgEnableElfDumpOnMacOS", "1").
WithLog(new TestRunner.TestLogger(outputHelper.IndentedOutput)).
WithTimeout(TimeSpan.FromMinutes(10));
if (dumpGeneration == DumpGenerator.CreateDump)
{
// Run the debuggee with the createdump environment variables set to generate a coredump on unhandled exception
processRunner.
WithRuntimeConfiguration("DbgEnableMiniDump", "1").
WithRuntimeConfiguration("DbgMiniDumpName", dumpName);
if (information.DumpDiagnostics)
{
processRunner.WithRuntimeConfiguration("CreateDumpDiagnostics", "1");
}
if (information.TestCrashReport)
{
processRunner.WithRuntimeConfiguration("EnableCrashReport", "1");
}
// Windows createdump's triage MiniDumpWriteDump flags for .NET 5.0 are broken
// Disable testing triage dumps on 6.0 until the DAC signing issue is resolved - issue https://github.com/dotnet/diagnostics/issues/2542
// if (OS.Kind == OSKind.Windows && dumpType == DumpType.Triage && config.IsNETCore && config.RuntimeFrameworkVersionMajor < 6)
DumpType dumpType = information.DumpType;
if (OS.Kind == OSKind.Windows && dumpType == DumpType.Triage)
{
dumpType = DumpType.Heap;
}
switch (dumpType)
{
case DumpType.Mini:
processRunner.WithRuntimeConfiguration("DbgMiniDumpType", "1");
break;
case DumpType.Heap:
processRunner.WithRuntimeConfiguration("DbgMiniDumpType", "2");
break;
case DumpType.Triage:
processRunner.WithRuntimeConfiguration("DbgMiniDumpType", "3");
break;
case DumpType.Full:
processRunner.WithRuntimeConfiguration("DbgMiniDumpType", "4");
break;
}
}
// Start the debuggee
processRunner.Start();
if (dumpGeneration == DumpGenerator.DotNetDump)
{
ITestOutputHelper dotnetDumpOutputHelper = new IndentedTestOutputHelper(outputHelper, " ");
try
{
if (string.IsNullOrWhiteSpace(config.DotNetDumpHost()) || string.IsNullOrWhiteSpace(config.DotNetDumpPath()))
{
throw new SkipTestException("dotnet-dump collect needs DotNetDumpHost and DotNetDumpPath config variables");
}
// Wait until the debuggee gets started. It needs time to spin up before generating the core dump.
if (pipeServer != null)
{
dotnetDumpOutputHelper.WriteLine("Waiting for connection on pipe {0}", pipeName);
using CancellationTokenSource source = new(TimeSpan.FromMinutes(5));
// Wait for debuggee to connect/write to pipe or if the process exits on some other failure/abnormally
// TODO: This is a resiliency issue - we'll try to collect the dump even if the debuggee fails to connect.
await Task.WhenAny(pipeServer.WaitForConnectionAsync(source.Token), processRunner.WaitForExit());
}
// Start dotnet-dump collect
DumpType dumpType = information.DumpType;
if (config.IsDesktop || config.RuntimeFrameworkVersionMajor < 6)
{
dumpType = DumpType.Full;
}
StringBuilder dotnetDumpArguments = new();
dotnetDumpArguments.Append(config.DotNetDumpPath());
dotnetDumpArguments.AppendFormat($" collect --process-id {processRunner.ProcessId} --output {dumpName} --type {dumpType}");
if (information.DumpDiagnostics)
{
dotnetDumpArguments.Append(" --diag");
}
ProcessRunner dotnetDumpRunner = new ProcessRunner(config.DotNetDumpHost(), ReplaceVariables(variables, dotnetDumpArguments.ToString())).
WithLog(new TestRunner.TestLogger(dotnetDumpOutputHelper)).
WithTimeout(TimeSpan.FromMinutes(10)).
WithExpectedExitCode(0);
dotnetDumpRunner.Start();
// Wait until dotnet-dump collect finishes generating the dump
await dotnetDumpRunner.WaitForExit();
}
catch (Exception ex)
{
// Log the exception
dotnetDumpOutputHelper.WriteLine(ex.ToString());
}
finally
{
dotnetDumpOutputHelper.WriteLine("}");
// Shutdown the debuggee
processRunner.Kill();
}
}
// Wait for the debuggee to finish
await processRunner.WaitForExit();
}
catch (Exception ex)
{
// Log the exception
outputHelper?.WriteLine(ex.ToString());
throw;
}
finally
{
outputHelper?.WriteLine("}");
outputHelper?.Dispose();
pipeServer?.Dispose();
}
}
return dumpName;
}
/// <summary>
/// Start a debuggee under a native debugger returning a sos runner instance.
/// </summary>
/// <param name="information">test info</param>
/// <param name="action">debugger action</param>
/// <returns>sos runner instance</returns>
public static async Task<SOSRunner> StartDebugger(TestInformation information, DebuggerAction action)
{
if (!information.IsValid())
{
throw new ArgumentException("Invalid TestInformation");
}
TestConfiguration config = information.TestConfiguration;
TestRunner.OutputHelper outputHelper = null;
SOSRunner sosRunner = null;
try
{
// Setup the logging from the options in the config file
outputHelper = TestRunner.ConfigureLogging(config, information.OutputHelper, information.TestName);
string sosLogFile = information.EnableSOSLogging ? Path.Combine(config.LogDirPath, $"{information.TestName}.{config.LogSuffix}.soslog") : null;
// Figure out which native debugger to use
NativeDebugger debugger = GetNativeDebuggerToUse(config, action);
// Restore and build the debuggee.
DebuggeeConfiguration debuggeeConfig = await DebuggeeCompiler.Execute(config, information.DebuggeeName, outputHelper);
outputHelper.WriteLine("SOSRunner processing {0}", information.TestName);
outputHelper.WriteLine("{");
Dictionary<string, string> variables = GenerateVariables(information, debuggeeConfig, action);
ScriptLogger scriptLogger = new(outputHelper.IndentedOutput);
// Make sure the dump file exists
if (action is DebuggerAction.LoadDump or DebuggerAction.LoadDumpWithDotNetDump)
{
if (!variables.TryGetValue("%DUMP_NAME%", out string dumpName) || !File.Exists(dumpName))
{
throw new FileNotFoundException($"Dump file does not exist: {dumpName ?? ""}");
}
}
// Get the full debuggee launch command line (includes the host if required)
StringBuilder debuggeeCommandLine = new();
if (!string.IsNullOrWhiteSpace(config.HostExe))
{
debuggeeCommandLine.Append(config.HostExe);
debuggeeCommandLine.Append(' ');
if (!string.IsNullOrWhiteSpace(config.HostArgs))
{
debuggeeCommandLine.Append(config.HostArgs);
debuggeeCommandLine.Append(' ');
}
}
debuggeeCommandLine.Append(debuggeeConfig.BinaryExePath);
if (!string.IsNullOrWhiteSpace(information.DebuggeeArguments))
{
debuggeeCommandLine.Append(' ');
debuggeeCommandLine.Append(information.DebuggeeArguments);
}
// Get the native debugger path
string debuggerPath = GetNativeDebuggerPath(debugger, config);
if (string.IsNullOrWhiteSpace(debuggerPath) || !File.Exists(debuggerPath))
{
throw new FileNotFoundException($"Native debugger ({debugger}) path not set or does not exist: {debuggerPath}");
}
// Get the debugger arguments and commands to run initially
List<string> initialCommands = new();
StringBuilder arguments = new();
switch (debugger)
{
case NativeDebugger.Cdb:
string helperExtension = config.CDBHelperExtension();
if (string.IsNullOrWhiteSpace(helperExtension) || !File.Exists(helperExtension))
{
throw new ArgumentException($"CDB helper script path not set or does not exist: {helperExtension}");
}
// Clear the default sympath (which puts a sym cache in the debugger binary directory in
// the .nuget cache) and set to just the directory containing the debuggee binaries.
arguments.AppendFormat(@" -y ""{0}""", debuggeeConfig.BinaryDirPath);
arguments.AppendFormat(@" -c "".load {0}""", helperExtension);
if (action == DebuggerAction.LoadDump)
{
arguments.Append(" -z %DUMP_NAME%");
}
else
{
arguments.AppendFormat(" -Gsins {0}", debuggeeCommandLine);
// disable stopping on integer divide-by-zero and integer overflow exceptions
initialCommands.Add("sxd dz");
initialCommands.Add("sxd iov");
}
initialCommands.Add(".extpath " + Path.GetDirectoryName(config.SOSPath()));
// Add the path to runtime so cdb/SOS can find DAC/DBI for triage dumps
if (information.DumpType == DumpType.Triage)
{
string runtimeSymbolsPath = config.RuntimeSymbolsPath;
if (runtimeSymbolsPath != null)
{
initialCommands.Add(".sympath+ " + runtimeSymbolsPath);
}
}
// Turn off warnings that can happen in the middle of a command's output
initialCommands.Add(".outmask- 0x244");
initialCommands.Add("!sym quiet");
// Turn on source/line numbers
initialCommands.Add(".lines");
bool shouldVerifyDacSignature = !config.IsPrivateBuildTesting()
&& !config.IsNightlyBuild()
&& !"-none".Equals(config.SetHostRuntime(), StringComparison.OrdinalIgnoreCase);
initialCommands.Add($"dx @Debugger.Settings.EngineInitialization.SecureLoadDotNetExtensions={(shouldVerifyDacSignature ? "true" : "false")}");
break;
case NativeDebugger.Lldb:
// Get the lldb python script file path necessary to capture the output of commands
// by printing a prompt after all the command output is printed.
string lldbHelperScript = config.LLDBHelperScript();
if (string.IsNullOrWhiteSpace(lldbHelperScript) || !File.Exists(lldbHelperScript))
{
throw new ArgumentException("LLDB helper script path not set or does not exist: " + lldbHelperScript);
}
arguments.Append(@"--no-lldbinit -o ""settings set target.disable-aslr false"" -o ""settings set interpreter.prompt-on-quit false""");
arguments.AppendFormat(@" -o ""command script import {0}"" -o ""version""", lldbHelperScript);
string debuggeeTarget = config.HostExe;
if (string.IsNullOrWhiteSpace(debuggeeTarget))
{
debuggeeTarget = debuggeeConfig.BinaryExePath;
}
// Load the dump or launch the debuggee process
if (action == DebuggerAction.LoadDump)
{
initialCommands.Add($@"target create --core ""%DUMP_NAME%"" ""{debuggeeTarget}""");
}
else
{
StringBuilder sb = new();
if (!string.IsNullOrWhiteSpace(config.HostArgs))
{
string[] args = ReplaceVariables(variables, config.HostArgs).Trim().Split(' ');
foreach (string arg in args)
{
sb.AppendFormat(@" ""{0}""", arg);
}
}
if (!string.IsNullOrWhiteSpace(config.HostExe))
{
sb.AppendFormat(@" ""{0}""", debuggeeConfig.BinaryExePath);
}
if (!string.IsNullOrWhiteSpace(information.DebuggeeArguments))
{
string[] args = ReplaceVariables(variables, information.DebuggeeArguments).Trim().Split(' ');
foreach (string arg in args)
{
sb.AppendFormat(@" ""{0}""", arg);
}
}
initialCommands.Add($@"target create ""{debuggeeTarget}""");
string targetRunArgs = sb.ToString();
if (!string.IsNullOrWhiteSpace(targetRunArgs))
{
initialCommands.Add($"settings set -- target.run-args {targetRunArgs}");
}
initialCommands.Add("process launch -s");
// .NET Core 1.1 or less don't catch stack overflow and abort so need to catch SIGSEGV
if (config.StackOverflowSIGSEGV)
{
initialCommands.Add("process handle -s true -n true -p true SIGSEGV");
}
else
{
initialCommands.Add("process handle -s false -n false -p true SIGSEGV");
}
initialCommands.Add("process handle -s false -n false -p true SIGFPE");
initialCommands.Add("process handle -s true -n true -p true SIGABRT");
}
break;
case NativeDebugger.Gdb:
if (action is DebuggerAction.LoadDump or DebuggerAction.LoadDumpWithDotNetDump)
{
throw new ArgumentException("GDB not meant for loading core dumps");
}
arguments.Append(@"--init-eval-command=""set prompt <END_COMMAND_OUTPUT>\n""");
arguments.AppendFormat(" --args {0}", debuggeeCommandLine);
// .NET Core 1.1 or less don't catch stack overflow and abort so need to catch SIGSEGV
if (config.StackOverflowSIGSEGV)
{
initialCommands.Add("handle SIGSEGV stop print");
}
else
{
initialCommands.Add("handle SIGSEGV nostop noprint");
}
initialCommands.Add("handle SIGFPE nostop noprint");
initialCommands.Add("handle SIGABRT stop print");
initialCommands.Add("set startup-with-shell off");
initialCommands.Add("set use-coredump-filter on");
initialCommands.Add("run");
break;
case NativeDebugger.DotNetDump:
if (action != DebuggerAction.LoadDumpWithDotNetDump)
{
throw new ArgumentException($"{action} not supported for dotnet-dump testing");
}
if (string.IsNullOrWhiteSpace(config.DotNetDumpHost()))
{
throw new ArgumentException("No DotNetDumpHost in configuration");
}
// Add the path to runtime so dotnet-dump/SOS can find DAC/DBI for triage dumps
if (information.DumpType == DumpType.Triage)
{
string runtimeSymbolsPath = config.RuntimeSymbolsPath;
if (runtimeSymbolsPath != null)
{
initialCommands.Add("setclrpath " + runtimeSymbolsPath);
}
}
initialCommands.Add("setsymbolserver -directory %DEBUG_ROOT%");
shouldVerifyDacSignature = OS.Kind == OSKind.Windows
&& !config.IsPrivateBuildTesting()
&& !config.IsNightlyBuild();
initialCommands.Add($"runtimes --DacSignatureVerification:{(shouldVerifyDacSignature ? "true" : "false")}");
if (config.TestCDAC)
{
initialCommands.Add("runtimes --forceusecdac");
}
arguments.Append(debuggerPath);
arguments.Append(@" analyze %DUMP_NAME%");
debuggerPath = config.DotNetDumpHost();
break;
}
// Create the native debugger process running
ProcessRunner processRunner = new ProcessRunner(debuggerPath, ReplaceVariables(variables, arguments.ToString())).
WithEnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0").
WithEnvironmentVariable("DOTNET_ROOT", config.DotNetRoot).
WithLog(scriptLogger).
WithTimeout(TimeSpan.FromMinutes(10));
if (config.TestCDAC)
{
processRunner.WithEnvironmentVariable("DOTNET_ENABLE_CDAC", "1");
}
// Exit codes on Windows should always be 0, but not on Linux/OSX for the faulting debuggees.
if (OS.Kind == OSKind.Windows)
{
processRunner.WithExpectedExitCode(0);
}
if (sosLogFile != null)
{
processRunner.WithEnvironmentVariable("DOTNET_ENABLED_SOS_LOGGING", sosLogFile);
}
// Disable W^E so that the bpmd command and the tests pass
// Issue: https://github.com/dotnet/diagnostics/issues/3126
processRunner.WithRuntimeConfiguration("EnableWriteXorExecute", "0");
// Setup the extension environment variable
string extensions = config.DotNetDiagnosticExtensions();
if (!string.IsNullOrEmpty(extensions))
{
processRunner.WithEnvironmentVariable("DOTNET_DIAGNOSTIC_EXTENSIONS", extensions);
}
string gcServerMode = config.GetValue("GCServer");
if (!string.IsNullOrEmpty(gcServerMode))
{
processRunner.WithEnvironmentVariable("DOTNET_gcServer", gcServerMode);
}
string gcName = config.GetValue("GCName");
if (!string.IsNullOrEmpty(gcName))
{
processRunner.WithEnvironmentVariable("DOTNET_gcName", gcName);
}
DumpType? dumpType = null;
if (action is DebuggerAction.LoadDump or DebuggerAction.LoadDumpWithDotNetDump)
{
dumpType = information.DumpType;
}
// Create the sos runner instance
sosRunner = new SOSRunner(debugger, config, outputHelper, variables, scriptLogger, processRunner, dumpType);
// Start the native debugger
processRunner.Start();
// Set the coredump_filter flags on the gdb process so the coredump it
// takes of the target process contains everything the tests need.
if (debugger == NativeDebugger.Gdb)
{
initialCommands.Insert(0, string.Format("shell echo 0x3F > /proc/{0}/coredump_filter", processRunner.ProcessId));
}
// Execute the initial debugger commands
await sosRunner.RunCommands(initialCommands);
return sosRunner;
}
catch (Exception ex)
{
// Log the exception
outputHelper?.WriteLine(ex.ToString());
// The runner needs to kill the process and dispose of the file logger
sosRunner?.Dispose();
// The file logging output helper needs to be disposed to close the file
outputHelper?.Dispose();
throw;
}
}
public async Task RunScript(string scriptRelativePath)
{
try
{
string scriptFile = Path.Combine(_config.ScriptRootDir, scriptRelativePath);
if (!File.Exists(scriptFile))
{
throw new FileNotFoundException("Script file does not exist: " + scriptFile);
}
HashSet<string> enabledDefines = GetEnabledDefines();
LogProcessingReproInfo(scriptFile, enabledDefines);
string[] scriptLines = File.ReadAllLines(scriptFile);
Dictionary<string, bool> activeDefines = new();
bool isActiveDefineRegionEnabled = IsActiveDefineRegionEnabled(activeDefines, enabledDefines);
int i = 0;
try
{
for (; i < scriptLines.Length; i++)
{
string line = scriptLines[i].TrimStart();
if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#"))
{
continue;
}
else if (line.StartsWith("IFDEF:"))
{
string define = line.Substring("IFDEF:".Length).Trim();
activeDefines.Add(define, true);
isActiveDefineRegionEnabled = IsActiveDefineRegionEnabled(activeDefines, enabledDefines);
}
else if (line.StartsWith("!IFDEF:"))
{
string define = line.Substring("!IFDEF:".Length).Trim();
activeDefines.Add(define, false);
isActiveDefineRegionEnabled = IsActiveDefineRegionEnabled(activeDefines, enabledDefines);
}
else if (line.StartsWith("ENDIF:"))
{
string define = line.Substring("ENDIF:".Length).Trim();
if (!activeDefines.Last().Key.Equals(define))
{
throw new Exception("Mismatched IFDEF/ENDIF. IFDEF: " + activeDefines.Last().Key + " ENDIF: " + define);
}
activeDefines.Remove(define);
isActiveDefineRegionEnabled = IsActiveDefineRegionEnabled(activeDefines, enabledDefines);
}
else if (!isActiveDefineRegionEnabled)
{
WriteLine(" SKIPPING: {0}", line);
continue;
}
else if (line.StartsWith("LOADSOS"))
{
await LoadSosExtension();
}
else if (line.StartsWith("CONTINUE"))
{
await ContinueExecution();
}
// Adds the "!" prefix under dbgeng, nothing under lldb. Meant for SOS (native) commands.
else if (line.StartsWith("SOSCOMMAND:"))
{
string input = line.Substring("SOSCOMMAND:".Length).TrimStart();
if (!await RunSosCommand(input))
{
throw new Exception($"SOS command FAILED: {input}");
}
}
else if (line.StartsWith("SOSCOMMAND_FAIL:"))
{
string input = line.Substring("SOSCOMMAND_FAIL:".Length).TrimStart();
if (await RunSosCommand(input))
{
// The cdb runcommand extension doesn't get the execute command failures (limitation in dbgeng).
if (Debugger != NativeDebugger.Cdb)
{
throw new Exception($"SOS command did not fail: {input}");
}
}
}
// Adds the "!sos" prefix under dbgeng, "sos " under lldb. Meant for extensions (managed) commands
else if (line.StartsWith("EXTCOMMAND:"))
{
string input = line.Substring("EXTCOMMAND:".Length).TrimStart();
if (!await RunSosCommand(input, extensionCommand: true))
{
throw new Exception($"Extension command FAILED: {input}");
}
}
else if (line.StartsWith("EXTCOMMAND_FAIL:"))
{
string input = line.Substring("EXTCOMMAND_FAIL:".Length).TrimStart();
if (await RunSosCommand(input, extensionCommand: true))
{
// The cdb runcommand extension doesn't get the execute command failures (limitation in dbgeng).
if (Debugger != NativeDebugger.Cdb)
{
throw new Exception($"Extension command did not fail: {input}");
}
}
}
// Never adds any prefix. Meant for native debugger commands.
else if (line.StartsWith("COMMAND:"))
{
string input = line.Substring("COMMAND:".Length).TrimStart();
if (!await RunCommand(input))
{
throw new Exception($"Debugger command FAILED: {input}");
}
}
// Switching threads is debugger specific and can cause issues
// with the runcommand helper.
else if (line.StartsWith("SWITCH_THREAD:"))
{
string input = line.Substring("SWITCH_THREAD:".Length).TrimStart();
await SwitchThread(input);
}
else if (line.StartsWith("COMMAND_FAIL:"))
{
string input = line.Substring("COMMAND_FAIL:".Length).TrimStart();
if (await RunCommand(input))
{
// The cdb runcommand extension doesn't get the execute command failures (limitation in dbgeng).
if (Debugger != NativeDebugger.Cdb)
{
throw new Exception($"Debugger command did not fail: {input}");
}
}
}
else if (line.StartsWith("VERIFY:"))
{
string verifyLine = line.Substring("VERIFY:".Length);
VerifyOutput(verifyLine, match: true);
}
else if (line.StartsWith("!VERIFY:"))
{
string verifyLine = line.Substring("!VERIFY:".Length);
VerifyOutput(verifyLine, match: false);
}
else
{
continue;
}
}
if (activeDefines.Count != 0)
{
throw new Exception("Error unbalanced IFDEFs. " + activeDefines.First().Key + " has no ENDIF.");
}
await QuitDebugger();
}
catch (Exception)
{
WriteLine("SOSRunner error at " + scriptFile + ":" + (i + 1));
WriteLine("Excerpt from " + scriptFile + ":");
for (int j = Math.Max(0, i - 2); j < Math.Min(i + 3, scriptLines.Length); j++)
{
WriteLine((j + 1).ToString().PadLeft(5) + " " + scriptLines[j]);
}
try
{
_scriptLogger.FlushCurrentOutputAsError(_processRunner);
await RunSosCommand("SOSStatus");
}
catch (Exception ex)
{
WriteLine("Exception executing SOSStatus {0}", ex.ToString());
}
throw;
}
}
catch (Exception ex)
{
WriteLine(ex.ToString());
throw;
}
}
public async Task LoadSosExtension()
{
string runtimeSymbolsPath = _config.RuntimeSymbolsPath;
string setHostRuntime = _config.SetHostRuntime();
string setSymbolServer = _config.SetSymbolServer();
string sosPath = _config.SOSPath();
List<string> commands = new();
bool isHostRuntimeNone = false;
if (!string.IsNullOrEmpty(setHostRuntime))
{
switch (setHostRuntime)
{
case "-none":
isHostRuntimeNone = true;
break;
case "-netfx":
case "-netcore":
case "-clear":
break;
default:
setHostRuntime = TestConfiguration.MakeCanonicalPath(setHostRuntime);
break;
}
}
switch (Debugger)
{
case NativeDebugger.Cdb:
if (_config.IsDesktop)
{
// Force the desktop sos to be loaded and then unload it.
if (!string.IsNullOrEmpty(runtimeSymbolsPath))
{
commands.Add($".cordll -lp {runtimeSymbolsPath}");
}
else
{
commands.Add(".cordll -l");