From 17f6aaba80c670fc6713a5db71e756f638545d40 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 13 Nov 2026 23:54:57 -0800 Subject: [PATCH 01/11] Add a discriminator to native format metadata writer records Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../NativeFormat/Generator/SchemaDef.cs | 11 +++++++- .../NativeFormat/Generator/WriterGen.cs | 10 +++++++ .../Writer/NativeFormatWriterGen.cs | 28 +++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs index 7716be9bef6943..518be8e0dad18e 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs @@ -19,6 +19,9 @@ public enum RecordDefFlags // implementing equality functionality; else all members are used. ReentrantEquals = 0x08, // The generated Equals method is potentially reentrant on the same instance // and should have a fast exit path to protect from infinite recursion. + Discriminated = 0x10, // The writer record has an additional member that is never persisted and only + // participates in equality functionality. It keeps records distinct (and + // prevents them from being pooled) when their persisted content is otherwise equal. } /// @@ -370,7 +373,7 @@ static SchemaDef() { new RecordDef( name: "TypeDefinition", - flags: RecordDefFlags.CustomCompare, + flags: RecordDefFlags.CustomCompare | RecordDefFlags.Discriminated, members: new MemberDef[] { new MemberDef("Flags", "TypeAttributes"), new MemberDef("BaseType", TypeDefOrRefOrSpec, MemberDefFlags.RecordRef), @@ -391,6 +394,7 @@ static SchemaDef() ), new RecordDef( name: "TypeReference", + flags: RecordDefFlags.Discriminated, members: new MemberDef[] { new MemberDef("NamespaceOrEnclosingType", new string[] { "NamespaceReference", "TypeReference" }, MemberDefFlags.RecordRef), new MemberDef("TypeName", "ConstantStringValue", MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.Name), @@ -459,6 +463,7 @@ static SchemaDef() ), new RecordDef( name: "Method", + flags: RecordDefFlags.Discriminated, members: new MemberDef[] { new MemberDef("Flags", "MethodAttributes"), new MemberDef("ImplFlags", "MethodImplAttributes"), @@ -486,6 +491,7 @@ static SchemaDef() ), new RecordDef( name: "MemberReference", + flags: RecordDefFlags.Discriminated, members: new MemberDef[] { new MemberDef("Parent", TypeDefOrRefOrSpec, MemberDefFlags.RecordRef), new MemberDef("Name", "ConstantStringValue", MemberDefFlags.RecordRef | MemberDefFlags.Child), @@ -495,6 +501,7 @@ static SchemaDef() ), new RecordDef( name: "Field", + flags: RecordDefFlags.Discriminated, members: new MemberDef[] { new MemberDef("Flags", "FieldAttributes"), new MemberDef("Name", "ConstantStringValue", MemberDefFlags.RecordRef | MemberDefFlags.Child), @@ -513,6 +520,7 @@ static SchemaDef() ), new RecordDef( name: "Property", + flags: RecordDefFlags.Discriminated, members: new MemberDef[] { new MemberDef("Flags", "PropertyAttributes"), new MemberDef("Name", "ConstantStringValue", MemberDefFlags.RecordRef | MemberDefFlags.Child), @@ -524,6 +532,7 @@ static SchemaDef() ), new RecordDef( name: "Event", + flags: RecordDefFlags.Discriminated, members: new MemberDef[] { new MemberDef("Flags", "EventAttributes"), new MemberDef("Name", "ConstantStringValue", MemberDefFlags.RecordRef | MemberDefFlags.Child), diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/WriterGen.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/WriterGen.cs index c60e86735dae89..aca10c4d3420fe 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/WriterGen.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/WriterGen.cs @@ -76,6 +76,8 @@ private void EmitRecord(RecordDef record) WriteLine("if (Object.ReferenceEquals(this, obj)) return true;"); WriteLine($"var other = obj as {record.Name};"); WriteLine("if (other == null) return false;"); + if ((record.Flags & RecordDefFlags.Discriminated) != 0) + WriteLine("if (Discriminator != other.Discriminator) return false;"); if ((record.Flags & RecordDefFlags.ReentrantEquals) != 0) { WriteLine("if (_equalsReentrancyGuard.Value.Contains(other))"); @@ -134,6 +136,8 @@ private void EmitRecord(RecordDef record) int hashSeed = System.BitConverter.ToInt32(hashBytes, 0); WriteLine("var hash = new HashCode();"); WriteLine($"hash.Add({hashSeed});"); + if ((record.Flags & RecordDefFlags.Discriminated) != 0) + WriteLine("hash.Add(Discriminator);"); foreach (var member in record.Members) { @@ -253,6 +257,12 @@ private void EmitRecord(RecordDef record) CloseScope("Handle"); WriteLineIfNeeded(); + if ((record.Flags & RecordDefFlags.Discriminated) != 0) + { + WriteLine("// Not persisted. Keeps records with otherwise identical content distinct, e.g. when their names were omitted."); + WriteLine("public int Discriminator;"); + } + foreach (var member in record.Members) { string fieldType = member.GetMemberType(MemberTypeKind.WriterField); diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/Internal/Metadata/NativeFormat/Writer/NativeFormatWriterGen.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/Internal/Metadata/NativeFormat/Writer/NativeFormatWriterGen.cs index 8a3ea9e5c9996a..72c44eeabd3c26 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/Internal/Metadata/NativeFormat/Writer/NativeFormatWriterGen.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/Internal/Metadata/NativeFormat/Writer/NativeFormatWriterGen.cs @@ -490,6 +490,7 @@ public override sealed bool Equals(Object obj) if (Object.ReferenceEquals(this, obj)) return true; var other = obj as Event; if (other == null) return false; + if (Discriminator != other.Discriminator) return false; if (Flags != other.Flags) return false; if (!Object.Equals(Name, other.Name)) return false; if (!Object.Equals(Type, other.Type)) return false; @@ -505,6 +506,7 @@ public override sealed int GetHashCode() EnterGetHashCode(); var hash = new HashCode(); hash.Add(-1454825650); + hash.Add(Discriminator); hash.Add(Flags); hash.Add(Name); hash.Add(Type); @@ -550,6 +552,8 @@ internal static EventHandle AsHandle(Event record) } } // Handle + // Not persisted. Keeps records with otherwise identical content distinct, e.g. when their names were omitted. + public int Discriminator; public EventAttributes Flags; public ConstantStringValue Name; public MetadataRecord Type; @@ -580,6 +584,7 @@ public override sealed bool Equals(Object obj) if (Object.ReferenceEquals(this, obj)) return true; var other = obj as Field; if (other == null) return false; + if (Discriminator != other.Discriminator) return false; if (Flags != other.Flags) return false; if (!Object.Equals(Name, other.Name)) return false; if (!Object.Equals(Signature, other.Signature)) return false; @@ -596,6 +601,7 @@ public override sealed int GetHashCode() EnterGetHashCode(); var hash = new HashCode(); hash.Add(-540975116); + hash.Add(Discriminator); hash.Add(Flags); hash.Add(Name); hash.Add(Signature); @@ -638,6 +644,8 @@ internal static FieldHandle AsHandle(Field record) } } // Handle + // Not persisted. Keeps records with otherwise identical content distinct, e.g. when their names were omitted. + public int Discriminator; public FieldAttributes Flags; public ConstantStringValue Name; public FieldSignature Signature; @@ -895,6 +903,7 @@ public override sealed bool Equals(Object obj) if (Object.ReferenceEquals(this, obj)) return true; var other = obj as MemberReference; if (other == null) return false; + if (Discriminator != other.Discriminator) return false; if (!Object.Equals(Parent, other.Parent)) return false; if (!Object.Equals(Name, other.Name)) return false; if (!Object.Equals(Signature, other.Signature)) return false; @@ -908,6 +917,7 @@ public override sealed int GetHashCode() EnterGetHashCode(); var hash = new HashCode(); hash.Add(-875402938); + hash.Add(Discriminator); hash.Add(Parent); hash.Add(Name); hash.Add(Signature); @@ -950,6 +960,8 @@ internal static MemberReferenceHandle AsHandle(MemberReference record) } } // Handle + // Not persisted. Keeps records with otherwise identical content distinct, e.g. when their names were omitted. + public int Discriminator; public MetadataRecord Parent; public ConstantStringValue Name; public MetadataRecord Signature; @@ -979,6 +991,7 @@ public override sealed bool Equals(Object obj) if (Object.ReferenceEquals(this, obj)) return true; var other = obj as Method; if (other == null) return false; + if (Discriminator != other.Discriminator) return false; if (Flags != other.Flags) return false; if (ImplFlags != other.ImplFlags) return false; if (!Object.Equals(Name, other.Name)) return false; @@ -996,6 +1009,7 @@ public override sealed int GetHashCode() EnterGetHashCode(); var hash = new HashCode(); hash.Add(-1225154478); + hash.Add(Discriminator); hash.Add(Flags); hash.Add(ImplFlags); hash.Add(Name); @@ -1040,6 +1054,8 @@ internal static MethodHandle AsHandle(Method record) } } // Handle + // Not persisted. Keeps records with otherwise identical content distinct, e.g. when their names were omitted. + public int Discriminator; public MethodAttributes Flags; public MethodImplAttributes ImplFlags; public ConstantStringValue Name; @@ -1760,6 +1776,7 @@ public override sealed bool Equals(Object obj) if (Object.ReferenceEquals(this, obj)) return true; var other = obj as Property; if (other == null) return false; + if (Discriminator != other.Discriminator) return false; if (Flags != other.Flags) return false; if (!Object.Equals(Name, other.Name)) return false; if (!Object.Equals(Signature, other.Signature)) return false; @@ -1776,6 +1793,7 @@ public override sealed int GetHashCode() EnterGetHashCode(); var hash = new HashCode(); hash.Add(-1324612544); + hash.Add(Discriminator); hash.Add(Flags); hash.Add(Name); hash.Add(Signature); @@ -1819,6 +1837,8 @@ internal static PropertyHandle AsHandle(Property record) } } // Handle + // Not persisted. Keeps records with otherwise identical content distinct, e.g. when their names were omitted. + public int Discriminator; public PropertyAttributes Flags; public ConstantStringValue Name; public PropertySignature Signature; @@ -2392,6 +2412,7 @@ public override sealed bool Equals(Object obj) if (Object.ReferenceEquals(this, obj)) return true; var other = obj as TypeDefinition; if (other == null) return false; + if (Discriminator != other.Discriminator) return false; if (!Object.Equals(NamespaceOrEnclosingType, other.NamespaceOrEnclosingType)) return false; if (!Object.Equals(Name, other.Name)) return false; return true; @@ -2404,6 +2425,7 @@ public override sealed int GetHashCode() EnterGetHashCode(); var hash = new HashCode(); hash.Add(-1095947977); + hash.Add(Discriminator); hash.Add(NamespaceOrEnclosingType); hash.Add(Name); LeaveGetHashCode(); @@ -2460,6 +2482,8 @@ internal static TypeDefinitionHandle AsHandle(TypeDefinition record) } } // Handle + // Not persisted. Keeps records with otherwise identical content distinct, e.g. when their names were omitted. + public int Discriminator; public TypeAttributes Flags; public MetadataRecord BaseType; public MetadataRecord NamespaceOrEnclosingType; @@ -2651,6 +2675,7 @@ public override sealed bool Equals(Object obj) if (Object.ReferenceEquals(this, obj)) return true; var other = obj as TypeReference; if (other == null) return false; + if (Discriminator != other.Discriminator) return false; if (!Object.Equals(NamespaceOrEnclosingType, other.NamespaceOrEnclosingType)) return false; if (!Object.Equals(TypeName, other.TypeName)) return false; return true; @@ -2663,6 +2688,7 @@ public override sealed int GetHashCode() EnterGetHashCode(); var hash = new HashCode(); hash.Add(-540108450); + hash.Add(Discriminator); hash.Add(NamespaceOrEnclosingType); hash.Add(TypeName); LeaveGetHashCode(); @@ -2699,6 +2725,8 @@ internal static TypeReferenceHandle AsHandle(TypeReference record) } } // Handle + // Not persisted. Keeps records with otherwise identical content distinct, e.g. when their names were omitted. + public int Discriminator; public MetadataRecord NamespaceOrEnclosingType; public ConstantStringValue TypeName; } // TypeReference From d7367019ec20bd58b9de677914ea26bbc5fc8213 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 13 Nov 2026 23:54:59 -0800 Subject: [PATCH 02/11] Add --stripnames option to strip names from reflection metadata Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Microsoft.NETCore.Native.targets | 1 + .../MetadataTypeHashingAlgorithms.cs | 8 +- .../Compiler/AnalysisBasedMetadataManager.cs | 13 +- .../DependencyAnalysis/TypeMetadataMapNode.cs | 11 +- .../Compiler/MetadataManager.cs | 12 +- .../Compiler/MetadataNameStrippingPolicy.cs | 40 ++++++ .../Compiler/StackTraceEmissionPolicy.cs | 11 +- .../Compiler/UsageBasedMetadataManager.cs | 12 +- .../ILCompiler.Compiler.csproj | 1 + .../ILCompiler.MetadataTransform.csproj | 1 + .../ILCompiler/Metadata/IMetadataPolicy.cs | 9 ++ .../ILCompiler/Metadata/Transform.Event.cs | 7 +- .../ILCompiler/Metadata/Transform.Field.cs | 10 +- .../ILCompiler/Metadata/Transform.Method.cs | 12 +- .../ILCompiler/Metadata/Transform.Names.cs | 134 ++++++++++++++++++ .../Metadata/Transform.Parameter.cs | 2 +- .../ILCompiler/Metadata/Transform.Property.cs | 7 +- .../ILCompiler/Metadata/Transform.Type.cs | 26 ++-- .../TestCasesRunner/TrimmingDriver.cs | 3 +- .../aot/ILCompiler/ILCompilerRootCommand.cs | 3 + src/coreclr/tools/aot/ILCompiler/Program.cs | 13 +- .../src/Internal/VersionResilientHashCode.cs | 10 ++ 22 files changed, 312 insertions(+), 34 deletions(-) create mode 100644 src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataNameStrippingPolicy.cs create mode 100644 src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs diff --git a/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.targets b/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.targets index 1dc7544bf9a5da..8310459fc2cd99 100644 --- a/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.targets +++ b/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.targets @@ -330,6 +330,7 @@ The .NET Foundation licenses this file to you under the MIT license. + diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MetadataTypeHashingAlgorithms.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MetadataTypeHashingAlgorithms.cs index 59d9320a4e5990..1938998a4bbac5 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MetadataTypeHashingAlgorithms.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MetadataTypeHashingAlgorithms.cs @@ -9,6 +9,12 @@ public static int ComputeHashCode(this TypeDefinitionHandle typeDefHandle, Metad { TypeDefinition typeDef = reader.GetTypeDefinition(typeDefHandle); + ReadOnlySpan name = reader.ReadStringAsBytes(typeDef.Name); + + // The name of the type was stripped from the metadata. The type map identifies such types by their handle. + if (name.IsEmpty) + return VersionResilientHashCode.MetadataHandleHashCode(typeDefHandle.GetHashCode()); + int namespaceHashCode = 0; Handle namespaceOrEnclosingType = typeDef.NamespaceOrEnclosingType; @@ -18,7 +24,7 @@ public static int ComputeHashCode(this TypeDefinitionHandle typeDefHandle, Metad namespaceHashCode = VersionResilientHashCode.NameHashCode(reader.ReadStringAsBytes(namespaceDefinition.Name)); } - int nameHashCode = VersionResilientHashCode.NameHashCode(reader.ReadStringAsBytes(typeDef.Name)); + int nameHashCode = VersionResilientHashCode.NameHashCode(name); int hashCode = VersionResilientHashCode.NameHashCode(namespaceHashCode, nameHashCode); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/AnalysisBasedMetadataManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/AnalysisBasedMetadataManager.cs index 9e6da3821faba7..3b1bb5689a29a1 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/AnalysisBasedMetadataManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/AnalysisBasedMetadataManager.cs @@ -39,7 +39,8 @@ public AnalysisBasedMetadataManager(CompilerTypeSystemContext typeSystemContext) Array.Empty>(), Array.Empty>(), Array.Empty>(), Array.Empty(), Array.Empty(), - default) + default, + MetadataNameStrippingPolicy.None) { } @@ -58,8 +59,9 @@ public AnalysisBasedMetadataManager( IEnumerable> reflectableFields, IEnumerable reflectableAttributes, IEnumerable reflectableParameters, - MetadataManagerOptions options) - : base(typeSystemContext, blockingPolicy, resourceBlockingPolicy, logFile, stackTracePolicy, invokeThunkGenerationPolicy, options, flowAnnotations) + MetadataManagerOptions options, + MetadataNameStrippingPolicy nameStrippingPolicy) + : base(typeSystemContext, blockingPolicy, resourceBlockingPolicy, logFile, stackTracePolicy, invokeThunkGenerationPolicy, options, flowAnnotations, nameStrippingPolicy) { _modulesWithMetadata = new List(modulesWithMetadata); _forcedTypes = new List(forcedTypes); @@ -284,6 +286,11 @@ public bool IsBlocked(MethodDesc methodDef) { return _blockingPolicy.IsBlocked(methodDef); } + + public bool GeneratesNames(ModuleDesc module) + { + return _parent.GeneratesNames(module); + } } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeMetadataMapNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeMetadataMapNode.cs index 5753c82fbe8980..9d4122bff57b64 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeMetadataMapNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeMetadataMapNode.cs @@ -61,7 +61,16 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) ); int hashCode = typeSymbol.Type.GetHashCode(); - typeMapHashTable.Append((uint)hashCode, hashTableSection.Place(vertex)); + Vertex placedVertex = hashTableSection.Place(vertex); + typeMapHashTable.Append((uint)hashCode, placedVertex); + + // Types whose names were stripped from the metadata are looked up by their metadata handle + // because the runtime can't compute the hash code from the name. + if (!factory.MetadataManager.GeneratesNames(mappingEntry.Entity.Module)) + { + int metadataHandleHashCode = Internal.VersionResilientHashCode.MetadataHandleHashCode(mappingEntry.MetadataHandle); + typeMapHashTable.Append((uint)metadataHandleHashCode, placedVertex); + } } byte[] hashTableBytes = writer.Save(); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataManager.cs index 6e9cc3b1a1500d..a24fec28a9aa10 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataManager.cs @@ -59,7 +59,7 @@ public abstract class MetadataManager : ICompilationRootProvider private List _reflectionStackTraceMappings; protected readonly string _metadataLogFile; protected readonly StackTraceEmissionPolicy _stackTraceEmissionPolicy; - + protected readonly MetadataNameStrippingPolicy _nameStrippingPolicy; protected readonly CompilerTypeSystemContext _typeSystemContext; protected readonly MetadataBlockingPolicy _blockingPolicy; protected readonly ManifestResourceBlockingPolicy _resourceBlockingPolicy; @@ -98,7 +98,8 @@ private readonly SortedSet _typeGVMEntries public MetadataManager(CompilerTypeSystemContext typeSystemContext, MetadataBlockingPolicy blockingPolicy, ManifestResourceBlockingPolicy resourceBlockingPolicy, string logFile, StackTraceEmissionPolicy stackTracePolicy, DynamicInvokeThunkGenerationPolicy dynamicInvokeThunkGenerationPolicy, - MetadataManagerOptions options, FlowAnnotations flowAnnotations) + MetadataManagerOptions options, FlowAnnotations flowAnnotations, + MetadataNameStrippingPolicy nameStrippingPolicy = null) { _typeSystemContext = typeSystemContext; _blockingPolicy = blockingPolicy; @@ -107,12 +108,19 @@ public MetadataManager(CompilerTypeSystemContext typeSystemContext, MetadataBloc _options = options; _metadataLogFile = logFile; _stackTraceEmissionPolicy = stackTracePolicy; + _nameStrippingPolicy = nameStrippingPolicy ?? MetadataNameStrippingPolicy.None; FlowAnnotations = flowAnnotations; } public bool IsDataDehydrated => (_options & MetadataManagerOptions.DehydrateData) != 0; + /// + /// Returns true if the names of the types and members defined in + /// are emitted into the metadata. + /// + internal bool GeneratesNames(ModuleDesc module) => !_nameStrippingPolicy.IsStripped(module); + internal ObjectNode.ObjectData PrepareForDehydration(DehydratableObjectNode node, ObjectNode.ObjectData hydratedData) { _dehydratableData.Add((node, hydratedData)); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataNameStrippingPolicy.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataNameStrippingPolicy.cs new file mode 100644 index 00000000000000..459052b7b31b9b --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataNameStrippingPolicy.cs @@ -0,0 +1,40 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Generic; + +using Internal.TypeSystem; + +namespace ILCompiler +{ + /// + /// Represents a policy that decides which assemblies have the names of their types and members stripped + /// from the reflection metadata and the stack trace data emitted into the executable. + /// + public sealed class MetadataNameStrippingPolicy + { + private readonly HashSet _strippedAssemblies; + + /// + /// Gets a policy that doesn't strip the names of any assemblies. + /// + public static MetadataNameStrippingPolicy None { get; } = new MetadataNameStrippingPolicy(Array.Empty()); + + /// Simple names of the assemblies to strip the names from. + public MetadataNameStrippingPolicy(IEnumerable strippedAssemblies) + { + _strippedAssemblies = new HashSet(strippedAssemblies, StringComparer.OrdinalIgnoreCase); + } + + /// + /// Returns true if the names of the types and members defined in are stripped. + /// + public bool IsStripped(ModuleDesc module) + { + return _strippedAssemblies.Count > 0 + && module.Assembly is IAssemblyDesc assembly + && _strippedAssemblies.Contains(assembly.GetName().Name); + } + } +} diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/StackTraceEmissionPolicy.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/StackTraceEmissionPolicy.cs index 67576210ec50ab..af045962930daf 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/StackTraceEmissionPolicy.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/StackTraceEmissionPolicy.cs @@ -29,15 +29,20 @@ public override MethodStackTraceVisibilityFlags GetMethodVisibility(MethodDesc m public class EcmaMethodStackTraceEmissionPolicy : StackTraceEmissionPolicy { private readonly MethodStackTraceVisibilityFlags _flags; + private readonly MetadataNameStrippingPolicy _nameStrippingPolicy; - public EcmaMethodStackTraceEmissionPolicy(bool includeLineNumbers) + public EcmaMethodStackTraceEmissionPolicy(bool includeLineNumbers, MetadataNameStrippingPolicy nameStrippingPolicy) { _flags = includeLineNumbers ? MethodStackTraceVisibilityFlags.HasLineNumbers : 0; + _nameStrippingPolicy = nameStrippingPolicy; } public override MethodStackTraceVisibilityFlags GetMethodVisibility(MethodDesc method) { - MethodStackTraceVisibilityFlags result = _flags; + // Methods from modules that strip names have no names to show in stack traces. + bool namesStripped = method.OwningType is MetadataType owningType && _nameStrippingPolicy.IsStripped(owningType.Module); + + MethodStackTraceVisibilityFlags result = namesStripped ? 0 : _flags; if (method.HasCustomAttribute("System.Diagnostics", "StackTraceHiddenAttribute") || (method.OwningType is MetadataType mdType && mdType.HasCustomAttribute("System.Diagnostics", "StackTraceHiddenAttribute")) @@ -46,7 +51,7 @@ public override MethodStackTraceVisibilityFlags GetMethodVisibility(MethodDesc m result |= MethodStackTraceVisibilityFlags.IsHidden; } - return (method.GetTypicalMethodDefinition() is Internal.TypeSystem.Ecma.EcmaMethod || (method.IsAsync && method.IsAsyncCall())) + return !namesStripped && (method.GetTypicalMethodDefinition() is Internal.TypeSystem.Ecma.EcmaMethod || (method.IsAsync && method.IsAsyncCall())) ? result | MethodStackTraceVisibilityFlags.HasMetadata : result; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedMetadataManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedMetadataManager.cs index e07c619123031b..95588b9c7146e4 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedMetadataManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedMetadataManager.cs @@ -87,8 +87,9 @@ public UsageBasedMetadataManager( IEnumerable rootEntireAssembliesModules, IEnumerable additionalRootedAssemblies, IEnumerable trimmedAssemblies, - IEnumerable satelliteAssemblyFilePaths) - : base(typeSystemContext, blockingPolicy, resourceBlockingPolicy, logFile, stackTracePolicy, invokeThunkGenerationPolicy, options, flowAnnotations) + IEnumerable satelliteAssemblyFilePaths, + MetadataNameStrippingPolicy nameStrippingPolicy) + : base(typeSystemContext, blockingPolicy, resourceBlockingPolicy, logFile, stackTracePolicy, invokeThunkGenerationPolicy, options, flowAnnotations, nameStrippingPolicy) { _compilationModuleGroup = group; _generationOptions = generationOptions; @@ -919,7 +920,7 @@ public MetadataManager ToAnalysisBasedMetadataManager() return new AnalysisBasedMetadataManager( _typeSystemContext, _blockingPolicy, _resourceBlockingPolicy, _metadataLogFile, _stackTraceEmissionPolicy, _dynamicInvokeThunkGenerationPolicy, FlowAnnotations, _modulesWithMetadata, _typesWithForcedEEType, reflectableTypes.ToEnumerable(), reflectableMethods.ToEnumerable(), - reflectableFields.ToEnumerable(), _customAttributesWithMetadata, _parametersWithMetadata, _options); + reflectableFields.ToEnumerable(), _customAttributesWithMetadata, _parametersWithMetadata, _options, _nameStrippingPolicy); } private void AddDataflowDependency(IDependencySink dependencies, NodeFactory factory, MethodIL methodIL, string reason) @@ -1060,6 +1061,11 @@ public bool IsBlocked(MethodDesc methodDef) { return _blockingPolicy.IsBlocked(methodDef); } + + public bool GeneratesNames(ModuleDesc module) + { + return _factory.MetadataManager.GeneratesNames(module); + } } private sealed class LinkAttributesHashTable : LockFreeReaderHashtable diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj index c8c106615e8686..b78f10f2ec8a33 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj @@ -560,6 +560,7 @@ + diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler.MetadataTransform.csproj b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler.MetadataTransform.csproj index fd1c66933d7512..2062e3d6c65bc3 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler.MetadataTransform.csproj +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler.MetadataTransform.csproj @@ -66,6 +66,7 @@ + diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/IMetadataPolicy.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/IMetadataPolicy.cs index c79bc3fe477aec..193ff8c91711e9 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/IMetadataPolicy.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/IMetadataPolicy.cs @@ -67,5 +67,14 @@ public interface IMetadataPolicy bool IsBlocked(Cts.MetadataType typeDef); bool IsBlocked(Cts.MethodDesc methodDef); + + /// + /// Returns true if the names of the types and members defined in the module should be emitted + /// into the metadata. If false, the names of the entities defined in the module are replaced with an + /// empty string, and the types are placed in the root namespace. Names that the runtime needs + /// for correctness (e.g. the names of constructors and enum members) and the names of type forwarders + /// are always emitted. + /// + bool GeneratesNames(Cts.ModuleDesc module); } } diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Event.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Event.cs index 17f507dbb1fcd6..7d1cc1a14f8d0d 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Event.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Event.cs @@ -12,8 +12,9 @@ namespace ILCompiler.Metadata { internal partial class Transform { - private Event HandleEvent(Cts.Ecma.EcmaModule module, Ecma.EventDefinitionHandle eventHandle) + private Event HandleEvent(Cts.Ecma.EcmaType owningType, Ecma.EventDefinitionHandle eventHandle) { + Cts.Ecma.EcmaModule module = owningType.Module; Ecma.MetadataReader reader = module.MetadataReader; Ecma.EventDefinition eventDef = reader.GetEventDefinition(eventHandle); @@ -31,9 +32,11 @@ private Event HandleEvent(Cts.Ecma.EcmaModule module, Ecma.EventDefinitionHandle if (!adderHasMetadata && !raiserHasMetadata && !removerHasMetadata) return null; + bool stripName = !_policy.GeneratesNames(module); Event result = new Event { - Name = HandleString(reader.GetString(eventDef.Name)), + Name = HandleName(reader.GetString(eventDef.Name), stripName), + Discriminator = stripName ? GetDiscriminator(owningType, eventHandle) : 0, Flags = eventDef.Attributes, Type = HandleType(module.GetType(eventDef.Type)), }; diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Field.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Field.cs index 351e556aa893e7..80c6466f7eaca9 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Field.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Field.cs @@ -46,7 +46,10 @@ private Field HandleFieldDefinition(Cts.FieldDesc field) private void InitializeFieldDefinition(Cts.FieldDesc entity, Field record) { - record.Name = HandleString(entity.GetName()); + bool stripName = StripsName(entity); + record.Name = HandleName(entity.GetName(), stripName); + if (stripName) + record.Discriminator = GetDiscriminator(entity); record.Flags = GetFieldAttributes(entity); var ecmaField = entity as Cts.Ecma.EcmaField; @@ -99,7 +102,10 @@ private MemberReference HandleFieldReference(Cts.FieldDesc field) private void InitializeFieldReference(Cts.FieldDesc entity, MemberReference record) { - record.Name = HandleString(entity.GetName()); + bool stripName = StripsName(entity.GetTypicalFieldDefinition()); + record.Name = HandleName(entity.GetName(), stripName); + if (stripName) + record.Discriminator = GetDiscriminator(entity); record.Parent = HandleType(entity.OwningType); record.Signature = new FieldSignature { diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Method.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Method.cs index 92f30cb3e9cdd2..dac3c885123dcb 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Method.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Method.cs @@ -60,7 +60,10 @@ private Method HandleMethodDefinition(Cts.MethodDesc method) private void InitializeMethodDefinition(Cts.MethodDesc entity, Method record) { - record.Name = HandleString(entity.GetName()); + bool stripName = StripsName(entity); + record.Name = HandleName(entity.GetName(), stripName); + if (stripName) + record.Discriminator = GetDiscriminator(entity); if (entity.HasInstantiation) { @@ -91,7 +94,7 @@ private void InitializeMethodDefinition(Cts.MethodDesc entity, Method record) Parameter paramRecord = new Parameter { Flags = param.Attributes, - Name = HandleString(reader.GetString(param.Name)), + Name = HandleName(reader.GetString(param.Name), !_policy.GeneratesNames(ecmaEntity.Module)), Sequence = checked((ushort)param.SequenceNumber) }; @@ -135,7 +138,10 @@ private MemberReference HandleMethodReference(Cts.MethodDesc method) private void InitializeMethodReference(Cts.MethodDesc entity, MemberReference record) { - record.Name = HandleString(entity.GetName()); + bool stripName = StripsName(entity.GetTypicalMethodDefinition()); + record.Name = HandleName(entity.GetName(), stripName); + if (stripName) + record.Discriminator = GetDiscriminator(entity); record.Parent = HandleType(entity.OwningType); record.Signature = HandleMethodSignature(entity.GetTypicalMethodDefinition().Signature); } diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs new file mode 100644 index 00000000000000..c15f5c706d166d --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs @@ -0,0 +1,134 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Internal.Metadata.NativeFormat.Writer; + +using Cts = Internal.TypeSystem; +using Debug = System.Diagnostics.Debug; +using Ecma = System.Reflection.Metadata; +using MetadataTokens = System.Reflection.Metadata.Ecma335.MetadataTokens; + +namespace ILCompiler.Metadata +{ + // Support for stripping the names of types and members from the metadata (see IMetadataPolicy.GeneratesNames). + // + // Names that are stripped are replaced with the empty string, which the metadata reader users treat as + // "name not available" (ECMA-335 doesn't allow empty names for types, methods, fields, properties and events). + // Records that only differ by their name would no longer be distinguishable by the writer, so the records get + // a discriminator that is derived from the metadata token of the entity. + internal partial class Transform + { + private Cts.MetadataType _attributeType; + + private ConstantStringValue HandleName(string name, bool stripName) + => HandleString(stripName ? string.Empty : name); + + // Types from modules that strip names are all placed into the root namespace. + private NamespaceDefinition HandleNamespaceDefinition(Cts.MetadataType type) + => HandleNamespaceDefinition(type.Module, StripsName(type) ? string.Empty : type.GetNamespace()); + + private NamespaceReference HandleNamespaceReference(Cts.MetadataType type) + => HandleNamespaceReference(type.Module, StripsName(type) ? string.Empty : type.GetNamespace()); + + private bool IsAttributeType(Cts.TypeDesc type) + { + _attributeType ??= type.Context.SystemModule.GetType("System"u8, "Attribute"u8); + return Cts.CastingHelper.CanCastTo(type, _attributeType); + } + + private bool StripsName(Cts.MetadataType type) + { + Debug.Assert(type.IsTypeDefinition); + return !_policy.GeneratesNames(type.Module); + } + + private bool StripsName(Cts.MethodDesc method) + { + Cts.MetadataType owningType = (Cts.MetadataType)method.OwningType; + if (_policy.GeneratesNames(owningType.Module)) + return false; + + // The runtime finds constructors by name. + if (method.IsConstructor || method.IsStaticConstructor) + return false; + + // The runtime finds the Invoke method of delegates by name. + if (owningType.IsDelegate && method.GetName() == "Invoke") + return false; + + // The runtime matches generic virtual methods (e.g. interface methods and their implementations) + // by name and signature. + if (method.IsVirtual && method.HasInstantiation) + return false; + + return true; + } + + private bool StripsName(Cts.FieldDesc field) + { + Cts.MetadataType owningType = (Cts.MetadataType)field.OwningType; + if (_policy.GeneratesNames(owningType.Module)) + return false; + + // Enum.ToString, Enum.Parse and friends need the names of the enum members. + if (field.IsLiteral && owningType.IsEnum) + return false; + + // Named arguments of custom attributes are resolved by name. + if (!field.IsStatic && IsAttributeType(owningType)) + return false; + + return true; + } + + private bool StripsPropertyName(Cts.Ecma.EcmaType owningType) + { + // Named arguments of custom attributes are resolved by name. + return !_policy.GeneratesNames(owningType.Module) && !IsAttributeType(owningType); + } + + // The discriminators below only need to be unique within the entities that can be compared + // by the writer, and be stable across compilations. Types are distinguished by their row number in + // the module, and members by their position in the member list of the declaring type. This keeps members + // with the same shape in different types poolable. + + private static int GetDiscriminator(Cts.MetadataType type) + => type is Cts.Ecma.EcmaType ecmaType ? MetadataTokens.GetRowNumber(ecmaType.Handle) : 0; + + private static int GetDiscriminator(Cts.MethodDesc method) + { + Cts.Ecma.EcmaMethod ecmaMethod = (Cts.Ecma.EcmaMethod)method.GetTypicalMethodDefinition(); + Cts.Ecma.EcmaType owningType = (Cts.Ecma.EcmaType)ecmaMethod.OwningType; + Ecma.MethodDefinitionHandleCollection.Enumerator methods + = owningType.MetadataReader.GetTypeDefinition(owningType.Handle).GetMethods().GetEnumerator(); + methods.MoveNext(); + return MetadataTokens.GetRowNumber(ecmaMethod.Handle) - MetadataTokens.GetRowNumber(methods.Current) + 1; + } + + private static int GetDiscriminator(Cts.FieldDesc field) + { + Cts.Ecma.EcmaField ecmaField = (Cts.Ecma.EcmaField)field.GetTypicalFieldDefinition(); + Cts.Ecma.EcmaType owningType = (Cts.Ecma.EcmaType)ecmaField.OwningType; + Ecma.FieldDefinitionHandleCollection.Enumerator fields + = owningType.MetadataReader.GetTypeDefinition(owningType.Handle).GetFields().GetEnumerator(); + fields.MoveNext(); + return MetadataTokens.GetRowNumber(ecmaField.Handle) - MetadataTokens.GetRowNumber(fields.Current) + 1; + } + + private static int GetDiscriminator(Cts.Ecma.EcmaType owningType, Ecma.PropertyDefinitionHandle property) + { + Ecma.PropertyDefinitionHandleCollection.Enumerator properties + = owningType.MetadataReader.GetTypeDefinition(owningType.Handle).GetProperties().GetEnumerator(); + properties.MoveNext(); + return MetadataTokens.GetRowNumber(property) - MetadataTokens.GetRowNumber(properties.Current) + 1; + } + + private static int GetDiscriminator(Cts.Ecma.EcmaType owningType, Ecma.EventDefinitionHandle eventHandle) + { + Ecma.EventDefinitionHandleCollection.Enumerator events + = owningType.MetadataReader.GetTypeDefinition(owningType.Handle).GetEvents().GetEnumerator(); + events.MoveNext(); + return MetadataTokens.GetRowNumber(eventHandle) - MetadataTokens.GetRowNumber(events.Current) + 1; + } + } +} diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Parameter.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Parameter.cs index 97f832d8904833..c52dbb52b30a69 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Parameter.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Parameter.cs @@ -34,7 +34,7 @@ private GenericParameter HandleGenericParameter(Cts.GenericParameterDesc genPara Ecma.GenericParameter genParamDef = reader.GetGenericParameter(ecmaGenParam.Handle); result.Flags = genParamDef.Attributes; - result.Name = HandleString(reader.GetString(genParamDef.Name)); + result.Name = HandleName(reader.GetString(genParamDef.Name), !_policy.GeneratesNames(ecmaGenParam.Module)); Ecma.CustomAttributeHandleCollection customAttributes = genParamDef.GetCustomAttributes(); if (customAttributes.Count > 0) diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Property.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Property.cs index 786d694be1dd6a..f98dac95747a60 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Property.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Property.cs @@ -13,8 +13,9 @@ namespace ILCompiler.Metadata { internal partial class Transform { - private Property HandleProperty(Cts.Ecma.EcmaModule module, Ecma.PropertyDefinitionHandle property) + private Property HandleProperty(Cts.Ecma.EcmaType owningType, Ecma.PropertyDefinitionHandle property) { + Cts.Ecma.EcmaModule module = owningType.Module; Ecma.MetadataReader reader = module.MetadataReader; Ecma.PropertyDefinition propDef = reader.GetPropertyDefinition(property); @@ -33,9 +34,11 @@ private Property HandleProperty(Cts.Ecma.EcmaModule module, Ecma.PropertyDefinit Ecma.BlobReader sigBlobReader = reader.GetBlobReader(propDef.Signature); Cts.PropertySignature sig = new Cts.Ecma.EcmaSignatureParser(module, sigBlobReader, Cts.NotFoundBehavior.Throw).ParsePropertySignature(); + bool stripName = StripsPropertyName(owningType); Property result = new Property { - Name = HandleString(reader.GetString(propDef.Name)), + Name = HandleName(reader.GetString(propDef.Name), stripName), + Discriminator = stripName ? GetDiscriminator(owningType, property) : 0, Flags = propDef.Attributes, Signature = new PropertySignature { diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Type.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Type.cs index b051f7a38684a8..a375d8790bc8b9 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Type.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Type.cs @@ -193,9 +193,12 @@ private TypeReference GetNestedReferenceParent(Cts.MetadataType entity) // will do the interning anyway. Debug.Assert(parentRecord is TypeDefinition); + bool stripName = StripsName(containingType); + parentReferenceRecord = new TypeReference { - TypeName = HandleString(containingType.GetName()), + TypeName = HandleName(containingType.GetName(), stripName), + Discriminator = stripName ? GetDiscriminator(containingType) : 0, }; if (containingType.ContainingType != null) @@ -204,7 +207,7 @@ private TypeReference GetNestedReferenceParent(Cts.MetadataType entity) } else { - parentReferenceRecord.NamespaceOrEnclosingType = HandleNamespaceReference(containingType.Module, containingType.GetNamespace()); + parentReferenceRecord.NamespaceOrEnclosingType = HandleNamespaceReference(containingType); } return parentReferenceRecord; @@ -214,16 +217,20 @@ private void InitializeTypeRef(Cts.MetadataType entity, TypeReference record) { Debug.Assert(entity.IsTypeDefinition); + bool stripName = StripsName(entity); + if (entity.ContainingType != null) { record.NamespaceOrEnclosingType = GetNestedReferenceParent(entity); } else { - record.NamespaceOrEnclosingType = HandleNamespaceReference(entity.Module, entity.GetNamespace()); + record.NamespaceOrEnclosingType = HandleNamespaceReference(entity); } - record.TypeName = HandleString(entity.GetName()); + record.TypeName = HandleName(entity.GetName(), stripName); + if (stripName) + record.Discriminator = GetDiscriminator(entity); } private void InitializeTypeDef(Cts.MetadataType entity, TypeDefinition record) @@ -239,7 +246,7 @@ private void InitializeTypeDef(Cts.MetadataType entity, TypeDefinition record) } else { - var namespaceDefinition = HandleNamespaceDefinition(entity.Module, entity.GetNamespace()); + var namespaceDefinition = HandleNamespaceDefinition(entity); record.NamespaceOrEnclosingType = namespaceDefinition; if (entity.IsModuleType) @@ -253,7 +260,10 @@ private void InitializeTypeDef(Cts.MetadataType entity, TypeDefinition record) } } - record.Name = HandleString(entity.GetName()); + bool stripName = StripsName(entity); + record.Name = HandleName(entity.GetName(), stripName); + if (stripName) + record.Discriminator = GetDiscriminator(entity); Cts.ClassLayoutMetadata layoutMetadata = entity.GetClassLayout(); record.Size = checked((uint)layoutMetadata.Size); @@ -332,14 +342,14 @@ private void InitializeTypeDef(Cts.MetadataType entity, TypeDefinition record) foreach (var e in ecmaRecord.GetEvents()) { - Event evt = HandleEvent(ecmaEntity.Module, e); + Event evt = HandleEvent(ecmaEntity, e); if (evt != null) record.Events.Add(evt); } foreach (var property in ecmaRecord.GetProperties()) { - Property prop = HandleProperty(ecmaEntity.Module, property); + Property prop = HandleProperty(ecmaEntity, property); if (prop != null) record.Properties.Add(prop); } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingDriver.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingDriver.cs index acf155339d2055..b3b8dd7adc7908 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingDriver.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingDriver.cs @@ -140,7 +140,8 @@ public ILScanResults Trim(ILCompilerOptions options, TrimmingCustomizations? cus rootEntireAssembliesModules: options.RootEntireAssemblies, additionalRootedAssemblies: options.AdditionalRootAssemblies.ToArray(), trimmedAssemblies: options.TrimAssemblies.ToArray(), - satelliteAssemblyFilePaths: Array.Empty()); + satelliteAssemblyFilePaths: Array.Empty(), + nameStrippingPolicy: MetadataNameStrippingPolicy.None); PInvokeILEmitterConfiguration pinvokePolicy = new ILCompilerTestPInvokePolicy(); InteropStateManager interopStateManager = new InteropStateManager(typeSystemContext.GeneratedAssembly); diff --git a/src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs b/src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs index 875bbeaf73b9e7..e35ff365b30ead 100644 --- a/src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs +++ b/src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs @@ -160,6 +160,8 @@ internal sealed class ILCompilerRootCommand : RootCommand new("--conditionalroot") { DefaultValueFactory = _ => Array.Empty(), Description = "Fully generate given assembly if it's used" }; public Option TrimmedAssemblies { get; } = new("--trim") { DefaultValueFactory = _ => Array.Empty(), Description = "Trim the specified assembly" }; + public Option StrippedNamesAssemblies { get; } = + new("--stripnames") { DefaultValueFactory = _ => Array.Empty(), Description = "Don't emit the names of types and members of the specified assembly into the reflection metadata" }; public Option RootDefaultAssemblies { get; } = new("--defaultrooting") { Description = "Root assemblies that are not marked [IsTrimmable]" }; public Option TargetArchitecture { get; } = @@ -266,6 +268,7 @@ public ILCompilerRootCommand(string[] args) : base(".NET Native IL Compiler") Options.Add(RootedAssemblies); Options.Add(ConditionallyRootedAssemblies); Options.Add(TrimmedAssemblies); + Options.Add(StrippedNamesAssemblies); Options.Add(RootDefaultAssemblies); Options.Add(TargetArchitecture); Options.Add(TargetOS); diff --git a/src/coreclr/tools/aot/ILCompiler/Program.cs b/src/coreclr/tools/aot/ILCompiler/Program.cs index 34305bc9ebf504..5f0310da400f1c 100644 --- a/src/coreclr/tools/aot/ILCompiler/Program.cs +++ b/src/coreclr/tools/aot/ILCompiler/Program.cs @@ -423,8 +423,16 @@ public int Run() _ => throw new CommandLineException($"Unknown stack trace data: {Get(_command.StackTraceData)}"), }; + var nameStrippingPolicy = new MetadataNameStrippingPolicy(Get(_command.StrippedNamesAssemblies)); + foreach (string strippedNamesAssembly in Get(_command.StrippedNamesAssemblies)) + { + // The reflection stack in the system module relies on the names of its own types and members. + if (string.Equals(strippedNamesAssembly, Get(_command.SystemModuleName), StringComparison.OrdinalIgnoreCase)) + throw new CommandLineException($"Stripping names of the system module '{strippedNamesAssembly}' is not supported"); + } + var stackTracePolicy = emitStackTraceData ? - (StackTraceEmissionPolicy)new EcmaMethodStackTraceEmissionPolicy(stackTraceLineNumbers) : new NoStackTraceEmissionPolicy(); + (StackTraceEmissionPolicy)new EcmaMethodStackTraceEmissionPolicy(stackTraceLineNumbers, nameStrippingPolicy) : new NoStackTraceEmissionPolicy(); MetadataBlockingPolicy mdBlockingPolicy; ManifestResourceBlockingPolicy resBlockingPolicy; @@ -474,7 +482,8 @@ public int Run() Get(_command.ConditionallyRootedAssemblies), rootedAssemblies, Get(_command.TrimmedAssemblies), - Get(_command.SatelliteFilePaths)); + Get(_command.SatelliteFilePaths), + nameStrippingPolicy); InteropStateManager interopStateManager = new InteropStateManager(typeSystemContext.GeneratedAssembly); InteropStubManager interopStubManager = new UsageBasedInteropStubManager(interopStateManager, pinvokePolicy, logger); diff --git a/src/libraries/Common/src/Internal/VersionResilientHashCode.cs b/src/libraries/Common/src/Internal/VersionResilientHashCode.cs index 5a5abdbabc5007..83d750600a6648 100644 --- a/src/libraries/Common/src/Internal/VersionResilientHashCode.cs +++ b/src/libraries/Common/src/Internal/VersionResilientHashCode.cs @@ -183,6 +183,16 @@ public static int ByrefTypeHashCode(int parameterTypeHashcode) return unchecked(parameterTypeHashcode + RotateLeft(parameterTypeHashcode, 7)) ^ 0x4C85; } + /// + /// Calculate hash code that identifies a type by its metadata handle. This is used for types whose + /// name is not available in metadata, so that the hash code can't be computed from the name. + /// + /// Metadata handle of the type + public static int MetadataHandleHashCode(int metadataHandle) + { + return (int)CombineTwoValuesIntoHash(0x4E414D45 /* NAME */, (uint)metadataHandle); + } + /// /// Bitwise left 32-bit rotation with wraparound. /// From 745d6e2c8542c7eae2752ad27640597105b8242c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 13 Nov 2026 23:55:01 -0800 Subject: [PATCH 03/11] Handle stripped names in the NativeAOT reflection runtime Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../CompilerServices/MethodNameAndSignature.cs | 17 ++++++++++++++++- ...ntimeAssembly.GetTypeCore.CaseInsensitive.cs | 9 +++++++-- ...RuntimeAssembly.GetTypeCore.CaseSensitive.cs | 4 ++++ .../Runtime/BindingFlagSupport/EventPolicies.cs | 3 ++- .../BindingFlagSupport/MemberPolicies.cs | 3 ++- .../NameFilter.NativeFormat.cs | 4 ++-- .../Runtime/BindingFlagSupport/NameFilter.cs | 7 +++++-- .../Runtime/BindingFlagSupport/Shared.cs | 6 ++++++ .../NativeFormatRuntimeNamedTypeInfo.cs | 7 +++++-- .../RuntimeConstructedGenericTypeInfo.cs | 15 ++++++++++++--- .../Runtime/TypeInfos/RuntimeNamedTypeInfo.cs | 7 +++++++ .../StackTraceMetadata/StackTraceMetadata.cs | 11 +++++++++-- 12 files changed, 77 insertions(+), 16 deletions(-) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/MethodNameAndSignature.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/MethodNameAndSignature.cs index 1f81afd1e620ac..1f2a0581b4190b 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/MethodNameAndSignature.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/MethodNameAndSignature.cs @@ -48,11 +48,22 @@ public override bool Equals(object? compare) // (Same assumption in GetHashCode below!) Debug.Assert(Reader == other.Reader); + // Methods with a name that was stripped by the compiler can only be identified by their handle, + // since the signature alone is not enough to tell them apart. + if (Handle.Equals(other.Handle)) + return true; + Method thisMethod = Reader.GetMethod(Handle); Method otherMethod = other.Reader.GetMethod(other.Handle); return thisMethod.Signature.Equals(otherMethod.Signature) - && thisMethod.Name.Equals(otherMethod.Name); + && thisMethod.Name.Equals(otherMethod.Name) + && !HasStrippedName(thisMethod); + } + + private bool HasStrippedName(Method method) + { + return Reader.ReadStringAsBytes(method.Name).IsEmpty; } public bool ReturnTypeHasInstantiation @@ -72,6 +83,10 @@ public override int GetHashCode() { Method method = Reader.GetMethod(Handle); + // Methods with a name that was stripped by the compiler are only identified by their handle + if (HasStrippedName(method)) + return Handle.GetHashCode(); + // Assumes we only have one metadata blob return method.Signature.GetHashCode() ^ method.Name.GetHashCode(); } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseInsensitive.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseInsensitive.cs index a40c7062483538..2e6c74a0b7a8e3 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseInsensitive.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseInsensitive.cs @@ -78,16 +78,21 @@ private LowLevelDictionary CreateCaseInsensitiveTypeDictionary( { TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader); NamespaceDefinitionHandle namespaceHandle = typeDefinition.NamespaceOrEnclosingType.ToNamespaceDefinitionHandle(reader); + string typeName = typeDefinition.Name.GetString(reader); + + // Types with a name that was stripped by the compiler can't be found by name. + if (typeName.Length == 0) + continue; + string ns = namespaceHandle.ToNamespaceName(reader); if (ns.Length != 0) ns += "."; - string fullName = (ns + typeDefinition.Name.GetString(reader)).ToLowerInvariant(); + string fullName = (ns + typeName).ToLowerInvariant(); if (!dict.TryGetValue(fullName, out _)) { dict.Add(fullName, new QHandle(reader, typeDefinitionHandle)); } } - foreach (TypeForwarderHandle typeForwarderHandle in scopeDefinition.TypeForwarders) { TypeForwarder typeForwarder = typeForwarderHandle.GetTypeForwarder(reader); diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseSensitive.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseSensitive.cs index dc3c789207070d..ad2ab39b902302 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseSensitive.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseSensitive.cs @@ -22,6 +22,10 @@ internal sealed override RuntimeTypeInfo UncachedGetTypeCoreCaseSensitive(string VersionResilientHashCode.NameHashCode(namespaceName), VersionResilientHashCode.NameHashCode(name)); + // Types with a name that was stripped by the compiler can't be found by name. + if (name.Length == 0) + return null; + MetadataReader reader = Scope.Reader; ScopeDefinition scopeDefinition = Scope.ScopeDefinition; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs index e7d8dbe776cfda..f4b751f0938d05 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs @@ -53,7 +53,8 @@ public sealed override bool IsSuppressedByMoreDerivedMember(EventInfo member, Ev { for (int i = startIndex; i < endIndex; i++) { - if (priorMembers[i].Name == member.Name) + // Members with a name that was stripped by the compiler never hide other members. + if (member.Name.Length != 0 && priorMembers[i].Name == member.Name) return true; } return false; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/MemberPolicies.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/MemberPolicies.cs index 18e4390d44a3e9..3560d1873f29db 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/MemberPolicies.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/MemberPolicies.cs @@ -72,7 +72,8 @@ public virtual BindingFlags ModifyBindingFlags(BindingFlags bindingFlags) // protected static bool AreNamesAndSignaturesEqual(MethodInfo method1, MethodInfo method2) { - if (method1.Name != method2.Name) + // Methods with a name that was stripped by the compiler can't be matched by name. + if (method1.Name.Length == 0 || method1.Name != method2.Name) return false; ReadOnlySpan p1 = method1.GetParametersAsSpan(); diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.NativeFormat.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.NativeFormat.cs index 68ff0cc338e655..d43a0ec64222fb 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.NativeFormat.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.NativeFormat.cs @@ -14,11 +14,11 @@ internal abstract partial class NameFilter internal sealed partial class NameFilterCaseSensitive : NameFilter { - public sealed override bool Matches(ConstantStringValueHandle stringHandle, MetadataReader reader) => stringHandle.StringEquals(ExpectedName, reader); + public sealed override bool Matches(ConstantStringValueHandle stringHandle, MetadataReader reader) => CanMatch && stringHandle.StringEquals(ExpectedName, reader); } internal sealed partial class NameFilterCaseInsensitive : NameFilter { - public sealed override bool Matches(ConstantStringValueHandle stringHandle, MetadataReader reader) => stringHandle.GetConstantStringValue(reader).Value.Equals(ExpectedName, StringComparison.OrdinalIgnoreCase); + public sealed override bool Matches(ConstantStringValueHandle stringHandle, MetadataReader reader) => CanMatch && stringHandle.GetConstantStringValue(reader).Value.Equals(ExpectedName, StringComparison.OrdinalIgnoreCase); } } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.cs index 2fe7754a6f2744..6c1acb5c4cb2ea 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.cs @@ -14,6 +14,9 @@ protected NameFilter(string expectedName) public abstract bool Matches(string name); protected string ExpectedName { get; } + + // Members with a name that was stripped by the compiler have an empty name. They can't be found by name. + protected bool CanMatch => ExpectedName.Length != 0; } internal sealed partial class NameFilterCaseSensitive : NameFilter @@ -23,7 +26,7 @@ public NameFilterCaseSensitive(string expectedName) { } - public sealed override bool Matches(string name) => name.Equals(ExpectedName, StringComparison.Ordinal); + public sealed override bool Matches(string name) => CanMatch && name.Equals(ExpectedName, StringComparison.Ordinal); } internal sealed partial class NameFilterCaseInsensitive : NameFilter @@ -33,6 +36,6 @@ public NameFilterCaseInsensitive(string expectedName) { } - public sealed override bool Matches(string name) => name.Equals(ExpectedName, StringComparison.OrdinalIgnoreCase); + public sealed override bool Matches(string name) => CanMatch && name.Equals(ExpectedName, StringComparison.OrdinalIgnoreCase); } } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/Shared.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/Shared.cs index 095fdb7bbe083b..e75053323eff75 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/Shared.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/Shared.cs @@ -157,6 +157,12 @@ public static bool QualifiesBasedOnParameterCount(this MethodBase methodBase, Bi } string name = member.Name; + if (name.Length == 0) + { + // The name was stripped by the compiler, so the base class members can't be matched by name. + return null; + } + Type type = member.DeclaringType!; for (; ; ) { diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs index 8bb3a569761825..093f783a760733 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs @@ -142,11 +142,14 @@ public sealed override string ToString() { StringBuilder? sb = null; + // The full name is null when the name of the type was stripped by the compiler. + string fullName = FullName ?? Name; + foreach (GenericParameterHandle genericParameterHandle in _typeDefinition.GenericParameters) { if (sb == null) { - sb = new StringBuilder(FullName); + sb = new StringBuilder(fullName); sb.Append('['); } else @@ -159,7 +162,7 @@ public sealed override string ToString() if (sb == null) { - return FullName; + return fullName; } else { diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeConstructedGenericTypeInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeConstructedGenericTypeInfo.cs index efb940d40daec1..ff875b4861f567 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeConstructedGenericTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeConstructedGenericTypeInfo.cs @@ -58,18 +58,27 @@ public sealed override string FullName if (ContainsGenericParameters) return null; + // The definition or a type argument might have a name that was stripped by the compiler. + string? definitionFullName = GenericTypeDefinitionTypeInfo.FullName; + if (definitionFullName is null) + return null; + StringBuilder fullName = new StringBuilder(); - fullName.Append(GenericTypeDefinitionTypeInfo.FullName); + fullName.Append(definitionFullName); fullName.Append('['); RuntimeTypeInfo[] genericTypeArguments = _key.GenericTypeArguments; for (int i = 0; i < genericTypeArguments.Length; i++) { + string? argumentName = genericTypeArguments[i].AssemblyQualifiedName; + if (argumentName is null) + return null; + if (i != 0) fullName.Append(','); fullName.Append('['); - fullName.Append(genericTypeArguments[i].AssemblyQualifiedName); + fullName.Append(argumentName); fullName.Append(']'); } fullName.Append(']'); @@ -149,7 +158,7 @@ public sealed override string ToString() { // Now, append the generic type arguments. StringBuilder sb = new StringBuilder(); - sb.Append(GenericTypeDefinitionTypeInfo.FullName); + sb.Append(GenericTypeDefinitionTypeInfo.FullName ?? GenericTypeDefinitionTypeInfo.Name); sb.Append('['); RuntimeTypeInfo[] genericTypeArguments = _key.GenericTypeArguments; for (int i = 0; i < genericTypeArguments.Length; i++) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeNamedTypeInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeNamedTypeInfo.cs index c76bf2311f7d6a..344f25e270251a 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeNamedTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeNamedTypeInfo.cs @@ -76,10 +76,17 @@ public sealed override string FullName string name = Name; + // The name of the type was stripped by the compiler (see IlcStripNamesAssembly), so it has no full name. + if (name.Length == 0) + return null; + RuntimeTypeInfo? declaringType = this.InternalDeclaringType; if (declaringType is not null) { string? declaringTypeFullName = declaringType.FullName; + if (declaringTypeFullName is null) + return null; + return declaringTypeFullName + "+" + name; } diff --git a/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs b/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs index efeda5f697e7b2..fee69ab652613b 100644 --- a/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs +++ b/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs @@ -85,7 +85,8 @@ public static unsafe string GetMethodNameFromStartAddressIfAvailable(IntPtr meth if (methodStartAddress != IntPtr.Zero && ReflectionExecution.TryGetMethodMetadataFromAddress(methodStartAddress, isFunctionPointer: false, out MetadataReader reader, out TypeDefinitionHandle typeHandle, - out MethodHandle methodHandle)) + out MethodHandle methodHandle) + && !IsNameStripped(reader, methodHandle)) { if (StackTraceHiddenMetadataPresent()) { @@ -203,7 +204,8 @@ private static unsafe (string, int) GetLineNumberInfo(IntPtr methodStartAddress, if (methodStartAddress != IntPtr.Zero && ReflectionExecution.TryGetMethodMetadataFromAddress(methodStartAddress, isFunctionPointer: false, out MetadataReader reader, out TypeDefinitionHandle typeHandle, - out MethodHandle methodHandle)) + out MethodHandle methodHandle) + && !IsNameStripped(reader, methodHandle)) { return CreateDiagnosticMethodInfo(reader, typeHandle, reader.GetMethod(methodHandle).Name); } @@ -246,6 +248,11 @@ private static DiagnosticMethodInfo CreateDiagnosticMethodInfo(MetadataReader re FormatAssemblyName(reader, owningType)); } + private static bool IsNameStripped(MetadataReader reader, MethodHandle methodHandle) + { + return reader.ReadStringAsBytes(reader.GetMethod(methodHandle).Name).IsEmpty; + } + private static string FormatAssemblyName(MetadataReader reader, Handle handle) { switch (handle.HandleType) From 8b9a0717aa2554f2d6f58ebb4fff4e6d53cb8744 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 13 Nov 2026 23:55:03 -0800 Subject: [PATCH 04/11] Add smoke test and docs for stripped names Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/coreclr/nativeaot/docs/optimizing.md | 32 ++ .../SmokeTests/StrippedNames/StrippedNames.cs | 328 ++++++++++++++++++ .../StrippedNames/StrippedNames.csproj | 25 ++ .../StrippedNames/StrippedNamesLibrary.cs | 87 +++++ .../StrippedNames/StrippedNamesLibrary.csproj | 9 + 5 files changed, 481 insertions(+) create mode 100644 src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs create mode 100644 src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.csproj create mode 100644 src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs create mode 100644 src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.csproj diff --git a/src/coreclr/nativeaot/docs/optimizing.md b/src/coreclr/nativeaot/docs/optimizing.md index 755fcc2710ca65..9433b37e48ae39 100644 --- a/src/coreclr/nativeaot/docs/optimizing.md +++ b/src/coreclr/nativeaot/docs/optimizing.md @@ -7,3 +7,35 @@ The rest of the document talks about options that exist, but their names and pur ## Options related to code generation * ``: By default, the compiler targets the minimum instruction set supported by the target OS and architecture. This option allows targeting newer instruction sets for better performance. The native binary will require the instruction sets to be supported by the hardware in order to run. For example, `avx2,bmi2,fma,pclmul,popcnt,aes` will produce binary that takes advantage of instruction sets that are typically present on current Intel and AMD processors. `native` will produce a binary that uses instructions that currently running CPU supports (no cross-compilation support). Run `ilc --help` for the full list of available instruction sets. `ilc` can be executed from the NativeAOT package in your local nuget cache e.g. `%USERPROFILE%\.nuget\packages\runtime.win-x64.microsoft.dotnet.ilcompiler\8.0.0-...\tools\ilc.exe` on Windows or `~/.nuget/packages/runtime.linux-arm64.microsoft.dotnet.ilcompiler/8.0.0-.../tools/ilc` on Linux. * ``: By default, the compiler targets a `Vector` size of `16` or `32` bytes, depending on the underlying instruction sets supported. This option allows specifying a different maximum bit width. For example, by default on x64 hardware `Vector` will be 16-bytes, however, if `AVX2` is targeted then `Vector` will automatically grow to be 32-bytes instead. Setting `128` would keep the size as 16-bytes. Alternatively, even if `AVX512F` is targeted then by default `Vector` will not grow larger than 32-bytes, setting `512` would allow it to grow to 64-bytes. + +## Options related to reflection metadata size + +### Stripping the names of types and members from specific assemblies + +* ``: Strips the names of all types and members of the assembly with the given simple name from the reflection metadata in the final binary. The item can be specified multiple times. It is passed to the compiler as `--stripnames:MyAssembly`. This is meant for assemblies that contain a large amount of generated code, such as interop assemblies with long generated type names, where the names are never used at runtime. The default behavior of the compiler is not affected unless the item is specified. + +The option is opt-in per assembly, because it changes the observable behavior of reflection for the types and members of that assembly. Names are replaced with the empty string in the metadata, so the cost of a name is no longer paid in the binary. Names remain available in the compiler map file (``), in the mstat file, and in the symbol files (`.pdb`, `.dwp`, `.dSYM`) because these are produced from the compiler's own type system and not from the reflection metadata. Note that on platforms where the debug information is part of the image, the names will be there as well. + +Behavior for types and members of an assembly that strips names: + +| API | Result | +| --- | --- | +| `Type.Name`, `MemberInfo.Name`, `ParameterInfo.Name`, names of generic parameters | `""` (empty string, the properties are not nullable) | +| `Type.Namespace`, `Type.FullName`, `Type.AssemblyQualifiedName` | `null` | +| `Type.ToString()` | `""`, matching `Type.Name` (the method is not nullable) | +| `FullName` and `AssemblyQualifiedName` of arrays, pointers, by-refs, nested types and constructed generic types that involve such a type (including as a type argument) | `null`, like for a generic parameter | +| `Type.GetType(string)`, `Assembly.GetType(string)`, `GetMethod(string)`, `GetField(string)`, `GetProperty(string)`, `GetEvent(string)`, `GetNestedType(string)`, `GetMember(string)` | Don't find the type or member, since nothing can match an empty name | +| Enum members, e.g. `Enum.ToString()`, `Enum.Parse` | Unchanged, the names of enum literals are kept | +| Constructors (`.ctor`, `.cctor`), `Invoke` of delegates, generic virtual methods | Unchanged, the runtime looks these up by name | +| Fields and properties of attribute types, and named arguments of custom attributes | Unchanged | +| Exception messages and `Exception.ToString()` | Use the empty name for the type | +| Stack traces | The frames of methods of the assembly don't have names. They show up as an offset in the module, which can be symbolicated with the symbol files, e.g. on a crash report server | + +Everything else is unchanged. In particular, type identity, `typeof`, `GetType()`, `Activator.CreateInstance`, `MethodInfo.Invoke`, `MakeGenericType`, `MakeGenericMethod`, custom attribute instantiation, and virtual and interface dispatch don't depend on the names. + +Limitations: + +* The names are removed from the reflection metadata only. Other places in the binary that contain names are not affected, e.g. the field names that are part of struct marshalling metadata, the keys of external type maps (`TypeMapping`), embedded resource names, and strings that code explicitly contains (e.g. the string passed to `[UnsafeAccessorType]`, `Type.GetType`, or the arguments of custom attributes). +* Code that looks up types or members of such an assembly by name, e.g. `Type.GetType("Namespace.Type, Assembly")`, will not find them, even if the compiler has seen the string. A reference that goes through metadata directly (e.g. a type referenced by a custom attribute argument) is not affected. +* Serializers, `EventSource`, `DataContract`, data binding, and anything else that derives behavior from type or member names don't work for these types. +* The setting is not supported for the framework assemblies or for multi-file compilation. diff --git a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs new file mode 100644 index 00000000000000..0f79ecf87a09a8 --- /dev/null +++ b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs @@ -0,0 +1,328 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; + +using StrippedNamesLibrary; + +// The StrippedNamesLibrary assembly is listed in IlcStripNamesAssembly (see StrippedNames.csproj), so the reflection +// metadata for its types and members has no names. Types and members from this assembly keep their names. +internal static class Program +{ + private static int Main() + { + TestNamesOfStrippedTypes.Run(); + TestNamesOfStrippedMembers.Run(); + TestNamesOfRetainedTypes.Run(); + TestRetainedMemberNames.Run(); + TestTypeIdentity.Run(); + TestGenericVirtualMethods.Run(); + TestLookupByName.Run(); + TestAttributes.Run(); + TestStackTrace.Run(); + TestNamesAreNotInTheImage.Run(); + + return 100; + } + + private static Type Keep([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type) => type; + + private static void Assert(bool condition, [CallerArgumentExpression(nameof(condition))] string message = null) + { + if (!condition) + throw new Exception(message); + } + + // Prevents the names from being constant folded into the program, which would defeat the check for the image contents. + private static string Join(params string[] parts) => string.Concat(parts); + + private static class TestNamesOfStrippedTypes + { + public static void Run() + { + Type widget = Keep(typeof(Widget)); + + Assert(widget.Name == string.Empty); + Assert(widget.FullName is null); + Assert(widget.Namespace is null); + Assert(widget.AssemblyQualifiedName is null); + Assert(widget.ToString() == string.Empty); + Assert(widget.Assembly == typeof(Base).Assembly); + + Type nested = Keep(typeof(Widget.Nested)); + Assert(nested.Name == string.Empty); + Assert(nested.FullName is null); + Assert(nested.DeclaringType == widget); + + Assert(typeof(Widget[]).FullName is null); + Assert(typeof(Widget).MakeByRefType().FullName is null); + Assert(typeof(Widget).MakePointerType().FullName is null); + + // Constructed generic types have no full name if any of their components has no name + Assert(typeof(GenericHolder<>).FullName is null); + Assert(typeof(GenericHolder).FullName is null); + Assert(typeof(GenericHolder).FullName is null); + Assert(typeof(List).FullName is null); + Assert(typeof(List).AssemblyQualifiedName is null); + Assert(typeof(List).ToString() is not null); + Assert(typeof(List).GetGenericArguments()[0] == typeof(Widget)); + + // ... but they keep it if they are not involved + Assert(typeof(List).FullName is not null); + Assert(typeof(List).FullName.StartsWith("System.Collections.Generic.List`1[[System.String", StringComparison.Ordinal)); + + Assert(typeof(Color).Name == string.Empty); + Assert(typeof(Callback).Name == string.Empty); + } + } + + private static class TestNamesOfStrippedMembers + { + public static void Run() + { + Type widget = Keep(typeof(Widget)); + const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; + + // Methods that have the same shape must stay distinct without their names + MethodInfo[] methods = widget.GetMethods(flags); + Assert(methods.Length == 7); + Assert(methods.All(m => m.Name == string.Empty)); + Assert(methods.All(m => m.DeclaringType == widget)); + + Widget instance = new Widget(); + List results = new(); + foreach (MethodInfo method in methods) + { + if (method.GetParameters().Length == 0 && method.ReturnType == typeof(string)) + results.Add((string)method.Invoke(instance, null)); + } + results.Sort(StringComparer.Ordinal); + Assert(results.Count == 2); + Assert(results[0] == "first"); + Assert(results[1] == "second"); + + FieldInfo[] fields = widget.GetFields(flags); + Assert(fields.Length == 1); + Assert(fields[0].Name == string.Empty); + fields[0].SetValue(instance, 42); + Assert(instance.Field == 42); + + PropertyInfo[] properties = widget.GetProperties(flags); + Assert(properties.Length == 1); + Assert(properties[0].Name == string.Empty); + properties[0].SetValue(instance, 7); + Assert((int)properties[0].GetValue(instance) == 7); + + EventInfo[] events = widget.GetEvents(flags); + Assert(events.Length == 1); + Assert(events[0].Name == string.Empty); + + Assert(widget.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic).Length == 1); + } + } + + private static class TestNamesOfRetainedTypes + { + public static void Run() + { + Type control = Keep(typeof(ControlNamespace.ControlType)); + + Assert(control.Name == "ControlType"); + Assert(control.Namespace == "ControlNamespace"); + Assert(control.FullName == "ControlNamespace.ControlType"); + Assert(control.ToString() == "ControlNamespace.ControlType"); + Assert(control.AssemblyQualifiedName.StartsWith("ControlNamespace.ControlType, ", StringComparison.Ordinal)); + + Assert(typeof(ControlNamespace.ControlType.NestedType).FullName == "ControlNamespace.ControlType+NestedType"); + Assert(typeof(ControlNamespace.ControlGeneric).FullName.StartsWith("ControlNamespace.ControlGeneric`1[[System.Int32", StringComparison.Ordinal)); + Assert(typeof(ControlNamespace.ControlType[]).FullName == "ControlNamespace.ControlType[]"); + + Assert(control.GetMethod(Join("Control", "Method")) is not null); + Assert(control.GetField(Join("Control", "Field")) is not null); + Assert(control.GetProperty(Join("Control", "Property")) is not null); + Assert(Type.GetType(Join("ControlNamespace.", "ControlType")) == control); + } + } + + private static class TestRetainedMemberNames + { + public static void Run() + { + // Constructors are found by name + Type widget = Keep(typeof(Widget)); + ConstructorInfo ctor = widget.GetConstructor(Type.EmptyTypes); + Assert(ctor is not null); + Assert(ctor.Name == ".ctor"); + Assert(ctor.Invoke(null) is Widget); + Assert(Activator.CreateInstance(widget) is Widget); + + // Enum members are retained + Assert(Color.Green.ToString() == "Green"); + Assert(Enum.Parse("Red") == Color.Red); + Assert(string.Join(",", Enum.GetNames()) == "Red,Green"); + Assert(Color.Red.ToString("G") == "Red"); + + // The Invoke method of delegates is retained + Callback callback = x => x * 2; + Assert(callback(2) == 4); + Assert((int)callback.DynamicInvoke(3) == 6); + Assert(Keep(typeof(Callback)).GetMethod("Invoke") is not null); + } + } + + private static class TestTypeIdentity + { + public static void Run() + { + // Types need to stay identifiable regardless of whether they are reached from a type handle or from the metadata + Type derived = Keep(typeof(Derived)); + Type baseType = derived.BaseType; + Assert(baseType == typeof(Base)); + Assert(baseType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Any(m => m.DeclaringType == typeof(Base))); + + Type[] types = typeof(Base).Assembly.GetTypes(); + Assert(Array.IndexOf(types, typeof(Base)) >= 0); + Assert(Array.IndexOf(types, typeof(Derived)) >= 0); + Assert(Array.IndexOf(types, typeof(Widget.Nested)) >= 0); + + Type marked = types.Single(t => t.IsDefined(typeof(MarkerAttribute))); + Assert(marked == Keep(typeof(Marked))); + Assert(Activator.CreateInstance(marked).GetType() == marked); + + Base instance = new Derived(); + Assert(instance.GetType() == derived); + Assert(instance.GetType().BaseType == baseType); + Assert(instance.Hello() == "Derived"); + } + } + + private static class TestGenericVirtualMethods + { + public static void Run() + { + // Generic virtual methods are matched by name and signature, so they keep their names + GvmBase gvm = new GvmDerived(); + Assert(gvm.Describe() == "GvmDerived"); + Assert(gvm.Other() == "GvmDerived.Other"); + Assert(gvm.Describe() == "GvmDerived"); + Assert(gvm.Other() == "GvmDerived.Other"); + + Type gvmType = Keep(typeof(GvmBase)); + MethodInfo describe = gvmType.GetMethod("Describe").MakeGenericMethod(typeof(Marked)); + Assert((string)describe.Invoke(gvm, null) == "GvmDerived"); + MethodInfo other = gvmType.GetMethod("Other").MakeGenericMethod(typeof(Marked)); + Assert((string)other.Invoke(gvm, null) == "GvmDerived.Other"); + + IConverter converter = new IntConverter(); + Assert(converter.Convert(1) == 2); + Assert(converter.Convert(1).Equals(2)); + } + } + + private static class TestLookupByName + { + public static void Run() + { + string ns = "StrippedNamesLibrary."; + Assert(Type.GetType(Join(ns, "Widget", ", StrippedNamesLibrary")) is null); + Assert(Type.GetType(Join(ns, "Widget", ", StrippedNamesLibrary"), throwOnError: false, ignoreCase: true) is null); + Assert(Type.GetType(Join(ns, "Derived")) is null); + Assert(typeof(Base).Assembly.GetType(Join(ns, "Base")) is null); + Assert(typeof(Base).Assembly.GetType(Join(ns, "Base"), throwOnError: false, ignoreCase: true) is null); + + Type widget = Keep(typeof(Widget)); + Assert(widget.GetMethod(Join("First", "Method")) is null); + Assert(widget.GetMethod(Join("first", "method"), BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase) is null); + Assert(widget.GetField(Join("Fie", "ld")) is null); + Assert(widget.GetProperty(Join("Co", "unt")) is null); + Assert(widget.GetEvent(Join("Chan", "ged")) is null); + Assert(widget.GetNestedType(Join("Nes", "ted")) is null); + } + } + + private static class TestAttributes + { + public static void Run() + { + // Named arguments are resolved by name, so the members of attribute types are retained + MarkerAttribute attribute = typeof(Marked).GetCustomAttribute(); + Assert(attribute is not null); + Assert(attribute.Label == "label"); + Assert(attribute.Number == 42); + + CustomAttributeData data = typeof(Marked).CustomAttributes.Single(); + Assert(data.AttributeType == typeof(MarkerAttribute)); + Assert(data.NamedArguments.Select(a => a.MemberName).OrderBy(n => n, StringComparer.Ordinal).SequenceEqual(new[] { "Label", "Number" })); + + Assert(new Marked() is not null); + } + } + + private static class TestStackTrace + { + public static void Run() + { + string stackTrace = null; + try + { + UniqueStrippedTypeNameMarker.UniqueStrippedThrowingMethodMarker(); + } + catch (InvalidOperationException ex) + { + stackTrace = ex.StackTrace; + _ = ex.ToString(); + } + + // The names are only available in the symbol files + Assert(!string.IsNullOrEmpty(stackTrace)); + Assert(!stackTrace.Contains(Join("Unique", "Stripped"))); + } + } + + private static class TestNamesAreNotInTheImage + { + public static void Run() + { + // The debug information of other platforms is part of the image + if (!OperatingSystem.IsWindows()) + return; + + byte[] image = File.ReadAllBytes(Environment.ProcessPath); + + // Check that the same lookup finds the names that are expected to be there + Assert(Contains(image, Join("ControlType"))); + Assert(Contains(image, Join("Control", "Method"))); + + Assert(!Contains(image, Join("Unique", "StrippedTypeNameMarker"))); + Assert(!Contains(image, Join("Unique", "StrippedThrowingMethodMarker"))); + Assert(!Contains(image, Join("First", "Method"))); + Assert(!Contains(image, Join("Second", "Method"))); + Assert(!Contains(image, Join("Rai", "seChanged"))); + Assert(!Contains(image, Join("Gvm", "Derived"))); + Assert(!Contains(image, Join("Int", "Converter"))); + } + + private static bool Contains(byte[] image, string text) => image.AsSpan().IndexOf(Encoding.UTF8.GetBytes(text)) >= 0; + } +} + +namespace ControlNamespace +{ + public class ControlType + { + public int ControlField; + public int ControlProperty { get; set; } + public void ControlMethod() { } + + public class NestedType { } + } + + public class ControlGeneric { } +} diff --git a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.csproj b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.csproj new file mode 100644 index 00000000000000..e284de49a7ad5e --- /dev/null +++ b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.csproj @@ -0,0 +1,25 @@ + + + Exe + 0 + true + + + true + $(NoWarn);IL3050 + + + true + true + false + + + + + + + + + + + diff --git a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs new file mode 100644 index 00000000000000..63016afed53815 --- /dev/null +++ b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs @@ -0,0 +1,87 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Runtime.CompilerServices; +namespace StrippedNamesLibrary +{ + public class Widget + { + public int Field; + + public Widget() { } + + public int Count { get; set; } + + public event EventHandler Changed; + + public string FirstMethod() => "first"; + public string SecondMethod() => "second"; + + public void RaiseChanged() => Changed?.Invoke(this, EventArgs.Empty); + + public class Nested { } + } + + public class Base + { + public virtual string Hello() => "Base"; + } + + public class Derived : Base + { + public override string Hello() => "Derived"; + } + + // Generic virtual methods are matched by name and signature at runtime, so they keep their names. + public class GvmBase + { + public virtual string Describe() => "GvmBase"; + public virtual string Other() => "GvmBase.Other"; + } + + public class GvmDerived : GvmBase + { + public override string Describe() => "GvmDerived"; + public override string Other() => "GvmDerived.Other"; + } + + public interface IConverter + { + U Convert(T value); + } + + public class IntConverter : IConverter + { + public U Convert(int value) => (U)(object)(value + 1); + } + + public class GenericHolder + { + public T Value; + } + + public enum Color + { + Red, + Green, + } + + public delegate int Callback(int x); + + [AttributeUsage(AttributeTargets.All)] + public class MarkerAttribute : Attribute + { + public string Label { get; set; } + public int Number; + } + + [Marker(Label = "label", Number = 42)] + public class Marked { } + + public class UniqueStrippedTypeNameMarker + { + [MethodImpl(MethodImplOptions.NoInlining)] + public static void UniqueStrippedThrowingMethodMarker() => throw new InvalidOperationException(); + } +} diff --git a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.csproj b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.csproj new file mode 100644 index 00000000000000..85bd69496a3985 --- /dev/null +++ b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.csproj @@ -0,0 +1,9 @@ + + + Library + SharedLibrary + + + + + From 4520e7f206baa9981c95b5d32eecd2d465c9fcb6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Nov 2026 00:39:24 -0800 Subject: [PATCH 05/11] Address review feedback for stripped names Keep the names of all generic methods and of methods of attribute types, reject multi-file compilation, and extend tests and docs. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../NativeFormatRuntimeNamedTypeInfo.cs | 6 ++- .../StackTraceMetadata/StackTraceMetadata.cs | 13 +++--- src/coreclr/nativeaot/docs/optimizing.md | 10 +++-- .../ILCompiler/Metadata/Transform.Names.cs | 11 +++-- src/coreclr/tools/aot/ILCompiler/Program.cs | 3 ++ .../SmokeTests/StrippedNames/StrippedNames.cs | 29 ++++++++++++++ .../StrippedNames/StrippedNamesLibrary.cs | 40 +++++++++++++++++++ 7 files changed, 98 insertions(+), 14 deletions(-) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs index 093f783a760733..d39ba099184f39 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs @@ -142,8 +142,10 @@ public sealed override string ToString() { StringBuilder? sb = null; - // The full name is null when the name of the type was stripped by the compiler. - string fullName = FullName ?? Name; + // The name of the type was stripped by the compiler, so there is nothing to print. + string? fullName = FullName; + if (fullName is null) + return Name; foreach (GenericParameterHandle genericParameterHandle in _typeDefinition.GenericParameters) { diff --git a/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs b/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs index fee69ab652613b..4431d0edbf3242 100644 --- a/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs +++ b/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs @@ -86,7 +86,7 @@ public static unsafe string GetMethodNameFromStartAddressIfAvailable(IntPtr meth out MetadataReader reader, out TypeDefinitionHandle typeHandle, out MethodHandle methodHandle) - && !IsNameStripped(reader, methodHandle)) + && !IsNameStripped(reader, typeHandle, methodHandle)) { if (StackTraceHiddenMetadataPresent()) { @@ -205,7 +205,7 @@ private static unsafe (string, int) GetLineNumberInfo(IntPtr methodStartAddress, out MetadataReader reader, out TypeDefinitionHandle typeHandle, out MethodHandle methodHandle) - && !IsNameStripped(reader, methodHandle)) + && !IsNameStripped(reader, typeHandle, methodHandle)) { return CreateDiagnosticMethodInfo(reader, typeHandle, reader.GetMethod(methodHandle).Name); } @@ -225,7 +225,8 @@ private static DiagnosticMethodInfo GetDiagnosticMethodInfoFromFunctionPointerIf if (ReflectionExecution.TryGetMethodMetadataFromAddress(functionPointer, isFunctionPointer: true, out MetadataReader reader, out TypeDefinitionHandle typeHandle, - out MethodHandle methodHandle)) + out MethodHandle methodHandle) + && !IsNameStripped(reader, typeHandle, methodHandle)) { return CreateDiagnosticMethodInfo(reader, typeHandle, reader.GetMethod(methodHandle).Name); } @@ -248,9 +249,11 @@ private static DiagnosticMethodInfo CreateDiagnosticMethodInfo(MetadataReader re FormatAssemblyName(reader, owningType)); } - private static bool IsNameStripped(MetadataReader reader, MethodHandle methodHandle) + private static bool IsNameStripped(MetadataReader reader, TypeDefinitionHandle typeHandle, MethodHandle methodHandle) { - return reader.ReadStringAsBytes(reader.GetMethod(methodHandle).Name).IsEmpty; + // Constructors and a few other methods keep their names, but are still declared on a type that doesn't have one. + return reader.ReadStringAsBytes(reader.GetMethod(methodHandle).Name).IsEmpty + || reader.ReadStringAsBytes(reader.GetTypeDefinition(typeHandle).Name).IsEmpty; } private static string FormatAssemblyName(MetadataReader reader, Handle handle) diff --git a/src/coreclr/nativeaot/docs/optimizing.md b/src/coreclr/nativeaot/docs/optimizing.md index 9433b37e48ae39..c1f2d16cac8cf2 100644 --- a/src/coreclr/nativeaot/docs/optimizing.md +++ b/src/coreclr/nativeaot/docs/optimizing.md @@ -22,14 +22,16 @@ Behavior for types and members of an assembly that strips names: | --- | --- | | `Type.Name`, `MemberInfo.Name`, `ParameterInfo.Name`, names of generic parameters | `""` (empty string, the properties are not nullable) | | `Type.Namespace`, `Type.FullName`, `Type.AssemblyQualifiedName` | `null` | -| `Type.ToString()` | `""`, matching `Type.Name` (the method is not nullable) | +| `Type.ToString()` | `""`, matching `Type.Name` (the method is not nullable). Also for generic type definitions | | `FullName` and `AssemblyQualifiedName` of arrays, pointers, by-refs, nested types and constructed generic types that involve such a type (including as a type argument) | `null`, like for a generic parameter | | `Type.GetType(string)`, `Assembly.GetType(string)`, `GetMethod(string)`, `GetField(string)`, `GetProperty(string)`, `GetEvent(string)`, `GetNestedType(string)`, `GetMember(string)` | Don't find the type or member, since nothing can match an empty name | | Enum members, e.g. `Enum.ToString()`, `Enum.Parse` | Unchanged, the names of enum literals are kept | -| Constructors (`.ctor`, `.cctor`), `Invoke` of delegates, generic virtual methods | Unchanged, the runtime looks these up by name | -| Fields and properties of attribute types, and named arguments of custom attributes | Unchanged | +| Constructors (`.ctor`, `.cctor`), `Invoke` of delegates, generic methods (the runtime looks up instantiations and implementations of generic virtual methods by name), methods, fields and properties of attribute types | Unchanged, the names are kept | +| Named arguments of custom attributes | Unchanged | | Exception messages and `Exception.ToString()` | Use the empty name for the type | | Stack traces | The frames of methods of the assembly don't have names. They show up as an offset in the module, which can be symbolicated with the symbol files, e.g. on a crash report server | +| `MethodInfo.GetBaseDefinition()`, `GetCustomAttributes(inherit: true)` on overridden methods, properties and events, `GetMethods()` and `GetProperties()` on derived types | Members are matched with the ones they override by name, so an override is not associated with the member of the base type. `GetBaseDefinition()` returns the method itself, inherited attributes of overridden members are not found, and both the override and the base member are listed. This also applies to a type from another assembly that overrides a member of a type that strips names | +| Compiler generated attribute types in the assembly, e.g. `NullableAttribute` | The types lose their names, so consumers that identify them by name, e.g. `NullabilityInfoContext`, don't recognize them | Everything else is unchanged. In particular, type identity, `typeof`, `GetType()`, `Activator.CreateInstance`, `MethodInfo.Invoke`, `MakeGenericType`, `MakeGenericMethod`, custom attribute instantiation, and virtual and interface dispatch don't depend on the names. @@ -38,4 +40,4 @@ Limitations: * The names are removed from the reflection metadata only. Other places in the binary that contain names are not affected, e.g. the field names that are part of struct marshalling metadata, the keys of external type maps (`TypeMapping`), embedded resource names, and strings that code explicitly contains (e.g. the string passed to `[UnsafeAccessorType]`, `Type.GetType`, or the arguments of custom attributes). * Code that looks up types or members of such an assembly by name, e.g. `Type.GetType("Namespace.Type, Assembly")`, will not find them, even if the compiler has seen the string. A reference that goes through metadata directly (e.g. a type referenced by a custom attribute argument) is not affected. * Serializers, `EventSource`, `DataContract`, data binding, and anything else that derives behavior from type or member names don't work for these types. -* The setting is not supported for the framework assemblies or for multi-file compilation. +* The setting is not supported for the system module or for multi-file compilation (the compiler reports an error). Assemblies that are not part of the compilation are ignored. diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs index c15f5c706d166d..0fe2df44ebe51d 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs @@ -56,9 +56,14 @@ private bool StripsName(Cts.MethodDesc method) if (owningType.IsDelegate && method.GetName() == "Invoke") return false; - // The runtime matches generic virtual methods (e.g. interface methods and their implementations) - // by name and signature. - if (method.IsVirtual && method.HasInstantiation) + // The runtime hashes and looks up generic method instantiations (and the implementations of + // generic virtual methods) by name. + if (method.HasInstantiation) + return false; + + // Named arguments of custom attributes are resolved by name, and the accessors of the properties + // are used to detect which properties override or hide the ones of the base type. + if (IsAttributeType(owningType)) return false; return true; diff --git a/src/coreclr/tools/aot/ILCompiler/Program.cs b/src/coreclr/tools/aot/ILCompiler/Program.cs index 5f0310da400f1c..6bce9bf25a37ca 100644 --- a/src/coreclr/tools/aot/ILCompiler/Program.cs +++ b/src/coreclr/tools/aot/ILCompiler/Program.cs @@ -424,6 +424,9 @@ public int Run() }; var nameStrippingPolicy = new MetadataNameStrippingPolicy(Get(_command.StrippedNamesAssemblies)); + if (multiFile && Get(_command.StrippedNamesAssemblies).Length > 0) + throw new CommandLineException("Stripping names is not supported in multi-file compilation"); + foreach (string strippedNamesAssembly in Get(_command.StrippedNamesAssemblies)) { // The reflection stack in the system module relies on the names of its own types and members. diff --git a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs index 0f79ecf87a09a8..22338c2e96b588 100644 --- a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs +++ b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs @@ -192,6 +192,11 @@ public static void Run() Assert(Array.IndexOf(types, typeof(Derived)) >= 0); Assert(Array.IndexOf(types, typeof(Widget.Nested)) >= 0); + // Generic definitions reached through the metadata unify with the ones from the type handles + Type holder = types.Single(t => t.IsGenericTypeDefinition && t == typeof(GenericHolder<>)); + Assert(holder == typeof(GenericHolder<>)); + Assert(holder.MakeGenericType(typeof(int)) == typeof(GenericHolder)); + Type marked = types.Single(t => t.IsDefined(typeof(MarkerAttribute))); Assert(marked == Keep(typeof(Marked))); Assert(Activator.CreateInstance(marked).GetType() == marked); @@ -223,7 +228,24 @@ public static void Run() IConverter converter = new IntConverter(); Assert(converter.Convert(1) == 2); Assert(converter.Convert(1).Equals(2)); + + // Generic methods that are not virtual are looked up by name at runtime too + Assert(GenericHelpers.Describe(null) == "helper:ref"); + Assert(GenericHelpers.Describe(default) == "helper:value"); + MethodInfo helper = Keep(typeof(GenericHelpers)).GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly).Single().MakeGenericMethod(typeof(Marked)); + Assert((string)helper.Invoke(null, new object[] { null }) == "helper:ref"); + helper = Keep(typeof(GenericHelpers)).GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly).Single().MakeGenericMethod(typeof(Point)); + Assert((string)helper.Invoke(null, new object[] { default(Point) }) == "helper:value"); + + // GenericCaller> is created by the type loader at runtime, sharing the code of GenericCaller<__Canon> + Assert(((ICaller)new GenericCaller()).Call() == "helper:ref"); + Type caller = Keep(typeof(GenericCaller<>)).MakeGenericType(typeof(GenericHolder<>).MakeGenericType(typeof(Marked))); + Assert(((ICaller)Activator.CreateInstance(caller)).Call() == "helper:ref"); + + Assert(CallMaker() == "made"); } + + private static string CallMaker() where T : IMaker => T.Make(); } private static class TestLookupByName @@ -262,6 +284,13 @@ public static void Run() Assert(data.NamedArguments.Select(a => a.MemberName).OrderBy(n => n, StringComparer.Ordinal).SequenceEqual(new[] { "Label", "Number" })); Assert(new Marked() is not null); + + // The accessors of properties of attribute types are used to match overrides + DerivedMarkerAttribute derived = typeof(MarkedWithOverride).GetCustomAttribute(); + Assert(derived is not null); + Assert(derived.Value == "overridden"); + Assert(typeof(MarkedWithOverride).CustomAttributes.Single().NamedArguments.Single().MemberName == "Value"); + Assert(new MarkedWithOverride() is not null); } } diff --git a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs index 63016afed53815..d4fe9315c8b5a9 100644 --- a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs +++ b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs @@ -79,6 +79,46 @@ public class MarkerAttribute : Attribute [Marker(Label = "label", Number = 42)] public class Marked { } + public abstract class BaseMarkerAttribute : Attribute + { + public virtual string Value { get; set; } + } + + public class DerivedMarkerAttribute : BaseMarkerAttribute + { + public override string Value { get; set; } + } + + [DerivedMarker(Value = "overridden")] + public class MarkedWithOverride { } + + public static class GenericHelpers + { + public static string Describe(T value) => "helper:" + (typeof(T).IsValueType ? "value" : "ref"); + } + + public interface ICaller + { + string Call(); + } + + public class GenericCaller : ICaller + { + public string Call() => GenericHelpers.Describe(default); + } + + public struct Point { public int X; } + + public interface IMaker + { + static abstract string Make(); + } + + public struct Maker : IMaker + { + public static string Make() => "made"; + } + public class UniqueStrippedTypeNameMarker { [MethodImpl(MethodImplOptions.NoInlining)] From cd54240b0c1abab810fe96d2d116a24355d2c512 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Nov 2026 13:44:43 -0800 Subject: [PATCH 06/11] Address final review feedback for stripped names Apply StackTraceHidden before skipping stripped reflection methods, ignore stripped interfaces in GetInterface, make the method name check defensive, and clarify the docs limitations. Extend the smoke test. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Reflection/Runtime/General/ThunkedApis.cs | 5 +++++ .../StackTraceMetadata/StackTraceMetadata.cs | 13 +++++++++-- src/coreclr/nativeaot/docs/optimizing.md | 7 +++--- .../ILCompiler/Metadata/Transform.Names.cs | 3 +-- .../SmokeTests/StrippedNames/StrippedNames.cs | 22 +++++++++++++++++++ .../StrippedNames/StrippedNamesLibrary.cs | 8 +++++++ 6 files changed, 51 insertions(+), 7 deletions(-) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/General/ThunkedApis.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/General/ThunkedApis.cs index 8c9f4cef2c25fc..ac6bc3e9e043d0 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/General/ThunkedApis.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/General/ThunkedApis.cs @@ -211,6 +211,11 @@ internal abstract partial class RuntimeTypeInfo foreach (Type ifc in GetInterfaces()) { string ifcSimpleName = ifc.Name; + + // Interfaces with a name that was stripped by the compiler can't be found by name. + if (ifcSimpleName.Length == 0) + continue; + bool simpleNameMatches = ignoreCase ? (0 == CultureInfo.InvariantCulture.CompareInfo.Compare(simpleName, ifcSimpleName, CompareOptions.IgnoreCase)) // @todo: This could be expressed simpler but the necessary parts of String api not yet ported. : simpleName.Equals(ifcSimpleName); diff --git a/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs b/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs index 4431d0edbf3242..6c47654e3144f5 100644 --- a/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs +++ b/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs @@ -85,8 +85,7 @@ public static unsafe string GetMethodNameFromStartAddressIfAvailable(IntPtr meth if (methodStartAddress != IntPtr.Zero && ReflectionExecution.TryGetMethodMetadataFromAddress(methodStartAddress, isFunctionPointer: false, out MetadataReader reader, out TypeDefinitionHandle typeHandle, - out MethodHandle methodHandle) - && !IsNameStripped(reader, typeHandle, methodHandle)) + out MethodHandle methodHandle)) { if (StackTraceHiddenMetadataPresent()) { @@ -109,6 +108,16 @@ public static unsafe string GetMethodNameFromStartAddressIfAvailable(IntPtr meth } } + // Methods with a name that was stripped by the compiler have no information to report. + if (IsNameStripped(reader, typeHandle, methodHandle)) + { + owningTypeName = null; + genericArgs = null; + methodSignature = null; + hashCodeForLineInfo = 0; + return null; + } + (owningTypeName, genericArgs, string methodName, methodSignature) = MethodNameFormatter.FormatMethodName(reader, typeHandle, methodHandle); hashCodeForLineInfo = (int)VersionResilientHashCode.CombineTwoValuesIntoHash((uint)((Handle)typeHandle).ToIntToken(), (uint)((Handle)methodHandle).ToIntToken()); return methodName; diff --git a/src/coreclr/nativeaot/docs/optimizing.md b/src/coreclr/nativeaot/docs/optimizing.md index c1f2d16cac8cf2..4692e6901dc004 100644 --- a/src/coreclr/nativeaot/docs/optimizing.md +++ b/src/coreclr/nativeaot/docs/optimizing.md @@ -24,12 +24,12 @@ Behavior for types and members of an assembly that strips names: | `Type.Namespace`, `Type.FullName`, `Type.AssemblyQualifiedName` | `null` | | `Type.ToString()` | `""`, matching `Type.Name` (the method is not nullable). Also for generic type definitions | | `FullName` and `AssemblyQualifiedName` of arrays, pointers, by-refs, nested types and constructed generic types that involve such a type (including as a type argument) | `null`, like for a generic parameter | -| `Type.GetType(string)`, `Assembly.GetType(string)`, `GetMethod(string)`, `GetField(string)`, `GetProperty(string)`, `GetEvent(string)`, `GetNestedType(string)`, `GetMember(string)` | Don't find the type or member, since nothing can match an empty name | +| `Type.GetType(string)`, `Assembly.GetType(string)`, `GetMethod(string)`, `GetField(string)`, `GetProperty(string)`, `GetEvent(string)`, `GetNestedType(string)`, `GetInterface(string)`, `GetMember(string)` | Don't find the type or member, since nothing can match an empty name | | Enum members, e.g. `Enum.ToString()`, `Enum.Parse` | Unchanged, the names of enum literals are kept | -| Constructors (`.ctor`, `.cctor`), `Invoke` of delegates, generic methods (the runtime looks up instantiations and implementations of generic virtual methods by name), methods, fields and properties of attribute types | Unchanged, the names are kept | +| Constructors (`.ctor`, `.cctor`), `Invoke` of delegates, generic methods (the runtime looks up instantiations and implementations of generic virtual methods by name), methods and properties of attribute types, and instance fields of attribute types | Unchanged, the names are kept | | Named arguments of custom attributes | Unchanged | | Exception messages and `Exception.ToString()` | Use the empty name for the type | -| Stack traces | The frames of methods of the assembly don't have names. They show up as an offset in the module, which can be symbolicated with the symbol files, e.g. on a crash report server | +| Stack traces | The frames of methods of the assembly don't have names. They show up as an offset in the module, which can be symbolicated with the symbol files, e.g. on a crash report server. `DiagnosticMethodInfo.Create` returns `null` for these methods. Frames of methods from other assemblies that have a type of the assembly in their signature show that type with an empty name | | `MethodInfo.GetBaseDefinition()`, `GetCustomAttributes(inherit: true)` on overridden methods, properties and events, `GetMethods()` and `GetProperties()` on derived types | Members are matched with the ones they override by name, so an override is not associated with the member of the base type. `GetBaseDefinition()` returns the method itself, inherited attributes of overridden members are not found, and both the override and the base member are listed. This also applies to a type from another assembly that overrides a member of a type that strips names | | Compiler generated attribute types in the assembly, e.g. `NullableAttribute` | The types lose their names, so consumers that identify them by name, e.g. `NullabilityInfoContext`, don't recognize them | @@ -40,4 +40,5 @@ Limitations: * The names are removed from the reflection metadata only. Other places in the binary that contain names are not affected, e.g. the field names that are part of struct marshalling metadata, the keys of external type maps (`TypeMapping`), embedded resource names, and strings that code explicitly contains (e.g. the string passed to `[UnsafeAccessorType]`, `Type.GetType`, or the arguments of custom attributes). * Code that looks up types or members of such an assembly by name, e.g. `Type.GetType("Namespace.Type, Assembly")`, will not find them, even if the compiler has seen the string. A reference that goes through metadata directly (e.g. a type referenced by a custom attribute argument) is not affected. * Serializers, `EventSource`, `DataContract`, data binding, and anything else that derives behavior from type or member names don't work for these types. +* Code that assumes a named type has a non-null `FullName` (e.g. `type.FullName!`) can throw for these types. For example, `ILogger` and `ILoggerFactory.CreateLogger(typeof(T))` throw a `NullReferenceException` when `T` is a stripped type, because the category name is derived from `FullName`. The default `Object.ToString()` and `ValueType.ToString()` return an empty string for these types. * The setting is not supported for the system module or for multi-file compilation (the compiler reports an error). Assemblies that are not part of the compilation are ignored. diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs index 0fe2df44ebe51d..5e2fef594a874f 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs @@ -44,8 +44,7 @@ private bool StripsName(Cts.MetadataType type) private bool StripsName(Cts.MethodDesc method) { - Cts.MetadataType owningType = (Cts.MetadataType)method.OwningType; - if (_policy.GeneratesNames(owningType.Module)) + if (method.OwningType is not Cts.MetadataType owningType || _policy.GeneratesNames(owningType.Module)) return false; // The runtime finds constructors by name. diff --git a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs index 22338c2e96b588..3941d09f870ec8 100644 --- a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs +++ b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs @@ -266,6 +266,12 @@ public static void Run() Assert(widget.GetProperty(Join("Co", "unt")) is null); Assert(widget.GetEvent(Join("Chan", "ged")) is null); Assert(widget.GetNestedType(Join("Nes", "ted")) is null); + + // Interfaces are looked up by name without going through the member filters + Type converter = Keep(typeof(IntConverter)); + Assert(converter.GetInterface(string.Empty) is null); + Assert(converter.GetInterface(string.Empty, ignoreCase: true) is null); + Assert(converter.GetInterface(Join("IConv", "erter`1")) is null); } } @@ -312,6 +318,22 @@ public static void Run() // The names are only available in the symbol files Assert(!string.IsNullOrEmpty(stackTrace)); Assert(!stackTrace.Contains(Join("Unique", "Stripped"))); + + // Methods that are reflectable have no stack trace data, but [StackTraceHidden] still applies + Keep(typeof(HiddenFrameHolder)); + string hiddenStackTrace = null; + try + { + HiddenFrameHolder.ThrowFromHiddenFrame(); + } + catch (InvalidOperationException ex) + { + hiddenStackTrace = ex.StackTrace; + } + + Assert(hiddenStackTrace is not null); + Assert(!hiddenStackTrace.Contains(Join("Hidden", "FrameHolder"))); + Assert(!hiddenStackTrace.Contains("+0x")); } } diff --git a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs index d4fe9315c8b5a9..de5a2ee9b7e2a4 100644 --- a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs +++ b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Diagnostics; using System.Runtime.CompilerServices; namespace StrippedNamesLibrary { @@ -124,4 +125,11 @@ public class UniqueStrippedTypeNameMarker [MethodImpl(MethodImplOptions.NoInlining)] public static void UniqueStrippedThrowingMethodMarker() => throw new InvalidOperationException(); } + + public class HiddenFrameHolder + { + [StackTraceHidden] + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowFromHiddenFrame() => throw new InvalidOperationException(); + } } From 642c158b9e43e407951daa058b77512c7c99973e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Nov 2026 14:33:10 -0800 Subject: [PATCH 07/11] Fix member lookup by metadata definition for stripped names GetMemberWithSameMetadataDefinitionAs filtered candidates by name, which can never match a stripped member. Also don't report diagnostic info for delegates that target a method with a stripped name. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../src/System/Delegate.NativeAot.cs | 5 +++++ .../Runtime/TypeInfos/RuntimeTypeInfo.GetMember.cs | 4 +++- src/coreclr/nativeaot/docs/optimizing.md | 2 +- .../nativeaot/SmokeTests/StrippedNames/StrippedNames.cs | 8 ++++++++ 4 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.NativeAot.cs index 6a5852ad6d27f8..2e895e8cdc76c9 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.NativeAot.cs @@ -317,6 +317,11 @@ internal DiagnosticMethodInfo GetDiagnosticMethodInfo() if (isOpenResolver) { MethodInfo mi = ReflectionAugments.GetDelegateMethod(this); + + // Methods and declaring types with a name that was stripped by the compiler have no information to report. + if (mi.Name.Length == 0 || mi.DeclaringType!.Name.Length == 0) + return null; + Type? declaringType = mi.DeclaringType; if (declaringType.IsConstructedGenericType) declaringType = declaringType.GetGenericTypeDefinition(); diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.GetMember.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.GetMember.cs index 40c25ee8e5be17..ba984636ae50f1 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.GetMember.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.GetMember.cs @@ -169,7 +169,9 @@ private MemberInfo GetDeclaredMemberWithSameMetadataDefinitionAs(MemberInfo memb private M QueryMemberWithSameMetadataDefinitionAs(MemberPolicies policies, MemberInfo member) where M : MemberInfo { - QueryResult members = Query(policies, member.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); + // Members with a name that was stripped by the compiler can't be filtered by name, so the metadata definition comparison below does all the work. + BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; + QueryResult members = member.Name.Length == 0 ? Query(policies, flags) : Query(policies, member.Name, flags); foreach (M candidate in members) { if (candidate.HasSameMetadataDefinitionAs(member)) diff --git a/src/coreclr/nativeaot/docs/optimizing.md b/src/coreclr/nativeaot/docs/optimizing.md index 4692e6901dc004..dee9c2c6f52983 100644 --- a/src/coreclr/nativeaot/docs/optimizing.md +++ b/src/coreclr/nativeaot/docs/optimizing.md @@ -29,7 +29,7 @@ Behavior for types and members of an assembly that strips names: | Constructors (`.ctor`, `.cctor`), `Invoke` of delegates, generic methods (the runtime looks up instantiations and implementations of generic virtual methods by name), methods and properties of attribute types, and instance fields of attribute types | Unchanged, the names are kept | | Named arguments of custom attributes | Unchanged | | Exception messages and `Exception.ToString()` | Use the empty name for the type | -| Stack traces | The frames of methods of the assembly don't have names. They show up as an offset in the module, which can be symbolicated with the symbol files, e.g. on a crash report server. `DiagnosticMethodInfo.Create` returns `null` for these methods. Frames of methods from other assemblies that have a type of the assembly in their signature show that type with an empty name | +| Stack traces | The frames of methods of the assembly don't have names. They show up as an offset in the module, which can be symbolicated with the symbol files, e.g. on a crash report server. `DiagnosticMethodInfo.Create` returns `null` for methods of the assembly (with the exception of the `Invoke` method of a stripped delegate type, which has no declaring type name). Frames of methods from other assemblies that have a type of the assembly in their signature show that type with an empty name | | `MethodInfo.GetBaseDefinition()`, `GetCustomAttributes(inherit: true)` on overridden methods, properties and events, `GetMethods()` and `GetProperties()` on derived types | Members are matched with the ones they override by name, so an override is not associated with the member of the base type. `GetBaseDefinition()` returns the method itself, inherited attributes of overridden members are not found, and both the override and the base member are listed. This also applies to a type from another assembly that overrides a member of a type that strips names | | Compiler generated attribute types in the assembly, e.g. `NullableAttribute` | The types lose their names, so consumers that identify them by name, e.g. `NullabilityInfoContext`, don't recognize them | diff --git a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs index 3941d09f870ec8..d3d7710293c19f 100644 --- a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs +++ b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs @@ -124,6 +124,13 @@ public static void Run() Assert(events.Length == 1); Assert(events[0].Name == string.Empty); + // Members are matched by their metadata definition, which doesn't depend on their name + FieldInfo definitionField = Keep(typeof(GenericHolder<>)).GetFields(flags | BindingFlags.Static).Single(); + Type constructed = Keep(typeof(GenericHolder)); + MemberInfo projected = constructed.GetMemberWithSameMetadataDefinitionAs(definitionField); + Assert(projected is FieldInfo { Name: "" } projectedField && projectedField.DeclaringType == constructed); + Assert(widget.GetMemberWithSameMetadataDefinitionAs(fields[0]) == fields[0]); + Assert(widget.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic).Length == 1); } } @@ -317,6 +324,7 @@ public static void Run() // The names are only available in the symbol files Assert(!string.IsNullOrEmpty(stackTrace)); + Assert(stackTrace.Contains("+0x")); Assert(!stackTrace.Contains(Join("Unique", "Stripped"))); // Methods that are reflectable have no stack trace data, but [StackTraceHidden] still applies From 0d3c47fd16c796322daa19b251a8d10645ab56ae Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Nov 2026 18:37:10 -0800 Subject: [PATCH 08/11] Spread stripped types in the scope type hashtable and fix includes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Metadata/NativeFormat/MetadataTypeHashingAlgorithms.cs | 2 ++ .../Metadata/NativeFormat/Writer/NativeMetadataWriter.cs | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MetadataTypeHashingAlgorithms.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MetadataTypeHashingAlgorithms.cs index 1938998a4bbac5..13ad2adfbe61de 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MetadataTypeHashingAlgorithms.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MetadataTypeHashingAlgorithms.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System; + namespace Internal.Metadata.NativeFormat { internal static class MetadataTypeHashingAlgorithms diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/Internal/Metadata/NativeFormat/Writer/NativeMetadataWriter.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/Internal/Metadata/NativeFormat/Writer/NativeMetadataWriter.cs index 3f8246d564e8a8..5afcf507483a6f 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/Internal/Metadata/NativeFormat/Writer/NativeMetadataWriter.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/Internal/Metadata/NativeFormat/Writer/NativeMetadataWriter.cs @@ -671,6 +671,11 @@ public partial class TypeDefinition { internal int GetLookupHashCode() { + // The name of the type was stripped, so it can't be looked up by name. Spread such types out + // instead of piling all of them into a single bucket of the hashtable. + if (Name.Value.Length == 0) + return VersionResilientHashCode.MetadataHandleHashCode(Discriminator); + Debug.Assert(NamespaceOrEnclosingType is NamespaceDefinition); NamespaceDefinition namespaceDefinition = (NamespaceDefinition)NamespaceOrEnclosingType; return VersionResilientHashCode.NameHashCode( From a50915e624e7008fd3e217ee6cad8e12cb0b17cb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Nov 2026 22:23:10 -0800 Subject: [PATCH 09/11] Strip only the names of types, not of members The compiler only emits metadata for members that are reflection targets, so their names are kept and lookups by name keep working. In the Store, none of the members of the stripped types were emitted other than attribute constructors, so this doesn't change the savings, and it removes the need to special case overrides, generic methods, attribute types and enum literals, and the method name and signature handling in the runtime. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../MethodNameAndSignature.cs | 17 +-- .../src/System/Delegate.NativeAot.cs | 4 +- .../BindingFlagSupport/EventPolicies.cs | 3 +- .../BindingFlagSupport/MemberPolicies.cs | 3 +- .../Runtime/BindingFlagSupport/NameFilter.cs | 2 +- .../Runtime/BindingFlagSupport/Shared.cs | 6 - .../TypeInfos/RuntimeTypeInfo.GetMember.cs | 2 +- .../StackTraceMetadata/StackTraceMetadata.cs | 15 +-- src/coreclr/nativeaot/docs/optimizing.md | 27 ++-- .../NativeFormat/Generator/SchemaDef.cs | 5 - .../Compiler/MetadataManager.cs | 2 +- .../Compiler/MetadataNameStrippingPolicy.cs | 4 +- .../ILCompiler/Metadata/IMetadataPolicy.cs | 8 +- .../ILCompiler/Metadata/Transform.Event.cs | 7 +- .../ILCompiler/Metadata/Transform.Field.cs | 10 +- .../ILCompiler/Metadata/Transform.Method.cs | 12 +- .../ILCompiler/Metadata/Transform.Names.cs | 110 ++------------- .../Metadata/Transform.Parameter.cs | 2 +- .../ILCompiler/Metadata/Transform.Property.cs | 7 +- .../ILCompiler/Metadata/Transform.Type.cs | 4 +- .../Writer/NativeFormatWriterGen.cs | 20 --- .../aot/ILCompiler/ILCompilerRootCommand.cs | 2 +- src/coreclr/tools/aot/ILCompiler/Program.cs | 2 +- .../SmokeTests/StrippedNames/StrippedNames.cs | 126 +++++++++++------- .../StrippedNames/StrippedNamesLibrary.cs | 2 +- 25 files changed, 132 insertions(+), 270 deletions(-) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/MethodNameAndSignature.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/MethodNameAndSignature.cs index 1f2a0581b4190b..1f81afd1e620ac 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/MethodNameAndSignature.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/MethodNameAndSignature.cs @@ -48,22 +48,11 @@ public override bool Equals(object? compare) // (Same assumption in GetHashCode below!) Debug.Assert(Reader == other.Reader); - // Methods with a name that was stripped by the compiler can only be identified by their handle, - // since the signature alone is not enough to tell them apart. - if (Handle.Equals(other.Handle)) - return true; - Method thisMethod = Reader.GetMethod(Handle); Method otherMethod = other.Reader.GetMethod(other.Handle); return thisMethod.Signature.Equals(otherMethod.Signature) - && thisMethod.Name.Equals(otherMethod.Name) - && !HasStrippedName(thisMethod); - } - - private bool HasStrippedName(Method method) - { - return Reader.ReadStringAsBytes(method.Name).IsEmpty; + && thisMethod.Name.Equals(otherMethod.Name); } public bool ReturnTypeHasInstantiation @@ -83,10 +72,6 @@ public override int GetHashCode() { Method method = Reader.GetMethod(Handle); - // Methods with a name that was stripped by the compiler are only identified by their handle - if (HasStrippedName(method)) - return Handle.GetHashCode(); - // Assumes we only have one metadata blob return method.Signature.GetHashCode() ^ method.Name.GetHashCode(); } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.NativeAot.cs index 2e895e8cdc76c9..44e08307663d4b 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.NativeAot.cs @@ -318,8 +318,8 @@ internal DiagnosticMethodInfo GetDiagnosticMethodInfo() { MethodInfo mi = ReflectionAugments.GetDelegateMethod(this); - // Methods and declaring types with a name that was stripped by the compiler have no information to report. - if (mi.Name.Length == 0 || mi.DeclaringType!.Name.Length == 0) + // Declaring types with a name that was stripped by the compiler have no information to report. + if (mi.DeclaringType!.Name.Length == 0) return null; Type? declaringType = mi.DeclaringType; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs index f4b751f0938d05..e7d8dbe776cfda 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs @@ -53,8 +53,7 @@ public sealed override bool IsSuppressedByMoreDerivedMember(EventInfo member, Ev { for (int i = startIndex; i < endIndex; i++) { - // Members with a name that was stripped by the compiler never hide other members. - if (member.Name.Length != 0 && priorMembers[i].Name == member.Name) + if (priorMembers[i].Name == member.Name) return true; } return false; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/MemberPolicies.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/MemberPolicies.cs index 3560d1873f29db..18e4390d44a3e9 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/MemberPolicies.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/MemberPolicies.cs @@ -72,8 +72,7 @@ public virtual BindingFlags ModifyBindingFlags(BindingFlags bindingFlags) // protected static bool AreNamesAndSignaturesEqual(MethodInfo method1, MethodInfo method2) { - // Methods with a name that was stripped by the compiler can't be matched by name. - if (method1.Name.Length == 0 || method1.Name != method2.Name) + if (method1.Name != method2.Name) return false; ReadOnlySpan p1 = method1.GetParametersAsSpan(); diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.cs index 6c1acb5c4cb2ea..6bb2f7bae18528 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.cs @@ -15,7 +15,7 @@ protected NameFilter(string expectedName) public abstract bool Matches(string name); protected string ExpectedName { get; } - // Members with a name that was stripped by the compiler have an empty name. They can't be found by name. + // Nested types with a name that was stripped by the compiler have an empty name. They can't be found by name. protected bool CanMatch => ExpectedName.Length != 0; } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/Shared.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/Shared.cs index e75053323eff75..095fdb7bbe083b 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/Shared.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/Shared.cs @@ -157,12 +157,6 @@ public static bool QualifiesBasedOnParameterCount(this MethodBase methodBase, Bi } string name = member.Name; - if (name.Length == 0) - { - // The name was stripped by the compiler, so the base class members can't be matched by name. - return null; - } - Type type = member.DeclaringType!; for (; ; ) { diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.GetMember.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.GetMember.cs index ba984636ae50f1..19d6a577085a58 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.GetMember.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.GetMember.cs @@ -169,7 +169,7 @@ private MemberInfo GetDeclaredMemberWithSameMetadataDefinitionAs(MemberInfo memb private M QueryMemberWithSameMetadataDefinitionAs(MemberPolicies policies, MemberInfo member) where M : MemberInfo { - // Members with a name that was stripped by the compiler can't be filtered by name, so the metadata definition comparison below does all the work. + // Nested types with a name that was stripped by the compiler can't be filtered by name, so the metadata definition comparison below does all the work. BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; QueryResult members = member.Name.Length == 0 ? Query(policies, flags) : Query(policies, member.Name, flags); foreach (M candidate in members) diff --git a/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs b/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs index 6c47654e3144f5..6920d9c0f0b942 100644 --- a/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs +++ b/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/StackTraceMetadata.cs @@ -108,8 +108,8 @@ public static unsafe string GetMethodNameFromStartAddressIfAvailable(IntPtr meth } } - // Methods with a name that was stripped by the compiler have no information to report. - if (IsNameStripped(reader, typeHandle, methodHandle)) + // Methods of types with a name that was stripped by the compiler have no information to report. + if (IsTypeNameStripped(reader, typeHandle)) { owningTypeName = null; genericArgs = null; @@ -214,7 +214,7 @@ private static unsafe (string, int) GetLineNumberInfo(IntPtr methodStartAddress, out MetadataReader reader, out TypeDefinitionHandle typeHandle, out MethodHandle methodHandle) - && !IsNameStripped(reader, typeHandle, methodHandle)) + && !IsTypeNameStripped(reader, typeHandle)) { return CreateDiagnosticMethodInfo(reader, typeHandle, reader.GetMethod(methodHandle).Name); } @@ -235,7 +235,7 @@ private static DiagnosticMethodInfo GetDiagnosticMethodInfoFromFunctionPointerIf out MetadataReader reader, out TypeDefinitionHandle typeHandle, out MethodHandle methodHandle) - && !IsNameStripped(reader, typeHandle, methodHandle)) + && !IsTypeNameStripped(reader, typeHandle)) { return CreateDiagnosticMethodInfo(reader, typeHandle, reader.GetMethod(methodHandle).Name); } @@ -258,11 +258,10 @@ private static DiagnosticMethodInfo CreateDiagnosticMethodInfo(MetadataReader re FormatAssemblyName(reader, owningType)); } - private static bool IsNameStripped(MetadataReader reader, TypeDefinitionHandle typeHandle, MethodHandle methodHandle) + private static bool IsTypeNameStripped(MetadataReader reader, TypeDefinitionHandle typeHandle) { - // Constructors and a few other methods keep their names, but are still declared on a type that doesn't have one. - return reader.ReadStringAsBytes(reader.GetMethod(methodHandle).Name).IsEmpty - || reader.ReadStringAsBytes(reader.GetTypeDefinition(typeHandle).Name).IsEmpty; + // The methods of a type that has its name stripped by the compiler have no information to report. + return reader.ReadStringAsBytes(reader.GetTypeDefinition(typeHandle).Name).IsEmpty; } private static string FormatAssemblyName(MetadataReader reader, Handle handle) diff --git a/src/coreclr/nativeaot/docs/optimizing.md b/src/coreclr/nativeaot/docs/optimizing.md index dee9c2c6f52983..deb41733c487ef 100644 --- a/src/coreclr/nativeaot/docs/optimizing.md +++ b/src/coreclr/nativeaot/docs/optimizing.md @@ -10,27 +10,28 @@ The rest of the document talks about options that exist, but their names and pur ## Options related to reflection metadata size -### Stripping the names of types and members from specific assemblies +### Stripping the names of types from specific assemblies -* ``: Strips the names of all types and members of the assembly with the given simple name from the reflection metadata in the final binary. The item can be specified multiple times. It is passed to the compiler as `--stripnames:MyAssembly`. This is meant for assemblies that contain a large amount of generated code, such as interop assemblies with long generated type names, where the names are never used at runtime. The default behavior of the compiler is not affected unless the item is specified. +* ``: Strips the names of all types of the assembly with the given simple name from the reflection metadata in the final binary. The item can be specified multiple times. It is passed to the compiler as `--stripnames:MyAssembly`. This is meant for assemblies that contain a large amount of generated code, such as interop assemblies with long generated type names, where the names are never used at runtime. The default behavior of the compiler is not affected unless the item is specified. -The option is opt-in per assembly, because it changes the observable behavior of reflection for the types and members of that assembly. Names are replaced with the empty string in the metadata, so the cost of a name is no longer paid in the binary. Names remain available in the compiler map file (``), in the mstat file, and in the symbol files (`.pdb`, `.dwp`, `.dSYM`) because these are produced from the compiler's own type system and not from the reflection metadata. Note that on platforms where the debug information is part of the image, the names will be there as well. +The option is opt-in per assembly, because it changes the observable behavior of reflection for the types of that assembly. Names are replaced with the empty string in the metadata, so the cost of a name is no longer paid in the binary. Names remain available in the compiler map file (``), in the mstat file, and in the symbol files (`.pdb`, `.dwp`, `.dSYM`) because these are produced from the compiler's own type system and not from the reflection metadata. Note that on platforms where the debug information is part of the image, the names will be there as well. -Behavior for types and members of an assembly that strips names: +Only the names of types are stripped. The compiler only emits metadata for a member if it is a reflection target (e.g. it is kept by a `DynamicallyAccessedMembers` annotation, a `DynamicDependency` attribute or a root descriptor), so the names of members are kept to keep lookups by name working. + +Behavior for types of an assembly that strips names: | API | Result | | --- | --- | -| `Type.Name`, `MemberInfo.Name`, `ParameterInfo.Name`, names of generic parameters | `""` (empty string, the properties are not nullable) | +| `Type.Name` | `""` (empty string, the property is not nullable) | | `Type.Namespace`, `Type.FullName`, `Type.AssemblyQualifiedName` | `null` | | `Type.ToString()` | `""`, matching `Type.Name` (the method is not nullable). Also for generic type definitions | | `FullName` and `AssemblyQualifiedName` of arrays, pointers, by-refs, nested types and constructed generic types that involve such a type (including as a type argument) | `null`, like for a generic parameter | -| `Type.GetType(string)`, `Assembly.GetType(string)`, `GetMethod(string)`, `GetField(string)`, `GetProperty(string)`, `GetEvent(string)`, `GetNestedType(string)`, `GetInterface(string)`, `GetMember(string)` | Don't find the type or member, since nothing can match an empty name | -| Enum members, e.g. `Enum.ToString()`, `Enum.Parse` | Unchanged, the names of enum literals are kept | -| Constructors (`.ctor`, `.cctor`), `Invoke` of delegates, generic methods (the runtime looks up instantiations and implementations of generic virtual methods by name), methods and properties of attribute types, and instance fields of attribute types | Unchanged, the names are kept | -| Named arguments of custom attributes | Unchanged | +| `Type.GetType(string)`, `Assembly.GetType(string)`, `GetNestedType(string)`, `GetInterface(string)`, `GetMember(string)` for nested types | Don't find the type, since nothing can match an empty name | +| Names of members (methods, fields, properties, events, parameters and generic parameters), `GetMethod(string)` and the other lookups of members by name | Unchanged, including for members of a stripped type | +| Named arguments of custom attributes, enum members, overrides and generic virtual methods | Unchanged | +| `MethodInfo.ToString()` and the like | The types in the signature are printed with an empty name, so `Void Foo()` can stand for `Foo(Widget)`. The output of `ToString()` can't be used as a key | | Exception messages and `Exception.ToString()` | Use the empty name for the type | -| Stack traces | The frames of methods of the assembly don't have names. They show up as an offset in the module, which can be symbolicated with the symbol files, e.g. on a crash report server. `DiagnosticMethodInfo.Create` returns `null` for methods of the assembly (with the exception of the `Invoke` method of a stripped delegate type, which has no declaring type name). Frames of methods from other assemblies that have a type of the assembly in their signature show that type with an empty name | -| `MethodInfo.GetBaseDefinition()`, `GetCustomAttributes(inherit: true)` on overridden methods, properties and events, `GetMethods()` and `GetProperties()` on derived types | Members are matched with the ones they override by name, so an override is not associated with the member of the base type. `GetBaseDefinition()` returns the method itself, inherited attributes of overridden members are not found, and both the override and the base member are listed. This also applies to a type from another assembly that overrides a member of a type that strips names | +| Stack traces | The frames of methods of the assembly don't have names. They show up as an offset in the module, which can be symbolicated with the symbol files, e.g. on a crash report server. This also applies to methods that are reflectable. `DiagnosticMethodInfo.Create` returns `null` for methods of the assembly. Frames of methods from other assemblies that have a type of the assembly in their signature show that type with an empty name | | Compiler generated attribute types in the assembly, e.g. `NullableAttribute` | The types lose their names, so consumers that identify them by name, e.g. `NullabilityInfoContext`, don't recognize them | Everything else is unchanged. In particular, type identity, `typeof`, `GetType()`, `Activator.CreateInstance`, `MethodInfo.Invoke`, `MakeGenericType`, `MakeGenericMethod`, custom attribute instantiation, and virtual and interface dispatch don't depend on the names. @@ -38,7 +39,7 @@ Everything else is unchanged. In particular, type identity, `typeof`, `GetType() Limitations: * The names are removed from the reflection metadata only. Other places in the binary that contain names are not affected, e.g. the field names that are part of struct marshalling metadata, the keys of external type maps (`TypeMapping`), embedded resource names, and strings that code explicitly contains (e.g. the string passed to `[UnsafeAccessorType]`, `Type.GetType`, or the arguments of custom attributes). -* Code that looks up types or members of such an assembly by name, e.g. `Type.GetType("Namespace.Type, Assembly")`, will not find them, even if the compiler has seen the string. A reference that goes through metadata directly (e.g. a type referenced by a custom attribute argument) is not affected. -* Serializers, `EventSource`, `DataContract`, data binding, and anything else that derives behavior from type or member names don't work for these types. +* Code that looks up types of such an assembly by name, e.g. `Type.GetType("Namespace.Type, Assembly")`, will not find them, even if the compiler has seen the string. A reference that goes through metadata directly (e.g. a type referenced by a custom attribute argument) is not affected. +* Serializers, `EventSource`, `DataContract`, data binding, and anything else that derives behavior from type names don't work for these types. * Code that assumes a named type has a non-null `FullName` (e.g. `type.FullName!`) can throw for these types. For example, `ILogger` and `ILoggerFactory.CreateLogger(typeof(T))` throw a `NullReferenceException` when `T` is a stripped type, because the category name is derived from `FullName`. The default `Object.ToString()` and `ValueType.ToString()` return an empty string for these types. * The setting is not supported for the system module or for multi-file compilation (the compiler reports an error). Assemblies that are not part of the compilation are ignored. diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs index 518be8e0dad18e..78493abef90e1e 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs @@ -463,7 +463,6 @@ static SchemaDef() ), new RecordDef( name: "Method", - flags: RecordDefFlags.Discriminated, members: new MemberDef[] { new MemberDef("Flags", "MethodAttributes"), new MemberDef("ImplFlags", "MethodImplAttributes"), @@ -491,7 +490,6 @@ static SchemaDef() ), new RecordDef( name: "MemberReference", - flags: RecordDefFlags.Discriminated, members: new MemberDef[] { new MemberDef("Parent", TypeDefOrRefOrSpec, MemberDefFlags.RecordRef), new MemberDef("Name", "ConstantStringValue", MemberDefFlags.RecordRef | MemberDefFlags.Child), @@ -501,7 +499,6 @@ static SchemaDef() ), new RecordDef( name: "Field", - flags: RecordDefFlags.Discriminated, members: new MemberDef[] { new MemberDef("Flags", "FieldAttributes"), new MemberDef("Name", "ConstantStringValue", MemberDefFlags.RecordRef | MemberDefFlags.Child), @@ -520,7 +517,6 @@ static SchemaDef() ), new RecordDef( name: "Property", - flags: RecordDefFlags.Discriminated, members: new MemberDef[] { new MemberDef("Flags", "PropertyAttributes"), new MemberDef("Name", "ConstantStringValue", MemberDefFlags.RecordRef | MemberDefFlags.Child), @@ -532,7 +528,6 @@ static SchemaDef() ), new RecordDef( name: "Event", - flags: RecordDefFlags.Discriminated, members: new MemberDef[] { new MemberDef("Flags", "EventAttributes"), new MemberDef("Name", "ConstantStringValue", MemberDefFlags.RecordRef | MemberDefFlags.Child), diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataManager.cs index a24fec28a9aa10..33aff63fe38501 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataManager.cs @@ -116,7 +116,7 @@ public MetadataManager(CompilerTypeSystemContext typeSystemContext, MetadataBloc public bool IsDataDehydrated => (_options & MetadataManagerOptions.DehydrateData) != 0; /// - /// Returns true if the names of the types and members defined in + /// Returns true if the names of the types defined in /// are emitted into the metadata. /// internal bool GeneratesNames(ModuleDesc module) => !_nameStrippingPolicy.IsStripped(module); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataNameStrippingPolicy.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataNameStrippingPolicy.cs index 459052b7b31b9b..172bcadbb711c2 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataNameStrippingPolicy.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataNameStrippingPolicy.cs @@ -9,7 +9,7 @@ namespace ILCompiler { /// - /// Represents a policy that decides which assemblies have the names of their types and members stripped + /// Represents a policy that decides which assemblies have the names of their types stripped /// from the reflection metadata and the stack trace data emitted into the executable. /// public sealed class MetadataNameStrippingPolicy @@ -28,7 +28,7 @@ public MetadataNameStrippingPolicy(IEnumerable strippedAssemblies) } /// - /// Returns true if the names of the types and members defined in are stripped. + /// Returns true if the names of the types defined in are stripped. /// public bool IsStripped(ModuleDesc module) { diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/IMetadataPolicy.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/IMetadataPolicy.cs index 193ff8c91711e9..97470631fcd480 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/IMetadataPolicy.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/IMetadataPolicy.cs @@ -69,11 +69,9 @@ public interface IMetadataPolicy bool IsBlocked(Cts.MethodDesc methodDef); /// - /// Returns true if the names of the types and members defined in the module should be emitted - /// into the metadata. If false, the names of the entities defined in the module are replaced with an - /// empty string, and the types are placed in the root namespace. Names that the runtime needs - /// for correctness (e.g. the names of constructors and enum members) and the names of type forwarders - /// are always emitted. + /// Returns true if the names of the types defined in the module should be emitted into the metadata. + /// If false, the names of the types defined in the module are replaced with an empty string, and the + /// types are placed in the root namespace. The names of members and type forwarders are always emitted. /// bool GeneratesNames(Cts.ModuleDesc module); } diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Event.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Event.cs index 7d1cc1a14f8d0d..17f507dbb1fcd6 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Event.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Event.cs @@ -12,9 +12,8 @@ namespace ILCompiler.Metadata { internal partial class Transform { - private Event HandleEvent(Cts.Ecma.EcmaType owningType, Ecma.EventDefinitionHandle eventHandle) + private Event HandleEvent(Cts.Ecma.EcmaModule module, Ecma.EventDefinitionHandle eventHandle) { - Cts.Ecma.EcmaModule module = owningType.Module; Ecma.MetadataReader reader = module.MetadataReader; Ecma.EventDefinition eventDef = reader.GetEventDefinition(eventHandle); @@ -32,11 +31,9 @@ private Event HandleEvent(Cts.Ecma.EcmaType owningType, Ecma.EventDefinitionHand if (!adderHasMetadata && !raiserHasMetadata && !removerHasMetadata) return null; - bool stripName = !_policy.GeneratesNames(module); Event result = new Event { - Name = HandleName(reader.GetString(eventDef.Name), stripName), - Discriminator = stripName ? GetDiscriminator(owningType, eventHandle) : 0, + Name = HandleString(reader.GetString(eventDef.Name)), Flags = eventDef.Attributes, Type = HandleType(module.GetType(eventDef.Type)), }; diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Field.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Field.cs index 80c6466f7eaca9..351e556aa893e7 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Field.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Field.cs @@ -46,10 +46,7 @@ private Field HandleFieldDefinition(Cts.FieldDesc field) private void InitializeFieldDefinition(Cts.FieldDesc entity, Field record) { - bool stripName = StripsName(entity); - record.Name = HandleName(entity.GetName(), stripName); - if (stripName) - record.Discriminator = GetDiscriminator(entity); + record.Name = HandleString(entity.GetName()); record.Flags = GetFieldAttributes(entity); var ecmaField = entity as Cts.Ecma.EcmaField; @@ -102,10 +99,7 @@ private MemberReference HandleFieldReference(Cts.FieldDesc field) private void InitializeFieldReference(Cts.FieldDesc entity, MemberReference record) { - bool stripName = StripsName(entity.GetTypicalFieldDefinition()); - record.Name = HandleName(entity.GetName(), stripName); - if (stripName) - record.Discriminator = GetDiscriminator(entity); + record.Name = HandleString(entity.GetName()); record.Parent = HandleType(entity.OwningType); record.Signature = new FieldSignature { diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Method.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Method.cs index dac3c885123dcb..92f30cb3e9cdd2 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Method.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Method.cs @@ -60,10 +60,7 @@ private Method HandleMethodDefinition(Cts.MethodDesc method) private void InitializeMethodDefinition(Cts.MethodDesc entity, Method record) { - bool stripName = StripsName(entity); - record.Name = HandleName(entity.GetName(), stripName); - if (stripName) - record.Discriminator = GetDiscriminator(entity); + record.Name = HandleString(entity.GetName()); if (entity.HasInstantiation) { @@ -94,7 +91,7 @@ private void InitializeMethodDefinition(Cts.MethodDesc entity, Method record) Parameter paramRecord = new Parameter { Flags = param.Attributes, - Name = HandleName(reader.GetString(param.Name), !_policy.GeneratesNames(ecmaEntity.Module)), + Name = HandleString(reader.GetString(param.Name)), Sequence = checked((ushort)param.SequenceNumber) }; @@ -138,10 +135,7 @@ private MemberReference HandleMethodReference(Cts.MethodDesc method) private void InitializeMethodReference(Cts.MethodDesc entity, MemberReference record) { - bool stripName = StripsName(entity.GetTypicalMethodDefinition()); - record.Name = HandleName(entity.GetName(), stripName); - if (stripName) - record.Discriminator = GetDiscriminator(entity); + record.Name = HandleString(entity.GetName()); record.Parent = HandleType(entity.OwningType); record.Signature = HandleMethodSignature(entity.GetTypicalMethodDefinition().Signature); } diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs index 5e2fef594a874f..0c4c1e58c17374 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Names.cs @@ -5,21 +5,21 @@ using Cts = Internal.TypeSystem; using Debug = System.Diagnostics.Debug; -using Ecma = System.Reflection.Metadata; using MetadataTokens = System.Reflection.Metadata.Ecma335.MetadataTokens; namespace ILCompiler.Metadata { - // Support for stripping the names of types and members from the metadata (see IMetadataPolicy.GeneratesNames). + // Support for stripping the names of types from the metadata (see IMetadataPolicy.GeneratesNames). // // Names that are stripped are replaced with the empty string, which the metadata reader users treat as - // "name not available" (ECMA-335 doesn't allow empty names for types, methods, fields, properties and events). + // "name not available" (ECMA-335 doesn't allow empty names for types). // Records that only differ by their name would no longer be distinguishable by the writer, so the records get - // a discriminator that is derived from the metadata token of the entity. + // a discriminator that is derived from the metadata token of the type. + // + // Members are not affected: a member only gets metadata if the compiler found that it is a reflection target, + // so its name is kept to keep lookups by name working. internal partial class Transform { - private Cts.MetadataType _attributeType; - private ConstantStringValue HandleName(string name, bool stripName) => HandleString(stripName ? string.Empty : name); @@ -30,109 +30,15 @@ private NamespaceDefinition HandleNamespaceDefinition(Cts.MetadataType type) private NamespaceReference HandleNamespaceReference(Cts.MetadataType type) => HandleNamespaceReference(type.Module, StripsName(type) ? string.Empty : type.GetNamespace()); - private bool IsAttributeType(Cts.TypeDesc type) - { - _attributeType ??= type.Context.SystemModule.GetType("System"u8, "Attribute"u8); - return Cts.CastingHelper.CanCastTo(type, _attributeType); - } - private bool StripsName(Cts.MetadataType type) { Debug.Assert(type.IsTypeDefinition); return !_policy.GeneratesNames(type.Module); } - private bool StripsName(Cts.MethodDesc method) - { - if (method.OwningType is not Cts.MetadataType owningType || _policy.GeneratesNames(owningType.Module)) - return false; - - // The runtime finds constructors by name. - if (method.IsConstructor || method.IsStaticConstructor) - return false; - - // The runtime finds the Invoke method of delegates by name. - if (owningType.IsDelegate && method.GetName() == "Invoke") - return false; - - // The runtime hashes and looks up generic method instantiations (and the implementations of - // generic virtual methods) by name. - if (method.HasInstantiation) - return false; - - // Named arguments of custom attributes are resolved by name, and the accessors of the properties - // are used to detect which properties override or hide the ones of the base type. - if (IsAttributeType(owningType)) - return false; - - return true; - } - - private bool StripsName(Cts.FieldDesc field) - { - Cts.MetadataType owningType = (Cts.MetadataType)field.OwningType; - if (_policy.GeneratesNames(owningType.Module)) - return false; - - // Enum.ToString, Enum.Parse and friends need the names of the enum members. - if (field.IsLiteral && owningType.IsEnum) - return false; - - // Named arguments of custom attributes are resolved by name. - if (!field.IsStatic && IsAttributeType(owningType)) - return false; - - return true; - } - - private bool StripsPropertyName(Cts.Ecma.EcmaType owningType) - { - // Named arguments of custom attributes are resolved by name. - return !_policy.GeneratesNames(owningType.Module) && !IsAttributeType(owningType); - } - - // The discriminators below only need to be unique within the entities that can be compared - // by the writer, and be stable across compilations. Types are distinguished by their row number in - // the module, and members by their position in the member list of the declaring type. This keeps members - // with the same shape in different types poolable. - + // The discriminator only needs to be unique within the types that can be compared by the writer, and be + // stable across compilations, so types are distinguished by their row number in the module. private static int GetDiscriminator(Cts.MetadataType type) => type is Cts.Ecma.EcmaType ecmaType ? MetadataTokens.GetRowNumber(ecmaType.Handle) : 0; - - private static int GetDiscriminator(Cts.MethodDesc method) - { - Cts.Ecma.EcmaMethod ecmaMethod = (Cts.Ecma.EcmaMethod)method.GetTypicalMethodDefinition(); - Cts.Ecma.EcmaType owningType = (Cts.Ecma.EcmaType)ecmaMethod.OwningType; - Ecma.MethodDefinitionHandleCollection.Enumerator methods - = owningType.MetadataReader.GetTypeDefinition(owningType.Handle).GetMethods().GetEnumerator(); - methods.MoveNext(); - return MetadataTokens.GetRowNumber(ecmaMethod.Handle) - MetadataTokens.GetRowNumber(methods.Current) + 1; - } - - private static int GetDiscriminator(Cts.FieldDesc field) - { - Cts.Ecma.EcmaField ecmaField = (Cts.Ecma.EcmaField)field.GetTypicalFieldDefinition(); - Cts.Ecma.EcmaType owningType = (Cts.Ecma.EcmaType)ecmaField.OwningType; - Ecma.FieldDefinitionHandleCollection.Enumerator fields - = owningType.MetadataReader.GetTypeDefinition(owningType.Handle).GetFields().GetEnumerator(); - fields.MoveNext(); - return MetadataTokens.GetRowNumber(ecmaField.Handle) - MetadataTokens.GetRowNumber(fields.Current) + 1; - } - - private static int GetDiscriminator(Cts.Ecma.EcmaType owningType, Ecma.PropertyDefinitionHandle property) - { - Ecma.PropertyDefinitionHandleCollection.Enumerator properties - = owningType.MetadataReader.GetTypeDefinition(owningType.Handle).GetProperties().GetEnumerator(); - properties.MoveNext(); - return MetadataTokens.GetRowNumber(property) - MetadataTokens.GetRowNumber(properties.Current) + 1; - } - - private static int GetDiscriminator(Cts.Ecma.EcmaType owningType, Ecma.EventDefinitionHandle eventHandle) - { - Ecma.EventDefinitionHandleCollection.Enumerator events - = owningType.MetadataReader.GetTypeDefinition(owningType.Handle).GetEvents().GetEnumerator(); - events.MoveNext(); - return MetadataTokens.GetRowNumber(eventHandle) - MetadataTokens.GetRowNumber(events.Current) + 1; - } } } diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Parameter.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Parameter.cs index c52dbb52b30a69..97f832d8904833 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Parameter.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Parameter.cs @@ -34,7 +34,7 @@ private GenericParameter HandleGenericParameter(Cts.GenericParameterDesc genPara Ecma.GenericParameter genParamDef = reader.GetGenericParameter(ecmaGenParam.Handle); result.Flags = genParamDef.Attributes; - result.Name = HandleName(reader.GetString(genParamDef.Name), !_policy.GeneratesNames(ecmaGenParam.Module)); + result.Name = HandleString(reader.GetString(genParamDef.Name)); Ecma.CustomAttributeHandleCollection customAttributes = genParamDef.GetCustomAttributes(); if (customAttributes.Count > 0) diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Property.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Property.cs index f98dac95747a60..786d694be1dd6a 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Property.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Property.cs @@ -13,9 +13,8 @@ namespace ILCompiler.Metadata { internal partial class Transform { - private Property HandleProperty(Cts.Ecma.EcmaType owningType, Ecma.PropertyDefinitionHandle property) + private Property HandleProperty(Cts.Ecma.EcmaModule module, Ecma.PropertyDefinitionHandle property) { - Cts.Ecma.EcmaModule module = owningType.Module; Ecma.MetadataReader reader = module.MetadataReader; Ecma.PropertyDefinition propDef = reader.GetPropertyDefinition(property); @@ -34,11 +33,9 @@ private Property HandleProperty(Cts.Ecma.EcmaType owningType, Ecma.PropertyDefin Ecma.BlobReader sigBlobReader = reader.GetBlobReader(propDef.Signature); Cts.PropertySignature sig = new Cts.Ecma.EcmaSignatureParser(module, sigBlobReader, Cts.NotFoundBehavior.Throw).ParsePropertySignature(); - bool stripName = StripsPropertyName(owningType); Property result = new Property { - Name = HandleName(reader.GetString(propDef.Name), stripName), - Discriminator = stripName ? GetDiscriminator(owningType, property) : 0, + Name = HandleString(reader.GetString(propDef.Name)), Flags = propDef.Attributes, Signature = new PropertySignature { diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Type.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Type.cs index a375d8790bc8b9..59cfa847115be2 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Type.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/Transform.Type.cs @@ -342,14 +342,14 @@ private void InitializeTypeDef(Cts.MetadataType entity, TypeDefinition record) foreach (var e in ecmaRecord.GetEvents()) { - Event evt = HandleEvent(ecmaEntity, e); + Event evt = HandleEvent(ecmaEntity.Module, e); if (evt != null) record.Events.Add(evt); } foreach (var property in ecmaRecord.GetProperties()) { - Property prop = HandleProperty(ecmaEntity, property); + Property prop = HandleProperty(ecmaEntity.Module, property); if (prop != null) record.Properties.Add(prop); } diff --git a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/Internal/Metadata/NativeFormat/Writer/NativeFormatWriterGen.cs b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/Internal/Metadata/NativeFormat/Writer/NativeFormatWriterGen.cs index 72c44eeabd3c26..90ccc7b8672153 100644 --- a/src/coreclr/tools/aot/ILCompiler.MetadataTransform/Internal/Metadata/NativeFormat/Writer/NativeFormatWriterGen.cs +++ b/src/coreclr/tools/aot/ILCompiler.MetadataTransform/Internal/Metadata/NativeFormat/Writer/NativeFormatWriterGen.cs @@ -490,7 +490,6 @@ public override sealed bool Equals(Object obj) if (Object.ReferenceEquals(this, obj)) return true; var other = obj as Event; if (other == null) return false; - if (Discriminator != other.Discriminator) return false; if (Flags != other.Flags) return false; if (!Object.Equals(Name, other.Name)) return false; if (!Object.Equals(Type, other.Type)) return false; @@ -506,7 +505,6 @@ public override sealed int GetHashCode() EnterGetHashCode(); var hash = new HashCode(); hash.Add(-1454825650); - hash.Add(Discriminator); hash.Add(Flags); hash.Add(Name); hash.Add(Type); @@ -552,8 +550,6 @@ internal static EventHandle AsHandle(Event record) } } // Handle - // Not persisted. Keeps records with otherwise identical content distinct, e.g. when their names were omitted. - public int Discriminator; public EventAttributes Flags; public ConstantStringValue Name; public MetadataRecord Type; @@ -584,7 +580,6 @@ public override sealed bool Equals(Object obj) if (Object.ReferenceEquals(this, obj)) return true; var other = obj as Field; if (other == null) return false; - if (Discriminator != other.Discriminator) return false; if (Flags != other.Flags) return false; if (!Object.Equals(Name, other.Name)) return false; if (!Object.Equals(Signature, other.Signature)) return false; @@ -601,7 +596,6 @@ public override sealed int GetHashCode() EnterGetHashCode(); var hash = new HashCode(); hash.Add(-540975116); - hash.Add(Discriminator); hash.Add(Flags); hash.Add(Name); hash.Add(Signature); @@ -644,8 +638,6 @@ internal static FieldHandle AsHandle(Field record) } } // Handle - // Not persisted. Keeps records with otherwise identical content distinct, e.g. when their names were omitted. - public int Discriminator; public FieldAttributes Flags; public ConstantStringValue Name; public FieldSignature Signature; @@ -903,7 +895,6 @@ public override sealed bool Equals(Object obj) if (Object.ReferenceEquals(this, obj)) return true; var other = obj as MemberReference; if (other == null) return false; - if (Discriminator != other.Discriminator) return false; if (!Object.Equals(Parent, other.Parent)) return false; if (!Object.Equals(Name, other.Name)) return false; if (!Object.Equals(Signature, other.Signature)) return false; @@ -917,7 +908,6 @@ public override sealed int GetHashCode() EnterGetHashCode(); var hash = new HashCode(); hash.Add(-875402938); - hash.Add(Discriminator); hash.Add(Parent); hash.Add(Name); hash.Add(Signature); @@ -960,8 +950,6 @@ internal static MemberReferenceHandle AsHandle(MemberReference record) } } // Handle - // Not persisted. Keeps records with otherwise identical content distinct, e.g. when their names were omitted. - public int Discriminator; public MetadataRecord Parent; public ConstantStringValue Name; public MetadataRecord Signature; @@ -991,7 +979,6 @@ public override sealed bool Equals(Object obj) if (Object.ReferenceEquals(this, obj)) return true; var other = obj as Method; if (other == null) return false; - if (Discriminator != other.Discriminator) return false; if (Flags != other.Flags) return false; if (ImplFlags != other.ImplFlags) return false; if (!Object.Equals(Name, other.Name)) return false; @@ -1009,7 +996,6 @@ public override sealed int GetHashCode() EnterGetHashCode(); var hash = new HashCode(); hash.Add(-1225154478); - hash.Add(Discriminator); hash.Add(Flags); hash.Add(ImplFlags); hash.Add(Name); @@ -1054,8 +1040,6 @@ internal static MethodHandle AsHandle(Method record) } } // Handle - // Not persisted. Keeps records with otherwise identical content distinct, e.g. when their names were omitted. - public int Discriminator; public MethodAttributes Flags; public MethodImplAttributes ImplFlags; public ConstantStringValue Name; @@ -1776,7 +1760,6 @@ public override sealed bool Equals(Object obj) if (Object.ReferenceEquals(this, obj)) return true; var other = obj as Property; if (other == null) return false; - if (Discriminator != other.Discriminator) return false; if (Flags != other.Flags) return false; if (!Object.Equals(Name, other.Name)) return false; if (!Object.Equals(Signature, other.Signature)) return false; @@ -1793,7 +1776,6 @@ public override sealed int GetHashCode() EnterGetHashCode(); var hash = new HashCode(); hash.Add(-1324612544); - hash.Add(Discriminator); hash.Add(Flags); hash.Add(Name); hash.Add(Signature); @@ -1837,8 +1819,6 @@ internal static PropertyHandle AsHandle(Property record) } } // Handle - // Not persisted. Keeps records with otherwise identical content distinct, e.g. when their names were omitted. - public int Discriminator; public PropertyAttributes Flags; public ConstantStringValue Name; public PropertySignature Signature; diff --git a/src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs b/src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs index e35ff365b30ead..e59c539eb5d94d 100644 --- a/src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs +++ b/src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs @@ -161,7 +161,7 @@ internal sealed class ILCompilerRootCommand : RootCommand public Option TrimmedAssemblies { get; } = new("--trim") { DefaultValueFactory = _ => Array.Empty(), Description = "Trim the specified assembly" }; public Option StrippedNamesAssemblies { get; } = - new("--stripnames") { DefaultValueFactory = _ => Array.Empty(), Description = "Don't emit the names of types and members of the specified assembly into the reflection metadata" }; + new("--stripnames") { DefaultValueFactory = _ => Array.Empty(), Description = "Don't emit the names of types of the specified assembly into the reflection metadata" }; public Option RootDefaultAssemblies { get; } = new("--defaultrooting") { Description = "Root assemblies that are not marked [IsTrimmable]" }; public Option TargetArchitecture { get; } = diff --git a/src/coreclr/tools/aot/ILCompiler/Program.cs b/src/coreclr/tools/aot/ILCompiler/Program.cs index 6bce9bf25a37ca..e90ab0daec495c 100644 --- a/src/coreclr/tools/aot/ILCompiler/Program.cs +++ b/src/coreclr/tools/aot/ILCompiler/Program.cs @@ -429,7 +429,7 @@ public int Run() foreach (string strippedNamesAssembly in Get(_command.StrippedNamesAssemblies)) { - // The reflection stack in the system module relies on the names of its own types and members. + // The reflection stack in the system module relies on the names of its own types. if (string.Equals(strippedNamesAssembly, Get(_command.SystemModuleName), StringComparison.OrdinalIgnoreCase)) throw new CommandLineException($"Stripping names of the system module '{strippedNamesAssembly}' is not supported"); } diff --git a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs index d3d7710293c19f..75dacc8bf8f82d 100644 --- a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs +++ b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs @@ -13,15 +13,16 @@ using StrippedNamesLibrary; // The StrippedNamesLibrary assembly is listed in IlcStripNamesAssembly (see StrippedNames.csproj), so the reflection -// metadata for its types and members has no names. Types and members from this assembly keep their names. +// metadata for its types has no names. Types from this assembly keep their names, and members keep their names everywhere. internal static class Program { private static int Main() { TestNamesOfStrippedTypes.Run(); - TestNamesOfStrippedMembers.Run(); + TestMembersOfStrippedTypes.Run(); TestNamesOfRetainedTypes.Run(); - TestRetainedMemberNames.Run(); + TestMemberNames.Run(); + TestOverrides.Run(); TestTypeIdentity.Run(); TestGenericVirtualMethods.Run(); TestLookupByName.Run(); @@ -83,55 +84,55 @@ public static void Run() } } - private static class TestNamesOfStrippedMembers + private static class TestMembersOfStrippedTypes { public static void Run() { Type widget = Keep(typeof(Widget)); const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; - // Methods that have the same shape must stay distinct without their names + // Members keep their names, even though the type that declares them has none MethodInfo[] methods = widget.GetMethods(flags); - Assert(methods.Length == 7); - Assert(methods.All(m => m.Name == string.Empty)); + Assert(methods.Length == 8); Assert(methods.All(m => m.DeclaringType == widget)); + Assert(methods.Select(m => m.Name).OrderBy(n => n, StringComparer.Ordinal).SequenceEqual( + new[] { "Echo", "FirstMethod", "RaiseChanged", "SecondMethod", "add_Changed", "get_Count", "remove_Changed", "set_Count" })); Widget instance = new Widget(); - List results = new(); - foreach (MethodInfo method in methods) - { - if (method.GetParameters().Length == 0 && method.ReturnType == typeof(string)) - results.Add((string)method.Invoke(instance, null)); - } - results.Sort(StringComparer.Ordinal); - Assert(results.Count == 2); - Assert(results[0] == "first"); - Assert(results[1] == "second"); - - FieldInfo[] fields = widget.GetFields(flags); - Assert(fields.Length == 1); - Assert(fields[0].Name == string.Empty); - fields[0].SetValue(instance, 42); + Assert((string)widget.GetMethod("FirstMethod").Invoke(instance, null) == "first"); + Assert((string)widget.GetMethod("SecondMethod").Invoke(instance, null) == "second"); + + MethodInfo echo = widget.GetMethod("Echo"); + Assert(echo.GetParameters().Single().Name == "text"); + Assert((string)echo.Invoke(instance, new object[] { "hello" }) == "hello"); + + FieldInfo field = widget.GetField("Field"); + Assert(field is not null); + field.SetValue(instance, 42); Assert(instance.Field == 42); - PropertyInfo[] properties = widget.GetProperties(flags); - Assert(properties.Length == 1); - Assert(properties[0].Name == string.Empty); - properties[0].SetValue(instance, 7); - Assert((int)properties[0].GetValue(instance) == 7); + PropertyInfo property = widget.GetProperty("Count"); + Assert(property is not null); + property.SetValue(instance, 7); + Assert((int)property.GetValue(instance) == 7); - EventInfo[] events = widget.GetEvents(flags); - Assert(events.Length == 1); - Assert(events[0].Name == string.Empty); + Assert(widget.GetEvent("Changed") is not null); - // Members are matched by their metadata definition, which doesn't depend on their name - FieldInfo definitionField = Keep(typeof(GenericHolder<>)).GetFields(flags | BindingFlags.Static).Single(); + // Members are matched by their metadata definition, even when the type has no name + FieldInfo definitionField = Keep(typeof(GenericHolder<>)).GetField("Value"); Type constructed = Keep(typeof(GenericHolder)); MemberInfo projected = constructed.GetMemberWithSameMetadataDefinitionAs(definitionField); - Assert(projected is FieldInfo { Name: "" } projectedField && projectedField.DeclaringType == constructed); - Assert(widget.GetMemberWithSameMetadataDefinitionAs(fields[0]) == fields[0]); + Assert(projected is FieldInfo { Name: "Value" } projectedField && projectedField.DeclaringType == constructed); + Assert(widget.GetMemberWithSameMetadataDefinitionAs(field) == field); - Assert(widget.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic).Length == 1); + // Nested types have no name, so they can't be filtered by it, but they are still found by their definition + Type nested = Keep(typeof(Widget.Nested)); + Assert(widget.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic).Single() == nested); + Assert(widget.GetMemberWithSameMetadataDefinitionAs(nested) == nested); + Assert(widget.GetNestedType(string.Empty) is null); + Assert(widget.GetNestedType(string.Empty, BindingFlags.Public | BindingFlags.IgnoreCase) is null); + Assert(widget.GetMember(string.Empty, MemberTypes.NestedType, BindingFlags.Public | BindingFlags.NonPublic).Length == 0); + Assert(widget.GetMember(string.Empty).Length == 0); } } @@ -158,7 +159,7 @@ public static void Run() } } - private static class TestRetainedMemberNames + private static class TestMemberNames { public static void Run() { @@ -170,13 +171,13 @@ public static void Run() Assert(ctor.Invoke(null) is Widget); Assert(Activator.CreateInstance(widget) is Widget); - // Enum members are retained + // Enum members work as usual Assert(Color.Green.ToString() == "Green"); Assert(Enum.Parse("Red") == Color.Red); Assert(string.Join(",", Enum.GetNames()) == "Red,Green"); Assert(Color.Red.ToString("G") == "Red"); - // The Invoke method of delegates is retained + // The Invoke method of delegates works as usual Callback callback = x => x * 2; Assert(callback(2) == 4); Assert((int)callback.DynamicInvoke(3) == 6); @@ -184,6 +185,26 @@ public static void Run() } } + private static class TestOverrides + { + public static void Run() + { + // Overrides are matched with the members they override by name, so this needs to work across stripped and not stripped types + MethodInfo baseMethod = Keep(typeof(Base)).GetMethod("Hello"); + Assert(baseMethod.DeclaringType == typeof(Base)); + + MethodInfo derivedMethod = Keep(typeof(Derived)).GetMethod("Hello", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); + Assert(derivedMethod.DeclaringType == typeof(Derived)); + Assert(derivedMethod.GetBaseDefinition() == baseMethod); + Assert(Keep(typeof(Derived)).GetMethods(BindingFlags.Public | BindingFlags.Instance).Count(m => m.Name == "Hello") == 1); + + MethodInfo mainMethod = Keep(typeof(MainDerived)).GetMethod("Hello", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); + Assert(mainMethod.GetBaseDefinition() == baseMethod); + Assert(Keep(typeof(MainDerived)).GetMethods(BindingFlags.Public | BindingFlags.Instance).Count(m => m.Name == "Hello") == 1); + Assert(new MainDerived().Hello() == "MainDerived"); + } + } + private static class TestTypeIdentity { public static void Run() @@ -219,7 +240,7 @@ private static class TestGenericVirtualMethods { public static void Run() { - // Generic virtual methods are matched by name and signature, so they keep their names + // Generic virtual methods are matched by name and signature GvmBase gvm = new GvmDerived(); Assert(gvm.Describe() == "GvmDerived"); Assert(gvm.Other() == "GvmDerived.Other"); @@ -236,7 +257,7 @@ public static void Run() Assert(converter.Convert(1) == 2); Assert(converter.Convert(1).Equals(2)); - // Generic methods that are not virtual are looked up by name at runtime too + // Generic methods are looked up by name at runtime too Assert(GenericHelpers.Describe(null) == "helper:ref"); Assert(GenericHelpers.Describe(default) == "helper:value"); MethodInfo helper = Keep(typeof(GenericHelpers)).GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly).Single().MakeGenericMethod(typeof(Marked)); @@ -267,11 +288,11 @@ public static void Run() Assert(typeof(Base).Assembly.GetType(Join(ns, "Base"), throwOnError: false, ignoreCase: true) is null); Type widget = Keep(typeof(Widget)); - Assert(widget.GetMethod(Join("First", "Method")) is null); - Assert(widget.GetMethod(Join("first", "method"), BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase) is null); - Assert(widget.GetField(Join("Fie", "ld")) is null); - Assert(widget.GetProperty(Join("Co", "unt")) is null); - Assert(widget.GetEvent(Join("Chan", "ged")) is null); + Assert(widget.GetMethod(Join("First", "Method")) is not null); + Assert(widget.GetMethod(Join("first", "method"), BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase) is not null); + Assert(widget.GetField(Join("Fie", "ld")) is not null); + Assert(widget.GetProperty(Join("Co", "unt")) is not null); + Assert(widget.GetEvent(Join("Chan", "ged")) is not null); Assert(widget.GetNestedType(Join("Nes", "ted")) is null); // Interfaces are looked up by name without going through the member filters @@ -286,7 +307,7 @@ private static class TestAttributes { public static void Run() { - // Named arguments are resolved by name, so the members of attribute types are retained + // Named arguments are resolved by name MarkerAttribute attribute = typeof(Marked).GetCustomAttribute(); Assert(attribute is not null); Assert(attribute.Label == "label"); @@ -298,7 +319,7 @@ public static void Run() Assert(new Marked() is not null); - // The accessors of properties of attribute types are used to match overrides + // Properties of attribute types are matched with the ones they override by name DerivedMarkerAttribute derived = typeof(MarkedWithOverride).GetCustomAttribute(); Assert(derived is not null); Assert(derived.Value == "overridden"); @@ -327,7 +348,7 @@ public static void Run() Assert(stackTrace.Contains("+0x")); Assert(!stackTrace.Contains(Join("Unique", "Stripped"))); - // Methods that are reflectable have no stack trace data, but [StackTraceHidden] still applies + // Methods of stripped types have no stack trace data, even if they are reflectable, but [StackTraceHidden] still applies Keep(typeof(HiddenFrameHolder)); string hiddenStackTrace = null; try @@ -358,12 +379,10 @@ public static void Run() // Check that the same lookup finds the names that are expected to be there Assert(Contains(image, Join("ControlType"))); Assert(Contains(image, Join("Control", "Method"))); + Assert(Contains(image, Join("First", "Method"))); Assert(!Contains(image, Join("Unique", "StrippedTypeNameMarker"))); Assert(!Contains(image, Join("Unique", "StrippedThrowingMethodMarker"))); - Assert(!Contains(image, Join("First", "Method"))); - Assert(!Contains(image, Join("Second", "Method"))); - Assert(!Contains(image, Join("Rai", "seChanged"))); Assert(!Contains(image, Join("Gvm", "Derived"))); Assert(!Contains(image, Join("Int", "Converter"))); } @@ -374,6 +393,11 @@ public static void Run() namespace ControlNamespace { + public class MainDerived : Base + { + public override string Hello() => "MainDerived"; + } + public class ControlType { public int ControlField; diff --git a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs index de5a2ee9b7e2a4..d6e8f585b0de3b 100644 --- a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs +++ b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs @@ -18,6 +18,7 @@ public Widget() { } public string FirstMethod() => "first"; public string SecondMethod() => "second"; + public string Echo(string text) => text; public void RaiseChanged() => Changed?.Invoke(this, EventArgs.Empty); @@ -34,7 +35,6 @@ public class Derived : Base public override string Hello() => "Derived"; } - // Generic virtual methods are matched by name and signature at runtime, so they keep their names. public class GvmBase { public virtual string Describe() => "GvmBase"; From 5e31c0f21f276686111933a2612cd05e17500199 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Nov 2026 23:16:29 -0800 Subject: [PATCH 10/11] Throw when the name of a type from an assembly that strips names is requested Returning an empty name lets bugs go unnoticed until they surface somewhere else, so Type.Name, Namespace, FullName, AssemblyQualifiedName and ToString (and everything that is composed from them) throw NotSupportedException for these types. The message mentions the assembly and IlcStripNamesAssembly. Lookups by name and the stack trace exclusion are unchanged. Crash reporting of an unhandled exception of such a type falls back to the message and the stack trace. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../src/System/Delegate.NativeAot.cs | 6 +- .../Runtime/BindingFlagSupport/NameFilter.cs | 4 +- .../Reflection/Runtime/General/ThunkedApis.cs | 5 +- .../NativeFormatRuntimeNamedTypeInfo.cs | 24 ++-- .../RuntimeConstructedGenericTypeInfo.cs | 17 +-- .../Runtime/TypeInfos/RuntimeNamedTypeInfo.cs | 7 -- .../TypeInfos/RuntimeTypeInfo.GetMember.cs | 2 +- .../Runtime/TypeInfos/RuntimeTypeInfo.cs | 16 ++- .../src/System/RuntimeExceptionHelpers.cs | 26 +++- src/coreclr/nativeaot/docs/optimizing.md | 23 ++-- .../src/Resources/Strings.resx | 3 + .../SmokeTests/StrippedNames/StrippedNames.cs | 118 ++++++++++++++---- .../StrippedNames/StrippedNamesLibrary.cs | 16 +++ 13 files changed, 191 insertions(+), 76 deletions(-) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.NativeAot.cs index 44e08307663d4b..33425c087a991f 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.NativeAot.cs @@ -4,6 +4,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; +using System.Reflection.Runtime.General; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -318,8 +319,9 @@ internal DiagnosticMethodInfo GetDiagnosticMethodInfo() { MethodInfo mi = ReflectionAugments.GetDelegateMethod(this); - // Declaring types with a name that was stripped by the compiler have no information to report. - if (mi.DeclaringType!.Name.Length == 0) + // Declaring types with a name that was stripped by the compiler have no information to report, + // which is consistent with the stack trace data of the methods of such types. + if (mi.DeclaringType!.ToRuntimeTypeInfo().IsNameStripped) return null; Type? declaringType = mi.DeclaringType; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.cs index 6bb2f7bae18528..b79b108be4a0b3 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/BindingFlagSupport/NameFilter.cs @@ -26,7 +26,7 @@ public NameFilterCaseSensitive(string expectedName) { } - public sealed override bool Matches(string name) => CanMatch && name.Equals(ExpectedName, StringComparison.Ordinal); + public sealed override bool Matches(string name) => name.Equals(ExpectedName, StringComparison.Ordinal); } internal sealed partial class NameFilterCaseInsensitive : NameFilter @@ -36,6 +36,6 @@ public NameFilterCaseInsensitive(string expectedName) { } - public sealed override bool Matches(string name) => CanMatch && name.Equals(ExpectedName, StringComparison.OrdinalIgnoreCase); + public sealed override bool Matches(string name) => name.Equals(ExpectedName, StringComparison.OrdinalIgnoreCase); } } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/General/ThunkedApis.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/General/ThunkedApis.cs index ac6bc3e9e043d0..9f0bc3c231e761 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/General/ThunkedApis.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/General/ThunkedApis.cs @@ -210,12 +210,11 @@ internal abstract partial class RuntimeTypeInfo Type? match = null; foreach (Type ifc in GetInterfaces()) { - string ifcSimpleName = ifc.Name; - // Interfaces with a name that was stripped by the compiler can't be found by name. - if (ifcSimpleName.Length == 0) + if (ifc.ToRuntimeTypeInfo().IsNameStripped) continue; + string ifcSimpleName = ifc.Name; bool simpleNameMatches = ignoreCase ? (0 == CultureInfo.InvariantCulture.CompareInfo.Compare(simpleName, ifcSimpleName, CompareOptions.IgnoreCase)) // @todo: This could be expressed simpler but the necessary parts of String api not yet ported. : simpleName.Equals(ifcSimpleName); diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs index d39ba099184f39..640b12187c4735 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.General; @@ -119,6 +120,12 @@ public sealed override string Namespace ns = NamespaceDefinition.Name.GetStringOrNull(_reader).EscapeTypeNameIdentifier() ?? string.Empty; _lazyNamespace = ns; } + + // The types with a name that was stripped are in the global namespace, which doesn't tell them from types + // that have a name in the global namespace. + if (ns.Length == 0 && IsNameStripped) + ThrowNameStripped(); + return ns.Length == 0 ? null : ns; } } @@ -142,16 +149,11 @@ public sealed override string ToString() { StringBuilder? sb = null; - // The name of the type was stripped by the compiler, so there is nothing to print. - string? fullName = FullName; - if (fullName is null) - return Name; - foreach (GenericParameterHandle genericParameterHandle in _typeDefinition.GenericParameters) { if (sb == null) { - sb = new StringBuilder(fullName); + sb = new StringBuilder(FullName); sb.Append('['); } else @@ -164,7 +166,7 @@ public sealed override string ToString() if (sb == null) { - return fullName; + return FullName; } else { @@ -209,10 +211,18 @@ public sealed override string Name ConstantStringValueHandle nameHandle = _typeDefinition.Name; string name = nameHandle.GetString(_reader); + if (name.Length == 0) + ThrowNameStripped(); + return name.EscapeTypeNameIdentifier(); } } + internal sealed override bool IsNameStripped => _typeDefinition.Name.StringEquals(string.Empty, _reader); + + [DoesNotReturn] + private void ThrowNameStripped() => throw new NotSupportedException(SR.Format(SR.NotSupported_StrippedTypeName, InternalFullNameOfAssembly)); + internal sealed override MetadataReader GetMetadataReader() => _reader; internal sealed override CustomAttributeHandleCollection GetCustomAttributeHandles() => _typeDefinition.CustomAttributes; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeConstructedGenericTypeInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeConstructedGenericTypeInfo.cs index ff875b4861f567..f5a9da0da49ac5 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeConstructedGenericTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeConstructedGenericTypeInfo.cs @@ -58,27 +58,18 @@ public sealed override string FullName if (ContainsGenericParameters) return null; - // The definition or a type argument might have a name that was stripped by the compiler. - string? definitionFullName = GenericTypeDefinitionTypeInfo.FullName; - if (definitionFullName is null) - return null; - StringBuilder fullName = new StringBuilder(); - fullName.Append(definitionFullName); + fullName.Append(GenericTypeDefinitionTypeInfo.FullName); fullName.Append('['); RuntimeTypeInfo[] genericTypeArguments = _key.GenericTypeArguments; for (int i = 0; i < genericTypeArguments.Length; i++) { - string? argumentName = genericTypeArguments[i].AssemblyQualifiedName; - if (argumentName is null) - return null; - if (i != 0) fullName.Append(','); fullName.Append('['); - fullName.Append(argumentName); + fullName.Append(genericTypeArguments[i].AssemblyQualifiedName); fullName.Append(']'); } fullName.Append(']'); @@ -158,7 +149,7 @@ public sealed override string ToString() { // Now, append the generic type arguments. StringBuilder sb = new StringBuilder(); - sb.Append(GenericTypeDefinitionTypeInfo.FullName ?? GenericTypeDefinitionTypeInfo.Name); + sb.Append(GenericTypeDefinitionTypeInfo.FullName); sb.Append('['); RuntimeTypeInfo[] genericTypeArguments = _key.GenericTypeArguments; for (int i = 0; i < genericTypeArguments.Length; i++) @@ -216,6 +207,8 @@ internal sealed override string InternalFullNameOfAssembly } } + internal sealed override bool IsNameStripped => GenericTypeDefinitionTypeInfo.IsNameStripped; + public sealed override string Name { get diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeNamedTypeInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeNamedTypeInfo.cs index 344f25e270251a..c76bf2311f7d6a 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeNamedTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeNamedTypeInfo.cs @@ -76,17 +76,10 @@ public sealed override string FullName string name = Name; - // The name of the type was stripped by the compiler (see IlcStripNamesAssembly), so it has no full name. - if (name.Length == 0) - return null; - RuntimeTypeInfo? declaringType = this.InternalDeclaringType; if (declaringType is not null) { string? declaringTypeFullName = declaringType.FullName; - if (declaringTypeFullName is null) - return null; - return declaringTypeFullName + "+" + name; } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.GetMember.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.GetMember.cs index 19d6a577085a58..caa76e2beb7a2a 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.GetMember.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.GetMember.cs @@ -171,7 +171,7 @@ private M QueryMemberWithSameMetadataDefinitionAs(MemberPolicies policies, { // Nested types with a name that was stripped by the compiler can't be filtered by name, so the metadata definition comparison below does all the work. BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; - QueryResult members = member.Name.Length == 0 ? Query(policies, flags) : Query(policies, member.Name, flags); + QueryResult members = member is Type ? Query(policies, flags) : Query(policies, member.Name, flags); foreach (M candidate in members) { if (candidate.HasSameMetadataDefinitionAs(member)) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs index 90ad8c3d9ecdfc..3e721c7153c0fc 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs @@ -594,6 +594,12 @@ internal virtual RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers // internal abstract string InternalFullNameOfAssembly { get; } + // + // Returns true if the compiler stripped the name of this type from the metadata (see IlcStripNamesAssembly). + // Getting the name of such a type throws. + // + internal virtual bool IsNameStripped => false; + // // Left unsealed as HasElement types must override this. // @@ -729,7 +735,15 @@ internal RuntimeTypeInfo EstablishDebugName() if (_debugName == null) { _debugName = "Constructing..."; // Protect against any inadvertent reentrancy. - _debugName = ToString() ?? ""; + try + { + _debugName = ToString() ?? ""; + } + catch (NotSupportedException) + { + // The name of the type was stripped + _debugName = ""; + } } #endif return this; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeExceptionHelpers.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeExceptionHelpers.cs index d61cc260f4b3d9..bb976d31b76b8b 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeExceptionHelpers.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeExceptionHelpers.cs @@ -295,7 +295,7 @@ internal static unsafe void FailFast(string? message = null, Exception? exceptio Internal.Console.Error.Write(exception.ToString()); Internal.Console.Error.WriteLine(); } - catch + catch (Exception toStringException) { // If ToString() fails (for example, due to OOM), fall back to a simpler message. try @@ -304,7 +304,19 @@ internal static unsafe void FailFast(string? message = null, Exception? exceptio Internal.Console.Error.Write(exception.GetMethodTable() == Internal.Runtime.MethodTable.Of() ? "Out of memory." : exception.GetType().FullName); Internal.Console.Error.WriteLine(); } - catch { } + catch + { + // The name of the type of the exception might not be available (see IlcStripNamesAssembly). + // Print the reason and the stack trace, which doesn't need the names of types. + try + { + Internal.Console.Error.Write(toStringException.Message); + Internal.Console.Error.WriteLine(); + Internal.Console.Error.Write(exception.StackTrace); + Internal.Console.Error.WriteLine(); + } + catch { } + } } } @@ -314,7 +326,15 @@ internal static unsafe void FailFast(string? message = null, Exception? exceptio var reporter = new EventReporter(reason); if (exception != null && reason is not RhFailFastReason.AssertionFailure) { - reporter.AddDescription($"{exception.GetType()}: {exception.Message}"); + try + { + reporter.AddDescription($"{exception.GetType()}: {exception.Message}"); + } + catch (Exception ex) + { + // The name of the type of the exception might not be available (see IlcStripNamesAssembly) + reporter.AddDescription(ex.Message); + } reporter.AddStackTrace(exception.StackTrace); } else diff --git a/src/coreclr/nativeaot/docs/optimizing.md b/src/coreclr/nativeaot/docs/optimizing.md index deb41733c487ef..afdc4f7310d15d 100644 --- a/src/coreclr/nativeaot/docs/optimizing.md +++ b/src/coreclr/nativeaot/docs/optimizing.md @@ -16,30 +16,29 @@ The rest of the document talks about options that exist, but their names and pur The option is opt-in per assembly, because it changes the observable behavior of reflection for the types of that assembly. Names are replaced with the empty string in the metadata, so the cost of a name is no longer paid in the binary. Names remain available in the compiler map file (``), in the mstat file, and in the symbol files (`.pdb`, `.dwp`, `.dSYM`) because these are produced from the compiler's own type system and not from the reflection metadata. Note that on platforms where the debug information is part of the image, the names will be there as well. +Asking for the name of such a type fails with a `NotSupportedException` right away, instead of returning an empty or made up name, so that a missing name is not mistaken for a bug of the runtime and can be diagnosed from the stack trace. The message of the exception says that the name was stripped and mentions `IlcStripNamesAssembly`. Apps that hit the exception need to remove the assembly from the item. + Only the names of types are stripped. The compiler only emits metadata for a member if it is a reflection target (e.g. it is kept by a `DynamicallyAccessedMembers` annotation, a `DynamicDependency` attribute or a root descriptor), so the names of members are kept to keep lookups by name working. Behavior for types of an assembly that strips names: | API | Result | | --- | --- | -| `Type.Name` | `""` (empty string, the property is not nullable) | -| `Type.Namespace`, `Type.FullName`, `Type.AssemblyQualifiedName` | `null` | -| `Type.ToString()` | `""`, matching `Type.Name` (the method is not nullable). Also for generic type definitions | -| `FullName` and `AssemblyQualifiedName` of arrays, pointers, by-refs, nested types and constructed generic types that involve such a type (including as a type argument) | `null`, like for a generic parameter | -| `Type.GetType(string)`, `Assembly.GetType(string)`, `GetNestedType(string)`, `GetInterface(string)`, `GetMember(string)` for nested types | Don't find the type, since nothing can match an empty name | +| `Type.Name`, `Type.Namespace`, `Type.FullName`, `Type.AssemblyQualifiedName`, `Type.ToString()` | Throw `NotSupportedException`. This includes `Object.ToString()` and `ValueType.ToString()`, and exception messages that print the name of the type (the exception thrown while building the message is `NotSupportedException` instead) | +| The same members for arrays, pointers, by-refs and constructed generic types that involve such a type (including as a type argument) | Throw `NotSupportedException` too, e.g. for `List` where `T` is such a type | +| `Type.GetType(string)`, `Assembly.GetType(string)`, `GetNestedType(string)`, `GetInterface(string)`, `GetMember(string)` for nested types | Don't find the type, since the name is not in the metadata. Interfaces that don't have a name are skipped by `GetInterface(string)` | | Names of members (methods, fields, properties, events, parameters and generic parameters), `GetMethod(string)` and the other lookups of members by name | Unchanged, including for members of a stripped type | | Named arguments of custom attributes, enum members, overrides and generic virtual methods | Unchanged | -| `MethodInfo.ToString()` and the like | The types in the signature are printed with an empty name, so `Void Foo()` can stand for `Foo(Widget)`. The output of `ToString()` can't be used as a key | -| Exception messages and `Exception.ToString()` | Use the empty name for the type | -| Stack traces | The frames of methods of the assembly don't have names. They show up as an offset in the module, which can be symbolicated with the symbol files, e.g. on a crash report server. This also applies to methods that are reflectable. `DiagnosticMethodInfo.Create` returns `null` for methods of the assembly. Frames of methods from other assemblies that have a type of the assembly in their signature show that type with an empty name | -| Compiler generated attribute types in the assembly, e.g. `NullableAttribute` | The types lose their names, so consumers that identify them by name, e.g. `NullabilityInfoContext`, don't recognize them | +| Stack traces | The frames of methods of the assembly don't have names. They show up as an offset in the module, which can be symbolicated with the symbol files, e.g. on a crash report server. This also applies to methods that are reflectable. `DiagnosticMethodInfo.Create` returns `null` for methods of the assembly. Frames of methods from other assemblies that have a type of the assembly in their signature show that type with an empty name, because stack traces are produced without going through reflection | +| Compiler generated attribute types in the assembly, e.g. `NullableAttribute` | Consumers that identify them by name, e.g. `NullabilityInfoContext`, fail on them | Everything else is unchanged. In particular, type identity, `typeof`, `GetType()`, `Activator.CreateInstance`, `MethodInfo.Invoke`, `MakeGenericType`, `MakeGenericMethod`, custom attribute instantiation, and virtual and interface dispatch don't depend on the names. Limitations: * The names are removed from the reflection metadata only. Other places in the binary that contain names are not affected, e.g. the field names that are part of struct marshalling metadata, the keys of external type maps (`TypeMapping`), embedded resource names, and strings that code explicitly contains (e.g. the string passed to `[UnsafeAccessorType]`, `Type.GetType`, or the arguments of custom attributes). -* Code that looks up types of such an assembly by name, e.g. `Type.GetType("Namespace.Type, Assembly")`, will not find them, even if the compiler has seen the string. A reference that goes through metadata directly (e.g. a type referenced by a custom attribute argument) is not affected. -* Serializers, `EventSource`, `DataContract`, data binding, and anything else that derives behavior from type names don't work for these types. -* Code that assumes a named type has a non-null `FullName` (e.g. `type.FullName!`) can throw for these types. For example, `ILogger` and `ILoggerFactory.CreateLogger(typeof(T))` throw a `NullReferenceException` when `T` is a stripped type, because the category name is derived from `FullName`. The default `Object.ToString()` and `ValueType.ToString()` return an empty string for these types. +* Code that looks up types of such an assembly by name, e.g. `Type.GetType("Namespace.Type, Assembly")`, will not find them, even if the compiler has seen the string. +* Serializers, `EventSource`, `DataContract`, data binding, logging that uses the name of the type (e.g. `ILogger`), and anything else that derives behavior from type names throw for these types. This includes the default `Exception.Message` and `Exception.ToString()` of exception types of the assembly, and code that goes through all the custom attributes of a member and compares the names of their types (e.g. `NullabilityInfoContext`), if any of them is an attribute type of the assembly. +* Error messages that are produced by the type loader from the metadata and not through reflection (e.g. when a generic type can't be created) can still print an empty name for the type. +* An unhandled exception of a type of such an assembly can't print its type name, so the crash report has the message of the `NotSupportedException` and the stack trace of the original exception instead. * The setting is not supported for the system module or for multi-file compilation (the compiler reports an error). Assemblies that are not part of the compilation are ignored. diff --git a/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx b/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx index 4eca1f73391a71..eb5bf98a41f3f4 100644 --- a/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx +++ b/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx @@ -4346,6 +4346,9 @@ TypeHandles are not supported for types that return true for ContainsGenericParameters. + + The name of a type from the assembly '{0}' is not available because it was stripped from the metadata. Remove the assembly from the 'IlcStripNamesAssembly' item to restore it. + The type '{0}' was created by a custom ReflectionContext and cannot be used here. diff --git a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs index 75dacc8bf8f82d..e52c7a90f67b75 100644 --- a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs +++ b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNames.cs @@ -10,6 +10,7 @@ using System.Runtime.CompilerServices; using System.Text; +using ControlNamespace; using StrippedNamesLibrary; // The StrippedNamesLibrary assembly is listed in IlcStripNamesAssembly (see StrippedNames.csproj), so the reflection @@ -44,43 +45,99 @@ private static void Assert(bool condition, [CallerArgumentExpression(nameof(cond // Prevents the names from being constant folded into the program, which would defeat the check for the image contents. private static string Join(params string[] parts) => string.Concat(parts); + private static void TakesWidget(Widget value) { } + + private static void AssertNameIsNotAvailable(Func getName, [CallerArgumentExpression(nameof(getName))] string message = null) + { + try + { + getName(); + } + catch (NotSupportedException) + { + return; + } + + throw new Exception(message); + } + private static class TestNamesOfStrippedTypes { public static void Run() { Type widget = Keep(typeof(Widget)); - Assert(widget.Name == string.Empty); - Assert(widget.FullName is null); - Assert(widget.Namespace is null); - Assert(widget.AssemblyQualifiedName is null); - Assert(widget.ToString() == string.Empty); - Assert(widget.Assembly == typeof(Base).Assembly); + // Getting any name of the type fails + AssertNameIsNotAvailable(() => widget.Name); + AssertNameIsNotAvailable(() => widget.Namespace); + AssertNameIsNotAvailable(() => widget.FullName); + AssertNameIsNotAvailable(() => widget.AssemblyQualifiedName); + AssertNameIsNotAvailable(() => widget.ToString()); + AssertNameIsNotAvailable(() => new Widget().ToString()); + AssertNameIsNotAvailable(() => default(Point).ToString()); + AssertNameIsNotAvailable(() => Keep(typeof(Widget.Nested)).Name); + AssertNameIsNotAvailable(() => Keep(typeof(Widget.Nested)).FullName); + AssertNameIsNotAvailable(() => typeof(Color).Name); + AssertNameIsNotAvailable(() => typeof(Callback).Name); + AssertNameIsNotAvailable(() => typeof(GenericHolder<>).Name); + AssertNameIsNotAvailable(() => typeof(GenericHolder<>).ToString()); + + // ... also if the type is a part of another type + AssertNameIsNotAvailable(() => typeof(Widget[]).Name); + AssertNameIsNotAvailable(() => typeof(Widget[]).FullName); + AssertNameIsNotAvailable(() => typeof(Widget).MakeByRefType().ToString()); + AssertNameIsNotAvailable(() => typeof(Widget).MakePointerType().AssemblyQualifiedName); + AssertNameIsNotAvailable(() => typeof(GenericHolder).Name); + AssertNameIsNotAvailable(() => typeof(GenericHolder).FullName); + AssertNameIsNotAvailable(() => typeof(GenericHolder).ToString()); + AssertNameIsNotAvailable(() => typeof(List).FullName); + AssertNameIsNotAvailable(() => typeof(List).AssemblyQualifiedName); + AssertNameIsNotAvailable(() => typeof(List).ToString()); + + // The error message mentions how to restore the names + try + { + _ = widget.Name; + } + catch (NotSupportedException ex) + { + Assert(ex.Message.Contains("IlcStripNamesAssembly", StringComparison.Ordinal)); + } - Type nested = Keep(typeof(Widget.Nested)); - Assert(nested.Name == string.Empty); - Assert(nested.FullName is null); - Assert(nested.DeclaringType == widget); - - Assert(typeof(Widget[]).FullName is null); - Assert(typeof(Widget).MakeByRefType().FullName is null); - Assert(typeof(Widget).MakePointerType().FullName is null); - - // Constructed generic types have no full name if any of their components has no name - Assert(typeof(GenericHolder<>).FullName is null); - Assert(typeof(GenericHolder).FullName is null); - Assert(typeof(GenericHolder).FullName is null); - Assert(typeof(List).FullName is null); - Assert(typeof(List).AssemblyQualifiedName is null); - Assert(typeof(List).ToString() is not null); + // Everything that doesn't need the name works + Assert(widget.Assembly == typeof(Base).Assembly); + Assert(Keep(typeof(Widget.Nested)).DeclaringType == widget); Assert(typeof(List).GetGenericArguments()[0] == typeof(Widget)); + Assert(typeof(Widget[]).GetElementType() == widget); + Assert(typeof(GenericHolder).GetGenericTypeDefinition() == typeof(GenericHolder<>)); + Assert(typeof(GenericHolder<>).GetGenericArguments()[0].Name == "T"); + Assert(widget.IsClass && !widget.IsValueType && typeof(Point).IsValueType && typeof(Color).IsEnum); - // ... but they keep it if they are not involved - Assert(typeof(List).FullName is not null); + // ... and the types that are not involved are not affected Assert(typeof(List).FullName.StartsWith("System.Collections.Generic.List`1[[System.String", StringComparison.Ordinal)); + Assert(typeof(string[]).Name == "String[]"); - Assert(typeof(Color).Name == string.Empty); - Assert(typeof(Callback).Name == string.Empty); + // Exceptions of the assembly have no name to print unless they have a message, and the stack trace doesn't need the name + AssertNameIsNotAvailable(() => new StrippedException().Message); + AssertNameIsNotAvailable(() => new StrippedException("message").ToString()); + Assert(new StrippedException("message").Message == "message"); + try + { + throw new StrippedException("message"); + } + catch (StrippedException ex) + { + Assert(!string.IsNullOrEmpty(ex.StackTrace)); + } + + // The names of enum members work as usual + Assert((Options.First | Options.Second).ToString() == "First, Second"); + + // Types of the assembly are returned from the reflection API of other types + MethodInfo takesWidget = Keep(typeof(Program)).GetMethod(nameof(TakesWidget), BindingFlags.NonPublic | BindingFlags.Static); + Assert(takesWidget.GetParameters()[0].ParameterType == widget); + Assert(takesWidget.GetParameters()[0].Name == "value"); + AssertNameIsNotAvailable(() => takesWidget.GetParameters()[0].ParameterType.Name); } } @@ -133,6 +190,10 @@ public static void Run() Assert(widget.GetNestedType(string.Empty, BindingFlags.Public | BindingFlags.IgnoreCase) is null); Assert(widget.GetMember(string.Empty, MemberTypes.NestedType, BindingFlags.Public | BindingFlags.NonPublic).Length == 0); Assert(widget.GetMember(string.Empty).Length == 0); + + // ... including when the nested type is reached through a constructed generic type + Type innerDefinition = Keep(typeof(GenericHolder<>)).GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic).Single(); + Assert(constructed.GetMemberWithSameMetadataDefinitionAs(innerDefinition) == innerDefinition); } } @@ -300,6 +361,11 @@ public static void Run() Assert(converter.GetInterface(string.Empty) is null); Assert(converter.GetInterface(string.Empty, ignoreCase: true) is null); Assert(converter.GetInterface(Join("IConv", "erter`1")) is null); + + // GetInterface looks at the names of all interfaces of the type, which includes the ones that don't have a name + Assert(converter.GetInterfaces().Length == 1); + Assert(converter.GetInterface("IDisposable") is null); + Assert(converter.GetMember(Join("Conv", "ert"), MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance).Length == 1); } } diff --git a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs index d6e8f585b0de3b..fd80a17e359fdc 100644 --- a/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs +++ b/src/tests/nativeaot/SmokeTests/StrippedNames/StrippedNamesLibrary.cs @@ -60,6 +60,8 @@ public class IntConverter : IConverter public class GenericHolder { public T Value; + + public class Inner { } } public enum Color @@ -68,6 +70,20 @@ public enum Color Green, } + [Flags] + public enum Options + { + None = 0, + First = 1, + Second = 2, + } + + public class StrippedException : Exception + { + public StrippedException() { } + public StrippedException(string message) : base(message) { } + } + public delegate int Callback(int x); [AttributeUsage(AttributeTargets.All)] From a4666653f4376ff669b44466b6250d4d4789cedd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Nov 2026 23:17:41 -0800 Subject: [PATCH 11/11] Use the MethodTable address as the debug name of types with a stripped name Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs index 3e721c7153c0fc..a8759da67fed9f 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs @@ -741,8 +741,12 @@ internal RuntimeTypeInfo EstablishDebugName() } catch (NotSupportedException) { - // The name of the type was stripped - _debugName = ""; + // The name of the type was stripped (see IlcStripNamesAssembly). Use the address of the MethodTable + // relative to the base of its module, which can be looked up in the symbol files. This code is only in debug builds. + RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable; + _debugName = typeHandle.IsNull + ? "" + : "EETypeRva:0x" + ((nint)typeHandle.Value - RuntimeAugments.GetModuleFromTypeHandle(typeHandle).OsModuleBase).ToString("x"); } } #endif