CheckerManager.h revision dbd658e139b3e0bf084f75feaea8d844af9e319f
1//===--- CheckerManager.h - Static Analyzer Checker Manager -----*- 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// Defines the Static Analyzer Checker Manager.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SA_CORE_CHECKERMANAGER_H
15#define LLVM_CLANG_SA_CORE_CHECKERMANAGER_H
16
17#include "clang/Basic/LangOptions.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/FoldingSet.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
22#include <vector>
23
24namespace clang {
25  class Decl;
26  class Stmt;
27  class CallExpr;
28
29namespace ento {
30  class CheckerBase;
31  class ExprEngine;
32  class AnalysisManager;
33  class BugReporter;
34  class CheckerContext;
35  class ObjCMessage;
36  class SVal;
37  class ExplodedNode;
38  class ExplodedNodeSet;
39  class ExplodedGraph;
40  class ProgramState;
41  class EndOfFunctionNodeBuilder;
42  class BranchNodeBuilder;
43  class MemRegion;
44  class SymbolReaper;
45
46class GraphExpander {
47public:
48  virtual ~GraphExpander();
49  virtual void expandGraph(ExplodedNodeSet &Dst, ExplodedNode *Pred) = 0;
50};
51
52template <typename T> class CheckerFn;
53
54template <typename RET, typename P1, typename P2, typename P3, typename P4>
55class CheckerFn<RET(P1, P2, P3, P4)> {
56  typedef RET (*Func)(void *, P1, P2, P3, P4);
57  Func Fn;
58public:
59  CheckerBase *Checker;
60  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
61  RET operator()(P1 p1, P2 p2, P3 p3, P4 p4) const {
62    return Fn(Checker, p1, p2, p3, p4);
63  }
64};
65
66template <typename RET, typename P1, typename P2, typename P3>
67class CheckerFn<RET(P1, P2, P3)> {
68  typedef RET (*Func)(void *, P1, P2, P3);
69  Func Fn;
70public:
71  CheckerBase *Checker;
72  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
73  RET operator()(P1 p1, P2 p2, P3 p3) const { return Fn(Checker, p1, p2, p3); }
74};
75
76template <typename RET, typename P1, typename P2>
77class CheckerFn<RET(P1, P2)> {
78  typedef RET (*Func)(void *, P1, P2);
79  Func Fn;
80public:
81  CheckerBase *Checker;
82  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
83  RET operator()(P1 p1, P2 p2) const { return Fn(Checker, p1, p2); }
84};
85
86template <typename RET, typename P1>
87class CheckerFn<RET(P1)> {
88  typedef RET (*Func)(void *, P1);
89  Func Fn;
90public:
91  CheckerBase *Checker;
92  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
93  RET operator()(P1 p1) const { return Fn(Checker, p1); }
94};
95
96template <typename RET>
97class CheckerFn<RET()> {
98  typedef RET (*Func)(void *);
99  Func Fn;
100public:
101  CheckerBase *Checker;
102  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
103  RET operator()() const { return Fn(Checker); }
104};
105
106class CheckerManager {
107  const LangOptions LangOpts;
108
109public:
110  CheckerManager(const LangOptions &langOpts) : LangOpts(langOpts) { }
111  ~CheckerManager();
112
113  bool hasPathSensitiveCheckers() const;
114
115  void finishedCheckerRegistration();
116
117  const LangOptions &getLangOptions() const { return LangOpts; }
118
119  typedef CheckerBase *CheckerRef;
120  typedef const void *CheckerTag;
121  typedef CheckerFn<void ()> CheckerDtor;
122
123//===----------------------------------------------------------------------===//
124// registerChecker
125//===----------------------------------------------------------------------===//
126
127  /// \brief Used to register checkers.
128  ///
129  /// \returns a pointer to the checker object.
130  template <typename CHECKER>
131  CHECKER *registerChecker() {
132    CheckerTag tag = getTag<CHECKER>();
133    CheckerRef &ref = CheckerTags[tag];
134    if (ref)
135      return static_cast<CHECKER *>(ref); // already registered.
136
137    CHECKER *checker = new CHECKER();
138    CheckerDtors.push_back(CheckerDtor(checker, destruct<CHECKER>));
139    CHECKER::_register(checker, *this);
140    ref = checker;
141    return checker;
142  }
143
144//===----------------------------------------------------------------------===//
145// Functions for running checkers for AST traversing..
146//===----------------------------------------------------------------------===//
147
148  /// \brief Run checkers handling Decls.
149  void runCheckersOnASTDecl(const Decl *D, AnalysisManager& mgr,
150                            BugReporter &BR);
151
152  /// \brief Run checkers handling Decls containing a Stmt body.
153  void runCheckersOnASTBody(const Decl *D, AnalysisManager& mgr,
154                            BugReporter &BR);
155
156//===----------------------------------------------------------------------===//
157// Functions for running checkers for path-sensitive checking.
158//===----------------------------------------------------------------------===//
159
160  /// \brief Run checkers for pre-visiting Stmts.
161  void runCheckersForPreStmt(ExplodedNodeSet &Dst,
162                             const ExplodedNodeSet &Src,
163                             const Stmt *S,
164                             ExprEngine &Eng) {
165    runCheckersForStmt(/*isPreVisit=*/true, Dst, Src, S, Eng);
166  }
167
168  /// \brief Run checkers for post-visiting Stmts.
169  void runCheckersForPostStmt(ExplodedNodeSet &Dst,
170                              const ExplodedNodeSet &Src,
171                              const Stmt *S,
172                              ExprEngine &Eng) {
173    runCheckersForStmt(/*isPreVisit=*/false, Dst, Src, S, Eng);
174  }
175
176  /// \brief Run checkers for visiting Stmts.
177  void runCheckersForStmt(bool isPreVisit,
178                          ExplodedNodeSet &Dst, const ExplodedNodeSet &Src,
179                          const Stmt *S, ExprEngine &Eng);
180
181  /// \brief Run checkers for pre-visiting obj-c messages.
182  void runCheckersForPreObjCMessage(ExplodedNodeSet &Dst,
183                                    const ExplodedNodeSet &Src,
184                                    const ObjCMessage &msg,
185                                    ExprEngine &Eng) {
186    runCheckersForObjCMessage(/*isPreVisit=*/true, Dst, Src, msg, Eng);
187  }
188
189  /// \brief Run checkers for post-visiting obj-c messages.
190  void runCheckersForPostObjCMessage(ExplodedNodeSet &Dst,
191                                     const ExplodedNodeSet &Src,
192                                     const ObjCMessage &msg,
193                                     ExprEngine &Eng) {
194    runCheckersForObjCMessage(/*isPreVisit=*/false, Dst, Src, msg, Eng);
195  }
196
197  /// \brief Run checkers for visiting obj-c messages.
198  void runCheckersForObjCMessage(bool isPreVisit,
199                                 ExplodedNodeSet &Dst,
200                                 const ExplodedNodeSet &Src,
201                                 const ObjCMessage &msg, ExprEngine &Eng);
202
203  /// \brief Run checkers for load/store of a location.
204  void runCheckersForLocation(ExplodedNodeSet &Dst,
205                              const ExplodedNodeSet &Src,
206                              SVal location, bool isLoad,
207                              const Stmt *S,
208                              ExprEngine &Eng);
209
210  /// \brief Run checkers for binding of a value to a location.
211  void runCheckersForBind(ExplodedNodeSet &Dst,
212                          const ExplodedNodeSet &Src,
213                          SVal location, SVal val,
214                          const Stmt *S, ExprEngine &Eng);
215
216  /// \brief Run checkers for end of analysis.
217  void runCheckersForEndAnalysis(ExplodedGraph &G, BugReporter &BR,
218                                 ExprEngine &Eng);
219
220  /// \brief Run checkers for end of path.
221  void runCheckersForEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng);
222
223  /// \brief Run checkers for branch condition.
224  void runCheckersForBranchCondition(const Stmt *condition,
225                                     BranchNodeBuilder &B, ExprEngine &Eng);
226
227  /// \brief Run checkers for live symbols.
228  void runCheckersForLiveSymbols(const ProgramState *state,
229                                 SymbolReaper &SymReaper);
230
231  /// \brief Run checkers for dead symbols.
232  void runCheckersForDeadSymbols(ExplodedNodeSet &Dst,
233                                 const ExplodedNodeSet &Src,
234                                 SymbolReaper &SymReaper, const Stmt *S,
235                                 ExprEngine &Eng);
236
237  /// \brief True if at least one checker wants to check region changes.
238  bool wantsRegionChangeUpdate(const ProgramState *state);
239
240  /// \brief Run checkers for region changes.
241  ///
242  /// This corresponds to the check::RegionChanges callback.
243  /// \param state The current program state.
244  /// \param invalidated A set of all symbols potentially touched by the change.
245  /// \param ExplicitRegions The regions explicitly requested for invalidation.
246  ///   For example, in the case of a function call, these would be arguments.
247  /// \param Regions The transitive closure of accessible regions,
248  ///   i.e. all regions that may have been touched by this change.
249  const ProgramState *
250  runCheckersForRegionChanges(const ProgramState *state,
251                            const StoreManager::InvalidatedSymbols *invalidated,
252                              ArrayRef<const MemRegion *> ExplicitRegions,
253                              ArrayRef<const MemRegion *> Regions);
254
255  /// \brief Run checkers for handling assumptions on symbolic values.
256  const ProgramState *runCheckersForEvalAssume(const ProgramState *state,
257                                          SVal Cond, bool Assumption);
258
259  /// \brief Run checkers for evaluating a call.
260  void runCheckersForEvalCall(ExplodedNodeSet &Dst,
261                              const ExplodedNodeSet &Src,
262                              const CallExpr *CE, ExprEngine &Eng,
263                              GraphExpander *defaultEval = 0);
264
265  /// \brief Run checkers for the entire Translation Unit.
266  void runCheckersOnEndOfTranslationUnit(const TranslationUnitDecl *TU,
267                                         AnalysisManager &mgr,
268                                         BugReporter &BR);
269
270  /// \brief Run checkers for debug-printing a ProgramState.
271  ///
272  /// Unlike most other callbacks, any checker can simply implement the virtual
273  /// method CheckerBase::printState if it has custom data to print.
274  /// \param Out The output stream
275  /// \param State The state being printed
276  /// \param NL The preferred representation of a newline.
277  /// \param Sep The preferred separator between different kinds of data.
278  void runCheckersForPrintState(raw_ostream &Out, const ProgramState *State,
279                                const char *NL, const char *Sep);
280
281//===----------------------------------------------------------------------===//
282// Internal registration functions for AST traversing.
283//===----------------------------------------------------------------------===//
284
285  // Functions used by the registration mechanism, checkers should not touch
286  // these directly.
287
288  typedef CheckerFn<void (const Decl *, AnalysisManager&, BugReporter &)>
289      CheckDeclFunc;
290
291  typedef bool (*HandlesDeclFunc)(const Decl *D);
292  void _registerForDecl(CheckDeclFunc checkfn, HandlesDeclFunc isForDeclFn);
293
294  void _registerForBody(CheckDeclFunc checkfn);
295
296//===----------------------------------------------------------------------===//
297// Internal registration functions for path-sensitive checking.
298//===----------------------------------------------------------------------===//
299
300  typedef CheckerFn<void (const Stmt *, CheckerContext &)> CheckStmtFunc;
301
302  typedef CheckerFn<void (const ObjCMessage &, CheckerContext &)>
303      CheckObjCMessageFunc;
304
305  typedef CheckerFn<void (const SVal &location, bool isLoad, CheckerContext &)>
306      CheckLocationFunc;
307
308  typedef CheckerFn<void (const SVal &location, const SVal &val,
309                          CheckerContext &)> CheckBindFunc;
310
311  typedef CheckerFn<void (ExplodedGraph &, BugReporter &, ExprEngine &)>
312      CheckEndAnalysisFunc;
313
314  typedef CheckerFn<void (EndOfFunctionNodeBuilder &, ExprEngine &)>
315      CheckEndPathFunc;
316
317  typedef CheckerFn<void (const Stmt *, BranchNodeBuilder &, ExprEngine &)>
318      CheckBranchConditionFunc;
319
320  typedef CheckerFn<void (SymbolReaper &, CheckerContext &)>
321      CheckDeadSymbolsFunc;
322
323  typedef CheckerFn<void (const ProgramState *,SymbolReaper &)> CheckLiveSymbolsFunc;
324
325  typedef CheckerFn<const ProgramState * (const ProgramState *,
326                                const StoreManager::InvalidatedSymbols *symbols,
327                                    ArrayRef<const MemRegion *> ExplicitRegions,
328                                          ArrayRef<const MemRegion *> Regions)>
329      CheckRegionChangesFunc;
330
331  typedef CheckerFn<bool (const ProgramState *)> WantsRegionChangeUpdateFunc;
332
333  typedef CheckerFn<const ProgramState * (const ProgramState *,
334                                          const SVal &cond, bool assumption)>
335      EvalAssumeFunc;
336
337  typedef CheckerFn<bool (const CallExpr *, CheckerContext &)>
338      EvalCallFunc;
339
340  typedef CheckerFn<void (const TranslationUnitDecl *,
341                          AnalysisManager&, BugReporter &)>
342      CheckEndOfTranslationUnit;
343
344  typedef bool (*HandlesStmtFunc)(const Stmt *D);
345  void _registerForPreStmt(CheckStmtFunc checkfn,
346                           HandlesStmtFunc isForStmtFn);
347  void _registerForPostStmt(CheckStmtFunc checkfn,
348                            HandlesStmtFunc isForStmtFn);
349
350  void _registerForPreObjCMessage(CheckObjCMessageFunc checkfn);
351  void _registerForPostObjCMessage(CheckObjCMessageFunc checkfn);
352
353  void _registerForLocation(CheckLocationFunc checkfn);
354
355  void _registerForBind(CheckBindFunc checkfn);
356
357  void _registerForEndAnalysis(CheckEndAnalysisFunc checkfn);
358
359  void _registerForEndPath(CheckEndPathFunc checkfn);
360
361  void _registerForBranchCondition(CheckBranchConditionFunc checkfn);
362
363  void _registerForLiveSymbols(CheckLiveSymbolsFunc checkfn);
364
365  void _registerForDeadSymbols(CheckDeadSymbolsFunc checkfn);
366
367  void _registerForRegionChanges(CheckRegionChangesFunc checkfn,
368                                 WantsRegionChangeUpdateFunc wantUpdateFn);
369
370  void _registerForEvalAssume(EvalAssumeFunc checkfn);
371
372  void _registerForEvalCall(EvalCallFunc checkfn);
373
374  void _registerForEndOfTranslationUnit(CheckEndOfTranslationUnit checkfn);
375
376//===----------------------------------------------------------------------===//
377// Internal registration functions for events.
378//===----------------------------------------------------------------------===//
379
380  typedef void *EventTag;
381  typedef CheckerFn<void (const void *event)> CheckEventFunc;
382
383  template <typename EVENT>
384  void _registerListenerForEvent(CheckEventFunc checkfn) {
385    EventInfo &info = Events[getTag<EVENT>()];
386    info.Checkers.push_back(checkfn);
387  }
388
389  template <typename EVENT>
390  void _registerDispatcherForEvent() {
391    EventInfo &info = Events[getTag<EVENT>()];
392    info.HasDispatcher = true;
393  }
394
395  template <typename EVENT>
396  void _dispatchEvent(const EVENT &event) const {
397    EventsTy::const_iterator I = Events.find(getTag<EVENT>());
398    if (I == Events.end())
399      return;
400    const EventInfo &info = I->second;
401    for (unsigned i = 0, e = info.Checkers.size(); i != e; ++i)
402      info.Checkers[i](&event);
403  }
404
405//===----------------------------------------------------------------------===//
406// Implementation details.
407//===----------------------------------------------------------------------===//
408
409private:
410  template <typename CHECKER>
411  static void destruct(void *obj) { delete static_cast<CHECKER *>(obj); }
412
413  template <typename T>
414  static void *getTag() { static int tag; return &tag; }
415
416  llvm::DenseMap<CheckerTag, CheckerRef> CheckerTags;
417
418  std::vector<CheckerDtor> CheckerDtors;
419
420  struct DeclCheckerInfo {
421    CheckDeclFunc CheckFn;
422    HandlesDeclFunc IsForDeclFn;
423  };
424  std::vector<DeclCheckerInfo> DeclCheckers;
425
426  std::vector<CheckDeclFunc> BodyCheckers;
427
428  typedef SmallVector<CheckDeclFunc, 4> CachedDeclCheckers;
429  typedef llvm::DenseMap<unsigned, CachedDeclCheckers> CachedDeclCheckersMapTy;
430  CachedDeclCheckersMapTy CachedDeclCheckersMap;
431
432  struct StmtCheckerInfo {
433    CheckStmtFunc CheckFn;
434    HandlesStmtFunc IsForStmtFn;
435    bool IsPreVisit;
436  };
437  std::vector<StmtCheckerInfo> StmtCheckers;
438
439  struct CachedStmtCheckersKey {
440    unsigned StmtKind;
441    bool IsPreVisit;
442
443    CachedStmtCheckersKey() : StmtKind(0), IsPreVisit(0) { }
444    CachedStmtCheckersKey(unsigned stmtKind, bool isPreVisit)
445      : StmtKind(stmtKind), IsPreVisit(isPreVisit) { }
446
447    static CachedStmtCheckersKey getSentinel() {
448      return CachedStmtCheckersKey(~0U, 0);
449    }
450    unsigned getHashValue() const {
451      llvm::FoldingSetNodeID ID;
452      ID.AddInteger(StmtKind);
453      ID.AddBoolean(IsPreVisit);
454      return ID.ComputeHash();
455    }
456    bool operator==(const CachedStmtCheckersKey &RHS) const {
457      return StmtKind == RHS.StmtKind && IsPreVisit == RHS.IsPreVisit;
458    }
459  };
460  friend struct llvm::DenseMapInfo<CachedStmtCheckersKey>;
461
462  typedef SmallVector<CheckStmtFunc, 4> CachedStmtCheckers;
463  typedef llvm::DenseMap<CachedStmtCheckersKey, CachedStmtCheckers>
464      CachedStmtCheckersMapTy;
465  CachedStmtCheckersMapTy CachedStmtCheckersMap;
466
467  CachedStmtCheckers *getCachedStmtCheckersFor(const Stmt *S, bool isPreVisit);
468
469  std::vector<CheckObjCMessageFunc> PreObjCMessageCheckers;
470  std::vector<CheckObjCMessageFunc> PostObjCMessageCheckers;
471
472  std::vector<CheckLocationFunc> LocationCheckers;
473
474  std::vector<CheckBindFunc> BindCheckers;
475
476  std::vector<CheckEndAnalysisFunc> EndAnalysisCheckers;
477
478  std::vector<CheckEndPathFunc> EndPathCheckers;
479
480  std::vector<CheckBranchConditionFunc> BranchConditionCheckers;
481
482  std::vector<CheckLiveSymbolsFunc> LiveSymbolsCheckers;
483
484  std::vector<CheckDeadSymbolsFunc> DeadSymbolsCheckers;
485
486  struct RegionChangesCheckerInfo {
487    CheckRegionChangesFunc CheckFn;
488    WantsRegionChangeUpdateFunc WantUpdateFn;
489  };
490  std::vector<RegionChangesCheckerInfo> RegionChangesCheckers;
491
492  std::vector<EvalAssumeFunc> EvalAssumeCheckers;
493
494  std::vector<EvalCallFunc> EvalCallCheckers;
495
496  std::vector<CheckEndOfTranslationUnit> EndOfTranslationUnitCheckers;
497
498  struct EventInfo {
499    SmallVector<CheckEventFunc, 4> Checkers;
500    bool HasDispatcher;
501    EventInfo() : HasDispatcher(false) { }
502  };
503
504  typedef llvm::DenseMap<EventTag, EventInfo> EventsTy;
505  EventsTy Events;
506};
507
508} // end ento namespace
509
510} // end clang namespace
511
512namespace llvm {
513  /// Define DenseMapInfo so that CachedStmtCheckersKey can be used as key
514  /// in DenseMap and DenseSets.
515  template <>
516  struct DenseMapInfo<clang::ento::CheckerManager::CachedStmtCheckersKey> {
517    static inline clang::ento::CheckerManager::CachedStmtCheckersKey
518        getEmptyKey() {
519      return clang::ento::CheckerManager::CachedStmtCheckersKey();
520    }
521    static inline clang::ento::CheckerManager::CachedStmtCheckersKey
522        getTombstoneKey() {
523      return clang::ento::CheckerManager::CachedStmtCheckersKey::getSentinel();
524    }
525
526    static unsigned
527        getHashValue(clang::ento::CheckerManager::CachedStmtCheckersKey S) {
528      return S.getHashValue();
529    }
530
531    static bool isEqual(clang::ento::CheckerManager::CachedStmtCheckersKey LHS,
532                       clang::ento::CheckerManager::CachedStmtCheckersKey RHS) {
533      return LHS == RHS;
534    }
535  };
536} // end namespace llvm
537
538#endif
539