Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace more Unsafe.As usage with pointers #78919

Merged
merged 1 commit into from
Nov 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/coreclr/vm/corelib.h
Original file line number Diff line number Diff line change
Expand Up @@ -693,7 +693,6 @@ DEFINE_METHOD(UNSAFE, AS_POINTER, AsPointer, NoSig)
DEFINE_METHOD(UNSAFE, BYREF_IS_NULL, IsNullRef, NoSig)
DEFINE_METHOD(UNSAFE, BYREF_NULLREF, NullRef, NoSig)
DEFINE_METHOD(UNSAFE, AS_REF_IN, AsRef, GM_RefT_RetRefT)
DEFINE_METHOD(UNSAFE, AS_REF_POINTER, AsRef, GM_VoidPtr_RetRefT)
DEFINE_METHOD(UNSAFE, BYREF_AS, As, GM_RefTFrom_RetRefTTo)
DEFINE_METHOD(UNSAFE, OBJECT_AS, As, GM_Obj_RetT)
DEFINE_METHOD(UNSAFE, BYREF_ADD, Add, GM_RefT_Int_RetRefT)
Expand Down
1 change: 0 additions & 1 deletion src/coreclr/vm/jitinterface.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6791,7 +6791,6 @@ bool getILIntrinsicImplementationForUnsafe(MethodDesc * ftn,
}
else if (tk == CoreLibBinder::GetMethod(METHOD__UNSAFE__BYREF_AS)->GetMemberDef() ||
tk == CoreLibBinder::GetMethod(METHOD__UNSAFE__OBJECT_AS)->GetMemberDef() ||
tk == CoreLibBinder::GetMethod(METHOD__UNSAFE__AS_REF_POINTER)->GetMemberDef() ||
tk == CoreLibBinder::GetMethod(METHOD__UNSAFE__AS_REF_IN)->GetMemberDef())
{
// Return the argument that was passed in.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;

#pragma warning disable 8500 // takes address of managed type

internal static partial class Interop
{
internal static partial class Sys
Expand All @@ -23,15 +25,14 @@ private struct AllMountPointsContext
[UnmanagedCallersOnly]
private static unsafe void AddMountPoint(void* context, byte* name)
{
ref AllMountPointsContext callbackContext = ref Unsafe.As<byte, AllMountPointsContext>(ref *(byte*)context);

AllMountPointsContext* callbackContext = (AllMountPointsContext*)context;
try
{
callbackContext._results.Add(Marshal.PtrToStringUTF8((IntPtr)name)!);
callbackContext->_results.Add(Marshal.PtrToStringUTF8((IntPtr)name)!);
}
catch (Exception e)
{
callbackContext._exception = ExceptionDispatchInfo.Capture(e);
callbackContext->_exception = ExceptionDispatchInfo.Capture(e);
}
}

Expand All @@ -42,7 +43,7 @@ internal static string[] GetAllMountPoints()

unsafe
{
GetAllMountPoints(&AddMountPoint, Unsafe.AsPointer(ref context));
GetAllMountPoints(&AddMountPoint, &context);
}

context._exception?.Throw();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
using System.Runtime.InteropServices;
using System.Runtime.Versioning;

#pragma warning disable 8500 // taking address of managed types

namespace System.Net.NetworkInformation
{
internal sealed class BsdIPv4GlobalStatistics : IPGlobalStatistics
Expand Down Expand Up @@ -37,10 +39,10 @@ private struct Context
[UnmanagedCallersOnly]
private static unsafe void ProcessIpv4Address(void* pContext, byte* ifaceName, Interop.Sys.IpAddressInfo* ipAddr)
{
ref Context context = ref Unsafe.As<byte, Context>(ref *(byte*)pContext);
Context* context = (Context*)pContext;

context._interfaceSet.Add(new string((sbyte*)ifaceName));
context._numIPAddresses++;
context->_interfaceSet.Add(new string((sbyte*)ifaceName));
context->_numIPAddresses++;
}

public unsafe BsdIPv4GlobalStatistics()
Expand Down Expand Up @@ -71,7 +73,7 @@ public unsafe BsdIPv4GlobalStatistics()
context._interfaceSet = new HashSet<string>();

Interop.Sys.EnumerateInterfaceAddresses(
Unsafe.AsPointer(ref context),
&context,
&ProcessIpv4Address,
null,
null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
using System.Runtime.InteropServices;
using System.Runtime.Versioning;

#pragma warning disable 8500 // taking address of managed types

namespace System.Net.NetworkInformation
{
internal sealed class BsdIpInterfaceProperties : UnixIPInterfaceProperties
Expand Down Expand Up @@ -74,7 +76,7 @@ private static unsafe GatewayIPAddressInformationCollection GetGatewayAddresses(
Context context;
context._interfaceIndex = interfaceIndex;
context._addressSet = new HashSet<IPAddress>();
if (Interop.Sys.EnumerateGatewayAddressesForInterface(Unsafe.AsPointer(ref context), (uint)interfaceIndex, &OnGatewayFound) == -1)
if (Interop.Sys.EnumerateGatewayAddressesForInterface(&context, (uint)interfaceIndex, &OnGatewayFound) == -1)
{
throw new NetworkInformationException(SR.net_PInvokeError);
}
Expand All @@ -91,15 +93,15 @@ private static unsafe GatewayIPAddressInformationCollection GetGatewayAddresses(
[UnmanagedCallersOnly]
private static unsafe void OnGatewayFound(void* pContext, Interop.Sys.IpAddressInfo* gatewayAddressInfo)
{
ref Context context = ref Unsafe.As<byte, Context>(ref *(byte*)pContext);
Context* context = (Context*)pContext;

IPAddress ipAddress = new IPAddress(new ReadOnlySpan<byte>(gatewayAddressInfo->AddressBytes, gatewayAddressInfo->NumAddressBytes));
if (ipAddress.IsIPv6LinkLocal)
{
// For Link-Local addresses add ScopeId as that is not part of the route entry.
ipAddress.ScopeId = context._interfaceIndex;
ipAddress.ScopeId = context->_interfaceIndex;
}
context._addressSet.Add(ipAddress);
context->_addressSet.Add(ipAddress);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

#pragma warning disable 8500 // taking address of managed types

namespace System.Net.NetworkInformation
{
internal sealed class BsdNetworkInterface : UnixNetworkInterface
Expand Down Expand Up @@ -72,42 +74,42 @@ internal void AddException(Exception e)
[UnmanagedCallersOnly]
private static unsafe void ProcessIpv4Address(void* pContext, byte* ifaceName, Interop.Sys.IpAddressInfo* ipAddr)
{
ref Context context = ref Unsafe.As<byte, Context>(ref *(byte*)pContext);
Context* context = (Context*)pContext;
try
{
context.GetOrCreate(ifaceName, ipAddr->InterfaceIndex).ProcessIpv4Address(ipAddr);
context->GetOrCreate(ifaceName, ipAddr->InterfaceIndex).ProcessIpv4Address(ipAddr);
}
catch (Exception e)
{
context.AddException(e);
context->AddException(e);
}
}

[UnmanagedCallersOnly]
private static unsafe void ProcessIpv6Address(void* pContext, byte* ifaceName, Interop.Sys.IpAddressInfo* ipAddr, uint* scopeId)
{
ref Context context = ref Unsafe.As<byte, Context>(ref *(byte*)pContext);
Context* context = (Context*)pContext;
try
{
context.GetOrCreate(ifaceName, ipAddr->InterfaceIndex).ProcessIpv6Address(ipAddr, *scopeId);
context->GetOrCreate(ifaceName, ipAddr->InterfaceIndex).ProcessIpv6Address(ipAddr, *scopeId);
}
catch (Exception e)
{
context.AddException(e);
context->AddException(e);
}
}

[UnmanagedCallersOnly]
private static unsafe void ProcessLinkLayerAddress(void* pContext, byte* ifaceName, Interop.Sys.LinkLayerAddressInfo* llAddr)
{
ref Context context = ref Unsafe.As<byte, Context>(ref *(byte*)pContext);
Context* context = (Context*)pContext;
try
{
context.GetOrCreate(ifaceName, llAddr->InterfaceIndex).ProcessLinkLayerAddress(llAddr);
context->GetOrCreate(ifaceName, llAddr->InterfaceIndex).ProcessLinkLayerAddress(llAddr);
}
catch (Exception e)
{
context.AddException(e);
context->AddException(e);
}
}

Expand All @@ -123,7 +125,7 @@ public static unsafe NetworkInterface[] GetBsdNetworkInterfaces()
// Because these callbacks are executed in a reverse-PInvoke, we do not want any exceptions
// to propagate out, because they will not be catchable. Instead, we track all the exceptions
// that are thrown in these callbacks, and aggregate them at the end.
int result = Interop.Sys.EnumerateInterfaceAddresses(Unsafe.AsPointer(ref context), &ProcessIpv4Address, &ProcessIpv6Address, &ProcessLinkLayerAddress);
int result = Interop.Sys.EnumerateInterfaceAddresses(&context, &ProcessIpv4Address, &ProcessIpv6Address, &ProcessLinkLayerAddress);
if (context._exceptions != null)
{
throw new NetworkInformationException(SR.net_PInvokeError, new AggregateException(context._exceptions));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
using System.Threading;
using System.Threading.Tasks;

#pragma warning disable 8500 // taking address of managed types

namespace System.Net.NetworkInformation
{
internal abstract class UnixIPGlobalProperties : IPGlobalProperties
Expand Down Expand Up @@ -70,36 +72,36 @@ internal void AddException(Exception e)
[UnmanagedCallersOnly]
private static unsafe void ProcessIpv4Address(void* pContext, byte* ifaceName, Interop.Sys.IpAddressInfo* ipAddr)
{
ref Context context = ref Unsafe.As<byte, Context>(ref *(byte*)pContext);
Context* context = (Context*)pContext;
try
{
IPAddress ipAddress = IPAddressUtil.GetIPAddressFromNativeInfo(ipAddr);
if (!IPAddressUtil.IsMulticast(ipAddress))
{
context._collection.InternalAdd(new UnixUnicastIPAddressInformation(ipAddress, ipAddr->PrefixLength));
context->_collection.InternalAdd(new UnixUnicastIPAddressInformation(ipAddress, ipAddr->PrefixLength));
}
}
catch (Exception e)
{
context.AddException(e);
context->AddException(e);
}
}

[UnmanagedCallersOnly]
private static unsafe void ProcessIpv6Address(void* pContext, byte* ifaceName, Interop.Sys.IpAddressInfo* ipAddr, uint* scopeId)
{
ref Context context = ref Unsafe.As<byte, Context>(ref *(byte*)pContext);
Context* context = (Context*)pContext;
try
{
IPAddress ipAddress = IPAddressUtil.GetIPAddressFromNativeInfo(ipAddr);
if (!IPAddressUtil.IsMulticast(ipAddress))
{
context._collection.InternalAdd(new UnixUnicastIPAddressInformation(ipAddress, ipAddr->PrefixLength));
context->_collection.InternalAdd(new UnixUnicastIPAddressInformation(ipAddress, ipAddr->PrefixLength));
}
}
catch (Exception e)
{
context.AddException(e);
context->AddException(e);
}
}

Expand All @@ -110,7 +112,7 @@ public override unsafe UnicastIPAddressInformationCollection GetUnicastAddresses
context._exceptions = null;

// Ignore link-layer addresses that are discovered; don't create a callback.
Interop.Sys.EnumerateInterfaceAddresses(Unsafe.AsPointer(ref context), &ProcessIpv4Address, &ProcessIpv6Address, null);
Interop.Sys.EnumerateInterfaceAddresses(&context, &ProcessIpv4Address, &ProcessIpv6Address, null);

if (context._exceptions != null)
throw new NetworkInformationException(SR.net_PInvokeError, new AggregateException(context._exceptions));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ private unsafe SocketError ProcessIOCPResult(bool success, int bytesTransferred,
socketError = (SocketError)(packedResult & 0xFFFFFFFF);
if (socketError != SocketError.Success)
{
GetOverlappedResultOnError(ref socketError, ref Unsafe.As<int, uint>(ref bytesTransferred), ref socketFlags, overlapped);
GetOverlappedResultOnError(ref socketError, ref *(uint*)&bytesTransferred, ref socketFlags, overlapped);
}
FreeNativeOverlapped(ref overlapped);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -427,11 +427,13 @@ private static unsafe void EnumCalendarInfoCallback(char* calendarStringPtr, Int
try
{
ReadOnlySpan<char> calendarStringSpan = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(calendarStringPtr);
ref IcuEnumCalendarsData callbackContext = ref Unsafe.As<byte, IcuEnumCalendarsData>(ref *(byte*)context);
#pragma warning disable 8500
IcuEnumCalendarsData* callbackContext = (IcuEnumCalendarsData*)context;
#pragma warning restore 8500

if (callbackContext.DisallowDuplicates)
if (callbackContext->DisallowDuplicates)
{
foreach (string existingResult in callbackContext.Results)
foreach (string existingResult in callbackContext->Results)
{
if (string.CompareOrdinal(calendarStringSpan, existingResult) == 0)
{
Expand All @@ -441,7 +443,7 @@ private static unsafe void EnumCalendarInfoCallback(char* calendarStringPtr, Int
}
}

callbackContext.Results.Add(calendarStringSpan.ToString());
callbackContext->Results.Add(calendarStringSpan.ToString());
}
catch (Exception e)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

#pragma warning disable 8500 // taking address of managed type

namespace System.Globalization
{
internal sealed partial class CalendarData
Expand Down Expand Up @@ -61,16 +63,16 @@ private struct EnumData
[UnmanagedCallersOnly]
private static unsafe Interop.BOOL EnumCalendarInfoCallback(char* lpCalendarInfoString, uint calendar, IntPtr pReserved, void* lParam)
{
ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)lParam);
EnumData* context = (EnumData*)lParam;
try
{
string calendarInfo = new string(lpCalendarInfoString);

// If we had a user override, check to make sure this differs
if (context.userOverride != calendarInfo)
if (context->userOverride != calendarInfo)
{
Debug.Assert(context.strings != null);
context.strings.Add(calendarInfo);
Debug.Assert(context->strings != null);
context->strings!.Add(calendarInfo); // TODO https://github.com/dotnet/roslyn/issues/65634: Remove ! when no longer needed
}

return Interop.BOOL.TRUE;
Expand All @@ -93,12 +95,12 @@ public struct NlsEnumCalendarsData
[UnmanagedCallersOnly]
private static unsafe Interop.BOOL EnumCalendarsCallback(char* lpCalendarInfoString, uint calendar, IntPtr reserved, void* lParam)
{
ref NlsEnumCalendarsData context = ref Unsafe.As<byte, NlsEnumCalendarsData>(ref *(byte*)lParam);
NlsEnumCalendarsData* context = (NlsEnumCalendarsData*)lParam;
try
{
// If we had a user override, check to make sure this differs
if (context.userOverride != calendar)
context.calendars.Add((int)calendar);
if (context->userOverride != calendar)
context->calendars.Add((int)calendar);

return Interop.BOOL.TRUE;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
using System.Diagnostics;
using System.Runtime.CompilerServices;

#pragma warning disable 8500 // taking address of managed type

namespace System.Globalization
{
internal sealed partial class CalendarData
Expand Down Expand Up @@ -265,7 +267,7 @@ private static unsafe bool CallEnumCalendarInfo(string localeName, CalendarId ca
}

// Now call the enumeration API. Work is done by our callback function
Interop.Kernel32.EnumCalendarInfoExEx(&EnumCalendarInfoCallback, localeName, (uint)calendar, null, calType, Unsafe.AsPointer(ref context));
Interop.Kernel32.EnumCalendarInfoExEx(&EnumCalendarInfoCallback, localeName, (uint)calendar, null, calType, &context);

// Now we have a list of data, fail if we didn't find anything.
Debug.Assert(context.strings != null);
Expand Down Expand Up @@ -417,7 +419,7 @@ private static int NlsGetCalendars(string localeName, bool useUserOverride, Cale

unsafe
{
Interop.Kernel32.EnumCalendarInfoExEx(&EnumCalendarsCallback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, Unsafe.AsPointer(ref data));
Interop.Kernel32.EnumCalendarInfoExEx(&EnumCalendarsCallback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, &data);
}

// Copy to the output array
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ private static double GetNumericValueNoBoundsCheck(uint codePoint)
{
ulong temp = Unsafe.ReadUnaligned<ulong>(ref refToValue);
temp = BinaryPrimitives.ReverseEndianness(temp);
return Unsafe.As<ulong, double>(ref temp);
return BitConverter.UInt64BitsToDouble(temp);
}
}

Expand Down
Loading