diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs index a57d85aa983fd9..12603f7df6ae9a 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs @@ -208,7 +208,7 @@ public static unsafe int AcquireDefaultCredential( ref outCredential._handle, out timeStamp); - if (NetEventSource.Log.IsEnabled()) NetEventSource.Verbose(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); if (errorCode != 0) { @@ -265,7 +265,7 @@ public static unsafe int AcquireCredentialsHandle( ref outCredential._handle, out _); - if (NetEventSource.Log.IsEnabled()) NetEventSource.Verbose(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); if (errorCode != 0) { @@ -296,7 +296,7 @@ public static unsafe int AcquireCredentialsHandle( ref outCredential._handle, out timeStamp); - if (NetEventSource.Log.IsEnabled()) NetEventSource.Verbose(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); if (errorCode != 0) { diff --git a/src/libraries/Common/src/System/Net/Http/aspnetcore/NetEventSource.Common.cs b/src/libraries/Common/src/System/Net/Http/aspnetcore/NetEventSource.Common.cs deleted file mode 100644 index 66c3d560337382..00000000000000 --- a/src/libraries/Common/src/System/Net/Http/aspnetcore/NetEventSource.Common.cs +++ /dev/null @@ -1,687 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -#if DEBUG -// Uncomment to enable runtime checks to help validate that NetEventSource isn't being misused -// in a way that will cause performance problems, e.g. unexpected boxing of value types. -//#define DEBUG_NETEVENTSOURCE_MISUSE -#endif - -#nullable enable -using System.Collections; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Tracing; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -#pragma warning disable CA1823 // not all IDs are used by all partial providers - -namespace System.Net -{ - // Implementation: - // This partial file is meant to be consumed into each System.Net.* assembly that needs to log. Each such assembly also provides - // its own NetEventSource partial class that adds an appropriate [EventSource] attribute, giving it a unique name for that assembly. - // Those partials can then also add additional events if needed, starting numbering from the NextAvailableEventId defined by this partial. - - // Usage: - // - Operations that may allocate (e.g. boxing a value type, using string interpolation, etc.) or that may have computations - // at call sites should guard access like: - // if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Found certificate: {cert}"); // info logging with a formattable string - // - Operations that have zero allocations / measurable computations at call sites can use a simpler pattern, calling methods like: - // NetEventSource.Info(this, "literal string"); // arbitrary message with a literal string - // Debug.Asserts inside the logging methods will help to flag some misuse if the DEBUG_NETEVENTSOURCE_MISUSE compilation constant is defined. - // However, because it can be difficult by observation to understand all of the costs involved, guarding can be done everywhere. - // - Messages can be strings, formattable strings, or any other object. Objects (including those used in formattable strings) have special - // formatting applied, controlled by the Format method. Partial specializations can also override this formatting by implementing a partial - // method that takes an object and optionally provides a string representation of it, in case a particular library wants to customize further. - - /// Provides logging facilities for System.Net libraries. - internal sealed partial class NetEventSource : EventSource - { - /// The single event source instance to use for all logging. - public static readonly NetEventSource Log = new NetEventSource(); - - #region Metadata - public static class Keywords - { - public const EventKeywords Default = (EventKeywords)0x0001; - public const EventKeywords Debug = (EventKeywords)0x0002; - public const EventKeywords EnterExit = (EventKeywords)0x0004; - } - - private const string MissingMember = "(?)"; - private const string NullInstance = "(null)"; - private const string StaticMethodObject = "(static)"; - private const string NoParameters = ""; - private const int MaxDumpSize = 1024; - - private const int EnterEventId = 1; - private const int ExitEventId = 2; - private const int AssociateEventId = 3; - private const int InfoEventId = 4; - private const int ErrorEventId = 5; - private const int DumpArrayEventId = 7; - - // These events are implemented in NetEventSource.Security.cs. - // Define the ids here so that projects that include NetEventSource.Security.cs will not have conflicts. - private const int EnumerateSecurityPackagesId = 8; - private const int SspiPackageNotFoundId = 9; - private const int AcquireDefaultCredentialId = 10; - private const int AcquireCredentialsHandleId = 11; - private const int InitializeSecurityContextId = 12; - private const int SecurityContextInputBufferId = 13; - private const int SecurityContextInputBuffersId = 14; - private const int AcceptSecuritContextId = 15; - private const int OperationReturnedSomethingId = 16; - - private const int NextAvailableEventId = 17; // Update this value whenever new events are added. Derived types should base all events off of this to avoid conflicts. - #endregion - - #region Events - #region Enter - /// Logs entrance to a method. - /// `this`, or another object that serves to provide context for the operation. - /// A description of the entrance, including any arguments to the call. - /// The calling member. - [NonEvent] - public static void Enter(object? thisOrContextObject, FormattableString? formattableString = null, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(formattableString); - if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters); - } - - /// Logs entrance to a method. - /// `this`, or another object that serves to provide context for the operation. - /// The object to log. - /// The calling member. - [NonEvent] - public static void Enter(object? thisOrContextObject, object arg0, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(arg0); - if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)})"); - } - - /// Logs entrance to a method. - /// `this`, or another object that serves to provide context for the operation. - /// The first object to log. - /// The second object to log. - /// The calling member. - [NonEvent] - public static void Enter(object? thisOrContextObject, object arg0, object arg1, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(arg0); - DebugValidateArg(arg1); - if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)})"); - } - - /// Logs entrance to a method. - /// `this`, or another object that serves to provide context for the operation. - /// The first object to log. - /// The second object to log. - /// The third object to log. - /// The calling member. - [NonEvent] - public static void Enter(object? thisOrContextObject, object arg0, object arg1, object arg2, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(arg0); - DebugValidateArg(arg1); - DebugValidateArg(arg2); - if (Log.IsEnabled()) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)}, {Format(arg2)})"); - } - - [Event(EnterEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)] - private void Enter(string thisOrContextObject, string? memberName, string parameters) => - WriteEvent(EnterEventId, thisOrContextObject, memberName ?? MissingMember, parameters); - #endregion - - #region Exit - /// Logs exit from a method. - /// `this`, or another object that serves to provide context for the operation. - /// A description of the exit operation, including any return values. - /// The calling member. - [NonEvent] - public static void Exit(object? thisOrContextObject, FormattableString? formattableString = null, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(formattableString); - if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters); - } - - /// Logs exit from a method. - /// `this`, or another object that serves to provide context for the operation. - /// A return value from the member. - /// The calling member. - [NonEvent] - public static void Exit(object? thisOrContextObject, object arg0, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(arg0); - if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, Format(arg0).ToString()); - } - - /// Logs exit from a method. - /// `this`, or another object that serves to provide context for the operation. - /// A return value from the member. - /// A second return value from the member. - /// The calling member. - [NonEvent] - public static void Exit(object? thisOrContextObject, object arg0, object arg1, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(arg0); - DebugValidateArg(arg1); - if (Log.IsEnabled()) Log.Exit(IdOf(thisOrContextObject), memberName, $"{Format(arg0)}, {Format(arg1)}"); - } - - [Event(ExitEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)] - private void Exit(string thisOrContextObject, string? memberName, string? result) => - WriteEvent(ExitEventId, thisOrContextObject, memberName ?? MissingMember, result); - #endregion - - #region Info - /// Logs an information message. - /// `this`, or another object that serves to provide context for the operation. - /// The message to be logged. - /// The calling member. - [NonEvent] - public static void Info(object? thisOrContextObject, FormattableString? formattableString = null, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(formattableString); - if (Log.IsEnabled()) Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters); - } - - /// Logs an information message. - /// `this`, or another object that serves to provide context for the operation. - /// The message to be logged. - /// The calling member. - [NonEvent] - public static void Info(object? thisOrContextObject, object? message, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(message); - if (Log.IsEnabled()) Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString()); - } - - [Event(InfoEventId, Level = EventLevel.Informational, Keywords = Keywords.Default)] - private void Info(string thisOrContextObject, string? memberName, string? message) => - WriteEvent(InfoEventId, thisOrContextObject, memberName ?? MissingMember, message); - #endregion - - #region Error - /// Logs an error message. - /// `this`, or another object that serves to provide context for the operation. - /// The message to be logged. - /// The calling member. - [NonEvent] - public static void Error(object? thisOrContextObject, FormattableString formattableString, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(formattableString); - if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString)); - } - - /// Logs an error message. - /// `this`, or another object that serves to provide context for the operation. - /// The message to be logged. - /// The calling member. - [NonEvent] - public static void Error(object? thisOrContextObject, object message, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(message); - if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString()); - } - - [Event(ErrorEventId, Level = EventLevel.Error, Keywords = Keywords.Default)] - private void ErrorMessage(string thisOrContextObject, string? memberName, string? message) => - WriteEvent(ErrorEventId, thisOrContextObject, memberName ?? MissingMember, message); - #endregion - - #region DumpBuffer - /// Logs the contents of a buffer. - /// `this`, or another object that serves to provide context for the operation. - /// The buffer to be logged. - /// The calling member. - [NonEvent] - public static void DumpBuffer(object? thisOrContextObject, byte[] buffer, [CallerMemberName] string? memberName = null) - { - DumpBuffer(thisOrContextObject, buffer, 0, buffer.Length, memberName); - } - - /// Logs the contents of a buffer. - /// `this`, or another object that serves to provide context for the operation. - /// The buffer to be logged. - /// The starting offset from which to log. - /// The number of bytes to log. - /// The calling member. - [NonEvent] - public static void DumpBuffer(object? thisOrContextObject, byte[] buffer, int offset, int count, [CallerMemberName] string? memberName = null) - { - if (Log.IsEnabled() && offset >= 0 && offset <= buffer.Length - count) - { - count = Math.Min(count, MaxDumpSize); - - byte[] slice = buffer; - if (offset != 0 || count != buffer.Length) - { - slice = new byte[count]; - Buffer.BlockCopy(buffer, offset, slice, 0, count); - } - - Log.DumpBuffer(IdOf(thisOrContextObject), memberName, slice); - } - } - - /// Logs the contents of a buffer. - /// `this`, or another object that serves to provide context for the operation. - /// The starting location of the buffer to be logged. - /// The number of bytes to log. - /// The calling member. - [NonEvent] - public static unsafe void DumpBuffer(object? thisOrContextObject, IntPtr bufferPtr, int count, [CallerMemberName] string? memberName = null) - { - Debug.Assert(bufferPtr != IntPtr.Zero); - Debug.Assert(count >= 0); - - if (Log.IsEnabled()) - { - var buffer = new byte[Math.Min(count, MaxDumpSize)]; - fixed (byte* targetPtr = buffer) - { - Buffer.MemoryCopy((byte*)bufferPtr, targetPtr, buffer.Length, buffer.Length); - } - Log.DumpBuffer(IdOf(thisOrContextObject), memberName, buffer); - } - } - - [Event(DumpArrayEventId, Level = EventLevel.Verbose, Keywords = Keywords.Debug)] - private void DumpBuffer(string thisOrContextObject, string? memberName, byte[] buffer) => - WriteEvent(DumpArrayEventId, thisOrContextObject, memberName ?? MissingMember, buffer); - #endregion - - #region Associate - /// Logs a relationship between two objects. - /// The first object. - /// The second object. - /// The calling member. - [NonEvent] - public static void Associate(object first, object second, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(first); - DebugValidateArg(second); - if (Log.IsEnabled()) Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second)); - } - - /// Logs a relationship between two objects. - /// `this`, or another object that serves to provide context for the operation. - /// The first object. - /// The second object. - /// The calling member. - [NonEvent] - public static void Associate(object? thisOrContextObject, object first, object second, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(first); - DebugValidateArg(second); - if (Log.IsEnabled()) Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second)); - } - - [Event(AssociateEventId, Level = EventLevel.Informational, Keywords = Keywords.Default, Message = "[{2}]<-->[{3}]")] - private void Associate(string thisOrContextObject, string? memberName, string first, string second) => - WriteEvent(AssociateEventId, thisOrContextObject, memberName ?? MissingMember, first, second); - #endregion - #endregion - - #region Helpers - [Conditional("DEBUG_NETEVENTSOURCE_MISUSE")] - private static void DebugValidateArg(object? arg) - { - if (!Log.IsEnabled()) - { - Debug.Assert(!(arg is ValueType), $"Should not be passing value type {arg?.GetType()} to logging without IsEnabled check"); - Debug.Assert(!(arg is FormattableString), $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled"); - } - } - - [Conditional("DEBUG_NETEVENTSOURCE_MISUSE")] - private static void DebugValidateArg(FormattableString? arg) - { - Debug.Assert(Log.IsEnabled() || arg == null, $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled"); - } - - [NonEvent] - public static string IdOf(object? value) => value != null ? value.GetType().Name + "#" + GetHashCode(value) : NullInstance; - - [NonEvent] - public static int GetHashCode(object value) => value?.GetHashCode() ?? 0; - - [NonEvent] - public static object Format(object? value) - { - // If it's null, return a known string for null values - if (value == null) - { - return NullInstance; - } - - // Give another partial implementation a chance to provide its own string representation - string? result = null; - AdditionalCustomizedToString(value, ref result); - if (result != null) - { - return result; - } - - // Format arrays with their element type name and length - if (value is Array arr) - { - return $"{arr.GetType().GetElementType()}[{((Array)value).Length}]"; - } - - // Format ICollections as the name and count - if (value is ICollection c) - { - return $"{c.GetType().Name}({c.Count})"; - } - - // Format SafeHandles as their type, hash code, and pointer value - if (value is SafeHandle handle) - { - return $"{handle.GetType().Name}:{handle.GetHashCode()}(0x{handle.DangerousGetHandle():X})"; - } - - // Format IntPtrs as hex - if (value is IntPtr) - { - return $"0x{value:X}"; - } - - // If the string representation of the instance would just be its type name, - // use its id instead. - string? toString = value.ToString(); - if (toString == null || toString == value.GetType().FullName) - { - return IdOf(value); - } - - // Otherwise, return the original object so that the caller does default formatting. - return value; - } - - [NonEvent] - private static string Format(FormattableString s) - { - switch (s.ArgumentCount) - { - case 0: return s.Format; - case 1: return string.Format(CultureInfo.CurrentCulture, s.Format, Format(s.GetArgument(0))); - case 2: return string.Format(CultureInfo.CurrentCulture, s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1))); - case 3: return string.Format(CultureInfo.CurrentCulture, s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1)), Format(s.GetArgument(2))); - default: - object?[] args = s.GetArguments(); - object[] formattedArgs = new object[args.Length]; - for (int i = 0; i < args.Length; i++) - { - formattedArgs[i] = Format(args[i]); - } - return string.Format(CultureInfo.CurrentCulture, s.Format, formattedArgs); - } - } - - static partial void AdditionalCustomizedToString(T value, ref string? result); - #endregion - - #region Custom WriteEvent overloads - - [NonEvent] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Parameters passed to WriteEvent are all primitive values.")] - private unsafe void WriteEvent(int eventId, string? arg1, string? arg2, string? arg3, string? arg4) - { - if (IsEnabled()) - { - if (arg1 == null) arg1 = ""; - if (arg2 == null) arg2 = ""; - if (arg3 == null) arg3 = ""; - if (arg4 == null) arg4 = ""; - - fixed (char* string1Bytes = arg1) - fixed (char* string2Bytes = arg2) - fixed (char* string3Bytes = arg3) - fixed (char* string4Bytes = arg4) - { - const int NumEventDatas = 4; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)string1Bytes, - Size = ((arg1.Length + 1) * 2) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)string2Bytes, - Size = ((arg2.Length + 1) * 2) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)string3Bytes, - Size = ((arg3.Length + 1) * 2) - }; - descrs[3] = new EventData - { - DataPointer = (IntPtr)string4Bytes, - Size = ((arg4.Length + 1) * 2) - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } - - [NonEvent] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Parameters passed to WriteEvent are all primitive values.")] - private unsafe void WriteEvent(int eventId, string? arg1, string? arg2, byte[]? arg3) - { - if (IsEnabled()) - { - if (arg1 == null) arg1 = ""; - if (arg2 == null) arg2 = ""; - if (arg3 == null) arg3 = Array.Empty(); - - fixed (char* arg1Ptr = arg1) - fixed (char* arg2Ptr = arg2) - fixed (byte* arg3Ptr = arg3) - { - int bufferLength = arg3.Length; - const int NumEventDatas = 4; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)arg1Ptr, - Size = (arg1.Length + 1) * sizeof(char) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)arg2Ptr, - Size = (arg2.Length + 1) * sizeof(char) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(&bufferLength), - Size = 4 - }; - descrs[3] = new EventData - { - DataPointer = (IntPtr)arg3Ptr, - Size = bufferLength - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } - - [NonEvent] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Can safely serialize primitive arguments.")] - private unsafe void WriteEvent(int eventId, string? arg1, int arg2, int arg3, int arg4) - { - if (IsEnabled()) - { - if (arg1 == null) arg1 = ""; - - fixed (char* arg1Ptr = arg1) - { - const int NumEventDatas = 4; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)(arg1Ptr), - Size = (arg1.Length + 1) * sizeof(char) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)(&arg2), - Size = sizeof(int) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(&arg3), - Size = sizeof(int) - }; - descrs[3] = new EventData - { - DataPointer = (IntPtr)(&arg4), - Size = sizeof(int) - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } - - [NonEvent] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Can safely serialize primitive arguments.")] - private unsafe void WriteEvent(int eventId, string? arg1, int arg2, string? arg3) - { - if (IsEnabled()) - { - if (arg1 == null) arg1 = ""; - if (arg3 == null) arg3 = ""; - - fixed (char* arg1Ptr = arg1) - fixed (char* arg3Ptr = arg3) - { - const int NumEventDatas = 3; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)(arg1Ptr), - Size = (arg1.Length + 1) * sizeof(char) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)(&arg2), - Size = sizeof(int) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(arg3Ptr), - Size = (arg3.Length + 1) * sizeof(char) - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } - - [NonEvent] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Can safely serialize primitive arguments.")] - private unsafe void WriteEvent(int eventId, string? arg1, string? arg2, int arg3) - { - if (IsEnabled()) - { - if (arg1 == null) arg1 = ""; - if (arg2 == null) arg2 = ""; - - fixed (char* arg1Ptr = arg1) - fixed (char* arg2Ptr = arg2) - { - const int NumEventDatas = 3; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)(arg1Ptr), - Size = (arg1.Length + 1) * sizeof(char) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)(arg2Ptr), - Size = (arg2.Length + 1) * sizeof(char) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(&arg3), - Size = sizeof(int) - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } - - [NonEvent] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Can safely serialize primitive arguments.")] - private unsafe void WriteEvent(int eventId, string? arg1, string? arg2, string? arg3, int arg4) - { - if (IsEnabled()) - { - if (arg1 == null) arg1 = ""; - if (arg2 == null) arg2 = ""; - if (arg3 == null) arg3 = ""; - - fixed (char* arg1Ptr = arg1) - fixed (char* arg2Ptr = arg2) - fixed (char* arg3Ptr = arg3) - { - const int NumEventDatas = 4; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)(arg1Ptr), - Size = (arg1.Length + 1) * sizeof(char) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)(arg2Ptr), - Size = (arg2.Length + 1) * sizeof(char) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(arg3Ptr), - Size = (arg3.Length + 1) * sizeof(char) - }; - descrs[3] = new EventData - { - DataPointer = (IntPtr)(&arg4), - Size = sizeof(int) - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } - #endregion - } -} diff --git a/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.Associate.cs b/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.Associate.cs new file mode 100644 index 00000000000000..b63eda98b68180 --- /dev/null +++ b/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.Associate.cs @@ -0,0 +1,82 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.Tracing; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Diagnostics; + +namespace System.Net +{ + internal sealed partial class NetEventSource + { + private const int AssociateEventId = 3; + + /// Logs a relationship between two objects. + /// The first object. + /// The second object. + /// The calling member. + [NonEvent] + public static void Associate(object first, object second, [CallerMemberName] string? memberName = null) => + Associate(first, first, second, memberName); + + /// Logs a relationship between two objects. + /// `this`, or another object that serves to provide context for the operation. + /// The first object. + /// The second object. + /// The calling member. + [NonEvent] + public static void Associate(object? thisOrContextObject, object first, object second, [CallerMemberName] string? memberName = null) => + Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second)); + + [Event(AssociateEventId, Level = EventLevel.Informational, Keywords = Keywords.Default, Message = "[{2}]<-->[{3}]")] + private void Associate(string thisOrContextObject, string? memberName, string first, string second) + { + Debug.Assert(IsEnabled()); + WriteEvent(AssociateEventId, thisOrContextObject, memberName ?? MissingMember, first, second); + } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", + Justification = EventSourceSuppressMessage)] + [NonEvent] + private unsafe void WriteEvent(int eventId, string? arg1, string? arg2, string? arg3, string? arg4) + { + arg1 ??= ""; + arg2 ??= ""; + arg3 ??= ""; + arg4 ??= ""; + + fixed (char* string1Bytes = arg1) + fixed (char* string2Bytes = arg2) + fixed (char* string3Bytes = arg3) + fixed (char* string4Bytes = arg4) + { + const int NumEventDatas = 4; + EventData* descrs = stackalloc EventData[NumEventDatas]; + + descrs[0] = new EventData + { + DataPointer = (IntPtr)string1Bytes, + Size = ((arg1.Length + 1) * 2) + }; + descrs[1] = new EventData + { + DataPointer = (IntPtr)string2Bytes, + Size = ((arg2.Length + 1) * 2) + }; + descrs[2] = new EventData + { + DataPointer = (IntPtr)string3Bytes, + Size = ((arg3.Length + 1) * 2) + }; + descrs[3] = new EventData + { + DataPointer = (IntPtr)string4Bytes, + Size = ((arg4.Length + 1) * 2) + }; + + WriteEventCore(eventId, NumEventDatas, descrs); + } + } + } +} diff --git a/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.DumpBuffer.cs b/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.DumpBuffer.cs new file mode 100644 index 00000000000000..8ddcaeb6253154 --- /dev/null +++ b/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.DumpBuffer.cs @@ -0,0 +1,83 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.Tracing; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace System.Net +{ + internal sealed partial class NetEventSource + { + private const int DumpArrayEventId = 4; + private const int MaxDumpSize = 1024; + + [NonEvent] + public static void DumpBuffer(object? thisOrContextObject, byte[] buffer, [CallerMemberName] string? memberName = null) => + DumpBuffer(thisOrContextObject, buffer.AsSpan(), memberName); + + /// Logs the contents of a buffer. + /// `this`, or another object that serves to provide context for the operation. + /// The buffer to be logged. + /// The starting offset from which to log. + /// The number of bytes to log. + /// The calling member. + [NonEvent] + public static void DumpBuffer(object? thisOrContextObject, byte[] buffer, int offset, int count, [CallerMemberName] string? memberName = null) => + DumpBuffer(thisOrContextObject, buffer.AsSpan(offset, count), memberName); + + /// Logs the contents of a buffer. + /// `this`, or another object that serves to provide context for the operation. + /// The buffer to be logged. + /// The calling member. + [NonEvent] + public static void DumpBuffer(object? thisOrContextObject, ReadOnlySpan buffer, [CallerMemberName] string? memberName = null) => + Log.DumpBuffer(IdOf(thisOrContextObject), memberName, buffer.Slice(0, Math.Min(buffer.Length, MaxDumpSize)).ToArray()); + + [Event(DumpArrayEventId, Level = EventLevel.Verbose, Keywords = Keywords.Debug)] + private unsafe void DumpBuffer(string thisOrContextObject, string? memberName, byte[] buffer) => + WriteEvent(DumpArrayEventId, thisOrContextObject, memberName ?? MissingMember, buffer); + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", + Justification = EventSourceSuppressMessage)] + [NonEvent] + private unsafe void WriteEvent(int eventId, string? arg1, string? arg2, byte[]? arg3) + { + arg1 ??= ""; + arg2 ??= ""; + arg3 ??= Array.Empty(); + + fixed (char* arg1Ptr = arg1) + fixed (char* arg2Ptr = arg2) + fixed (byte* arg3Ptr = arg3) + { + int bufferLength = arg3.Length; + const int NumEventDatas = 4; + EventData* descrs = stackalloc EventData[NumEventDatas]; + + descrs[0] = new EventData + { + DataPointer = (IntPtr)arg1Ptr, + Size = (arg1.Length + 1) * sizeof(char) + }; + descrs[1] = new EventData + { + DataPointer = (IntPtr)arg2Ptr, + Size = (arg2.Length + 1) * sizeof(char) + }; + descrs[2] = new EventData + { + DataPointer = (IntPtr)(&bufferLength), + Size = 4 + }; + descrs[3] = new EventData + { + DataPointer = (IntPtr)arg3Ptr, + Size = bufferLength + }; + + WriteEventCore(eventId, NumEventDatas, descrs); + } + } + } +} diff --git a/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs b/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs index b61309980ec36a..8dadcacb9be91f 100644 --- a/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs +++ b/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs @@ -1,16 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#if DEBUG -// Uncomment to enable runtime checks to help validate that NetEventSource isn't being misused -// in a way that will cause performance problems, e.g. unexpected boxing of value types. -//#define DEBUG_NETEVENTSOURCE_MISUSE -#endif - using System.Collections; using System.Diagnostics; -using System.Diagnostics.Tracing; using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.Tracing; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -48,71 +42,44 @@ public static class Keywords { public const EventKeywords Default = (EventKeywords)0x0001; public const EventKeywords Debug = (EventKeywords)0x0002; - - // No longer used: - // EnterExit = (EventKeywords)0x0004; } private const string MissingMember = "(?)"; private const string NullInstance = "(null)"; private const string StaticMethodObject = "(static)"; private const string NoParameters = ""; - private const int MaxDumpSize = 1024; - - // No longer used: - // EnterEventId = 1; - // ExitEventId = 2; - - private const int AssociateEventId = 3; - private const int InfoEventId = 4; - private const int ErrorEventId = 5; - private const int VerboseEventId = 6; - private const int DumpArrayEventId = 7; - - // These events are implemented in NetEventSource.Security.cs. - // Define the ids here so that projects that include NetEventSource.Security.cs will not have conflicts. - private const int EnumerateSecurityPackagesId = 8; - private const int SspiPackageNotFoundId = 9; - private const int AcquireDefaultCredentialId = 10; - private const int AcquireCredentialsHandleId = 11; - private const int InitializeSecurityContextId = 12; - private const int SecurityContextInputBufferId = 13; - private const int SecurityContextInputBuffersId = 14; - private const int AcceptSecuritContextId = 15; - private const int OperationReturnedSomethingId = 16; - - private const int NextAvailableEventId = 17; // Update this value whenever new events are added. Derived types should base all events off of this to avoid conflicts. + + private const int InfoEventId = 1; + private const int ErrorEventId = 2; + // private const int AssociateEventId = 3; // Defined in NetEventSource.Common.Associate.cs + // private const int DumpArrayEventId = 4; // Defined in NetEventSource.Common.DumpBuffer.cs + + private const int NextAvailableEventId = 5; // Update this value whenever new events are added. Derived types should base all events off of this to avoid conflicts. #endregion - #region Events #region Info /// Logs an information message. /// `this`, or another object that serves to provide context for the operation. /// The message to be logged. /// The calling member. [NonEvent] - public static void Info(object? thisOrContextObject, FormattableString? formattableString = null, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(formattableString); - if (Log.IsEnabled()) Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters); - } + public static void Info(object? thisOrContextObject, FormattableString? formattableString = null, [CallerMemberName] string? memberName = null) => + Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters); /// Logs an information message. /// `this`, or another object that serves to provide context for the operation. /// The message to be logged. /// The calling member. [NonEvent] - public static void Info(object? thisOrContextObject, object? message, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(message); - if (Log.IsEnabled()) Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString()); - } + public static void Info(object? thisOrContextObject, object? message, [CallerMemberName] string? memberName = null) => + Log.Info(IdOf(thisOrContextObject), memberName, Format(message)); [Event(InfoEventId, Level = EventLevel.Informational, Keywords = Keywords.Default)] - private void Info(string thisOrContextObject, string? memberName, string? message) => + private void Info(string thisOrContextObject, string? memberName, string? message) + { + Debug.Assert(IsEnabled()); WriteEvent(InfoEventId, thisOrContextObject, memberName ?? MissingMember, message); + } #endregion #region Error @@ -121,172 +88,26 @@ private void Info(string thisOrContextObject, string? memberName, string? messag /// The message to be logged. /// The calling member. [NonEvent] - public static void Error(object? thisOrContextObject, FormattableString formattableString, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(formattableString); - if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString)); - } + public static void Error(object? thisOrContextObject, FormattableString formattableString, [CallerMemberName] string? memberName = null) => + Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString)); /// Logs an error message. /// `this`, or another object that serves to provide context for the operation. /// The message to be logged. /// The calling member. [NonEvent] - public static void Error(object? thisOrContextObject, object message, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(message); - if (Log.IsEnabled()) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString()); - } + public static void Error(object? thisOrContextObject, object message, [CallerMemberName] string? memberName = null) => + Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message)); [Event(ErrorEventId, Level = EventLevel.Error, Keywords = Keywords.Default)] - private void ErrorMessage(string thisOrContextObject, string? memberName, string? message) => - WriteEvent(ErrorEventId, thisOrContextObject, memberName ?? MissingMember, message); - #endregion - - #region Verbose - /// Logs an info message at verbose mode. - /// `this`, or another object that serves to provide context for the operation. - /// The message to be logged. - /// The calling member. - [NonEvent] - public static void Verbose(object? thisOrContextObject, FormattableString formattableString, [CallerMemberName] string? memberName = null) + private void ErrorMessage(string thisOrContextObject, string? memberName, string? message) { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(formattableString); - if (Log.IsEnabled()) Log.VerboseMessage(IdOf(thisOrContextObject), memberName, Format(formattableString)); - } - - /// Logs an info at verbose mode. - /// `this`, or another object that serves to provide context for the operation. - /// The message to be logged. - /// The calling member. - [NonEvent] - public static void Verbose(object? thisOrContextObject, object message, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(message); - if (Log.IsEnabled()) Log.VerboseMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString()); - } - - [Event(VerboseEventId, Level = EventLevel.Verbose, Keywords = Keywords.Default)] - private void VerboseMessage(string thisOrContextObject, string? memberName, string? message) => - WriteEvent(VerboseEventId, thisOrContextObject, memberName ?? MissingMember, message); - #endregion - - #region DumpBuffer - /// Logs the contents of a buffer. - /// `this`, or another object that serves to provide context for the operation. - /// The buffer to be logged. - /// The calling member. - [NonEvent] - public static void DumpBuffer(object? thisOrContextObject, byte[] buffer, [CallerMemberName] string? memberName = null) - { - DumpBuffer(thisOrContextObject, buffer, 0, buffer.Length, memberName); - } - - /// Logs the contents of a buffer. - /// `this`, or another object that serves to provide context for the operation. - /// The buffer to be logged. - /// The starting offset from which to log. - /// The number of bytes to log. - /// The calling member. - [NonEvent] - public static void DumpBuffer(object? thisOrContextObject, byte[] buffer, int offset, int count, [CallerMemberName] string? memberName = null) - { - if (Log.IsEnabled() && offset >= 0 && offset <= buffer.Length - count) - { - count = Math.Min(count, MaxDumpSize); - - byte[] slice = buffer; - if (offset != 0 || count != buffer.Length) - { - slice = new byte[count]; - Buffer.BlockCopy(buffer, offset, slice, 0, count); - } - - Log.DumpBuffer(IdOf(thisOrContextObject), memberName, slice); - } - } - - /// Logs the contents of a buffer. - /// `this`, or another object that serves to provide context for the operation. - /// The starting location of the buffer to be logged. - /// The number of bytes to log. - /// The calling member. - [NonEvent] - public static unsafe void DumpBuffer(object? thisOrContextObject, IntPtr bufferPtr, int count, [CallerMemberName] string? memberName = null) - { - Debug.Assert(bufferPtr != IntPtr.Zero); - Debug.Assert(count >= 0); - - if (Log.IsEnabled()) - { - var buffer = new byte[Math.Min(count, MaxDumpSize)]; - fixed (byte* targetPtr = buffer) - { - Buffer.MemoryCopy((byte*)bufferPtr, targetPtr, buffer.Length, buffer.Length); - } - Log.DumpBuffer(IdOf(thisOrContextObject), memberName, buffer); - } - } - - [Event(DumpArrayEventId, Level = EventLevel.Verbose, Keywords = Keywords.Debug)] - private void DumpBuffer(string thisOrContextObject, string? memberName, byte[] buffer) => - WriteEvent(DumpArrayEventId, thisOrContextObject, memberName ?? MissingMember, buffer); - #endregion - - #region Associate - /// Logs a relationship between two objects. - /// The first object. - /// The second object. - /// The calling member. - [NonEvent] - public static void Associate(object first, object second, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(first); - DebugValidateArg(second); - if (Log.IsEnabled()) Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second)); - } - - /// Logs a relationship between two objects. - /// `this`, or another object that serves to provide context for the operation. - /// The first object. - /// The second object. - /// The calling member. - [NonEvent] - public static void Associate(object? thisOrContextObject, object first, object second, [CallerMemberName] string? memberName = null) - { - DebugValidateArg(thisOrContextObject); - DebugValidateArg(first); - DebugValidateArg(second); - if (Log.IsEnabled()) Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second)); + Debug.Assert(IsEnabled()); + WriteEvent(ErrorEventId, thisOrContextObject, memberName ?? MissingMember, message); } - - [Event(AssociateEventId, Level = EventLevel.Informational, Keywords = Keywords.Default, Message = "[{2}]<-->[{3}]")] - private void Associate(string thisOrContextObject, string? memberName, string first, string second) => - WriteEvent(AssociateEventId, thisOrContextObject, memberName ?? MissingMember, first, second); - #endregion #endregion #region Helpers - [Conditional("DEBUG_NETEVENTSOURCE_MISUSE")] - private static void DebugValidateArg(object? arg) - { - if (!Log.IsEnabled()) - { - Debug.Assert(!(arg is ValueType), $"Should not be passing value type {arg?.GetType()} to logging without IsEnabled check"); - Debug.Assert(!(arg is FormattableString), $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled"); - } - } - - [Conditional("DEBUG_NETEVENTSOURCE_MISUSE")] - private static void DebugValidateArg(FormattableString? arg) - { - Debug.Assert(Log.IsEnabled() || arg == null, $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled"); - } - [NonEvent] public static string IdOf(object? value) => value != null ? value.GetType().Name + "#" + GetHashCode(value) : NullInstance; @@ -294,7 +115,7 @@ private static void DebugValidateArg(FormattableString? arg) public static int GetHashCode(object? value) => value?.GetHashCode() ?? 0; [NonEvent] - public static object Format(object? value) + public static string? Format(object? value) { // If it's null, return a known string for null values if (value == null) @@ -305,7 +126,7 @@ public static object Format(object? value) // Give another partial implementation a chance to provide its own string representation string? result = null; AdditionalCustomizedToString(value, ref result); - if (result != null) + if (result is not null) { return result; } @@ -343,7 +164,7 @@ public static object Format(object? value) } // Otherwise, return the original object so that the caller does default formatting. - return value; + return value.ToString(); } [NonEvent] @@ -356,376 +177,50 @@ private static string Format(FormattableString s) case 2: return string.Format(s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1))); case 3: return string.Format(s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1)), Format(s.GetArgument(2))); default: - object?[] args = s.GetArguments(); - object[] formattedArgs = new object[args.Length]; - for (int i = 0; i < args.Length; i++) + string?[] formattedArgs = new string?[s.ArgumentCount]; + for (int i = 0; i < formattedArgs.Length; i++) { - formattedArgs[i] = Format(args[i]); + formattedArgs[i] = Format(s.GetArgument(i)); } return string.Format(s.Format, formattedArgs); } } - static partial void AdditionalCustomizedToString(T value, ref string? result); + static partial void AdditionalCustomizedToString(object value, ref string? result); #endregion - #region Custom WriteEvent overloads - - [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", - Justification = EventSourceSuppressMessage)] - [NonEvent] - private unsafe void WriteEvent(int eventId, string? arg1, string? arg2, string? arg3, string? arg4) - { - if (Log.IsEnabled()) - { - arg1 ??= ""; - arg2 ??= ""; - arg3 ??= ""; - arg4 ??= ""; - - fixed (char* string1Bytes = arg1) - fixed (char* string2Bytes = arg2) - fixed (char* string3Bytes = arg3) - fixed (char* string4Bytes = arg4) - { - const int NumEventDatas = 4; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)string1Bytes, - Size = ((arg1.Length + 1) * 2) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)string2Bytes, - Size = ((arg2.Length + 1) * 2) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)string3Bytes, - Size = ((arg3.Length + 1) * 2) - }; - descrs[3] = new EventData - { - DataPointer = (IntPtr)string4Bytes, - Size = ((arg4.Length + 1) * 2) - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } - - [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", - Justification = EventSourceSuppressMessage)] - [NonEvent] - private unsafe void WriteEvent(int eventId, string? arg1, string? arg2, byte[]? arg3) - { - if (Log.IsEnabled()) - { - arg1 ??= ""; - arg2 ??= ""; - arg3 ??= Array.Empty(); - - fixed (char* arg1Ptr = arg1) - fixed (char* arg2Ptr = arg2) - fixed (byte* arg3Ptr = arg3) - { - int bufferLength = arg3.Length; - const int NumEventDatas = 4; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)arg1Ptr, - Size = (arg1.Length + 1) * sizeof(char) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)arg2Ptr, - Size = (arg2.Length + 1) * sizeof(char) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(&bufferLength), - Size = 4 - }; - descrs[3] = new EventData - { - DataPointer = (IntPtr)arg3Ptr, - Size = bufferLength - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } - - [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", - Justification = EventSourceSuppressMessage)] - [NonEvent] - private unsafe void WriteEvent(int eventId, string? arg1, int arg2, int arg3, int arg4) - { - if (Log.IsEnabled()) - { - arg1 ??= ""; - - fixed (char* arg1Ptr = arg1) - { - const int NumEventDatas = 4; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)(arg1Ptr), - Size = (arg1.Length + 1) * sizeof(char) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)(&arg2), - Size = sizeof(int) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(&arg3), - Size = sizeof(int) - }; - descrs[3] = new EventData - { - DataPointer = (IntPtr)(&arg4), - Size = sizeof(int) - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } - - [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", - Justification = EventSourceSuppressMessage)] - [NonEvent] - private unsafe void WriteEvent(int eventId, string? arg1, int arg2, string? arg3) - { - if (Log.IsEnabled()) - { - arg1 ??= ""; - arg3 ??= ""; - - fixed (char* arg1Ptr = arg1) - fixed (char* arg3Ptr = arg3) - { - const int NumEventDatas = 3; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)(arg1Ptr), - Size = (arg1.Length + 1) * sizeof(char) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)(&arg2), - Size = sizeof(int) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(arg3Ptr), - Size = (arg3.Length + 1) * sizeof(char) - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } - [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] [NonEvent] private unsafe void WriteEvent(int eventId, string? arg1, string? arg2, int arg3) { - if (Log.IsEnabled()) - { - arg1 ??= ""; - arg2 ??= ""; - - fixed (char* arg1Ptr = arg1) - fixed (char* arg2Ptr = arg2) - { - const int NumEventDatas = 3; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)(arg1Ptr), - Size = (arg1.Length + 1) * sizeof(char) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)(arg2Ptr), - Size = (arg2.Length + 1) * sizeof(char) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(&arg3), - Size = sizeof(int) - }; + arg1 ??= ""; + arg2 ??= ""; - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } - - [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", - Justification = EventSourceSuppressMessage)] - [NonEvent] - private unsafe void WriteEvent(int eventId, string? arg1, string? arg2, string? arg3, int arg4) - { - if (Log.IsEnabled()) + fixed (char* arg1Ptr = arg1) + fixed (char* arg2Ptr = arg2) { - arg1 ??= ""; - arg2 ??= ""; - arg3 ??= ""; + const int NumEventDatas = 3; + EventData* descrs = stackalloc EventData[NumEventDatas]; - fixed (char* arg1Ptr = arg1) - fixed (char* arg2Ptr = arg2) - fixed (char* arg3Ptr = arg3) + descrs[0] = new EventData { - const int NumEventDatas = 4; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)(arg1Ptr), - Size = (arg1.Length + 1) * sizeof(char) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)(arg2Ptr), - Size = (arg2.Length + 1) * sizeof(char) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(arg3Ptr), - Size = (arg3.Length + 1) * sizeof(char) - }; - descrs[3] = new EventData - { - DataPointer = (IntPtr)(&arg4), - Size = sizeof(int) - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } - - [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", - Justification = EventSourceSuppressMessage)] - [NonEvent] - private unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8) - { - if (Log.IsEnabled()) - { - arg1 ??= ""; - - fixed (char* arg1Ptr = arg1) + DataPointer = (IntPtr)(arg1Ptr), + Size = (arg1.Length + 1) * sizeof(char) + }; + descrs[1] = new EventData { - const int NumEventDatas = 8; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)(arg1Ptr), - Size = (arg1.Length + 1) * sizeof(char) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)(&arg2), - Size = sizeof(int) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(&arg3), - Size = sizeof(int) - }; - descrs[3] = new EventData - { - DataPointer = (IntPtr)(&arg4), - Size = sizeof(int) - }; - descrs[4] = new EventData - { - DataPointer = (IntPtr)(&arg5), - Size = sizeof(int) - }; - descrs[5] = new EventData - { - DataPointer = (IntPtr)(&arg6), - Size = sizeof(int) - }; - descrs[6] = new EventData - { - DataPointer = (IntPtr)(&arg7), - Size = sizeof(int) - }; - descrs[7] = new EventData - { - DataPointer = (IntPtr)(&arg8), - Size = sizeof(int) - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } - - [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", - Justification = EventSourceSuppressMessage)] - [NonEvent] - private unsafe void WriteEvent(int eventId, string arg1, string arg2, int arg3, int arg4, int arg5) - { - if (Log.IsEnabled()) - { - arg1 ??= ""; - arg2 ??= ""; - - fixed (char* arg1Ptr = arg1) - fixed (char* arg2Ptr = arg2) + DataPointer = (IntPtr)(arg2Ptr), + Size = (arg2.Length + 1) * sizeof(char) + }; + descrs[2] = new EventData { - const int NumEventDatas = 5; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)(arg1Ptr), - Size = (arg1.Length + 1) * sizeof(char) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)(arg2Ptr), - Size = (arg2.Length + 1) * sizeof(char) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(&arg3), - Size = sizeof(int) - }; - descrs[3] = new EventData - { - DataPointer = (IntPtr)(&arg4), - Size = sizeof(int) - }; - descrs[4] = new EventData - { - DataPointer = (IntPtr)(&arg5), - Size = sizeof(int) - }; + DataPointer = (IntPtr)(&arg3), + Size = sizeof(int) + }; - WriteEventCore(eventId, NumEventDatas, descrs); - } + WriteEventCore(eventId, NumEventDatas, descrs); } } - #endregion } } diff --git a/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.Windows.cs b/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.Windows.cs index 77ef71b94d3592..c1bad7d5963db6 100644 --- a/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.Windows.cs +++ b/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.Windows.cs @@ -9,55 +9,51 @@ namespace System.Net { internal sealed partial class NetEventSource { + private const int EnumerateSecurityPackagesId = NextAvailableEventId; + private const int SspiPackageNotFoundId = EnumerateSecurityPackagesId + 1; + private const int AcquireDefaultCredentialId = SspiPackageNotFoundId + 1; + private const int AcquireCredentialsHandleId = AcquireDefaultCredentialId + 1; + private const int InitializeSecurityContextId = AcquireCredentialsHandleId + 1; + private const int SecurityContextInputBufferId = InitializeSecurityContextId + 1; + private const int SecurityContextInputBuffersId = SecurityContextInputBufferId + 1; + private const int AcceptSecuritContextId = SecurityContextInputBuffersId + 1; + private const int OperationReturnedSomethingId = AcceptSecuritContextId + 1; + // Make sure to update the event IDs in NetEventSource.Security.cs if you add more events here + + [Event(EnumerateSecurityPackagesId, Keywords = Keywords.Default, Level = EventLevel.Informational)] + public void EnumerateSecurityPackages(string? securityPackage) => + WriteEvent(EnumerateSecurityPackagesId, securityPackage); + + [Event(SspiPackageNotFoundId, Keywords = Keywords.Default, Level = EventLevel.Informational)] + public void SspiPackageNotFound(string packageName) => + WriteEvent(SspiPackageNotFoundId, packageName); + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "parameter intent is an enum and is trimmer safe")] [Event(AcquireDefaultCredentialId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void AcquireDefaultCredential(string packageName, Interop.SspiCli.CredentialUse intent) - { - if (IsEnabled()) - { - WriteEvent(AcquireDefaultCredentialId, packageName, intent); - } - } + public void AcquireDefaultCredential(string packageName, Interop.SspiCli.CredentialUse intent) => + WriteEvent(AcquireDefaultCredentialId, packageName, intent); [NonEvent] - public void AcquireCredentialsHandle(string packageName, Interop.SspiCli.CredentialUse intent, object authdata) - { - if (IsEnabled()) - { - AcquireCredentialsHandle(packageName, intent, IdOf(authdata)); - } - } + public void AcquireCredentialsHandle(string packageName, Interop.SspiCli.CredentialUse intent, object authdata) => + AcquireCredentialsHandle(packageName, intent, IdOf(authdata)); [Event(AcquireCredentialsHandleId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void AcquireCredentialsHandle(string packageName, Interop.SspiCli.CredentialUse intent, string authdata) - { - if (IsEnabled()) - { - WriteEvent(AcquireCredentialsHandleId, packageName, (int)intent, authdata); - } - } + public void AcquireCredentialsHandle(string packageName, Interop.SspiCli.CredentialUse intent, string authdata) => + WriteEvent(AcquireCredentialsHandleId, packageName, (int)intent, authdata); [NonEvent] - public void InitializeSecurityContext(SafeFreeCredentials? credential, SafeDeleteContext? context, string? targetName, Interop.SspiCli.ContextFlags inFlags) - { - if (IsEnabled()) - { - InitializeSecurityContext(IdOf(credential), IdOf(context), targetName, inFlags); - } - } + public void InitializeSecurityContext(SafeFreeCredentials? credential, SafeDeleteContext? context, string? targetName, Interop.SspiCli.ContextFlags inFlags) => + InitializeSecurityContext(IdOf(credential), IdOf(context), targetName, inFlags); + [Event(InitializeSecurityContextId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private void InitializeSecurityContext(string? credential, string? context, string? targetName, Interop.SspiCli.ContextFlags inFlags) => + private void InitializeSecurityContext(string credential, string context, string? targetName, Interop.SspiCli.ContextFlags inFlags) => WriteEvent(InitializeSecurityContextId, credential, context, targetName, (int)inFlags); [NonEvent] - public void AcceptSecurityContext(SafeFreeCredentials? credential, SafeDeleteContext? context, Interop.SspiCli.ContextFlags inFlags) - { - if (IsEnabled()) - { - AcceptSecurityContext(IdOf(credential), IdOf(context), inFlags); - } - } + public void AcceptSecurityContext(SafeFreeCredentials? credential, SafeDeleteContext? context, Interop.SspiCli.ContextFlags inFlags) => + AcceptSecurityContext(IdOf(credential), IdOf(context), inFlags); + [Event(AcceptSecuritContextId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void AcceptSecurityContext(string credential, string context, Interop.SspiCli.ContextFlags inFlags) => WriteEvent(AcceptSecuritContextId, credential, context, (int)inFlags); @@ -65,31 +61,126 @@ private void AcceptSecurityContext(string credential, string context, Interop.Ss [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "parameter errorCode is an enum and is trimmer safe")] [Event(OperationReturnedSomethingId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void OperationReturnedSomething(string operation, Interop.SECURITY_STATUS errorCode) + public void OperationReturnedSomething(string operation, Interop.SECURITY_STATUS errorCode) => + WriteEvent(OperationReturnedSomethingId, operation, errorCode); + + [Event(SecurityContextInputBufferId, Keywords = Keywords.Default, Level = EventLevel.Informational)] + public void SecurityContextInputBuffer(string context, int inputBufferSize, int outputBufferSize, Interop.SECURITY_STATUS errorCode) => + WriteEvent(SecurityContextInputBufferId, context, inputBufferSize, outputBufferSize, (int)errorCode); + + [Event(SecurityContextInputBuffersId, Keywords = Keywords.Default, Level = EventLevel.Informational)] + public void SecurityContextInputBuffers(string context, int inputBuffersSize, int outputBufferSize, Interop.SECURITY_STATUS errorCode) => + WriteEvent(SecurityContextInputBuffersId, context, inputBuffersSize, outputBufferSize, (int)errorCode); + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", + Justification = EventSourceSuppressMessage)] + [NonEvent] + private unsafe void WriteEvent(int eventId, string? arg1, int arg2, int arg3, int arg4) { - if (IsEnabled()) + arg1 ??= ""; + + fixed (char* arg1Ptr = arg1) { - WriteEvent(OperationReturnedSomethingId, operation, errorCode); + const int NumEventDatas = 4; + EventData* descrs = stackalloc EventData[NumEventDatas]; + + descrs[0] = new EventData + { + DataPointer = (IntPtr)(arg1Ptr), + Size = (arg1.Length + 1) * sizeof(char) + }; + descrs[1] = new EventData + { + DataPointer = (IntPtr)(&arg2), + Size = sizeof(int) + }; + descrs[2] = new EventData + { + DataPointer = (IntPtr)(&arg3), + Size = sizeof(int) + }; + descrs[3] = new EventData + { + DataPointer = (IntPtr)(&arg4), + Size = sizeof(int) + }; + + WriteEventCore(eventId, NumEventDatas, descrs); } } - [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", - Justification = "parameter errorCode is an enum and is trimmer safe")] - [Event(SecurityContextInputBufferId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void SecurityContextInputBuffer(string context, int inputBufferSize, int outputBufferSize, Interop.SECURITY_STATUS errorCode) + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", + Justification = EventSourceSuppressMessage)] + [NonEvent] + private unsafe void WriteEvent(int eventId, string? arg1, int arg2, string? arg3) { - if (IsEnabled()) + arg1 ??= ""; + arg3 ??= ""; + + fixed (char* arg1Ptr = arg1) + fixed (char* arg3Ptr = arg3) { - WriteEvent(SecurityContextInputBufferId, context, inputBufferSize, outputBufferSize, (int)errorCode); + const int NumEventDatas = 3; + EventData* descrs = stackalloc EventData[NumEventDatas]; + + descrs[0] = new EventData + { + DataPointer = (IntPtr)(arg1Ptr), + Size = (arg1.Length + 1) * sizeof(char) + }; + descrs[1] = new EventData + { + DataPointer = (IntPtr)(&arg2), + Size = sizeof(int) + }; + descrs[2] = new EventData + { + DataPointer = (IntPtr)(arg3Ptr), + Size = (arg3.Length + 1) * sizeof(char) + }; + + WriteEventCore(eventId, NumEventDatas, descrs); } } - [Event(SecurityContextInputBuffersId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void SecurityContextInputBuffers(string context, int inputBuffersSize, int outputBufferSize, Interop.SECURITY_STATUS errorCode) + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", + Justification = EventSourceSuppressMessage)] + [NonEvent] + private unsafe void WriteEvent(int eventId, string? arg1, string? arg2, string? arg3, int arg4) { - if (IsEnabled()) + arg1 ??= ""; + arg2 ??= ""; + arg3 ??= ""; + + fixed (char* arg1Ptr = arg1) + fixed (char* arg2Ptr = arg2) + fixed (char* arg3Ptr = arg3) { - WriteEvent(SecurityContextInputBuffersId, context, inputBuffersSize, outputBufferSize, (int)errorCode); + const int NumEventDatas = 4; + EventData* descrs = stackalloc EventData[NumEventDatas]; + + descrs[0] = new EventData + { + DataPointer = (IntPtr)(arg1Ptr), + Size = (arg1.Length + 1) * sizeof(char) + }; + descrs[1] = new EventData + { + DataPointer = (IntPtr)(arg2Ptr), + Size = (arg2.Length + 1) * sizeof(char) + }; + descrs[2] = new EventData + { + DataPointer = (IntPtr)(arg3Ptr), + Size = (arg3.Length + 1) * sizeof(char) + }; + descrs[3] = new EventData + { + DataPointer = (IntPtr)(&arg4), + Size = sizeof(int) + }; + + WriteEventCore(eventId, NumEventDatas, descrs); } } } diff --git a/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.cs b/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.cs deleted file mode 100644 index e73296532a9d8d..00000000000000 --- a/src/libraries/Common/src/System/Net/Security/NetEventSource.Security.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System.Diagnostics.Tracing; -using System.Globalization; -using System.Net.Security; -using System.Security.Authentication; -using System.Security.Cryptography.X509Certificates; - -namespace System.Net -{ - internal sealed partial class NetEventSource - { - // Event ids are defined in NetEventSource.Common.cs. - - [Event(EnumerateSecurityPackagesId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void EnumerateSecurityPackages(string? securityPackage) - { - if (IsEnabled()) - { - WriteEvent(EnumerateSecurityPackagesId, securityPackage ?? ""); - } - } - - [Event(SspiPackageNotFoundId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void SspiPackageNotFound(string packageName) - { - if (IsEnabled()) - { - WriteEvent(SspiPackageNotFoundId, packageName ?? ""); - } - } - } -} diff --git a/src/libraries/Common/tests/TestUtilities/TestEventListener.cs b/src/libraries/Common/tests/TestUtilities/TestEventListener.cs index e41987992c80b6..08effe41433246 100644 --- a/src/libraries/Common/tests/TestUtilities/TestEventListener.cs +++ b/src/libraries/Common/tests/TestUtilities/TestEventListener.cs @@ -35,7 +35,6 @@ public sealed class TestEventListener : EventListener "Private.InternalDiagnostics.System.Net.HttpListener", "Private.InternalDiagnostics.System.Net.Mail", "Private.InternalDiagnostics.System.Net.NetworkInformation", - "Private.InternalDiagnostics.System.Net.Ping", "Private.InternalDiagnostics.System.Net.Primitives", "Private.InternalDiagnostics.System.Net.Requests", }; diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/NetEventSource.WinHttpHandler.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/NetEventSource.WinHttpHandler.cs index daac483268a70b..0af41d190fca8e 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/NetEventSource.WinHttpHandler.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/NetEventSource.WinHttpHandler.cs @@ -6,7 +6,5 @@ namespace System.Net { [EventSource(Name = "Private.InternalDiagnostics.System.Net.Http.WinHttpHandler", LocalizationResources = "FxResources.System.Net.Http.WinHttpHandler.SR")] - internal sealed partial class NetEventSource : EventSource - { - } + internal sealed partial class NetEventSource { } } diff --git a/src/libraries/System.Net.Http/src/System.Net.Http.csproj b/src/libraries/System.Net.Http/src/System.Net.Http.csproj index e1c24b7265fe42..eb072b1d63cd4f 100644 --- a/src/libraries/System.Net.Http/src/System.Net.Http.csproj +++ b/src/libraries/System.Net.Http/src/System.Net.Http.csproj @@ -1,4 +1,4 @@ - + win true @@ -134,6 +134,8 @@ Link="Common\System\Text\StringBuilderCache.cs" /> + - - WriteEvent(UriBaseAddressId, uriBaseAddress, objName, objHash); + private void UriBaseAddress(string? uriBaseAddress, string objName) => + WriteEvent(UriBaseAddressId, uriBaseAddress, objName); [NonEvent] public static void ContentNull(object obj) @@ -75,49 +75,46 @@ public void AuthenticationError(string? uri, string message) => WriteEvent(AuthenticationErrorId, uri, message); [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", - Justification = "Parameters to this method are primitive and are trimmer safe")] + Justification = EventSourceSuppressMessage)] [NonEvent] private unsafe void WriteEvent(int eventId, int arg1, int arg2, int arg3, string? arg4, string? arg5) { - if (IsEnabled()) + arg4 ??= ""; + arg5 ??= ""; + + fixed (char* string4Bytes = arg4) + fixed (char* string5Bytes = arg5) { - arg4 ??= ""; - arg5 ??= ""; + const int NumEventDatas = 5; + EventData* descrs = stackalloc EventData[NumEventDatas]; - fixed (char* string4Bytes = arg4) - fixed (char* string5Bytes = arg5) + descrs[0] = new EventData + { + DataPointer = (IntPtr)(&arg1), + Size = sizeof(int) + }; + descrs[1] = new EventData + { + DataPointer = (IntPtr)(&arg2), + Size = sizeof(int) + }; + descrs[2] = new EventData { - const int NumEventDatas = 5; - var descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)(&arg1), - Size = sizeof(int) - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)(&arg2), - Size = sizeof(int) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(&arg3), - Size = sizeof(int) - }; - descrs[3] = new EventData - { - DataPointer = (IntPtr)string4Bytes, - Size = ((arg4.Length + 1) * 2) - }; - descrs[4] = new EventData - { - DataPointer = (IntPtr)string5Bytes, - Size = ((arg5.Length + 1) * 2) - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } + DataPointer = (IntPtr)(&arg3), + Size = sizeof(int) + }; + descrs[3] = new EventData + { + DataPointer = (IntPtr)string4Bytes, + Size = ((arg4.Length + 1) * 2) + }; + descrs[4] = new EventData + { + DataPointer = (IntPtr)string5Bytes, + Size = ((arg5.Length + 1) * 2) + }; + + WriteEventCore(eventId, NumEventDatas, descrs); } } } diff --git a/src/libraries/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj b/src/libraries/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj index 038a3d3a52ca17..85139c5391ff85 100644 --- a/src/libraries/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj +++ b/src/libraries/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj @@ -36,6 +36,8 @@ Link="ProductionCode\Common\System\Net\HttpStatusDescription.cs" /> + + + - diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/NetEventSource.HttpListener.cs b/src/libraries/System.Net.HttpListener/src/System/Net/NetEventSource.HttpListener.cs index b1e28de72bb060..9f444955c0d18f 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/NetEventSource.HttpListener.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/NetEventSource.HttpListener.cs @@ -6,7 +6,5 @@ namespace System.Net { [EventSource(Name = "Private.InternalDiagnostics.System.Net.HttpListener", LocalizationResources = "FxResources.System.Net.HttpListener.SR")] - internal sealed partial class NetEventSource - { - } + internal sealed partial class NetEventSource { } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs index 52167a955eefff..7ea7b16d9d942e 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs @@ -315,7 +315,7 @@ private static void IOCompleted(HttpRequestStreamAsyncResult asyncResult, uint e else { result = numBytes; - if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(asyncResult, (IntPtr)asyncResult._pPinnedBuffer, (int)numBytes); + if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(asyncResult, new ReadOnlySpan(asyncResult._pPinnedBuffer, (int)numBytes)); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"asyncResult: {asyncResult} calling Complete()"); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs index 28649cc6ce0259..4d50b7addc3cf1 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs @@ -200,12 +200,18 @@ private static void IOCompleted(HttpResponseStreamAsyncResult asyncResult, uint if (asyncResult._dataChunks == null) { result = (uint)0; - if (NetEventSource.Log.IsEnabled()) { NetEventSource.DumpBuffer(null, IntPtr.Zero, 0); } + if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(null, Array.Empty()); } else { result = asyncResult._dataChunks.Length == 1 ? asyncResult._dataChunks[0].BufferLength : 0; - if (NetEventSource.Log.IsEnabled()) { for (int i = 0; i < asyncResult._dataChunks.Length; i++) { NetEventSource.DumpBuffer(null, (IntPtr)asyncResult._dataChunks[0].pBuffer, (int)asyncResult._dataChunks[0].BufferLength); } } + if (NetEventSource.Log.IsEnabled()) + { + foreach (Interop.HttpApi.HTTP_DATA_CHUNK chunk in asyncResult._dataChunks) + { + NetEventSource.DumpBuffer(null, new ReadOnlySpan(chunk.pBuffer, (int)chunk.BufferLength)); + } + } } } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, "Calling Complete()"); diff --git a/src/libraries/System.Net.Mail/src/System.Net.Mail.csproj b/src/libraries/System.Net.Mail/src/System.Net.Mail.csproj index e8178dfff5eda9..5d2ce4cc28099d 100644 --- a/src/libraries/System.Net.Mail/src/System.Net.Mail.csproj +++ b/src/libraries/System.Net.Mail/src/System.Net.Mail.csproj @@ -1,4 +1,4 @@ - + true $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Browser;$(NetCoreAppCurrent) @@ -70,6 +70,8 @@ Link="Common\System\Net\LazyAsyncResult.cs" /> + - diff --git a/src/libraries/System.Net.Mail/tests/Unit/System.Net.Mail.Unit.Tests.csproj b/src/libraries/System.Net.Mail/tests/Unit/System.Net.Mail.Unit.Tests.csproj index b203a1c6d100ba..0fbb5d7c49728c 100644 --- a/src/libraries/System.Net.Mail/tests/Unit/System.Net.Mail.Unit.Tests.csproj +++ b/src/libraries/System.Net.Mail/tests/Unit/System.Net.Mail.Unit.Tests.csproj @@ -121,6 +121,8 @@ Link="Common\System\Net\LazyAsyncResult.cs" /> + - diff --git a/src/libraries/System.Net.NameResolution/tests/FunctionalTests/LoggingTest.cs b/src/libraries/System.Net.NameResolution/tests/FunctionalTests/LoggingTest.cs index c3333760a4d094..1e7b168c711c9b 100644 --- a/src/libraries/System.Net.NameResolution/tests/FunctionalTests/LoggingTest.cs +++ b/src/libraries/System.Net.NameResolution/tests/FunctionalTests/LoggingTest.cs @@ -98,10 +98,9 @@ await listener.RunWithCallbackAsync(ev => events.Enqueue(ev), async () => static async Task WaitForErrorEventAsync(ConcurrentQueue events) { - const int ErrorEventId = 5; DateTime startTime = DateTime.UtcNow; - while (!events.Any(e => e.EventId == ErrorEventId)) + while (!events.Any(e => e.EventName == "ErrorMessage")) { if (DateTime.UtcNow.Subtract(startTime) > TimeSpan.FromSeconds(30)) throw new TimeoutException("Timeout waiting for error event"); diff --git a/src/libraries/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj b/src/libraries/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj index 37cb80afcfa429..d36ad67504ed4f 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj +++ b/src/libraries/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj @@ -1,4 +1,4 @@ - + true $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Linux;$(NetCoreAppCurrent)-Android;$(NetCoreAppCurrent)-OSX;$(NetCoreAppCurrent)-iOS;$(NetCoreAppCurrent)-tvOS;$(NetCoreAppCurrent)-FreeBSD;$(NetCoreAppCurrent)-illumos;$(NetCoreAppCurrent)-Solaris;$(NetCoreAppCurrent) @@ -54,8 +54,6 @@ - - @@ -120,7 +118,6 @@ - diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetEventSource.NetworkInformation.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetEventSource.NetworkInformation.cs index 73575689b1e413..87a07eb1cdd2a0 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetEventSource.NetworkInformation.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetEventSource.NetworkInformation.cs @@ -1,10 +1,28 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics; using System.Diagnostics.Tracing; +using System.Runtime.CompilerServices; namespace System.Net { [EventSource(Name = "Private.InternalDiagnostics.System.Net.NetworkInformation")] - internal sealed partial class NetEventSource { } + internal sealed class NetEventSource : EventSource + { + public static readonly NetEventSource Log = new NetEventSource(); + + private const int ErrorEventId = 2; + + [NonEvent] + public static void Error(Exception exception, [CallerMemberName] string? memberName = null) => + Log.ErrorMessage(memberName ?? "(?)", exception.ToString()); + + [Event(ErrorEventId, Level = EventLevel.Error)] + private void ErrorMessage(string memberName, string message) + { + Debug.Assert(IsEnabled()); + WriteEvent(ErrorEventId, memberName, message); + } + } } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Unix.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Unix.cs index ebebfd916dce79..7fdc4454677564 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Unix.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Unix.cs @@ -219,7 +219,7 @@ private static async void ReadEventsAsync(Socket socket) { // Unexpected error. Debug.Fail($"Unexpected error: {ex}"); - if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, ex); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(ex); } static unsafe Interop.Error ReadEvents(Socket socket) diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs index a9c2a5ec07745b..345aa6c509cd1b 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs @@ -166,7 +166,7 @@ private static void AddressChangedCallback(object? stateObject, bool signaled) } catch (NetworkInformationException nie) { - if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, nie); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(nie); } } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemNetworkInterface.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemNetworkInterface.cs index c80e1cd206bde8..4c62c3770d96a2 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemNetworkInterface.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemNetworkInterface.cs @@ -73,7 +73,7 @@ internal static bool InternalGetIsNetworkAvailable() } catch (NetworkInformationException nie) { - if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(null, nie); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(nie); } return false; diff --git a/src/libraries/System.Net.Ping/src/System.Net.Ping.csproj b/src/libraries/System.Net.Ping/src/System.Net.Ping.csproj index 159f21b6bb298b..71b5d783c459ea 100644 --- a/src/libraries/System.Net.Ping/src/System.Net.Ping.csproj +++ b/src/libraries/System.Net.Ping/src/System.Net.Ping.csproj @@ -1,4 +1,4 @@ - + true $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-OSX;$(NetCoreAppCurrent)-iOS;$(NetCoreAppCurrent)-tvOS;$(NetCoreAppCurrent) @@ -11,7 +11,6 @@ - @@ -27,9 +26,6 @@ Link="Common\System\Net\SocketAddress.cs" /> - - diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/NetEventSource.Ping.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/NetEventSource.Ping.cs deleted file mode 100644 index ec0a5dbccf4207..00000000000000 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/NetEventSource.Ping.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System.Diagnostics.Tracing; - -namespace System.Net -{ - [EventSource(Name = "Private.InternalDiagnostics.System.Net.Ping")] - internal sealed partial class NetEventSource { } -} diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/NetEventSource.Quic.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/NetEventSource.Quic.cs index 7a66c960efc098..37dbeab080837c 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/NetEventSource.Quic.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/NetEventSource.Quic.cs @@ -7,12 +7,11 @@ namespace System.Net { [EventSource(Name = "Private.InternalDiagnostics.System.Net.Quic")] - internal sealed partial class NetEventSource : EventSource + internal sealed partial class NetEventSource { - static partial void AdditionalCustomizedToString(T value, ref string? result) + static partial void AdditionalCustomizedToString(object value, ref string? result) { - MsQuicSafeHandle? safeHandle = value as MsQuicSafeHandle; - if (safeHandle is not null) + if (value is MsQuicSafeHandle safeHandle) { result = safeHandle.ToString(); } diff --git a/src/libraries/System.Net.Requests/src/System.Net.Requests.csproj b/src/libraries/System.Net.Requests/src/System.Net.Requests.csproj index f7768942312164..d16970c9a19a91 100644 --- a/src/libraries/System.Net.Requests/src/System.Net.Requests.csproj +++ b/src/libraries/System.Net.Requests/src/System.Net.Requests.csproj @@ -56,6 +56,8 @@ Link="Common\System\Net\InternalException.cs" /> + - @@ -62,6 +61,8 @@ + @@ -147,11 +148,12 @@ - + Logs the contents of a buffer - /// `this`, or another object that serves to provide context for the operation. - /// The buffer to be logged. - /// The calling member. - [NonEvent] - public static void DumpBuffer(object thisOrContextObject, ReadOnlySpan buffer, [CallerMemberName] string? memberName = null) - { - if (Log.IsEnabled()) - { - int count = Math.Min(buffer.Length, MaxDumpSize); - - byte[] slice = buffer.Slice(0, count).ToArray(); - Log.DumpBuffer(IdOf(thisOrContextObject), memberName, slice); - } - } - } -} diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.Windows.cs deleted file mode 100644 index 12694700cf8a36..00000000000000 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.Windows.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Tracing; -using System.Net.Security; - -namespace System.Net -{ - internal sealed partial class NetEventSource - { - [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", - Justification = "parameter intent is an enum and is trimmer safe")] - [Event(AcquireDefaultCredentialId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void AcquireDefaultCredential(string packageName, Interop.SspiCli.CredentialUse intent) - { - if (IsEnabled()) - { - WriteEvent(AcquireDefaultCredentialId, packageName, intent); - } - } - - [NonEvent] - public void AcquireCredentialsHandle(string packageName, Interop.SspiCli.CredentialUse intent, object authdata) - { - if (IsEnabled()) - { - AcquireCredentialsHandle(packageName, intent, IdOf(authdata)); - } - } - - [Event(AcquireCredentialsHandleId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void AcquireCredentialsHandle(string packageName, Interop.SspiCli.CredentialUse intent, string authdata) - { - if (IsEnabled()) - { - WriteEvent(AcquireCredentialsHandleId, packageName, (int)intent, authdata); - } - } - - [NonEvent] - public void InitializeSecurityContext(SafeFreeCredentials? credential, SafeDeleteContext? context, string? targetName, Interop.SspiCli.ContextFlags inFlags) - { - if (IsEnabled()) - { - InitializeSecurityContext(IdOf(credential), IdOf(context), targetName, inFlags); - } - } - [Event(InitializeSecurityContextId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private void InitializeSecurityContext(string credential, string context, string? targetName, Interop.SspiCli.ContextFlags inFlags) => - WriteEvent(InitializeSecurityContextId, credential, context, targetName, (int)inFlags); - - [NonEvent] - public void AcceptSecurityContext(SafeFreeCredentials? credential, SafeDeleteContext? context, Interop.SspiCli.ContextFlags inFlags) - { - if (IsEnabled()) - { - AcceptSecurityContext(IdOf(credential), IdOf(context), inFlags); - } - } - [Event(AcceptSecuritContextId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private void AcceptSecurityContext(string credential, string context, Interop.SspiCli.ContextFlags inFlags) => - WriteEvent(AcceptSecuritContextId, credential, context, (int)inFlags); - - [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", - Justification = "parameter errorCode is an enum and is trimmer safe")] - [Event(OperationReturnedSomethingId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void OperationReturnedSomething(string operation, Interop.SECURITY_STATUS errorCode) - { - if (IsEnabled()) - { - WriteEvent(OperationReturnedSomethingId, operation, errorCode); - } - } - - [Event(SecurityContextInputBufferId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void SecurityContextInputBuffer(string context, int inputBufferSize, int outputBufferSize, Interop.SECURITY_STATUS errorCode) - { - if (IsEnabled()) - { - WriteEvent(SecurityContextInputBufferId, context, inputBufferSize, outputBufferSize, (int)errorCode); - } - } - - [Event(SecurityContextInputBuffersId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void SecurityContextInputBuffers(string context, int inputBuffersSize, int outputBufferSize, Interop.SECURITY_STATUS errorCode) - { - if (IsEnabled()) - { - WriteEvent(SecurityContextInputBuffersId, context, inputBuffersSize, outputBufferSize, (int)errorCode); - } - } - } -} diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs index 5134be4e86db4c..a3b0a37fbae84d 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs @@ -1,8 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; -using System.Globalization; using System.IO; using System.Net.Security; using System.Net.Sockets; @@ -14,7 +14,12 @@ namespace System.Net [EventSource(Name = "Private.InternalDiagnostics.System.Net.Security", LocalizationResources = "FxResources.System.Net.Security.SR")] internal sealed partial class NetEventSource { - private const int LocatingPrivateKeyId = NextAvailableEventId + 1; +#if WINDOWS + // More events are defined in NetEventSource.Security.Windows.cs + private const int LocatingPrivateKeyId = OperationReturnedSomethingId + 1; +#else + private const int LocatingPrivateKeyId = NextAvailableEventId; +#endif private const int CertIsType2Id = LocatingPrivateKeyId + 1; private const int FoundCertInStoreId = CertIsType2Id + 1; private const int NotFoundCertInStoreId = FoundCertInStoreId + 1; @@ -38,48 +43,25 @@ internal sealed partial class NetEventSource private const int SentFrameId = SslStreamCtorId + 1; private const int ReceivedFrameId = SentFrameId + 1; - [Event(EnumerateSecurityPackagesId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void EnumerateSecurityPackages(string? securityPackage) - { - if (IsEnabled()) - { - WriteEvent(EnumerateSecurityPackagesId, securityPackage ?? ""); - } - } - - [Event(SspiPackageNotFoundId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public void SspiPackageNotFound(string packageName) - { - if (IsEnabled()) - { - WriteEvent(SspiPackageNotFoundId, packageName ?? ""); - } - } - [NonEvent] public void SslStreamCtor(SslStream sslStream, Stream innerStream) { - if (IsEnabled()) - { - string? localId = null; - string? remoteId = null; + string? localId = null; + string? remoteId = null; - NetworkStream? ns = innerStream as NetworkStream; - if (ns != null) + if (innerStream is NetworkStream ns) + { + try { - try - { - localId = ns.Socket.LocalEndPoint?.ToString(); - remoteId = ns.Socket.RemoteEndPoint?.ToString(); - - } - catch { }; + localId = ns.Socket.LocalEndPoint?.ToString(); + remoteId = ns.Socket.RemoteEndPoint?.ToString(); } + catch { }; + } - localId ??= IdOf(innerStream); + localId ??= IdOf(innerStream); - SslStreamCtor(IdOf(sslStream), localId, remoteId); - } + SslStreamCtor(IdOf(sslStream), localId, remoteId); } [Event(SslStreamCtorId, Keywords = Keywords.Default, Level = EventLevel.Informational)] @@ -87,181 +69,121 @@ private void SslStreamCtor(string thisOrContextObject, string? localId, string? WriteEvent(SslStreamCtorId, thisOrContextObject, localId, remoteId); [NonEvent] - public void LocatingPrivateKey(X509Certificate x509Certificate, object instance) - { - if (IsEnabled()) - { - LocatingPrivateKey(x509Certificate.ToString(true), GetHashCode(instance)); - } - } + public void LocatingPrivateKey(X509Certificate x509Certificate, object instance) => + LocatingPrivateKey(x509Certificate.ToString(fVerbose: true), GetHashCode(instance)); + [Event(LocatingPrivateKeyId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void LocatingPrivateKey(string x509Certificate, int sslStreamHash) => WriteEvent(LocatingPrivateKeyId, x509Certificate, sslStreamHash); [NonEvent] - public void CertIsType2(object instance) - { - if (IsEnabled()) - { - CertIsType2(GetHashCode(instance)); - } - } + public void CertIsType2(object instance) => + CertIsType2(GetHashCode(instance)); + [Event(CertIsType2Id, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void CertIsType2(int sslStreamHash) => WriteEvent(CertIsType2Id, sslStreamHash); [NonEvent] - public void FoundCertInStore(bool serverMode, object instance) - { - if (IsEnabled()) - { - FoundCertInStore(serverMode ? "LocalMachine" : "CurrentUser", GetHashCode(instance)); - } - } + public void FoundCertInStore(bool serverMode, object instance) => + FoundCertInStore(serverMode ? "LocalMachine" : "CurrentUser", GetHashCode(instance)); + [Event(FoundCertInStoreId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void FoundCertInStore(string store, int sslStreamHash) => WriteEvent(FoundCertInStoreId, store, sslStreamHash); [NonEvent] - public void NotFoundCertInStore(object instance) - { - if (IsEnabled()) - { - NotFoundCertInStore(GetHashCode(instance)); - } - } + public void NotFoundCertInStore(object instance) => + NotFoundCertInStore(GetHashCode(instance)); + [Event(NotFoundCertInStoreId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void NotFoundCertInStore(int sslStreamHash) => WriteEvent(NotFoundCertInStoreId, sslStreamHash); [NonEvent] - public void RemoteCertificate(X509Certificate? remoteCertificate) - { - if (IsEnabled()) - { - RemoteCertificate(remoteCertificate?.ToString(true)); - } - } + public void RemoteCertificate(X509Certificate? remoteCertificate) => + RemoteCertificate(remoteCertificate?.ToString(fVerbose: true)); + [Event(RemoteCertificateId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void RemoteCertificate(string? remoteCertificate) => WriteEvent(RemoteCertificateId, remoteCertificate); [NonEvent] - public void CertificateFromDelegate(SslStream SslStream) - { - if (IsEnabled()) - { - CertificateFromDelegate(GetHashCode(SslStream)); - } - } + public void CertificateFromDelegate(SslStream SslStream) => + CertificateFromDelegate(GetHashCode(SslStream)); + [Event(CertificateFromDelegateId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void CertificateFromDelegate(int sslStreamHash) => WriteEvent(CertificateFromDelegateId, sslStreamHash); [NonEvent] - public void NoDelegateNoClientCert(SslStream SslStream) - { - if (IsEnabled()) - { - NoDelegateNoClientCert(GetHashCode(SslStream)); - } - } + public void NoDelegateNoClientCert(SslStream SslStream) => + NoDelegateNoClientCert(GetHashCode(SslStream)); + [Event(NoDelegateNoClientCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void NoDelegateNoClientCert(int sslStreamHash) => WriteEvent(NoDelegateNoClientCertId, sslStreamHash); [NonEvent] - public void NoDelegateButClientCert(SslStream SslStream) - { - if (IsEnabled()) - { - NoDelegateButClientCert(GetHashCode(SslStream)); - } - } + public void NoDelegateButClientCert(SslStream SslStream) => + NoDelegateButClientCert(GetHashCode(SslStream)); + [Event(NoDelegateButClientCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void NoDelegateButClientCert(int sslStreamHash) => WriteEvent(NoDelegateButClientCertId, sslStreamHash); [NonEvent] - public void AttemptingRestartUsingCert(X509Certificate? clientCertificate, SslStream SslStream) - { - if (IsEnabled()) - { - AttemptingRestartUsingCert(clientCertificate?.ToString(true), GetHashCode(SslStream)); - } - } + public void AttemptingRestartUsingCert(X509Certificate? clientCertificate, SslStream SslStream) => + AttemptingRestartUsingCert(clientCertificate?.ToString(fVerbose: true), GetHashCode(SslStream)); + [Event(AttemptingRestartUsingCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void AttemptingRestartUsingCert(string? clientCertificate, int sslStreamHash) => WriteEvent(AttemptingRestartUsingCertId, clientCertificate, sslStreamHash); [NonEvent] - public void NoIssuersTryAllCerts(SslStream SslStream) - { - if (IsEnabled()) - { - NoIssuersTryAllCerts(GetHashCode(SslStream)); - } - } + public void NoIssuersTryAllCerts(SslStream SslStream) => + NoIssuersTryAllCerts(GetHashCode(SslStream)); + [Event(NoIssuersTryAllCertsId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void NoIssuersTryAllCerts(int sslStreamHash) => WriteEvent(NoIssuersTryAllCertsId, sslStreamHash); [NonEvent] - public void LookForMatchingCerts(int issuersCount, SslStream SslStream) - { - if (IsEnabled()) - { - LookForMatchingCerts(issuersCount, GetHashCode(SslStream)); - } - } + public void LookForMatchingCerts(int issuersCount, SslStream SslStream) => + LookForMatchingCerts(issuersCount, GetHashCode(SslStream)); + [Event(LookForMatchingCertsId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void LookForMatchingCerts(int issuersCount, int sslStreamHash) => WriteEvent(LookForMatchingCertsId, issuersCount, sslStreamHash); [NonEvent] - public void SelectedCert(X509Certificate clientCertificate, SslStream SslStream) - { - if (IsEnabled()) - { - SelectedCert(clientCertificate?.ToString(true), GetHashCode(SslStream)); - } - } + public void SelectedCert(X509Certificate clientCertificate, SslStream SslStream) => + SelectedCert(clientCertificate?.ToString(fVerbose: true), GetHashCode(SslStream)); + [Event(SelectedCertId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void SelectedCert(string? clientCertificate, int sslStreamHash) => WriteEvent(SelectedCertId, clientCertificate, sslStreamHash); [NonEvent] - public void CertsAfterFiltering(int filteredCertsCount, SslStream SslStream) - { - if (IsEnabled()) - { - CertsAfterFiltering(filteredCertsCount, GetHashCode(SslStream)); - } - } + public void CertsAfterFiltering(int filteredCertsCount, SslStream SslStream) => + CertsAfterFiltering(filteredCertsCount, GetHashCode(SslStream)); + [Event(CertsAfterFilteringId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void CertsAfterFiltering(int filteredCertsCount, int sslStreamHash) => WriteEvent(CertsAfterFilteringId, filteredCertsCount, sslStreamHash); [NonEvent] - public void FindingMatchingCerts(SslStream SslStream) - { - if (IsEnabled()) - { - FindingMatchingCerts(GetHashCode(SslStream)); - } - } + public void FindingMatchingCerts(SslStream SslStream) => + FindingMatchingCerts(GetHashCode(SslStream)); + [Event(FindingMatchingCertsId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void FindingMatchingCerts(int sslStreamHash) => WriteEvent(FindingMatchingCertsId, sslStreamHash); [NonEvent] - public void UsingCachedCredential(SslStream SslStream) - { - if (IsEnabled()) - { - UsingCachedCredential(GetHashCode(SslStream)); - } - } + public void UsingCachedCredential(SslStream SslStream) => + UsingCachedCredential(GetHashCode(SslStream)); + [Event(UsingCachedCredentialId, Keywords = Keywords.Default, Level = EventLevel.Informational)] private void UsingCachedCredential(int sslStreamHash) => WriteEvent(UsingCachedCredentialId, sslStreamHash); @@ -277,58 +199,39 @@ public void SspiSelectedCipherSuite( ExchangeAlgorithmType keyExchangeAlgorithm, int keyExchangeStrength) { - if (IsEnabled()) - { - WriteEvent(SspiSelectedCipherSuitId, - process, (int)sslProtocol, (int)cipherAlgorithm, cipherStrength, - (int)hashAlgorithm, hashStrength, (int)keyExchangeAlgorithm, keyExchangeStrength); - } + WriteEvent(SspiSelectedCipherSuitId, + process, (int)sslProtocol, (int)cipherAlgorithm, cipherStrength, + (int)hashAlgorithm, hashStrength, (int)keyExchangeAlgorithm, keyExchangeStrength); } [NonEvent] - public void RemoteCertificateError(SslStream SslStream, string message) - { - if (IsEnabled()) - { - RemoteCertificateError(GetHashCode(SslStream), message); - } - } + public void RemoteCertificateError(SslStream SslStream, string message) => + RemoteCertificateError(GetHashCode(SslStream), message); + [Event(RemoteCertificateErrorId, Keywords = Keywords.Default, Level = EventLevel.Verbose)] private void RemoteCertificateError(int sslStreamHash, string message) => WriteEvent(RemoteCertificateErrorId, sslStreamHash, message); [NonEvent] - public void RemoteCertDeclaredValid(SslStream SslStream) - { - if (IsEnabled()) - { - RemoteCertDeclaredValid(GetHashCode(SslStream)); - } - } + public void RemoteCertDeclaredValid(SslStream SslStream) => + RemoteCertDeclaredValid(GetHashCode(SslStream)); + [Event(RemoteVertificateValidId, Keywords = Keywords.Default, Level = EventLevel.Verbose)] private void RemoteCertDeclaredValid(int sslStreamHash) => WriteEvent(RemoteVertificateValidId, sslStreamHash); [NonEvent] - public void RemoteCertHasNoErrors(SslStream SslStream) - { - if (IsEnabled()) - { - RemoteCertHasNoErrors(GetHashCode(SslStream)); - } - } + public void RemoteCertHasNoErrors(SslStream SslStream) => + RemoteCertHasNoErrors(GetHashCode(SslStream)); + [Event(RemoteCertificateSuccessId, Keywords = Keywords.Default, Level = EventLevel.Verbose)] private void RemoteCertHasNoErrors(int sslStreamHash) => WriteEvent(RemoteCertificateSuccessId, sslStreamHash); [NonEvent] - public void RemoteCertUserDeclaredInvalid(SslStream SslStream) - { - if (IsEnabled()) - { - RemoteCertUserDeclaredInvalid(GetHashCode(SslStream)); - } - } + public void RemoteCertUserDeclaredInvalid(SslStream SslStream) => + RemoteCertUserDeclaredInvalid(GetHashCode(SslStream)); + [Event(RemoteCertificateInvalidId, Keywords = Keywords.Default, Level = EventLevel.Verbose)] private void RemoteCertUserDeclaredInvalid(int sslStreamHash) => WriteEvent(RemoteCertificateInvalidId, sslStreamHash); @@ -336,46 +239,94 @@ private void RemoteCertUserDeclaredInvalid(int sslStreamHash) => [NonEvent] public void SentFrame(SslStream sslStream, ReadOnlySpan frame) { - if (IsEnabled()) - { - TlsFrameHelper.TlsFrameInfo info = default; - bool isComplete = TlsFrameHelper.TryGetFrameInfo(frame, ref info); - SentFrame(IdOf(sslStream), info.ToString(), isComplete ? 1 : 0); - } + TlsFrameHelper.TlsFrameInfo info = default; + bool isComplete = TlsFrameHelper.TryGetFrameInfo(frame, ref info); + SentFrame(IdOf(sslStream), info.ToString(), isComplete ? 1 : 0); } + [Event(SentFrameId, Keywords = Keywords.Default, Level = EventLevel.Verbose)] private void SentFrame(string sslStream, string tlsFrame, int isComplete) => WriteEvent(SentFrameId, sslStream, tlsFrame, isComplete); [NonEvent] - public void ReceivedFrame(SslStream sslStream, TlsFrameHelper.TlsFrameInfo frameInfo) - { - if (IsEnabled()) - { - ReceivedFrame(IdOf(sslStream), frameInfo.ToString(), 1); - } - } + public void ReceivedFrame(SslStream sslStream, TlsFrameHelper.TlsFrameInfo frameInfo) => + ReceivedFrame(IdOf(sslStream), frameInfo.ToString(), 1); + [NonEvent] public void ReceivedFrame(SslStream sslStream, ReadOnlySpan frame) { - if (IsEnabled()) - { - TlsFrameHelper.TlsFrameInfo info = default; - bool isComplete = TlsFrameHelper.TryGetFrameInfo(frame, ref info); - ReceivedFrame(IdOf(sslStream), info.ToString(), isComplete ? 1 : 0); - } + TlsFrameHelper.TlsFrameInfo info = default; + bool isComplete = TlsFrameHelper.TryGetFrameInfo(frame, ref info); + ReceivedFrame(IdOf(sslStream), info.ToString(), isComplete ? 1 : 0); } + [Event(ReceivedFrameId, Keywords = Keywords.Default, Level = EventLevel.Verbose)] private void ReceivedFrame(string sslStream, string tlsFrame, int isComplete) => WriteEvent(ReceivedFrameId, sslStream, tlsFrame, isComplete); - static partial void AdditionalCustomizedToString(T value, ref string? result) + static partial void AdditionalCustomizedToString(object value, ref string? result) { - X509Certificate? cert = value as X509Certificate; - if (cert != null) + if (value is X509Certificate cert) { result = cert.ToString(fVerbose: true); } } + + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", + Justification = EventSourceSuppressMessage)] + [NonEvent] + private unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8) + { + arg1 ??= ""; + + fixed (char* arg1Ptr = arg1) + { + const int NumEventDatas = 8; + EventData* descrs = stackalloc EventData[NumEventDatas]; + + descrs[0] = new EventData + { + DataPointer = (IntPtr)(arg1Ptr), + Size = (arg1.Length + 1) * sizeof(char) + }; + descrs[1] = new EventData + { + DataPointer = (IntPtr)(&arg2), + Size = sizeof(int) + }; + descrs[2] = new EventData + { + DataPointer = (IntPtr)(&arg3), + Size = sizeof(int) + }; + descrs[3] = new EventData + { + DataPointer = (IntPtr)(&arg4), + Size = sizeof(int) + }; + descrs[4] = new EventData + { + DataPointer = (IntPtr)(&arg5), + Size = sizeof(int) + }; + descrs[5] = new EventData + { + DataPointer = (IntPtr)(&arg6), + Size = sizeof(int) + }; + descrs[6] = new EventData + { + DataPointer = (IntPtr)(&arg7), + Size = sizeof(int) + }; + descrs[7] = new EventData + { + DataPointer = (IntPtr)(&arg8), + Size = sizeof(int) + }; + + WriteEventCore(eventId, NumEventDatas, descrs); + } + } } } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NetSecurityTelemetry.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NetSecurityTelemetry.cs index b177cd615432ee..985662d9f21465 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NetSecurityTelemetry.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NetSecurityTelemetry.cs @@ -138,7 +138,8 @@ private void HandshakeStop(SslProtocols protocol) { if (IsEnabled(EventLevel.Informational, EventKeywords.None)) { - WriteEvent(eventId: 2, protocol); + Debug.Assert(sizeof(SslProtocols) == 4); + WriteEvent(eventId: 2, (int)protocol); } } @@ -250,45 +251,25 @@ public void ConnectionClosed(SslProtocols protocol) [NonEvent] private unsafe void WriteEvent(int eventId, bool arg1, string? arg2) { - if (IsEnabled()) - { - arg2 ??= string.Empty; - - fixed (char* arg2Ptr = arg2) - { - const int NumEventDatas = 2; - EventData* descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)(&arg1), - Size = sizeof(int) // EventSource defines bool as a 32-bit type - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)(arg2Ptr), - Size = (arg2.Length + 1) * sizeof(char) - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } - } - } + arg2 ??= string.Empty; - [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", - Justification = EventSourceSuppressMessage)] - [NonEvent] - private unsafe void WriteEvent(int eventId, SslProtocols arg1) - { - if (IsEnabled()) + fixed (char* arg2Ptr = arg2) { - var data = new EventData + const int NumEventDatas = 2; + EventData* descrs = stackalloc EventData[NumEventDatas]; + + descrs[0] = new EventData { DataPointer = (IntPtr)(&arg1), - Size = sizeof(SslProtocols) + Size = sizeof(int) // EventSource defines bool as a 32-bit type + }; + descrs[1] = new EventData + { + DataPointer = (IntPtr)(arg2Ptr), + Size = (arg2.Length + 1) * sizeof(char) }; - WriteEventCore(eventId, eventDataCount: 1, &data); + WriteEventCore(eventId, NumEventDatas, descrs); } } @@ -297,33 +278,30 @@ private unsafe void WriteEvent(int eventId, SslProtocols arg1) [NonEvent] private unsafe void WriteEvent(int eventId, bool arg1, double arg2, string? arg3) { - if (IsEnabled()) + arg3 ??= string.Empty; + + fixed (char* arg3Ptr = arg3) { - arg3 ??= string.Empty; + const int NumEventDatas = 3; + EventData* descrs = stackalloc EventData[NumEventDatas]; - fixed (char* arg3Ptr = arg3) + descrs[0] = new EventData + { + DataPointer = (IntPtr)(&arg1), + Size = sizeof(int) // EventSource defines bool as a 32-bit type + }; + descrs[1] = new EventData + { + DataPointer = (IntPtr)(&arg2), + Size = sizeof(double) + }; + descrs[2] = new EventData { - const int NumEventDatas = 3; - EventData* descrs = stackalloc EventData[NumEventDatas]; - - descrs[0] = new EventData - { - DataPointer = (IntPtr)(&arg1), - Size = sizeof(int) // EventSource defines bool as a 32-bit type - }; - descrs[1] = new EventData - { - DataPointer = (IntPtr)(&arg2), - Size = sizeof(double) - }; - descrs[2] = new EventData - { - DataPointer = (IntPtr)(arg3Ptr), - Size = (arg3.Length + 1) * sizeof(char) - }; - - WriteEventCore(eventId, NumEventDatas, descrs); - } + DataPointer = (IntPtr)(arg3Ptr), + Size = (arg3.Length + 1) * sizeof(char) + }; + + WriteEventCore(eventId, NumEventDatas, descrs); } } } diff --git a/src/libraries/System.Net.Sockets/src/System.Net.Sockets.csproj b/src/libraries/System.Net.Sockets/src/System.Net.Sockets.csproj index 7f9c5ae276aa97..61f9c6fa2d4a9b 100644 --- a/src/libraries/System.Net.Sockets/src/System.Net.Sockets.csproj +++ b/src/libraries/System.Net.Sockets/src/System.Net.Sockets.csproj @@ -51,6 +51,8 @@ + diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetEventSource.Sockets.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetEventSource.Sockets.cs index 27963c7b25e3e2..2734e1caffc1df 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetEventSource.Sockets.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetEventSource.Sockets.cs @@ -1,11 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Diagnostics; using System.Diagnostics.Tracing; using System.Net.Sockets; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; namespace System.Net { @@ -18,74 +16,36 @@ internal sealed partial class NetEventSource private const int NotLoggedFileId = ConnectedAsyncDnsId + 1; [NonEvent] - public static void Accepted(Socket socket, object? remoteEp, object? localEp) - { - if (Log.IsEnabled()) - { - Log.Accepted(IdOf(remoteEp), IdOf(localEp), GetHashCode(socket)); - } - } + public static void Accepted(Socket socket, object? remoteEp, object? localEp) => + Log.Accepted(IdOf(remoteEp), IdOf(localEp), GetHashCode(socket)); [Event(AcceptedId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private void Accepted(string remoteEp, string localEp, int socketHash) - { + private void Accepted(string remoteEp, string localEp, int socketHash) => WriteEvent(AcceptedId, remoteEp, localEp, socketHash); - } [NonEvent] - public static void Connected(Socket socket, object? localEp, object? remoteEp) - { - if (Log.IsEnabled()) - { - Log.Connected(IdOf(localEp), IdOf(remoteEp), GetHashCode(socket)); - } - } + public static void Connected(Socket socket, object? localEp, object? remoteEp) => + Log.Connected(IdOf(localEp), IdOf(remoteEp), GetHashCode(socket)); [Event(ConnectedId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private void Connected(string localEp, string remoteEp, int socketHash) - { + private void Connected(string localEp, string remoteEp, int socketHash) => WriteEvent(ConnectedId, localEp, remoteEp, socketHash); - } [NonEvent] - public static void ConnectedAsyncDns(Socket socket) - { - if (Log.IsEnabled()) - { - Log.ConnectedAsyncDns(GetHashCode(socket)); - } - } + public static void ConnectedAsyncDns(Socket socket) => + Log.ConnectedAsyncDns(GetHashCode(socket)); [Event(ConnectedAsyncDnsId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private void ConnectedAsyncDns(int socketHash) - { + private void ConnectedAsyncDns(int socketHash) => WriteEvent(ConnectedAsyncDnsId, socketHash); - } [NonEvent] - public static void NotLoggedFile(string filePath, Socket socket, SocketAsyncOperation completedOperation) - { - if (Log.IsEnabled()) - { - Log.NotLoggedFile(filePath, GetHashCode(socket), completedOperation); - } - } + public static void NotLoggedFile(string filePath, Socket socket, SocketAsyncOperation completedOperation) => + Log.NotLoggedFile(filePath, GetHashCode(socket), completedOperation); [Event(NotLoggedFileId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private void NotLoggedFile(string filePath, int socketHash, SocketAsyncOperation completedOperation) - { + private void NotLoggedFile(string filePath, int socketHash, SocketAsyncOperation completedOperation) => WriteEvent(NotLoggedFileId, filePath, socketHash, (int)completedOperation); - } - - /// Logs the contents of a buffer. - /// `this`, or another object that serves to provide context for the operation. - /// The buffer to be logged. - /// The calling member. - [NonEvent] - public static void DumpBuffer(object thisOrContextObject, Memory buffer, [CallerMemberName] string? memberName = null) - { - DumpBuffer(thisOrContextObject, buffer, 0, buffer.Length, memberName); - } /// Logs the contents of a buffer. /// `this`, or another object that serves to provide context for the operation. @@ -94,23 +54,7 @@ public static void DumpBuffer(object thisOrContextObject, Memory buffer, [ /// The number of bytes to log. /// The calling member. [NonEvent] - public static void DumpBuffer(object thisOrContextObject, Memory buffer, int offset, int count, [CallerMemberName] string? memberName = null) - { - if (Log.IsEnabled()) - { - if (offset < 0 || offset > buffer.Length - count) - { - Debug.Fail($"Invalid {nameof(DumpBuffer)} Args. Length={buffer.Length}, Offset={offset}, Count={count}"); - return; - } - - buffer = buffer.Slice(offset, Math.Min(count, MaxDumpSize)); - byte[] slice = MemoryMarshal.TryGetArray(buffer, out ArraySegment arraySegment) && arraySegment.Offset == 0 && arraySegment.Count == buffer.Length ? - arraySegment.Array! : - buffer.ToArray(); - - Log.DumpBuffer(IdOf(thisOrContextObject), memberName, slice); - } - } + public static void DumpBuffer(object thisOrContextObject, Memory buffer, int offset, int count, [CallerMemberName] string? memberName = null) => + DumpBuffer(thisOrContextObject, buffer.Span.Slice(offset, count), memberName); } } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs index 7de84ed6e763d4..84cf302cb2b89e 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs @@ -1026,7 +1026,7 @@ private unsafe Interop.Winsock.TransmitPacketsElement[] SetupPinHandlesSendPacke return sendPacketsDescriptorPinned; } - internal void LogBuffer(int size) + internal unsafe void LogBuffer(int size) { // This should only be called if tracing is enabled. However, there is the potential for a race // condition where tracing is disabled between a calling check and here, in which case the assert @@ -1038,7 +1038,7 @@ internal void LogBuffer(int size) for (int i = 0; i < _bufferListInternal!.Count; i++) { WSABuffer wsaBuffer = _wsaBufferArrayPinned![i]; - NetEventSource.DumpBuffer(this, wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size)); + NetEventSource.DumpBuffer(this, new ReadOnlySpan((byte*)wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size))); if ((size -= wsaBuffer.Length) <= 0) { break;