CheckerContext.h revision 7b73e0832b20af1f43601a3d19e76d02d9f4dce5
1//== CheckerContext.h - Context info for path-sensitive checkers--*- 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 file defines CheckerContext that provides contextual info for
11// path-sensitive checkers.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_SA_CORE_PATHSENSITIVE_CHECKERCONTEXT
16#define LLVM_CLANG_SA_CORE_PATHSENSITIVE_CHECKERCONTEXT
17
18#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
19
20namespace clang {
21namespace ento {
22
23class CheckerContext {
24  ExprEngine &Eng;
25  /// The current exploded(symbolic execution) graph node.
26  ExplodedNode *Pred;
27  /// The flag is true if the (state of the execution) has been modified
28  /// by the checker using this context. For example, a new transition has been
29  /// added or a bug report issued.
30  bool Changed;
31  /// The tagged location, which is used to generate all new nodes.
32  const ProgramPoint Location;
33  NodeBuilder &NB;
34
35public:
36  /// If we are post visiting a call, this flag will be set if the
37  /// call was inlined.  In all other cases it will be false.
38  const bool wasInlined;
39
40  CheckerContext(NodeBuilder &builder,
41                 ExprEngine &eng,
42                 ExplodedNode *pred,
43                 const ProgramPoint &loc,
44                 bool wasInlined = false)
45    : Eng(eng),
46      Pred(pred),
47      Changed(false),
48      Location(loc),
49      NB(builder),
50      wasInlined(wasInlined) {
51    assert(Pred->getState() &&
52           "We should not call the checkers on an empty state.");
53  }
54
55  AnalysisManager &getAnalysisManager() {
56    return Eng.getAnalysisManager();
57  }
58
59  ConstraintManager &getConstraintManager() {
60    return Eng.getConstraintManager();
61  }
62
63  StoreManager &getStoreManager() {
64    return Eng.getStoreManager();
65  }
66
67  const AnalysisManager::ConfigTable &getConfig() const {
68    return Eng.getAnalysisManager().Config;
69  }
70
71  /// \brief Returns the previous node in the exploded graph, which includes
72  /// the state of the program before the checker ran. Note, checkers should
73  /// not retain the node in their state since the nodes might get invalidated.
74  ExplodedNode *getPredecessor() { return Pred; }
75  ProgramStateRef getState() const { return Pred->getState(); }
76
77  /// \brief Check if the checker changed the state of the execution; ex: added
78  /// a new transition or a bug report.
79  bool isDifferent() { return Changed; }
80
81  /// \brief Returns the number of times the current block has been visited
82  /// along the analyzed path.
83  unsigned blockCount() const {
84    return NB.getContext().blockCount();
85  }
86
87  ASTContext &getASTContext() {
88    return Eng.getContext();
89  }
90
91  const LangOptions &getLangOpts() const {
92    return Eng.getContext().getLangOpts();
93  }
94
95  const LocationContext *getLocationContext() const {
96    return Pred->getLocationContext();
97  }
98
99  const StackFrameContext *getStackFrame() const {
100    return Pred->getStackFrame();
101  }
102
103  BugReporter &getBugReporter() {
104    return Eng.getBugReporter();
105  }
106
107  SourceManager &getSourceManager() {
108    return getBugReporter().getSourceManager();
109  }
110
111  SValBuilder &getSValBuilder() {
112    return Eng.getSValBuilder();
113  }
114
115  SymbolManager &getSymbolManager() {
116    return getSValBuilder().getSymbolManager();
117  }
118
119  bool isObjCGCEnabled() const {
120    return Eng.isObjCGCEnabled();
121  }
122
123  ProgramStateManager &getStateManager() {
124    return Eng.getStateManager();
125  }
126
127  AnalysisDeclContext *getCurrentAnalysisDeclContext() const {
128    return Pred->getLocationContext()->getAnalysisDeclContext();
129  }
130
131  /// \brief If the given node corresponds to a PostStore program point, retrieve
132  /// the location region as it was uttered in the code.
133  ///
134  /// This utility can be useful for generating extensive diagnostics, for
135  /// example, for finding variables that the given symbol was assigned to.
136  static const MemRegion *getLocationRegionIfPostStore(const ExplodedNode *N) {
137    ProgramPoint L = N->getLocation();
138    if (const PostStore *PSL = dyn_cast<PostStore>(&L))
139      return reinterpret_cast<const MemRegion*>(PSL->getLocationValue());
140    return 0;
141  }
142
143  /// \brief Get the value of arbitrary expressions at this point in the path.
144  SVal getSVal(const Stmt *S) const {
145    return getState()->getSVal(S, getLocationContext());
146  }
147
148  /// \brief Generates a new transition in the program state graph
149  /// (ExplodedGraph). Uses the default CheckerContext predecessor node.
150  ///
151  /// @param State The state of the generated node. If not specified, the state
152  ///        will not be changed, but the new node will have the checker's tag.
153  /// @param Tag The tag is used to uniquely identify the creation site. If no
154  ///        tag is specified, a default tag, unique to the given checker,
155  ///        will be used. Tags are used to prevent states generated at
156  ///        different sites from caching out.
157  ExplodedNode *addTransition(ProgramStateRef State = 0,
158                              const ProgramPointTag *Tag = 0) {
159    return addTransitionImpl(State ? State : getState(), false, 0, Tag);
160  }
161
162  /// \brief Generates a new transition with the given predecessor.
163  /// Allows checkers to generate a chain of nodes.
164  ///
165  /// @param State The state of the generated node.
166  /// @param Pred The transition will be generated from the specified Pred node
167  ///             to the newly generated node.
168  /// @param Tag The tag to uniquely identify the creation site.
169  ExplodedNode *addTransition(ProgramStateRef State,
170                              ExplodedNode *Pred,
171                              const ProgramPointTag *Tag = 0) {
172    return addTransitionImpl(State, false, Pred, Tag);
173  }
174
175  /// \brief Generate a sink node. Generating a sink stops exploration of the
176  /// given path.
177  ExplodedNode *generateSink(ProgramStateRef State = 0,
178                             ExplodedNode *Pred = 0,
179                             const ProgramPointTag *Tag = 0) {
180    return addTransitionImpl(State ? State : getState(), true, Pred, Tag);
181  }
182
183  /// \brief Emit the diagnostics report.
184  void EmitReport(BugReport *R) {
185    Changed = true;
186    Eng.getBugReporter().EmitReport(R);
187  }
188
189  /// \brief Get the declaration of the called function (path-sensitive).
190  const FunctionDecl *getCalleeDecl(const CallExpr *CE) const;
191
192  /// \brief Get the name of the called function (path-sensitive).
193  StringRef getCalleeName(const FunctionDecl *FunDecl) const;
194
195  /// \brief Get the name of the called function (path-sensitive).
196  StringRef getCalleeName(const CallExpr *CE) const {
197    const FunctionDecl *FunDecl = getCalleeDecl(CE);
198    return getCalleeName(FunDecl);
199  }
200
201  /// Given a function declaration and a name checks if this is a C lib
202  /// function with the given name.
203  bool isCLibraryFunction(const FunctionDecl *FD, StringRef Name);
204  static bool isCLibraryFunction(const FunctionDecl *FD, StringRef Name,
205                                 ASTContext &Context);
206
207  /// \brief Depending on wither the location corresponds to a macro, return
208  /// either the macro name or the token spelling.
209  ///
210  /// This could be useful when checkers' logic depends on whether a function
211  /// is called with a given macro argument. For example:
212  ///   s = socket(AF_INET,..)
213  /// If AF_INET is a macro, the result should be treated as a source of taint.
214  ///
215  /// \sa clang::Lexer::getSpelling(), clang::Lexer::getImmediateMacroName().
216  StringRef getMacroNameOrSpelling(SourceLocation &Loc);
217
218private:
219  ExplodedNode *addTransitionImpl(ProgramStateRef State,
220                                 bool MarkAsSink,
221                                 ExplodedNode *P = 0,
222                                 const ProgramPointTag *Tag = 0) {
223    if (!State || (State == Pred->getState() && !Tag && !MarkAsSink))
224      return Pred;
225
226    Changed = true;
227    const ProgramPoint &LocalLoc = (Tag ? Location.withTag(Tag) : Location);
228    if (!P)
229      P = Pred;
230
231    ExplodedNode *node;
232    if (MarkAsSink)
233      node = NB.generateSink(LocalLoc, State, P);
234    else
235      node = NB.generateNode(LocalLoc, State, P);
236    return node;
237  }
238};
239
240/// \brief A helper class which wraps a boolean value set to false by default.
241struct DefaultBool {
242  bool Val;
243  DefaultBool() : Val(false) {}
244  operator bool() const { return Val; }
245  DefaultBool &operator=(bool b) { Val = b; return *this; }
246};
247
248} // end GR namespace
249
250} // end clang namespace
251
252#endif
253