PthreadLockChecker.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. //===--- PthreadLockChecker.cpp - Check for locking problems ---*- C++ -*--===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This defines PthreadLockChecker, a simple lock -> unlock checker.
  11. // Also handles XNU locks, which behave similarly enough to share code.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "ClangSACheckers.h"
  15. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  16. #include "clang/StaticAnalyzer/Core/Checker.h"
  17. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  20. #include "llvm/ADT/ImmutableList.h"
  21. using namespace clang;
  22. using namespace ento;
  23. namespace {
  24. struct LockState {
  25. enum Kind { Destroyed, Locked, Unlocked } K;
  26. private:
  27. LockState(Kind K) : K(K) {}
  28. public:
  29. static LockState getLocked(void) { return LockState(Locked); }
  30. static LockState getUnlocked(void) { return LockState(Unlocked); }
  31. static LockState getDestroyed(void) { return LockState(Destroyed); }
  32. bool operator==(const LockState &X) const {
  33. return K == X.K;
  34. }
  35. bool isLocked() const { return K == Locked; }
  36. bool isUnlocked() const { return K == Unlocked; }
  37. bool isDestroyed() const { return K == Destroyed; }
  38. void Profile(llvm::FoldingSetNodeID &ID) const {
  39. ID.AddInteger(K);
  40. }
  41. };
  42. class PthreadLockChecker : public Checker< check::PostStmt<CallExpr> > {
  43. mutable std::unique_ptr<BugType> BT_doublelock;
  44. mutable std::unique_ptr<BugType> BT_doubleunlock;
  45. mutable std::unique_ptr<BugType> BT_destroylock;
  46. mutable std::unique_ptr<BugType> BT_initlock;
  47. mutable std::unique_ptr<BugType> BT_lor;
  48. enum LockingSemantics {
  49. NotApplicable = 0,
  50. PthreadSemantics,
  51. XNUSemantics
  52. };
  53. public:
  54. void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
  55. void AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock,
  56. bool isTryLock, enum LockingSemantics semantics) const;
  57. void ReleaseLock(CheckerContext &C, const CallExpr *CE, SVal lock) const;
  58. void DestroyLock(CheckerContext &C, const CallExpr *CE, SVal Lock) const;
  59. void InitLock(CheckerContext &C, const CallExpr *CE, SVal Lock) const;
  60. void reportUseDestroyedBug(CheckerContext &C, const CallExpr *CE) const;
  61. };
  62. } // end anonymous namespace
  63. // GDM Entry for tracking lock state.
  64. REGISTER_LIST_WITH_PROGRAMSTATE(LockSet, const MemRegion *)
  65. REGISTER_MAP_WITH_PROGRAMSTATE(LockMap, const MemRegion *, LockState)
  66. void PthreadLockChecker::checkPostStmt(const CallExpr *CE,
  67. CheckerContext &C) const {
  68. ProgramStateRef state = C.getState();
  69. const LocationContext *LCtx = C.getLocationContext();
  70. StringRef FName = C.getCalleeName(CE);
  71. if (FName.empty())
  72. return;
  73. if (CE->getNumArgs() != 1 && CE->getNumArgs() != 2)
  74. return;
  75. if (FName == "pthread_mutex_lock" ||
  76. FName == "pthread_rwlock_rdlock" ||
  77. FName == "pthread_rwlock_wrlock")
  78. AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
  79. false, PthreadSemantics);
  80. else if (FName == "lck_mtx_lock" ||
  81. FName == "lck_rw_lock_exclusive" ||
  82. FName == "lck_rw_lock_shared")
  83. AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
  84. false, XNUSemantics);
  85. else if (FName == "pthread_mutex_trylock" ||
  86. FName == "pthread_rwlock_tryrdlock" ||
  87. FName == "pthread_rwlock_trywrlock")
  88. AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
  89. true, PthreadSemantics);
  90. else if (FName == "lck_mtx_try_lock" ||
  91. FName == "lck_rw_try_lock_exclusive" ||
  92. FName == "lck_rw_try_lock_shared")
  93. AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
  94. true, XNUSemantics);
  95. else if (FName == "pthread_mutex_unlock" ||
  96. FName == "pthread_rwlock_unlock" ||
  97. FName == "lck_mtx_unlock" ||
  98. FName == "lck_rw_done")
  99. ReleaseLock(C, CE, state->getSVal(CE->getArg(0), LCtx));
  100. else if (FName == "pthread_mutex_destroy" ||
  101. FName == "lck_mtx_destroy")
  102. DestroyLock(C, CE, state->getSVal(CE->getArg(0), LCtx));
  103. else if (FName == "pthread_mutex_init")
  104. InitLock(C, CE, state->getSVal(CE->getArg(0), LCtx));
  105. }
  106. void PthreadLockChecker::AcquireLock(CheckerContext &C, const CallExpr *CE,
  107. SVal lock, bool isTryLock,
  108. enum LockingSemantics semantics) const {
  109. const MemRegion *lockR = lock.getAsRegion();
  110. if (!lockR)
  111. return;
  112. ProgramStateRef state = C.getState();
  113. SVal X = state->getSVal(CE, C.getLocationContext());
  114. if (X.isUnknownOrUndef())
  115. return;
  116. DefinedSVal retVal = X.castAs<DefinedSVal>();
  117. if (const LockState *LState = state->get<LockMap>(lockR)) {
  118. if (LState->isLocked()) {
  119. if (!BT_doublelock)
  120. BT_doublelock.reset(new BugType(this, "Double locking",
  121. "Lock checker"));
  122. ExplodedNode *N = C.generateSink();
  123. if (!N)
  124. return;
  125. auto report = llvm::make_unique<BugReport>(
  126. *BT_doublelock, "This lock has already been acquired", N);
  127. report->addRange(CE->getArg(0)->getSourceRange());
  128. C.emitReport(std::move(report));
  129. return;
  130. } else if (LState->isDestroyed()) {
  131. reportUseDestroyedBug(C, CE);
  132. return;
  133. }
  134. }
  135. ProgramStateRef lockSucc = state;
  136. if (isTryLock) {
  137. // Bifurcate the state, and allow a mode where the lock acquisition fails.
  138. ProgramStateRef lockFail;
  139. switch (semantics) {
  140. case PthreadSemantics:
  141. std::tie(lockFail, lockSucc) = state->assume(retVal);
  142. break;
  143. case XNUSemantics:
  144. std::tie(lockSucc, lockFail) = state->assume(retVal);
  145. break;
  146. default:
  147. llvm_unreachable("Unknown tryLock locking semantics");
  148. }
  149. assert(lockFail && lockSucc);
  150. C.addTransition(lockFail);
  151. } else if (semantics == PthreadSemantics) {
  152. // Assume that the return value was 0.
  153. lockSucc = state->assume(retVal, false);
  154. assert(lockSucc);
  155. } else {
  156. // XNU locking semantics return void on non-try locks
  157. assert((semantics == XNUSemantics) && "Unknown locking semantics");
  158. lockSucc = state;
  159. }
  160. // Record that the lock was acquired.
  161. lockSucc = lockSucc->add<LockSet>(lockR);
  162. lockSucc = lockSucc->set<LockMap>(lockR, LockState::getLocked());
  163. C.addTransition(lockSucc);
  164. }
  165. void PthreadLockChecker::ReleaseLock(CheckerContext &C, const CallExpr *CE,
  166. SVal lock) const {
  167. const MemRegion *lockR = lock.getAsRegion();
  168. if (!lockR)
  169. return;
  170. ProgramStateRef state = C.getState();
  171. if (const LockState *LState = state->get<LockMap>(lockR)) {
  172. if (LState->isUnlocked()) {
  173. if (!BT_doubleunlock)
  174. BT_doubleunlock.reset(new BugType(this, "Double unlocking",
  175. "Lock checker"));
  176. ExplodedNode *N = C.generateSink();
  177. if (!N)
  178. return;
  179. auto Report = llvm::make_unique<BugReport>(
  180. *BT_doubleunlock, "This lock has already been unlocked", N);
  181. Report->addRange(CE->getArg(0)->getSourceRange());
  182. C.emitReport(std::move(Report));
  183. return;
  184. } else if (LState->isDestroyed()) {
  185. reportUseDestroyedBug(C, CE);
  186. return;
  187. }
  188. }
  189. LockSetTy LS = state->get<LockSet>();
  190. // FIXME: Better analysis requires IPA for wrappers.
  191. if (!LS.isEmpty()) {
  192. const MemRegion *firstLockR = LS.getHead();
  193. if (firstLockR != lockR) {
  194. if (!BT_lor)
  195. BT_lor.reset(new BugType(this, "Lock order reversal", "Lock checker"));
  196. ExplodedNode *N = C.generateSink();
  197. if (!N)
  198. return;
  199. auto report = llvm::make_unique<BugReport>(
  200. *BT_lor, "This was not the most recently acquired lock. Possible "
  201. "lock order reversal", N);
  202. report->addRange(CE->getArg(0)->getSourceRange());
  203. C.emitReport(std::move(report));
  204. return;
  205. }
  206. // Record that the lock was released.
  207. state = state->set<LockSet>(LS.getTail());
  208. }
  209. state = state->set<LockMap>(lockR, LockState::getUnlocked());
  210. C.addTransition(state);
  211. }
  212. void PthreadLockChecker::DestroyLock(CheckerContext &C, const CallExpr *CE,
  213. SVal Lock) const {
  214. const MemRegion *LockR = Lock.getAsRegion();
  215. if (!LockR)
  216. return;
  217. ProgramStateRef State = C.getState();
  218. const LockState *LState = State->get<LockMap>(LockR);
  219. if (!LState || LState->isUnlocked()) {
  220. State = State->set<LockMap>(LockR, LockState::getDestroyed());
  221. C.addTransition(State);
  222. return;
  223. }
  224. StringRef Message;
  225. if (LState->isLocked()) {
  226. Message = "This lock is still locked";
  227. } else {
  228. Message = "This lock has already been destroyed";
  229. }
  230. if (!BT_destroylock)
  231. BT_destroylock.reset(new BugType(this, "Destroy invalid lock",
  232. "Lock checker"));
  233. ExplodedNode *N = C.generateSink();
  234. if (!N)
  235. return;
  236. auto Report = llvm::make_unique<BugReport>(*BT_destroylock, Message, N);
  237. Report->addRange(CE->getArg(0)->getSourceRange());
  238. C.emitReport(std::move(Report));
  239. }
  240. void PthreadLockChecker::InitLock(CheckerContext &C, const CallExpr *CE,
  241. SVal Lock) const {
  242. const MemRegion *LockR = Lock.getAsRegion();
  243. if (!LockR)
  244. return;
  245. ProgramStateRef State = C.getState();
  246. const struct LockState *LState = State->get<LockMap>(LockR);
  247. if (!LState || LState->isDestroyed()) {
  248. State = State->set<LockMap>(LockR, LockState::getUnlocked());
  249. C.addTransition(State);
  250. return;
  251. }
  252. StringRef Message;
  253. if (LState->isLocked()) {
  254. Message = "This lock is still being held";
  255. } else {
  256. Message = "This lock has already been initialized";
  257. }
  258. if (!BT_initlock)
  259. BT_initlock.reset(new BugType(this, "Init invalid lock",
  260. "Lock checker"));
  261. ExplodedNode *N = C.generateSink();
  262. if (!N)
  263. return;
  264. auto Report = llvm::make_unique<BugReport>(*BT_initlock, Message, N);
  265. Report->addRange(CE->getArg(0)->getSourceRange());
  266. C.emitReport(std::move(Report));
  267. }
  268. void PthreadLockChecker::reportUseDestroyedBug(CheckerContext &C,
  269. const CallExpr *CE) const {
  270. if (!BT_destroylock)
  271. BT_destroylock.reset(new BugType(this, "Use destroyed lock",
  272. "Lock checker"));
  273. ExplodedNode *N = C.generateSink();
  274. if (!N)
  275. return;
  276. auto Report = llvm::make_unique<BugReport>(
  277. *BT_destroylock, "This lock has already been destroyed", N);
  278. Report->addRange(CE->getArg(0)->getSourceRange());
  279. C.emitReport(std::move(Report));
  280. }
  281. void ento::registerPthreadLockChecker(CheckerManager &mgr) {
  282. mgr.registerChecker<PthreadLockChecker>();
  283. }