Skip to content

Commit

Permalink
Fix more diagnostics with CA2263 (#100490)
Browse files Browse the repository at this point in the history
* Fix more diagnostics with CA2263

* Apply feedbacks
  • Loading branch information
buyaa-n authored Apr 2, 2024
1 parent 93483ba commit 1ec64a7
Show file tree
Hide file tree
Showing 38 changed files with 104 additions and 109 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ internal static ComTypes.ITypeInfo GetITypeInfoFromIDispatch(IDispatch dispatch)
return typeInfo;
}

internal static ComTypes.TYPEATTR GetTypeAttrForTypeInfo(ComTypes.ITypeInfo typeInfo)
internal static unsafe ComTypes.TYPEATTR GetTypeAttrForTypeInfo(ComTypes.ITypeInfo typeInfo)
{
IntPtr pAttrs;
typeInfo.GetTypeAttr(out pAttrs);
Expand All @@ -179,15 +179,15 @@ internal static ComTypes.TYPEATTR GetTypeAttrForTypeInfo(ComTypes.ITypeInfo type

try
{
return (ComTypes.TYPEATTR)Marshal.PtrToStructure(pAttrs, typeof(ComTypes.TYPEATTR));
return *(ComTypes.TYPEATTR*)pAttrs;
}
finally
{
typeInfo.ReleaseTypeAttr(pAttrs);
}
}

internal static ComTypes.TYPELIBATTR GetTypeAttrForTypeLib(ComTypes.ITypeLib typeLib)
internal static unsafe ComTypes.TYPELIBATTR GetTypeAttrForTypeLib(ComTypes.ITypeLib typeLib)
{
IntPtr pAttrs;
typeLib.GetLibAttr(out pAttrs);
Expand All @@ -200,7 +200,7 @@ internal static ComTypes.TYPELIBATTR GetTypeAttrForTypeLib(ComTypes.ITypeLib typ

try
{
return (ComTypes.TYPELIBATTR)Marshal.PtrToStructure(pAttrs, typeof(ComTypes.TYPELIBATTR));
return *(ComTypes.TYPELIBATTR*)pAttrs;
}
finally
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ internal ComTypeEnumDesc(ComTypes.ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc

try
{
varDesc = (ComTypes.VARDESC)Marshal.PtrToStructure(p, typeof(ComTypes.VARDESC));
varDesc = Marshal.PtrToStructure<ComTypes.VARDESC>(p);

if (varDesc.varkind == ComTypes.VARKIND.VAR_CONST)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ internal struct ExcepInfo
#if DEBUG
static ExcepInfo()
{
Debug.Assert(Marshal.SizeOf(typeof(ExcepInfo)) == Marshal.SizeOf(typeof(ComTypes.EXCEPINFO)));
Debug.Assert(Marshal.SizeOf<ExcepInfo>() == Marshal.SizeOf<ComTypes.EXCEPINFO>());
}
#endif

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter)
return new IDispatchMetaObject(parameter, this);
}

private static void GetFuncDescForDescIndex(ComTypes.ITypeInfo typeInfo, int funcIndex, out ComTypes.FUNCDESC funcDesc, out IntPtr funcDescHandle)
private static unsafe void GetFuncDescForDescIndex(ComTypes.ITypeInfo typeInfo, int funcIndex, out ComTypes.FUNCDESC funcDesc, out IntPtr funcDescHandle)
{
IntPtr pFuncDesc;
typeInfo.GetFuncDesc(funcIndex, out pFuncDesc);
Expand All @@ -339,7 +339,7 @@ private static void GetFuncDescForDescIndex(ComTypes.ITypeInfo typeInfo, int fun
throw Error.CannotRetrieveTypeInformation();
}

funcDesc = (ComTypes.FUNCDESC)Marshal.PtrToStructure(pFuncDesc, typeof(ComTypes.FUNCDESC));
funcDesc = *(ComTypes.FUNCDESC*)pFuncDesc;
funcDescHandle = pFuncDesc;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1439,7 +1439,7 @@ private static void SetParameterDataForMethProp(MethodOrPropertySymbol methProp,
if (parameters.Length > 0)
{
// See if we have a param array.
if (parameters[parameters.Length - 1].GetCustomAttribute(typeof(ParamArrayAttribute), false) != null)
if (parameters[parameters.Length - 1].GetCustomAttribute<ParamArrayAttribute>(false) != null)
{
methProp.isParamArray = true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,6 @@ public static IServiceCollection AddKeyedScoped<TService, TImplementation>(
return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory);
}


/// <summary>
/// Adds a singleton service of the type specified in <paramref name="serviceType"/> with an
/// implementation of the type specified in <paramref name="implementationType"/> to the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -892,7 +892,7 @@ Namespace Microsoft.VisualBasic.FileIO
Private Shared Sub CopyOrMoveDirectory(ByVal operation As CopyOrMove,
ByVal sourceDirectoryName As String, ByVal destinationDirectoryName As String,
ByVal overwrite As Boolean, ByVal showUI As UIOptionInternal, ByVal onUserCancel As UICancelOption)
Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), operation), "Invalid Operation")
Debug.Assert([Enum].IsDefined(operation), "Invalid Operation")

' Verify enums.
VerifyUICancelOption("onUserCancel", onUserCancel)
Expand Down Expand Up @@ -961,7 +961,7 @@ Namespace Microsoft.VisualBasic.FileIO
Private Shared Sub FxCopyOrMoveDirectory(ByVal operation As CopyOrMove,
ByVal sourceDirectoryPath As String, ByVal targetDirectoryPath As String, ByVal overwrite As Boolean)

Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), operation), "Invalid Operation")
Debug.Assert([Enum].IsDefined(operation), "Invalid Operation")
Debug.Assert(sourceDirectoryPath <> "" And IO.Path.IsPathRooted(sourceDirectoryPath), "Invalid Source")
Debug.Assert(targetDirectoryPath <> "" And IO.Path.IsPathRooted(targetDirectoryPath), "Invalid Target")

