Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using ILLink.RoslynAnalyzer.TrimAnalysis;
using ILLink.Shared.DataFlow;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FlowAnalysis;
Expand Down Expand Up @@ -421,6 +422,32 @@ public override TValue VisitExpressionStatement (IExpressionStatementOperation o
public override TValue VisitInvocation (IInvocationOperation operation, LocalDataFlowState<TValue, TValueLattice> state)
=> ProcessMethodCall (operation, operation.TargetMethod, operation.Instance, operation.Arguments, state);

public override TValue VisitDelegateCreation (IDelegateCreationOperation operation, LocalDataFlowState<TValue, TValueLattice> state)
{
if (operation.Target is IFlowAnonymousFunctionOperation lambda) {
VisitFlowAnonymousFunction (lambda, state);

// Instance of a lambda or local function should be the instance of the containing method.
// Don't need to track a dataflow value, since the delegate creation will warn if the
// lambda or local function has an annotated this parameter.
var instance = TopValue;
return HandleDelegateCreation (lambda.Symbol, instance, operation);
}

Debug.Assert (operation.Target is IMethodReferenceOperation);
if (operation.Target is not IMethodReferenceOperation methodReference)
return TopValue;

TValue instanceValue = Visit (methodReference.Instance, state);
IMethodSymbol? method = methodReference.Method;
Debug.Assert (method != null);
if (method == null)
return TopValue;
return HandleDelegateCreation (method, instanceValue, operation);
}

public abstract TValue HandleDelegateCreation (IMethodSymbol methodReference, TValue instance, IOperation operation);

public override TValue VisitPropertyReference (IPropertyReferenceOperation operation, LocalDataFlowState<TValue, TValueLattice> state)
{
if (!operation.GetValueUsageInfo (OwningSymbol).HasFlag (ValueUsageInfo.Read))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,25 @@ public DiagnosticContext (Location location)

public static DiagnosticContext CreateDisabled () => new () { Location = null };

public Diagnostic CreateDiagnostic (DiagnosticId id, params string[] args)
{
return Diagnostic.Create (DiagnosticDescriptors.GetDiagnosticDescriptor (id), Location, args);
}

public void AddDiagnostic (Diagnostic diagnostic)
{
if (Location == null)
return;

Diagnostics.Add (diagnostic);
}

public partial void AddDiagnostic (DiagnosticId id, params string[] args)
{
if (Location == null)
return;

Diagnostics.Add (Diagnostic.Create (DiagnosticDescriptors.GetDiagnosticDescriptor (id), Location, args));
Diagnostics.Add (CreateDiagnostic (id, args));
}

public partial void AddDiagnostic (DiagnosticId id, ValueWithDynamicallyAccessedMembers actualValue, ValueWithDynamicallyAccessedMembers expectedAnnotationsValue, params string[] args)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// 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.

using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using ILLink.RoslynAnalyzer.DataFlow;
Expand Down Expand Up @@ -80,15 +81,23 @@ static void ReportRequiresUnreferencedCodeDiagnostic (in DiagnosticContext diagn

internal static void GetReflectionAccessDiagnosticsForMethod (in DiagnosticContext diagnosticContext, IMethodSymbol methodSymbol)
{
if (methodSymbol.IsInRequiresUnreferencedCodeAttributeScope (out var requiresUnreferencedCodeAttributeData))
if (methodSymbol.IsInRequiresUnreferencedCodeAttributeScope (out var requiresUnreferencedCodeAttributeData)) {
ReportRequiresUnreferencedCodeDiagnostic (diagnosticContext, requiresUnreferencedCodeAttributeData, methodSymbol);
else if (methodSymbol.IsVirtual && FlowAnnotations.GetMethodReturnValueAnnotation (methodSymbol) != DynamicallyAccessedMemberTypes.None)
diagnosticContext.AddDiagnostic (DiagnosticId.DynamicallyAccessedMembersMethodAccessedViaReflection, methodSymbol.GetDisplayName ());
else {
} else {
foreach (var diagnostic in GetDiagnosticsForReflectionAccessToDAMOnMethod (diagnosticContext, methodSymbol))
diagnosticContext.AddDiagnostic (diagnostic);
}
}

internal static IEnumerable<Diagnostic> GetDiagnosticsForReflectionAccessToDAMOnMethod (DiagnosticContext diagnosticContext, IMethodSymbol methodSymbol)
{
if (methodSymbol.IsVirtual && FlowAnnotations.GetMethodReturnValueAnnotation (methodSymbol) != DynamicallyAccessedMemberTypes.None) {
yield return diagnosticContext.CreateDiagnostic (DiagnosticId.DynamicallyAccessedMembersMethodAccessedViaReflection, methodSymbol.GetDisplayName ());
} else {
foreach (var parameter in methodSymbol.GetParameters ()) {
if (FlowAnnotations.GetMethodParameterAnnotation (parameter) != DynamicallyAccessedMemberTypes.None) {
diagnosticContext.AddDiagnostic (DiagnosticId.DynamicallyAccessedMembersMethodAccessedViaReflection, methodSymbol.GetDisplayName ());
break;
yield return diagnosticContext.CreateDiagnostic (DiagnosticId.DynamicallyAccessedMembersMethodAccessedViaReflection, methodSymbol.GetDisplayName ());
yield break;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ public readonly struct TrimAnalysisPatternStore
{
readonly Dictionary<(IOperation, bool), TrimAnalysisAssignmentPattern> AssignmentPatterns;
readonly Dictionary<IOperation, TrimAnalysisMethodCallPattern> MethodCallPatterns;
readonly Dictionary<IOperation, TrimAnalysisReflectionAccessPattern> ReflectionAccessPatterns;
readonly ValueSetLattice<SingleValue> Lattice;

public TrimAnalysisPatternStore (ValueSetLattice<SingleValue> lattice)
{
AssignmentPatterns = new Dictionary<(IOperation, bool), TrimAnalysisAssignmentPattern> ();
MethodCallPatterns = new Dictionary<IOperation, TrimAnalysisMethodCallPattern> ();
ReflectionAccessPatterns = new Dictionary<IOperation, TrimAnalysisReflectionAccessPattern> ();
Lattice = lattice;
}

Expand Down Expand Up @@ -48,6 +50,16 @@ public void Add (TrimAnalysisMethodCallPattern pattern)
MethodCallPatterns[pattern.Operation] = pattern.Merge (Lattice, existingPattern);
}

public void Add (TrimAnalysisReflectionAccessPattern pattern)
{
if (!ReflectionAccessPatterns.TryGetValue (pattern.Operation, out var existingPattern)) {
ReflectionAccessPatterns.Add (pattern.Operation, pattern);
return;
}

ReflectionAccessPatterns[pattern.Operation] = pattern.Merge (Lattice, existingPattern);
}

public IEnumerable<Diagnostic> CollectDiagnostics ()
{
foreach (var assignmentPattern in AssignmentPatterns.Values) {
Expand All @@ -59,6 +71,11 @@ public IEnumerable<Diagnostic> CollectDiagnostics ()
foreach (var diagnostic in methodCallPattern.CollectDiagnostics ())
yield return diagnostic;
}

foreach (var reflectionAccessPattern in ReflectionAccessPatterns.Values) {
foreach (var diagnostic in reflectionAccessPattern.CollectDiagnostics ())
yield return diagnostic;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// 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.

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using ILLink.Shared;
using ILLink.Shared.DataFlow;
using ILLink.Shared.TrimAnalysis;
using ILLink.Shared.TypeSystemProxy;
using Microsoft.CodeAnalysis;

using MultiValue = ILLink.Shared.DataFlow.ValueSet<ILLink.Shared.DataFlow.SingleValue>;

namespace ILLink.RoslynAnalyzer.TrimAnalysis
{
public readonly record struct TrimAnalysisReflectionAccessPattern
{
public IMethodSymbol ReferencedMethod { init; get; }
public MultiValue Instance { init; get; }
public IOperation Operation { init; get; }
public ISymbol OwningSymbol { init; get; }

public TrimAnalysisReflectionAccessPattern (
IMethodSymbol referencedMethod,
MultiValue instance,
IOperation operation,
ISymbol owningSymbol)
{
ReferencedMethod = referencedMethod;
Instance = instance.DeepCopy ();
Operation = operation;
OwningSymbol = owningSymbol;
}

public TrimAnalysisReflectionAccessPattern Merge (ValueSetLattice<SingleValue> lattice, TrimAnalysisReflectionAccessPattern other)
{
Debug.Assert (Operation == other.Operation);
Debug.Assert (SymbolEqualityComparer.Default.Equals (ReferencedMethod, other.ReferencedMethod));

return new TrimAnalysisReflectionAccessPattern (
ReferencedMethod,
lattice.Meet (Instance, other.Instance),
Operation,
OwningSymbol);
}

public IEnumerable<Diagnostic> CollectDiagnostics ()
{
DiagnosticContext diagnosticContext = new (Operation.Syntax.GetLocation ());
foreach (var diagnostic in ReflectionAccessAnalyzer.GetDiagnosticsForReflectionAccessToDAMOnMethod (diagnosticContext, ReferencedMethod))
yield return diagnostic;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,18 @@ public override void HandleReturnValue (MultiValue returnValue, IOperation opera
}
}

public override MultiValue HandleDelegateCreation (IMethodSymbol method, MultiValue instance, IOperation operation)
{
TrimAnalysisPatterns.Add (new TrimAnalysisReflectionAccessPattern (
method,
instance,
operation,
OwningSymbol
));

return TopValue;
}

static bool TryGetConstantValue (IOperation operation, out MultiValue constValue)
{
if (operation.ConstantValue.HasValue) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,20 @@
using Mono.Linker.Tests.Cases.DataFlow;
using Mono.Linker.Tests.Cases.Expectations.Assertions;
using Mono.Linker.Tests.Cases.Expectations.Helpers;
using Mono.Linker.Tests.Cases.Expectations.Metadata;

namespace Mono.Linker.Tests.Cases.DataFlow
{
[SkipKeptItemsValidation]
[SandboxDependency ("Dependencies/TestSystemTypeBase.cs")]
[ExpectedNoWarnings]
[UnconditionalSuppressMessage ("AOT", "IL3050", Justification = "These tests are not targeted at AOT scenarios")]
class AnnotatedMembersAccessedViaReflection
{
public static void Main ()
{
AnnotatedField.Test ();
AnnotatedMethodThisParameter.Test ();
AnnotatedMethodParameters.Test ();
AnnotatedMethodReturnValue.Test ();
AnnotatedProperty.Test ();
Expand Down Expand Up @@ -150,6 +153,54 @@ public static void Test ()
}
}

public class AnnotatedMethodThisParameter : TestSystemTypeBase
{
[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)]
public void MethodWithAnnotatedThisParameter ()
{ }

[ExpectedWarning ("IL2111", nameof (MethodWithAnnotatedThisParameter))]
static void Reflection ()
{
typeof (AnnotatedMethodThisParameter).GetMethod (nameof (MethodWithAnnotatedThisParameter)).Invoke (null, null);
}

[ExpectedWarning ("IL2111", nameof (MethodWithAnnotatedThisParameter))]
void Ldftn ()
{
var _ = new Action (MethodWithAnnotatedThisParameter);
}

[ExpectedWarning ("IL2111")]
void LdftnOnLambda ()
{
var _ = new Action (
[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)]
() => MethodWithAnnotatedThisParameter ());
}

[ExpectedWarning ("IL2111")]
void LdftnOnLocalMethod ()
{
var _ = new Action (LocalMethod);

[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)]
void LocalMethod ()
{
MethodWithAnnotatedThisParameter ();
}
}

public static void Test ()
{
var instance = new AnnotatedMethodThisParameter ();
Reflection ();
instance.Ldftn ();
instance.LdftnOnLambda ();
instance.LdftnOnLocalMethod ();
}
}

class AnnotatedMethodParameters
{
public static void MethodWithSingleAnnotatedParameter (
Expand Down Expand Up @@ -213,20 +264,36 @@ static void DynamicallyAccessedMembersSuppressedByRUC ()
typeof (AnnotatedMethodParameters).RequiresPublicMethods ();
}

// Action delegate is not handled correctly https://github.com/dotnet/runtime/issues/84918
[ExpectedWarning ("IL2111", nameof (MethodWithSingleAnnotatedParameter), ProducedBy = Tool.Trimmer | Tool.NativeAot)]
[ExpectedWarning ("IL2111", nameof (MethodWithSingleAnnotatedParameter))]
static void Ldftn ()
{
var _ = new Action<Type> (AnnotatedMethodParameters.MethodWithSingleAnnotatedParameter);
}

[ExpectedWarning ("IL2111")]
static void
LdftnOnLambda ()
{
var _ = new Action<Type> (
([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type type) => { });
}

[ExpectedWarning ("IL2111")]
static void LdftnOnLocalMethod ()
{
var _ = new Action<Type> (LocalMethod);

void LocalMethod (
[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type type)
{ }
}

interface IWithAnnotatedMethod
{
public void AnnotatedMethod ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors)] Type type);
}

// Action delegate is not handled correctly https://github.com/dotnet/runtime/issues/84918
[ExpectedWarning ("IL2111", nameof (IWithAnnotatedMethod.AnnotatedMethod), ProducedBy = Tool.Trimmer | Tool.NativeAot)]
[ExpectedWarning ("IL2111", nameof (IWithAnnotatedMethod.AnnotatedMethod))]
static void Ldvirtftn ()
{
IWithAnnotatedMethod instance = null;
Expand Down Expand Up @@ -274,6 +341,8 @@ public static void Test ()
DynamicallyAccessedMembers ();
DynamicallyAccessedMembersSuppressedByRUC ();
Ldftn ();
LdftnOnLambda ();
LdftnOnLocalMethod ();
Ldvirtftn ();
DynamicallyAccessedMembersAll1 ();
DynamicallyAccessedMembersAll2 ();
Expand Down Expand Up @@ -369,8 +438,7 @@ static void LdftnOnInstance ()
var _ = new Func<Type> ((new AnnotatedMethodReturnValue ()).InstanceMethodWithAnnotatedReturnValue);
}

// Action delegate is not handled correctly https://github.com/dotnet/runtime/issues/84918
[ExpectedWarning ("IL2111", nameof (VirtualMethodWithAnnotatedReturnValue), ProducedBy = Tool.Trimmer | Tool.NativeAot)]
[ExpectedWarning ("IL2111", nameof (VirtualMethodWithAnnotatedReturnValue))]
static void LdftnOnVirtual ()
{
var _ = new Func<Type> ((new AnnotatedMethodReturnValue ()).VirtualMethodWithAnnotatedReturnValue);
Expand Down Expand Up @@ -689,8 +757,7 @@ public static void GenericMethodWithAnnotation<T> (
[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type type)
{ }

// Action delegate is not handled correctly https://github.com/dotnet/runtime/issues/84918
[ExpectedWarning ("IL2111", nameof (GenericWithAnnotatedMethod<TestType>.AnnotatedMethod), ProducedBy = Tool.Trimmer | Tool.NativeAot)]
[ExpectedWarning ("IL2111", nameof (GenericWithAnnotatedMethod<TestType>.AnnotatedMethod))]
public static void GenericTypeWithStaticMethodViaLdftn ()
{
var _ = new Action<Type> (GenericWithAnnotatedMethod<TestType>.AnnotatedMethod);
Expand All @@ -708,8 +775,7 @@ public static void GenericMethodWithAnnotationDirectCall ()
GenericMethodWithAnnotation<TestType> (typeof (TestType));
}

// Action delegate is not handled correctly https://github.com/dotnet/runtime/issues/84918
[ExpectedWarning ("IL2111", nameof (GenericMethodWithAnnotation), ProducedBy = Tool.Trimmer | Tool.NativeAot)]
[ExpectedWarning ("IL2111", nameof (GenericMethodWithAnnotation))]
public static void GenericMethodWithAnnotationViaLdftn ()
{
var _ = new Action<Type> (GenericMethodWithAnnotation<TestType>);
Expand Down
Loading