Skip to content

Commit

Permalink
Remove some unnecessary unsafe usage (#43430)
Browse files Browse the repository at this point in the history
  • Loading branch information
stephentoub committed Oct 17, 2020
1 parent 838fde6 commit e8339af
Show file tree
Hide file tree
Showing 111 changed files with 612 additions and 699 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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
{
Expand All @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down
21 changes: 11 additions & 10 deletions src/libraries/Common/src/Interop/FreeBSD/Interop.Process.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,7 @@ internal struct proc_stats
/// <returns>Returns a list of PIDs corresponding to all running processes</returns>
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)
Expand All @@ -44,9 +41,10 @@ internal static unsafe int[] ListAllPids()
}

var list = new ReadOnlySpan<kinfo_proc>(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)
Expand All @@ -60,14 +58,15 @@ internal static unsafe int[] ListAllPids()
idx += 1;
}
}

// Remove extra elements
Array.Resize<int>(ref pids, numProcesses);
return pids;
}
finally
{
Marshal.FreeHGlobal((IntPtr)entries);
}
return pids;
}


Expand All @@ -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);
}

Expand Down Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions src/libraries/Common/src/Interop/Interop.Collation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/Common/src/Interop/Interop.Locale.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<byte> data) =>
HmacUpdate(ctx, ref MemoryMarshal.GetReference(data), data.Length);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

internal static partial class Interop
{
internal unsafe partial class Sys
internal partial class Sys
{
[StructLayout(LayoutKind.Sequential)]
internal struct ProcessCpuInformation
Expand All @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/// <summary>Categorizes a file system name into a drive type.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
/// </returns>
[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);

/// <summary>
/// Takes a path to a symbolic link and returns the link target path.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Loading

0 comments on commit e8339af

Please sign in to comment.