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;
32 UntouchedAndPossiblyDestroyed,
33 UnlockedAndPossiblyDestroyed
37 LockState(Kind K) : K(K) {}
40 static LockState getLocked() { return LockState(Locked); }
41 static LockState getUnlocked() { return LockState(Unlocked); }
42 static LockState getDestroyed() { return LockState(Destroyed); }
43 static LockState getUntouchedAndPossiblyDestroyed() {
44 return LockState(UntouchedAndPossiblyDestroyed);
46 static LockState getUnlockedAndPossiblyDestroyed() {
47 return LockState(UnlockedAndPossiblyDestroyed);
50 bool operator==(const LockState &X) const {
54 bool isLocked() const { return K == Locked; }
55 bool isUnlocked() const { return K == Unlocked; }
56 bool isDestroyed() const { return K == Destroyed; }
57 bool isUntouchedAndPossiblyDestroyed() const {
58 return K == UntouchedAndPossiblyDestroyed;
60 bool isUnlockedAndPossiblyDestroyed() const {
61 return K == UnlockedAndPossiblyDestroyed;
64 void Profile(llvm::FoldingSetNodeID &ID) const {
69 class PthreadLockChecker
70 : public Checker<check::PostStmt<CallExpr>, check::DeadSymbols> {
71 mutable std::unique_ptr<BugType> BT_doublelock;
72 mutable std::unique_ptr<BugType> BT_doubleunlock;
73 mutable std::unique_ptr<BugType> BT_destroylock;
74 mutable std::unique_ptr<BugType> BT_initlock;
75 mutable std::unique_ptr<BugType> BT_lor;
76 enum LockingSemantics {
82 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
83 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
85 void AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock,
86 bool isTryLock, enum LockingSemantics semantics) const;
88 void ReleaseLock(CheckerContext &C, const CallExpr *CE, SVal lock) const;
89 void DestroyLock(CheckerContext &C, const CallExpr *CE, SVal Lock,
90 enum LockingSemantics semantics) const;
91 void InitLock(CheckerContext &C, const CallExpr *CE, SVal Lock) const;
92 void reportUseDestroyedBug(CheckerContext &C, const CallExpr *CE) const;
93 ProgramStateRef resolvePossiblyDestroyedMutex(ProgramStateRef state,
94 const MemRegion *lockR,
95 const SymbolRef *sym) const;
97 } // end anonymous namespace
99 // A stack of locks for tracking lock-unlock order.
100 REGISTER_LIST_WITH_PROGRAMSTATE(LockSet, const MemRegion *)
102 // An entry for tracking lock states.
103 REGISTER_MAP_WITH_PROGRAMSTATE(LockMap, const MemRegion *, LockState)
105 // Return values for unresolved calls to pthread_mutex_destroy().
106 REGISTER_MAP_WITH_PROGRAMSTATE(DestroyRetVal, const MemRegion *, SymbolRef)
108 void PthreadLockChecker::checkPostStmt(const CallExpr *CE,
109 CheckerContext &C) const {
110 ProgramStateRef state = C.getState();
111 const LocationContext *LCtx = C.getLocationContext();
112 StringRef FName = C.getCalleeName(CE);
116 if (CE->getNumArgs() != 1 && CE->getNumArgs() != 2)
119 if (FName == "pthread_mutex_lock" ||
120 FName == "pthread_rwlock_rdlock" ||
121 FName == "pthread_rwlock_wrlock")
122 AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
123 false, PthreadSemantics);
124 else if (FName == "lck_mtx_lock" ||
125 FName == "lck_rw_lock_exclusive" ||
126 FName == "lck_rw_lock_shared")
127 AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
128 false, XNUSemantics);
129 else if (FName == "pthread_mutex_trylock" ||
130 FName == "pthread_rwlock_tryrdlock" ||
131 FName == "pthread_rwlock_trywrlock")
132 AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
133 true, PthreadSemantics);
134 else if (FName == "lck_mtx_try_lock" ||
135 FName == "lck_rw_try_lock_exclusive" ||
136 FName == "lck_rw_try_lock_shared")
137 AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
139 else if (FName == "pthread_mutex_unlock" ||
140 FName == "pthread_rwlock_unlock" ||
141 FName == "lck_mtx_unlock" ||
142 FName == "lck_rw_done")
143 ReleaseLock(C, CE, state->getSVal(CE->getArg(0), LCtx));
144 else if (FName == "pthread_mutex_destroy")
145 DestroyLock(C, CE, state->getSVal(CE->getArg(0), LCtx), PthreadSemantics);
146 else if (FName == "lck_mtx_destroy")
147 DestroyLock(C, CE, state->getSVal(CE->getArg(0), LCtx), XNUSemantics);
148 else if (FName == "pthread_mutex_init")
149 InitLock(C, CE, state->getSVal(CE->getArg(0), LCtx));
152 // When a lock is destroyed, in some semantics(like PthreadSemantics) we are not
153 // sure if the destroy call has succeeded or failed, and the lock enters one of
154 // the 'possibly destroyed' state. There is a short time frame for the
155 // programmer to check the return value to see if the lock was successfully
156 // destroyed. Before we model the next operation over that lock, we call this
157 // function to see if the return value was checked by now and set the lock state
158 // - either to destroyed state or back to its previous state.
160 // In PthreadSemantics, pthread_mutex_destroy() returns zero if the lock is
161 // successfully destroyed and it returns a non-zero value otherwise.
162 ProgramStateRef PthreadLockChecker::resolvePossiblyDestroyedMutex(
163 ProgramStateRef state, const MemRegion *lockR, const SymbolRef *sym) const {
164 const LockState *lstate = state->get<LockMap>(lockR);
165 // Existence in DestroyRetVal ensures existence in LockMap.
166 // Existence in Destroyed also ensures that the lock state for lockR is either
167 // UntouchedAndPossiblyDestroyed or UnlockedAndPossiblyDestroyed.
168 assert(lstate->isUntouchedAndPossiblyDestroyed() ||
169 lstate->isUnlockedAndPossiblyDestroyed());
171 ConstraintManager &CMgr = state->getConstraintManager();
172 ConditionTruthVal retZero = CMgr.isNull(state, *sym);
173 if (retZero.isConstrainedFalse()) {
174 if (lstate->isUntouchedAndPossiblyDestroyed())
175 state = state->remove<LockMap>(lockR);
176 else if (lstate->isUnlockedAndPossiblyDestroyed())
177 state = state->set<LockMap>(lockR, LockState::getUnlocked());
179 state = state->set<LockMap>(lockR, LockState::getDestroyed());
181 // Removing the map entry (lockR, sym) from DestroyRetVal as the lock state is
183 state = state->remove<DestroyRetVal>(lockR);
187 void PthreadLockChecker::AcquireLock(CheckerContext &C, const CallExpr *CE,
188 SVal lock, bool isTryLock,
189 enum LockingSemantics semantics) const {
191 const MemRegion *lockR = lock.getAsRegion();
195 ProgramStateRef state = C.getState();
196 const SymbolRef *sym = state->get<DestroyRetVal>(lockR);
198 state = resolvePossiblyDestroyedMutex(state, lockR, sym);
200 SVal X = state->getSVal(CE, C.getLocationContext());
201 if (X.isUnknownOrUndef())
204 DefinedSVal retVal = X.castAs<DefinedSVal>();
206 if (const LockState *LState = state->get<LockMap>(lockR)) {
207 if (LState->isLocked()) {
209 BT_doublelock.reset(new BugType(this, "Double locking",
211 ExplodedNode *N = C.generateErrorNode();
214 auto report = llvm::make_unique<BugReport>(
215 *BT_doublelock, "This lock has already been acquired", N);
216 report->addRange(CE->getArg(0)->getSourceRange());
217 C.emitReport(std::move(report));
219 } else if (LState->isDestroyed()) {
220 reportUseDestroyedBug(C, CE);
225 ProgramStateRef lockSucc = state;
227 // Bifurcate the state, and allow a mode where the lock acquisition fails.
228 ProgramStateRef lockFail;
230 case PthreadSemantics:
231 std::tie(lockFail, lockSucc) = state->assume(retVal);
234 std::tie(lockSucc, lockFail) = state->assume(retVal);
237 llvm_unreachable("Unknown tryLock locking semantics");
239 assert(lockFail && lockSucc);
240 C.addTransition(lockFail);
242 } else if (semantics == PthreadSemantics) {
243 // Assume that the return value was 0.
244 lockSucc = state->assume(retVal, false);
248 // XNU locking semantics return void on non-try locks
249 assert((semantics == XNUSemantics) && "Unknown locking semantics");
253 // Record that the lock was acquired.
254 lockSucc = lockSucc->add<LockSet>(lockR);
255 lockSucc = lockSucc->set<LockMap>(lockR, LockState::getLocked());
256 C.addTransition(lockSucc);
259 void PthreadLockChecker::ReleaseLock(CheckerContext &C, const CallExpr *CE,
262 const MemRegion *lockR = lock.getAsRegion();
266 ProgramStateRef state = C.getState();
267 const SymbolRef *sym = state->get<DestroyRetVal>(lockR);
269 state = resolvePossiblyDestroyedMutex(state, lockR, sym);
271 if (const LockState *LState = state->get<LockMap>(lockR)) {
272 if (LState->isUnlocked()) {
273 if (!BT_doubleunlock)
274 BT_doubleunlock.reset(new BugType(this, "Double unlocking",
276 ExplodedNode *N = C.generateErrorNode();
279 auto Report = llvm::make_unique<BugReport>(
280 *BT_doubleunlock, "This lock has already been unlocked", N);
281 Report->addRange(CE->getArg(0)->getSourceRange());
282 C.emitReport(std::move(Report));
284 } else if (LState->isDestroyed()) {
285 reportUseDestroyedBug(C, CE);
290 LockSetTy LS = state->get<LockSet>();
292 // FIXME: Better analysis requires IPA for wrappers.
295 const MemRegion *firstLockR = LS.getHead();
296 if (firstLockR != lockR) {
298 BT_lor.reset(new BugType(this, "Lock order reversal", "Lock checker"));
299 ExplodedNode *N = C.generateErrorNode();
302 auto report = llvm::make_unique<BugReport>(
303 *BT_lor, "This was not the most recently acquired lock. Possible "
304 "lock order reversal", N);
305 report->addRange(CE->getArg(0)->getSourceRange());
306 C.emitReport(std::move(report));
309 // Record that the lock was released.
310 state = state->set<LockSet>(LS.getTail());
313 state = state->set<LockMap>(lockR, LockState::getUnlocked());
314 C.addTransition(state);
317 void PthreadLockChecker::DestroyLock(CheckerContext &C, const CallExpr *CE,
319 enum LockingSemantics semantics) const {
321 const MemRegion *LockR = Lock.getAsRegion();
325 ProgramStateRef State = C.getState();
327 const SymbolRef *sym = State->get<DestroyRetVal>(LockR);
329 State = resolvePossiblyDestroyedMutex(State, LockR, sym);
331 const LockState *LState = State->get<LockMap>(LockR);
332 // Checking the return value of the destroy method only in the case of
334 if (semantics == PthreadSemantics) {
335 if (!LState || LState->isUnlocked()) {
336 SymbolRef sym = C.getSVal(CE).getAsSymbol();
338 State = State->remove<LockMap>(LockR);
339 C.addTransition(State);
342 State = State->set<DestroyRetVal>(LockR, sym);
343 if (LState && LState->isUnlocked())
344 State = State->set<LockMap>(
345 LockR, LockState::getUnlockedAndPossiblyDestroyed());
347 State = State->set<LockMap>(
348 LockR, LockState::getUntouchedAndPossiblyDestroyed());
349 C.addTransition(State);
353 if (!LState || LState->isUnlocked()) {
354 State = State->set<LockMap>(LockR, LockState::getDestroyed());
355 C.addTransition(State);
361 if (LState->isLocked()) {
362 Message = "This lock is still locked";
364 Message = "This lock has already been destroyed";
368 BT_destroylock.reset(new BugType(this, "Destroy invalid lock",
370 ExplodedNode *N = C.generateErrorNode();
373 auto Report = llvm::make_unique<BugReport>(*BT_destroylock, Message, N);
374 Report->addRange(CE->getArg(0)->getSourceRange());
375 C.emitReport(std::move(Report));
378 void PthreadLockChecker::InitLock(CheckerContext &C, const CallExpr *CE,
381 const MemRegion *LockR = Lock.getAsRegion();
385 ProgramStateRef State = C.getState();
387 const SymbolRef *sym = State->get<DestroyRetVal>(LockR);
389 State = resolvePossiblyDestroyedMutex(State, LockR, sym);
391 const struct LockState *LState = State->get<LockMap>(LockR);
392 if (!LState || LState->isDestroyed()) {
393 State = State->set<LockMap>(LockR, LockState::getUnlocked());
394 C.addTransition(State);
400 if (LState->isLocked()) {
401 Message = "This lock is still being held";
403 Message = "This lock has already been initialized";
407 BT_initlock.reset(new BugType(this, "Init invalid lock",
409 ExplodedNode *N = C.generateErrorNode();
412 auto Report = llvm::make_unique<BugReport>(*BT_initlock, Message, N);
413 Report->addRange(CE->getArg(0)->getSourceRange());
414 C.emitReport(std::move(Report));
417 void PthreadLockChecker::reportUseDestroyedBug(CheckerContext &C,
418 const CallExpr *CE) const {
420 BT_destroylock.reset(new BugType(this, "Use destroyed lock",
422 ExplodedNode *N = C.generateErrorNode();
425 auto Report = llvm::make_unique<BugReport>(
426 *BT_destroylock, "This lock has already been destroyed", N);
427 Report->addRange(CE->getArg(0)->getSourceRange());
428 C.emitReport(std::move(Report));
431 void PthreadLockChecker::checkDeadSymbols(SymbolReaper &SymReaper,
432 CheckerContext &C) const {
433 ProgramStateRef State = C.getState();
435 // TODO: Clean LockMap when a mutex region dies.
437 DestroyRetValTy TrackedSymbols = State->get<DestroyRetVal>();
438 for (DestroyRetValTy::iterator I = TrackedSymbols.begin(),
439 E = TrackedSymbols.end();
441 const SymbolRef Sym = I->second;
442 const MemRegion *lockR = I->first;
443 bool IsSymDead = SymReaper.isDead(Sym);
444 // Remove the dead symbol from the return value symbols map.
446 State = resolvePossiblyDestroyedMutex(State, lockR, &Sym);
448 C.addTransition(State);
451 void ento::registerPthreadLockChecker(CheckerManager &mgr) {
452 mgr.registerChecker<PthreadLockChecker>();