diff --git a/src/Microsoft.Diagnostics.NETCore.Client/DiagnosticsIpc/IpcEndpointConfig.cs b/src/Microsoft.Diagnostics.NETCore.Client/DiagnosticsIpc/IpcEndpointConfig.cs index bf63c928b6..77d8429577 100644 --- a/src/Microsoft.Diagnostics.NETCore.Client/DiagnosticsIpc/IpcEndpointConfig.cs +++ b/src/Microsoft.Diagnostics.NETCore.Client/DiagnosticsIpc/IpcEndpointConfig.cs @@ -133,7 +133,7 @@ public static IpcEndpointConfig Parse(string config) string[] parts = config.Split(','); if (parts.Length > 2) { - throw new FormatException($"Unknow IPC endpoint config format, {config}."); + throw new FormatException($"Unknown IPC endpoint config format, {config}."); } if (string.IsNullOrEmpty(parts[0])) @@ -156,7 +156,7 @@ public static IpcEndpointConfig Parse(string config) } else { - throw new FormatException($"Unknow IPC endpoint config keyword, {parts[1]} in {config}."); + throw new FormatException($"Unknown IPC endpoint config keyword, {parts[1]} in {config}."); } } } diff --git a/src/Tools/Common/Commands/Utils.cs b/src/Tools/Common/CommandUtils.cs similarity index 53% rename from src/Tools/Common/Commands/Utils.cs rename to src/Tools/Common/CommandUtils.cs index 06b739111b..5f597f73aa 100644 --- a/src/Tools/Common/Commands/Utils.cs +++ b/src/Tools/Common/CommandUtils.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Diagnostics; using Microsoft.Diagnostics.NETCore.Client; -using Microsoft.Diagnostics.Tools.Common; +using Microsoft.Diagnostics.Tools; namespace Microsoft.Internal.Common.Utils { @@ -27,15 +27,14 @@ public static int FindProcessIdWithName(string name) { if (commonId != -1) { - Console.WriteLine("There are more than one active processes with the given name: {0}", name); - return -1; + throw new DiagnosticToolException($"There are more than one active processes with the given name: {name}"); } commonId = processesWithMatchingName[i].Id; } } if (commonId == -1) { - Console.WriteLine("There is no active process with the given name: {0}", name); + throw new DiagnosticToolException($"There is no active process with the given name: {name}"); } return commonId; } @@ -61,45 +60,39 @@ public static int LaunchDSRouterProcess(string dsrouterCommand) /// name /// port /// - public static bool ValidateArgumentsForChildProcess(int processId, string name, string port) + public static void ValidateArgumentsForChildProcess(int processId, string name, string port) { if (processId != 0 || name != null || !string.IsNullOrEmpty(port)) { - Console.WriteLine("None of the --name, --process-id, or --diagnostic-port options may be specified when launching a child process."); - return false; + throw new DiagnosticToolException("None of the --name, --process-id, or --diagnostic-port options may be specified when launching a child process."); } - - return true; } /// /// A helper method for validating --process-id, --name options for collect commands and resolving the process ID and name. /// Only one of these options can be specified, so it checks for duplicate options specified and if there is - /// such duplication, it prints the appropriate error message. + /// such duplication, it throws the appropriate DiagnosticToolException error message. /// /// process ID /// name /// resolvedProcessId /// resolvedProcessName /// - public static bool ResolveProcess(int processId, string name, out int resolvedProcessId, out string resolvedProcessName) + public static void ResolveProcess(int processId, string name, out int resolvedProcessId, out string resolvedProcessName) { resolvedProcessId = -1; resolvedProcessName = name; if (processId == 0 && string.IsNullOrEmpty(name)) { - Console.Error.WriteLine("Must specify either --process-id or --name."); - return false; + throw new DiagnosticToolException("Must specify either --process-id or --name."); } else if (processId < 0) { - Console.Error.WriteLine($"{processId} is not a valid process ID"); - return false; + throw new DiagnosticToolException($"{processId} is not a valid process ID"); } else if ((processId != 0) && !string.IsNullOrEmpty(name)) { - Console.Error.WriteLine("Only one of the --name or --process-id options may be specified."); - return false; + throw new DiagnosticToolException("Only one of the --name or --process-id options may be specified."); } try { @@ -116,17 +109,14 @@ public static bool ResolveProcess(int processId, string name, out int resolvedPr } catch (ArgumentException) { - Console.Error.WriteLine($"No process with ID {processId} is currently running."); - return false; + throw new DiagnosticToolException($"No process with ID {processId} is currently running."); } - - return resolvedProcessId != -1; } /// /// A helper method for validating --process-id, --name, --diagnostic-port, --dsrouter options for collect commands and resolving the process ID. /// Only one of these options can be specified, so it checks for duplicate options specified and if there is - /// such duplication, it prints the appropriate error message. + /// such duplication, it throws the appropriate DiagnosticToolException error message. /// /// process ID /// name @@ -134,18 +124,16 @@ public static bool ResolveProcess(int processId, string name, out int resolvedPr /// dsrouter /// resolvedProcessId /// - public static bool ResolveProcessForAttach(int processId, string name, string port, string dsrouter, out int resolvedProcessId) + public static void ResolveProcessForAttach(int processId, string name, string port, string dsrouter, out int resolvedProcessId) { resolvedProcessId = -1; if (processId == 0 && string.IsNullOrEmpty(name) && string.IsNullOrEmpty(port) && string.IsNullOrEmpty(dsrouter)) { - Console.WriteLine("Must specify either --process-id, --name, --diagnostic-port, or --dsrouter."); - return false; + throw new DiagnosticToolException("Must specify either --process-id, --name, --diagnostic-port, or --dsrouter."); } else if (processId < 0) { - Console.WriteLine($"{processId} is not a valid process ID"); - return false; + throw new DiagnosticToolException($"{processId} is not a valid process ID"); } else if ((processId != 0 ? 1 : 0) + (!string.IsNullOrEmpty(name) ? 1 : 0) + @@ -153,122 +141,38 @@ public static bool ResolveProcessForAttach(int processId, string name, string po (!string.IsNullOrEmpty(dsrouter) ? 1 : 0) != 1) { - Console.WriteLine("Only one of the --name, --process-id, --diagnostic-port, or --dsrouter options may be specified."); - return false; + throw new DiagnosticToolException("Only one of the --name, --process-id, --diagnostic-port, or --dsrouter options may be specified."); } // If we got this far it means only one of --name/--diagnostic-port/--process-id/--dsrouter was specified else if (!string.IsNullOrEmpty(port)) { - return true; + return; } // Resolve name option else if (!string.IsNullOrEmpty(name)) { - if ((processId = FindProcessIdWithName(name)) < 0) - { - return false; - } + processId = FindProcessIdWithName(name); } else if (!string.IsNullOrEmpty(dsrouter)) { if (dsrouter != "ios" && dsrouter != "android" && dsrouter != "ios-sim" && dsrouter != "android-emu") { - Console.WriteLine("Invalid value for --dsrouter. Valid values are 'ios', 'ios-sim', 'android' and 'android-emu'."); - return false; + throw new DiagnosticToolException("Invalid value for --dsrouter. Valid values are 'ios', 'ios-sim', 'android' and 'android-emu'."); } if ((processId = LaunchDSRouterProcess(dsrouter)) < 0) { if (processId == -2) { - Console.WriteLine($"Failed to launch dsrouter: {dsrouter}. Make sure that dotnet-dsrouter is not already running. You can connect to an already running dsrouter with -p."); + throw new DiagnosticToolException($"Failed to launch dsrouter: {dsrouter}. Make sure that dotnet-dsrouter is not already running. You can connect to an already running dsrouter with -p.", ReturnCode.TracingError); } else { - Console.WriteLine($"Failed to launch dsrouter: {dsrouter}. Please make sure that dotnet-dsrouter is installed and available in the same directory as dotnet-trace."); - Console.WriteLine("You can install dotnet-dsrouter by running 'dotnet tool install --global dotnet-dsrouter'. More info at https://learn.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-dsrouter"); + throw new DiagnosticToolException($"Failed to launch dsrouter: {dsrouter}. Please make sure that dotnet-dsrouter is installed and available in the same directory as dotnet-trace.\n" + + "You can install dotnet-dsrouter by running 'dotnet tool install --global dotnet-dsrouter'. More info at https://learn.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-dsrouter", ReturnCode.TracingError); } - return false; } } resolvedProcessId = processId; - return true; } } - - internal sealed class LineRewriter - { - public int LineToClear { get; set; } - - private IConsole Console { get; } - - public LineRewriter(IConsole console) - { - Console = console; - } - - // ANSI escape codes: - // [2K => clear current line - // [{LineToClear};0H => move cursor to column 0 of row `LineToClear` - public void RewriteConsoleLine() - { - bool useConsoleFallback = true; - if (!Console.IsInputRedirected) - { - // in case of console input redirection, the control ANSI codes would appear - - // first attempt ANSI Codes - int before = Console.CursorTop; - Console.Out.Write($"\u001b[2K\u001b[{LineToClear};0H"); - int after = Console.CursorTop; - - // Some consoles claim to be VT100 compliant, but don't respect - // all of the ANSI codes, so fallback to the System.Console impl in that case - useConsoleFallback = (before == after); - } - - if (useConsoleFallback) - { - SystemConsoleLineRewriter(); - } - } - - private void SystemConsoleLineRewriter() => Console.SetCursorPosition(0, LineToClear); - - private static bool? _isSetCursorPositionSupported; - public bool IsRewriteConsoleLineSupported - { - get - { - bool isSupported = _isSetCursorPositionSupported ?? EnsureInitialized(); - return isSupported; - - bool EnsureInitialized() - { - try - { - int left = Console.CursorLeft; - int top = Console.CursorTop; - Console.SetCursorPosition(0, LineToClear); - Console.SetCursorPosition(left, top); - _isSetCursorPositionSupported = true; - } - catch - { - _isSetCursorPositionSupported = false; - } - return (bool)_isSetCursorPositionSupported; - } - } - } - } - - internal enum ReturnCode - { - Ok, - SessionCreationError, - TracingError, - ArgumentError, - PlatformNotSupportedError, - UnknownError - } } diff --git a/src/Tools/Common/DefaultConsole.cs b/src/Tools/Common/DefaultConsole.cs index 974c80a21c..41e9556d7f 100644 --- a/src/Tools/Common/DefaultConsole.cs +++ b/src/Tools/Common/DefaultConsole.cs @@ -15,7 +15,7 @@ namespace Microsoft.Diagnostics.Tools.Common internal class DefaultConsole : IConsole { private readonly bool _useAnsi; - public DefaultConsole(bool useAnsi) + public DefaultConsole(bool useAnsi = false) { _useAnsi = useAnsi; } diff --git a/src/Tools/Common/CommandLineErrorException.cs b/src/Tools/Common/DiagnosticToolException.cs similarity index 72% rename from src/Tools/Common/CommandLineErrorException.cs rename to src/Tools/Common/DiagnosticToolException.cs index aa1792e8e9..224582347f 100644 --- a/src/Tools/Common/CommandLineErrorException.cs +++ b/src/Tools/Common/DiagnosticToolException.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using Microsoft.Internal.Common.Utils; namespace Microsoft.Diagnostics.Tools { @@ -16,8 +17,12 @@ namespace Microsoft.Diagnostics.Tools // // For any other error conditions that were unanticipated or do not have // contextualized error messages, don't use this type. - internal sealed class CommandLineErrorException : Exception + internal sealed class DiagnosticToolException : Exception { - public CommandLineErrorException(string errorMessage) : base(errorMessage) { } + public ReturnCode ReturnCode { get; } + public DiagnosticToolException(string errorMessage, ReturnCode returnCode = ReturnCode.ArgumentError ) : base(errorMessage) + { + ReturnCode = returnCode; + } } } diff --git a/src/Tools/Common/LineRewriter.cs b/src/Tools/Common/LineRewriter.cs new file mode 100644 index 0000000000..e42e9b4a71 --- /dev/null +++ b/src/Tools/Common/LineRewriter.cs @@ -0,0 +1,74 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Diagnostics.Tools.Common; + +namespace Microsoft.Internal.Common.Utils +{ + internal sealed class LineRewriter + { + public int LineToClear { get; set; } + + private IConsole Console { get; } + + public LineRewriter(IConsole console) + { + Console = console; + } + + // ANSI escape codes: + // [2K => clear current line + // [{LineToClear};0H => move cursor to column 0 of row `LineToClear` + public void RewriteConsoleLine() + { + bool useConsoleFallback = true; + if (!Console.IsInputRedirected) + { + // in case of console input redirection, the control ANSI codes would appear + + // first attempt ANSI Codes + int before = Console.CursorTop; + Console.Out.Write($"\u001b[2K\u001b[{LineToClear};0H"); + int after = Console.CursorTop; + + // Some consoles claim to be VT100 compliant, but don't respect + // all of the ANSI codes, so fallback to the System.Console impl in that case + useConsoleFallback = (before == after); + } + + if (useConsoleFallback) + { + SystemConsoleLineRewriter(); + } + } + + private void SystemConsoleLineRewriter() => Console.SetCursorPosition(0, LineToClear); + + private static bool? _isSetCursorPositionSupported; + public bool IsRewriteConsoleLineSupported + { + get + { + bool isSupported = _isSetCursorPositionSupported ?? EnsureInitialized(); + return isSupported; + + bool EnsureInitialized() + { + try + { + int left = Console.CursorLeft; + int top = Console.CursorTop; + Console.SetCursorPosition(0, LineToClear); + Console.SetCursorPosition(left, top); + _isSetCursorPositionSupported = true; + } + catch + { + _isSetCursorPositionSupported = false; + } + return (bool)_isSetCursorPositionSupported; + } + } + } + } +} diff --git a/src/Tools/Common/ReturnCode.cs b/src/Tools/Common/ReturnCode.cs new file mode 100644 index 0000000000..8b3e01e955 --- /dev/null +++ b/src/Tools/Common/ReturnCode.cs @@ -0,0 +1,15 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.Internal.Common.Utils +{ + internal enum ReturnCode + { + Ok, + SessionCreationError, + TracingError, + ArgumentError, + PlatformNotSupportedError, + UnknownError + } +} diff --git a/src/Tools/Common/ReversedServerHelpers/ReversedServerHelpers.cs b/src/Tools/Common/ReversedServerHelpers/ReversedServerHelpers.cs index b51f0cb130..79f8af70b5 100644 --- a/src/Tools/Common/ReversedServerHelpers/ReversedServerHelpers.cs +++ b/src/Tools/Common/ReversedServerHelpers/ReversedServerHelpers.cs @@ -89,7 +89,7 @@ public Process ChildProc return _childProc; } } - public bool Start(string diagnosticTransportName, CancellationToken ct, bool showChildIO, bool printLaunchCommand) + public void Start(string diagnosticTransportName, CancellationToken ct, bool showChildIO, bool printLaunchCommand) { _childProc.StartInfo.UseShellExecute = false; _childProc.StartInfo.RedirectStandardOutput = !showChildIO; @@ -107,15 +107,13 @@ public bool Start(string diagnosticTransportName, CancellationToken ct, bool sho } catch (Exception e) { - throw new CommandLineErrorException($"An error occurred trying to start process '{_childProc.StartInfo.FileName}' with working directory '{System.IO.Directory.GetCurrentDirectory()}'. {e.Message}"); + throw new DiagnosticToolException($"An error occurred trying to start process '{_childProc.StartInfo.FileName}' with working directory '{System.IO.Directory.GetCurrentDirectory()}'. {e.Message}"); } if (!showChildIO) { _stdOutTask = ReadAndIgnoreAllStreamAsync(_childProc.StandardOutput, ct); _stdErrTask = ReadAndIgnoreAllStreamAsync(_childProc.StandardError, ct); } - - return true; } public void Cleanup() @@ -231,10 +229,7 @@ public async Task Build(CancellationToken ct, int proce server.Start(); // Start the child proc - if (!ProcessLauncher.Launcher.Start(diagnosticTransportName, ct, showChildIO, printLaunchCommand)) - { - throw new InvalidOperationException($"Failed to start '{ProcessLauncher.Launcher.ChildProc.StartInfo.FileName} {ProcessLauncher.Launcher.ChildProc.StartInfo.Arguments}'."); - } + ProcessLauncher.Launcher.Start(diagnosticTransportName, ct, showChildIO, printLaunchCommand); IpcEndpointInfo endpointInfo; try { diff --git a/src/Tools/dotnet-counters/CounterMonitor.cs b/src/Tools/dotnet-counters/CounterMonitor.cs index 9235c65a26..230bea4940 100644 --- a/src/Tools/dotnet-counters/CounterMonitor.cs +++ b/src/Tools/dotnet-counters/CounterMonitor.cs @@ -25,8 +25,7 @@ internal class CounterMonitor : ICountersLogger private const int BufferDelaySecs = 1; private const string EventCountersProviderPrefix = "EventCounters\\"; private int _processId; - private TextWriter _stdOutput; - private TextWriter _stdError; + private IConsole _console; private List _counterList; private ICounterRenderer _renderer; private string _output; @@ -43,12 +42,11 @@ private class ProviderEventState private readonly Dictionary _providerEventStates = new(); private readonly Queue _bufferedEvents = new(); - public CounterMonitor(TextWriter stdOutput, TextWriter stdError) + public CounterMonitor(IConsole console = null) { _pauseCmdSet = false; _shouldExit = new TaskCompletionSource(); - _stdOutput = stdOutput; - _stdError = stdError; + _console = console ?? new DefaultConsole(); } private void MeterInstrumentEventObserved(string meterName, DateTime timestamp) @@ -187,9 +185,9 @@ public async Task Monitor( // to it. ValidateNonNegative(maxHistograms, nameof(maxHistograms)); ValidateNonNegative(maxTimeSeries, nameof(maxTimeSeries)); - if (!ProcessLauncher.Launcher.HasChildProc && !CommandUtils.ResolveProcessForAttach(processId, name, diagnosticPort, dsrouter, out _processId)) + if (!ProcessLauncher.Launcher.HasChildProc) { - return ReturnCode.ArgumentError; + CommandUtils.ResolveProcessForAttach(processId, name, diagnosticPort, dsrouter, out _processId); } ct.Register(() => _shouldExit.TrySetResult((int)ReturnCode.Ok)); @@ -238,15 +236,15 @@ public async Task Monitor( { //Cancellation token should automatically stop the session - _stdOutput.WriteLine($"Complete"); + _console.Out.WriteLine($"Complete"); return ReturnCode.Ok; } } } - catch (CommandLineErrorException e) + catch (DiagnosticToolException dte) { - _stdError.WriteLine(e.Message); - return ReturnCode.ArgumentError; + _console.Error.WriteLine(dte.Message); + return dte.ReturnCode; } finally { @@ -276,9 +274,9 @@ public async Task Collect( // to it. ValidateNonNegative(maxHistograms, nameof(maxHistograms)); ValidateNonNegative(maxTimeSeries, nameof(maxTimeSeries)); - if (!ProcessLauncher.Launcher.HasChildProc && !CommandUtils.ResolveProcessForAttach(processId, name, diagnosticPort, dsrouter, out _processId)) + if (!ProcessLauncher.Launcher.HasChildProc) { - return ReturnCode.ArgumentError; + CommandUtils.ResolveProcessForAttach(processId, name, diagnosticPort, dsrouter, out _processId); } ct.Register(() => _shouldExit.TrySetResult((int)ReturnCode.Ok)); @@ -306,7 +304,7 @@ public async Task Collect( _diagnosticsClient = holder.Client; if (_output.Length == 0) { - _stdError.WriteLine("Output cannot be an empty string"); + _console.Error.WriteLine("Output cannot be an empty string"); return ReturnCode.ArgumentError; } if (format == CountersExportFormat.csv) @@ -330,7 +328,7 @@ public async Task Collect( } else { - _stdError.WriteLine($"The output format {format} is not a valid output format."); + _console.Error.WriteLine($"The output format {format} is not a valid output format."); return ReturnCode.ArgumentError; } @@ -350,10 +348,10 @@ public async Task Collect( } } } - catch (CommandLineErrorException e) + catch (DiagnosticToolException dte) { - _stdError.WriteLine(e.Message); - return ReturnCode.ArgumentError; + _console.Error.WriteLine(dte.Message); + return dte.ReturnCode; } finally { @@ -365,7 +363,7 @@ private static void ValidateNonNegative(int value, string argName) { if (value < 0) { - throw new CommandLineErrorException($"Argument --{argName} must be non-negative"); + throw new DiagnosticToolException($"Argument --{argName} must be non-negative"); } } @@ -383,12 +381,12 @@ internal List ConfigureCounters(string commaSeparatedProv { // the FormatException message strings thrown by ParseProviderList are controlled // by us and anticipate being integrated into the command-line error text. - throw new CommandLineErrorException("Error parsing --counters argument: " + e.Message); + throw new DiagnosticToolException("Error parsing --counters argument: " + e.Message); } if (counters.Count == 0) { - _stdOutput.WriteLine($"--counters is unspecified. Monitoring System.Runtime counters by default."); + _console.Out.WriteLine($"--counters is unspecified. Monitoring System.Runtime counters by default."); ParseCounterProvider("System.Runtime", counters); } return counters; @@ -537,7 +535,7 @@ private async Task Start(MetricsPipeline pipeline, CancellationToken } catch (DiagnosticsClientException ex) { - Console.WriteLine($"Failed to start the counter session: {ex}"); + _console.WriteLine($"Failed to start the counter session: {ex}"); } catch (Exception ex) { diff --git a/src/Tools/dotnet-counters/Program.cs b/src/Tools/dotnet-counters/Program.cs index 2be10faea4..e108fa18c9 100644 --- a/src/Tools/dotnet-counters/Program.cs +++ b/src/Tools/dotnet-counters/Program.cs @@ -39,7 +39,7 @@ private static Command MonitorCommand() monitorCommand.TreatUnmatchedTokensAsErrors = false; // see the logic in Main - monitorCommand.SetAction(static (parseResult, ct) => new CounterMonitor(parseResult.Configuration.Output, parseResult.Configuration.Error).Monitor( + monitorCommand.SetAction(static (parseResult, ct) => new CounterMonitor().Monitor( ct, counters: parseResult.GetValue(CounterOption), processId: parseResult.GetValue(ProcessIdOption), @@ -79,7 +79,7 @@ private static Command CollectCommand() collectCommand.TreatUnmatchedTokensAsErrors = false; // see the logic in Main - collectCommand.SetAction((parseResult, ct) => new CounterMonitor(parseResult.Configuration.Output, parseResult.Configuration.Error).Collect( + collectCommand.SetAction((parseResult, ct) => new CounterMonitor().Collect( ct, counters: parseResult.GetValue(CounterOption), processId: parseResult.GetValue(ProcessIdOption), diff --git a/src/Tools/dotnet-counters/dotnet-counters.csproj b/src/Tools/dotnet-counters/dotnet-counters.csproj index 2ac31e5434..1c56c69d0b 100644 --- a/src/Tools/dotnet-counters/dotnet-counters.csproj +++ b/src/Tools/dotnet-counters/dotnet-counters.csproj @@ -16,13 +16,14 @@ - + - + + - + diff --git a/src/Tools/dotnet-dsrouter/dotnet-dsrouter.csproj b/src/Tools/dotnet-dsrouter/dotnet-dsrouter.csproj index ebed4febb6..db3fdb5d81 100644 --- a/src/Tools/dotnet-dsrouter/dotnet-dsrouter.csproj +++ b/src/Tools/dotnet-dsrouter/dotnet-dsrouter.csproj @@ -13,7 +13,8 @@ - + + diff --git a/src/Tools/dotnet-dump/Dumper.cs b/src/Tools/dotnet-dump/Dumper.cs index 65c30d32f3..54d12eafd9 100644 --- a/src/Tools/dotnet-dump/Dumper.cs +++ b/src/Tools/dotnet-dump/Dumper.cs @@ -35,14 +35,8 @@ public int Collect(TextWriter stdOutput, TextWriter stdError, int processId, str { try { - if (CommandUtils.ResolveProcessForAttach(processId, name, diagnosticPort, string.Empty, out int resolvedProcessId)) - { - processId = resolvedProcessId; - } - else - { - return -1; - } + CommandUtils.ResolveProcessForAttach(processId, name, diagnosticPort, string.Empty, out int resolvedProcessId); + processId = resolvedProcessId; if (output == null) { @@ -132,6 +126,11 @@ public int Collect(TextWriter stdOutput, TextWriter stdError, int processId, str client.WriteDump(dumpType, output, flags); } } + catch (DiagnosticToolException dte) + { + stdError.WriteLine($"[ERROR] {dte.Message}"); + return -1; + } catch (Exception ex) { if (diag) diff --git a/src/Tools/dotnet-dump/dotnet-dump.csproj b/src/Tools/dotnet-dump/dotnet-dump.csproj index 991a0fadcf..60705a32d8 100644 --- a/src/Tools/dotnet-dump/dotnet-dump.csproj +++ b/src/Tools/dotnet-dump/dotnet-dump.csproj @@ -19,11 +19,12 @@ - + - + + diff --git a/src/Tools/dotnet-gcdump/CommandLine/CollectCommandHandler.cs b/src/Tools/dotnet-gcdump/CommandLine/CollectCommandHandler.cs index 26af23d866..b5a44b6895 100644 --- a/src/Tools/dotnet-gcdump/CommandLine/CollectCommandHandler.cs +++ b/src/Tools/dotnet-gcdump/CommandLine/CollectCommandHandler.cs @@ -30,16 +30,12 @@ internal static class CollectCommandHandler /// private static async Task Collect(CancellationToken ct, int processId, string output, int timeout, bool verbose, string name, string diagnosticPort, string dsrouter) { - if (!CommandUtils.ResolveProcessForAttach(processId, name, diagnosticPort, dsrouter, out int resolvedProcessId)) + try { - return -1; - } + CommandUtils.ResolveProcessForAttach(processId, name, diagnosticPort, dsrouter, out int resolvedProcessId); + processId = resolvedProcessId; - processId = resolvedProcessId; - - if (!string.IsNullOrEmpty(diagnosticPort)) - { - try + if (!string.IsNullOrEmpty(diagnosticPort)) { IpcEndpointConfig config = IpcEndpointConfig.Parse(diagnosticPort); if (!config.IsConnectConfig) @@ -47,18 +43,10 @@ private static async Task Collect(CancellationToken ct, int processId, stri Console.Error.WriteLine("--diagnostic-port is only supporting connect mode."); return -1; } - } - catch (Exception ex) - { - Console.Error.WriteLine($"--diagnostic-port argument error: {ex.Message}"); - return -1; - } - processId = 0; - } + processId = 0; + } - try - { output = string.IsNullOrEmpty(output) ? $"{DateTime.Now:yyyyMMdd\\_HHmmss}_{processId}.gcdump" : output; @@ -106,6 +94,16 @@ private static async Task Collect(CancellationToken ct, int processId, stri return -1; } } + catch (DiagnosticToolException dte) + { + Console.Error.WriteLine($"[ERROR] {dte.Message}"); + return -1; + } + catch (FormatException fe) + { + Console.Error.WriteLine($"--diagnostic-port argument error: {fe.Message}"); + return -1; + } catch (Exception ex) { Console.Error.WriteLine($"[ERROR] {ex}"); diff --git a/src/Tools/dotnet-gcdump/CommandLine/ReportCommandHandler.cs b/src/Tools/dotnet-gcdump/CommandLine/ReportCommandHandler.cs index c0bab3af39..092a8c592a 100644 --- a/src/Tools/dotnet-gcdump/CommandLine/ReportCommandHandler.cs +++ b/src/Tools/dotnet-gcdump/CommandLine/ReportCommandHandler.cs @@ -91,16 +91,12 @@ private static Task HandleUnknownParam() private static Task ReportFromProcess(int processId, string diagnosticPort, string dsrouter, CancellationToken ct) { - if (!CommandUtils.ResolveProcessForAttach(processId, string.Empty, diagnosticPort, dsrouter, out int resolvedProcessId)) + try { - return Task.FromResult(-1); - } + CommandUtils.ResolveProcessForAttach(processId, string.Empty, diagnosticPort, dsrouter, out int resolvedProcessId); + processId = resolvedProcessId; - processId = resolvedProcessId; - - if (!string.IsNullOrEmpty(diagnosticPort)) - { - try + if (!string.IsNullOrEmpty(diagnosticPort)) { IpcEndpointConfig config = IpcEndpointConfig.Parse(diagnosticPort); if (!config.IsConnectConfig) @@ -108,14 +104,23 @@ private static Task ReportFromProcess(int processId, string diagnosticPort, Console.Error.WriteLine("--diagnostic-port is only supporting connect mode."); return Task.FromResult(-1); } + processId = 0; } - catch (Exception ex) - { - Console.Error.WriteLine($"--diagnostic-port argument error: {ex.Message}"); - return Task.FromResult(-1); - } - - processId = 0; + } + catch (DiagnosticToolException dte) + { + Console.Error.WriteLine($"[ERROR] {dte.Message}"); + return Task.FromResult(-1); + } + catch (FormatException fe) + { + Console.Error.WriteLine($"--diagnostic-port argument error: {fe.Message}"); + return Task.FromResult(-1); + } + catch (Exception ex) + { + Console.Error.WriteLine($"[ERROR] {ex}"); + return Task.FromResult(-1); } if (!CollectCommandHandler diff --git a/src/Tools/dotnet-gcdump/dotnet-gcdump.csproj b/src/Tools/dotnet-gcdump/dotnet-gcdump.csproj index 4586ecfc20..a0b4064b9c 100644 --- a/src/Tools/dotnet-gcdump/dotnet-gcdump.csproj +++ b/src/Tools/dotnet-gcdump/dotnet-gcdump.csproj @@ -23,11 +23,12 @@ - + - + + diff --git a/src/Tools/dotnet-stack/ReportCommand.cs b/src/Tools/dotnet-stack/ReportCommand.cs index c8f2ecc365..21e73f2d7e 100644 --- a/src/Tools/dotnet-stack/ReportCommand.cs +++ b/src/Tools/dotnet-stack/ReportCommand.cs @@ -35,32 +35,8 @@ private static async Task Report(CancellationToken ct, TextWriter stdOutput try { - // Either processName or processId has to be specified. - if (!string.IsNullOrEmpty(name)) - { - if (processId != 0) - { - Console.WriteLine("Can only specify either --name or --process-id option."); - return -1; - } - processId = CommandUtils.FindProcessIdWithName(name); - if (processId < 0) - { - return -1; - } - } - - if (processId < 0) - { - stdError.WriteLine("Process ID should not be negative."); - return -1; - } - else if (processId == 0) - { - stdError.WriteLine("--process-id is required"); - return -1; - } - + CommandUtils.ResolveProcess(processId, name, out int resolvedProcessId, out string _); + processId = resolvedProcessId; DiagnosticsClient client = new(processId); List providers = new() @@ -143,6 +119,11 @@ private static async Task Report(CancellationToken ct, TextWriter stdOutput } } } + catch (DiagnosticToolException dte) + { + stdError.WriteLine($"[ERROR] {dte.Message}"); + return -1; + } catch (OperationCanceledException) { return -1; diff --git a/src/Tools/dotnet-stack/dotnet-stack.csproj b/src/Tools/dotnet-stack/dotnet-stack.csproj index beacb323f4..403ee760d6 100644 --- a/src/Tools/dotnet-stack/dotnet-stack.csproj +++ b/src/Tools/dotnet-stack/dotnet-stack.csproj @@ -22,11 +22,12 @@ - + - + + diff --git a/src/Tools/dotnet-trace/CommandLine/Commands/CollectCommand.cs b/src/Tools/dotnet-trace/CommandLine/Commands/CollectCommand.cs index c9d4124f78..9c6ec43d63 100644 --- a/src/Tools/dotnet-trace/CommandLine/Commands/CollectCommand.cs +++ b/src/Tools/dotnet-trace/CommandLine/Commands/CollectCommand.cs @@ -23,9 +23,9 @@ internal class CollectCommandHandler { internal bool IsQuiet { get; set; } - public CollectCommandHandler() + public CollectCommandHandler(IConsole console = null) { - Console = new DefaultConsole(false); + Console = console ?? new DefaultConsole(); StartTraceSessionAsync = async (client, config, ct) => new CollectSession(await client.StartEventPipeSessionAsync(config, ct).ConfigureAwait(false)); ResumeRuntimeAsync = (client, ct) => client.ResumeRuntimeAsync(ct); CollectSessionEventStream = (name) => new FileStream(name, FileMode.Create, FileAccess.Write); @@ -103,18 +103,12 @@ internal async Task Collect(CancellationToken ct, CommandLineConfiguration Console.WriteLine("--show-child-io must not be specified when attaching to a process"); return (int)ReturnCode.ArgumentError; } - if (CommandUtils.ResolveProcessForAttach(processId, name, diagnosticPort, dsrouter, out int resolvedProcessId)) - { - processId = resolvedProcessId; - } - else - { - return (int)ReturnCode.ArgumentError; - } + CommandUtils.ResolveProcessForAttach(processId, name, diagnosticPort, dsrouter, out int resolvedProcessId); + processId = resolvedProcessId; } - else if (!CommandUtils.ValidateArgumentsForChildProcess(processId, name, diagnosticPort)) + else { - return (int)ReturnCode.ArgumentError; + CommandUtils.ValidateArgumentsForChildProcess(processId, name, diagnosticPort); } if (profile.Length == 0 && providers.Length == 0 && clrevents.Length == 0) @@ -474,11 +468,11 @@ internal async Task Collect(CancellationToken ct, CommandLineConfiguration } } } - catch (CommandLineErrorException e) + catch (DiagnosticToolException dte) { - Console.Error.WriteLine($"[ERROR] {e.Message}"); + Console.Error.WriteLine($"[ERROR] {dte.Message}"); collectionStopped = true; - ret = (int)ReturnCode.TracingError; + ret = (int)dte.ReturnCode; } catch (OperationCanceledException) { diff --git a/src/Tools/dotnet-trace/CommandLine/Commands/CollectLinuxCommand.cs b/src/Tools/dotnet-trace/CommandLine/Commands/CollectLinuxCommand.cs index 1129cab856..63bb18dabb 100644 --- a/src/Tools/dotnet-trace/CommandLine/Commands/CollectLinuxCommand.cs +++ b/src/Tools/dotnet-trace/CommandLine/Commands/CollectLinuxCommand.cs @@ -37,7 +37,7 @@ internal sealed record CollectLinuxArgs( public CollectLinuxCommandHandler(IConsole console = null) { - Console = console ?? new DefaultConsole(false); + Console = console ?? new DefaultConsole(); rewriter = new LineRewriter(Console); } @@ -71,15 +71,6 @@ internal int CollectLinux(CollectLinuxArgs args) return (int)ReturnCode.PlatformNotSupportedError; } - if (args.ProcessId != 0 || !string.IsNullOrEmpty(args.Name)) - { - if (!CommandUtils.ResolveProcess(args.ProcessId, args.Name, out int resolvedProcessId, out string resolvedProcessName)) - { - return (int)ReturnCode.ArgumentError; - } - args = args with { Name = resolvedProcessName, ProcessId = resolvedProcessId }; - } - Console.WriteLine("=========================================================================================="); Console.WriteLine("The collect-linux verb is a new preview feature and relies on an updated version of the"); Console.WriteLine(".nettrace file format. The latest PerfView release supports these trace files but other"); @@ -87,11 +78,17 @@ internal int CollectLinux(CollectLinuxArgs args) Console.WriteLine("https://learn.microsoft.com/dotnet/core/diagnostics/dotnet-trace."); Console.WriteLine("=========================================================================================="); - args.Ct.Register(() => stopTracing = true); int ret = (int)ReturnCode.TracingError; string scriptPath = null; try { + if (args.ProcessId != 0 || !string.IsNullOrEmpty(args.Name)) + { + CommandUtils.ResolveProcess(args.ProcessId, args.Name, out int resolvedProcessId, out string resolvedProcessName); + args = args with { Name = resolvedProcessName, ProcessId = resolvedProcessId }; + } + + args.Ct.Register(() => stopTracing = true); Console.CursorVisible = false; byte[] command = BuildRecordTraceArgs(args, out scriptPath); @@ -108,10 +105,10 @@ internal int CollectLinux(CollectLinuxArgs args) stopwatch.Start(); ret = RecordTraceInvoker(command, (UIntPtr)command.Length, OutputHandler); } - catch (CommandLineErrorException e) + catch (DiagnosticToolException dte) { - Console.Error.WriteLine($"[ERROR] {e.Message}"); - ret = (int)ReturnCode.TracingError; + Console.Error.WriteLine($"[ERROR] {dte.Message}"); + ret = (int)dte.ReturnCode; } catch (DllNotFoundException dnfe) { @@ -236,7 +233,7 @@ private byte[] BuildRecordTraceArgs(CollectLinuxArgs args, out string scriptPath string[] split = perfEvent.Split(':', 2, StringSplitOptions.TrimEntries); if (split.Length != 2 || string.IsNullOrEmpty(split[0]) || string.IsNullOrEmpty(split[1])) { - throw new CommandLineErrorException($"Invalid perf event specification '{perfEvent}'. Expected format 'provider:event'."); + throw new DiagnosticToolException($"Invalid perf event specification '{perfEvent}'. Expected format 'provider:event'."); } string perfProvider = split[0]; diff --git a/src/Tools/dotnet-trace/ProviderUtils.cs b/src/Tools/dotnet-trace/ProviderUtils.cs index 0adffe6450..c8dd83312c 100644 --- a/src/Tools/dotnet-trace/ProviderUtils.cs +++ b/src/Tools/dotnet-trace/ProviderUtils.cs @@ -76,7 +76,7 @@ private enum ProviderSource public static List ComputeProviderConfig(string[] providersArg, string clreventsArg, string clreventlevel, string[] profiles, bool shouldPrintProviders = false, string verbExclusivity = null, IConsole console = null) { - console ??= new DefaultConsole(false); + console ??= new DefaultConsole(); Dictionary merged = new(StringComparer.OrdinalIgnoreCase); Dictionary providerSources = new(StringComparer.OrdinalIgnoreCase); @@ -101,14 +101,14 @@ public static List ComputeProviderConfig(string[] providersAr if (traceProfile == null) { - throw new CommandLineErrorException($"Invalid profile name: {profile}"); + throw new DiagnosticToolException($"Invalid profile name: {profile}"); } if (!string.IsNullOrEmpty(verbExclusivity) && !string.IsNullOrEmpty(traceProfile.VerbExclusivity) && !string.Equals(traceProfile.VerbExclusivity, verbExclusivity, StringComparison.OrdinalIgnoreCase)) { - throw new CommandLineErrorException($"The specified profile '{traceProfile.Name}' does not apply to `dotnet-trace {verbExclusivity}`."); + throw new DiagnosticToolException($"The specified profile '{traceProfile.Name}' does not apply to `dotnet-trace {verbExclusivity}`."); } IEnumerable profileProviders = traceProfile.Providers; @@ -158,7 +158,7 @@ private static EventPipeProvider MergeProviderConfigs(EventPipeProvider provider if (providerConfigA.Arguments != null && providerConfigB.Arguments != null) { - throw new CommandLineErrorException($"Provider \"{providerConfigA.Name}\" is declared multiple times with filter arguments."); + throw new DiagnosticToolException($"Provider \"{providerConfigA.Name}\" is declared multiple times with filter arguments."); } return new EventPipeProvider(providerConfigA.Name, level, providerConfigA.Keywords | providerConfigB.Keywords, providerConfigA.Arguments ?? providerConfigB.Arguments); @@ -218,7 +218,7 @@ public static EventPipeProvider ToCLREventPipeProvider(string clreventslist, str } else { - throw new CommandLineErrorException($"{clrevents[i]} is not a valid CLR event keyword"); + throw new DiagnosticToolException($"{clrevents[i]} is not a valid CLR event keyword"); } } @@ -256,7 +256,7 @@ private static EventLevel GetEventLevel(string token) case "warning": return EventLevel.Warning; default: - throw new CommandLineErrorException($"Unknown EventLevel: {token}"); + throw new DiagnosticToolException($"Unknown EventLevel: {token}"); } } } @@ -281,7 +281,7 @@ private static EventPipeProvider ToProvider(string provider, IConsole console) if (string.IsNullOrWhiteSpace(providerName)) { - throw new CommandLineErrorException("Provider name was not specified."); + throw new DiagnosticToolException("Provider name was not specified."); } // Keywords diff --git a/src/Tools/dotnet-trace/TraceFileFormatConverter.cs b/src/Tools/dotnet-trace/TraceFileFormatConverter.cs index 61e4c4c1b8..a6e08ac74c 100644 --- a/src/Tools/dotnet-trace/TraceFileFormatConverter.cs +++ b/src/Tools/dotnet-trace/TraceFileFormatConverter.cs @@ -62,7 +62,7 @@ internal static void ConvertToFormat(TextWriter stdOut, TextWriter stdError, Tra break; default: // Validation happened way before this, so we shoud never reach this... - throw new CommandLineErrorException($"Invalid TraceFileFormat \"{format}\""); + throw new DiagnosticToolException($"Invalid TraceFileFormat \"{format}\""); } stdOut.WriteLine("Conversion complete"); } @@ -94,7 +94,7 @@ private static void Convert(TraceFileFormat format, string fileToConvert, string break; default: // we should never get here - throw new CommandLineErrorException($"Invalid TraceFileFormat \"{format}\""); + throw new DiagnosticToolException($"Invalid TraceFileFormat \"{format}\""); } } diff --git a/src/tests/dotnet-counters/CounterMonitorPayloadTests.cs b/src/tests/dotnet-counters/CounterMonitorPayloadTests.cs index f1f6b554c0..38bc614706 100644 --- a/src/tests/dotnet-counters/CounterMonitorPayloadTests.cs +++ b/src/tests/dotnet-counters/CounterMonitorPayloadTests.cs @@ -196,7 +196,7 @@ private async Task> GetCounterTrace(TestConfiguration con { try { - CounterMonitor monitor = new CounterMonitor(TextWriter.Null, TextWriter.Null); + CounterMonitor monitor = new CounterMonitor(); using CancellationTokenSource source = new CancellationTokenSource(DefaultTimeout); diff --git a/src/tests/dotnet-counters/CounterMonitorTests.cs b/src/tests/dotnet-counters/CounterMonitorTests.cs index 30e7bbb816..c840d91b83 100644 --- a/src/tests/dotnet-counters/CounterMonitorTests.cs +++ b/src/tests/dotnet-counters/CounterMonitorTests.cs @@ -79,7 +79,7 @@ public void GenerateCounterListTestManyProvidersWithFilter() [Fact] public void GenerateCounterListWithOptionAndArgumentsTest() { - CounterMonitor monitor = new(TextWriter.Null, TextWriter.Null); + CounterMonitor monitor = new(); string countersOptionText = "MyEventSource1,MyEventSource2"; List counters = monitor.ConfigureCounters(countersOptionText); Assert.Contains("MyEventSource1", counters.Select(g => g.ProviderName)); @@ -89,45 +89,45 @@ public void GenerateCounterListWithOptionAndArgumentsTest() [Fact] public void ParseErrorUnbalancedBracketsInCountersArg() { - CounterMonitor monitor = new(TextWriter.Null, TextWriter.Null); + CounterMonitor monitor = new(); string countersOptionText = "System.Runtime[cpu-usage,MyEventSource"; - CommandLineErrorException e = Assert.Throws(() => monitor.ConfigureCounters(countersOptionText)); + DiagnosticToolException e = Assert.Throws(() => monitor.ConfigureCounters(countersOptionText)); Assert.Equal("Error parsing --counters argument: Expected to find closing ']' in counter_provider", e.Message); } [Fact] public void ParseErrorTrailingTextInCountersArg() { - CounterMonitor monitor = new(TextWriter.Null, TextWriter.Null); + CounterMonitor monitor = new(); string countersOptionText = "System.Runtime[cpu-usage]hello,MyEventSource"; - CommandLineErrorException e = Assert.Throws(() => monitor.ConfigureCounters(countersOptionText)); + DiagnosticToolException e = Assert.Throws(() => monitor.ConfigureCounters(countersOptionText)); Assert.Equal("Error parsing --counters argument: Unexpected characters after closing ']' in counter_provider", e.Message); } [Fact] public void ParseErrorEmptyProvider() { - CounterMonitor monitor = new(TextWriter.Null, TextWriter.Null); + CounterMonitor monitor = new(); string countersOptionText = ",MyEventSource"; - CommandLineErrorException e = Assert.Throws(() => monitor.ConfigureCounters(countersOptionText)); + DiagnosticToolException e = Assert.Throws(() => monitor.ConfigureCounters(countersOptionText)); Assert.Equal("Error parsing --counters argument: Expected non-empty counter_provider", e.Message); } [Fact] public void ParseErrorMultipleCounterLists() { - CounterMonitor monitor = new(TextWriter.Null, TextWriter.Null); + CounterMonitor monitor = new(); string countersOptionText = "System.Runtime[cpu-usage][working-set],MyEventSource"; - CommandLineErrorException e = Assert.Throws(() => monitor.ConfigureCounters(countersOptionText)); + DiagnosticToolException e = Assert.Throws(() => monitor.ConfigureCounters(countersOptionText)); Assert.Equal("Error parsing --counters argument: Expected at most one '[' in counter_provider", e.Message); } [Fact] public void ParseErrorMultiplePrefixesOnSameProvider() { - CounterMonitor monitor = new(TextWriter.Null, TextWriter.Null); + CounterMonitor monitor = new(); string countersOptionText = "System.Runtime,MyEventSource,EventCounters\\System.Runtime"; - CommandLineErrorException e = Assert.Throws(() => monitor.ConfigureCounters(countersOptionText)); + DiagnosticToolException e = Assert.Throws(() => monitor.ConfigureCounters(countersOptionText)); Assert.Equal("Error parsing --counters argument: Using the same provider name with and without the EventCounters\\ prefix in the counter list is not supported.", e.Message); } } diff --git a/src/tests/dotnet-trace/CLRProviderParsing.cs b/src/tests/dotnet-trace/CLRProviderParsing.cs index 3b3f80a35e..427a0cfd22 100644 --- a/src/tests/dotnet-trace/CLRProviderParsing.cs +++ b/src/tests/dotnet-trace/CLRProviderParsing.cs @@ -29,7 +29,7 @@ public void ValidSingleCLREvent(string providerToParse) [InlineData("haha")] public void InValidSingleCLREvent(string providerToParse) { - Assert.Throws(() => ProviderUtils.ToCLREventPipeProvider(providerToParse, "4")); + Assert.Throws(() => ProviderUtils.ToCLREventPipeProvider(providerToParse, "4")); } [Theory] @@ -64,7 +64,7 @@ public void ValidCLREventLevel(string clreventlevel) [InlineData("hello")] public void InvalidCLREventLevel(string clreventlevel) { - Assert.Throws(() => ProviderUtils.ToCLREventPipeProvider("gc", clreventlevel)); + Assert.Throws(() => ProviderUtils.ToCLREventPipeProvider("gc", clreventlevel)); } } } diff --git a/src/tests/dotnet-trace/CollectCommandFunctionalTests.cs b/src/tests/dotnet-trace/CollectCommandFunctionalTests.cs index ec6d537f3f..2ca87ace32 100644 --- a/src/tests/dotnet-trace/CollectCommandFunctionalTests.cs +++ b/src/tests/dotnet-trace/CollectCommandFunctionalTests.cs @@ -66,17 +66,16 @@ public async Task CollectCommandInvalidProviderConfiguration_Throws(CollectArgs { MockConsole console = new(200, 30); int exitCode = await RunAsync(args, console).ConfigureAwait(true); - Assert.Equal((int)ReturnCode.TracingError, exitCode); + Assert.Equal((int)ReturnCode.ArgumentError, exitCode); console.AssertSanitizedLinesEqual(CollectSanitizer, expectedException); } private static async Task RunAsync(CollectArgs config, MockConsole console) { - var handler = new CollectCommandHandler(); + var handler = new CollectCommandHandler(console); handler.StartTraceSessionAsync = (client, cfg, ct) => Task.FromResult(new TestCollectSession()); handler.ResumeRuntimeAsync = (client, ct) => Task.CompletedTask; handler.CollectSessionEventStream = (name) => config.EventStream; - handler.Console = console; return await handler.Collect( config.ct, diff --git a/src/tests/dotnet-trace/CollectLinuxCommandFunctionalTests.cs b/src/tests/dotnet-trace/CollectLinuxCommandFunctionalTests.cs index 142872cd41..f9b7616cf5 100644 --- a/src/tests/dotnet-trace/CollectLinuxCommandFunctionalTests.cs +++ b/src/tests/dotnet-trace/CollectLinuxCommandFunctionalTests.cs @@ -71,7 +71,7 @@ public void CollectLinuxCommandProviderConfigurationConsolidation_Throws(object int exitCode = Run(testArgs, console); if (CollectLinuxCommandHandler.IsSupported()) { - Assert.Equal((int)ReturnCode.TracingError, exitCode); + Assert.Equal((int)ReturnCode.ArgumentError, exitCode); console.AssertSanitizedLinesEqual(null, expectedException); } else diff --git a/src/tests/dotnet-trace/ProviderCompositionTests.cs b/src/tests/dotnet-trace/ProviderCompositionTests.cs index d7441fbe6c..c5a9a8c766 100644 --- a/src/tests/dotnet-trace/ProviderCompositionTests.cs +++ b/src/tests/dotnet-trace/ProviderCompositionTests.cs @@ -43,10 +43,10 @@ public static IEnumerable ValidProviders() public static IEnumerable InvalidProviders() { - yield return new object[] { ":::", typeof(CommandLineErrorException) }; - yield return new object[] { ":1:1", typeof(CommandLineErrorException) }; - yield return new object[] { "ProviderOne:0x1:UnknownLevel", typeof(CommandLineErrorException) }; - yield return new object[] { "VeryCoolProvider:0x0:-1", typeof(CommandLineErrorException) }; + yield return new object[] { ":::", typeof(DiagnosticToolException) }; + yield return new object[] { ":1:1", typeof(DiagnosticToolException) }; + yield return new object[] { "ProviderOne:0x1:UnknownLevel", typeof(DiagnosticToolException) }; + yield return new object[] { "VeryCoolProvider:0x0:-1", typeof(DiagnosticToolException) }; yield return new object[] { "VeryCoolProvider:0xFFFFFFFFFFFFFFFFF:5:FilterAndPayloadSpecs=\"QuotedValue\"", typeof(OverflowException) }; yield return new object[] { "VeryCoolProvider:0x10000000000000000::FilterAndPayloadSpecs=\"QuotedValue\"", typeof(OverflowException) }; yield return new object[] { "VeryCoolProvider:__:5:FilterAndPayloadSpecs=\"QuotedValue\"", typeof(FormatException) }; @@ -120,7 +120,7 @@ public void MultipleProviders_Parse_AsExpected(string providersArg, EventPipePro public static IEnumerable MultipleInvalidProviders() { - yield return new object[] { "ProviderOne:0x1:5:FilterAndPayloadSpecs=\"QuotedValue\",:2:2:key=value,ProviderThree:3:3:key=value", typeof(CommandLineErrorException) }; + yield return new object[] { "ProviderOne:0x1:5:FilterAndPayloadSpecs=\"QuotedValue\",:2:2:key=value,ProviderThree:3:3:key=value", typeof(DiagnosticToolException) }; yield return new object[] { "ProviderOne:0x1:5:FilterAndPayloadSpecs=\"QuotedValue\",ProviderTwo:0xFFFFFFFFFFFFFFFFF:5:FilterAndPayloadSpecs=\"QuotedValue\",ProviderThree:3:3:key=value", typeof(OverflowException) }; yield return new object[] { "ProviderOne:0x1:5:FilterAndPayloadSpecs=\"QuotedValue\",ProviderTwo:0x10000000000000000:5:FilterAndPayloadSpecs=\"QuotedValue\",ProviderThree:3:3:key=value", typeof(OverflowException) }; yield return new object[] { "ProviderOne:0x1:5:FilterAndPayloadSpecs=\"QuotedValue\",ProviderTwo:18446744073709551615:5:FilterAndPayloadSpecs=\"QuotedValue\",ProviderThree:3:3:key=value", typeof(OverflowException) }; @@ -146,7 +146,7 @@ public static IEnumerable DedupeSuccessCases() public static IEnumerable DedupeFailureCases() { - yield return new object[] { new[]{ "MyProvider:::key=value", "MyProvider:::key=value" }, typeof(CommandLineErrorException) }; + yield return new object[] { new[]{ "MyProvider:::key=value", "MyProvider:::key=value" }, typeof(DiagnosticToolException) }; } [Theory] @@ -233,7 +233,7 @@ public void ProviderSourcePrecedence(string[] providersArg, string clreventsArg, public static IEnumerable InvalidClrEvents() { - yield return new object[] { Array.Empty(), "gc+bogus", string.Empty, Array.Empty(), typeof(CommandLineErrorException) }; + yield return new object[] { Array.Empty(), "gc+bogus", string.Empty, Array.Empty(), typeof(DiagnosticToolException) }; } [Theory]