Skip to content

Commit

Permalink
Replace most corelib uses of Unsafe.SizeOf<T> with sizeof(T) (#104923)
Browse files Browse the repository at this point in the history
Also suppress CS8500 globally rather than in hundreds of files individually and fix NoWarns that weren't inheriting global NoWarns.
  • Loading branch information
stephentoub authored Jul 17, 2024
1 parent 769ead4 commit 19f0385
Show file tree
Hide file tree
Showing 140 changed files with 112 additions and 442 deletions.
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@
<Features>strict;nullablePublicOnly</Features>
<TreatWarningsAsErrors Condition="'$(TreatWarningsAsErrors)' == ''">true</TreatWarningsAsErrors>
<!-- Warnings to always disable -->
<NoWarn>$(NoWarn),CS8969</NoWarn>
<NoWarn>$(NoWarn);CS8500;CS8969</NoWarn>
<!-- Always pass portable to override arcade sdk which uses embedded for local builds -->
<DebugType>portable</DebugType>
<KeepNativeSymbols Condition="'$(KeepNativeSymbols)' == '' and '$(DotNetBuildSourceOnly)' == 'true'">true</KeepNativeSymbols>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ public ArgIterator(RuntimeArgumentHandle arglist, void* ptr)
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ArgIterator_Init2")]
private static partial void Init(ArgIterator* thisPtr, IntPtr cookie, void* ptr);

#pragma warning disable CS8500 // Takes a pointer to a managed type
// Fetch an argument as a typed referece, advance the iterator.
// Throws an exception if past end of argument list
[CLSCompliant(false)]
Expand Down
4 changes: 0 additions & 4 deletions src/coreclr/System.Private.CoreLib/src/System/GC.CoreCLR.cs
Original file line number Diff line number Diff line change
Expand Up @@ -790,9 +790,7 @@ public static unsafe T[] AllocateUninitializedArray<T>(int length, bool pinned =
// for debug builds we always want to call AllocateNewArray to detect AllocateNewArray bugs
#if !DEBUG
// small arrays are allocated using `new[]` as that is generally faster.
#pragma warning disable 8500 // sizeof of managed types
if (length < 2048 / sizeof(T))
#pragma warning restore 8500
{
return new T[length];
}
Expand Down Expand Up @@ -892,9 +890,7 @@ public static unsafe IReadOnlyDictionary<string, object> GetConfigurationVariabl
Configurations = new Dictionary<string, object>()
};

#pragma warning disable CS8500 // takes address of managed type
_EnumerateConfigurationValues(&context, &ConfigCallback);
#pragma warning restore CS8500
return context.Configurations!;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,7 @@ public override int GetHashCode() =>
throw new ArgumentException(SR.Arg_TypedReference_Null);

// Passing TypedReference by reference is easier to make correct in native code
#pragma warning disable CS8500 // Takes a pointer to a managed type
return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType?)DeclaringType);
#pragma warning restore CS8500
}

[DebuggerStepThrough]
Expand All @@ -111,9 +109,7 @@ public override void SetValueDirect(TypedReference obj, object value)
throw new ArgumentException(SR.Arg_TypedReference_Null);

// Passing TypedReference by reference is easier to make correct in native code
#pragma warning disable CS8500 // Takes a pointer to a managed type
RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType?)DeclaringType);
#pragma warning restore CS8500
}

