Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//= CStringChecker.cpp - Checks calls to C string functions --------*- 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
// This defines CStringChecker, which is an assortment of checks on calls
10
// to functions in <string.h>.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "InterCheckerAPI.h"
15
#include "clang/Basic/CharInfo.h"
16
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
17
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18
#include "clang/StaticAnalyzer/Core/Checker.h"
19
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
20
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
21
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22
#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h"
23
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
24
#include "llvm/ADT/STLExtras.h"
25
#include "llvm/ADT/SmallString.h"
26
#include "llvm/Support/raw_ostream.h"
27
28
using namespace clang;
29
using namespace ento;
30
31
namespace {
32
enum class ConcatFnKind { none = 0, strcat = 1, strlcat = 2 };
33
class CStringChecker : public Checker< eval::Call,
34
                                         check::PreStmt<DeclStmt>,
35
                                         check::LiveSymbols,
36
                                         check::DeadSymbols,
37
                                         check::RegionChanges
38
                                         > {
39
  mutable std::unique_ptr<BugType> BT_Null, BT_Bounds, BT_Overlap,
40
      BT_NotCString, BT_AdditionOverflow;
41
42
  mutable const char *CurrentFunctionDescription;
43
44
public:
45
  /// The filter is used to filter out the diagnostics which are not enabled by
46
  /// the user.
47
  struct CStringChecksFilter {
48
    DefaultBool CheckCStringNullArg;
49
    DefaultBool CheckCStringOutOfBounds;
50
    DefaultBool CheckCStringBufferOverlap;
51
    DefaultBool CheckCStringNotNullTerm;
52
53
    CheckerNameRef CheckNameCStringNullArg;
54
    CheckerNameRef CheckNameCStringOutOfBounds;
55
    CheckerNameRef CheckNameCStringBufferOverlap;
56
    CheckerNameRef CheckNameCStringNotNullTerm;
57
  };
58
59
  CStringChecksFilter Filter;
60
61
617
  static void *getTag() { static int tag; return &tag; }
62
63
  bool evalCall(const CallEvent &Call, CheckerContext &C) const;
64
  void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
65
  void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
66
  void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
67
68
  ProgramStateRef
69
    checkRegionChanges(ProgramStateRef state,
70
                       const InvalidatedSymbols *,
71
                       ArrayRef<const MemRegion *> ExplicitRegions,
72
                       ArrayRef<const MemRegion *> Regions,
73
                       const LocationContext *LCtx,
74
                       const CallEvent *Call) const;
75
76
  typedef void (CStringChecker::*FnCheck)(CheckerContext &,
77
                                          const CallExpr *) const;
78
  CallDescriptionMap<FnCheck> Callbacks = {
79
      {{CDF_MaybeBuiltin, "memcpy", 3}, &CStringChecker::evalMemcpy},
80
      {{CDF_MaybeBuiltin, "mempcpy", 3}, &CStringChecker::evalMempcpy},
81
      {{CDF_MaybeBuiltin, "memcmp", 3}, &CStringChecker::evalMemcmp},
82
      {{CDF_MaybeBuiltin, "memmove", 3}, &CStringChecker::evalMemmove},
83
      {{CDF_MaybeBuiltin, "memset", 3}, &CStringChecker::evalMemset},
84
      {{CDF_MaybeBuiltin, "explicit_memset", 3}, &CStringChecker::evalMemset},
85
      {{CDF_MaybeBuiltin, "strcpy", 2}, &CStringChecker::evalStrcpy},
86
      {{CDF_MaybeBuiltin, "strncpy", 3}, &CStringChecker::evalStrncpy},
87
      {{CDF_MaybeBuiltin, "stpcpy", 2}, &CStringChecker::evalStpcpy},
88
      {{CDF_MaybeBuiltin, "strlcpy", 3}, &CStringChecker::evalStrlcpy},
89
      {{CDF_MaybeBuiltin, "strcat", 2}, &CStringChecker::evalStrcat},
90
      {{CDF_MaybeBuiltin, "strncat", 3}, &CStringChecker::evalStrncat},
91
      {{CDF_MaybeBuiltin, "strlcat", 3}, &CStringChecker::evalStrlcat},
92
      {{CDF_MaybeBuiltin, "strlen", 1}, &CStringChecker::evalstrLength},
93
      {{CDF_MaybeBuiltin, "strnlen", 2}, &CStringChecker::evalstrnLength},
94
      {{CDF_MaybeBuiltin, "strcmp", 2}, &CStringChecker::evalStrcmp},
95
      {{CDF_MaybeBuiltin, "strncmp", 3}, &CStringChecker::evalStrncmp},
96
      {{CDF_MaybeBuiltin, "strcasecmp", 2}, &CStringChecker::evalStrcasecmp},
97
      {{CDF_MaybeBuiltin, "strncasecmp", 3}, &CStringChecker::evalStrncasecmp},
98
      {{CDF_MaybeBuiltin, "strsep", 2}, &CStringChecker::evalStrsep},
99
      {{CDF_MaybeBuiltin, "bcopy", 3}, &CStringChecker::evalBcopy},
100
      {{CDF_MaybeBuiltin, "bcmp", 3}, &CStringChecker::evalMemcmp},
101
      {{CDF_MaybeBuiltin, "bzero", 2}, &CStringChecker::evalBzero},
102
      {{CDF_MaybeBuiltin, "explicit_bzero", 2}, &CStringChecker::evalBzero},
103
  };
104
105
  // These require a bit of special handling.
106
  CallDescription StdCopy{{"std", "copy"}, 3},
107
      StdCopyBackward{{"std", "copy_backward"}, 3};
108
109
  FnCheck identifyCall(const CallEvent &Call, CheckerContext &C) const;
110
  void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
111
  void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
112
  void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
113
  void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
114
  void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
115
                      ProgramStateRef state,
116
                      const Expr *Size,
117
                      const Expr *Source,
118
                      const Expr *Dest,
119
                      bool Restricted = false,
120
                      bool IsMempcpy = false) const;
121
122
  void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
123
124
  void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
125
  void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
126
  void evalstrLengthCommon(CheckerContext &C,
127
                           const CallExpr *CE,
128
                           bool IsStrnlen = false) const;
129
130
  void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
131
  void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
132
  void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
133
  void evalStrlcpy(CheckerContext &C, const CallExpr *CE) const;
134
  void evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, bool ReturnEnd,
135
                        bool IsBounded, ConcatFnKind appendK,
136
                        bool returnPtr = true) const;
137
138
  void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
139
  void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
140
  void evalStrlcat(CheckerContext &C, const CallExpr *CE) const;
141
142
  void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
143
  void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
144
  void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
145
  void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
146
  void evalStrcmpCommon(CheckerContext &C,
147
                        const CallExpr *CE,
148
                        bool IsBounded = false,
149
                        bool IgnoreCase = false) const;
150
151
  void evalStrsep(CheckerContext &C, const CallExpr *CE) const;
152
153
  void evalStdCopy(CheckerContext &C, const CallExpr *CE) const;
154
  void evalStdCopyBackward(CheckerContext &C, const CallExpr *CE) const;
155
  void evalStdCopyCommon(CheckerContext &C, const CallExpr *CE) const;
156
  void evalMemset(CheckerContext &C, const CallExpr *CE) const;
157
  void evalBzero(CheckerContext &C, const CallExpr *CE) const;
158
159
  // Utility methods
160
  std::pair<ProgramStateRef , ProgramStateRef >
161
  static assumeZero(CheckerContext &C,
162
                    ProgramStateRef state, SVal V, QualType Ty);
163
164
  static ProgramStateRef setCStringLength(ProgramStateRef state,
165
                                              const MemRegion *MR,
166
                                              SVal strLength);
167
  static SVal getCStringLengthForRegion(CheckerContext &C,
168
                                        ProgramStateRef &state,
169
                                        const Expr *Ex,
170
                                        const MemRegion *MR,
171
                                        bool hypothetical);
172
  SVal getCStringLength(CheckerContext &C,
173
                        ProgramStateRef &state,
174
                        const Expr *Ex,
175
                        SVal Buf,
176
                        bool hypothetical = false) const;
177
178
  const StringLiteral *getCStringLiteral(CheckerContext &C,
179
                                         ProgramStateRef &state,
180
                                         const Expr *expr,
181
                                         SVal val) const;
182
183
  static ProgramStateRef InvalidateBuffer(CheckerContext &C,
184
                                          ProgramStateRef state,
185
                                          const Expr *Ex, SVal V,
186
                                          bool IsSourceBuffer,
187
                                          const Expr *Size);
188
189
  static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
190
                              const MemRegion *MR);
191
192
  static bool memsetAux(const Expr *DstBuffer, SVal CharE,
193
                        const Expr *Size, CheckerContext &C,
194
                        ProgramStateRef &State);
195
196
  // Re-usable checks
197
  ProgramStateRef checkNonNull(CheckerContext &C,
198
                                   ProgramStateRef state,
199
                                   const Expr *S,
200
                                   SVal l,
201
                                   unsigned IdxOfArg) const;
202
  ProgramStateRef CheckLocation(CheckerContext &C,
203
                                    ProgramStateRef state,
204
                                    const Expr *S,
205
                                    SVal l,
206
                                    const char *message = nullptr) const;
207
  ProgramStateRef CheckBufferAccess(CheckerContext &C,
208
                                        ProgramStateRef state,
209
                                        const Expr *Size,
210
                                        const Expr *FirstBuf,
211
                                        const Expr *SecondBuf,
212
                                        const char *firstMessage = nullptr,
213
                                        const char *secondMessage = nullptr,
214
                                        bool WarnAboutSize = false) const;
215
216
  ProgramStateRef CheckBufferAccess(CheckerContext &C,
217
                                        ProgramStateRef state,
218
                                        const Expr *Size,
219
                                        const Expr *Buf,
220
                                        const char *message = nullptr,
221
184
                                        bool WarnAboutSize = false) const {
222
184
    // This is a convenience overload.
223
184
    return CheckBufferAccess(C, state, Size, Buf, nullptr, message, nullptr,
224
184
                             WarnAboutSize);
225
184
  }
226
  ProgramStateRef CheckOverlap(CheckerContext &C,
227
                                   ProgramStateRef state,
228
                                   const Expr *Size,
229
                                   const Expr *First,
230
                                   const Expr *Second) const;
231
  void emitOverlapBug(CheckerContext &C,
232
                      ProgramStateRef state,
233
                      const Stmt *First,
234
                      const Stmt *Second) const;
235
236
  void emitNullArgBug(CheckerContext &C, ProgramStateRef State, const Stmt *S,
237
                      StringRef WarningMsg) const;
238
  void emitOutOfBoundsBug(CheckerContext &C, ProgramStateRef State,
239
                          const Stmt *S, StringRef WarningMsg) const;
240
  void emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
241
                         const Stmt *S, StringRef WarningMsg) const;
242
  void emitAdditionOverflowBug(CheckerContext &C, ProgramStateRef State) const;
243
244
  ProgramStateRef checkAdditionOverflow(CheckerContext &C,
245
                                            ProgramStateRef state,
246
                                            NonLoc left,
247
                                            NonLoc right) const;
248
249
  // Return true if the destination buffer of the copy function may be in bound.
250
  // Expects SVal of Size to be positive and unsigned.
251
  // Expects SVal of FirstBuf to be a FieldRegion.
252
  static bool IsFirstBufInBound(CheckerContext &C,
253
                                ProgramStateRef state,
254
                                const Expr *FirstBuf,
255
                                const Expr *Size);
256
};
257
258
} //end anonymous namespace
259
260
REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
261
262
//===----------------------------------------------------------------------===//
263
// Individual checks and utility methods.
264
//===----------------------------------------------------------------------===//
265
266
std::pair<ProgramStateRef , ProgramStateRef >
267
CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
268
4.52k
                           QualType Ty) {
269
4.52k
  Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
270
4.52k
  if (!val)
271
11
    return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
272
4.51k
273
4.51k
  SValBuilder &svalBuilder = C.getSValBuilder();
274
4.51k
  DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
275
4.51k
  return state->assume(svalBuilder.evalEQ(state, *val, zero));
276
4.51k
}
277
278
ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
279
                                            ProgramStateRef state,
280
                                            const Expr *S, SVal l,
281
3.62k
                                            unsigned IdxOfArg) const {
282
3.62k
  // If a previous check has failed, propagate the failure.
283
3.62k
  if (!state)
284
0
    return nullptr;
285
3.62k
286
3.62k
  ProgramStateRef stateNull, stateNonNull;
287
3.62k
  std::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
288
3.62k
289
3.62k
  if (stateNull && 
!stateNonNull574
) {
290
168
    if (Filter.CheckCStringNullArg) {
291
168
      SmallString<80> buf;
292
168
      llvm::raw_svector_ostream OS(buf);
293
168
      assert(CurrentFunctionDescription);
294
168
      OS << "Null pointer passed as " << IdxOfArg
295
168
         << llvm::getOrdinalSuffix(IdxOfArg) << " argument to "
296
168
         << CurrentFunctionDescription;
297
168
298
168
      emitNullArgBug(C, stateNull, S, OS.str());
299
168
    }
300
168
    return nullptr;
301
168
  }
302
3.45k
303
3.45k
  // From here on, assume that the value is non-null.
304
3.45k
  assert(stateNonNull);
305
3.45k
  return stateNonNull;
306
3.45k
}
307
308
// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
309
ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
310
                                             ProgramStateRef state,
311
                                             const Expr *S, SVal l,
