Skip to content

Commit e1588c8

Browse files
committed
Delete NetEventSource.Fail
At some point some Debug.Asserts/Fails were replaced by this NetEventSource.Fail helper, which both Debug.Fails and fires an EventSource event. But asserts in our code base are intended for things that should never happen, and we needn't be emitting events for them (if we did want to emit events for them, we'd need to tackle the other ~20,000 Debug.Assert/Fails in the codebase. I've deleted NetEventSource.Fail, and fixed up the call sites. Some were simply replaced by Debug.Assert/Fail. Some were deleted entirely, when from code inspection it looked like they could actually be hit, but were guarded by a check for the event source being enabled and thus were unlikely to have been triggered in our previous testing. Etc.
1 parent 159a6ea commit e1588c8

28 files changed

+96
-357
lines changed

src/libraries/Common/src/Interop/Windows/SspiCli/SSPIAuthType.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
#nullable enable
5+
using System.Diagnostics;
56
using System.Net.Security;
67
using System.Runtime.InteropServices;
78

@@ -93,7 +94,7 @@ public unsafe int DecryptMessage(SafeDeleteContext context, ref Interop.SspiCli.
9394

9495
if (status == 0 && qop == Interop.SspiCli.SECQOP_WRAP_NO_ENCRYPT)
9596
{
96-
NetEventSource.Fail(this, $"Expected qop = 0, returned value = {qop}");
97+
Debug.Fail($"Expected qop = 0, returned value = {qop}");
9798
throw new InvalidOperationException(SR.net_auth_message_not_encrypted);
9899
}
99100

src/libraries/Common/src/Interop/Windows/SspiCli/SSPIWrapper.cs

Lines changed: 13 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,7 @@ private ref struct ThreeByteArrays
226226

227227
private static unsafe int EncryptDecryptHelper(OP op, ISSPIInterface secModule, SafeDeleteContext context, Span<SecurityBuffer> input, uint sequenceNumber)
228228
{
229+
Debug.Assert(Enum.IsDefined<OP>(op), $"Unknown op: {op}");
229230
Debug.Assert(input.Length <= 3, "The below logic only works for 3 or fewer buffers.");
230231

231232
Interop.SspiCli.SecBufferDesc sdcInOut = new Interop.SspiCli.SecBufferDesc(input.Length);
@@ -259,29 +260,13 @@ private static unsafe int EncryptDecryptHelper(OP op, ISSPIInterface secModule,
259260
}
260261

261262
// The result is written in the input Buffer passed as type=BufferType.Data.
262-
int errorCode;
263-
switch (op)
263+
int errorCode = op switch
264264
{
265-
case OP.Encrypt:
266-
errorCode = secModule.EncryptMessage(context, ref sdcInOut, sequenceNumber);
267-
break;
268-
269-
case OP.Decrypt:
270-
errorCode = secModule.DecryptMessage(context, ref sdcInOut, sequenceNumber);
271-
break;
272-
273-
case OP.MakeSignature:
274-
errorCode = secModule.MakeSignature(context, ref sdcInOut, sequenceNumber);
275-
break;
276-
277-
case OP.VerifySignature:
278-
errorCode = secModule.VerifySignature(context, ref sdcInOut, sequenceNumber);
279-
break;
280-
281-
default:
282-
NetEventSource.Fail(null, $"Unknown OP: {op}");
283-
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
284-
}
265+
OP.Encrypt => secModule.EncryptMessage(context, ref sdcInOut, sequenceNumber),
266+
OP.Decrypt => secModule.DecryptMessage(context, ref sdcInOut, sequenceNumber),
267+
OP.MakeSignature => secModule.MakeSignature(context, ref sdcInOut, sequenceNumber),
268+
_ /* OP.VerifySignature */ => secModule.VerifySignature(context, ref sdcInOut, sequenceNumber),
269+
};
285270

286271
// Marshalling back returned sizes / data.
287272
for (int i = 0; i < input.Length; i++)
@@ -320,35 +305,23 @@ private static unsafe int EncryptDecryptHelper(OP op, ISSPIInterface secModule,
320305

321306
if (j >= input.Length)
322307
{
323-
NetEventSource.Fail(null, "Output buffer out of range.");
308+
Debug.Fail("Output buffer out of range.");
324309
iBuffer.size = 0;
325310
iBuffer.offset = 0;
326311
iBuffer.token = null;
327312
}
328313
}
329314

330315
// Backup validate the new sizes.
331-
if (iBuffer.offset < 0 || iBuffer.offset > (iBuffer.token == null ? 0 : iBuffer.token.Length))
332-
{
333-
NetEventSource.Fail(null, $"'offset' out of range. [{iBuffer.offset}]");
334-
}
335-
336-
if (iBuffer.size < 0 || iBuffer.size > (iBuffer.token == null ? 0 : iBuffer.token.Length - iBuffer.offset))
337-
{
338-
NetEventSource.Fail(null, $"'size' out of range. [{iBuffer.size}]");
339-
}
316+
Debug.Assert(iBuffer.offset >= 0 && iBuffer.offset <= (iBuffer.token == null ? 0 : iBuffer.token.Length), $"'offset' out of range. [{iBuffer.offset}]");
317+
Debug.Assert(iBuffer.size >= 0 && iBuffer.size <= (iBuffer.token == null ? 0 : iBuffer.token.Length - iBuffer.offset), $"'size' out of range. [{iBuffer.size}]");
340318
}
341319

