PthreadLockChecker.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. using namespace clang;
  21. using namespace ento;
  22. namespace {
  23. struct LockState {
  24. enum Kind {
  25. Destroyed,
  26. Locked,
  27. Unlocked,
  28. UntouchedAndPossiblyDestroyed,
  29. UnlockedAndPossiblyDestroyed
  30. } K;
  31. private:
  32. LockState(Kind K) : K(K) {}
  33. public:
  34. static LockState getLocked() { return LockState(Locked); }
  35. static LockState getUnlocked() { return LockState(Unlocked); }
  36. static LockState getDestroyed() { return LockState(Destroyed); }
  37. static LockState getUntouchedAndPossiblyDestroyed() {
  38. return LockState(UntouchedAndPossiblyDestroyed);
  39. }
  40. static LockState getUnlockedAndPossiblyDestroyed() {
  41. return LockState(UnlockedAndPossiblyDestroyed);
  42. }
  43. bool operator==(const LockState &X) const {
  44. return K == X.K;
  45. }
  46. bool isLocked() const { return K == Locked; }
  47. bool isUnlocked() const { return K == Unlocked; }
  48. bool isDestroyed() const { return K == Destroyed; }
  49. bool isUntouchedAndPossiblyDestroyed() const {
  50. return K == UntouchedAndPossiblyDestroyed;
  51. }
  52. bool isUnlockedAndPossiblyDestroyed() const {
  53. return K == UnlockedAndPossiblyDestroyed;
  54. }
  55. void Profile(llvm::FoldingSetNodeID &ID) const {
  56. ID.AddInteger(K);
  57. }
  58. };
  59. class PthreadLockChecker
  60. : public Checker<check::PostStmt<CallExpr>, check::DeadSymbols> {
  61. mutable std::unique_ptr<BugType> BT_doublelock;
  62. mutable std::unique_ptr<BugType> BT_doubleunlock;
  63. mutable std::unique_ptr<BugType> BT_destroylock;
  64. mutable std::unique_ptr<BugType> BT_initlock;
  65. mutable std::unique_ptr<BugType> BT_lor;
  66. enum LockingSemantics {
  67. NotApplicable = 0,
  68. PthreadSemantics,
  69. XNUSemantics
  70. };
  71. public:
  72. void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
  73. void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
  74. void printState(raw_ostream &Out, ProgramStateRef State,
  75. const char *NL, const char *Sep) const override;
  76. void AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock,
  77. bool isTryLock, enum LockingSemantics semantics) const;
  78. void ReleaseLock(CheckerContext &C, const CallExpr *CE, SVal lock) const;
  79. void DestroyLock(CheckerContext &C, const CallExpr *CE, SVal Lock,
  80. enum LockingSemantics semantics) const;
  81. void InitLock(CheckerContext &C, const CallExpr *CE, SVal Lock) const;
  82. void reportUseDestroyedBug(CheckerContext &C, const CallExpr *CE) const;
  83. ProgramStateRef resolvePossiblyDestroyedMutex(ProgramStateRef state,
  84. const MemRegion *lockR,
  85. const SymbolRef *sym) const;
  86. };
  87. } // end anonymous namespace
  88. // A stack of locks for tracking lock-unlock order.
  89. REGISTER_LIST_WITH_PROGRAMSTATE(LockSet, const MemRegion *)
  90. // An entry for tracking lock states.
  91. REGISTER_MAP_WITH_PROGRAMSTATE(LockMap, const MemRegion *, LockState)
  92. // Return values for unresolved calls to pthread_mutex_destroy().
  93. REGISTER_MAP_WITH_PROGRAMSTATE(DestroyRetVal, const MemRegion *, SymbolRef)
  94. void PthreadLockChecker::checkPostStmt(const CallExpr *CE,
  95. CheckerContext &C) const {
  96. StringRef FName = C.getCalleeName(CE);
  97. if (FName.empty())
  98. return;
  99. if (CE->getNumArgs() != 1 && CE->getNumArgs() != 2)
  100. return;
  101. if (FName == "pthread_mutex_lock" ||
  102. FName == "pthread_rwlock_rdlock" ||
  103. FName == "pthread_rwlock_wrlock")
  104. AcquireLock(C, CE, C.getSVal(CE->getArg(0)), false, PthreadSemantics);
  105. else if (FName == "lck_mtx_lock" ||
  106. FName == "lck_rw_lock_exclusive" ||
  107. FName == "lck_rw_lock_shared")
  108. AcquireLock(C, CE, C.getSVal(CE->getArg(0)), false, XNUSemantics);
  109. else if (FName == "pthread_mutex_trylock" ||
  110. FName == "pthread_rwlock_tryrdlock" ||
  111. FName == "pthread_rwlock_trywrlock")
  112. AcquireLock(C, CE, C.getSVal(CE->getArg(0)),
  113. true, PthreadSemantics);
  114. else if (FName == "lck_mtx_try_lock" ||
  115. FName == "lck_rw_try_lock_exclusive" ||
  116. FName == "lck_rw_try_lock_shared")
  117. AcquireLock(C, CE, C.getSVal(CE->getArg(0)), true, XNUSemantics);
  118. else if (FName == "pthread_mutex_unlock" ||
  119. FName == "pthread_rwlock_unlock" ||
  120. FName == "lck_mtx_unlock" ||
  121. FName == "lck_rw_done")
  122. ReleaseLock(C, CE, C.getSVal(CE->getArg(0)));
  123. else if (FName == "pthread_mutex_destroy")
  124. DestroyLock(C, CE, C.getSVal(CE->getArg(0)), PthreadSemantics);
  125. else if (FName == "lck_mtx_destroy")
  126. DestroyLock(C, CE, C.getSVal(CE->getArg(0)), XNUSemantics);
  127. else if (FName == "pthread_mutex_init")
  128. InitLock(C, CE, C.getSVal(CE->getArg(0)));
  129. }
  130. // When a lock is destroyed, in some semantics(like PthreadSemantics) we are not
  131. // sure if the destroy call has succeeded or failed, and the lock enters one of
  132. // the 'possibly destroyed' state. There is a short time frame for the
  133. // programmer to check the return value to see if the lock was successfully
  134. // destroyed. Before we model the next operation over that lock, we call this
  135. // function to see if the return value was checked by now and set the lock state
  136. // - either to destroyed state or back to its previous state.
  137. // In PthreadSemantics, pthread_mutex_destroy() returns zero if the lock is
  138. // successfully destroyed and it returns a non-zero value otherwise.
  139. ProgramStateRef PthreadLockChecker::resolvePossiblyDestroyedMutex(
  140. ProgramStateRef state, const MemRegion *lockR, const SymbolRef *sym) const {
  141. const LockState *lstate = state->get<LockMap>(lockR);
  142. // Existence in DestroyRetVal ensures existence in LockMap.
  143. // Existence in Destroyed also ensures that the lock state for lockR is either
  144. // UntouchedAndPossiblyDestroyed or UnlockedAndPossiblyDestroyed.
  145. assert(lstate->isUntouchedAndPossiblyDestroyed() ||
  146. lstate->isUnlockedAndPossiblyDestroyed());
  147. ConstraintManager &CMgr = state->getConstraintManager();
  148. ConditionTruthVal retZero = CMgr.isNull(state, *sym);
  149. if (retZero.isConstrainedFalse()) {
  150. if (lstate->isUntouchedAndPossiblyDestroyed())
  151. state = state->remove<LockMap>(lockR);
  152. else if (lstate->isUnlockedAndPossiblyDestroyed())
  153. state = state->set<LockMap>(lockR, LockState::getUnlocked());
  154. } else
  155. state = state->set<LockMap>(lockR, LockState::getDestroyed());
  156. // Removing the map entry (lockR, sym) from DestroyRetVal as the lock state is
  157. // now resolved.
  158. state = state->remove<DestroyRetVal>(lockR);
  159. return state;
  160. }
  161. void PthreadLockChecker::printState(raw_ostream &Out, ProgramStateRef State,
  162. const char *NL, const char *Sep) const {
  163. LockMapTy LM = State->get<LockMap>();
  164. if (!LM.isEmpty()) {
  165. Out << Sep << "Mutex states:" << NL;
  166. for (auto I : LM) {
  167. I.first->dumpToStream(Out);
  168. if (I.second.isLocked())
  169. Out << ": locked";
  170. else if (I.second.isUnlocked())
  171. Out << ": unlocked";
  172. else if (I.second.isDestroyed())
  173. Out << ": destroyed";
  174. else if (I.second.isUntouchedAndPossiblyDestroyed())
  175. Out << ": not tracked, possibly destroyed";
  176. else if (I.second.isUnlockedAndPossiblyDestroyed())
  177. Out << ": unlocked, possibly destroyed";
  178. Out << NL;
  179. }
  180. }
  181. LockSetTy LS = State->get<LockSet>();
  182. if (!LS.isEmpty()) {
  183. Out << Sep << "Mutex lock order:" << NL;
  184. for (auto I: LS) {
  185. I->dumpToStream(Out);
  186. Out << NL;
  187. }
  188. }
  189. // TODO: Dump destroyed mutex symbols?
  190. }
  191. void PthreadLockChecker::AcquireLock(CheckerContext &C, const CallExpr *CE,
  192. SVal lock, bool isTryLock,
  193. enum LockingSemantics semantics) const {
  194. const MemRegion *lockR = lock.getAsRegion();
  195. if (!lockR)
  196. return;
  197. ProgramStateRef state = C.getState();
  198. const SymbolRef *sym = state->get<DestroyRetVal>(lockR);
  199. if (sym)
  200. state = resolvePossiblyDestroyedMutex(state, lockR, sym);
  201. SVal X = C.getSVal(CE);
  202. if (X.isUnknownOrUndef())
  203. return;
  204. DefinedSVal retVal = X.castAs<DefinedSVal>();
  205. if (const LockState *LState = state->get<LockMap>(lockR)) {
  206. if (LState->isLocked()) {
  207. if (!BT_doublelock)
  208. BT_doublelock.reset(new BugType(this, "Double locking",
  209. "Lock checker"));
  210. ExplodedNode *N = C.generateErrorNode();
  211. if (!N)
  212. return;
  213. auto report = llvm::make_unique<BugReport>(
  214. *BT_doublelock, "This lock has already been acquired", N);
  215. report->addRange(CE->getArg(0)->getSourceRange());
  216. C.emitReport(std::move(report));
  217. return;
  218. } else if (LState->isDestroyed()) {
  219. reportUseDestroyedBug(C, CE);
  220. return;
  221. }
  222. }
  223. ProgramStateRef lockSucc = state;
  224. if (isTryLock) {
  225. // Bifurcate the state, and allow a mode where the lock acquisition fails.
  226. ProgramStateRef lockFail;
  227. switch (semantics) {
  228. case PthreadSemantics:
  229. std::tie(lockFail, lockSucc) = state->assume(retVal);
  230. break;
  231. case XNUSemantics:
  232. std::tie(lockSucc, lockFail) = state->assume(retVal);
  233. break;
  234. default:
  235. llvm_unreachable("Unknown tryLock locking semantics");
  236. }
  237. assert(lockFail && lockSucc);
  238. C.addTransition(lockFail);
  239. } else if (semantics == PthreadSemantics) {
  240. // Assume that the return value was 0.
  241. lockSucc = state->assume(retVal, false);
  242. assert(lockSucc);
  243. } else {
  244. // XNU locking semantics return void on non-try locks
  245. assert((semantics == XNUSemantics) && "Unknown locking semantics");
  246. lockSucc = state;
  247. }
  248. // Record that the lock was acquired.
  249. lockSucc = lockSucc->add<LockSet>(lockR);
  250. lockSucc = lockSucc->set<LockMap>(lockR, LockState::getLocked());
  251. C.addTransition(lockSucc);
  252. }
  253. void PthreadLockChecker::ReleaseLock(CheckerContext &C, const CallExpr *CE,
  254. SVal lock) const {
  255. const MemRegion *lockR = lock.getAsRegion();
  256. if (!lockR)
  257. return;
  258. ProgramStateRef state = C.getState();
  259. const SymbolRef *sym = state->get<DestroyRetVal>(lockR);
  260. if (sym)
  261. state = resolvePossiblyDestroyedMutex(state, lockR, sym);
  262. if (const LockState *LState = state->get<LockMap>(lockR)) {
  263. if (LState->isUnlocked()) {
  264. if (!BT_doubleunlock)
  265. BT_doubleunlock.reset(new BugType(this, "Double unlocking",
  266. "Lock checker"));
  267. ExplodedNode *N = C.generateErrorNode();
  268. if (!N)
  269. return;
  270. auto Report = llvm::make_unique<BugReport>(
  271. *BT_doubleunlock, "This lock has already been unlocked", N);
  272. Report->addRange(CE->getArg(0)->getSourceRange());
  273. C.emitReport(std::move(Report));
  274. return;
  275. } else if (LState->isDestroyed()) {
  276. reportUseDestroyedBug(C, CE);
  277. return;
  278. }
  279. }
  280. LockSetTy LS = state->get<LockSet>();
  281. // FIXME: Better analysis requires IPA for wrappers.
  282. if (!LS.isEmpty()) {
  283. const MemRegion *firstLockR = LS.getHead();
  284. if (firstLockR != lockR) {
  285. if (!BT_lor)
  286. BT_lor.reset(new BugType(this, "Lock order reversal", "Lock checker"));
  287. ExplodedNode *N = C.generateErrorNode();
  288. if (!N)
  289. return;
  290. auto report = llvm::make_unique<BugReport>(
  291. *BT_lor, "This was not the most recently acquired lock. Possible "
  292. "lock order reversal", N);
  293. report->addRange(CE->getArg(0)->getSourceRange());
  294. C.emitReport(std::move(report));
  295. return;
  296. }
  297. // Record that the lock was released.
  298. state = state->set<LockSet>(LS.getTail());
  299. }
  300. state = state->set<LockMap>(lockR, LockState::getUnlocked());
  301. C.addTransition(state);
  302. }
  303. void PthreadLockChecker::DestroyLock(CheckerContext &C, const CallExpr *CE,
  304. SVal Lock,
  305. enum LockingSemantics semantics) const {
  306. const MemRegion *LockR = Lock.getAsRegion();
  307. if (!LockR)
  308. return;
  309. ProgramStateRef State = C.getState();
  310. const SymbolRef *sym = State->get<DestroyRetVal>(LockR);
  311. if (sym)
  312. State = resolvePossiblyDestroyedMutex(State, LockR, sym);
  313. const LockState *LState = State->get<LockMap>(LockR);
  314. // Checking the return value of the destroy method only in the case of
  315. // PthreadSemantics
  316. if (semantics == PthreadSemantics) {
  317. if (!LState || LState->isUnlocked()) {
  318. SymbolRef sym = C.getSVal(CE).getAsSymbol();
  319. if (!sym) {
  320. State = State->remove<LockMap>(LockR);
  321. C.addTransition(State);
  322. return;
  323. }
  324. State = State->set<DestroyRetVal>(LockR, sym);
  325. if (LState && LState->isUnlocked())
  326. State = State->set<LockMap>(
  327. LockR, LockState::getUnlockedAndPossiblyDestroyed());
  328. else
  329. State = State->set<LockMap>(
  330. LockR, LockState::getUntouchedAndPossiblyDestroyed());
  331. C.addTransition(State);
  332. return;
  333. }
  334. } else {
  335. if (!LState || LState->isUnlocked()) {
  336. State = State->set<LockMap>(LockR, LockState::getDestroyed());
  337. C.addTransition(State);
  338. return;
  339. }
  340. }
  341. StringRef Message;
  342. if (LState->isLocked()) {
  343. Message = "This lock is still locked";
  344. } else {
  345. Message = "This lock has already been destroyed";
  346. }
  347. if (!BT_destroylock)
  348. BT_destroylock.reset(new BugType(this, "Destroy invalid lock",
  349. "Lock checker"));
  350. ExplodedNode *N = C.generateErrorNode();
  351. if (!N)
  352. return;
  353. auto Report = llvm::make_unique<BugReport>(*BT_destroylock, Message, N);
  354. Report->addRange(CE->getArg(0)->getSourceRange());
  355. C.emitReport(std::move(Report));
  356. }
  357. void PthreadLockChecker::InitLock(CheckerContext &C, const CallExpr *CE,
  358. SVal Lock) const {
  359. const MemRegion *LockR = Lock.getAsRegion();
  360. if (!LockR)
  361. return;
  362. ProgramStateRef State = C.getState();
  363. const SymbolRef *sym = State->get<DestroyRetVal>(LockR);
  364. if (sym)
  365. State = resolvePossiblyDestroyedMutex(State, LockR, sym);
  366. const struct LockState *LState = State->get<LockMap>(LockR);
  367. if (!LState || LState->isDestroyed()) {
  368. State = State->set<LockMap>(LockR, LockState::getUnlocked());
  369. C.addTransition(State);
  370. return;
  371. }
  372. StringRef Message;
  373. if (LState->isLocked()) {
  374. Message = "This lock is still being held";
  375. } else {
  376. Message = "This lock has already been initialized";
  377. }
  378. if (!BT_initlock)
  379. BT_initlock.reset(new BugType(this, "Init invalid lock",
  380. "Lock checker"));
  381. ExplodedNode *N = C.generateErrorNode();
  382. if (!N)
  383. return;
  384. auto Report = llvm::make_unique<BugReport>(*BT_initlock, Message, N);
  385. Report->addRange(CE->getArg(0)->getSourceRange());
  386. C.emitReport(std::move(Report));
  387. }
  388. void PthreadLockChecker::reportUseDestroyedBug(CheckerContext &C,
  389. const CallExpr *CE) const {
  390. if (!BT_destroylock)
  391. BT_destroylock.reset(new BugType(this, "Use destroyed lock",
  392. "Lock checker"));
  393. ExplodedNode *N = C.generateErrorNode();
  394. if (!N)
  395. return;
  396. auto Report = llvm::make_unique<BugReport>(
  397. *BT_destroylock, "This lock has already been destroyed", N);
  398. Report->addRange(CE->getArg(0)->getSourceRange());
  399. C.emitReport(std::move(Report));
  400. }
  401. void PthreadLockChecker::checkDeadSymbols(SymbolReaper &SymReaper,
  402. CheckerContext &C) const {
  403. ProgramStateRef State = C.getState();
  404. // TODO: Clean LockMap when a mutex region dies.
  405. DestroyRetValTy TrackedSymbols = State->get<DestroyRetVal>();
  406. for (DestroyRetValTy::iterator I = TrackedSymbols.begin(),
  407. E = TrackedSymbols.end();
  408. I != E; ++I) {
  409. const SymbolRef Sym = I->second;
  410. const MemRegion *lockR = I->first;
  411. bool IsSymDead = SymReaper.isDead(Sym);
  412. // Remove the dead symbol from the return value symbols map.
  413. if (IsSymDead)
  414. State = resolvePossiblyDestroyedMutex(State, lockR, &Sym);
  415. }
  416. C.addTransition(State);
  417. }
  418. void ento::registerPthreadLockChecker(CheckerManager &mgr) {
  419. mgr.registerChecker<PthreadLockChecker>();
  420. }