312
782
                                             const char *warningMsg) const {
313
782
  // If a previous check has failed, propagate the failure.
314
782
  if (!state)
315
0
    return nullptr;
316
782
317
782
  // Check for out of bound array element access.
318
782
  const MemRegion *R = l.getAsRegion();
319
782
  if (!R)
320
0
    return state;
321
782
322
782
  const ElementRegion *ER = dyn_cast<ElementRegion>(R);
323
782
  if (!ER)
324
0
    return state;
325
782
326
782
  if (ER->getValueType() != C.getASTContext().CharTy)
327
1
    return state;
328
781
329
781
  // Get the size of the array.
330
781
  const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
331
781
  DefinedOrUnknownSVal Size =
332
781
      getDynamicSize(state, superReg, C.getSValBuilder());
333
781
334
781
  // Get the index of the accessed element.
335
781
  DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
336
781
337
781
  ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
338
781
  ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
339
781
  if (StOutBound && 
!StInBound272
) {
340
150
    // These checks are either enabled by the CString out-of-bounds checker
341
150
    // explicitly or implicitly by the Malloc checker.
342
150
    // In the latter case we only do modeling but do not emit warning.
343
150
    if (!Filter.CheckCStringOutOfBounds)
344
25
      return nullptr;
345
125
    // Emit a bug report.
346
125
    if (warningMsg) {
347
87
      emitOutOfBoundsBug(C, StOutBound, S, warningMsg);
348
87
    } else {
349
38
      assert(CurrentFunctionDescription);
350
38
      assert(CurrentFunctionDescription[0] != '\0');
351
38
352
38
      SmallString<80> buf;
353
38
      llvm::raw_svector_ostream os(buf);
354
38
      os << toUppercase(CurrentFunctionDescription[0])
355
38
         << &CurrentFunctionDescription[1]
356
38
         << " accesses out-of-bound array element";
357
38
      emitOutOfBoundsBug(C, StOutBound, S, os.str());
358
38
    }
359
125
    return nullptr;
360
125
  }
361
631
362
631
  // Array bound check succeeded.  From this point forward the array bound
363
631
  // should always succeed.
364
631
  return StInBound;
365
631
}
366
367
ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
368
                                                 ProgramStateRef state,
369
                                                 const Expr *Size,
370
                                                 const Expr *FirstBuf,
371
                                                 const Expr *SecondBuf,
372
                                                 const char *firstMessage,
373
                                                 const char *secondMessage,
374
426
                                                 bool WarnAboutSize) const {
375
426
  // If a previous check has failed, propagate the failure.
376
426
  if (!state)
377
0
    return nullptr;
378
426
379
426
  SValBuilder &svalBuilder = C.getSValBuilder();
380
426
  ASTContext &Ctx = svalBuilder.getContext();
381
426
  const LocationContext *LCtx = C.getLocationContext();
382
426
383
426
  QualType sizeTy = Size->getType();
384
426
  QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
385
426
386
426
  // Check that the first buffer is non-null.
387
426
  SVal BufVal = C.getSVal(FirstBuf);
388
426
  state = checkNonNull(C, state, FirstBuf, BufVal, 1);
389
426
  if (!state)
390
0
    return nullptr;
391
426
392
426
  // If out-of-bounds checking is turned off, skip the rest.
393
426
  if (!Filter.CheckCStringOutOfBounds)
394
102
    return state;
395
324
396
324
  // Get the access length and make sure it is known.
397
324
  // FIXME: This assumes the caller has already checked that the access length
398
324
  // is positive. And that it's unsigned.
399
324
  SVal LengthVal = C.getSVal(Size);
400
324
  Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
401
324
  if (!Length)
402
4
    return state;
403
320
404
320
  // Compute the offset of the last element to be accessed: size-1.
405
320
  NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
406
320
  SVal Offset = svalBuilder.evalBinOpNN(state, BO_Sub, *Length, One, sizeTy);
407
320
  if (Offset.isUnknown())
408
4
    return nullptr;
409
316
  NonLoc LastOffset = Offset.castAs<NonLoc>();
410
316
411
316
  // Check that the first buffer is sufficiently long.
412
316
  SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
413
316
  if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
414
312
    const Expr *warningExpr = (WarnAboutSize ? 
Size0
: FirstBuf);
415
312
416
312
    SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
417
312
                                          LastOffset, PtrTy);
418
312
    state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
419
312
420
312
    // If the buffer isn't large enough, abort.
421
312
    if (!state)
422
34
      return nullptr;
423
282
  }
424
282
425
282
  // If there's a second buffer, check it as well.
426
282
  if (SecondBuf) {
427
152
    BufVal = state->getSVal(SecondBuf, LCtx);
428
152
    state = checkNonNull(C, state, SecondBuf, BufVal, 2);
429
152
    if (!state)
430
4
      return nullptr;
431
148
432
148
    BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
433
148
    if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
434
148
      const Expr *warningExpr = (WarnAboutSize ? 
Size0
: SecondBuf);
435
148
436
148
      SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
437
148
                                            LastOffset, PtrTy);
438
148
      state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
439
148
    }
440
148
  }
441
282
442
282
  // Large enough or not, return this state!
443
282
  
return state278
;
444
282
}
445
446
ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
447
                                            ProgramStateRef state,
448
                                            const Expr *Size,
449
                                            const Expr *First,
450
524
                                            const Expr *Second) const {
451
524
  if (!Filter.CheckCStringBufferOverlap)
452
173
    return state;
453
351
454
351
  // Do a simple check for overlap: if the two arguments are from the same
455
351
  // buffer, see if the end of the first is greater than the start of the second
456
351
  // or vice versa.
457
351
458
351
  // If a previous check has failed, propagate the failure.
459
351
  if (!state)
460
36
    return nullptr;
461
315
462
315
  ProgramStateRef stateTrue, stateFalse;
463
315
464
315
  // Get the buffer values and make sure they're known locations.
465
315
  const LocationContext *LCtx = C.getLocationContext();
466
315
  SVal firstVal = state->getSVal(First, LCtx);
467
315
  SVal secondVal = state->getSVal(Second, LCtx);
468
315
469
315
  Optional<Loc> firstLoc = firstVal.getAs<Loc>();
470
315
  if (!firstLoc)
471
0
    return state;
472
315
473
315
  Optional<Loc> secondLoc = secondVal.getAs<Loc>();
474
315
  if (!secondLoc)
475
1
    return state;
476
314
477
314
  // Are the two values the same?
478
314
  SValBuilder &svalBuilder = C.getSValBuilder();
479
314
  std::tie(stateTrue, stateFalse) =
480
314
    state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
481
314
482
314
  if (stateTrue && 
!stateFalse49
) {
483
8
    // If the values are known to be equal, that's automatically an overlap.
484
8
    emitOverlapBug(C, stateTrue, First, Second);
485
8
    return nullptr;
486
8
  }
487
306
488
306
  // assume the two expressions are not equal.
489
306
  assert(stateFalse);
490
306
  state = stateFalse;
491
306
492
306
  // Which value comes first?
493
306
  QualType cmpTy = svalBuilder.getConditionType();
494
306
  SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
495
306
                                         *firstLoc, *secondLoc, cmpTy);
496
306
  Optional<DefinedOrUnknownSVal> reverseTest =
497
306
      reverse.getAs<DefinedOrUnknownSVal>();
498
306
  if (!reverseTest)
499
0
    return state;
500
306
501
306
  std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
502
306
  if (stateTrue) {
503
289
    if (stateFalse) {
504
273
      // If we don't know which one comes first, we can't perform this test.
505
273
      return state;
506
273
    } else {
507
16
      // Switch the values so that firstVal is before secondVal.
508
16
      std::swap(firstLoc, secondLoc);
509
16
510
16
      // Switch the Exprs as well, so that they still correspond.
511
16
      std::swap(First, Second);
512
16
    }
513
289
  }
514
306
515
306
  // Get the length, and make sure it too is known.
516
306
  SVal LengthVal = state->getSVal(Size, LCtx);
517
33
  Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
518
33
  if (!Length)
519
0
    return state;
520
33
521
33
  // Convert the first buffer's start address to char*.
522
33
  // Bail out if the cast fails.
523
33
  ASTContext &Ctx = svalBuilder.getContext();
524
33
  QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
525
33
  SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
526
33
                                         First->getType());
527
33
  Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
528
33
  if (!FirstStartLoc)
529
0
    return state;
530
33
531
33
  // Compute the end of the first buffer. Bail out if THAT fails.
532
33
  SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
533
33
                                 *FirstStartLoc, *Length, CharPtrTy);
534
33
  Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
535
33
  if (!FirstEndLoc)
536
0
    return state;
537
33
538
33
  // Is the end of the first buffer past the start of the second buffer?
539
33
  SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
540
33
                                *FirstEndLoc, *secondLoc, cmpTy);
541
33
  Optional<DefinedOrUnknownSVal> OverlapTest =
542
33
      Overlap.getAs<DefinedOrUnknownSVal>();
543
33
  if (!OverlapTest)
544
0
    return state;
545
33
546
33
  std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
547
33
548
33
  if (stateTrue && 
!stateFalse17
) {
549
17
    // Overlap!
550
17
    emitOverlapBug(C, stateTrue, First, Second);
551
17
    return nullptr;
552
17
  }
553
16
554
16
  // assume the two expressions don't overlap.
555
16
  assert(stateFalse);
556
16
  return stateFalse;
557
16
}
558
559
void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
560
25
                                  const Stmt *First, const Stmt *Second) const {
561
25
  ExplodedNode *N = C.generateErrorNode(state);
562
25
  if (!N)
563
0
    return;
564
25
565
25
  if (!BT_Overlap)
566
5
    BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
567
5
                                 categories::UnixAPI, "Improper arguments"));
568
25
569
25
  // Generate a report for this bug.
570
25
  auto report = std::make_unique<PathSensitiveBugReport>(
571
25
      *BT_Overlap, "Arguments must not be overlapping buffers", N);
572
25
  report->addRange(First->getSourceRange());
573
25
  report->addRange(Second->getSourceRange());
574
25
575
25
  C.emitReport(std::move(report));
576
25
}
577
578
void CStringChecker::emitNullArgBug(CheckerContext &C, ProgramStateRef State,
579
168
                                    const Stmt *S, StringRef WarningMsg) const {
580
168
  if (ExplodedNode *N = C.generateErrorNode(State)) {
581
168
    if (!BT_Null)
582
13
      BT_Null.reset(new BuiltinBug(
583
13
          Filter.CheckNameCStringNullArg, categories::UnixAPI,
584
13
          "Null pointer argument in call to byte string function"));
585
168
586
168
    BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Null.get());
587
168
    auto Report = std::make_unique<PathSensitiveBugReport>(*BT, WarningMsg, N);
588
168
    Report->addRange(S->getSourceRange());
589
168
    if (const auto *Ex = dyn_cast<Expr>(S))
590
168
      bugreporter::trackExpressionValue(N, Ex, *Report);
591
168
    C.emitReport(std::move(Report));
592
168
  }
593
168
}
594
595
void CStringChecker::emitOutOfBoundsBug(CheckerContext &C,
596
                                        ProgramStateRef State, const Stmt *S,
597
125
                                        StringRef WarningMsg) const {
598
125
  if (ExplodedNode *N = C.generateErrorNode(State)) {
599
125
    if (!BT_Bounds)
600
10
      BT_Bounds.reset(new BuiltinBug(
601
10
          Filter.CheckCStringOutOfBounds ? Filter.CheckNameCStringOutOfBounds
602
10
                                         : 
Filter.CheckNameCStringNullArg0
,
603
10
          "Out-of-bound array access",
604
10
          "Byte string function accesses out-of-bound array element"));
605
125
606
125
    BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Bounds.get());
607
125
608
125
    // FIXME: It would be nice to eventually make this diagnostic more clear,
609
125
    // e.g., by referencing the original declaration or by saying *why* this
610
125
    // reference is outside the range.
611
125
    auto Report = std::make_unique<PathSensitiveBugReport>(*BT, WarningMsg, N);
612
125
    Report->addRange(S->getSourceRange());
613
125
    C.emitReport(std::move(Report));
614
125
  }
615
125
}
616
617
void CStringChecker::emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
618
                                       const Stmt *S,
619
46
                                       StringRef WarningMsg) const {
620
46
  if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
621
46
    if (!BT_NotCString)
622
6
      BT_NotCString.reset(new BuiltinBug(
623
6
          Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
624
6
          "Argument is not a null-terminated string."));
625
46
626
46
    auto Report =
627
46
        std::make_unique<PathSensitiveBugReport>(*BT_NotCString, WarningMsg, N);
628
46
629
46
    Report->addRange(S->getSourceRange());
630
46
    C.emitReport(std::move(Report));
631
46
  }
632
46
}
633
634
void CStringChecker::emitAdditionOverflowBug(CheckerContext &C,
635
0
                                             ProgramStateRef State) const {
636
0
  if (ExplodedNode *N = C.generateErrorNode(State)) {
637
0
    if (!BT_NotCString)
638
0
      BT_NotCString.reset(
639
0
          new BuiltinBug(Filter.CheckNameCStringOutOfBounds, "API",
640
0
                         "Sum of expressions causes overflow."));
641
0
642
0
    // This isn't a great error message, but this should never occur in real
643
0
    // code anyway -- you'd have to create a buffer longer than a size_t can
644
0
    // represent, which is sort of a contradiction.
645
0
    const char *WarningMsg =
646
0
        "This expression will create a string whose length is too big to "
647
0
        "be represented as a size_t";
648
0
649
0
    auto Report =
650
0
        std::make_unique<PathSensitiveBugReport>(*BT_NotCString, WarningMsg, N);
651
0
    C.emitReport(std::move(Report));
652
0
  }
653
0
}
654
655
ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
656
                                                     ProgramStateRef state,
657
                                                     NonLoc left,
