[DFAJumpThreading] Remove incoming StartBlock from all phis when unfolding select...
[llvm-project.git] / clang / lib / StaticAnalyzer / Checkers / SimpleStreamChecker.cpp
blob32d95e944195390bc76804310afeff659e66beae
1 //===-- SimpleStreamChecker.cpp -----------------------------------------*- C++ -*--//
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 a checker for proper use of fopen/fclose APIs.
10 // - If a file has been closed with fclose, it should not be accessed again.
11 // Accessing a closed file results in undefined behavior.
12 // - If a file was opened with fopen, it must be closed with fclose before
13 // the execution ends. Failing to do so results in a resource leak.
15 //===----------------------------------------------------------------------===//
17 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23 #include <utility>
25 using namespace clang;
26 using namespace ento;
28 namespace {
29 typedef SmallVector<SymbolRef, 2> SymbolVector;
31 struct StreamState {
32 private:
33 enum Kind { Opened, Closed } K;
34 StreamState(Kind InK) : K(InK) { }
36 public:
37 bool isOpened() const { return K == Opened; }
38 bool isClosed() const { return K == Closed; }
40 static StreamState getOpened() { return StreamState(Opened); }
41 static StreamState getClosed() { return StreamState(Closed); }
43 bool operator==(const StreamState &X) const {
44 return K == X.K;
46 void Profile(llvm::FoldingSetNodeID &ID) const {
47 ID.AddInteger(K);
51 class SimpleStreamChecker : public Checker<check::PostCall,
52 check::PreCall,
53 check::DeadSymbols,
54 check::PointerEscape> {
55 CallDescription OpenFn, CloseFn;
57 std::unique_ptr<BugType> DoubleCloseBugType;
58 std::unique_ptr<BugType> LeakBugType;
60 void reportDoubleClose(SymbolRef FileDescSym,
61 const CallEvent &Call,
62 CheckerContext &C) const;
64 void reportLeaks(ArrayRef<SymbolRef> LeakedStreams, CheckerContext &C,
65 ExplodedNode *ErrNode) const;
67 bool guaranteedNotToCloseFile(const CallEvent &Call) const;
69 public:
70 SimpleStreamChecker();
72 /// Process fopen.
73 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
74 /// Process fclose.
75 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
77 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
79 /// Stop tracking addresses which escape.
80 ProgramStateRef checkPointerEscape(ProgramStateRef State,
81 const InvalidatedSymbols &Escaped,
82 const CallEvent *Call,
83 PointerEscapeKind Kind) const;
86 } // end anonymous namespace
88 /// The state of the checker is a map from tracked stream symbols to their
89 /// state. Let's store it in the ProgramState.
90 REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap, SymbolRef, StreamState)
92 SimpleStreamChecker::SimpleStreamChecker()
93 : OpenFn({"fopen"}), CloseFn({"fclose"}, 1) {
94 // Initialize the bug types.
95 DoubleCloseBugType.reset(
96 new BugType(this, "Double fclose", "Unix Stream API Error"));
98 // Sinks are higher importance bugs as well as calls to assert() or exit(0).
99 LeakBugType.reset(
100 new BugType(this, "Resource Leak", "Unix Stream API Error",
101 /*SuppressOnSink=*/true));
104 void SimpleStreamChecker::checkPostCall(const CallEvent &Call,
105 CheckerContext &C) const {
106 if (!Call.isGlobalCFunction())
107 return;
109 if (!OpenFn.matches(Call))
110 return;
112 // Get the symbolic value corresponding to the file handle.
113 SymbolRef FileDesc = Call.getReturnValue().getAsSymbol();
114 if (!FileDesc)
115 return;
117 // Generate the next transition (an edge in the exploded graph).
118 ProgramStateRef State = C.getState();
119 State = State->set<StreamMap>(FileDesc, StreamState::getOpened());
120 C.addTransition(State);
123 void SimpleStreamChecker::checkPreCall(const CallEvent &Call,
124 CheckerContext &C) const {
125 if (!Call.isGlobalCFunction())
126 return;
128 if (!CloseFn.matches(Call))
129 return;
131 // Get the symbolic value corresponding to the file handle.
132 SymbolRef FileDesc = Call.getArgSVal(0).getAsSymbol();
133 if (!FileDesc)
134 return;
136 // Check if the stream has already been closed.
137 ProgramStateRef State = C.getState();
138 const StreamState *SS = State->get<StreamMap>(FileDesc);
139 if (SS && SS->isClosed()) {
140 reportDoubleClose(FileDesc, Call, C);
141 return;
144 // Generate the next transition, in which the stream is closed.
145 State = State->set<StreamMap>(FileDesc, StreamState::getClosed());
146 C.addTransition(State);
149 static bool isLeaked(SymbolRef Sym, const StreamState &SS,
150 bool IsSymDead, ProgramStateRef State) {
151 if (IsSymDead && SS.isOpened()) {
152 // If a symbol is NULL, assume that fopen failed on this path.
153 // A symbol should only be considered leaked if it is non-null.
154 ConstraintManager &CMgr = State->getConstraintManager();
155 ConditionTruthVal OpenFailed = CMgr.isNull(State, Sym);
156 return !OpenFailed.isConstrainedTrue();
158 return false;
161 void SimpleStreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
162 CheckerContext &C) const {
163 ProgramStateRef State = C.getState();
164 SymbolVector LeakedStreams;
165 StreamMapTy TrackedStreams = State->get<StreamMap>();
166 for (auto [Sym, StreamStatus] : TrackedStreams) {
167 bool IsSymDead = SymReaper.isDead(Sym);
169 // Collect leaked symbols.
170 if (isLeaked(Sym, StreamStatus, IsSymDead, State))
171 LeakedStreams.push_back(Sym);
173 // Remove the dead symbol from the streams map.
174 if (IsSymDead)
175 State = State->remove<StreamMap>(Sym);
178 ExplodedNode *N = C.generateNonFatalErrorNode(State);
179 if (!N)
180 return;
181 reportLeaks(LeakedStreams, C, N);
184 void SimpleStreamChecker::reportDoubleClose(SymbolRef FileDescSym,
185 const CallEvent &Call,
186 CheckerContext &C) const {
187 // We reached a bug, stop exploring the path here by generating a sink.
188 ExplodedNode *ErrNode = C.generateErrorNode();
189 // If we've already reached this node on another path, return.
190 if (!ErrNode)
191 return;
193 // Generate the report.
194 auto R = std::make_unique<PathSensitiveBugReport>(
195 *DoubleCloseBugType, "Closing a previously closed file stream", ErrNode);
196 R->addRange(Call.getSourceRange());
197 R->markInteresting(FileDescSym);
198 C.emitReport(std::move(R));
201 void SimpleStreamChecker::reportLeaks(ArrayRef<SymbolRef> LeakedStreams,
202 CheckerContext &C,
203 ExplodedNode *ErrNode) const {
204 // Attach bug reports to the leak node.
205 // TODO: Identify the leaked file descriptor.
206 for (SymbolRef LeakedStream : LeakedStreams) {
207 auto R = std::make_unique<PathSensitiveBugReport>(
208 *LeakBugType, "Opened file is never closed; potential resource leak",
209 ErrNode);
210 R->markInteresting(LeakedStream);
211 C.emitReport(std::move(R));
215 bool SimpleStreamChecker::guaranteedNotToCloseFile(const CallEvent &Call) const{
216 // If it's not in a system header, assume it might close a file.
217 if (!Call.isInSystemHeader())
218 return false;
220 // Handle cases where we know a buffer's /address/ can escape.
221 if (Call.argumentsMayEscape())
222 return false;
224 // Note, even though fclose closes the file, we do not list it here
225 // since the checker is modeling the call.
227 return true;
230 // If the pointer we are tracking escaped, do not track the symbol as
231 // we cannot reason about it anymore.
232 ProgramStateRef
233 SimpleStreamChecker::checkPointerEscape(ProgramStateRef State,
234 const InvalidatedSymbols &Escaped,
235 const CallEvent *Call,
236 PointerEscapeKind Kind) const {
237 // If we know that the call cannot close a file, there is nothing to do.
238 if (Kind == PSK_DirectEscapeOnCall && guaranteedNotToCloseFile(*Call)) {
239 return State;
242 for (SymbolRef Sym : Escaped) {
243 // The symbol escaped. Optimistically, assume that the corresponding file
244 // handle will be closed somewhere else.
245 State = State->remove<StreamMap>(Sym);
247 return State;
250 void ento::registerSimpleStreamChecker(CheckerManager &mgr) {
251 mgr.registerChecker<SimpleStreamChecker>();
254 // This checker should be enabled regardless of how language options are set.
255 bool ento::shouldRegisterSimpleStreamChecker(const CheckerManager &mgr) {
256 return true;