Skip to content

Make DisablePrivateReflectionAttribute work: hide the non public types of an assembly from reflection - #138109

Draft
Sergio0694 wants to merge 1 commit into
dotnet:mainfrom
Sergio0694:user/sergiopedri/disable-private-reflection-main
Draft

Sergio0694 wants to merge 1 commit into
dotnet:mainfrom
Sergio0694:user/sergiopedri/disable-private-reflection-main

Conversation

@Sergio0694

@Sergio0694 Sergio0694 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Gives System.Runtime.CompilerServices.DisablePrivateReflectionAttribute an 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).

  • Hidden types: no members, nested types or custom attributes; Name/FullName/ToString() return a placeholder (<PrivateType 0x...>); GUID and AssemblyQualifiedName throw NotSupportedException (so does Assembly on Native AOT); not found by Type.GetType(string)/Assembly.GetType(string) and not listed by GetTypes/GetNestedTypes; Activator.CreateInstance and MakeGenericType over a hidden generic definition fail.
  • Hidden members (of any type, also public ones): private, internal, protected, protected internal, private protected, explicit interface implementations and backing fields. Only the public members of an externally visible type are available; a property or event is available if one of its accessors is. They are not returned by the GetMethods/GetFields/GetProperties/GetEvents/GetConstructors/GetMember(s)/GetNestedTypes family, not found by name (also InvokeMember and Delegate.CreateDelegate), and ldtoken/Delegate.Method of them can't be converted to MethodBase/FieldInfo.
  • Still works for the program: instances, casts, 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.
  • Custom attributes: those of an available type or member are returned, also when they mention a hidden type (it is surfaced as a hidden type); an attribute whose class is hidden is not returned by GetCustomAttributes, IsDefined or CustomAttributeData on both runtimes.
  • Not hidden: enums, delegates, top-level attribute classes, generic types (except those nested in a hidden type) and types with generic virtual methods stay available since the runtime needs their metadata, and so do the types that contain one of these as a nested type. Their non public members are hidden, except for all the members of enums and delegates and the constructors, fields and properties of attribute classes.
  • Diagnostics: stack traces, Environment.StackTrace, DiagnosticMethodInfo and the debugger show the real names for hidden types and members. StackFrame.GetMethod() and Exception.TargetSite are null for 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 with StackTraceSupport=false.

ILC: DisablePrivateReflectionMetadataBlockingPolicy matches the attribute by name and strips the metadata of the hidden types and members. Generic methods that the type loader needs get a small detached Method record that reflection never returns. The runtime represents hidden types with RuntimeBlockedTypeInfo.

CoreCLR: Module::IsPrivateReflectionDisabled reads the attribute once per module (cached in RuntimeModule), RuntimeTypeHandle_GetReflectionVisibility applies the same rules as ILC, and RuntimeTypeCache and 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.dll MSIX (estimated)
Before (typed values, no attribute) 82,376,192 27,012,840
After 81,507,328 (-868,864, -1.05%) 26,861,600 (-151,240)

The 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): MakeGenericType about +4% (about 7 ns), CustomAttributeData +5% (about 16 ns), Type.GetType(string) of a framework type +5%, GetBaseDefinition +5%, IsDefined and Assembly.GetType about +2.5%; Activator.CreateInstance(Type), GetCustomAttributes and 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() and object.ToString() of an instance of a hidden type use the placeholder name on Native AOT (CoreCLR prints the real name in the messages and in Exception.ToString()); Delegate.Method of 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.Emit assemblies are not covered on CoreCLR; no AppContext opt-out.

Tests: src/tests/nativeaot/SmokeTests/TrimmingBehaviors and src/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) and System.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.

@azure-pipelines

Copy link
Copy Markdown
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.

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 23, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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

* 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The design should be justified from user point of view.

Current implementation details are not a good user-centric justification.

…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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Reflection community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[API Proposal]: Make DisablePrivateReflectionAttribute non obsolete and hide non public types from reflection

2 participants