Skip to content

Correctness fixes to interface stripping #1305

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/linker/Linker.Dataflow/ReflectionMethodBodyScanner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -790,7 +790,7 @@ public override bool HandleCall (MethodBody callingMethodBody, MethodReference c
// Intentionally ignore - it's not wrong for code to call Type.GetType on non-existing name, the code might expect null/exception back.
reflectionContext.RecordHandledPattern ();
} else {
reflectionContext.RecordRecognizedPattern (foundType, () => _markStep.MarkType (foundType, new DependencyInfo (DependencyKind.AccessedViaReflection, callingMethodDefinition), callingMethodDefinition));
reflectionContext.RecordRecognizedPattern (foundType, () => _markStep.MarkTypeVisibleToReflection (foundType, new DependencyInfo (DependencyKind.AccessedViaReflection, callingMethodDefinition), callingMethodDefinition));
methodReturnValue = MergePointValue.MergeValues (methodReturnValue, new SystemTypeValue (foundType));
}
} else if (typeNameValue == NullValue.Instance) {
Expand Down Expand Up @@ -1408,7 +1408,7 @@ void MarkMethod (ref ReflectionPatternContext reflectionContext, MethodDefinitio
void MarkNestedType (ref ReflectionPatternContext reflectionContext, TypeDefinition nestedType)
{
var source = reflectionContext.Source;
reflectionContext.RecordRecognizedPattern (nestedType, () => _markStep.MarkType (nestedType, new DependencyInfo (DependencyKind.AccessedViaReflection, source), source));
reflectionContext.RecordRecognizedPattern (nestedType, () => _markStep.MarkTypeVisibleToReflection (nestedType, new DependencyInfo (DependencyKind.AccessedViaReflection, source), source));
}

void MarkField (ref ReflectionPatternContext reflectionContext, FieldDefinition field)
Expand Down
30 changes: 26 additions & 4 deletions src/linker/Linker.Steps/MarkStep.cs
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ void ProcessMarkedTypesWithInterfaces ()
foreach (var type in typesWithInterfaces) {
// Exception, types that have not been flagged as instantiated yet. These types may not need their interfaces even if the
// interface type is marked
if (!Annotations.IsInstantiated (type))
if (!Annotations.IsInstantiated (type) && !Annotations.IsRelevantToVariantCasting (type))
continue;

MarkInterfaceImplementations (type);
Expand Down Expand Up @@ -1285,6 +1285,16 @@ protected virtual void MarkSerializable (TypeDefinition type)
MarkMethodsIf (type.Methods, IsSpecialSerializationConstructor, new DependencyInfo (DependencyKind.SerializationMethodForType, type), type);
}

internal protected virtual TypeDefinition MarkTypeVisibleToReflection (TypeReference reference, DependencyInfo reason, IMemberDefinition sourceLocationMember)
{
// If a type is visible to reflection, we need to stop doing optimization that could cause observable difference
// in reflection APIs. This includes APIs like MakeGenericType (where variant castability of the produced type
// could be incorrect) or IsAssignableFrom (where assignability of unconstructed types might change).
Annotations.MarkRelevantToVariantCasting (reference.Resolve ());

return MarkType (reference, reason, sourceLocationMember);
}

/// <summary>
/// Marks the specified <paramref name="reference"/> as referenced.
/// </summary>
Expand Down Expand Up @@ -2001,9 +2011,12 @@ void MarkModifierType (IModifierType mod, IMemberDefinition sourceLocationMember

void MarkGenericArguments (IGenericInstance instance, IMemberDefinition sourceLocationMember)
{
foreach (TypeReference argument in instance.GenericArguments)
foreach (TypeReference argument in instance.GenericArguments) {
MarkType (argument, new DependencyInfo (DependencyKind.GenericArgumentType, instance), sourceLocationMember);

Annotations.MarkRelevantToVariantCasting (argument.Resolve ());
}

MarkGenericArgumentConstructors (instance, sourceLocationMember);
}

Expand Down Expand Up @@ -2173,8 +2186,14 @@ protected virtual MethodDefinition MarkMethod (MethodReference reference, Depend
{
(reference, reason) = GetOriginalMethod (reference, reason, sourceLocationMember);

if (reference.DeclaringType is ArrayType)
if (reference.DeclaringType is ArrayType arrayType) {
MarkType (reference.DeclaringType, new DependencyInfo (DependencyKind.DeclaringType, reference), sourceLocationMember);

if (reference.Name == ".ctor") {
Annotations.MarkRelevantToVariantCasting (arrayType.Resolve ());
}
return null;
}

if (reference.DeclaringType is GenericInstanceType) {
// Blame the method reference on the original reason without marking it.
Expand Down Expand Up @@ -2642,7 +2661,7 @@ protected virtual void MarkInstruction (Instruction instruction, MethodDefinitio
Debug.Assert (instruction.OpCode.Code == Code.Ldtoken);
var reason = new DependencyInfo (DependencyKind.Ldtoken, method);
if (token is TypeReference typeReference) {
MarkType (typeReference, reason, method);
MarkTypeVisibleToReflection (typeReference, reason, method);
} else if (token is MethodReference methodReference) {
MarkMethod (methodReference, reason, method);
} else {
Expand All @@ -2652,6 +2671,9 @@ protected virtual void MarkInstruction (Instruction instruction, MethodDefinitio
}

case OperandType.InlineType:
if (instruction.OpCode.Code == Code.Newarr) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Are you sure this is the only relevant opcode? What about code like var foos = (IFoo[]) Array.CreateInstance (typeof (Foo), 1); ?

Copy link
Member Author

Choose a reason for hiding this comment

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

That pattern should be fine because the typeof(Foo) means "visible to reflection" and that's handled elsewhere in this pull request.

Annotations.MarkRelevantToVariantCasting (((TypeReference) instruction.Operand).Resolve ());
Copy link
Member

Choose a reason for hiding this comment

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

Resolve may return null - in which case we will add null to the HashSet in Annotations. I guess it doesn't matter that much, but it might be cleaner to check for null in the MarkRelevantToVariantCasting before adding it to the hashset.

}
MarkType ((TypeReference) instruction.Operand, new DependencyInfo (DependencyKind.InstructionTypeRef, method), method);
break;
default:
Expand Down
12 changes: 12 additions & 0 deletions src/linker/Linker/Annotations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ public partial class AnnotationStore
readonly HashSet<TypeDefinition> marked_types_with_cctor = new HashSet<TypeDefinition> ();
protected readonly HashSet<TypeDefinition> marked_instantiated = new HashSet<TypeDefinition> ();
protected readonly HashSet<MethodDefinition> indirectly_called = new HashSet<MethodDefinition> ();
protected readonly HashSet<TypeDefinition> types_relevant_to_variant_casting = new HashSet<TypeDefinition> ();

public AnnotationStore (LinkContext context) => this.context = context;

Expand Down Expand Up @@ -216,6 +217,17 @@ public bool IsInstantiated (TypeDefinition type)
return marked_instantiated.Contains (type);
}

public void MarkRelevantToVariantCasting (TypeDefinition type)
{
if (type != null)
types_relevant_to_variant_casting.Add (type);
}

public bool IsRelevantToVariantCasting (TypeDefinition type)
{
return types_relevant_to_variant_casting.Contains (type);
}

public void Processed (IMetadataTokenProvider provider)
{
processed.Add (provider);
Expand Down
44 changes: 44 additions & 0 deletions test/Mono.Linker.Tests.Cases/Generics/ArrayVariantCasting.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using Mono.Linker.Tests.Cases.Expectations.Assertions;

namespace Mono.Linker.Tests.Cases.Generics
{
public class ArrayVariantCasting
{
[Kept]
interface IFoo { }

[Kept]
[KeptInterface (typeof (IFoo))]
class Foo : IFoo
{
// Even though Foo is never allocated (as seen from the removal of the constructor),
// we need to make sure linker keeps its interface list because it's relevant
// for variant casting.
public Foo () { }
}

[Kept]
class Base
{
// Removed
public Base () { }
}

[Kept]
[KeptBaseType (typeof (Base))]
class Derived : Base
{
// Even though Derived is never allocated (as seen from the removal of the constructor),
// we need to make sure linker keeps its base types because it's relevant
// for variant casting.
public Derived () { }
}

public static void Main ()
{
// These casts need to succeed after trimming
var foos = (IFoo[]) (object) new Foo[0];
var bases = (Base[]) (object) new Derived[0];
}
}
}
44 changes: 44 additions & 0 deletions test/Mono.Linker.Tests.Cases/Generics/MdArrayVariantCasting.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using Mono.Linker.Tests.Cases.Expectations.Assertions;

namespace Mono.Linker.Tests.Cases.Generics
{
public class MdArrayVariantCasting
{
[Kept]
interface IFoo { }

[Kept]
[KeptInterface (typeof (IFoo))]
class Foo : IFoo
{
// Even though Foo is never allocated (as seen from the removal of the constructor),
// we need to make sure linker keeps its interface list because it's relevant
// for variant casting.
public Foo () { }
}

[Kept]
class Base
{
// Removed
public Base () { }
}

[Kept]
[KeptBaseType (typeof (Base))]
class Derived : Base
{
// Even though Derived is never allocated (as seen from the removal of the constructor),
// we need to make sure linker keeps its base types because it's relevant
// for variant casting.
public Derived () { }
}

public static void Main ()
{
// These casts need to succeed after trimming
var foos = (IFoo[,]) (object) new Foo[0, 0];
var bases = (Base[,]) (object) new Derived[0, 0];
}
}
}
63 changes: 63 additions & 0 deletions test/Mono.Linker.Tests.Cases/Generics/VariantCasting.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using Mono.Linker.Tests.Cases.Expectations.Assertions;

namespace Mono.Linker.Tests.Cases.Generics
{
public class VariantCasting
{
[Kept]
interface IVariant<out T> { }

[Kept]
interface IFoo { }

[Kept]
[KeptInterface (typeof (IFoo))]
class Foo : IFoo
{
// Even though Foo is never allocated (as seen from the removal of the constructor),
// we need to make sure linker keeps its interface list because it's relevant
// for variant casting.
public Foo () { }
}

[Kept]
class Base
{
// Removed
public Base () { }
}

[Kept]
[KeptBaseType (typeof (Base))]
class Derived : Base
{
// Even though Derived is never allocated (as seen from the removal of the constructor),
// we need to make sure linker keeps its base types because it's relevant
// for variant casting.
public Derived () { }
}

[Kept]
[KeptInterface (typeof (IVariant<>))]
class Interesting<T> : IVariant<T>
{
[Kept]
public Interesting () { }
}

[Kept]
[KeptBaseType (typeof (Interesting<>), "T")]
class Boring<T> : Interesting<T>
{
[Kept]
public Boring () { }
}

public static void Main ()
{
// These casts need to succeed after trimming
IVariant<IFoo> foos = (IVariant<IFoo>) (object) new Boring<Foo> ();
IVariant<Base> bases = (IVariant<Base>) (object) new Boring<Derived> ();
}
}
}
21 changes: 21 additions & 0 deletions test/Mono.Linker.Tests.Cases/Reflection/IsAssignableFrom.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

using Mono.Linker.Tests.Cases.Expectations.Assertions;

namespace Mono.Linker.Tests.Cases.Reflection
{
class IsAssignableFrom
{
[Kept]
interface IFoo { }

[Kept]
[KeptInterface (typeof (IFoo))]
class Foo : IFoo { }

static void Main ()
{
typeof (IFoo).IsAssignableFrom (typeof (Foo));
}

}
}