Skip to content

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

Open
wants to merge 27 commits into
base: main
Choose a base branch
from

Conversation

jkoritzinsky
Copy link
Member

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.

@github-actions github-actions bot added the needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners label May 14, 2025
Copy link
Contributor

@Copilot Copilot AI left a 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;

@jkoritzinsky jkoritzinsky force-pushed the unsafe-accessor-type-usage branch from 4e1e330 to d71b334 Compare May 14, 2025 21:39
Co-authored-by: Jan Kotas <[email protected]>
@teo-tsirpanis
Copy link
Contributor

There's also this:

private static Func<string, AssemblyName>? s_getAssemblyName;
private static Func<string, AssemblyName> InitGetAssemblyName()
{
Type readerType = Type.GetType(
"System.Reflection.Metadata.MetadataReader, System.Reflection.Metadata",
throwOnError: true)!;
MethodInfo? getAssemblyNameMethod = readerType.GetMethod(
"GetAssemblyName",
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static,
null,
[typeof(string)],
null) ??
throw new MissingMethodException(readerType.FullName, "GetAssemblyName");
return s_getAssemblyName = getAssemblyNameMethod.CreateDelegate<Func<string, AssemblyName>>();
}
/*
* Get the AssemblyName for a given file. This will only work
* if the file contains an assembly manifest. This method causes
* the file to be opened and closed.
*/
public static AssemblyName GetAssemblyName(string assemblyFile)
{
return (s_getAssemblyName ?? InitGetAssemblyName())(assemblyFile);
}

Copy link
Member

@jkotas jkotas left a 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();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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();
Copy link
Member

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
Copy link
Member

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");
Copy link
Member

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?

Copy link
Member Author

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.

Comment on lines +197 to +199
object sendTask = SendAsync(httpClient, requestMessage, cancellationToken);
await ((Task)sendTask).ConfigureAwait(false);
responseMessage = taskResultProperty.GetValue(sendTask)!;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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)!;

?

Comment on lines +236 to +238
object sendTask = SendAsync(httpClient, requestMessage, cancellationToken);
await ((Task)sendTask).ConfigureAwait(false);
responseMessage = taskResultProperty.GetValue(sendTask)!;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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.
Copy link
Member

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?

Copy link
Member Author

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants