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