Skip to content

Commit 1ec64a7

Browse files
authored
Fix more diagnostics with CA2263 (#100490)
* Fix more diagnostics with CA2263 * Apply feedbacks
1 parent 93483ba commit 1ec64a7

File tree

38 files changed

+104
-109
lines changed

38 files changed

+104
-109
lines changed

src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComRuntimeHelpers.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ internal static ComTypes.ITypeInfo GetITypeInfoFromIDispatch(IDispatch dispatch)
166166
return typeInfo;
167167
}
168168

169-
internal static ComTypes.TYPEATTR GetTypeAttrForTypeInfo(ComTypes.ITypeInfo typeInfo)
169+
internal static unsafe ComTypes.TYPEATTR GetTypeAttrForTypeInfo(ComTypes.ITypeInfo typeInfo)
170170
{
171171
IntPtr pAttrs;
172172
typeInfo.GetTypeAttr(out pAttrs);
@@ -179,15 +179,15 @@ internal static ComTypes.TYPEATTR GetTypeAttrForTypeInfo(ComTypes.ITypeInfo type
179179

180180
try
181181
{
182-
return (ComTypes.TYPEATTR)Marshal.PtrToStructure(pAttrs, typeof(ComTypes.TYPEATTR));
182+
return *(ComTypes.TYPEATTR*)pAttrs;
183183
}
184184
finally
185185
{
186186
typeInfo.ReleaseTypeAttr(pAttrs);
187187
}
188188
}
189189

190-
internal static ComTypes.TYPELIBATTR GetTypeAttrForTypeLib(ComTypes.ITypeLib typeLib)
190+
internal static unsafe ComTypes.TYPELIBATTR GetTypeAttrForTypeLib(ComTypes.ITypeLib typeLib)
191191
{
192192
IntPtr pAttrs;
193193
typeLib.GetLibAttr(out pAttrs);
@@ -200,7 +200,7 @@ internal static ComTypes.TYPELIBATTR GetTypeAttrForTypeLib(ComTypes.ITypeLib typ
200200

201201
try
202202
{
203-
return (ComTypes.TYPELIBATTR)Marshal.PtrToStructure(pAttrs, typeof(ComTypes.TYPELIBATTR));
203+
return *(ComTypes.TYPELIBATTR*)pAttrs;
204204
}
205205
finally
206206
{

src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeEnumDesc.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ internal ComTypeEnumDesc(ComTypes.ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc
3636

3737
try
3838
{
39-
varDesc = (ComTypes.VARDESC)Marshal.PtrToStructure(p, typeof(ComTypes.VARDESC));
39+
varDesc = Marshal.PtrToStructure<ComTypes.VARDESC>(p);
4040

4141
if (varDesc.varkind == ComTypes.VARKIND.VAR_CONST)
4242
{

src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ExcepInfo.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ internal struct ExcepInfo
2929
#if DEBUG
3030
static ExcepInfo()
3131
{
32-
Debug.Assert(Marshal.SizeOf(typeof(ExcepInfo)) == Marshal.SizeOf(typeof(ComTypes.EXCEPINFO)));
32+
Debug.Assert(Marshal.SizeOf<ExcepInfo>() == Marshal.SizeOf<ComTypes.EXCEPINFO>());
3333
}
3434
#endif
3535

src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,7 @@ DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter)
328328
return new IDispatchMetaObject(parameter, this);
329329
}
330330

331-
private static void GetFuncDescForDescIndex(ComTypes.ITypeInfo typeInfo, int funcIndex, out ComTypes.FUNCDESC funcDesc, out IntPtr funcDescHandle)
331+
private static unsafe void GetFuncDescForDescIndex(ComTypes.ITypeInfo typeInfo, int funcIndex, out ComTypes.FUNCDESC funcDesc, out IntPtr funcDescHandle)
332332
{
333333
IntPtr pFuncDesc;
334334
typeInfo.GetFuncDesc(funcIndex, out pFuncDesc);
@@ -339,7 +339,7 @@ private static void GetFuncDescForDescIndex(ComTypes.ITypeInfo typeInfo, int fun
339339
throw Error.CannotRetrieveTypeInformation();
340340
}
341341

342-
funcDesc = (ComTypes.FUNCDESC)Marshal.PtrToStructure(pFuncDesc, typeof(ComTypes.FUNCDESC));
342+
funcDesc = *(ComTypes.FUNCDESC*)pFuncDesc;
343343
funcDescHandle = pFuncDesc;
344344
}
345345

src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1439,7 +1439,7 @@ private static void SetParameterDataForMethProp(MethodOrPropertySymbol methProp,
14391439
if (parameters.Length > 0)
14401440
{
14411441
// See if we have a param array.
1442-
if (parameters[parameters.Length - 1].GetCustomAttribute(typeof(ParamArrayAttribute), false) != null)
1442+
if (parameters[parameters.Length - 1].GetCustomAttribute<ParamArrayAttribute>(false) != null)
14431443
{
14441444
methProp.isParamArray = true;
14451445
}

src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.Keyed.cs

-1
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,6 @@ public static IServiceCollection AddKeyedScoped<TService, TImplementation>(
327327
return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory);
328328
}
329329

330-
331330
/// <summary>
332331
/// Adds a singleton service of the type specified in <paramref name="serviceType"/> with an
333332
/// implementation of the type specified in <paramref name="implementationType"/> to the

src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/FileSystem.vb

+8-8
Original file line numberDiff line numberDiff line change
@@ -892,7 +892,7 @@ Namespace Microsoft.VisualBasic.FileIO
892892
Private Shared Sub CopyOrMoveDirectory(ByVal operation As CopyOrMove,
893893
ByVal sourceDirectoryName As String, ByVal destinationDirectoryName As String,
894894
ByVal overwrite As Boolean, ByVal showUI As UIOptionInternal, ByVal onUserCancel As UICancelOption)
895-
Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), operation), "Invalid Operation")
895+
Debug.Assert([Enum].IsDefined(operation), "Invalid Operation")
896896

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

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

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

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

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

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

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

src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs

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

317317
// Add item to end of list. Note: If event handler returned an item not of type T,
318318
// the cast below will trigger an InvalidCastException. This is by design.

src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ internal SidList(Interop.SID_AND_ATTRIBUTES[] sidAndAttr)
6262
TranslateSids(null, pSids);
6363
}
6464

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

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

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

164164
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: got {0} groups in {1} domains", sidCount, domainCount);

src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ out pClientContext
131131

132132
// Extract TOKEN_GROUPS.GroupCount
133133

134-
Interop.TOKEN_GROUPS tokenGroups = (Interop.TOKEN_GROUPS)Marshal.PtrToStructure(pBuffer, typeof(Interop.TOKEN_GROUPS));
134+
Interop.TOKEN_GROUPS tokenGroups = *(Interop.TOKEN_GROUPS*)pBuffer;
135135

136136
uint groupCount = tokenGroups.GroupCount;
137137

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

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

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

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

153153
_groupSidList = new SidList(groups);

src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1053,7 +1053,7 @@ private void LoadComputerInfo()
10531053
if (err == 0)
10541054
{
10551055
UnsafeNativeMethods.WKSTA_INFO_100 wkstaInfo =
1056-
(UnsafeNativeMethods.WKSTA_INFO_100)Marshal.PtrToStructure(buffer, typeof(UnsafeNativeMethods.WKSTA_INFO_100));
1056+
Marshal.PtrToStructure<UnsafeNativeMethods.WKSTA_INFO_100>(buffer);
10571057

10581058
_machineFlatName = wkstaInfo.wki100_computername;
10591059
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo: machineFlatName={0}", _machineFlatName);

src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs

+8-10
Original file line numberDiff line numberDiff line change
@@ -198,15 +198,14 @@ internal static SidType ClassifySID(byte[] sid)
198198
}
199199

200200

201-
internal static SidType ClassifySID(IntPtr pSid)
201+
internal static unsafe SidType ClassifySID(IntPtr pSid)
202202
{
203203
Debug.Assert(Interop.Advapi32.IsValidSid(pSid));
204204

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

208-
Interop.Advapi32.SID_IDENTIFIER_AUTHORITY identAuth =
209-
(Interop.Advapi32.SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(Interop.Advapi32.SID_IDENTIFIER_AUTHORITY));
208+
Interop.Advapi32.SID_IDENTIFIER_AUTHORITY identAuth = *(Interop.Advapi32.SID_IDENTIFIER_AUTHORITY*)pIdentAuth;
210209

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

335334

336-
internal static IntPtr GetCurrentUserSid()
335+
internal static unsafe IntPtr GetCurrentUserSid()
337336
{
338337
SafeTokenHandle tokenHandle = null;
339338
IntPtr pBuffer = IntPtr.Zero;
@@ -425,7 +424,7 @@ out tokenHandle
425424
}
426425

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

431430
Debug.Assert(Interop.Advapi32.IsValidSid(pUserSid));
@@ -457,7 +456,7 @@ out tokenHandle
457456
}
458457

459458

460-
internal static IntPtr GetMachineDomainSid()
459+
internal static unsafe IntPtr GetMachineDomainSid()
461460
{
462461
SafeLsaPolicyHandle policyHandle = null;
463462
IntPtr pBuffer = IntPtr.Zero;
@@ -496,8 +495,7 @@ internal static IntPtr GetMachineDomainSid()
496495
}
497496

498497
Debug.Assert(pBuffer != IntPtr.Zero);
499-
UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO info = (UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO)
500-
Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO));
498+
UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO info = *(UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO*)pBuffer;
501499

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

