# 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
# 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
public override int GetHashCode()
{
- return RuntimeHelpers.GetHashCodeOfPtr(ArgCookie);
+ return HashCode.Combine(ArgCookie);
}
// Inherited from object
case GCConfigurationType.StringUtf8:
{
- string? dataAsString = Marshal.PtrToStringUTF8((IntPtr)data);
+ string? dataAsString = Marshal.PtrToStringUTF8((nint)data);
configurationDictionary[nameAsString] = dataAsString ?? string.Empty;
break;
}
// 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
internal bool IsUnmanagedFunctionPtr()
{
- return _invocationCount == (IntPtr)(-1);
+ return _invocationCount == -1;
}
internal bool InvocationListLogicallyNull()
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[])
}
result._target = result;
result._invocationList = invocationList;
- result._invocationCount = (IntPtr)invocationCount;
+ result._invocationCount = invocationCount;
return result;
}
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
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)
{
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
protected override MethodInfo GetMethodImpl()
{
- if (_invocationCount != (IntPtr)0 && _invocationList != null)
+ if (_invocationCount != 0 && _invocationList != null)
{
// multicast case
if (_invocationList is object[] invocationList)
public override int GetHashCode()
{
- return RuntimeHelpers.GetHashCodeOfPtr(m_metadataImport2);
+ return HashCode.Combine(m_metadataImport2);
}
public override bool Equals(object? obj)
{
public static partial class RuntimeHelpers
{
- private static int s_pointerHashSeed;
-
[Intrinsic]
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void InitializeArray(Array array, RuntimeFieldHandle fldHandle);
[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.
public override int GetHashCode()
{
- return RuntimeHelpers.GetHashCodeOfPtr(Value);
+ return HashCode.Combine(Value);
}
public override bool Equals(object? obj)
public override int GetHashCode()
{
- return RuntimeHelpers.GetHashCodeOfPtr(Value);
+ return HashCode.Combine(Value);
}
public override bool Equals(object? obj)
{
if (IntPtr.Zero != pNative)
{
- Marshal.FreeCoTaskMem((IntPtr)(((long)pNative) - sizeof(uint)));
+ Marshal.FreeCoTaskMem(pNative - sizeof(uint));
}
}
} // class VBByValStrMarshaler
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
isInterpreterEntrypoint = true;
return IntPtr.Zero;
}
- else if (m_extraFunctionPointerOrData != IntPtr.Zero)
+ else if (m_extraFunctionPointerOrData != 0)
{
if (GetThunk(OpenInstanceThunk) == m_functionPointer)
{
{
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++)
case RuntimeImports.GCConfigurationType.StringUtf8:
{
- string? dataAsString = Marshal.PtrToStringUTF8((IntPtr)data);
+ string? dataAsString = Marshal.PtrToStringUTF8((nint)data);
configurationDictionary[nameAsString] = dataAsString ?? string.Empty;
break;
}
}
[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();
}
[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;
private class IntPtrCell : GenericDictionaryCell
{
- internal IntPtr Value;
+ internal nint Value;
internal override unsafe void Prepare(TypeBuilder builder)
{
}
}
}
#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);
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)
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()
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));
}
}
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;
}
}
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)
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)
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);
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;
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)
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)
{
foreach (TypeSystemEntityOrUnknown typeVal in typeArray)
{
- IntPtr ptrVal;
+ nint ptrVal;
if (typeVal.AsType != null && (typeFilter == null || typeFilter(typeVal.AsType)))
{
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;
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);
}
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);
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)
{
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);
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;
if (method.HasInstantiation || method.OwningType.HasInstantiation)
{
- MethodIL methodIL = (MethodIL)HandleToObject((IntPtr)pScope);
+ MethodIL methodIL = (MethodIL)HandleToObject((void*)pScope);
_compilation.DetectGenericCycles(methodIL.OwningMethod, method);
}
// 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))
{
// 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
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,
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,
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)
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);
}
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);
[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)]
_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);
}
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);
{
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;
}
[StructLayout(LayoutKind.Sequential)]
- internal struct CLIENT_ID
+ internal unsafe struct CLIENT_ID
{
- internal IntPtr UniqueProcess;
- internal IntPtr UniqueThread;
+ internal void* UniqueProcess;
+ internal void* UniqueThread;
}
}
}
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
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
/// <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!");
}
}
- 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;
}
/// 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);
/// <summary>
/// Handler for WM_POWERBROADCAST.
/// </summary>
- private void OnPowerModeChanged(IntPtr wParam)
+ private void OnPowerModeChanged(nint wParam)
{
PowerModes mode;
/// <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;
/// <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)
{
try
{
- if (lParam != IntPtr.Zero)
+ if (lParam != 0)
{
Marshal.FreeHGlobal(lParam);
}
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;
}
}
}
{
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);
/// <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)
{
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;
string columnname;
int ordinal;
int keyColumns = 0;
- IntPtr cbActual;
+ nint cbActual;
if (IsClosed || (_cmdWrapper == null))
{
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 ...
{
bindings.DangerousAddRef(ref mustRelease);
IntPtr ptr = bindings.ReadIntPtr(ValueOffset);
- if (ADP.PtrZero != ptr)
+ if (IntPtr.Zero != ptr)
{
value = Marshal.PtrToStringBSTR(ptr);
}
{
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);
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);
{
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);
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);
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);
{
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)
{
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();
}
// 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))
{
// 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
Marshal.StructureToPtr(propset, propsetPtr, false/*deleteold*/);
}
}
- if (ADP.PtrZero == propset.rgProperties)
+ if (IntPtr.Zero == propset.rgProperties)
{
throw new OutOfMemoryException();
}
{
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)
{
// (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;
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)
{
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
{
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);
}
}
}
return dbprops[0].dwStatus;
}
- internal DataTable? BuildInfoLiterals()
+ internal unsafe DataTable? BuildInfoLiterals()
{
using (IDBInfoWrapper wrapper = IDBInfo())
{
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();
return null;
}
string? literalValue = null;
- IntPtr literalInfo = ADP.PtrZero;
+ IntPtr literalInfo = IntPtr.Zero;
int literalCount = 0;
OleDbHResult hr;
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))
{
}
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)
{
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)
{
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
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;
// if from ADODB, connection will be null
if ((null == _connection) || (ChapterHandle.DB_NULL_HCHAPTER != chapterHandle))
{
- _rowHandleFetchCount = new IntPtr(1);
+ _rowHandleFetchCount = 1;
}
Initialize();
}
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))
{
{
ProcessResults(hr);
}
- if (0 < (int)columnCount)
+ if (0 < checked((int)columnCount))
{
- BuildSchemaTableInfoTable(columnCount.ToInt32(), columnInfos, filterITypeInfo, filterChapters);
+ BuildSchemaTableInfoTable((int)columnCount, columnInfos, filterITypeInfo, filterChapters);
}
}
}
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;
}
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;
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);
}
}
break;
default:
- info.propid = ADP.PtrZero;
+ info.propid = IntPtr.Zero;
break;
}
metainfo[rowCount] = info;
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");
}
_currentRow = 0;
- _rowFetchedCount = IntPtr.Zero;
+ _rowFetchedCount = 0;
_dbSchemaTable = null;
_visibleFieldCount = 0;
{ 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
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.
{
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
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))
{
// 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");
}
}
- 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;
}
}
}
{
if (info.type.islong)
{
- maxLen = ADP.PtrSize;
+ maxLen = IntPtr.Size;
getType = (short)((ushort)getType | (ushort)NativeDBType.BYREF);
}
else if (-1 == maxLen)
|| ((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))
|| ((null != command) && command.Connection.PropertyGetProviderOwnedMemory())) {
bindings.MemOwner = DBMemOwner.ProviderOwned;
}*/
- maxLen = ADP.PtrSize;
+ maxLen = IntPtr.Size;
getType = (short)((ushort)getType | (ushort)NativeDBType.BYREF);
}
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()
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)
{
//ProcessFailure(hr);
SafeNativeMethods.Wrapper.ClearErrorInfo();
}
- _rowFetchedCount = IntPtr.Zero;
+ _rowFetchedCount = 0;
_currentRow = 0;
_isRead = false;
}
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())
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)
internal NativeDBType type = null!; // Late-initialized
- internal IntPtr ordinal;
+ internal nint ordinal;
internal int size;
internal int flags;
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));
}
}
}
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)
if (dbtype.islong)
{ // long data (image, text, ntext)
- bytecount = ADP.PtrSize;
+ bytecount = IntPtr.Size;
if (ShouldSerializeSize())
{
size = Size;
if (ODB.LargeDataSize < bytecount)
{
- bytecount = ADP.PtrSize;
+ bytecount = IntPtr.Size;
wtype |= NativeDBType.BYREF;
}
}
}
else if (-1 == size)
{
- bytecount = ADP.PtrSize;
+ bytecount = IntPtr.Size;
wtype |= NativeDBType.BYREF;
}
else
// 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;
//[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;
{
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}");
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
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)
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)
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;
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();
{
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;
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*/);
{
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();
}
try
{
DangerousAddRef(ref mustRelease);
- if (ADP.PtrZero != this.handle)
+ if (IntPtr.Zero != this.handle)
{
propertyLookup = new Dictionary<string, OleDbPropertyInfo>(StringComparer.OrdinalIgnoreCase);
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)
{
{
// 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;
// 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
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);
}
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
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));
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 _);
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);
}
}
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);
}
}
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;
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;
}
// SxS: clearing error information is considered safe
internal static void ClearErrorInfo()
{
- Interop.OleAut32.SetErrorInfo(0, ADP.PtrZero);
+ Interop.OleAut32.SetErrorInfo(0, IntPtr.Zero);
}
}
}
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;
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;
}
{
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;
{
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");
{
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");
{
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");
{
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");
{
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;
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();
{
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");
{
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");
{
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");
{
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");
namespace System.Diagnostics
{
- internal sealed class SharedPerformanceCounter
+ internal sealed unsafe class SharedPerformanceCounter
{
private const int MaxSpinCount = 5000;
internal const int DefaultCountersFileMappingSize = 524288;
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;
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;
}
freeMemoryOffset = CalculateAndAllocateMemory(totalSize, out alignmentAdjustment);
}
- long nextPtr = ResolveOffset(freeMemoryOffset, totalSize + alignmentAdjustment);
+ byte* nextPtr = (byte*)ResolveOffset(freeMemoryOffset, totalSize + alignmentAdjustment);
CategoryEntry* newCategoryEntryPointer;
InstanceEntry* newInstanceEntryPointer;
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;
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)
}
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;
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;
SetValue(newCounterEntryPointer, 0);
newCounterEntryPointer->CounterNameOffset = firstCounterInCategoryPointer->CounterNameOffset;
- previousCounterEntryPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - _baseAddress);
+ previousCounterEntryPointer->NextCounterOffset = (int)((byte*)newCounterEntryPointer - _baseAddress);
}
}
else
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++;
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
freeMemoryOffset += alignmentAdjustment;
- long nextPtr = ResolveOffset(freeMemoryOffset, totalSize);
+ byte* nextPtr = (byte*)ResolveOffset(freeMemoryOffset, totalSize);
CounterEntry* newCounterEntryPointer = (CounterEntry*)nextPtr;
nextPtr += sizeof(CounterEntry);
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;
}
}
}
}
- _baseAddress = (long)data.FileMapping.FileViewAddress;
+ _baseAddress = (byte*)data.FileMapping.FileViewAddress;
if (data.UseUniqueSharedMemory)
_initialOffset = 8;
{
if (counterPointer != null && instancePointer != null)
{
- _thisInstanceOffset = ResolveAddress((long)instancePointer, s_instanceEntrySize);
+ _thisInstanceOffset = ResolveAddress((byte*)instancePointer, s_instanceEntrySize);
}
}
catch (InvalidOperationException)
{
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");
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);
}
try
{
// Make copy with zero-term
- SafeMarshalCopy(instanceName, (IntPtr)instanceNamePtr);
+ SafeMarshalCopy(instanceName, instanceNamePtr);
currentInstancePointer->InstanceNameHashCode = instanceNameHashCode;
// return
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
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);
// 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>
_threadId = (ulong)tid,
_basePriority = pi.BasePriority,
_currentPriority = (int)stat.nice,
- _startAddress = IntPtr.Zero,
+ _startAddress = null,
_threadState = ProcFsStateToThreadState(stat.state),
_threadWaitReason = ThreadWaitReason.Unknown
});
_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
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++)
threadInfo._currentPriority = (int)value;
break;
case ValueId.StartAddress:
- threadInfo._startAddress = (IntPtr)value;
+ threadInfo._startAddress = (void*)value;
break;
case ValueId.ThreadState:
threadInfo._threadState = (ThreadState)value;
/// 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>
/// 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
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;
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++)
{
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);
}
}
- public override byte[] GetValue()
+ public override unsafe byte[] GetValue()
{
SortKeyInterop[] nativeSortKeys = new SortKeyInterop[_keys.Length];
for (int i = 0; i < _keys.Length; ++i)
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);
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;
try
{
- IntPtr tempPtr = IntPtr.Zero;
-
// Build server control.
managedServerControls = BuildControlArray(request.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
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)
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)
{
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.
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;
return managedControls;
}
- internal static LdapMod[] BuildAttributes(CollectionBase directoryAttributes, ArrayList ptrToFree)
+ internal static unsafe LdapMod[] BuildAttributes(CollectionBase directoryAttributes, ArrayList ptrToFree)
{
LdapMod[] attributes = null;
}
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++)
// 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;
}
}
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.
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);
_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;
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;
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(
/// <summary>
/// Gets the names of all printers installed on the machine.
/// </summary>
- public static StringCollection InstalledPrinters
+ public static unsafe StringCollection InstalledPrinters
{
get
{
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)!;
}
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);
// 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);
}
}
/// 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
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;
return result;
}
- internal PaperSize[] Get_PaperSizes()
+ internal unsafe PaperSize[] Get_PaperSizes()
{
string printerName = PrinterName; // this is quite expensive if PrinterName is left default
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));
return result;
}
- internal PaperSource[] Get_PaperSources()
+ internal unsafe PaperSource[] Get_PaperSources()
{
string printerName = PrinterName; // this is quite expensive if PrinterName is left default
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);
}
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;
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);
}
}
// 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));
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)
}
// 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));
}
public static IntPtr VirtualAlloc(
SafeHandle baseAddress,
- UIntPtr size,
+ nuint size,
int allocationType,
int protection)
{
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)
}
// 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();
{
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);
}
return false;
}
- IntPtr byteOffset = Unsafe.ByteOffset(
+ nint byteOffset = Unsafe.ByteOffset(
ref MemoryMarshal.GetReference(span),
ref MemoryMarshal.GetReference(other));
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
}
#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
}
#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
}
[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>
[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>
[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);
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)
{
}
[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;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static void ReleaseCSOwnedObject(IntPtr jsHandle)
+ public static void ReleaseCSOwnedObject(nint jsHandle)
{
if (jsHandle != IntPtr.Zero)
{
return signature;
}
- public static JSObject CreateCSOwnedProxy(IntPtr jsHandle)
+ public static JSObject CreateCSOwnedProxy(nint jsHandle)
{
JSObject? res = null;
{
public partial class JSObject
{
- internal IntPtr JSHandle;
+ internal nint JSHandle;
internal GCHandle? InFlight;
internal int InFlightCounter;
/// <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
{
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);
}
}
/// 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;
// 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);
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);
}
}
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);
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);
// 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));
{
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" +