|
| 1 | +using System.Collections.Immutable; |
| 2 | +using System.Linq; |
| 3 | +using Microsoft.CodeAnalysis; |
| 4 | +using Microsoft.CodeAnalysis.CSharp; |
| 5 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 6 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 7 | + |
| 8 | +namespace OpenCvSharp.Analyzers; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// Detects the misuse pattern <c>mat.Row(i).At<T>(col)</c> where the column index is |
| 12 | +/// silently interpreted as a row index, causing out-of-bounds memory access. |
| 13 | +/// </summary> |
| 14 | +/// <remarks> |
| 15 | +/// <para> |
| 16 | +/// <c>Mat.Row(i)</c> returns a 1×N submatrix. <c>At<T>(int i0)</c> on a 2D matrix |
| 17 | +/// treats <c>i0</c> as the row index (dimension 0), not a column index. The resulting |
| 18 | +/// address is <c>data + step * col</c> — jumping entire rows past the end of the submatrix. |
| 19 | +/// </para> |
| 20 | +/// <para> |
| 21 | +/// Use <c>mat.At<T>(row, col)</c> or <c>mat.AsRows<T>()</c> instead. |
| 22 | +/// See https://github.com/shimat/opencvsharp/issues/1775 |
| 23 | +/// </para> |
| 24 | +/// </remarks> |
| 25 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 26 | +public sealed class RowAtAnalyzer : DiagnosticAnalyzer |
| 27 | +{ |
| 28 | + public const string DiagnosticId = "OCVS001"; |
| 29 | + |
| 30 | + private static readonly DiagnosticDescriptor Rule = new( |
| 31 | + id: DiagnosticId, |
| 32 | + title: "At<T>(int) called on a Mat row submatrix", |
| 33 | + messageFormat: "At<T>(int) on the 1-row Mat returned by Row() treats the argument as a row index, " + |
| 34 | + "not a column index, silently producing wrong results or out-of-bounds access. " + |
| 35 | + "Use mat.At<T>(row, col) or mat.AsRows<T>() instead.", |
| 36 | + category: "Correctness", |
| 37 | + defaultSeverity: DiagnosticSeverity.Warning, |
| 38 | + isEnabledByDefault: true, |
| 39 | + description: "Mat.Row(i) returns a 2D 1×N submatrix. At<T>(int i0) interprets i0 as a row " + |
| 40 | + "index (dimension 0), not a column index. Access the parent matrix directly: " + |
| 41 | + "mat.At<T>(row, col), or use mat.AsRows<T>() for high-performance loops.", |
| 42 | + helpLinkUri: "https://github.com/shimat/opencvsharp/issues/1775"); |
| 43 | + |
| 44 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics |
| 45 | + => ImmutableArray.Create(Rule); |
| 46 | + |
| 47 | + public override void Initialize(AnalysisContext context) |
| 48 | + { |
| 49 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 50 | + context.EnableConcurrentExecution(); |
| 51 | + context.RegisterSyntaxNodeAction(AnalyzeInvocation, SyntaxKind.InvocationExpression); |
| 52 | + } |
| 53 | + |
| 54 | + private static void AnalyzeInvocation(SyntaxNodeAnalysisContext context) |
| 55 | + { |
| 56 | + var atInvocation = (InvocationExpressionSyntax)context.Node; |
| 57 | + |
| 58 | + if (!IsMatAtIntCall(atInvocation, context.SemanticModel)) |
| 59 | + return; |
| 60 | + |
| 61 | + if (atInvocation.Expression is not MemberAccessExpressionSyntax memberAccess) |
| 62 | + return; |
| 63 | + |
| 64 | + var receiver = memberAccess.Expression; |
| 65 | + |
| 66 | + // Case 1: direct chain — mat.Row(i).At<T>(c) |
| 67 | + if (IsMatRowCall(receiver, context.SemanticModel)) |
| 68 | + { |
| 69 | + context.ReportDiagnostic(Diagnostic.Create(Rule, atInvocation.GetLocation())); |
| 70 | + return; |
| 71 | + } |
| 72 | + |
| 73 | + // Case 2: local variable — var row = mat.Row(i); row.At<T>(c) |
| 74 | + if (receiver is IdentifierNameSyntax identifier && |
| 75 | + context.SemanticModel.GetSymbolInfo(identifier).Symbol is ILocalSymbol local && |
| 76 | + IsLocalDeclaredFromRowCall(local, context.SemanticModel)) |
| 77 | + { |
| 78 | + context.ReportDiagnostic(Diagnostic.Create(Rule, atInvocation.GetLocation())); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + /// <summary> |
| 83 | + /// Returns true when <paramref name="expr"/> is a call to <c>OpenCvSharp.Mat.At<T>(int)</c>. |
| 84 | + /// </summary> |
| 85 | + private static bool IsMatAtIntCall(InvocationExpressionSyntax expr, SemanticModel model) |
| 86 | + { |
| 87 | + if (expr.Expression is not MemberAccessExpressionSyntax ma) |
| 88 | + return false; |
| 89 | + if (ma.Name.Identifier.ValueText != "At") |
| 90 | + return false; |
| 91 | + if (expr.ArgumentList.Arguments.Count != 1) |
| 92 | + return false; |
| 93 | + |
| 94 | + var sym = model.GetSymbolInfo(expr).Symbol as IMethodSymbol; |
| 95 | + return sym is { Parameters.Length: 1 } && |
| 96 | + sym.ContainingType?.ToDisplayString() == "OpenCvSharp.Mat" && |
| 97 | + sym.Parameters[0].Type.SpecialType == SpecialType.System_Int32; |
| 98 | + } |
| 99 | + |
| 100 | + /// <summary> |
| 101 | + /// Returns true when <paramref name="expr"/> is a call to <c>OpenCvSharp.Mat.Row(int)</c>. |
| 102 | + /// </summary> |
| 103 | + private static bool IsMatRowCall(ExpressionSyntax expr, SemanticModel model) |
| 104 | + { |
| 105 | + if (expr is not InvocationExpressionSyntax inv) |
| 106 | + return false; |
| 107 | + if (inv.Expression is not MemberAccessExpressionSyntax ma) |
| 108 | + return false; |
| 109 | + if (ma.Name.Identifier.ValueText != "Row") |
| 110 | + return false; |
| 111 | + |
| 112 | + var sym = model.GetSymbolInfo(inv).Symbol as IMethodSymbol; |
| 113 | + return sym?.ContainingType?.ToDisplayString() == "OpenCvSharp.Mat"; |
| 114 | + } |
| 115 | + |
| 116 | + /// <summary> |
| 117 | + /// Returns true when the local variable's declaration initializer is a call to <c>Mat.Row(int)</c>. |
| 118 | + /// Covers: <c>var row = mat.Row(i);</c> |
| 119 | + /// </summary> |
| 120 | + private static bool IsLocalDeclaredFromRowCall(ILocalSymbol local, SemanticModel model) |
| 121 | + { |
| 122 | + var syntaxRef = local.DeclaringSyntaxReferences.FirstOrDefault(); |
| 123 | + if (syntaxRef?.GetSyntax() is not VariableDeclaratorSyntax { Initializer.Value: { } initializer }) |
| 124 | + return false; |
| 125 | + |
| 126 | + return IsMatRowCall(initializer, model); |
| 127 | + } |
| 128 | +} |
0 commit comments