1 //== CheckerContext.h - Context info for path-sensitive checkers--*- C++ -*--=//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines CheckerContext that provides contextual info for
10 // path-sensitive checkers.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CHECKERCONTEXT_H
15 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CHECKERCONTEXT_H
17 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
23 class CheckerContext {
25 /// The current exploded(symbolic execution) graph node.
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.
31 /// The tagged location, which is used to generate all new nodes.
32 const ProgramPoint Location;
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;
40 CheckerContext(NodeBuilder &builder,
43 const ProgramPoint &loc,
44 bool wasInlined = false)
50 wasInlined(wasInlined) {
51 assert(Pred->getState() &&
52 "We should not call the checkers on an empty state.");
55 AnalysisManager &getAnalysisManager() {
56 return Eng.getAnalysisManager();
59 ConstraintManager &getConstraintManager() {
60 return Eng.getConstraintManager();
63 StoreManager &getStoreManager() {
64 return Eng.getStoreManager();
67 /// Returns the previous node in the exploded graph, which includes
68 /// the state of the program before the checker ran. Note, checkers should
69 /// not retain the node in their state since the nodes might get invalidated.
70 ExplodedNode *getPredecessor() { return Pred; }
71 const ProgramStateRef &getState() const { return Pred->getState(); }
73 /// Check if the checker changed the state of the execution; ex: added
74 /// a new transition or a bug report.
75 bool isDifferent() { return Changed; }
77 /// Returns the number of times the current block has been visited
78 /// along the analyzed path.
79 unsigned blockCount() const {
80 return NB.getContext().blockCount();
83 ASTContext &getASTContext() {
84 return Eng.getContext();
87 const LangOptions &getLangOpts() const {
88 return Eng.getContext().getLangOpts();
91 const LocationContext *getLocationContext() const {
92 return Pred->getLocationContext();
95 const StackFrameContext *getStackFrame() const {
96 return Pred->getStackFrame();
99 /// Return true if the current LocationContext has no caller context.
100 bool inTopFrame() const { return getLocationContext()->inTopFrame(); }
102 BugReporter &getBugReporter() {
103 return Eng.getBugReporter();
106 const SourceManager &getSourceManager() {
107 return getBugReporter().getSourceManager();
110 SValBuilder &getSValBuilder() {
111 return Eng.getSValBuilder();
114 SymbolManager &getSymbolManager() {
115 return getSValBuilder().getSymbolManager();
118 ProgramStateManager &getStateManager() {
119 return Eng.getStateManager();
122 AnalysisDeclContext *getCurrentAnalysisDeclContext() const {
123 return Pred->getLocationContext()->getAnalysisDeclContext();
127 unsigned getBlockID() const {
128 return NB.getContext().getBlock()->getBlockID();
131 /// If the given node corresponds to a PostStore program point,
132 /// retrieve the location region as it was uttered in the code.
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 (Optional<PostStore> PSL = L.getAs<PostStore>())
139 return reinterpret_cast<const MemRegion*>(PSL->getLocationValue());
143 /// Get the value of arbitrary expressions at this point in the path.
144 SVal getSVal(const Stmt *S) const {
145 return Pred->getSVal(S);
148 /// Returns true if the value of \p E is greater than or equal to \p
149 /// Val under unsigned comparison
150 bool isGreaterOrEqual(const Expr *E, unsigned long long Val);
152 /// Returns true if the value of \p E is negative.
153 bool isNegative(const Expr *E);
155 /// Generates a new transition in the program state graph
156 /// (ExplodedGraph). Uses the default CheckerContext predecessor node.
158 /// @param State The state of the generated node. If not specified, the state
159 /// will not be changed, but the new node will have the checker's tag.
160 /// @param Tag The tag is used to uniquely identify the creation site. If no
161 /// tag is specified, a default tag, unique to the given checker,
162 /// will be used. Tags are used to prevent states generated at
163 /// different sites from caching out.
164 ExplodedNode *addTransition(ProgramStateRef State = nullptr,
165 const ProgramPointTag *Tag = nullptr) {
166 return addTransitionImpl(State ? State : getState(), false, nullptr, Tag);
169 /// Generates a new transition with the given predecessor.
170 /// Allows checkers to generate a chain of nodes.
172 /// @param State The state of the generated node.
173 /// @param Pred The transition will be generated from the specified Pred node
174 /// to the newly generated node.
175 /// @param Tag The tag to uniquely identify the creation site.
176 ExplodedNode *addTransition(ProgramStateRef State,
178 const ProgramPointTag *Tag = nullptr) {
179 return addTransitionImpl(State, false, Pred, Tag);
182 /// Generate a sink node. Generating a sink stops exploration of the
183 /// given path. To create a sink node for the purpose of reporting an error,
184 /// checkers should use generateErrorNode() instead.
185 ExplodedNode *generateSink(ProgramStateRef State, ExplodedNode *Pred,
186 const ProgramPointTag *Tag = nullptr) {
187 return addTransitionImpl(State ? State : getState(), true, Pred, Tag);
190 /// Generate a transition to a node that will be used to report
191 /// an error. This node will be a sink. That is, it will stop exploration of
194 /// @param State The state of the generated node.
195 /// @param Tag The tag to uniquely identify the creation site. If null,
196 /// the default tag for the checker will be used.
197 ExplodedNode *generateErrorNode(ProgramStateRef State = nullptr,
198 const ProgramPointTag *Tag = nullptr) {
199 return generateSink(State, Pred,
200 (Tag ? Tag : Location.getTag()));
203 /// Generate a transition to a node that will be used to report
204 /// an error. This node will not be a sink. That is, exploration will
205 /// continue along this path.
207 /// @param State The state of the generated node.
208 /// @param Tag The tag to uniquely identify the creation site. If null,
209 /// the default tag for the checker will be used.
211 generateNonFatalErrorNode(ProgramStateRef State = nullptr,
212 const ProgramPointTag *Tag = nullptr) {
213 return addTransition(State, (Tag ? Tag : Location.getTag()));
216 /// Emit the diagnostics report.
217 void emitReport(std::unique_ptr<BugReport> R) {
219 Eng.getBugReporter().emitReport(std::move(R));
222 /// Produce a program point tag that displays an additional path note
223 /// to the user. This is a lightweight alternative to the
224 /// BugReporterVisitor mechanism: instead of visiting the bug report
225 /// node-by-node to restore the sequence of events that led to discovering
226 /// a bug, you can add notes as you add your transitions.
228 /// @param Cb Callback with 'BugReporterContext &, BugReport &' parameters.
229 /// @param IsPrunable Whether the note is prunable. It allows BugReporter
230 /// to omit the note from the report if it would make the displayed
231 /// bug path significantly shorter.
232 const NoteTag *getNoteTag(NoteTag::Callback &&Cb, bool IsPrunable = false) {
233 return Eng.getNoteTags().makeNoteTag(std::move(Cb), IsPrunable);
236 /// A shorthand version of getNoteTag that doesn't require you to accept
237 /// the 'BugReporterContext' argument when you don't need it.
239 /// @param Cb Callback only with 'BugReport &' parameter.
240 /// @param IsPrunable Whether the note is prunable. It allows BugReporter
241 /// to omit the note from the report if it would make the displayed
242 /// bug path significantly shorter.
243 const NoteTag *getNoteTag(std::function<std::string(BugReport &)> &&Cb,
244 bool IsPrunable = false) {
246 [Cb](BugReporterContext &, BugReport &BR) { return Cb(BR); },
250 /// A shorthand version of getNoteTag that doesn't require you to accept
251 /// the arguments when you don't need it.
253 /// @param Cb Callback without parameters.
254 /// @param IsPrunable Whether the note is prunable. It allows BugReporter
255 /// to omit the note from the report if it would make the displayed
256 /// bug path significantly shorter.
257 const NoteTag *getNoteTag(std::function<std::string()> &&Cb,
258 bool IsPrunable = false) {
259 return getNoteTag([Cb](BugReporterContext &, BugReport &) { return Cb(); },
263 /// A shorthand version of getNoteTag that accepts a plain note.
265 /// @param Note The note.
266 /// @param IsPrunable Whether the note is prunable. It allows BugReporter
267 /// to omit the note from the report if it would make the displayed
268 /// bug path significantly shorter.
269 const NoteTag *getNoteTag(StringRef Note, bool IsPrunable = false) {
271 [Note](BugReporterContext &, BugReport &) { return Note; }, IsPrunable);
274 /// Returns the word that should be used to refer to the declaration
276 StringRef getDeclDescription(const Decl *D);
278 /// Get the declaration of the called function (path-sensitive).
279 const FunctionDecl *getCalleeDecl(const CallExpr *CE) const;
281 /// Get the name of the called function (path-sensitive).
282 StringRef getCalleeName(const FunctionDecl *FunDecl) const;
284 /// Get the identifier of the called function (path-sensitive).
285 const IdentifierInfo *getCalleeIdentifier(const CallExpr *CE) const {
286 const FunctionDecl *FunDecl = getCalleeDecl(CE);
288 return FunDecl->getIdentifier();
293 /// Get the name of the called function (path-sensitive).
294 StringRef getCalleeName(const CallExpr *CE) const {
295 const FunctionDecl *FunDecl = getCalleeDecl(CE);
296 return getCalleeName(FunDecl);
299 /// Returns true if the callee is an externally-visible function in the
300 /// top-level namespace, such as \c malloc.
302 /// If a name is provided, the function must additionally match the given
305 /// Note that this deliberately excludes C++ library functions in the \c std
306 /// namespace, but will include C library functions accessed through the
307 /// \c std namespace. This also does not check if the function is declared
308 /// as 'extern "C"', or if it uses C++ name mangling.
309 static bool isCLibraryFunction(const FunctionDecl *FD,
310 StringRef Name = StringRef());
312 /// Depending on wither the location corresponds to a macro, return
313 /// either the macro name or the token spelling.
315 /// This could be useful when checkers' logic depends on whether a function
316 /// is called with a given macro argument. For example:
317 /// s = socket(AF_INET,..)
318 /// If AF_INET is a macro, the result should be treated as a source of taint.
320 /// \sa clang::Lexer::getSpelling(), clang::Lexer::getImmediateMacroName().
321 StringRef getMacroNameOrSpelling(SourceLocation &Loc);
324 ExplodedNode *addTransitionImpl(ProgramStateRef State,
326 ExplodedNode *P = nullptr,
327 const ProgramPointTag *Tag = nullptr) {
328 // The analyzer may stop exploring if it sees a state it has previously
329 // visited ("cache out"). The early return here is a defensive check to
330 // prevent accidental caching out by checker API clients. Unless there is a
331 // tag or the client checker has requested that the generated node be
332 // marked as a sink, we assume that a client requesting a transition to a
333 // state that is the same as the predecessor state has made a mistake. We
334 // return the predecessor rather than cache out.
336 // TODO: We could potentially change the return to an assertion to alert
337 // clients to their mistake, but several checkers (including
338 // DereferenceChecker, CallAndMessageChecker, and DynamicTypePropagation)
339 // rely upon the defensive behavior and would need to be updated.
340 if (!State || (State == Pred->getState() && !Tag && !MarkAsSink))
344 const ProgramPoint &LocalLoc = (Tag ? Location.withTag(Tag) : Location);
350 node = NB.generateSink(LocalLoc, State, P);
352 node = NB.generateNode(LocalLoc, State, P);
357 } // end GR namespace
359 } // end clang namespace