73 lines
2.0 KiB
Plaintext
73 lines
2.0 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Locking on a local variable 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.
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,csharp]
|
|
----
|
|
private void DoSomething()
|
|
{
|
|
object local = new object();
|
|
// Code potentially modifying the local variable ...
|
|
|
|
lock (local) // Noncompliant
|
|
{
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,csharp]
|
|
----
|
|
private readonly object lockObj = new object();
|
|
|
|
private void DoSomething()
|
|
{
|
|
lock (lockObj)
|
|
{
|
|
//...
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock[Lock Statement] - lock statement - ensure exclusive access to a shared resource
|
|
* CWE - https://cwe.mitre.org/data/definitions/412[CWE-412 - Unrestricted Externally Accessible Lock]
|
|
* CWE - https://cwe.mitre.org/data/definitions/413[CWE-413 - Improper Resource Locking]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Do not lock on local variable "xxx", use a readonly field instead.
|
|
|
|
|
|
=== Highlighting
|
|
|
|
locked object in `lock (xxx)` statement
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== is related to: S2445
|
|
|
|
=== on 3 Mar 2022, 10:46:00 Antonio Aversa wrote:
|
|
Rule derived from the C# version of S2445, due to this branch of the rule generating a lot of FPs.
|
|
|
|
Valid scenarios using local variables include retrieval of the object being locked from a collection or complex logic, to support a fine graned synchronization, renaming of a readonly field in the context of the current method or locking inside a loop, on the iteration variable.
|
|
|
|
The rule still makes sense, however, for all scenarios which don't require advanced synchronization, and prevents synchronization issues captured by S2445 to be circumvented via a local variable. For example via `var local = new object(); lock (local) { ... }`.
|
|
|
|
endif::env-github,rspecator-view[]
|