Skip to content
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

New Rule S2445: Blocks should be synchronized on read-only fields #6750

Merged
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 17 additions & 0 deletions analyzers/its/expected/Automapper/AutoMapper--net461-S2445.json
@@ -0,0 +1,17 @@
{
"issues": [
{
Copy link
Contributor Author

Choose a reason for hiding this comment

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

By looking at this test case, I have some doubts about the validity of the rule on local method variables.

The code for this IT is the following:

TypeMap ResolveTypeMap(in TypePair typePair)
{
    if (_resolvedMaps.TryGetValue(typePair, out TypeMap typeMap))
    {
        return typeMap;
    }
    if (_sealed)
    {
        typeMap = _runtimeMaps.GetOrAdd(typePair);
        // if it's a dynamically created type map, we need to seal it outside GetTypeMap to handle recursion
        if (typeMap != null && typeMap.MapExpression == null)
        {
            lock (typeMap)
            {
                typeMap.Seal(this, null);
            }
        }
    }
    else
    {
        typeMap = GetTypeMap(typePair);
        _resolvedMaps.Add(typePair, typeMap);
    }
    return typeMap;
}

While typeMap is a local variable, which can mutate, it is read from _runtimeMaps.GetOrAdd(typePair), which is a private readonly LockingConcurrentDictionary<TypePair, TypeMap>.

So basically the variable itself is not immutable, but the collection from which is read it is, and such a collection is used to have fine-graned locking based on TypePair.

While this all seems perfectly legitimate to me, and even necessary when you need a variable number of locks, I don't see how to easily distinguish between this scenario and the other ones.

Do we accept it as a false positive, or do we reduce the scope of the rule, to just ignore local variables?

What do you think?

Copy link
Contributor

Choose a reason for hiding this comment

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

I think it can be refined by adding an exception to the rule: if the code block is locked on a local variable and that local variable is assigned the value of a method call then it should be ignored.

var localVar = MethodCall();
...
lock (localVar) // Compliant
{
  ...
}

But I'd do this in a separate PR, and mark it as FP for now.

@andrei-epure-sonarsource What do you think?

Copy link
Contributor

Choose a reason for hiding this comment

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

sorry I didn't reply. If it's an edge case, it's acceptable to have an FP.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

While it appears in our ITs, it seems to me enough rare, to consider it as an FP.

"id": "S2445",
"message": "Do not lock on local variable 'typeMap', use a readonly field instead.",
"location": {
"uri": "sources\Automapper\src\AutoMapper\Configuration\MapperConfiguration.cs",
"region": {
"startLine": 256,
"startColumn": 27,
"endLine": 256,
"endColumn": 34
}
}
}
]
}
@@ -0,0 +1,17 @@
{
"issues": [
{
"id": "S2445",
"message": "Do not lock on local variable 'typeMap', use a readonly field instead.",
"location": {
"uri": "sources\Automapper\src\AutoMapper\Configuration\MapperConfiguration.cs",
"region": {
"startLine": 256,
"startColumn": 27,
"endLine": 256,
"endColumn": 34
}
}
}
]
}
17 changes: 17 additions & 0 deletions analyzers/its/expected/Nancy/Nancy--net452-S2445.json
@@ -0,0 +1,17 @@
{
"issues": [
{
"id": "S2445",
"message": "Do not lock on writable field 'entitiesLock', use a readonly field instead.",
"location": {
"uri": "sources\Nancy\src\Nancy\Helpers\HttpEncoder.cs",
"region": {
"startLine": 62,
"startColumn": 23,
"endLine": 62,
"endColumn": 35
}
}
}
]
}
17 changes: 17 additions & 0 deletions analyzers/its/expected/Nancy/Nancy--netstandard2.0-S2445.json
@@ -0,0 +1,17 @@
{
"issues": [
{
"id": "S2445",
"message": "Do not lock on writable field 'entitiesLock', use a readonly field instead.",
"location": {
"uri": "sources\Nancy\src\Nancy\Helpers\HttpEncoder.cs",
"region": {
"startLine": 62,
"startColumn": 23,
"endLine": 62,
"endColumn": 35
}
}
}
]
}
58 changes: 58 additions & 0 deletions analyzers/rspec/cs/S2445_c#.html
@@ -0,0 +1,58 @@
<p>Locking on a class field synchronizes not on the field itself, but on the object assigned to it. Thus, there are some good practices to follow to
avoid bugs related to thread synchronization.</p>
<ol>
<li> Locking on a non-<code>readonly</code> field makes it possible for the field’s value to change while a thread is in the code block locked on
the old value. This allows another thread to lock on the new value and access the same block concurrently. </li>
<li> Locking on a local variable or a new instance of an object can undermine synchronization because two different threads running the same method
in parallel will potentially lock on different instances of the same object, allowing them to access the synchronized block at the same time. </li>
<li> Locking on a string literal is also dangerous since, depending on whether the string is interned or not, different threads may or may not
synchronize on the same object instance. </li>
</ol>
<h2>Noncompliant Code Example</h2>
<pre>
private Color color = new Color("red");
private readonly string colorString = "red";