public override RuntimeFieldHandle FieldHandle => new RuntimeFieldHandle(this);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,7 @@ private static IntPtr InternalAllocWithGCTransition(object? target, object? depe
// This optimization is the same that is used in GCHandle in RELEASE mode.
// This is not used in DEBUG builds as the runtime performs additional checks.
// The logic below is the inlined copy of ObjectFromHandle in the unmanaged runtime.
#pragma warning disable 8500 // address of managed types
private static unsafe object? InternalGetTarget(IntPtr dependentHandle) => *(object*)dependentHandle;
#pragma warning restore 8500
#endif

[MethodImpl(MethodImplOptions.InternalCall)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ internal static partial class InternalCalls
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ResumeAtInterceptionLocation")]
internal static unsafe partial void ResumeAtInterceptionLocation(void* pvRegDisplay);

#pragma warning disable CS8500
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "CallCatchFunclet")]
internal static unsafe partial IntPtr RhpCallCatchFunclet(
ObjectHandleOnStack exceptionObj, byte* pHandlerIP, void* pvRegDisplay, EH.ExInfo* exInfo);
Expand All @@ -38,7 +37,6 @@ internal static unsafe partial bool RhpCallFilterFunclet(

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "AppendExceptionStackFrame")]
internal static unsafe partial void RhpAppendExceptionStackFrame(ObjectHandleOnStack exceptionObj, IntPtr ip, UIntPtr sp, int flags, EH.ExInfo* exInfo);
#pragma warning restore CS8500

