1 //===--- PthreadLockChecker.cpp - Check for locking problems ---*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines PthreadLockChecker, a simple lock -> unlock checker.
11 // Also handles XNU locks, which behave similarly enough to share code.
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.h"
16 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
17 #include "clang/StaticAnalyzer/Core/Checker.h"
18 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
22 using namespace clang;
28 enum Kind { Destroyed, Locked, Unlocked } K;
31 LockState(Kind K) : K(K) {}
34 static LockState getLocked() { return LockState(Locked); }
35 static LockState getUnlocked() { return LockState(Unlocked); }
36 static LockState getDestroyed() { return LockState(Destroyed); }
38 bool operator==(const LockState &X) const {
42 bool isLocked() const { return K == Locked; }
43 bool isUnlocked() const { return K == Unlocked; }
44 bool isDestroyed() const { return K == Destroyed; }
46 void Profile(llvm::FoldingSetNodeID &ID) const {
51 class PthreadLockChecker : public Checker< check::PostStmt<CallExpr> > {
52 mutable std::unique_ptr<BugType> BT_doublelock;
53 mutable std::unique_ptr<BugType> BT_doubleunlock;
54 mutable std::unique_ptr<BugType> BT_destroylock;
55 mutable std::unique_ptr<BugType> BT_initlock;
56 mutable std::unique_ptr<BugType> BT_lor;
57 enum LockingSemantics {
63 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
65 void AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock,
66 bool isTryLock, enum LockingSemantics semantics) const;
68 void ReleaseLock(CheckerContext &C, const CallExpr *CE, SVal lock) const;
69 void DestroyLock(CheckerContext &C, const CallExpr *CE, SVal Lock) const;
70 void InitLock(CheckerContext &C, const CallExpr *CE, SVal Lock) const;
71 void reportUseDestroyedBug(CheckerContext &C, const CallExpr *CE) const;
73 } // end anonymous namespace
75 // GDM Entry for tracking lock state.
76 REGISTER_LIST_WITH_PROGRAMSTATE(LockSet, const MemRegion *)
78 REGISTER_MAP_WITH_PROGRAMSTATE(LockMap, const MemRegion *, LockState)
80 void PthreadLockChecker::checkPostStmt(const CallExpr *CE,
81 CheckerContext &C) const {
82 ProgramStateRef state = C.getState();
83 const LocationContext *LCtx = C.getLocationContext();
84 StringRef FName = C.getCalleeName(CE);
88 if (CE->getNumArgs() != 1 && CE->getNumArgs() != 2)
91 if (FName == "pthread_mutex_lock" ||
92 FName == "pthread_rwlock_rdlock" ||
93 FName == "pthread_rwlock_wrlock")
94 AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
95 false, PthreadSemantics);
96 else if (FName == "lck_mtx_lock" ||
97 FName == "lck_rw_lock_exclusive" ||
98 FName == "lck_rw_lock_shared")
99 AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
100 false, XNUSemantics);
101 else if (FName == "pthread_mutex_trylock" ||
102 FName == "pthread_rwlock_tryrdlock" ||
103 FName == "pthread_rwlock_trywrlock")
104 AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
105 true, PthreadSemantics);
106 else if (FName == "lck_mtx_try_lock" ||
107 FName == "lck_rw_try_lock_exclusive" ||
108 FName == "lck_rw_try_lock_shared")
109 AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
111 else if (FName == "pthread_mutex_unlock" ||
112 FName == "pthread_rwlock_unlock" ||
113 FName == "lck_mtx_unlock" ||
114 FName == "lck_rw_done")
115 ReleaseLock(C, CE, state->getSVal(CE->getArg(0), LCtx));
116 else if (FName == "pthread_mutex_destroy" ||
117 FName == "lck_mtx_destroy")
118 DestroyLock(C, CE, state->getSVal(CE->getArg(0), LCtx));
119 else if (FName == "pthread_mutex_init")
120 InitLock(C, CE, state->getSVal(CE->getArg(0), LCtx));
123 void PthreadLockChecker::AcquireLock(CheckerContext &C, const CallExpr *CE,
124 SVal lock, bool isTryLock,
125 enum LockingSemantics semantics) const {
127 const MemRegion *lockR = lock.getAsRegion();
131 ProgramStateRef state = C.getState();
133 SVal X = state->getSVal(CE, C.getLocationContext());
134 if (X.isUnknownOrUndef())
137 DefinedSVal retVal = X.castAs<DefinedSVal>();
139 if (const LockState *LState = state->get<LockMap>(lockR)) {
140 if (LState->isLocked()) {
142 BT_doublelock.reset(new BugType(this, "Double locking",
144 ExplodedNode *N = C.generateErrorNode();
147 auto report = llvm::make_unique<BugReport>(
148 *BT_doublelock, "This lock has already been acquired", N);
149 report->addRange(CE->getArg(0)->getSourceRange());
150 C.emitReport(std::move(report));
152 } else if (LState->isDestroyed()) {
153 reportUseDestroyedBug(C, CE);
158 ProgramStateRef lockSucc = state;
160 // Bifurcate the state, and allow a mode where the lock acquisition fails.
161 ProgramStateRef lockFail;
163 case PthreadSemantics:
164 std::tie(lockFail, lockSucc) = state->assume(retVal);
167 std::tie(lockSucc, lockFail) = state->assume(retVal);
170 llvm_unreachable("Unknown tryLock locking semantics");
172 assert(lockFail && lockSucc);
173 C.addTransition(lockFail);
175 } else if (semantics == PthreadSemantics) {
176 // Assume that the return value was 0.
177 lockSucc = state->assume(retVal, false);
181 // XNU locking semantics return void on non-try locks
182 assert((semantics == XNUSemantics) && "Unknown locking semantics");
186 // Record that the lock was acquired.
187 lockSucc = lockSucc->add<LockSet>(lockR);
188 lockSucc = lockSucc->set<LockMap>(lockR, LockState::getLocked());
189 C.addTransition(lockSucc);
192 void PthreadLockChecker::ReleaseLock(CheckerContext &C, const CallExpr *CE,
195 const MemRegion *lockR = lock.getAsRegion();
199 ProgramStateRef state = C.getState();
201 if (const LockState *LState = state->get<LockMap>(lockR)) {
202 if (LState->isUnlocked()) {
203 if (!BT_doubleunlock)
204 BT_doubleunlock.reset(new BugType(this, "Double unlocking",
206 ExplodedNode *N = C.generateErrorNode();
209 auto Report = llvm::make_unique<BugReport>(
210 *BT_doubleunlock, "This lock has already been unlocked", N);
211 Report->addRange(CE->getArg(0)->getSourceRange());
212 C.emitReport(std::move(Report));
214 } else if (LState->isDestroyed()) {
215 reportUseDestroyedBug(C, CE);
220 LockSetTy LS = state->get<LockSet>();
222 // FIXME: Better analysis requires IPA for wrappers.
225 const MemRegion *firstLockR = LS.getHead();
226 if (firstLockR != lockR) {
228 BT_lor.reset(new BugType(this, "Lock order reversal", "Lock checker"));
229 ExplodedNode *N = C.generateErrorNode();
232 auto report = llvm::make_unique<BugReport>(
233 *BT_lor, "This was not the most recently acquired lock. Possible "
234 "lock order reversal", N);
235 report->addRange(CE->getArg(0)->getSourceRange());
236 C.emitReport(std::move(report));
239 // Record that the lock was released.
240 state = state->set<LockSet>(LS.getTail());
243 state = state->set<LockMap>(lockR, LockState::getUnlocked());
244 C.addTransition(state);
247 void PthreadLockChecker::DestroyLock(CheckerContext &C, const CallExpr *CE,
250 const MemRegion *LockR = Lock.getAsRegion();
254 ProgramStateRef State = C.getState();
256 const LockState *LState = State->get<LockMap>(LockR);
257 if (!LState || LState->isUnlocked()) {
258 State = State->set<LockMap>(LockR, LockState::getDestroyed());
259 C.addTransition(State);
265 if (LState->isLocked()) {
266 Message = "This lock is still locked";
268 Message = "This lock has already been destroyed";
272 BT_destroylock.reset(new BugType(this, "Destroy invalid lock",
274 ExplodedNode *N = C.generateErrorNode();
277 auto Report = llvm::make_unique<BugReport>(*BT_destroylock, Message, N);
278 Report->addRange(CE->getArg(0)->getSourceRange());
279 C.emitReport(std::move(Report));
282 void PthreadLockChecker::InitLock(CheckerContext &C, const CallExpr *CE,
285 const MemRegion *LockR = Lock.getAsRegion();
289 ProgramStateRef State = C.getState();
291 const struct LockState *LState = State->get<LockMap>(LockR);
292 if (!LState || LState->isDestroyed()) {
293 State = State->set<LockMap>(LockR, LockState::getUnlocked());
294 C.addTransition(State);
300 if (LState->isLocked()) {
301 Message = "This lock is still being held";
303 Message = "This lock has already been initialized";
307 BT_initlock.reset(new BugType(this, "Init invalid lock",
309 ExplodedNode *N = C.generateErrorNode();
312 auto Report = llvm::make_unique<BugReport>(*BT_initlock, Message, N);
313 Report->addRange(CE->getArg(0)->getSourceRange());
314 C.emitReport(std::move(Report));
317 void PthreadLockChecker::reportUseDestroyedBug(CheckerContext &C,
318 const CallExpr *CE) const {
320 BT_destroylock.reset(new BugType(this, "Use destroyed lock",
322 ExplodedNode *N = C.generateErrorNode();
325 auto Report = llvm::make_unique<BugReport>(
326 *BT_destroylock, "This lock has already been destroyed", N);
327 Report->addRange(CE->getArg(0)->getSourceRange());
328 C.emitReport(std::move(Report));
331 void ento::registerPthreadLockChecker(CheckerManager &mgr) {
332 mgr.registerChecker<PthreadLockChecker>();