private void DoSomething()
{
// Synchronizing access via "color"
lock (color) // Noncompliant; lock is actually on object instance "red" referred to by the "color" field
{
//...
color = new Color("green"); // other threads now allowed into this block
// ...
}
lock (new object()) // Noncompliant; this is a no-op
{
// ...
}
lock (colorString) // Noncompliant; strings can be interned
{
// ...
}
}
</pre>
<h2>Compliant Solution</h2>
<pre>
private Color color = new Color("red");
private readonly object lockObj = new object();

private void DoSomething()
{
lock (lockObj)
{
//...
color = new Color("green");
// ...
}
}
</pre>
<h2>See</h2>
<ul>
<li> <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock">Lock Statement</a> - lock statement - ensure
exclusive access to a shared resource </li>
<li> <a href="https://learn.microsoft.com/en-us/dotnet/api/system.string.intern">String.Intern</a> - <code>String.Intern(String)</code> Method </li>
<li> <a href="https://cwe.mitre.org/data/definitions/412">MITRE, CWE-412</a> - Unrestricted Externally Accessible Lock </li>
<li> <a href="https://cwe.mitre.org/data/definitions/413">MITRE, CWE-413</a> - Improper Resource Locking </li>
</ul>

24 changes: 24 additions & 0 deletions analyzers/rspec/cs/S2445_c#.json
@@ -0,0 +1,24 @@
{
"title": "Blocks should be synchronized on read-only fields",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "15min"
},
"tags": [
"cwe",
"multi-threading"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-2445",
"sqKey": "S2445",
"scope": "All",
"securityStandards": {
"CWE": [
412,
413
]
},
"quickfix": "unknown"
}
1 change: 1 addition & 0 deletions analyzers/rspec/cs/Sonar_way_profile.json
Expand Up @@ -99,6 +99,7 @@
"S2386",
"S2436",
"S2437",
"S2445",
"S2479",
"S2486",
"S2551",
Expand Down
@@ -0,0 +1,79 @@
/*
* SonarAnalyzer for .NET
* Copyright (C) 2015-2023 SonarSource SA
* mailto: contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

namespace SonarAnalyzer.Rules.CSharp;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class LockedFieldShouldBeReadonly : SonarDiagnosticAnalyzer
{
private const string DiagnosticId = "S2445";

private static readonly DiagnosticDescriptor Rule = DescriptorFactory.Create(DiagnosticId, "Do not lock on {0}, use a readonly field instead.");

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);

protected override void Initialize(SonarAnalysisContext context) =>
context.RegisterNodeAction(CheckLockStatement, SyntaxKind.LockStatement);

private static void CheckLockStatement(SonarSyntaxNodeReportingContext context)
{
var expression = ((LockStatementSyntax)context.Node).Expression?.RemoveParentheses();
if (IsCreation(expression))
{
ReportIssue("a new instance because is a no-op");
}
else
{
var lazySymbol = new Lazy<ISymbol>(() => context.SemanticModel.GetSymbolInfo(expression).Symbol);
if (IsOfTypeString(expression, lazySymbol))
{
ReportIssue("strings as they can be interned");
}
else if (expression is IdentifierNameSyntax && lazySymbol.Value is ILocalSymbol lockedSymbol)
Copy link
Contributor

Choose a reason for hiding this comment

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

All of them are locked, this branch is distinguished by being local

Suggested change
else if (expression is IdentifierNameSyntax && lazySymbol.Value is ILocalSymbol lockedSymbol)
else if (expression is IdentifierNameSyntax && lazySymbol.Value is ILocalSymbol localSymbol)

{
ReportIssue($"local variable '{lockedSymbol.Name}'");
}
else if (FieldWritable(expression, lazySymbol) is { } lockedField)
{
ReportIssue($"writable field '{lockedField.Name}'");
}
}

void ReportIssue(string message) =>
context.ReportIssue(Diagnostic.Create(Rule, expression.GetLocation(), message));
}

private static bool IsCreation(ExpressionSyntax expression) =>
expression.IsAnyKind(
SyntaxKind.ObjectCreationExpression,
SyntaxKind.AnonymousObjectCreationExpression,
SyntaxKind.ArrayCreationExpression,
SyntaxKind.ImplicitArrayCreationExpression,
SyntaxKind.QueryExpression);

private static bool IsOfTypeString(ExpressionSyntax expression, Lazy<ISymbol> lazySymbol) =>
expression.IsAnyKind(SyntaxKind.StringLiteralExpression, SyntaxKind.InterpolatedStringExpression)
pavel-mikula-sonarsource marked this conversation as resolved.
Show resolved Hide resolved
|| lazySymbol.Value.GetSymbolType().Is(KnownType.System_String);

private static IFieldSymbol FieldWritable(ExpressionSyntax expression, Lazy<ISymbol> lazySymbol) =>
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
private static IFieldSymbol FieldWritable(ExpressionSyntax expression, Lazy<ISymbol> lazySymbol) =>
private static IFieldSymbol FieldIsWritable(ExpressionSyntax expression, Lazy<ISymbol> lazySymbol) =>

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The name FieldIsWritable seems to assume that the expression provided as input is necessarily a field.
In this case the method receives an ExpressionSyntax which may or may not be a field: for example it may be a SimpleMemberAccessExpressionSyntax accessing a property, for which Expression would be an IPropertySymbol.

IsFieldWritable would already be a better name, but imo violates the principle of least astonishment: one would expect a method starting with Is to return a bool. Instead, this method returns a IFieldSymbol which may or may not be null, depending on whether all the conditions of "being a member", "referring to a field" and "being a non-readonly field" are respected.

The closest semantics to this is the one of (a very elaborate) as operator: if you prefer, I may change the name into AsWritableField. WritableField may suggest a "cast" semantic, i.e. it may suggest throwing an exception rather than returning null.

However, I would avoid IsFieldWritable or FieldIsWritable... unless there is a specific code convention driving the choice. If there's not, I would assume any options of the ones above, except maybe IsFieldWritable due to POLA violation, should be considered valid for this PR.

Copy link
Contributor

Choose a reason for hiding this comment

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

🤦 my bad - you are right.
I think I'd just change it then to FindWritableField or ExtractFieldSymbol or something a bit more descriptive if you have other ideas.
IMO just FieldWritable is a bit confusing.

expression.IsAnyKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression) && lazySymbol.Value is IFieldSymbol lockedField && !lockedField.IsReadOnly
? lockedField
: null;
}
Expand Up @@ -2369,7 +2369,7 @@ internal static class RuleTypeMappingCS
// ["S2442"],
// ["S2443"],
// ["S2444"],
// ["S2445"],
["S2445"] = "BUG",
// ["S2446"],
// ["S2447"],
// ["S2448"],
Expand Down
@@ -0,0 +1,54 @@
/*
* SonarAnalyzer for .NET
* Copyright (C) 2015-2023 SonarSource SA
* mailto: contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

using SonarAnalyzer.Rules.CSharp;

namespace SonarAnalyzer.UnitTest.Rules;

[TestClass]
public class LockedFieldShouldBeReadonlyTest
{
private readonly VerifierBuilder builder = new VerifierBuilder<LockedFieldShouldBeReadonly>();

[TestMethod]
public void LockedFieldShouldBeReadonly_CS() =>
builder.AddPaths("LockedFieldShouldBeReadonly.cs").Verify();

[TestMethod]
public void LockedFieldShouldBeReadonly_CSharp8() =>
builder
.AddPaths("LockedFieldShouldBeReadonly.CSharp8.cs")
.WithOptions(ParseOptionsHelper.FromCSharp8)
.Verify();

[TestMethod]
public void LockedFieldShouldBeReadonly_CSharp9() =>
builder
.AddPaths("LockedFieldShouldBeReadonly.CSharp9.cs")
.WithOptions(ParseOptionsHelper.FromCSharp9)
.Verify();

[TestMethod]
public void LockedFieldShouldBeReadonly_CSharp11() =>
builder
.AddPaths("LockedFieldShouldBeReadonly.CSharp11.cs")
.WithOptions(ParseOptionsHelper.FromCSharp11)
.Verify();
}
@@ -0,0 +1,21 @@
using System;

class Test
{
static readonly object staticReadonlyField = null;
static object staticReadWriteField = null;
Copy link
Contributor

Choose a reason for hiding this comment

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

None of the fields here is used => remove them all


readonly object readonlyField = null;
object readWriteField = null;
Copy link
Contributor

Choose a reason for hiding this comment

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

These seem to be unused fields - in case they should be deleted to reduce the noise.


void OnANewInstance()
{
lock ("""a raw string literal""") { } // Noncompliant
lock ($"""an interpolated {"raw string literal"}""") { } // Noncompliant
}

void TargetTypedObjectCreation()
{
lock (new() as Tuple<int>) { } // Error [CS8754]
}
}
@@ -0,0 +1,46 @@
class Test
{
static readonly object staticReadonlyField = null;
static object staticReadWriteField = null;
Copy link
Contributor

Choose a reason for hiding this comment

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

Same for this - it can be deleted.

Copy link
Contributor

Choose a reason for hiding this comment

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

3 out of 4 should be removed

Copy link
Contributor Author

Choose a reason for hiding this comment

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

staticReadWriteField seems the only one which is not used anymore:

  • staticReadonlyField reference is returned on line 29
  • readonlyField reference is returned on line 14
  • readWriteField reference is returned on line 17

@pavel-mikula-sonarsource: was it rather 3 out of 4 to be kept?


readonly object readonlyField = null;
object readWriteField = null;

Test()
{
ref object refToReadonlyField = ref readonlyField;
lock (refToReadonlyField) { } // Noncompliant, while the reference is to a readonly field, the reference itself is a local variable and as of C# 7.3 can be ref reassigned

ref object refToReadWriteField = ref readWriteField;
lock (refToReadWriteField) { } // Noncompliant
}

void ReadonlyReferences()
{
lock (RefReturnReadonlyField(this)) { }
lock (RefReturnStaticReadonlyField()) { }
lock (StaticRefReturnReadonlyField(this)) { }
lock (StaticRefReturnStaticReadonlyField()) { }

ref readonly object RefReturnReadonlyField(Test instance) => ref instance.readonlyField;
ref readonly object RefReturnStaticReadonlyField() => ref Test.staticReadonlyField;
static ref readonly object StaticRefReturnReadonlyField(Test instance) => ref instance.readonlyField;
static ref readonly object StaticRefReturnStaticReadonlyField() => ref Test.staticReadonlyField;
}

void OnANewInstanceOnStack()
{
lock (stackalloc int[] { }) { } // Error [CS0185]
lock (stackalloc [] { 1 }) { } // Error [CS0185]
}

void CoalescingAssignment(object oPar)
{
lock (oPar ??= readonlyField) { } // FN, null conditional assignment not supported
}

void SwitchExpression(object oPar)
{
lock (oPar switch { _ => new object() }) { } // FN, switch expression not supported
}
}