Repository navigation
Description
Background and motivation
Follow up to #128161
Reflection-based components need to be able to identify the set of derived types of a closed type. See #125449.
We discussed how to best make this information available in cc-list-subtypes.md. When we met about this, we leaned against adding a reflection API like Type.GetSameAssemblySubtypes(), in part due to the relatively narrow use case and C#-specific purpose of that API. Instead we settled on listing the derived types in an attribute on the closed type.
API Proposal
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class IsClosedTypeAttribute : Attribute
{
public IsClosedTypeAttribute() { }
+ public Type[] DerivedTypes { get; set; }
}
}API Usage
[IsClosedType] cannot be used explicitly in C#. It is used by the compiler in the following way:
public closed class Animal;
public class Dog : Animal;
public class Cat : Animal;
public class CalicoCat : Cat;
// generates the following metadata:
[IsClosedType(DerivedTypes = [typeof(Dog), typeof(Cat)])]
public class Animal;
public class Dog : Animal;
public class Cat : Animal;
public class CalicoCat : Cat;// In generic cases, the attribute lists the definitions of the derived types
public closed class C<T>;
public class D1<T> : C<T>;
public class D2<T, U> : C<Dictionary<T, U>>;
public class D3 : C<string>;
// generates the following metadata:
[IsClosedType(DerivedTypes = [typeof(D1<>), typeof(D2<,>), typeof(D3)])]
public class C<T>;
public class D1<T> : C<T>;
public class D2<T, U> : C<Dictionary<T, U>>;
public class D3 : C<string>;If this API proposal is accepted, then the compiler will always set a value for this property, and the compiler will guarantee that the value will be consistent with the TypeDef table for the containing module. i.e. it will contain the same set of subtype definitions that we would have discovered by scanning the TypeDef table. Note that this doesn't protect us against post-build tools adding new derived types and failing to update the attribute. See also Risks.
Alternative Designs
We might want to make it so tools which use this attribute, are required to specify a value for DerivedTypes. We could consider one of the following to try to emphasize the need to specify a value:
- Put
requiredmodifier on the attribute property. I didn't see any pre-existing example of a public required property in the core libraries, and, this isn't wouldn't be especially "binding" for post-compilation tools, so I didn't suggest this in the main proposal. - Change the constructor signature to take a (possibly
params)Type[] derivedTypes, and do not include theDerivedTypes.setaccessor.
Risks
Quoting cc-list-subtypes.md:
We resisted doing this until now, because we felt the information was redundant. The TypeDef table is already a source of truth for this, and theoretically a type using this encoding could have differences between the table and the attribute.
The risk of having multiple sources of truth for this is: different tools which operate in a similar domain, may end up using different sources for the information. For example, maybe STJ uses the attribute to find the subtypes, and Newtonsoft uses the TypeDef table. This creates an interoperability issue which may or may not amount to a security bug.
Although we assume that the compiler is going to provide a correct list of subtypes in the attribute, post-build rewriting tools might not. The possibility of divergence might further motivate runtime enforcement. For example, throwing InvalidProgramException at runtime, when a subtype is loaded, and its base type has [IsClosedType] attribute, and the attribute doesn't include the subtype.
Moving forward with this API proposal, may motivate us to add a runtime enforcement when a type is loaded, when the base type is a closed type, that:
- the derived type is listed in the
IsClosedTypeAttribute.DerivedTypeson the base type. - the derived type is declared in the same module as the base type.
Regarding runtime enforcement, there was also a corner case pointed out with type forwarding. It doesn't seem valid/sane to forward a derived type of a closed type to another assembly, because it seems to require declaring the derived type in a different assembly. It feels reasonable to block that.
Activity
[-]IsClosedTypeAttribute: add DerivedTypes property[/-][+][API Proposal]: IsClosedTypeAttribute: add DerivedTypes property[/+]dotnet-policy-service commentedon Jun 4, 2026
Tagging subscribers to this area: @dotnet/area-system-runtime-compilerservices
See info in area-owners.md if you want to be subscribed.
tannergooding commentedon Jun 4, 2026
This was raised as a possibility when we reviewed #128161, so I don't expect any big pushback against it.
jkotas commentedon Jun 5, 2026
Does this need to be nullable
Type{]?? What are the consumers expected to do when this property is null?It may make more sense to go with the constructor argument from the alternative proposals.
I do not think we want to be wasting cycles during startup on runtime enforcement.
eiriktsarpalis commentedon Jun 5, 2026
I missed the previews API review for the attribute, but I will say I'm not a huge fan of the current
IsClosedTypeAttributename, especially now that under this proposal it ceases to be a simple marker. I get that we wanted to preserveClosedTypeAttributefor other uses, but given that we're dedicating theclosedkeyword to this feature I fail to see where we might use the term "closed type" elsewhere without introducing confusion.@bartonjs @tannergooding thoughts?
eiriktsarpalis commentedon Jun 5, 2026
I'm assuming it would be treated the same way as an empty array (which canonically represents a closed class without descendants). I think marking it non-nullable is the way to go.
10 remaining items
bartonjs commentedon Jun 8, 2026
Hopefully you'll agree that when there are two pieces of data representing the same thing, only one is authoritative, and you're reading the other, this is fundamentally a Time-of-Check/Time-of-Use gap. That means, from a security footing, this starts of at negative a trillion or so. The existence of this ToC/ToU introduces the space for other security gap types, such as the aforementioned parser differential.
Also, from a security perspective, the weakness of something like this isn't the worst thing I can come up with in an hour, it's the worst thing anyone can come up with in the fullness of time.
If the runtime enforces the correctness of the attribute, ToC/ToU goes away, and the redundant data can be treated as authoritative.
The expected use case is useful input into designing the ergonomics of the feature. The security aspects of a feature come from "what if the guard rails are missing?". That means that the security view of this compiler does not come from the Roslyn experience, it come from ilasm.
I hope that's not a suggestion that declaring a type closed automatically makes it eligible for JSON polymorphic serialization, because I'll have to be a security nay-sayer on that, too. (If there's a gesture of "Allow all of my closed types in serialization", then, well, OK, but it can't be gesture-free).
Well, remember, sometimes a lack of a
[JsonDerivedType]is intentional. That's why the related-but-different STJ+closed-types enhancement still needs an explicit gesture... just because someone A) does serialization, and B) wants their switch-expression blocks to not need a drain doesn't mean that they want all data serialized. And over-exposed data is a security issue.Another point that I think is worth making is that even if the list is correct for an assembly, it's not guaranteed to be consistent across assemblies. Adding types to a closed set is a breaking change, but people outside the BCL make breaking changes all the time. Utility assemblies for semi-closed ecosystems, for example (foundational libraries for an enterprise).
Now, maybe that means that sane components should never use it for a remote assembly, and "never use this for a remote assembly" becomes the message/mantra, at which point this does devolve to "it's about producing local consistency while producing a single compilation output", and maybe a lot of risk goes away. But, I very much see it as "if it's written down, someone will read it and think it's meaningful".
My feeling of bad is visceral. This redundant data being available creates space for problems. The more secure position is to not write it down. The data being so low level makes it hard to understand actual risks.
This is a perf enhancement at the risk of (admittedly theoretical) security. What's the perf gain from doing this? What's the clock/cycle tolerance that was exceeded that justifies the need for this?
The presence of this data makes it such that anything that touches it now needs to answer "what if it's wrong?". I am a huge fan of just taking away that question.
eiriktsarpalis commentedon Jun 8, 2026
That's not really an option given we're targeting older runtimes.
The proposed gesture is an
InferedDerivedTypesflag, but applying a polymorphism convention for closed types specifically is also on the table: #129041If you look at what the STJ generator does (and what most generated serializers do for that matter) is emitting redundant models that emulate System.Type and System.Reflection.PropertyInfo that happen to work well in Native AOT. This creates exactly the kind of consistency problem you're describing. If the concern is having that redundancy in the C# compiler's code generation, we could instead move it over to the source generator. However, supporting the same feature in the reflection-based serializer would require running expensive queries at startup.
bartonjs commentedon Jun 8, 2026
I prefer that, because now it can be analyzed as an STJ feature, with understood risks.
So? It seems pretty opt-in, it's one-time expense, and "expensive" is still going to be pretty fast.
jkotas commentedon Jun 8, 2026
It is very common for binaries to contain duplicated data optimized for different use cases. It is the case for both in .NET and non-.NET binaries. The tooling used to produce the binaries must ensure that the duplicate data are self-consistent.
According to Wikipedia, Time-of-Check/Time-of-Use is a race condition. Race conditions require two components running in parallel. It is not the case here. We are worried about serial execution of a tool that produces corrupted binary.
bartonjs commentedon Jun 16, 2026
Video
We discussed an optional property vs a ctor parameter, and decided optional property (as proposed) is fine.
Add DerivedTypes property to IsClosedTypeAttribute (#129529)
Add DerivedTypes property to IsClosedTypeAttribute (#129529)
Add DerivedTypes property to IsClosedTypeAttribute (dotnet#129529)