CheckerManager.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. //===- CheckerManager.cpp - Static Analyzer Checker Manager ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Defines the Static Analyzer Checker Manager.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  13. #include "clang/AST/DeclBase.h"
  14. #include "clang/AST/Stmt.h"
  15. #include "clang/Analysis/ProgramPoint.h"
  16. #include "clang/Basic/JsonSupport.h"
  17. #include "clang/Basic/LLVM.h"
  18. #include "clang/Driver/DriverDiagnostic.h"
  19. #include "clang/StaticAnalyzer/Core/Checker.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
  23. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  24. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/Support/Casting.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/FormatVariadic.h"
  29. #include <cassert>
  30. #include <vector>
  31. using namespace clang;
  32. using namespace ento;
  33. bool CheckerManager::hasPathSensitiveCheckers() const {
  34. const auto IfAnyAreNonEmpty = [](const auto &... Callbacks) -> bool {
  35. bool Result = false;
  36. // FIXME: Use fold expressions in C++17.
  37. LLVM_ATTRIBUTE_UNUSED int Unused[]{0, (Result |= !Callbacks.empty())...};
  38. return Result;
  39. };
  40. return IfAnyAreNonEmpty(
  41. StmtCheckers, PreObjCMessageCheckers, ObjCMessageNilCheckers,
  42. PostObjCMessageCheckers, PreCallCheckers, PostCallCheckers,
  43. LocationCheckers, BindCheckers, EndAnalysisCheckers,
  44. BeginFunctionCheckers, EndFunctionCheckers, BranchConditionCheckers,
  45. NewAllocatorCheckers, LiveSymbolsCheckers, DeadSymbolsCheckers,
  46. RegionChangesCheckers, PointerEscapeCheckers, EvalAssumeCheckers,
  47. EvalCallCheckers, EndOfTranslationUnitCheckers);
  48. }
  49. void CheckerManager::finishedCheckerRegistration() {
  50. #ifndef NDEBUG
  51. // Make sure that for every event that has listeners, there is at least
  52. // one dispatcher registered for it.
  53. for (const auto &Event : Events)
  54. assert(Event.second.HasDispatcher &&
  55. "No dispatcher registered for an event");
  56. #endif
  57. }
  58. void CheckerManager::reportInvalidCheckerOptionValue(
  59. const CheckerBase *C, StringRef OptionName,
  60. StringRef ExpectedValueDesc) const {
  61. getDiagnostics().Report(diag::err_analyzer_checker_option_invalid_input)
  62. << (llvm::Twine() + C->getTagDescription() + ":" + OptionName).str()
  63. << ExpectedValueDesc;
  64. }
  65. //===----------------------------------------------------------------------===//
  66. // Functions for running checkers for AST traversing..
  67. //===----------------------------------------------------------------------===//
  68. void CheckerManager::runCheckersOnASTDecl(const Decl *D, AnalysisManager& mgr,
  69. BugReporter &BR) {
  70. assert(D);
  71. unsigned DeclKind = D->getKind();
  72. CachedDeclCheckers *checkers = nullptr;
  73. CachedDeclCheckersMapTy::iterator CCI = CachedDeclCheckersMap.find(DeclKind);
  74. if (CCI != CachedDeclCheckersMap.end()) {
  75. checkers = &(CCI->second);
  76. } else {
  77. // Find the checkers that should run for this Decl and cache them.
  78. checkers = &CachedDeclCheckersMap[DeclKind];
  79. for (const auto &info : DeclCheckers)
  80. if (info.IsForDeclFn(D))
  81. checkers->push_back(info.CheckFn);
  82. }
  83. assert(checkers);
  84. for (const auto &checker : *checkers)
  85. checker(D, mgr, BR);
  86. }
  87. void CheckerManager::runCheckersOnASTBody(const Decl *D, AnalysisManager& mgr,
  88. BugReporter &BR) {
  89. assert(D && D->hasBody());
  90. for (const auto &BodyChecker : BodyCheckers)
  91. BodyChecker(D, mgr, BR);
  92. }
  93. //===----------------------------------------------------------------------===//
  94. // Functions for running checkers for path-sensitive checking.
  95. //===----------------------------------------------------------------------===//
  96. template <typename CHECK_CTX>
  97. static void expandGraphWithCheckers(CHECK_CTX checkCtx,
  98. ExplodedNodeSet &Dst,
  99. const ExplodedNodeSet &Src) {
  100. const NodeBuilderContext &BldrCtx = checkCtx.Eng.getBuilderContext();
  101. if (Src.empty())
  102. return;
  103. typename CHECK_CTX::CheckersTy::const_iterator
  104. I = checkCtx.checkers_begin(), E = checkCtx.checkers_end();
  105. if (I == E) {
  106. Dst.insert(Src);
  107. return;
  108. }
  109. ExplodedNodeSet Tmp1, Tmp2;
  110. const ExplodedNodeSet *PrevSet = &Src;
  111. for (; I != E; ++I) {
  112. ExplodedNodeSet *CurrSet = nullptr;
  113. if (I+1 == E)
  114. CurrSet = &Dst;
  115. else {
  116. CurrSet = (PrevSet == &Tmp1) ? &Tmp2 : &Tmp1;
  117. CurrSet->clear();
  118. }
  119. NodeBuilder B(*PrevSet, *CurrSet, BldrCtx);
  120. for (const auto &NI : *PrevSet)
  121. checkCtx.runChecker(*I, B, NI);
  122. // If all the produced transitions are sinks, stop.
  123. if (CurrSet->empty())
  124. return;
  125. // Update which NodeSet is the current one.
  126. PrevSet = CurrSet;
  127. }
  128. }
  129. namespace {
  130. struct CheckStmtContext {
  131. using CheckersTy = SmallVectorImpl<CheckerManager::CheckStmtFunc>;
  132. bool IsPreVisit;
  133. const CheckersTy &Checkers;
  134. const Stmt *S;
  135. ExprEngine &Eng;
  136. bool WasInlined;
  137. CheckStmtContext(bool isPreVisit, const CheckersTy &checkers,
  138. const Stmt *s, ExprEngine &eng, bool wasInlined = false)
  139. : IsPreVisit(isPreVisit), Checkers(checkers), S(s), Eng(eng),
  140. WasInlined(wasInlined) {}
  141. CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
  142. CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
  143. void runChecker(CheckerManager::CheckStmtFunc checkFn,
  144. NodeBuilder &Bldr, ExplodedNode *Pred) {
  145. // FIXME: Remove respondsToCallback from CheckerContext;
  146. ProgramPoint::Kind K = IsPreVisit ? ProgramPoint::PreStmtKind :
  147. ProgramPoint::PostStmtKind;
  148. const ProgramPoint &L = ProgramPoint::getProgramPoint(S, K,
  149. Pred->getLocationContext(), checkFn.Checker);
  150. CheckerContext C(Bldr, Eng, Pred, L, WasInlined);
  151. checkFn(S, C);
  152. }
  153. };
  154. } // namespace
  155. /// Run checkers for visiting Stmts.
  156. void CheckerManager::runCheckersForStmt(bool isPreVisit,
  157. ExplodedNodeSet &Dst,
  158. const ExplodedNodeSet &Src,
  159. const Stmt *S,
  160. ExprEngine &Eng,
  161. bool WasInlined) {
  162. CheckStmtContext C(isPreVisit, getCachedStmtCheckersFor(S, isPreVisit),
  163. S, Eng, WasInlined);
  164. expandGraphWithCheckers(C, Dst, Src);
  165. }
  166. namespace {
  167. struct CheckObjCMessageContext {
  168. using CheckersTy = std::vector<CheckerManager::CheckObjCMessageFunc>;
  169. ObjCMessageVisitKind Kind;
  170. bool WasInlined;
  171. const CheckersTy &Checkers;
  172. const ObjCMethodCall &Msg;
  173. ExprEngine &Eng;
  174. CheckObjCMessageContext(ObjCMessageVisitKind visitKind,
  175. const CheckersTy &checkers,
  176. const ObjCMethodCall &msg, ExprEngine &eng,
  177. bool wasInlined)
  178. : Kind(visitKind), WasInlined(wasInlined), Checkers(checkers), Msg(msg),
  179. Eng(eng) {}
  180. CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
  181. CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
  182. void runChecker(CheckerManager::CheckObjCMessageFunc checkFn,
  183. NodeBuilder &Bldr, ExplodedNode *Pred) {
  184. bool IsPreVisit;
  185. switch (Kind) {
  186. case ObjCMessageVisitKind::Pre:
  187. IsPreVisit = true;
  188. break;
  189. case ObjCMessageVisitKind::MessageNil:
  190. case ObjCMessageVisitKind::Post:
  191. IsPreVisit = false;
  192. break;
  193. }
  194. const ProgramPoint &L = Msg.getProgramPoint(IsPreVisit,checkFn.Checker);
  195. CheckerContext C(Bldr, Eng, Pred, L, WasInlined);
  196. checkFn(*Msg.cloneWithState<ObjCMethodCall>(Pred->getState()), C);
  197. }
  198. };
  199. } // namespace
  200. /// Run checkers for visiting obj-c messages.
  201. void CheckerManager::runCheckersForObjCMessage(ObjCMessageVisitKind visitKind,
  202. ExplodedNodeSet &Dst,
  203. const ExplodedNodeSet &Src,
  204. const ObjCMethodCall &msg,
  205. ExprEngine &Eng,
  206. bool WasInlined) {
  207. const auto &checkers = getObjCMessageCheckers(visitKind);
  208. CheckObjCMessageContext C(visitKind, checkers, msg, Eng, WasInlined);
  209. expandGraphWithCheckers(C, Dst, Src);
  210. }
  211. const std::vector<CheckerManager::CheckObjCMessageFunc> &
  212. CheckerManager::getObjCMessageCheckers(ObjCMessageVisitKind Kind) const {
  213. switch (Kind) {
  214. case ObjCMessageVisitKind::Pre:
  215. return PreObjCMessageCheckers;
  216. break;
  217. case ObjCMessageVisitKind::Post:
  218. return PostObjCMessageCheckers;
  219. case ObjCMessageVisitKind::MessageNil:
  220. return ObjCMessageNilCheckers;
  221. }
  222. llvm_unreachable("Unknown Kind");
  223. }
  224. namespace {
  225. // FIXME: This has all the same signatures as CheckObjCMessageContext.
  226. // Is there a way we can merge the two?
  227. struct CheckCallContext {
  228. using CheckersTy = std::vector<CheckerManager::CheckCallFunc>;
  229. bool IsPreVisit, WasInlined;
  230. const CheckersTy &Checkers;
  231. const CallEvent &Call;
  232. ExprEngine &Eng;
  233. CheckCallContext(bool isPreVisit, const CheckersTy &checkers,
  234. const CallEvent &call, ExprEngine &eng,
  235. bool wasInlined)
  236. : IsPreVisit(isPreVisit), WasInlined(wasInlined), Checkers(checkers),
  237. Call(call), Eng(eng) {}
  238. CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
  239. CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
  240. void runChecker(CheckerManager::CheckCallFunc checkFn,
  241. NodeBuilder &Bldr, ExplodedNode *Pred) {
  242. const ProgramPoint &L = Call.getProgramPoint(IsPreVisit,checkFn.Checker);
  243. CheckerContext C(Bldr, Eng, Pred, L, WasInlined);
  244. checkFn(*Call.cloneWithState(Pred->getState()), C);
  245. }
  246. };
  247. } // namespace
  248. /// Run checkers for visiting an abstract call event.
  249. void CheckerManager::runCheckersForCallEvent(bool isPreVisit,
  250. ExplodedNodeSet &Dst,
  251. const ExplodedNodeSet &Src,
  252. const CallEvent &Call,
  253. ExprEngine &Eng,
  254. bool WasInlined) {
  255. CheckCallContext C(isPreVisit,
  256. isPreVisit ? PreCallCheckers
  257. : PostCallCheckers,
  258. Call, Eng, WasInlined);
  259. expandGraphWithCheckers(C, Dst, Src);
  260. }
  261. namespace {
  262. struct CheckLocationContext {
  263. using CheckersTy = std::vector<CheckerManager::CheckLocationFunc>;
  264. const CheckersTy &Checkers;
  265. SVal Loc;
  266. bool IsLoad;
  267. const Stmt *NodeEx; /* Will become a CFGStmt */
  268. const Stmt *BoundEx;
  269. ExprEngine &Eng;
  270. CheckLocationContext(const CheckersTy &checkers,
  271. SVal loc, bool isLoad, const Stmt *NodeEx,
  272. const Stmt *BoundEx,
  273. ExprEngine &eng)
  274. : Checkers(checkers), Loc(loc), IsLoad(isLoad), NodeEx(NodeEx),
  275. BoundEx(BoundEx), Eng(eng) {}
  276. CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
  277. CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
  278. void runChecker(CheckerManager::CheckLocationFunc checkFn,
  279. NodeBuilder &Bldr, ExplodedNode *Pred) {
  280. ProgramPoint::Kind K = IsLoad ? ProgramPoint::PreLoadKind :
  281. ProgramPoint::PreStoreKind;
  282. const ProgramPoint &L =
  283. ProgramPoint::getProgramPoint(NodeEx, K,
  284. Pred->getLocationContext(),
  285. checkFn.Checker);
  286. CheckerContext C(Bldr, Eng, Pred, L);
  287. checkFn(Loc, IsLoad, BoundEx, C);
  288. }
  289. };
  290. } // namespace
  291. /// Run checkers for load/store of a location.
  292. void CheckerManager::runCheckersForLocation(ExplodedNodeSet &Dst,
  293. const ExplodedNodeSet &Src,
  294. SVal location, bool isLoad,
  295. const Stmt *NodeEx,
  296. const Stmt *BoundEx,
  297. ExprEngine &Eng) {
  298. CheckLocationContext C(LocationCheckers, location, isLoad, NodeEx,
  299. BoundEx, Eng);
  300. expandGraphWithCheckers(C, Dst, Src);
  301. }
  302. namespace {
  303. struct CheckBindContext {
  304. using CheckersTy = std::vector<CheckerManager::CheckBindFunc>;
  305. const CheckersTy &Checkers;
  306. SVal Loc;
  307. SVal Val;
  308. const Stmt *S;
  309. ExprEngine &Eng;
  310. const ProgramPoint &PP;
  311. CheckBindContext(const CheckersTy &checkers,
  312. SVal loc, SVal val, const Stmt *s, ExprEngine &eng,
  313. const ProgramPoint &pp)
  314. : Checkers(checkers), Loc(loc), Val(val), S(s), Eng(eng), PP(pp) {}
  315. CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
  316. CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
  317. void runChecker(CheckerManager::CheckBindFunc checkFn,
  318. NodeBuilder &Bldr, ExplodedNode *Pred) {
  319. const ProgramPoint &L = PP.withTag(checkFn.Checker);
  320. CheckerContext C(Bldr, Eng, Pred, L);
  321. checkFn(Loc, Val, S, C);
  322. }
  323. };
  324. } // namespace
  325. /// Run checkers for binding of a value to a location.
  326. void CheckerManager::runCheckersForBind(ExplodedNodeSet &Dst,
  327. const ExplodedNodeSet &Src,
  328. SVal location, SVal val,
  329. const Stmt *S, ExprEngine &Eng,
  330. const ProgramPoint &PP) {
  331. CheckBindContext C(BindCheckers, location, val, S, Eng, PP);
  332. expandGraphWithCheckers(C, Dst, Src);
  333. }
  334. void CheckerManager::runCheckersForEndAnalysis(ExplodedGraph &G,
  335. BugReporter &BR,
  336. ExprEngine &Eng) {
  337. for (const auto &EndAnalysisChecker : EndAnalysisCheckers)
  338. EndAnalysisChecker(G, BR, Eng);
  339. }
  340. namespace {
  341. struct CheckBeginFunctionContext {
  342. using CheckersTy = std::vector<CheckerManager::CheckBeginFunctionFunc>;
  343. const CheckersTy &Checkers;
  344. ExprEngine &Eng;
  345. const ProgramPoint &PP;
  346. CheckBeginFunctionContext(const CheckersTy &Checkers, ExprEngine &Eng,
  347. const ProgramPoint &PP)
  348. : Checkers(Checkers), Eng(Eng), PP(PP) {}
  349. CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
  350. CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
  351. void runChecker(CheckerManager::CheckBeginFunctionFunc checkFn,
  352. NodeBuilder &Bldr, ExplodedNode *Pred) {
  353. const ProgramPoint &L = PP.withTag(checkFn.Checker);
  354. CheckerContext C(Bldr, Eng, Pred, L);
  355. checkFn(C);
  356. }
  357. };
  358. } // namespace
  359. void CheckerManager::runCheckersForBeginFunction(ExplodedNodeSet &Dst,
  360. const BlockEdge &L,
  361. ExplodedNode *Pred,
  362. ExprEngine &Eng) {
  363. ExplodedNodeSet Src;
  364. Src.insert(Pred);
  365. CheckBeginFunctionContext C(BeginFunctionCheckers, Eng, L);
  366. expandGraphWithCheckers(C, Dst, Src);
  367. }
  368. /// Run checkers for end of path.
  369. // Note, We do not chain the checker output (like in expandGraphWithCheckers)
  370. // for this callback since end of path nodes are expected to be final.
  371. void CheckerManager::runCheckersForEndFunction(NodeBuilderContext &BC,
  372. ExplodedNodeSet &Dst,
  373. ExplodedNode *Pred,
  374. ExprEngine &Eng,
  375. const ReturnStmt *RS) {
  376. // We define the builder outside of the loop because if at least one checker
  377. // creates a successor for Pred, we do not need to generate an
  378. // autotransition for it.
  379. NodeBuilder Bldr(Pred, Dst, BC);
  380. for (const auto &checkFn : EndFunctionCheckers) {
  381. const ProgramPoint &L =
  382. FunctionExitPoint(RS, Pred->getLocationContext(), checkFn.Checker);
  383. CheckerContext C(Bldr, Eng, Pred, L);
  384. checkFn(RS, C);
  385. }
  386. }
  387. namespace {
  388. struct CheckBranchConditionContext {
  389. using CheckersTy = std::vector<CheckerManager::CheckBranchConditionFunc>;
  390. const CheckersTy &Checkers;
  391. const Stmt *Condition;
  392. ExprEngine &Eng;
  393. CheckBranchConditionContext(const CheckersTy &checkers,
  394. const Stmt *Cond, ExprEngine &eng)
  395. : Checkers(checkers), Condition(Cond), Eng(eng) {}
  396. CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
  397. CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
  398. void runChecker(CheckerManager::CheckBranchConditionFunc checkFn,
  399. NodeBuilder &Bldr, ExplodedNode *Pred) {
  400. ProgramPoint L = PostCondition(Condition, Pred->getLocationContext(),
  401. checkFn.Checker);
  402. CheckerContext C(Bldr, Eng, Pred, L);
  403. checkFn(Condition, C);
  404. }
  405. };
  406. } // namespace
  407. /// Run checkers for branch condition.
  408. void CheckerManager::runCheckersForBranchCondition(const Stmt *Condition,
  409. ExplodedNodeSet &Dst,
  410. ExplodedNode *Pred,
  411. ExprEngine &Eng) {
  412. ExplodedNodeSet Src;
  413. Src.insert(Pred);
  414. CheckBranchConditionContext C(BranchConditionCheckers, Condition, Eng);
  415. expandGraphWithCheckers(C, Dst, Src);
  416. }
  417. namespace {
  418. struct CheckNewAllocatorContext {
  419. using CheckersTy = std::vector<CheckerManager::CheckNewAllocatorFunc>;
  420. const CheckersTy &Checkers;
  421. const CXXAllocatorCall &Call;
  422. bool WasInlined;
  423. ExprEngine &Eng;
  424. CheckNewAllocatorContext(const CheckersTy &Checkers,
  425. const CXXAllocatorCall &Call, bool WasInlined,
  426. ExprEngine &Eng)
  427. : Checkers(Checkers), Call(Call), WasInlined(WasInlined), Eng(Eng) {}
  428. CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
  429. CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
  430. void runChecker(CheckerManager::CheckNewAllocatorFunc checkFn,
  431. NodeBuilder &Bldr, ExplodedNode *Pred) {
  432. ProgramPoint L =
  433. PostAllocatorCall(Call.getOriginExpr(), Pred->getLocationContext());
  434. CheckerContext C(Bldr, Eng, Pred, L, WasInlined);
  435. checkFn(cast<CXXAllocatorCall>(*Call.cloneWithState(Pred->getState())),
  436. C);
  437. }
  438. };
  439. } // namespace
  440. void CheckerManager::runCheckersForNewAllocator(const CXXAllocatorCall &Call,
  441. ExplodedNodeSet &Dst,
  442. ExplodedNode *Pred,
  443. ExprEngine &Eng,
  444. bool WasInlined) {
  445. ExplodedNodeSet Src;
  446. Src.insert(Pred);
  447. CheckNewAllocatorContext C(NewAllocatorCheckers, Call, WasInlined, Eng);
  448. expandGraphWithCheckers(C, Dst, Src);
  449. }
  450. /// Run checkers for live symbols.
  451. void CheckerManager::runCheckersForLiveSymbols(ProgramStateRef state,
  452. SymbolReaper &SymReaper) {
  453. for (const auto &LiveSymbolsChecker : LiveSymbolsCheckers)
  454. LiveSymbolsChecker(state, SymReaper);
  455. }
  456. namespace {
  457. struct CheckDeadSymbolsContext {
  458. using CheckersTy = std::vector<CheckerManager::CheckDeadSymbolsFunc>;
  459. const CheckersTy &Checkers;
  460. SymbolReaper &SR;
  461. const Stmt *S;
  462. ExprEngine &Eng;
  463. ProgramPoint::Kind ProgarmPointKind;
  464. CheckDeadSymbolsContext(const CheckersTy &checkers, SymbolReaper &sr,
  465. const Stmt *s, ExprEngine &eng,
  466. ProgramPoint::Kind K)
  467. : Checkers(checkers), SR(sr), S(s), Eng(eng), ProgarmPointKind(K) {}
  468. CheckersTy::const_iterator checkers_begin() { return Checkers.begin(); }
  469. CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
  470. void runChecker(CheckerManager::CheckDeadSymbolsFunc checkFn,
  471. NodeBuilder &Bldr, ExplodedNode *Pred) {
  472. const ProgramPoint &L = ProgramPoint::getProgramPoint(S, ProgarmPointKind,
  473. Pred->getLocationContext(), checkFn.Checker);
  474. CheckerContext C(Bldr, Eng, Pred, L);
  475. // Note, do not pass the statement to the checkers without letting them
  476. // differentiate if we ran remove dead bindings before or after the
  477. // statement.
  478. checkFn(SR, C);
  479. }
  480. };
  481. } // namespace
  482. /// Run checkers for dead symbols.
  483. void CheckerManager::runCheckersForDeadSymbols(ExplodedNodeSet &Dst,
  484. const ExplodedNodeSet &Src,
  485. SymbolReaper &SymReaper,
  486. const Stmt *S,
  487. ExprEngine &Eng,
  488. ProgramPoint::Kind K) {
  489. CheckDeadSymbolsContext C(DeadSymbolsCheckers, SymReaper, S, Eng, K);
  490. expandGraphWithCheckers(C, Dst, Src);
  491. }
  492. /// Run checkers for region changes.
  493. ProgramStateRef
  494. CheckerManager::runCheckersForRegionChanges(ProgramStateRef state,
  495. const InvalidatedSymbols *invalidated,
  496. ArrayRef<const MemRegion *> ExplicitRegions,
  497. ArrayRef<const MemRegion *> Regions,
  498. const LocationContext *LCtx,
  499. const CallEvent *Call) {
  500. for (const auto &RegionChangesChecker : RegionChangesCheckers) {
  501. // If any checker declares the state infeasible (or if it starts that way),
  502. // bail out.
  503. if (!state)
  504. return nullptr;
  505. state = RegionChangesChecker(state, invalidated, ExplicitRegions, Regions,
  506. LCtx, Call);
  507. }
  508. return state;
  509. }
  510. /// Run checkers to process symbol escape event.
  511. ProgramStateRef
  512. CheckerManager::runCheckersForPointerEscape(ProgramStateRef State,
  513. const InvalidatedSymbols &Escaped,
  514. const CallEvent *Call,
  515. PointerEscapeKind Kind,
  516. RegionAndSymbolInvalidationTraits *ETraits) {
  517. assert((Call != nullptr ||
  518. (Kind != PSK_DirectEscapeOnCall &&
  519. Kind != PSK_IndirectEscapeOnCall)) &&
  520. "Call must not be NULL when escaping on call");
  521. for (const auto &PointerEscapeChecker : PointerEscapeCheckers) {
  522. // If any checker declares the state infeasible (or if it starts that
  523. // way), bail out.
  524. if (!State)
  525. return nullptr;
  526. State = PointerEscapeChecker(State, Escaped, Call, Kind, ETraits);
  527. }
  528. return State;
  529. }
  530. /// Run checkers for handling assumptions on symbolic values.
  531. ProgramStateRef
  532. CheckerManager::runCheckersForEvalAssume(ProgramStateRef state,
  533. SVal Cond, bool Assumption) {
  534. for (const auto &EvalAssumeChecker : EvalAssumeCheckers) {
  535. // If any checker declares the state infeasible (or if it starts that way),
  536. // bail out.
  537. if (!state)
  538. return nullptr;
  539. state = EvalAssumeChecker(state, Cond, Assumption);
  540. }
  541. return state;
  542. }
  543. /// Run checkers for evaluating a call.
  544. /// Only one checker will evaluate the call.
  545. void CheckerManager::runCheckersForEvalCall(ExplodedNodeSet &Dst,
  546. const ExplodedNodeSet &Src,
  547. const CallEvent &Call,
  548. ExprEngine &Eng,
  549. const EvalCallOptions &CallOpts) {
  550. for (auto *const Pred : Src) {
  551. Optional<CheckerNameRef> evaluatorChecker;
  552. ExplodedNodeSet checkDst;
  553. NodeBuilder B(Pred, checkDst, Eng.getBuilderContext());
  554. // Check if any of the EvalCall callbacks can evaluate the call.
  555. for (const auto &EvalCallChecker : EvalCallCheckers) {
  556. // TODO: Support the situation when the call doesn't correspond
  557. // to any Expr.
  558. ProgramPoint L = ProgramPoint::getProgramPoint(
  559. Call.getOriginExpr(), ProgramPoint::PostStmtKind,
  560. Pred->getLocationContext(), EvalCallChecker.Checker);
  561. bool evaluated = false;
  562. { // CheckerContext generates transitions(populates checkDest) on
  563. // destruction, so introduce the scope to make sure it gets properly
  564. // populated.
  565. CheckerContext C(B, Eng, Pred, L);
  566. evaluated = EvalCallChecker(Call, C);
  567. }
  568. #ifndef NDEBUG
  569. if (evaluated && evaluatorChecker) {
  570. const auto toString = [](const CallEvent &Call) -> std::string {
  571. std::string Buf;
  572. llvm::raw_string_ostream OS(Buf);
  573. Call.dump(OS);
  574. OS.flush();
  575. return Buf;
  576. };
  577. std::string AssertionMessage = llvm::formatv(
  578. "The '{0}' call has been already evaluated by the {1} checker, "
  579. "while the {2} checker also tried to evaluate the same call. At "
  580. "most one checker supposed to evaluate a call.",
  581. toString(Call), evaluatorChecker->getName(),
  582. EvalCallChecker.Checker->getCheckerName());
  583. llvm_unreachable(AssertionMessage.c_str());
  584. }
  585. #endif
  586. if (evaluated) {
  587. evaluatorChecker = EvalCallChecker.Checker->getCheckerName();
  588. Dst.insert(checkDst);
  589. #ifdef NDEBUG
  590. break; // on release don't check that no other checker also evals.
  591. #endif
  592. }
  593. }
  594. // If none of the checkers evaluated the call, ask ExprEngine to handle it.
  595. if (!evaluatorChecker) {
  596. NodeBuilder B(Pred, Dst, Eng.getBuilderContext());
  597. Eng.defaultEvalCall(B, Pred, Call, CallOpts);
  598. }
  599. }
  600. }
  601. /// Run checkers for the entire Translation Unit.
  602. void CheckerManager::runCheckersOnEndOfTranslationUnit(
  603. const TranslationUnitDecl *TU,
  604. AnalysisManager &mgr,
  605. BugReporter &BR) {
  606. for (const auto &EndOfTranslationUnitChecker : EndOfTranslationUnitCheckers)
  607. EndOfTranslationUnitChecker(TU, mgr, BR);
  608. }
  609. void CheckerManager::runCheckersForPrintStateJson(raw_ostream &Out,
  610. ProgramStateRef State,
  611. const char *NL,
  612. unsigned int Space,
  613. bool IsDot) const {
  614. Indent(Out, Space, IsDot) << "\"checker_messages\": ";
  615. // Create a temporary stream to see whether we have any message.
  616. SmallString<1024> TempBuf;
  617. llvm::raw_svector_ostream TempOut(TempBuf);
  618. unsigned int InnerSpace = Space + 2;
  619. // Create the new-line in JSON with enough space.
  620. SmallString<128> NewLine;
  621. llvm::raw_svector_ostream NLOut(NewLine);
  622. NLOut << "\", " << NL; // Inject the ending and a new line
  623. Indent(NLOut, InnerSpace, IsDot) << "\""; // then begin the next message.
  624. ++Space;
  625. bool HasMessage = false;
  626. // Store the last CheckerTag.
  627. const void *LastCT = nullptr;
  628. for (const auto &CT : CheckerTags) {
  629. // See whether the current checker has a message.
  630. CT.second->printState(TempOut, State, /*NL=*/NewLine.c_str(), /*Sep=*/"");
  631. if (TempBuf.empty())
  632. continue;
  633. if (!HasMessage) {
  634. Out << '[' << NL;
  635. HasMessage = true;
  636. }
  637. LastCT = &CT;
  638. TempBuf.clear();
  639. }
  640. for (const auto &CT : CheckerTags) {
  641. // See whether the current checker has a message.
  642. CT.second->printState(TempOut, State, /*NL=*/NewLine.c_str(), /*Sep=*/"");
  643. if (TempBuf.empty())
  644. continue;
  645. Indent(Out, Space, IsDot)
  646. << "{ \"checker\": \"" << CT.second->getCheckerName().getName()
  647. << "\", \"messages\": [" << NL;
  648. Indent(Out, InnerSpace, IsDot)
  649. << '\"' << TempBuf.str().trim() << '\"' << NL;
  650. Indent(Out, Space, IsDot) << "]}";
  651. if (&CT != LastCT)
  652. Out << ',';
  653. Out << NL;
  654. TempBuf.clear();
  655. }
  656. // It is the last element of the 'program_state' so do not add a comma.
  657. if (HasMessage)
  658. Indent(Out, --Space, IsDot) << "]";
  659. else
  660. Out << "null";
  661. Out << NL;
  662. }
  663. //===----------------------------------------------------------------------===//
  664. // Internal registration functions for AST traversing.
  665. //===----------------------------------------------------------------------===//
  666. void CheckerManager::_registerForDecl(CheckDeclFunc checkfn,
  667. HandlesDeclFunc isForDeclFn) {
  668. DeclCheckerInfo info = { checkfn, isForDeclFn };
  669. DeclCheckers.push_back(info);
  670. }
  671. void CheckerManager::_registerForBody(CheckDeclFunc checkfn) {
  672. BodyCheckers.push_back(checkfn);
  673. }
  674. //===----------------------------------------------------------------------===//
  675. // Internal registration functions for path-sensitive checking.
  676. //===----------------------------------------------------------------------===//
  677. void CheckerManager::_registerForPreStmt(CheckStmtFunc checkfn,
  678. HandlesStmtFunc isForStmtFn) {
  679. StmtCheckerInfo info = { checkfn, isForStmtFn, /*IsPreVisit*/true };
  680. StmtCheckers.push_back(info);
  681. }
  682. void CheckerManager::_registerForPostStmt(CheckStmtFunc checkfn,
  683. HandlesStmtFunc isForStmtFn) {
  684. StmtCheckerInfo info = { checkfn, isForStmtFn, /*IsPreVisit*/false };
  685. StmtCheckers.push_back(info);
  686. }
  687. void CheckerManager::_registerForPreObjCMessage(CheckObjCMessageFunc checkfn) {
  688. PreObjCMessageCheckers.push_back(checkfn);
  689. }
  690. void CheckerManager::_registerForObjCMessageNil(CheckObjCMessageFunc checkfn) {
  691. ObjCMessageNilCheckers.push_back(checkfn);
  692. }
  693. void CheckerManager::_registerForPostObjCMessage(CheckObjCMessageFunc checkfn) {
  694. PostObjCMessageCheckers.push_back(checkfn);
  695. }
  696. void CheckerManager::_registerForPreCall(CheckCallFunc checkfn) {
  697. PreCallCheckers.push_back(checkfn);
  698. }
  699. void CheckerManager::_registerForPostCall(CheckCallFunc checkfn) {
  700. PostCallCheckers.push_back(checkfn);
  701. }
  702. void CheckerManager::_registerForLocation(CheckLocationFunc checkfn) {
  703. LocationCheckers.push_back(checkfn);
  704. }
  705. void CheckerManager::_registerForBind(CheckBindFunc checkfn) {
  706. BindCheckers.push_back(checkfn);
  707. }
  708. void CheckerManager::_registerForEndAnalysis(CheckEndAnalysisFunc checkfn) {
  709. EndAnalysisCheckers.push_back(checkfn);
  710. }
  711. void CheckerManager::_registerForBeginFunction(CheckBeginFunctionFunc checkfn) {
  712. BeginFunctionCheckers.push_back(checkfn);
  713. }
  714. void CheckerManager::_registerForEndFunction(CheckEndFunctionFunc checkfn) {
  715. EndFunctionCheckers.push_back(checkfn);
  716. }
  717. void CheckerManager::_registerForBranchCondition(
  718. CheckBranchConditionFunc checkfn) {
  719. BranchConditionCheckers.push_back(checkfn);
  720. }
  721. void CheckerManager::_registerForNewAllocator(CheckNewAllocatorFunc checkfn) {
  722. NewAllocatorCheckers.push_back(checkfn);
  723. }
  724. void CheckerManager::_registerForLiveSymbols(CheckLiveSymbolsFunc checkfn) {
  725. LiveSymbolsCheckers.push_back(checkfn);
  726. }
  727. void CheckerManager::_registerForDeadSymbols(CheckDeadSymbolsFunc checkfn) {
  728. DeadSymbolsCheckers.push_back(checkfn);
  729. }
  730. void CheckerManager::_registerForRegionChanges(CheckRegionChangesFunc checkfn) {
  731. RegionChangesCheckers.push_back(checkfn);
  732. }
  733. void CheckerManager::_registerForPointerEscape(CheckPointerEscapeFunc checkfn){
  734. PointerEscapeCheckers.push_back(checkfn);
  735. }
  736. void CheckerManager::_registerForConstPointerEscape(
  737. CheckPointerEscapeFunc checkfn) {
  738. PointerEscapeCheckers.push_back(checkfn);
  739. }
  740. void CheckerManager::_registerForEvalAssume(EvalAssumeFunc checkfn) {
  741. EvalAssumeCheckers.push_back(checkfn);
  742. }
  743. void CheckerManager::_registerForEvalCall(EvalCallFunc checkfn) {
  744. EvalCallCheckers.push_back(checkfn);
  745. }
  746. void CheckerManager::_registerForEndOfTranslationUnit(
  747. CheckEndOfTranslationUnit checkfn) {
  748. EndOfTranslationUnitCheckers.push_back(checkfn);
  749. }
  750. //===----------------------------------------------------------------------===//
  751. // Implementation details.
  752. //===----------------------------------------------------------------------===//
  753. const CheckerManager::CachedStmtCheckers &
  754. CheckerManager::getCachedStmtCheckersFor(const Stmt *S, bool isPreVisit) {
  755. assert(S);
  756. unsigned Key = (S->getStmtClass() << 1) | unsigned(isPreVisit);
  757. CachedStmtCheckersMapTy::iterator CCI = CachedStmtCheckersMap.find(Key);
  758. if (CCI != CachedStmtCheckersMap.end())
  759. return CCI->second;
  760. // Find the checkers that should run for this Stmt and cache them.
  761. CachedStmtCheckers &Checkers = CachedStmtCheckersMap[Key];
  762. for (const auto &Info : StmtCheckers)
  763. if (Info.IsPreVisit == isPreVisit && Info.IsForStmtFn(S))
  764. Checkers.push_back(Info.CheckFn);
  765. return Checkers;
  766. }