342320
if (NetEventSource.Log.IsEnabled() && errorCode != 0)
343321
{
344-
if (errorCode == Interop.SspiCli.SEC_I_RENEGOTIATE)
345-
{
346-
NetEventSource.Error(null, SR.Format(SR.event_OperationReturnedSomething, op, "SEC_I_RENEGOTIATE"));
347-
}
348-
else
349-
{
350-
NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, op, $"0x{0:X}"));
351-
}
322+
NetEventSource.Error(null, errorCode == Interop.SspiCli.SEC_I_RENEGOTIATE ?
323+
SR.Format(SR.event_OperationReturnedSomething, op, "SEC_I_RENEGOTIATE") :
324+
SR.Format(SR.net_log_operation_failed_with_error, op, $"0x{0:X}"));
352325
}
353326

354327
return errorCode;

src/libraries/Common/src/System/Net/ContextAwareResult.cs

Lines changed: 8 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
#nullable enable
5+
using System.Diagnostics;
56
using System.Threading;
67

78
namespace System.Net
@@ -130,11 +131,7 @@ internal ExecutionContext? ContextCopy
130131
{
131132
if (InternalPeekCompleted)
132133
{
133-
if ((_flags & StateFlags.ThreadSafeContextCopy) == 0)
134-
{
135-
NetEventSource.Fail(this, "Called on completed result.");
136-
}
137-
134+
Debug.Assert((_flags & StateFlags.ThreadSafeContextCopy) != 0, "Called on completed result.");
138135
throw new InvalidOperationException(SR.net_completed_result);
139136
}
140137

@@ -145,29 +142,19 @@ internal ExecutionContext? ContextCopy
145142
}
146143

147144
// Make sure the context was requested.
148-
if (AsyncCallback == null && (_flags & StateFlags.CaptureContext) == 0)
149-
{
150-
NetEventSource.Fail(this, "No context captured - specify a callback or forceCaptureContext.");
151-
}
145+
Debug.Assert(AsyncCallback != null || (_flags & StateFlags.CaptureContext) != 0, "No context captured - specify a callback or forceCaptureContext.");
152146

153147
// Just use the lock to block. We might be on the thread that owns the lock which is great, it means we
154148
// don't need a context anyway.
155149
if ((_flags & StateFlags.PostBlockFinished) == 0)
156150
{
157-
if (_lock == null)
158-
{
159-
NetEventSource.Fail(this, "Must lock (StartPostingAsyncOp()) { ... FinishPostingAsyncOp(); } when calling ContextCopy (unless it's only called after FinishPostingAsyncOp).");
160-
}
151+
Debug.Assert(_lock != null, "Must lock (StartPostingAsyncOp()) { ... FinishPostingAsyncOp(); } when calling ContextCopy (unless it's only called after FinishPostingAsyncOp).");
161152
lock (_lock) { }
162153
}
163154

