blob: fd5a2ff705d4cbf6356e78fe726820c4ddb24069 [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 {
28typedef llvm::SmallVector<SymbolRef, 2> SymbolVector;
29
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
Jordan Rose32f38c12012-11-01 00:18:41 +000057 OwningPtr<BugType> DoubleCloseBugType;
58 OwningPtr<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,
85 const CallEvent *Call) const;
Anna Zaksd65e55d2012-10-29 22:51:50 +000086};
87
88} // end anonymous namespace
89
90/// The state of the checker is a map from tracked stream symbols to their
Anna Zaksac150f22012-10-30 04:17:18 +000091/// state. Let's store it in the ProgramState.
92REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap, SymbolRef, StreamState)
Anna Zaksd65e55d2012-10-29 22:51:50 +000093
Anna Zaks35d4a092012-11-06 04:20:57 +000094namespace {
95class StopTrackingCallback : public SymbolVisitor {
96 ProgramStateRef state;
97public:
98 StopTrackingCallback(ProgramStateRef st) : state(st) {}
99 ProgramStateRef getState() const { return state; }
100
101 bool VisitSymbol(SymbolRef sym) {
102 state = state->remove<StreamMap>(sym);
103 return true;
104 }
105};
106} // end anonymous namespace
107
108
Anna Zaks32133cf2012-10-31 02:32:41 +0000109SimpleStreamChecker::SimpleStreamChecker() : IIfopen(0), IIfclose(0) {
110 // Initialize the bug types.
111 DoubleCloseBugType.reset(new BugType("Double fclose",
112 "Unix Stream API Error"));
113
114 LeakBugType.reset(new BugType("Resource Leak",
115 "Unix Stream API Error"));
116 // Sinks are higher importance bugs as well as calls to assert() or exit(0).
117 LeakBugType->setSuppressOnSink(true);
118}
119
Jordan Rose0c396d62012-11-02 23:49:35 +0000120void SimpleStreamChecker::checkPostCall(const CallEvent &Call,
Anna Zaksd65e55d2012-10-29 22:51:50 +0000121 CheckerContext &C) const {
122 initIdentifierInfo(C.getASTContext());
123
Jordan Rose0c396d62012-11-02 23:49:35 +0000124 if (!Call.isGlobalCFunction())
125 return;
126
127 if (Call.getCalleeIdentifier() != IIfopen)
Anna Zaksd65e55d2012-10-29 22:51:50 +0000128 return;
129
130 // Get the symbolic value corresponding to the file handle.
Jordan Rose0c396d62012-11-02 23:49:35 +0000131 SymbolRef FileDesc = Call.getReturnValue().getAsSymbol();
Anna Zaksd65e55d2012-10-29 22:51:50 +0000132 if (!FileDesc)
133 return;
134
135 // Generate the next transition (an edge in the exploded graph).
136 ProgramStateRef State = C.getState();
137 State = State->set<StreamMap>(FileDesc, StreamState::getOpened());
138 C.addTransition(State);
139}
140
Jordan Rose0c396d62012-11-02 23:49:35 +0000141void SimpleStreamChecker::checkPreCall(const CallEvent &Call,
Anna Zaksd65e55d2012-10-29 22:51:50 +0000142 CheckerContext &C) const {
143 initIdentifierInfo(C.getASTContext());
144
Jordan Rose0c396d62012-11-02 23:49:35 +0000145 if (!Call.isGlobalCFunction())
146 return;
147
148 if (Call.getCalleeIdentifier() != IIfclose)
149 return;
150
151 if (Call.getNumArgs() != 1)
Anna Zaksd65e55d2012-10-29 22:51:50 +0000152 return;
153
154 // Get the symbolic value corresponding to the file handle.
Jordan Rose0c396d62012-11-02 23:49:35 +0000155 SymbolRef FileDesc = Call.getArgSVal(0).getAsSymbol();
Anna Zaksd65e55d2012-10-29 22:51:50 +0000156 if (!FileDesc)
157 return;
158
159 // Check if the stream has already been closed.
160 ProgramStateRef State = C.getState();
161 const StreamState *SS = State->get<StreamMap>(FileDesc);
Anna Zaksbbb751a2012-10-31 22:17:48 +0000162 if (SS && SS->isClosed()) {
Anna Zaksd65e55d2012-10-29 22:51:50 +0000163 reportDoubleClose(FileDesc, Call, C);
Anna Zaksbbb751a2012-10-31 22:17:48 +0000164 return;
165 }
Anna Zaksd65e55d2012-10-29 22:51:50 +0000166
167 // Generate the next transition, in which the stream is closed.
168 State = State->set<StreamMap>(FileDesc, StreamState::getClosed());
169 C.addTransition(State);
170}
171
Anna Zaksedd07f42012-11-02 21:30:04 +0000172static bool isLeaked(SymbolRef Sym, const StreamState &SS,
173 bool IsSymDead, ProgramStateRef State) {
174 if (IsSymDead && SS.isOpened()) {
175 // If a symbol is NULL, assume that fopen failed on this path.
176 // A symbol should only be considered leaked if it is non-null.
177 ConstraintManager &CMgr = State->getConstraintManager();
178 ConditionTruthVal OpenFailed = CMgr.isNull(State, Sym);
179 return !OpenFailed.isConstrainedTrue();
180 }
181 return false;
182}
183
Anna Zaksd65e55d2012-10-29 22:51:50 +0000184void SimpleStreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
185 CheckerContext &C) const {
186 ProgramStateRef State = C.getState();
Anna Zaksd65e55d2012-10-29 22:51:50 +0000187 SymbolVector LeakedStreams;
Anna Zaksedd07f42012-11-02 21:30:04 +0000188 StreamMapTy TrackedStreams = State->get<StreamMap>();
Anna Zaks360b29c2012-10-30 04:17:40 +0000189 for (StreamMapTy::iterator I = TrackedStreams.begin(),
Jordan Roseec8d4202012-11-01 00:18:27 +0000190 E = TrackedStreams.end(); I != E; ++I) {
Anna Zaksd65e55d2012-10-29 22:51:50 +0000191 SymbolRef Sym = I->first;
Anna Zaksedd07f42012-11-02 21:30:04 +0000192 bool IsSymDead = SymReaper.isDead(Sym);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000193
Anna Zaksedd07f42012-11-02 21:30:04 +0000194 // Collect leaked symbols.
195 if (isLeaked(Sym, I->second, IsSymDead, State))
196 LeakedStreams.push_back(Sym);
197
198 // Remove the dead symbol from the streams map.
199 if (IsSymDead)
Anna Zaksd65e55d2012-10-29 22:51:50 +0000200 State = State->remove<StreamMap>(Sym);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000201 }
202
Anna Zaks32133cf2012-10-31 02:32:41 +0000203 ExplodedNode *N = C.addTransition(State);
204 reportLeaks(LeakedStreams, C, N);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000205}
206
207void SimpleStreamChecker::reportDoubleClose(SymbolRef FileDescSym,
Jordan Rose0c396d62012-11-02 23:49:35 +0000208 const CallEvent &Call,
Anna Zaksd65e55d2012-10-29 22:51:50 +0000209 CheckerContext &C) const {
210 // We reached a bug, stop exploring the path here by generating a sink.
211 ExplodedNode *ErrNode = C.generateSink();
Anna Zaks32133cf2012-10-31 02:32:41 +0000212 // If we've already reached this node on another path, return.
Anna Zaksd65e55d2012-10-29 22:51:50 +0000213 if (!ErrNode)
214 return;
215
Anna Zaksd65e55d2012-10-29 22:51:50 +0000216 // Generate the report.
217 BugReport *R = new BugReport(*DoubleCloseBugType,
218 "Closing a previously closed file stream", ErrNode);
Jordan Rose0c396d62012-11-02 23:49:35 +0000219 R->addRange(Call.getSourceRange());
Anna Zaksd65e55d2012-10-29 22:51:50 +0000220 R->markInteresting(FileDescSym);
Jordan Rose785950e2012-11-02 01:53:40 +0000221 C.emitReport(R);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000222}
223
Anna Zaks32133cf2012-10-31 02:32:41 +0000224void SimpleStreamChecker::reportLeaks(SymbolVector LeakedStreams,
225 CheckerContext &C,
226 ExplodedNode *ErrNode) const {
Anna Zaksd65e55d2012-10-29 22:51:50 +0000227 // Attach bug reports to the leak node.
Anna Zaksbdbb17b2012-10-30 04:18:21 +0000228 // TODO: Identify the leaked file descriptor.
Anna Zaksd65e55d2012-10-29 22:51:50 +0000229 for (llvm::SmallVector<SymbolRef, 2>::iterator
230 I = LeakedStreams.begin(), E = LeakedStreams.end(); I != E; ++I) {
231 BugReport *R = new BugReport(*LeakBugType,
232 "Opened file is never closed; potential resource leak", ErrNode);
Anna Zaksbdbb17b2012-10-30 04:18:21 +0000233 R->markInteresting(*I);
Jordan Rose785950e2012-11-02 01:53:40 +0000234 C.emitReport(R);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000235 }
Anna Zaksd65e55d2012-10-29 22:51:50 +0000236}
237
Anna Zaks35d4a092012-11-06 04:20:57 +0000238bool SimpleStreamChecker::guaranteedNotToCloseFile(const CallEvent &Call) const{
239 // If it's not in a system header, assume it might close a file.
240 if (!Call.isInSystemHeader())
241 return false;
242
243 // Handle cases where we know a buffer's /address/ can escape.
244 if (Call.argumentsMayEscape())
245 return false;
246
247 // Note, even though fclose closes the file, we do not list it here
248 // since the checker is modeling the call.
249
250 return true;
251}
252
Anna Zaks4b6bb402012-12-22 00:18:39 +0000253// If the pointer we are tracking escaped, do not track the symbol as
Anna Zaks35d4a092012-11-06 04:20:57 +0000254// we cannot reason about it anymore.
255ProgramStateRef
Anna Zaks4b6bb402012-12-22 00:18:39 +0000256SimpleStreamChecker::checkPointerEscape(ProgramStateRef State,
257 const InvalidatedSymbols &Escaped,
258 const CallEvent *Call) const {
259 // If we know that the call cannot close a file, there is nothing to do.
260 if (Call && guaranteedNotToCloseFile(*Call))
Anna Zaks35d4a092012-11-06 04:20:57 +0000261 return State;
262
Anna Zaks4b6bb402012-12-22 00:18:39 +0000263 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
264 E = Escaped.end();
265 I != E; ++I) {
266 SymbolRef Sym = *I;
Anna Zaks35d4a092012-11-06 04:20:57 +0000267
Anna Zaks35d4a092012-11-06 04:20:57 +0000268 // The symbol escaped. Optimistically, assume that the corresponding file
269 // handle will be closed somewhere else.
Anna Zaks4b6bb402012-12-22 00:18:39 +0000270 State = State->remove<StreamMap>(Sym);
Anna Zaks35d4a092012-11-06 04:20:57 +0000271 }
272 return State;
273}
274
Anna Zaksd65e55d2012-10-29 22:51:50 +0000275void SimpleStreamChecker::initIdentifierInfo(ASTContext &Ctx) const {
276 if (IIfopen)
277 return;
278 IIfopen = &Ctx.Idents.get("fopen");
279 IIfclose = &Ctx.Idents.get("fclose");
280}
281
282void ento::registerSimpleStreamChecker(CheckerManager &mgr) {
283 mgr.registerChecker<SimpleStreamChecker>();
284}