blob: 83b15ec8b754b4d84986d1a57482a1d6d17dd9c7 [file] [log] [blame]
Anna Zaksd65e55d2012-10-29 22:51:50 +00001//===-- SimpleStreamChecker.cpp -----------------------------------------*- 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 a checker for proper use of fopen/fclose APIs.
11// - If a file has been closed with fclose, it should not be accessed again.
12// Accessing a closed file results in undefined behavior.
13// - If a file was opened with fopen, it must be closed with fclose before
14// the execution ends. Failing to do so results in a resource leak.
15//
16//===----------------------------------------------------------------------===//
17
18#include "ClangSACheckers.h"
Anna Zaksd65e55d2012-10-29 22:51:50 +000019#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/StaticAnalyzer/Core/Checker.h"
Jordan Rose0c396d62012-11-02 23:49:35 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Anna Zaksd65e55d2012-10-29 22:51:50 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23
24using namespace clang;
25using namespace ento;
26
27namespace {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000028typedef SmallVector<SymbolRef, 2> SymbolVector;
Anna Zaksd65e55d2012-10-29 22:51:50 +000029
30struct StreamState {
Anna Zaks32133cf2012-10-31 02:32:41 +000031private:
Anna Zaksd65e55d2012-10-29 22:51:50 +000032 enum Kind { Opened, Closed } K;
Anna Zaksd65e55d2012-10-29 22:51:50 +000033 StreamState(Kind InK) : K(InK) { }
34
Anna Zaks32133cf2012-10-31 02:32:41 +000035public:
Anna Zaksd65e55d2012-10-29 22:51:50 +000036 bool isOpened() const { return K == Opened; }
37 bool isClosed() const { return K == Closed; }
38
39 static StreamState getOpened() { return StreamState(Opened); }
40 static StreamState getClosed() { return StreamState(Closed); }
41
42 bool operator==(const StreamState &X) const {
43 return K == X.K;
44 }
45 void Profile(llvm::FoldingSetNodeID &ID) const {
46 ID.AddInteger(K);
47 }
48};
49
Jordan Rose0c396d62012-11-02 23:49:35 +000050class SimpleStreamChecker : public Checker<check::PostCall,
51 check::PreCall,
Anna Zaks35d4a092012-11-06 04:20:57 +000052 check::DeadSymbols,
Anna Zaks4b6bb402012-12-22 00:18:39 +000053 check::PointerEscape> {
Anna Zaksd65e55d2012-10-29 22:51:50 +000054
55 mutable IdentifierInfo *IIfopen, *IIfclose;
56
Stephen Hines651f13c2014-04-23 16:59:28 -070057 std::unique_ptr<BugType> DoubleCloseBugType;
58 std::unique_ptr<BugType> LeakBugType;
Anna Zaksd65e55d2012-10-29 22:51:50 +000059
60 void initIdentifierInfo(ASTContext &Ctx) const;
61
62 void reportDoubleClose(SymbolRef FileDescSym,
Jordan Rose0c396d62012-11-02 23:49:35 +000063 const CallEvent &Call,
Anna Zaksd65e55d2012-10-29 22:51:50 +000064 CheckerContext &C) const;
65
Jordan Rose32f38c12012-11-01 00:18:41 +000066 void reportLeaks(SymbolVector LeakedStreams,
67 CheckerContext &C,
68 ExplodedNode *ErrNode) const;
Anna Zaksd65e55d2012-10-29 22:51:50 +000069
Anna Zaks35d4a092012-11-06 04:20:57 +000070 bool guaranteedNotToCloseFile(const CallEvent &Call) const;
71
Anna Zaksd65e55d2012-10-29 22:51:50 +000072public:
Anna Zaks32133cf2012-10-31 02:32:41 +000073 SimpleStreamChecker();
Anna Zaksd65e55d2012-10-29 22:51:50 +000074
75 /// Process fopen.
Jordan Rose0c396d62012-11-02 23:49:35 +000076 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksd65e55d2012-10-29 22:51:50 +000077 /// Process fclose.
Jordan Rose0c396d62012-11-02 23:49:35 +000078 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksd65e55d2012-10-29 22:51:50 +000079
80 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks35d4a092012-11-06 04:20:57 +000081
Anna Zaks4b6bb402012-12-22 00:18:39 +000082 /// Stop tracking addresses which escape.
83 ProgramStateRef checkPointerEscape(ProgramStateRef State,
84 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +000085 const CallEvent *Call,
86 PointerEscapeKind Kind) const;
Anna Zaksd65e55d2012-10-29 22:51:50 +000087};
88
89} // end anonymous namespace
90
91/// The state of the checker is a map from tracked stream symbols to their
Anna Zaksac150f22012-10-30 04:17:18 +000092/// state. Let's store it in the ProgramState.
93REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap, SymbolRef, StreamState)
Anna Zaksd65e55d2012-10-29 22:51:50 +000094
Anna Zaks35d4a092012-11-06 04:20:57 +000095namespace {
96class StopTrackingCallback : public SymbolVisitor {
97 ProgramStateRef state;
98public:
99 StopTrackingCallback(ProgramStateRef st) : state(st) {}
100 ProgramStateRef getState() const { return state; }
101
Stephen Hines651f13c2014-04-23 16:59:28 -0700102 bool VisitSymbol(SymbolRef sym) override {
Anna Zaks35d4a092012-11-06 04:20:57 +0000103 state = state->remove<StreamMap>(sym);
104 return true;
105 }
106};
107} // end anonymous namespace
108
109
Anna Zaks32133cf2012-10-31 02:32:41 +0000110SimpleStreamChecker::SimpleStreamChecker() : IIfopen(0), IIfclose(0) {
111 // Initialize the bug types.
Stephen Hines651f13c2014-04-23 16:59:28 -0700112 DoubleCloseBugType.reset(
113 new BugType(this, "Double fclose", "Unix Stream API Error"));
Anna Zaks32133cf2012-10-31 02:32:41 +0000114
Stephen Hines651f13c2014-04-23 16:59:28 -0700115 LeakBugType.reset(
116 new BugType(this, "Resource Leak", "Unix Stream API Error"));
Anna Zaks32133cf2012-10-31 02:32:41 +0000117 // Sinks are higher importance bugs as well as calls to assert() or exit(0).
118 LeakBugType->setSuppressOnSink(true);
119}
120
Jordan Rose0c396d62012-11-02 23:49:35 +0000121void SimpleStreamChecker::checkPostCall(const CallEvent &Call,
Anna Zaksd65e55d2012-10-29 22:51:50 +0000122 CheckerContext &C) const {
123 initIdentifierInfo(C.getASTContext());
124
Jordan Rose0c396d62012-11-02 23:49:35 +0000125 if (!Call.isGlobalCFunction())
126 return;
127
128 if (Call.getCalleeIdentifier() != IIfopen)
Anna Zaksd65e55d2012-10-29 22:51:50 +0000129 return;
130
131 // Get the symbolic value corresponding to the file handle.
Jordan Rose0c396d62012-11-02 23:49:35 +0000132 SymbolRef FileDesc = Call.getReturnValue().getAsSymbol();
Anna Zaksd65e55d2012-10-29 22:51:50 +0000133 if (!FileDesc)
134 return;
135
136 // Generate the next transition (an edge in the exploded graph).
137 ProgramStateRef State = C.getState();
138 State = State->set<StreamMap>(FileDesc, StreamState::getOpened());
139 C.addTransition(State);
140}
141
Jordan Rose0c396d62012-11-02 23:49:35 +0000142void SimpleStreamChecker::checkPreCall(const CallEvent &Call,
Anna Zaksd65e55d2012-10-29 22:51:50 +0000143 CheckerContext &C) const {
144 initIdentifierInfo(C.getASTContext());
145
Jordan Rose0c396d62012-11-02 23:49:35 +0000146 if (!Call.isGlobalCFunction())
147 return;
148
149 if (Call.getCalleeIdentifier() != IIfclose)
150 return;
151
152 if (Call.getNumArgs() != 1)
Anna Zaksd65e55d2012-10-29 22:51:50 +0000153 return;
154
155 // Get the symbolic value corresponding to the file handle.
Jordan Rose0c396d62012-11-02 23:49:35 +0000156 SymbolRef FileDesc = Call.getArgSVal(0).getAsSymbol();
Anna Zaksd65e55d2012-10-29 22:51:50 +0000157 if (!FileDesc)
158 return;
159
160 // Check if the stream has already been closed.
161 ProgramStateRef State = C.getState();
162 const StreamState *SS = State->get<StreamMap>(FileDesc);
Anna Zaksbbb751a2012-10-31 22:17:48 +0000163 if (SS && SS->isClosed()) {
Anna Zaksd65e55d2012-10-29 22:51:50 +0000164 reportDoubleClose(FileDesc, Call, C);
Anna Zaksbbb751a2012-10-31 22:17:48 +0000165 return;
166 }
Anna Zaksd65e55d2012-10-29 22:51:50 +0000167
168 // Generate the next transition, in which the stream is closed.
169 State = State->set<StreamMap>(FileDesc, StreamState::getClosed());
170 C.addTransition(State);
171}
172
Anna Zaksedd07f42012-11-02 21:30:04 +0000173static bool isLeaked(SymbolRef Sym, const StreamState &SS,
174 bool IsSymDead, ProgramStateRef State) {
175 if (IsSymDead && SS.isOpened()) {
176 // If a symbol is NULL, assume that fopen failed on this path.
177 // A symbol should only be considered leaked if it is non-null.
178 ConstraintManager &CMgr = State->getConstraintManager();
179 ConditionTruthVal OpenFailed = CMgr.isNull(State, Sym);
180 return !OpenFailed.isConstrainedTrue();
181 }
182 return false;
183}
184
Anna Zaksd65e55d2012-10-29 22:51:50 +0000185void SimpleStreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
186 CheckerContext &C) const {
187 ProgramStateRef State = C.getState();
Anna Zaksd65e55d2012-10-29 22:51:50 +0000188 SymbolVector LeakedStreams;
Anna Zaksedd07f42012-11-02 21:30:04 +0000189 StreamMapTy TrackedStreams = State->get<StreamMap>();
Anna Zaks360b29c2012-10-30 04:17:40 +0000190 for (StreamMapTy::iterator I = TrackedStreams.begin(),
Jordan Roseec8d4202012-11-01 00:18:27 +0000191 E = TrackedStreams.end(); I != E; ++I) {
Anna Zaksd65e55d2012-10-29 22:51:50 +0000192 SymbolRef Sym = I->first;
Anna Zaksedd07f42012-11-02 21:30:04 +0000193 bool IsSymDead = SymReaper.isDead(Sym);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000194
Anna Zaksedd07f42012-11-02 21:30:04 +0000195 // Collect leaked symbols.
196 if (isLeaked(Sym, I->second, IsSymDead, State))
197 LeakedStreams.push_back(Sym);
198
199 // Remove the dead symbol from the streams map.
200 if (IsSymDead)
Anna Zaksd65e55d2012-10-29 22:51:50 +0000201 State = State->remove<StreamMap>(Sym);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000202 }
203
Anna Zaks32133cf2012-10-31 02:32:41 +0000204 ExplodedNode *N = C.addTransition(State);
205 reportLeaks(LeakedStreams, C, N);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000206}
207
208void SimpleStreamChecker::reportDoubleClose(SymbolRef FileDescSym,
Jordan Rose0c396d62012-11-02 23:49:35 +0000209 const CallEvent &Call,
Anna Zaksd65e55d2012-10-29 22:51:50 +0000210 CheckerContext &C) const {
211 // We reached a bug, stop exploring the path here by generating a sink.
212 ExplodedNode *ErrNode = C.generateSink();
Anna Zaks32133cf2012-10-31 02:32:41 +0000213 // If we've already reached this node on another path, return.
Anna Zaksd65e55d2012-10-29 22:51:50 +0000214 if (!ErrNode)
215 return;
216
Anna Zaksd65e55d2012-10-29 22:51:50 +0000217 // Generate the report.
218 BugReport *R = new BugReport(*DoubleCloseBugType,
219 "Closing a previously closed file stream", ErrNode);
Jordan Rose0c396d62012-11-02 23:49:35 +0000220 R->addRange(Call.getSourceRange());
Anna Zaksd65e55d2012-10-29 22:51:50 +0000221 R->markInteresting(FileDescSym);
Jordan Rose785950e2012-11-02 01:53:40 +0000222 C.emitReport(R);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000223}
224
Anna Zaks32133cf2012-10-31 02:32:41 +0000225void SimpleStreamChecker::reportLeaks(SymbolVector LeakedStreams,
226 CheckerContext &C,
227 ExplodedNode *ErrNode) const {
Anna Zaksd65e55d2012-10-29 22:51:50 +0000228 // Attach bug reports to the leak node.
Anna Zaksbdbb17b2012-10-30 04:18:21 +0000229 // TODO: Identify the leaked file descriptor.
Craig Topper09d19ef2013-07-04 03:08:24 +0000230 for (SmallVectorImpl<SymbolRef>::iterator
231 I = LeakedStreams.begin(), E = LeakedStreams.end(); I != E; ++I) {
Anna Zaksd65e55d2012-10-29 22:51:50 +0000232 BugReport *R = new BugReport(*LeakBugType,
233 "Opened file is never closed; potential resource leak", ErrNode);
Anna Zaksbdbb17b2012-10-30 04:18:21 +0000234 R->markInteresting(*I);
Jordan Rose785950e2012-11-02 01:53:40 +0000235 C.emitReport(R);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000236 }
Anna Zaksd65e55d2012-10-29 22:51:50 +0000237}
238
Anna Zaks35d4a092012-11-06 04:20:57 +0000239bool SimpleStreamChecker::guaranteedNotToCloseFile(const CallEvent &Call) const{
240 // If it's not in a system header, assume it might close a file.
241 if (!Call.isInSystemHeader())
242 return false;
243
244 // Handle cases where we know a buffer's /address/ can escape.
245 if (Call.argumentsMayEscape())
246 return false;
247
248 // Note, even though fclose closes the file, we do not list it here
249 // since the checker is modeling the call.
250
251 return true;
252}
253
Anna Zaks4b6bb402012-12-22 00:18:39 +0000254// If the pointer we are tracking escaped, do not track the symbol as
Anna Zaks35d4a092012-11-06 04:20:57 +0000255// we cannot reason about it anymore.
256ProgramStateRef
Anna Zaks4b6bb402012-12-22 00:18:39 +0000257SimpleStreamChecker::checkPointerEscape(ProgramStateRef State,
258 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +0000259 const CallEvent *Call,
260 PointerEscapeKind Kind) const {
Anna Zaks4b6bb402012-12-22 00:18:39 +0000261 // If we know that the call cannot close a file, there is nothing to do.
Jordan Rose374ae322013-05-10 17:07:16 +0000262 if (Kind == PSK_DirectEscapeOnCall && guaranteedNotToCloseFile(*Call)) {
Anna Zaks35d4a092012-11-06 04:20:57 +0000263 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +0000264 }
Anna Zaks35d4a092012-11-06 04:20:57 +0000265
Anna Zaks4b6bb402012-12-22 00:18:39 +0000266 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
267 E = Escaped.end();
268 I != E; ++I) {
269 SymbolRef Sym = *I;
Anna Zaks35d4a092012-11-06 04:20:57 +0000270
Anna Zaks35d4a092012-11-06 04:20:57 +0000271 // The symbol escaped. Optimistically, assume that the corresponding file
272 // handle will be closed somewhere else.
Anna Zaks4b6bb402012-12-22 00:18:39 +0000273 State = State->remove<StreamMap>(Sym);
Anna Zaks35d4a092012-11-06 04:20:57 +0000274 }
275 return State;
276}
277
Anna Zaksd65e55d2012-10-29 22:51:50 +0000278void SimpleStreamChecker::initIdentifierInfo(ASTContext &Ctx) const {
279 if (IIfopen)
280 return;
281 IIfopen = &Ctx.Idents.get("fopen");
282 IIfclose = &Ctx.Idents.get("fclose");
283}
284
285void ento::registerSimpleStreamChecker(CheckerManager &mgr) {
286 mgr.registerChecker<SimpleStreamChecker>();
287}