164155
if (InternalPeekCompleted)
165156
{
166-
if ((_flags & StateFlags.ThreadSafeContextCopy) == 0)
167-
{
168-
NetEventSource.Fail(this, "Result became completed during call.");
169-
}
170-
157+
Debug.Assert((_flags & StateFlags.ThreadSafeContextCopy) != 0, "Result became completed during call.");
171158
throw new InvalidOperationException(SR.net_completed_result);
172159
}
173160

@@ -197,11 +184,7 @@ internal object StartPostingAsyncOp()
197184
// object from being created.
198185
internal object? StartPostingAsyncOp(bool lockCapture)
199186
{
200-
if (InternalPeekCompleted)
201-
{
202-
NetEventSource.Fail(this, "Called on completed result.");
203-
}
204-
187+
Debug.Assert(!InternalPeekCompleted, "Called on completed result.");
205188
DebugProtectState(true);
206189

207190
_lock = lockCapture ? new object() : null;
@@ -285,10 +268,7 @@ protected override void Cleanup()
285268
// Returns whether the operation completed sync or not.
286269
private bool CaptureOrComplete(ref ExecutionContext? cachedContext, bool returnContext)
287270
{
288-
if ((_flags & StateFlags.PostBlockStarted) == 0)
289-
{
290-
NetEventSource.Fail(this, "Called without calling StartPostingAsyncOp.");
291-
}
271+
Debug.Assert((_flags & StateFlags.PostBlockStarted) != 0, "Called without calling StartPostingAsyncOp.");
292272

293273
// See if we're going to need to capture the context.
294274
bool capturingContext = AsyncCallback != null || (_flags & StateFlags.CaptureContext) != 0;
@@ -334,10 +314,7 @@ private bool CaptureOrComplete(ref ExecutionContext? cachedContext, bool returnC
334314
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Skipping capture");
335315

336316
cachedContext = null;
337-
if (AsyncCallback != null && !CompletedSynchronously)
338-
{
339-
NetEventSource.Fail(this, "Didn't capture context, but didn't complete synchronously!");
340-
}
317+
Debug.Assert(AsyncCallback == null || CompletedSynchronously, "Didn't capture context, but didn't complete synchronously!");
341318
}
342319

343320
// Now we want to see for sure what to do. We might have just captured the context for no reason.

src/libraries/Common/src/System/Net/Http/aspnetcore/NetEventSource.Common.cs

Lines changed: 1 addition & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,6 @@ namespace System.Net
3535
// NetEventSource.Info(this, "literal string"); // arbitrary message with a literal string
3636
// Debug.Asserts inside the logging methods will help to flag some misuse if the DEBUG_NETEVENTSOURCE_MISUSE compilation constant is defined.
3737
// However, because it can be difficult by observation to understand all of the costs involved, guarding can be done everywhere.
38-
// - NetEventSource.Fail calls typically do not need to be prefixed with an IsEnabled check, even if they allocate, as FailMessage
39-
// should only be used in cases similar to Debug.Fail, where they are not expected to happen in retail builds, and thus extra costs
40-
// don't matter.
4138
// - Messages can be strings, formattable strings, or any other object. Objects (including those used in formattable strings) have special
4239
// formatting applied, controlled by the Format method. Partial specializations can also override this formatting by implementing a partial
4340
// method that takes an object and optionally provides a string representation of it, in case a particular library wants to customize further.
@@ -70,7 +67,6 @@ public class Keywords
7067
private const int AssociateEventId = 3;
7168
private const int InfoEventId = 4;
7269
private const int ErrorEventId = 5;
73-
private const int CriticalFailureEventId = 6;
7470
private const int DumpArrayEventId = 7;
7571

7672
// These events are implemented in NetEventSource.Security.cs.
@@ -253,40 +249,6 @@ private void ErrorMessage(string thisOrContextObject, string? memberName, string
253249
WriteEvent(ErrorEventId, thisOrContextObject, memberName ?? MissingMember, message);
254250
#endregion
255251

256-
#region Fail
257-
/// <summary>Logs a fatal error and raises an assert.</summary>
258-
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
259-
/// <param name="formattableString">The message to be logged.</param>
260-
/// <param name="memberName">The calling member.</param>
261-
[NonEvent]
262-
public static void Fail(object? thisOrContextObject, FormattableString formattableString, [CallerMemberName] string? memberName = null)
263-
{
264-
// Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
265-
// that should never happen in production, and thus we don't care about extra costs.
266-
267-
if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(formattableString));
268-
Debug.Fail(Format(formattableString), $"{IdOf(thisOrContextObject)}.{memberName}");
269-
}
270-
271-
/// <summary>Logs a fatal error and raises an assert.</summary>
272-
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
273-
/// <param name="message">The message to be logged.</param>
274-
/// <param name="memberName">The calling member.</param>
275-
[NonEvent]
276-
public static void Fail(object? thisOrContextObject, object message, [CallerMemberName] string? memberName = null)
277-
{
278-
// Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
279-
// that should never happen in production, and thus we don't care about extra costs.
280-
281-
if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(message).ToString());
282-
Debug.Fail(Format(message).ToString(), $"{IdOf(thisOrContextObject)}.{memberName}");
283-
}
284-
285-
[Event(CriticalFailureEventId, Level = EventLevel.Critical, Keywords = Keywords.Debug)]
286-
private void CriticalFailure(string thisOrContextObject, string? memberName, string? message) =>
287-
WriteEvent(CriticalFailureEventId, thisOrContextObject, memberName ?? MissingMember, message);
288-
#endregion
289-
290252
#region DumpBuffer
291253
/// <summary>Logs the contents of a buffer.</summary>
292254
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
@@ -307,14 +269,8 @@ public static void DumpBuffer(object? thisOrContextObject, byte[] buffer, [Calle
307269
[NonEvent]
308270
public static void DumpBuffer(object? thisOrContextObject, byte[] buffer, int offset, int count, [CallerMemberName] string? memberName = null)
309271
{
310-
if (IsEnabled)
272+
if (IsEnabled && offset >= 0 && offset <= buffer.Length - count)
311273
{
312-
if (offset < 0 || offset > buffer.Length - count)
313-
{
314-
Fail(thisOrContextObject, $"Invalid {nameof(DumpBuffer)} Args. Length={buffer.Length}, Offset={offset}, Count={count}", memberName);
315-
return;
316-
}
317-
318274
count = Math.Min(count, MaxDumpSize);
319275

320276
byte[] slice = buffer;

src/libraries/Common/src/System/Net/InternalException.cs

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,20 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
#nullable enable
5+
using System.Diagnostics;
6+
57
namespace System.Net
68
{
79
internal sealed class InternalException : Exception
810
{
911
private readonly object? _unexpectedValue;
1012

11-
internal InternalException()
12-
{
13-
NetEventSource.Fail(this, "InternalException thrown.");
14-
}
13+
internal InternalException() : this(null) { }
1514

16-
internal InternalException(object unexpectedValue)
15+
internal InternalException(object? unexpectedValue)
1716
{
17+
Debug.Fail($"InternalException thrown for unexpected value: {unexpectedValue}");
1818
_unexpectedValue = unexpectedValue;
19-
if (NetEventSource.Log.IsEnabled())
20-
{
21-
NetEventSource.Fail(this, $"InternalException thrown for unexpected value: {unexpectedValue}");
22-
}
2319
}
2420

2521
public override string Message => _unexpectedValue != null ?

src/libraries/Common/src/System/Net/LazyAsyncResult.cs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -257,15 +257,9 @@ internal object? Result
257257
// then the "result" parameter passed to InvokeCallback() will be ignored.
258258

259259
// It's an error to call after the result has been completed or with DBNull.
260-
if (value == DBNull.Value)
261-
{
262-
NetEventSource.Fail(this, "Result can't be set to DBNull - it's a special internal value.");
263-
}
260+
Debug.Assert(value != DBNull.Value, "Result can't be set to DBNull - it's a special internal value.");
264261

265-
if (InternalPeekCompleted)
266-
{
267-
NetEventSource.Fail(this, "Called on completed result.");
268-
}
262+
Debug.Assert(!InternalPeekCompleted, "Called on completed result.");
269263
_result = value;
270264
}
271265
}

0 commit comments

Comments
 (0)