658
116
                                                     NonLoc right) const {
659
116
  // If out-of-bounds checking is turned off, skip the rest.
660
116
  if (!Filter.CheckCStringOutOfBounds)
661
39
    return state;
662
77
663
77
  // If a previous check has failed, propagate the failure.
664
77
  if (!state)
665
0
    return nullptr;
666
77
667
77
  SValBuilder &svalBuilder = C.getSValBuilder();
668
77
  BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
669
77
670
77
  QualType sizeTy = svalBuilder.getContext().getSizeType();
671
77
  const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
672
77
  NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
673
77
674
77
  SVal maxMinusRight;
675
77
  if (right.getAs<nonloc::ConcreteInt>()) {
676
65
    maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
677
65
                                                 sizeTy);
678
65
  } else {
679
12
    // Try switching the operands. (The order of these two assignments is
680
12
    // important!)
681
12
    maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
682
12
                                            sizeTy);
683
12
    left = right;
684
12
  }
685
77
686
77
  if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
687
77
    QualType cmpTy = svalBuilder.getConditionType();
688
77
    // If left > max - right, we have an overflow.
689
77
    SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
690
77
                                                *maxMinusRightNL, cmpTy);
691
77
692
77
    ProgramStateRef stateOverflow, stateOkay;
693
77
    std::tie(stateOverflow, stateOkay) =
694
77
      state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
695
77
696
77
    if (stateOverflow && 
!stateOkay0
) {
697
0
      // We have an overflow. Emit a bug report.
698
0
      emitAdditionOverflowBug(C, stateOverflow);
699
0
      return nullptr;
700
0
    }
701
77
702
77
    // From now on, assume an overflow didn't occur.
703
77
    assert(stateOkay);
704
77
    state = stateOkay;
705
77
  }
706
77
707
77
  return state;
708
77
}
709
710
ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
711
                                                const MemRegion *MR,
712
385
                                                SVal strLength) {
713
385
  assert(!strLength.isUndef() && "Attempt to set an undefined string length");
714
385
715
385
  MR = MR->StripCasts();
716
385
717
385
  switch (MR->getKind()) {
718
0
  case MemRegion::StringRegionKind:
719
0
    // FIXME: This can happen if we strcpy() into a string region. This is
720
0
    // undefined [C99 6.4.5p6], but we should still warn about it.
721
0
    return state;
722
0
723
381
  case MemRegion::SymbolicRegionKind:
724
381
  case MemRegion::AllocaRegionKind:
725
381
  case MemRegion::VarRegionKind:
726
381
  case MemRegion::FieldRegionKind:
727
381
  case MemRegion::ObjCIvarRegionKind:
728
381
    // These are the types we can currently track string lengths for.
729
381
    break;
730
381
731
381
  case MemRegion::ElementRegionKind:
732
4
    // FIXME: Handle element regions by upper-bounding the parent region's
733
4
    // string length.
734
4
    return state;
735
381
736
381
  default:
737
0
    // Other regions (mostly non-data) can't have a reliable C string length.
738
0
    // For now, just ignore the change.
739
0
    // FIXME: These are rare but not impossible. We should output some kind of
740
0
    // warning for things like strcpy((char[]){'a', 0}, "b");
741
0
    return state;
742
381
  }
743
381
744
381
  if (strLength.isUnknown())
745
51
    return state->remove<CStringLength>(MR);
746
330
747
330
  return state->set<CStringLength>(MR, strLength);
748
330
}
749
750
SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
751
                                               ProgramStateRef &state,
752
                                               const Expr *Ex,
753
                                               const MemRegion *MR,
754
1.22k
                                               bool hypothetical) {
755
1.22k
  if (!hypothetical) {
756
1.17k
    // If there's a recorded length, go ahead and return it.
757
1.17k
    const SVal *Recorded = state->get<CStringLength>(MR);
758
1.17k
    if (Recorded)
759
661
      return *Recorded;
760
568
  }
761
568
762
568
  // Otherwise, get a new symbol and update the state.
763
568
  SValBuilder &svalBuilder = C.getSValBuilder();
764
568
  QualType sizeTy = svalBuilder.getContext().getSizeType();
765
568
  SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
766
568
                                                    MR, Ex, sizeTy,
767
568
                                                    C.getLocationContext(),
768
568
                                                    C.blockCount());
769
568
770
568
  if (!hypothetical) {
771
516
    if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
772
516
      // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
773
516
      BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
774
516
      const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
775
516
      llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
776
516
      const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
777
516
                                                        fourInt);
778
516
      NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
779
516
      SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
780
516
                                                maxLength, sizeTy);
781
516
      state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
782
516
    }
783
516
    state = state->set<CStringLength>(MR, strLength);
784
516
  }
785
568
786
568
  return strLength;
787
568
}
788
789
SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
790
                                      const Expr *Ex, SVal Buf,
791
2.40k
                                      bool hypothetical) const {
792
2.40k
  const MemRegion *MR = Buf.getAsRegion();
793
2.40k
  if (!MR) {
794
16
    // If we can't get a region, see if it's something we /know/ isn't a
795
16
    // C string. In the context of locations, the only time we can issue such
796
16
    // a warning is for labels.
797
16
    if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
798
10
      if (Filter.CheckCStringNotNullTerm) {
799
10
        SmallString<120> buf;
800
10
        llvm::raw_svector_ostream os(buf);
801
10
        assert(CurrentFunctionDescription);
802
10
        os << "Argument to " << CurrentFunctionDescription
803
10
           << " is the address of the label '" << Label->getLabel()->getName()
804
10
           << "', which is not a null-terminated string";
805
10
806
10
        emitNotCStringBug(C, state, Ex, os.str());
807
10
      }
808
10
      return UndefinedVal();
809
10
    }
810
6
811
6
    // If it's not a region and not a label, give up.
812
6
    return UnknownVal();
813
6
  }
814
2.38k
815
2.38k
  // If we have a region, strip casts from it and see if we can figure out
816
2.38k
  // its length. For anything we can't figure out, just return UnknownVal.
817
2.38k
  MR = MR->StripCasts();
818
2.38k
819
2.38k
  switch (MR->getKind()) {
820
1.08k
  case MemRegion::StringRegionKind: {
821
1.08k
    // Modifying the contents of string regions is undefined [C99 6.4.5p6],
822
1.08k
    // so we can assume that the byte length is the correct C string length.
823
1.08k
    SValBuilder &svalBuilder = C.getSValBuilder();
824
1.08k
    QualType sizeTy = svalBuilder.getContext().getSizeType();
825
1.08k
    const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
826
1.08k
    return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
827
0
  }
828
1.22k
  case MemRegion::SymbolicRegionKind:
829
1.22k
  case MemRegion::AllocaRegionKind:
830
1.22k
  case MemRegion::VarRegionKind:
831
1.22k
  case MemRegion::FieldRegionKind:
832
1.22k
  case MemRegion::ObjCIvarRegionKind:
833
1.22k
    return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
834
1.22k
  case MemRegion::CompoundLiteralRegionKind:
835
5
    // FIXME: Can we track this? Is it necessary?
836
5
    return UnknownVal();
837
1.22k
  case MemRegion::ElementRegionKind:
838
31
    // FIXME: How can we handle this? It's not good enough to subtract the
839
31
    // offset from the base string length; consider "123\x00567" and &a[5].
840
31
    return UnknownVal();
841
1.22k
  default:
842
36
    // Other regions (mostly non-data) can't have a reliable C string length.
843
36
    // In this case, an error is emitted and UndefinedVal is returned.
844
36
    // The caller should always be prepared to handle this case.
845
36
    if (Filter.CheckCStringNotNullTerm) {
846
36
      SmallString<120> buf;
847
36
      llvm::raw_svector_ostream os(buf);
848
36
849
36
      assert(CurrentFunctionDescription);
850
36
      os << "Argument to " << CurrentFunctionDescription << " is ";
851
36
852
36
      if (SummarizeRegion(os, C.getASTContext(), MR))
853
36
        os << ", which is not a null-terminated string";
854
0
      else
855
0
        os << "not a null-terminated string";
856
36
857
36
      emitNotCStringBug(C, state, Ex, os.str());
858
36
    }
859
36
    return UndefinedVal();
860
2.38k
  }
861
2.38k
}
862
863
const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
864
752
  ProgramStateRef &state, const Expr *expr, SVal val) const {
865
752
866
752
  // Get the memory region pointed to by the val.
867
752
  const MemRegion *bufRegion = val.getAsRegion();
868
752
  if (!bufRegion)
869
5
    return nullptr;
870
747
871
747
  // Strip casts off the memory region.
872
747
  bufRegion = bufRegion->StripCasts();
873
747
874
747
  // Cast the memory region to a string region.
875
747
  const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
876
747
  if (!strRegion)
877
2
    return nullptr;
878
745
879
745
  // Return the actual string in the string region.
880
745
  return strRegion->getStringLiteral();
881
745
}
882
883
bool CStringChecker::IsFirstBufInBound(CheckerContext &C,
884
                                       ProgramStateRef state,
885
                                       const Expr *FirstBuf,
886
42
                                       const Expr *Size) {
887
42
  // If we do not know that the buffer is long enough we return 'true'.
888
42
  // Otherwise the parent region of this field region would also get
889
42
  // invalidated, which would lead to warnings based on an unknown state.
890
42
891
42
  // Originally copied from CheckBufferAccess and CheckLocation.
892
42
  SValBuilder &svalBuilder = C.getSValBuilder();
893
42
  ASTContext &Ctx = svalBuilder.getContext();
894
42
  const LocationContext *LCtx = C.getLocationContext();
895
42
896
42
  QualType sizeTy = Size->getType();
897
42
  QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
898
42
  SVal BufVal = state->getSVal(FirstBuf, LCtx);
899
42
900
42
  SVal LengthVal = state->getSVal(Size, LCtx);
901
42
  Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
902
42
  if (!Length)
903
1
    return true; // cf top comment.
904
41
905
41
  // Compute the offset of the last element to be accessed: size-1.
906
41
  NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
907
41
  SVal Offset = svalBuilder.evalBinOpNN(state, BO_Sub, *Length, One, sizeTy);
908
41
  if (Offset.isUnknown())
909
0
    return true; // cf top comment
910
41
  NonLoc LastOffset = Offset.castAs<NonLoc>();
911
41
912
41
  // Check that the first buffer is sufficiently long.
913
41
  SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
914
41
  Optional<Loc> BufLoc = BufStart.getAs<Loc>();
915
41
  if (!BufLoc)
916
1
    return true; // cf top comment.
917
40
918
40
  SVal BufEnd =
919
40
      svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc, LastOffset, PtrTy);
920
40
921
40
  // Check for out of bound array element access.
922
40
  const MemRegion *R = BufEnd.getAsRegion();
923
40
  if (!R)
924
0
    return true; // cf top comment.
925
40
926
40
  const ElementRegion *ER = dyn_cast<ElementRegion>(R);
927
40
  if (!ER)
928
0
    return true; // cf top comment.
929
40
930
40
  // FIXME: Does this crash when a non-standard definition
931
40
  // of a library function is encountered?
932
40
  assert(ER->getValueType() == C.getASTContext().CharTy &&
933
40
         "IsFirstBufInBound should only be called with char* ElementRegions");
934
40
935
40
  // Get the size of the array.
936
40
  const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
937
40
  DefinedOrUnknownSVal SizeDV = getDynamicSize(state, superReg, svalBuilder);
938
40
939
40
  // Get the index of the accessed element.
940
40
  DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
941
40
942
40
  ProgramStateRef StInBound = state->assumeInBound(Idx, SizeDV, true);
943
40
944
40
  return static_cast<bool>(StInBound);
945
40
}
946
947
ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
948
                                                 ProgramStateRef state,
949
                                                 const Expr *E, SVal V,
950
                                                 bool IsSourceBuffer,
951
859
                                                 const Expr *Size) {
952
859
  Optional<Loc> L = V.getAs<Loc>();
953
859
  if (!L)
954
0
    return state;
955
859
956
859
  // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
957
859
  // some assumptions about the value that CFRefCount can't. Even so, it should
958
859
  // probably be refactored.
959
859
  if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
960
853
    const MemRegion *R = MR->getRegion()->StripCasts();
961
853
962
853
    // Are we dealing with an ElementRegion?  If so, we should be invalidating
963
853
    // the super-region.
964
853
    if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
965
97
      R = ER->getSuperRegion();
966
97
      // FIXME: What about layers of ElementRegions?
967
97
    }
968
853
969
853
    // Invalidate this region.
970
853
    const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
971
853
972
853
    bool CausesPointerEscape = false;
973
853
    RegionAndSymbolInvalidationTraits ITraits;
974
853
    // Invalidate and escape only indirect regions accessible through the source
975
853
    // buffer.
976
853
    if (IsSourceBuffer) {
977
374
      ITraits.setTrait(R->getBaseRegion(),
978
374
                       RegionAndSymbolInvalidationTraits::TK_PreserveContents);
979
374
      ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
980
374
      CausesPointerEscape = true;
981
479
    } else {
982
479
      const MemRegion::Kind& K = R->getKind();
983
479
      if (K == MemRegion::FieldRegionKind)
984
42
        if (Size && IsFirstBufInBound(C, state, E, Size)) {
985
35
          // If destination buffer is a field region and access is in bound,
986
35
          // do not invalidate its super region.
987
35
          ITraits.setTrait(
988
35
              R,
989
35
              RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
990
35
        }
991
479
    }
992
853
993
853
    return state->invalidateRegions(R, E, C.blockCount(), LCtx,
994
853
                                    CausesPointerEscape, nullptr, nullptr,
995
853
                                    &ITraits);
996
853
  }
