From c26203ed3c3f599c50c756191624ec4210e5b2b0 Mon Sep 17 00:00:00 2001 From: Buyaa Namnan Date: Thu, 1 Oct 2020 09:39:38 -0700 Subject: [PATCH 1/3] Fix warnings revealed after enabling analyzer for projects not having access to RuntimeInformation, OSPlatofrm types --- .../Runtime/InteropServices/ComEventsSink.cs | 6 ++++++ .../System/Runtime/InteropServices/Variant.cs | 7 ++++++- .../ComInterop/ComEventSinksContainer.cs | 2 ++ .../RuntimeBinder/ComInterop/ComObject.cs | 2 ++ .../ComInterop/ComRuntimeHelpers.cs | 4 ++++ .../ComInterop/ComTypeClassDesc.cs | 2 ++ .../ComInterop/ComTypeEnumDesc.cs | 2 ++ .../ComInterop/DispatchArgBuilder.cs | 2 ++ .../ComInterop/IDispatchComObject.cs | 2 ++ .../ComInterop/Variant.Extended.cs | 2 ++ .../Diagnostics/PerformanceCounterLib.cs | 3 +++ .../src/System/Diagnostics/Process.Win32.cs | 2 ++ .../src/System/Diagnostics/Process.Windows.cs | 1 + .../Diagnostics/ProcessStartInfo.Win32.cs | 1 + .../ref/System.DirectoryServices.Protocols.cs | 2 ++ .../Protocols/common/DirectoryControl.cs | 3 +++ .../src/System/IO/FileSystemWatcher.Win32.cs | 3 +++ .../System/IO/IsolatedStorage/Helper.Win32.cs | 2 ++ .../ref/System.IO.Pipes.AccessControl.cs | 4 ++++ .../IO/Pipes/ConnectionCompletionSource.cs | 1 + .../IO/Pipes/NamedPipeClientStream.Windows.cs | 2 ++ .../IO/Pipes/NamedPipeServerStream.Windows.cs | 1 + .../src/System/IO/Pipes/PipeAccessRule.cs | 2 ++ .../src/System/IO/Pipes/PipeAuditRule.cs | 2 ++ .../System/IO/Pipes/PipeCompletionSource.cs | 6 +++++- .../src/System/IO/Pipes/PipeSecurity.cs | 2 ++ .../src/System/IO/Pipes/PipeStream.Windows.cs | 6 ++++++ .../src/System/IO/Pipes/PipesAclExtensions.cs | 2 ++ .../IO/Pipes/ReadWriteCompletionSource.cs | 1 + .../CurrentUserIdentityProvider.Windows.cs | 2 ++ .../Http/SocketsHttpHandler/HttpConnection.cs | 2 +- .../System/Net/Windows/AsyncRequestContext.cs | 3 +++ .../Net/Windows/HttpListener.Windows.cs | 6 ++++++ .../Windows/HttpListenerSession.Windows.cs | 3 +++ .../Net/Windows/HttpRequestStream.Windows.cs | 4 ++++ .../Windows/HttpResponseStreamAsyncResult.cs | 4 ++++ .../Windows/ListenerAsyncResult.Windows.cs | 1 + .../ListenerClientCertAsyncResult.Windows.cs | 5 +++++ .../WebSocketHttpListenerDuplexStream.cs | 2 ++ .../NetworkAddressChange.Windows.cs | 3 +++ .../Net/CertificateValidationPal.Windows.cs | 2 ++ .../Security/NegotiateStreamPal.Windows.cs | 1 + .../Net/Security/SslStreamPal.Windows.cs | 2 ++ .../ref/System.Runtime.InteropServices.cs | 1 + .../IDispatchConstantAttribute.cs | 2 ++ .../Cryptography/BasicSymmetricCipherCsp.cs | 1 + .../Cryptography/CapiHelper.Windows.cs | 6 +++++- .../DSACryptoServiceProvider.Windows.cs | 7 +++++++ .../PasswordDeriveBytes.Windows.cs | 2 ++ .../Cryptography/PasswordDeriveBytes.cs | 2 ++ .../RSACryptoServiceProvider.Windows.cs | 6 ++++++ .../Pal.Windows/CertificatePal.PrivateKey.cs | 21 +++++++++++++++++++ .../Pal.Windows/CertificatePal.cs | 1 + .../Pal.Windows/Native/SafeHandles.cs | 1 + .../Pal.Windows/X509Pal.PublicKey.cs | 8 +++++++ 55 files changed, 171 insertions(+), 4 deletions(-) diff --git a/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsSink.cs b/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsSink.cs index e9b6cd0370f6cf..11d1cfda361c58 100644 --- a/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsSink.cs +++ b/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsSink.cs @@ -215,7 +215,9 @@ unsafe void IDispatch.Invoke( // convert result to VARIANT if (pVarResult != IntPtr.Zero) { +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods Marshal.GetNativeVariantForObject(result, pVarResult); +#pragma warning restore CA1416 } // Now we need to marshal all the byrefs back @@ -237,7 +239,9 @@ CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out ppv = IntPtr.Zero; if (iid == _iidSourceItf || iid == typeof(IDispatch).GUID) { +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods ppv = Marshal.GetComInterfaceForObject(this, typeof(IDispatch), CustomQueryInterfaceMode.Ignore); +#pragma warning restore CA1416 return CustomQueryInterfaceResult.Handled; } @@ -267,7 +271,9 @@ private void Unadvise() try { _connectionPoint.Unadvise(_cookie); +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods Marshal.ReleaseComObject(_connectionPoint); +#pragma warning restore CA1416 } catch { diff --git a/src/libraries/Common/src/System/Runtime/InteropServices/Variant.cs b/src/libraries/Common/src/System/Runtime/InteropServices/Variant.cs index f845179c510664..6bb08e61754fe6 100644 --- a/src/libraries/Common/src/System/Runtime/InteropServices/Variant.cs +++ b/src/libraries/Common/src/System/Runtime/InteropServices/Variant.cs @@ -130,7 +130,7 @@ public unsafe void CopyFromIndirect(object value) } return; } - +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods if ((vt & VarEnum.VT_ARRAY) != 0) { Variant vArray; @@ -224,6 +224,7 @@ public unsafe void CopyFromIndirect(object value) default: throw new ArgumentException(); } +#pragma warning restore CA1416 } /// @@ -269,7 +270,9 @@ public unsafe void CopyFromIndirect(object value) { fixed (void* pThis = &this) { +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods return Marshal.GetObjectForNativeVariant((System.IntPtr)pThis); +#pragma warning restore CA1416 } } } @@ -645,6 +648,7 @@ public string AsBstr // VT_UNKNOWN +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods public object? AsUnknown { get @@ -698,6 +702,7 @@ public object? AsDispatch } } } +#pragma warning restore CA1416 public IntPtr AsByRefVariant { diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComEventSinksContainer.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComEventSinksContainer.cs index 2b9a068b3cc113..9e577e92151a59 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComEventSinksContainer.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComEventSinksContainer.cs @@ -22,6 +22,7 @@ private ComEventSinksContainer() public static ComEventSinksContainer FromRuntimeCallableWrapper(object rcw, bool createIfNotFound) { +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods object data = Marshal.GetComObjectData(rcw, s_comObjectEventSinksKey); if (data != null || createIfNotFound == false) { @@ -41,6 +42,7 @@ public static ComEventSinksContainer FromRuntimeCallableWrapper(object rcw, bool { throw Error.SetComObjectDataFailed(); } +#pragma warning restore CA1416 return comEventSinks; } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComObject.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComObject.cs index b4724ca2fccdce..d6cabc6cbc379c 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComObject.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComObject.cs @@ -34,6 +34,7 @@ public static ComObject ObjectToComObject(object rcw) { Debug.Assert(ComBinder.IsComObject(rcw)); +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods object data = Marshal.GetComObjectData(rcw, s_comObjectInfoKey); if (data != null) { @@ -53,6 +54,7 @@ public static ComObject ObjectToComObject(object rcw) { throw Error.SetComObjectDataFailed(); } +#pragma warning restore CA1416 return comObjectInfo; } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComRuntimeHelpers.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComRuntimeHelpers.cs index 475c2c5753bf15..47701f8774bcea 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComRuntimeHelpers.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComRuntimeHelpers.cs @@ -146,6 +146,7 @@ internal static ComTypes.ITypeInfo GetITypeInfoFromIDispatch(IDispatch dispatch) Marshal.ThrowExceptionForHR(ComHresults.E_FAIL); } +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods ComTypes.ITypeInfo typeInfo = null; try { @@ -155,6 +156,7 @@ internal static ComTypes.ITypeInfo GetITypeInfoFromIDispatch(IDispatch dispatch) { Marshal.Release(typeInfoPtr); } +#pragma warning restore CA1416 return typeInfo; } @@ -236,6 +238,7 @@ internal static Variant GetVariantForObject(object obj) return variant; } +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods internal static void InitVariantForObject(object obj, ref Variant variant) { Debug.Assert(obj != null); @@ -258,6 +261,7 @@ public static object GetObjectForVariant(Variant variant) IntPtr ptr = UnsafeMethods.ConvertVariantByrefToPtr(ref variant); return Marshal.GetObjectForNativeVariant(ptr); } +#pragma warning restore CA1416 // This method is intended for use through reflection and should only be used directly by IUnknownReleaseNotZero public static unsafe int IUnknownRelease(IntPtr interfacePointer) diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeClassDesc.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeClassDesc.cs index 1c33aff3b4358a..552d3f95a1e34d 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeClassDesc.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeClassDesc.cs @@ -17,11 +17,13 @@ internal class ComTypeClassDesc : ComTypeDesc, IDynamicMetaObjectProvider public object CreateInstance() { +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods if (_typeObj == null) { _typeObj = Type.GetTypeFromCLSID(Guid); } return Activator.CreateInstance(Type.GetTypeFromCLSID(Guid)); +#pragma warning restore CA1416 } internal ComTypeClassDesc(ComTypes.ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc) : diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeEnumDesc.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeEnumDesc.cs index 470f55e59a00b4..31905220b99449 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeEnumDesc.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeEnumDesc.cs @@ -43,7 +43,9 @@ internal ComTypeEnumDesc(ComTypes.ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc if (varDesc.varkind == ComTypes.VARKIND.VAR_CONST) { +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods memberValues[i] = Marshal.GetObjectForNativeVariant(varDesc.desc.lpvarValue); +#pragma warning restore CA1416 } } finally diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/DispatchArgBuilder.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/DispatchArgBuilder.cs index 2c0c9d05af987b..83740a168c0731 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/DispatchArgBuilder.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/DispatchArgBuilder.cs @@ -24,10 +24,12 @@ internal override Expression Marshal(Expression parameter) // parameter.WrappedObject if (_isWrapper) { +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods parameter = Expression.Property( Helpers.Convert(parameter, typeof(DispatchWrapper)), typeof(DispatchWrapper).GetProperty(nameof(DispatchWrapper.WrappedObject)) ); +#pragma warning restore CA1416 } return Helpers.Convert(parameter, typeof(object)); diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs index 4ce86951f1aa80..83ccfa70bda81a 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs @@ -477,6 +477,7 @@ private static ComTypes.ITypeInfo GetCoClassTypeInfo(object rcw, ComTypes.ITypeI if (rcw is IProvideClassInfo provideClassInfo) { IntPtr typeInfoPtr = IntPtr.Zero; +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods try { provideClassInfo.GetClassInfo(out typeInfoPtr); @@ -492,6 +493,7 @@ private static ComTypes.ITypeInfo GetCoClassTypeInfo(object rcw, ComTypes.ITypeI Marshal.Release(typeInfoPtr); } } +#pragma warning restore CA1416 } // retrieving class information through IPCI has failed - diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/Variant.Extended.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/Variant.Extended.cs index 777518d1a6dbcd..0ff0f770278483 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/Variant.Extended.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/Variant.Extended.cs @@ -157,7 +157,9 @@ public object AsVariant { get { +#pragma warning disable CA1416 // Validate platform compatibility, cannot use any of guard methods return Marshal.GetObjectForNativeVariant(UnsafeMethods.ConvertVariantByrefToPtr(ref this)); +#pragma warning restore CA1416 } set diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/PerformanceCounterLib.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/PerformanceCounterLib.cs index 08ff0741e0e1a8..d23f4021885abc 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/PerformanceCounterLib.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/PerformanceCounterLib.cs @@ -94,6 +94,7 @@ private Dictionary GetStringTable(bool isHelp) Dictionary stringTable; RegistryKey libraryKey; + Debug.Assert(OperatingSystem.IsWindows()); libraryKey = Registry.PerformanceData; try @@ -208,6 +209,7 @@ internal PerformanceMonitor(string machineName) [MemberNotNull(nameof(_perfDataKey))] private void Init() { + Debug.Assert(OperatingSystem.IsWindows()); if (ProcessManager.IsRemoteMachine(_machineName)) { _perfDataKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, _machineName); @@ -236,6 +238,7 @@ private void Init() byte[]? data = null; int error = 0; + Debug.Assert(OperatingSystem.IsWindows()); while (waitRetries > 0) { try diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs index 76419e195cee14..3bcd9de2a395e1 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs @@ -28,6 +28,7 @@ private bool StartCore(ProcessStartInfo startInfo) private unsafe bool StartWithShellExecuteEx(ProcessStartInfo startInfo) { + Debug.Assert(OperatingSystem.IsWindows()); if (!string.IsNullOrEmpty(startInfo.UserName) || startInfo.Password != null) throw new InvalidOperationException(SR.CantStartAsUser); @@ -166,6 +167,7 @@ public bool ShellExecuteOnSTAThread() { ThreadStart threadStart = new ThreadStart(ShellExecuteFunction); Thread executionThread = new Thread(threadStart) { IsBackground = true }; + Debug.Assert(OperatingSystem.IsWindows()); executionThread.SetApartmentState(ApartmentState.STA); executionThread.Start(); executionThread.Join(); diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs index 44323f9ef7111e..aebedb99a7a351 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs @@ -541,6 +541,7 @@ private unsafe bool StartWithCreateProcess(ProcessStartInfo startInfo) if (startInfo.UserName.Length != 0) { + Debug.Assert(OperatingSystem.IsWindows()); if (startInfo.Password != null && startInfo.PasswordInClearText != null) { throw new ArgumentException(SR.CantSetDuplicatePassword); diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.Win32.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.Win32.cs index 6b3503675d0be3..e68762ef950aba 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.Win32.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.Win32.cs @@ -17,6 +17,7 @@ public string[] Verbs if (string.IsNullOrEmpty(extension)) return Array.Empty(); + Debug.Assert(OperatingSystem.IsWindows()); using (RegistryKey? key = Registry.ClassesRoot.OpenSubKey(extension)) { if (key == null) diff --git a/src/libraries/System.DirectoryServices.Protocols/ref/System.DirectoryServices.Protocols.cs b/src/libraries/System.DirectoryServices.Protocols/ref/System.DirectoryServices.Protocols.cs index 8f6e8b6270f59f..5521b3d8cb45ed 100644 --- a/src/libraries/System.DirectoryServices.Protocols/ref/System.DirectoryServices.Protocols.cs +++ b/src/libraries/System.DirectoryServices.Protocols/ref/System.DirectoryServices.Protocols.cs @@ -469,7 +469,9 @@ public partial class PermissiveModifyControl : System.DirectoryServices.Protocol public partial class QuotaControl : System.DirectoryServices.Protocols.DirectoryControl { public QuotaControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } + [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public QuotaControl(System.Security.Principal.SecurityIdentifier querySid) : base (default(string), default(byte[]), default(bool), default(bool)) { } + [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public System.Security.Principal.SecurityIdentifier QuerySid { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs index 4341ca2c60d469..9e3bd91f6506cd 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs @@ -7,6 +7,7 @@ using System.Text; using System.Runtime.InteropServices; using System.Security.Principal; +using System.Runtime.Versioning; namespace System.DirectoryServices.Protocols { @@ -1026,11 +1027,13 @@ public class QuotaControl : DirectoryControl public QuotaControl() : base("1.2.840.113556.1.4.1852", null, true, true) { } + [SupportedOSPlatform("windows")] public QuotaControl(SecurityIdentifier querySid) : this() { QuerySid = querySid; } + [SupportedOSPlatform("windows")] public SecurityIdentifier QuerySid { get => _sid == null ? null : new SecurityIdentifier(_sid, 0); diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs index 96d601de841b8b..b1bed69783bb09 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs @@ -51,6 +51,7 @@ private void StartRaisingEvents() int session = Interlocked.Increment(ref _currentSession); byte[] buffer = AllocateBuffer(); + Debug.Assert(OperatingSystem.IsWindows()); // Store all state, including a preallocated overlapped, into the state object that'll be // passed from iteration to iteration during the lifetime of the operation. The buffer will be pinned // from now until the end of the operation. @@ -59,6 +60,7 @@ private void StartRaisingEvents() { state.PreAllocatedOverlapped = new PreAllocatedOverlapped((errorCode, numBytes, overlappedPointer) => { + Debug.Assert(OperatingSystem.IsWindows()); AsyncReadState state = (AsyncReadState)ThreadPoolBoundHandle.GetNativeOverlappedState(overlappedPointer)!; state.ThreadPoolBinding.FreeNativeOverlapped(overlappedPointer); if (state.WeakWatcher.TryGetTarget(out FileSystemWatcher? watcher)) @@ -153,6 +155,7 @@ private unsafe void Monitor(AsyncReadState state) if (!_enabled || IsHandleInvalid(state.DirectoryHandle)) return; + Debug.Assert(OperatingSystem.IsWindows()); // Get the overlapped pointer to use for this iteration. overlappedPointer = state.ThreadPoolBinding.AllocateNativeOverlapped(state.PreAllocatedOverlapped); continueExecuting = Interop.Kernel32.ReadDirectoryChangesW( diff --git a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/Helper.Win32.cs b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/Helper.Win32.cs index 3a51074260637d..959a38b4c68bc0 100644 --- a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/Helper.Win32.cs +++ b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/Helper.Win32.cs @@ -1,6 +1,7 @@ // 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.Security.AccessControl; using System.Security.Principal; @@ -35,6 +36,7 @@ internal static void CreateDirectory(string path, IsolatedStorageScope scope) // (But applies CREATOR OWNER as expected for items and subdirectories.) Setting up front when creating the directory // doesn't exhibit this behavior, but as we can't currently do that we'll take the rough equivalent for now. + Debug.Assert(OperatingSystem.IsWindows()); DirectorySecurity security = new DirectorySecurity(); // Don't inherit the existing rules diff --git a/src/libraries/System.IO.Pipes.AccessControl/ref/System.IO.Pipes.AccessControl.cs b/src/libraries/System.IO.Pipes.AccessControl/ref/System.IO.Pipes.AccessControl.cs index 38f133af27cccc..4f65b4fada484d 100644 --- a/src/libraries/System.IO.Pipes.AccessControl/ref/System.IO.Pipes.AccessControl.cs +++ b/src/libraries/System.IO.Pipes.AccessControl/ref/System.IO.Pipes.AccessControl.cs @@ -27,23 +27,27 @@ public enum PipeAccessRights FullControl = 2032031, AccessSystemSecurity = 16777216, } + [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public sealed partial class PipeAccessRule : System.Security.AccessControl.AccessRule { public PipeAccessRule(System.Security.Principal.IdentityReference identity, System.IO.Pipes.PipeAccessRights rights, System.Security.AccessControl.AccessControlType type) : base (default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AccessControlType)) { } public PipeAccessRule(string identity, System.IO.Pipes.PipeAccessRights rights, System.Security.AccessControl.AccessControlType type) : base (default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AccessControlType)) { } public System.IO.Pipes.PipeAccessRights PipeAccessRights { get { throw null; } } } + [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public sealed partial class PipeAuditRule : System.Security.AccessControl.AuditRule { public PipeAuditRule(System.Security.Principal.IdentityReference identity, System.IO.Pipes.PipeAccessRights rights, System.Security.AccessControl.AuditFlags flags) : base (default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AuditFlags)) { } public PipeAuditRule(string identity, System.IO.Pipes.PipeAccessRights rights, System.Security.AccessControl.AuditFlags flags) : base (default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AuditFlags)) { } public System.IO.Pipes.PipeAccessRights PipeAccessRights { get { throw null; } } } + [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public static partial class PipesAclExtensions { public static System.IO.Pipes.PipeSecurity GetAccessControl(this System.IO.Pipes.PipeStream stream) { throw null; } public static void SetAccessControl(this System.IO.Pipes.PipeStream stream, System.IO.Pipes.PipeSecurity pipeSecurity) { } } + [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public partial class PipeSecurity : System.Security.AccessControl.NativeObjectSecurity { public PipeSecurity() : base (default(bool), default(System.Security.AccessControl.ResourceType)) { } diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/ConnectionCompletionSource.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/ConnectionCompletionSource.cs index 96d94e0ab53672..5d5d5b9ea87eec 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/ConnectionCompletionSource.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/ConnectionCompletionSource.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.ExceptionServices; +using System.Runtime.Versioning; using System.Threading; namespace System.IO.Pipes diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.Windows.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.Windows.cs index a082a3da863972..4b8ecf7db24b92 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.Windows.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.Windows.cs @@ -7,6 +7,7 @@ using System.Threading; using Microsoft.Win32.SafeHandles; using System.Runtime.Versioning; +using System.Diagnostics; namespace System.IO.Pipes { @@ -135,6 +136,7 @@ private void ValidateRemotePipeUser() if (!IsCurrentUserOnly) return; + Debug.Assert(OperatingSystem.IsWindows()); PipeSecurity accessControl = this.GetAccessControl(); IdentityReference? remoteOwnerSid = accessControl.GetOwner(typeof(SecurityIdentifier)); using (WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent()) diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Windows.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Windows.cs index 8168691c9a93ff..b93118faeb111f 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Windows.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Windows.cs @@ -72,6 +72,7 @@ private void Create(string pipeName, PipeDirection direction, int maxNumberOfSer if (IsCurrentUserOnly) { Debug.Assert(pipeSecurity == null); + Debug.Assert(OperatingSystem.IsWindows()); using (WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent()) { diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeAccessRule.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeAccessRule.cs index 35d1b9702419dc..c43045a8b9e183 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeAccessRule.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeAccessRule.cs @@ -1,11 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Runtime.Versioning; using System.Security.AccessControl; using System.Security.Principal; namespace System.IO.Pipes { + [SupportedOSPlatform("windows")] public sealed class PipeAccessRule : AccessRule { // diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeAuditRule.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeAuditRule.cs index ad8dc528f9f1be..63ad8432fb3a6c 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeAuditRule.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeAuditRule.cs @@ -1,11 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Runtime.Versioning; using System.Security.AccessControl; using System.Security.Principal; namespace System.IO.Pipes { + [SupportedOSPlatform("windows")] public sealed class PipeAuditRule : AuditRule { public PipeAuditRule( diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs index 118463c35d0f7f..f43caf333dc0f5 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs @@ -4,6 +4,7 @@ using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; +using System.Runtime.Versioning; using System.Security; using System.Threading; using System.Threading.Tasks; @@ -29,7 +30,6 @@ internal abstract unsafe class PipeCompletionSource : TaskCompletionSou #if DEBUG private bool _cancellationHasBeenRegistered; #endif - // Using RunContinuationsAsynchronously for compat reasons (old API used ThreadPool.QueueUserWorkItem for continuations) protected PipeCompletionSource(ThreadPoolBoundHandle handle, ReadOnlyMemory bufferToPin) : base(TaskCreationOptions.RunContinuationsAsynchronously) @@ -40,8 +40,10 @@ protected PipeCompletionSource(ThreadPoolBoundHandle handle, ReadOnlyMemory { + Debug.Assert(OperatingSystem.IsWindows()); var completionSource = (PipeCompletionSource)ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped)!; Debug.Assert(completionSource.Overlapped == pOverlapped); @@ -98,6 +100,7 @@ internal void ReleaseResources() // (this is why we disposed the registration above) if (_overlapped != null) { + Debug.Assert(OperatingSystem.IsWindows()); _threadPoolBinding.FreeNativeOverlapped(Overlapped); _overlapped = null; } @@ -138,6 +141,7 @@ protected virtual void AsyncCallback(uint errorCode, uint numBytes) private void Cancel() { + Debug.Assert(OperatingSystem.IsWindows()); SafeHandle handle = _threadPoolBinding.Handle; NativeOverlapped* overlapped = Overlapped; diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeSecurity.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeSecurity.cs index c37f180e35df93..4f351b41f79e0d 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeSecurity.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeSecurity.cs @@ -5,9 +5,11 @@ using System.Security.AccessControl; using System.Security.Principal; using System.Runtime.InteropServices; +using System.Runtime.Versioning; namespace System.IO.Pipes { + [SupportedOSPlatform("windows")] public class PipeSecurity : NativeObjectSecurity { public PipeSecurity() diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs index b221c9880b6cfa..e2de17b78a3c44 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs @@ -41,6 +41,7 @@ internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) /// The handle. private void InitializeAsyncHandle(SafePipeHandle handle) { + Debug.Assert(OperatingSystem.IsWindows()); // If the handle is of async type, bind the handle to the ThreadPool so that we can use // the async operations (it's needed so that our native callbacks get called). _threadPoolBinding = ThreadPoolBoundHandle.BindHandle(handle); @@ -50,6 +51,7 @@ private void DisposeCore(bool disposing) { if (disposing) { + Debug.Assert(OperatingSystem.IsWindows()); _threadPoolBinding?.Dispose(); } } @@ -113,6 +115,7 @@ private ValueTask ReadAsyncCore(Memory buffer, CancellationToken canc unsafe { + Debug.Assert(OperatingSystem.IsWindows()); // Clear the overlapped status bit for this special case. Failure to do so looks // like we are freeing a pending overlapped. completionSource.Overlapped->InternalLow = IntPtr.Zero; @@ -212,6 +215,7 @@ public unsafe virtual PipeTransmissionMode TransmissionMode } if ((pipeFlags & Interop.Kernel32.PipeOptions.PIPE_TYPE_MESSAGE) != 0) { + Debug.Assert(OperatingSystem.IsWindows()); return PipeTransmissionMode.Message; } else @@ -407,6 +411,7 @@ internal static unsafe Interop.Kernel32.SECURITY_ATTRIBUTES GetSecAttrs(HandleIn if (pipeSecurity != null) { + Debug.Assert(OperatingSystem.IsWindows()); byte[] securityDescriptor = pipeSecurity.GetSecurityDescriptorBinaryForm(); pinningHandle = GCHandle.Alloc(securityDescriptor, GCHandleType.Pinned); fixed (byte* pSecurityDescriptor = securityDescriptor) @@ -433,6 +438,7 @@ private unsafe void UpdateReadMode() if ((flags & Interop.Kernel32.PipeOptions.PIPE_READMODE_MESSAGE) != 0) { + Debug.Assert(OperatingSystem.IsWindows()); _readMode = PipeTransmissionMode.Message; } else diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipesAclExtensions.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipesAclExtensions.cs index 6ebcb91b312920..f31839385243c1 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipesAclExtensions.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipesAclExtensions.cs @@ -2,10 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.IO; +using System.Runtime.Versioning; using System.Security.AccessControl; namespace System.IO.Pipes { + [SupportedOSPlatform("windows")] public static class PipesAclExtensions { public static PipeSecurity GetAccessControl(this PipeStream stream) diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/ReadWriteCompletionSource.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/ReadWriteCompletionSource.cs index af6ad5a99d92a1..370f09a846dc2f 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/ReadWriteCompletionSource.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/ReadWriteCompletionSource.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.ExceptionServices; +using System.Runtime.Versioning; using System.Threading; namespace System.IO.Pipes diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/CurrentUserIdentityProvider.Windows.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/CurrentUserIdentityProvider.Windows.cs index 9108be362d7627..03739ae0e51d50 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/CurrentUserIdentityProvider.Windows.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/CurrentUserIdentityProvider.Windows.cs @@ -1,6 +1,7 @@ // 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.Security.Principal; namespace System.Net.Http @@ -9,6 +10,7 @@ internal static class CurrentUserIdentityProvider { public static string GetIdentity() { + Debug.Assert(OperatingSystem.IsWindows()); using WindowsIdentity identity = WindowsIdentity.GetCurrent(); return identity.Name; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs index ca579ec3ae4034..98b8c115fc596d 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs @@ -748,7 +748,7 @@ public async Task SendAsyncCore(HttpRequestMessage request, // Map the exception the same way as we normally do. catch (Exception ex) when (MapSendException(ex, cancellationToken, out Exception mappedEx)) { - throw mappedEx; + throw; } } LogExceptions(sendRequestContentTask); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs index 8af3aa485366f7..6e2350fc479b99 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs @@ -37,6 +37,7 @@ internal AsyncRequestContext(ThreadPoolBoundHandle boundHandle, ListenerAsyncRes private Interop.HttpApi.HTTP_REQUEST* Allocate(ThreadPoolBoundHandle boundHandle, uint size) { + Debug.Assert(OperatingSystem.IsWindows()); uint newSize = size != 0 ? size : RequestBuffer == IntPtr.Zero ? 4096 : Size; if (_nativeOverlapped != null) { @@ -75,6 +76,7 @@ protected override void OnReleasePins() NativeOverlapped* nativeOverlapped = _nativeOverlapped; _nativeOverlapped = null; + Debug.Assert(OperatingSystem.IsWindows()); _boundHandle!.FreeNativeOverlapped(nativeOverlapped); } } @@ -89,6 +91,7 @@ protected override void Dispose(bool disposing) #if DEBUG DebugRefCountReleaseNativeOverlapped(); #endif + Debug.Assert(OperatingSystem.IsWindows()); _boundHandle!.FreeNativeOverlapped(_nativeOverlapped); } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs index 2d47b0ff70c401..d3153c453ba728 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs @@ -703,6 +703,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) WindowsPrincipal? principal = disconnectResult?.AuthenticatedConnection; if (principal != null) { + Debug.Assert(OperatingSystem.IsWindows()); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Principal: {principal} principal.Identity.Name: {principal.Identity.Name} creating request"); stoleBlob = true; HttpListenerContext ntlmContext = new HttpListenerContext(session, memoryBlob); @@ -967,6 +968,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) $"HandleAuthentication creating new WindowsIdentity from user context: {userContext.DangerousGetHandle().ToString("x8")}"); } + Debug.Assert(OperatingSystem.IsWindows()); WindowsPrincipal windowsPrincipal = new WindowsPrincipal( new WindowsIdentity(userContext.DangerousGetHandle(), context.ProtocolName)); @@ -1836,6 +1838,7 @@ internal unsafe DisconnectAsyncResult(HttpListenerSession session, ulong connect _listenerSession = session; _connectionId = connectionId; + Debug.Assert(OperatingSystem.IsWindows()); // we can call the Unsafe API here, we won't ever call user code _nativeOverlapped = session.RequestQueueBoundHandle.AllocateNativeOverlapped(s_IOCallback, state: this, pinData: null); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info($"DisconnectAsyncResult: ThreadPoolBoundHandle.AllocateNativeOverlapped({session.RequestQueueBoundHandle}) -> {_nativeOverlapped->GetHashCode()}"); @@ -1874,6 +1877,7 @@ private static unsafe void IOCompleted(DisconnectAsyncResult asyncResult, uint e { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, "_connectionId:" + asyncResult._connectionId); + Debug.Assert(OperatingSystem.IsWindows()); asyncResult._listenerSession.RequestQueueBoundHandle.FreeNativeOverlapped(nativeOverlapped); if (Interlocked.Exchange(ref asyncResult._ownershipState, 2) == 0) { @@ -1884,6 +1888,7 @@ private static unsafe void IOCompleted(DisconnectAsyncResult asyncResult, uint e private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode: {errorCode}, numBytes: {numBytes}, nativeOverlapped: {((IntPtr)nativeOverlapped).ToString("x")}"); + Debug.Assert(OperatingSystem.IsWindows()); // take the DisconnectAsyncResult object from the state DisconnectAsyncResult asyncResult = (DisconnectAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; IOCompleted(asyncResult, errorCode, numBytes, nativeOverlapped); @@ -1903,6 +1908,7 @@ private void HandleDisconnect() // Clean up the identity. This is for scenarios where identity was not cleaned up before due to // identity caching for unsafe ntlm authentication + Debug.Assert(OperatingSystem.IsWindows()); IDisposable? identity = _authenticatedConnection == null ? null : _authenticatedConnection.Identity as IDisposable; if ((identity != null) && (_authenticatedConnection!.Identity.AuthenticationType == AuthenticationTypes.NTLM) && diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs index 777335be91a983..2fd0d36eb77933 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs @@ -1,6 +1,7 @@ // 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.Runtime.InteropServices; using System.Threading; @@ -22,6 +23,7 @@ public ThreadPoolBoundHandle RequestQueueBoundHandle { if (_requestQueueBoundHandle == null) { + Debug.Assert(OperatingSystem.IsWindows()); _requestQueueBoundHandle = ThreadPoolBoundHandle.BindHandle(RequestQueueHandle); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info($"ThreadPoolBoundHandle.BindHandle({RequestQueueHandle}) -> {_requestQueueBoundHandle}"); } @@ -65,6 +67,7 @@ public unsafe void CloseRequestQueueHandle() if (!RequestQueueHandle.IsInvalid) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info($"Dispose ThreadPoolBoundHandle: {_requestQueueBoundHandle}"); + Debug.Assert(OperatingSystem.IsWindows()); _requestQueueBoundHandle?.Dispose(); RequestQueueHandle.Dispose(); 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 3eadb3cf7e5e4a..4f85b42b286b17 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 @@ -1,6 +1,7 @@ // 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.IO; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; @@ -295,6 +296,7 @@ internal HttpRequestStreamAsyncResult(ThreadPoolBoundHandle boundHandle, object { _dataAlreadyRead = dataAlreadyRead; _boundHandle = boundHandle; + Debug.Assert(OperatingSystem.IsWindows()); _pOverlapped = boundHandle.AllocateNativeOverlapped(s_IOCallback, state: this, pinData: buffer); _pPinnedBuffer = (void*)(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset)); } @@ -331,6 +333,7 @@ private static void IOCompleted(HttpRequestStreamAsyncResult asyncResult, uint e private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { + Debug.Assert(OperatingSystem.IsWindows()); HttpRequestStreamAsyncResult asyncResult = (HttpRequestStreamAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes} nativeOverlapped:0x {((IntPtr)nativeOverlapped).ToString("x8")}"); @@ -344,6 +347,7 @@ protected override void Cleanup() base.Cleanup(); if (_pOverlapped != null) { + Debug.Assert(OperatingSystem.IsWindows()); _boundHandle!.FreeNativeOverlapped(_pOverlapped); } } 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 5a41b0ddeed6a9..416654849a9927 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 @@ -1,6 +1,7 @@ // 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.Runtime.InteropServices; using System.Threading; @@ -114,6 +115,7 @@ internal HttpResponseStreamAsyncResult(object asyncObject, object? userState, As _boundHandle = boundHandle; _sentHeaders = sentHeaders; + Debug.Assert(OperatingSystem.IsWindows()); if (size == 0) { _dataChunks = null; @@ -219,6 +221,7 @@ private static void IOCompleted(HttpResponseStreamAsyncResult asyncResult, uint private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { + Debug.Assert(OperatingSystem.IsWindows()); object state = ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; HttpResponseStreamAsyncResult asyncResult = (state as HttpResponseStreamAsyncResult)!; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, "errorCode:0x" + errorCode.ToString("x8") + " numBytes:" + numBytes + " nativeOverlapped:0x" + ((IntPtr)nativeOverlapped).ToString("x8")); @@ -232,6 +235,7 @@ protected override void Cleanup() base.Cleanup(); if (_pOverlapped != null) { + Debug.Assert(OperatingSystem.IsWindows()); _boundHandle!.FreeNativeOverlapped(_pOverlapped); } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs index b36252e9de8222..1846f6518fed77 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs @@ -96,6 +96,7 @@ private static void IOCompleted(ListenerAsyncResult asyncResult, uint errorCode, private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { + Debug.Assert(OperatingSystem.IsWindows()); ListenerAsyncResult asyncResult = (ListenerAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; IOCompleted(asyncResult, errorCode, numBytes); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs index 50521139e7619c..adce0b624a367f 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs @@ -1,6 +1,7 @@ // 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.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; @@ -49,6 +50,7 @@ internal void Reset(uint size) { return; } + Debug.Assert(OperatingSystem.IsWindows()); if (_size != 0) { _boundHandle!.FreeNativeOverlapped(_pOverlapped); @@ -162,6 +164,7 @@ private static unsafe void IOCompleted(ListenerClientCertAsyncResult asyncResult private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { + Debug.Assert(OperatingSystem.IsWindows()); ListenerClientCertAsyncResult asyncResult = (ListenerClientCertAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode:[{errorCode}] numBytes:[{numBytes}] nativeOverlapped:[{((long)nativeOverlapped)}]"); IOCompleted(asyncResult, errorCode, numBytes); @@ -173,6 +176,7 @@ protected override void Cleanup() if (_pOverlapped != null) { _memoryBlob = null; + Debug.Assert(OperatingSystem.IsWindows()); _boundHandle!.FreeNativeOverlapped(_pOverlapped); _pOverlapped = null; _boundHandle = null; @@ -185,6 +189,7 @@ protected override void Cleanup() { if (_pOverlapped != null && !Environment.HasShutdownStarted) { + Debug.Assert(OperatingSystem.IsWindows()); _boundHandle!.FreeNativeOverlapped(_pOverlapped); _pOverlapped = null; // Must do this in case application calls GC.ReRegisterForFinalize(). _boundHandle = null; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs index 1a07f99cb8686b..5bce6dd475cf92 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs @@ -908,6 +908,7 @@ private unsafe void InitializeOverlapped(ThreadPoolBoundHandle boundHandle) DebugRefCountAllocNativeOverlapped(); #endif _boundHandle = boundHandle; + Debug.Assert(OperatingSystem.IsWindows()); _ptrNativeOverlapped = boundHandle.AllocateNativeOverlapped(CompletionPortCallback, null, null); } @@ -922,6 +923,7 @@ private unsafe void FreeOverlapped(bool checkForShutdown) #if DEBUG DebugRefCountReleaseNativeOverlapped(); #endif + Debug.Assert(OperatingSystem.IsWindows()); _boundHandle!.FreeNativeOverlapped(_ptrNativeOverlapped); _ptrNativeOverlapped = null; } 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 6f644daafe4923..d13b7bab42e908 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 @@ -4,6 +4,7 @@ using Microsoft.Win32.SafeHandles; using System.Collections.Generic; +using System.Diagnostics; using System.Net.Sockets; using System.Threading; @@ -229,6 +230,8 @@ private static void StartHelper(NetworkAddressChangedEventHandler? caller, bool if (!s_isPending) { + Debug.Assert(OperatingSystem.IsWindows()); + if (Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0) { ThreadPool.RegisterWaitForSingleObject( diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs index 557b2e2e4e0904..ca2846e33f37fd 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; +using System.Diagnostics; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Cryptography; @@ -175,6 +176,7 @@ internal static X509Store OpenStore(StoreLocation storeLocation) // For app-compat We want to ensure the store is opened under the **process** account. try { + Debug.Assert(OperatingSystem.IsWindows()); WindowsIdentity.RunImpersonated(SafeAccessTokenHandle.InvalidHandle, () => { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs index e21530a82c854d..85276a42cf08ba 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs @@ -48,6 +48,7 @@ internal static IIdentity GetIdentity(NTAuthentication context) } string authtype = context.ProtocolName; + Debug.Assert(OperatingSystem.IsWindows()); // The following call was also specifying WindowsAccountType.Normal, true. // WindowsIdentity.IsAuthenticated is no longer supported in .NET Core result = new WindowsIdentity(token.DangerousGetHandle(), authtype); diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs index 4c3c2c22db42e0..ba419ac7f1b9c5 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs @@ -506,6 +506,7 @@ private static unsafe SafeFreeCredentials AcquireCredentialsHandle(Interop.SspiC // // For app-compat we want to ensure the credential are accessed under >>process<< account. // + Debug.Assert(OperatingSystem.IsWindows()); return WindowsIdentity.RunImpersonated(SafeAccessTokenHandle.InvalidHandle, () => { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); @@ -526,6 +527,7 @@ private static unsafe SafeFreeCredentials AcquireCredentialsHandle(Interop.SspiC // // For app-compat we want to ensure the credential are accessed under >>process<< account. // + Debug.Assert(OperatingSystem.IsWindows()); return WindowsIdentity.RunImpersonated(SafeAccessTokenHandle.InvalidHandle, () => { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); diff --git a/src/libraries/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.cs b/src/libraries/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.cs index 6112112d59bc60..26aa79b2c0c6e9 100644 --- a/src/libraries/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.cs +++ b/src/libraries/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.cs @@ -80,6 +80,7 @@ namespace System.Runtime.CompilerServices public sealed partial class IDispatchConstantAttribute : System.Runtime.CompilerServices.CustomConstantAttribute { public IDispatchConstantAttribute() { } + [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public override object Value { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter, Inherited=false)] diff --git a/src/libraries/System.Runtime.InteropServices/src/System/Runtime/CompilerServices/IDispatchConstantAttribute.cs b/src/libraries/System.Runtime.InteropServices/src/System/Runtime/CompilerServices/IDispatchConstantAttribute.cs index 3a3b8329e4c58e..841c036f08dfda 100644 --- a/src/libraries/System.Runtime.InteropServices/src/System/Runtime/CompilerServices/IDispatchConstantAttribute.cs +++ b/src/libraries/System.Runtime.InteropServices/src/System/Runtime/CompilerServices/IDispatchConstantAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; +using System.Runtime.Versioning; namespace System.Runtime.CompilerServices { @@ -10,6 +11,7 @@ public sealed partial class IDispatchConstantAttribute : CustomConstantAttribute { public IDispatchConstantAttribute() { } + [SupportedOSPlatform("windows")] public override object Value => new DispatchWrapper(null); } } diff --git a/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/BasicSymmetricCipherCsp.cs b/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/BasicSymmetricCipherCsp.cs index 892df2169b88c8..42412abc88ba3a 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/BasicSymmetricCipherCsp.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/BasicSymmetricCipherCsp.cs @@ -122,6 +122,7 @@ private static SafeKeyHandle ImportCspBlob(SafeProvHandle safeProvHandle, int al private static SafeProvHandle AcquireSafeProviderHandle() { SafeProvHandle safeProvHandle; + Debug.Assert(OperatingSystem.IsWindows()); var cspParams = new CspParameters((int)ProviderType.PROV_RSA_FULL); CapiHelper.AcquireCsp(cspParams, out safeProvHandle); return safeProvHandle; diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs index 47d67ae2ae6b0f..0aeeaa260f8db8 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs @@ -176,7 +176,7 @@ private static int AcquireCryptContext(out SafeProvHandle safeProvHandle, string internal static void AcquireCsp(CspParameters cspParameters, out SafeProvHandle safeProvHandle) { Debug.Assert(cspParameters != null); - Debug.Assert(cspParameters.KeyContainerName == null); + Debug.Assert(OperatingSystem.IsWindows() && cspParameters.KeyContainerName == null); SafeProvHandle hProv; // @@ -205,6 +205,7 @@ public static int OpenCSP(CspParameters cspParameters, uint flags, out SafeProvH throw new ArgumentException(SR.Format(SR.CspParameter_invalid, nameof(cspParameters))); } + Debug.Assert(OperatingSystem.IsWindows()); //look for provider type in the cspParameters int providerType = cspParameters.ProviderType; @@ -274,6 +275,7 @@ internal static SafeProvHandle CreateProvHandle(CspParameters parameters, bool r SafeProvHandle safeProvHandle; uint flag = 0; uint hr = unchecked((uint)OpenCSP(parameters, flag, out safeProvHandle)); + Debug.Assert(OperatingSystem.IsWindows()); //Open container failed if (hr != S_OK) { @@ -664,6 +666,7 @@ internal static CspParameters SaveCspParameters( out bool randomKeyContainer) { CspParameters parameters; + Debug.Assert(OperatingSystem.IsWindows()); if (userParameters == null) { parameters = new CspParameters(keyType == CspAlgorithmType.Dss ? @@ -732,6 +735,7 @@ internal static SafeKeyHandle GetKeyPairHelper( { // If the key already exists, use it, else generate a new one SafeKeyHandle hKey; + Debug.Assert(OperatingSystem.IsWindows()); int hr = CapiHelper.GetUserKey(safeProvHandle, parameters.KeyNumber, out hKey); if (hr != S_OK) { diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs index 186f9c80100c5f..a4c9ab3652a954 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs @@ -24,11 +24,13 @@ public sealed class DSACryptoServiceProvider : DSA, ICspAsymmetricAlgorithm /// Initializes a new instance of the DSACryptoServiceProvider class. /// public DSACryptoServiceProvider() +#pragma warning disable CA1416 // Validate platform compatibility : this( new CspParameters(CapiHelper.DefaultDssProviderType, null, null, s_useMachineKeyStore)) +#pragma warning restore CA1416 // { } @@ -37,11 +39,13 @@ public DSACryptoServiceProvider() /// /// The size of the key for the asymmetric algorithm in bits. public DSACryptoServiceProvider(int dwKeySize) +#pragma warning disable CA1416 // Validate platform compatibility : this(dwKeySize, new CspParameters(CapiHelper.DefaultDssProviderType, null, null, s_useMachineKeyStore)) +#pragma warning restore CA1416 // Validate platform compatibility { } @@ -324,6 +328,7 @@ public override DSAParameters ExportParameters(bool includePrivateParameters) private SafeProvHandle AcquireSafeProviderHandle() { SafeProvHandle safeProvHandle; + Debug.Assert(OperatingSystem.IsWindows()); CapiHelper.AcquireCsp(new CspParameters(CapiHelper.DefaultDssProviderType), out safeProvHandle); return safeProvHandle; } @@ -348,6 +353,7 @@ public void ImportCspBlob(byte[] keyBlob) } else { + Debug.Assert(OperatingSystem.IsWindows()); CapiHelper.ImportKeyBlob(SafeProvHandle, _parameters.Flags, false, keyBlob, out safeKeyHandle); } @@ -489,6 +495,7 @@ public byte[] SignHash(byte[] rgbHash, string? str) if (rgbHash.Length != _sha1.HashSize / 8) throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHashSize, "SHA1", _sha1.HashSize / 8)); + Debug.Assert(OperatingSystem.IsWindows()); return CapiHelper.SignValue( SafeProvHandle, SafeKeyHandle, diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.Windows.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.Windows.cs index c516653016400e..c82c47b2b4775d 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.Windows.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using Internal.NativeCrypto; +using System.Diagnostics; using System.Runtime.Versioning; #pragma warning disable CA5373 // Call to obsolete key derivation function PasswordDeriveBytes.* @@ -58,6 +59,7 @@ private static SafeProvHandle AcquireSafeProviderHandle(CspParameters? cspParams { if (cspParams == null) { + Debug.Assert(OperatingSystem.IsWindows()); cspParams = new CspParameters(CapiHelper.DefaultRsaProviderType); } diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.cs index 4b5e73dc340ebc..d5ef0012ec1413 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/PasswordDeriveBytes.cs @@ -25,6 +25,7 @@ public partial class PasswordDeriveBytes : DeriveBytes private HashAlgorithm? _hash; private readonly CspParameters? _cspParams; +#pragma warning disable CA1416 // Validate platform compatibility, CspParametersis windows only, this is feels wrong suppressing for now public PasswordDeriveBytes(string strPassword, byte[]? rgbSalt) : this(strPassword, rgbSalt, new CspParameters()) { } public PasswordDeriveBytes(byte[] password, byte[]? salt) : this(password, salt, new CspParameters()) { } @@ -34,6 +35,7 @@ public PasswordDeriveBytes(string strPassword, byte[]? rgbSalt, string strHashNa public PasswordDeriveBytes(byte[] password, byte[]? salt, string hashName, int iterations) : this(password, salt, hashName, iterations, new CspParameters()) { } +#pragma warning restore CA1416 public PasswordDeriveBytes(string strPassword, byte[]? rgbSalt, CspParameters? cspParams) : this(strPassword, rgbSalt, "SHA1", 100, cspParams) { } diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs index 6843a3aa30fca2..4a967e9d496a83 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs @@ -22,6 +22,7 @@ public sealed partial class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgori private static volatile CspProviderFlags s_useMachineKeyStore; private bool _disposed; +#pragma warning disable CA1416 // Validate platform compatibility public RSACryptoServiceProvider() : this(0, new CspParameters(CapiHelper.DefaultRsaProviderType, null, @@ -39,6 +40,7 @@ public RSACryptoServiceProvider(int dwKeySize) s_useMachineKeyStore), false) { } +#pragma warning restore CA1416 [SupportedOSPlatform("windows")] public RSACryptoServiceProvider(int dwKeySize, CspParameters? parameters) @@ -374,6 +376,7 @@ public override RSAParameters ExportParameters(bool includePrivateParameters) private SafeProvHandle AcquireSafeProviderHandle() { SafeProvHandle safeProvHandle; + Debug.Assert(OperatingSystem.IsWindows()); CapiHelper.AcquireCsp(new CspParameters(CapiHelper.DefaultRsaProviderType), out safeProvHandle); return safeProvHandle; } @@ -397,6 +400,7 @@ public void ImportCspBlob(byte[] keyBlob) } else { + Debug.Assert(OperatingSystem.IsWindows()); CapiHelper.ImportKeyBlob(SafeProvHandle, _parameters.Flags, false, keyBlob, out safeKeyHandle); } @@ -507,6 +511,7 @@ public byte[] SignHash(byte[] rgbHash, string? str) private byte[] SignHash(byte[] rgbHash, int calgHash) { Debug.Assert(rgbHash != null); + Debug.Assert(OperatingSystem.IsWindows()); return CapiHelper.SignValue( SafeProvHandle, @@ -714,6 +719,7 @@ public override string? KeyExchangeAlgorithm { get { + Debug.Assert(OperatingSystem.IsWindows()); if (_parameters.KeyNumber == (int)Interop.Advapi32.KeySpec.AT_KEYEXCHANGE) { return "RSA-PKCS1-KeyEx"; diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs index 16ab88ef29e7e4..219579f3ce109e 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs @@ -28,10 +28,12 @@ public bool HasPrivateKey return GetPrivateKey( delegate (CspParameters csp) { + Debug.Assert(OperatingSystem.IsWindows()); return new RSACryptoServiceProvider(csp); }, delegate (CngKey cngKey) { + Debug.Assert(OperatingSystem.IsWindows()); return new RSACng(cngKey); } ); @@ -42,10 +44,12 @@ public bool HasPrivateKey return GetPrivateKey( delegate (CspParameters csp) { + Debug.Assert(OperatingSystem.IsWindows()); return new DSACryptoServiceProvider(csp); }, delegate (CngKey cngKey) { + Debug.Assert(OperatingSystem.IsWindows()); return new DSACng(cngKey); } ); @@ -60,6 +64,7 @@ public bool HasPrivateKey }, delegate (CngKey cngKey) { + Debug.Assert(OperatingSystem.IsWindows()); return new ECDsaCng(cngKey); } ); @@ -69,7 +74,9 @@ public bool HasPrivateKey { return GetPrivateKey( csp => throw new NotSupportedException(SR.NotSupported_ECDiffieHellman_Csp), +#pragma warning disable CA1416 // Validate platform compatibility cngKey => new ECDiffieHellmanCng(cngKey) +#pragma warning restore CA1416 // Validate platform compatibility ); } @@ -78,6 +85,7 @@ public ICertificatePal CopyWithPrivateKey(DSA dsa) DSACng? dsaCng = dsa as DSACng; ICertificatePal? clone = null; + Debug.Assert(OperatingSystem.IsWindows()); if (dsaCng != null) { clone = CopyWithPersistedCngKey(dsaCng.Key); @@ -115,6 +123,7 @@ public ICertificatePal CopyWithPrivateKey(ECDsa ecdsa) { ECDsaCng? ecdsaCng = ecdsa as ECDsaCng; + Debug.Assert(OperatingSystem.IsWindows()); if (ecdsaCng != null) { ICertificatePal? clone = CopyWithPersistedCngKey(ecdsaCng.Key); @@ -140,6 +149,7 @@ public ICertificatePal CopyWithPrivateKey(ECDiffieHellman ecdh) { ECDiffieHellmanCng? ecdhCng = ecdh as ECDiffieHellmanCng; + Debug.Assert(OperatingSystem.IsWindows()); if (ecdhCng != null) { ICertificatePal? clone = CopyWithPersistedCngKey(ecdhCng.Key); @@ -166,6 +176,7 @@ public ICertificatePal CopyWithPrivateKey(RSA rsa) RSACng? rsaCng = rsa as RSACng; ICertificatePal? clone = null; + Debug.Assert(OperatingSystem.IsWindows()); if (rsaCng != null) { clone = CopyWithPersistedCngKey(rsaCng.Key); @@ -208,6 +219,7 @@ public ICertificatePal CopyWithPrivateKey(RSA rsa) { CngKeyHandleOpenOptions cngHandleOptions; SafeNCryptKeyHandle? ncryptKey = TryAcquireCngPrivateKey(CertContext, out cngHandleOptions); + Debug.Assert(OperatingSystem.IsWindows()); if (ncryptKey != null) { CngKey cngKey = CngKey.Open(ncryptKey, cngHandleOptions); @@ -244,6 +256,7 @@ public ICertificatePal CopyWithPrivateKey(RSA rsa) Debug.Assert(certificateContext != null, "certificateContext != null"); Debug.Assert(!certificateContext.IsClosed && !certificateContext.IsInvalid, "!certificateContext.IsClosed && !certificateContext.IsInvalid"); + Debug.Assert(OperatingSystem.IsWindows()); IntPtr privateKeyPtr; @@ -345,6 +358,7 @@ public ICertificatePal CopyWithPrivateKey(RSA rsa) throw Marshal.GetLastWin32Error().ToCryptographicException(); CRYPT_KEY_PROV_INFO* pKeyProvInfo = (CRYPT_KEY_PROV_INFO*)pPrivateKey; + Debug.Assert(OperatingSystem.IsWindows()); CspParameters cspParameters = new CspParameters(); cspParameters.ProviderName = Marshal.PtrToStringUni((IntPtr)(pKeyProvInfo->pwszProvName)); cspParameters.KeyContainerName = Marshal.PtrToStringUni((IntPtr)(pKeyProvInfo->pwszContainerName)); @@ -358,6 +372,7 @@ public ICertificatePal CopyWithPrivateKey(RSA rsa) private unsafe ICertificatePal? CopyWithPersistedCngKey(CngKey cngKey) { + Debug.Assert(OperatingSystem.IsWindows()); if (string.IsNullOrEmpty(cngKey.KeyName)) { return null; @@ -404,6 +419,7 @@ private static int GuessKeySpec( bool machineKey, CngAlgorithmGroup? algorithmGroup) { + Debug.Assert(OperatingSystem.IsWindows()); if (provider == CngProvider.MicrosoftSoftwareKeyStorageProvider || provider == CngProvider.MicrosoftSmartCardKeyStorageProvider) { @@ -457,6 +473,7 @@ private static bool TryGuessKeySpec( CngAlgorithmGroup? algorithmGroup, out int keySpec) { + Debug.Assert(OperatingSystem.IsWindows()); if (algorithmGroup == CngAlgorithmGroup.Rsa) { return TryGuessRsaKeySpec(cspParameters, out keySpec); @@ -493,6 +510,7 @@ private static bool TryGuessRsaKeySpec(CspParameters cspParameters, out int keyS PROV_RSA_SIG, }; + Debug.Assert(OperatingSystem.IsWindows()); foreach (int provType in provTypes) { cspParameters.ProviderType = provType; @@ -528,6 +546,7 @@ private static bool TryGuessDsaKeySpec(CspParameters cspParameters, out int keyS PROV_DSS, }; + Debug.Assert(OperatingSystem.IsWindows()); foreach (int provType in provTypes) { cspParameters.ProviderType = provType; @@ -554,6 +573,7 @@ private static bool TryGuessDsaKeySpec(CspParameters cspParameters, out int keyS private unsafe ICertificatePal? CopyWithPersistedCapiKey(CspKeyContainerInfo keyContainerInfo) { + Debug.Assert(OperatingSystem.IsWindows()); if (string.IsNullOrEmpty(keyContainerInfo.KeyContainerName)) { return null; @@ -588,6 +608,7 @@ private static bool TryGuessDsaKeySpec(CspParameters cspParameters, out int keyS private ICertificatePal CopyWithEphemeralKey(CngKey cngKey) { + Debug.Assert(OperatingSystem.IsWindows()); Debug.Assert(string.IsNullOrEmpty(cngKey.KeyName)); SafeNCryptKeyHandle handle = cngKey.Handle; diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.cs index 10ac6e7480a1f6..24449d9da824d2 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.cs @@ -410,6 +410,7 @@ public void AppendPrivateKeyInfo(StringBuilder sb) sb.AppendLine(); sb.AppendLine("[Private Key]"); + Debug.Assert(OperatingSystem.IsWindows()); CspKeyContainerInfo? cspKeyContainerInfo = null; try { diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/SafeHandles.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/SafeHandles.cs index 4643f6fa211cc9..57e8ef2f8b7183 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/SafeHandles.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/SafeHandles.cs @@ -169,6 +169,7 @@ public static void DeleteKeyContainer(SafeCertContextHandle pCertContext) try { + Debug.Assert(OperatingSystem.IsWindows()); using (CngKey cngKey = CngKey.Open(keyContainerName, new CngProvider(providerName))) { cngKey.Delete(); diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs index dd11ea04d08309..72c2c9d0fd0b66 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs @@ -30,8 +30,10 @@ public ECDsa DecodeECDsaPublicKey(ICertificatePal? certificatePal) { return DecodeECPublicKey( pal, +#pragma warning disable CA1416 // Validate platform compatibility, flow analysis bug factory: cngKey => new ECDsaCng(cngKey), import: (algorithm, ecParams) => algorithm.ImportParameters(ecParams)); +#pragma warning restore CA1416 } throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); @@ -41,10 +43,13 @@ public ECDiffieHellman DecodeECDiffieHellmanPublicKey(ICertificatePal? certifica { if (certificatePal is CertificatePal pal) { + Debug.Assert(OperatingSystem.IsWindows()); return DecodeECPublicKey( pal, +#pragma warning disable CA1416 // Validate platform compatibility factory: cngKey => new ECDiffieHellmanCng(cngKey), import: (algorithm, ecParams) => algorithm.ImportParameters(ecParams), +#pragma warning restore CA1416 importFlags: CryptImportPublicKeyInfoFlags.CRYPT_OID_INFO_PUBKEY_ENCRYPT_KEY_FLAG); } @@ -59,6 +64,7 @@ public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte case AlgId.CALG_RSA_KEYX: case AlgId.CALG_RSA_SIGN: { + Debug.Assert(OperatingSystem.IsWindows()); byte[] keyBlob = DecodeKeyBlob(CryptDecodeObjectStructType.CNG_RSA_PUBLIC_KEY_BLOB, encodedKeyValue); CngKey cngKey = CngKey.Import(keyBlob, CngKeyBlobFormat.GenericPublicBlob); return new RSACng(cngKey); @@ -90,6 +96,7 @@ private static TAlgorithm DecodeECPublicKey( byte[] keyBlob; string? curveName = GetCurveName(bCryptKeyHandle); + Debug.Assert(OperatingSystem.IsWindows()); if (curveName == null) { if (HasExplicitParameters(bCryptKeyHandle)) @@ -149,6 +156,7 @@ private static SafeBCryptKeyHandle ImportPublicKeyInfo(SafeCertContextHandle cer private static byte[] ExportKeyBlob(SafeBCryptKeyHandle bCryptKeyHandle, CngKeyBlobFormat blobFormat) { + Debug.Assert(OperatingSystem.IsWindows()); string blobFormatString = blobFormat.Format; int numBytesNeeded = 0; From 82b074d7b27ebfa4dce5c9f3b6fd745089a1e6df Mon Sep 17 00:00:00 2001 From: Buyaa Namnan Date: Thu, 1 Oct 2020 14:04:00 -0700 Subject: [PATCH 2/3] Few typo fix --- .../System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs | 1 + .../src/System/IO/Pipes/ReadWriteCompletionSource.cs | 1 - .../src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs | 1 - 3 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs index f43caf333dc0f5..3967ff37616b26 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs @@ -30,6 +30,7 @@ internal abstract unsafe class PipeCompletionSource : TaskCompletionSou #if DEBUG private bool _cancellationHasBeenRegistered; #endif + // Using RunContinuationsAsynchronously for compat reasons (old API used ThreadPool.QueueUserWorkItem for continuations) protected PipeCompletionSource(ThreadPoolBoundHandle handle, ReadOnlyMemory bufferToPin) : base(TaskCreationOptions.RunContinuationsAsynchronously) diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/ReadWriteCompletionSource.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/ReadWriteCompletionSource.cs index 370f09a846dc2f..af6ad5a99d92a1 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/ReadWriteCompletionSource.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/ReadWriteCompletionSource.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.ExceptionServices; -using System.Runtime.Versioning; using System.Threading; namespace System.IO.Pipes diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs index 72c2c9d0fd0b66..196bb7dde48d85 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs @@ -43,7 +43,6 @@ public ECDiffieHellman DecodeECDiffieHellmanPublicKey(ICertificatePal? certifica { if (certificatePal is CertificatePal pal) { - Debug.Assert(OperatingSystem.IsWindows()); return DecodeECPublicKey( pal, #pragma warning disable CA1416 // Validate platform compatibility From 262f9cc62ef6d8d83672da11ff835c45ab558d7c Mon Sep 17 00:00:00 2001 From: Buyaa Namnan Date: Fri, 2 Oct 2020 13:38:31 -0700 Subject: [PATCH 3/3] Apply feedback --- .../src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs | 2 +- .../src/System/Security/Cryptography/CapiHelper.Windows.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs index 98b8c115fc596d..ca579ec3ae4034 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs @@ -748,7 +748,7 @@ public async Task SendAsyncCore(HttpRequestMessage request, // Map the exception the same way as we normally do. catch (Exception ex) when (MapSendException(ex, cancellationToken, out Exception mappedEx)) { - throw; + throw mappedEx; } } LogExceptions(sendRequestContentTask); diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs index 0aeeaa260f8db8..d2217d03a0436e 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs @@ -176,7 +176,8 @@ private static int AcquireCryptContext(out SafeProvHandle safeProvHandle, string internal static void AcquireCsp(CspParameters cspParameters, out SafeProvHandle safeProvHandle) { Debug.Assert(cspParameters != null); - Debug.Assert(OperatingSystem.IsWindows() && cspParameters.KeyContainerName == null); + Debug.Assert(OperatingSystem.IsWindows()); + Debug.Assert(cspParameters.KeyContainerName == null); SafeProvHandle hProv; //