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

Merged
merged 30 commits into from
Jun 10, 2025

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!

@teo-tsirpanis teo-tsirpanis added area-Meta and removed needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners labels May 31, 2025
Copy link
Contributor

Tagging subscribers to this area: @dotnet/area-meta
See info in area-owners.md if you want to be subscribed.

@jkoritzinsky
Copy link
Member Author

/ba-g ios failure unrelated

@kotlarmilos
Copy link
Member

I think this commit caused a runtime initialization error in iOS library mode: #116558. I tested against the latest main branch without this change, and it worked correctly. I assume it is calling into UnsafeAccessor methods that have no actual implementation in the Mono runtime.

@jkoritzinsky Do you have an idea what could be the cause? If not, I’ll disable the test to avoid polluting the CI.

@jkoritzinsky
Copy link
Member Author

I don't know which type might not be on Mono (99% of these types are in the shared BCL).

If this could have been caused by an invalid UnsafeAccessor, I did just fix one around HttpClient. If this test is still broken in main then I'm not sure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

8 participants