blob: 641f2ed0b94171ccb8ce54f00641277229adb22a [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"
19#include "clang/StaticAnalyzer/Core/Checker.h"
20#include "clang/StaticAnalyzer/Core/BugReporter/BugType.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,
Jordan Rose32f38c12012-11-01 00:18:41 +000052 check::DeadSymbols > {
Anna Zaksd65e55d2012-10-29 22:51:50 +000053
54 mutable IdentifierInfo *IIfopen, *IIfclose;
55
Jordan Rose32f38c12012-11-01 00:18:41 +000056 OwningPtr<BugType> DoubleCloseBugType;
57 OwningPtr<BugType> LeakBugType;
Anna Zaksd65e55d2012-10-29 22:51:50 +000058
59 void initIdentifierInfo(ASTContext &Ctx) const;
60
61 void reportDoubleClose(SymbolRef FileDescSym,
Jordan Rose0c396d62012-11-02 23:49:35 +000062 const CallEvent &Call,
Anna Zaksd65e55d2012-10-29 22:51:50 +000063 CheckerContext &C) const;
64
Jordan Rose32f38c12012-11-01 00:18:41 +000065 void reportLeaks(SymbolVector LeakedStreams,
66 CheckerContext &C,
67 ExplodedNode *ErrNode) const;
Anna Zaksd65e55d2012-10-29 22:51:50 +000068
69public:
Anna Zaks32133cf2012-10-31 02:32:41 +000070 SimpleStreamChecker();
Anna Zaksd65e55d2012-10-29 22:51:50 +000071
72 /// Process fopen.
Jordan Rose0c396d62012-11-02 23:49:35 +000073 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksd65e55d2012-10-29 22:51:50 +000074 /// Process fclose.
Jordan Rose0c396d62012-11-02 23:49:35 +000075 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksd65e55d2012-10-29 22:51:50 +000076
77 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksd65e55d2012-10-29 22:51:50 +000078};
79
80} // end anonymous namespace
81
82/// The state of the checker is a map from tracked stream symbols to their
Anna Zaksac150f22012-10-30 04:17:18 +000083/// state. Let's store it in the ProgramState.
84REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap, SymbolRef, StreamState)
Anna Zaksd65e55d2012-10-29 22:51:50 +000085
Anna Zaks32133cf2012-10-31 02:32:41 +000086SimpleStreamChecker::SimpleStreamChecker() : IIfopen(0), IIfclose(0) {
87 // Initialize the bug types.
88 DoubleCloseBugType.reset(new BugType("Double fclose",
89 "Unix Stream API Error"));
90
91 LeakBugType.reset(new BugType("Resource Leak",
92 "Unix Stream API Error"));
93 // Sinks are higher importance bugs as well as calls to assert() or exit(0).
94 LeakBugType->setSuppressOnSink(true);
95}
96
Jordan Rose0c396d62012-11-02 23:49:35 +000097void SimpleStreamChecker::checkPostCall(const CallEvent &Call,
Anna Zaksd65e55d2012-10-29 22:51:50 +000098 CheckerContext &C) const {
99 initIdentifierInfo(C.getASTContext());
100
Jordan Rose0c396d62012-11-02 23:49:35 +0000101 if (!Call.isGlobalCFunction())
102 return;
103
104 if (Call.getCalleeIdentifier() != IIfopen)
Anna Zaksd65e55d2012-10-29 22:51:50 +0000105 return;
106
107 // Get the symbolic value corresponding to the file handle.
Jordan Rose0c396d62012-11-02 23:49:35 +0000108 SymbolRef FileDesc = Call.getReturnValue().getAsSymbol();
Anna Zaksd65e55d2012-10-29 22:51:50 +0000109 if (!FileDesc)
110 return;
111
112 // Generate the next transition (an edge in the exploded graph).
113 ProgramStateRef State = C.getState();
114 State = State->set<StreamMap>(FileDesc, StreamState::getOpened());
115 C.addTransition(State);
116}
117
Jordan Rose0c396d62012-11-02 23:49:35 +0000118void SimpleStreamChecker::checkPreCall(const CallEvent &Call,
Anna Zaksd65e55d2012-10-29 22:51:50 +0000119 CheckerContext &C) const {
120 initIdentifierInfo(C.getASTContext());
121
Jordan Rose0c396d62012-11-02 23:49:35 +0000122 if (!Call.isGlobalCFunction())
123 return;
124
125 if (Call.getCalleeIdentifier() != IIfclose)
126 return;
127
128 if (Call.getNumArgs() != 1)
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.getArgSVal(0).getAsSymbol();
Anna Zaksd65e55d2012-10-29 22:51:50 +0000133 if (!FileDesc)
134 return;
135
136 // Check if the stream has already been closed.
137 ProgramStateRef State = C.getState();
138 const StreamState *SS = State->get<StreamMap>(FileDesc);
Anna Zaksbbb751a2012-10-31 22:17:48 +0000139 if (SS && SS->isClosed()) {
Anna Zaksd65e55d2012-10-29 22:51:50 +0000140 reportDoubleClose(FileDesc, Call, C);
Anna Zaksbbb751a2012-10-31 22:17:48 +0000141 return;
142 }
Anna Zaksd65e55d2012-10-29 22:51:50 +0000143
144 // Generate the next transition, in which the stream is closed.
145 State = State->set<StreamMap>(FileDesc, StreamState::getClosed());
146 C.addTransition(State);
147}
148
Anna Zaksedd07f42012-11-02 21:30:04 +0000149static 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();
157 }
158 return false;
159}
160
Anna Zaksd65e55d2012-10-29 22:51:50 +0000161void SimpleStreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
162 CheckerContext &C) const {
163 ProgramStateRef State = C.getState();
Anna Zaksd65e55d2012-10-29 22:51:50 +0000164 SymbolVector LeakedStreams;
Anna Zaksedd07f42012-11-02 21:30:04 +0000165 StreamMapTy TrackedStreams = State->get<StreamMap>();
Anna Zaks360b29c2012-10-30 04:17:40 +0000166 for (StreamMapTy::iterator I = TrackedStreams.begin(),
Jordan Roseec8d4202012-11-01 00:18:27 +0000167 E = TrackedStreams.end(); I != E; ++I) {
Anna Zaksd65e55d2012-10-29 22:51:50 +0000168 SymbolRef Sym = I->first;
Anna Zaksedd07f42012-11-02 21:30:04 +0000169 bool IsSymDead = SymReaper.isDead(Sym);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000170
Anna Zaksedd07f42012-11-02 21:30:04 +0000171 // Collect leaked symbols.
172 if (isLeaked(Sym, I->second, IsSymDead, State))
173 LeakedStreams.push_back(Sym);
174
175 // Remove the dead symbol from the streams map.
176 if (IsSymDead)
Anna Zaksd65e55d2012-10-29 22:51:50 +0000177 State = State->remove<StreamMap>(Sym);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000178 }
179
Anna Zaks32133cf2012-10-31 02:32:41 +0000180 ExplodedNode *N = C.addTransition(State);
181 reportLeaks(LeakedStreams, C, N);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000182}
183
184void SimpleStreamChecker::reportDoubleClose(SymbolRef FileDescSym,
Jordan Rose0c396d62012-11-02 23:49:35 +0000185 const CallEvent &Call,
Anna Zaksd65e55d2012-10-29 22:51:50 +0000186 CheckerContext &C) const {
187 // We reached a bug, stop exploring the path here by generating a sink.
188 ExplodedNode *ErrNode = C.generateSink();
Anna Zaks32133cf2012-10-31 02:32:41 +0000189 // If we've already reached this node on another path, return.
Anna Zaksd65e55d2012-10-29 22:51:50 +0000190 if (!ErrNode)
191 return;
192
Anna Zaksd65e55d2012-10-29 22:51:50 +0000193 // Generate the report.
194 BugReport *R = new BugReport(*DoubleCloseBugType,
195 "Closing a previously closed file stream", ErrNode);
Jordan Rose0c396d62012-11-02 23:49:35 +0000196 R->addRange(Call.getSourceRange());
Anna Zaksd65e55d2012-10-29 22:51:50 +0000197 R->markInteresting(FileDescSym);
Jordan Rose785950e2012-11-02 01:53:40 +0000198 C.emitReport(R);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000199}
200
Anna Zaks32133cf2012-10-31 02:32:41 +0000201void SimpleStreamChecker::reportLeaks(SymbolVector LeakedStreams,
202 CheckerContext &C,
203 ExplodedNode *ErrNode) const {
Anna Zaksd65e55d2012-10-29 22:51:50 +0000204 // Attach bug reports to the leak node.
Anna Zaksbdbb17b2012-10-30 04:18:21 +0000205 // TODO: Identify the leaked file descriptor.
Anna Zaksd65e55d2012-10-29 22:51:50 +0000206 for (llvm::SmallVector<SymbolRef, 2>::iterator
207 I = LeakedStreams.begin(), E = LeakedStreams.end(); I != E; ++I) {
208 BugReport *R = new BugReport(*LeakBugType,
209 "Opened file is never closed; potential resource leak", ErrNode);
Anna Zaksbdbb17b2012-10-30 04:18:21 +0000210 R->markInteresting(*I);
Jordan Rose785950e2012-11-02 01:53:40 +0000211 C.emitReport(R);
Anna Zaksd65e55d2012-10-29 22:51:50 +0000212 }
Anna Zaksd65e55d2012-10-29 22:51:50 +0000213}
214
215void SimpleStreamChecker::initIdentifierInfo(ASTContext &Ctx) const {
216 if (IIfopen)
217 return;
218 IIfopen = &Ctx.Idents.get("fopen");
219 IIfclose = &Ctx.Idents.get("fclose");
220}
221
222void ento::registerSimpleStreamChecker(CheckerManager &mgr) {
223 mgr.registerChecker<SimpleStreamChecker>();
224}