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