Fix numeric IntPtr behavioral changes analyzer findings (#75557)
authorBuyaa Namnan <bunamnan@microsoft.com>
Wed, 5 Oct 2022 00:26:05 +0000 (17:26 -0700)
committerGitHub <noreply@github.com>
Wed, 5 Oct 2022 00:26:05 +0000 (17:26 -0700)
Co-authored-by: Jan Kotas <jkotas@microsoft.com>
Co-authored-by: Tanner Gooding <tagoo@outlook.com>
77 files changed:
eng/CodeAnalysis.src.globalconfig
eng/CodeAnalysis.test.globalconfig
src/coreclr/System.Private.CoreLib/src/System/ArgIterator.cs
src/coreclr/System.Private.CoreLib/src/System/GC.CoreCLR.cs
src/coreclr/System.Private.CoreLib/src/System/MulticastDelegate.cs
src/coreclr/System.Private.CoreLib/src/System/Reflection/MdImport.cs
src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs
src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs
src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs
src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.cs
src/coreclr/nativeaot/System.Private.CoreLib/src/System/Exception.NativeAot.cs
src/coreclr/nativeaot/System.Private.CoreLib/src/System/GC.NativeAot.cs
src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Timer.Windows.cs
src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Win32ThreadPoolBoundHandle.cs
src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/GenericDictionaryCell.cs
src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs
src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs
src/coreclr/tools/aot/ILCompiler.RyuJit/JitInterface/CorInfoImpl.RyuJit.cs
src/libraries/Common/src/Interop/BSD/System.Native/Interop.Sysctl.cs
src/libraries/Common/src/Interop/FreeBSD/Interop.Process.GetProcInfo.cs
src/libraries/Common/src/Interop/FreeBSD/Interop.Process.cs
src/libraries/Common/src/Interop/Windows/Kernel32/Interop.Timer.cs
src/libraries/Common/src/Interop/Windows/NtDll/Interop.SYSTEM_PROCESS_INFORMATION.cs
src/libraries/Common/src/Interop/Windows/WinSock/Interop.GetAddrInfoExW.cs
src/libraries/Common/src/Interop/Windows/WinSock/Interop.GetAddrInfoW.cs
src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs
src/libraries/Microsoft.Win32.SystemEvents/src/Microsoft/Win32/SystemEvents.cs
src/libraries/System.Data.Odbc/src/Common/System/Data/Common/AdapterUtil.Odbc.cs
src/libraries/System.Data.Odbc/src/Common/System/Data/Common/SafeNativeMethods.cs
src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs
src/libraries/System.Data.OleDb/src/ColumnBinding.cs
src/libraries/System.Data.OleDb/src/DbBindings.cs
src/libraries/System.Data.OleDb/src/DbPropSet.cs
src/libraries/System.Data.OleDb/src/OleDbCommand.cs
src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs
src/libraries/System.Data.OleDb/src/OleDbDataReader.cs
src/libraries/System.Data.OleDb/src/OleDbEnumerator.cs
src/libraries/System.Data.OleDb/src/OleDbParameter.cs
src/libraries/System.Data.OleDb/src/OleDbStruct.cs
src/libraries/System.Data.OleDb/src/OleDb_Enum.cs
src/libraries/System.Data.OleDb/src/OleDb_Util.cs
src/libraries/System.Data.OleDb/src/PropertyIDSet.cs
src/libraries/System.Data.OleDb/src/PropertyInfoSet.cs
src/libraries/System.Data.OleDb/src/RowBinding.cs
src/libraries/System.Data.OleDb/src/SafeHandles.cs
src/libraries/System.Data.OleDb/src/SafeNativeMethods.cs
src/libraries/System.Data.OleDb/src/System/Data/Common/AdapterUtil.cs
src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbBuffer.cs
src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedPerformanceCounter.cs
src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs
src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.OSX.cs
src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs
src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.cs
src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ThreadInfo.cs
src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs
src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs
src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs
src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ColorPalette.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameters.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageAttributes.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs
src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/Interop.Windows.cs
src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs
src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeClientStream.cs
src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipePayloadDecoder.cs
src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs
src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs
src/libraries/System.Private.CoreLib/src/System/Threading/Interlocked.cs
src/libraries/System.Private.CoreLib/src/System/Threading/Volatile.cs
src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Interop/LegacyExports.cs
src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSHostImplementation.cs
src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.References.cs
src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs
src/libraries/System.Speech/src/Internal/StreamMarshaler.cs
src/libraries/System.Speech/src/Internal/Synthesis/EngineSiteSapi.cs
src/libraries/System.Speech/src/Result/RecognizedPhrase.cs

index 7b6e68e..e97722c 100644 (file)
@@ -456,6 +456,9 @@ dotnet_diagnostic.CA2018.severity = warning
 # CA2019: Improper 'ThreadStatic' field initialization
 dotnet_diagnostic.CA2019.severity = warning
 
+# CA2020: Prevent behavioral changes
+dotnet_diagnostic.CA2020.severity = warning
+
 # CA2100: Review SQL queries for security vulnerabilities
 dotnet_diagnostic.CA2100.severity = none
 
index 8f22c48..31bb97d 100644 (file)
@@ -453,6 +453,9 @@ dotnet_diagnostic.CA2018.severity = none
 # CA2019: Improper 'ThreadStatic' field initialization
 dotnet_diagnostic.CA2019.severity = none
 
+# CA2020: Prevent behavioral changes
+dotnet_diagnostic.CA2020.severity = none
+
 # CA2100: Review SQL queries for security vulnerabilities
 dotnet_diagnostic.CA2100.severity = none
 
index 37a7599..530f26c 100644 (file)
@@ -123,7 +123,7 @@ namespace System
 
         public override int GetHashCode()
         {
-            return RuntimeHelpers.GetHashCodeOfPtr(ArgCookie);
+            return HashCode.Combine(ArgCookie);
         }
 
         // Inherited from object
index b965a4c..bfb289a 100644 (file)
@@ -781,7 +781,7 @@ namespace System
 
                 case GCConfigurationType.StringUtf8:
                     {
-                        string? dataAsString = Marshal.PtrToStringUTF8((IntPtr)data);
+                        string? dataAsString = Marshal.PtrToStringUTF8((nint)data);
                         configurationDictionary[nameAsString] = dataAsString ?? string.Empty;
                         break;
                     }
index 4746430..e7e016e 100644 (file)
@@ -18,7 +18,7 @@ namespace System
         // 1. Multicast delegate
         // 2. Wrapper delegate
         private object? _invocationList; // Initialized by VM as needed
-        private IntPtr _invocationCount;
+        private nint _invocationCount;
 
         // This constructor is called from the class generated by the
         //    compiler generated code (This must match the constructor
@@ -37,7 +37,7 @@ namespace System
 
         internal bool IsUnmanagedFunctionPtr()
         {
-            return _invocationCount == (IntPtr)(-1);
+            return _invocationCount == -1;
         }
 
         internal bool InvocationListLogicallyNull()
@@ -67,7 +67,7 @@ namespace System
             Debug.Assert(obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!");
             MulticastDelegate d = Unsafe.As<MulticastDelegate>(obj);
 
-            if (_invocationCount != (IntPtr)0)
+            if (_invocationCount != 0)
             {
                 // there are 4 kind of delegate kinds that fall into this bucket
                 // 1- Multicast (_invocationList is Object[])
@@ -194,7 +194,7 @@ namespace System
             }
             result._target = result;
             result._invocationList = invocationList;
-            result._invocationCount = (IntPtr)invocationCount;
+            result._invocationCount = invocationCount;
 
             return result;
         }
@@ -206,7 +206,7 @@ namespace System
 
         internal void StoreDynamicMethod(MethodInfo dynamicMethod)
         {
-            if (_invocationCount != (IntPtr)0)
+            if (_invocationCount != 0)
             {
                 Debug.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined");
                 // must be a secure/wrapper one, unwrap and save
@@ -460,9 +460,9 @@ namespace System
         public sealed override int GetHashCode()
         {
             if (IsUnmanagedFunctionPtr())
-                return RuntimeHelpers.GetHashCodeOfPtr(_methodPtr) ^ RuntimeHelpers.GetHashCodeOfPtr(_methodPtrAux);
+                return HashCode.Combine(_methodPtr, _methodPtrAux);
 
-            if (_invocationCount != (IntPtr)0)
+            if (_invocationCount != 0)
             {
                 if (_invocationList is Delegate t)
                 {
@@ -489,7 +489,7 @@ namespace System
 
         internal override object? GetTarget()
         {
-            if (_invocationCount != (IntPtr)0)
+            if (_invocationCount != 0)
             {
                 // _invocationCount != 0 we are in one of these cases:
                 // - Multicast -> return the target of the last delegate in the list
@@ -520,7 +520,7 @@ namespace System
 
         protected override MethodInfo GetMethodImpl()
         {
-            if (_invocationCount != (IntPtr)0 && _invocationList != null)
+            if (_invocationCount != 0 && _invocationList != null)
             {
                 // multicast case
                 if (_invocationList is object[] invocationList)
index f945f3c..b0f4f8a 100644 (file)
@@ -206,7 +206,7 @@ namespace System.Reflection
 
         public override int GetHashCode()
         {
-            return RuntimeHelpers.GetHashCodeOfPtr(m_metadataImport2);
+            return HashCode.Combine(m_metadataImport2);
         }
 
         public override bool Equals(object? obj)
index 9465e62..31fc4aa 100644 (file)
@@ -14,8 +14,6 @@ namespace System.Runtime.CompilerServices
 {
     public static partial class RuntimeHelpers
     {
-        private static int s_pointerHashSeed;
-
         [Intrinsic]
         [MethodImpl(MethodImplOptions.InternalCall)]
         public static extern void InitializeArray(Array array, RuntimeFieldHandle fldHandle);
@@ -400,31 +398,6 @@ namespace System.Runtime.CompilerServices
 
         [MethodImpl(MethodImplOptions.InternalCall)]
         internal static extern unsafe void UnregisterForGCReporting(GCFrameRegistration* pRegistration);
-
-        internal static int GetHashCodeOfPtr(IntPtr ptr)
-        {
-            int hashCode = (int)ptr;
-
-            if (hashCode == 0)
-            {
-                return 0;
-            }
-
-            int seed = s_pointerHashSeed;
-
-            // Initialize s_pointerHashSeed lazily
-            if (seed == 0)
-            {
-                // We use the first non-0 pointer as the seed, all hashcodes will be based off that.
-                // This is to make sure that we only reveal relative memory addresses and never absolute ones.
-                seed = hashCode;
-                Interlocked.CompareExchange(ref s_pointerHashSeed, seed, 0);
-                seed = s_pointerHashSeed;
-            }
-
-            Debug.Assert(s_pointerHashSeed != 0);
-            return hashCode - seed;
-        }
     }
     // Helper class to assist with unsafe pinning of arbitrary objects.
     // It's used by VM code.
index 4b8846c..1959209 100644 (file)
@@ -873,7 +873,7 @@ namespace System
 
         public override int GetHashCode()
         {
-            return RuntimeHelpers.GetHashCodeOfPtr(Value);
+            return HashCode.Combine(Value);
         }
 
         public override bool Equals(object? obj)
@@ -1225,7 +1225,7 @@ namespace System
 
         public override int GetHashCode()
         {
-            return RuntimeHelpers.GetHashCodeOfPtr(Value);
+            return HashCode.Combine(Value);
         }
 
         public override bool Equals(object? obj)
index bc731b6..f00e69d 100644 (file)
@@ -382,7 +382,7 @@ namespace System.StubHelpers
         {
             if (IntPtr.Zero != pNative)
             {
-                Marshal.FreeCoTaskMem((IntPtr)(((long)pNative) - sizeof(uint)));
+                Marshal.FreeCoTaskMem(pNative - sizeof(uint));
             }
         }
     }  // class VBByValStrMarshaler
index bb89c0e..f2c9c29 100644 (file)
@@ -43,7 +43,7 @@ namespace System
 
         internal object m_firstParameter;
         internal object m_helperObject;
-        internal IntPtr m_extraFunctionPointerOrData;
+        internal nint m_extraFunctionPointerOrData;
         internal IntPtr m_functionPointer;
 
         // WARNING: These constants are also declared in System.Private.TypeLoader\Internal\Runtime\TypeLoader\CallConverterThunk.cs
@@ -100,7 +100,7 @@ namespace System
                 isInterpreterEntrypoint = true;
                 return IntPtr.Zero;
             }
-            else if (m_extraFunctionPointerOrData != IntPtr.Zero)
+            else if (m_extraFunctionPointerOrData != 0)
             {
                 if (GetThunk(OpenInstanceThunk) == m_functionPointer)
                 {
index f454f6a..bc2261b 100644 (file)
@@ -237,7 +237,7 @@ namespace System
                 {
                     SERIALIZED_EXCEPTION_HEADER* pHeader = (SERIALIZED_EXCEPTION_HEADER*)pBuffer;
                     pHeader->HResult = _HResult;
-                    pHeader->ExceptionEEType = (IntPtr)this.GetMethodTable();
+                    pHeader->ExceptionEEType = (nint)this.GetMethodTable();
                     pHeader->StackTraceElementCount = nStackTraceElements;
                     IntPtr* pStackTraceElements = (IntPtr*)(pBuffer + sizeof(SERIALIZED_EXCEPTION_HEADER));
                     for (int i = 0; i < nStackTraceElements; i++)
index 8e0e523..eff2963 100644 (file)
@@ -623,7 +623,7 @@ namespace System
 
                 case RuntimeImports.GCConfigurationType.StringUtf8:
                     {
-                        string? dataAsString = Marshal.PtrToStringUTF8((IntPtr)data);
+                        string? dataAsString = Marshal.PtrToStringUTF8((nint)data);
                         configurationDictionary[nameAsString] = dataAsString ?? string.Empty;
                         break;
                     }
index 1e2cc88..1f11b66 100644 (file)
@@ -22,7 +22,7 @@ namespace System.Threading
         }
 
         [UnmanagedCallersOnly]
-        private static void TimerCallback(IntPtr instance, IntPtr context, IntPtr timer)
+        private static unsafe void TimerCallback(void* instance, void* context, void* timer)
         {
             int id = (int)context;
             var wrapper = ThreadPoolCallbackWrapper.Enter();
index e1a3ea3..bdabf72 100644 (file)
@@ -167,7 +167,7 @@ namespace System.Threading
         }
 
         [UnmanagedCallersOnly]
-        private static unsafe void OnNativeIOCompleted(IntPtr instance, IntPtr context, IntPtr overlappedPtr, uint ioResult, UIntPtr numberOfBytesTransferred, IntPtr ioPtr)
+        private static unsafe void OnNativeIOCompleted(IntPtr instance, IntPtr context, IntPtr overlappedPtr, uint ioResult, nuint numberOfBytesTransferred, IntPtr ioPtr)
         {
             var wrapper = ThreadPoolCallbackWrapper.Enter();
             Win32ThreadPoolNativeOverlapped* overlapped = (Win32ThreadPoolNativeOverlapped*)overlappedPtr;
index 1d4b84a..181f525 100644 (file)
@@ -586,7 +586,7 @@ namespace Internal.Runtime.TypeLoader
 
         private class IntPtrCell : GenericDictionaryCell
         {
-            internal IntPtr Value;
+            internal nint Value;
             internal override unsafe void Prepare(TypeBuilder builder)
             {
             }
index 05ca315..0166a9f 100644 (file)
@@ -538,7 +538,7 @@ namespace Internal.JitInterface
                 }
             }
 #else
-            var methodIL = (MethodIL)HandleToObject((IntPtr)_methodScope);
+            var methodIL = (MethodIL)HandleToObject((void*)_methodScope);
             CodeBasedDependencyAlgorithm.AddDependenciesDueToMethodCodePresence(ref _additionalDependencies, _compilation.NodeFactory, MethodBeingCompiled, methodIL);
             _methodCodeNode.InitializeNonRelocationDependencies(_additionalDependencies);
             _methodCodeNode.InitializeDebugInfo(_debugInfo);
@@ -682,24 +682,24 @@ namespace Internal.JitInterface
             return handle;
         }
 
-        private object HandleToObject(IntPtr handle)
+        private object HandleToObject(void* handle)
         {
 #if DEBUG
-            handle = new IntPtr(~(long)s_handleHighBitSet & (long) handle);
+            handle = (void*)(~s_handleHighBitSet & (nint)handle);
 #endif
             int index = ((int)handle - handleBase) / handleMultiplier;
             return _handleToObject[index];
         }
 
-        private MethodDesc HandleToObject(CORINFO_METHOD_STRUCT_* method) => (MethodDesc)HandleToObject((IntPtr)method);
+        private MethodDesc HandleToObject(CORINFO_METHOD_STRUCT_* method) => (MethodDesc)HandleToObject((void*)method);
         private CORINFO_METHOD_STRUCT_* ObjectToHandle(MethodDesc method) => (CORINFO_METHOD_STRUCT_*)ObjectToHandle((object)method);
-        private TypeDesc HandleToObject(CORINFO_CLASS_STRUCT_* type) => (TypeDesc)HandleToObject((IntPtr)type);
+        private TypeDesc HandleToObject(CORINFO_CLASS_STRUCT_* type) => (TypeDesc)HandleToObject((void*)type);
         private CORINFO_CLASS_STRUCT_* ObjectToHandle(TypeDesc type) => (CORINFO_CLASS_STRUCT_*)ObjectToHandle((object)type);
-        private FieldDesc HandleToObject(CORINFO_FIELD_STRUCT_* field) => (FieldDesc)HandleToObject((IntPtr)field);
+        private FieldDesc HandleToObject(CORINFO_FIELD_STRUCT_* field) => (FieldDesc)HandleToObject((void*)field);
         private CORINFO_FIELD_STRUCT_* ObjectToHandle(FieldDesc field) => (CORINFO_FIELD_STRUCT_*)ObjectToHandle((object)field);
-        private MethodILScope HandleToObject(CORINFO_MODULE_STRUCT_* module) => (MethodIL)HandleToObject((IntPtr)module);
+        private MethodILScope HandleToObject(CORINFO_MODULE_STRUCT_* module) => (MethodIL)HandleToObject((void*)module);
         private CORINFO_MODULE_STRUCT_* ObjectToHandle(MethodILScope methodIL) => (CORINFO_MODULE_STRUCT_*)ObjectToHandle((object)methodIL);
-        private MethodSignature HandleToObject(MethodSignatureInfo* method) => (MethodSignature)HandleToObject((IntPtr)method);
+        private MethodSignature HandleToObject(MethodSignatureInfo* method) => (MethodSignature)HandleToObject((void*)method);
         private MethodSignatureInfo* ObjectToHandle(MethodSignature method) => (MethodSignatureInfo*)ObjectToHandle((object)method);
 
         private bool Get_CORINFO_METHOD_INFO(MethodDesc method, MethodIL methodIL, CORINFO_METHOD_INFO* methodInfo)
@@ -914,12 +914,12 @@ namespace Internal.JitInterface
 
         private CORINFO_CONTEXT_STRUCT* contextFromMethod(MethodDesc method)
         {
-            return (CORINFO_CONTEXT_STRUCT*)(((ulong)ObjectToHandle(method)) | (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_METHOD);
+            return (CORINFO_CONTEXT_STRUCT*)(((nuint)ObjectToHandle(method)) | (nuint)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_METHOD);
         }
 
         private CORINFO_CONTEXT_STRUCT* contextFromType(TypeDesc type)
         {
-            return (CORINFO_CONTEXT_STRUCT*)(((ulong)ObjectToHandle(type)) | (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS);
+            return (CORINFO_CONTEXT_STRUCT*)(((nuint)ObjectToHandle(type)) | (nuint)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS);
         }
 
         private static CORINFO_CONTEXT_STRUCT* contextFromMethodBeingCompiled()
@@ -934,13 +934,13 @@ namespace Internal.JitInterface
                 return MethodBeingCompiled;
             }
 
-            if (((ulong)contextStruct & (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK) == (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS)
+            if (((nuint)contextStruct & (nuint)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK) == (nuint)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS)
             {
                 return null;
             }
             else
             {
-                return HandleToObject((CORINFO_METHOD_STRUCT_*)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK));
+                return HandleToObject((CORINFO_METHOD_STRUCT_*)((nuint)contextStruct & ~(nuint)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK));
             }
         }
 
@@ -951,13 +951,13 @@ namespace Internal.JitInterface
                 return MethodBeingCompiled.OwningType;
             }
 
-            if (((ulong)contextStruct & (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK) == (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS)
+            if (((nuint)contextStruct & (nuint)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK) == (nuint)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS)
             {
-                return HandleToObject((CORINFO_CLASS_STRUCT_*)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK));
+                return HandleToObject((CORINFO_CLASS_STRUCT_*)((nuint)contextStruct & ~(nuint)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK));
             }
             else
             {
-                return HandleToObject((CORINFO_METHOD_STRUCT_*)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK)).OwningType;
+                return HandleToObject((CORINFO_METHOD_STRUCT_*)((nuint)contextStruct & ~(nuint)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK)).OwningType;
             }
         }
 
@@ -968,7 +968,7 @@ namespace Internal.JitInterface
                 return MethodBeingCompiled.HasInstantiation ? (TypeSystemEntity)MethodBeingCompiled: (TypeSystemEntity)MethodBeingCompiled.OwningType;
             }
 
-            return (TypeSystemEntity)HandleToObject((IntPtr)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK));
+            return (TypeSystemEntity)HandleToObject((void*)((nuint)contextStruct & ~(nuint)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK));
         }
 
         private bool isIntrinsic(CORINFO_METHOD_STRUCT_* ftn)
@@ -1607,7 +1607,7 @@ namespace Internal.JitInterface
             var methodIL = HandleToObject(pResolvedToken.tokenScope);
 
             var typeOrMethodContext = (pResolvedToken.tokenContext == contextFromMethodBeingCompiled()) ?
-                MethodBeingCompiled : HandleToObject((IntPtr)pResolvedToken.tokenContext);
+                MethodBeingCompiled : HandleToObject((void*)pResolvedToken.tokenContext);
 
             object result = GetRuntimeDeterminedObjectForToken(methodIL, typeOrMethodContext, pResolvedToken.token);
             if (pResolvedToken.tokenType == CorInfoTokenKind.CORINFO_TOKENKIND_Newarr)
@@ -1661,7 +1661,7 @@ namespace Internal.JitInterface
             var methodIL = HandleToObject(pResolvedToken.tokenScope);
 
             var typeOrMethodContext = (pResolvedToken.tokenContext == contextFromMethodBeingCompiled()) ?
-                MethodBeingCompiled : HandleToObject((IntPtr)pResolvedToken.tokenContext);
+                MethodBeingCompiled : HandleToObject((void*)pResolvedToken.tokenContext);
 
             object result = ResolveTokenInScope(methodIL, typeOrMethodContext, pResolvedToken.token);
 
@@ -2908,7 +2908,7 @@ namespace Internal.JitInterface
         private CorInfoTypeWithMod getArgType(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args, CORINFO_CLASS_STRUCT_** vcTypeRet)
         {
             int index = (int)args;
-            object sigObj = HandleToObject((IntPtr)sig->methodSignature);
+            object sigObj = HandleToObject((void*)sig->methodSignature);
 
             MethodSignature methodSig = sigObj as MethodSignature;
 
@@ -2933,7 +2933,7 @@ namespace Internal.JitInterface
         private CORINFO_CLASS_STRUCT_* getArgClass(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args)
         {
             int index = (int)args;
-            object sigObj = HandleToObject((IntPtr)sig->methodSignature);
+            object sigObj = HandleToObject((void*)sig->methodSignature);
 
             MethodSignature methodSig = sigObj as MethodSignature;
             if (methodSig != null)
@@ -3632,7 +3632,7 @@ namespace Internal.JitInterface
 
                 default:
                     // Reloc points to something outside of the generated blocks
-                    var targetObject = HandleToObject((IntPtr)target);
+                    var targetObject = HandleToObject(target);
 
 #if READYTORUN
                     if (targetObject is RequiresRuntimeJitIfUsedSymbol requiresRuntimeSymbol)
@@ -3864,7 +3864,7 @@ namespace Internal.JitInterface
                     {
                         foreach (TypeSystemEntityOrUnknown typeVal in typeArray)
                         {
-                            IntPtr ptrVal;
+                            nint ptrVal;
 
                             if (typeVal.AsType != null && (typeFilter == null || typeFilter(typeVal.AsType)))
                             {
index 7b89e36..4a4e902 100644 (file)
@@ -2972,7 +2972,7 @@ namespace Internal.JitInterface
             if (_compilation.TypeSystemContext.Target.Architecture != TargetArchitecture.X64)
                 return;
 
-            object node = HandleToObject((IntPtr)entryPoint.addr);
+            object node = HandleToObject(entryPoint.addr);
             if (node is not DelayLoadMethodImport imp)
                 return;
 
index efc9c60..8a0e974 100644 (file)
@@ -340,7 +340,7 @@ namespace Internal.JitInterface
                         Debug.Assert(pGenericLookupKind.needsRuntimeLookup);
 
                         ReadyToRunHelperId helperId = (ReadyToRunHelperId)pGenericLookupKind.runtimeLookupFlags;
-                        object helperArg = HandleToObject((IntPtr)pGenericLookupKind.runtimeLookupArgs);
+                        object helperArg = HandleToObject(pGenericLookupKind.runtimeLookupArgs);
                         ISymbolNode helper = GetGenericLookupHelper(pGenericLookupKind.runtimeLookupKind, helperId, helperArg);
                         pLookup = CreateConstLookupToSymbol(helper);
                     }
@@ -375,7 +375,7 @@ namespace Internal.JitInterface
 
                 var methodIL = HandleToObject(pTargetMethod.tokenScope);
                 var typeOrMethodContext = (pTargetMethod.tokenContext == contextFromMethodBeingCompiled()) ?
-                    MethodBeingCompiled : HandleToObject((IntPtr)pTargetMethod.tokenContext);
+                    MethodBeingCompiled : HandleToObject((void*)pTargetMethod.tokenContext);
                 var canonConstrainedType = (TypeDesc)ResolveTokenInScope(methodIL, typeOrMethodContext, targetConstraint);
                 TypeDesc interfaceType = HandleToObject(pTargetMethod.hClass);
                 var interfaceMethod = (MethodDesc)ResolveTokenInScope(methodIL, typeOrMethodContext, pTargetMethod.token);
@@ -808,7 +808,7 @@ namespace Internal.JitInterface
 
         private InfoAccessType constructStringLiteral(CORINFO_MODULE_STRUCT_* module, mdToken metaTok, ref void* ppValue)
         {
-            MethodIL methodIL = (MethodIL)HandleToObject((IntPtr)module);
+            MethodIL methodIL = (MethodIL)HandleToObject((void*)module);
 
             ISymbolNode stringObject;
             if (metaTok == (mdToken)CorConstants.CorTokenType.mdtString)
@@ -905,7 +905,7 @@ namespace Internal.JitInterface
                         {
                             builder.EmitCompressedUInt(clause.HandlerOffset);
 
-                            var methodIL = (MethodIL)HandleToObject((IntPtr)_methodScope);
+                            var methodIL = (MethodIL)HandleToObject((void*)_methodScope);
                             var type = (TypeDesc)methodIL.GetObject((int)clause.ClassTokenOrOffset);
 
                             var typeSymbol = _compilation.NecessaryTypeSymbolIfPossible(type);
@@ -935,7 +935,7 @@ namespace Internal.JitInterface
 
         private void setVars(CORINFO_METHOD_STRUCT_* ftn, uint cVars, NativeVarInfo* vars)
         {
-            var methodIL = (MethodIL)HandleToObject((IntPtr)_methodScope);
+            var methodIL = (MethodIL)HandleToObject((void*)_methodScope);
 
             MethodSignature sig = methodIL.OwningMethod.Signature;
             int numLocals = methodIL.GetLocals().Length;
@@ -1132,7 +1132,7 @@ namespace Internal.JitInterface
 
             if (method.HasInstantiation || method.OwningType.HasInstantiation)
             {
-                MethodIL methodIL = (MethodIL)HandleToObject((IntPtr)pScope);
+                MethodIL methodIL = (MethodIL)HandleToObject((void*)pScope);
                 _compilation.DetectGenericCycles(methodIL.OwningMethod, method);
             }
 
@@ -1260,7 +1260,7 @@ namespace Internal.JitInterface
                     // The scanner won't be able to predict such inlinig. See https://github.com/dotnet/runtimelab/pull/489
                     !MethodBeingCompiled.HasInstantiation)
                 {
-                    var methodIL = (MethodIL)HandleToObject((IntPtr)pResolvedToken.tokenScope);
+                    var methodIL = (MethodIL)HandleToObject((void*)pResolvedToken.tokenScope);
                     var rawMethod = (MethodDesc)methodIL.GetMethodILDefinition().GetObject((int)pResolvedToken.token);
                     if (IsTypeSpecForTypicalInstantiation(rawMethod.OwningType))
                     {
@@ -1407,7 +1407,7 @@ namespace Internal.JitInterface
                     // If this is an intrinsic method with a callsite-specific expansion, this will replace
                     // the method with a method the intrinsic expands into. If it's not the special intrinsic,
                     // method stays unchanged.
-                    var methodIL = (MethodIL)HandleToObject((IntPtr)pResolvedToken.tokenScope);
+                    var methodIL = (MethodIL)HandleToObject((void*)pResolvedToken.tokenScope);
                     targetMethod = _compilation.ExpandIntrinsicForCallsite(targetMethod, methodIL.OwningMethod);
 
                     // For multidim array Address method, we pretend the method requires a hidden instantiation argument
@@ -1523,7 +1523,7 @@ namespace Internal.JitInterface
                 MethodDesc targetOfLookup = _compilation.GetTargetOfGenericVirtualMethodCall((MethodDesc)GetRuntimeDeterminedObjectForToken(ref pResolvedToken));
 
                 _compilation.DetectGenericCycles(
-                    ((MethodILScope)HandleToObject((IntPtr)pResolvedToken.tokenScope)).OwningMethod,
+                    ((MethodILScope)HandleToObject((void*)pResolvedToken.tokenScope)).OwningMethod,
                     targetOfLookup.GetCanonMethodTarget(CanonicalFormKind.Specific));
 
                 ComputeLookup(ref pResolvedToken,
@@ -1898,7 +1898,7 @@ namespace Internal.JitInterface
             if (handle == null)
             {
 #if DEBUG
-                MethodSignature methodSignature = (MethodSignature)HandleToObject((IntPtr)callSiteSig->pSig);
+                MethodSignature methodSignature = (MethodSignature)HandleToObject((void*)callSiteSig->pSig);
 
                 MethodDesc stub = _compilation.PInvokeILProvider.GetCalliStub(
                     methodSignature,
@@ -1926,7 +1926,7 @@ namespace Internal.JitInterface
 
         private bool convertPInvokeCalliToCall(ref CORINFO_RESOLVED_TOKEN pResolvedToken, bool mustConvert)
         {
-            var methodIL = (MethodIL)HandleToObject((IntPtr)pResolvedToken.tokenScope);
+            var methodIL = (MethodIL)HandleToObject((void*)pResolvedToken.tokenScope);
 
             // Suppress recursive expansion of calli in marshaling stubs
             if (methodIL is Internal.IL.Stubs.PInvokeILStubMethodIL)
index 8ea3d57..d158452 100644 (file)
@@ -32,7 +32,7 @@ internal static partial class Interop
 
         private static unsafe void Sysctl(int* name, int name_len, ref byte* value, ref int len)
         {
-            IntPtr bytesLength = (IntPtr)len;
+            nint bytesLength = len;
             int ret = -1;
             bool autoSize = (value == null && len == 0);
 
@@ -60,11 +60,11 @@ internal static partial class Interop
                 }
                 if ((int)bytesLength >= int.MaxValue / 2)
                 {
-                    bytesLength = (IntPtr)int.MaxValue;
+                    bytesLength = int.MaxValue;
                 }
                 else
                 {
-                    bytesLength = (IntPtr)((int)bytesLength * 2);
+                    bytesLength = (int)bytesLength * 2;
                 }
                 value = (byte*)Marshal.AllocHGlobal(bytesLength);
                 ret = Sysctl(name, name_len, value, &bytesLength);
index 2d1861e..ca25076 100644 (file)
@@ -52,8 +52,8 @@ internal static partial class Interop
         [StructLayout(LayoutKind.Sequential)]
         public struct @timeval
         {
-            public IntPtr tv_sec;
-            public IntPtr tv_usec;
+            public nint tv_sec;
+            public nint tv_usec;
         }
 
         [StructLayout(LayoutKind.Sequential)]
index 01e4f94..e61abfa 100644 (file)
@@ -136,7 +136,7 @@ internal static partial class Interop
                         _processId = pid,
                         _threadId = (ulong)process[i].ki_tid,
                         _basePriority = process[i].ki_nice,
-                        _startAddress = (IntPtr)process[i].ki_tdaddr
+                        _startAddress = process[i].ki_tdaddr
                     };
                     info._threadInfoList.Add(ti);
                 }
index 426e57c..9687398 100644 (file)
@@ -9,7 +9,7 @@ internal static partial class Interop
     internal static partial class Kernel32
     {
         [LibraryImport(Libraries.Kernel32)]
-        internal static unsafe partial IntPtr CreateThreadpoolTimer(delegate* unmanaged<IntPtr, IntPtr, IntPtr, void> pfnti, IntPtr pv, IntPtr pcbe);
+        internal static unsafe partial IntPtr CreateThreadpoolTimer(delegate* unmanaged<void*, void*, void*, void> pfnti, IntPtr pv, IntPtr pcbe);
 
         [LibraryImport(Libraries.Kernel32)]
         internal static unsafe partial IntPtr SetThreadpoolTimer(IntPtr pti, long* pftDueTime, uint msPeriod, uint msWindowLength);
index 428f2c2..eb8a393 100644 (file)
@@ -45,7 +45,7 @@ internal static partial class Interop
         {
             private fixed long Reserved1[3];
             private readonly uint Reserved2;
-            internal IntPtr StartAddress;
+            internal void* StartAddress;
             internal CLIENT_ID ClientId;
             internal int Priority;
             internal int BasePriority;
@@ -55,10 +55,10 @@ internal static partial class Interop
         }
 
         [StructLayout(LayoutKind.Sequential)]
-        internal struct CLIENT_ID
+        internal unsafe struct CLIENT_ID
         {
-            internal IntPtr UniqueProcess;
-            internal IntPtr UniqueThread;
+            internal void* UniqueProcess;
+            internal void* UniqueThread;
         }
     }
 }
index a0d6906..be6b7ca 100644 (file)
@@ -43,7 +43,7 @@ internal static partial class Interop
             internal AddressFamily ai_family;
             internal int ai_socktype;
             internal int ai_protocol;
-            internal IntPtr ai_addrlen;
+            internal nuint ai_addrlen;
             internal IntPtr ai_canonname;    // Ptr to the canonical name - check for NULL
             internal byte* ai_addr;          // Ptr to the sockaddr structure
             internal IntPtr ai_blob;         // Unused ptr to blob data about provider
index a1f93ba..76cb302 100644 (file)
@@ -26,7 +26,7 @@ internal static partial class Interop
             internal AddressFamily ai_family;
             internal int ai_socktype;
             internal int ai_protocol;
-            internal IntPtr ai_addrlen;
+            internal nuint ai_addrlen;
             internal sbyte* ai_canonname;   // Ptr to the canonical name - check for NULL
             internal byte* ai_addr;         // Ptr to the sockaddr structure
             internal AddressInfo* ai_next;  // Ptr to the next AddressInfo structure
index abe640e..f133f0d 100644 (file)
@@ -197,7 +197,7 @@ namespace Microsoft.Win32
         /// <returns>The RegistryKey requested.</returns>
         private static RegistryKey OpenBaseKeyCore(RegistryHive hKeyHive, RegistryView view)
         {
-            IntPtr hKey = (IntPtr)((int)hKeyHive);
+            nint hKey = (int)hKeyHive;
 
             int index = ((int)hKey) & 0x0FFFFFFF;
             Debug.Assert(index >= 0 && index < s_hkeyNames.Length, "index is out of range!");
index 3564737..3067cd0 100644 (file)
@@ -517,17 +517,17 @@ namespace Microsoft.Win32
             }
         }
 
-        private static UserPreferenceCategory GetUserPreferenceCategory(int msg, IntPtr wParam, IntPtr lParam)
+        private static UserPreferenceCategory GetUserPreferenceCategory(int msg, nint wParam, nint lParam)
         {
             UserPreferenceCategory pref = UserPreferenceCategory.General;
 
             if (msg == Interop.User32.WM_SETTINGCHANGE)
             {
-                if (lParam != IntPtr.Zero && Marshal.PtrToStringUni(lParam)!.Equals("Policy"))
+                if (lParam != 0 && Marshal.PtrToStringUni(lParam)!.Equals("Policy"))
                 {
                     pref = UserPreferenceCategory.Policy;
                 }
-                else if (lParam != IntPtr.Zero && Marshal.PtrToStringUni(lParam)!.Equals("intl"))
+                else if (lParam != 0 && Marshal.PtrToStringUni(lParam)!.Equals("intl"))
                 {
                     pref = UserPreferenceCategory.Locale;
                 }
@@ -808,7 +808,7 @@ namespace Microsoft.Win32
         ///  Callback that handles the create timer
         ///  user message.
         /// </summary>
-        private IntPtr OnCreateTimer(IntPtr wParam)
+        private IntPtr OnCreateTimer(nint wParam)
         {
             IntPtr timerId = (IntPtr)s_randomTimerId.Next();
             IntPtr res = Interop.User32.SetTimer(_windowHandle, timerId, (int)wParam, IntPtr.Zero);
@@ -856,7 +856,7 @@ namespace Microsoft.Win32
         /// <summary>
         ///  Handler for WM_POWERBROADCAST.
         /// </summary>
-        private void OnPowerModeChanged(IntPtr wParam)
+        private void OnPowerModeChanged(nint wParam)
         {
             PowerModes mode;
 
@@ -889,11 +889,11 @@ namespace Microsoft.Win32
         /// <summary>
         ///  Handler for WM_ENDSESSION.
         /// </summary>
-        private void OnSessionEnded(IntPtr wParam, IntPtr lParam)
+        private void OnSessionEnded(nint wParam, nint lParam)
         {
             // wParam will be nonzero if the session is actually ending.  If
             // it was canceled then we do not want to raise the event.
-            if (wParam != (IntPtr)0)
+            if (wParam != 0)
             {
                 SessionEndReasons reason = SessionEndReasons.SystemShutdown;
 
@@ -1126,14 +1126,14 @@ namespace Microsoft.Win32
         /// <summary>
         ///  A standard Win32 window proc for our broadcast window.
         /// </summary>
-        private IntPtr WindowProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam)
+        private IntPtr WindowProc(IntPtr hWnd, int msg, nint wParam, nint lParam)
         {
             switch (msg)
             {
                 case Interop.User32.WM_SETTINGCHANGE:
                     string? newString;
                     IntPtr newStringPtr = lParam;
-                    if (lParam != IntPtr.Zero)
+                    if (lParam != 0)
                     {
                         newString = Marshal.PtrToStringUni(lParam);
                         if (newString != null)
@@ -1173,7 +1173,7 @@ namespace Microsoft.Win32
                     {
                         try
                         {
-                            if (lParam != IntPtr.Zero)
+                            if (lParam != 0)
                             {
                                 Marshal.FreeHGlobal(lParam);
                             }
index fbe13f6..5be37ae 100644 (file)
@@ -658,12 +658,7 @@ namespace System.Data.Common
 
         internal static IntPtr IntPtrOffset(IntPtr pbase, int offset)
         {
-            if (4 == ADP.PtrSize)
-            {
-                return (IntPtr)checked(pbase.ToInt32() + offset);
-            }
-            Debug.Assert(8 == ADP.PtrSize, "8 != IntPtr.Size"); // MDAC 73747
-            return (IntPtr)checked(pbase.ToInt64() + offset);
+            return (nint)pbase + offset;
         }
     }
 }
index 7980064..713c692 100644 (file)
@@ -7,7 +7,7 @@ namespace System.Data
 {
     internal static partial class SafeNativeMethods
     {
-        internal static IntPtr LocalAlloc(IntPtr initialSize)
+        internal static IntPtr LocalAlloc(nint initialSize)
         {
             var handle = Marshal.AllocHGlobal(initialSize);
             ZeroMemory(handle, (int)initialSize);
index 88df3ca..5013c28 100644 (file)
@@ -1716,7 +1716,7 @@ namespace System.Data.Odbc
         /// <returns>false if value is DbNull, true otherwise</returns>
         private bool GetData(int i, ODBC32.SQL_C sqlctype, int cb, out int cbLengthOrIndicator)
         {
-            IntPtr cbActual;  // Length or an indicator value
+            nint cbActual;  // Length or an indicator value
 
             if (IsCancelingCommand)
             {
@@ -1769,7 +1769,7 @@ namespace System.Data.Odbc
                     if (cbActual == (IntPtr)ODBC32.SQL_NO_TOTAL)
                     {
                         // ensure SQL_NO_TOTAL value gets replaced with zero if the driver has fully consumed the current column
-                        cbActual = (IntPtr)0;
+                        cbActual = 0;
                     }
                     break;
 
@@ -2311,7 +2311,7 @@ namespace System.Data.Odbc
             string columnname;
             int ordinal;
             int keyColumns = 0;
-            IntPtr cbActual;
+            nint cbActual;
 
             if (IsClosed || (_cmdWrapper == null))
             {
@@ -2482,8 +2482,8 @@ namespace System.Data.Odbc
             bool partialcolumnset = false;
             int ordinal;
             int indexordinal;
-            IntPtr cbIndexLen;
-            IntPtr cbColnameLen;
+            nint cbIndexLen;
+            nint cbColnameLen;
             int keyColumns = 0;
 
             // devnote: this test is already done by calling method ...
index a55b6b9..05ccebd 100644 (file)
@@ -633,7 +633,7 @@ namespace System.Data.OleDb
             {
                 bindings.DangerousAddRef(ref mustRelease);
                 IntPtr ptr = bindings.ReadIntPtr(ValueOffset);
-                if (ADP.PtrZero != ptr)
+                if (IntPtr.Zero != ptr)
                 {
                     value = Marshal.PtrToStringBSTR(ptr);
                 }
@@ -668,7 +668,7 @@ namespace System.Data.OleDb
             {
                 bindings.DangerousAddRef(ref mustRelease);
                 IntPtr ptr = bindings.ReadIntPtr(ValueOffset);
-                if (ADP.PtrZero != ptr)
+                if (IntPtr.Zero != ptr)
                 {
                     value = new byte[LengthValue()];
                     Marshal.Copy(ptr, value, 0, value.Length);
@@ -694,7 +694,7 @@ namespace System.Data.OleDb
             LengthValue(((0 < ValueBindingSize) ? Math.Min(ValueBindingSize, length) : length));
             StatusValue(DBStatus.S_OK);
 
-            IntPtr ptr = ADP.PtrZero;
+            IntPtr ptr = IntPtr.Zero;
             if (0 < length)
             { // avoid pinning empty byte[]
                 _pinnedBuffer = GCHandle.Alloc(value, GCHandleType.Pinned);
@@ -716,7 +716,7 @@ namespace System.Data.OleDb
             {
                 bindings.DangerousAddRef(ref mustRelease);
                 IntPtr ptr = bindings.ReadIntPtr(ValueOffset);
-                if (ADP.PtrZero != ptr)
+                if (IntPtr.Zero != ptr)
                 {
                     int charCount = LengthValue() / 2;
                     value = Marshal.PtrToStringUni(ptr, charCount);
@@ -741,7 +741,7 @@ namespace System.Data.OleDb
             LengthValue(((0 < ValueBindingSize) ? Math.Min(ValueBindingSize, length) : length) * 2); /* charcount->bytecount*/
             StatusValue(DBStatus.S_OK);
 
-            IntPtr ptr = ADP.PtrZero;
+            IntPtr ptr = IntPtr.Zero;
             if (0 < length)
             { // avoid pinning empty string, i.e String.Empty
                 _pinnedBuffer = GCHandle.Alloc(value, GCHandleType.Pinned);
@@ -760,7 +760,7 @@ namespace System.Data.OleDb
             LengthValue(((0 < ValueBindingSize) ? Math.Min(ValueBindingSize, length) : length) * 2); /* charcount->bytecount*/
             StatusValue(DBStatus.S_OK);
 
-            IntPtr ptr = ADP.PtrZero;
+            IntPtr ptr = IntPtr.Zero;
             if (0 < length)
             { // avoid pinning empty char[]
                 _pinnedBuffer = GCHandle.Alloc(value, GCHandleType.Pinned);
index 63ef444..2575cfd 100644 (file)
@@ -179,10 +179,10 @@ namespace System.Data.OleDb
             {
                 Debug.Assert(0 <= value, "invalid MaxLen");
 
-                _dbbindings[_index].obStatus = (IntPtr)(_dataBufferSize + 0);
-                _dbbindings[_index].obLength = (IntPtr)(_dataBufferSize + ADP.PtrSize);
-                _dbbindings[_index].obValue = (IntPtr)(_dataBufferSize + ADP.PtrSize + ADP.PtrSize);
-                _dataBufferSize += ADP.PtrSize + ADP.PtrSize;
+                _dbbindings[_index].obStatus = (IntPtr)(_dataBufferSize);
+                _dbbindings[_index].obLength = (IntPtr)(_dataBufferSize + IntPtr.Size);
+                _dbbindings[_index].obValue = (IntPtr)(_dataBufferSize + IntPtr.Size + IntPtr.Size);
+                _dataBufferSize += IntPtr.Size + IntPtr.Size;
 
                 switch (DbType)
                 {
index 7a79d06..0a51512 100644 (file)
@@ -31,12 +31,12 @@ namespace System.Data.OleDb
             finally
             {
                 base.handle = Interop.Ole32.CoTaskMemAlloc(countOfBytes);
-                if (ADP.PtrZero != base.handle)
+                if (IntPtr.Zero != base.handle)
                 {
                     SafeNativeMethods.ZeroMemory(base.handle, (int)countOfBytes);
                 }
             }
-            if (ADP.PtrZero == base.handle)
+            if (IntPtr.Zero == base.handle)
             {
                 throw new OutOfMemoryException();
             }
@@ -131,15 +131,15 @@ namespace System.Data.OleDb
             // NOTE: The SafeHandle class guarantees this will be called exactly once and is non-interrutible.
             IntPtr ptr = base.handle;
             base.handle = IntPtr.Zero;
-            if (ADP.PtrZero != ptr)
+            if (IntPtr.Zero != ptr)
             {
                 int count = this.propertySetCount;
                 for (int i = 0, offset = 0; i < count; ++i, offset += ODB.SizeOf_tagDBPROPSET)
                 {
                     IntPtr rgProperties = Marshal.ReadIntPtr(ptr, offset);
-                    if (ADP.PtrZero != rgProperties)
+                    if (IntPtr.Zero != rgProperties)
                     {
-                        int cProperties = Marshal.ReadInt32(ptr, offset + ADP.PtrSize);
+                        int cProperties = Marshal.ReadInt32(ptr, offset + IntPtr.Size);
 
                         IntPtr vptr = ADP.IntPtrOffset(rgProperties, ODB.OffsetOf_tagDBPROP_Value);
                         for (int k = 0; k < cProperties; ++k, vptr = ADP.IntPtrOffset(vptr, ODB.SizeOf_tagDBPROP))
@@ -244,7 +244,7 @@ namespace System.Data.OleDb
                 {
                     // must allocate and clear the memory without interruption
                     propset.rgProperties = Interop.Ole32.CoTaskMemAlloc(countOfBytes);
-                    if (ADP.PtrZero != propset.rgProperties)
+                    if (IntPtr.Zero != propset.rgProperties)
                     {
                         // clearing is important so that we don't treat existing
                         // garbage as important information during releaseHandle
@@ -254,7 +254,7 @@ namespace System.Data.OleDb
                         Marshal.StructureToPtr(propset, propsetPtr, false/*deleteold*/);
                     }
                 }
-                if (ADP.PtrZero == propset.rgProperties)
+                if (IntPtr.Zero == propset.rgProperties)
                 {
                     throw new OutOfMemoryException();
                 }
index 30e6831..94f805d 100644 (file)
@@ -857,7 +857,7 @@ namespace System.Data.OleDb
         {
             Debug.Assert(0 == (CommandBehavior.SingleRow & this.commandBehavior), "SingleRow implies SingleResult");
             OleDbHResult hr;
-            hr = _icommandText!.Execute(ADP.PtrZero, ref ODB.IID_IMultipleResults, dbParams, out _recordsAffected, out executeResult);
+            hr = _icommandText!.Execute(IntPtr.Zero, ref ODB.IID_IMultipleResults, dbParams, out _recordsAffected, out executeResult);
 
             if (OleDbHResult.E_NOINTERFACE != hr)
             {
@@ -875,11 +875,11 @@ namespace System.Data.OleDb
             // (Microsoft.Jet.OLEDB.4.0 returns 0 for recordsAffected instead of -1)
             if (_executeQuery)
             {
-                hr = _icommandText!.Execute(ADP.PtrZero, ref ODB.IID_IRowset, dbParams, out _recordsAffected, out executeResult);
+                hr = _icommandText!.Execute(IntPtr.Zero, ref ODB.IID_IRowset, dbParams, out _recordsAffected, out executeResult);
             }
             else
             {
-                hr = _icommandText!.Execute(ADP.PtrZero, ref ODB.IID_NULL, dbParams, out _recordsAffected, out executeResult);
+                hr = _icommandText!.Execute(IntPtr.Zero, ref ODB.IID_NULL, dbParams, out _recordsAffected, out executeResult);
             }
             ExecuteCommandTextErrorHandling(hr);
             return ODB.ExecutedIRowset;
@@ -892,7 +892,7 @@ namespace System.Data.OleDb
             if (_connection!.SupportIRow(this))
             {
                 OleDbHResult hr;
-                hr = _icommandText!.Execute(ADP.PtrZero, ref ODB.IID_IRow, dbParams, out _recordsAffected, out executeResult);
+                hr = _icommandText!.Execute(IntPtr.Zero, ref ODB.IID_IRow, dbParams, out _recordsAffected, out executeResult);
 
                 if (OleDbHResult.DB_E_NOTFOUND == hr)
                 {
@@ -993,7 +993,7 @@ namespace System.Data.OleDb
                                 try
                                 {
                                     propSet.DangerousAddRef(ref mustRelease);
-                                    hr = iopenRowset.Value.OpenRowset(ADP.PtrZero, tableID, ADP.PtrZero, ref ODB.IID_IRowset, propSet.PropertySetCount, propSet.DangerousGetHandle(), out executeResult);
+                                    hr = iopenRowset.Value.OpenRowset(IntPtr.Zero, tableID, IntPtr.Zero, ref ODB.IID_IRowset, propSet.PropertySetCount, propSet.DangerousGetHandle(), out executeResult);
                                 }
                                 finally
                                 {
@@ -1005,12 +1005,12 @@ namespace System.Data.OleDb
 
                                 if (OleDbHResult.DB_E_ERRORSOCCURRED == hr)
                                 {
-                                    hr = iopenRowset.Value.OpenRowset(ADP.PtrZero, tableID, ADP.PtrZero, ref ODB.IID_IRowset, 0, IntPtr.Zero, out executeResult);
+                                    hr = iopenRowset.Value.OpenRowset(IntPtr.Zero, tableID, IntPtr.Zero, ref ODB.IID_IRowset, 0, IntPtr.Zero, out executeResult);
                                 }
                             }
                             else
                             {
-                                hr = iopenRowset.Value.OpenRowset(ADP.PtrZero, tableID, ADP.PtrZero, ref ODB.IID_IRowset, 0, IntPtr.Zero, out executeResult);
+                                hr = iopenRowset.Value.OpenRowset(IntPtr.Zero, tableID, IntPtr.Zero, ref ODB.IID_IRowset, 0, IntPtr.Zero, out executeResult);
                             }
                         }
                     }
index ef9f821..dd3cb1f 100644 (file)
@@ -373,7 +373,7 @@ namespace System.Data.OleDb
             return dbprops[0].dwStatus;
         }
 
-        internal DataTable? BuildInfoLiterals()
+        internal unsafe DataTable? BuildInfoLiterals()
         {
             using (IDBInfoWrapper wrapper = IDBInfo())
             {
@@ -402,17 +402,17 @@ namespace System.Data.OleDb
 
                 OleDbHResult hr;
                 int literalCount = 0;
-                IntPtr literalInfo = ADP.PtrZero;
+                IntPtr literalInfo = IntPtr.Zero;
                 using (DualCoTaskMem handle = new DualCoTaskMem(dbInfo, null, out literalCount, out literalInfo, out hr))
                 {
                     // All literals were either invalid or unsupported. The provider allocates memory for *prgLiteralInfo and sets the value of the fSupported element in all of the structures to FALSE. The consumer frees this memory when it no longer needs the information.
                     if (OleDbHResult.DB_E_ERRORSOCCURRED != hr)
                     {
-                        long offset = literalInfo.ToInt64();
+                        byte* offset = (byte*)literalInfo;
                         tagDBLITERALINFO tag = new tagDBLITERALINFO();
                         for (int i = 0; i < literalCount; ++i, offset += ODB.SizeOf_tagDBLITERALINFO)
                         {
-                            Marshal.PtrToStructure((IntPtr)offset, tag);
+                            Marshal.PtrToStructure((nint)offset, tag);
 
                             DataRow row = table.NewRow();
                             row[literalName] = ((OleDbLiteral)tag.it).ToString();
@@ -527,7 +527,7 @@ namespace System.Data.OleDb
                     return null;
                 }
                 string? literalValue = null;
-                IntPtr literalInfo = ADP.PtrZero;
+                IntPtr literalInfo = IntPtr.Zero;
                 int literalCount = 0;
                 OleDbHResult hr;
 
@@ -572,8 +572,8 @@ namespace System.Data.OleDb
 
                 OleDbHResult hr;
                 int schemaCount = 0;
-                IntPtr schemaGuids = ADP.PtrZero;
-                IntPtr schemaRestrictions = ADP.PtrZero;
+                IntPtr schemaGuids = IntPtr.Zero;
+                IntPtr schemaRestrictions = IntPtr.Zero;
 
                 using (DualCoTaskMem safehandle = new DualCoTaskMem(dbSchemaRowset, out schemaCount, out schemaGuids, out schemaRestrictions, out hr))
                 {
@@ -584,7 +584,7 @@ namespace System.Data.OleDb
                     }
 
                     supportedSchemas = new SchemaSupport[schemaCount];
-                    if (ADP.PtrZero != schemaGuids)
+                    if (IntPtr.Zero != schemaGuids)
                     {
                         for (int i = 0, offset = 0; i < supportedSchemas.Length; ++i, offset += ODB.SizeOf_Guid)
                         {
@@ -592,7 +592,7 @@ namespace System.Data.OleDb
                             supportedSchemas[i]._schemaRowset = (Guid)Marshal.PtrToStructure(ptr, typeof(Guid))!;
                         }
                     }
-                    if (ADP.PtrZero != schemaRestrictions)
+                    if (IntPtr.Zero != schemaRestrictions)
                     {
                         for (int i = 0; i < supportedSchemas.Length; ++i)
                         {
@@ -622,7 +622,7 @@ namespace System.Data.OleDb
 
                 UnsafeNativeMethods.IRowset? rowset = null;
                 OleDbHResult hr;
-                hr = dbSchemaRowset.GetRowset(ADP.PtrZero, ref schema, restrictions.Length, restrictions, ref ODB.IID_IRowset, 0, ADP.PtrZero, out rowset);
+                hr = dbSchemaRowset.GetRowset(IntPtr.Zero, ref schema, restrictions.Length, restrictions, ref ODB.IID_IRowset, 0, IntPtr.Zero, out rowset);
 
                 if (hr < 0)
                 { // ignore infomsg
index 96e4257..2424504 100644 (file)
@@ -55,10 +55,10 @@ namespace System.Data.OleDb
         private bool _singleRow;
 
         // cached information for Reading (rowhandles/status)
-        private IntPtr _rowHandleFetchCount; // (>1 fails against jet)
+        private nint _rowHandleFetchCount; // (>1 fails against jet)
         private RowHandleBuffer? _rowHandleNativeBuffer;
 
-        private IntPtr _rowFetchedCount;
+        private nint _rowFetchedCount;
         private int _currentRow;
 
         private DataTable? _dbSchemaTable;
@@ -103,7 +103,7 @@ namespace System.Data.OleDb
             // if from ADODB, connection will be null
             if ((null == _connection) || (ChapterHandle.DB_NULL_HCHAPTER != chapterHandle))
             {
-                _rowHandleFetchCount = new IntPtr(1);
+                _rowHandleFetchCount = 1;
             }
 
             Initialize();
@@ -470,8 +470,8 @@ namespace System.Data.OleDb
             }
 
             OleDbHResult hr;
-            IntPtr columnCount = ADP.PtrZero; // column count
-            IntPtr columnInfos = ADP.PtrZero; // ptr to byvalue tagDBCOLUMNINFO[]
+            nint columnCount = 0; // column count
+            IntPtr columnInfos = IntPtr.Zero; // ptr to byvalue tagDBCOLUMNINFO[]
 
             using (DualCoTaskMem safehandle = new DualCoTaskMem(icolumnsInfo, out columnCount, out columnInfos, out hr))
             {
@@ -479,9 +479,9 @@ namespace System.Data.OleDb
                 {
                     ProcessResults(hr);
                 }
-                if (0 < (int)columnCount)
+                if (0 < checked((int)columnCount))
                 {
-                    BuildSchemaTableInfoTable(columnCount.ToInt32(), columnInfos, filterITypeInfo, filterChapters);
+                    BuildSchemaTableInfoTable((int)columnCount, columnInfos, filterITypeInfo, filterChapters);
                 }
             }
         }
@@ -502,7 +502,7 @@ namespace System.Data.OleDb
             for (int i = 0, offset = 0; i < columnCount; ++i, offset += ODB.SizeOf_tagDBCOLUMNINFO)
             {
                 Marshal.PtrToStructure(ADP.IntPtrOffset(columnInfos, offset), dbColumnInfo);
-                if ((ODB.IsRunningOnX86 && 0 >= (int)dbColumnInfo.iOrdinal) || (!ODB.IsRunningOnX86 && 0 >= (long)dbColumnInfo.iOrdinal))
+                if (0 >= dbColumnInfo.iOrdinal)
                 {
                     continue;
                 }
@@ -532,15 +532,8 @@ namespace System.Data.OleDb
                 info.columnName = dbColumnInfo.pwszName;
                 info.type = dbType;
                 info.ordinal = dbColumnInfo.iOrdinal;
-                if (ODB.IsRunningOnX86)
-                {
-                    info.size = (int)dbColumnInfo.ulColumnSize;
-                }
-                else
-                {
-                    long maxsize = (long)dbColumnInfo.ulColumnSize;
-                    info.size = (((maxsize < 0) || (int.MaxValue < maxsize)) ? int.MaxValue : (int)maxsize);
-                }
+                nint maxsize = dbColumnInfo.ulColumnSize;
+                info.size = (((maxsize < 0) || (int.MaxValue < maxsize)) ? int.MaxValue : (int)maxsize);
                 info.flags = dbColumnInfo.dwFlags;
                 info.precision = dbColumnInfo.bPrecision;
                 info.scale = dbColumnInfo.bScale;
@@ -567,7 +560,7 @@ namespace System.Data.OleDb
                         break;
                     case ODB.DBKIND_GUID_NAME:
                     case ODB.DBKIND_NAME:
-                        if (ADP.PtrZero != dbColumnInfo.columnid.ulPropid)
+                        if (IntPtr.Zero != dbColumnInfo.columnid.ulPropid)
                         {
                             info.idname = Marshal.PtrToStringUni(dbColumnInfo.columnid.ulPropid);
                         }
@@ -577,7 +570,7 @@ namespace System.Data.OleDb
                         }
                         break;
                     default:
-                        info.propid = ADP.PtrZero;
+                        info.propid = IntPtr.Zero;
                         break;
                 }
                 metainfo[rowCount] = info;
@@ -618,7 +611,7 @@ namespace System.Data.OleDb
                 using (DualCoTaskMem prgOptColumns = new DualCoTaskMem(icolumnsRowset, out cOptColumns, out hr))
                 {
                     Debug.Assert((0 == hr) || prgOptColumns.IsInvalid, "GetAvailableCOlumns: unexpected return");
-                    hr = icolumnsRowset.GetColumnsRowset(ADP.PtrZero, cOptColumns, prgOptColumns, ref ODB.IID_IRowset, 0, ADP.PtrZero, out rowset);
+                    hr = icolumnsRowset.GetColumnsRowset(IntPtr.Zero, cOptColumns, prgOptColumns, ref ODB.IID_IRowset, 0, IntPtr.Zero, out rowset);
                 }
 
                 Debug.Assert((0 <= hr) || (null == rowset), "if GetColumnsRowset failed, rowset should be null");
@@ -767,7 +760,7 @@ namespace System.Data.OleDb
             }
 
             _currentRow = 0;
-            _rowFetchedCount = IntPtr.Zero;
+            _rowFetchedCount = 0;
 
             _dbSchemaTable = null;
             _visibleFieldCount = 0;
@@ -1200,32 +1193,17 @@ namespace System.Data.OleDb
             { throw e; }
         }
 
-        private static IntPtr AddRecordsAffected(IntPtr recordsAffected, IntPtr affected)
+        private static nint AddRecordsAffected(nint recordsAffected, nint affected)
         {
-            if (ODB.IsRunningOnX86)
+            if (0 <= affected)
             {
-                if (0 <= (int)affected)
+                if (0 <= recordsAffected)
                 {
-                    if (0 <= (int)recordsAffected)
-                    {
-                        return (IntPtr)((int)recordsAffected + (int)affected);
-                    }
-                    return affected;
+                    return recordsAffected + affected;
                 }
-                return recordsAffected;
-            }
-            else
-            {
-                if (0 <= (long)affected)
-                {
-                    if (0 <= (long)recordsAffected)
-                    {
-                        return (IntPtr)((long)recordsAffected + (long)affected);
-                    }
-                    return affected;
-                }
-                return recordsAffected;
+                return affected;
             }
+            return recordsAffected;
         }
 
         public override int VisibleFieldCount
@@ -1255,7 +1233,7 @@ namespace System.Data.OleDb
             List<OleDbException>? exceptions = null;
             if (null != imultipleResults)
             {
-                IntPtr affected;
+                nint affected;
                 OleDbHResult hr;
 
                 // MSOLAP provider doesn't move onto the next result when calling GetResult with IID_NULL, but does return S_OK with 0 affected records.
@@ -1266,7 +1244,7 @@ namespace System.Data.OleDb
                     {
                         break;
                     }
-                    hr = imultipleResults.GetResult(ADP.PtrZero, ODB.DBRESULTFLAG_DEFAULT, ref ODB.IID_NULL, out affected, out _);
+                    hr = imultipleResults.GetResult(IntPtr.Zero, ODB.DBRESULTFLAG_DEFAULT, ref ODB.IID_NULL, out affected, out _);
 
                     // If a provider doesn't support IID_NULL and returns E_NOINTERFACE we want to break out
                     // of the loop without throwing an exception.  Our behavior will match ADODB in that scenario
@@ -1357,7 +1335,7 @@ namespace System.Data.OleDb
                         Close();
                         break;
                     }
-                    hr = imultipleResults.GetResult(ADP.PtrZero, ODB.DBRESULTFLAG_DEFAULT, ref ODB.IID_IRowset, out affected, out result);
+                    hr = imultipleResults.GetResult(IntPtr.Zero, ODB.DBRESULTFLAG_DEFAULT, ref ODB.IID_IRowset, out affected, out result);
 
                     if ((0 <= hr) && (null != result))
                     {
@@ -1456,7 +1434,7 @@ namespace System.Data.OleDb
 
             // making the check if (null != irowset) unnecessary
             // if necessary, get next group of row handles
-            if (IntPtr.Zero == _rowFetchedCount)
+            if (0 == _rowFetchedCount)
             { // starts at (-1 <= 0)
                 Debug.Assert(0 == _currentRow, "incorrect state for _currentRow");
                 Debug.Assert(0 <= _metadata.Length, "incorrect state for fieldCount");
@@ -1511,25 +1489,25 @@ namespace System.Data.OleDb
                 }
             }
 
-            if (IntPtr.Zero == _rowHandleFetchCount)
+            if (0 == _rowHandleFetchCount)
             {
-                _rowHandleFetchCount = new IntPtr(1);
+                _rowHandleFetchCount = 1;
 
                 object? maxRows = GetPropertyValue(ODB.DBPROP_MAXROWS);
-                if (maxRows is int)
+                if (maxRows is int intValue)
                 {
-                    _rowHandleFetchCount = new IntPtr((int)maxRows);
-                    if ((ADP.PtrZero == _rowHandleFetchCount) || (20 <= (int)_rowHandleFetchCount))
+                    _rowHandleFetchCount = intValue;
+                    if ((0 == _rowHandleFetchCount) || (20 <= _rowHandleFetchCount))
                     {
-                        _rowHandleFetchCount = new IntPtr(20);
+                        _rowHandleFetchCount = 20;
                     }
                 }
-                else if (maxRows is long)
+                else if (maxRows is long longValue)
                 {
-                    _rowHandleFetchCount = new IntPtr((long)maxRows);
-                    if ((ADP.PtrZero == _rowHandleFetchCount) || (20 <= (long)_rowHandleFetchCount))
+                    _rowHandleFetchCount = (nint)longValue;
+                    if ((0 == _rowHandleFetchCount) || (20 <= _rowHandleFetchCount))
                     {
-                        _rowHandleFetchCount = new IntPtr(20);
+                        _rowHandleFetchCount = 20;
                     }
                 }
             }
@@ -1634,7 +1612,7 @@ namespace System.Data.OleDb
                 {
                     if (info.type.islong)
                     {
-                        maxLen = ADP.PtrSize;
+                        maxLen = IntPtr.Size;
                         getType = (short)((ushort)getType | (ushort)NativeDBType.BYREF);
                     }
                     else if (-1 == maxLen)
@@ -1644,14 +1622,14 @@ namespace System.Data.OleDb
                             || ((null != command) && command.Connection.PropertyGetProviderOwnedMemory())) {
                             bindings.MemOwner = DBMemOwner.ProviderOwned;
 
-                            bindings.MaxLen = ADP.PtrSize;
+                            bindings.MaxLen = IntPtr.Size;
                             bindings.DbType = (short) (getType | DbType.BYREF);
                         }
                         else*/
 
                         if (ODB.LargeDataSize < info.size)
                         {
-                            maxLen = ADP.PtrSize;
+                            maxLen = IntPtr.Size;
                             getType = (short)((ushort)getType | (ushort)NativeDBType.BYREF);
                         }
                         else if ((NativeDBType.WSTR == getType) && (-1 != info.size))
@@ -1671,7 +1649,7 @@ namespace System.Data.OleDb
                         || ((null != command) && command.Connection.PropertyGetProviderOwnedMemory())) {
                         bindings.MemOwner = DBMemOwner.ProviderOwned;
                     }*/
-                    maxLen = ADP.PtrSize;
+                    maxLen = IntPtr.Size;
                     getType = (short)((ushort)getType | (ushort)NativeDBType.BYREF);
                 }
 
@@ -1762,7 +1740,7 @@ namespace System.Data.OleDb
                 ProcessResults(hr);
             }
             _isRead = ((OleDbHResult.DB_S_ENDOFROWSET != hr) || (0 < (int)_rowFetchedCount));
-            _rowFetchedCount = (IntPtr)Math.Max((int)_rowFetchedCount, 0);
+            _rowFetchedCount = Math.Max((int)_rowFetchedCount, 0);
         }
 
         private void GetRowDataFromHandle()
@@ -1809,7 +1787,7 @@ namespace System.Data.OleDb
 
             OleDbHResult hr;
             UnsafeNativeMethods.IRowset irowset = IRowset();
-            hr = irowset.ReleaseRows(_rowFetchedCount, _rowHandleNativeBuffer!, ADP.PtrZero, ADP.PtrZero, ADP.PtrZero);
+            hr = irowset.ReleaseRows(_rowFetchedCount, _rowHandleNativeBuffer!, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
 
             if (hr < 0)
             {
@@ -1817,7 +1795,7 @@ namespace System.Data.OleDb
                 //ProcessFailure(hr);
                 SafeNativeMethods.Wrapper.ClearErrorInfo();
             }
-            _rowFetchedCount = IntPtr.Zero;
+            _rowFetchedCount = 0;
             _currentRow = 0;
             _isRead = false;
         }
@@ -2344,24 +2322,17 @@ namespace System.Data.OleDb
                         info.columnName = "";
                     }
 
-                    if (4 == ADP.PtrSize)
-                    {
-                        info.ordinal = (IntPtr)columnordinal.columnBinding.Value_UI4();
-                    }
-                    else
-                    {
-                        info.ordinal = (IntPtr)columnordinal.columnBinding.Value_UI8();
-                    }
-                    short wType = unchecked((short)dbtype.columnBinding.Value_UI2());
-
-                    if (4 == ADP.PtrSize)
+                    if (4 == IntPtr.Size)
                     {
+                        info.ordinal = (nint)columnordinal.columnBinding.Value_UI4();
                         info.size = unchecked((int)columnsize.columnBinding.Value_UI4());
                     }
                     else
                     {
-                        info.size = ADP.IntPtrToInt32((IntPtr)unchecked((long)columnsize.columnBinding.Value_UI8()));
+                        info.ordinal = (nint)columnordinal.columnBinding.Value_UI8();
+                        info.size = ADP.IntPtrToInt32((nint)columnsize.columnBinding.Value_UI8());
                     }
+                    short wType = unchecked((short)dbtype.columnBinding.Value_UI2());
 
                     binding = numericprecision.columnBinding;
                     if (!binding.IsValueNull())
@@ -2498,7 +2469,7 @@ namespace System.Data.OleDb
                     info.isHidden = true;
                     visibleCount--;
                 }
-                else if ((ODB.IsRunningOnX86 && 0 >= (int)info.ordinal) || (!ODB.IsRunningOnX86 && 0 >= (long)info.ordinal))
+                else if (0 >= info.ordinal)
                 {
 #if DEBUG
                     if (AdapterSwitches.DataSchema.TraceVerbose)
@@ -2590,7 +2561,7 @@ namespace System.Data.OleDb
 
         internal NativeDBType type = null!; // Late-initialized
 
-        internal IntPtr ordinal;
+        internal nint ordinal;
         internal int size;
 
         internal int flags;
@@ -2610,15 +2581,15 @@ namespace System.Data.OleDb
 
         int IComparable.CompareTo(object? obj)
         {
-            if (isHidden == (obj as MetaData)!.isHidden)
+            if (obj is MetaData m && isHidden == m.isHidden)
             {
                 if (ODB.IsRunningOnX86)
                 {
-                    return ((int)ordinal - (int)(obj as MetaData)!.ordinal);
+                    return (int)ordinal - (int)m.ordinal;
                 }
                 else
                 {
-                    long v = ((long)ordinal - (long)(obj as MetaData)!.ordinal);
+                    long v = (long)ordinal - (long)m.ordinal;
                     return ((0 < v) ? 1 : ((v < 0) ? -1 : 0));
                 }
             }
index d06d83e..13761fc 100644 (file)
@@ -50,8 +50,8 @@ namespace System.Data.OleDb
             }
 
             int propCount = 0;
-            IntPtr propSets = ADP.PtrZero;
-            OleDbHResult hr = srcrowset.GetSourcesRowset(ADP.PtrZero, ODB.IID_IRowset, propCount, propSets, out value);
+            IntPtr propSets = IntPtr.Zero;
+            OleDbHResult hr = srcrowset.GetSourcesRowset(IntPtr.Zero, ODB.IID_IRowset, propCount, propSets, out value);
 
             Exception? f = OleDbConnection.ProcessResults(hr, null, null);
             if (null != f)
index f3a69ed..81055cf 100644 (file)
@@ -332,7 +332,7 @@ namespace System.Data.OleDb
 
             if (dbtype.islong)
             { // long data (image, text, ntext)
-                bytecount = ADP.PtrSize;
+                bytecount = IntPtr.Size;
                 if (ShouldSerializeSize())
                 {
                     size = Size;
@@ -396,7 +396,7 @@ namespace System.Data.OleDb
 
                     if (ODB.LargeDataSize < bytecount)
                     {
-                        bytecount = ADP.PtrSize;
+                        bytecount = IntPtr.Size;
                         wtype |= NativeDBType.BYREF;
                     }
                 }
@@ -415,7 +415,7 @@ namespace System.Data.OleDb
                 }
                 else if (-1 == size)
                 {
-                    bytecount = ADP.PtrSize;
+                    bytecount = IntPtr.Size;
                     wtype |= NativeDBType.BYREF;
                 }
                 else
@@ -432,7 +432,7 @@ namespace System.Data.OleDb
 
             // tagDBPARAMBINDINFO info for SetParameterInfo
             bindings.DataSourceType = dbtype.dbString.DangerousGetHandle(); // NOTE: This is a constant and isn't exposed publicly, so there really isn't a potential for Handle Recycling.
-            bindings.Name = ADP.PtrZero;
+            bindings.Name = IntPtr.Zero;
             bindings.ParamSize = new IntPtr(size);
             bindings.Flags = GetBindFlags(direction);
             //bindings.Precision    = precision;
index d0c79b2..25c696c 100644 (file)
@@ -420,11 +420,11 @@ namespace System.Data.OleDb
         //[MarshalAs(UnmanagedType.Interface)]
         internal IntPtr pTypeInfo = (IntPtr)0;
 
-        internal IntPtr iOrdinal = (IntPtr)0;
+        internal nint iOrdinal = 0;
 
         internal int dwFlags;
 
-        internal IntPtr ulColumnSize = (IntPtr)0;
+        internal nint ulColumnSize = 0;
 
         internal short wType;
 
@@ -442,7 +442,7 @@ namespace System.Data.OleDb
         {
             StringBuilder builder = new StringBuilder();
             builder.AppendLine($"tagDBCOLUMNINFO: {Convert.ToString(pwszName, CultureInfo.InvariantCulture)}");
-            builder.AppendLine($"\t{iOrdinal.ToInt64().ToString(CultureInfo.InvariantCulture)}");
+            builder.AppendLine($"\t{((long)iOrdinal).ToString(CultureInfo.InvariantCulture)}");
             builder.AppendLine($"\t0x{dwFlags:X8}");
             builder.AppendLine($"\t{ulColumnSize}");
             builder.AppendLine($"\t0x{wType:X2}");
index a3c3432..a584e8f 100644 (file)
@@ -128,7 +128,7 @@ namespace System.Data.OleDb
 
         private static readonly NativeDBType D_Binary = new NativeDBType(0xff, -1, true, false, OleDbType.Binary, NativeDBType.BYTES, S_BINARY, typeof(byte[]), NativeDBType.BYTES, DbType.Binary); //  0
         private static readonly NativeDBType D_Boolean = new NativeDBType(0xff, 2, true, false, OleDbType.Boolean, NativeDBType.BOOL, S_BOOL, typeof(bool), NativeDBType.BOOL, DbType.Boolean); //  1 - integer2 (variant_bool)
-        private static readonly NativeDBType D_BSTR = new NativeDBType(0xff, ADP.PtrSize, false, false, OleDbType.BSTR, NativeDBType.BSTR, S_BSTR, typeof(string), NativeDBType.BSTR, DbType.String); //  2 - integer4 (pointer)
+        private static readonly NativeDBType D_BSTR = new NativeDBType(0xff, IntPtr.Size, false, false, OleDbType.BSTR, NativeDBType.BSTR, S_BSTR, typeof(string), NativeDBType.BSTR, DbType.String); //  2 - integer4 (pointer)
         private static readonly NativeDBType D_Char = new NativeDBType(0xff, -1, true, false, OleDbType.Char, NativeDBType.STR, S_CHAR, typeof(string), NativeDBType.WSTR/*STR*/, DbType.AnsiStringFixedLength); //  3 - (ansi pointer)
         private static readonly NativeDBType D_Currency = new NativeDBType(19, 8, true, false, OleDbType.Currency, NativeDBType.CY, S_CY, typeof(decimal), NativeDBType.CY, DbType.Currency); //  4 - integer8
         private static readonly NativeDBType D_Date = new NativeDBType(0xff, 8, true, false, OleDbType.Date, NativeDBType.DATE, S_DATE, typeof(System.DateTime), NativeDBType.DATE, DbType.DateTime); //  5 - double
@@ -143,8 +143,8 @@ namespace System.Data.OleDb
         private static readonly NativeDBType D_SmallInt = new NativeDBType(5, 2, true, false, OleDbType.SmallInt, NativeDBType.I2, S_I2, typeof(short), NativeDBType.I2, DbType.Int16); // 14 - integer2
         private static readonly NativeDBType D_Integer = new NativeDBType(10, 4, true, false, OleDbType.Integer, NativeDBType.I4, S_I4, typeof(int), NativeDBType.I4, DbType.Int32); // 15 - integer4
         private static readonly NativeDBType D_BigInt = new NativeDBType(19, 8, true, false, OleDbType.BigInt, NativeDBType.I8, S_I8, typeof(long), NativeDBType.I8, DbType.Int64); // 16 - integer8
-        private static readonly NativeDBType D_IDispatch = new NativeDBType(0xff, ADP.PtrSize, true, false, OleDbType.IDispatch, NativeDBType.IDISPATCH, S_IDISPATCH, typeof(object), NativeDBType.IDISPATCH, DbType.Object); // 17 - integer4 (pointer)
-        private static readonly NativeDBType D_IUnknown = new NativeDBType(0xff, ADP.PtrSize, true, false, OleDbType.IUnknown, NativeDBType.IUNKNOWN, S_IUNKNOWN, typeof(object), NativeDBType.IUNKNOWN, DbType.Object); // 18 - integer4 (pointer)
+        private static readonly NativeDBType D_IDispatch = new NativeDBType(0xff, IntPtr.Size, true, false, OleDbType.IDispatch, NativeDBType.IDISPATCH, S_IDISPATCH, typeof(object), NativeDBType.IDISPATCH, DbType.Object); // 17 - integer4 (pointer)
+        private static readonly NativeDBType D_IUnknown = new NativeDBType(0xff, IntPtr.Size, true, false, OleDbType.IUnknown, NativeDBType.IUNKNOWN, S_IUNKNOWN, typeof(object), NativeDBType.IUNKNOWN, DbType.Object); // 18 - integer4 (pointer)
         private static readonly NativeDBType D_LongVarBinary = new NativeDBType(0xff, -1, false, true, OleDbType.LongVarBinary, NativeDBType.BYTES, S_LONGVARBINARY, typeof(byte[]), NativeDBType.BYTES, DbType.Binary); // 19
         private static readonly NativeDBType D_LongVarChar = new NativeDBType(0xff, -1, false, true, OleDbType.LongVarChar, NativeDBType.STR, S_LONGVARCHAR, typeof(string), NativeDBType.WSTR/*STR*/, DbType.AnsiString); // 20 - (ansi pointer)
         private static readonly NativeDBType D_Numeric = new NativeDBType(28, 19, true, false, OleDbType.Numeric, NativeDBType.NUMERIC, S_NUMERIC, typeof(decimal), NativeDBType.NUMERIC, DbType.Decimal); // 21 - (tagDB_Numeric)
@@ -163,7 +163,7 @@ namespace System.Data.OleDb
         private static readonly NativeDBType D_WChar = new NativeDBType(0xff, -1, true, false, OleDbType.WChar, NativeDBType.WSTR, S_WCHAR, typeof(string), NativeDBType.WSTR, DbType.StringFixedLength); // 33 - (unicode pointer)
         private static readonly NativeDBType D_VarWChar = new NativeDBType(0xff, -1, false, false, OleDbType.VarWChar, NativeDBType.WSTR, S_WVARCHAR, typeof(string), NativeDBType.WSTR, DbType.String); // 34 - (unicode pointer)
         private static readonly NativeDBType D_LongVarWChar = new NativeDBType(0xff, -1, false, true, OleDbType.LongVarWChar, NativeDBType.WSTR, S_WLONGVARCHAR, typeof(string), NativeDBType.WSTR, DbType.String); // 35 - (unicode pointer)
-        private static readonly NativeDBType D_Chapter = new NativeDBType(0xff, ADP.PtrSize, false, false, OleDbType.Empty, NativeDBType.HCHAPTER, S_UDT, typeof(IDataReader), NativeDBType.HCHAPTER, DbType.Object); // 36 - (hierarchical chaper)
+        private static readonly NativeDBType D_Chapter = new NativeDBType(0xff, IntPtr.Size, false, false, OleDbType.Empty, NativeDBType.HCHAPTER, S_UDT, typeof(IDataReader), NativeDBType.HCHAPTER, DbType.Object); // 36 - (hierarchical chaper)
         private static readonly NativeDBType D_Empty = new NativeDBType(0xff, 0, false, false, OleDbType.Empty, NativeDBType.EMPTY, "", null, NativeDBType.EMPTY, DbType.Object); // 37 - invalid param default
         private static readonly NativeDBType D_Xml = new NativeDBType(0xff, -1, false, false, OleDbType.VarWChar, NativeDBType.XML, S_XML, typeof(string), NativeDBType.WSTR, DbType.String); // 38 - (unicode pointer)
         private static readonly NativeDBType D_Udt = new NativeDBType(0xff, -1, false, false, OleDbType.VarBinary, NativeDBType.UDT, S_BINARY, typeof(byte[]), NativeDBType.BYTES, DbType.Binary); // 39 - (unicode pointer)
index 2cced8c..d42b001 100644 (file)
@@ -553,9 +553,9 @@ namespace System.Data.OleDb
         internal const uint DB_ALL_EXCEPT_LIKE = 3;
         internal const uint DB_SEARCHABLE = 4;
 
-        internal static readonly IntPtr DB_INVALID_HACCESSOR = ADP.PtrZero;
-        internal static readonly IntPtr DB_NULL_HCHAPTER = ADP.PtrZero;
-        internal static readonly IntPtr DB_NULL_HROW = ADP.PtrZero;
+        internal static readonly IntPtr DB_INVALID_HACCESSOR = IntPtr.Zero;
+        internal static readonly IntPtr DB_NULL_HCHAPTER = IntPtr.Zero;
+        internal static readonly IntPtr DB_NULL_HROW = IntPtr.Zero;
 
         internal static readonly bool IsRunningOnX86 = RuntimeInformation.ProcessArchitecture == Architecture.X86;
 
@@ -569,7 +569,7 @@ namespace System.Data.OleDb
         internal static readonly int SizeOf_tagDBPROPINFO = IsRunningOnX86 ? Marshal.SizeOf(typeof(tagDBPROPINFO_x86)) : Marshal.SizeOf(typeof(tagDBPROPINFO));
         internal static readonly int SizeOf_tagDBPROPIDSET = Marshal.SizeOf(typeof(tagDBPROPIDSET));
         internal static readonly int SizeOf_Guid = Marshal.SizeOf(typeof(Guid));
-        internal static readonly int SizeOf_Variant = 8 + (2 * ADP.PtrSize); // 16 on 32bit, 24 on 64bit
+        internal static readonly int SizeOf_Variant = 8 + (2 * IntPtr.Size); // 16 on 32bit, 24 on 64bit
 
         internal static readonly int OffsetOf_tagDBPROP_Status = IsRunningOnX86 ? Marshal.OffsetOf(typeof(tagDBPROP_x86), "dwStatus").ToInt32() : Marshal.OffsetOf(typeof(tagDBPROP), "dwStatus").ToInt32();
         internal static readonly int OffsetOf_tagDBPROP_Value = IsRunningOnX86 ? Marshal.OffsetOf(typeof(tagDBPROP_x86), "vValue").ToInt32() : Marshal.OffsetOf(typeof(tagDBPROP), "vValue").ToInt32();
index 52b854c..4cd4bb9 100644 (file)
@@ -9,7 +9,7 @@ namespace System.Data.OleDb
 {
     internal sealed class PropertyIDSet : DbBuffer
     {
-        private static readonly int PropertyIDSetAndValueSize = ODB.SizeOf_tagDBPROPIDSET + ADP.PtrSize; // sizeof(tagDBPROPIDSET) + sizeof(int)
+        private static readonly int PropertyIDSetAndValueSize = ODB.SizeOf_tagDBPROPIDSET + IntPtr.Size; // sizeof(tagDBPROPIDSET) + sizeof(int)
         private static readonly int PropertyIDSetSize = ODB.SizeOf_tagDBPROPIDSET;
 
         private readonly int _count;
@@ -25,7 +25,7 @@ namespace System.Data.OleDb
             IntPtr ptr = ADP.IntPtrOffset(base.handle, PropertyIDSetSize);
             Marshal.WriteIntPtr(base.handle, 0, ptr);
 
-            Marshal.WriteInt32(base.handle, ADP.PtrSize, /*propertyid count*/1);
+            Marshal.WriteInt32(base.handle, IntPtr.Size, /*propertyid count*/1);
 
             ptr = ADP.IntPtrOffset(base.handle, ODB.OffsetOf_tagDBPROPIDSET_PropertySet);
             Marshal.StructureToPtr(propertySet, ptr, false/*deleteold*/);
index 1ae3aa2..da47966 100644 (file)
@@ -40,7 +40,7 @@ namespace System.Data.OleDb
             {
                 hr = idbProperties.GetPropertyInfo(propIDSetCount, propIDSet, out this.setCount, out base.handle, out this.descBuffer);
             }
-            if ((0 <= hr) && (ADP.PtrZero != handle))
+            if ((0 <= hr) && (IntPtr.Zero != handle))
             {
                 SafeNativeMethods.Wrapper.ClearErrorInfo();
             }
@@ -63,7 +63,7 @@ namespace System.Data.OleDb
             try
             {
                 DangerousAddRef(ref mustRelease);
-                if (ADP.PtrZero != this.handle)
+                if (IntPtr.Zero != this.handle)
                 {
                     propertyLookup = new Dictionary<string, OleDbPropertyInfo>(StringComparer.OrdinalIgnoreCase);
 
@@ -120,7 +120,7 @@ namespace System.Data.OleDb
                     IntPtr infoPtr = Marshal.ReadIntPtr(ptr, offset);
                     if (IntPtr.Zero != infoPtr)
                     {
-                        int infoCount = Marshal.ReadInt32(ptr, offset + ADP.PtrSize);
+                        int infoCount = Marshal.ReadInt32(ptr, offset + IntPtr.Size);
 
                         for (int k = 0; k < infoCount; ++k)
                         {
index 302098f..0a9ea89 100644 (file)
@@ -238,7 +238,7 @@ namespace System.Data.OleDb
         {
             // two contiguous BSTR ptr, second should be a binary copy of the first
             Debug.Assert(_needToReset, "data type requires resetting and _needToReset is false");
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
             ValidateCheck(offset, 2 * IntPtr.Size);
 
             IntPtr ptr;
@@ -257,7 +257,7 @@ namespace System.Data.OleDb
 
                     // safe to copy ptr, even if SysAllocStringLen failed
                     Marshal.WriteIntPtr(base.handle, offset, ptr);
-                    Marshal.WriteIntPtr(base.handle, offset + ADP.PtrSize, ptr);
+                    Marshal.WriteIntPtr(base.handle, offset + IntPtr.Size, ptr);
                 }
             }
             finally
@@ -277,10 +277,10 @@ namespace System.Data.OleDb
         internal void SetByRefValue(int offset, IntPtr pinnedValue)
         {
             Debug.Assert(_needToReset, "data type requires resetting and _needToReset is false");
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
             ValidateCheck(offset, 2 * IntPtr.Size);
 
-            if (ADP.PtrZero == pinnedValue)
+            if (IntPtr.Zero == pinnedValue)
             { // empty array scenario
                 pinnedValue = ADP.IntPtrOffset(base.handle, _emptyStringOffset);
             }
@@ -296,7 +296,7 @@ namespace System.Data.OleDb
                 finally
                 {
                     Marshal.WriteIntPtr(base.handle, offset, pinnedValue);               // parameter input value
-                    Marshal.WriteIntPtr(base.handle, offset + ADP.PtrSize, pinnedValue); // original parameter value
+                    Marshal.WriteIntPtr(base.handle, offset + IntPtr.Size, pinnedValue); // original parameter value
                 }
             }
             finally
@@ -392,7 +392,7 @@ namespace System.Data.OleDb
 
         private unsafe void ResetValues(IntPtr buffer, object? iaccessor)
         {
-            Debug.Assert(ADP.PtrZero != buffer && _needToReset && _haveData, "shouldn't be calling ResetValues");
+            Debug.Assert(IntPtr.Zero != buffer && _needToReset && _haveData, "shouldn't be calling ResetValues");
             for (int i = 0; i < _bindingCount; ++i)
             {
                 IntPtr ptr = ADP.IntPtrOffset(buffer, (i * ODB.SizeOf_tagDBBINDING));
@@ -471,7 +471,7 @@ namespace System.Data.OleDb
             Debug.Assert(0 == valueOffset % 8, "unexpected unaligned ptr offset");
 
             UnsafeNativeMethods.IChapteredRowset chapteredRowset = (iaccessor as UnsafeNativeMethods.IChapteredRowset)!;
-            IntPtr chapter = SafeNativeMethods.InterlockedExchangePointer(ADP.IntPtrOffset(buffer, valueOffset), ADP.PtrZero);
+            IntPtr chapter = SafeNativeMethods.InterlockedExchangePointer(ADP.IntPtrOffset(buffer, valueOffset), IntPtr.Zero);
             if (ODB.DB_NULL_HCHAPTER != chapter)
             {
                 chapteredRowset.ReleaseChapter(chapter, out _);
@@ -490,20 +490,20 @@ namespace System.Data.OleDb
             finally
             {
                 IntPtr currentValue = Marshal.ReadIntPtr(buffer, valueOffset);
-                IntPtr originalValue = Marshal.ReadIntPtr(buffer, valueOffset + ADP.PtrSize);
+                IntPtr originalValue = Marshal.ReadIntPtr(buffer, valueOffset + IntPtr.Size);
 
-                if ((ADP.PtrZero != currentValue) && (currentValue != originalValue))
+                if ((IntPtr.Zero != currentValue) && (currentValue != originalValue))
                 {
                     Interop.OleAut32.SysFreeString(currentValue);
                 }
-                if (ADP.PtrZero != originalValue)
+                if (IntPtr.Zero != originalValue)
                 {
                     Interop.OleAut32.SysFreeString(originalValue);
                 }
 
                 // for debugability - delay clearing memory until after FreeBSTR
-                Marshal.WriteIntPtr(buffer, valueOffset, ADP.PtrZero);
-                Marshal.WriteIntPtr(buffer, valueOffset + ADP.PtrSize, ADP.PtrZero);
+                Marshal.WriteIntPtr(buffer, valueOffset, IntPtr.Zero);
+                Marshal.WriteIntPtr(buffer, valueOffset + IntPtr.Size, IntPtr.Zero);
             }
         }
 
@@ -519,17 +519,17 @@ namespace System.Data.OleDb
             finally
             {
                 IntPtr currentValue = Marshal.ReadIntPtr(buffer, valueOffset);
-                IntPtr originalValue = Marshal.ReadIntPtr(buffer, valueOffset + ADP.PtrSize);
+                IntPtr originalValue = Marshal.ReadIntPtr(buffer, valueOffset + IntPtr.Size);
 
                 // originalValue is pinned managed memory or pointer to emptyStringOffset
-                if ((ADP.PtrZero != currentValue) && (currentValue != originalValue))
+                if ((IntPtr.Zero != currentValue) && (currentValue != originalValue))
                 {
                     Interop.Ole32.CoTaskMemFree(currentValue);
                 }
 
                 // for debugability - delay clearing memory until after CoTaskMemFree
-                Marshal.WriteIntPtr(buffer, valueOffset, ADP.PtrZero);
-                Marshal.WriteIntPtr(buffer, valueOffset + ADP.PtrSize, ADP.PtrZero);
+                Marshal.WriteIntPtr(buffer, valueOffset, IntPtr.Zero);
+                Marshal.WriteIntPtr(buffer, valueOffset + IntPtr.Size, IntPtr.Zero);
             }
         }
 
@@ -599,7 +599,7 @@ namespace System.Data.OleDb
         internal IntPtr InterlockedExchangePointer(int offset)
         {
             ValidateCheck(offset, IntPtr.Size);
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
 
             IntPtr value;
             bool mustRelease = false;
index 3d918e2..c976194 100644 (file)
@@ -79,13 +79,13 @@ namespace System.Data.OleDb
 
     internal sealed class RowHandleBuffer : DbBuffer
     {
-        internal RowHandleBuffer(IntPtr rowHandleFetchCount) : base((int)rowHandleFetchCount * ADP.PtrSize)
+        internal RowHandleBuffer(nint rowHandleFetchCount) : base(checked((int)rowHandleFetchCount * IntPtr.Size))
         {
         }
 
         internal IntPtr GetRowHandle(int index)
         {
-            IntPtr value = ReadIntPtr(index * ADP.PtrSize);
+            IntPtr value = ReadIntPtr(index * IntPtr.Size);
             Debug.Assert(ODB.DB_NULL_HROW != value, "bad rowHandle");
             return value;
         }
index 147bf16..9b29bb0 100644 (file)
@@ -51,7 +51,7 @@ namespace System.Data.Common
             // SxS: clearing error information is considered safe
             internal static void ClearErrorInfo()
             {
-                Interop.OleAut32.SetErrorInfo(0, ADP.PtrZero);
+                Interop.OleAut32.SetErrorInfo(0, IntPtr.Zero);
             }
         }
     }
index 46c062c..6f8526a 100644 (file)
@@ -899,8 +899,6 @@ namespace System.Data.Common
         internal const int DefaultCommandTimeout = 30;
         internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout;
 
-        internal static readonly IntPtr PtrZero = new IntPtr(0); // IntPtr.Zero
-        internal static readonly int PtrSize = IntPtr.Size;
         internal static readonly IntPtr RecordsUnaffected = new IntPtr(-1);
 
         internal const int CharSize = System.Text.UnicodeEncoding.CharSize;
@@ -1256,17 +1254,12 @@ namespace System.Data.Common
 
         internal static IntPtr IntPtrOffset(IntPtr pbase, int offset)
         {
-            if (4 == ADP.PtrSize)
-            {
-                return (IntPtr)checked(pbase.ToInt32() + offset);
-            }
-            Debug.Assert(8 == ADP.PtrSize, "8 != IntPtr.Size");
-            return (IntPtr)checked(pbase.ToInt64() + offset);
+            return (nint)pbase + offset;
         }
 
-        internal static int IntPtrToInt32(IntPtr value)
+        internal static int IntPtrToInt32(nint value)
         {
-            if (4 == ADP.PtrSize)
+            if (4 == IntPtr.Size)
             {
                 return (int)value;
             }
index 3f50fd3..dac3f18 100644 (file)
@@ -65,7 +65,7 @@ namespace System.Data.ProviderBase
         {
             offset += BaseOffset;
             Validate(offset, 2 * length);
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
 
             string? value = null;
             bool mustRelease = false;
@@ -123,7 +123,7 @@ namespace System.Data.ProviderBase
         {
             offset += BaseOffset;
             Validate(offset, length);
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
             Debug.Assert(null != destination, "null destination");
             Debug.Assert(startIndex + length <= destination.Length, "destination too small");
 
@@ -156,7 +156,7 @@ namespace System.Data.ProviderBase
         {
             offset += BaseOffset;
             Validate(offset, 2 * length);
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
             Debug.Assert(null != destination, "null destination");
             Debug.Assert(startIndex + length <= destination.Length, "destination too small");
 
@@ -215,7 +215,7 @@ namespace System.Data.ProviderBase
         {
             offset += BaseOffset;
             Validate(offset, 2 * length);
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
             Debug.Assert(null != destination, "null destination");
             Debug.Assert(startIndex + length <= destination.Length, "destination too small");
 
@@ -267,7 +267,7 @@ namespace System.Data.ProviderBase
         {
             offset += BaseOffset;
             Validate(offset, 4 * length);
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
             Debug.Assert(null != destination, "null destination");
             Debug.Assert(startIndex + length <= destination.Length, "destination too small");
 
@@ -319,7 +319,7 @@ namespace System.Data.ProviderBase
         {
             offset += BaseOffset;
             ValidateCheck(offset, IntPtr.Size);
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
 
             IntPtr value;
             bool mustRelease = false;
@@ -364,7 +364,7 @@ namespace System.Data.ProviderBase
             Debug.Assert(null != structure, "null structure");
             offset += BaseOffset;
             ValidateCheck(offset, Marshal.SizeOf(structure.GetType()));
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
 
             bool mustRelease = false;
             RuntimeHelpers.PrepareConstrainedRegions();
@@ -412,7 +412,7 @@ namespace System.Data.ProviderBase
         {
             offset += BaseOffset;
             Validate(offset, length);
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
             Debug.Assert(null != source, "null source");
             Debug.Assert(startIndex + length <= source.Length, "source too small");
 
@@ -438,7 +438,7 @@ namespace System.Data.ProviderBase
         {
             offset += BaseOffset;
             Validate(offset, 2 * length);
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
             Debug.Assert(null != source, "null source");
             Debug.Assert(startIndex + length <= source.Length, "source too small");
 
@@ -493,7 +493,7 @@ namespace System.Data.ProviderBase
         {
             offset += BaseOffset;
             Validate(offset, 2 * length);
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
             Debug.Assert(null != source, "null source");
             Debug.Assert(startIndex + length <= source.Length, "source too small");
 
@@ -543,7 +543,7 @@ namespace System.Data.ProviderBase
         {
             offset += BaseOffset;
             Validate(offset, 4 * length);
-            Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+            Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
             Debug.Assert(null != source, "null source");
             Debug.Assert(startIndex + length <= source.Length, "source too small");
 
index 830733b..6eead85 100644 (file)
@@ -12,7 +12,7 @@ using Microsoft.Win32.SafeHandles;
 
 namespace System.Diagnostics
 {
-    internal sealed class SharedPerformanceCounter
+    internal sealed unsafe class SharedPerformanceCounter
     {
         private const int MaxSpinCount = 5000;
         internal const int DefaultCountersFileMappingSize = 524288;
@@ -78,7 +78,7 @@ namespace System.Diagnostics
         internal int _initialOffset = 4;
 
         private readonly CategoryData _categoryData;
-        private long _baseAddress;
+        private byte* _baseAddress;
         private readonly unsafe CounterEntry* _counterEntryPointer;
         private readonly string _categoryName;
         private readonly int _categoryNameHashCode;
@@ -167,7 +167,7 @@ namespace System.Diagnostics
                 int endAlignmentAdjustment = (8 - endAddressMod8) & 0x7;
                 newOffset += endAlignmentAdjustment;
 
-            } while (Interlocked.CompareExchange(ref *(int*)((IntPtr)_baseAddress).ToPointer(), newOffset, oldOffset) != oldOffset);
+            } while (Interlocked.CompareExchange(ref *(int*)_baseAddress, newOffset, oldOffset) != oldOffset);
 
             return oldOffset;
         }
@@ -242,7 +242,7 @@ namespace System.Diagnostics
                 freeMemoryOffset = CalculateAndAllocateMemory(totalSize, out alignmentAdjustment);
             }
 
-            long nextPtr = ResolveOffset(freeMemoryOffset, totalSize + alignmentAdjustment);
+            byte* nextPtr = (byte*)ResolveOffset(freeMemoryOffset, totalSize + alignmentAdjustment);
 
             CategoryEntry* newCategoryEntryPointer;
             InstanceEntry* newInstanceEntryPointer;
@@ -277,30 +277,30 @@ namespace System.Diagnostics
                 ProcessLifetimeEntry* newLifetimeEntry = (ProcessLifetimeEntry*)nextPtr;
                 nextPtr += s_processLifetimeEntrySize;
 
-                newCounterEntryPointer->LifetimeOffset = (int)((long)newLifetimeEntry - _baseAddress);
+                newCounterEntryPointer->LifetimeOffset = (int)((byte*)newLifetimeEntry - _baseAddress);
                 PopulateLifetimeEntry(newLifetimeEntry, lifetime);
             }
 
             newCategoryEntryPointer->CategoryNameHashCode = _categoryNameHashCode;
             newCategoryEntryPointer->NextCategoryOffset = 0;
-            newCategoryEntryPointer->FirstInstanceOffset = (int)((long)newInstanceEntryPointer - _baseAddress);
+            newCategoryEntryPointer->FirstInstanceOffset = (int)((byte*)newInstanceEntryPointer - _baseAddress);
             newCategoryEntryPointer->CategoryNameOffset = (int)(nextPtr - _baseAddress);
-            SafeMarshalCopy(_categoryName, (IntPtr)nextPtr);
+            SafeMarshalCopy(_categoryName, nextPtr);
             nextPtr += categoryNameLength;
 
             newInstanceEntryPointer->InstanceNameHashCode = instanceNameHashCode;
             newInstanceEntryPointer->NextInstanceOffset = 0;
-            newInstanceEntryPointer->FirstCounterOffset = (int)((long)newCounterEntryPointer - _baseAddress);
+            newInstanceEntryPointer->FirstCounterOffset = (int)((byte*)newCounterEntryPointer - _baseAddress);
             newInstanceEntryPointer->RefCount = 1;
             newInstanceEntryPointer->InstanceNameOffset = (int)(nextPtr - _baseAddress);
-            SafeMarshalCopy(instanceName, (IntPtr)nextPtr);
+            SafeMarshalCopy(instanceName, nextPtr);
             nextPtr += instanceNameLength;
 
             string counterName = (string)_categoryData.CounterNames[0];
             newCounterEntryPointer->CounterNameHashCode = GetWstrHashCode(counterName);
             SetValue(newCounterEntryPointer, 0);
             newCounterEntryPointer->CounterNameOffset = (int)(nextPtr - _baseAddress);
-            SafeMarshalCopy(counterName, (IntPtr)nextPtr);
+            SafeMarshalCopy(counterName, nextPtr);
             nextPtr += (counterName.Length + 1) * 2;
 
             CounterEntry* previousCounterEntryPointer;
@@ -313,15 +313,15 @@ namespace System.Diagnostics
                 newCounterEntryPointer->CounterNameHashCode = GetWstrHashCode(counterName);
                 SetValue(newCounterEntryPointer, 0);
                 newCounterEntryPointer->CounterNameOffset = (int)(nextPtr - _baseAddress);
-                SafeMarshalCopy(counterName, (IntPtr)nextPtr);
+                SafeMarshalCopy(counterName, nextPtr);
 
                 nextPtr += (counterName.Length + 1) * 2;
-                previousCounterEntryPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - _baseAddress);
+                previousCounterEntryPointer->NextCounterOffset = (int)((byte*)newCounterEntryPointer - _baseAddress);
             }
 
             Debug.Assert(nextPtr - _baseAddress == freeMemoryOffset + totalSize + alignmentAdjustment, "We should have used all of the space we requested at this point");
 
-            int offset = (int)((long)newCategoryEntryPointer - _baseAddress);
+            int offset = (int)((byte*)newCategoryEntryPointer - _baseAddress);
             lastCategoryPointer->IsConsistent = 0;
             // If not the first category node, link it.
             if (offset != _initialOffset)
@@ -373,8 +373,8 @@ namespace System.Diagnostics
             }
 
             freeMemoryOffset += alignmentAdjustment;
-            long nextPtr = ResolveOffset(freeMemoryOffset, totalSize);    // don't add alignmentAdjustment since it's already
-                                                                          // been added to freeMemoryOffset
+            byte* nextPtr = (byte*)ResolveOffset(freeMemoryOffset, totalSize);    // don't add alignmentAdjustment since it's already
+                                                                                  // been added to freeMemoryOffset
 
             InstanceEntry* newInstanceEntryPointer = (InstanceEntry*)nextPtr;
             nextPtr += s_instanceEntrySize;
@@ -389,17 +389,17 @@ namespace System.Diagnostics
                 ProcessLifetimeEntry* newLifetimeEntry = (ProcessLifetimeEntry*)nextPtr;
                 nextPtr += s_processLifetimeEntrySize;
 
-                newCounterEntryPointer->LifetimeOffset = (int)((long)newLifetimeEntry - _baseAddress);
+                newCounterEntryPointer->LifetimeOffset = (int)((byte*)newLifetimeEntry - _baseAddress);
                 PopulateLifetimeEntry(newLifetimeEntry, lifetime);
             }
 
             // set up the InstanceEntry
             newInstanceEntryPointer->InstanceNameHashCode = instanceNameHashCode;
             newInstanceEntryPointer->NextInstanceOffset = 0;
-            newInstanceEntryPointer->FirstCounterOffset = (int)((long)newCounterEntryPointer - _baseAddress);
+            newInstanceEntryPointer->FirstCounterOffset = (int)((byte*)newCounterEntryPointer - _baseAddress);
             newInstanceEntryPointer->RefCount = 1;
             newInstanceEntryPointer->InstanceNameOffset = (int)(nextPtr - _baseAddress);
-            SafeMarshalCopy(instanceName, (IntPtr)nextPtr);
+            SafeMarshalCopy(instanceName, nextPtr);
 
             nextPtr += instanceNameLength;
 
@@ -426,7 +426,7 @@ namespace System.Diagnostics
                     SetValue(newCounterEntryPointer, 0);
                     newCounterEntryPointer->CounterNameOffset = firstCounterInCategoryPointer->CounterNameOffset;
 
-                    previousCounterEntryPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - _baseAddress);
+                    previousCounterEntryPointer->NextCounterOffset = (int)((byte*)newCounterEntryPointer - _baseAddress);
                 }
             }
             else
@@ -438,13 +438,13 @@ namespace System.Diagnostics
                     string counterName = (string)_categoryData.CounterNames[i];
                     newCounterEntryPointer->CounterNameHashCode = GetWstrHashCode(counterName);
                     newCounterEntryPointer->CounterNameOffset = (int)(nextPtr - _baseAddress);
-                    SafeMarshalCopy(counterName, (IntPtr)nextPtr);
+                    SafeMarshalCopy(counterName, nextPtr);
                     nextPtr += (counterName.Length + 1) * 2;
 
                     SetValue(newCounterEntryPointer, 0);
 
                     if (i != 0)
-                        previousCounterEntryPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - _baseAddress);
+                        previousCounterEntryPointer->NextCounterOffset = (int)((byte*)newCounterEntryPointer - _baseAddress);
 
                     previousCounterEntryPointer = newCounterEntryPointer;
                     newCounterEntryPointer++;
@@ -453,7 +453,7 @@ namespace System.Diagnostics
 
             Debug.Assert(nextPtr - _baseAddress == freeMemoryOffset + totalSize, "We should have used all of the space we requested at this point");
 
-            int offset = (int)((long)newInstanceEntryPointer - _baseAddress);
+            int offset = (int)((byte*)newInstanceEntryPointer - _baseAddress);
             categoryPointer->IsConsistent = 0;
 
             // prepend the new instance rather than append, helps with perf of hooking up subsequent counters
@@ -482,7 +482,7 @@ namespace System.Diagnostics
 
             freeMemoryOffset += alignmentAdjustment;
 
-            long nextPtr = ResolveOffset(freeMemoryOffset, totalSize);
+            byte* nextPtr = (byte*)ResolveOffset(freeMemoryOffset, totalSize);
             CounterEntry* newCounterEntryPointer = (CounterEntry*)nextPtr;
             nextPtr += sizeof(CounterEntry);
 
@@ -490,11 +490,11 @@ namespace System.Diagnostics
             newCounterEntryPointer->CounterNameHashCode = counterNameHashCode;
             newCounterEntryPointer->NextCounterOffset = 0;
             SetValue(newCounterEntryPointer, 0);
-            SafeMarshalCopy(counterName, (IntPtr)nextPtr);
+            SafeMarshalCopy(counterName, nextPtr);
 
             Debug.Assert(nextPtr + counterNameLength - _baseAddress == freeMemoryOffset + totalSize, "We should have used all of the space we requested at this point");
 
-            lastCounterPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - _baseAddress);
+            lastCounterPointer->NextCounterOffset = (int)((byte*)newCounterEntryPointer - _baseAddress);
             return freeMemoryOffset;
         }
 
@@ -716,7 +716,7 @@ namespace System.Diagnostics
                     }
                 }
             }
-            _baseAddress = (long)data.FileMapping.FileViewAddress;
+            _baseAddress = (byte*)data.FileMapping.FileViewAddress;
 
             if (data.UseUniqueSharedMemory)
                 _initialOffset = 8;
@@ -869,7 +869,7 @@ namespace System.Diagnostics
                 {
                     if (counterPointer != null && instancePointer != null)
                     {
-                        _thisInstanceOffset = ResolveAddress((long)instancePointer, s_instanceEntrySize);
+                        _thisInstanceOffset = ResolveAddress((byte*)instancePointer, s_instanceEntrySize);
                     }
                 }
                 catch (InvalidOperationException)
@@ -1121,11 +1121,11 @@ namespace System.Diagnostics
                 {
 
                     bool hasFit;
-                    long instanceNamePtr;       // we need cache this to avoid race conditions.
+                    char* instanceNamePtr;       // we need cache this to avoid race conditions.
 
                     if (_categoryData.UseUniqueSharedMemory)
                     {
-                        instanceNamePtr = ResolveOffset(currentInstancePointer->InstanceNameOffset, InstanceNameSlotSize);
+                        instanceNamePtr = (char*)ResolveOffset(currentInstancePointer->InstanceNameOffset, InstanceNameSlotSize);
                         // In the separate shared memory case we should always have enough space for instances.  The
                         // name slot size is fixed.
                         Debug.Assert(((instanceName.Length + 1) * 2) <= InstanceNameSlotSize, "The instance name length should always fit in our slot size");
@@ -1134,12 +1134,12 @@ namespace System.Diagnostics
                     else
                     {
                         // we don't know the string length yet.
-                        instanceNamePtr = ResolveOffset(currentInstancePointer->InstanceNameOffset, 0);
+                        instanceNamePtr = (char*)ResolveOffset(currentInstancePointer->InstanceNameOffset, 0);
 
                         // In the global shared memory, we require names to be exactly the same length in order
                         // to reuse them.  This way we don't end up leaking any space and we don't need to
                         // depend on the layout of the memory to calculate the space we have.
-                        int length = GetStringLength((char*)instanceNamePtr);
+                        int length = GetStringLength(instanceNamePtr);
                         hasFit = (length == instanceName.Length);
                     }
 
@@ -1159,7 +1159,7 @@ namespace System.Diagnostics
                             try
                             {
                                 // Make copy with zero-term
-                                SafeMarshalCopy(instanceName, (IntPtr)instanceNamePtr);
+                                SafeMarshalCopy(instanceName, instanceNamePtr);
                                 currentInstancePointer->InstanceNameHashCode = instanceNameHashCode;
 
                                 // return
@@ -1224,7 +1224,7 @@ namespace System.Diagnostics
             ResolveOffset(freeOffset, 0);        // verify next free offset
 
             // begin by verifying the head node's offset
-            int currentOffset = ResolveAddress((long)currentCategoryPointer, s_categoryEntrySize);
+            int currentOffset = ResolveAddress((byte*)currentCategoryPointer, s_categoryEntrySize);
             if (currentOffset >= freeOffset)
             {
                 // zero out the bad head node entry
@@ -1621,19 +1621,19 @@ namespace System.Diagnostics
             return (((long)counterEntry & 0x7) != 0);
         }
 
-        private long ResolveOffset(int offset, int sizeToRead)
+        private unsafe void* ResolveOffset(int offset, int sizeToRead)
         {
             //It is very important to check the integrity of the shared memory
             //everytime a new address is resolved.
             if (offset > (FileView._fileMappingSize - sizeToRead) || offset < 0)
                 throw new InvalidOperationException(SR.MappingCorrupted);
 
-            long address = _baseAddress + offset;
+            void* address = (void*)(_baseAddress + offset);
 
             return address;
         }
 
-        private int ResolveAddress(long address, int sizeToRead)
+        private int ResolveAddress(byte* address, int sizeToRead)
         {
             int offset = (int)(address - _baseAddress);
 
@@ -1771,13 +1771,13 @@ namespace System.Diagnostics
         // SafeMarshalCopy always null terminates the char array
         // before copying it to native memory
         //
-        private static void SafeMarshalCopy(string str, IntPtr nativePointer)
+        private static unsafe void SafeMarshalCopy(string str, void* nativePointer)
         {
             // convert str to a char array and copy it to the unmanaged memory pointer
             char[] tmp = new char[str.Length + 1];
             str.CopyTo(0, tmp, 0, str.Length);
             tmp[str.Length] = '\0';  // make sure the char[] is null terminated
-            Marshal.Copy(tmp, 0, nativePointer, tmp.Length);
+            Marshal.Copy(tmp, 0, (nint)nativePointer, tmp.Length);
         }
 
         // <WARNING>
index ec877c7..34088e3 100644 (file)
@@ -123,7 +123,7 @@ namespace System.Diagnostics
                             _threadId = (ulong)tid,
                             _basePriority = pi.BasePriority,
                             _currentPriority = (int)stat.nice,
-                            _startAddress = IntPtr.Zero,
+                            _startAddress = null,
                             _threadState = ProcFsStateToThreadState(stat.state),
                             _threadWaitReason = ThreadWaitReason.Unknown
                         });
index 3baa7dd..621546e 100644 (file)
@@ -83,7 +83,7 @@ namespace System.Diagnostics
                     _processId = pid,
                     _threadId = t.Key,
                     _basePriority = procInfo.BasePriority,
-                    _startAddress = IntPtr.Zero
+                    _startAddress = null
                 };
 
                 // Fill in additional info if we were able to retrieve such data about the thread
index f1b2142..4ec733b 100644 (file)
@@ -576,7 +576,7 @@ namespace System.Diagnostics
             return temp;
         }
 
-        private static ThreadInfo GetThreadInfo(ReadOnlySpan<byte> instanceData, PERF_COUNTER_DEFINITION[] counters)
+        private static unsafe ThreadInfo GetThreadInfo(ReadOnlySpan<byte> instanceData, PERF_COUNTER_DEFINITION[] counters)
         {
             ThreadInfo threadInfo = new ThreadInfo();
             for (int i = 0; i < counters.Length; i++)
@@ -598,7 +598,7 @@ namespace System.Diagnostics
                         threadInfo._currentPriority = (int)value;
                         break;
                     case ValueId.StartAddress:
-                        threadInfo._startAddress = (IntPtr)value;
+                        threadInfo._startAddress = (void*)value;
                         break;
                     case ValueId.ThreadState:
                         threadInfo._threadState = (ThreadState)value;
index 215e67e..aaf8434 100644 (file)
@@ -111,9 +111,9 @@ namespace System.Diagnostics
         ///     Returns the memory address of the function that was called when the associated
         ///     thread was started.
         /// </devdoc>
-        public IntPtr StartAddress
+        public unsafe IntPtr StartAddress
         {
-            get { return _threadInfo._startAddress; }
+            get { return (IntPtr)_threadInfo._startAddress; }
         }
 
         /// <devdoc>
index 1205e73..cce0d13 100644 (file)
@@ -10,14 +10,14 @@ namespace System.Diagnostics
     ///     can throw it away all at once when Refresh is called on the component.
     /// </devdoc>
     /// <internalonly/>
-    internal sealed class ThreadInfo
+    internal sealed unsafe class ThreadInfo
     {
 #pragma warning disable CS0649 // The fields are unused on iOS/tvOS as the respective managed logic (mostly around libproc) is excluded.
         internal ulong _threadId;
         internal int _processId;
         internal int _basePriority;
         internal int _currentPriority;
-        internal IntPtr _startAddress;
+        internal void* _startAddress;
         internal ThreadState _threadState;
         internal ThreadWaitReason _threadWaitReason;
 #pragma warning restore CS0649
index 650f9c4..7e37a4c 100644 (file)
@@ -515,10 +515,9 @@ namespace System.DirectoryServices.Protocols
             return byteArray;
         }
 
-        private static int EncodingMultiByteArrayHelper(SafeBerHandle berElement, byte[][] tempValue, char fmt, nuint tag)
+        private static unsafe int EncodingMultiByteArrayHelper(SafeBerHandle berElement, byte[][] tempValue, char fmt, nuint tag)
         {
             IntPtr berValArray = IntPtr.Zero;
-            IntPtr tempPtr;
             BerVal[] managedBervalArray = null;
             int error = 0;
 
@@ -530,6 +529,7 @@ namespace System.DirectoryServices.Protocols
                     berValArray = Utility.AllocHGlobalIntPtrArray(tempValue.Length + 1);
                     int structSize = Marshal.SizeOf(typeof(BerVal));
                     managedBervalArray = new BerVal[tempValue.Length];
+                    void** pBerValArray = (void**)berValArray;
 
                     for (i = 0; i < tempValue.Length; i++)
                     {
@@ -549,12 +549,10 @@ namespace System.DirectoryServices.Protocols
                         IntPtr valPtr = Marshal.AllocHGlobal(structSize);
                         Marshal.StructureToPtr(managedBervalArray[i], valPtr, false);
 
-                        tempPtr = (IntPtr)((long)berValArray + IntPtr.Size * i);
-                        Marshal.WriteIntPtr(tempPtr, valPtr);
+                        pBerValArray[i] = (void*)valPtr;
                     }
 
-                    tempPtr = (IntPtr)((long)berValArray + IntPtr.Size * i);
-                    Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
+                    pBerValArray[i] = null;
                 }
 
                 error = BerPal.PrintBerArray(berElement, new string(fmt, 1), berValArray, tag);
index adeaa4a..73e919f 100644 (file)
@@ -707,7 +707,7 @@ namespace System.DirectoryServices.Protocols
             }
         }
 
-        public override byte[] GetValue()
+        public override unsafe byte[] GetValue()
         {
             SortKeyInterop[] nativeSortKeys = new SortKeyInterop[_keys.Length];
             for (int i = 0; i < _keys.Length; ++i)
@@ -722,18 +722,16 @@ namespace System.DirectoryServices.Protocols
 
             try
             {
-                IntPtr tempPtr = IntPtr.Zero;
+                void** pMemHandle = (void**)memHandle;
                 IntPtr sortPtr = IntPtr.Zero;
                 int i = 0;
                 for (i = 0; i < keyCount; i++)
                 {
                     sortPtr = Marshal.AllocHGlobal(structSize);
                     Marshal.StructureToPtr(nativeSortKeys[i], sortPtr, false);
-                    tempPtr = (IntPtr)((long)memHandle + IntPtr.Size * i);
-                    Marshal.WriteIntPtr(tempPtr, sortPtr);
+                    pMemHandle[i] = (void*)sortPtr;
                 }
-                tempPtr = (IntPtr)((long)memHandle + IntPtr.Size * i);
-                Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
+                pMemHandle[i] = null;
 
                 bool critical = IsCritical;
                 int error = LdapPal.CreateDirectorySortControl(UtilityHandle.GetHandle(), memHandle, critical ? (byte)1 : (byte)0, ref control);
index eee26ae..e6a9ea6 100644 (file)
@@ -529,7 +529,7 @@ namespace System.DirectoryServices.Protocols
             return s_partialResultsProcessor.GetCompleteResult((LdapPartialAsyncResult)asyncResult);
         }
 
-        private int SendRequestHelper(DirectoryRequest request, ref int messageID)
+        private unsafe int SendRequestHelper(DirectoryRequest request, ref int messageID)
         {
             IntPtr serverControlArray = IntPtr.Zero;
             LdapControl[] managedServerControls = null;
@@ -565,8 +565,6 @@ namespace System.DirectoryServices.Protocols
 
             try
             {
-                IntPtr tempPtr = IntPtr.Zero;
-
                 // Build server control.
                 managedServerControls = BuildControlArray(request.Controls, true);
                 int structSize = Marshal.SizeOf(typeof(LdapControl));
@@ -574,16 +572,15 @@ namespace System.DirectoryServices.Protocols
                 if (managedServerControls != null)
                 {
                     serverControlArray = Utility.AllocHGlobalIntPtrArray(managedServerControls.Length + 1);
+                    void** pServerControlArray = (void**)serverControlArray;
                     for (int i = 0; i < managedServerControls.Length; i++)
                     {
                         IntPtr controlPtr = Marshal.AllocHGlobal(structSize);
                         Marshal.StructureToPtr(managedServerControls[i], controlPtr, false);
-                        tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * i);
-                        Marshal.WriteIntPtr(tempPtr, controlPtr);
+                        pServerControlArray[i] = (void*)controlPtr;
                     }
 
-                    tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * managedServerControls.Length);
-                    Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
+                    pServerControlArray[managedServerControls.Length] = null;
                 }
 
                 // build client control
@@ -591,16 +588,15 @@ namespace System.DirectoryServices.Protocols
                 if (managedClientControls != null)
                 {
                     clientControlArray = Utility.AllocHGlobalIntPtrArray(managedClientControls.Length + 1);
+                    void** pClientControlArray = (void**)clientControlArray;
                     for (int i = 0; i < managedClientControls.Length; i++)
                     {
                         IntPtr controlPtr = Marshal.AllocHGlobal(structSize);
                         Marshal.StructureToPtr(managedClientControls[i], controlPtr, false);
-                        tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * i);
-                        Marshal.WriteIntPtr(tempPtr, controlPtr);
+                        pClientControlArray[i] = (void*)controlPtr;
                     }
 
-                    tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * managedClientControls.Length);
-                    Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
+                    pClientControlArray[managedClientControls.Length] = null;
                 }
 
                 if (request is DeleteRequest)
@@ -684,17 +680,16 @@ namespace System.DirectoryServices.Protocols
 
                     addModCount = (modifications == null ? 1 : modifications.Length + 1);
                     modArray = Utility.AllocHGlobalIntPtrArray(addModCount);
+                    void** pModArray = (void**)modArray;
                     int modStructSize = Marshal.SizeOf(typeof(LdapMod));
                     int i = 0;
                     for (i = 0; i < addModCount - 1; i++)
                     {
                         IntPtr controlPtr = Marshal.AllocHGlobal(modStructSize);
                         Marshal.StructureToPtr(modifications[i], controlPtr, false);
-                        tempPtr = (IntPtr)((long)modArray + IntPtr.Size * i);
-                        Marshal.WriteIntPtr(tempPtr, controlPtr);
+                        pModArray[i] = (void*)controlPtr;
                     }
-                    tempPtr = (IntPtr)((long)modArray + IntPtr.Size * i);
-                    Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
+                    pModArray[i] = null;
 
                     if (request is AddRequest)
                     {
@@ -755,16 +750,15 @@ namespace System.DirectoryServices.Protocols
                     if (attributeCount != 0)
                     {
                         searchAttributes = Utility.AllocHGlobalIntPtrArray(attributeCount + 1);
+                        void** pSearchAttributes = (void**)searchAttributes;
                         int i = 0;
                         for (i = 0; i < attributeCount; i++)
                         {
                             IntPtr controlPtr = LdapPal.StringToPtr(searchRequest.Attributes[i]);
-                            tempPtr = (IntPtr)((long)searchAttributes + IntPtr.Size * i);
-                            Marshal.WriteIntPtr(tempPtr, controlPtr);
+                            pSearchAttributes[i] = (void*)controlPtr;
                         }
 
-                        tempPtr = (IntPtr)((long)searchAttributes + IntPtr.Size * i);
-                        Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
+                        pSearchAttributes[i] = null;
                     }
 
                     // Process the scope.
@@ -951,7 +945,7 @@ namespace System.DirectoryServices.Protocols
                 int issuerNumber = trustedCAs.cIssuers;
                 for (int i = 0; i < issuerNumber; i++)
                 {
-                    IntPtr tempPtr = (IntPtr)((long)trustedCAs.aIssuers + Marshal.SizeOf(typeof(CRYPTOAPI_BLOB)) * i);
+                    IntPtr tempPtr = (IntPtr)((byte*)trustedCAs.aIssuers + Marshal.SizeOf(typeof(CRYPTOAPI_BLOB)) * (nint)i);
                     CRYPTOAPI_BLOB info = (CRYPTOAPI_BLOB)Marshal.PtrToStructure(tempPtr, typeof(CRYPTOAPI_BLOB));
                     int dataLength = info.cbData;
 
@@ -1283,7 +1277,7 @@ namespace System.DirectoryServices.Protocols
             return managedControls;
         }
 
-        internal static LdapMod[] BuildAttributes(CollectionBase directoryAttributes, ArrayList ptrToFree)
+        internal static unsafe LdapMod[] BuildAttributes(CollectionBase directoryAttributes, ArrayList ptrToFree)
         {
             LdapMod[] attributes = null;
 
@@ -1370,9 +1364,9 @@ namespace System.DirectoryServices.Protocols
                     }
 
                     attributes[i].values = Utility.AllocHGlobalIntPtrArray(valuesCount + 1);
+                    void** pAttributesValues = (void**)attributes[i].values;
                     int structSize = Marshal.SizeOf(typeof(BerVal));
                     IntPtr controlPtr;
-                    IntPtr tempPtr;
 
                     int m;
                     for (m = 0; m < valuesCount; m++)
@@ -1382,11 +1376,9 @@ namespace System.DirectoryServices.Protocols
                         // Need to free the memory allocated on the heap when we are done.
                         ptrToFree.Add(controlPtr);
                         Marshal.StructureToPtr(berValues[m], controlPtr, false);
-                        tempPtr = (IntPtr)((long)attributes[i].values + IntPtr.Size * m);
-                        Marshal.WriteIntPtr(tempPtr, controlPtr);
+                        pAttributesValues[m] = (void*)controlPtr;
                     }
-                    tempPtr = (IntPtr)((long)attributes[i].values + IntPtr.Size * m);
-                    Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
+                    pAttributesValues[m] = null;
                 }
             }
 
index 651a99f..f7fa06b 100644 (file)
@@ -553,24 +553,21 @@ namespace System.DirectoryServices.Protocols
 
             try
             {
-                IntPtr tempPtr = IntPtr.Zero;
-
                 // build server control
                 managedServerControls = LdapConnection.BuildControlArray(controls, true);
                 int structSize = Marshal.SizeOf(typeof(LdapControl));
                 if (managedServerControls != null)
                 {
                     serverControlArray = Utility.AllocHGlobalIntPtrArray(managedServerControls.Length + 1);
+                    void** pServerControlArray = (void**)serverControlArray;
                     for (int i = 0; i < managedServerControls.Length; i++)
                     {
                         IntPtr controlPtr = Marshal.AllocHGlobal(structSize);
                         Marshal.StructureToPtr(managedServerControls[i], controlPtr, false);
-                        tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * i);
-                        Marshal.WriteIntPtr(tempPtr, controlPtr);
+                        pServerControlArray[i] = (void*)controlPtr;
                     }
 
-                    tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * managedServerControls.Length);
-                    Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
+                    pServerControlArray[managedServerControls.Length] = null;
                 }
 
                 // Build client control.
@@ -578,16 +575,15 @@ namespace System.DirectoryServices.Protocols
                 if (managedClientControls != null)
                 {
                     clientControlArray = Utility.AllocHGlobalIntPtrArray(managedClientControls.Length + 1);
+                    void** pClientControlArray = (void**)clientControlArray;
                     for (int i = 0; i < managedClientControls.Length; i++)
                     {
                         IntPtr controlPtr = Marshal.AllocHGlobal(structSize);
                         Marshal.StructureToPtr(managedClientControls[i], controlPtr, false);
-                        tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * i);
-                        Marshal.WriteIntPtr(tempPtr, controlPtr);
+                        pClientControlArray[i] = (void*)controlPtr;
                     }
 
-                    tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * managedClientControls.Length);
-                    Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
+                    pClientControlArray[managedClientControls.Length] = null;
                 }
 
                 int error = LdapPal.StartTls(_connection._ldapHandle, ref serverError, ref ldapResult, serverControlArray, clientControlArray);
index 973718e..e6e9367 100644 (file)
@@ -50,48 +50,45 @@ namespace System.Drawing.Imaging
             _entries = new Color[1];
         }
 
-        internal void ConvertFromMemory(IntPtr memory)
+        internal unsafe void ConvertFromMemory(IntPtr memory)
         {
             // Memory layout is:
             //    UINT Flags
             //    UINT Count
             //    ARGB Entries[size]
 
-            _flags = Marshal.ReadInt32(memory);
+            byte* pMemory = (byte*)memory;
 
-            int size;
+            _flags = *(int*)pMemory;
 
-            size = Marshal.ReadInt32((IntPtr)((long)memory + 4));  // Marshal.SizeOf(size.GetType())
+            int size = *(int*)(pMemory + 4);
 
             _entries = new Color[size];
 
             for (int i = 0; i < size; i++)
             {
-                // use Marshal.SizeOf()
-                int argb = Marshal.ReadInt32((IntPtr)((long)memory + 8 + i * 4));
+                int argb = *(int*)(pMemory + 8 + i * 4);
                 _entries[i] = Color.FromArgb(argb);
             }
         }
 
-        internal IntPtr ConvertToMemory()
+        internal unsafe IntPtr ConvertToMemory()
         {
             // Memory layout is:
             //    UINT Flags
             //    UINT Count
             //    ARGB Entries[size]
 
-            // use Marshal.SizeOf()
             int length = _entries.Length;
             IntPtr memory = Marshal.AllocHGlobal(checked(4 * (2 + length)));
+            byte* pMemory = (byte*)memory;
 
-            Marshal.WriteInt32(memory, 0, _flags);
-            // use Marshal.SizeOf()
-            Marshal.WriteInt32((IntPtr)checked((long)memory + 4), 0, length);
+            *(int*)pMemory = _flags;
+            *(int*)(pMemory + 4) = length;
 
             for (int i = 0; i < length; i++)
             {
-                // use Marshal.SizeOf()
-                Marshal.WriteInt32((IntPtr)((long)memory + 4 * (i + 2)), 0, _entries[i].ToArgb());
+                *(int*)(pMemory + 4 * (i + 2)) = _entries[i].ToArgb();
             }
 
             return memory;
index ddf56a7..4e5620a 100644 (file)
@@ -56,15 +56,15 @@ namespace System.Drawing.Imaging
             int size = sizeof(EncoderParameterPrivate);
 
             int length = _param.Length;
-            IntPtr memory = Marshal.AllocHGlobal(checked(length * size + IntPtr.Size));
+            IntPtr memory = Marshal.AllocHGlobal(length * size + IntPtr.Size);
 
-            Marshal.WriteIntPtr(memory, (IntPtr)length);
+            Marshal.WriteIntPtr(memory, (nint)length);
 
-            long arrayOffset = checked((long)memory + IntPtr.Size);
+            byte* arrayOffset = (byte*)memory + IntPtr.Size;
 
             for (int i = 0; i < length; i++)
             {
-                Marshal.StructureToPtr(_param[i], (IntPtr)(arrayOffset + i * size), false);
+                Marshal.StructureToPtr(_param[i], (nint)(arrayOffset + (nint)i * size), false);
             }
 
             return memory;
index cf64a39..21853ff 100644 (file)
@@ -441,19 +441,20 @@ namespace System.Drawing.Imaging
             SetRemapTable(map, ColorAdjustType.Default);
         }
 
-        public void SetRemapTable(ColorMap[] map, ColorAdjustType type)
+        public unsafe void SetRemapTable(ColorMap[] map, ColorAdjustType type)
         {
             int index;
             int mapSize = map.Length;
             int size = 4; // Marshal.SizeOf(index.GetType());
             IntPtr memory = Marshal.AllocHGlobal(checked(mapSize * size * 2));
+            byte* pMemory = (byte*)memory;
 
             try
             {
                 for (index = 0; index < mapSize; index++)
                 {
-                    Marshal.StructureToPtr(map[index].OldColor.ToArgb(), (IntPtr)((long)memory + index * size * 2), false);
-                    Marshal.StructureToPtr(map[index].NewColor.ToArgb(), (IntPtr)((long)memory + index * size * 2 + size), false);
+                    Marshal.StructureToPtr(map[index].OldColor.ToArgb(), (IntPtr)(pMemory + (nint)index * size * 2), false);
+                    Marshal.StructureToPtr(map[index].NewColor.ToArgb(), (IntPtr)(pMemory + (nint)index * size * 2 + size), false);
                 }
 
                 Gdip.CheckStatus(Gdip.GdipSetImageAttributesRemapTable(
index 933589d..3a414f0 100644 (file)
@@ -169,7 +169,7 @@ namespace System.Drawing.Printing
         /// <summary>
         /// Gets the names of all printers installed on the machine.
         /// </summary>
-        public static StringCollection InstalledPrinters
+        public static unsafe StringCollection InstalledPrinters
         {
             get
             {
@@ -202,11 +202,11 @@ namespace System.Drawing.Printing
                     throw new Win32Exception();
                 }
 
+                byte* pBuffer = (byte*)buffer;
                 for (int i = 0; i < count; i++)
                 {
                     // The printer name is at offset 0
-                    //
-                    IntPtr namePointer = (IntPtr)Marshal.ReadIntPtr((IntPtr)(checked((long)buffer + i * sizeofstruct)));
+                    IntPtr namePointer = *(IntPtr*)(pBuffer + (nint)i * sizeofstruct);
                     array[i] = Marshal.PtrToStringAuto(namePointer)!;
                 }
 
@@ -820,7 +820,7 @@ namespace System.Drawing.Printing
             return GetHdevmodeInternal(PrinterNameInternal);
         }
 
-        private IntPtr GetHdevmodeInternal(string printer)
+        private unsafe IntPtr GetHdevmodeInternal(string printer)
         {
             // Create DEVMODE
             int modeSize = Interop.Winspool.DocumentProperties(NativeMethods.NullHandleRef, NativeMethods.NullHandleRef, printer, IntPtr.Zero, NativeMethods.NullHandleRef, 0);
@@ -853,7 +853,7 @@ namespace System.Drawing.Printing
                 // by checking for a large enough buffer size before copying the extrainfo buffer
                 if (_extrabytes <= mode.dmDriverExtra)
                 {
-                    IntPtr pointeroffset = (IntPtr)(checked((long)pointer + (long)mode.dmSize));
+                    IntPtr pointeroffset = (IntPtr)((byte*)pointer + mode.dmSize);
                     Marshal.Copy(_extrainfo, 0, pointeroffset, _extrabytes);
                 }
             }
@@ -910,7 +910,7 @@ namespace System.Drawing.Printing
         ///   Interop.Kernel32.GlobalFree(handle);
         ///   Where "handle" is the return value from this method.
         /// </summary>
-        public IntPtr GetHdevnames()
+        public unsafe IntPtr GetHdevnames()
         {
             string printerName = PrinterName; // the PrinterName property is slow when using the default printer
             string driver = DriverName;  // make sure we are writing out exactly the same string as we got the length of
@@ -925,14 +925,15 @@ namespace System.Drawing.Printing
             uint namesSize = (uint)checked(Marshal.SystemDefaultCharSize * (offset + namesCharacters)); // always >0
             IntPtr handle = Interop.Kernel32.GlobalAlloc(SafeNativeMethods.GMEM_MOVEABLE | SafeNativeMethods.GMEM_ZEROINIT, namesSize);
             IntPtr namesPointer = Interop.Kernel32.GlobalLock(handle);
+            byte* pNamesPointer = (byte*)namesPointer;
 
-            Marshal.WriteInt16(namesPointer, offset); // wDriverOffset
+            *(short*)(pNamesPointer) = offset; // wDriverOffset
             offset += WriteOneDEVNAME(driver, namesPointer, offset);
-            Marshal.WriteInt16((IntPtr)(checked((long)namesPointer + 2)), offset); // wDeviceOffset
+            *(short*)(pNamesPointer + 2) = offset; // wDeviceOffset
             offset += WriteOneDEVNAME(printerName, namesPointer, offset);
-            Marshal.WriteInt16((IntPtr)(checked((long)namesPointer + 4)), offset); // wOutputOffset
+            *(short*)(pNamesPointer + 4) = offset; // wOutputOffset
             offset += WriteOneDEVNAME(outPort, namesPointer, offset);
-            Marshal.WriteInt16((IntPtr)(checked((long)namesPointer + 6)), offset); // wDefault
+            *(short*)(pNamesPointer + 6) = offset; // wDefault
 
             Interop.Kernel32.GlobalUnlock(handle);
             return handle;
@@ -1020,7 +1021,7 @@ namespace System.Drawing.Printing
             return result;
         }
 
-        internal PaperSize[] Get_PaperSizes()
+        internal unsafe PaperSize[] Get_PaperSizes()
         {
             string printerName = PrinterName; //  this is quite expensive if PrinterName is left default
 
@@ -1042,17 +1043,20 @@ namespace System.Drawing.Printing
             FastDeviceCapabilities(SafeNativeMethods.DC_PAPERSIZE, dimensionsBuffer, -1, printerName);
 
             PaperSize[] result = new PaperSize[count];
+            byte* pNamesBuffer = (byte*)namesBuffer;
+            short* pKindsBuffer = (short*)kindsBuffer;
+            int* pDimensionsBuffer = (int*)dimensionsBuffer;
             for (int i = 0; i < count; i++)
             {
-                string name = Marshal.PtrToStringAuto((IntPtr)(checked((long)namesBuffer + stringSize * i)), 64)!;
+                string name = Marshal.PtrToStringAuto((nint)(pNamesBuffer + stringSize * (nint)i), 64)!;
                 int index = name.IndexOf('\0');
                 if (index > -1)
                 {
                     name = name.Substring(0, index);
                 }
-                short kind = Marshal.ReadInt16((IntPtr)(checked((long)kindsBuffer + i * 2)));
-                int width = Marshal.ReadInt32((IntPtr)(checked((long)dimensionsBuffer + i * 8)));
-                int height = Marshal.ReadInt32((IntPtr)(checked((long)dimensionsBuffer + i * 8 + 4)));
+                short kind = pKindsBuffer[i];
+                int width = pDimensionsBuffer[i * 2];
+                int height = pDimensionsBuffer[i * 2 + 1];
                 result[i] = new PaperSize((PaperKind)kind, name,
                                           PrinterUnitConvert.Convert(width, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display),
                                           PrinterUnitConvert.Convert(height, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display));
@@ -1064,7 +1068,7 @@ namespace System.Drawing.Printing
             return result;
         }
 
-        internal PaperSource[] Get_PaperSources()
+        internal unsafe PaperSource[] Get_PaperSources()
         {
             string printerName = PrinterName; //  this is quite expensive if PrinterName is left default
 
@@ -1083,17 +1087,19 @@ namespace System.Drawing.Printing
             IntPtr kindsBuffer = Marshal.AllocCoTaskMem(2 * count);
             FastDeviceCapabilities(SafeNativeMethods.DC_BINS, kindsBuffer, -1, printerName);
 
+            byte* pNamesBuffer = (byte*)namesBuffer;
+            short* pKindsBuffer = (short*)kindsBuffer;
             PaperSource[] result = new PaperSource[count];
             for (int i = 0; i < count; i++)
             {
-                string name = Marshal.PtrToStringAuto((IntPtr)(checked((long)namesBuffer + stringSize * i)), 24)!;
+                string name = Marshal.PtrToStringAuto((nint)(pNamesBuffer + stringSize * (nint)i), 24)!;
                 int index = name.IndexOf('\0');
                 if (index > -1)
                 {
                     name = name.Substring(0, index);
                 }
 
-                short kind = Marshal.ReadInt16((IntPtr)(checked((long)kindsBuffer + 2 * i)));
+                short kind = pKindsBuffer[i];
                 result[i] = new PaperSource((PaperSourceKind)kind, name);
             }
 
@@ -1102,7 +1108,7 @@ namespace System.Drawing.Printing
             return result;
         }
 
-        internal PrinterResolution[] Get_PrinterResolutions()
+        internal unsafe PrinterResolution[] Get_PrinterResolutions()
         {
             string printerName = PrinterName; //  this is quite expensive if PrinterName is left default
             PrinterResolution[] result;
@@ -1129,10 +1135,11 @@ namespace System.Drawing.Printing
             IntPtr buffer = Marshal.AllocCoTaskMem(checked(8 * count));
             FastDeviceCapabilities(SafeNativeMethods.DC_ENUMRESOLUTIONS, buffer, -1, printerName);
 
+            byte* pBuffer = (byte*)buffer;
             for (int i = 0; i < count; i++)
             {
-                int x = Marshal.ReadInt32((IntPtr)(checked((long)buffer + i * 8)));
-                int y = Marshal.ReadInt32((IntPtr)(checked((long)buffer + i * 8 + 4)));
+                int x = *(int*)(pBuffer + i * 8);
+                int y = *(int*)(pBuffer + i * 8 + 4);
                 result[i + 4] = new PrinterResolution(PrinterResolutionKind.Custom, x, y);
             }
 
@@ -1141,17 +1148,18 @@ namespace System.Drawing.Printing
         }
 
         // names is pointer to DEVNAMES
-        private static string ReadOneDEVNAME(IntPtr pDevnames, int slot)
+        private static unsafe string ReadOneDEVNAME(IntPtr pDevnames, int slot)
         {
-            int offset = checked(Marshal.SystemDefaultCharSize * Marshal.ReadInt16((IntPtr)(checked((long)pDevnames + slot * 2))));
-            string result = Marshal.PtrToStringAuto((IntPtr)(checked((long)pDevnames + offset)))!;
+            byte* bDevNames = (byte*)pDevnames;
+            int offset = Marshal.SystemDefaultCharSize * ((ushort*)bDevNames)[slot];
+            string result = Marshal.PtrToStringAuto((nint)(bDevNames + offset))!;
             return result;
         }
 
         /// <summary>
         /// Copies the relevant information out of the handle and into the PrinterSettings.
         /// </summary>
-        public void SetHdevmode(IntPtr hdevmode)
+        public unsafe void SetHdevmode(IntPtr hdevmode)
         {
             if (hdevmode == IntPtr.Zero)
                 throw new ArgumentException(SR.Format(SR.InvalidPrinterHandle, hdevmode));
@@ -1172,7 +1180,7 @@ namespace System.Drawing.Printing
             if (_extrabytes > 0)
             {
                 _extrainfo = new byte[_extrabytes];
-                Marshal.Copy((IntPtr)(checked((long)pointer + (long)mode.dmSize)), _extrainfo, 0, _extrabytes);
+                Marshal.Copy((nint)((byte*)pointer + mode.dmSize), _extrainfo, 0, _extrabytes);
             }
 
             if ((mode.dmFields & SafeNativeMethods.DM_COPIES) == SafeNativeMethods.DM_COPIES)
@@ -1234,14 +1242,14 @@ namespace System.Drawing.Printing
         }
 
         // Write null terminated string, return length of string in characters (including null)
-        private static short WriteOneDEVNAME(string str, IntPtr bufferStart, int index)
+        private static unsafe short WriteOneDEVNAME(string str, IntPtr bufferStart, int index)
         {
             str ??= "";
-            IntPtr address = (IntPtr)(checked((long)bufferStart + index * Marshal.SystemDefaultCharSize));
+            byte* address = (byte*)bufferStart + (nint)index * Marshal.SystemDefaultCharSize;
 
             char[] data = str.ToCharArray();
-            Marshal.Copy(data, 0, address, data.Length);
-            Marshal.WriteInt16((IntPtr)(checked((long)address + data.Length * 2)), 0);
+            Marshal.Copy(data, 0, (nint)address, data.Length);
+            *(short*)(address + data.Length * 2) = 0;
 
             return checked((short)(str.Length + 1));
         }
index d30e42c..7c04070 100644 (file)
@@ -74,7 +74,7 @@ internal static partial class Interop
 
     public static IntPtr VirtualAlloc(
             SafeHandle baseAddress,
-            UIntPtr size,
+            nuint size,
             int allocationType,
             int protection)
     {
index 9d14b13..f92c402 100644 (file)
@@ -60,7 +60,7 @@ namespace System.IO.MemoryMappedFiles
             if (((viewInfo.State & Interop.Kernel32.MemOptions.MEM_RESERVE) != 0) || ((ulong)viewSize < (ulong)nativeSize))
             {
                 Interop.VirtualAlloc(
-                    viewHandle, (UIntPtr)(nativeSize != MemoryMappedFile.DefaultSize ? nativeSize : viewSize),
+                    viewHandle, (nuint)(nativeSize != MemoryMappedFile.DefaultSize ? nativeSize : viewSize),
                     Interop.Kernel32.MemOptions.MEM_COMMIT, MemoryMappedFile.GetPageAccess(access));
                 int lastError = Marshal.GetLastPInvokeError();
                 if (viewHandle.IsInvalid)
index f21cb31..977816d 100644 (file)
@@ -34,7 +34,7 @@ namespace System.IO.Pipes
             }
 
             // next check whether the handle is invalid
-            SafePipeHandle safePipeHandle = new SafePipeHandle((IntPtr)result, true);
+            SafePipeHandle safePipeHandle = new SafePipeHandle((nint)result, true);
             if (safePipeHandle.IsInvalid)
             {
                 safePipeHandle.Dispose();
index fd181fb..a5c396c 100644 (file)
@@ -33,11 +33,11 @@ namespace System.Diagnostics.Tracing
                 {
                     if (IntPtr.Size == 8)
                     {
-                        decodedFields[i] = (IntPtr)BinaryPrimitives.ReadInt64LittleEndian(payload);
+                        decodedFields[i] = (nint)BinaryPrimitives.ReadInt64LittleEndian(payload);
                     }
                     else
                     {
-                        decodedFields[i] = (IntPtr)BinaryPrimitives.ReadInt32LittleEndian(payload);
+                        decodedFields[i] = (nint)BinaryPrimitives.ReadInt32LittleEndian(payload);
                     }
                     payload = payload.Slice(IntPtr.Size);
                 }
index fd6229f..d14051e 100644 (file)
@@ -2320,7 +2320,7 @@ namespace System
                 return false;
             }
 
-            IntPtr byteOffset = Unsafe.ByteOffset(
+            nint byteOffset = Unsafe.ByteOffset(
                 ref MemoryMarshal.GetReference(span),
                 ref MemoryMarshal.GetReference(other));
 
index aee2103..4c6dca1 100644 (file)
@@ -363,18 +363,18 @@ namespace System.Runtime.InteropServices
         public static IntPtr ReadIntPtr(object ptr, int ofs)
         {
 #if TARGET_64BIT
-            return (IntPtr)ReadInt64(ptr, ofs);
+            return (nint)ReadInt64(ptr, ofs);
 #else // 32
-            return (IntPtr)ReadInt32(ptr, ofs);
+            return (nint)ReadInt32(ptr, ofs);
 #endif
         }
 
         public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
         {
 #if TARGET_64BIT
-            return (IntPtr)ReadInt64(ptr, ofs);
+            return (nint)ReadInt64(ptr, ofs);
 #else // 32
-            return (IntPtr)ReadInt32(ptr, ofs);
+            return (nint)ReadInt32(ptr, ofs);
 #endif
         }
 
@@ -482,7 +482,9 @@ namespace System.Runtime.InteropServices
 #if TARGET_64BIT
             WriteInt64(ptr, ofs, (long)val);
 #else // 32
+#pragma warning disable CA2020 // Prevent from behavioral change
             WriteInt32(ptr, ofs, (int)val);
+#pragma warning restore CA2020
 #endif
         }
 
@@ -494,7 +496,9 @@ namespace System.Runtime.InteropServices
 #if TARGET_64BIT
             WriteInt64(ptr, ofs, (long)val);
 #else // 32
+#pragma warning disable CA2020 // Prevent from behavioral change
             WriteInt32(ptr, ofs, (int)val);
+#pragma warning restore CA2020
 #endif
         }
 
index 5db01a4..751035f 100644 (file)
@@ -77,11 +77,13 @@ namespace System.Threading
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         public static IntPtr Exchange(ref IntPtr location1, IntPtr value)
         {
+#pragma warning disable CA2020 // Prevent from behavioral change
 #if TARGET_64BIT
             return (IntPtr)Interlocked.Exchange(ref Unsafe.As<IntPtr, long>(ref location1), (long)value);
 #else
             return (IntPtr)Interlocked.Exchange(ref Unsafe.As<IntPtr, int>(ref location1), (int)value);
 #endif
+#pragma warning restore CA2020
         }
 
         /// <summary>Sets a platform-specific handle or pointer to a specified value and returns the original value, as an atomic operation.</summary>
@@ -133,11 +135,13 @@ namespace System.Threading
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         public static IntPtr CompareExchange(ref IntPtr location1, IntPtr value, IntPtr comparand)
         {
+#pragma warning disable CA2020 // Prevent from behavioral change
 #if TARGET_64BIT
             return (IntPtr)Interlocked.CompareExchange(ref Unsafe.As<IntPtr, long>(ref location1), (long)value, (long)comparand);
 #else
             return (IntPtr)Interlocked.CompareExchange(ref Unsafe.As<IntPtr, int>(ref location1), (int)value, (int)comparand);
 #endif
+#pragma warning restore CA2020
         }
 
         /// <summary>Compares two platform-specific handles or pointers for equality and, if they are equal, replaces the first one.</summary>
index 886ea97..80b2a21 100644 (file)
@@ -99,7 +99,7 @@ namespace System.Threading
         [NonVersionable]
         public static void Write(ref long location, long value) =>
 #if TARGET_64BIT
-            Unsafe.As<long, VolatileIntPtr>(ref location).Value = (IntPtr)value;
+            Unsafe.As<long, VolatileIntPtr>(ref location).Value = (nint)value;
 #else
             // On 32-bit, we use Interlocked, since an ordinary volatile write would not be atomic.
             Interlocked.Exchange(ref location, value);
index 1b5b1f9..757eddc 100644 (file)
@@ -14,7 +14,7 @@ namespace System.Runtime.InteropServices.JavaScript
     internal static unsafe partial class LegacyExports
     {
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // https://github.com/dotnet/runtime/issues/71425
-        public static void GetCSOwnedObjectByJSHandleRef(IntPtr jsHandle, int shouldAddInflight, out JSObject? result)
+        public static void GetCSOwnedObjectByJSHandleRef(nint jsHandle, int shouldAddInflight, out JSObject? result)
         {
             lock (JSHostImplementation.s_csOwnedObjects)
             {
@@ -56,7 +56,7 @@ namespace System.Runtime.InteropServices.JavaScript
         }
 
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // https://github.com/dotnet/runtime/issues/71425
-        public static void CreateCSOwnedProxyRef(IntPtr jsHandle, JSHostImplementation.MappedType mappedType, int shouldAddInflight, out JSObject jsObject)
+        public static void CreateCSOwnedProxyRef(nint jsHandle, JSHostImplementation.MappedType mappedType, int shouldAddInflight, out JSObject jsObject)
         {
             JSObject? res = null;
 
index f42902e..52876f9 100644 (file)
@@ -29,7 +29,7 @@ namespace System.Runtime.InteropServices.JavaScript
         }
 
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public static void ReleaseCSOwnedObject(IntPtr jsHandle)
+        public static void ReleaseCSOwnedObject(nint jsHandle)
         {
             if (jsHandle != IntPtr.Zero)
             {
@@ -318,7 +318,7 @@ namespace System.Runtime.InteropServices.JavaScript
             return signature;
         }
 
-        public static JSObject CreateCSOwnedProxy(IntPtr jsHandle)
+        public static JSObject CreateCSOwnedProxy(nint jsHandle)
         {
             JSObject? res = null;
 
index 3c07744..0df7811 100644 (file)
@@ -8,7 +8,7 @@ namespace System.Runtime.InteropServices.JavaScript
 {
     public partial class JSObject
     {
-        internal IntPtr JSHandle;
+        internal nint JSHandle;
 
         internal GCHandle? InFlight;
         internal int InFlightCounter;
index 2d32c79..91ce969 100644 (file)
@@ -174,7 +174,7 @@ namespace System.ServiceProcess
         /// <summary>
         /// The set of services that depend on this service. These are the services that will be stopped if this service is stopped.
         /// </summary>
-        public ServiceController[] DependentServices
+        public unsafe ServiceController[] DependentServices
         {
             get
             {
@@ -207,12 +207,13 @@ namespace System.ServiceProcess
                         if (!result)
                             throw new Win32Exception();
 
+                        byte* pEnumBuffer = (byte*)enumBuffer;
                         // for each of the entries in the buffer, create a new ServiceController object.
                         _dependentServices = new ServiceController[numEnumerated];
                         for (int i = 0; i < numEnumerated; i++)
                         {
                             Interop.Advapi32.ENUM_SERVICE_STATUS status = new Interop.Advapi32.ENUM_SERVICE_STATUS();
-                            IntPtr structPtr = (IntPtr)((long)enumBuffer + (i * Marshal.SizeOf<Interop.Advapi32.ENUM_SERVICE_STATUS>()));
+                            IntPtr structPtr = (IntPtr)(pEnumBuffer + ((nint)i * Marshal.SizeOf<Interop.Advapi32.ENUM_SERVICE_STATUS>()));
                             Marshal.PtrToStructure(structPtr, status);
                             _dependentServices[i] = new ServiceController(_machineName, status);
                         }
@@ -736,7 +737,7 @@ namespace System.ServiceProcess
         }
 
         /// Helper for GetDevices, GetServices, and ServicesDependedOn
-        private static T[] GetServices<T>(string machineName, int serviceType, string? group, Func<Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS, T> selector)
+        private static unsafe T[] GetServices<T>(string machineName, int serviceType, string? group, Func<Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS, T> selector)
         {
             int resumeHandle = 0;
 
@@ -777,9 +778,10 @@ namespace System.ServiceProcess
                 // Go through the block of memory it returned to us and select the results
                 //
                 services = new T[servicesReturned];
+                byte* pMemory = (byte*)memory;
                 for (int i = 0; i < servicesReturned; i++)
                 {
-                    IntPtr structPtr = (IntPtr)((long)memory + (i * Marshal.SizeOf<Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS>()));
+                    IntPtr structPtr = (IntPtr)(pMemory + ((nint)i * Marshal.SizeOf<Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS>()));
                     Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS status = new Interop.Advapi32.ENUM_SERVICE_STATUS_PROCESS();
                     Marshal.PtrToStructure(structPtr, status);
                     services[i] = selector(status);
index eba58d9..48a6c25 100644 (file)
@@ -39,7 +39,7 @@ namespace System.Speech.Internal
             Marshal.Copy(ab, 0, buffer, sizeObject);
             for (int i = 0; i < c; i++)
             {
-                ao[i] = Marshal.PtrToStructure<T>((IntPtr)((long)buffer + i * sizeOfOne));
+                ao[i] = Marshal.PtrToStructure<T>((nint)buffer + (nint)i * sizeOfOne);
             }
         }
 
@@ -52,7 +52,7 @@ namespace System.Speech.Internal
 
             for (int i = 0; i < c; i++)
             {
-                Marshal.StructureToPtr<T>(ao[i], (IntPtr)((long)buffer + i * sizeOfOne), false);
+                Marshal.StructureToPtr<T>(ao[i], (nint)buffer + (nint)i * sizeOfOne, false);
             }
 
             Marshal.Copy(buffer, ab, 0, sizeObject);
index e44843b..3731171 100644 (file)
@@ -184,7 +184,7 @@ namespace System.Speech.Internal.Synthesis
         public short ParameterType;
         public int StreamNumber;
         public long AudioStreamOffset;
-        public IntPtr Param1;   // Always just a numeric type - contains no unmanaged resources so does not need special clean-up.
+        public nint Param1;   // Always just a numeric type - contains no unmanaged resources so does not need special clean-up.
         public IntPtr Param2;   // Can be a numeric type, or pointer to string or object. Use SafeSapiLParamHandle to cleanup.
 
         public static bool operator ==(SpeechEventSapi event1, SpeechEventSapi event2) => event1.Equals(event2);
index 864b97a..9794db2 100644 (file)
@@ -292,7 +292,7 @@ namespace System.Speech.Recognition
 
                         // Get the ITN and Look for replacement phrase/
                         IntPtr itnBuffer = new((long)buffer + _serializedPhrase.ReplacementsOffset);
-                        for (int i = 0; i < _serializedPhrase.cReplacements; i++, itnBuffer = (IntPtr)((long)itnBuffer + Marshal.SizeOf<SPPHRASEREPLACEMENT>()))
+                        for (int i = 0; i < _serializedPhrase.cReplacements; i++, itnBuffer = (nint)itnBuffer + Marshal.SizeOf<SPPHRASEREPLACEMENT>())
                         {
                             SPPHRASEREPLACEMENT replacement = (SPPHRASEREPLACEMENT)Marshal.PtrToStructure<SPPHRASEREPLACEMENT>(itnBuffer);
                             string text = Marshal.PtrToStringUni(new IntPtr((long)buffer + replacement.pszReplacementText));
@@ -778,11 +778,11 @@ namespace System.Speech.Recognition
             {
                 IntPtr smlBuffer = gc.AddrOfPinnedObject();
 
-                SPSEMANTICERRORINFO semanticError = Marshal.PtrToStructure<SPSEMANTICERRORINFO>((IntPtr)((long)smlBuffer + (int)_serializedPhrase.SemanticErrorInfoOffset));
+                SPSEMANTICERRORINFO semanticError = Marshal.PtrToStructure<SPSEMANTICERRORINFO>((nint)smlBuffer + (nint)_serializedPhrase.SemanticErrorInfoOffset);
 
-                string source = Marshal.PtrToStringUni(new IntPtr((long)smlBuffer + semanticError.pszSourceOffset));
-                string description = Marshal.PtrToStringUni(new IntPtr((long)smlBuffer + semanticError.pszDescriptionOffset));
-                string script = Marshal.PtrToStringUni(new IntPtr((long)smlBuffer + semanticError.pszScriptLineOffset));
+                string source = Marshal.PtrToStringUni((nint)smlBuffer + (nint)semanticError.pszSourceOffset);
+                string description = Marshal.PtrToStringUni((nint)smlBuffer + (nint)semanticError.pszDescriptionOffset);
+                string script = Marshal.PtrToStringUni((nint)smlBuffer + (nint)semanticError.pszScriptLineOffset);
 
                 string error = string.Format(CultureInfo.InvariantCulture, "Error while evaluating semantic interpretation:\n" +
                                             "  HRESULT:     {0:x}\n" +