Expand Down Expand Up @@ -1010,7 +1010,7 @@ Namespace Microsoft.VisualBasic.FileIO
Private Shared Sub CopyOrMoveDirectoryNode(ByVal Operation As CopyOrMove,
ByVal SourceDirectoryNode As DirectoryNode, ByVal Overwrite As Boolean, ByVal Exceptions As ListDictionary)

Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), Operation), "Invalid Operation")
Debug.Assert([Enum].IsDefined(Operation), "Invalid Operation")
Debug.Assert(Exceptions IsNot Nothing, "Null exception list")
Debug.Assert(SourceDirectoryNode IsNot Nothing, "Null source node")

Expand Down Expand Up @@ -1092,7 +1092,7 @@ Namespace Microsoft.VisualBasic.FileIO
ByVal sourceFileName As String, ByVal destinationFileName As String,
ByVal overwrite As Boolean, ByVal showUI As UIOptionInternal, ByVal onUserCancel As UICancelOption
)
Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), operation), "Invalid Operation")
Debug.Assert([Enum].IsDefined(operation), "Invalid Operation")

' Verify enums.
VerifyUICancelOption("onUserCancel", onUserCancel)
Expand Down Expand Up @@ -1597,8 +1597,8 @@ Namespace Microsoft.VisualBasic.FileIO
''' </remarks>
Private Shared Sub ShellCopyOrMove(ByVal Operation As CopyOrMove, ByVal TargetType As FileOrDirectory,
ByVal FullSourcePath As String, ByVal FullTargetPath As String, ByVal ShowUI As UIOptionInternal, ByVal OnUserCancel As UICancelOption)
Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), Operation))
Debug.Assert(System.Enum.IsDefined(GetType(FileOrDirectory), TargetType))
Debug.Assert([Enum].IsDefined(Operation))
Debug.Assert([Enum].IsDefined(TargetType))
Debug.Assert(FullSourcePath <> "" And IO.Path.IsPathRooted(FullSourcePath), "Invalid FullSourcePath")
Debug.Assert(FullTargetPath <> "" And IO.Path.IsPathRooted(FullTargetPath), "Invalid FullTargetPath")
Debug.Assert(ShowUI <> UIOptionInternal.NoUI, "Why call ShellDelete if ShowUI is NoUI???")
Expand Down Expand Up @@ -1693,7 +1693,7 @@ Namespace Microsoft.VisualBasic.FileIO
Private Shared Sub ShellFileOperation(ByVal OperationType As SHFileOperationType, ByVal OperationFlags As ShFileOperationFlags,
ByVal FullSource As String, ByVal FullTarget As String, ByVal OnUserCancel As UICancelOption, ByVal FileOrDirectory As FileOrDirectory)

Debug.Assert(System.Enum.IsDefined(GetType(SHFileOperationType), OperationType))
Debug.Assert([Enum].IsDefined(OperationType))
Debug.Assert(OperationType <> SHFileOperationType.FO_RENAME, "Don't call Shell to rename")
Debug.Assert(FullSource <> "" And IO.Path.IsPathRooted(FullSource), "Invalid FullSource path")
Debug.Assert(OperationType = SHFileOperationType.FO_DELETE OrElse (FullTarget <> "" And IO.Path.IsPathRooted(FullTarget)), "Invalid FullTarget path")
Expand Down Expand Up @@ -1750,7 +1750,7 @@ Namespace Microsoft.VisualBasic.FileIO
Private Shared Function GetShellOperationInfo(
ByVal OperationType As SHFileOperationType, ByVal OperationFlags As ShFileOperationFlags,
ByVal SourcePaths() As String, Optional ByVal TargetPath As String = Nothing) As SHFILEOPSTRUCT
Debug.Assert(System.Enum.IsDefined(GetType(SHFileOperationType), OperationType), "Invalid OperationType")
Debug.Assert([Enum].IsDefined(OperationType), "Invalid OperationType")
Debug.Assert(TargetPath = "" Or IO.Path.IsPathRooted(TargetPath), "Invalid TargetPath")
Debug.Assert(SourcePaths IsNot Nothing AndAlso SourcePaths.Length > 0, "Invalid SourcePaths")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ public virtual void EndNew(int itemIndex)
{
// Allow event handler to supply the new item for us
// If event handler did not supply new item, create one ourselves
object? newItem = FireAddingNew() ?? Activator.CreateInstance(typeof(T));
object? newItem = FireAddingNew() ?? Activator.CreateInstance<T>();

// Add item to end of list. Note: If event handler returned an item not of type T,
// the cast below will trigger an InvalidCastException. This is by design.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ internal SidList(Interop.SID_AND_ATTRIBUTES[] sidAndAttr)
TranslateSids(null, pSids);
}

private void TranslateSids(string target, IntPtr[] pSids)
private unsafe void TranslateSids(string target, IntPtr[] pSids)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: processing {0} SIDs", pSids.Length);

Expand Down Expand Up @@ -157,8 +157,8 @@ private void TranslateSids(string target, IntPtr[] pSids)

for (int i = 0; i < domainCount; i++)
{
domains[i] = (Interop.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(pCurrentDomain, typeof(Interop.LSA_TRUST_INFORMATION));
pCurrentDomain = new IntPtr(pCurrentDomain.ToInt64() + Marshal.SizeOf(typeof(Interop.LSA_TRUST_INFORMATION)));
domains[i] = *(Interop.LSA_TRUST_INFORMATION*)pCurrentDomain;
pCurrentDomain += sizeof(Interop.LSA_TRUST_INFORMATION);
}

GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: got {0} groups in {1} domains", sidCount, domainCount);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ out pClientContext

// Extract TOKEN_GROUPS.GroupCount

Interop.TOKEN_GROUPS tokenGroups = (Interop.TOKEN_GROUPS)Marshal.PtrToStructure(pBuffer, typeof(Interop.TOKEN_GROUPS));
Interop.TOKEN_GROUPS tokenGroups = *(Interop.TOKEN_GROUPS*)pBuffer;

uint groupCount = tokenGroups.GroupCount;

Expand All @@ -141,13 +141,13 @@ out pClientContext
// each native SID_AND_ATTRIBUTES into a managed SID_AND_ATTR.
Interop.SID_AND_ATTRIBUTES[] groups = new Interop.SID_AND_ATTRIBUTES[groupCount];

IntPtr currentItem = new IntPtr(pBuffer.ToInt64() + Marshal.SizeOf(typeof(Interop.TOKEN_GROUPS)) - sizeof(Interop.SID_AND_ATTRIBUTES));
IntPtr currentItem = pBuffer + sizeof(Interop.TOKEN_GROUPS) - sizeof(Interop.SID_AND_ATTRIBUTES);

for (int i = 0; i < groupCount; i++)
{
groups[i] = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure(currentItem, typeof(Interop.SID_AND_ATTRIBUTES));
groups[i] = *(Interop.SID_AND_ATTRIBUTES*)currentItem;

currentItem = new IntPtr(currentItem.ToInt64() + Marshal.SizeOf(typeof(Interop.SID_AND_ATTRIBUTES)));
currentItem += sizeof(Interop.SID_AND_ATTRIBUTES);
}

_groupSidList = new SidList(groups);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1053,7 +1053,7 @@ private void LoadComputerInfo()
if (err == 0)
{
UnsafeNativeMethods.WKSTA_INFO_100 wkstaInfo =
(UnsafeNativeMethods.WKSTA_INFO_100)Marshal.PtrToStructure(buffer, typeof(UnsafeNativeMethods.WKSTA_INFO_100));
Marshal.PtrToStructure<UnsafeNativeMethods.WKSTA_INFO_100>(buffer);

_machineFlatName = wkstaInfo.wki100_computername;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo: machineFlatName={0}", _machineFlatName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,15 +198,14 @@ internal static SidType ClassifySID(byte[] sid)
}


internal static SidType ClassifySID(IntPtr pSid)
internal static unsafe SidType ClassifySID(IntPtr pSid)
{
Debug.Assert(Interop.Advapi32.IsValidSid(pSid));

// Get the issuing authority and the first RID
IntPtr pIdentAuth = Interop.Advapi32.GetSidIdentifierAuthority(pSid);

Interop.Advapi32.SID_IDENTIFIER_AUTHORITY identAuth =
(Interop.Advapi32.SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(Interop.Advapi32.SID_IDENTIFIER_AUTHORITY));
Interop.Advapi32.SID_IDENTIFIER_AUTHORITY identAuth = *(Interop.Advapi32.SID_IDENTIFIER_AUTHORITY*)pIdentAuth;

IntPtr pRid = Interop.Advapi32.GetSidSubAuthority(pSid, 0);
int rid = Marshal.ReadInt32(pRid);
Expand Down Expand Up @@ -333,7 +332,7 @@ internal static bool IsSamUser()
}


internal static IntPtr GetCurrentUserSid()
internal static unsafe IntPtr GetCurrentUserSid()
{
SafeTokenHandle tokenHandle = null;
IntPtr pBuffer = IntPtr.Zero;
Expand Down Expand Up @@ -425,7 +424,7 @@ out tokenHandle
}

// Retrieve the user's SID from the user info
Interop.TOKEN_USER tokenUser = (Interop.TOKEN_USER)Marshal.PtrToStructure(pBuffer, typeof(Interop.TOKEN_USER));
Interop.TOKEN_USER tokenUser = *(Interop.TOKEN_USER*)pBuffer;
IntPtr pUserSid = tokenUser.sidAndAttributes.Sid; // this is a reference into the NATIVE memory (into pBuffer)

Debug.Assert(Interop.Advapi32.IsValidSid(pUserSid));
Expand Down Expand Up @@ -457,7 +456,7 @@ out tokenHandle
}


internal static IntPtr GetMachineDomainSid()
internal static unsafe IntPtr GetMachineDomainSid()
{
SafeLsaPolicyHandle policyHandle = null;
IntPtr pBuffer = IntPtr.Zero;
Expand Down Expand Up @@ -496,8 +495,7 @@ internal static IntPtr GetMachineDomainSid()
}

Debug.Assert(pBuffer != IntPtr.Zero);
UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO info = (UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO)
Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO));
UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO info = *(UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO*)pBuffer;

Debug.Assert(Interop.Advapi32.IsValidSid(info.DomainSid));

Expand Down Expand Up @@ -570,7 +568,7 @@ internal static UnsafeNativeMethods.DomainControllerInfo GetDcName(string comput
}

UnsafeNativeMethods.DomainControllerInfo domainControllerInfo =
(UnsafeNativeMethods.DomainControllerInfo)Marshal.PtrToStructure(domainControllerInfoPtr, typeof(UnsafeNativeMethods.DomainControllerInfo));
Marshal.PtrToStructure<UnsafeNativeMethods.DomainControllerInfo>(domainControllerInfoPtr);

return domainControllerInfo;
}
Expand Down Expand Up @@ -802,7 +800,7 @@ internal static bool IsMachineDC(string computerName)
}

UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC dsRolePrimaryDomainInfo =
(UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC)Marshal.PtrToStructure(dsRoleInfoPtr, typeof(UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC));
Marshal.PtrToStructure<UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC>(dsRoleInfoPtr);

return (dsRolePrimaryDomainInfo.MachineRole == UnsafeNativeMethods.DSROLE_MACHINE_ROLE.DsRole_RoleBackupDomainController ||
dsRolePrimaryDomainInfo.MachineRole == UnsafeNativeMethods.DSROLE_MACHINE_ROLE.DsRole_RolePrimaryDomainController);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ private static unsafe int EncodingMultiByteArrayHelper(SafeBerHandle berElement,
{
int i = 0;
berValArray = Utility.AllocHGlobalIntPtrArray(tempValue.Length + 1);
int structSize = Marshal.SizeOf(typeof(BerVal));
int structSize = Marshal.SizeOf<BerVal>();
managedBervalArray = new BerVal[tempValue.Length];
void** pBerValArray = (void**)berValArray;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -716,7 +716,7 @@ public override unsafe byte[] GetValue()
}

IntPtr control = IntPtr.Zero;
int structSize = Marshal.SizeOf(typeof(SortKeyInterop));
int structSize = Marshal.SizeOf<SortKeyInterop>();
int keyCount = nativeSortKeys.Length;
IntPtr memHandle = Utility.AllocHGlobalIntPtrArray(keyCount + 1);

Expand Down
Loading

0 comments on commit 1ec64a7

Please sign in to comment.