Repository navigation
Make DisablePrivateReflectionAttribute work: hide the non public types of an assembly from reflection - #138109
Draft
Sergio0694 wants to merge 1 commit into
Draft
Sergio0694 wants to merge 1 commit into
Sergio0694 wants to merge 1 commit into
Conversation
|
Azure Pipelines: Successfully started running 4 pipeline(s). 11 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
16 tasks
Contributor
|
Tagging subscribers to this area: @steveisok, @dotnet/area-system-reflection |
jkotas
reviewed
Nov 23, 2026
| * enums and delegates: the runtime needs their metadata (`Enum.ToString`, `Delegate.DynamicInvoke`) | ||
| * top-level types that derive from `System.Attribute`: attributes are meant to be read, and the compiler embeds some in every assembly | ||
| (`NullableAttribute`) to describe the public types. Attribute classes nested in other types are blocked with them. | ||
| * types that declare generic virtual methods: the runtime type loader identifies these methods by their metadata |
Member
There was a problem hiding this comment.
The design should be justified from user point of view.
Current implementation details are not a good user-centric justification.
Open
3 tasks
3 tasks
…s and members of an assembly from reflection Un-obsolete System.Runtime.CompilerServices.DisablePrivateReflectionAttribute (assembly level, no API shape change) and give it an effect in NativeAOT and CoreCLR. In an assembly that has the attribute: * The types that are not externally visible (not public, or nested in a type that is not public) are not available to reflection: no members, nested types or custom attributes, no names (a placeholder is returned), they are not found by name or listed, and handles to their members can not be converted to MethodBase/FieldInfo. * The non public members of every type, also of the public ones, are not available either: private, internal, protected, protected internal, private protected, explicit interface implementations and backing fields (only the public members of an externally visible type are). A property or event is available if one of its accessors is. They are not returned by the member lists, not found by name (GetMethod, InvokeMember, Delegate.CreateDelegate by name), and ldtoken/Delegate.Method of them can not be converted to a MethodBase or FieldInfo. * Everything works for the program: instances, casts, GetType, typeof, calls, delegates, virtual and interface dispatch, generic methods and generic virtual methods, static abstract members, type maps, IDynamicInterfaceCastable, ValueType.Equals, Marshal.OffsetOf and [UnsafeAccessor] (it does not use reflection). * Enums, delegates, top-level attribute classes, generic types (except the ones nested in a hidden type), types with generic virtual methods and the types that contain them keep their type metadata (the runtime needs it). Their non public members are hidden too, except for the members of enums and delegates (all of them stay) and the constructors, fields and properties of attribute classes (attributes are instantiated through them). The global <Module> type is never hidden. * The custom attributes of a type or member that is available are returned, also if they mention a hidden type (generic argument, typeof, array; it is surfaced as a hidden type). An attribute whose attribute class is hidden is not returned by GetCustomAttributes, IsDefined or CustomAttributeData, on both runtimes, also for a member of an assembly without the attribute. * Diagnostics are not affected: stack traces, DiagnosticMethodInfo and the debugger show the real names of hidden types and members (also the exception type name of Exception.ToString on CoreCLR). StackFrame.GetMethod() and Exception.TargetSite are null for a hidden method. NativeAOT: ILC matches the attribute by name in any assembly (DisablePrivateReflectionMetadataBlockingPolicy) and strips the metadata of the hidden types (type definition, members, custom attributes) and of the hidden members (IsStripped for types, methods and fields). The runtime represents hidden types with RuntimeBlockedTypeInfo. Generic methods and generic virtual methods that the type loader needs to identify get a small detached Method record (not part of the type, marked with a bit that the metadata of an assembly can not have) that the runtime rejects when a MethodBase is requested. The stack trace data keeps the real names of hidden types and members (references that are not shared with the placeholders of reflection), only when the stack trace support is on. A hidden type that an attribute mentions gets a reflected MethodTable and a placeholder type reference with the hash code of the type. IsAbstract and IsSealed of a hidden type come from two spare flags of its MethodTable that ILC sets only for the types that it strips. The exception messages that NativeAOT formats keep the placeholder name of a hidden type. CoreCLR: Module::IsPrivateReflectionDisabled reads the attribute by name once per module (cached in RuntimeModule), RuntimeTypeHandle_GetReflectionVisibility applies the same rules as ILC (the type blocked bit and the member visibility), RuntimeTypeCache caches the result per type, and the member caches, Associates, GetInterfaceMap, GetInterface, Delegate.CreateDelegate by name and the activator filter by it. The diagnostics (stack traces, Exception.Source and the exception type name, the debugger function evaluation, DiagnosticMethodInfo) use uncached MethodBase objects and diagnostics names, so reflection can not get to the hidden members. Assemblies without the attribute only pay for reads of the module flag at the custom attribute, type by name, activator and MakeGenericType entry points (the measured costs are in the design document). Includes the NativeAOT smoke test (TrimmingBehaviors) and a CoreCLR runtime test that share their cases (also in another assembly without the attribute), and the design document with the CoreCLR versus NativeAOT fidelity table. Co-authored-by: Copilot App <[email protected]>
Sergio0694
force-pushed
the
user/sergiopedri/disable-private-reflection-main
branch
from
November 23, 2026 21:30
3b0ec47 to
fae5ad4
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Gives
System.Runtime.CompilerServices.DisablePrivateReflectionAttributean effect in Native AOT and CoreCLR and removes its[Obsolete](SYSLIB0015). In an assembly that has the attribute, the non public types (not public, or nested in a type that is not public) and the non public members of every type are hidden from reflection. Diagnostics are not affected. See #138108 for the motivation and the API (no change in shape).Name/FullName/ToString()return a placeholder (<PrivateType 0x...>);GUIDandAssemblyQualifiedNamethrowNotSupportedException(so doesAssemblyon Native AOT); not found byType.GetType(string)/Assembly.GetType(string)and not listed byGetTypes/GetNestedTypes;Activator.CreateInstanceandMakeGenericTypeover a hidden generic definition fail.GetMethods/GetFields/GetProperties/GetEvents/GetConstructors/GetMember(s)/GetNestedTypesfamily, not found by name (alsoInvokeMemberandDelegate.CreateDelegate), andldtoken/Delegate.Methodof them can't be converted toMethodBase/FieldInfo.GetType,typeof, calls, delegates, virtual and interface dispatch, generic (virtual) methods, static abstract members, type maps,IDynamicInterfaceCastable, and[UnsafeAccessor](including[UnsafeAccessorType]by name) on hidden types and members.GetCustomAttributes,IsDefinedorCustomAttributeDataon both runtimes.Environment.StackTrace,DiagnosticMethodInfoand the debugger show the real names for hidden types and members.StackFrame.GetMethod()andException.TargetSitearenullfor a hidden method. On Native AOT the stack trace data keeps the names of hidden types and members only if stack trace support is on; nothing is added withStackTraceSupport=false.ILC:
DisablePrivateReflectionMetadataBlockingPolicymatches the attribute by name and strips the metadata of the hidden types and members. Generic methods that the type loader needs get a small detachedMethodrecord that reflection never returns. The runtime represents hidden types withRuntimeBlockedTypeInfo.CoreCLR:
Module::IsPrivateReflectionDisabledreads the attribute once per module (cached inRuntimeModule),RuntimeTypeHandle_GetReflectionVisibilityapplies the same rules as ILC, andRuntimeTypeCacheand the member caches filter by it.The design, the fidelity table between the runtimes and the known limits are in
docs/design/features/disable-private-reflection.md.Binary size on a large Native AOT app (the Microsoft Store,
OptimizationPreference=Size), on top of the typed type map values (#138065) and the ILC type loader gate (#137541):WinStore.App.dllThe MSIX column is the image compressed at zlib level 6, as a proxy for its size in the package. It is not a measured MSIX build. All the measured builds have stack trace support off. The "After" build uses CsWinRT 3.0 emitting the attribute in its generated assemblies, with the helper types internal and the few types read by the COM source generated attributes public. If stack trace support is on, keeping the real names of hidden types in stack traces costs about 2.8 MB (+2.85%) on this app compared with dropping them. Hiding the non public members of the remaining visible types showed no measurable change on this app (the cause was not isolated). On a small generated app (150 public and 150 internal types) the executable is 11 to 12% smaller with the attribute, with or without stack traces.
CoreCLR (x64 Release, interleaved hot runs against a baseline build of the parent commit, median of 4):
MakeGenericTypeabout +4% (about 7 ns),CustomAttributeData+5% (about 16 ns),Type.GetType(string)of a framework type +5%,GetBaseDefinition+5%,IsDefinedandAssembly.GetTypeabout +2.5%;Activator.CreateInstance(Type),GetCustomAttributesand the member lists are within noise. Assemblies without the attribute only pay for module flag reads.Known limits (details in the design document): messages that the Native AOT runtime formats itself (
InvalidCastException,TypeLoadException),Exception.ToString()andobject.ToString()of an instance of a hidden type use the placeholder name on Native AOT (CoreCLR prints the real name in the messages and inException.ToString());Delegate.Methodof a lambda or of a delegate to a non public method fails; the types that keep their metadata are still listed and found by name;Reflection.Emitassemblies are not covered on CoreCLR; noAppContextopt-out.Tests:
src/tests/nativeaot/SmokeTests/TrimmingBehaviorsandsrc/tests/reflection/DisablePrivateReflection(CoreCLR) share their cases (DisablePrivateReflectionLibrary.cs, plus a consumer in another assembly) and run the same assertions on both runtimes.ILCompiler.Trimming.Tests(626),SmokeTests/Reflection,System.Reflection.Tests(2068) andSystem.Runtime.Tests(78724) pass locally. Not built or run: wasm/wasi, Mono, Unix, checked CoreCLR.This is a behavior change for existing assemblies that carry the attribute (breaking change documentation is needed). Supersedes #138067.
Part of #137567.
Resolves #138108
Note
This PR description and the change were prepared with GitHub Copilot.