Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- SimpleStreamChecker.cpp -----------------------------------------*- C++ -*--//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// Defines a checker for proper use of fopen/fclose APIs.
10
//   - If a file has been closed with fclose, it should not be accessed again.
11
//   Accessing a closed file results in undefined behavior.
12
//   - If a file was opened with fopen, it must be closed with fclose before
13
//   the execution ends. Failing to do so results in a resource leak.
14
//
15
//===----------------------------------------------------------------------===//
16
17
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
18
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
19
#include "clang/StaticAnalyzer/Core/Checker.h"
20
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
21
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22
#include <utility>
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;
33
17
  StreamState(Kind InK) : K(InK) { }
34
35
public:
36
14
  bool isOpened() const { return K == Opened; }
37
5
  bool isClosed() const { return K == Closed; }
38
39
13
  static StreamState getOpened() { return StreamState(Opened); }
40
4
  static StreamState getClosed() { return StreamState(Closed); }
41
42
16
  bool operator==(const StreamState &X) const {
43
16
    return K == X.K;
44
16
  }
45
32
  void Profile(llvm::FoldingSetNodeID &ID) const {
46
32
    ID.AddInteger(K);
47
32
  }
48
};
49
50
class SimpleStreamChecker : public Checker<check::PostCall,
51
                                           check::PreCall,
52
                                           check::DeadSymbols,
