Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//==- ExprInspectionChecker.cpp - Used for regression tests ------*- 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
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
10
#include "clang/StaticAnalyzer/Checkers/SValExplainer.h"
11
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
12
#include "clang/StaticAnalyzer/Core/Checker.h"
13
#include "clang/StaticAnalyzer/Core/IssueHash.h"
14
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
15
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
16
#include "llvm/ADT/StringSwitch.h"
17
#include "llvm/Support/ScopedPrinter.h"
18
19
using namespace clang;
20
using namespace ento;
21
22
namespace {
23
class ExprInspectionChecker : public Checker<eval::Call, check::DeadSymbols,
24
                                             check::EndAnalysis> {
25
  mutable std::unique_ptr<BugType> BT;
26
27
  // These stats are per-analysis, not per-branch, hence they shouldn't
28
  // stay inside the program state.
29
  struct ReachedStat {
30
    ExplodedNode *ExampleNode;
31
    unsigned NumTimesReached;
32
  };
33
  mutable llvm::DenseMap<const CallExpr *, ReachedStat> ReachedStats;
34
35
  void analyzerEval(const CallExpr *CE, CheckerContext &C) const;
36
  void analyzerCheckInlined(const CallExpr *CE, CheckerContext &C) const;
37
  void analyzerWarnIfReached(const CallExpr *CE, CheckerContext &C) const;
38
  void analyzerNumTimesReached(const CallExpr *CE, CheckerContext &C) const;
39
  void analyzerCrash(const CallExpr *CE, CheckerContext &C) const;
40
  void analyzerWarnOnDeadSymbol(const CallExpr *CE, CheckerContext &C) const;
41
  void analyzerDump(const CallExpr *CE, CheckerContext &C) const;
42
  void analyzerExplain(const CallExpr *CE, CheckerContext &C) const;
43
  void analyzerPrintState(const CallExpr *CE, CheckerContext &C) const;
44
  void analyzerGetExtent(const CallExpr *CE, CheckerContext &C) const;
45
  void analyzerHashDump(const CallExpr *CE, CheckerContext &C) const;
46
  void analyzerDenote(const CallExpr *CE, CheckerContext &C) const;
47
  void analyzerExpress(const CallExpr *CE, CheckerContext &C) const;
48
49
  typedef void (ExprInspectionChecker::*FnCheck)(const CallExpr *,
50
                                                 CheckerContext &C) const;
51
52
  ExplodedNode *reportBug(llvm::StringRef Msg, CheckerContext &C) const;
53
  ExplodedNode *reportBug(llvm::StringRef Msg, BugReporter &BR,
54
                          ExplodedNode *N) const;
55
56
public:
57
  bool evalCall(const CallEvent &Call, CheckerContext &C) const;
58
  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
59
  void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
60
                        ExprEngine &Eng) const;
61
};
62
}
63
64
REGISTER_SET_WITH_PROGRAMSTATE(MarkedSymbols, SymbolRef)
65
REGISTER_MAP_WITH_PROGRAMSTATE(DenotedSymbols, SymbolRef, const StringLiteral *)
66
67
bool ExprInspectionChecker::evalCall(const CallEvent &Call,
68
25.2k
                                     CheckerContext &C) const {
69
25.2k
  const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
70
25.2k
  if (!CE)
71
0
    return false;
72
25.2k
73
25.2k
  // These checks should have no effect on the surrounding environment
74
25.2k
  // (globals should not be invalidated, etc), hence the use of evalCall.
75
25.2k
  FnCheck Handler = llvm::StringSwitch<FnCheck>(C.getCalleeName(CE))
76
25.2k
    .Case("clang_analyzer_eval", &ExprInspectionChecker::analyzerEval)
77
25.2k
    .Case("clang_analyzer_checkInlined",
78
25.2k
          &ExprInspectionChecker::analyzerCheckInlined)
79
25.2k
    .Case("clang_analyzer_crash", &ExprInspectionChecker::analyzerCrash)
80
25.2k
    .Case("clang_analyzer_warnIfReached",
81
25.2k
          &ExprInspectionChecker::analyzerWarnIfReached)
82
25.2k
    .Case("clang_analyzer_warnOnDeadSymbol",
83
25.2k
          &ExprInspectionChecker::analyzerWarnOnDeadSymbol)
84
25.2k
    .StartsWith("clang_analyzer_explain", &ExprInspectionChecker::analyzerExplain)
85
25.2k
    .StartsWith("clang_analyzer_dump", &ExprInspectionChecker::analyzerDump)
86
25.2k
    .Case("clang_analyzer_getExtent", &ExprInspectionChecker::analyzerGetExtent)
87
25.2k
    .Case("clang_analyzer_printState",
88
25.2k
          &ExprInspectionChecker::analyzerPrintState)
89
25.2k
    .Case("clang_analyzer_numTimesReached",
90
25.2k
          &ExprInspectionChecker::analyzerNumTimesReached)
91
25.2k
    .Case("clang_analyzer_hashDump", &ExprInspectionChecker::analyzerHashDump)
92
25.2k
    .Case("clang_analyzer_denote", &ExprInspectionChecker::analyzerDenote)
93
25.2k
    .Case("clang_analyzer_express", &ExprInspectionChecker::analyzerExpress)
94
25.2k
    .Default(nullptr);
95
25.2k
96
25.2k
  if (!Handler)
97
17.5k
    return false;
98
7.70k
99
7.70k
  (this->*Handler)(CE, C);
100
7.70k
  return true;
101
7.70k
}
102
103
static const char *getArgumentValueString(const CallExpr *CE,
104
5.28k
                                          CheckerContext &C) {
105
5.28k
  if (CE->getNumArgs() == 0)
106
0
    return "Missing assertion argument";
107
5.28k
108
5.28k
  ExplodedNode *N = C.getPredecessor();
109
5.28k
  const LocationContext *LC = N->getLocationContext();
110
5.28k
  ProgramStateRef State = N->getState();
111
5.28k
112
5.28k
  const Expr *Assertion = CE->getArg(0);
113
5.28k
  SVal AssertionVal = State->getSVal(Assertion, LC);
114
5.28k
115
5.28k
  if (AssertionVal.isUndef())
116
2
    return "UNDEFINED";
117
5.28k
118
5.28k
  ProgramStateRef StTrue, StFalse;
119
5.28k
  std::tie(StTrue, StFalse) =
120
5.28k
    State->assume(AssertionVal.castAs<DefinedOrUnknownSVal>());
121
5.28k
122
5.28k
  if (StTrue) {
123
4.87k
    if (StFalse)
124
1.28k
      return "UNKNOWN";
125
3.58k
    else
126
3.58k
      return "TRUE";
127
414
  } else {
128
414
    if (StFalse)
129
414
      return "FALSE";
130
414
    else
131
414
      llvm_unreachable("Invalid constraint; neither true or false.");
132
414
  }
133
5.28k
}
134
135
ExplodedNode *ExprInspectionChecker::reportBug(llvm::StringRef Msg,
136
5.77k
                                               CheckerContext &C) const {
137
5.77k
  ExplodedNode *N = C.generateNonFatalErrorNode();
138
5.77k
  reportBug(Msg, C.getBugReporter(), N);
139
5.77k
  return N;
140
5.77k
}
141
142
ExplodedNode *ExprInspectionChecker::reportBug(llvm::StringRef Msg,
143
                                               BugReporter &BR,
144
5.88k
                                               ExplodedNode *N) const {
145
5.88k
  if (!N)
146
0
    return nullptr;
147
5.88k
148
5.88k
  if (!BT)
149
206
    BT.reset(new BugType(this, "Checking analyzer assumptions", "debug"));
150
5.88k
151
5.88k
  BR.emitReport(llvm::make_unique<BugReport>(*BT, Msg, N));
152
5.88k
  return N;
153
5.88k
}
154
155
void ExprInspectionChecker::analyzerEval(const CallExpr *CE,
156
5.17k
                                         CheckerContext &C) const {
157
5.17k
  const LocationContext *LC = C.getPredecessor()->getLocationContext();
158
5.17k
159
5.17k
  // A specific instantiation of an inlined function may have more constrained
160
5.17k
  // values than can generally be assumed. Skip the check.
161
5.17k
  if (LC->getStackFrame()->getParent() != nullptr)
162
5
    return;
163
5.16k
164
5.16k
  reportBug(getArgumentValueString(CE, C), C);
165
5.16k
}
166
167
void ExprInspectionChecker::analyzerWarnIfReached(const CallExpr *CE,
168
150
                                                  CheckerContext &C) const {
169
150
  reportBug("REACHABLE", C);
170
150
}
171
172
void ExprInspectionChecker::analyzerNumTimesReached(const CallExpr *CE,
173
1.73k
                                                    CheckerContext &C) const {
174
1.73k
  ++ReachedStats[CE].NumTimesReached;
175
1.73k
  if (!ReachedStats[CE].ExampleNode) {
176
119
    // Later, in checkEndAnalysis, we'd throw a report against it.
177
119
    ReachedStats[CE].ExampleNode = C.generateNonFatalErrorNode();
178
119
  }
179
1.73k
}
180
181
void ExprInspectionChecker::analyzerCheckInlined(const CallExpr *CE,
182
137
                                                 CheckerContext &C) const {
183
137
  const LocationContext *LC = C.getPredecessor()->getLocationContext();
184
137
185
137
  // An inlined function could conceivably also be analyzed as a top-level
186
137
  // function. We ignore this case and only emit a message (TRUE or FALSE)
187
137
  // when we are analyzing it as an inlined function. This means that
188
137
  // clang_analyzer_checkInlined(true) should always print TRUE, but
189
137
  // clang_analyzer_checkInlined(false) should never actually print anything.
190
137
  if (LC->getStackFrame()->getParent() == nullptr)
191
15
    return;
192
122
193
122
  reportBug(getArgumentValueString(CE, C), C);
194
122
}
195
196
void ExprInspectionChecker::analyzerExplain(const CallExpr *CE,
197
45
                                            CheckerContext &C) const {
198
45
  if (CE->getNumArgs() == 0) {
199
0
    reportBug("Missing argument for explaining", C);
200
0
    return;
201
0
  }
202
45
203
45
  SVal V = C.getSVal(CE->getArg(0));
204
45
  SValExplainer Ex(C.getASTContext());
205
45
  reportBug(Ex.Visit(V), C);
206
45
}
207
208
void ExprInspectionChecker::analyzerDump(const CallExpr *CE,
209
3
                                         CheckerContext &C) const {
210
3
  if (CE->getNumArgs() == 0) {
211
0
    reportBug("Missing argument for dumping", C);
212
0
    return;
213
0
  }
214
3
215
3
  SVal V = C.getSVal(CE->getArg(0));
216
3
217
3
  llvm::SmallString<32> Str;
218
3
  llvm::raw_svector_ostream OS(Str);
219
3
  V.dumpToStream(OS);
220
3
  reportBug(OS.str(), C);
221
3
}
222
223
void ExprInspectionChecker::analyzerGetExtent(const CallExpr *CE,
224
2
                                              CheckerContext &C) const {
225
2
  if (CE->getNumArgs() == 0) {
226
0
    reportBug("Missing region for obtaining extent", C);
227
0
    return;
228
0
  }
229
2
230
2
  auto MR = dyn_cast_or_null<SubRegion>(C.getSVal(CE->getArg(0)).getAsRegion());
231
2
  if (!MR) {
232
0
    reportBug("Obtaining extent of a non-region", C);
233
0
    return;
234
0
  }
235
2
236
2
  ProgramStateRef State = C.getState();
237
2
  State = State->BindExpr(CE, C.getLocationContext(),
238
2
                          MR->getExtent(C.getSValBuilder()));
239
2
  C.addTransition(State);
240
2
}
241
242
void ExprInspectionChecker::analyzerPrintState(const CallExpr *CE,
243
4
                                               CheckerContext &C) const {
244
4
  C.getState()->dump();
245
4
}
246
247
void ExprInspectionChecker::analyzerWarnOnDeadSymbol(const CallExpr *CE,
248
14
                                                     CheckerContext &C) const {
249
14
  if (CE->getNumArgs() == 0)
250
0
    return;
251
14
  SVal Val = C.getSVal(CE->getArg(0));
252
14
  SymbolRef Sym = Val.getAsSymbol();
253
14
  if (!Sym)
254
0
    return;
255
14
256
14
  ProgramStateRef State = C.getState();
257
14
  State = State->add<MarkedSymbols>(Sym);
258
14
  C.addTransition(State);
259
14
}
260
261
void ExprInspectionChecker::checkDeadSymbols(SymbolReaper &SymReaper,
262
134k
                                             CheckerContext &C) const {
263
134k
  ProgramStateRef State = C.getState();
264
134k
  const MarkedSymbolsTy &Syms = State->get<MarkedSymbols>();
265
134k
  ExplodedNode *N = C.getPredecessor();
266
134k
  for (auto I = Syms.begin(), E = Syms.end(); I != E; 
++I75
) {
267
75
    SymbolRef Sym = *I;
268
75
    if (!SymReaper.isDead(Sym))
269
67
      continue;
270
8
271
8
    // The non-fatal error node should be the same for all reports.
272
8
    if (ExplodedNode *BugNode = reportBug("SYMBOL DEAD", C))
273
8
      N = BugNode;
274
8
    State = State->remove<MarkedSymbols>(Sym);
275
8
  }
276
134k
277
134k
  for (auto I : State->get<DenotedSymbols>()) {
278
723
    SymbolRef Sym = I.first;
279
723
    if (!SymReaper.isLive(Sym))
280
167
      State = State->remove<DenotedSymbols>(Sym);
281
723
  }
282
134k
283
134k
  C.addTransition(State, N);
284
134k
}
285
286
void ExprInspectionChecker::checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
287
5.37k
                                             ExprEngine &Eng) const {
288
5.37k
  for (auto Item: ReachedStats) {
289
119
    unsigned NumTimesReached = Item.second.NumTimesReached;
290
119
    ExplodedNode *N = Item.second.ExampleNode;
291
119
292
119
    reportBug(llvm::to_string(NumTimesReached), BR, N);
293
119
  }
294
5.37k
  ReachedStats.clear();
295
5.37k
}
296
297
void ExprInspectionChecker::analyzerCrash(const CallExpr *CE,
298
0
                                          CheckerContext &C) const {
299
0
  LLVM_BUILTIN_TRAP;
300
0
}
301
302
void ExprInspectionChecker::analyzerHashDump(const CallExpr *CE,
303
21
                                             CheckerContext &C) const {
304
21
  const LangOptions &Opts = C.getLangOpts();
305
21
  const SourceManager &SM = C.getSourceManager();
306
21
  FullSourceLoc FL(CE->getArg(0)->getBeginLoc(), SM);
307
21
  std::string HashContent =
308
21
      GetIssueString(SM, FL, getCheckName().getName(), "Category",
309
21
                     C.getLocationContext()->getDecl(), Opts);
310
21
311
21
  reportBug(HashContent, C);
312
21
}
313
314
void ExprInspectionChecker::analyzerDenote(const CallExpr *CE,
315
171
                                           CheckerContext &C) const {
316
171
  if (CE->getNumArgs() < 2) {
317
2
    reportBug("clang_analyzer_denote() requires a symbol and a string literal",
318
2
              C);
319
2
    return;
320
2
  }
321
169
322
169
  SymbolRef Sym = C.getSVal(CE->getArg(0)).getAsSymbol();
323
169
  if (!Sym) {
324
2
    reportBug("Not a symbol", C);
325
2
    return;
326
2
  }
327
167
328
167
  const auto *E = dyn_cast<StringLiteral>(CE->getArg(1)->IgnoreParenCasts());
329
167
  if (!E) {
330
0
    reportBug("Not a string literal", C);
331
0
    return;
332
0
  }
333
167
334
167
  ProgramStateRef State = C.getState();
335
167
336
167
  C.addTransition(C.getState()->set<DenotedSymbols>(Sym, E));
337
167
}
338
339
namespace {
340
class SymbolExpressor
341
    : public SymExprVisitor<SymbolExpressor, Optional<std::string>> {
342
  ProgramStateRef State;
343
344
public:
345
248
  SymbolExpressor(ProgramStateRef State) : State(State) {}
346
347
618
  Optional<std::string> lookup(const SymExpr *S) {
348
618
    if (const StringLiteral *const *SLPtr = State->get<DenotedSymbols>(S)) {
349
321
      const StringLiteral *SL = *SLPtr;
350
321
      return std::string(SL->getBytes());
351
321
    }
352
297
    return None;
353
297
  }
354
355
321
  Optional<std::string> VisitSymExpr(const SymExpr *S) {
356
321
    return lookup(S);
357
321
  }
358
359
223
  Optional<std::string> VisitSymIntExpr(const SymIntExpr *S) {
360
223
    if (Optional<std::string> Str = lookup(S))
361
1
      return Str;
362
222
    if (Optional<std::string> Str = Visit(S->getLHS()))
363
222
      return (*Str + " " + BinaryOperator::getOpcodeStr(S->getOpcode()) + " " +
364
222
              std::to_string(S->getRHS().getLimitedValue()) +
365
222
              (S->getRHS().isUnsigned() ? 
"U"64
:
""158
))
366
222
          .str();
367
0
    return None;
368
0
  }
369
370
74
  Optional<std::string> VisitSymSymExpr(const SymSymExpr *S) {
371
74
    if (Optional<std::string> Str = lookup(S))
372
0
      return Str;
373
74
    if (Optional<std::string> Str1 = Visit(S->getLHS()))
374
74
      if (Optional<std::string> Str2 = Visit(S->getRHS()))
375
74
        return (*Str1 + " " + BinaryOperator::getOpcodeStr(S->getOpcode()) +
376
74
                " " + *Str2).str();
377
0
    return None;
378
0
  }
379
380
0
  Optional<std::string> VisitSymbolCast(const SymbolCast *S) {
381
0
    if (Optional<std::string> Str = lookup(S))
382
0
      return Str;
383
0
    if (Optional<std::string> Str = Visit(S->getOperand()))
384
0
      return (Twine("(") + S->getType().getAsString() + ")" + *Str).str();
385
0
    return None;
386
0
  }
387
};
388
} // namespace
389
390
void ExprInspectionChecker::analyzerExpress(const CallExpr *CE,
391
251
                                            CheckerContext &C) const {
392
251
  if (CE->getNumArgs() == 0) {
393
1
    reportBug("clang_analyzer_express() requires a symbol", C);
394
1
    return;
395
1
  }
396
250
397
250
  SymbolRef Sym = C.getSVal(CE->getArg(0)).getAsSymbol();
398
250
  if (!Sym) {
399
2
    reportBug("Not a symbol", C);
400
2
    return;
401
2
  }
402
248
403
248
  SymbolExpressor V(C.getState());
404
248
  auto Str = V.Visit(Sym);
405
248
  if (!Str) {
406
1
    reportBug("Unable to express", C);
407
1
    return;
408
1
  }
409
247
410
247
  reportBug(*Str, C);
411
247
}
412
413
241
void ento::registerExprInspectionChecker(CheckerManager &Mgr) {
414
241
  Mgr.registerChecker<ExprInspectionChecker>();
415
241
}
416
417
241
bool ento::shouldRegisterExprInspectionChecker(const LangOptions &LO) {
418
241
  return true;
419
241
}