997
6
998
6
  // If we have a non-region value by chance, just remove the binding.
999
6
  // FIXME: is this necessary or correct? This handles the non-Region
1000
6
  //  cases.  Is it ever valid to store to these?
1001
6
  return state->killBinding(*L);
1002
6
}
1003
1004
bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
1005
36
                                     const MemRegion *MR) {
1006
36
  switch (MR->getKind()) {
1007
36
  case MemRegion::FunctionCodeRegionKind: {
1008
36
    if (const auto *FD = cast<FunctionCodeRegion>(MR)->getDecl())
1009
36
      os << "the address of the function '" << *FD << '\'';
1010
0
    else
1011
0
      os << "the address of a function";
1012
36
    return true;
1013
0
  }
1014
0
  case MemRegion::BlockCodeRegionKind:
1015
0
    os << "block text";
1016
0
    return true;
1017
0
  case MemRegion::BlockDataRegionKind:
1018
0
    os << "a block";
1019
0
    return true;
1020
0
  case MemRegion::CXXThisRegionKind:
1021
0
  case MemRegion::CXXTempObjectRegionKind:
1022
0
    os << "a C++ temp object of type "
1023
0
       << cast<TypedValueRegion>(MR)->getValueType().getAsString();
1024
0
    return true;
1025
0
  case MemRegion::VarRegionKind:
1026
0
    os << "a variable of type"
1027
0
       << cast<TypedValueRegion>(MR)->getValueType().getAsString();
1028
0
    return true;
1029
0
  case MemRegion::FieldRegionKind:
1030
0
    os << "a field of type "
1031
0
       << cast<TypedValueRegion>(MR)->getValueType().getAsString();
1032
0
    return true;
1033
0
  case MemRegion::ObjCIvarRegionKind:
1034
0
    os << "an instance variable of type "
1035
0
       << cast<TypedValueRegion>(MR)->getValueType().getAsString();
1036
0
    return true;
1037
0
  default:
1038
0
    return false;
1039
36
  }
1040
36
}
1041
1042
bool CStringChecker::memsetAux(const Expr *DstBuffer, SVal CharVal,
1043
                               const Expr *Size, CheckerContext &C,
1044
172
                               ProgramStateRef &State) {
1045
172
  SVal MemVal = C.getSVal(DstBuffer);
1046
172
  SVal SizeVal = C.getSVal(Size);
1047
172
  const MemRegion *MR = MemVal.getAsRegion();
1048
172
  if (!MR)
1049
0
    return false;
1050
172
1051
172
  // We're about to model memset by producing a "default binding" in the Store.
1052
172
  // Our current implementation - RegionStore - doesn't support default bindings
1053
172
  // that don't cover the whole base region. So we should first get the offset
1054
172
  // and the base region to figure out whether the offset of buffer is 0.
1055
172
  RegionOffset Offset = MR->getAsOffset();
1056
172
  const MemRegion *BR = Offset.getRegion();
1057
172
1058
172
  Optional<NonLoc> SizeNL = SizeVal.getAs<NonLoc>();
1059
172
  if (!SizeNL)
1060
0
    return false;
1061
172
1062
172
  SValBuilder &svalBuilder = C.getSValBuilder();
1063
172
  ASTContext &Ctx = C.getASTContext();
1064
172
1065
172
  // void *memset(void *dest, int ch, size_t count);
1066
172
  // For now we can only handle the case of offset is 0 and concrete char value.
1067
172
  if (Offset.isValid() && !Offset.hasSymbolicOffset() &&
1068
172
      
Offset.getOffset() == 0171
) {
1069
145
    // Get the base region's size.
1070
145
    DefinedOrUnknownSVal SizeDV = getDynamicSize(State, BR, svalBuilder);
1071
145
1072
145
    ProgramStateRef StateWholeReg, StateNotWholeReg;
1073
145
    std::tie(StateWholeReg, StateNotWholeReg) =
1074
145
        State->assume(svalBuilder.evalEQ(State, SizeDV, *SizeNL));
1075
145
1076
145
    // With the semantic of 'memset()', we should convert the CharVal to
1077
145
    // unsigned char.
1078
145
    CharVal = svalBuilder.evalCast(CharVal, Ctx.UnsignedCharTy, Ctx.IntTy);
1079
145
1080
145
    ProgramStateRef StateNullChar, StateNonNullChar;
1081
145
    std::tie(StateNullChar, StateNonNullChar) =
1082
145
        assumeZero(C, State, CharVal, Ctx.UnsignedCharTy);
1083
145
1084
145
    if (StateWholeReg && 
!StateNotWholeReg113
&&
StateNullChar113
&&
1085
145
        
!StateNonNullChar91
) {
1086
91
      // If the 'memset()' acts on the whole region of destination buffer and
1087
91
      // the value of the second argument of 'memset()' is zero, bind the second
1088
91
      // argument's value to the destination buffer with 'default binding'.
1089
91
      // FIXME: Since there is no perfect way to bind the non-zero character, we
1090
91
      // can only deal with zero value here. In the future, we need to deal with
1091
91
      // the binding of non-zero value in the case of whole region.
1092
91
      State = State->bindDefaultZero(svalBuilder.makeLoc(BR),
1093
91
                                     C.getLocationContext());
1094
91
    } else {
1095
54
      // If the destination buffer's extent is not equal to the value of
1096
54
      // third argument, just invalidate buffer.
1097
54
      State = InvalidateBuffer(C, State, DstBuffer, MemVal,
1098
54
                               /*IsSourceBuffer*/ false, Size);
1099
54
    }
1100
145
1101
145
    if (StateNullChar && 
!StateNonNullChar116
) {
1102
116
      // If the value of the second argument of 'memset()' is zero, set the
1103
116
      // string length of destination buffer to 0 directly.
1104
116
      State = setCStringLength(State, MR,
1105
116
                               svalBuilder.makeZeroVal(Ctx.getSizeType()));
1106
116
    } else 
if (29
!StateNullChar29
&&
StateNonNullChar29
) {
1107
29
      SVal NewStrLen = svalBuilder.getMetadataSymbolVal(
1108
29
          CStringChecker::getTag(), MR, DstBuffer, Ctx.getSizeType(),
1109
29
          C.getLocationContext(), C.blockCount());
1110
29
1111
29
      // If the value of second argument is not zero, then the string length
1112
29
      // is at least the size argument.
1113
29
      SVal NewStrLenGESize = svalBuilder.evalBinOp(
1114
29
          State, BO_GE, NewStrLen, SizeVal, svalBuilder.getConditionType());
1115
29
1116
29
      State = setCStringLength(
1117
29
          State->assume(NewStrLenGESize.castAs<DefinedOrUnknownSVal>(), true),
1118
29
          MR, NewStrLen);
1119
29
    }
1120
145
  } else {
1121
27
    // If the offset is not zero and char value is not concrete, we can do
1122
27
    // nothing but invalidate the buffer.
1123
27
    State = InvalidateBuffer(C, State, DstBuffer, MemVal,
1124
27
                             /*IsSourceBuffer*/ false, Size);
1125
27
  }
1126
172
  return true;
1127
172
}
1128
1129
//===----------------------------------------------------------------------===//
1130
// evaluation of individual function calls.
1131
//===----------------------------------------------------------------------===//
1132
1133
void CStringChecker::evalCopyCommon(CheckerContext &C,
1134
                                    const CallExpr *CE,
1135
                                    ProgramStateRef state,
1136
                                    const Expr *Size, const Expr *Dest,
1137
                                    const Expr *Source, bool Restricted,
1138
256
                                    bool IsMempcpy) const {
1139
256
  CurrentFunctionDescription = "memory copy function";
1140
256
1141
256
  // See if the size argument is zero.
1142
256
  const LocationContext *LCtx = C.getLocationContext();
1143
256
  SVal sizeVal = state->getSVal(Size, LCtx);
1144
256
  QualType sizeTy = Size->getType();
1145
256
1146
256
  ProgramStateRef stateZeroSize, stateNonZeroSize;
1147
256
  std::tie(stateZeroSize, stateNonZeroSize) =
1148
256
    assumeZero(C, state, sizeVal, sizeTy);
1149
256
1150
256
  // Get the value of the Dest.
1151
256
  SVal destVal = state->getSVal(Dest, LCtx);
1152
256
1153
256
  // If the size is zero, there won't be any actual memory access, so
1154
256
  // just bind the return value to the destination buffer and return.
1155
256
  if (stateZeroSize && 
!stateNonZeroSize48
) {
1156
16
    stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
1157
16
    C.addTransition(stateZeroSize);
1158
16
    return;
1159
16
  }
1160
240
1161
240
  // If the size can be nonzero, we have to check the other arguments.
1162
240
  if (stateNonZeroSize) {
1163
240
    state = stateNonZeroSize;
1164
240
1165
240
    // Ensure the destination is not null. If it is NULL there will be a
1166
240
    // NULL pointer dereference.
1167
240
    state = checkNonNull(C, state, Dest, destVal, 1);
1168
240
    if (!state)
1169
14
      return;
1170
226
1171
226
    // Get the value of the Src.
1172
226
    SVal srcVal = state->getSVal(Source, LCtx);
1173
226
1174
226
    // Ensure the source is not null. If it is NULL there will be a
1175
226
    // NULL pointer dereference.
1176
226
    state = checkNonNull(C, state, Source, srcVal, 2);
1177
226
    if (!state)
1178
16
      return;
1179
210
1180
210
    // Ensure the accesses are valid and that the buffers do not overlap.
1181
210
    const char * const writeWarning =
1182
210
      "Memory copy function overflows destination buffer";
1183
210
    state = CheckBufferAccess(C, state, Size, Dest, Source,
1184
210
                              writeWarning, /* sourceWarning = */ nullptr);
1185
210
    if (Restricted)
1186
182
      state = CheckOverlap(C, state, Size, Dest, Source);
1187
210
1188
210
    if (!state)
1189
76
      return;
1190
134
1191
134
    // If this is mempcpy, get the byte after the last byte copied and
1192
134
    // bind the expr.
1193
134
    if (IsMempcpy) {
1194
41
      // Get the byte after the last byte copied.
1195
41
      SValBuilder &SvalBuilder = C.getSValBuilder();
1196
41
      ASTContext &Ctx = SvalBuilder.getContext();
1197
41
      QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
1198
41
      SVal DestRegCharVal =
1199
41
          SvalBuilder.evalCast(destVal, CharPtrTy, Dest->getType());
1200
41
      SVal lastElement = C.getSValBuilder().evalBinOp(
1201
41
          state, BO_Add, DestRegCharVal, sizeVal, Dest->getType());
1202
41
      // If we don't know how much we copied, we can at least
1203
41
      // conjure a return value for later.
1204
41
      if (lastElement.isUnknown())
1205
9
        lastElement = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1206
9
                                                          C.blockCount());
1207
41
1208
41
      // The byte after the last byte copied is the return value.
1209
41
      state = state->BindExpr(CE, LCtx, lastElement);
1210
93
    } else {
1211
93
      // All other copies return the destination buffer.
1212
93
      // (Well, bcopy() has a void return type, but this won't hurt.)
1213
93
      state = state->BindExpr(CE, LCtx, destVal);
1214
93
    }
1215
134
1216
134
    // Invalidate the destination (regular invalidation without pointer-escaping
1217
134
    // the address of the top-level region).
1218
134
    // FIXME: Even if we can't perfectly model the copy, we should see if we
1219
134
    // can use LazyCompoundVals to copy the source values into the destination.
1220
134
    // This would probably remove any existing bindings past the end of the
1221
134
    // copied region, but that's still an improvement over blank invalidation.
1222
134
    state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest),
1223
134
                             /*IsSourceBuffer*/false, Size);
1224
134
1225
134
    // Invalidate the source (const-invalidation without const-pointer-escaping
1226
134
    // the address of the top-level region).
1227
134
    state = InvalidateBuffer(C, state, Source, C.getSVal(Source),
1228
134
                             /*IsSourceBuffer*/true, nullptr);
1229
134
1230
134
    C.addTransition(state);
1231
134
  }
1232
240
}
1233
1234
1235
139
void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
1236
139
  // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
1237
139
  // The return value is the address of the destination buffer.
1238
139
  const Expr *Dest = CE->getArg(0);
1239
139
  ProgramStateRef state = C.getState();
1240
139
1241
139
  evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
1242
139
}
1243
1244
89
void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
1245
89
  // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1246
89
  // The return value is a pointer to the byte following the last written byte.
1247
89
  const Expr *Dest = CE->getArg(0);
1248
89
  ProgramStateRef state = C.getState();
1249
89
1250
89
  evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
1251
89
}
1252
1253
16
void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
1254
16
  // void *memmove(void *dst, const void *src, size_t n);
1255
16
  // The return value is the address of the destination buffer.
1256
16
  const Expr *Dest = CE->getArg(0);
1257
16
  ProgramStateRef state = C.getState();
1258
16
1259
16
  evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
1260
16
}
1261
1262
12
void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
1263
12
  // void bcopy(const void *src, void *dst, size_t n);
1264
12
  evalCopyCommon(C, CE, C.getState(),
1265
12
                 CE->getArg(2), CE->getArg(1), CE->getArg(0));
1266
12
}
1267
1268
54
void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
1269
54
  // int memcmp(const void *s1, const void *s2, size_t n);
1270
54
  CurrentFunctionDescription = "memory comparison function";
1271
54
1272
54
  const Expr *Left = CE->getArg(0);
1273
54
  const Expr *Right = CE->getArg(1);
1274
54
  const Expr *Size = CE->getArg(2);
1275
54
1276
54
  ProgramStateRef state = C.getState();
1277
54
  SValBuilder &svalBuilder = C.getSValBuilder();
