1 //===-- SimpleStreamChecker.cpp -----------------------------------------*- 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 // 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/CallEvent.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
24 using namespace clang;
28 typedef SmallVector<SymbolRef, 2> SymbolVector;
32 enum Kind { Opened, Closed } K;
33 StreamState(Kind InK) : K(InK) { }
36 bool isOpened() const { return K == Opened; }
37 bool isClosed() const { return K == Closed; }
39 static StreamState getOpened() { return StreamState(Opened); }
40 static StreamState getClosed() { return StreamState(Closed); }
42 bool operator==(const StreamState &X) const {
45 void Profile(llvm::FoldingSetNodeID &ID) const {
50 class SimpleStreamChecker : public Checker<check::PostCall,
53 check::PointerEscape> {
54 CallDescription OpenFn, CloseFn;
56 std::unique_ptr<BugType> DoubleCloseBugType;
57 std::unique_ptr<BugType> LeakBugType;
59 void reportDoubleClose(SymbolRef FileDescSym,
60 const CallEvent &Call,
61 CheckerContext &C) const;
63 void reportLeaks(ArrayRef<SymbolRef> LeakedStreams, CheckerContext &C,
64 ExplodedNode *ErrNode) const;
66 bool guaranteedNotToCloseFile(const CallEvent &Call) const;
69 SimpleStreamChecker();
72 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
74 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
76 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
78 /// Stop tracking addresses which escape.
79 ProgramStateRef checkPointerEscape(ProgramStateRef State,
80 const InvalidatedSymbols &Escaped,
81 const CallEvent *Call,
82 PointerEscapeKind Kind) const;
85 } // end anonymous namespace
87 /// The state of the checker is a map from tracked stream symbols to their
88 /// state. Let's store it in the ProgramState.
89 REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap, SymbolRef, StreamState)
92 class StopTrackingCallback final : public SymbolVisitor {
93 ProgramStateRef state;
95 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
96 ProgramStateRef getState() const { return state; }
98 bool VisitSymbol(SymbolRef sym) override {
99 state = state->remove<StreamMap>(sym);
103 } // end anonymous namespace
105 SimpleStreamChecker::SimpleStreamChecker()
106 : OpenFn("fopen"), CloseFn("fclose", 1) {
107 // Initialize the bug types.
108 DoubleCloseBugType.reset(
109 new BugType(this, "Double fclose", "Unix Stream API Error"));
111 // Sinks are higher importance bugs as well as calls to assert() or exit(0).
113 new BugType(this, "Resource Leak", "Unix Stream API Error",
114 /*SuppressOnSink=*/true));
117 void SimpleStreamChecker::checkPostCall(const CallEvent &Call,
118 CheckerContext &C) const {
119 if (!Call.isGlobalCFunction())
122 if (!Call.isCalled(OpenFn))
125 // Get the symbolic value corresponding to the file handle.
126 SymbolRef FileDesc = Call.getReturnValue().getAsSymbol();
130 // Generate the next transition (an edge in the exploded graph).
131 ProgramStateRef State = C.getState();
132 State = State->set<StreamMap>(FileDesc, StreamState::getOpened());
133 C.addTransition(State);
136 void SimpleStreamChecker::checkPreCall(const CallEvent &Call,
137 CheckerContext &C) const {
138 if (!Call.isGlobalCFunction())
141 if (!Call.isCalled(CloseFn))
144 // Get the symbolic value corresponding to the file handle.
145 SymbolRef FileDesc = Call.getArgSVal(0).getAsSymbol();
149 // Check if the stream has already been closed.
150 ProgramStateRef State = C.getState();
151 const StreamState *SS = State->get<StreamMap>(FileDesc);
152 if (SS && SS->isClosed()) {
153 reportDoubleClose(FileDesc, Call, C);
157 // Generate the next transition, in which the stream is closed.
158 State = State->set<StreamMap>(FileDesc, StreamState::getClosed());
159 C.addTransition(State);
162 static bool isLeaked(SymbolRef Sym, const StreamState &SS,
163 bool IsSymDead, ProgramStateRef State) {
164 if (IsSymDead && SS.isOpened()) {
165 // If a symbol is NULL, assume that fopen failed on this path.
166 // A symbol should only be considered leaked if it is non-null.
167 ConstraintManager &CMgr = State->getConstraintManager();
168 ConditionTruthVal OpenFailed = CMgr.isNull(State, Sym);
169 return !OpenFailed.isConstrainedTrue();
174 void SimpleStreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
175 CheckerContext &C) const {
176 ProgramStateRef State = C.getState();
177 SymbolVector LeakedStreams;
178 StreamMapTy TrackedStreams = State->get<StreamMap>();
179 for (StreamMapTy::iterator I = TrackedStreams.begin(),
180 E = TrackedStreams.end(); I != E; ++I) {
181 SymbolRef Sym = I->first;
182 bool IsSymDead = SymReaper.isDead(Sym);
184 // Collect leaked symbols.
185 if (isLeaked(Sym, I->second, IsSymDead, State))
186 LeakedStreams.push_back(Sym);
188 // Remove the dead symbol from the streams map.
190 State = State->remove<StreamMap>(Sym);
193 ExplodedNode *N = C.generateNonFatalErrorNode(State);
196 reportLeaks(LeakedStreams, C, N);
199 void SimpleStreamChecker::reportDoubleClose(SymbolRef FileDescSym,
200 const CallEvent &Call,
201 CheckerContext &C) const {
202 // We reached a bug, stop exploring the path here by generating a sink.
203 ExplodedNode *ErrNode = C.generateErrorNode();
204 // If we've already reached this node on another path, return.
208 // Generate the report.
209 auto R = llvm::make_unique<BugReport>(*DoubleCloseBugType,
210 "Closing a previously closed file stream", ErrNode);
211 R->addRange(Call.getSourceRange());
212 R->markInteresting(FileDescSym);
213 C.emitReport(std::move(R));
216 void SimpleStreamChecker::reportLeaks(ArrayRef<SymbolRef> LeakedStreams,
218 ExplodedNode *ErrNode) const {
219 // Attach bug reports to the leak node.
220 // TODO: Identify the leaked file descriptor.
221 for (SymbolRef LeakedStream : LeakedStreams) {
222 auto R = llvm::make_unique<BugReport>(*LeakBugType,
223 "Opened file is never closed; potential resource leak", ErrNode);
224 R->markInteresting(LeakedStream);
225 C.emitReport(std::move(R));
229 bool SimpleStreamChecker::guaranteedNotToCloseFile(const CallEvent &Call) const{
230 // If it's not in a system header, assume it might close a file.
231 if (!Call.isInSystemHeader())
234 // Handle cases where we know a buffer's /address/ can escape.
235 if (Call.argumentsMayEscape())
238 // Note, even though fclose closes the file, we do not list it here
239 // since the checker is modeling the call.
244 // If the pointer we are tracking escaped, do not track the symbol as
245 // we cannot reason about it anymore.
247 SimpleStreamChecker::checkPointerEscape(ProgramStateRef State,
248 const InvalidatedSymbols &Escaped,
249 const CallEvent *Call,
250 PointerEscapeKind Kind) const {
251 // If we know that the call cannot close a file, there is nothing to do.
252 if (Kind == PSK_DirectEscapeOnCall && guaranteedNotToCloseFile(*Call)) {
256 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
261 // The symbol escaped. Optimistically, assume that the corresponding file
262 // handle will be closed somewhere else.
263 State = State->remove<StreamMap>(Sym);
268 void ento::registerSimpleStreamChecker(CheckerManager &mgr) {
269 mgr.registerChecker<SimpleStreamChecker>();
272 // This checker should be enabled regardless of how language options are set.
273 bool ento::shouldRegisterSimpleStreamChecker(const LangOptions &LO) {