From e8339af091988247c90bd7d347753da05f7e74cd Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Fri, 16 Oct 2020 22:24:20 -0400 Subject: [PATCH] Remove some unnecessary unsafe usage (#43430) --- .../Interop.ProtocolStatistics.cs | 22 +- .../Interop.TcpConnectionInfo.cs | 4 +- .../FreeBSD/Interop.Process.GetProcInfo.cs | 2 +- .../src/Interop/FreeBSD/Interop.Process.cs | 21 +- .../Common/src/Interop/Interop.Collation.cs | 6 +- .../Common/src/Interop/Interop.Locale.cs | 2 +- .../OSX/Interop.libproc.GetProcessInfoById.cs | 4 +- .../Interop.Hmac.cs | 2 +- ...nterop.ConfigureTerminalForChildProcess.cs | 2 +- .../Unix/System.Native/Interop.Disconnect.cs | 2 +- .../Interop.GetCpuUtilization.cs | 4 +- .../Unix/System.Native/Interop.GetPeerID.cs | 2 +- .../System.Native/Interop.GetPeerUserName.cs | 2 +- .../System.Native/Interop.GetRandomBytes.cs | 2 +- .../Interop.GetSystemTimeAsTicks.cs | 2 +- .../Interop.InterfaceNameToIndex.cs | 2 +- .../Unix/System.Native/Interop.MemAlloc.cs | 2 +- .../Interop.MountPoints.FormatInfo.cs | 37 ++- .../Unix/System.Native/Interop.ReadLink.cs | 2 +- .../Interop.ReadStdinUnbuffered.cs | 4 +- .../Unix/System.Native/Interop.SendFile.cs | 2 +- .../Unix/System.Native/Interop.SetEUid.cs | 2 +- .../Interop.SetReceiveTimeout.cs | 2 +- .../System.Native/Interop.SetSendTimeout.cs | 2 +- .../Unix/System.Native/Interop.SocketEvent.cs | 2 +- .../Unix/System.Native/Interop.Stat.Span.cs | 12 +- .../Unix/System.Native/Interop.StdinReady.cs | 2 +- .../Interop.Ssl.cs | 4 +- .../Interop.SslCtx.cs | 2 +- ...gSecurityDescriptorToSecurityDescriptor.cs | 2 +- .../Advapi32/Interop.QueryServiceStatus.cs | 1 - .../Windows/Advapi32/Interop.RegEnumKeyEx.cs | 2 +- .../Windows/Advapi32/Interop.RegEnumValue.cs | 2 +- .../Common/src/Interop/Windows/BCrypt/Cng.cs | 4 +- .../Windows/BCrypt/Interop.BCryptImportKey.cs | 41 ++-- .../Interop.CryptEncodeDecodeWrappers.cs | 27 +-- .../Windows/HttpApi/Interop.HttpApi.cs | 8 +- .../Kernel32/Interop.CompareStringOrdinal.cs | 2 +- .../Kernel32/Interop.ConditionVariable.cs | 8 +- .../Kernel32/Interop.CriticalSection.cs | 10 +- ...Interop.FormatMessage_SafeLibraryHandle.cs | 2 +- .../Kernel32/Interop.GetComputerName.cs | 4 +- .../Interop.GetEnvironmentVariable.cs | 2 +- .../Kernel32/Interop.GetModuleFileName.cs | 2 +- .../Windows/Kernel32/Interop.Globalization.cs | 30 +-- ...erop.SetFileCompletionNotificationModes.cs | 2 +- .../NCrypt/Interop.NCryptDeriveKeyMaterial.cs | 41 ++-- .../Windows/NCrypt/Interop.Properties.cs | 68 +++--- .../Interop.FILE_FULL_DIR_INFORMATION.cs | 4 +- .../NtDll/Interop.FILE_FULL_EA_INFORMATION.cs | 2 +- .../NtDll/Interop.RtlNtStatusToDosError.cs | 3 +- .../Interop/Windows/Ole32/Interop.IStream.cs | 10 +- .../PerfCounter/Interop.FormatFromRawValue.cs | 2 +- .../PerfCounter/Interop.PerformanceData.cs | 4 +- .../UnmanagedCertificateContext.IntPtr.cs | 10 +- .../SChannel/UnmanagedCertificateContext.cs | 2 +- .../Interop/Windows/SspiCli/Interop.SSPI.cs | 12 +- .../Windows/WinSock/Interop.WSAStartup.cs | 2 +- .../Windows/WinSock/SafeNativeOverlapped.cs | 17 +- .../Globalization/FormatProvider.Number.cs | 2 +- .../System/Memory/FixedBufferExtensions.cs | 4 +- .../Http/aspnetcore/NetEventSource.Common.cs | 2 +- .../System/Net/IPv4AddressHelper.Common.cs | 45 ++-- .../System/Net/IPv6AddressHelper.Common.cs | 5 +- .../Net/Logging/NetEventSource.Common.cs | 2 +- .../NetworkInformation/UnixCommandLinePing.cs | 2 +- .../Security/NegotiateStreamPal.Windows.cs | 2 +- .../System/Net/SocketAddressPal.Windows.cs | 48 ++-- .../src/System/Net/WebHeaderEncoding.cs | 9 +- .../System/Net/WebSockets/ManagedWebSocket.cs | 2 +- .../Cryptography/DSACng.ImportExport.cs | 218 +++++++++--------- .../Cryptography/ECCng.ImportExport.cs | 101 ++++---- .../Security/Cryptography/KeyFormatHelper.cs | 4 +- .../Cryptography/RSACng.EncryptDecrypt.cs | 4 +- .../Cryptography/RSACng.ImportExport.cs | 173 +++++++------- .../Security/Cryptography/RSAOpenSsl.cs | 2 +- .../Common/src/System/Text/DBCSDecoder.cs | 4 +- .../src/System/Diagnostics/Process.BSD.cs | 2 +- .../src/System/Diagnostics/Process.Linux.cs | 2 +- .../System/Diagnostics/Process.UnknownUnix.cs | 2 +- .../Diagnostics/ProcessManager.Linux.cs | 21 +- .../Protocols/common/BerConverter.Linux.cs | 2 +- .../Protocols/common/BerConverter.Windows.cs | 2 +- .../src/Interop/AdsValueHelper2.cs | 2 +- .../System/Drawing/GdiplusNative.Windows.cs | 4 +- .../src/System/Drawing/GdiplusNative.cs | 4 +- .../IO/Compression/dec/BrotliDecoder.cs | 17 +- .../IO/Compression/enc/BrotliEncoder.cs | 1 + .../src/System/IO/FileSystemWatcher.OSX.cs | 2 +- .../Win32/SafeMemoryMappedFileHandle.Unix.cs | 11 +- .../MemoryMappedFile.Unix.cs | 2 +- .../MemoryMappedView.Unix.cs | 2 +- .../MemoryMappedView.Windows.cs | 77 +++---- .../IO/MemoryMappedFiles/MemoryMappedView.cs | 3 +- .../MemoryMappedViewAccessor.cs | 5 +- .../MemoryMappedViewStream.cs | 2 +- .../Pipes/AnonymousPipeServerStream.Unix.cs | 2 +- .../System.IO.Pipes/tests/InteropTest.Unix.cs | 2 +- .../src/System/IO/Ports/SerialStream.Unix.cs | 4 +- .../System/Buffers/SequenceReader.Search.cs | 2 +- .../System/Net/Http/NetEventSource.Http.cs | 2 +- .../AuthenticationHelper.Digest.cs | 2 +- .../BsdIPGlobalProperties.cs | 3 +- .../NetworkAddressChange.Windows.cs | 2 +- .../NetworkInformation/SystemTcpConnection.cs | 2 +- .../MsQuic/Internal/MsQuicAddressHelpers.cs | 2 +- .../MsQuic/MsQuicConnection.cs | 2 +- .../Implementations/MsQuic/MsQuicListener.cs | 2 +- .../Implementations/MsQuic/MsQuicStream.cs | 2 +- .../Net/Security/NetEventSource.Security.cs | 6 +- .../Net/Security/SslStreamPal.Windows.cs | 2 +- 111 files changed, 612 insertions(+), 699 deletions(-) diff --git a/src/libraries/Common/src/Interop/BSD/System.Native/Interop.ProtocolStatistics.cs b/src/libraries/Common/src/Interop/BSD/System.Native/Interop.ProtocolStatistics.cs index be9716f486a15..ab7ac0fb962c6 100644 --- a/src/libraries/Common/src/Interop/BSD/System.Native/Interop.ProtocolStatistics.cs +++ b/src/libraries/Common/src/Interop/BSD/System.Native/Interop.ProtocolStatistics.cs @@ -19,7 +19,7 @@ internal enum InterfaceFlags } [StructLayoutAttribute(LayoutKind.Sequential)] - public readonly unsafe struct TcpGlobalStatistics + public readonly struct TcpGlobalStatistics { public readonly ulong ConnectionsAccepted; public readonly ulong ConnectionsInitiated; @@ -34,10 +34,10 @@ public readonly unsafe struct TcpGlobalStatistics } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetTcpGlobalStatistics")] - public static extern unsafe int GetTcpGlobalStatistics(out TcpGlobalStatistics statistics); + public static extern int GetTcpGlobalStatistics(out TcpGlobalStatistics statistics); [StructLayoutAttribute(LayoutKind.Sequential)] - public readonly unsafe struct IPv4GlobalStatistics + public readonly struct IPv4GlobalStatistics { public readonly ulong OutboundPackets; public readonly ulong OutputPacketsNoRoute; @@ -56,10 +56,10 @@ public readonly unsafe struct IPv4GlobalStatistics } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetIPv4GlobalStatistics")] - public static extern unsafe int GetIPv4GlobalStatistics(out IPv4GlobalStatistics statistics); + public static extern int GetIPv4GlobalStatistics(out IPv4GlobalStatistics statistics); [StructLayoutAttribute(LayoutKind.Sequential)] - public readonly unsafe struct UdpGlobalStatistics + public readonly struct UdpGlobalStatistics { public readonly ulong DatagramsReceived; public readonly ulong DatagramsSent; @@ -69,10 +69,10 @@ public readonly unsafe struct UdpGlobalStatistics } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetUdpGlobalStatistics")] - public static extern unsafe int GetUdpGlobalStatistics(out UdpGlobalStatistics statistics); + public static extern int GetUdpGlobalStatistics(out UdpGlobalStatistics statistics); [StructLayoutAttribute(LayoutKind.Sequential)] - public readonly unsafe struct Icmpv4GlobalStatistics + public readonly struct Icmpv4GlobalStatistics { public readonly ulong AddressMaskRepliesReceived; public readonly ulong AddressMaskRepliesSent; @@ -99,10 +99,10 @@ public readonly unsafe struct Icmpv4GlobalStatistics } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetIcmpv4GlobalStatistics")] - public static extern unsafe int GetIcmpv4GlobalStatistics(out Icmpv4GlobalStatistics statistics); + public static extern int GetIcmpv4GlobalStatistics(out Icmpv4GlobalStatistics statistics); [StructLayoutAttribute(LayoutKind.Sequential)] - public readonly unsafe struct Icmpv6GlobalStatistics + public readonly struct Icmpv6GlobalStatistics { public readonly ulong DestinationUnreachableMessagesReceived; public readonly ulong DestinationUnreachableMessagesSent; @@ -135,7 +135,7 @@ public readonly unsafe struct Icmpv6GlobalStatistics } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetIcmpv6GlobalStatistics")] - public static extern unsafe int GetIcmpv6GlobalStatistics(out Icmpv6GlobalStatistics statistics); + public static extern int GetIcmpv6GlobalStatistics(out Icmpv6GlobalStatistics statistics); public readonly struct NativeIPInterfaceStatistics { @@ -156,7 +156,7 @@ public readonly struct NativeIPInterfaceStatistics } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetNativeIPInterfaceStatistics")] - public static extern unsafe int GetNativeIPInterfaceStatistics(string name, out NativeIPInterfaceStatistics stats); + public static extern int GetNativeIPInterfaceStatistics(string name, out NativeIPInterfaceStatistics stats); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetNumRoutes")] public static extern int GetNumRoutes(); diff --git a/src/libraries/Common/src/Interop/BSD/System.Native/Interop.TcpConnectionInfo.cs b/src/libraries/Common/src/Interop/BSD/System.Native/Interop.TcpConnectionInfo.cs index 02bcff8dfa72c..3d48cd67060ae 100644 --- a/src/libraries/Common/src/Interop/BSD/System.Native/Interop.TcpConnectionInfo.cs +++ b/src/libraries/Common/src/Interop/BSD/System.Native/Interop.TcpConnectionInfo.cs @@ -26,13 +26,13 @@ public struct NativeTcpConnectionInformation } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetEstimatedTcpConnectionCount")] - public static extern unsafe int GetEstimatedTcpConnectionCount(); + public static extern int GetEstimatedTcpConnectionCount(); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetActiveTcpConnectionInfos")] public static extern unsafe int GetActiveTcpConnectionInfos(NativeTcpConnectionInformation* infos, int* infoCount); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetEstimatedUdpListenerCount")] - public static extern unsafe int GetEstimatedUdpListenerCount(); + public static extern int GetEstimatedUdpListenerCount(); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetActiveUdpListeners")] public static extern unsafe int GetActiveUdpListeners(IPEndPointInfo* infos, int* infoCount); diff --git a/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.GetProcInfo.cs b/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.GetProcInfo.cs index 6496fbd7a1c68..90310c7035b26 100644 --- a/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.GetProcInfo.cs +++ b/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.GetProcInfo.cs @@ -64,7 +64,7 @@ private struct vnode // sys/resource.h [StructLayout(LayoutKind.Sequential)] - internal unsafe struct rusage + internal struct rusage { public timeval ru_utime; /* user time used */ public timeval ru_stime; /* system time used */ diff --git a/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.cs b/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.cs index b2b18eab0cdb7..59dd664901ad4 100644 --- a/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.cs +++ b/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.cs @@ -32,10 +32,7 @@ internal struct proc_stats /// Returns a list of PIDs corresponding to all running processes internal static unsafe int[] ListAllPids() { - int[] pids; - kinfo_proc * entries = GetProcInfo(0, false, out int numProcesses); - int idx; - + kinfo_proc* entries = GetProcInfo(0, false, out int numProcesses); try { if (numProcesses <= 0) @@ -44,9 +41,10 @@ internal static unsafe int[] ListAllPids() } var list = new ReadOnlySpan(entries, numProcesses); - pids = new int[numProcesses]; - idx = 0; + var pids = new int[numProcesses]; + // walk through process list and skip kernel threads + int idx = 0; for (int i = 0; i < list.Length; i++) { if (list[i].ki_ppid == 0) @@ -60,14 +58,15 @@ internal static unsafe int[] ListAllPids() idx += 1; } } + // Remove extra elements Array.Resize(ref pids, numProcesses); + return pids; } finally { Marshal.FreeHGlobal((IntPtr)entries); } - return pids; } @@ -86,10 +85,12 @@ internal static unsafe int[] ListAllPids() sysctlName[2] = KERN_PROC_PATHNAME; sysctlName[3] = pid; - int ret = Interop.Sys.Sysctl(sysctlName, ref pBuffer, ref bytesLength); - if (ret != 0 ) { + if (Interop.Sys.Sysctl(sysctlName, ref pBuffer, ref bytesLength) != 0) + { return null; } + + // TODO Fix freeing of pBuffer: https://github.com/dotnet/runtime/issues/43418 return System.Text.Encoding.UTF8.GetString(pBuffer, (int)bytesLength-1); } @@ -167,7 +168,7 @@ public static unsafe proc_stats GetThreadInfo(int pid, int tid) try { - info = GetProcInfo(pid, (tid != 0), out count); + info = GetProcInfo(pid, (tid != 0), out count); if (info != null && count >= 1) { if (tid == 0) diff --git a/src/libraries/Common/src/Interop/Interop.Collation.cs b/src/libraries/Common/src/Interop/Interop.Collation.cs index beb8e2cac84a7..89dfb5bcd98ec 100644 --- a/src/libraries/Common/src/Interop/Interop.Collation.cs +++ b/src/libraries/Common/src/Interop/Interop.Collation.cs @@ -13,7 +13,7 @@ internal static partial class Globalization internal static extern unsafe ResultCode GetSortHandle(string localeName, out IntPtr sortHandle); [DllImport(Libraries.GlobalizationNative, EntryPoint = "GlobalizationNative_CloseSortHandle")] - internal static extern unsafe void CloseSortHandle(IntPtr handle); + internal static extern void CloseSortHandle(IntPtr handle); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CompareString")] internal static extern unsafe int CompareString(IntPtr sortHandle, char* lpStr1, int cwStr1Len, char* lpStr2, int cwStr2Len, CompareOptions options); @@ -34,11 +34,11 @@ internal static partial class Globalization [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_StartsWith")] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool StartsWith(IntPtr sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options); + internal static extern bool StartsWith(IntPtr sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_EndsWith")] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool EndsWith(IntPtr sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options); + internal static extern bool EndsWith(IntPtr sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetSortKey")] internal static extern unsafe int GetSortKey(IntPtr sortHandle, char* str, int strLength, byte* sortKey, int sortKeyLength, CompareOptions options); diff --git a/src/libraries/Common/src/Interop/Interop.Locale.cs b/src/libraries/Common/src/Interop/Interop.Locale.cs index 81ce1c133eede..2634ed9505ec0 100644 --- a/src/libraries/Common/src/Interop/Interop.Locale.cs +++ b/src/libraries/Common/src/Interop/Interop.Locale.cs @@ -21,7 +21,7 @@ internal static partial class Globalization [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IsPredefinedLocale")] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool IsPredefinedLocale(string localeName); + internal static extern bool IsPredefinedLocale(string localeName); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleTimeFormat")] [return: MarshalAs(UnmanagedType.Bool)] diff --git a/src/libraries/Common/src/Interop/OSX/Interop.libproc.GetProcessInfoById.cs b/src/libraries/Common/src/Interop/OSX/Interop.libproc.GetProcessInfoById.cs index 868fce30d6e99..e2e735746d71e 100644 --- a/src/libraries/Common/src/Interop/OSX/Interop.libproc.GetProcessInfoById.cs +++ b/src/libraries/Common/src/Interop/OSX/Interop.libproc.GetProcessInfoById.cs @@ -48,7 +48,7 @@ internal unsafe struct proc_bsdinfo // From proc_info.h [StructLayout(LayoutKind.Sequential)] - internal unsafe struct proc_taskinfo + internal struct proc_taskinfo { internal ulong pti_virtual_size; internal ulong pti_resident_size; @@ -72,7 +72,7 @@ internal unsafe struct proc_taskinfo // From proc_info.h [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] - internal unsafe struct proc_taskallinfo + internal struct proc_taskallinfo { internal proc_bsdinfo pbsd; internal proc_taskinfo ptinfo; diff --git a/src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.Hmac.cs b/src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.Hmac.cs index 65b6e412fbf62..09bb04e86f78d 100644 --- a/src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.Hmac.cs +++ b/src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.Hmac.cs @@ -16,7 +16,7 @@ internal static partial class AppleCrypto internal static extern SafeHmacHandle HmacCreate(PAL_HashAlgorithm algorithm, ref int cbDigest); [DllImport(Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_HmacInit")] - internal static extern unsafe int HmacInit(SafeHmacHandle ctx, [In] byte[] pbKey, int cbKey); + internal static extern int HmacInit(SafeHmacHandle ctx, [In] byte[] pbKey, int cbKey); internal static int HmacUpdate(SafeHmacHandle ctx, ReadOnlySpan data) => HmacUpdate(ctx, ref MemoryMarshal.GetReference(data), data.Length); diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ConfigureTerminalForChildProcess.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ConfigureTerminalForChildProcess.cs index 73112e7c2e83c..0801ed3b84e05 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ConfigureTerminalForChildProcess.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ConfigureTerminalForChildProcess.cs @@ -9,6 +9,6 @@ internal static partial class Interop internal static partial class Sys { [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConfigureTerminalForChildProcess")] - internal static extern unsafe void ConfigureTerminalForChildProcess(bool childUsesTerminal); + internal static extern void ConfigureTerminalForChildProcess(bool childUsesTerminal); } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.Disconnect.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.Disconnect.cs index 815238d06a76d..0ecfc3192373d 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.Disconnect.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.Disconnect.cs @@ -9,6 +9,6 @@ internal static partial class Interop internal static partial class Sys { [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Disconnect")] - internal static extern unsafe Error Disconnect(IntPtr socket); + internal static extern Error Disconnect(IntPtr socket); } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetCpuUtilization.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetCpuUtilization.cs index f87f6a97bd7bd..3a7aaecc1f6fd 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetCpuUtilization.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetCpuUtilization.cs @@ -5,7 +5,7 @@ internal static partial class Interop { - internal unsafe partial class Sys + internal partial class Sys { [StructLayout(LayoutKind.Sequential)] internal struct ProcessCpuInformation @@ -16,6 +16,6 @@ internal struct ProcessCpuInformation } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetCpuUtilization")] - internal static extern unsafe int GetCpuUtilization(ref ProcessCpuInformation previousCpuInfo); + internal static extern int GetCpuUtilization(ref ProcessCpuInformation previousCpuInfo); } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetPeerID.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetPeerID.cs index ad8cc50dbe589..2e9e6f139c3bb 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetPeerID.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetPeerID.cs @@ -9,6 +9,6 @@ internal static partial class Interop internal static partial class Sys { [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPeerID", SetLastError = true)] - internal static extern unsafe int GetPeerID(SafeHandle socket, out uint euid); + internal static extern int GetPeerID(SafeHandle socket, out uint euid); } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetPeerUserName.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetPeerUserName.cs index cae12e50dca54..ccc7d9c88e5a3 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetPeerUserName.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetPeerUserName.cs @@ -10,6 +10,6 @@ internal static partial class Interop internal static partial class Sys { [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPeerUserName", SetLastError = true)] - internal static extern unsafe string GetPeerUserName(SafeHandle socket); + internal static extern string GetPeerUserName(SafeHandle socket); } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetRandomBytes.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetRandomBytes.cs index c3389aad84654..543487754ed7c 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetRandomBytes.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetRandomBytes.cs @@ -6,7 +6,7 @@ internal static partial class Interop { - internal unsafe partial class Sys + internal partial class Sys { [DllImport(Interop.Libraries.SystemNative, EntryPoint = "SystemNative_GetNonCryptographicallySecureRandomBytes")] internal static extern unsafe void GetNonCryptographicallySecureRandomBytes(byte* buffer, int length); diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetSystemTimeAsTicks.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetSystemTimeAsTicks.cs index 62c83123c86d8..6811f5b45bfc4 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetSystemTimeAsTicks.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetSystemTimeAsTicks.cs @@ -5,7 +5,7 @@ internal static partial class Interop { - internal unsafe partial class Sys + internal partial class Sys { [DllImport(Interop.Libraries.SystemNative, EntryPoint = "SystemNative_GetSystemTimeAsTicks")] internal static extern long GetSystemTimeAsTicks(); diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.InterfaceNameToIndex.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.InterfaceNameToIndex.cs index 8cb18bfb30020..74fab3ed6d6a2 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.InterfaceNameToIndex.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.InterfaceNameToIndex.cs @@ -9,6 +9,6 @@ internal static partial class Interop internal static partial class Sys { [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_InterfaceNameToIndex", SetLastError = true)] - public static extern unsafe uint InterfaceNameToIndex(string name); + public static extern uint InterfaceNameToIndex(string name); } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.MemAlloc.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.MemAlloc.cs index b7f4bfd374216..6bf296ffdbeae 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.MemAlloc.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.MemAlloc.cs @@ -6,7 +6,7 @@ internal static partial class Interop { - internal unsafe partial class Sys + internal partial class Sys { [DllImport(Interop.Libraries.SystemNative, EntryPoint = "SystemNative_MemAlloc")] internal static extern IntPtr MemAlloc(nuint sizeInBytes); diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs index 44db77808f85b..fb59b17534680 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs @@ -173,29 +173,26 @@ internal static int GetFormatInfoForMountPoint(string name, out DriveType type) return GetFormatInfoForMountPoint(name, out _, out type); } - private static int GetFormatInfoForMountPoint(string name, out string format, out DriveType type) + private static unsafe int GetFormatInfoForMountPoint(string name, out string format, out DriveType type) { - unsafe + byte* formatBuffer = stackalloc byte[MountPointFormatBufferSizeInBytes]; // format names should be small + long numericFormat; + int result = GetFormatInfoForMountPoint(name, formatBuffer, MountPointFormatBufferSizeInBytes, &numericFormat); + if (result == 0) { - byte* formatBuffer = stackalloc byte[MountPointFormatBufferSizeInBytes]; // format names should be small - long numericFormat; - int result = GetFormatInfoForMountPoint(name, formatBuffer, MountPointFormatBufferSizeInBytes, &numericFormat); - if (result == 0) - { - // Check if we have a numeric answer or string - format = numericFormat != -1 ? - Enum.GetName(typeof(UnixFileSystemTypes), numericFormat) ?? string.Empty : - Marshal.PtrToStringAnsi((IntPtr)formatBuffer)!; - type = GetDriveType(format); - } - else - { - format = string.Empty; - type = DriveType.Unknown; - } - - return result; + // Check if we have a numeric answer or string + format = numericFormat != -1 ? + Enum.GetName(typeof(UnixFileSystemTypes), numericFormat) ?? string.Empty : + Marshal.PtrToStringAnsi((IntPtr)formatBuffer)!; + type = GetDriveType(format); + } + else + { + format = string.Empty; + type = DriveType.Unknown; } + + return result; } /// Categorizes a file system name into a drive type. diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ReadLink.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ReadLink.cs index 9735b0ff776f9..660259ff907c1 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ReadLink.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ReadLink.cs @@ -21,7 +21,7 @@ internal static partial class Sys /// Returns the number of bytes placed into the buffer on success; bufferSize if the buffer is too small; and -1 on error. /// [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ReadLink", SetLastError = true)] - private static extern unsafe int ReadLink(string path, byte[] buffer, int bufferSize); + private static extern int ReadLink(string path, byte[] buffer, int bufferSize); /// /// Takes a path to a symbolic link and returns the link target path. diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ReadStdinUnbuffered.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ReadStdinUnbuffered.cs index c4419f69c0506..2ac19f1d9d1bb 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ReadStdinUnbuffered.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ReadStdinUnbuffered.cs @@ -12,9 +12,9 @@ internal static partial class Sys internal static extern unsafe int ReadStdin(byte* buffer, int bufferSize); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_InitializeConsoleBeforeRead")] - internal static extern unsafe void InitializeConsoleBeforeRead(byte minChars = 1, byte decisecondsTimeout = 0); + internal static extern void InitializeConsoleBeforeRead(byte minChars = 1, byte decisecondsTimeout = 0); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_UninitializeConsoleAfterRead")] - internal static extern unsafe void UninitializeConsoleAfterRead(); + internal static extern void UninitializeConsoleAfterRead(); } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SendFile.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SendFile.cs index 1566cdc75ca65..3eb343895fafb 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SendFile.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SendFile.cs @@ -8,6 +8,6 @@ internal static partial class Interop internal static partial class Sys { [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SendFile", SetLastError = true)] - internal static extern unsafe Error SendFile(SafeHandle out_fd, SafeHandle in_fd, long offset, long count, out long sent); + internal static extern Error SendFile(SafeHandle out_fd, SafeHandle in_fd, long offset, long count, out long sent); } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SetEUid.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SetEUid.cs index ad3a2fcd9031b..6a40f17c6dead 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SetEUid.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SetEUid.cs @@ -9,6 +9,6 @@ internal static partial class Interop internal static partial class Sys { [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetEUid")] - internal static extern unsafe int SetEUid(uint euid); + internal static extern int SetEUid(uint euid); } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SetReceiveTimeout.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SetReceiveTimeout.cs index 36926851e0798..daba80bbed250 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SetReceiveTimeout.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SetReceiveTimeout.cs @@ -10,6 +10,6 @@ internal static partial class Interop internal static partial class Sys { [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetReceiveTimeout")] - internal static extern unsafe Error SetReceiveTimeout(SafeHandle socket, int millisecondsTimeout); + internal static extern Error SetReceiveTimeout(SafeHandle socket, int millisecondsTimeout); } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SetSendTimeout.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SetSendTimeout.cs index db2a3632c10c8..ac7171fa48352 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SetSendTimeout.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SetSendTimeout.cs @@ -10,6 +10,6 @@ internal static partial class Interop internal static partial class Sys { [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetSendTimeout")] - internal static extern unsafe Error SetSendTimeout(SafeHandle socket, int millisecondsTimeout); + internal static extern Error SetSendTimeout(SafeHandle socket, int millisecondsTimeout); } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SocketEvent.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SocketEvent.cs index af9fcd32739b7..2a8246a7b9ab0 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SocketEvent.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.SocketEvent.cs @@ -28,7 +28,7 @@ internal struct SocketEvent } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_CreateSocketEventPort")] - internal static extern unsafe Error CreateSocketEventPort(out IntPtr port); + internal static extern Error CreateSocketEventPort(out IntPtr port); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_CloseSocketEventPort")] internal static extern Error CloseSocketEventPort(IntPtr port); diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.Stat.Span.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.Stat.Span.cs index 278dbeb1de4dd..3c638cb60aa52 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.Stat.Span.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.Stat.Span.cs @@ -14,12 +14,11 @@ internal static partial class Sys private const int StackBufferSize = 256; [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Stat", SetLastError = true)] - internal static extern unsafe int Stat(ref byte path, out FileStatus output); + internal static extern int Stat(ref byte path, out FileStatus output); - internal static unsafe int Stat(ReadOnlySpan path, out FileStatus output) + internal static int Stat(ReadOnlySpan path, out FileStatus output) { - byte* buffer = stackalloc byte[StackBufferSize]; - var converter = new ValueUtf8Converter(new Span(buffer, StackBufferSize)); + var converter = new ValueUtf8Converter(stackalloc byte[StackBufferSize]); int result = Stat(ref MemoryMarshal.GetReference(converter.ConvertAndTerminateString(path)), out output); converter.Dispose(); return result; @@ -28,10 +27,9 @@ internal static unsafe int Stat(ReadOnlySpan path, out FileStatus output) [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LStat", SetLastError = true)] internal static extern int LStat(ref byte path, out FileStatus output); - internal static unsafe int LStat(ReadOnlySpan path, out FileStatus output) + internal static int LStat(ReadOnlySpan path, out FileStatus output) { - byte* buffer = stackalloc byte[StackBufferSize]; - var converter = new ValueUtf8Converter(new Span(buffer, StackBufferSize)); + var converter = new ValueUtf8Converter(stackalloc byte[StackBufferSize]); int result = LStat(ref MemoryMarshal.GetReference(converter.ConvertAndTerminateString(path)), out output); converter.Dispose(); return result; diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.StdinReady.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.StdinReady.cs index 51104f30af366..8ba426acc962d 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.StdinReady.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.StdinReady.cs @@ -8,6 +8,6 @@ internal static partial class Interop internal static partial class Sys { [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_StdinReady")] - internal static extern unsafe bool StdinReady(); + internal static extern bool StdinReady(); } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs index 4ea3397f6be48..1f7cc6c1bbdaa 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs @@ -72,7 +72,7 @@ internal static partial class Ssl } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslWrite")] - internal static extern unsafe int SslWrite(SafeSslHandle ssl, ref byte buf, int num); + internal static extern int SslWrite(SafeSslHandle ssl, ref byte buf, int num); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRead")] internal static extern unsafe int SslRead(SafeSslHandle ssl, byte* buf, int num); @@ -102,7 +102,7 @@ internal static partial class Ssl internal static extern unsafe int BioWrite(SafeBioHandle b, byte* data, int len); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioWrite")] - internal static extern unsafe int BioWrite(SafeBioHandle b, ref byte data, int len); + internal static extern int BioWrite(SafeBioHandle b, ref byte data, int len); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertificate")] internal static extern SafeX509Handle SslGetPeerCertificate(SafeSslHandle ssl); diff --git a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs index 8df7733f06715..2cf3b38f03370 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs @@ -32,7 +32,7 @@ internal static partial class Ssl internal static extern int SslCtxSetAlpnProtos(SafeSslContextHandle ctx, IntPtr protos, int len); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCtxSetAlpnSelectCb")] - internal static extern unsafe void SslCtxSetAlpnSelectCb(SafeSslContextHandle ctx, SslCtxSetAlpnCallback callback, IntPtr arg); + internal static extern void SslCtxSetAlpnSelectCb(SafeSslContextHandle ctx, SslCtxSetAlpnCallback callback, IntPtr arg); internal static unsafe int SslCtxSetAlpnProtos(SafeSslContextHandle ctx, List protocols) { diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertStringSecurityDescriptorToSecurityDescriptor.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertStringSecurityDescriptorToSecurityDescriptor.cs index ab5b3ab8e1212..838c1124947da 100644 --- a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertStringSecurityDescriptorToSecurityDescriptor.cs +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertStringSecurityDescriptorToSecurityDescriptor.cs @@ -10,7 +10,7 @@ internal partial class Interop internal partial class Advapi32 { [DllImport(Interop.Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)] - internal static extern unsafe bool ConvertStringSecurityDescriptorToSecurityDescriptor( + internal static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor( string StringSecurityDescriptor, int StringSDRevision, out SafeLocalAllocHandle pSecurityDescriptor, diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.QueryServiceStatus.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.QueryServiceStatus.cs index 7591a0740e568..c71d58b220373 100644 --- a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.QueryServiceStatus.cs +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.QueryServiceStatus.cs @@ -11,6 +11,5 @@ internal partial class Advapi32 { [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern unsafe bool QueryServiceStatus(SafeServiceHandle serviceHandle, SERVICE_STATUS* pStatus); - } } diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.RegEnumKeyEx.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.RegEnumKeyEx.cs index 6be8c154dbb0e..5fa7759b2259a 100644 --- a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.RegEnumKeyEx.cs +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.RegEnumKeyEx.cs @@ -14,7 +14,7 @@ internal static partial class Interop internal static partial class Advapi32 { [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegEnumKeyExW", ExactSpelling = true)] - internal static extern unsafe int RegEnumKeyEx( + internal static extern int RegEnumKeyEx( SafeRegistryHandle hKey, int dwIndex, char[] lpName, diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.RegEnumValue.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.RegEnumValue.cs index d8d2cbe860959..29788f2760fba 100644 --- a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.RegEnumValue.cs +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.RegEnumValue.cs @@ -15,7 +15,7 @@ internal static partial class Interop internal static partial class Advapi32 { [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegEnumValueW", ExactSpelling = true)] - internal static extern unsafe int RegEnumValue( + internal static extern int RegEnumValue( SafeRegistryHandle hKey, int dwIndex, char[] lpValueName, diff --git a/src/libraries/Common/src/Interop/Windows/BCrypt/Cng.cs b/src/libraries/Common/src/Interop/Windows/BCrypt/Cng.cs index 078288ade2647..e1f7c16e7d291 100644 --- a/src/libraries/Common/src/Interop/Windows/BCrypt/Cng.cs +++ b/src/libraries/Common/src/Interop/Windows/BCrypt/Cng.cs @@ -124,10 +124,10 @@ internal static class Interop public static extern NTSTATUS BCryptOpenAlgorithmProvider(out SafeAlgorithmHandle phAlgorithm, string pszAlgId, string? pszImplementation, int dwFlags); [DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)] - public static extern unsafe NTSTATUS BCryptSetProperty(SafeAlgorithmHandle hObject, string pszProperty, string pbInput, int cbInput, int dwFlags); + public static extern NTSTATUS BCryptSetProperty(SafeAlgorithmHandle hObject, string pszProperty, string pbInput, int cbInput, int dwFlags); [DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode, EntryPoint = "BCryptSetProperty")] - private static extern unsafe NTSTATUS BCryptSetIntPropertyPrivate(SafeBCryptHandle hObject, string pszProperty, ref int pdwInput, int cbInput, int dwFlags); + private static extern NTSTATUS BCryptSetIntPropertyPrivate(SafeBCryptHandle hObject, string pszProperty, ref int pdwInput, int cbInput, int dwFlags); public static unsafe NTSTATUS BCryptSetIntProperty(SafeBCryptHandle hObject, string pszProperty, ref int pdwInput, int dwFlags) { diff --git a/src/libraries/Common/src/Interop/Windows/BCrypt/Interop.BCryptImportKey.cs b/src/libraries/Common/src/Interop/Windows/BCrypt/Interop.BCryptImportKey.cs index c5015bf258783..848ef7f57c2fb 100644 --- a/src/libraries/Common/src/Interop/Windows/BCrypt/Interop.BCryptImportKey.cs +++ b/src/libraries/Common/src/Interop/Windows/BCrypt/Interop.BCryptImportKey.cs @@ -11,32 +11,29 @@ internal partial class Interop { internal partial class BCrypt { - internal static SafeKeyHandle BCryptImportKey(SafeAlgorithmHandle hAlg, ReadOnlySpan key) + internal static unsafe SafeKeyHandle BCryptImportKey(SafeAlgorithmHandle hAlg, ReadOnlySpan key) { - unsafe + const string BCRYPT_KEY_DATA_BLOB = "KeyDataBlob"; + int keySize = key.Length; + int blobSize = sizeof(BCRYPT_KEY_DATA_BLOB_HEADER) + keySize; + byte[] blob = new byte[blobSize]; + fixed (byte* pbBlob = blob) { - const string BCRYPT_KEY_DATA_BLOB = "KeyDataBlob"; - int keySize = key.Length; - int blobSize = sizeof(BCRYPT_KEY_DATA_BLOB_HEADER) + keySize; - byte[] blob = new byte[blobSize]; - fixed (byte* pbBlob = blob) - { - BCRYPT_KEY_DATA_BLOB_HEADER* pBlob = (BCRYPT_KEY_DATA_BLOB_HEADER*)pbBlob; - pBlob->dwMagic = BCRYPT_KEY_DATA_BLOB_HEADER.BCRYPT_KEY_DATA_BLOB_MAGIC; - pBlob->dwVersion = BCRYPT_KEY_DATA_BLOB_HEADER.BCRYPT_KEY_DATA_BLOB_VERSION1; - pBlob->cbKeyData = (uint)keySize; - } - - key.CopyTo(blob.AsSpan(sizeof(BCRYPT_KEY_DATA_BLOB_HEADER))); - SafeKeyHandle hKey; - NTSTATUS ntStatus = BCryptImportKey(hAlg, IntPtr.Zero, BCRYPT_KEY_DATA_BLOB, out hKey, IntPtr.Zero, 0, blob, blobSize, 0); - if (ntStatus != NTSTATUS.STATUS_SUCCESS) - { - throw CreateCryptographicException(ntStatus); - } + BCRYPT_KEY_DATA_BLOB_HEADER* pBlob = (BCRYPT_KEY_DATA_BLOB_HEADER*)pbBlob; + pBlob->dwMagic = BCRYPT_KEY_DATA_BLOB_HEADER.BCRYPT_KEY_DATA_BLOB_MAGIC; + pBlob->dwVersion = BCRYPT_KEY_DATA_BLOB_HEADER.BCRYPT_KEY_DATA_BLOB_VERSION1; + pBlob->cbKeyData = (uint)keySize; + } - return hKey; + key.CopyTo(blob.AsSpan(sizeof(BCRYPT_KEY_DATA_BLOB_HEADER))); + SafeKeyHandle hKey; + NTSTATUS ntStatus = BCryptImportKey(hAlg, IntPtr.Zero, BCRYPT_KEY_DATA_BLOB, out hKey, IntPtr.Zero, 0, blob, blobSize, 0); + if (ntStatus != NTSTATUS.STATUS_SUCCESS) + { + throw CreateCryptographicException(ntStatus); } + + return hKey; } [StructLayout(LayoutKind.Sequential)] diff --git a/src/libraries/Common/src/Interop/Windows/Crypt32/Interop.CryptEncodeDecodeWrappers.cs b/src/libraries/Common/src/Interop/Windows/Crypt32/Interop.CryptEncodeDecodeWrappers.cs index e5f2c2af3d0ed..d26bd3404b7b1 100644 --- a/src/libraries/Common/src/Interop/Windows/Crypt32/Interop.CryptEncodeDecodeWrappers.cs +++ b/src/libraries/Common/src/Interop/Windows/Crypt32/Interop.CryptEncodeDecodeWrappers.cs @@ -16,31 +16,26 @@ internal static partial class Interop // internal static partial class Crypt32 { - internal static SafeHandle CryptDecodeObjectToMemory(CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded) + internal static unsafe SafeHandle CryptDecodeObjectToMemory(CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded) { - unsafe + fixed (byte* pbEncodedPointer = pbEncoded) { - fixed (byte* pbEncodedPointer = pbEncoded) - { - return CryptDecodeObjectToMemory(lpszStructType, (IntPtr)pbEncodedPointer, pbEncoded.Length); - } + return CryptDecodeObjectToMemory(lpszStructType, (IntPtr)pbEncodedPointer, pbEncoded.Length); } } - internal static SafeHandle CryptDecodeObjectToMemory(CryptDecodeObjectStructType lpszStructType, IntPtr pbEncoded, int cbEncoded) + internal static unsafe SafeHandle CryptDecodeObjectToMemory(CryptDecodeObjectStructType lpszStructType, IntPtr pbEncoded, int cbEncoded) { int cbRequired = 0; - unsafe - { - if (!CryptDecodeObject(MsgEncodingType.All, (IntPtr)lpszStructType, pbEncoded, cbEncoded, 0, null, ref cbRequired)) - throw Marshal.GetLastWin32Error().ToCryptographicException(); - SafeHandle sh = SafeHeapAllocHandle.Alloc(cbRequired); - if (!CryptDecodeObject(MsgEncodingType.All, (IntPtr)lpszStructType, pbEncoded, cbEncoded, 0, (void*)sh.DangerousGetHandle(), ref cbRequired)) - throw Marshal.GetLastWin32Error().ToCryptographicException(); + if (!CryptDecodeObject(MsgEncodingType.All, (IntPtr)lpszStructType, pbEncoded, cbEncoded, 0, null, ref cbRequired)) + throw Marshal.GetLastWin32Error().ToCryptographicException(); - return sh; - } + SafeHandle sh = SafeHeapAllocHandle.Alloc(cbRequired); + if (!CryptDecodeObject(MsgEncodingType.All, (IntPtr)lpszStructType, pbEncoded, cbEncoded, 0, (void*)sh.DangerousGetHandle(), ref cbRequired)) + throw Marshal.GetLastWin32Error().ToCryptographicException(); + + return sh; } internal static unsafe byte[] CryptEncodeObjectToByteArray(CryptDecodeObjectStructType lpszStructType, void* decoded) diff --git a/src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs b/src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs index 25b03f5ddebf8..e0982d907c687 100644 --- a/src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs +++ b/src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs @@ -21,9 +21,9 @@ internal static partial class HttpApi internal const int IPv4AddressSize = 16; internal const int IPv6AddressSize = 28; - private static unsafe bool InitHttpApi(HTTPAPI_VERSION version) + private static bool InitHttpApi(HTTPAPI_VERSION version) { - uint statusCode = HttpInitialize(version, (uint)HTTP_FLAGS.HTTP_INITIALIZE_SERVER, null); + uint statusCode = HttpInitialize(version, (uint)HTTP_FLAGS.HTTP_INITIALIZE_SERVER, IntPtr.Zero); return statusCode == ERROR_SUCCESS; } @@ -456,7 +456,7 @@ internal struct HTTP_BINDING_INFO [DllImport(Libraries.HttpApi, SetLastError = true)] - internal static extern unsafe uint HttpInitialize(HTTPAPI_VERSION version, uint flags, void* pReserved); + internal static extern uint HttpInitialize(HTTPAPI_VERSION version, uint flags, IntPtr pReserved); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern uint HttpSetUrlGroupProperty(ulong urlGroupId, HTTP_SERVER_PROPERTY serverProperty, IntPtr pPropertyInfo, uint propertyInfoLength); @@ -496,7 +496,7 @@ internal static extern unsafe uint HttpCreateRequestQueue(HTTPAPI_VERSION versio internal static extern unsafe uint HttpSendResponseEntityBody(SafeHandle requestQueueHandle, ulong requestId, uint flags, ushort entityChunkCount, HTTP_DATA_CHUNK* pEntityChunks, uint* pBytesSent, SafeLocalAllocHandle pRequestBuffer, uint requestBufferLength, NativeOverlapped* pOverlapped, void* pLogData); [DllImport(Libraries.HttpApi, SetLastError = true)] - internal static extern unsafe uint HttpCloseRequestQueue(IntPtr pReqQueueHandle); + internal static extern uint HttpCloseRequestQueue(IntPtr pReqQueueHandle); [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern uint HttpCancelHttpRequest(SafeHandle requestQueueHandle, ulong requestId, IntPtr pOverlapped); diff --git a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CompareStringOrdinal.cs b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CompareStringOrdinal.cs index 5bc410bcca1e1..4b3d8c75b90df 100644 --- a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CompareStringOrdinal.cs +++ b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CompareStringOrdinal.cs @@ -9,7 +9,7 @@ internal partial class Kernel32 { // https://msdn.microsoft.com/en-us/library/windows/desktop/dd317762.aspx [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] - public static extern unsafe int CompareStringOrdinal( + public static extern int CompareStringOrdinal( ref char lpString1, int cchCount1, ref char lpString2, diff --git a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.ConditionVariable.cs b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.ConditionVariable.cs index 683be9fbef6e7..6f736eebcb2db 100644 --- a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.ConditionVariable.cs +++ b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.ConditionVariable.cs @@ -4,7 +4,7 @@ using System; using System.Runtime.InteropServices; -internal static unsafe partial class Interop +internal static partial class Interop { internal static partial class Kernel32 { @@ -15,12 +15,12 @@ internal struct CONDITION_VARIABLE } [DllImport(Libraries.Kernel32, ExactSpelling = true)] - internal static extern void InitializeConditionVariable(CONDITION_VARIABLE* ConditionVariable); + internal static extern unsafe void InitializeConditionVariable(CONDITION_VARIABLE* ConditionVariable); [DllImport(Libraries.Kernel32, ExactSpelling = true)] - internal static extern void WakeConditionVariable(CONDITION_VARIABLE* ConditionVariable); + internal static extern unsafe void WakeConditionVariable(CONDITION_VARIABLE* ConditionVariable); [DllImport(Libraries.Kernel32, ExactSpelling = true)] - internal static extern bool SleepConditionVariableCS(CONDITION_VARIABLE* ConditionVariable, CRITICAL_SECTION* CriticalSection, int dwMilliseconds); + internal static extern unsafe bool SleepConditionVariableCS(CONDITION_VARIABLE* ConditionVariable, CRITICAL_SECTION* CriticalSection, int dwMilliseconds); } } diff --git a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CriticalSection.cs b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CriticalSection.cs index 864d557861523..1d9a6ef5c7aca 100644 --- a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CriticalSection.cs +++ b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CriticalSection.cs @@ -4,7 +4,7 @@ using System; using System.Runtime.InteropServices; -internal static unsafe partial class Interop +internal static partial class Interop { internal static partial class Kernel32 { @@ -20,15 +20,15 @@ internal struct CRITICAL_SECTION } [DllImport(Libraries.Kernel32, ExactSpelling = true)] - internal static extern void InitializeCriticalSection(CRITICAL_SECTION* lpCriticalSection); + internal static extern unsafe void InitializeCriticalSection(CRITICAL_SECTION* lpCriticalSection); [DllImport(Libraries.Kernel32, ExactSpelling = true)] - internal static extern void EnterCriticalSection(CRITICAL_SECTION* lpCriticalSection); + internal static extern unsafe void EnterCriticalSection(CRITICAL_SECTION* lpCriticalSection); [DllImport(Libraries.Kernel32, ExactSpelling = true)] - internal static extern void LeaveCriticalSection(CRITICAL_SECTION* lpCriticalSection); + internal static extern unsafe void LeaveCriticalSection(CRITICAL_SECTION* lpCriticalSection); [DllImport(Libraries.Kernel32, ExactSpelling = true)] - internal static extern void DeleteCriticalSection(CRITICAL_SECTION* lpCriticalSection); + internal static extern unsafe void DeleteCriticalSection(CRITICAL_SECTION* lpCriticalSection); } } diff --git a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.FormatMessage_SafeLibraryHandle.cs b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.FormatMessage_SafeLibraryHandle.cs index a0a9ed7c9feda..6626deb755ec5 100644 --- a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.FormatMessage_SafeLibraryHandle.cs +++ b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.FormatMessage_SafeLibraryHandle.cs @@ -14,7 +14,7 @@ internal partial class Kernel32 public const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = true)] - public static extern unsafe int FormatMessage( + public static extern int FormatMessage( int dwFlags, SafeLibraryHandle lpSource, uint dwMessageId, diff --git a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetComputerName.cs b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetComputerName.cs index f267d51b65fbe..4d41070638856 100644 --- a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetComputerName.cs +++ b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetComputerName.cs @@ -10,12 +10,12 @@ internal static partial class Interop internal static partial class Kernel32 { [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, EntryPoint = "GetComputerNameW", ExactSpelling = true)] - private static extern unsafe int GetComputerName(ref char lpBuffer, ref uint nSize); + private static extern int GetComputerName(ref char lpBuffer, ref uint nSize); // maximum length of the NETBIOS name (not including NULL) private const int MAX_COMPUTERNAME_LENGTH = 15; - internal static unsafe string? GetComputerName() + internal static string? GetComputerName() { Span buffer = stackalloc char[MAX_COMPUTERNAME_LENGTH + 1]; uint length = (uint)buffer.Length; diff --git a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetEnvironmentVariable.cs b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetEnvironmentVariable.cs index 74e2a02d9ba39..425ea9ef1e2c8 100644 --- a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetEnvironmentVariable.cs +++ b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetEnvironmentVariable.cs @@ -9,6 +9,6 @@ internal static partial class Interop internal static partial class Kernel32 { [DllImport(Libraries.Kernel32, EntryPoint = "GetEnvironmentVariableW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)] - internal static extern unsafe uint GetEnvironmentVariable(string lpName, ref char lpBuffer, uint nSize); + internal static extern uint GetEnvironmentVariable(string lpName, ref char lpBuffer, uint nSize); } } diff --git a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetModuleFileName.cs b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetModuleFileName.cs index 9c8f0109177b3..3973f9747937f 100644 --- a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetModuleFileName.cs +++ b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetModuleFileName.cs @@ -8,7 +8,7 @@ internal static partial class Interop { - internal static unsafe partial class Kernel32 + internal static partial class Kernel32 { [DllImport(Libraries.Kernel32, EntryPoint = "GetModuleFileNameW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)] internal static extern uint GetModuleFileName(IntPtr hModule, ref char lpFilename, uint nSize); diff --git a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.Globalization.cs b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.Globalization.cs index 3a61901297a3c..cda3b0b2009dc 100644 --- a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.Globalization.cs +++ b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.Globalization.cs @@ -6,7 +6,7 @@ internal static partial class Interop { - internal static unsafe partial class Kernel32 + internal static partial class Kernel32 { // Under debug mode only, we'll want to check the error codes // of some of the p/invokes we make. @@ -48,13 +48,13 @@ internal static unsafe partial class Kernel32 internal const string LOCALE_NAME_SYSTEM_DEFAULT = "!x-sys-default-locale"; [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal static extern int LCIDToLocaleName(int locale, char* pLocaleName, int cchName, uint dwFlags); + internal static extern unsafe int LCIDToLocaleName(int locale, char* pLocaleName, int cchName, uint dwFlags); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern int LocaleNameToLCID(string lpName, uint dwFlags); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern int LCMapStringEx( + internal static extern unsafe int LCMapStringEx( string? lpLocaleName, uint dwMapFlags, char* lpSrcStr, @@ -66,7 +66,7 @@ internal static extern int LCMapStringEx( IntPtr sortHandle); [DllImport("kernel32.dll", EntryPoint = "FindNLSStringEx", SetLastError = SetLastErrorForDebug)] - internal static extern int FindNLSStringEx( + internal static extern unsafe int FindNLSStringEx( char* lpLocaleName, uint dwFindNLSStringFlags, char* lpStringSource, @@ -79,7 +79,7 @@ internal static extern int FindNLSStringEx( IntPtr sortHandle); [DllImport("kernel32.dll", EntryPoint = "CompareStringEx")] - internal static extern int CompareStringEx( + internal static extern unsafe int CompareStringEx( char* lpLocaleName, uint dwCmpFlags, char* lpString1, @@ -91,7 +91,7 @@ internal static extern int CompareStringEx( IntPtr lParam); [DllImport("kernel32.dll", EntryPoint = "CompareStringOrdinal")] - internal static extern int CompareStringOrdinal( + internal static extern unsafe int CompareStringOrdinal( char* lpString1, int cchCount1, char* lpString2, @@ -99,7 +99,7 @@ internal static extern int CompareStringOrdinal( bool bIgnoreCase); [DllImport("kernel32.dll", EntryPoint = "FindStringOrdinal", SetLastError = SetLastErrorForDebug)] - internal static extern int FindStringOrdinal( + internal static extern unsafe int FindStringOrdinal( uint dwFindStringOrdinalFlags, char* lpStringSource, int cchSource, @@ -108,7 +108,7 @@ internal static extern int FindStringOrdinal( BOOL bIgnoreCase); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal static extern bool IsNLSDefinedString( + internal static extern unsafe bool IsNLSDefinedString( int Function, uint dwFlags, IntPtr lpVersionInformation, @@ -116,16 +116,16 @@ internal static extern bool IsNLSDefinedString( int cchStr); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] - internal static extern Interop.BOOL GetUserPreferredUILanguages(uint dwFlags, uint* pulNumLanguages, char* pwszLanguagesBuffer, uint* pcchLanguagesBuffer); + internal static extern unsafe Interop.BOOL GetUserPreferredUILanguages(uint dwFlags, uint* pulNumLanguages, char* pwszLanguagesBuffer, uint* pcchLanguagesBuffer); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, void* lpLCData, int cchData); + internal static extern unsafe int GetLocaleInfoEx(string lpLocaleName, uint LCType, void* lpLCData, int cchData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal static extern bool EnumSystemLocalesEx(delegate* unmanaged lpLocaleEnumProcEx, uint dwFlags, void* lParam, IntPtr reserved); + internal static extern unsafe bool EnumSystemLocalesEx(delegate* unmanaged lpLocaleEnumProcEx, uint dwFlags, void* lParam, IntPtr reserved); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal static extern bool EnumTimeFormatsEx(delegate* unmanaged lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, void* lParam); + internal static extern unsafe bool EnumTimeFormatsEx(delegate* unmanaged lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, void* lParam); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern int GetCalendarInfoEx(string? lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, out int lpValue); @@ -137,10 +137,10 @@ internal static extern bool IsNLSDefinedString( internal static extern int GetUserGeoID(int geoClass); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal static extern int GetGeoInfo(int location, int geoType, char* lpGeoData, int cchData, int LangId); + internal static extern unsafe int GetGeoInfo(int location, int geoType, char* lpGeoData, int cchData, int LangId); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal static extern bool EnumCalendarInfoExEx(delegate* unmanaged pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string? lpReserved, uint CalType, void* lParam); + internal static extern unsafe bool EnumCalendarInfoExEx(delegate* unmanaged pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string? lpReserved, uint CalType, void* lParam); [StructLayout(LayoutKind.Sequential)] internal struct NlsVersionInfoEx @@ -153,6 +153,6 @@ internal struct NlsVersionInfoEx } [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal static extern bool GetNLSVersionEx(int function, string localeName, NlsVersionInfoEx* lpVersionInformation); + internal static extern unsafe bool GetNLSVersionEx(int function, string localeName, NlsVersionInfoEx* lpVersionInformation); } } diff --git a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.SetFileCompletionNotificationModes.cs b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.SetFileCompletionNotificationModes.cs index 084cf297c2bf0..684fabc0cafd0 100644 --- a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.SetFileCompletionNotificationModes.cs +++ b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.SetFileCompletionNotificationModes.cs @@ -17,6 +17,6 @@ internal enum FileCompletionNotificationModes : byte } [DllImport(Libraries.Kernel32, SetLastError = true)] - internal static extern unsafe bool SetFileCompletionNotificationModes(SafeHandle handle, FileCompletionNotificationModes flags); + internal static extern bool SetFileCompletionNotificationModes(SafeHandle handle, FileCompletionNotificationModes flags); } } diff --git a/src/libraries/Common/src/Interop/Windows/NCrypt/Interop.NCryptDeriveKeyMaterial.cs b/src/libraries/Common/src/Interop/Windows/NCrypt/Interop.NCryptDeriveKeyMaterial.cs index 8e8509310ae3b..5015c59b70b35 100644 --- a/src/libraries/Common/src/Interop/Windows/NCrypt/Interop.NCryptDeriveKeyMaterial.cs +++ b/src/libraries/Common/src/Interop/Windows/NCrypt/Interop.NCryptDeriveKeyMaterial.cs @@ -213,7 +213,7 @@ internal static byte[] DeriveKeyMaterialHmac( /// /// Derive key material from a secret agreement using the TLS KDF /// - internal static byte[] DeriveKeyMaterialTls( + internal static unsafe byte[] DeriveKeyMaterialTls( SafeNCryptSecretHandle secretAgreement, byte[] label, byte[] seed, @@ -221,28 +221,25 @@ internal static byte[] DeriveKeyMaterialTls( { Span buffers = stackalloc NCryptBuffer[2]; - unsafe + fixed (byte* pLabel = label, pSeed = seed) { - fixed (byte* pLabel = label, pSeed = seed) - { - NCryptBuffer labelBuffer = default; - labelBuffer.cbBuffer = label.Length; - labelBuffer.BufferType = BufferType.KdfTlsLabel; - labelBuffer.pvBuffer = new IntPtr(pLabel); - buffers[0] = labelBuffer; - - NCryptBuffer seedBuffer = default; - seedBuffer.cbBuffer = seed.Length; - seedBuffer.BufferType = BufferType.KdfTlsSeed; - seedBuffer.pvBuffer = new IntPtr(pSeed); - buffers[1] = seedBuffer; - - return DeriveKeyMaterial( - secretAgreement, - BCryptNative.KeyDerivationFunction.Tls, - buffers, - flags); - } + NCryptBuffer labelBuffer = default; + labelBuffer.cbBuffer = label.Length; + labelBuffer.BufferType = BufferType.KdfTlsLabel; + labelBuffer.pvBuffer = new IntPtr(pLabel); + buffers[0] = labelBuffer; + + NCryptBuffer seedBuffer = default; + seedBuffer.cbBuffer = seed.Length; + seedBuffer.BufferType = BufferType.KdfTlsSeed; + seedBuffer.pvBuffer = new IntPtr(pSeed); + buffers[1] = seedBuffer; + + return DeriveKeyMaterial( + secretAgreement, + BCryptNative.KeyDerivationFunction.Tls, + buffers, + flags); } } } diff --git a/src/libraries/Common/src/Interop/Windows/NCrypt/Interop.Properties.cs b/src/libraries/Common/src/Interop/Windows/NCrypt/Interop.Properties.cs index 64acf11a952f6..9c6ce0359c00a 100644 --- a/src/libraries/Common/src/Interop/Windows/NCrypt/Interop.Properties.cs +++ b/src/libraries/Common/src/Interop/Windows/NCrypt/Interop.Properties.cs @@ -20,62 +20,50 @@ internal static partial class NCrypt internal static extern unsafe ErrorCode NCryptSetProperty(SafeNCryptHandle hObject, string pszProperty, [In] void* pbInput, int cbInput, CngPropertyOptions dwFlags); [SupportedOSPlatform("windows")] - internal static ErrorCode NCryptGetByteProperty(SafeNCryptHandle hObject, string pszProperty, ref byte result, CngPropertyOptions options = CngPropertyOptions.None) + internal static unsafe ErrorCode NCryptGetByteProperty(SafeNCryptHandle hObject, string pszProperty, ref byte result, CngPropertyOptions options = CngPropertyOptions.None) { - int cbResult; - ErrorCode errorCode; - - unsafe + fixed (byte* pResult = &result) { - fixed (byte* pResult = &result) + ErrorCode errorCode = Interop.NCrypt.NCryptGetProperty( + hObject, + pszProperty, + pResult, + sizeof(byte), + out int cbResult, + options); + + if (errorCode == ErrorCode.ERROR_SUCCESS) { - errorCode = Interop.NCrypt.NCryptGetProperty( - hObject, - pszProperty, - pResult, - sizeof(byte), - out cbResult, - options); + Debug.Assert(cbResult == sizeof(byte)); } - } - if (errorCode == ErrorCode.ERROR_SUCCESS) - { - Debug.Assert(cbResult == sizeof(byte)); + return errorCode; } - - return errorCode; } - internal static ErrorCode NCryptGetIntProperty(SafeNCryptHandle hObject, string pszProperty, ref int result) + internal static unsafe ErrorCode NCryptGetIntProperty(SafeNCryptHandle hObject, string pszProperty, ref int result) { - int cbResult; - ErrorCode errorCode; - - unsafe + fixed (int* pResult = &result) { - fixed (int* pResult = &result) - { #if NETSTANDARD || NETCOREAPP - Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); + Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); #endif - errorCode = Interop.NCrypt.NCryptGetProperty( - hObject, - pszProperty, - pResult, - sizeof(int), - out cbResult, - CngPropertyOptions.None); + ErrorCode errorCode = Interop.NCrypt.NCryptGetProperty( + hObject, + pszProperty, + pResult, + sizeof(int), + out int cbResult, + CngPropertyOptions.None); + + if (errorCode == ErrorCode.ERROR_SUCCESS) + { + Debug.Assert(cbResult == sizeof(int)); } - } - if (errorCode == ErrorCode.ERROR_SUCCESS) - { - Debug.Assert(cbResult == sizeof(int)); + return errorCode; } - - return errorCode; } } } diff --git a/src/libraries/Common/src/Interop/Windows/NtDll/Interop.FILE_FULL_DIR_INFORMATION.cs b/src/libraries/Common/src/Interop/Windows/NtDll/Interop.FILE_FULL_DIR_INFORMATION.cs index 697c317376e24..ea1365e844e8c 100644 --- a/src/libraries/Common/src/Interop/Windows/NtDll/Interop.FILE_FULL_DIR_INFORMATION.cs +++ b/src/libraries/Common/src/Interop/Windows/NtDll/Interop.FILE_FULL_DIR_INFORMATION.cs @@ -15,7 +15,7 @@ internal partial class NtDll /// Equivalent to FILE_FULL_DIR_INFO structure. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public unsafe struct FILE_FULL_DIR_INFORMATION + public struct FILE_FULL_DIR_INFORMATION { /// /// Offset in bytes of the next entry, if any. @@ -54,7 +54,7 @@ public unsafe struct FILE_FULL_DIR_INFORMATION public uint EaSize; private char _fileName; - public ReadOnlySpan FileName { get { fixed (char* c = &_fileName) { return new ReadOnlySpan(c, (int)FileNameLength / sizeof(char)); } } } + public unsafe ReadOnlySpan FileName { get { fixed (char* c = &_fileName) { return new ReadOnlySpan(c, (int)FileNameLength / sizeof(char)); } } } /// /// Gets the next info pointer or null if there are no more. diff --git a/src/libraries/Common/src/Interop/Windows/NtDll/Interop.FILE_FULL_EA_INFORMATION.cs b/src/libraries/Common/src/Interop/Windows/NtDll/Interop.FILE_FULL_EA_INFORMATION.cs index 05b0335b988b9..539d9fd67dc98 100644 --- a/src/libraries/Common/src/Interop/Windows/NtDll/Interop.FILE_FULL_EA_INFORMATION.cs +++ b/src/libraries/Common/src/Interop/Windows/NtDll/Interop.FILE_FULL_EA_INFORMATION.cs @@ -13,7 +13,7 @@ internal partial class NtDll /// Provides extended attribute (EA) information. This structure is used primarily by network drivers. /// [StructLayoutAttribute(LayoutKind.Sequential)] - internal unsafe struct FILE_FULL_EA_INFORMATION + internal struct FILE_FULL_EA_INFORMATION { /// /// The offset of the next FILE_FULL_EA_INFORMATION-type entry. This member is zero if no other entries follow this one. diff --git a/src/libraries/Common/src/Interop/Windows/NtDll/Interop.RtlNtStatusToDosError.cs b/src/libraries/Common/src/Interop/Windows/NtDll/Interop.RtlNtStatusToDosError.cs index d3834cd20cab9..666a533a21900 100644 --- a/src/libraries/Common/src/Interop/Windows/NtDll/Interop.RtlNtStatusToDosError.cs +++ b/src/libraries/Common/src/Interop/Windows/NtDll/Interop.RtlNtStatusToDosError.cs @@ -10,7 +10,6 @@ internal partial class NtDll { // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680600(v=vs.85).aspx [DllImport(Libraries.NtDll, ExactSpelling = true)] - public static extern unsafe uint RtlNtStatusToDosError( - int Status); + public static extern uint RtlNtStatusToDosError(int Status); } } diff --git a/src/libraries/Common/src/Interop/Windows/Ole32/Interop.IStream.cs b/src/libraries/Common/src/Interop/Windows/Ole32/Interop.IStream.cs index 4687aa075040c..1b78ce6f4745a 100644 --- a/src/libraries/Common/src/Interop/Windows/Ole32/Interop.IStream.cs +++ b/src/libraries/Common/src/Interop/Windows/Ole32/Interop.IStream.cs @@ -18,21 +18,21 @@ internal static partial class Ole32 [ComImport, Guid("0000000C-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal unsafe interface IStream + internal interface IStream { // pcbRead is optional so it must be a pointer - void Read(byte* pv, uint cb, uint* pcbRead); + unsafe void Read(byte* pv, uint cb, uint* pcbRead); // pcbWritten is optional so it must be a pointer - void Write(byte* pv, uint cb, uint* pcbWritten); + unsafe void Write(byte* pv, uint cb, uint* pcbWritten); // SeekOrgin matches the native values, plibNewPosition is optional - void Seek(long dlibMove, SeekOrigin dwOrigin, ulong* plibNewPosition); + unsafe void Seek(long dlibMove, SeekOrigin dwOrigin, ulong* plibNewPosition); void SetSize(ulong libNewSize); // pcbRead and pcbWritten are optional - void CopyTo( + unsafe void CopyTo( IStream pstm, ulong cb, ulong* pcbRead, diff --git a/src/libraries/Common/src/Interop/Windows/PerfCounter/Interop.FormatFromRawValue.cs b/src/libraries/Common/src/Interop/Windows/PerfCounter/Interop.FormatFromRawValue.cs index f20fc3d329218..3402ed24d9ef6 100644 --- a/src/libraries/Common/src/Interop/Windows/PerfCounter/Interop.FormatFromRawValue.cs +++ b/src/libraries/Common/src/Interop/Windows/PerfCounter/Interop.FormatFromRawValue.cs @@ -8,7 +8,7 @@ internal partial class Interop internal partial class PerfCounter { [DllImport(Libraries.PerfCounter, CharSet = CharSet.Unicode)] - public static extern unsafe int FormatFromRawValue( + public static extern int FormatFromRawValue( uint dwCounterType, uint dwFormat, ref long pTimeBase, diff --git a/src/libraries/Common/src/Interop/Windows/PerfCounter/Interop.PerformanceData.cs b/src/libraries/Common/src/Interop/Windows/PerfCounter/Interop.PerformanceData.cs index cf6e20f9b149a..2fa286c648e75 100644 --- a/src/libraries/Common/src/Interop/Windows/PerfCounter/Interop.PerformanceData.cs +++ b/src/libraries/Common/src/Interop/Windows/PerfCounter/Interop.PerformanceData.cs @@ -10,7 +10,7 @@ internal static partial class Interop internal partial class PerfCounter { [DllImport(Libraries.Advapi32, ExactSpelling = true)] - internal static extern unsafe uint PerfStopProvider( + internal static extern uint PerfStopProvider( IntPtr hProvider ); @@ -54,7 +54,7 @@ internal struct PerfCounterSetInstanceStruct } [DllImport(Libraries.Advapi32, ExactSpelling = true)] - internal static extern unsafe uint PerfStartProvider( + internal static extern uint PerfStartProvider( ref Guid ProviderGuid, PERFLIBREQUEST ControlCallback, out SafePerfProviderHandle phProvider diff --git a/src/libraries/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.IntPtr.cs b/src/libraries/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.IntPtr.cs index 5d937acaf0391..64eb3eb02de53 100644 --- a/src/libraries/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.IntPtr.cs +++ b/src/libraries/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.IntPtr.cs @@ -8,9 +8,9 @@ namespace System.Net { - internal static unsafe partial class UnmanagedCertificateContext + internal static partial class UnmanagedCertificateContext { - internal static X509Certificate2Collection GetRemoteCertificatesFromStoreContext(IntPtr certContext) + internal static unsafe X509Certificate2Collection GetRemoteCertificatesFromStoreContext(IntPtr certContext) { X509Certificate2Collection result = new X509Certificate2Collection(); @@ -19,11 +19,7 @@ internal static X509Certificate2Collection GetRemoteCertificatesFromStoreContext return result; } - Interop.Crypt32.CERT_CONTEXT context; - unsafe - { - context = *(Interop.Crypt32.CERT_CONTEXT*)certContext; - } + Interop.Crypt32.CERT_CONTEXT context = *(Interop.Crypt32.CERT_CONTEXT*)certContext; if (context.hCertStore != IntPtr.Zero) { diff --git a/src/libraries/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs b/src/libraries/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs index cfac8ca347163..8a7857d5caccd 100644 --- a/src/libraries/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs +++ b/src/libraries/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs @@ -8,7 +8,7 @@ namespace System.Net { - internal static unsafe partial class UnmanagedCertificateContext + internal static partial class UnmanagedCertificateContext { internal static X509Certificate2Collection GetRemoteCertificatesFromStoreContext(SafeFreeCertContext certContext) { diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/Interop.SSPI.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/Interop.SSPI.cs index 04682754bc58e..396023fad2319 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/Interop.SSPI.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/Interop.SSPI.cs @@ -165,7 +165,7 @@ internal struct CERT_CHAIN_ELEMENT // schannel.h [StructLayout(LayoutKind.Sequential)] - internal unsafe struct SecPkgContext_IssuerListInfoEx + internal struct SecPkgContext_IssuerListInfoEx { public IntPtr aIssuers; public uint cIssuers; @@ -292,13 +292,13 @@ public enum TlsAlgorithmUsage } [StructLayout(LayoutKind.Sequential)] - internal unsafe struct SecBuffer + internal struct SecBuffer { public int cbBuffer; public SecurityBufferType BufferType; public IntPtr pvBuffer; - public static readonly int Size = sizeof(SecBuffer); + public static readonly unsafe int Size = sizeof(SecBuffer); } [StructLayout(LayoutKind.Sequential)] @@ -371,7 +371,7 @@ internal static extern unsafe int QueryContextAttributesW( [In] void* buffer); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] - internal static extern unsafe int SetContextAttributesW( + internal static extern int SetContextAttributesW( ref CredHandle contextHandle, [In] ContextAttribute attribute, [In] byte[] buffer, @@ -464,11 +464,11 @@ internal static extern unsafe int ApplyControlToken( ); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] - internal static extern unsafe SECURITY_STATUS SspiFreeAuthIdentity( + internal static extern SECURITY_STATUS SspiFreeAuthIdentity( [In] IntPtr authData); [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern unsafe SECURITY_STATUS SspiEncodeStringsAsAuthIdentity( + internal static extern SECURITY_STATUS SspiEncodeStringsAsAuthIdentity( [In] string userName, [In] string domainName, [In] string password, diff --git a/src/libraries/Common/src/Interop/Windows/WinSock/Interop.WSAStartup.cs b/src/libraries/Common/src/Interop/Windows/WinSock/Interop.WSAStartup.cs index 7f90a3ae79435..aec9156128381 100644 --- a/src/libraries/Common/src/Interop/Windows/WinSock/Interop.WSAStartup.cs +++ b/src/libraries/Common/src/Interop/Windows/WinSock/Interop.WSAStartup.cs @@ -46,7 +46,7 @@ static unsafe void Initialize() private static extern SocketError WSACleanup(); [StructLayout(LayoutKind.Sequential, Size = 408)] - private unsafe struct WSAData + private struct WSAData { // WSADATA is defined as follows: // diff --git a/src/libraries/Common/src/Interop/Windows/WinSock/SafeNativeOverlapped.cs b/src/libraries/Common/src/Interop/Windows/WinSock/SafeNativeOverlapped.cs index bf684547ac8ee..5a4a68a1d53ea 100644 --- a/src/libraries/Common/src/Interop/Windows/WinSock/SafeNativeOverlapped.cs +++ b/src/libraries/Common/src/Interop/Windows/WinSock/SafeNativeOverlapped.cs @@ -48,24 +48,21 @@ protected override bool ReleaseHandle() return true; } - private void FreeNativeOverlapped() + private unsafe void FreeNativeOverlapped() { // Do not call free during AppDomain shutdown, there may be an outstanding operation. // Overlapped will take care calling free when the native callback completes. IntPtr oldHandle = Interlocked.Exchange(ref handle, IntPtr.Zero); if (oldHandle != IntPtr.Zero && !Environment.HasShutdownStarted) { - unsafe - { - Debug.Assert(OperatingSystem.IsWindows()); - Debug.Assert(_socketHandle != null, "_socketHandle is null."); + Debug.Assert(OperatingSystem.IsWindows()); + Debug.Assert(_socketHandle != null, "_socketHandle is null."); - ThreadPoolBoundHandle? boundHandle = _socketHandle.IOCPBoundHandle; - Debug.Assert(boundHandle != null, "SafeNativeOverlapped::FreeNativeOverlapped - boundHandle is null"); + ThreadPoolBoundHandle? boundHandle = _socketHandle.IOCPBoundHandle; + Debug.Assert(boundHandle != null, "SafeNativeOverlapped::FreeNativeOverlapped - boundHandle is null"); - // FreeNativeOverlapped will be called even if boundHandle was previously disposed. - boundHandle?.FreeNativeOverlapped((NativeOverlapped*)oldHandle); - } + // FreeNativeOverlapped will be called even if boundHandle was previously disposed. + boundHandle?.FreeNativeOverlapped((NativeOverlapped*)oldHandle); } } } diff --git a/src/libraries/Common/src/System/Globalization/FormatProvider.Number.cs b/src/libraries/Common/src/System/Globalization/FormatProvider.Number.cs index 817756627f93d..c787e2983aed1 100644 --- a/src/libraries/Common/src/System/Globalization/FormatProvider.Number.cs +++ b/src/libraries/Common/src/System/Globalization/FormatProvider.Number.cs @@ -640,7 +640,7 @@ internal static unsafe void Int32ToDecChars(char* buffer, ref int index, uint va } } - internal static unsafe char ParseFormatSpecifier(ReadOnlySpan format, out int digits) + internal static char ParseFormatSpecifier(ReadOnlySpan format, out int digits) { char c = default; if (format.Length > 0) diff --git a/src/libraries/Common/src/System/Memory/FixedBufferExtensions.cs b/src/libraries/Common/src/System/Memory/FixedBufferExtensions.cs index 7db8d2e2f3768..3d2a3199b53ee 100644 --- a/src/libraries/Common/src/System/Memory/FixedBufferExtensions.cs +++ b/src/libraries/Common/src/System/Memory/FixedBufferExtensions.cs @@ -21,7 +21,7 @@ internal static unsafe string GetStringFromFixedBuffer(this ReadOnlySpan s /// /// Gets the null-terminated string length of the given span. /// - internal static unsafe int GetFixedBufferStringLength(this ReadOnlySpan span) + internal static int GetFixedBufferStringLength(this ReadOnlySpan span) { int length = span.IndexOf('\0'); return length < 0 ? span.Length : length; @@ -31,7 +31,7 @@ internal static unsafe int GetFixedBufferStringLength(this ReadOnlySpan sp /// Returns true if the given string equals the given span. /// The span's logical length is to the first null if present. /// - internal static unsafe bool FixedBufferEqualsString(this ReadOnlySpan span, string value) + internal static bool FixedBufferEqualsString(this ReadOnlySpan span, string value) { if (value == null || value.Length > span.Length) return false; diff --git a/src/libraries/Common/src/System/Net/Http/aspnetcore/NetEventSource.Common.cs b/src/libraries/Common/src/System/Net/Http/aspnetcore/NetEventSource.Common.cs index c7c062c0750e7..1d81a6b7fd066 100644 --- a/src/libraries/Common/src/System/Net/Http/aspnetcore/NetEventSource.Common.cs +++ b/src/libraries/Common/src/System/Net/Http/aspnetcore/NetEventSource.Common.cs @@ -350,7 +350,7 @@ public static unsafe void DumpBuffer(object? thisOrContextObject, IntPtr bufferP } [Event(DumpArrayEventId, Level = EventLevel.Verbose, Keywords = Keywords.Debug)] - private unsafe void DumpBuffer(string thisOrContextObject, string? memberName, byte[] buffer) => + private void DumpBuffer(string thisOrContextObject, string? memberName, byte[] buffer) => WriteEvent(DumpArrayEventId, thisOrContextObject, memberName ?? MissingMember, buffer); #endregion diff --git a/src/libraries/Common/src/System/Net/IPv4AddressHelper.Common.cs b/src/libraries/Common/src/System/Net/IPv4AddressHelper.Common.cs index a02d6e8c66bc3..cbcb01c4c105c 100644 --- a/src/libraries/Common/src/System/Net/IPv4AddressHelper.Common.cs +++ b/src/libraries/Common/src/System/Net/IPv4AddressHelper.Common.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Buffers.Binary; + namespace System { internal static partial class IPv4AddressHelper @@ -14,11 +16,25 @@ internal static partial class IPv4AddressHelper private const int NumberOfLabels = 4; // Only called from the IPv6Helper, only parse the canonical format - internal static unsafe int ParseHostNumber(ReadOnlySpan str, int start, int end) + internal static int ParseHostNumber(ReadOnlySpan str, int start, int end) { - byte* numbers = stackalloc byte[NumberOfLabels]; - ParseCanonical(str, numbers, start, end); - return (numbers[0] << 24) + (numbers[1] << 16) + (numbers[2] << 8) + numbers[3]; + Span numbers = stackalloc byte[NumberOfLabels]; + + for (int i = 0; i < numbers.Length; ++i) + { + int b = 0; + char ch; + + for (; (start < end) && (ch = str[start]) != '.' && ch != ':'; ++start) + { + b = (b * 10) + ch - '0'; + } + + numbers[i] = (byte)b; + ++start; + } + + return BinaryPrimitives.ReadInt32BigEndian(numbers); } // @@ -76,27 +92,6 @@ internal static unsafe bool IsValid(char* name, int start, ref int end, bool all } } - // Assumes: - // has been validated and contains only decimal digits in groups - // of 8-bit numbers and the characters '.' - // Address may terminate with ':' or with the end of the string - // - private static unsafe bool ParseCanonical(ReadOnlySpan name, byte* numbers, int start, int end) - { - for (int i = 0; i < NumberOfLabels; ++i) - { - int b = 0; - char ch; - for (; (start < end) && (ch = name[start]) != '.' && ch != ':'; ++start) - { - b = (b * 10) + ch - '0'; - } - numbers[i] = (byte)b; - ++start; - } - return numbers[0] == 127; - } - // // IsValidCanonical // diff --git a/src/libraries/Common/src/System/Net/IPv6AddressHelper.Common.cs b/src/libraries/Common/src/System/Net/IPv6AddressHelper.Common.cs index b9e4a0b917116..a4b0ed05bbe4d 100644 --- a/src/libraries/Common/src/System/Net/IPv6AddressHelper.Common.cs +++ b/src/libraries/Common/src/System/Net/IPv6AddressHelper.Common.cs @@ -13,8 +13,7 @@ internal static partial class IPv6AddressHelper // RFC 5952 Section 4.2.3 // Longest consecutive sequence of zero segments, minimum 2. // On equal, first sequence wins. <-1, -1> for no compression. - internal static unsafe (int longestSequenceStart, int longestSequenceLength) FindCompressionRange( - ReadOnlySpan numbers) + internal static (int longestSequenceStart, int longestSequenceLength) FindCompressionRange(ReadOnlySpan numbers) { int longestSequenceLength = 0, longestSequenceStart = -1, currentSequenceLength = 0; @@ -42,7 +41,7 @@ internal static unsafe (int longestSequenceStart, int longestSequenceLength) Fin // Returns true if the IPv6 address should be formatted with an embedded IPv4 address: // ::192.168.1.1 - internal static unsafe bool ShouldHaveIpv4Embedded(ReadOnlySpan numbers) + internal static bool ShouldHaveIpv4Embedded(ReadOnlySpan numbers) { // 0:0 : 0:0 : x:x : x.x.x.x if (numbers[0] == 0 && numbers[1] == 0 && numbers[2] == 0 && numbers[3] == 0 && numbers[6] != 0) diff --git a/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs b/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs index f55fedcf04ae5..3075eb10c38f9 100644 --- a/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs +++ b/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs @@ -287,7 +287,7 @@ public static unsafe void DumpBuffer(object? thisOrContextObject, IntPtr bufferP } [Event(DumpArrayEventId, Level = EventLevel.Verbose, Keywords = Keywords.Debug)] - private unsafe void DumpBuffer(string thisOrContextObject, string? memberName, byte[] buffer) => + private void DumpBuffer(string thisOrContextObject, string? memberName, byte[] buffer) => WriteEvent(DumpArrayEventId, thisOrContextObject, memberName ?? MissingMember, buffer); #endregion diff --git a/src/libraries/Common/src/System/Net/NetworkInformation/UnixCommandLinePing.cs b/src/libraries/Common/src/System/Net/NetworkInformation/UnixCommandLinePing.cs index 98db97f3106e8..cd4c492467e8b 100644 --- a/src/libraries/Common/src/System/Net/NetworkInformation/UnixCommandLinePing.cs +++ b/src/libraries/Common/src/System/Net/NetworkInformation/UnixCommandLinePing.cs @@ -37,7 +37,7 @@ internal static class UnixCommandLinePing } // Check if found ping is symlink to busybox like alpine /bin/ping -> /bin/busybox - private static unsafe bool IsBusyboxPing(string? pingBinary) + private static bool IsBusyboxPing(string? pingBinary) { if (pingBinary != null) { diff --git a/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs b/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs index 5e095ce96fd8e..d7d9d6cf03d5a 100644 --- a/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs +++ b/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs @@ -32,7 +32,7 @@ internal static SafeFreeCredentials AcquireDefaultCredential(string package, boo (isServer ? Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND : Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND)); } - internal static unsafe SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential) + internal static SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential) { SafeSspiAuthDataHandle? authData = null; try diff --git a/src/libraries/Common/src/System/Net/SocketAddressPal.Windows.cs b/src/libraries/Common/src/System/Net/SocketAddressPal.Windows.cs index bc54cea438af8..cfa97d7a0e7ba 100644 --- a/src/libraries/Common/src/System/Net/SocketAddressPal.Windows.cs +++ b/src/libraries/Common/src/System/Net/SocketAddressPal.Windows.cs @@ -10,12 +10,12 @@ internal static class SocketAddressPal public const int IPv6AddressSize = 28; public const int IPv4AddressSize = 16; - public static unsafe AddressFamily GetAddressFamily(ReadOnlySpan buffer) + public static AddressFamily GetAddressFamily(ReadOnlySpan buffer) { return (AddressFamily)BitConverter.ToInt16(buffer); } - public static unsafe void SetAddressFamily(byte[] buffer, AddressFamily family) + public static void SetAddressFamily(byte[] buffer, AddressFamily family) { if ((int)(family) > ushort.MaxValue) { @@ -34,28 +34,17 @@ public static unsafe void SetAddressFamily(byte[] buffer, AddressFamily family) #endif } - public static unsafe ushort GetPort(ReadOnlySpan buffer) - { - return buffer.NetworkBytesToHostUInt16(2); - } + public static ushort GetPort(ReadOnlySpan buffer) => buffer.NetworkBytesToHostUInt16(2); - public static unsafe void SetPort(byte[] buffer, ushort port) - { - port.HostToNetworkBytes(buffer, 2); - } + public static void SetPort(byte[] buffer, ushort port) => port.HostToNetworkBytes(buffer, 2); - public static unsafe uint GetIPv4Address(ReadOnlySpan buffer) - { - unchecked - { - return (uint)((buffer[4] & 0x000000FF) | - (buffer[5] << 8 & 0x0000FF00) | - (buffer[6] << 16 & 0x00FF0000) | - (buffer[7] << 24)); - } - } + public static uint GetIPv4Address(ReadOnlySpan buffer) => + (uint)((buffer[4] & 0x000000FF) | + (buffer[5] << 8 & 0x0000FF00) | + (buffer[6] << 16 & 0x00FF0000) | + (buffer[7] << 24)); - public static unsafe void GetIPv6Address(ReadOnlySpan buffer, Span address, out uint scope) + public static void GetIPv6Address(ReadOnlySpan buffer, Span address, out uint scope) { for (int i = 0; i < address.Length; i++) { @@ -69,7 +58,7 @@ public static unsafe void GetIPv6Address(ReadOnlySpan buffer, Span a (buffer[24]))); } - public static unsafe void SetIPv4Address(byte[] buffer, uint address) + public static void SetIPv4Address(byte[] buffer, uint address) { // IPv4 Address serialization buffer[4] = unchecked((byte)(address)); @@ -78,7 +67,7 @@ public static unsafe void SetIPv4Address(byte[] buffer, uint address) buffer[7] = unchecked((byte)(address >> 24)); } - public static unsafe void SetIPv6Address(byte[] buffer, Span address, uint scope) + public static void SetIPv6Address(byte[] buffer, Span address, uint scope) { // No handling for Flow Information buffer[4] = (byte)0; @@ -86,14 +75,11 @@ public static unsafe void SetIPv6Address(byte[] buffer, Span address, uint buffer[6] = (byte)0; buffer[7] = (byte)0; - unchecked - { - // Scope serialization - buffer[24] = (byte)scope; - buffer[25] = (byte)(scope >> 8); - buffer[26] = (byte)(scope >> 16); - buffer[27] = (byte)(scope >> 24); - } + // Scope serialization + buffer[24] = (byte)scope; + buffer[25] = (byte)(scope >> 8); + buffer[26] = (byte)(scope >> 16); + buffer[27] = (byte)(scope >> 24); // Address serialization for (int i = 0; i < address.Length; i++) diff --git a/src/libraries/Common/src/System/Net/WebHeaderEncoding.cs b/src/libraries/Common/src/System/Net/WebHeaderEncoding.cs index 2115d60df39e9..b654e07eb8437 100644 --- a/src/libraries/Common/src/System/Net/WebHeaderEncoding.cs +++ b/src/libraries/Common/src/System/Net/WebHeaderEncoding.cs @@ -53,16 +53,15 @@ internal static unsafe string GetString(byte[] bytes, int byteIndex, int byteCou }); } - internal static int GetByteCount(string myString) - { - return myString.Length; - } + internal static int GetByteCount(string myString) => myString.Length; + internal static unsafe void GetBytes(string myString, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (myString.Length == 0) { return; } + fixed (byte* bufferPointer = bytes) { byte* newBufferPointer = bufferPointer + byteIndex; @@ -73,7 +72,7 @@ internal static unsafe void GetBytes(string myString, int charIndex, int charCou } } } - internal static unsafe byte[] GetBytes(string myString) + internal static byte[] GetBytes(string myString) { byte[] bytes = new byte[myString.Length]; if (myString.Length != 0) diff --git a/src/libraries/Common/src/System/Net/WebSockets/ManagedWebSocket.cs b/src/libraries/Common/src/System/Net/WebSockets/ManagedWebSocket.cs index 38a83c25d151c..7ed7a15994062 100644 --- a/src/libraries/Common/src/System/Net/WebSockets/ManagedWebSocket.cs +++ b/src/libraries/Common/src/System/Net/WebSockets/ManagedWebSocket.cs @@ -1287,7 +1287,7 @@ private void ReleaseSendBuffer() } } - private static unsafe int CombineMaskBytes(Span buffer, int maskOffset) => + private static int CombineMaskBytes(Span buffer, int maskOffset) => BitConverter.ToInt32(buffer.Slice(maskOffset)); /// Applies a mask to a portion of a byte array. diff --git a/src/libraries/Common/src/System/Security/Cryptography/DSACng.ImportExport.cs b/src/libraries/Common/src/System/Security/Cryptography/DSACng.ImportExport.cs index 61ec4f336c606..f60e09560c055 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/DSACng.ImportExport.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/DSACng.ImportExport.cs @@ -169,7 +169,7 @@ public override bool TryExportEncryptedPkcs8PrivateKey( out bytesWritten); } - private static void GenerateV1DsaBlob(out byte[] blob, DSAParameters parameters, int cbKey, bool includePrivate) + private static unsafe void GenerateV1DsaBlob(out byte[] blob, DSAParameters parameters, int cbKey, bool includePrivate) { // We need to build a key blob structured as follows: // @@ -180,68 +180,65 @@ private static void GenerateV1DsaBlob(out byte[] blob, DSAParameters parameters, // -- Private only -- // byte[Sha1HashOutputSize] X - unsafe - { - int blobSize = - sizeof(BCRYPT_DSA_KEY_BLOB) + - cbKey + - cbKey + - cbKey; - - if (includePrivate) - { - blobSize += Sha1HashOutputSize; - } + int blobSize = + sizeof(BCRYPT_DSA_KEY_BLOB) + + cbKey + + cbKey + + cbKey; - blob = new byte[blobSize]; - fixed (byte* pDsaBlob = &blob[0]) - { - // Build the header - BCRYPT_DSA_KEY_BLOB* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB*)pDsaBlob; + if (includePrivate) + { + blobSize += Sha1HashOutputSize; + } - pBcryptBlob->Magic = includePrivate ? KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC : KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC; - pBcryptBlob->cbKey = cbKey; + blob = new byte[blobSize]; + fixed (byte* pDsaBlob = &blob[0]) + { + // Build the header + BCRYPT_DSA_KEY_BLOB* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB*)pDsaBlob; - int offset = sizeof(KeyBlobMagicNumber) + sizeof(int); // skip Magic and cbKey + pBcryptBlob->Magic = includePrivate ? KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC : KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC; + pBcryptBlob->cbKey = cbKey; - if (parameters.Seed != null) - { - // The Seed length is hardcoded into BCRYPT_DSA_KEY_BLOB, so check it now we can give a nicer error message. - if (parameters.Seed.Length != Sha1HashOutputSize) - throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_SeedRestriction_ShortKey); + int offset = sizeof(KeyBlobMagicNumber) + sizeof(int); // skip Magic and cbKey - Interop.BCrypt.EmitBigEndian(blob, ref offset, parameters.Counter); - Interop.BCrypt.Emit(blob, ref offset, parameters.Seed); - } - else - { - // If Seed is not present, back fill both counter and seed with 0xff. Do not use parameters.Counter as CNG is more strict than CAPI and will reject - // anything other than 0xffffffff. That could complicate efforts to switch usage of DSACryptoServiceProvider to DSACng. - Interop.BCrypt.EmitByte(blob, ref offset, 0xff, Sha1HashOutputSize + sizeof(int)); - } + if (parameters.Seed != null) + { + // The Seed length is hardcoded into BCRYPT_DSA_KEY_BLOB, so check it now we can give a nicer error message. + if (parameters.Seed.Length != Sha1HashOutputSize) + throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_SeedRestriction_ShortKey); - // The Q length is hardcoded into BCRYPT_DSA_KEY_BLOB, so check it now we can give a nicer error message. - if (parameters.Q!.Length != Sha1HashOutputSize) - throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_QRestriction_ShortKey); + Interop.BCrypt.EmitBigEndian(blob, ref offset, parameters.Counter); + Interop.BCrypt.Emit(blob, ref offset, parameters.Seed); + } + else + { + // If Seed is not present, back fill both counter and seed with 0xff. Do not use parameters.Counter as CNG is more strict than CAPI and will reject + // anything other than 0xffffffff. That could complicate efforts to switch usage of DSACryptoServiceProvider to DSACng. + Interop.BCrypt.EmitByte(blob, ref offset, 0xff, Sha1HashOutputSize + sizeof(int)); + } - Interop.BCrypt.Emit(blob, ref offset, parameters.Q); + // The Q length is hardcoded into BCRYPT_DSA_KEY_BLOB, so check it now we can give a nicer error message. + if (parameters.Q!.Length != Sha1HashOutputSize) + throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_QRestriction_ShortKey); - Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB)}"); + Interop.BCrypt.Emit(blob, ref offset, parameters.Q); - Interop.BCrypt.Emit(blob, ref offset, parameters.P!); - Interop.BCrypt.Emit(blob, ref offset, parameters.G!); - Interop.BCrypt.Emit(blob, ref offset, parameters.Y!); - if (includePrivate) - { - Interop.BCrypt.Emit(blob, ref offset, parameters.X!); - } + Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB)}"); - Debug.Assert(offset == blobSize, $"Expected offset = blobSize, got {offset} != {blobSize}"); + Interop.BCrypt.Emit(blob, ref offset, parameters.P!); + Interop.BCrypt.Emit(blob, ref offset, parameters.G!); + Interop.BCrypt.Emit(blob, ref offset, parameters.Y!); + if (includePrivate) + { + Interop.BCrypt.Emit(blob, ref offset, parameters.X!); } + + Debug.Assert(offset == blobSize, $"Expected offset = blobSize, got {offset} != {blobSize}"); } } - private static void GenerateV2DsaBlob(out byte[] blob, DSAParameters parameters, int cbKey, bool includePrivateParameters) + private static unsafe void GenerateV2DsaBlob(out byte[] blob, DSAParameters parameters, int cbKey, bool includePrivateParameters) { // We need to build a key blob structured as follows: // BCRYPT_DSA_KEY_BLOB_V2 header @@ -253,76 +250,73 @@ private static void GenerateV2DsaBlob(out byte[] blob, DSAParameters parameters, // -- Private only -- // byte[cbGroupSize] X - unsafe + int blobSize = + sizeof(BCRYPT_DSA_KEY_BLOB_V2) + + (parameters.Seed == null ? parameters.Q!.Length : parameters.Seed.Length) + // Use Q size if Seed is not present + parameters.Q!.Length + + parameters.P!.Length + + parameters.G!.Length + + parameters.Y!.Length + + (includePrivateParameters ? parameters.X!.Length : 0); + + blob = new byte[blobSize]; + fixed (byte* pDsaBlob = &blob[0]) { - int blobSize = - sizeof(BCRYPT_DSA_KEY_BLOB_V2) + - (parameters.Seed == null ? parameters.Q!.Length : parameters.Seed.Length) + // Use Q size if Seed is not present - parameters.Q!.Length + - parameters.P!.Length + - parameters.G!.Length + - parameters.Y!.Length + - (includePrivateParameters ? parameters.X!.Length : 0); - - blob = new byte[blobSize]; - fixed (byte* pDsaBlob = &blob[0]) + // Build the header + BCRYPT_DSA_KEY_BLOB_V2* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB_V2*)pDsaBlob; + + pBcryptBlob->Magic = includePrivateParameters ? KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2 : KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2; + pBcryptBlob->cbKey = cbKey; + + // For some reason, Windows bakes the hash algorithm into the key itself. Furthermore, it demands that the Q length match the + // length of the named hash algorithm's output - otherwise, the Import fails. So we have to give it the hash algorithm that matches + // the Q length - and if there is no matching hash algorithm, we throw up our hands and throw a PlatformNotSupported. + // + // Note that this has no bearing on the hash algorithm you pass to SignData(). The class library (not Windows) hashes that according + // to the hash algorithm passed to SignData() and presents the hash result to NCryptSignHash(), truncating the hash to the Q length + // if necessary (and as demanded by the NIST spec.) Windows will be no wiser and we'll get the result we want. + pBcryptBlob->hashAlgorithm = parameters.Q.Length switch { - // Build the header - BCRYPT_DSA_KEY_BLOB_V2* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB_V2*)pDsaBlob; - - pBcryptBlob->Magic = includePrivateParameters ? KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2 : KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2; - pBcryptBlob->cbKey = cbKey; - - // For some reason, Windows bakes the hash algorithm into the key itself. Furthermore, it demands that the Q length match the - // length of the named hash algorithm's output - otherwise, the Import fails. So we have to give it the hash algorithm that matches - // the Q length - and if there is no matching hash algorithm, we throw up our hands and throw a PlatformNotSupported. - // - // Note that this has no bearing on the hash algorithm you pass to SignData(). The class library (not Windows) hashes that according - // to the hash algorithm passed to SignData() and presents the hash result to NCryptSignHash(), truncating the hash to the Q length - // if necessary (and as demanded by the NIST spec.) Windows will be no wiser and we'll get the result we want. - pBcryptBlob->hashAlgorithm = parameters.Q.Length switch - { - Sha1HashOutputSize => HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA1, - Sha256HashOutputSize => HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA256, - Sha512HashOutputSize => HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA512, - _ => throw new PlatformNotSupportedException(SR.Cryptography_InvalidDsaParameters_QRestriction_LargeKey), - }; - pBcryptBlob->standardVersion = DSAFIPSVERSION_ENUM.DSA_FIPS186_3; + Sha1HashOutputSize => HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA1, + Sha256HashOutputSize => HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA256, + Sha512HashOutputSize => HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA512, + _ => throw new PlatformNotSupportedException(SR.Cryptography_InvalidDsaParameters_QRestriction_LargeKey), + }; + pBcryptBlob->standardVersion = DSAFIPSVERSION_ENUM.DSA_FIPS186_3; - int offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2) - 4; //skip to Count[4] + int offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2) - 4; //skip to Count[4] - if (parameters.Seed != null) - { - Interop.BCrypt.EmitBigEndian(blob, ref offset, parameters.Counter); - Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB_V2), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB_V2)}"); - pBcryptBlob->cbSeedLength = parameters.Seed.Length; - pBcryptBlob->cbGroupSize = parameters.Q.Length; - Interop.BCrypt.Emit(blob, ref offset, parameters.Seed); - } - else - { - // If Seed is not present, back fill both counter and seed with 0xff. Do not use parameters.Counter as CNG is more strict than CAPI and will reject - // anything other than 0xffffffff. That could complicate efforts to switch usage of DSACryptoServiceProvider to DSACng. - Interop.BCrypt.EmitByte(blob, ref offset, 0xff, sizeof(int)); - Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB_V2), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB_V2)}"); - int defaultSeedLength = parameters.Q.Length; - pBcryptBlob->cbSeedLength = defaultSeedLength; - pBcryptBlob->cbGroupSize = parameters.Q.Length; - Interop.BCrypt.EmitByte(blob, ref offset, 0xff, defaultSeedLength); - } - - Interop.BCrypt.Emit(blob, ref offset, parameters.Q); - Interop.BCrypt.Emit(blob, ref offset, parameters.P); - Interop.BCrypt.Emit(blob, ref offset, parameters.G); - Interop.BCrypt.Emit(blob, ref offset, parameters.Y); + if (parameters.Seed != null) + { + Interop.BCrypt.EmitBigEndian(blob, ref offset, parameters.Counter); + Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB_V2), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB_V2)}"); + pBcryptBlob->cbSeedLength = parameters.Seed.Length; + pBcryptBlob->cbGroupSize = parameters.Q.Length; + Interop.BCrypt.Emit(blob, ref offset, parameters.Seed); + } + else + { + // If Seed is not present, back fill both counter and seed with 0xff. Do not use parameters.Counter as CNG is more strict than CAPI and will reject + // anything other than 0xffffffff. That could complicate efforts to switch usage of DSACryptoServiceProvider to DSACng. + Interop.BCrypt.EmitByte(blob, ref offset, 0xff, sizeof(int)); + Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB_V2), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB_V2)}"); + int defaultSeedLength = parameters.Q.Length; + pBcryptBlob->cbSeedLength = defaultSeedLength; + pBcryptBlob->cbGroupSize = parameters.Q.Length; + Interop.BCrypt.EmitByte(blob, ref offset, 0xff, defaultSeedLength); + } - if (includePrivateParameters) - { - Interop.BCrypt.Emit(blob, ref offset, parameters.X!); - } + Interop.BCrypt.Emit(blob, ref offset, parameters.Q); + Interop.BCrypt.Emit(blob, ref offset, parameters.P); + Interop.BCrypt.Emit(blob, ref offset, parameters.G); + Interop.BCrypt.Emit(blob, ref offset, parameters.Y); - Debug.Assert(offset == blobSize, $"Expected offset = blobSize, got {offset} != {blobSize}"); + if (includePrivateParameters) + { + Interop.BCrypt.Emit(blob, ref offset, parameters.X!); } + + Debug.Assert(offset == blobSize, $"Expected offset = blobSize, got {offset} != {blobSize}"); } } diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECCng.ImportExport.cs b/src/libraries/Common/src/System/Security/Cryptography/ECCng.ImportExport.cs index d26b894234a00..5103363c3d323 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECCng.ImportExport.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECCng.ImportExport.cs @@ -262,64 +262,61 @@ internal static void ExportPrimeCurveParameters(ref ECParameters ecParams, byte[ } } - internal static byte[] GetPrimeCurveParameterBlob(ref ECCurve curve) + internal static unsafe byte[] GetPrimeCurveParameterBlob(ref ECCurve curve) { - unsafe - { - // We need to build a key blob structured as follows: - // BCRYPT_ECC_PARAMETER_HEADER header - // byte[cbFieldLength] P - // byte[cbFieldLength] A - // byte[cbFieldLength] B - // byte[cbFieldLength] G.X - // byte[cbFieldLength] G.Y - // byte[cbSubgroupOrder] Order (n) - // byte[cbCofactor] Cofactor (h) - // byte[cbSeed] Seed - - int blobSize = sizeof(BCRYPT_ECC_PARAMETER_HEADER) + - curve.Prime!.Length + - curve.A!.Length + - curve.B!.Length + - curve.G.X!.Length + - curve.G.Y!.Length + - curve.Order!.Length + - curve.Cofactor!.Length + - (curve.Seed == null ? 0 : curve.Seed.Length); + // We need to build a key blob structured as follows: + // BCRYPT_ECC_PARAMETER_HEADER header + // byte[cbFieldLength] P + // byte[cbFieldLength] A + // byte[cbFieldLength] B + // byte[cbFieldLength] G.X + // byte[cbFieldLength] G.Y + // byte[cbSubgroupOrder] Order (n) + // byte[cbCofactor] Cofactor (h) + // byte[cbSeed] Seed - byte[] blob = new byte[blobSize]; - fixed (byte* pBlob = &blob[0]) + int blobSize = sizeof(BCRYPT_ECC_PARAMETER_HEADER) + + curve.Prime!.Length + + curve.A!.Length + + curve.B!.Length + + curve.G.X!.Length + + curve.G.Y!.Length + + curve.Order!.Length + + curve.Cofactor!.Length + + (curve.Seed == null ? 0 : curve.Seed.Length); + + byte[] blob = new byte[blobSize]; + fixed (byte* pBlob = &blob[0]) + { + // Build the header + BCRYPT_ECC_PARAMETER_HEADER* pBcryptBlob = (BCRYPT_ECC_PARAMETER_HEADER*)pBlob; + pBcryptBlob->Version = Interop.BCrypt.BCRYPT_ECC_PARAMETER_HEADER_V1; + pBcryptBlob->cbCofactor = curve.Cofactor.Length; + pBcryptBlob->cbFieldLength = curve.A.Length; // P, A, B, X, Y have the same length + pBcryptBlob->cbSeed = curve.Seed == null ? 0 : curve.Seed.Length; + pBcryptBlob->cbSubgroupOrder = curve.Order.Length; + pBcryptBlob->CurveGenerationAlgId = ECCng.GetHashAlgorithmId(curve.Hash); + pBcryptBlob->CurveType = ECCng.ConvertToCurveTypeEnum(curve.CurveType); + + // Emit the blob + int offset = sizeof(BCRYPT_ECC_PARAMETER_HEADER); + Interop.BCrypt.Emit(blob, ref offset, curve.Prime); + Interop.BCrypt.Emit(blob, ref offset, curve.A); + Interop.BCrypt.Emit(blob, ref offset, curve.B); + Interop.BCrypt.Emit(blob, ref offset, curve.G.X); + Interop.BCrypt.Emit(blob, ref offset, curve.G.Y); + Interop.BCrypt.Emit(blob, ref offset, curve.Order); + Interop.BCrypt.Emit(blob, ref offset, curve.Cofactor); + if (curve.Seed != null) { - // Build the header - BCRYPT_ECC_PARAMETER_HEADER* pBcryptBlob = (BCRYPT_ECC_PARAMETER_HEADER*)pBlob; - pBcryptBlob->Version = Interop.BCrypt.BCRYPT_ECC_PARAMETER_HEADER_V1; - pBcryptBlob->cbCofactor = curve.Cofactor.Length; - pBcryptBlob->cbFieldLength = curve.A.Length; // P, A, B, X, Y have the same length - pBcryptBlob->cbSeed = curve.Seed == null ? 0 : curve.Seed.Length; - pBcryptBlob->cbSubgroupOrder = curve.Order.Length; - pBcryptBlob->CurveGenerationAlgId = ECCng.GetHashAlgorithmId(curve.Hash); - pBcryptBlob->CurveType = ECCng.ConvertToCurveTypeEnum(curve.CurveType); - - // Emit the blob - int offset = sizeof(BCRYPT_ECC_PARAMETER_HEADER); - Interop.BCrypt.Emit(blob, ref offset, curve.Prime); - Interop.BCrypt.Emit(blob, ref offset, curve.A); - Interop.BCrypt.Emit(blob, ref offset, curve.B); - Interop.BCrypt.Emit(blob, ref offset, curve.G.X); - Interop.BCrypt.Emit(blob, ref offset, curve.G.Y); - Interop.BCrypt.Emit(blob, ref offset, curve.Order); - Interop.BCrypt.Emit(blob, ref offset, curve.Cofactor); - if (curve.Seed != null) - { - Interop.BCrypt.Emit(blob, ref offset, curve.Seed); - } - - // We better have computed the right allocation size above! - Debug.Assert(offset == blobSize, "offset == blobSize"); + Interop.BCrypt.Emit(blob, ref offset, curve.Seed); } - return blob; + // We better have computed the right allocation size above! + Debug.Assert(offset == blobSize, "offset == blobSize"); } + + return blob; } /// diff --git a/src/libraries/Common/src/System/Security/Cryptography/KeyFormatHelper.cs b/src/libraries/Common/src/System/Security/Cryptography/KeyFormatHelper.cs index 8caddc96624c8..11f8ec0fa9759 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/KeyFormatHelper.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/KeyFormatHelper.cs @@ -347,7 +347,7 @@ internal static AsnWriter WritePkcs8( return writer; } - internal static unsafe AsnWriter WriteEncryptedPkcs8( + internal static AsnWriter WriteEncryptedPkcs8( ReadOnlySpan password, AsnWriter pkcs8Writer, PbeParameters pbeParameters) @@ -371,7 +371,7 @@ internal static AsnWriter WriteEncryptedPkcs8( pbeParameters); } - private static unsafe AsnWriter WriteEncryptedPkcs8( + private static AsnWriter WriteEncryptedPkcs8( ReadOnlySpan password, ReadOnlySpan passwordBytes, AsnWriter pkcs8Writer, diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs b/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs index cb2b302f9a206..ace52b302c552 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs @@ -21,11 +21,11 @@ public sealed partial class RSACng : RSA private const int StatusUnsuccessfulRetryCount = 1; /// Encrypts data using the public key. - public override unsafe byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) => + public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) => EncryptOrDecrypt(data, padding, encrypt: true); /// Decrypts data using the private key. - public override unsafe byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) => + public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) => EncryptOrDecrypt(data, padding, encrypt: false); /// Encrypts data using the public key. diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSACng.ImportExport.cs b/src/libraries/Common/src/System/Security/Cryptography/RSACng.ImportExport.cs index b428fa2a62739..e5946db307e7b 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSACng.ImportExport.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSACng.ImportExport.cs @@ -33,114 +33,111 @@ public sealed partial class RSACng : RSA /// if is not a valid RSA key or if is a full key pair and the default KSP is used. /// - public override void ImportParameters(RSAParameters parameters) + public override unsafe void ImportParameters(RSAParameters parameters) { - unsafe + if (parameters.Exponent == null || parameters.Modulus == null) + throw new CryptographicException(SR.Cryptography_InvalidRsaParameters); + + bool includePrivate; + if (parameters.D == null) { - if (parameters.Exponent == null || parameters.Modulus == null) - throw new CryptographicException(SR.Cryptography_InvalidRsaParameters); + includePrivate = false; - bool includePrivate; - if (parameters.D == null) + if (parameters.P != null || + parameters.DP != null || + parameters.Q != null || + parameters.DQ != null || + parameters.InverseQ != null) { - includePrivate = false; - - if (parameters.P != null || - parameters.DP != null || - parameters.Q != null || - parameters.DQ != null || - parameters.InverseQ != null) - { - throw new CryptographicException(SR.Cryptography_InvalidRsaParameters); - } + throw new CryptographicException(SR.Cryptography_InvalidRsaParameters); } - else - { - includePrivate = true; - - if (parameters.P == null || - parameters.DP == null || - parameters.Q == null || - parameters.DQ == null || - parameters.InverseQ == null) - { - throw new CryptographicException(SR.Cryptography_InvalidRsaParameters); - } + } + else + { + includePrivate = true; - // Half, rounded up. - int halfModulusLength = (parameters.Modulus.Length + 1) / 2; - - // The same checks are done by RSACryptoServiceProvider on import (when building the key blob) - // Historically RSACng let CNG handle this (reporting NTE_NOT_SUPPORTED), but on RS1 CNG let the - // import succeed, then on private key use (e.g. signing) it would report NTE_INVALID_PARAMETER. - // - // Doing the check here prevents the state in RS1 where the Import succeeds, but corrupts the key, - // and makes for a friendlier exception message. - if (parameters.D.Length != parameters.Modulus.Length || - parameters.P.Length != halfModulusLength || - parameters.Q.Length != halfModulusLength || - parameters.DP.Length != halfModulusLength || - parameters.DQ.Length != halfModulusLength || - parameters.InverseQ.Length != halfModulusLength) - { - throw new CryptographicException(SR.Cryptography_InvalidRsaParameters); - } + if (parameters.P == null || + parameters.DP == null || + parameters.Q == null || + parameters.DQ == null || + parameters.InverseQ == null) + { + throw new CryptographicException(SR.Cryptography_InvalidRsaParameters); } - // - // We need to build a key blob structured as follows: - // - // BCRYPT_RSAKEY_BLOB header - // byte[cbPublicExp] publicExponent - Exponent - // byte[cbModulus] modulus - Modulus - // -- Only if "includePrivate" is true -- - // byte[cbPrime1] prime1 - P - // byte[cbPrime2] prime2 - Q - // ------------------ - // + // Half, rounded up. + int halfModulusLength = (parameters.Modulus.Length + 1) / 2; - int blobSize = sizeof(BCRYPT_RSAKEY_BLOB) + - parameters.Exponent.Length + - parameters.Modulus.Length; - if (includePrivate) + // The same checks are done by RSACryptoServiceProvider on import (when building the key blob) + // Historically RSACng let CNG handle this (reporting NTE_NOT_SUPPORTED), but on RS1 CNG let the + // import succeed, then on private key use (e.g. signing) it would report NTE_INVALID_PARAMETER. + // + // Doing the check here prevents the state in RS1 where the Import succeeds, but corrupts the key, + // and makes for a friendlier exception message. + if (parameters.D.Length != parameters.Modulus.Length || + parameters.P.Length != halfModulusLength || + parameters.Q.Length != halfModulusLength || + parameters.DP.Length != halfModulusLength || + parameters.DQ.Length != halfModulusLength || + parameters.InverseQ.Length != halfModulusLength) { - blobSize += parameters.P!.Length + - parameters.Q!.Length; + throw new CryptographicException(SR.Cryptography_InvalidRsaParameters); } + } - byte[] rsaBlob = new byte[blobSize]; - fixed (byte* pRsaBlob = &rsaBlob[0]) - { - // Build the header - BCRYPT_RSAKEY_BLOB* pBcryptBlob = (BCRYPT_RSAKEY_BLOB*)pRsaBlob; - pBcryptBlob->Magic = includePrivate ? KeyBlobMagicNumber.BCRYPT_RSAPRIVATE_MAGIC : KeyBlobMagicNumber.BCRYPT_RSAPUBLIC_MAGIC; - pBcryptBlob->BitLength = parameters.Modulus.Length * 8; - pBcryptBlob->cbPublicExp = parameters.Exponent.Length; - pBcryptBlob->cbModulus = parameters.Modulus.Length; + // + // We need to build a key blob structured as follows: + // + // BCRYPT_RSAKEY_BLOB header + // byte[cbPublicExp] publicExponent - Exponent + // byte[cbModulus] modulus - Modulus + // -- Only if "includePrivate" is true -- + // byte[cbPrime1] prime1 - P + // byte[cbPrime2] prime2 - Q + // ------------------ + // - if (includePrivate) - { - pBcryptBlob->cbPrime1 = parameters.P!.Length; - pBcryptBlob->cbPrime2 = parameters.Q!.Length; - } + int blobSize = sizeof(BCRYPT_RSAKEY_BLOB) + + parameters.Exponent.Length + + parameters.Modulus.Length; + if (includePrivate) + { + blobSize += parameters.P!.Length + + parameters.Q!.Length; + } - int offset = sizeof(BCRYPT_RSAKEY_BLOB); + byte[] rsaBlob = new byte[blobSize]; + fixed (byte* pRsaBlob = &rsaBlob[0]) + { + // Build the header + BCRYPT_RSAKEY_BLOB* pBcryptBlob = (BCRYPT_RSAKEY_BLOB*)pRsaBlob; + pBcryptBlob->Magic = includePrivate ? KeyBlobMagicNumber.BCRYPT_RSAPRIVATE_MAGIC : KeyBlobMagicNumber.BCRYPT_RSAPUBLIC_MAGIC; + pBcryptBlob->BitLength = parameters.Modulus.Length * 8; + pBcryptBlob->cbPublicExp = parameters.Exponent.Length; + pBcryptBlob->cbModulus = parameters.Modulus.Length; + + if (includePrivate) + { + pBcryptBlob->cbPrime1 = parameters.P!.Length; + pBcryptBlob->cbPrime2 = parameters.Q!.Length; + } - Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Exponent); - Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Modulus); + int offset = sizeof(BCRYPT_RSAKEY_BLOB); - if (includePrivate) - { - Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.P!); - Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Q!); - } + Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Exponent); + Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Modulus); - // We better have computed the right allocation size above! - Debug.Assert(offset == blobSize, "offset == blobSize"); + if (includePrivate) + { + Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.P!); + Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Q!); } - ImportKeyBlob(rsaBlob, includePrivate); + // We better have computed the right allocation size above! + Debug.Assert(offset == blobSize, "offset == blobSize"); } + + ImportKeyBlob(rsaBlob, includePrivate); } public override void ImportPkcs8PrivateKey(ReadOnlySpan source, out int bytesRead) diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs b/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs index a65a88c77478d..c9b9aa4bb0bf1 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs @@ -436,7 +436,7 @@ public override void ImportParameters(RSAParameters parameters) ForceSetKeySize(BitsPerByte * Interop.Crypto.RsaSize(key)); } - public override unsafe void ImportRSAPublicKey(ReadOnlySpan source, out int bytesRead) + public override void ImportRSAPublicKey(ReadOnlySpan source, out int bytesRead) { ThrowIfDisposed(); diff --git a/src/libraries/Common/src/System/Text/DBCSDecoder.cs b/src/libraries/Common/src/System/Text/DBCSDecoder.cs index 3379f5fd88443..24cef3e86216a 100644 --- a/src/libraries/Common/src/System/Text/DBCSDecoder.cs +++ b/src/libraries/Common/src/System/Text/DBCSDecoder.cs @@ -40,7 +40,7 @@ public override void Reset() _leftOverLeadByte = 0; } - public override unsafe int GetCharCount(byte[] bytes, int index, int count) + public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } @@ -121,7 +121,7 @@ public unsafe override int GetCharCount(byte* bytes, int count, bool flush) return ConvertWithLeftOverByte(bytes, count, null, 0); } - public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, + public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.BSD.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.BSD.cs index ec2e319bb8096..02b7cce02263d 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.BSD.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.BSD.cs @@ -40,7 +40,7 @@ public static Process[] GetProcessesByName(string? processName, string machineNa /// /// Gets or sets which processors the threads in this process can be scheduled to run on. /// - private unsafe IntPtr ProcessorAffinityCore + private IntPtr ProcessorAffinityCore { get { diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs index 775c170da1d1e..6942d82d6d159 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs @@ -170,7 +170,7 @@ partial void EnsureHandleCountPopulated() /// /// Gets or sets which processors the threads in this process can be scheduled to run on. /// - private unsafe IntPtr ProcessorAffinityCore + private IntPtr ProcessorAffinityCore { get { diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.UnknownUnix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.UnknownUnix.cs index 67b4af31225b6..46c652a7fb6a6 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.UnknownUnix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.UnknownUnix.cs @@ -52,7 +52,7 @@ public TimeSpan UserProcessorTime /// /// Gets or sets which processors the threads in this process can be scheduled to run on. /// - private unsafe IntPtr ProcessorAffinityCore + private IntPtr ProcessorAffinityCore { get { throw new PlatformNotSupportedException(); } set { throw new PlatformNotSupportedException(); } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs index cc514764fa4d8..01461e9b4f061 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs @@ -151,19 +151,16 @@ internal static ProcessInfo CreateProcessInfo(ref Interop.procfs.ParsedStat proc if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out tid) && Interop.procfs.TryReadStatFile(pid, tid, out stat)) { - unsafe + pi._threadInfoList.Add(new ThreadInfo() { - pi._threadInfoList.Add(new ThreadInfo() - { - _processId = pid, - _threadId = (ulong)tid, - _basePriority = pi.BasePriority, - _currentPriority = (int)stat.nice, - _startAddress = IntPtr.Zero, - _threadState = ProcFsStateToThreadState(stat.state), - _threadWaitReason = ThreadWaitReason.Unknown - }); - } + _processId = pid, + _threadId = (ulong)tid, + _basePriority = pi.BasePriority, + _currentPriority = (int)stat.nice, + _startAddress = IntPtr.Zero, + _threadState = ProcFsStateToThreadState(stat.state), + _threadWaitReason = ThreadWaitReason.Unknown + }); } } } diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.Linux.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.Linux.cs index 34ef616dbe374..393ebf330c2b5 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.Linux.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.Linux.cs @@ -7,7 +7,7 @@ namespace System.DirectoryServices.Protocols { public static partial class BerConverter { - private static unsafe int DecodeBitStringHelper(ArrayList resultList, SafeBerHandle berElement) + private static int DecodeBitStringHelper(ArrayList resultList, SafeBerHandle berElement) { // Windows doesn't really decode BitStrings correctly, and wldap32 will internally treat it as 'O' Octet string. // In order to match behavior, in Linux we will interpret 'B' as 'O' when passing the call to libldap. diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.Windows.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.Windows.cs index ef3a659d2cce4..e4bd5d14c474e 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.Windows.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.Windows.cs @@ -9,7 +9,7 @@ namespace System.DirectoryServices.Protocols { public static partial class BerConverter { - private static unsafe int DecodeBitStringHelper(ArrayList resultList, SafeBerHandle berElement) + private static int DecodeBitStringHelper(ArrayList resultList, SafeBerHandle berElement) { int error; // return a bitstring and its length diff --git a/src/libraries/System.DirectoryServices/src/Interop/AdsValueHelper2.cs b/src/libraries/System.DirectoryServices/src/Interop/AdsValueHelper2.cs index d5868092c7a8b..63abf247b8392 100644 --- a/src/libraries/System.DirectoryServices/src/Interop/AdsValueHelper2.cs +++ b/src/libraries/System.DirectoryServices/src/Interop/AdsValueHelper2.cs @@ -250,7 +250,7 @@ public object GetVlvValue() }; } - private unsafe void SetValue(object managedValue, AdsType adsType) + private void SetValue(object managedValue, AdsType adsType) { adsvalue = new AdsValue() { diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/GdiplusNative.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/GdiplusNative.Windows.cs index a80aed81dc481..234eed272a771 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/GdiplusNative.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/GdiplusNative.Windows.cs @@ -8,9 +8,9 @@ namespace System.Drawing { - internal static unsafe partial class SafeNativeMethods + internal static partial class SafeNativeMethods { - internal static partial class Gdip + internal static unsafe partial class Gdip { private const string LibraryName = "gdiplus.dll"; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/GdiplusNative.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/GdiplusNative.cs index f35039fb59561..dd5d77b25f73f 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/GdiplusNative.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/GdiplusNative.cs @@ -10,9 +10,9 @@ namespace System.Drawing { // Raw function imports for gdiplus // Functions are loaded manually in order to accomodate different shared library names on Unix. - internal static unsafe partial class SafeNativeMethods + internal static partial class SafeNativeMethods { - internal static partial class Gdip + internal static unsafe partial class Gdip { // Shared function imports (all platforms) [DllImport(LibraryName, ExactSpelling = true)] diff --git a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/dec/BrotliDecoder.cs b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/dec/BrotliDecoder.cs index d73883ed8b3b3..181afc5cb9861 100644 --- a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/dec/BrotliDecoder.cs +++ b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/dec/BrotliDecoder.cs @@ -89,18 +89,15 @@ public OperationStatus Decompress(ReadOnlySpan source, Span destinat } } - public static bool TryDecompress(ReadOnlySpan source, Span destination, out int bytesWritten) + public static unsafe bool TryDecompress(ReadOnlySpan source, Span destination, out int bytesWritten) { - unsafe + fixed (byte* inBytes = &MemoryMarshal.GetReference(source)) + fixed (byte* outBytes = &MemoryMarshal.GetReference(destination)) { - fixed (byte* inBytes = &MemoryMarshal.GetReference(source)) - fixed (byte* outBytes = &MemoryMarshal.GetReference(destination)) - { - size_t availableOutput = (size_t)destination.Length; - bool success = Interop.Brotli.BrotliDecoderDecompress((size_t)source.Length, inBytes, ref availableOutput, outBytes); - bytesWritten = (int)availableOutput; - return success; - } + size_t availableOutput = (size_t)destination.Length; + bool success = Interop.Brotli.BrotliDecoderDecompress((size_t)source.Length, inBytes, ref availableOutput, outBytes); + bytesWritten = (int)availableOutput; + return success; } } } diff --git a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliEncoder.cs b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliEncoder.cs index c6ab42b73329e..870cdc05c65ed 100644 --- a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliEncoder.cs +++ b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliEncoder.cs @@ -170,6 +170,7 @@ public static bool TryCompress(ReadOnlySpan source, Span destination { throw new ArgumentOutOfRangeException(nameof(window), SR.Format(SR.BrotliEncoder_Window, window, BrotliUtils.WindowBits_Min, BrotliUtils.WindowBits_Max)); } + unsafe { fixed (byte* inBytes = &MemoryMarshal.GetReference(source)) diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs index 3e07cea34d546..abd5c3b689b62 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs @@ -577,7 +577,7 @@ private bool CheckIfPathIsNested(ReadOnlySpan eventPath) return _includeChildren || _fullDirectory.AsSpan().StartsWith(System.IO.Path.GetDirectoryName(eventPath), StringComparison.OrdinalIgnoreCase); } - private unsafe int? FindRenameChangePairedChange( + private int? FindRenameChangePairedChange( int currentIndex, Span flags, Span ids) { diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/Microsoft/Win32/SafeMemoryMappedFileHandle.Unix.cs b/src/libraries/System.IO.MemoryMappedFiles/src/Microsoft/Win32/SafeMemoryMappedFileHandle.Unix.cs index 3892e6189ace6..32e76bd946743 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/Microsoft/Win32/SafeMemoryMappedFileHandle.Unix.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/Microsoft/Win32/SafeMemoryMappedFileHandle.Unix.cs @@ -74,15 +74,8 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } - protected override unsafe bool ReleaseHandle() - { - // Nothing to clean up. We unlinked immediately after creating the backing store. - return true; - } + protected override bool ReleaseHandle() => true; // Nothing to clean up. We unlinked immediately after creating the backing store. - public override bool IsInvalid - { - get { return (long)handle <= 0; } - } + public override bool IsInvalid => (long)handle <= 0; } } diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs index abe63639a4eb0..174b91bb219a1 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs @@ -52,7 +52,7 @@ private static void VerifyMemoryMappedFileAccess(MemoryMappedFileAccess access, /// memory mapped file should not be associated with an existing file on disk (i.e. start /// out empty). /// - private static unsafe SafeMemoryMappedFileHandle CreateCore( + private static SafeMemoryMappedFileHandle CreateCore( FileStream? fileStream, string? mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Unix.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Unix.cs index b5e97b23518b4..83a60d4ccf914 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Unix.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Unix.cs @@ -8,7 +8,7 @@ namespace System.IO.MemoryMappedFiles { internal partial class MemoryMappedView { - public static unsafe MemoryMappedView CreateView( + public static MemoryMappedView CreateView( SafeMemoryMappedFileHandle memMappedFileHandle, MemoryMappedFileAccess access, long requestedOffset, long requestedSize) { diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs index 4e6e6259a7aee..01117ab6960bc 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs @@ -14,7 +14,7 @@ internal partial class MemoryMappedView private const int MaxFlushWaits = 15; // must be <=30 private const int MaxFlushRetriesPerWait = 20; - public static unsafe MemoryMappedView CreateView(SafeMemoryMappedFileHandle memMappedFileHandle, + public static MemoryMappedView CreateView(SafeMemoryMappedFileHandle memMappedFileHandle, MemoryMappedFileAccess access, long offset, long size) { // MapViewOfFile can only create views that start at a multiple of the system memory allocation @@ -93,57 +93,54 @@ public static unsafe MemoryMappedView CreateView(SafeMemoryMappedFileHandle memM // flush to the disk. // NOTE: This will flush all bytes before and after the view up until an offset that is a multiple // of SystemPageSize. - public void Flush(UIntPtr capacity) + public unsafe void Flush(UIntPtr capacity) { - unsafe + byte* firstPagePtr = null; + try { - byte* firstPagePtr = null; - try - { - _viewHandle.AcquirePointer(ref firstPagePtr); + _viewHandle.AcquirePointer(ref firstPagePtr); - if (Interop.Kernel32.FlushViewOfFile((IntPtr)firstPagePtr, capacity)) - return; + if (Interop.Kernel32.FlushViewOfFile((IntPtr)firstPagePtr, capacity)) + return; - // It is a known issue within the NTFS transaction log system that - // causes FlushViewOfFile to intermittently fail with ERROR_LOCK_VIOLATION - // As a workaround, we catch this particular error and retry the flush operation - // a few milliseconds later. If it does not work, we give it a few more tries with - // increasing intervals. Eventually, however, we need to give up. In ad-hoc tests - // this strategy successfully flushed the view after no more than 3 retries. + // It is a known issue within the NTFS transaction log system that + // causes FlushViewOfFile to intermittently fail with ERROR_LOCK_VIOLATION + // As a workaround, we catch this particular error and retry the flush operation + // a few milliseconds later. If it does not work, we give it a few more tries with + // increasing intervals. Eventually, however, we need to give up. In ad-hoc tests + // this strategy successfully flushed the view after no more than 3 retries. - int error = Marshal.GetLastWin32Error(); - if (error != Interop.Errors.ERROR_LOCK_VIOLATION) - throw Win32Marshal.GetExceptionForWin32Error(error); + int error = Marshal.GetLastWin32Error(); + if (error != Interop.Errors.ERROR_LOCK_VIOLATION) + throw Win32Marshal.GetExceptionForWin32Error(error); - SpinWait spinWait = default; - for (int w = 0; w < MaxFlushWaits; w++) - { - int pause = (1 << w); // MaxFlushRetries should never be over 30 - Thread.Sleep(pause); + SpinWait spinWait = default; + for (int w = 0; w < MaxFlushWaits; w++) + { + int pause = (1 << w); // MaxFlushRetries should never be over 30 + Thread.Sleep(pause); - for (int r = 0; r < MaxFlushRetriesPerWait; r++) - { - if (Interop.Kernel32.FlushViewOfFile((IntPtr)firstPagePtr, capacity)) - return; + for (int r = 0; r < MaxFlushRetriesPerWait; r++) + { + if (Interop.Kernel32.FlushViewOfFile((IntPtr)firstPagePtr, capacity)) + return; - error = Marshal.GetLastWin32Error(); - if (error != Interop.Errors.ERROR_LOCK_VIOLATION) - throw Win32Marshal.GetExceptionForWin32Error(error); + error = Marshal.GetLastWin32Error(); + if (error != Interop.Errors.ERROR_LOCK_VIOLATION) + throw Win32Marshal.GetExceptionForWin32Error(error); - spinWait.SpinOnce(); - } + spinWait.SpinOnce(); } - - // We got to here, so there was no success: - throw Win32Marshal.GetExceptionForWin32Error(error); } - finally + + // We got to here, so there was no success: + throw Win32Marshal.GetExceptionForWin32Error(error); + } + finally + { + if (firstPagePtr != null) { - if (firstPagePtr != null) - { - _viewHandle.ReleasePointer(); - } + _viewHandle.ReleasePointer(); } } } diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.cs index 0f677f257f099..32730cb04b9de 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.cs @@ -13,8 +13,7 @@ internal partial class MemoryMappedView : IDisposable private readonly long _size; private readonly MemoryMappedFileAccess _access; - private unsafe MemoryMappedView(SafeMemoryMappedViewHandle viewHandle, long pointerOffset, - long size, MemoryMappedFileAccess access) + private MemoryMappedView(SafeMemoryMappedViewHandle viewHandle, long pointerOffset, long size, MemoryMappedFileAccess access) { Debug.Assert(viewHandle != null); diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewAccessor.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewAccessor.cs index 5bef12efb4bac..8bde897dc57e6 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewAccessor.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewAccessor.cs @@ -64,10 +64,7 @@ public void Flush() throw new ObjectDisposedException(nameof(MemoryMappedViewAccessor), SR.ObjectDisposed_ViewAccessorClosed); } - unsafe - { - _view.Flush((UIntPtr)Capacity); - } + _view.Flush((UIntPtr)Capacity); } } } diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewStream.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewStream.cs index 1a51c7e2814b6..3a8a56d4313c6 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewStream.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewStream.cs @@ -10,7 +10,7 @@ public sealed class MemoryMappedViewStream : UnmanagedMemoryStream { private readonly MemoryMappedView _view; - internal unsafe MemoryMappedViewStream(MemoryMappedView view) + internal MemoryMappedViewStream(MemoryMappedView view) { Debug.Assert(view != null, "view is null"); diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeServerStream.Unix.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeServerStream.Unix.cs index 0806586d95555..d144a12a0ed1a 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeServerStream.Unix.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeServerStream.Unix.cs @@ -12,7 +12,7 @@ namespace System.IO.Pipes public sealed partial class AnonymousPipeServerStream : PipeStream { // Creates the anonymous pipe. - private unsafe void Create(PipeDirection direction, HandleInheritability inheritability, int bufferSize) + private void Create(PipeDirection direction, HandleInheritability inheritability, int bufferSize) { Debug.Assert(direction != PipeDirection.InOut, "Anonymous pipe direction shouldn't be InOut"); // Ignore bufferSize. It's optional, and the fcntl F_SETPIPE_SZ for changing it is Linux specific. diff --git a/src/libraries/System.IO.Pipes/tests/InteropTest.Unix.cs b/src/libraries/System.IO.Pipes/tests/InteropTest.Unix.cs index 4cc874f20041a..17e6b08134e0f 100644 --- a/src/libraries/System.IO.Pipes/tests/InteropTest.Unix.cs +++ b/src/libraries/System.IO.Pipes/tests/InteropTest.Unix.cs @@ -36,7 +36,7 @@ internal static unsafe bool TryGetHostName(out string hostName) // @todo: These are called by some Windows-specific tests. Those tests should really be split out into // partial classes and included only in Windows builds. - internal static unsafe bool CancelIoEx(SafeHandle handle) { throw new Exception("Should not call on Unix."); } + internal static bool CancelIoEx(SafeHandle handle) { throw new Exception("Should not call on Unix."); } internal static bool TryGetImpersonationUserName(SafePipeHandle handle, out string impersonationUserName) { throw new Exception("Should not call on Unix."); } internal static bool TryGetNumberOfServerInstances(SafePipeHandle handle, out uint numberOfServerInstances) { throw new Exception("Should not call on Unix."); } } diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs index 65f7fd62b1bff..3b1c766340651 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs @@ -403,7 +403,7 @@ public override int Read(byte[] array, int offset, int count) return Read(array, offset, count, ReadTimeout); } - internal unsafe int Read(byte[] array, int offset, int count, int timeout) + internal int Read(byte[] array, int offset, int count, int timeout) { using (CancellationTokenSource cts = GetCancellationTokenSourceFromTimeout(timeout)) { @@ -786,7 +786,7 @@ private static int DoIORequest(ConcurrentQueue q, Request return 0; } - private unsafe void IOLoop() + private void IOLoop() { bool eofReceived = false; // we do not care about bytes we got before - only about changes diff --git a/src/libraries/System.Memory/src/System/Buffers/SequenceReader.Search.cs b/src/libraries/System.Memory/src/System/Buffers/SequenceReader.Search.cs index 8f8da6a76efb7..af602ae6ae4a2 100644 --- a/src/libraries/System.Memory/src/System/Buffers/SequenceReader.Search.cs +++ b/src/libraries/System.Memory/src/System/Buffers/SequenceReader.Search.cs @@ -775,7 +775,7 @@ public bool IsNext(ReadOnlySpan next, bool advancePast = false) return unread.Length < next.Length && IsNextSlow(next, advancePast); } - private unsafe bool IsNextSlow(ReadOnlySpan next, bool advancePast) + private bool IsNextSlow(ReadOnlySpan next, bool advancePast) { ReadOnlySpan currentSpan = UnreadSpan; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs b/src/libraries/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs index d30e6cc90e7c2..5ba0eed91c17d 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs @@ -25,7 +25,7 @@ public static void UriBaseAddress(object obj, Uri? baseAddress) } [Event(UriBaseAddressId, Keywords = Keywords.Debug, Level = EventLevel.Informational)] - private unsafe void UriBaseAddress(string? uriBaseAddress, string objName, int objHash) => + private void UriBaseAddress(string? uriBaseAddress, string objName, int objHash) => WriteEvent(UriBaseAddressId, uriBaseAddress, objName, objHash); [NonEvent] diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs index 6def0c00e3b5d..b2d27035c5534 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs @@ -389,7 +389,7 @@ private static bool MustValueBeQuoted(string key) return StringBuilderCache.GetStringAndRelease(sb); } - private unsafe void Parse(string challenge) + private void Parse(string challenge) { int parsedIndex = 0; while (parsedIndex < challenge.Length) diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdIPGlobalProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdIPGlobalProperties.cs index ee34db4eff030..c4b5d6c38bbec 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdIPGlobalProperties.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdIPGlobalProperties.cs @@ -64,7 +64,8 @@ private unsafe TcpConnectionInformation[] GetTcpConnections(bool listeners) return connectionInformations; } - public unsafe override TcpConnectionInformation[] GetActiveTcpConnections() + + public override TcpConnectionInformation[] GetActiveTcpConnections() { return GetTcpConnections(listeners:false); } 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 6f644daafe492..745b8492f87e1 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 @@ -121,7 +121,7 @@ internal static void Stop(NetworkAvailabilityChangedEventHandler? caller) } // Helper class for detecting address change events. - internal static unsafe class AddressChangeListener + internal static class AddressChangeListener { // Need to keep the reference so it isn't GC'd before the native call executes. private static bool s_isListening; diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemTcpConnection.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemTcpConnection.cs index 2121b407791c4..069e61f4fe83d 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemTcpConnection.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemTcpConnection.cs @@ -24,7 +24,7 @@ internal SystemTcpConnectionInformation(in Interop.IpHlpApi.MibTcpRow row) } // IPV6 version of the Tcp row. - internal unsafe SystemTcpConnectionInformation(in Interop.IpHlpApi.MibTcp6RowOwnerPid row) + internal SystemTcpConnectionInformation(in Interop.IpHlpApi.MibTcp6RowOwnerPid row) { _state = row.state; diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicAddressHelpers.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicAddressHelpers.cs index a06a08f3b424a..bf5279ea859bc 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicAddressHelpers.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicAddressHelpers.cs @@ -11,7 +11,7 @@ internal static class MsQuicAddressHelpers internal const ushort IPv4 = 2; internal const ushort IPv6 = 23; - internal static unsafe IPEndPoint INetToIPEndPoint(ref SOCKADDR_INET inetAddress) + internal static IPEndPoint INetToIPEndPoint(ref SOCKADDR_INET inetAddress) { if (inetAddress.si_family == IPv4) { diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicConnection.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicConnection.cs index fb9a28691d8c6..fcc975f021dd2 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicConnection.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicConnection.cs @@ -237,7 +237,7 @@ internal override long GetRemoteAvailableBidirectionalStreamCount() return MsQuicParameterHelpers.GetUShortParam(MsQuicApi.Api, _ptr, (uint)QUIC_PARAM_LEVEL.CONNECTION, (uint)QUIC_PARAM_CONN.PEER_BIDI_STREAM_COUNT); } - private unsafe void SetIdleTimeout(TimeSpan timeout) + private void SetIdleTimeout(TimeSpan timeout) { MsQuicParameterHelpers.SetULongParam(MsQuicApi.Api, _ptr, (uint)QUIC_PARAM_LEVEL.CONNECTION, (uint)QUIC_PARAM_CONN.IDLE_TIMEOUT, (ulong)timeout.TotalMilliseconds); } diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicListener.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicListener.cs index 4e83c8613d5b4..60b17a6ad0e01 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicListener.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicListener.cs @@ -139,7 +139,7 @@ internal override void Close() MsQuicApi.Api.ListenerStopDelegate(_ptr); } - private unsafe void SetListenPort() + private void SetListenPort() { SOCKADDR_INET inetAddress = MsQuicParameterHelpers.GetINetParam(MsQuicApi.Api, _ptr, (uint)QUIC_PARAM_LEVEL.LISTENER, (uint)QUIC_PARAM_LISTENER.LOCAL_ADDRESS); diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicStream.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicStream.cs index 3a0a353fe7309..0069a234b92a6 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicStream.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicStream.cs @@ -951,7 +951,7 @@ private void ReceiveComplete(int bufferLength) } // This can fail if the stream isn't started. - private unsafe long GetStreamId() + private long GetStreamId() { return (long)MsQuicParameterHelpers.GetULongParam(MsQuicApi.Api, _ptr, (uint)QUIC_PARAM_LEVEL.STREAM, (uint)QUIC_PARAM_STREAM.ID); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs index 0f2c58d0a18a0..d1d7a0af41851 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs @@ -87,7 +87,7 @@ public void SslStreamCtor(SslStream sslStream, Stream innerStream) } [Event(SslStreamCtorId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private unsafe void SslStreamCtor(string thisOrContextObject, string? localId, string? remoteId) => + private void SslStreamCtor(string thisOrContextObject, string? localId, string? remoteId) => WriteEvent(SslStreamCtorId, thisOrContextObject, localId, remoteId); [NonEvent] @@ -100,7 +100,7 @@ public void SecureChannelCtor(SecureChannel secureChannel, SslStream sslStream, } [Event(SecureChannelCtorId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - private unsafe void SecureChannelCtor(string sslStream, string hostname, int secureChannelHash, int clientCertificatesCount, EncryptionPolicy encryptionPolicy) => + private void SecureChannelCtor(string sslStream, string hostname, int secureChannelHash, int clientCertificatesCount, EncryptionPolicy encryptionPolicy) => WriteEvent(SecureChannelCtorId, sslStream, hostname, secureChannelHash, clientCertificatesCount, (int)encryptionPolicy); [NonEvent] @@ -284,7 +284,7 @@ private void UsingCachedCredential(int secureChannelHash) => WriteEvent(UsingCachedCredentialId, secureChannelHash); [Event(SspiSelectedCipherSuitId, Keywords = Keywords.Default, Level = EventLevel.Informational)] - public unsafe void SspiSelectedCipherSuite( + public void SspiSelectedCipherSuite( string process, SslProtocols sslProtocol, CipherAlgorithmType cipherAlgorithm, 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 4c3c2c22db42e..25ddc615ab53c 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 @@ -396,7 +396,7 @@ public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials? cred return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException: true); } - public static unsafe SafeFreeContextBufferChannelBinding? QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute) + public static SafeFreeContextBufferChannelBinding? QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute) { return SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, securityContext, (Interop.SspiCli.ContextAttribute)attribute); }