1278
54
1279
54
  // See if the size argument is zero.
1280
54
  const LocationContext *LCtx = C.getLocationContext();
1281
54
  SVal sizeVal = state->getSVal(Size, LCtx);
1282
54
  QualType sizeTy = Size->getType();
1283
54
1284
54
  ProgramStateRef stateZeroSize, stateNonZeroSize;
1285
54
  std::tie(stateZeroSize, stateNonZeroSize) =
1286
54
    assumeZero(C, state, sizeVal, sizeTy);
1287
54
1288
54
  // If the size can be zero, the result will be 0 in that case, and we don't
1289
54
  // have to check either of the buffers.
1290
54
  if (stateZeroSize) {
1291
28
    state = stateZeroSize;
1292
28
    state = state->BindExpr(CE, LCtx,
1293
28
                            svalBuilder.makeZeroVal(CE->getType()));
1294
28
    C.addTransition(state);
1295
28
  }
1296
54
1297
54
  // If the size can be nonzero, we have to check the other arguments.
1298
54
  if (stateNonZeroSize) {
1299
38
    state = stateNonZeroSize;
1300
38
    // If we know the two buffers are the same, we know the result is 0.
1301
38
    // First, get the two buffers' addresses. Another checker will have already
1302
38
    // made sure they're not undefined.
1303
38
    DefinedOrUnknownSVal LV =
1304
38
        state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
1305
38
    DefinedOrUnknownSVal RV =
1306
38
        state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
1307
38
1308
38
    // See if they are the same.
1309
38
    DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1310
38
    ProgramStateRef StSameBuf, StNotSameBuf;
1311
38
    std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1312
38
1313
38
    // If the two arguments are the same buffer, we know the result is 0,
1314
38
    // and we only need to check one size.
1315
38
    if (StSameBuf && 
!StNotSameBuf22
) {
1316
6
      state = StSameBuf;
1317
6
      state = CheckBufferAccess(C, state, Size, Left);
1318
6
      if (state) {
1319
6
        state = StSameBuf->BindExpr(CE, LCtx,
1320
6
                                    svalBuilder.makeZeroVal(CE->getType()));
1321
6
        C.addTransition(state);
1322
6
      }
1323
6
      return;
1324
6
    }
1325
32
1326
32
    // If the two arguments might be different buffers, we have to check
1327
32
    // the size of both of them.
1328
32
    assert(StNotSameBuf);
1329
32
    state = CheckBufferAccess(C, state, Size, Left, Right);
1330
32
    if (state) {
1331
20
      // The return value is the comparison result, which we don't know.
1332
20
      SVal CmpV =
1333
20
          svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
1334
20
      state = state->BindExpr(CE, LCtx, CmpV);
1335
20
      C.addTransition(state);
1336
20
    }
1337
32
  }
1338
54
}
1339
1340
void CStringChecker::evalstrLength(CheckerContext &C,
1341
578
                                   const CallExpr *CE) const {
1342
578
  // size_t strlen(const char *s);
1343
578
  evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1344
578
}
1345
1346
void CStringChecker::evalstrnLength(CheckerContext &C,
1347
108
                                    const CallExpr *CE) const {
1348
108
  // size_t strnlen(const char *s, size_t maxlen);
1349
108
  evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1350
108
}
1351
1352
void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
1353
686
                                         bool IsStrnlen) const {
1354
686
  CurrentFunctionDescription = "string length function";
1355
686
  ProgramStateRef state = C.getState();
1356
686
  const LocationContext *LCtx = C.getLocationContext();
1357
686
1358
686
  if (IsStrnlen) {
1359
108
    const Expr *maxlenExpr = CE->getArg(1);
1360
108
    SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1361
108
1362
108
    ProgramStateRef stateZeroSize, stateNonZeroSize;
1363
108
    std::tie(stateZeroSize, stateNonZeroSize) =
1364
108
      assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1365
108
1366
108
    // If the size can be zero, the result will be 0 in that case, and we don't
1367
108
    // have to check the string itself.
1368
108
    if (stateZeroSize) {
1369
20
      SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
1370
20
      stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
1371
20
      C.addTransition(stateZeroSize);
1372
20
    }
1373
108
1374
108
    // If the size is GUARANTEED to be zero, we're done!
1375
108
    if (!stateNonZeroSize)
1376
10
      return;
1377
98
1378
98
    // Otherwise, record the assumption that the size is nonzero.
1379
98
    state = stateNonZeroSize;
1380
98
  }
1381
686
1382
686
  // Check that the string argument is non-null.
1383
686
  const Expr *Arg = CE->getArg(0);
1384
676
  SVal ArgVal = state->getSVal(Arg, LCtx);
1385
676
1386
676
  state = checkNonNull(C, state, Arg, ArgVal, 1);
1387
676
1388
676
  if (!state)
1389
10
    return;
1390
666
1391
666
  SVal strLength = getCStringLength(C, state, Arg, ArgVal);
1392
666
1393
666
  // If the argument isn't a valid C string, there's no valid state to
1394
666
  // transition to.
1395
666
  if (strLength.isUndef())
1396
21
    return;
1397
645
1398
645
  DefinedOrUnknownSVal result = UnknownVal();
1399
645
1400
645
  // If the check is for strnlen() then bind the return value to no more than
1401
645
  // the maxlen value.
1402
645
  if (IsStrnlen) {
1403
83
    QualType cmpTy = C.getSValBuilder().getConditionType();
1404
83
1405
83
    // It's a little unfortunate to be getting this again,
1406
83
    // but it's not that expensive...
1407
83
    const Expr *maxlenExpr = CE->getArg(1);
1408
83
    SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1409
83
1410
83
    Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1411
83
    Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
1412
83
1413
83
    if (strLengthNL && 
maxlenValNL78
) {
1414
73
      ProgramStateRef stateStringTooLong, stateStringNotTooLong;
1415
73
1416
73
      // Check if the strLength is greater than the maxlen.
1417
73
      std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
1418
73
          C.getSValBuilder()
1419
73
              .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1420
73
              .castAs<DefinedOrUnknownSVal>());
1421
73
1422
73
      if (stateStringTooLong && 
!stateStringNotTooLong58
) {
1423
15
        // If the string is longer than maxlen, return maxlen.
1424
15
        result = *maxlenValNL;
1425
58
      } else if (stateStringNotTooLong && !stateStringTooLong) {
1426
15
        // If the string is shorter than maxlen, return its length.
1427
15
        result = *strLengthNL;
1428
15
      }
1429
73
    }
1430
83
1431
83
    if (result.isUnknown()) {
1432
53
      // If we don't have enough information for a comparison, there's
1433
53
      // no guarantee the full string length will actually be returned.
1434
53
      // All we know is the return value is the min of the string length
1435
53
      // and the limit. This is better than nothing.
1436
53
      result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1437
53
                                                   C.blockCount());
1438
53
      NonLoc resultNL = result.castAs<NonLoc>();
1439
53
1440
53
      if (strLengthNL) {
1441
48
        state = state->assume(C.getSValBuilder().evalBinOpNN(
1442
48
                                  state, BO_LE, resultNL, *strLengthNL, cmpTy)
1443
48
                                  .castAs<DefinedOrUnknownSVal>(), true);
1444
48
      }
1445
53
1446
53
      if (maxlenValNL) {
1447
48
        state = state->assume(C.getSValBuilder().evalBinOpNN(
1448
48
                                  state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1449
48
                                  .castAs<DefinedOrUnknownSVal>(), true);
1450
48
      }
1451
53
    }
1452
83
1453
562
  } else {
1454
562
    // This is a plain strlen(), not strnlen().
1455
562
    result = strLength.castAs<DefinedOrUnknownSVal>();
1456
562
1457
562
    // If we don't know the length of the string, conjure a return
1458
562
    // value, so it can be used in constraints, at least.
1459
562
    if (result.isUnknown()) {
1460
2
      result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1461
2
                                                   C.blockCount());
1462
2
    }
1463
562
  }
1464
645
1465
645
  // Bind the return value.
1466
645
  assert(!result.isUnknown() && "Should have conjured a value by now");
1467
645
  state = state->BindExpr(CE, LCtx, result);
1468
645
  C.addTransition(state);
1469
645
}
1470
1471
48
void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
1472
48
  // char *strcpy(char *restrict dst, const char *restrict src);
1473
48
  evalStrcpyCommon(C, CE,
1474
48
                   /* ReturnEnd = */ false,
1475
48
                   /* IsBounded = */ false,
1476
48
                   /* appendK = */ ConcatFnKind::none);
1477
48
}
1478
1479
67
void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
1480
67
  // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
1481
67
  evalStrcpyCommon(C, CE,
1482
67
                   /* ReturnEnd = */ false,
1483
67
                   /* IsBounded = */ true,
1484
67
                   /* appendK = */ ConcatFnKind::none);
1485
67
}
1486
1487
14
void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
1488
14
  // char *stpcpy(char *restrict dst, const char *restrict src);
1489
14
  evalStrcpyCommon(C, CE,
1490
14
                   /* ReturnEnd = */ true,
1491
14
                   /* IsBounded = */ false,
1492
14
                   /* appendK = */ ConcatFnKind::none);
1493
14
}
1494
1495
75
void CStringChecker::evalStrlcpy(CheckerContext &C, const CallExpr *CE) const {
1496
75
  // size_t strlcpy(char *dest, const char *src, size_t size);
1497
75
  evalStrcpyCommon(C, CE,
1498
75
                   /* ReturnEnd = */ true,
1499
75
                   /* IsBounded = */ true,
1500
75
                   /* appendK = */ ConcatFnKind::none,
1501
75
                   /* returnPtr = */ false);
1502
75
}
1503
1504
57
void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
1505
57
  // char *strcat(char *restrict s1, const char *restrict s2);
1506
57
  evalStrcpyCommon(C, CE,
1507
57
                   /* ReturnEnd = */ false,
1508
57
                   /* IsBounded = */ false,
1509
57
                   /* appendK = */ ConcatFnKind::strcat);
1510
57
}
1511
1512
107
void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
1513
107
  //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1514
107
  evalStrcpyCommon(C, CE,
1515
107
                   /* ReturnEnd = */ false,
1516
107
                   /* IsBounded = */ true,
1517
107
                   /* appendK = */ ConcatFnKind::strcat);
1518
107
}
1519
1520
42
void CStringChecker::evalStrlcat(CheckerContext &C, const CallExpr *CE) const {
1521
42
  // size_t strlcat(char *dst, const char *src, size_t size);
1522
42
  // It will append at most size - strlen(dst) - 1 bytes,
1523
42
  // NULL-terminating the result.
1524
42
  evalStrcpyCommon(C, CE,
1525
42
                   /* ReturnEnd = */ false,
1526
42
                   /* IsBounded = */ true,
1527
42
                   /* appendK = */ ConcatFnKind::strlcat,
1528
42
                   /* returnPtr = */ false);
1529
42
}
1530
1531
void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
1532
                                      bool ReturnEnd, bool IsBounded,
1533
                                      ConcatFnKind appendK,
