1 //===-- 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/BugReporter/BugType.h"
20 #include "clang/StaticAnalyzer/Core/Checker.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23
24 using namespace clang;
25 using namespace ento;
26
27 namespace {
28 typedef SmallVector<SymbolRef, 2> SymbolVector;
29
30 struct StreamState {
31 private:
32 enum Kind { Opened, Closed } K;
StreamState__anon49d2d0bf0111::StreamState33 StreamState(Kind InK) : K(InK) { }
34
35 public:
isOpened__anon49d2d0bf0111::StreamState36 bool isOpened() const { return K == Opened; }
isClosed__anon49d2d0bf0111::StreamState37 bool isClosed() const { return K == Closed; }
38
getOpened__anon49d2d0bf0111::StreamState39 static StreamState getOpened() { return StreamState(Opened); }
getClosed__anon49d2d0bf0111::StreamState40 static StreamState getClosed() { return StreamState(Closed); }
41
operator ==__anon49d2d0bf0111::StreamState42 bool operator==(const StreamState &X) const {
43 return K == X.K;
44 }
Profile__anon49d2d0bf0111::StreamState45 void Profile(llvm::FoldingSetNodeID &ID) const {
46 ID.AddInteger(K);
47 }
48 };
49
50 class SimpleStreamChecker : public Checker<check::PostCall,
51 check::PreCall,
52 check::DeadSymbols,
53 check::PointerEscape> {
54
55 mutable IdentifierInfo *IIfopen, *IIfclose;
56
57 std::unique_ptr<BugType> DoubleCloseBugType;
58 std::unique_ptr<BugType> LeakBugType;
59
60 void initIdentifierInfo(ASTContext &Ctx) const;
61
62 void reportDoubleClose(SymbolRef FileDescSym,
63 const CallEvent &Call,
64 CheckerContext &C) const;
65
66 void reportLeaks(SymbolVector LeakedStreams,
67 CheckerContext &C,
68 ExplodedNode *ErrNode) const;
69
70 bool guaranteedNotToCloseFile(const CallEvent &Call) const;
71
72 public:
73 SimpleStreamChecker();
74
75 /// Process fopen.
76 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
77 /// Process fclose.
78 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
79
80 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
81
82 /// Stop tracking addresses which escape.
83 ProgramStateRef checkPointerEscape(ProgramStateRef State,
84 const InvalidatedSymbols &Escaped,
85 const CallEvent *Call,
86 PointerEscapeKind Kind) const;
87 };
88
89 } // end anonymous namespace
90
91 /// The state of the checker is a map from tracked stream symbols to their
92 /// state. Let's store it in the ProgramState.
93 REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap, SymbolRef, StreamState)
94
95 namespace {
96 class StopTrackingCallback : public SymbolVisitor {
97 ProgramStateRef state;
98 public:
StopTrackingCallback(ProgramStateRef st)99 StopTrackingCallback(ProgramStateRef st) : state(st) {}
getState() const100 ProgramStateRef getState() const { return state; }
101
VisitSymbol(SymbolRef sym)102 bool VisitSymbol(SymbolRef sym) override {
103 state = state->remove<StreamMap>(sym);
104 return true;
105 }
106 };
107 } // end anonymous namespace
108
SimpleStreamChecker()109 SimpleStreamChecker::SimpleStreamChecker()
110 : IIfopen(nullptr), IIfclose(nullptr) {
111 // Initialize the bug types.
112 DoubleCloseBugType.reset(
113 new BugType(this, "Double fclose", "Unix Stream API Error"));
114
115 LeakBugType.reset(
116 new BugType(this, "Resource Leak", "Unix Stream API Error"));
117 // Sinks are higher importance bugs as well as calls to assert() or exit(0).
118 LeakBugType->setSuppressOnSink(true);
119 }
120
checkPostCall(const CallEvent & Call,CheckerContext & C) const121 void SimpleStreamChecker::checkPostCall(const CallEvent &Call,
122 CheckerContext &C) const {
123 initIdentifierInfo(C.getASTContext());
124
125 if (!Call.isGlobalCFunction())
126 return;
127
128 if (Call.getCalleeIdentifier() != IIfopen)
129 return;
130
131 // Get the symbolic value corresponding to the file handle.
132 SymbolRef FileDesc = Call.getReturnValue().getAsSymbol();
133 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
checkPreCall(const CallEvent & Call,CheckerContext & C) const142 void SimpleStreamChecker::checkPreCall(const CallEvent &Call,
143 CheckerContext &C) const {
144 initIdentifierInfo(C.getASTContext());
145
146 if (!Call.isGlobalCFunction())
147 return;
148
149 if (Call.getCalleeIdentifier() != IIfclose)
150 return;
151
152 if (Call.getNumArgs() != 1)
153 return;
154
155 // Get the symbolic value corresponding to the file handle.
156 SymbolRef FileDesc = Call.getArgSVal(0).getAsSymbol();
157 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);
163 if (SS && SS->isClosed()) {
164 reportDoubleClose(FileDesc, Call, C);
165 return;
166 }
167
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
isLeaked(SymbolRef Sym,const StreamState & SS,bool IsSymDead,ProgramStateRef State)173 static 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
checkDeadSymbols(SymbolReaper & SymReaper,CheckerContext & C) const185 void SimpleStreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
186 CheckerContext &C) const {
187 ProgramStateRef State = C.getState();
188 SymbolVector LeakedStreams;
189 StreamMapTy TrackedStreams = State->get<StreamMap>();
190 for (StreamMapTy::iterator I = TrackedStreams.begin(),
191 E = TrackedStreams.end(); I != E; ++I) {
192 SymbolRef Sym = I->first;
193 bool IsSymDead = SymReaper.isDead(Sym);
194
195 // 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)
201 State = State->remove<StreamMap>(Sym);
202 }
203
204 ExplodedNode *N = C.addTransition(State);
205 reportLeaks(LeakedStreams, C, N);
206 }
207
reportDoubleClose(SymbolRef FileDescSym,const CallEvent & Call,CheckerContext & C) const208 void SimpleStreamChecker::reportDoubleClose(SymbolRef FileDescSym,
209 const CallEvent &Call,
210 CheckerContext &C) const {
211 // We reached a bug, stop exploring the path here by generating a sink.
212 ExplodedNode *ErrNode = C.generateSink();
213 // If we've already reached this node on another path, return.
214 if (!ErrNode)
215 return;
216
217 // Generate the report.
218 BugReport *R = new BugReport(*DoubleCloseBugType,
219 "Closing a previously closed file stream", ErrNode);
220 R->addRange(Call.getSourceRange());
221 R->markInteresting(FileDescSym);
222 C.emitReport(R);
223 }
224
reportLeaks(SymbolVector LeakedStreams,CheckerContext & C,ExplodedNode * ErrNode) const225 void SimpleStreamChecker::reportLeaks(SymbolVector LeakedStreams,
226 CheckerContext &C,
227 ExplodedNode *ErrNode) const {
228 // Attach bug reports to the leak node.
229 // TODO: Identify the leaked file descriptor.
230 for (SmallVectorImpl<SymbolRef>::iterator
231 I = LeakedStreams.begin(), E = LeakedStreams.end(); I != E; ++I) {
232 BugReport *R = new BugReport(*LeakBugType,
233 "Opened file is never closed; potential resource leak", ErrNode);
234 R->markInteresting(*I);
235 C.emitReport(R);
236 }
237 }
238
guaranteedNotToCloseFile(const CallEvent & Call) const239 bool 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
254 // If the pointer we are tracking escaped, do not track the symbol as
255 // we cannot reason about it anymore.
256 ProgramStateRef
checkPointerEscape(ProgramStateRef State,const InvalidatedSymbols & Escaped,const CallEvent * Call,PointerEscapeKind Kind) const257 SimpleStreamChecker::checkPointerEscape(ProgramStateRef State,
258 const InvalidatedSymbols &Escaped,
259 const CallEvent *Call,
260 PointerEscapeKind Kind) const {
261 // If we know that the call cannot close a file, there is nothing to do.
262 if (Kind == PSK_DirectEscapeOnCall && guaranteedNotToCloseFile(*Call)) {
263 return State;
264 }
265
266 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
267 E = Escaped.end();
268 I != E; ++I) {
269 SymbolRef Sym = *I;
270
271 // The symbol escaped. Optimistically, assume that the corresponding file
272 // handle will be closed somewhere else.
273 State = State->remove<StreamMap>(Sym);
274 }
275 return State;
276 }
277
initIdentifierInfo(ASTContext & Ctx) const278 void SimpleStreamChecker::initIdentifierInfo(ASTContext &Ctx) const {
279 if (IIfopen)
280 return;
281 IIfopen = &Ctx.Idents.get("fopen");
282 IIfclose = &Ctx.Idents.get("fclose");
283 }
284
registerSimpleStreamChecker(CheckerManager & mgr)285 void ento::registerSimpleStreamChecker(CheckerManager &mgr) {
286 mgr.registerChecker<SimpleStreamChecker>();
287 }
288