Thanks to visit codestin.com
Credit goes to github.com

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
Next Next commit
Fix dynamic object analysis holes
Move dynamic object handling into dataflow handling
  • Loading branch information
sbomer committed Oct 31, 2023
commit 21e03bdaa78c4348aa52fef4a4ace6193b0b7a6a
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 System.Linq;
using ILLink.RoslynAnalyzer.TrimAnalysis;
using ILLink.Shared.DataFlow;
using Microsoft.CodeAnalysis;
Expand All @@ -16,7 +17,7 @@ namespace ILLink.RoslynAnalyzer.DataFlow
// - field
// - parameter
// - method return
public abstract class LocalDataFlowVisitor<TValue, TValueLattice> : OperationWalker<LocalDataFlowState<TValue, TValueLattice>, TValue>,
public abstract partial class LocalDataFlowVisitor<TValue, TValueLattice> : OperationWalker<LocalDataFlowState<TValue, TValueLattice>, TValue>,
ITransfer<BlockProxy, LocalState<TValue>, LocalDataFlowState<TValue, TValueLattice>, LocalStateLattice<TValue, TValueLattice>>
// This struct constraint prevents warnings due to possible null returns from the visitor methods.
// Note that this assumes that default(TValue) is equal to the TopValue.
Expand All @@ -27,6 +28,8 @@ public abstract class LocalDataFlowVisitor<TValue, TValueLattice> : OperationWal

protected readonly InterproceduralStateLattice<TValue, TValueLattice> InterproceduralStateLattice;

protected readonly Compilation Compilation;

protected readonly ISymbol OwningSymbol;

private readonly ControlFlowGraph ControlFlowGraph;
Expand All @@ -44,12 +47,14 @@ bool IsRValueFlowCapture (CaptureId captureId)
=> !lValueFlowCaptures.TryGetValue (captureId, out var captureKind) || captureKind != FlowCaptureKind.LValueCapture;

public LocalDataFlowVisitor (
Compilation compilation,
LocalStateLattice<TValue, TValueLattice> lattice,
ISymbol owningSymbol,
ControlFlowGraph cfg,
ImmutableDictionary<CaptureId, FlowCaptureKind> lValueFlowCaptures,
InterproceduralState<TValue, TValueLattice> interproceduralState)
{
Compilation = compilation;
LocalStateLattice = lattice;
InterproceduralStateLattice = default;
OwningSymbol = owningSymbol;
Expand Down Expand Up @@ -124,6 +129,30 @@ public override TValue VisitLocalReference (ILocalReferenceOperation operation,
return GetLocal (operation, state);
}

TValue ProcessBinderCall (IOperation operation, string methodName, LocalDataFlowState<TValue, TValueLattice> state) {
var assemblyType = Compilation.GetTypeByMetadataName ("Microsoft.CSharp.RuntimeBinder.Binder");
Debug.Assert (assemblyType != null);
if (assemblyType == null)
return TopValue;
var method = assemblyType.GetMembers (methodName).OfType<IMethodSymbol> ().SingleOrDefault ();
Debug.Assert (method != null);
if (method == null)
return TopValue;
return ProcessMethodCall (operation, method, null, ImmutableArray<IArgumentOperation>.Empty, state);
}

public override TValue VisitDynamicInvocation (IDynamicInvocationOperation operation, LocalDataFlowState<TValue, TValueLattice> state)
=> ProcessBinderCall (operation, "InvokeMember", state);

public override TValue VisitDynamicObjectCreation (IDynamicObjectCreationOperation operation, LocalDataFlowState<TValue, TValueLattice> state)
=> ProcessBinderCall (operation, "InvokeConstructor", state);

public override TValue VisitDynamicMemberReference (IDynamicMemberReferenceOperation operation, LocalDataFlowState<TValue, TValueLattice> state)
=> ProcessBinderCall (operation, operation.GetValueUsageInfo (OwningSymbol).HasFlag (ValueUsageInfo.Write) ? "SetMember" : "GetMember", state);

public override TValue VisitDynamicIndexerAccess (IDynamicIndexerAccessOperation operation, LocalDataFlowState<TValue, TValueLattice> state)
=> ProcessBinderCall (operation, operation.GetValueUsageInfo (OwningSymbol).HasFlag (ValueUsageInfo.Write) ? "SetIndex" : "GetIndex", state);

bool IsReferenceToCapturedVariable (ILocalReferenceOperation localReference)
{
var local = localReference.Local;
Expand Down Expand Up @@ -283,12 +312,11 @@ TValue ProcessSingleTargetAssignment (IOperation targetOperation, IAssignmentOpe
// also produces warnings for ref params/locals/returns.
// https://github.com/dotnet/linker/issues/2632
// https://github.com/dotnet/linker/issues/2158
Visit (targetOperation, state);
break;
case IDynamicMemberReferenceOperation:
case IDynamicIndexerAccessOperation:
// Not yet implemented in analyzer:
// https://github.com/dotnet/runtime/issues/94057
// Assignment to dynamic member/indexer will translate into a call to runtime binder methods
// which should produce warnings, but isn't relevant for dataflow.
Visit (targetOperation, state);
break;

// Keep these cases in sync with those in CapturedReferenceValue, for any that
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ public abstract class RequiresAnalyzerBase : DiagnosticAnalyzer
private protected abstract DiagnosticDescriptor RequiresAttributeMismatch { get; }
private protected abstract DiagnosticDescriptor RequiresOnStaticCtor { get; }

private protected virtual ImmutableArray<(Action<OperationAnalysisContext> Action, OperationKind[] OperationKind)> ExtraOperationActions { get; } = ImmutableArray<(Action<OperationAnalysisContext> Action, OperationKind[] OperationKind)>.Empty;

private protected virtual ImmutableArray<(Action<SyntaxNodeAnalysisContext> Action, SyntaxKind[] SyntaxKind)> ExtraSyntaxNodeActions { get; } = ImmutableArray<(Action<SyntaxNodeAnalysisContext> Action, SyntaxKind[] SyntaxKind)>.Empty;
private protected virtual ImmutableArray<(Action<SymbolAnalysisContext> Action, SymbolKind[] SymbolKind)> ExtraSymbolActions { get; } = ImmutableArray<(Action<SymbolAnalysisContext> Action, SymbolKind[] SymbolKind)>.Empty;

Expand Down Expand Up @@ -103,10 +101,6 @@ public override void Initialize (AnalysisContext context)
}
}, SyntaxKind.GenericName);

