blob: ccf816c80c1e4ac6b399dc4b02624c01492320d2 [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
Stephen Hines176edba2014-12-01 14:53:08 -080066 void reportLeaks(ArrayRef<SymbolRef> LeakedStreams, CheckerContext &C,
Jordan Rose32f38c12012-11-01 00:18:41 +000067 ExplodedNode *ErrNode) const;
Anna Zaksd65e55d2012-10-29 22:51:50 +000068
Anna Zaks35d4a092012-11-06 04:20:57 +000069 bool guaranteedNotToCloseFile(const CallEvent &Call) const;
70
Anna Zaksd65e55d2012-10-29 22:51:50 +000071public:
Anna Zaks32133cf2012-10-31 02:32:41 +000072 SimpleStreamChecker();
Anna Zaksd65e55d2012-10-29 22:51:50 +000073
74 /// Process fopen.
Jordan Rose0c396d62012-11-02 23:49:35 +000075 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksd65e55d2012-10-29 22:51:50 +000076 /// Process fclose.
Jordan Rose0c396d62012-11-02 23:49:35 +000077 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksd65e55d2012-10-29 22:51:50 +000078
79 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks35d4a092012-11-06 04:20:57 +000080
Anna Zaks4b6bb402012-12-22 00:18:39 +000081 /// Stop tracking addresses which escape.
82 ProgramStateRef checkPointerEscape(ProgramStateRef State,
83 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +000084 const CallEvent *Call,
85 PointerEscapeKind Kind) 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
Stephen Hines651f13c2014-04-23 16:59:28 -0700101 bool VisitSymbol(SymbolRef sym) override {
Anna Zaks35d4a092012-11-06 04:20:57 +0000102 state = state->remove<StreamMap>(sym);
103 return true;
104 }
105};
106} // end anonymous namespace
107
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700108SimpleStreamChecker::SimpleStreamChecker()
109 : IIfopen(nullptr), IIfclose(nullptr) {
Anna Zaks32133cf2012-10-31 02:32:41 +0000110 // Initialize the bug types.
Stephen Hines651f13c2014-04-23 16:59:28 -0700111 DoubleCloseBugType.reset(
112 new BugType(this, "Double fclose", "Unix Stream API Error"));
Anna Zaks32133cf2012-10-31 02:32:41 +0000113
Stephen Hines651f13c2014-04-23 16:59:28 -0700114 LeakBugType.reset(
115 new BugType(this, "Resource Leak", "Unix Stream API Error"));
Anna Zaks32133cf2012-10-31 02:32:41 +0000116 // 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
Stephen Hines176edba2014-12-01 14:53:08 -0800224void SimpleStreamChecker::reportLeaks(ArrayRef<SymbolRef> 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.
Stephen Hines176edba2014-12-01 14:53:08 -0800229 for (SymbolRef LeakedStream : LeakedStreams) {
Anna Zaksd65e55d2012-10-29 22:51:50 +0000230 BugReport *R = new BugReport(*LeakBugType,
231 "Opened file is never closed; potential resource leak", ErrNode);
Stephen Hines176edba2014-12-01 14:53:08 -0800232 R->markInteresting(LeakedStream);
Jordan Rose785950e2012-11-02 01:53:40 +0000233 C.emitReport(R);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000234 }
Anna Zaksd65e55d2012-10-29 22:51:50 +0000235}
236
Anna Zaks35d4a092012-11-06 04:20:57 +0000237bool SimpleStreamChecker::guaranteedNotToCloseFile(const CallEvent &Call) const{
238 // If it's not in a system header, assume it might close a file.
239 if (!Call.isInSystemHeader())
240 return false;
241
242 // Handle cases where we know a buffer's /address/ can escape.
243 if (Call.argumentsMayEscape())
244 return false;
245
246 // Note, even though fclose closes the file, we do not list it here
247 // since the checker is modeling the call.
248
249 return true;
250}
251
Anna Zaks4b6bb402012-12-22 00:18:39 +0000252// If the pointer we are tracking escaped, do not track the symbol as
Anna Zaks35d4a092012-11-06 04:20:57 +0000253// we cannot reason about it anymore.
254ProgramStateRef
Anna Zaks4b6bb402012-12-22 00:18:39 +0000255SimpleStreamChecker::checkPointerEscape(ProgramStateRef State,
256 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +0000257 const CallEvent *Call,
258 PointerEscapeKind Kind) const {
Anna Zaks4b6bb402012-12-22 00:18:39 +0000259 // If we know that the call cannot close a file, there is nothing to do.
Jordan Rose374ae322013-05-10 17:07:16 +0000260 if (Kind == PSK_DirectEscapeOnCall && guaranteedNotToCloseFile(*Call)) {
Anna Zaks35d4a092012-11-06 04:20:57 +0000261 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +0000262 }
Anna Zaks35d4a092012-11-06 04:20:57 +0000263
Anna Zaks4b6bb402012-12-22 00:18:39 +0000264 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
265 E = Escaped.end();
266 I != E; ++I) {
267 SymbolRef Sym = *I;
Anna Zaks35d4a092012-11-06 04:20:57 +0000268
Anna Zaks35d4a092012-11-06 04:20:57 +0000269 // The symbol escaped. Optimistically, assume that the corresponding file
270 // handle will be closed somewhere else.
Anna Zaks4b6bb402012-12-22 00:18:39 +0000271 State = State->remove<StreamMap>(Sym);
Anna Zaks35d4a092012-11-06 04:20:57 +0000272 }
273 return State;
274}
275
Anna Zaksd65e55d2012-10-29 22:51:50 +0000276void SimpleStreamChecker::initIdentifierInfo(ASTContext &Ctx) const {
277 if (IIfopen)
278 return;
279 IIfopen = &Ctx.Idents.get("fopen");
280 IIfclose = &Ctx.Idents.get("fclose");
281}
282
283void ento::registerSimpleStreamChecker(CheckerManager &mgr) {
284 mgr.registerChecker<SimpleStreamChecker>();
285}