From 2f7d9586d2b0c5a7cd4675d3391cd4b33685442b Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Wed, 26 Jun 2024 21:43:04 +0000 Subject: [PATCH 01/11] Fix type name parsing issues in ILLink and ILC --- .../CustomAttributeTypeNameParser.cs | 36 +++++++++--- .../Compiler/Dataflow/ReflectionMarker.cs | 9 +-- .../illink/src/ILLink.Shared/DiagnosticId.cs | 3 +- .../src/ILLink.Shared/SharedStrings.resx | 6 ++ ...RequireDynamicallyAccessedMembersAction.cs | 2 +- .../Linker.Steps/LinkAttributesParser.cs | 34 ++++++----- .../src/linker/Linker.Steps/MarkStep.cs | 4 -- .../TypeNameResolver.WithDiagnostics.cs | 56 +++++++------------ .../src/linker/Linker/TypeNameResolver.cs | 11 ++++ .../ComponentModel/TypeConverterOnMembers.cs | 4 +- .../DataFlow/ApplyTypeAnnotations.cs | 23 ++++++-- .../DataFlow/AssemblyQualifiedNameDataflow.cs | 2 +- .../DataFlow/AttributeConstructorDataflow.cs | 2 +- .../DataFlow/AttributeFieldDataflow.cs | 3 +- .../DataFlow/AttributePropertyDataflow.cs | 8 +-- .../GenericParameterWarningLocation.cs | 28 ++++++---- .../Dependencies/EscapedTypeNames.il | 4 +- .../Reflection/Dependencies/RequireHelper.cs | 14 +++++ .../Reflection/TypeUsedViaReflection.cs | 51 ++++++++++++++--- 19 files changed, 195 insertions(+), 105 deletions(-) create mode 100644 src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/Dependencies/RequireHelper.cs diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameParser.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameParser.cs index 7f19644ad10d9a..1fb3df94dac0a1 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameParser.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameParser.cs @@ -36,13 +36,18 @@ public static TypeDesc GetTypeByCustomAttributeTypeName(this ModuleDesc module, } public static TypeDesc GetTypeByCustomAttributeTypeNameForDataFlow(string name, ModuleDesc callingModule, - TypeSystemContext context, List referencedModules, out bool typeWasNotFoundInAssemblyNorBaseLibrary) + TypeSystemContext context, List referencedModules, bool needsAssemblyName, out bool failedBecauseNotFullyQualified) { - typeWasNotFoundInAssemblyNorBaseLibrary = false; - + failedBecauseNotFullyQualified = false; if (!TypeName.TryParse(name.AsSpan(), out TypeName parsed, s_typeNameParseOptions)) return null; + if (needsAssemblyName && !IsFullyQualified(parsed)) + { + failedBecauseNotFullyQualified = true; + return null; + } + TypeNameResolver resolver = new() { _context = context, @@ -52,8 +57,28 @@ public static TypeDesc GetTypeByCustomAttributeTypeNameForDataFlow(string name, TypeDesc type = resolver.Resolve(parsed); - typeWasNotFoundInAssemblyNorBaseLibrary = resolver._typeWasNotFoundInAssemblyNorBaseLibrary; return type; + + static bool IsFullyQualified (TypeName typeName) + { + if (typeName.AssemblyName is null) + { + return false; + } + + if (typeName.IsConstructedGenericType) + { + foreach (var typeArgument in typeName.GetGenericArguments()) + { + if (!IsFullyQualified(typeArgument)) + { + return false; + } + } + } + + return true; + } } private struct TypeNameResolver @@ -64,7 +89,6 @@ private struct TypeNameResolver internal Func _canonResolver; internal List _referencedModules; - internal bool _typeWasNotFoundInAssemblyNorBaseLibrary; internal TypeDesc Resolve(TypeName typeName) { @@ -136,8 +160,6 @@ private TypeDesc GetSimpleType(TypeName typeName) return type; } } - - _typeWasNotFoundInAssemblyNorBaseLibrary = true; } if (_throwIfNotFound) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMarker.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMarker.cs index d4e81f23b0c80e..bf966393c0f2ef 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMarker.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMarker.cs @@ -89,12 +89,13 @@ internal bool TryResolveTypeNameAndMark(string typeName, in DiagnosticContext di List referencedModules = new(); TypeDesc foundType = CustomAttributeTypeNameParser.GetTypeByCustomAttributeTypeNameForDataFlow(typeName, callingModule, diagnosticContext.Origin.MemberDefinition!.Context, - referencedModules, out bool typeWasNotFoundInAssemblyNorBaseLibrary); + referencedModules, needsAssemblyName, out bool failedBecauseNotFullyQualified); if (foundType == null) { - if (needsAssemblyName && typeWasNotFoundInAssemblyNorBaseLibrary) - diagnosticContext.AddDiagnostic(DiagnosticId.TypeWasNotFoundInAssemblyNorBaseLibrary, typeName); - + if (failedBecauseNotFullyQualified) + { + diagnosticContext.AddDiagnostic(DiagnosticId.TypeNameIsNotAssemblyQualified, typeName); + } type = default; return false; } diff --git a/src/tools/illink/src/ILLink.Shared/DiagnosticId.cs b/src/tools/illink/src/ILLink.Shared/DiagnosticId.cs index 5d40efbbaaf994..b403d0f503c68d 100644 --- a/src/tools/illink/src/ILLink.Shared/DiagnosticId.cs +++ b/src/tools/illink/src/ILLink.Shared/DiagnosticId.cs @@ -83,7 +83,7 @@ public enum DiagnosticId _unused_RearrangedXmlWarning2 = 2021, XmlCouldNotFindMatchingConstructorForCustomAttribute = 2022, XmlMoreThanOneReturnElementForMethod = 2023, - XmlMoreThanOneValyForParameterOfMethod = 2024, + XmlMoreThanOneValueForParameterOfMethod = 2024, XmlDuplicatePreserveMember = 2025, RequiresUnreferencedCode = 2026, AttributeShouldOnlyBeUsedOnceOnMember = 2027, @@ -186,6 +186,7 @@ public enum DiagnosticId DynamicallyAccessedMembersOnTypeReferencesCompilerGeneratedMember = 2119, DynamicallyAccessedMembersOnTypeReferencesCompilerGeneratedMemberOnBase = 2120, RedundantSuppression = 2121, + TypeNameIsNotAssemblyQualified = 2122, // Single-file diagnostic ids. AvoidAssemblyLocationInSingleFile = 3000, diff --git a/src/tools/illink/src/ILLink.Shared/SharedStrings.resx b/src/tools/illink/src/ILLink.Shared/SharedStrings.resx index c9bb62de5263c7..8cd897a230da72 100644 --- a/src/tools/illink/src/ILLink.Shared/SharedStrings.resx +++ b/src/tools/illink/src/ILLink.Shared/SharedStrings.resx @@ -1209,4 +1209,10 @@ Invalid FeatureGuardAttribute. + + Type '{0}' is not assembly qualified. Type name strings used for dynamically accessing a type should be assembly qualified. + + + Type name is not assembly qualified. + diff --git a/src/tools/illink/src/ILLink.Shared/TrimAnalysis/RequireDynamicallyAccessedMembersAction.cs b/src/tools/illink/src/ILLink.Shared/TrimAnalysis/RequireDynamicallyAccessedMembersAction.cs index dd8e5891c37bce..862445d36aff25 100644 --- a/src/tools/illink/src/ILLink.Shared/TrimAnalysis/RequireDynamicallyAccessedMembersAction.cs +++ b/src/tools/illink/src/ILLink.Shared/TrimAnalysis/RequireDynamicallyAccessedMembersAction.cs @@ -44,7 +44,7 @@ public void Invoke (in MultiValue value, ValueWithDynamicallyAccessedMembers tar } else if (uniqueValue is SystemTypeValue systemTypeValue) { MarkTypeForDynamicallyAccessedMembers (systemTypeValue.RepresentedType, targetValue.DynamicallyAccessedMemberTypes); } else if (uniqueValue is KnownStringValue knownStringValue) { - if (!TryResolveTypeNameAndMark (knownStringValue.Contents, true, out TypeProxy foundType)) { + if (!TryResolveTypeNameAndMark (knownStringValue.Contents, needsAssemblyName: true, out TypeProxy foundType)) { // Intentionally ignore - it's not wrong for code to call Type.GetType on non-existing name, the code might expect null/exception back. } else { MarkTypeForDynamicallyAccessedMembers (foundType, targetValue.DynamicallyAccessedMemberTypes); diff --git a/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs b/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs index 2d2fed251ac8f6..1a4aebb06db48d 100644 --- a/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs +++ b/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs @@ -72,7 +72,7 @@ public void Parse (AttributeInfo xmlInfo) continue; } - CustomAttribute? customAttribute = CreateCustomAttribute (attributeNav, attributeType); + CustomAttribute? customAttribute = CreateCustomAttribute (attributeNav, attributeType, provider); if (customAttribute != null) { _context.LogMessage ($"Assigning external custom attribute '{FormatCustomAttribute (customAttribute)}' instance to '{provider}'."); customAttributesBuilder.Add (customAttribute); @@ -153,9 +153,9 @@ static string FormatCustomAttribute (CustomAttribute ca) return _context.MarkedKnownMembers.RemoveAttributeInstancesAttributeDefinition = td; } - CustomAttribute? CreateCustomAttribute (XPathNavigator nav, TypeDefinition attributeType) + CustomAttribute? CreateCustomAttribute (XPathNavigator nav, TypeDefinition attributeType, ICustomAttributeProvider provider) { - CustomAttributeArgument[] arguments = ReadCustomAttributeArguments (nav, attributeType); + CustomAttributeArgument[] arguments = ReadCustomAttributeArguments (nav, provider); MethodDefinition? constructor = FindBestMatchingConstructor (attributeType, arguments); if (constructor == null) { @@ -223,12 +223,12 @@ void ReadCustomAttributeProperties (XPathNavigator nav, TypeDefinition attribute } } - CustomAttributeArgument[] ReadCustomAttributeArguments (XPathNavigator nav, TypeDefinition attributeType) + CustomAttributeArgument[] ReadCustomAttributeArguments (XPathNavigator nav, ICustomAttributeProvider provider) { ArrayBuilder args = default; foreach (XPathNavigator argumentNav in nav.SelectChildren ("argument", string.Empty)) { - CustomAttributeArgument? caa = ReadCustomAttributeArgument (argumentNav, attributeType); + CustomAttributeArgument? caa = ReadCustomAttributeArgument (argumentNav, provider); if (caa is not null) args.Add (caa.Value); } @@ -236,9 +236,9 @@ CustomAttributeArgument[] ReadCustomAttributeArguments (XPathNavigator nav, Type return args.ToArray () ?? Array.Empty (); } - CustomAttributeArgument? ReadCustomAttributeArgument (XPathNavigator nav, IMemberDefinition memberWithAttribute) + CustomAttributeArgument? ReadCustomAttributeArgument (XPathNavigator nav, ICustomAttributeProvider provider) { - TypeReference? typeref = ResolveArgumentType (nav, memberWithAttribute); + TypeReference? typeref = ResolveArgumentType (nav, provider); if (typeref is null) return null; @@ -295,8 +295,8 @@ CustomAttributeArgument[] ReadCustomAttributeArguments (XPathNavigator nav, Type if (!typeref.IsTypeOf (WellKnownType.System_Type)) goto default; - var diagnosticContext = new DiagnosticContext (new MessageOrigin (memberWithAttribute), diagnosticsEnabled: true, _context); - if (!_context.TypeNameResolver.TryResolveTypeName (svalue, diagnosticContext, out TypeReference? type, out _)) { + var diagnosticContext = new DiagnosticContext (new MessageOrigin (provider), diagnosticsEnabled: true, _context); + if (!_context.TypeNameResolver.TryResolveTypeName (svalue, diagnosticContext, out TypeReference? type, out _, needsAssemblyName: true)) { _context.LogError (GetMessageOriginForPosition (nav), DiagnosticId.CouldNotResolveCustomAttributeTypeValue, svalue); return null; } @@ -308,7 +308,7 @@ CustomAttributeArgument[] ReadCustomAttributeArguments (XPathNavigator nav, Type var arrayArgumentIterator = nav.SelectChildren ("argument", string.Empty); ArrayBuilder elements = default; foreach (XPathNavigator elementNav in arrayArgumentIterator) { - if (ReadCustomAttributeArgument (elementNav, memberWithAttribute) is CustomAttributeArgument arg) { + if (ReadCustomAttributeArgument (elementNav, provider) is CustomAttributeArgument arg) { // To match Cecil, elements of a list that are subclasses of the list type must be boxed in the base type // e.g. object[] { 73 } translates to Cecil.CAA { Type: object[] : Value: CAA{ Type: object, Value: CAA{ Type: int, Value: 73} } } if (arg.Type == elementType) { @@ -338,14 +338,14 @@ CustomAttributeArgument[] ReadCustomAttributeArguments (XPathNavigator nav, Type return null; } - TypeReference? ResolveArgumentType (XPathNavigator nav, IMemberDefinition memberWithAttribute) + TypeReference? ResolveArgumentType (XPathNavigator nav, ICustomAttributeProvider provider) { string typeName = GetAttribute (nav, "type"); if (string.IsNullOrEmpty (typeName)) typeName = "System.String"; - var diagnosticContext = new DiagnosticContext (new MessageOrigin (memberWithAttribute), diagnosticsEnabled: true, _context); - if (!_context.TypeNameResolver.TryResolveTypeName (typeName, diagnosticContext, out TypeReference? typeref, out _)) { + var diagnosticContext = new DiagnosticContext (new MessageOrigin (provider), diagnosticsEnabled: true, _context); + if (!_context.TypeNameResolver.TryResolveTypeName (typeName, diagnosticContext, out TypeReference? typeref, out _, needsAssemblyName: false)) { _context.LogError (GetMessageOriginForPosition (nav), DiagnosticId.TypeUsedWithAttributeValueCouldNotBeFound, typeName, nav.Value); return null; } @@ -501,7 +501,7 @@ void ProcessParameters (MethodDefinition method, XPathNavigator nav) foreach (ParameterDefinition parameter in method.Parameters) { if (paramName == parameter.Name) { if (parameter.HasCustomAttributes || _attributeInfo.CustomAttributes.ContainsKey (parameter)) - LogWarning (parameterNav, DiagnosticId.XmlMoreThanOneValyForParameterOfMethod, paramName, method.GetDisplayName ()); + LogWarning (parameterNav, DiagnosticId.XmlMoreThanOneValueForParameterOfMethod, paramName, method.GetDisplayName ()); _attributeInfo.AddCustomAttributes (parameter, attributes, origins); break; } @@ -513,11 +513,15 @@ void ProcessParameters (MethodDefinition method, XPathNavigator nav) void ProcessReturnParameters (MethodDefinition method, XPathNavigator nav) { + Debug.Assert (_attributeInfo != null); bool firstAppearance = true; foreach (XPathNavigator returnNav in nav.SelectChildren ("return", string.Empty)) { if (firstAppearance) { firstAppearance = false; - PopulateAttributeInfo (method.MethodReturnType, returnNav); + var (attributes, origins) = ProcessAttributes (returnNav, method); + if (attributes != null && origins != null) { + _attributeInfo.AddCustomAttributes (method.MethodReturnType, attributes, origins); + } } else { LogWarning (returnNav, DiagnosticId.XmlMoreThanOneReturnElementForMethod, method.GetDisplayName ()); } diff --git a/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs b/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs index ab03c049415833..2cd240d292741d 100644 --- a/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs +++ b/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs @@ -45,10 +45,6 @@ using Mono.Collections.Generic; using Mono.Linker.Dataflow; -using AssemblyNameInfo = System.Reflection.Metadata.AssemblyNameInfo; -using TypeName = System.Reflection.Metadata.TypeName; -using TypeNameParseOptions = System.Reflection.Metadata.TypeNameParseOptions; - namespace Mono.Linker.Steps { diff --git a/src/tools/illink/src/linker/Linker/TypeNameResolver.WithDiagnostics.cs b/src/tools/illink/src/linker/Linker/TypeNameResolver.WithDiagnostics.cs index 24bd45aba1877f..1f321127a653c1 100644 --- a/src/tools/illink/src/linker/Linker/TypeNameResolver.WithDiagnostics.cs +++ b/src/tools/illink/src/linker/Linker/TypeNameResolver.WithDiagnostics.cs @@ -21,7 +21,7 @@ public bool TryResolveTypeName ( in DiagnosticContext diagnosticContext, [NotNullWhen (true)] out TypeReference? typeReference, [NotNullWhen (true)] out List? typeResolutionRecords, - bool needsAssemblyName = true) + bool needsAssemblyName) { typeReference = null; typeResolutionRecords = null; @@ -31,28 +31,16 @@ public bool TryResolveTypeName ( if (!TypeName.TryParse (typeNameString, out TypeName? parsedTypeName, s_typeNameParseOptions)) return false; - typeResolutionRecords = new List (); - AssemblyDefinition? typeAssembly; - if (parsedTypeName.AssemblyName is AssemblyNameInfo assemblyName) { - typeAssembly = _assemblyResolver.TryResolve (assemblyName.Name); - if (typeAssembly is null) { - typeResolutionRecords = null; - return false; - } - - typeReference = ResolveTypeName (typeAssembly, parsedTypeName, typeResolutionRecords); - if (typeReference == null) { - typeResolutionRecords = null; - } - - return typeReference != null; + if (needsAssemblyName && !IsFullyQualified (parsedTypeName)) { + diagnosticContext.AddDiagnostic (DiagnosticId.TypeNameIsNotAssemblyQualified, typeNameString); + return false; } // If parsedTypeName doesn't have an assembly name in it but it does have a namespace, // search for the type in the calling object's assembly. If not found, look in the core // assembly. ICustomAttributeProvider? provider = diagnosticContext.Origin.Provider; - typeAssembly = provider switch { + AssemblyDefinition? referencingAssembly = provider switch { AssemblyDefinition asm => asm, TypeDefinition type => type.Module?.Assembly, IMemberDefinition member => member.DeclaringType.Module.Assembly, @@ -60,30 +48,26 @@ public bool TryResolveTypeName ( _ => throw new NotSupportedException () }; - if (typeAssembly != null && TryResolveTypeName (typeAssembly, parsedTypeName, out typeReference, typeResolutionRecords)) - return true; - - // If type is not found in the caller's assembly, try in core assembly. - typeAssembly = _assemblyResolver.TryResolve (PlatformAssemblies.CoreLib); - if (typeAssembly != null && TryResolveTypeName (typeAssembly, parsedTypeName, out typeReference, typeResolutionRecords)) - return true; - - // It is common to use Type.GetType for looking if a type is available. - // If no type was found only warn and return null. - if (needsAssemblyName && provider != null) - diagnosticContext.AddDiagnostic (DiagnosticId.TypeWasNotFoundInAssemblyNorBaseLibrary, typeNameString); + if (referencingAssembly is null) + return false; - typeResolutionRecords = null; - return false; + typeResolutionRecords = new List (); + typeReference = ResolveTypeName (referencingAssembly, parsedTypeName, typeResolutionRecords); + return typeReference != null; - bool TryResolveTypeName (AssemblyDefinition assemblyDefinition, TypeName? typeName, [NotNullWhen (true)] out TypeReference? typeReference, List typeResolutionRecords) + static bool IsFullyQualified (TypeName typeName) { - typeReference = null; - if (assemblyDefinition == null) + if (typeName.AssemblyName is null) return false; - typeReference = ResolveTypeName (assemblyDefinition, typeName, typeResolutionRecords); - return typeReference != null; + if (typeName.IsConstructedGenericType) { + foreach (var typeArgument in typeName.GetGenericArguments()) { + if (!IsFullyQualified (typeArgument)) + return false; + } + } + + return true; } } } diff --git a/src/tools/illink/src/linker/Linker/TypeNameResolver.cs b/src/tools/illink/src/linker/Linker/TypeNameResolver.cs index 3bb0e4452cb2dd..55e85741274262 100644 --- a/src/tools/illink/src/linker/Linker/TypeNameResolver.cs +++ b/src/tools/illink/src/linker/Linker/TypeNameResolver.cs @@ -107,6 +107,17 @@ public bool TryResolveTypeName ( return resolvedType; } + // If it didn't resolve and wasn't assembly-qualified, we also try core library + if (topLevelTypeName.AssemblyName == null && assembly.Name.Name != PlatformAssemblies.CoreLib) { + if (_assemblyResolver.TryResolve (PlatformAssemblies.CoreLib) is AssemblyDefinition coreLib) { + resolvedType = GetSimpleTypeFromModule (typeName, coreLib.MainModule); + if (resolvedType != null) { + typeResolutionRecords.Add (new (coreLib, resolvedType)); + return resolvedType; + } + } + } + return null; TypeDefinition? GetSimpleTypeFromModule (TypeName typeName, ModuleDefinition module) diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/ComponentModel/TypeConverterOnMembers.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/ComponentModel/TypeConverterOnMembers.cs index 99cedbb69de385..ad9b4907cbb3d2 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/ComponentModel/TypeConverterOnMembers.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/ComponentModel/TypeConverterOnMembers.cs @@ -45,8 +45,8 @@ public OnProperty () [Kept] [KeptAttributeAttribute (typeof (TypeConverterAttribute))] [KeptBackingField] - [ExpectedWarning ("IL2105", - "Type 'NonExistentType' was not found in the caller assembly nor in the base library. " + + [ExpectedWarning ("IL2122", + "Type 'NonExistentType' is not assembly qualified. " + "Type name strings used for dynamically accessing a type should be assembly qualified.")] public string Bar { [Kept] get; set; } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ApplyTypeAnnotations.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ApplyTypeAnnotations.cs index 29ac004666c38e..5f4023752387ac 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ApplyTypeAnnotations.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ApplyTypeAnnotations.cs @@ -78,7 +78,7 @@ private void PrivateMethod () { } [Kept] static void TestFromStringContantWithAnnotation () { - RequireCombinationOnString ("Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithAnnotationTestType"); + RequireCombinationOnString ("Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithAnnotationTestType, test"); } [Kept] @@ -188,10 +188,19 @@ class FromStringConstantWithGenericTwoParameters [UnconditionalSuppressMessage("test", "IL3050", Justification = "The test applies DAM on System.Array, which contains CreateInstance method which has RDC on it.")] static void TestFromStringConstantWithGeneric () { - RequireCombinationOnString ("Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGeneric`1[[Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGenericInner]]"); - RequireCombinationOnString ("Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGenericTwoParameters`2[Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGenericInnerOne`1[Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGenericInnerInner],Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGenericInnerTwo]"); - RequireCombinationOnString ("Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGeneric`1[[Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWitGenericInnerMultiDimArray[,]]]"); - RequireCombinationOnString ("Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithMultiDimArray[,]"); + RequireCombinationOnString ("Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGeneric`1[" + + "[Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGenericInner, test]" + + "], test"); + RequireCombinationOnString ("Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGenericTwoParameters`2[" + + "[Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGenericInnerOne`1[" + + "[Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGenericInnerInner, test]" + + "], test]," + + "[Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGenericInnerTwo, test]" + + "], test"); + RequireCombinationOnString ("Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGeneric`1[" + + "[Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWitGenericInnerMultiDimArray[,], test]" + + "], test"); + RequireCombinationOnString ("Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithMultiDimArray[,], test"); } [Kept] @@ -205,7 +214,9 @@ class FromStringConstantWithGenericAndAssemblyQualified [Kept] static void TestFromStringConstantWithGenericAndAssemblyQualified () { - RequireCombinationOnString ("Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGenericAndAssemblyQualified`1[[Mono.Linker.Tests.Cases.Expectations.Assertions.KeptAttribute,Mono.Linker.Tests.Cases.Expectations]]"); + RequireCombinationOnString ("Mono.Linker.Tests.Cases.DataFlow.ApplyTypeAnnotations+FromStringConstantWithGenericAndAssemblyQualified`1[" + + "[Mono.Linker.Tests.Cases.Expectations.Assertions.KeptAttribute, Mono.Linker.Tests.Cases.Expectations]" + + "], test"); } class InvalidAssemblyNameType diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AssemblyQualifiedNameDataflow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AssemblyQualifiedNameDataflow.cs index 4a3689cda9e6b9..c32a472e625bcc 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AssemblyQualifiedNameDataflow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AssemblyQualifiedNameDataflow.cs @@ -58,7 +58,7 @@ static void TestConstructors () RequireNothing (type); } - [ExpectedWarning ("IL2105", "Type 'System.Invalid.TypeName' was not found in the caller assembly nor in the base library. " + "Type name strings used for dynamically accessing a type should be assembly qualified.", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] + [ExpectedWarning ("IL2122", "Type 'System.Invalid.TypeName' is not assembly qualified. " + "Type name strings used for dynamically accessing a type should be assembly qualified.", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] static void TestUnqualifiedTypeNameWarns () { RequirePublicConstructors ("System.Invalid.TypeName"); diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributeConstructorDataflow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributeConstructorDataflow.cs index b4e991b9928cde..c2e5fd1367734e 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributeConstructorDataflow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributeConstructorDataflow.cs @@ -22,7 +22,7 @@ class AttributeConstructorDataflow [KeptAttributeAttribute (typeof (KeepsPublicFieldsAttribute))] [KeptAttributeAttribute (typeof (TypeArrayAttribute))] [KeepsPublicConstructor (typeof (ClassWithKeptPublicConstructor))] - [KeepsPublicMethods ("Mono.Linker.Tests.Cases.DataFlow.AttributeConstructorDataflow+ClassWithKeptPublicMethods")] + [KeepsPublicMethods ("Mono.Linker.Tests.Cases.DataFlow.AttributeConstructorDataflow+ClassWithKeptPublicMethods, test")] [KeepsPublicFields (null, null)] [TypeArray (new Type[] { typeof (AttributeConstructorDataflow) })] [ExpectedWarning ("IL2026", "--ClassWithKeptPublicMethods--", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/linker/issues/2273")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributeFieldDataflow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributeFieldDataflow.cs index 7d0a08861b5990..e7683d1f33806a 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributeFieldDataflow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributeFieldDataflow.cs @@ -40,9 +40,8 @@ public static void TestKeepsPublicMethods () [Kept] [KeptAttributeAttribute (typeof (KeepsPublicMethodsAttribute))] - // Trimmer/NativeAot only for now - https://github.com/dotnet/linker/issues/2273 [ExpectedWarning ("IL2026", "--ClassWithKeptPublicMethods--", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] - [KeepsPublicMethods (TypeName = "Mono.Linker.Tests.Cases.DataFlow.AttributeFieldDataflow+ClassWithKeptPublicMethods")] + [KeepsPublicMethods (TypeName = "Mono.Linker.Tests.Cases.DataFlow.AttributeFieldDataflow+ClassWithKeptPublicMethods, test")] public static void TestKeepsPublicMethodsString () { typeof (AttributeFieldDataflow).GetMethod (nameof (TestKeepsPublicMethodsString)).GetCustomAttribute (typeof (KeepsPublicMethodsAttribute)); diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributePropertyDataflow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributePropertyDataflow.cs index e56d961102c4b0..de7186fc7f54a4 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributePropertyDataflow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributePropertyDataflow.cs @@ -57,7 +57,7 @@ public static void TestKeepsPublicMethods () [KeptAttributeAttribute (typeof (KeepsPublicMethodsAttribute))] // Trimmer/NativeAot only for now [ExpectedWarning ("IL2026", "--ClassWithKeptPublicMethodsKeptByName--", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] - [KeepsPublicMethods (TypeName = "Mono.Linker.Tests.Cases.DataFlow.AttributePropertyDataflow+AttributesOnMethod+ClassWithKeptPublicMethodsKeptByName")] + [KeepsPublicMethods (TypeName = "Mono.Linker.Tests.Cases.DataFlow.AttributePropertyDataflow+AttributesOnMethod+ClassWithKeptPublicMethodsKeptByName, test")] public static void TestKeepsPublicMethodsByName () { typeof (AttributesOnMethod).GetMethod (nameof (TestKeepsPublicMethodsByName)).GetCustomAttribute (typeof (KeepsPublicMethodsAttribute)); @@ -213,7 +213,7 @@ class AttributeWithConditionalExpression [KeptAttributeAttribute (typeof (KeepsPublicMethodsAttribute))] // Trimmer/NativeAot only for now [ExpectedWarning ("IL2026", "--ClassWithKeptPublicMethods--", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] - [KeepsPublicMethods (TypeName = 1 + 1 == 2 ? "Mono.Linker.Tests.Cases.DataFlow.AttributePropertyDataflow+AttributeWithConditionalExpression+ClassWithKeptPublicMethods" : null)] + [KeepsPublicMethods (TypeName = 1 + 1 == 2 ? "Mono.Linker.Tests.Cases.DataFlow.AttributePropertyDataflow+AttributeWithConditionalExpression+ClassWithKeptPublicMethodsKeptByName, test" : null)] public static void Test () { typeof (AttributeWithConditionalExpression).GetMethod ("Test").GetCustomAttribute (typeof (KeepsPublicMethodsAttribute)); @@ -225,11 +225,11 @@ public static void Test () [Kept] [KeptAttributeAttribute (typeof (KeepsPublicMethodsAttribute))] [ExpectedWarning ("IL2026", "--ClassWithKeptPublicMethods--", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] - [KeepsPublicMethods (TypeName = 1 + 1 == 2 ? "Mono.Linker.Tests.Cases.DataFlow.AttributePropertyDataflow+AttributeWithConditionalExpression+ClassWithKeptPublicMethods" : null)] + [KeepsPublicMethods (TypeName = 1 + 1 == 2 ? "Mono.Linker.Tests.Cases.DataFlow.AttributePropertyDataflow+AttributeWithConditionalExpression+ClassWithKeptPublicMethodsKeptByName, test" : null)] public static int field; [Kept] - class ClassWithKeptPublicMethods + class ClassWithKeptPublicMethodsKeptByName { [Kept] [KeptAttributeAttribute (typeof (RequiresUnreferencedCodeAttribute))] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/GenericParameterWarningLocation.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/GenericParameterWarningLocation.cs index 560560df1223d0..f28802c174d116 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/GenericParameterWarningLocation.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/GenericParameterWarningLocation.cs @@ -1372,29 +1372,32 @@ class AnnotatedString { static void MethodWithAnnotatedParameter ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] string typeName) { } - // Analyzer: https://github.com/dotnet/runtime/issues/95118 - [ExpectedWarning ("IL2026", "TypeWithRUCMethod.PrivateRUCMethod", Tool.Trimmer | Tool.NativeAot, "")] + [ExpectedWarning ("IL2026", "TypeWithRUCMethod.PrivateRUCMethod", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] static void AnnotatedParameter () { - MethodWithAnnotatedParameter ("Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithPrivateMethods`1[[Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithRUCMethod]]"); + MethodWithAnnotatedParameter ("Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithPrivateMethods`1[[" + + "Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithRUCMethod, test" + + "]], test"); } - // Analyzer: https://github.com/dotnet/runtime/issues/95118 - [ExpectedWarning ("IL2026", "TypeWithRUCMethod.PrivateRUCMethod", Tool.Trimmer | Tool.NativeAot, "")] + [ExpectedWarning ("IL2026", "TypeWithRUCMethod.PrivateRUCMethod", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] static string AnnotatedReturnValue () { - return "Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithPrivateMethods`1[[Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithRUCMethod]]"; + return "Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithPrivateMethods`1[[" + + "Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithRUCMethod, test" + + "]], test"; } [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] static string _annotatedField; - // Analyzer: https://github.com/dotnet/runtime/issues/95118 - [ExpectedWarning ("IL2026", "TypeWithRUCMethod.PrivateRUCMethod", Tool.Trimmer | Tool.NativeAot, "")] + [ExpectedWarning ("IL2026", "TypeWithRUCMethod.PrivateRUCMethod", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] static void AnnotatedField () { - _annotatedField = "Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithPrivateMethods`1[[Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithRUCMethod]]"; + _annotatedField = "Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithPrivateMethods`1[[" + + "Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithRUCMethod, test" + + "]], test"; } public static void Test () @@ -1407,11 +1410,12 @@ public static void Test () class TypeGetType { - // Analyzer: https://github.com/dotnet/runtime/issues/95118 - [ExpectedWarning ("IL2026", "TypeWithRUCMethod.PrivateRUCMethod", Tool.Trimmer | Tool.NativeAot, "")] + [ExpectedWarning ("IL2026", "TypeWithRUCMethod.PrivateRUCMethod", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] static void SpecificType () { - Type.GetType ("Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithPrivateMethods`1[[Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithRUCMethod]]"); + Type.GetType ("Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithPrivateMethods`1[[" + + "Mono.Linker.Tests.Cases.DataFlow.GenericParameterWarningLocation+MethodBody+TypeWithRUCMethod" + + "]]"); } public static void Test () diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/Dependencies/EscapedTypeNames.il b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/Dependencies/EscapedTypeNames.il index 392f5903be75eb..0dc9cabc2859ab 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/Dependencies/EscapedTypeNames.il +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/Dependencies/EscapedTypeNames.il @@ -3,12 +3,12 @@ { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: } -.assembly 'library' +.assembly 'EscapedTypeNames' { .hash algorithm 0x00008004 .ver 1:0:0:0 } -.module library.dll +.module EscapedTypeNames.dll // =============== CLASS MEMBERS DECLARATION =================== diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/Dependencies/RequireHelper.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/Dependencies/RequireHelper.cs new file mode 100644 index 00000000000000..0d83320a8f3992 --- /dev/null +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/Dependencies/RequireHelper.cs @@ -0,0 +1,14 @@ +using System; +using System.Diagnostics.CodeAnalysis; + +namespace Mono.Linker.Tests.Cases.Reflection.Dependencies +{ + public class RequireHelper + { + public static Type RequireType ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string type) { + return Type.GetType (type); + } + } + + public class TypeDefinedInSameAssemblyAsGetType {} +} diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs index dcf6be970e8197..9c82ee3aac3b74 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs @@ -4,16 +4,19 @@ using Mono.Linker.Tests.Cases.Expectations.Assertions; using Mono.Linker.Tests.Cases.Expectations.Helpers; using Mono.Linker.Tests.Cases.Expectations.Metadata; +using Mono.Linker.Tests.Cases.Reflection.Dependencies; namespace Mono.Linker.Tests.Cases.Reflection { [KeptMember (".cctor()")] [ExpectedNoWarnings ()] [Define ("IL_ASSEMBLY_AVAILABLE")] - [SetupCompileBefore ("library.dll", new[] { "Dependencies/EscapedTypeNames.il" })] - [KeptTypeInAssembly ("library", "Library.Not\\+Nested")] - [KeptTypeInAssembly ("library", "Library.Not\\+Nested+Nes\\\\ted")] - [KeptTypeInAssembly ("library", "Library.Not\\+Nested+Nes/ted")] + [SetupCompileBefore ("EscapedTypeNames.dll", new[] { "Dependencies/EscapedTypeNames.il" })] + [SetupCompileBefore ("RequireHelper.dll", new[] { "Dependencies/RequireHelper.cs" })] + [KeptTypeInAssembly ("EscapedTypeNames", "Library.Not\\+Nested")] + [KeptTypeInAssembly ("EscapedTypeNames", "Library.Not\\+Nested+Nes\\\\ted")] + [KeptTypeInAssembly ("EscapedTypeNames", "Library.Not\\+Nested+Nes/ted")] + [RemovedTypeInAssembly ("RequireHelper", typeof (TypeDefinedInSameAssemblyAsGetType))] [KeptDelegateCacheField ("0", nameof (AssemblyResolver))] [KeptDelegateCacheField ("1", nameof (GetTypeFromAssembly))] public class TypeUsedViaReflection @@ -55,6 +58,7 @@ public static void Main () TestInvalidTypeCombination (); TestEscapedTypeName (); + AssemblyTypeResolutionBehavior.Test (); } [Kept] @@ -475,9 +479,42 @@ static void TestInvalidTypeCombination () [Kept] static void TestEscapedTypeName () { - var typeKept = Type.GetType ("Library.Not\\+Nested, library"); - typeKept = Type.GetType ("Library.Not\\+Nested+Nes\\\\ted, library"); - typeKept = Type.GetType ("Library.Not\\+Nested+Nes/ted, library"); + var typeKept = Type.GetType ("Library.Not\\+Nested, EscapedTypeNames"); + typeKept = Type.GetType ("Library.Not\\+Nested+Nes\\\\ted, EscapedTypeNames"); + typeKept = Type.GetType ("Library.Not\\+Nested+Nes/ted, EscapedTypeNames"); + } + + [Kept] + class AssemblyTypeResolutionBehavior + { + [Kept] + [ExpectedWarning ("IL2122")] + static void TestRequireTypeInSameAssemblyAsGetType () { + RequireHelper.RequireType ("Mono.Linker.Tests.Cases.Reflection.Dependencies.TypeDefinedInSameAssemblyAsGetType"); + } + + [Kept] + [ExpectedWarning ("IL2122")] + static void TestRequireTypeInSameAssemblyAsCallToRequireType () { + RequireHelper.RequireType ("Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+TypeDefinedInSameAssemblyAsCallToRequireType"); + } + + [Kept] + [ExpectedWarning ("IL2122")] + static void TestRequireTypeWithNonAssemblyQualifiedGenericArguments () { + RequireHelper.RequireType ("Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+Generic`1[[System.Int32]], test"); + } + + [Kept] + public static void Test () { + TestRequireTypeInSameAssemblyAsGetType (); + TestRequireTypeInSameAssemblyAsCallToRequireType (); + TestRequireTypeWithNonAssemblyQualifiedGenericArguments (); + } + + class TypeDefinedInSameAssemblyAsCallToRequireType {} + + class Generic {} } } } From 5be10637d69eb628c6d38698059fdfde5d8b1b41 Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Wed, 26 Jun 2024 21:58:40 +0000 Subject: [PATCH 02/11] Add test for generic over corelib type --- .../Reflection/TypeUsedViaReflection.cs | 45 ++++++++++++------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs index 9c82ee3aac3b74..fca736d6af8128 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs @@ -34,8 +34,9 @@ public static void Main () TestReference (); TestArray (); TestArrayOfArray (); - TestGenericArray (); - TestGenericArrayFullString (); + TestGenericInstantiation (); + TestGenericInstantiationFullString (); + TestGenericInstantiationOverCoreLib (); TestMultiDimensionalArray (); TestMultiDimensionalArrayFullString (); TestMultiDimensionalArrayAsmName (); @@ -96,30 +97,42 @@ public static void TestGenericString () } [Kept] - public class GenericArray { } + public class GenericInstantiation { } [Kept] public class GenericArgument { } [Kept] - public static void TestGenericArray () + public static void TestGenericInstantiation () { - const string reflectionTypeKeptString = "Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+GenericArray`1[[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+GenericArgument]]"; + const string reflectionTypeKeptString = "Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+GenericInstantiation`1[[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+GenericArgument]]"; var typeKept = Type.GetType (reflectionTypeKeptString, false); } [Kept] - public class GenericArrayFullString { } + public class GenericInstantiationFullString { } [Kept] public class GenericArgumentFullString { } [Kept] - public static void TestGenericArrayFullString () + public static void TestGenericInstantiationFullString () { - const string reflectionTypeKeptString = "Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+GenericArrayFullString`1" + - "[[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+GenericArgumentFullString, test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]," + - " test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"; + const string reflectionTypeKeptString = "Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+GenericInstantiationFullString`1[" + + "[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+GenericArgumentFullString, test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]" + + "], test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"; + var typeKept = Type.GetType (reflectionTypeKeptString, false); + } + + [Kept] + public class GenericInstantiationOverCoreLib { } + + [Kept] + public static void TestGenericInstantiationOverCoreLib () + { + // Note: the argument type should not be assembly-qualified for this test, which is checking that + // we can resolve non-assembly-qualified generic argument types from corelib. + const string reflectionTypeKeptString = "Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+GenericInstantiationOverCoreLib`1[[System.String]], test"; var typeKept = Type.GetType (reflectionTypeKeptString, false); } @@ -424,9 +437,9 @@ private static void PrivateMethod () { } [Kept] static void TestGenericTypeWithAnnotations () { - const string reflectionTypeKeptString = "Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+GenericTypeWithAnnotations_OuterType`1" + - "[[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+GenericTypeWithAnnotations_InnerType, test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]," + - " test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"; + const string reflectionTypeKeptString = "Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+GenericTypeWithAnnotations_OuterType`1[" + + "[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+GenericTypeWithAnnotations_InnerType, test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]" + + "], test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"; Type.GetType (reflectionTypeKeptString); } @@ -488,19 +501,19 @@ static void TestEscapedTypeName () class AssemblyTypeResolutionBehavior { [Kept] - [ExpectedWarning ("IL2122")] + [ExpectedWarning ("IL2122", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] static void TestRequireTypeInSameAssemblyAsGetType () { RequireHelper.RequireType ("Mono.Linker.Tests.Cases.Reflection.Dependencies.TypeDefinedInSameAssemblyAsGetType"); } [Kept] - [ExpectedWarning ("IL2122")] + [ExpectedWarning ("IL2122", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] static void TestRequireTypeInSameAssemblyAsCallToRequireType () { RequireHelper.RequireType ("Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+TypeDefinedInSameAssemblyAsCallToRequireType"); } [Kept] - [ExpectedWarning ("IL2122")] + [ExpectedWarning ("IL2122", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] static void TestRequireTypeWithNonAssemblyQualifiedGenericArguments () { RequireHelper.RequireType ("Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+Generic`1[[System.Int32]], test"); } From c0b9690be904d901f69bbffbf43c3bbc4a91d3ac Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Wed, 26 Jun 2024 22:10:41 +0000 Subject: [PATCH 03/11] Fix tests - Revert change to needsAssemblyName for types in attribute XML - Update SharedStrings.resx to match renamed DiagnosticId --- src/tools/illink/src/ILLink.Shared/SharedStrings.resx | 4 ++-- .../illink/src/linker/Linker.Steps/LinkAttributesParser.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/tools/illink/src/ILLink.Shared/SharedStrings.resx b/src/tools/illink/src/ILLink.Shared/SharedStrings.resx index 8cd897a230da72..3a61bafdff5a72 100644 --- a/src/tools/illink/src/ILLink.Shared/SharedStrings.resx +++ b/src/tools/illink/src/ILLink.Shared/SharedStrings.resx @@ -525,10 +525,10 @@ There is more than one 'return' child element specified for method '{0}'. - + Method has more than one parameter for the XML element 'parameter'. There can only be one value specified for each parameter. - + More than one value specified for parameter '{0}' of method '{1}'. diff --git a/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs b/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs index 1a4aebb06db48d..1309e7526d6834 100644 --- a/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs +++ b/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs @@ -296,7 +296,7 @@ CustomAttributeArgument[] ReadCustomAttributeArguments (XPathNavigator nav, ICus goto default; var diagnosticContext = new DiagnosticContext (new MessageOrigin (provider), diagnosticsEnabled: true, _context); - if (!_context.TypeNameResolver.TryResolveTypeName (svalue, diagnosticContext, out TypeReference? type, out _, needsAssemblyName: true)) { + if (!_context.TypeNameResolver.TryResolveTypeName (svalue, diagnosticContext, out TypeReference? type, out _, needsAssemblyName: false)) { _context.LogError (GetMessageOriginForPosition (nav), DiagnosticId.CouldNotResolveCustomAttributeTypeValue, svalue); return null; } From e8338e062be5093f9fbeadd7dc0cbd312ab9fcf3 Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Wed, 26 Jun 2024 22:13:58 +0000 Subject: [PATCH 04/11] Mark IL2105 as unused --- src/tools/illink/src/ILLink.Shared/DiagnosticId.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/illink/src/ILLink.Shared/DiagnosticId.cs b/src/tools/illink/src/ILLink.Shared/DiagnosticId.cs index b403d0f503c68d..849f656e89ed0a 100644 --- a/src/tools/illink/src/ILLink.Shared/DiagnosticId.cs +++ b/src/tools/illink/src/ILLink.Shared/DiagnosticId.cs @@ -169,7 +169,7 @@ public enum DiagnosticId InvalidIsTrimmableValue = 2102, PropertyAccessorParameterInLinqExpressionsCannotBeStaticallyDetermined = 2103, AssemblyProducedTrimWarnings = 2104, - TypeWasNotFoundInAssemblyNorBaseLibrary = 2105, + _unused_TypeWasNotFoundInAssemblyNorBaseLibrary = 2105, DynamicallyAccessedMembersOnMethodReturnValueCanOnlyApplyToTypesOrStrings = 2106, MethodsAreAssociatedWithStateMachine = 2107, InvalidScopeInUnconditionalSuppressMessage = 2108, From 39855301444303a87feb3992ce59f61c997ccbdb Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Wed, 26 Jun 2024 23:49:33 +0000 Subject: [PATCH 05/11] PR feedback - Test array/byref/pointer that's not assembly-qualified Also: - Fix ILCompiler.Trimming.Tests build - Clean up usings --- .../ILCompiler.Trimming.Tests.csproj | 1 + .../TypeNameResolver.WithDiagnostics.cs | 2 -- .../Reflection/TypeUsedViaReflection.cs | 33 +++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/ILCompiler.Trimming.Tests.csproj b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/ILCompiler.Trimming.Tests.csproj index de47993ee6f56b..e5e9ef8930b9fd 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/ILCompiler.Trimming.Tests.csproj +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/ILCompiler.Trimming.Tests.csproj @@ -26,6 +26,7 @@ + diff --git a/src/tools/illink/src/linker/Linker/TypeNameResolver.WithDiagnostics.cs b/src/tools/illink/src/linker/Linker/TypeNameResolver.WithDiagnostics.cs index 1f321127a653c1..562f61aa6c0770 100644 --- a/src/tools/illink/src/linker/Linker/TypeNameResolver.WithDiagnostics.cs +++ b/src/tools/illink/src/linker/Linker/TypeNameResolver.WithDiagnostics.cs @@ -7,10 +7,8 @@ using ILLink.Shared; using ILLink.Shared.TrimAnalysis; using Mono.Cecil; -using Mono.Linker; using TypeName = System.Reflection.Metadata.TypeName; -using AssemblyNameInfo = System.Reflection.Metadata.AssemblyNameInfo; namespace Mono.Linker { diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs index fca736d6af8128..f5495443335aac 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs @@ -518,16 +518,49 @@ static void TestRequireTypeWithNonAssemblyQualifiedGenericArguments () { RequireHelper.RequireType ("Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+Generic`1[[System.Int32]], test"); } + [Kept] + [ExpectedWarning ("IL2122", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] + static void TestRequireTypeWithNonAssemblyQualifiedArrayType () { + RequireHelper.RequireType ("Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+Generic`1[" + + "[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+ArrayElementType[]]" + + "], test"); + } + + [Kept] + [ExpectedWarning ("IL2122", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] + static void TestRequireTypeWithNonAssemblyQualifiedPointerType () { + RequireHelper.RequireType ("Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+Generic`1[" + + "[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+PointerElementType*]" + + "], test"); + } + + [Kept] + [ExpectedWarning ("IL2122", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] + static void TestRequireTypeWithNonAssemblyQualifiedByRefType () { + RequireHelper.RequireType ("Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+Generic`1[" + + "[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+ByRefElementType&]" + + "], test"); + } + [Kept] public static void Test () { TestRequireTypeInSameAssemblyAsGetType (); TestRequireTypeInSameAssemblyAsCallToRequireType (); TestRequireTypeWithNonAssemblyQualifiedGenericArguments (); + TestRequireTypeWithNonAssemblyQualifiedArrayType (); + TestRequireTypeWithNonAssemblyQualifiedPointerType (); + TestRequireTypeWithNonAssemblyQualifiedByRefType (); } class TypeDefinedInSameAssemblyAsCallToRequireType {} class Generic {} + + class ArrayElementType {} + + class PointerElementType {} + + class ByRefElementType {} } } } From 781674448877ff1abe43b51f0b081731680fe80c Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Thu, 27 Jun 2024 16:54:01 +0000 Subject: [PATCH 06/11] PR feedback - Fix check for array/pointer/byref types, update tests --- .../Utilities/CustomAttributeTypeNameParser.cs | 5 +++++ .../Linker/TypeNameResolver.WithDiagnostics.cs | 5 ++++- .../Reflection/TypeUsedViaReflection.cs | 18 +++++++++--------- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameParser.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameParser.cs index 1fb3df94dac0a1..b3a72baf41c411 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameParser.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameParser.cs @@ -66,6 +66,11 @@ static bool IsFullyQualified (TypeName typeName) return false; } + if (typeName.IsArray || typeName.IsPointer || typeName.IsByRef) + { + return IsFullyQualified(typeName.GetElementType()); + } + if (typeName.IsConstructedGenericType) { foreach (var typeArgument in typeName.GetGenericArguments()) diff --git a/src/tools/illink/src/linker/Linker/TypeNameResolver.WithDiagnostics.cs b/src/tools/illink/src/linker/Linker/TypeNameResolver.WithDiagnostics.cs index 562f61aa6c0770..51f71ee39fb94d 100644 --- a/src/tools/illink/src/linker/Linker/TypeNameResolver.WithDiagnostics.cs +++ b/src/tools/illink/src/linker/Linker/TypeNameResolver.WithDiagnostics.cs @@ -58,8 +58,11 @@ static bool IsFullyQualified (TypeName typeName) if (typeName.AssemblyName is null) return false; + if (typeName.IsArray || typeName.IsPointer || typeName.IsByRef) + return IsFullyQualified (typeName.GetElementType ()); + if (typeName.IsConstructedGenericType) { - foreach (var typeArgument in typeName.GetGenericArguments()) { + foreach (var typeArgument in typeName.GetGenericArguments ()) { if (!IsFullyQualified (typeArgument)) return false; } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs index f5495443335aac..9dc4df8ff039cd 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeUsedViaReflection.cs @@ -522,24 +522,24 @@ static void TestRequireTypeWithNonAssemblyQualifiedGenericArguments () { [ExpectedWarning ("IL2122", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] static void TestRequireTypeWithNonAssemblyQualifiedArrayType () { RequireHelper.RequireType ("Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+Generic`1[" - + "[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+ArrayElementType[]]" - + "], test"); + + "[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+ArrayElementGenericArgumentType]" + + "][], test"); } [Kept] [ExpectedWarning ("IL2122", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] static void TestRequireTypeWithNonAssemblyQualifiedPointerType () { RequireHelper.RequireType ("Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+Generic`1[" - + "[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+PointerElementType*]" - + "], test"); + + "[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+PointerElementGenericArgumentType]" + + "]*, test"); } [Kept] [ExpectedWarning ("IL2122", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/95118")] static void TestRequireTypeWithNonAssemblyQualifiedByRefType () { RequireHelper.RequireType ("Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+Generic`1[" - + "[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+ByRefElementType&]" - + "], test"); + + "[Mono.Linker.Tests.Cases.Reflection.TypeUsedViaReflection+AssemblyTypeResolutionBehavior+ByRefElementGenericArgumentType]" + + "]&, test"); } [Kept] @@ -556,11 +556,11 @@ class TypeDefinedInSameAssemblyAsCallToRequireType {} class Generic {} - class ArrayElementType {} + class ArrayElementGenericArgumentType {} - class PointerElementType {} + class PointerElementGenericArgumentType {} - class ByRefElementType {} + class ByRefElementGenericArgumentType {} } } } From f02bf627881d9b6180a43f305c42b0f1a777e334 Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Thu, 27 Jun 2024 17:34:16 +0000 Subject: [PATCH 07/11] Use System.Runtime as system module in library mode --- .../src/linker/Linker.Steps/LinkAttributesParser.cs | 2 +- .../illink/src/linker/Linker.Steps/MarkStep.cs | 2 +- .../linker/Linker.Steps/RootAssemblyInputStep.cs | 3 +++ src/tools/illink/src/linker/Linker/LinkContext.cs | 13 +++++++------ .../illink/src/linker/Linker/PlatformAssemblies.cs | 10 ---------- .../illink/src/linker/Linker/TypeNameResolver.cs | 12 +++++++----- .../TestCasesRunner/ResultChecker.cs | 3 ++- 7 files changed, 21 insertions(+), 24 deletions(-) delete mode 100644 src/tools/illink/src/linker/Linker/PlatformAssemblies.cs diff --git a/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs b/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs index 1309e7526d6834..47ba941c640be4 100644 --- a/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs +++ b/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs @@ -447,7 +447,7 @@ protected override AllowedAssemblies AllowedAssemblySelector { return AllowedAssemblies.AllAssemblies; // Corelib XML may contain assembly wildcard to support compiler-injected attribute types - if (_resource?.Assembly.Name.Name == PlatformAssemblies.CoreLib) + if (_resource?.Assembly.Name.Name == _context.SystemModuleName) return AllowedAssemblies.AllAssemblies; return AllowedAssemblies.ContainingAssembly; diff --git a/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs b/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs index 2cd240d292741d..9dc826aadd0313 100644 --- a/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs +++ b/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs @@ -257,7 +257,7 @@ void InitializeCorelibAttributeXml () // corelib attribute XML can contain modifications to other assemblies. // We could just mark it here, but the attribute processing isn't necessarily tied to marking, // so this would rely on implementation details of corelib. - var coreLib = Context.TryResolve (PlatformAssemblies.CoreLib); + var coreLib = Context.TryResolve (Context.SystemModuleName); if (coreLib == null) return; diff --git a/src/tools/illink/src/linker/Linker.Steps/RootAssemblyInputStep.cs b/src/tools/illink/src/linker/Linker.Steps/RootAssemblyInputStep.cs index b167ed5f58be20..2cb513d5f76eef 100644 --- a/src/tools/illink/src/linker/Linker.Steps/RootAssemblyInputStep.cs +++ b/src/tools/illink/src/linker/Linker.Steps/RootAssemblyInputStep.cs @@ -86,6 +86,9 @@ protected override void Process () // No metadata trimming Context.MetadataTrimming = MetadataTrimming.None; + + // Library mode builds against System.Runtime ref assembly + Context.SystemModuleName = "System.Runtime"; break; case AssemblyRootMode.AllMembers: Annotations.SetRootAssembly (assembly); diff --git a/src/tools/illink/src/linker/Linker/LinkContext.cs b/src/tools/illink/src/linker/Linker/LinkContext.cs index 31733b0c6ad565..dc0ebb69047401 100644 --- a/src/tools/illink/src/linker/Linker/LinkContext.cs +++ b/src/tools/illink/src/linker/Linker/LinkContext.cs @@ -68,7 +68,7 @@ public class LinkContext : IMetadataResolver, ITryResolveMetadata, ITryResolveAs int? _targetRuntime; readonly AssemblyResolver _resolver; - readonly TypeNameResolver _typeNameResolver; + TypeNameResolver? _typeNameResolver; readonly AnnotationStore _annotations; readonly CustomAttributeSource _customAttributes; @@ -146,9 +146,8 @@ public AssemblyResolver Resolver { get { return _resolver; } } - internal TypeNameResolver TypeNameResolver { - get { return _typeNameResolver; } - } + internal TypeNameResolver TypeNameResolver + => _typeNameResolver ??= new TypeNameResolver (this, this, this.SystemModuleName); public ISymbolReaderProvider SymbolReaderProvider { get; set; } @@ -194,6 +193,8 @@ internal TypeNameResolver TypeNameResolver { public SerializationMarker SerializationMarker { get; } + public string SystemModuleName { get; set; } + public LinkContext (Pipeline pipeline, ILogger logger, string outputDirectory) : this(pipeline, logger, outputDirectory, new UnintializedContextFactory ()) { @@ -205,7 +206,6 @@ protected LinkContext (Pipeline pipeline, ILogger logger, string outputDirectory _logger = logger ?? throw new ArgumentNullException (nameof (logger)); _resolver = factory.CreateResolver (this); - _typeNameResolver = new TypeNameResolver (this, this); _actions = new Dictionary (); _parameters = new Dictionary (StringComparer.Ordinal); _customAttributes = new CustomAttributeSource (this); @@ -252,6 +252,7 @@ protected LinkContext (Pipeline pipeline, ILogger logger, string outputDirectory DisableEventSourceSpecialHandling = true; Optimizations = new CodeOptimizationsSettings (defaultOptimizations); + SystemModuleName = "System.Private.CoreLib"; } public void SetFeatureValue (string feature, bool value) @@ -973,7 +974,7 @@ public int GetTargetRuntimeVersion () public TypeDefinition? TryResolve (AssemblyDefinition assembly, string typeNameString) { // It could be cached if it shows up on fast path - return _typeNameResolver.TryResolveTypeName (assembly, typeNameString, out TypeReference? typeReference, out _) + return TypeNameResolver.TryResolveTypeName (assembly, typeNameString, out TypeReference? typeReference, out _) ? TryResolve (typeReference) : null; } diff --git a/src/tools/illink/src/linker/Linker/PlatformAssemblies.cs b/src/tools/illink/src/linker/Linker/PlatformAssemblies.cs deleted file mode 100644 index b93f120844e051..00000000000000 --- a/src/tools/illink/src/linker/Linker/PlatformAssemblies.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) .NET Foundation and contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace Mono.Linker -{ - public static class PlatformAssemblies - { - public const string CoreLib = "System.Private.CoreLib"; - } -} diff --git a/src/tools/illink/src/linker/Linker/TypeNameResolver.cs b/src/tools/illink/src/linker/Linker/TypeNameResolver.cs index 55e85741274262..62b0d373f150e2 100644 --- a/src/tools/illink/src/linker/Linker/TypeNameResolver.cs +++ b/src/tools/illink/src/linker/Linker/TypeNameResolver.cs @@ -19,15 +19,17 @@ internal sealed partial class TypeNameResolver { readonly ITryResolveMetadata _metadataResolver; readonly ITryResolveAssemblyName _assemblyResolver; + readonly string _systemModuleName; private static readonly TypeNameParseOptions s_typeNameParseOptions = new () { MaxNodes = int.MaxValue }; public readonly record struct TypeResolutionRecord (AssemblyDefinition ReferringAssembly, TypeDefinition ResolvedType); - public TypeNameResolver (ITryResolveMetadata metadataResolver, ITryResolveAssemblyName assemblyNameResolver) + public TypeNameResolver (ITryResolveMetadata metadataResolver, ITryResolveAssemblyName assemblyNameResolver, string systemModuleName) { _metadataResolver = metadataResolver; _assemblyResolver = assemblyNameResolver; + _systemModuleName = systemModuleName; } public bool TryResolveTypeName ( @@ -108,11 +110,11 @@ public bool TryResolveTypeName ( } // If it didn't resolve and wasn't assembly-qualified, we also try core library - if (topLevelTypeName.AssemblyName == null && assembly.Name.Name != PlatformAssemblies.CoreLib) { - if (_assemblyResolver.TryResolve (PlatformAssemblies.CoreLib) is AssemblyDefinition coreLib) { - resolvedType = GetSimpleTypeFromModule (typeName, coreLib.MainModule); + if (topLevelTypeName.AssemblyName == null && assembly.Name.Name != _systemModuleName) { + if (_assemblyResolver.TryResolve (_systemModuleName) is AssemblyDefinition systemModule) { + resolvedType = GetSimpleTypeFromModule (typeName, systemModule.MainModule); if (resolvedType != null) { - typeResolutionRecords.Add (new (coreLib, resolvedType)); + typeResolutionRecords.Add (new (systemModule, resolvedType)); return resolvedType; } } diff --git a/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ResultChecker.cs b/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ResultChecker.cs index f6480e554c3528..513a6d78e5f3b1 100644 --- a/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ResultChecker.cs +++ b/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ResultChecker.cs @@ -14,6 +14,7 @@ using Mono.Cecil.Cil; using Mono.Linker; using Mono.Linker.Tests.Cases.Expectations.Assertions; +using Mono.Linker.Tests.Cases.Expectations.Helpers; using Mono.Linker.Tests.Cases.Expectations.Metadata; using Mono.Linker.Tests.Extensions; using Mono.Linker.Tests.TestCasesRunner.ILVerification; @@ -47,7 +48,7 @@ public ResultChecker (BaseAssemblyResolver originalsResolver, BaseAssemblyResolv { _originalsResolver = originalsResolver; _linkedResolver = linkedResolver; - _linkedTypeNameResolver = new TypeNameResolver (new TestResolver (), new TestAssemblyNameResolver (_linkedResolver)); + _linkedTypeNameResolver = new TypeNameResolver (new TestResolver (), new TestAssemblyNameResolver (_linkedResolver), PlatformAssemblies.CoreLib); _originalReaderParameters = originalReaderParameters; _linkedReaderParameters = linkedReaderParameters; } From e48b9402f23855cce6a22bf69285b141470741a8 Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Thu, 27 Jun 2024 18:33:27 +0000 Subject: [PATCH 08/11] Fix ApiCompat --- .../illink/src/linker/CompatibilitySuppressions.xml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/tools/illink/src/linker/CompatibilitySuppressions.xml b/src/tools/illink/src/linker/CompatibilitySuppressions.xml index af38ca258f95ba..c027ee4c6681a6 100644 --- a/src/tools/illink/src/linker/CompatibilitySuppressions.xml +++ b/src/tools/illink/src/linker/CompatibilitySuppressions.xml @@ -1509,6 +1509,12 @@ ref/net9.0/illink.dll lib/net9.0/illink.dll + + CP0002 + M:Mono.Linker.LinkContext.get_SystemModuleName + ref/net9.0/illink.dll + lib/net9.0/illink.dll + CP0002 M:Mono.Linker.LinkContext.set_KeepComInterfaces(System.Boolean) @@ -1521,6 +1527,12 @@ ref/net9.0/illink.dll lib/net9.0/illink.dll + + CP0002 + M:Mono.Linker.LinkContext.set_SystemModuleName(System.String) + ref/net9.0/illink.dll + lib/net9.0/illink.dll + CP0008 T:Mono.Linker.LinkContext From 970d2c4f70ef363ea229eb4d5fb918bc7ebb8b32 Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Thu, 27 Jun 2024 21:13:47 +0000 Subject: [PATCH 09/11] Various fixes - Fix ILCompiler.Trimming.Tests build - Replace IL2105 suppressions with IL2122 - Fix trimming tests that were not using fully-qualified type names --- docs/tools/illink/error-codes.md | 16 ++++++++++++++++ eng/testing/tests.mobile.targets | 2 +- eng/testing/tests.singlefile.targets | 2 +- .../ILCompiler.Trimming.Tests.csproj | 1 - .../TestCasesRunner/AssemblyChecker.cs | 3 ++- .../DebuggerTypeProxyAttributeTests.cs | 2 +- .../DebuggerVisualizerAttributeTests.cs | 4 ++-- .../apple/build/AppleBuild.LocalBuild.targets | 2 +- 8 files changed, 24 insertions(+), 8 deletions(-) diff --git a/docs/tools/illink/error-codes.md b/docs/tools/illink/error-codes.md index 4850f92152b874..282ff575a94489 100644 --- a/docs/tools/illink/error-codes.md +++ b/docs/tools/illink/error-codes.md @@ -1870,6 +1870,22 @@ void TestMethod() } ``` +#### `IL2122`: Type 'typeName' is not assembly qualified. Type name strings used for dynamically accessing a type should be assembly qualified. + +- The type name string passed to a location with `DynamicallyAccessedMembers` requirements was not assembly-qualified, so the trimmer cannot guarantee that the type is preserved. Consider using an assembly-qualified name instead. + + ```C# + // warning IL2122: Type 'MyClass' is not assembly qualified. Type name strings used for dynamically accessing a type should be assembly qualified. + GetTypeWrapper("MyClass"); + + class MyClass { } + + // May be defined in another assembly, so at runtime Type.GetType will look in that assembly for "MyClass". + void GetTypeWrapper([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string typeName) + { + var type = Type.GetType(typeName); + } + ``` ## Single-File Warning Codes diff --git a/eng/testing/tests.mobile.targets b/eng/testing/tests.mobile.targets index e87458abd06991..b599da5d228e6e 100644 --- a/eng/testing/tests.mobile.targets +++ b/eng/testing/tests.mobile.targets @@ -29,7 +29,7 @@ true true - $(NoWarn);IL2103;IL2105;IL2025;IL2111 + $(NoWarn);IL2103;IL2025;IL2111;IL2122 false diff --git a/eng/testing/tests.singlefile.targets b/eng/testing/tests.singlefile.targets index 9e6e4d0b3589e4..f40703bac41c39 100644 --- a/eng/testing/tests.singlefile.targets +++ b/eng/testing/tests.singlefile.targets @@ -29,7 +29,7 @@ $(CoreCLRAotSdkDir) $(NetCoreAppCurrentTestHostSharedFrameworkPath) $(NetCoreAppCurrentTestHostSharedFrameworkPath) - $(NoWarn);IL1005;IL2105;IL3000;IL3001;IL3002;IL3003;IL3050;IL3051;IL3052;IL3053 + $(NoWarn);IL1005;IL2122;IL3000;IL3001;IL3002;IL3003;IL3050;IL3051;IL3052;IL3053 partial true false diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/ILCompiler.Trimming.Tests.csproj b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/ILCompiler.Trimming.Tests.csproj index e5e9ef8930b9fd..de47993ee6f56b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/ILCompiler.Trimming.Tests.csproj +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/ILCompiler.Trimming.Tests.csproj @@ -26,7 +26,6 @@ - diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyChecker.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyChecker.cs index b2a6ea4cee9601..ab0e600091e6d2 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyChecker.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyChecker.cs @@ -12,6 +12,7 @@ using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Linker.Tests.Cases.Expectations.Assertions; +using Mono.Linker.Tests.Cases.Expectations.Helpers; using Mono.Linker.Tests.Extensions; using Xunit; using MetadataType = Internal.TypeSystem.MetadataType; @@ -70,7 +71,7 @@ public AssemblyChecker ( TrimmedTestCaseResult testResult) { this.originalsResolver = originalsResolver; - this.originalsTypeNameResolver = new TypeNameResolver (new TestResolver (), new TestAssemblyNameResolver (originalsResolver)); + this.originalsTypeNameResolver = new TypeNameResolver (new TestResolver (), new TestAssemblyNameResolver (originalsResolver), PlatformAssemblies.CoreLib); this.originalReaderParameters = originalReaderParameters; this.originalAssembly = original; this.testResult = testResult; diff --git a/src/libraries/System.Runtime/tests/System.Runtime.Tests/TrimmingTests/DebuggerTypeProxyAttributeTests.cs b/src/libraries/System.Runtime/tests/System.Runtime.Tests/TrimmingTests/DebuggerTypeProxyAttributeTests.cs index b80f4a1d61b00b..382d8edbfd8a17 100644 --- a/src/libraries/System.Runtime/tests/System.Runtime.Tests/TrimmingTests/DebuggerTypeProxyAttributeTests.cs +++ b/src/libraries/System.Runtime/tests/System.Runtime.Tests/TrimmingTests/DebuggerTypeProxyAttributeTests.cs @@ -53,7 +53,7 @@ public DebuggerProxy(MyClass instance) } } - [DebuggerTypeProxy("Program+MyClassWithProxyStringProxy")] + [DebuggerTypeProxy("Program+MyClassWithProxyStringProxy, project")] public class MyClassWithProxyString { public string Name { get; set; } diff --git a/src/libraries/System.Runtime/tests/System.Runtime.Tests/TrimmingTests/DebuggerVisualizerAttributeTests.cs b/src/libraries/System.Runtime/tests/System.Runtime.Tests/TrimmingTests/DebuggerVisualizerAttributeTests.cs index dccaf03b4dd668..51ace3fa295a5d 100644 --- a/src/libraries/System.Runtime/tests/System.Runtime.Tests/TrimmingTests/DebuggerVisualizerAttributeTests.cs +++ b/src/libraries/System.Runtime/tests/System.Runtime.Tests/TrimmingTests/DebuggerVisualizerAttributeTests.cs @@ -113,8 +113,8 @@ public DebuggerVisualizerObjectSource(MyClass instance) } } - [DebuggerVisualizer("Program+MyClassWithVisualizerStringVisualizer")] - [DebuggerVisualizer("Program+MyClassWithVisualizerStringVisualizer2", "Program+MyClassWithVisualizerStringVisualizerObjectSource")] + [DebuggerVisualizer("Program+MyClassWithVisualizerStringVisualizer, project")] + [DebuggerVisualizer("Program+MyClassWithVisualizerStringVisualizer2, project", "Program+MyClassWithVisualizerStringVisualizerObjectSource, project")] public class MyClassWithVisualizerString { public string Name { get; set; } diff --git a/src/mono/msbuild/apple/build/AppleBuild.LocalBuild.targets b/src/mono/msbuild/apple/build/AppleBuild.LocalBuild.targets index a28bff240a64a7..14df939e12ffe6 100644 --- a/src/mono/msbuild/apple/build/AppleBuild.LocalBuild.targets +++ b/src/mono/msbuild/apple/build/AppleBuild.LocalBuild.targets @@ -37,7 +37,7 @@ true - $(NoWarn);IL2103;IL2105;IL2025;IL2111 + $(NoWarn);IL2103;IL2025;IL2111;IL2122