// Register any extra operation actions supported by the analyzer.
foreach (var extraOperationAction in ExtraOperationActions)
context.RegisterOperationAction (extraOperationAction.Action, extraOperationAction.OperationKind);

foreach (var extraSyntaxNodeAction in ExtraSyntaxNodeActions)
context.RegisterSyntaxNodeAction (extraSyntaxNodeAction.Action, extraSyntaxNodeAction.SyntaxKind);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,24 +19,12 @@ public sealed class RequiresUnreferencedCodeAnalyzer : RequiresAnalyzerBase

static readonly DiagnosticDescriptor s_requiresUnreferencedCodeRule = DiagnosticDescriptors.GetDiagnosticDescriptor (DiagnosticId.RequiresUnreferencedCode);
static readonly DiagnosticDescriptor s_requiresUnreferencedCodeAttributeMismatch = DiagnosticDescriptors.GetDiagnosticDescriptor (DiagnosticId.RequiresUnreferencedCodeAttributeMismatch);
static readonly DiagnosticDescriptor s_dynamicTypeInvocationRule = DiagnosticDescriptors.GetDiagnosticDescriptor (DiagnosticId.RequiresUnreferencedCode,
new LocalizableResourceString (nameof (SharedStrings.DynamicTypeInvocationTitle), SharedStrings.ResourceManager, typeof (SharedStrings)),
new LocalizableResourceString (nameof (SharedStrings.DynamicTypeInvocationMessage), SharedStrings.ResourceManager, typeof (SharedStrings)));
static readonly DiagnosticDescriptor s_makeGenericTypeRule = DiagnosticDescriptors.GetDiagnosticDescriptor (DiagnosticId.MakeGenericType);
static readonly DiagnosticDescriptor s_makeGenericMethodRule = DiagnosticDescriptors.GetDiagnosticDescriptor (DiagnosticId.MakeGenericMethod);
static readonly DiagnosticDescriptor s_requiresUnreferencedCodeOnStaticCtor = DiagnosticDescriptors.GetDiagnosticDescriptor (DiagnosticId.RequiresUnreferencedCodeOnStaticConstructor);