1534
410
                                      bool returnPtr) const {
1535
410
  if (appendK == ConcatFnKind::none)
1536
204
    CurrentFunctionDescription = "string copy function";
1537
206
  else
1538
206
    CurrentFunctionDescription = "string concatenation function";
1539
410
  ProgramStateRef state = C.getState();
1540
410
  const LocationContext *LCtx = C.getLocationContext();
1541
410
1542
410
  // Check that the destination is non-null.
1543
410
  const Expr *Dst = CE->getArg(0);
1544
410
  SVal DstVal = state->getSVal(Dst, LCtx);
1545
410
1546
410
  state = checkNonNull(C, state, Dst, DstVal, 1);
1547
410
  if (!state)
1548
23
    return;
1549
387
1550
387
  // Check that the source is non-null.
1551
387
  const Expr *srcExpr = CE->getArg(1);
1552
387
  SVal srcVal = state->getSVal(srcExpr, LCtx);
1553
387
  state = checkNonNull(C, state, srcExpr, srcVal, 2);
1554
387
  if (!state)
1555
20
    return;
1556
367
1557
367
  // Get the string length of the source.
1558
367
  SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
1559
367
  Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1560
367
1561
367
  // Get the string length of the destination buffer.
1562
367
  SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1563
367
  Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
1564
367
1565
367
  // If the source isn't a valid C string, give up.
1566
367
  if (strLength.isUndef())
1567
25
    return;
1568
342
1569
342
  SValBuilder &svalBuilder = C.getSValBuilder();
1570
342
  QualType cmpTy = svalBuilder.getConditionType();
1571
342
  QualType sizeTy = svalBuilder.getContext().getSizeType();
1572
342
1573
342
  // These two values allow checking two kinds of errors:
1574
342
  // - actual overflows caused by a source that doesn't fit in the destination
1575
342
  // - potential overflows caused by a bound that could exceed the destination
1576
342
  SVal amountCopied = UnknownVal();
1577
342
  SVal maxLastElementIndex = UnknownVal();
1578
342
  const char *boundWarning = nullptr;
1579
342
1580
342
  state = CheckOverlap(C, state, IsBounded ? 
CE->getArg(2)259
:
CE->getArg(1)83
, Dst,
1581
342
                       srcExpr);
1582
342
1583
342
  if (!state)
1584
1
    return;
1585
341
1586
341
  // If the function is strncpy, strncat, etc... it is bounded.
1587
341
  if (IsBounded) {
1588
258
    // Get the max number of characters to copy.
1589
258
    const Expr *lenExpr = CE->getArg(2);
1590
258
    SVal lenVal = state->getSVal(lenExpr, LCtx);
1591
258
1592
258
    // Protect against misdeclared strncpy().
1593
258
    lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
1594
258
1595
258
    Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
1596
258
1597
258
    // If we know both values, we might be able to figure out how much
1598
258
    // we're copying.
1599
258
    if (strLengthNL && 
lenValNL248
) {
1600
235
      switch (appendK) {
1601
200
      case ConcatFnKind::none:
1602
200
      case ConcatFnKind::strcat: {
1603
200
        ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
1604
200
        // Check if the max number to copy is less than the length of the src.
1605
200
        // If the bound is equal to the source length, strncpy won't null-
1606
200
        // terminate the result!
1607
200
        std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
1608
200
            svalBuilder
1609
200
                .evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1610
200
                .castAs<DefinedOrUnknownSVal>());
1611
200
1612
200
        if (stateSourceTooLong && 
!stateSourceNotTooLong153
) {
1613
83
          // Max number to copy is less than the length of the src, so the
1614
83
          // actual strLength copied is the max number arg.
1615
83
          state = stateSourceTooLong;
1616
83
          amountCopied = lenVal;
1617
83
1618
117
        } else if (!stateSourceTooLong && 
stateSourceNotTooLong47
) {
1619
47
          // The source buffer entirely fits in the bound.
1620
47
          state = stateSourceNotTooLong;
1621
47
          amountCopied = strLength;
1622
47
        }
1623
200
        break;
1624
200
      }
1625
200
      case ConcatFnKind::strlcat:
1626
35
        if (!dstStrLengthNL)
1627
4
          return;
1628
31
1629
31
        // amountCopied = min (size - dstLen - 1 , srcLen)
1630
31
        SVal freeSpace = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1631
31
                                                 *dstStrLengthNL, sizeTy);
1632
31
        if (!freeSpace.getAs<NonLoc>())
1633
0
          return;
1634
31
        freeSpace =
1635
31
            svalBuilder.evalBinOp(state, BO_Sub, freeSpace,
1636
31
                                  svalBuilder.makeIntVal(1, sizeTy), sizeTy);
1637
31
        Optional<NonLoc> freeSpaceNL = freeSpace.getAs<NonLoc>();
1638
31
1639
31
        // While unlikely, it is possible that the subtraction is
1640
31
        // too complex to compute, let's check whether it succeeded.
1641
31
        if (!freeSpaceNL)
1642
0
          return;
1643
31
        SVal hasEnoughSpace = svalBuilder.evalBinOpNN(
1644
31
            state, BO_LE, *strLengthNL, *freeSpaceNL, cmpTy);
1645
31
1646
31
        ProgramStateRef TrueState, FalseState;
1647
31
        std::tie(TrueState, FalseState) =
1648
31
            state->assume(hasEnoughSpace.castAs<DefinedOrUnknownSVal>());
1649
31
1650
31
        // srcStrLength <= size - dstStrLength -1
1651
31
        if (TrueState && 
!FalseState23
) {
1652
14
          amountCopied = strLength;
1653
14
        }
1654
31
1655
31
        // srcStrLength > size - dstStrLength -1
1656
31
        if (!TrueState && 
FalseState8
) {
1657
8
          amountCopied = freeSpace;
1658
8
        }
1659
31
1660
31
        if (TrueState && 
FalseState23
)
1661
9
          amountCopied = UnknownVal();
1662
31
        break;
1663
235
      }
1664
235
    }
1665
254
    // We still want to know if the bound is known to be too large.
1666
254
    if (lenValNL) {
1667
241
      switch (appendK) {
1668
87
      case ConcatFnKind::strcat:
1669
87
        // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1670
87
1671
87
        // Get the string length of the destination. If the destination is
1672
87
        // memory that can't have a string length, we shouldn't be copying
1673
87
        // into it anyway.
1674
87
        if (dstStrLength.isUndef())
1675
0
          return;
1676
87
1677
87
        if (dstStrLengthNL) {
1678
87
          maxLastElementIndex = svalBuilder.evalBinOpNN(
1679
87
              state, BO_Add, *lenValNL, *dstStrLengthNL, sizeTy);
1680
87
1681
87
          boundWarning = "Size argument is greater than the free space in the "
1682
87
                         "destination buffer";
1683
87
        }
1684
87
        break;
1685
154
      case ConcatFnKind::none:
1686
154
      case ConcatFnKind::strlcat:
1687
154
        // For strncpy and strlcat, this is just checking
1688
154
        //  that lenVal <= sizeof(dst).
1689
154
        // (Yes, strncpy and strncat differ in how they treat termination.
1690
154
        // strncat ALWAYS terminates, but strncpy doesn't.)
1691
154
1692
154
        // We need a special case for when the copy size is zero, in which
1693
154
        // case strncpy will do no work at all. Our bounds check uses n-1
1694
154
        // as the last element accessed, so n == 0 is problematic.
1695
154
        ProgramStateRef StateZeroSize, StateNonZeroSize;
1696
154
        std::tie(StateZeroSize, StateNonZeroSize) =
1697
154
            assumeZero(C, state, *lenValNL, sizeTy);
1698
154
1699
154
        // If the size is known to be zero, we're done.
1700
154
        if (StateZeroSize && 
!StateNonZeroSize14
) {
1701
9
          if (returnPtr) {
1702
5
            StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1703
5
          } else {
1704
4
            if (appendK == ConcatFnKind::none) {
1705
2
              // strlcpy returns strlen(src)
1706
2
              StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, strLength);
1707
2
            } else {
1708
2
              // strlcat returns strlen(src) + strlen(dst)
1709
2
              SVal retSize = svalBuilder.evalBinOp(
1710
2
                  state, BO_Add, strLength, dstStrLength, sizeTy);
1711
2
              StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, retSize);
1712
2
            }
1713
4
          }
1714
9
          C.addTransition(StateZeroSize);
1715
9
          return;
1716
9
        }
1717
145
1718
145
        // Otherwise, go ahead and figure out the last element we'll touch.
1719
145
        // We don't record the non-zero assumption here because we can't
1720
145
        // be sure. We won't warn on a possible zero.
1721
145
        NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
1722
145
        maxLastElementIndex =
1723
145
            svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL, one, sizeTy);
1724
145
        boundWarning = "Size argument is greater than the length of the "
1725
145
                       "destination buffer";
1726
145
        break;
1727
241
      }
1728
241
    }
1729
83
  } else {
1730
83
    // The function isn't bounded. The amount copied should match the length
1731
83
    // of the source buffer.
1732
83
    amountCopied = strLength;
1733
83
  }
1734
341
1735
341
  assert(state);
1736
328
1737
328
  // This represents the number of characters copied into the destination
1738
328
  // buffer. (It may not actually be the strlen if the destination buffer
1739
328
  // is not terminated.)
1740
328
  SVal finalStrLength = UnknownVal();
1741
328
  SVal strlRetVal = UnknownVal();
1742
328
1743
328
  if (appendK == ConcatFnKind::none && 
!returnPtr159
) {
1744
71
    // strlcpy returns the sizeof(src)
1745
71
    strlRetVal = strLength;
1746
71
  }
1747
328
1748
328
  // If this is an appending function (strcat, strncat...) then set the
1749
328
  // string length to strlen(src) + strlen(dst) since the buffer will
1750
328
  // ultimately contain both.
1751
328
  if (appendK != ConcatFnKind::none) {
1752
169
    // Get the string length of the destination. If the destination is memory
1753
169
    // that can't have a string length, we shouldn't be copying into it anyway.
1754
169
    if (dstStrLength.isUndef())
1755
0
      return;
1756
169
1757
169
    if (appendK == ConcatFnKind::strlcat && 
dstStrLengthNL35
&&
strLengthNL34
) {
1758
34
      strlRetVal = svalBuilder.evalBinOpNN(state, BO_Add, *strLengthNL,
1759
34
                                           *dstStrLengthNL, sizeTy);
1760
34
    }
1761
169
1762
169
    Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>();
1763
169
1764
169
    // If we know both string lengths, we might know the final string length.
1765
169
    if (amountCopiedNL && 
dstStrLengthNL116
) {
1766
116
      // Make sure the two lengths together don't overflow a size_t.
1767
116
      state = checkAdditionOverflow(C, state, *amountCopiedNL, *dstStrLengthNL);
1768
116
      if (!state)
1769
0
        return;
1770
116
1771
116
      finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *amountCopiedNL,
1772
116
                                               *dstStrLengthNL, sizeTy);
1773
116
    }
1774
169
1775
169
    // If we couldn't get a single value for the final string length,
1776
169
    // we can at least bound it by the individual lengths.
1777
169
    if (finalStrLength.isUnknown()) {
1778
53
      // Try to get a "hypothetical" string length symbol, which we can later
1779
53
      // set as a real value if that turns out to be the case.
1780
53
      finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1781
53
      assert(!finalStrLength.isUndef());
1782
53
1783
53
      if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
1784
52
        if (amountCopiedNL && 
appendK == ConcatFnKind::none0
) {
1785
0
          // we overwrite dst string with the src
1786
0
          // finalStrLength >= srcStrLength
1787
0
          SVal sourceInResult = svalBuilder.evalBinOpNN(
1788
0
              state, BO_GE, *finalStrLengthNL, *amountCopiedNL, cmpTy);
1789
0
          state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
1790
0
                                true);
1791
0
          if (!state)
1792
0
            return;
1793
52
        }
1794
52
1795
52
        if (dstStrLengthNL && appendK != ConcatFnKind::none) {
1796
52
          // we extend the dst string with the src
1797
52
          // finalStrLength >= dstStrLength
1798
52
          SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1799
52
                                                      *finalStrLengthNL,
1800
52
                                                      *dstStrLengthNL,
1801
52
                                                      cmpTy);
1802
52
          state =
1803
52
              state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
1804
52
          if (!state)
1805
0
            return;
1806
159
        }
1807
52
      }
1808
53
    }
1809
159
1810
159
  } else {
1811
159
    // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1812
159
    // the final string length will match the input string length.
1813
159
    finalStrLength = amountCopied;
1814
159
  }
1815
328
1816
328
  SVal Result;
1817
328
1818
328
  if (returnPtr) {
1819
222
    // The final result of the function will either be a pointer past the last
1820
222
    // copied element, or a pointer to the start of the destination buffer.
1821
222
    Result = (ReturnEnd ? 
UnknownVal()14
:
DstVal208
);
1822
222
  } else {
1823
106
    if (appendK == ConcatFnKind::strlcat || 
appendK == ConcatFnKind::none71
)
1824
106
      //strlcpy, strlcat
1825
106
      Result = strlRetVal;
1826
0
    else
1827
0
      Result = finalStrLength;
1828
106
  }
1829
328
1830
328
  assert(state);
1831
328
1832
328
  // If the destination is a MemRegion, try to check for a buffer overflow and
1833
328
  // record the new string length.
1834
328
  if (Optional<loc::MemRegionVal> dstRegVal =
1835
328
      DstVal.getAs<loc::MemRegionVal>()) {
1836
328
    QualType ptrTy = Dst->getType();
1837
328
1838
328
    // If we have an exact value on a bounded copy, use that to check for
1839
328
    // overflows, rather than our estimate about how much is actually copied.
1840
328
    if (boundWarning) {
1841
232
      if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
1842
230
        SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1843
230
            *maxLastNL, ptrTy);
1844
230
        state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1845
230
            boundWarning);
1846
230
        if (!state)
1847
68
          return;
1848
260
      }
1849
232
    }
1850
260
1851
260
    // Then, if the final length is known...
1852
260
    if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
1853
219
      SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1854
219
          *knownStrLength, ptrTy);
1855
219
1856
219
      // ...and we haven't checked the bound, we'll check the actual copy.
1857
219
      if (!boundWarning) {
1858
92
        const char * const warningMsg =
1859
92
          "String copy function overflows destination buffer";
1860
92
        state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1861
92
        if (!state)
1862
20
          return;
1863
199
      }
1864
199
1865
199
      // If this is a stpcpy-style copy, the last element is the return value.
1866
199
      if (returnPtr && 
ReturnEnd147
)
1867
10
        Result = lastElement;
1868
199
    }
1869
260
1870
260
    // Invalidate the destination (regular invalidation without pointer-escaping
1871
260
    // the address of the top-level region). This must happen before we set the
1872
260
    // C string length because invalidation will clear the length.
1873
260
    // FIXME: Even if we can't perfectly model the copy, we should see if we
1874
260
    // can use LazyCompoundVals to copy the source values into the destination.
1875
260
    // This would probably remove any existing bindings past the end of the
1876
260
    // string, but that's still an improvement over blank invalidation.
1877
260
    state = InvalidateBuffer(C, state, Dst, *dstRegVal,
1878
240
        /*IsSourceBuffer*/false, nullptr);
1879
240
1880
240
    // Invalidate the source (const-invalidation without const-pointer-escaping
1881
240
    // the address of the top-level region).
1882
240
    state = InvalidateBuffer(C, state, srcExpr, srcVal, /*IsSourceBuffer*/true,
1883
240
        nullptr);
1884
240
1885
240
    // Set the C string length of the destination, if we know it.
1886
240
    if (IsBounded && 
(appendK == ConcatFnKind::none)177
) {
1887
88
      // strncpy is annoying in that it doesn't guarantee to null-terminate
1888
88
      // the result string. If the original string didn't fit entirely inside
1889
88
      // the bound (including the null-terminator), we don't know how long the
1890
88
      // result is.
1891
88
      if (amountCopied != strLength)
1892
55
        finalStrLength = UnknownVal();
1893
88
    }
1894
240
    state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
1895
240
  }
1896
328
1897
328
  assert(state);