[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "EHEnumInitFromStackFrameIterator")]
[return: MarshalAs(UnmanagedType.Bool)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ private static void InternalFreeWithGCTransition(IntPtr dependentHandle)
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object? InternalGet(IntPtr handle);
#else
#pragma warning disable 8500 // address of managed types
internal static unsafe object? InternalGet(IntPtr handle) => *(object*)handle;
#pragma warning restore 8500
#endif

[MethodImpl(MethodImplOptions.InternalCall)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,6 @@ private static unsafe object[] InitializeStatics(IntPtr gcStaticRegionStart, int
nint blockAddr = MethodTable.SupportsRelativePointers ? (nint)ReadRelPtr32(pBlock) : *pBlock;
if ((blockAddr & GCStaticRegionConstants.Uninitialized) == GCStaticRegionConstants.Uninitialized)
{
#pragma warning disable CS8500 // takes address of managed type
object? obj = null;
RuntimeImports.RhAllocateNewObject(
new IntPtr(blockAddr & ~GCStaticRegionConstants.Mask),
Expand Down Expand Up @@ -234,7 +233,6 @@ private static unsafe object[] InitializeStatics(IntPtr gcStaticRegionStart, int

// Update the base pointer to point to the pinned object
*pBlock = *(IntPtr*)&obj;
#pragma warning restore CS8500
}

currentBase++;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ internal static unsafe class CachedInterfaceDispatch
private static unsafe IntPtr RhpCidResolve(IntPtr callerTransitionBlockParam, IntPtr pCell)
{
IntPtr locationOfThisPointer = callerTransitionBlockParam + TransitionBlock.GetThisOffset();
#pragma warning disable 8500 // address of managed types
object pObject = *(object*)locationOfThisPointer;
#pragma warning restore 8500
IntPtr dispatchResolveTarget = RhpCidResolve_Worker(pObject, pCell);
return dispatchResolveTarget;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -279,12 +279,11 @@ private static void AppendExceptionStackFrameViaClasslib(object exception, IntPt
isFirstFrame = false;
}
#else
#pragma warning disable CS8500
fixed (EH.ExInfo* pExInfo = &exInfo)
{
InternalCalls.RhpAppendExceptionStackFrame(ObjectHandleOnStack.Create(ref exception), ip, sp, flags, pExInfo);
}
#pragma warning restore CS8500

// Clear flags only if we called the function
isFirstRethrowFrame = false;
isFirstFrame = false;
Expand Down Expand Up @@ -686,13 +685,11 @@ public static void RhUnwindAndIntercept(ref ExInfo exInfo, UIntPtr interceptStac
if (unwoundReversePInvoke)
{
object exceptionObj = exInfo.ThrownException;
#pragma warning disable CS8500
fixed (EH.ExInfo* pExInfo = &exInfo)
{
InternalCalls.RhpCallCatchFunclet(
ObjectHandleOnStack.Create(ref exceptionObj), null, exInfo._frameIter.RegisterSet, pExInfo);
}
#pragma warning restore CS8500
}
else
{
Expand Down Expand Up @@ -922,13 +919,11 @@ private static void DispatchEx(scoped ref StackFrameIterator frameIter, ref ExIn
InternalCalls.RhpCallCatchFunclet(
exceptionObj, pCatchHandler, frameIter.RegisterSet, ref exInfo);
#else // NATIVEAOT
#pragma warning disable CS8500
fixed (EH.ExInfo* pExInfo = &exInfo)
{
InternalCalls.RhpCallCatchFunclet(
ObjectHandleOnStack.Create(ref exceptionObj), pCatchHandler, frameIter.RegisterSet, pExInfo);
}
#pragma warning restore CS8500
#endif // NATIVEAOT
// currently, RhpCallCatchFunclet will resume after the catch
Debug.Assert(false, "unreachable");
Expand Down Expand Up @@ -1209,12 +1204,10 @@ private static void InvokeSecondPass(ref ExInfo exInfo, uint idxStart, uint idxL
#if NATIVEAOT
InternalCalls.RhpCallFinallyFunclet(pFinallyHandler, exInfo._frameIter.RegisterSet);
#else // NATIVEAOT
#pragma warning disable CS8500
fixed (EH.ExInfo* pExInfo = &exInfo)
{
InternalCalls.RhpCallFinallyFunclet(pFinallyHandler, exInfo._frameIter.RegisterSet, pExInfo);
}
#pragma warning restore CS8500
#endif // NATIVEAOT
exInfo._idxCurClause = MaxTryRegionIdx;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -695,9 +695,7 @@ public static unsafe IReadOnlyDictionary<string, object> GetConfigurationVariabl
Configurations = new Dictionary<string, object>()
};

#pragma warning disable CS8500 // takes address of managed type
RuntimeImports.RhEnumerateConfigurationValues(&context, &ConfigCallback);
#pragma warning restore CS8500
return context.Configurations!;
}

Expand Down Expand Up @@ -810,9 +808,7 @@ public static unsafe T[] AllocateUninitializedArray<T>(int length, bool pinned =
// for debug builds we always want to call AllocateNewArray to detect AllocateNewArray bugs
#if !DEBUG
// small arrays are allocated using `new[]` as that is generally faster.
#pragma warning disable 8500 // sizeof of managed types
if (length < 2048 / sizeof(T))
#pragma warning restore 8500
{
return new T[length];
}
Expand All @@ -832,9 +828,7 @@ static T[] AllocateNewUninitializedArray(int length, bool pinned)
throw new OverflowException();

T[]? array = null;
#pragma warning disable CS8500 // takes address of managed type
RuntimeImports.RhAllocateNewArray(MethodTable.Of<T[]>(), (uint)length, (uint)flags, &array);
#pragma warning restore CS8500
if (array == null)
throw new OutOfMemoryException();

Expand All @@ -861,9 +855,7 @@ public static unsafe T[] AllocateArray<T>(int length, bool pinned = false)
throw new OverflowException();

T[]? array = null;
#pragma warning disable CS8500 // takes address of managed type
RuntimeImports.RhAllocateNewArray(MethodTable.Of<T[]>(), (uint)length, (uint)flags, &array);
#pragma warning restore CS8500
if (array == null)
throw new OutOfMemoryException();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -365,9 +365,7 @@ public unsafe DynamicInvokeInfo(MethodBase method, IntPtr invokeThunk)
else if (argCount == 1)
{
ByReference br = ByReference.Create(ref parameters[0]);
#pragma warning disable CS8500
void* pByrefStorage = &br;
#pragma warning restore CS8500

// Since no copy of args is required, pass 'parameters' for both arguments.
CheckArguments(parameters, pByrefStorage, parameters);
Expand Down Expand Up @@ -410,9 +408,7 @@ private unsafe ref byte InvokeWithManyArguments(
IntPtr* pStorage = stackalloc IntPtr[2 * argCount];
NativeMemory.Clear(pStorage, (nuint)(2 * argCount) * (nuint)sizeof(IntPtr));

#pragma warning disable 8500
void* pByRefStorage = (ByReference*)(pStorage + argCount);
#pragma warning restore 8500

GCFrameRegistration regArgStorage = new((void**)pStorage, (uint)argCount, areByRefs: false);
GCFrameRegistration regByRefStorage = new((void**)pByRefStorage, (uint)argCount, areByRefs: true);
Expand Down Expand Up @@ -461,9 +457,7 @@ private unsafe ref byte InvokeWithManyArguments(
IntPtr* pStorage = stackalloc IntPtr[2 * argCount];
NativeMemory.Clear(pStorage, (nuint)(2 * argCount) * (nuint)sizeof(IntPtr));

#pragma warning disable 8500
void* pByRefStorage = (ByReference*)(pStorage + argCount);
#pragma warning restore 8500

GCFrameRegistration regArgStorage = new((void**)pStorage, (uint)argCount, areByRefs: false);
GCFrameRegistration regByRefStorage = new((void**)pByRefStorage, (uint)argCount, areByRefs: true);
Expand Down Expand Up @@ -501,9 +495,7 @@ private unsafe ref byte InvokeWithFewArguments(
StackAllocatedArguments argStorage = default;
Span<object?> copyOfParameters = ((Span<object?>)argStorage._args).Slice(0, _argumentCount);
StackAllocatedByRefs byrefStorage = default;
#pragma warning disable CS8500
void* pByRefStorage = (ByReference*)&byrefStorage;
#pragma warning restore CS8500

CheckArguments(copyOfParameters, pByRefStorage, parameters, binderBundle);

Expand Down Expand Up @@ -535,9 +527,7 @@ private unsafe ref byte InvokeWithFewArguments(
StackAllocatedArguments argStorage = default;
Span<object?> copyOfParameters = ((Span<object?>)argStorage._args).Slice(0, _argumentCount);
StackAllocatedByRefs byrefStorage = default;
#pragma warning disable CS8500
void* pByRefStorage = (ByReference*)&byrefStorage;
#pragma warning restore CS8500

CheckArguments(copyOfParameters, pByRefStorage, parameters);

Expand All @@ -562,9 +552,7 @@ private unsafe ref byte InvokeDirectWithFewArguments(
Debug.Assert(_argumentCount <= MaxStackAllocArgCount);

StackAllocatedByRefs byrefStorage = default;
#pragma warning disable CS8500
void* pByRefStorage = (ByReference*)&byrefStorage;
#pragma warning restore CS8500

// Since no copy of args is required, pass 'parameters' for both arguments.
CheckArguments(parameters, pByRefStorage, parameters);
Expand Down Expand Up @@ -686,10 +674,10 @@ private unsafe void CheckArguments(

copyOfParameters[i] = arg!;

#pragma warning disable 8500, 9094
#pragma warning disable 9094
((ByReference*)byrefParameters)[i] = new ByReference(ref (argumentInfo.Transform & Transform.Reference) != 0 ?
ref Unsafe.As<object?, byte>(ref copyOfParameters[i]) : ref arg.GetRawData());
#pragma warning restore 8500, 9094
#pragma warning restore 9094
}
}

Expand Down Expand Up @@ -763,10 +751,10 @@ private unsafe void CheckArguments(

copyOfParameters[i] = arg;

#pragma warning disable 8500, 9094
#pragma warning disable 9094
((ByReference*)byrefParameters)[i] = new ByReference(ref (argumentInfo.Transform & Transform.Reference) != 0 ?
ref Unsafe.As<object?, byte>(ref copyOfParameters[i]) : ref arg.GetRawData());
#pragma warning restore 8500, 9094
#pragma warning restore 9094
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

#pragma warning disable CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type

namespace System.Reflection
{
public abstract class EnumInfo
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -429,10 +429,8 @@ static ManagedObjectWrapperHolder()
private static bool IsRootedCallback(IntPtr pObj)
{
// We are paused in the GC, so this is safe.
#pragma warning disable CS8500 // Takes a pointer to a managed type
ManagedObjectWrapperHolder* holder = (ManagedObjectWrapperHolder*)&pObj;
return holder->_wrapper->IsRooted;
#pragma warning restore CS8500
}

private readonly ManagedObjectWrapper* _wrapper;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,9 +260,7 @@ ptr is string ||

// Compat note: CLR wouldn't bother with a range check. If someone does this,
// they're likely taking dependency on some CLR implementation detail quirk.
#pragma warning disable 8500 // sizeof of managed types
ArgumentOutOfRangeException.ThrowIfGreaterThan(checked(ofs + sizeof(T)), size, nameof(ofs));
#pragma warning restore 8500

IntPtr nativeBytes = AllocCoTaskMem(size);
NativeMemory.Clear((void*)nativeBytes, (nuint)size);
Expand Down Expand Up @@ -340,9 +338,7 @@ ptr is string ||

// Compat note: CLR wouldn't bother with a range check. If someone does this,
// they're likely taking dependency on some CLR implementation detail quirk.
#pragma warning disable 8500 // sizeof of managed types
ArgumentOutOfRangeException.ThrowIfGreaterThan(checked(ofs + sizeof(T)), size, nameof(ofs));
#pragma warning restore 8500

IntPtr nativeBytes = AllocCoTaskMem(size);
NativeMemory.Clear((void*)nativeBytes, (nuint)size);
Expand Down
2 changes: 0 additions & 2 deletions src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -350,11 +350,9 @@ private CompilationResult CompileMethodInternal(IMethodNode methodCodeNodeNeedin
IntPtr exception;
IntPtr nativeEntry;
uint codeSize;
#pragma warning disable CS8500 // takes address of managed type
var result = JitCompileMethod(out exception,
_jit, (IntPtr)(&_this), _unmanagedCallbacks,
ref methodInfo, (uint)CorJitFlag.CORJIT_FLAG_CALL_GETJITFLAGS, out nativeEntry, out codeSize);
#pragma warning restore CS8500
if (exception != IntPtr.Zero)
{
if (_lastException != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<!-- ILSpy requires this assembly to target netstandard2.0 -->
<TargetFramework>netstandard2.0</TargetFramework>
<CLSCompliant>false</CLSCompliant>
<NoWarn>8002,NU1701</NoWarn>
<NoWarn>$(NoWarn);8002;NU1701</NoWarn>
<RuntimeIdentifiers>win-x64;win-x86</RuntimeIdentifiers>
<OutputPath>$(RuntimeBinDir)</OutputPath>
<Platforms>AnyCPU;x64</Platforms>
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/tools/r2rdump/R2RDump.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<IsDotNetFrameworkProductAssembly>true</IsDotNetFrameworkProductAssembly>
<TargetFramework>$(NetCoreAppToolCurrent)</TargetFramework>
<CLSCompliant>false</CLSCompliant>
<NoWarn>8002,NU1701</NoWarn>
<NoWarn>$(NoWarn);8002;NU1701</NoWarn>
<RuntimeIdentifiers>win-x64;win-x86</RuntimeIdentifiers>
<OutputPath>$(RuntimeBinDir)/R2RDump</OutputPath>
<RunAnalyzers>false</RunAnalyzers>
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/tools/r2rtest/R2RTest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<OutputType>Exe</OutputType>
<TargetFramework>$(NetCoreAppToolCurrent)</TargetFramework>
<NoWarn>8002,NU1701</NoWarn>
<NoWarn>$(NoWarn);8002;NU1701</NoWarn>
<PlatformTarget>AnyCPU</PlatformTarget>
<OutputPath>$(RuntimeBinDir)\R2RTest</OutputPath>
<RunAnalyzers>false</RunAnalyzers>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
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 Down
2 changes: 0 additions & 2 deletions src/libraries/Common/src/System/HexConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,8 @@ public static unsafe string ToString(ReadOnlySpan<byte> bytes, Casing casing = C
}
return result.ToString();
#else
#pragma warning disable CS8500 // takes address of managed type
return string.Create(bytes.Length * 2, (RosPtr: (IntPtr)(&bytes), casing), static (chars, args) =>
EncodeToUtf16(*(ReadOnlySpan<byte>*)args.RosPtr, chars, args.casing));
#pragma warning restore CS8500
#endif
}

Expand Down
Loading

0 comments on commit 19f0385

Please sign in to comment.