53
                                           check::PointerEscape> {
54
  CallDescription OpenFn, CloseFn;
55
56
  std::unique_ptr<BugType> DoubleCloseBugType;
57
  std::unique_ptr<BugType> LeakBugType;
58
59
  void reportDoubleClose(SymbolRef FileDescSym,
60
                         const CallEvent &Call,
61
                         CheckerContext &C) const;
62
63
  void reportLeaks(ArrayRef<SymbolRef> LeakedStreams, CheckerContext &C,
64
                   ExplodedNode *ErrNode) const;
65
66
  bool guaranteedNotToCloseFile(const CallEvent &Call) const;
67
68
public:
69
  SimpleStreamChecker();
70
71
  /// Process fopen.
72
  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
73
  /// Process fclose.
74
  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
75
76
  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
77
78
  /// Stop tracking addresses which escape.
79
  ProgramStateRef checkPointerEscape(ProgramStateRef State,
80
                                    const InvalidatedSymbols &Escaped,
81
                                    const CallEvent *Call,
82
                                    PointerEscapeKind Kind) const;
83
};
84
85
} // end anonymous namespace
86
87
/// The state of the checker is a map from tracked stream symbols to their
88
/// state. Let's store it in the ProgramState.
89
REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap, SymbolRef, StreamState)
90
91
namespace {
92
class StopTrackingCallback final : public SymbolVisitor {
93
  ProgramStateRef state;
94
public:
95
0
  StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
96
0
  ProgramStateRef getState() const { return state; }
97
98
0
  bool VisitSymbol(SymbolRef sym) override {
99
0
    state = state->remove<StreamMap>(sym);
100
0
    return true;
101
0
  }
102
};
103
} // end anonymous namespace
104
105
SimpleStreamChecker::SimpleStreamChecker()
106
5
    : OpenFn("fopen"), CloseFn("fclose", 1) {
107
5
  // Initialize the bug types.
108
5
  DoubleCloseBugType.reset(
109
5
      new BugType(this, "Double fclose", "Unix Stream API Error"));
110
5
111
5
  // Sinks are higher importance bugs as well as calls to assert() or exit(0).
112
5
  LeakBugType.reset(
113
5
      new BugType(this, "Resource Leak", "Unix Stream API Error",
114
5
                  /*SuppressOnSink=*/true));
115
5
}
116
117
void SimpleStreamChecker::checkPostCall(const CallEvent &Call,
118
51
                                        CheckerContext &C) const {
119
51
  if (!Call.isGlobalCFunction())
120
8
    return;
121
43
122
43
  if (!Call.isCalled(OpenFn))
123
30
    return;
124
13
125
13
  // Get the symbolic value corresponding to the file handle.
126
13
  SymbolRef FileDesc = Call.getReturnValue().getAsSymbol();
127
13
  if (!FileDesc)
128
0
    return;
129
13
130
13
  // Generate the next transition (an edge in the exploded graph).
131
13
  ProgramStateRef State = C.getState();
132
13
  State = State->set<StreamMap>(FileDesc, StreamState::getOpened());
133
13
  C.addTransition(State);
134
13
}
135
136
void SimpleStreamChecker::checkPreCall(const CallEvent &Call,
137
55
                                       CheckerContext &C) const {
138
55
  if (!Call.isGlobalCFunction())
139
8
    return;
140
47
141
47
  if (!Call.isCalled(CloseFn))
142
42
    return;
143
5
144
5
  // Get the symbolic value corresponding to the file handle.
145
5
  SymbolRef FileDesc = Call.getArgSVal(0).getAsSymbol();
146
5
  if (!FileDesc)
147
0
    return;
148
5
149
5
  // Check if the stream has already been closed.
150
5
  ProgramStateRef State = C.getState();
151
5
  const StreamState *SS = State->get<StreamMap>(FileDesc);
152
5
  if (SS && SS->isClosed()) {
153
1
    reportDoubleClose(FileDesc, Call, C);
154
1
    return;
155
1
  }
156
4
157
4
  // Generate the next transition, in which the stream is closed.
158
4
  State = State->set<StreamMap>(FileDesc, StreamState::getClosed());
159
4
  C.addTransition(State);
160
4
}
161
162
static bool isLeaked(SymbolRef Sym, const StreamState &SS,
163
53
                     bool IsSymDead, ProgramStateRef State) {
164
53
  if (IsSymDead && 
SS.isOpened()14
) {
165
11
    // If a symbol is NULL, assume that fopen failed on this path.
166
11
    // A symbol should only be considered leaked if it is non-null.
167
11
    ConstraintManager &CMgr = State->getConstraintManager();
168
11
    ConditionTruthVal OpenFailed = CMgr.isNull(State, Sym);
169
11
    return !OpenFailed.isConstrainedTrue();
170
11
  }
171
42
  return false;
172
42
}
173
174
void SimpleStreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
175
276
                                           CheckerContext &C) const {
176
276
  ProgramStateRef State = C.getState();
177
276
  SymbolVector LeakedStreams;
178
276
  StreamMapTy TrackedStreams = State->get<StreamMap>();
179
276
  for (StreamMapTy::iterator I = TrackedStreams.begin(),
180
329
                             E = TrackedStreams.end(); I != E; 
++I53
) {
181
53
    SymbolRef Sym = I->first;
182
53
    bool IsSymDead = SymReaper.isDead(Sym);
183
53
184
53
    // Collect leaked symbols.
185
53
    if (isLeaked(Sym, I->second, IsSymDead, State))
186
7
      LeakedStreams.push_back(Sym);
187
53
188
53
    // Remove the dead symbol from the streams map.
189
53
    if (IsSymDead)
190
14
      State = State->remove<StreamMap>(Sym);
191
53
  }
192
276
193
276
  ExplodedNode *N = C.generateNonFatalErrorNode(State);
194
276
  if (!N)
195
0
    return;
196
276
  reportLeaks(LeakedStreams, C, N);
197
276
}
198
199
void SimpleStreamChecker::reportDoubleClose(SymbolRef FileDescSym,
200
                                            const CallEvent &Call,
201
1
                                            CheckerContext &C) const {
202
1
  // We reached a bug, stop exploring the path here by generating a sink.
203
1
  ExplodedNode *ErrNode = C.generateErrorNode();
204
1
  // If we've already reached this node on another path, return.
205
1
  if (!ErrNode)
206
0
    return;
207
1
208
1
  // Generate the report.
209
1
  auto R = llvm::make_unique<BugReport>(*DoubleCloseBugType,
210
1
      "Closing a previously closed file stream", ErrNode);
211
1
  R->addRange(Call.getSourceRange());
212
1
  R->markInteresting(FileDescSym);
213
1
  C.emitReport(std::move(R));
214
1
}
215
216
void SimpleStreamChecker::reportLeaks(ArrayRef<SymbolRef> LeakedStreams,
217
                                      CheckerContext &C,
218
276
                                      ExplodedNode *ErrNode) const {
219
276
  // Attach bug reports to the leak node.
220
276
  // TODO: Identify the leaked file descriptor.
221
276
  for (SymbolRef LeakedStream : LeakedStreams) {
222
7
    auto R = llvm::make_unique<BugReport>(*LeakBugType,
223
7
        "Opened file is never closed; potential resource leak", ErrNode);
224
7
    R->markInteresting(LeakedStream);
225
7
    C.emitReport(std::move(R));
226
7
  }
227
276
}
228
229
20
bool SimpleStreamChecker::guaranteedNotToCloseFile(const CallEvent &Call) const{
230
20
  // If it's not in a system header, assume it might close a file.
231
20
  if (!Call.isInSystemHeader())
232
11
    return false;
233
9
234
9
  // Handle cases where we know a buffer's /address/ can escape.
235
9
  if (Call.argumentsMayEscape())
236
0
    return false;
237
9
238
9
  // Note, even though fclose closes the file, we do not list it here
239
9
  // since the checker is modeling the call.
240
9
241
9
  return true;
242
9
}
243
244
// If the pointer we are tracking escaped, do not track the symbol as
245
// we cannot reason about it anymore.
246
ProgramStateRef
247
SimpleStreamChecker::checkPointerEscape(ProgramStateRef State,
248
                                        const InvalidatedSymbols &Escaped,
249
                                        const CallEvent *Call,
250
69
                                        PointerEscapeKind Kind) const {
251
69
  // If we know that the call cannot close a file, there is nothing to do.
252
69
  if (Kind == PSK_DirectEscapeOnCall && 
guaranteedNotToCloseFile(*Call)20
) {
253
9
    return State;
254
9
  }
255
60
256
60
  for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
257
60
                                          E = Escaped.end();
258
126
                                          I != E; 
++I66
) {
259
66
    SymbolRef Sym = *I;
260
66
261
66
    // The symbol escaped. Optimistically, assume that the corresponding file
262
66
    // handle will be closed somewhere else.
263
66
    State = State->remove<StreamMap>(Sym);
264
66
  }
265
60
  return State;
266
60
}
267
268
5
void ento::registerSimpleStreamChecker(CheckerManager &mgr) {
269
5
  mgr.registerChecker<SimpleStreamChecker>();
270
5
}
271
272
// This checker should be enabled regardless of how language options are set.
273
5
bool ento::shouldRegisterSimpleStreamChecker(const LangOptions &LO) {
274
5
  return true;
275
5
}