@@ -570,7 +568,7 @@ internal static UnsafeNativeMethods.DomainControllerInfo GetDcName(string comput
570568
}
571569

572570
UnsafeNativeMethods.DomainControllerInfo domainControllerInfo =
573-
(UnsafeNativeMethods.DomainControllerInfo)Marshal.PtrToStructure(domainControllerInfoPtr, typeof(UnsafeNativeMethods.DomainControllerInfo));
571+
Marshal.PtrToStructure<UnsafeNativeMethods.DomainControllerInfo>(domainControllerInfoPtr);
574572

575573
return domainControllerInfo;
576574
}
@@ -802,7 +800,7 @@ internal static bool IsMachineDC(string computerName)
802800
}
803801

804802
UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC dsRolePrimaryDomainInfo =
805-
(UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC)Marshal.PtrToStructure(dsRoleInfoPtr, typeof(UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC));
803+
Marshal.PtrToStructure<UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC>(dsRoleInfoPtr);
806804

807805
return (dsRolePrimaryDomainInfo.MachineRole == UnsafeNativeMethods.DSROLE_MACHINE_ROLE.DsRole_RoleBackupDomainController ||
808806
dsRolePrimaryDomainInfo.MachineRole == UnsafeNativeMethods.DSROLE_MACHINE_ROLE.DsRole_RolePrimaryDomainController);

src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -527,7 +527,7 @@ private static unsafe int EncodingMultiByteArrayHelper(SafeBerHandle berElement,
527527
{
528528
int i = 0;
529529
berValArray = Utility.AllocHGlobalIntPtrArray(tempValue.Length + 1);
530-
int structSize = Marshal.SizeOf(typeof(BerVal));
530+
int structSize = Marshal.SizeOf<BerVal>();
531531
managedBervalArray = new BerVal[tempValue.Length];
532532
void** pBerValArray = (void**)berValArray;
533533

src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -716,7 +716,7 @@ public override unsafe byte[] GetValue()
716716
}
717717

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

0 commit comments

Comments
 (0)