-
Notifications
You must be signed in to change notification settings - Fork 5k
Use UnsafeAccessorType in System.Private.CoreLib and the BCL #115583
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Use UnsafeAccessorType in System.Private.CoreLib and the BCL #115583
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
This PR replaces legacy reflection‐based access with the new UnsafeAccessorTypeAttribute mechanism to provide strongly-typed, direct calls for improved performance and maintainability across core libraries. Key changes include:
- Replacing reflection calls with extern methods annotated with UnsafeAccessor attributes in libraries like System.Security.Cryptography, System.Private.CoreLib, and System.Net.Requests.
- Removing intermediate reflection caching and delegate creation in favor of direct unsafe access to type members.
- Updating several helper and interop classes to use these new patterns for cleaner API interactions.
Reviewed Changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated no comments.
Show a summary per file
File | Description |
---|---|
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/XmlKeyHelper.cs | Replaces reflection-based XML element access with unsafe accessor extern methods. |
src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.Core.cs | Eliminates reflection for BinaryFormatter-related instantiation in favor of unsafe accessors. |
src/libraries/System.Private.CoreLib/src/System/ComponentModel/DefaultValueAttribute.cs | Switches from ad hoc reflection delegates to a direct unsafe accessor call for conversion. |
src/libraries/System.Private.CoreLib/src/System/AppDomain.cs | Substitutes reflection-based principal retrieval with unsafe accessor methods. |
src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs | Uses unsafe accessor extern methods to directly get/set private fields instead of reflection. |
src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/DelegateHelpers.cs | Utilizes an unsafe accessor method to create object array delegates. |
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs | Implements an unsafe accessor call to perform type conversion reliably under trimming. |
src/coreclr/System.Private.CoreLib/src/System/Diagnostics/StackFrameHelper.cs | Replaces dynamic delegate creation with unsafe accessor caching for source line info. |
src/coreclr/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs | Refactors licensing interop to use static unsafe accessor methods for COM activation. |
Comments suppressed due to low confidence (4)
src/coreclr/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs:893
- Confirm that switching to the UnsafeAccessor-based SetSavedLicenseKey call maintains the required initialization order and COM activation assumptions without side effects.
SetSavedLicenseKey(_licContext, _targetRcwType, key);
src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs:1696
- Ensure that the ref-return usage from GetImpersonationLevel supports inline assignment on all targeted platforms and behaves equivalently to the previous reflection-based implementation.
GetImpersonationLevel(GetSettings(handler)) = request.ImpersonationLevel;
src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/DelegateHelpers.cs:32
- Verify that passing null as the first parameter to CreateObjectArrayDelegate is safe and does not lead to unexpected behavior in scenarios where an instance value might be required.
return CreateObjectArrayDelegate(null, delegateType, invoker);
src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.Core.cs:116
- Review the removal of the fallback logic for s_binaryFormatterType and s_deserializeMethod to ensure that the new unsafe accessor approach does not introduce regressions in environments with differing binary formatter support.
return true;
4e1e330
to
d71b334
Compare
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/XmlKeyHelper.cs
Outdated
Show resolved
Hide resolved
Co-authored-by: Jan Kotas <[email protected]>
There's also this: runtime/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs Lines 168 to 193 in c7c961a
|
src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.Core.cs
Outdated
Show resolved
Hide resolved
src/coreclr/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs
Show resolved
Hide resolved
…descriptor for new settings property
src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/DelegateHelpers.cs
Outdated
Show resolved
Hide resolved
src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/DelegateHelpers.cs
Show resolved
Hide resolved
...aries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.InvokeNativeHandler.cs
Show resolved
Hide resolved
src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.Core.cs
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A few style nits. LGTM otherwise. Thank you!
@@ -222,7 +196,7 @@ private static Delegate CreateObjectArrayDelegateRefEmit(Type delegateType, Func | |||
// for example when running on CoreClr with PublishAot=true, this will allow IL to be emitted. | |||
// If we are running on a runtime that really doesn't support dynamic code, like NativeAOT, | |||
// CanEmitObjectArrayDelegate will be flipped to 'false', and this method won't be invoked. | |||
return ForceAllowDynamicCodeLightup.ForceAllowDynamicCodeDelegate?.Invoke(); | |||
return ForceAllowDynamicCode(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
return ForceAllowDynamicCode(); | |
return ForceAllowDynamicCode(null); | |
[UnsafeAccessor(UnsafeAccessorKind.StaticMethod, Name="ForceAllowDynamicCode")] | |
static extern IDisposable ForceAllowDynamicCode(AssemblyBuilder? _); |
Make it local?
@@ -63,7 +37,7 @@ internal static Delegate CreateObjectArrayDelegate(Type delegateType, Func<objec | |||
} | |||
else | |||
{ | |||
return DynamicDelegateLightup.CreateObjectArrayDelegate(delegateType, handler); | |||
return CreateObjectArrayDelegate(null, delegateType, handler); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
return CreateObjectArrayDelegate(null, delegateType, handler); | |
return CreateObjectArrayDelegate(null, delegateType, handler); | |
[UnsafeAccessor(UnsafeAccessorKind.StaticMethod, Name="CreateObjectArrayDelegate")] | |
static extern Delegate CreateObjectArrayDelegate( | |
[UnsafeAccessorType("Internal.Runtime.Augments.DynamicDelegateAugments, System.Private.CoreLib")] object? _, | |
Type delegateType, | |
Func<object?[], object?> invoker); |
@@ -3044,6 +3045,10 @@ private sealed class TypeDescriptorComObject | |||
// string method is the failure is silent during type load making diagnosing the issue difficult. | |||
private sealed class ComNativeDescriptorProxy : TypeDescriptionProvider | |||
{ | |||
[UnsafeAccessor(UnsafeAccessorKind.Constructor)] | |||
[return: UnsafeAccessorType("System.Windows.Forms.ComponentModel.Com2Interop.ComNativeDescriptor, System.Windows.Forms")] | |||
private static extern object CreateComNativeDescriptor(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Make it local?
(Our style https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/coding-style.md prefers to have fields the first thing in the type.)
[UnsafeAccessor(UnsafeAccessorKind.Method)] | ||
private static extern bool Contains( | ||
[UnsafeAccessorType(LicInfoHelperLicenseContextTypeName)] object? licInfoHelperContext, | ||
string assemblyName); | ||
|
||
// RCW Activation |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Style nit: Move fields to the top
} | ||
Type? taskOfHttpResponseMessageType = Type.GetType(TaskOfHttpResponseMessageTypeName, throwOnError: false); | ||
|
||
PropertyInfo? taskResultProperty = taskOfHttpResponseMessageType?.GetProperty("Result"); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There's no way to express Task<HttpResponseMessage>
and its Result
via UnsafeAccessorType?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can't represent an unknown type argument for a type in the UnsafeAccessor logic. Maybe I can play some games with my own wrapper method. I'll see what I can figure out.
object sendTask = SendAsync(httpClient, requestMessage, cancellationToken); | ||
await ((Task)sendTask).ConfigureAwait(false); | ||
responseMessage = taskResultProperty.GetValue(sendTask)!; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
object sendTask = SendAsync(httpClient, requestMessage, cancellationToken); | |
await ((Task)sendTask).ConfigureAwait(false); | |
responseMessage = taskResultProperty.GetValue(sendTask)!; | |
Task sendTask = (Task)SendAsync(httpClient, requestMessage, cancellationToken); | |
await sendTask.ConfigureAwait(false); | |
responseMessage = taskResultProperty.GetValue(sendTask)!; |
?
object sendTask = SendAsync(httpClient, requestMessage, cancellationToken); | ||
await ((Task)sendTask).ConfigureAwait(false); | ||
responseMessage = taskResultProperty.GetValue(sendTask)!; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
object sendTask = SendAsync(httpClient, requestMessage, cancellationToken); | |
await ((Task)sendTask).ConfigureAwait(false); | |
responseMessage = taskResultProperty.GetValue(sendTask)!; | |
Task sendTask = (Task)SendAsync(httpClient, requestMessage, cancellationToken); | |
await sendTask.ConfigureAwait(false); | |
responseMessage = taskResultProperty.GetValue(sendTask)!; |
{ | ||
// A type named in UnsafeAccessorType may point to a type that is forwarded. | ||
// Mark the type forwarders so we can avoid needing to rewrite the type name | ||
// in the UnsafeAccessorTypeAttribute. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
NAOT's trimmer already handles UnsafeAccessorType appropriately?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yep.
The problem here is that while both the linker and NAOT can follow type forwards, the linker must also preserve the type forwards for CoreCLR to use at runtime. Otherwise we'll trim away the type forwards we used and then CoreCLR won't have them available (what was happening beforehand).
Use the new
UnsafeAccessorTypeAttribute
to provide a more strongly-typed and straightforward mechanism to solve our layering issues in the product than the traditional Reflection API surface.