Skip to content

Commit 77acc7a

Browse files
yoffraulpardoSimonJorgensenMancofibjornarjatten
committed
java: add ThreadSafe query (P3)
Co-authored-by: Raúl Pardo <[email protected]> Co-authored-by: SimonJorgensenMancofi <[email protected]> Co-authored-by: Bjørnar Haugstad Jåtten <[email protected]>
1 parent dfbe08d commit 77acc7a

20 files changed

+1113
-0
lines changed
Lines changed: 337 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,337 @@
1+
/**
2+
* Provides classes and predicates for detecting conflicting accesses in the sense of the Java Memory Model.
3+
*/
4+
5+
import java
6+
import Concurrency
7+
8+
/**
9+
* Holds if `t` is the type of a lock.
10+
* Currently a crude test of the type name.
11+
*/
12+
pragma[inline]
13+
predicate isLockType(Type t) { t.getName().matches("%Lock%") }
14+
15+
/**
16+
* This module provides predicates, chiefly `locallyMonitors`, to check if a given expression is synchronized on a specific monitor.
17+
*/
18+
module Monitors {
19+
/**
20+
* A monitor is any object that is used to synchronize access to a shared resource.
21+
* This includes locks as well as variables used in synchronized blocks (including `this`).
22+
*/
23+
newtype TMonitor =
24+
/** Either a lock or a variable used in a synchronized block. */
25+
TVariableMonitor(Variable v) { isLockType(v.getType()) or locallySynchronizedOn(_, _, v) } or
26+
/** An instance reference used as a monitor. */
27+
TInstanceMonitor(RefType thisType) { locallySynchronizedOnThis(_, thisType) } or
28+
/** A class used as a monitor. */
29+
TClassMonitor(RefType classType) { locallySynchronizedOnClass(_, classType) }
30+
31+
/**
32+
* A monitor is any object that is used to synchronize access to a shared resource.
33+
* This includes locks as well as variables used in synchronized blocks (including `this`).
34+
*/
35+
class Monitor extends TMonitor {
36+
/** Gets the location of this monitor. */
37+
abstract Location getLocation();
38+
39+
/** Gets a textual representation of this element. */
40+
string toString() { result = "Monitor" }
41+
}
42+
43+
/**
44+
* Either a lock or a variable used in a synchronized block.
45+
* E.g `synchronized (m) { ... }` or `m.lock();`
46+
*/
47+
class VariableMonitor extends Monitor, TVariableMonitor {
48+
Variable v;
49+
50+
VariableMonitor() { this = TVariableMonitor(v) }
51+
52+
override Location getLocation() { result = v.getLocation() }
53+
54+
override string toString() { result = "VariableMonitor(" + v.toString() + ")" }
55+
56+
/** Gets the variable being used as a monitor. */
57+
Variable getVariable() { result = v }
58+
}
59+
60+
/**
61+
* An instance reference used as a monitor.
62+
* Either via `synchronized (this) { ... }` or by marking a non-static method as `synchronized`.
63+
*/
64+
class InstanceMonitor extends Monitor, TInstanceMonitor {
65+
RefType thisType;
66+
67+
InstanceMonitor() { this = TInstanceMonitor(thisType) }
68+
69+
override Location getLocation() { result = thisType.getLocation() }
70+
71+
override string toString() { result = "InstanceMonitor(" + thisType.toString() + ")" }
72+
73+
/** Gets the instance reference being used as a monitor. */
74+
RefType getThisType() { result = thisType }
75+
}
76+
77+
/**
78+
* A class used as a monitor.
79+
* This is achieved by marking a static method as `synchronized`.
80+
*/
81+
class ClassMonitor extends Monitor, TClassMonitor {
82+
RefType classType;
83+
84+
ClassMonitor() { this = TClassMonitor(classType) }
85+
86+
override Location getLocation() { result = classType.getLocation() }
87+
88+
override string toString() { result = "ClassMonitor(" + classType.toString() + ")" }
89+
90+
/** Gets the class being used as a monitor. */
91+
RefType getClassType() { result = classType }
92+
}
93+
94+
/** Holds if the expression `e` is synchronized on the monitor `m`. */
95+
predicate locallyMonitors(Expr e, Monitor m) {
96+
exists(Variable v | v = m.(VariableMonitor).getVariable() |
97+
locallyLockedOn(e, v)
98+
or
99+
locallySynchronizedOn(e, _, v)
100+
)
101+
or
102+
locallySynchronizedOnThis(e, m.(InstanceMonitor).getThisType())
103+
or
104+
locallySynchronizedOnClass(e, m.(ClassMonitor).getClassType())
105+
}
106+
107+
/** Holds if `localLock` refers to `lock`. */
108+
predicate represents(Field lock, Variable localLock) {
109+
isLockType(lock.getType()) and
110+
(
111+
localLock = lock
112+
or
113+
localLock.getInitializer() = lock.getAnAccess()
114+
)
115+
}
116+
117+
/** Holds if `e` is synchronized on the `Lock` `lock` by a locking call. */
118+
predicate locallyLockedOn(Expr e, Field lock) {
119+
isLockType(lock.getType()) and
120+
exists(Variable localLock, MethodCall lockCall, MethodCall unlockCall |
121+
represents(lock, localLock) and
122+
lockCall.getQualifier() = localLock.getAnAccess() and
123+
lockCall.getMethod().getName() in ["lock", "lockInterruptibly", "tryLock"] and
124+
unlockCall.getQualifier() = localLock.getAnAccess() and
125+
unlockCall.getMethod().getName() = "unlock"
126+
|
127+
dominates(lockCall.getControlFlowNode(), unlockCall.getControlFlowNode()) and
128+
dominates(lockCall.getControlFlowNode(), e.getControlFlowNode()) and
129+
postDominates(unlockCall.getControlFlowNode(), e.getControlFlowNode())
130+
)
131+
}
132+
}
133+
134+
/** Provides predicates, chiefly `isModifying`, to check if a given expression modifies a shared resource. */
135+
module Modification {
136+
import semmle.code.java.dataflow.FlowSummary
137+
138+
/** Holds if the field access `a` modifies a shared resource. */
139+
predicate isModifying(FieldAccess a) {
140+
a.isVarWrite()
141+
or
142+
exists(Call c | c.(MethodCall).getQualifier() = a | isModifyingCall(c))
143+
or
144+
exists(ArrayAccess aa, Assignment asa | aa.getArray() = a | asa.getDest() = aa)
145+
}
146+
147+
/** Holds if the call `c` modifies a shared resource. */
148+
predicate isModifyingCall(Call c) {
149+
exists(SummarizedCallable sc, string output, string prefix | sc.getACall() = c |
150+
sc.propagatesFlow(_, output, _, _) and
151+
prefix = "Argument[this]" and
152+
output.prefix(prefix.length()) = prefix
153+
)
154+
}
155+
}
156+
157+
/** Holds if the class is annotated as `@ThreadSafe`. */
158+
Class annotatedAsThreadSafe() { result.getAnAnnotation().getType().getName() = "ThreadSafe" }
159+
160+
/** Holds if the type `t` is thread-safe. */
161+
predicate isThreadSafeType(Type t) {
162+
t.getName().matches(["Atomic%", "Concurrent%"])
163+
or
164+
t.getName() in [
165+
"CopyOnWriteArraySet", "BlockingQueue", "ThreadLocal",
166+
// this is a method that returns a thread-safe version of the collection used as parameter
167+
"synchronizedMap", "Executor", "ExecutorService", "CopyOnWriteArrayList",
168+
"LinkedBlockingDeque", "LinkedBlockingQueue", "CompletableFuture"
169+
]
170+
or
171+
t = annotatedAsThreadSafe()
172+
}
173+
174+
/**
175+
* Represents a field access that is exposed to potential data races.
176+
* We require the field to be in a class that is annotated as `@ThreadSafe`.
177+
*/
178+
class ExposedFieldAccess extends FieldAccess {
179+
ExposedFieldAccess() {
180+
this.getField() = annotatedAsThreadSafe().getAField() and
181+
not this.getField().isVolatile() and
182+
// field is not a lock
183+
not isLockType(this.getField().getType()) and
184+
// field is not thread-safe
185+
not isThreadSafeType(this.getField().getType()) and
186+
not isThreadSafeType(this.getField().getInitializer().getType()) and
187+
// access is not the initializer of the field
188+
not this.(VarWrite).getASource() = this.getField().getInitializer() and
189+
// access not in a constructor
190+
not this.getEnclosingCallable() = this.getField().getDeclaringType().getAConstructor() and
191+
// not a field on a local variable
192+
not this.getQualifier+().(VarAccess).getVariable() instanceof LocalVariableDecl and
193+
// not the variable mention in a synchronized statement
194+
not this = any(SynchronizedStmt sync).getExpr()
195+
}
196+
197+
// LHS of assignments are excluded from the control flow graph,
198+
// so we use the control flow node for the assignment itself instead.
199+
override ControlFlowNode getControlFlowNode() {
200+
// this is the LHS of an assignment, use the control flow node for the assignment
201+
exists(Assignment asgn | asgn.getDest() = this | result = asgn.getControlFlowNode())
202+
or
203+
// this is not the LHS of an assignment, use the default control flow node
204+
not exists(Assignment asgn | asgn.getDest() = this) and
205+
result = super.getControlFlowNode()
206+
}
207+
}
208+
209+
/** Holds if the location of `a` is strictly before the location of `b`. */
210+
pragma[inline]
211+
predicate orderedLocations(Location a, Location b) {
212+
a.getStartLine() < b.getStartLine()
213+
or
214+
a.getStartLine() = b.getStartLine() and
215+
a.getStartColumn() < b.getStartColumn()
216+
}
217+
218+
/**
219+
* A class annotated as `@ThreadSafe`.
220+
* Provides predicates to check for concurrency issues.
221+
*/
222+
class ClassAnnotatedAsThreadSafe extends Class {
223+
ClassAnnotatedAsThreadSafe() { this = annotatedAsThreadSafe() }
224+
225+
/** Holds if `a` and `b` are conflicting accesses to the same field and not monitored by the same monitor. */
226+
predicate unsynchronised(ExposedFieldAccess a, ExposedFieldAccess b) {
227+
this.conflicting(a, b) and
228+
this.publicAccess(_, a) and
229+
this.publicAccess(_, b) and
230+
not exists(Monitors::Monitor m |
231+
this.monitors(a, m) and
232+
this.monitors(b, m)
233+
)
234+
}
235+
236+
/** Holds if `a` is the earliest write to its field that is unsynchronized with `b`. */
237+
predicate unsynchronised_normalized(ExposedFieldAccess a, ExposedFieldAccess b) {
238+
this.unsynchronised(a, b) and
239+
// Eliminate double reporting by making `a` the earliest write to this field
240+
// that is unsynchronized with `b`.
241+
not exists(ExposedFieldAccess earlier_a |
242+
earlier_a.getField() = a.getField() and
243+
orderedLocations(earlier_a.getLocation(), a.getLocation())
244+
|
245+
this.unsynchronised(earlier_a, b)
246+
)
247+
}
248+
249+
/**
250+
* Holds if `a` and `b` are unsynchronized and both publicly accessible
251+
* as witnessed by `witness_a` and `witness_b`.
252+
*/
253+
predicate witness(ExposedFieldAccess a, Expr witness_a, ExposedFieldAccess b, Expr witness_b) {
254+
this.unsynchronised_normalized(a, b) and
255+
this.publicAccess(witness_a, a) and
256+
this.publicAccess(witness_b, b) and
257+
// avoid double reporting
258+
not exists(Expr better_witness_a | this.publicAccess(better_witness_a, a) |
259+
orderedLocations(better_witness_a.getLocation(), witness_a.getLocation())
260+
) and
261+
not exists(Expr better_witness_b | this.publicAccess(better_witness_b, b) |
262+
orderedLocations(better_witness_b.getLocation(), witness_b.getLocation())
263+
)
264+
}
265+
266+
/**
267+
* Actions `a` and `b` are conflicting iff
268+
* they are field access operations on the same field and
269+
* at least one of them is a write.
270+
*/
271+
predicate conflicting(ExposedFieldAccess a, ExposedFieldAccess b) {
272+
// We allow a = b, since they could be executed on different threads
273+
// We are looking for two operations:
274+
// - on the same non-volatile field
275+
a.getField() = b.getField() and
276+
// - on this class
277+
a.getField() = this.getAField() and
278+
// - where at least one is a write
279+
// wlog we assume that is `a`
280+
// We use a slightly more inclusive definition than simply `a.isVarWrite()`
281+
Modification::isModifying(a) and
282+
// Avoid reporting both `(a, b)` and `(b, a)` by choosing the tuple
283+
// where `a` appears before `b` in the source code.
284+
(
285+
(
286+
Modification::isModifying(b) and
287+
a != b
288+
)
289+
implies
290+
orderedLocations(a.getLocation(), b.getLocation())
291+
)
292+
}
293+
294+
/** Holds if `a` can be reached by a path from a public method, and all such paths are monitored by `monitor`. */
295+
predicate monitors(ExposedFieldAccess a, Monitors::Monitor monitor) {
296+
forex(Method m | this.providesAccess(m, _, a) and m.isPublic() |
297+
this.monitorsVia(m, a, monitor)
298+
)
299+
}
300+
301+
/** Holds if `a` can be reached by a path from a public method and `e` is the expression in that method that stsarts the path. */
302+
predicate publicAccess(Expr e, ExposedFieldAccess a) {
303+
exists(Method m | m.isPublic() | this.providesAccess(m, e, a))
304+
}
305+
306+
/**
307+
* Holds if a call to method `m` can cause an access of `a` and `e` is the expression inside `m` that leads to that access.
308+
* `e` will either be `a` itself or a method call that leads to `a`.
309+
*/
310+
predicate providesAccess(Method m, Expr e, ExposedFieldAccess a) {
311+
m = this.getAMethod() and
312+
(
313+
a.getEnclosingCallable() = m and
314+
e = a
315+
or
316+
exists(MethodCall c | c.getEnclosingCallable() = m |
317+
this.providesAccess(c.getCallee(), _, a) and
318+
e = c
319+
)
320+
)
321+
}
322+
323+
/** Holds if all paths from `m` to `a` are monitored by `monitor`. */
324+
predicate monitorsVia(Method m, ExposedFieldAccess a, Monitors::Monitor monitor) {
325+
m = this.getAMethod() and
326+
this.providesAccess(m, _, a) and
327+
(a.getEnclosingCallable() = m implies Monitors::locallyMonitors(a, monitor)) and
328+
forall(MethodCall c |
329+
c.getEnclosingCallable() = m and
330+
this.providesAccess(c.getCallee(), _, a)
331+
|
332+
Monitors::locallyMonitors(c, monitor)
333+
or
334+
this.monitorsVia(c.getCallee(), a, monitor)
335+
)
336+
}
337+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<!DOCTYPE qhelp PUBLIC
2+
"-//Semmle//qhelp//EN"
3+
"qhelp.dtd">
4+
<qhelp>
5+
6+
7+
<overview>
8+
<p>
9+
In a thread-safe class, all field accesses that can be caused by calls to public methods must be properly synchronized.</p>
10+
11+
</overview>
12+
<recommendation>
13+
14+
<p>
15+
Protect the field access with a lock. Alternatively mark the field as <code>volatile</code> if the write operation is atomic. You can also choose to use a data type that guarantees atomic access. If the field is immutable, mark it as <code>final</code>.</p>
16+
17+
</recommendation>
18+
19+
<references>
20+
21+
22+
<li>
23+
Java Language Specification, chapter 17:
24+
<a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4">Threads and Locks</a>.
25+
</li>
26+
<li>
27+
Java concurrency package:
28+
<a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html">java.util.concurrent</a>.
29+
</li>
30+
31+
32+
</references>
33+
</qhelp>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @id java/not-threadsafe
3+
* @name Not thread-safe
4+
* @description This class is not thread-safe. It is annotated as `@ThreadSafe`, but it has a
5+
* conflicting access to a field that is not synchronized with the same monitor.
6+
* @kind problem
7+
* @problem.severity warning
8+
*/
9+
10+
import java
11+
import semmle.code.java.ConflictingAccess
12+
13+
from
14+
ClassAnnotatedAsThreadSafe cls, FieldAccess modifyingAccess, Expr witness_modifyingAccess,
15+
FieldAccess conflictingAccess, Expr witness_conflictingAccess
16+
where
17+
cls.witness(modifyingAccess, witness_modifyingAccess, conflictingAccess, witness_conflictingAccess)
18+
select modifyingAccess,
19+
"This modifying field access (publicly accessible via $@) is conflicting with $@ (publicly accessible via $@) because they are not synchronized with the same monitor.",
20+
witness_modifyingAccess, "this expression", conflictingAccess, "this field access",
21+
witness_conflictingAccess, "this expression"
22+
// select c, a.getField()

0 commit comments

Comments
 (0)