1898
240
1899
240
  if (returnPtr) {
1900
157
    // If this is a stpcpy-style copy, but we were unable to check for a buffer
1901
157
    // overflow, we still need a result. Conjure a return value.
1902
157
    if (ReturnEnd && 
Result.isUnknown()10
) {
1903
0
      Result = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
1904
0
    }
1905
157
  }
1906
240
  // Set the return value.
1907
240
  state = state->BindExpr(CE, LCtx, Result);
1908
240
  C.addTransition(state);
1909
240
}
1910
1911
111
void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1912
111
  //int strcmp(const char *s1, const char *s2);
1913
111
  evalStrcmpCommon(C, CE, /* IsBounded = */ false, /* IgnoreCase = */ false);
1914
111
}
1915
1916
115
void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
1917
115
  //int strncmp(const char *s1, const char *s2, size_t n);
1918
115
  evalStrcmpCommon(C, CE, /* IsBounded = */ true, /* IgnoreCase = */ false);
1919
115
}
1920
1921
void CStringChecker::evalStrcasecmp(CheckerContext &C,
1922
100
    const CallExpr *CE) const {
1923
100
  //int strcasecmp(const char *s1, const char *s2);
1924
100
  evalStrcmpCommon(C, CE, /* IsBounded = */ false, /* IgnoreCase = */ true);
1925
100
}
1926
1927
void CStringChecker::evalStrncasecmp(CheckerContext &C,
1928
115
    const CallExpr *CE) const {
1929
115
  //int strncasecmp(const char *s1, const char *s2, size_t n);
1930
115
  evalStrcmpCommon(C, CE, /* IsBounded = */ true, /* IgnoreCase = */ true);
1931
115
}
1932
1933
void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
1934
441
    bool IsBounded, bool IgnoreCase) const {
1935
441
  CurrentFunctionDescription = "string comparison function";
1936
441
  ProgramStateRef state = C.getState();
1937
441
  const LocationContext *LCtx = C.getLocationContext();
1938
441
1939
441
  // Check that the first string is non-null
1940
441
  const Expr *s1 = CE->getArg(0);
1941
441
  SVal s1Val = state->getSVal(s1, LCtx);
1942
441
  state = checkNonNull(C, state, s1, s1Val, 1);
1943
441
  if (!state)
1944
20
    return;
1945
421
1946
421
  // Check that the second string is non-null.
1947
421
  const Expr *s2 = CE->getArg(1);
1948
421
  SVal s2Val = state->getSVal(s2, LCtx);
1949
421
  state = checkNonNull(C, state, s2, s2Val, 2);
1950
421
  if (!state)
1951
40
    return;
1952
381
1953
381
  // Get the string length of the first string or give up.
1954
381
  SVal s1Length = getCStringLength(C, state, s1, s1Val);
1955
381
  if (s1Length.isUndef())
1956
0
    return;
1957
381
1958
381
  // Get the string length of the second string or give up.
1959
381
  SVal s2Length = getCStringLength(C, state, s2, s2Val);
1960
381
  if (s2Length.isUndef())
1961
0
    return;
1962
381
1963
381
  // If we know the two buffers are the same, we know the result is 0.
1964
381
  // First, get the two buffers' addresses. Another checker will have already
1965
381
  // made sure they're not undefined.
1966
381
  DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1967
381
  DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
1968
381
1969
381
  // See if they are the same.
1970
381
  SValBuilder &svalBuilder = C.getSValBuilder();
1971
381
  DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1972
381
  ProgramStateRef StSameBuf, StNotSameBuf;
1973
381
  std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1974
381
1975
381
  // If the two arguments might be the same buffer, we know the result is 0,
1976
381
  // and we only need to check one size.
1977
381
  if (StSameBuf) {
1978
11
    StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1979
11
        svalBuilder.makeZeroVal(CE->getType()));
1980
11
    C.addTransition(StSameBuf);
1981
11
1982
11
    // If the two arguments are GUARANTEED to be the same, we're done!
1983
11
    if (!StNotSameBuf)
1984
5
      return;
1985
376
  }
1986
376
1987
376
  assert(StNotSameBuf);
1988
376
  state = StNotSameBuf;
1989
376
1990
376
  // At this point we can go about comparing the two buffers.
1991
376
  // For now, we only do this if they're both known string literals.
1992
376
1993
376
  // Attempt to extract string literals from both expressions.
1994
376
  const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1995
376
  const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1996
376
  bool canComputeResult = false;
1997
376
  SVal resultVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1998
376
      C.blockCount());
1999
376
2000
376
  if (s1StrLiteral && 
s2StrLiteral375
) {
2001
370
    StringRef s1StrRef = s1StrLiteral->getString();
2002
370
    StringRef s2StrRef = s2StrLiteral->getString();
2003
370
2004
370
    if (IsBounded) {
2005
200
      // Get the max number of characters to compare.
2006
200
      const Expr *lenExpr = CE->getArg(2);
2007
200
      SVal lenVal = state->getSVal(lenExpr, LCtx);
2008
200
2009
200
      // If the length is known, we can get the right substrings.
2010
200
      if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
2011
200
        // Create substrings of each to compare the prefix.
2012
200
        s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
2013
200
        s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
2014
200
        canComputeResult = true;
2015
200
      }
2016
200
    } else {
2017
170
      // This is a normal, unbounded strcmp.
2018
170
      canComputeResult = true;
2019
170
    }
2020
370
2021
370
    if (canComputeResult) {
2022
370
      // Real strcmp stops at null characters.
2023
370
      size_t s1Term = s1StrRef.find('\0');
2024
370
      if (s1Term != StringRef::npos)
2025
20
        s1StrRef = s1StrRef.substr(0, s1Term);
2026
370
2027
370
      size_t s2Term = s2StrRef.find('\0');
2028
370
      if (s2Term != StringRef::npos)
2029
20
        s2StrRef = s2StrRef.substr(0, s2Term);
2030
370
2031
370
      // Use StringRef's comparison methods to compute the actual result.
2032
370
      int compareRes = IgnoreCase ? 
s1StrRef.compare_lower(s2StrRef)185
2033
370
        : 
s1StrRef.compare(s2StrRef)185
;
2034
370
2035
370
      // The strcmp function returns an integer greater than, equal to, or less
2036
370
      // than zero, [c11, p7.24.4.2].
2037
370
      if (compareRes == 0) {
2038
110
        resultVal = svalBuilder.makeIntVal(compareRes, CE->getType());
2039
110
      }
2040
260
      else {
2041
260
        DefinedSVal zeroVal = svalBuilder.makeIntVal(0, CE->getType());
2042
260
        // Constrain strcmp's result range based on the result of StringRef's
2043
260
        // comparison methods.
2044
260
        BinaryOperatorKind op = (compareRes == 1) ? 
BO_GT110
:
BO_LT150
;
2045
260
        SVal compareWithZero =
2046
260
          svalBuilder.evalBinOp(state, op, resultVal, zeroVal,
2047
260
              svalBuilder.getConditionType());
2048
260
        DefinedSVal compareWithZeroVal = compareWithZero.castAs<DefinedSVal>();
2049
260
        state = state->assume(compareWithZeroVal, true);
2050
260
      }
2051
370
    }
2052
370
  }
2053
376
2054
376
  state = state->BindExpr(CE, LCtx, resultVal);
2055
376
2056
376
  // Record this as a possible path.
2057
376
  C.addTransition(state);
2058
376
}
2059
2060
30
void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
2061
30
  //char *strsep(char **stringp, const char *delim);
2062
30
  // Sanity: does the search string parameter match the return type?
2063
30
  const Expr *SearchStrPtr = CE->getArg(0);
2064
30
  QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
2065
30
  if (CharPtrTy.isNull() ||
2066
30
      CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
2067
0
    return;
2068
30
2069
30
  CurrentFunctionDescription = "strsep()";
2070
30
  ProgramStateRef State = C.getState();
2071
30
  const LocationContext *LCtx = C.getLocationContext();
2072
30
2073
30
  // Check that the search string pointer is non-null (though it may point to
2074
30
  // a null string).
2075
30
  SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
2076
30
  State = checkNonNull(C, State, SearchStrPtr, SearchStrVal, 1);
2077
30
  if (!State)
2078
5
    return;
2079
25
2080
25
  // Check that the delimiter string is non-null.
2081
25
  const Expr *DelimStr = CE->getArg(1);
2082
25
  SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
2083
25
  State = checkNonNull(C, State, DelimStr, DelimStrVal, 2);
2084
25
  if (!State)
2085
5
    return;
2086
20
2087
20
  SValBuilder &SVB = C.getSValBuilder();
2088
20
  SVal Result;
2089
20
  if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
2090
20
    // Get the current value of the search string pointer, as a char*.
2091
20
    Result = State->getSVal(*SearchStrLoc, CharPtrTy);
2092
20
2093
20
    // Invalidate the search string, representing the change of one delimiter
2094
20
    // character to NUL.
2095
20
    State = InvalidateBuffer(C, State, SearchStrPtr, Result,
2096
20
        /*IsSourceBuffer*/false, nullptr);
2097
20
2098
20
    // Overwrite the search string pointer. The new value is either an address
2099
20
    // further along in the same string, or NULL if there are no more tokens.
2100
20
    State = State->bindLoc(*SearchStrLoc,
2101
20
        SVB.conjureSymbolVal(getTag(),
2102
20
          CE,
2103
20
          LCtx,
2104
20
          CharPtrTy,
2105
20
          C.blockCount()),
2106
20
        LCtx);
2107
20
  } else {
2108
0
    assert(SearchStrVal.isUnknown());
2109
0
    // Conjure a symbolic value. It's the best we can do.
2110
0
    Result = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
2111
0
  }
2112
20
2113
20
  // Set the return value, and finish.
2114
20
  State = State->BindExpr(CE, LCtx, Result);
2115
20
  C.addTransition(State);
2116
20
}
2117
2118
// These should probably be moved into a C++ standard library checker.
2119
7
void CStringChecker::evalStdCopy(CheckerContext &C, const CallExpr *CE) const {
2120
7
  evalStdCopyCommon(C, CE);
2121
7
}
2122
2123
void CStringChecker::evalStdCopyBackward(CheckerContext &C,
2124
5
    const CallExpr *CE) const {
2125
5
  evalStdCopyCommon(C, CE);
2126
5
}
2127
2128
void CStringChecker::evalStdCopyCommon(CheckerContext &C,
2129
12
    const CallExpr *CE) const {
2130
12
  if (!CE->getArg(2)->getType()->isPointerType())
2131
2
    return;
2132
10
2133
10
  ProgramStateRef State = C.getState();
2134
10
2135
10
  const LocationContext *LCtx = C.getLocationContext();
2136
10
2137
10
  // template <class _InputIterator, class _OutputIterator>
2138
10
  // _OutputIterator
2139
10
  // copy(_InputIterator __first, _InputIterator __last,
2140
10
  //        _OutputIterator __result)
2141
10
2142
10
  // Invalidate the destination buffer
2143
10
  const Expr *Dst = CE->getArg(2);
2144
10
  SVal DstVal = State->getSVal(Dst, LCtx);
2145
10
  State = InvalidateBuffer(C, State, Dst, DstVal, /*IsSource=*/false,
2146
10
      /*Size=*/nullptr);
2147
10
2148
10
  SValBuilder &SVB = C.getSValBuilder();
2149
10
2150
10
  SVal ResultVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
2151
10
  State = State->BindExpr(CE, LCtx, ResultVal);
2152
10
2153
10
  C.addTransition(State);
2154
10
}
2155
2156
159
void CStringChecker::evalMemset(CheckerContext &C, const CallExpr *CE) const {
2157
159
  CurrentFunctionDescription = "memory set function";
2158
159
2159
159
  const Expr *Mem = CE->getArg(0);
2160
159
  const Expr *CharE = CE->getArg(1);
2161
159
  const Expr *Size = CE->getArg(2);
2162
159
  ProgramStateRef State = C.getState();
2163
159
2164
159
  // See if the size argument is zero.
2165
159
  const LocationContext *LCtx = C.getLocationContext();
2166
159
  SVal SizeVal = State->getSVal(Size, LCtx);
2167
159
  QualType SizeTy = Size->getType();
2168
159
2169
159
  ProgramStateRef StateZeroSize, StateNonZeroSize;
2170
159
  std::tie(StateZeroSize, StateNonZeroSize) =
2171
159
    assumeZero(C, State, SizeVal, SizeTy);
2172
159
2173
159
  // Get the value of the memory area.
2174
159
  SVal MemVal = State->getSVal(Mem, LCtx);
2175
159
2176
159
  // If the size is zero, there won't be any actual memory access, so
2177
159
  // just bind the return value to the Mem buffer and return.
2178
159
  if (StateZeroSize && 
!StateNonZeroSize0
) {
2179
0
    StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, MemVal);
2180
0
    C.addTransition(StateZeroSize);
2181
0
    return;
2182
0
  }
2183
159
2184
159
  // Ensure the memory area is not null.
2185
159
  // If it is NULL there will be a NULL pointer dereference.
2186
159
  State = checkNonNull(C, StateNonZeroSize, Mem, MemVal, 1);
2187
159
  if (!State)
2188
1
    return;
2189
158
2190
158
  State = CheckBufferAccess(C, State, Size, Mem);
2191
158
  if (!State)
2192
2
    return;
2193
156
2194
156
  // According to the values of the arguments, bind the value of the second
2195
156
  // argument to the destination buffer and set string length, or just
2196
156
  // invalidate the destination buffer.
2197
156
  if (!memsetAux(Mem, C.getSVal(CharE), Size, C, State))
2198
0
    return;
2199
156
2200
156
  State = State->BindExpr(CE, LCtx, MemVal);
2201
156
  C.addTransition(State);
