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