static readonly DiagnosticDescriptor s_typeDerivesFromRucClassRule = DiagnosticDescriptors.GetDiagnosticDescriptor (DiagnosticId.RequiresUnreferencedCodeOnBaseClass);

static readonly Action<OperationAnalysisContext> s_dynamicTypeInvocation = operationContext => {
if (FindContainingSymbol (operationContext, DiagnosticTargets.All) is ISymbol containingSymbol &&
containingSymbol.IsInRequiresScope (RequiresUnreferencedCodeAttribute, out _))
return;

operationContext.ReportDiagnostic (Diagnostic.Create (s_dynamicTypeInvocationRule,
operationContext.Operation.Syntax.GetLocation ()));
};

private Action<SymbolAnalysisContext> typeDerivesFromRucBase {
get {
return symbolAnalysisContext => {
Expand All @@ -56,7 +44,7 @@ private Action<SymbolAnalysisContext> typeDerivesFromRucBase {
}

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
ImmutableArray.Create (s_dynamicTypeInvocationRule, s_makeGenericMethodRule, s_makeGenericTypeRule, s_requiresUnreferencedCodeRule, s_requiresUnreferencedCodeAttributeMismatch, s_typeDerivesFromRucClassRule, s_requiresUnreferencedCodeOnStaticCtor);
ImmutableArray.Create (s_makeGenericMethodRule, s_makeGenericTypeRule, s_requiresUnreferencedCodeRule, s_requiresUnreferencedCodeAttributeMismatch, s_typeDerivesFromRucClassRule, s_requiresUnreferencedCodeOnStaticCtor);

private protected override string RequiresAttributeName => RequiresUnreferencedCodeAttribute;

Expand Down Expand Up @@ -90,11 +78,6 @@ protected override bool CreateSpecialIncompatibleMembersDiagnostic (
private protected override ImmutableArray<(Action<SymbolAnalysisContext> Action, SymbolKind[] SymbolKind)> ExtraSymbolActions =>
ImmutableArray.Create<(Action<SymbolAnalysisContext> Action, SymbolKind[] SymbolKind)> ((typeDerivesFromRucBase, new SymbolKind[] { SymbolKind.NamedType }));



private protected override ImmutableArray<(Action<OperationAnalysisContext> Action, OperationKind[] OperationKind)> ExtraOperationActions =>
ImmutableArray.Create ((s_dynamicTypeInvocation, new OperationKind[] { OperationKind.DynamicInvocation }));

protected override bool VerifyAttributeArguments (AttributeData attribute) =>
RequiresUnreferencedCodeUtils.VerifyRequiresUnreferencedCodeAttributeArguments (attribute);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,14 @@ public class TrimAnalysisVisitor : LocalDataFlowVisitor<MultiValue, ValueSetLatt
const int MaxTrackedArrayValues = 32;

public TrimAnalysisVisitor (
Compilation compilation,
LocalStateLattice<MultiValue, ValueSetLattice<SingleValue>> lattice,
ISymbol owningSymbol,
ControlFlowGraph methodCFG,
ImmutableDictionary<CaptureId, FlowCaptureKind> lValueFlowCaptures,
TrimAnalysisPatternStore trimAnalysisPatterns,
InterproceduralState<MultiValue, ValueSetLattice<SingleValue>> interproceduralState
) : base (lattice, owningSymbol, methodCFG, lValueFlowCaptures, interproceduralState)
) : base (compilation, lattice, owningSymbol, methodCFG, lValueFlowCaptures, interproceduralState)
{
_multiValueLattice = lattice.Lattice.ValueLattice;
TrimAnalysisPatterns = trimAnalysisPatterns;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ protected override TrimAnalysisVisitor GetVisitor (
ControlFlowGraph methodCFG,
ImmutableDictionary<CaptureId, FlowCaptureKind> lValueFlowCaptures,
InterproceduralState<MultiValue, ValueSetLattice<SingleValue>> interproceduralState)
=> new (Lattice, owningSymbol, methodCFG, lValueFlowCaptures, TrimAnalysisPatterns, interproceduralState);
=> new (Context.Compilation, Lattice, owningSymbol, methodCFG, lValueFlowCaptures, TrimAnalysisPatterns, interproceduralState);

#if DEBUG
#pragma warning disable CA1805 // Do not initialize unnecessarily
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ public static void Main ()

class InvocationOnDynamicType
{
// Analyzer hole: https://github.com/dotnet/runtime/issues/94057
[ExpectedWarning ("IL2026", "Invoking members on dynamic types is not trimming-compatible.", ProducedBy = Tool.Analyzer)]
[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember", ProducedBy = Tool.Trimmer | Tool.NativeAot)]
[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember")]
[ExpectedWarning ("IL3050", ProducedBy = Tool.NativeAot)]
static void DynamicArgument ()
{
Expand All @@ -46,16 +44,14 @@ static void MethodWithDynamicParameterDoNothing (dynamic arg)
{
}

// Analyzer hole: https://github.com/dotnet/runtime/issues/94057
[ExpectedWarning ("IL2026", "Invoking members on dynamic types is not trimming-compatible.", ProducedBy = Tool.Analyzer)]
[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember", ProducedBy = Tool.Trimmer | Tool.NativeAot)]
[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember")]
[ExpectedWarning ("IL3050", ProducedBy = Tool.NativeAot)]
static void MethodWithDynamicParameter (dynamic arg)
{
arg.MethodWithDynamicParameter (arg);
}

[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.InvokeConstructor", ProducedBy = Tool.Trimmer | Tool.NativeAot)]
[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.InvokeConstructor")]
[ExpectedWarning ("IL3050", ProducedBy = Tool.NativeAot)]
// TODO: analyzer hole!
static void ObjectCreationDynamicArgument ()
Expand All @@ -81,16 +77,14 @@ public static void Test ()

class DynamicMemberReference
{
// Analyzer hole: https://github.com/dotnet/runtime/issues/94057
[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.GetMember", ProducedBy = Tool.Trimmer | Tool.NativeAot)]
[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.GetMember")]
[ExpectedWarning ("IL3050", ProducedBy = Tool.NativeAot)]
static void Read (dynamic d)
{
var x = d.Member;
}

// Analyzer hole: https://github.com/dotnet/runtime/issues/94057
[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.SetMember", ProducedBy = Tool.Trimmer | Tool.NativeAot)]
[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.SetMember")]
[ExpectedWarning ("IL3050", ProducedBy = Tool.NativeAot)]
static void Write (dynamic d)
{
Expand All @@ -106,16 +100,14 @@ public static void Test ()

class DynamicIndexerAccess
{
// Analyzer hole: https://github.com/dotnet/runtime/issues/94057
[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.GetIndex", ProducedBy = Tool.Trimmer | Tool.NativeAot)]
[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.GetIndex")]
[ExpectedWarning ("IL3050", ProducedBy = Tool.NativeAot)]
static void Read (dynamic d)
{
var x = d[0];
}

// Analyzer hole: https://github.com/dotnet/runtime/issues/94057
[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.SetIndex", ProducedBy = Tool.Trimmer | Tool.NativeAot)]
[ExpectedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.SetIndex")]
[ExpectedWarning ("IL3050", ProducedBy = Tool.NativeAot)]
static void Write (dynamic d)
{
Expand All @@ -134,7 +126,6 @@ class DynamicInRequiresUnreferencedCodeClass
[RequiresUnreferencedCode("message")]
class ClassWithRequires
{
// Analyzer hole: https://github.com/dotnet/runtime/issues/94057
[ExpectedWarning ("IL3050", ProducedBy = Tool.NativeAot)]
public static void MethodWithDynamicArg (dynamic arg)
{
Expand All @@ -151,7 +142,6 @@ public static void Test ()

class InvocationOnDynamicTypeInMethodWithRUCDoesNotWarnTwoTimes ()
{
// Analyzer hole: https://github.com/dotnet/runtime/issues/94057
[RequiresUnreferencedCode ("We should only see the warning related to this annotation, and none about the dynamic type.")]
[RequiresDynamicCode ("We should only see the warning related to this annotation, and none about the dynamic type.")]
static void MethodWithRequires ()
Expand Down