2202
156
}
2203
2204
30
void CStringChecker::evalBzero(CheckerContext &C, const CallExpr *CE) const {
2205
30
  CurrentFunctionDescription = "memory clearance function";
2206
30
2207
30
  const Expr *Mem = CE->getArg(0);
2208
30
  const Expr *Size = CE->getArg(1);
2209
30
  SVal Zero = C.getSValBuilder().makeZeroVal(C.getASTContext().IntTy);
2210
30
2211
30
  ProgramStateRef State = C.getState();
2212
30
2213
30
  // See if the size argument is zero.
2214
30
  SVal SizeVal = C.getSVal(Size);
2215
30
  QualType SizeTy = Size->getType();
2216
30
2217
30
  ProgramStateRef StateZeroSize, StateNonZeroSize;
2218
30
  std::tie(StateZeroSize, StateNonZeroSize) =
2219
30
    assumeZero(C, State, SizeVal, SizeTy);
2220
30
2221
30
  // If the size is zero, there won't be any actual memory access,
2222
30
  // In this case we just return.
2223
30
  if (StateZeroSize && 
!StateNonZeroSize0
) {
2224
0
    C.addTransition(StateZeroSize);
2225
0
    return;
2226
0
  }
2227
30
2228
30
  // Get the value of the memory area.
2229
30
  SVal MemVal = C.getSVal(Mem);
2230
30
2231
30
  // Ensure the memory area is not null.
2232
30
  // If it is NULL there will be a NULL pointer dereference.
2233
30
  State = checkNonNull(C, StateNonZeroSize, Mem, MemVal, 1);
2234
30
  if (!State)
2235
10
    return;
2236
20
2237
20
  State = CheckBufferAccess(C, State, Size, Mem);
2238
20
  if (!State)
2239
4
    return;
2240
16
2241
16
  if (!memsetAux(Mem, Zero, Size, C, State))
2242
0
    return;
2243
16
2244
16
  C.addTransition(State);
2245
16
}
2246
2247
//===----------------------------------------------------------------------===//
2248
// The driver method, and other Checker callbacks.
2249
//===----------------------------------------------------------------------===//
2250
2251
CStringChecker::FnCheck CStringChecker::identifyCall(const CallEvent &Call,
2252
25.0k
                                                     CheckerContext &C) const {
2253
25.0k
  const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
2254
25.0k
  if (!CE)
2255
0
    return nullptr;
2256
25.0k
2257
25.0k
  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
2258
25.0k
  if (!FD)
2259
16
    return nullptr;
2260
25.0k
2261
25.0k
  if (Call.isCalled(StdCopy)) {
2262
7
    return &CStringChecker::evalStdCopy;
2263
25.0k
  } else if (Call.isCalled(StdCopyBackward)) {
2264
5
    return &CStringChecker::evalStdCopyBackward;
2265
5
  }
2266
24.9k
2267
24.9k
  // Pro-actively check that argument types are safe to do arithmetic upon.
2268
24.9k
  // We do not want to crash if someone accidentally passes a structure
2269
24.9k
  // into, say, a C++ overload of any of these functions. We could not check
2270
24.9k
  // that for std::copy because they may have arguments of other types.
2271
24.9k
  for (auto I : CE->arguments()) {
2272
24.0k
    QualType T = I->getType();
2273
24.0k
    if (!T->isIntegralOrEnumerationType() && 
!T->isPointerType()16.8k
)
2274
8.32k
      return nullptr;
2275
24.0k
  }
2276
24.9k
2277
24.9k
  const FnCheck *Callback = Callbacks.lookup(Call);
2278
16.6k
  if (Callback)
2279
2.06k
    return *Callback;
2280
14.6k
2281
14.6k
  return nullptr;
2282
14.6k
}
2283
2284
25.0k
bool CStringChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
2285
25.0k
  FnCheck Callback = identifyCall(Call, C);
2286
25.0k
2287
25.0k
  // If the callee isn't a string function, let another checker handle it.
2288
25.0k
  if (!Callback)
2289
22.9k
    return false;
2290
2.07k
2291
2.07k
  // Check and evaluate the call.
2292
2.07k
  const auto *CE = cast<CallExpr>(Call.getOriginExpr());
2293
2.07k
  (this->*Callback)(C, CE);
2294
2.07k
2295
2.07k
  // If the evaluate call resulted in no change, chain to the next eval call
2296
2.07k
  // handler.
2297
2.07k
  // Note, the custom CString evaluation calls assume that basic safety
2298
2.07k
  // properties are held. However, if the user chooses to turn off some of these
2299
2.07k
  // checks, we ignore the issues and leave the call evaluation to a generic
2300
2.07k
  // handler.
2301
2.07k
  return C.isDifferent();
2302
2.07k
}
2303
2304
10.5k
void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
2305
10.5k
  // Record string length for char a[] = "abc";
2306
10.5k
  ProgramStateRef state = C.getState();
2307
10.5k
2308
10.5k
  for (const auto *I : DS->decls()) {
2309
10.5k
    const VarDecl *D = dyn_cast<VarDecl>(I);
2310
10.5k
    if (!D)
2311
0
      continue;
2312
10.5k
2313
10.5k
    // FIXME: Handle array fields of structs.
2314
10.5k
    if (!D->getType()->isArrayType())
2315
9.84k
      continue;
2316
699
2317
699
    const Expr *Init = D->getInit();
2318
699
    if (!Init)
2319
205
      continue;
2320
494
    if (!isa<StringLiteral>(Init))
2321
306
      continue;
2322
188
2323
188
    Loc VarLoc = state->getLValue(D, C.getLocationContext());
2324
188
    const MemRegion *MR = VarLoc.getAsRegion();
2325
188
    if (!MR)
2326
0
      continue;
2327
188
2328
188
    SVal StrVal = C.getSVal(Init);
2329
188
    assert(StrVal.isValid() && "Initializer string is unknown or undefined");
2330
188
    DefinedOrUnknownSVal strLength =
2331
188
      getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
2332
188
2333
188
    state = state->set<CStringLength>(MR, strLength);
2334
188
  }
2335
10.5k
2336
10.5k
  C.addTransition(state);
2337
10.5k
}
2338
2339
ProgramStateRef
2340
CStringChecker::checkRegionChanges(ProgramStateRef state,
2341
    const InvalidatedSymbols *,
2342
    ArrayRef<const MemRegion *> ExplicitRegions,
2343
    ArrayRef<const MemRegion *> Regions,
2344
    const LocationContext *LCtx,
2345
55.3k
    const CallEvent *Call) const {
2346
55.3k
  CStringLengthTy Entries = state->get<CStringLength>();
2347
55.3k
  if (Entries.isEmpty())
2348
54.3k
    return state;
2349
1.00k
2350
1.00k
  llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
2351
1.00k
  llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
2352
1.00k
2353
1.00k
  // First build sets for the changed regions and their super-regions.
2354
1.00k
  for (ArrayRef<const MemRegion *>::iterator
2355
2.23k
      I = Regions.begin(), E = Regions.end(); I != E; 
++I1.22k
) {
2356
1.22k
    const MemRegion *MR = *I;
2357
1.22k
    Invalidated.insert(MR);
2358
1.22k
2359
1.22k
    SuperRegions.insert(MR);
2360
2.13k
    while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
2361
910
      MR = SR->getSuperRegion();
2362
910
      SuperRegions.insert(MR);
2363
910
    }
2364
1.22k
  }
2365
1.00k
2366
1.00k
  CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2367
1.00k
2368
1.00k
  // Then loop over the entries in the current state.
2369
1.00k
  for (CStringLengthTy::iterator I = Entries.begin(),
2370
2.20k
      E = Entries.end(); I != E; 
++I1.19k
) {
2371
1.19k
    const MemRegion *MR = I.getKey();
2372
1.19k
2373
1.19k
    // Is this entry for a super-region of a changed region?
2374
1.19k
    if (SuperRegions.count(MR)) {
2375
583
      Entries = F.remove(Entries, MR);
2376
583
      continue;
2377
583
    }
2378
613
2379
613
    // Is this entry for a sub-region of a changed region?
2380
613
    const MemRegion *Super = MR;
2381
1.23k
    while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2382
647
      Super = SR->getSuperRegion();
2383
647
      if (Invalidated.count(Super)) {
2384
24
        Entries = F.remove(Entries, MR);
2385
24
        break;
2386
24
      }
2387
647
    }
2388
613
  }
2389
1.00k
2390
1.00k
  return state->set<CStringLength>(Entries);
2391
1.00k
}
2392
2393
void CStringChecker::checkLiveSymbols(ProgramStateRef state,
2394
119k
    SymbolReaper &SR) const {
2395
119k
  // Mark all symbols in our string length map as valid.
2396
119k
  CStringLengthTy Entries = state->get<CStringLength>();
2397
119k
2398
119k
  for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2399
121k
      I != E; 
++I2.78k
) {
2400
2.78k
    SVal Len = I.getData();
2401
2.78k
2402
2.78k
    for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2403
4.45k
        se = Len.symbol_end(); si != se; 
++si1.66k
)
2404
1.66k
      SR.markInUse(*si);
2405
2.78k
  }
2406
119k
}
2407
2408
void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2409
119k
    CheckerContext &C) const {
2410
119k
  ProgramStateRef state = C.getState();
2411
119k
  CStringLengthTy Entries = state->get<CStringLength>();
2412
119k
  if (Entries.isEmpty())
2413
116k
    return;
2414
2.31k
2415
2.31k
  CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2416
2.31k
  for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2417
5.10k
      I != E; 
++I2.78k
) {
2418
2.78k
    SVal Len = I.getData();
2419
2.78k
    if (SymbolRef Sym = Len.getAsSymbol()) {
2420
1.61k
      if (SR.isDead(Sym))
2421
437
        Entries = F.remove(Entries, I.getKey());
2422
1.61k
    }
2423
2.78k
  }
2424
2.31k
2425
2.31k
  state = state->set<CStringLength>(Entries);
2426
2.31k
  C.addTransition(state);
2427
2.31k
}
2428
2429
228
void ento::registerCStringModeling(CheckerManager &Mgr) {
2430
228
  Mgr.registerChecker<CStringChecker>();
2431
228
}
2432
2433
57
bool ento::shouldRegisterCStringModeling(const LangOptions &LO) {
2434
57
  return true;
2435
57
}
2436
2437
#define REGISTER_CHECKER(name)                                                 \
2438
119
  void ento::register##name(CheckerManager &mgr) {                             \
2439
119
    CStringChecker *checker = mgr.getChecker<CStringChecker>();                \
2440
119
    checker->Filter.Check##name = true;                                        \
2441
119
    checker->Filter.CheckName##name = mgr.getCurrentCheckerName();             \
2442
119
  }                                                                            \
clang::ento::registerCStringNullArg(clang::ento::CheckerManager&)
Line
Count
Source
2438
58
  void ento::register##name(CheckerManager &mgr) {                             \
2439
58
    CStringChecker *checker = mgr.getChecker<CStringChecker>();                \
2440
58
    checker->Filter.Check##name = true;                                        \
2441
58
    checker->Filter.CheckName##name = mgr.getCurrentCheckerName();             \
2442
58
  }                                                                            \
clang::ento::registerCStringOutOfBounds(clang::ento::CheckerManager&)
Line
Count
Source
2438
19
  void ento::register##name(CheckerManager &mgr) {                             \
2439
19
    CStringChecker *checker = mgr.getChecker<CStringChecker>();                \
2440
19
    checker->Filter.Check##name = true;                                        \
2441
19
    checker->Filter.CheckName##name = mgr.getCurrentCheckerName();             \
2442
19
  }                                                                            \
clang::ento::registerCStringBufferOverlap(clang::ento::CheckerManager&)
Line
Count
Source
2438
21
  void ento::register##name(CheckerManager &mgr) {                             \
2439
21
    CStringChecker *checker = mgr.getChecker<CStringChecker>();                \
2440
21
    checker->Filter.Check##name = true;                                        \
2441
21
    checker->Filter.CheckName##name = mgr.getCurrentCheckerName();             \
2442
21
  }                                                                            \
clang::ento::registerCStringNotNullTerm(clang::ento::CheckerManager&)
Line
Count
Source
2438
21
  void ento::register##name(CheckerManager &mgr) {                             \
2439
21
    CStringChecker *checker = mgr.getChecker<CStringChecker>();                \
2440
21
    checker->Filter.Check##name = true;                                        \
2441
21
    checker->Filter.CheckName##name = mgr.getCurrentCheckerName();             \
2442
21
  }                                                                            \
2443
                                                                               \
2444
120
  bool ento::shouldRegister##name(const LangOptions &LO) { return true; }
clang::ento::shouldRegisterCStringNullArg(clang::LangOptions const&)
Line
Count
Source
2444
59
  bool ento::shouldRegister##name(const LangOptions &LO) { return true; }
clang::ento::shouldRegisterCStringOutOfBounds(clang::LangOptions const&)
Line
Count
Source
2444
19
  bool ento::shouldRegister##name(const LangOptions &LO) { return true; }
clang::ento::shouldRegisterCStringBufferOverlap(clang::LangOptions const&)
Line
Count
Source
2444
21
  bool ento::shouldRegister##name(const LangOptions &LO) { return true; }
clang::ento::shouldRegisterCStringNotNullTerm(clang::LangOptions const&)
Line
Count
Source
2444
21
  bool ento::shouldRegister##name(const LangOptions &LO) { return true; }
2445
2446
REGISTER_CHECKER(CStringNullArg)
2447
REGISTER_CHECKER(CStringOutOfBounds)
2448
REGISTER_CHECKER(CStringBufferOverlap)
2449
REGISTER_CHECKER(CStringNotNullTerm)