1 //= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This defines CStringChecker, which is an assortment of checks on calls
10 // to functions in <string.h>.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15 #include "InterCheckerAPI.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18 #include "clang/StaticAnalyzer/Core/Checker.h"
19 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Support/raw_ostream.h"
26 
27 using namespace clang;
28 using namespace ento;
29 
30 namespace {
31 enum class ConcatFnKind { none = 0, strcat = 1, strlcat = 2 };
32 class CStringChecker : public Checker< eval::Call,
33                                          check::PreStmt<DeclStmt>,
34                                          check::LiveSymbols,
35                                          check::DeadSymbols,
36                                          check::RegionChanges
37                                          > {
38   mutable std::unique_ptr<BugType> BT_Null, BT_Bounds, BT_Overlap,
39       BT_NotCString, BT_AdditionOverflow;
40 
41   mutable const char *CurrentFunctionDescription;
42 
43 public:
44   /// The filter is used to filter out the diagnostics which are not enabled by
45   /// the user.
46   struct CStringChecksFilter {
47     DefaultBool CheckCStringNullArg;
48     DefaultBool CheckCStringOutOfBounds;
49     DefaultBool CheckCStringBufferOverlap;
50     DefaultBool CheckCStringNotNullTerm;
51 
52     CheckerNameRef CheckNameCStringNullArg;
53     CheckerNameRef CheckNameCStringOutOfBounds;
54     CheckerNameRef CheckNameCStringBufferOverlap;
55     CheckerNameRef CheckNameCStringNotNullTerm;
56   };
57 
58   CStringChecksFilter Filter;
59 
60   static void *getTag() { static int tag; return &tag; }
61 
62   bool evalCall(const CallEvent &Call, CheckerContext &C) const;
63   void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
64   void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
65   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
66 
67   ProgramStateRef
68     checkRegionChanges(ProgramStateRef state,
69                        const InvalidatedSymbols *,
70                        ArrayRef<const MemRegion *> ExplicitRegions,
71                        ArrayRef<const MemRegion *> Regions,
72                        const LocationContext *LCtx,
73                        const CallEvent *Call) const;
74 
75   typedef void (CStringChecker::*FnCheck)(CheckerContext &,
76                                           const CallExpr *) const;
77   CallDescriptionMap<FnCheck> Callbacks = {
78       {{CDF_MaybeBuiltin, "memcpy", 3}, &CStringChecker::evalMemcpy},
79       {{CDF_MaybeBuiltin, "mempcpy", 3}, &CStringChecker::evalMempcpy},
80       {{CDF_MaybeBuiltin, "memcmp", 3}, &CStringChecker::evalMemcmp},
81       {{CDF_MaybeBuiltin, "memmove", 3}, &CStringChecker::evalMemmove},
82       {{CDF_MaybeBuiltin, "memset", 3}, &CStringChecker::evalMemset},
83       {{CDF_MaybeBuiltin, "explicit_memset", 3}, &CStringChecker::evalMemset},
84       {{CDF_MaybeBuiltin, "strcpy", 2}, &CStringChecker::evalStrcpy},
85       {{CDF_MaybeBuiltin, "strncpy", 3}, &CStringChecker::evalStrncpy},
86       {{CDF_MaybeBuiltin, "stpcpy", 2}, &CStringChecker::evalStpcpy},
87       {{CDF_MaybeBuiltin, "strlcpy", 3}, &CStringChecker::evalStrlcpy},
88       {{CDF_MaybeBuiltin, "strcat", 2}, &CStringChecker::evalStrcat},
89       {{CDF_MaybeBuiltin, "strncat", 3}, &CStringChecker::evalStrncat},
90       {{CDF_MaybeBuiltin, "strlcat", 3}, &CStringChecker::evalStrlcat},
91       {{CDF_MaybeBuiltin, "strlen", 1}, &CStringChecker::evalstrLength},
92       {{CDF_MaybeBuiltin, "strnlen", 2}, &CStringChecker::evalstrnLength},
93       {{CDF_MaybeBuiltin, "strcmp", 2}, &CStringChecker::evalStrcmp},
94       {{CDF_MaybeBuiltin, "strncmp", 3}, &CStringChecker::evalStrncmp},
95       {{CDF_MaybeBuiltin, "strcasecmp", 2}, &CStringChecker::evalStrcasecmp},
96       {{CDF_MaybeBuiltin, "strncasecmp", 3}, &CStringChecker::evalStrncasecmp},
97       {{CDF_MaybeBuiltin, "strsep", 2}, &CStringChecker::evalStrsep},
98       {{CDF_MaybeBuiltin, "bcopy", 3}, &CStringChecker::evalBcopy},
99       {{CDF_MaybeBuiltin, "bcmp", 3}, &CStringChecker::evalMemcmp},
100       {{CDF_MaybeBuiltin, "bzero", 2}, &CStringChecker::evalBzero},
101       {{CDF_MaybeBuiltin, "explicit_bzero", 2}, &CStringChecker::evalBzero},
102   };
103 
104   // These require a bit of special handling.
105   CallDescription StdCopy{{"std", "copy"}, 3},
106       StdCopyBackward{{"std", "copy_backward"}, 3};
107 
108   FnCheck identifyCall(const CallEvent &Call, CheckerContext &C) const;
109   void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
110   void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
111   void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
112   void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
113   void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
114                       ProgramStateRef state,
115                       const Expr *Size,
116                       const Expr *Source,
117                       const Expr *Dest,
118                       bool Restricted = false,
119                       bool IsMempcpy = false) const;
120 
121   void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
122 
123   void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
124   void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
125   void evalstrLengthCommon(CheckerContext &C,
126                            const CallExpr *CE,
127                            bool IsStrnlen = false) const;
128 
129   void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
130   void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
131   void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
132   void evalStrlcpy(CheckerContext &C, const CallExpr *CE) const;
133   void evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, bool ReturnEnd,
134                         bool IsBounded, ConcatFnKind appendK,
135                         bool returnPtr = true) const;
136 
137   void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
138   void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
139   void evalStrlcat(CheckerContext &C, const CallExpr *CE) const;
140 
141   void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
142   void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
143   void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
144   void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
145   void evalStrcmpCommon(CheckerContext &C,
146                         const CallExpr *CE,
147                         bool IsBounded = false,
148                         bool IgnoreCase = false) const;
149 
150   void evalStrsep(CheckerContext &C, const CallExpr *CE) const;
151 
152   void evalStdCopy(CheckerContext &C, const CallExpr *CE) const;
153   void evalStdCopyBackward(CheckerContext &C, const CallExpr *CE) const;
154   void evalStdCopyCommon(CheckerContext &C, const CallExpr *CE) const;
155   void evalMemset(CheckerContext &C, const CallExpr *CE) const;
156   void evalBzero(CheckerContext &C, const CallExpr *CE) const;
157 
158   // Utility methods
159   std::pair<ProgramStateRef , ProgramStateRef >
160   static assumeZero(CheckerContext &C,
161                     ProgramStateRef state, SVal V, QualType Ty);
162 
163   static ProgramStateRef setCStringLength(ProgramStateRef state,
164                                               const MemRegion *MR,
165                                               SVal strLength);
166   static SVal getCStringLengthForRegion(CheckerContext &C,
167                                         ProgramStateRef &state,
168                                         const Expr *Ex,
169                                         const MemRegion *MR,
170                                         bool hypothetical);
171   SVal getCStringLength(CheckerContext &C,
172                         ProgramStateRef &state,
173                         const Expr *Ex,
174                         SVal Buf,
175                         bool hypothetical = false) const;
176 
177   const StringLiteral *getCStringLiteral(CheckerContext &C,
178                                          ProgramStateRef &state,
179                                          const Expr *expr,
180                                          SVal val) const;
181 
182   static ProgramStateRef InvalidateBuffer(CheckerContext &C,
183                                           ProgramStateRef state,
184                                           const Expr *Ex, SVal V,
185                                           bool IsSourceBuffer,
186                                           const Expr *Size);
187 
188   static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
189                               const MemRegion *MR);
190 
191   static bool memsetAux(const Expr *DstBuffer, SVal CharE,
192                         const Expr *Size, CheckerContext &C,
193                         ProgramStateRef &State);
194 
195   // Re-usable checks
196   ProgramStateRef checkNonNull(CheckerContext &C,
197                                    ProgramStateRef state,
198                                    const Expr *S,
199                                    SVal l,
200                                    unsigned IdxOfArg) const;
201   ProgramStateRef CheckLocation(CheckerContext &C,
202                                     ProgramStateRef state,
203                                     const Expr *S,
204                                     SVal l,
205                                     const char *message = nullptr) const;
206   ProgramStateRef CheckBufferAccess(CheckerContext &C,
207                                         ProgramStateRef state,
208                                         const Expr *Size,
209                                         const Expr *FirstBuf,
210                                         const Expr *SecondBuf,
211                                         const char *firstMessage = nullptr,
212                                         const char *secondMessage = nullptr,
213                                         bool WarnAboutSize = false) const;
214 
215   ProgramStateRef CheckBufferAccess(CheckerContext &C,
216                                         ProgramStateRef state,
217                                         const Expr *Size,
218                                         const Expr *Buf,
219                                         const char *message = nullptr,
220                                         bool WarnAboutSize = false) const {
221     // This is a convenience overload.
222     return CheckBufferAccess(C, state, Size, Buf, nullptr, message, nullptr,
223                              WarnAboutSize);
224   }
225   ProgramStateRef CheckOverlap(CheckerContext &C,
226                                    ProgramStateRef state,
227                                    const Expr *Size,
228                                    const Expr *First,
229                                    const Expr *Second) const;
230   void emitOverlapBug(CheckerContext &C,
231                       ProgramStateRef state,
232                       const Stmt *First,
233                       const Stmt *Second) const;
234 
235   void emitNullArgBug(CheckerContext &C, ProgramStateRef State, const Stmt *S,
236                       StringRef WarningMsg) const;
237   void emitOutOfBoundsBug(CheckerContext &C, ProgramStateRef State,
238                           const Stmt *S, StringRef WarningMsg) const;
239   void emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
240                          const Stmt *S, StringRef WarningMsg) const;
241   void emitAdditionOverflowBug(CheckerContext &C, ProgramStateRef State) const;
242 
243   ProgramStateRef checkAdditionOverflow(CheckerContext &C,
244                                             ProgramStateRef state,
245                                             NonLoc left,
246                                             NonLoc right) const;
247 
248   // Return true if the destination buffer of the copy function may be in bound.
249   // Expects SVal of Size to be positive and unsigned.
250   // Expects SVal of FirstBuf to be a FieldRegion.
251   static bool IsFirstBufInBound(CheckerContext &C,
252                                 ProgramStateRef state,
253                                 const Expr *FirstBuf,
254                                 const Expr *Size);
255 };
256 
257 } //end anonymous namespace
258 
259 REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
260 
261 //===----------------------------------------------------------------------===//
262 // Individual checks and utility methods.
263 //===----------------------------------------------------------------------===//
264 
265 std::pair<ProgramStateRef , ProgramStateRef >
266 CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
267                            QualType Ty) {
268   Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
269   if (!val)
270     return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
271 
272   SValBuilder &svalBuilder = C.getSValBuilder();
273   DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
274   return state->assume(svalBuilder.evalEQ(state, *val, zero));
275 }
276 
277 ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
278                                             ProgramStateRef state,
279                                             const Expr *S, SVal l,
280                                             unsigned IdxOfArg) const {
281   // If a previous check has failed, propagate the failure.
282   if (!state)
283     return nullptr;
284 
285   ProgramStateRef stateNull, stateNonNull;
286   std::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
287 
288   if (stateNull && !stateNonNull) {
289     if (Filter.CheckCStringNullArg) {
290       SmallString<80> buf;
291       llvm::raw_svector_ostream OS(buf);
292       assert(CurrentFunctionDescription);
293       OS << "Null pointer argument in call to " << CurrentFunctionDescription
294          << ' ' << IdxOfArg << llvm::getOrdinalSuffix(IdxOfArg)
295          << " parameter";
296 
297       emitNullArgBug(C, stateNull, S, OS.str());
298     }
299     return nullptr;
300   }
301 
302   // From here on, assume that the value is non-null.
303   assert(stateNonNull);
304   return stateNonNull;
305 }
306 
307 // FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
308 ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
309                                              ProgramStateRef state,
310                                              const Expr *S, SVal l,
311                                              const char *warningMsg) const {
312   // If a previous check has failed, propagate the failure.
313   if (!state)
314     return nullptr;
315 
316   // Check for out of bound array element access.
317   const MemRegion *R = l.getAsRegion();
318   if (!R)
319     return state;
320 
321   const ElementRegion *ER = dyn_cast<ElementRegion>(R);
322   if (!ER)
323     return state;
324 
325   if (ER->getValueType() != C.getASTContext().CharTy)
326     return state;
327 
328   // Get the size of the array.
329   const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
330   SValBuilder &svalBuilder = C.getSValBuilder();
331   SVal Extent =
332     svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
333   DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>();
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   SVal Extent =
939       svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
940   DefinedOrUnknownSVal ExtentSize = Extent.castAs<DefinedOrUnknownSVal>();
941 
942   // Get the index of the accessed element.
943   DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
944 
945   ProgramStateRef StInBound = state->assumeInBound(Idx, ExtentSize, true);
946 
947   return static_cast<bool>(StInBound);
948 }
949 
950 ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
951                                                  ProgramStateRef state,
952                                                  const Expr *E, SVal V,
953                                                  bool IsSourceBuffer,
954                                                  const Expr *Size) {
955   Optional<Loc> L = V.getAs<Loc>();
956   if (!L)
957     return state;
958 
959   // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
960   // some assumptions about the value that CFRefCount can't. Even so, it should
961   // probably be refactored.
962   if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
963     const MemRegion *R = MR->getRegion()->StripCasts();
964 
965     // Are we dealing with an ElementRegion?  If so, we should be invalidating
966     // the super-region.
967     if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
968       R = ER->getSuperRegion();
969       // FIXME: What about layers of ElementRegions?
970     }
971 
972     // Invalidate this region.
973     const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
974 
975     bool CausesPointerEscape = false;
976     RegionAndSymbolInvalidationTraits ITraits;
977     // Invalidate and escape only indirect regions accessible through the source
978     // buffer.
979     if (IsSourceBuffer) {
980       ITraits.setTrait(R->getBaseRegion(),
981                        RegionAndSymbolInvalidationTraits::TK_PreserveContents);
982       ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
983       CausesPointerEscape = true;
984     } else {
985       const MemRegion::Kind& K = R->getKind();
986       if (K == MemRegion::FieldRegionKind)
987         if (Size && IsFirstBufInBound(C, state, E, Size)) {
988           // If destination buffer is a field region and access is in bound,
989           // do not invalidate its super region.
990           ITraits.setTrait(
991               R,
992               RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
993         }
994     }
995 
996     return state->invalidateRegions(R, E, C.blockCount(), LCtx,
997                                     CausesPointerEscape, nullptr, nullptr,
998                                     &ITraits);
999   }
1000 
1001   // If we have a non-region value by chance, just remove the binding.
1002   // FIXME: is this necessary or correct? This handles the non-Region
1003   //  cases.  Is it ever valid to store to these?
1004   return state->killBinding(*L);
1005 }
1006 
1007 bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
1008                                      const MemRegion *MR) {
1009   const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
1010 
1011   switch (MR->getKind()) {
1012   case MemRegion::FunctionCodeRegionKind: {
1013     const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1014     if (FD)
1015       os << "the address of the function '" << *FD << '\'';
1016     else
1017       os << "the address of a function";
1018     return true;
1019   }
1020   case MemRegion::BlockCodeRegionKind:
1021     os << "block text";
1022     return true;
1023   case MemRegion::BlockDataRegionKind:
1024     os << "a block";
1025     return true;
1026   case MemRegion::CXXThisRegionKind:
1027   case MemRegion::CXXTempObjectRegionKind:
1028     os << "a C++ temp object of type " << TVR->getValueType().getAsString();
1029     return true;
1030   case MemRegion::VarRegionKind:
1031     os << "a variable of type" << TVR->getValueType().getAsString();
1032     return true;
1033   case MemRegion::FieldRegionKind:
1034     os << "a field of type " << TVR->getValueType().getAsString();
1035     return true;
1036   case MemRegion::ObjCIvarRegionKind:
1037     os << "an instance variable of type " << TVR->getValueType().getAsString();
1038     return true;
1039   default:
1040     return false;
1041   }
1042 }
1043 
1044 bool CStringChecker::memsetAux(const Expr *DstBuffer, SVal CharVal,
1045                                const Expr *Size, CheckerContext &C,
1046                                ProgramStateRef &State) {
1047   SVal MemVal = C.getSVal(DstBuffer);
1048   SVal SizeVal = C.getSVal(Size);
1049   const MemRegion *MR = MemVal.getAsRegion();
1050   if (!MR)
1051     return false;
1052 
1053   // We're about to model memset by producing a "default binding" in the Store.
1054   // Our current implementation - RegionStore - doesn't support default bindings
1055   // that don't cover the whole base region. So we should first get the offset
1056   // and the base region to figure out whether the offset of buffer is 0.
1057   RegionOffset Offset = MR->getAsOffset();
1058   const MemRegion *BR = Offset.getRegion();
1059 
1060   Optional<NonLoc> SizeNL = SizeVal.getAs<NonLoc>();
1061   if (!SizeNL)
1062     return false;
1063 
1064   SValBuilder &svalBuilder = C.getSValBuilder();
1065   ASTContext &Ctx = C.getASTContext();
1066 
1067   // void *memset(void *dest, int ch, size_t count);
1068   // For now we can only handle the case of offset is 0 and concrete char value.
1069   if (Offset.isValid() && !Offset.hasSymbolicOffset() &&
1070       Offset.getOffset() == 0) {
1071     // Get the base region's extent.
1072     auto *SubReg = cast<SubRegion>(BR);
1073     DefinedOrUnknownSVal Extent = SubReg->getExtent(svalBuilder);
1074 
1075     ProgramStateRef StateWholeReg, StateNotWholeReg;
1076     std::tie(StateWholeReg, StateNotWholeReg) =
1077         State->assume(svalBuilder.evalEQ(State, Extent, *SizeNL));
1078 
1079     // With the semantic of 'memset()', we should convert the CharVal to
1080     // unsigned char.
1081     CharVal = svalBuilder.evalCast(CharVal, Ctx.UnsignedCharTy, Ctx.IntTy);
1082 
1083     ProgramStateRef StateNullChar, StateNonNullChar;
1084     std::tie(StateNullChar, StateNonNullChar) =
1085         assumeZero(C, State, CharVal, Ctx.UnsignedCharTy);
1086 
1087     if (StateWholeReg && !StateNotWholeReg && StateNullChar &&
1088         !StateNonNullChar) {
1089       // If the 'memset()' acts on the whole region of destination buffer and
1090       // the value of the second argument of 'memset()' is zero, bind the second
1091       // argument's value to the destination buffer with 'default binding'.
1092       // FIXME: Since there is no perfect way to bind the non-zero character, we
1093       // can only deal with zero value here. In the future, we need to deal with
1094       // the binding of non-zero value in the case of whole region.
1095       State = State->bindDefaultZero(svalBuilder.makeLoc(BR),
1096                                      C.getLocationContext());
1097     } else {
1098       // If the destination buffer's extent is not equal to the value of
1099       // third argument, just invalidate buffer.
1100       State = InvalidateBuffer(C, State, DstBuffer, MemVal,
1101                                /*IsSourceBuffer*/ false, Size);
1102     }
1103 
1104     if (StateNullChar && !StateNonNullChar) {
1105       // If the value of the second argument of 'memset()' is zero, set the
1106       // string length of destination buffer to 0 directly.
1107       State = setCStringLength(State, MR,
1108                                svalBuilder.makeZeroVal(Ctx.getSizeType()));
1109     } else if (!StateNullChar && StateNonNullChar) {
1110       SVal NewStrLen = svalBuilder.getMetadataSymbolVal(
1111           CStringChecker::getTag(), MR, DstBuffer, Ctx.getSizeType(),
1112           C.getLocationContext(), C.blockCount());
1113 
1114       // If the value of second argument is not zero, then the string length
1115       // is at least the size argument.
1116       SVal NewStrLenGESize = svalBuilder.evalBinOp(
1117           State, BO_GE, NewStrLen, SizeVal, svalBuilder.getConditionType());
1118 
1119       State = setCStringLength(
1120           State->assume(NewStrLenGESize.castAs<DefinedOrUnknownSVal>(), true),
1121           MR, NewStrLen);
1122     }
1123   } else {
1124     // If the offset is not zero and char value is not concrete, we can do
1125     // nothing but invalidate the buffer.
1126     State = InvalidateBuffer(C, State, DstBuffer, MemVal,
1127                              /*IsSourceBuffer*/ false, Size);
1128   }
1129   return true;
1130 }
1131 
1132 //===----------------------------------------------------------------------===//
1133 // evaluation of individual function calls.
1134 //===----------------------------------------------------------------------===//
1135 
1136 void CStringChecker::evalCopyCommon(CheckerContext &C,
1137                                     const CallExpr *CE,
1138                                     ProgramStateRef state,
1139                                     const Expr *Size, const Expr *Dest,
1140                                     const Expr *Source, bool Restricted,
1141                                     bool IsMempcpy) const {
1142   CurrentFunctionDescription = "memory copy function";
1143 
1144   // See if the size argument is zero.
1145   const LocationContext *LCtx = C.getLocationContext();
1146   SVal sizeVal = state->getSVal(Size, LCtx);
1147   QualType sizeTy = Size->getType();
1148 
1149   ProgramStateRef stateZeroSize, stateNonZeroSize;
1150   std::tie(stateZeroSize, stateNonZeroSize) =
1151     assumeZero(C, state, sizeVal, sizeTy);
1152 
1153   // Get the value of the Dest.
1154   SVal destVal = state->getSVal(Dest, LCtx);
1155 
1156   // If the size is zero, there won't be any actual memory access, so
1157   // just bind the return value to the destination buffer and return.
1158   if (stateZeroSize && !stateNonZeroSize) {
1159     stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
1160     C.addTransition(stateZeroSize);
1161     return;
1162   }
1163 
1164   // If the size can be nonzero, we have to check the other arguments.
1165   if (stateNonZeroSize) {
1166     state = stateNonZeroSize;
1167 
1168     // Ensure the destination is not null. If it is NULL there will be a
1169     // NULL pointer dereference.
1170     state = checkNonNull(C, state, Dest, destVal, 1);
1171     if (!state)
1172       return;
1173 
1174     // Get the value of the Src.
1175     SVal srcVal = state->getSVal(Source, LCtx);
1176 
1177     // Ensure the source is not null. If it is NULL there will be a
1178     // NULL pointer dereference.
1179     state = checkNonNull(C, state, Source, srcVal, 2);
1180     if (!state)
1181       return;
1182 
1183     // Ensure the accesses are valid and that the buffers do not overlap.
1184     const char * const writeWarning =
1185       "Memory copy function overflows destination buffer";
1186     state = CheckBufferAccess(C, state, Size, Dest, Source,
1187                               writeWarning, /* sourceWarning = */ nullptr);
1188     if (Restricted)
1189       state = CheckOverlap(C, state, Size, Dest, Source);
1190 
1191     if (!state)
1192       return;
1193 
1194     // If this is mempcpy, get the byte after the last byte copied and
1195     // bind the expr.
1196     if (IsMempcpy) {
1197       // Get the byte after the last byte copied.
1198       SValBuilder &SvalBuilder = C.getSValBuilder();
1199       ASTContext &Ctx = SvalBuilder.getContext();
1200       QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
1201       SVal DestRegCharVal =
1202           SvalBuilder.evalCast(destVal, CharPtrTy, Dest->getType());
1203       SVal lastElement = C.getSValBuilder().evalBinOp(
1204           state, BO_Add, DestRegCharVal, sizeVal, Dest->getType());
1205       // If we don't know how much we copied, we can at least
1206       // conjure a return value for later.
1207       if (lastElement.isUnknown())
1208         lastElement = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1209                                                           C.blockCount());
1210 
1211       // The byte after the last byte copied is the return value.
1212       state = state->BindExpr(CE, LCtx, lastElement);
1213     } else {
1214       // All other copies return the destination buffer.
1215       // (Well, bcopy() has a void return type, but this won't hurt.)
1216       state = state->BindExpr(CE, LCtx, destVal);
1217     }
1218 
1219     // Invalidate the destination (regular invalidation without pointer-escaping
1220     // the address of the top-level region).
1221     // FIXME: Even if we can't perfectly model the copy, we should see if we
1222     // can use LazyCompoundVals to copy the source values into the destination.
1223     // This would probably remove any existing bindings past the end of the
1224     // copied region, but that's still an improvement over blank invalidation.
1225     state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest),
1226                              /*IsSourceBuffer*/false, Size);
1227 
1228     // Invalidate the source (const-invalidation without const-pointer-escaping
1229     // the address of the top-level region).
1230     state = InvalidateBuffer(C, state, Source, C.getSVal(Source),
1231                              /*IsSourceBuffer*/true, nullptr);
1232 
1233     C.addTransition(state);
1234   }
1235 }
1236 
1237 
1238 void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
1239   // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
1240   // The return value is the address of the destination buffer.
1241   const Expr *Dest = CE->getArg(0);
1242   ProgramStateRef state = C.getState();
1243 
1244   evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
1245 }
1246 
1247 void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
1248   // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1249   // The return value is a pointer to the byte following the last written byte.
1250   const Expr *Dest = CE->getArg(0);
1251   ProgramStateRef state = C.getState();
1252 
1253   evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
1254 }
1255 
1256 void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
1257   // void *memmove(void *dst, const void *src, size_t n);
1258   // The return value is the address of the destination buffer.
1259   const Expr *Dest = CE->getArg(0);
1260   ProgramStateRef state = C.getState();
1261 
1262   evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
1263 }
1264 
1265 void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
1266   // void bcopy(const void *src, void *dst, size_t n);
1267   evalCopyCommon(C, CE, C.getState(),
1268                  CE->getArg(2), CE->getArg(1), CE->getArg(0));
1269 }
1270 
1271 void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
1272   // int memcmp(const void *s1, const void *s2, size_t n);
1273   CurrentFunctionDescription = "memory comparison function";
1274 
1275   const Expr *Left = CE->getArg(0);
1276   const Expr *Right = CE->getArg(1);
1277   const Expr *Size = CE->getArg(2);
1278 
1279   ProgramStateRef state = C.getState();
1280   SValBuilder &svalBuilder = C.getSValBuilder();
1281 
1282   // See if the size argument is zero.
1283   const LocationContext *LCtx = C.getLocationContext();
1284   SVal sizeVal = state->getSVal(Size, LCtx);
1285   QualType sizeTy = Size->getType();
1286 
1287   ProgramStateRef stateZeroSize, stateNonZeroSize;
1288   std::tie(stateZeroSize, stateNonZeroSize) =
1289     assumeZero(C, state, sizeVal, sizeTy);
1290 
1291   // If the size can be zero, the result will be 0 in that case, and we don't
1292   // have to check either of the buffers.
1293   if (stateZeroSize) {
1294     state = stateZeroSize;
1295     state = state->BindExpr(CE, LCtx,
1296                             svalBuilder.makeZeroVal(CE->getType()));
1297     C.addTransition(state);
1298   }
1299 
1300   // If the size can be nonzero, we have to check the other arguments.
1301   if (stateNonZeroSize) {
1302     state = stateNonZeroSize;
1303     // If we know the two buffers are the same, we know the result is 0.
1304     // First, get the two buffers' addresses. Another checker will have already
1305     // made sure they're not undefined.
1306     DefinedOrUnknownSVal LV =
1307         state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
1308     DefinedOrUnknownSVal RV =
1309         state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
1310 
1311     // See if they are the same.
1312     DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1313     ProgramStateRef StSameBuf, StNotSameBuf;
1314     std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1315 
1316     // If the two arguments might be the same buffer, we know the result is 0,
1317     // and we only need to check one size.
1318     if (StSameBuf) {
1319       state = StSameBuf;
1320       state = CheckBufferAccess(C, state, Size, Left);
1321       if (state) {
1322         state = StSameBuf->BindExpr(CE, LCtx,
1323                                     svalBuilder.makeZeroVal(CE->getType()));
1324         C.addTransition(state);
1325       }
1326     }
1327 
1328     // If the two arguments might be different buffers, we have to check the
1329     // size of both of them.
1330     if (StNotSameBuf) {
1331       state = StNotSameBuf;
1332       state = CheckBufferAccess(C, state, Size, Left, Right);
1333       if (state) {
1334         // The return value is the comparison result, which we don't know.
1335         SVal CmpV = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1336                                                  C.blockCount());
1337         state = state->BindExpr(CE, LCtx, CmpV);
1338         C.addTransition(state);
1339       }
1340     }
1341   }
1342 }
1343 
1344 void CStringChecker::evalstrLength(CheckerContext &C,
1345                                    const CallExpr *CE) const {
1346   // size_t strlen(const char *s);
1347   evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1348 }
1349 
1350 void CStringChecker::evalstrnLength(CheckerContext &C,
1351                                     const CallExpr *CE) const {
1352   // size_t strnlen(const char *s, size_t maxlen);
1353   evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1354 }
1355 
1356 void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
1357                                          bool IsStrnlen) const {
1358   CurrentFunctionDescription = "string length function";
1359   ProgramStateRef state = C.getState();
1360   const LocationContext *LCtx = C.getLocationContext();
1361 
1362   if (IsStrnlen) {
1363     const Expr *maxlenExpr = CE->getArg(1);
1364     SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1365 
1366     ProgramStateRef stateZeroSize, stateNonZeroSize;
1367     std::tie(stateZeroSize, stateNonZeroSize) =
1368       assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1369 
1370     // If the size can be zero, the result will be 0 in that case, and we don't
1371     // have to check the string itself.
1372     if (stateZeroSize) {
1373       SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
1374       stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
1375       C.addTransition(stateZeroSize);
1376     }
1377 
1378     // If the size is GUARANTEED to be zero, we're done!
1379     if (!stateNonZeroSize)
1380       return;
1381 
1382     // Otherwise, record the assumption that the size is nonzero.
1383     state = stateNonZeroSize;
1384   }
1385 
1386   // Check that the string argument is non-null.
1387   const Expr *Arg = CE->getArg(0);
1388   SVal ArgVal = state->getSVal(Arg, LCtx);
1389 
1390   state = checkNonNull(C, state, Arg, ArgVal, 1);
1391 
1392   if (!state)
1393     return;
1394 
1395   SVal strLength = getCStringLength(C, state, Arg, ArgVal);
1396 
1397   // If the argument isn't a valid C string, there's no valid state to
1398   // transition to.
1399   if (strLength.isUndef())
1400     return;
1401 
1402   DefinedOrUnknownSVal result = UnknownVal();
1403 
1404   // If the check is for strnlen() then bind the return value to no more than
1405   // the maxlen value.
1406   if (IsStrnlen) {
1407     QualType cmpTy = C.getSValBuilder().getConditionType();
1408 
1409     // It's a little unfortunate to be getting this again,
1410     // but it's not that expensive...
1411     const Expr *maxlenExpr = CE->getArg(1);
1412     SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1413 
1414     Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1415     Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
1416 
1417     if (strLengthNL && maxlenValNL) {
1418       ProgramStateRef stateStringTooLong, stateStringNotTooLong;
1419 
1420       // Check if the strLength is greater than the maxlen.
1421       std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
1422           C.getSValBuilder()
1423               .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1424               .castAs<DefinedOrUnknownSVal>());
1425 
1426       if (stateStringTooLong && !stateStringNotTooLong) {
1427         // If the string is longer than maxlen, return maxlen.
1428         result = *maxlenValNL;
1429       } else if (stateStringNotTooLong && !stateStringTooLong) {
1430         // If the string is shorter than maxlen, return its length.
1431         result = *strLengthNL;
1432       }
1433     }
1434 
1435     if (result.isUnknown()) {
1436       // If we don't have enough information for a comparison, there's
1437       // no guarantee the full string length will actually be returned.
1438       // All we know is the return value is the min of the string length
1439       // and the limit. This is better than nothing.
1440       result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1441                                                    C.blockCount());
1442       NonLoc resultNL = result.castAs<NonLoc>();
1443 
1444       if (strLengthNL) {
1445         state = state->assume(C.getSValBuilder().evalBinOpNN(
1446                                   state, BO_LE, resultNL, *strLengthNL, cmpTy)
1447                                   .castAs<DefinedOrUnknownSVal>(), true);
1448       }
1449 
1450       if (maxlenValNL) {
1451         state = state->assume(C.getSValBuilder().evalBinOpNN(
1452                                   state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1453                                   .castAs<DefinedOrUnknownSVal>(), true);
1454       }
1455     }
1456 
1457   } else {
1458     // This is a plain strlen(), not strnlen().
1459     result = strLength.castAs<DefinedOrUnknownSVal>();
1460 
1461     // If we don't know the length of the string, conjure a return
1462     // value, so it can be used in constraints, at least.
1463     if (result.isUnknown()) {
1464       result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1465                                                    C.blockCount());
1466     }
1467   }
1468 
1469   // Bind the return value.
1470   assert(!result.isUnknown() && "Should have conjured a value by now");
1471   state = state->BindExpr(CE, LCtx, result);
1472   C.addTransition(state);
1473 }
1474 
1475 void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
1476   // char *strcpy(char *restrict dst, const char *restrict src);
1477   evalStrcpyCommon(C, CE,
1478                    /* ReturnEnd = */ false,
1479                    /* IsBounded = */ false,
1480                    /* appendK = */ ConcatFnKind::none);
1481 }
1482 
1483 void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
1484   // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
1485   evalStrcpyCommon(C, CE,
1486                    /* ReturnEnd = */ false,
1487                    /* IsBounded = */ true,
1488                    /* appendK = */ ConcatFnKind::none);
1489 }
1490 
1491 void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
1492   // char *stpcpy(char *restrict dst, const char *restrict src);
1493   evalStrcpyCommon(C, CE,
1494                    /* ReturnEnd = */ true,
1495                    /* IsBounded = */ false,
1496                    /* appendK = */ ConcatFnKind::none);
1497 }
1498 
1499 void CStringChecker::evalStrlcpy(CheckerContext &C, const CallExpr *CE) const {
1500   // size_t strlcpy(char *dest, const char *src, size_t size);
1501   evalStrcpyCommon(C, CE,
1502                    /* ReturnEnd = */ true,
1503                    /* IsBounded = */ true,
1504                    /* appendK = */ ConcatFnKind::none,
1505                    /* returnPtr = */ false);
1506 }
1507 
1508 void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
1509   // char *strcat(char *restrict s1, const char *restrict s2);
1510   evalStrcpyCommon(C, CE,
1511                    /* ReturnEnd = */ false,
1512                    /* IsBounded = */ false,
1513                    /* appendK = */ ConcatFnKind::strcat);
1514 }
1515 
1516 void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
1517   //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1518   evalStrcpyCommon(C, CE,
1519                    /* ReturnEnd = */ false,
1520                    /* IsBounded = */ true,
1521                    /* appendK = */ ConcatFnKind::strcat);
1522 }
1523 
1524 void CStringChecker::evalStrlcat(CheckerContext &C, const CallExpr *CE) const {
1525   // size_t strlcat(char *dst, const char *src, size_t size);
1526   // It will append at most size - strlen(dst) - 1 bytes,
1527   // NULL-terminating the result.
1528   evalStrcpyCommon(C, CE,
1529                    /* ReturnEnd = */ false,
1530                    /* IsBounded = */ true,
1531                    /* appendK = */ ConcatFnKind::strlcat,
1532                    /* returnPtr = */ false);
1533 }
1534 
1535 void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
1536                                       bool ReturnEnd, bool IsBounded,
1537                                       ConcatFnKind appendK,
1538                                       bool returnPtr) const {
1539   CurrentFunctionDescription = "string copy 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, *strLengthNL);
1708             } else if (dstStrLengthNL) {
1709               // strlcat returns strlen(src) + strlen(dst)
1710               SVal retSize = svalBuilder.evalBinOpNN(
1711                   state, BO_Add, *strLengthNL, *dstStrLengthNL, sizeTy);
1712               StateZeroSize =
1713                   StateZeroSize->BindExpr(CE, LCtx, *(retSize.getAs<NonLoc>()));
1714             }
1715           }
1716           C.addTransition(StateZeroSize);
1717           return;
1718         }
1719 
1720         // Otherwise, go ahead and figure out the last element we'll touch.
1721         // We don't record the non-zero assumption here because we can't
1722         // be sure. We won't warn on a possible zero.
1723         NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
1724         maxLastElementIndex =
1725             svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL, one, sizeTy);
1726         boundWarning = "Size argument is greater than the length of the "
1727                        "destination buffer";
1728         break;
1729       }
1730     }
1731   } else {
1732     // The function isn't bounded. The amount copied should match the length
1733     // of the source buffer.
1734     amountCopied = strLength;
1735   }
1736 
1737   assert(state);
1738 
1739   // This represents the number of characters copied into the destination
1740   // buffer. (It may not actually be the strlen if the destination buffer
1741   // is not terminated.)
1742   SVal finalStrLength = UnknownVal();
1743   SVal strlRetVal = UnknownVal();
1744 
1745   if (appendK == ConcatFnKind::none && !returnPtr) {
1746     // strlcpy returns the sizeof(src)
1747     strlRetVal = strLength;
1748   }
1749 
1750   // If this is an appending function (strcat, strncat...) then set the
1751   // string length to strlen(src) + strlen(dst) since the buffer will
1752   // ultimately contain both.
1753   if (appendK != ConcatFnKind::none) {
1754     // Get the string length of the destination. If the destination is memory
1755     // that can't have a string length, we shouldn't be copying into it anyway.
1756     if (dstStrLength.isUndef())
1757       return;
1758 
1759     if (appendK == ConcatFnKind::strlcat && dstStrLengthNL && strLengthNL) {
1760       strlRetVal = svalBuilder.evalBinOpNN(state, BO_Add, *strLengthNL,
1761                                            *dstStrLengthNL, sizeTy);
1762     }
1763 
1764     Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>();
1765 
1766     // If we know both string lengths, we might know the final string length.
1767     if (amountCopiedNL && dstStrLengthNL) {
1768       // Make sure the two lengths together don't overflow a size_t.
1769       state = checkAdditionOverflow(C, state, *amountCopiedNL, *dstStrLengthNL);
1770       if (!state)
1771         return;
1772 
1773       finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *amountCopiedNL,
1774                                                *dstStrLengthNL, sizeTy);
1775     }
1776 
1777     // If we couldn't get a single value for the final string length,
1778     // we can at least bound it by the individual lengths.
1779     if (finalStrLength.isUnknown()) {
1780       // Try to get a "hypothetical" string length symbol, which we can later
1781       // set as a real value if that turns out to be the case.
1782       finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1783       assert(!finalStrLength.isUndef());
1784 
1785       if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
1786         if (amountCopiedNL && appendK == ConcatFnKind::none) {
1787           // we overwrite dst string with the src
1788           // finalStrLength >= srcStrLength
1789           SVal sourceInResult = svalBuilder.evalBinOpNN(
1790               state, BO_GE, *finalStrLengthNL, *amountCopiedNL, cmpTy);
1791           state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
1792                                 true);
1793           if (!state)
1794             return;
1795         }
1796 
1797         if (dstStrLengthNL && appendK != ConcatFnKind::none) {
1798           // we extend the dst string with the src
1799           // finalStrLength >= dstStrLength
1800           SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1801                                                       *finalStrLengthNL,
1802                                                       *dstStrLengthNL,
1803                                                       cmpTy);
1804           state =
1805               state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
1806           if (!state)
1807             return;
1808         }
1809       }
1810     }
1811 
1812   } else {
1813     // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1814     // the final string length will match the input string length.
1815     finalStrLength = amountCopied;
1816   }
1817 
1818   SVal Result;
1819 
1820   if (returnPtr) {
1821     // The final result of the function will either be a pointer past the last
1822     // copied element, or a pointer to the start of the destination buffer.
1823     Result = (ReturnEnd ? UnknownVal() : DstVal);
1824   } else {
1825     if (appendK == ConcatFnKind::strlcat || appendK == ConcatFnKind::none)
1826       //strlcpy, strlcat
1827       Result = strlRetVal;
1828     else
1829       Result = finalStrLength;
1830   }
1831 
1832   assert(state);
1833 
1834   // If the destination is a MemRegion, try to check for a buffer overflow and
1835   // record the new string length.
1836   if (Optional<loc::MemRegionVal> dstRegVal =
1837       DstVal.getAs<loc::MemRegionVal>()) {
1838     QualType ptrTy = Dst->getType();
1839 
1840     // If we have an exact value on a bounded copy, use that to check for
1841     // overflows, rather than our estimate about how much is actually copied.
1842     if (boundWarning) {
1843       if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
1844         SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1845             *maxLastNL, ptrTy);
1846         state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1847             boundWarning);
1848         if (!state)
1849           return;
1850       }
1851     }
1852 
1853     // Then, if the final length is known...
1854     if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
1855       SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1856           *knownStrLength, ptrTy);
1857 
1858       // ...and we haven't checked the bound, we'll check the actual copy.
1859       if (!boundWarning) {
1860         const char * const warningMsg =
1861           "String copy function overflows destination buffer";
1862         state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1863         if (!state)
1864           return;
1865       }
1866 
1867       // If this is a stpcpy-style copy, the last element is the return value.
1868       if (returnPtr && ReturnEnd)
1869         Result = lastElement;
1870     }
1871 
1872     // Invalidate the destination (regular invalidation without pointer-escaping
1873     // the address of the top-level region). This must happen before we set the
1874     // C string length because invalidation will clear the length.
1875     // FIXME: Even if we can't perfectly model the copy, we should see if we
1876     // can use LazyCompoundVals to copy the source values into the destination.
1877     // This would probably remove any existing bindings past the end of the
1878     // string, but that's still an improvement over blank invalidation.
1879     state = InvalidateBuffer(C, state, Dst, *dstRegVal,
1880         /*IsSourceBuffer*/false, nullptr);
1881 
1882     // Invalidate the source (const-invalidation without const-pointer-escaping
1883     // the address of the top-level region).
1884     state = InvalidateBuffer(C, state, srcExpr, srcVal, /*IsSourceBuffer*/true,
1885         nullptr);
1886 
1887     // Set the C string length of the destination, if we know it.
1888     if (IsBounded && (appendK == ConcatFnKind::none)) {
1889       // strncpy is annoying in that it doesn't guarantee to null-terminate
1890       // the result string. If the original string didn't fit entirely inside
1891       // the bound (including the null-terminator), we don't know how long the
1892       // result is.
1893       if (amountCopied != strLength)
1894         finalStrLength = UnknownVal();
1895     }
1896     state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
1897   }
1898 
1899   assert(state);
1900 
1901   if (returnPtr) {
1902     // If this is a stpcpy-style copy, but we were unable to check for a buffer
1903     // overflow, we still need a result. Conjure a return value.
1904     if (ReturnEnd && Result.isUnknown()) {
1905       Result = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
1906     }
1907   }
1908   // Set the return value.
1909   state = state->BindExpr(CE, LCtx, Result);
1910   C.addTransition(state);
1911 }
1912 
1913 void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1914   //int strcmp(const char *s1, const char *s2);
1915   evalStrcmpCommon(C, CE, /* IsBounded = */ false, /* IgnoreCase = */ false);
1916 }
1917 
1918 void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
1919   //int strncmp(const char *s1, const char *s2, size_t n);
1920   evalStrcmpCommon(C, CE, /* IsBounded = */ true, /* IgnoreCase = */ false);
1921 }
1922 
1923 void CStringChecker::evalStrcasecmp(CheckerContext &C,
1924     const CallExpr *CE) const {
1925   //int strcasecmp(const char *s1, const char *s2);
1926   evalStrcmpCommon(C, CE, /* IsBounded = */ false, /* IgnoreCase = */ true);
1927 }
1928 
1929 void CStringChecker::evalStrncasecmp(CheckerContext &C,
1930     const CallExpr *CE) const {
1931   //int strncasecmp(const char *s1, const char *s2, size_t n);
1932   evalStrcmpCommon(C, CE, /* IsBounded = */ true, /* IgnoreCase = */ true);
1933 }
1934 
1935 void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
1936     bool IsBounded, bool IgnoreCase) const {
1937   CurrentFunctionDescription = "string comparison function";
1938   ProgramStateRef state = C.getState();
1939   const LocationContext *LCtx = C.getLocationContext();
1940 
1941   // Check that the first string is non-null
1942   const Expr *s1 = CE->getArg(0);
1943   SVal s1Val = state->getSVal(s1, LCtx);
1944   state = checkNonNull(C, state, s1, s1Val, 1);
1945   if (!state)
1946     return;
1947 
1948   // Check that the second string is non-null.
1949   const Expr *s2 = CE->getArg(1);
1950   SVal s2Val = state->getSVal(s2, LCtx);
1951   state = checkNonNull(C, state, s2, s2Val, 2);
1952   if (!state)
1953     return;
1954 
1955   // Get the string length of the first string or give up.
1956   SVal s1Length = getCStringLength(C, state, s1, s1Val);
1957   if (s1Length.isUndef())
1958     return;
1959 
1960   // Get the string length of the second string or give up.
1961   SVal s2Length = getCStringLength(C, state, s2, s2Val);
1962   if (s2Length.isUndef())
1963     return;
1964 
1965   // If we know the two buffers are the same, we know the result is 0.
1966   // First, get the two buffers' addresses. Another checker will have already
1967   // made sure they're not undefined.
1968   DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1969   DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
1970 
1971   // See if they are the same.
1972   SValBuilder &svalBuilder = C.getSValBuilder();
1973   DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1974   ProgramStateRef StSameBuf, StNotSameBuf;
1975   std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1976 
1977   // If the two arguments might be the same buffer, we know the result is 0,
1978   // and we only need to check one size.
1979   if (StSameBuf) {
1980     StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1981         svalBuilder.makeZeroVal(CE->getType()));
1982     C.addTransition(StSameBuf);
1983 
1984     // If the two arguments are GUARANTEED to be the same, we're done!
1985     if (!StNotSameBuf)
1986       return;
1987   }
1988 
1989   assert(StNotSameBuf);
1990   state = StNotSameBuf;
1991 
1992   // At this point we can go about comparing the two buffers.
1993   // For now, we only do this if they're both known string literals.
1994 
1995   // Attempt to extract string literals from both expressions.
1996   const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1997   const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1998   bool canComputeResult = false;
1999   SVal resultVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
2000       C.blockCount());
2001 
2002   if (s1StrLiteral && s2StrLiteral) {
2003     StringRef s1StrRef = s1StrLiteral->getString();
2004     StringRef s2StrRef = s2StrLiteral->getString();
2005 
2006     if (IsBounded) {
2007       // Get the max number of characters to compare.
2008       const Expr *lenExpr = CE->getArg(2);
2009       SVal lenVal = state->getSVal(lenExpr, LCtx);
2010 
2011       // If the length is known, we can get the right substrings.
2012       if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
2013         // Create substrings of each to compare the prefix.
2014         s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
2015         s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
2016         canComputeResult = true;
2017       }
2018     } else {
2019       // This is a normal, unbounded strcmp.
2020       canComputeResult = true;
2021     }
2022 
2023     if (canComputeResult) {
2024       // Real strcmp stops at null characters.
2025       size_t s1Term = s1StrRef.find('\0');
2026       if (s1Term != StringRef::npos)
2027         s1StrRef = s1StrRef.substr(0, s1Term);
2028 
2029       size_t s2Term = s2StrRef.find('\0');
2030       if (s2Term != StringRef::npos)
2031         s2StrRef = s2StrRef.substr(0, s2Term);
2032 
2033       // Use StringRef's comparison methods to compute the actual result.
2034       int compareRes = IgnoreCase ? s1StrRef.compare_lower(s2StrRef)
2035         : s1StrRef.compare(s2StrRef);
2036 
2037       // The strcmp function returns an integer greater than, equal to, or less
2038       // than zero, [c11, p7.24.4.2].
2039       if (compareRes == 0) {
2040         resultVal = svalBuilder.makeIntVal(compareRes, CE->getType());
2041       }
2042       else {
2043         DefinedSVal zeroVal = svalBuilder.makeIntVal(0, CE->getType());
2044         // Constrain strcmp's result range based on the result of StringRef's
2045         // comparison methods.
2046         BinaryOperatorKind op = (compareRes == 1) ? BO_GT : BO_LT;
2047         SVal compareWithZero =
2048           svalBuilder.evalBinOp(state, op, resultVal, zeroVal,
2049               svalBuilder.getConditionType());
2050         DefinedSVal compareWithZeroVal = compareWithZero.castAs<DefinedSVal>();
2051         state = state->assume(compareWithZeroVal, true);
2052       }
2053     }
2054   }
2055 
2056   state = state->BindExpr(CE, LCtx, resultVal);
2057 
2058   // Record this as a possible path.
2059   C.addTransition(state);
2060 }
2061 
2062 void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
2063   //char *strsep(char **stringp, const char *delim);
2064   // Sanity: does the search string parameter match the return type?
2065   const Expr *SearchStrPtr = CE->getArg(0);
2066   QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
2067   if (CharPtrTy.isNull() ||
2068       CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
2069     return;
2070 
2071   CurrentFunctionDescription = "strsep()";
2072   ProgramStateRef State = C.getState();
2073   const LocationContext *LCtx = C.getLocationContext();
2074 
2075   // Check that the search string pointer is non-null (though it may point to
2076   // a null string).
2077   SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
2078   State = checkNonNull(C, State, SearchStrPtr, SearchStrVal, 1);
2079   if (!State)
2080     return;
2081 
2082   // Check that the delimiter string is non-null.
2083   const Expr *DelimStr = CE->getArg(1);
2084   SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
2085   State = checkNonNull(C, State, DelimStr, DelimStrVal, 2);
2086   if (!State)
2087     return;
2088 
2089   SValBuilder &SVB = C.getSValBuilder();
2090   SVal Result;
2091   if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
2092     // Get the current value of the search string pointer, as a char*.
2093     Result = State->getSVal(*SearchStrLoc, CharPtrTy);
2094 
2095     // Invalidate the search string, representing the change of one delimiter
2096     // character to NUL.
2097     State = InvalidateBuffer(C, State, SearchStrPtr, Result,
2098         /*IsSourceBuffer*/false, nullptr);
2099 
2100     // Overwrite the search string pointer. The new value is either an address
2101     // further along in the same string, or NULL if there are no more tokens.
2102     State = State->bindLoc(*SearchStrLoc,
2103         SVB.conjureSymbolVal(getTag(),
2104           CE,
2105           LCtx,
2106           CharPtrTy,
2107           C.blockCount()),
2108         LCtx);
2109   } else {
2110     assert(SearchStrVal.isUnknown());
2111     // Conjure a symbolic value. It's the best we can do.
2112     Result = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
2113   }
2114 
2115   // Set the return value, and finish.
2116   State = State->BindExpr(CE, LCtx, Result);
2117   C.addTransition(State);
2118 }
2119 
2120 // These should probably be moved into a C++ standard library checker.
2121 void CStringChecker::evalStdCopy(CheckerContext &C, const CallExpr *CE) const {
2122   evalStdCopyCommon(C, CE);
2123 }
2124 
2125 void CStringChecker::evalStdCopyBackward(CheckerContext &C,
2126     const CallExpr *CE) const {
2127   evalStdCopyCommon(C, CE);
2128 }
2129 
2130 void CStringChecker::evalStdCopyCommon(CheckerContext &C,
2131     const CallExpr *CE) const {
2132   if (!CE->getArg(2)->getType()->isPointerType())
2133     return;
2134 
2135   ProgramStateRef State = C.getState();
2136 
2137   const LocationContext *LCtx = C.getLocationContext();
2138 
2139   // template <class _InputIterator, class _OutputIterator>
2140   // _OutputIterator
2141   // copy(_InputIterator __first, _InputIterator __last,
2142   //        _OutputIterator __result)
2143 
2144   // Invalidate the destination buffer
2145   const Expr *Dst = CE->getArg(2);
2146   SVal DstVal = State->getSVal(Dst, LCtx);
2147   State = InvalidateBuffer(C, State, Dst, DstVal, /*IsSource=*/false,
2148       /*Size=*/nullptr);
2149 
2150   SValBuilder &SVB = C.getSValBuilder();
2151 
2152   SVal ResultVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
2153   State = State->BindExpr(CE, LCtx, ResultVal);
2154 
2155   C.addTransition(State);
2156 }
2157 
2158 void CStringChecker::evalMemset(CheckerContext &C, const CallExpr *CE) const {
2159   CurrentFunctionDescription = "memory set function";
2160 
2161   const Expr *Mem = CE->getArg(0);
2162   const Expr *CharE = CE->getArg(1);
2163   const Expr *Size = CE->getArg(2);
2164   ProgramStateRef State = C.getState();
2165 
2166   // See if the size argument is zero.
2167   const LocationContext *LCtx = C.getLocationContext();
2168   SVal SizeVal = State->getSVal(Size, LCtx);
2169   QualType SizeTy = Size->getType();
2170 
2171   ProgramStateRef StateZeroSize, StateNonZeroSize;
2172   std::tie(StateZeroSize, StateNonZeroSize) =
2173     assumeZero(C, State, SizeVal, SizeTy);
2174 
2175   // Get the value of the memory area.
2176   SVal MemVal = State->getSVal(Mem, LCtx);
2177 
2178   // If the size is zero, there won't be any actual memory access, so
2179   // just bind the return value to the Mem buffer and return.
2180   if (StateZeroSize && !StateNonZeroSize) {
2181     StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, MemVal);
2182     C.addTransition(StateZeroSize);
2183     return;
2184   }
2185 
2186   // Ensure the memory area is not null.
2187   // If it is NULL there will be a NULL pointer dereference.
2188   State = checkNonNull(C, StateNonZeroSize, Mem, MemVal, 1);
2189   if (!State)
2190     return;
2191 
2192   State = CheckBufferAccess(C, State, Size, Mem);
2193   if (!State)
2194     return;
2195 
2196   // According to the values of the arguments, bind the value of the second
2197   // argument to the destination buffer and set string length, or just
2198   // invalidate the destination buffer.
2199   if (!memsetAux(Mem, C.getSVal(CharE), Size, C, State))
2200     return;
2201 
2202   State = State->BindExpr(CE, LCtx, MemVal);
2203   C.addTransition(State);
2204 }
2205 
2206 void CStringChecker::evalBzero(CheckerContext &C, const CallExpr *CE) const {
2207   CurrentFunctionDescription = "memory clearance function";
2208 
2209   const Expr *Mem = CE->getArg(0);
2210   const Expr *Size = CE->getArg(1);
2211   SVal Zero = C.getSValBuilder().makeZeroVal(C.getASTContext().IntTy);
2212 
2213   ProgramStateRef State = C.getState();
2214 
2215   // See if the size argument is zero.
2216   SVal SizeVal = C.getSVal(Size);
2217   QualType SizeTy = Size->getType();
2218 
2219   ProgramStateRef StateZeroSize, StateNonZeroSize;
2220   std::tie(StateZeroSize, StateNonZeroSize) =
2221     assumeZero(C, State, SizeVal, SizeTy);
2222 
2223   // If the size is zero, there won't be any actual memory access,
2224   // In this case we just return.
2225   if (StateZeroSize && !StateNonZeroSize) {
2226     C.addTransition(StateZeroSize);
2227     return;
2228   }
2229 
2230   // Get the value of the memory area.
2231   SVal MemVal = C.getSVal(Mem);
2232 
2233   // Ensure the memory area is not null.
2234   // If it is NULL there will be a NULL pointer dereference.
2235   State = checkNonNull(C, StateNonZeroSize, Mem, MemVal, 1);
2236   if (!State)
2237     return;
2238 
2239   State = CheckBufferAccess(C, State, Size, Mem);
2240   if (!State)
2241     return;
2242 
2243   if (!memsetAux(Mem, Zero, Size, C, State))
2244     return;
2245 
2246   C.addTransition(State);
2247 }
2248 
2249 //===----------------------------------------------------------------------===//
2250 // The driver method, and other Checker callbacks.
2251 //===----------------------------------------------------------------------===//
2252 
2253 CStringChecker::FnCheck CStringChecker::identifyCall(const CallEvent &Call,
2254                                                      CheckerContext &C) const {
2255   const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
2256   if (!CE)
2257     return nullptr;
2258 
2259   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
2260   if (!FD)
2261     return nullptr;
2262 
2263   if (Call.isCalled(StdCopy)) {
2264     return &CStringChecker::evalStdCopy;
2265   } else if (Call.isCalled(StdCopyBackward)) {
2266     return &CStringChecker::evalStdCopyBackward;
2267   }
2268 
2269   // Pro-actively check that argument types are safe to do arithmetic upon.
2270   // We do not want to crash if someone accidentally passes a structure
2271   // into, say, a C++ overload of any of these functions. We could not check
2272   // that for std::copy because they may have arguments of other types.
2273   for (auto I : CE->arguments()) {
2274     QualType T = I->getType();
2275     if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
2276       return nullptr;
2277   }
2278 
2279   const FnCheck *Callback = Callbacks.lookup(Call);
2280   if (Callback)
2281     return *Callback;
2282 
2283   return nullptr;
2284 }
2285 
2286 bool CStringChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
2287   FnCheck Callback = identifyCall(Call, C);
2288 
2289   // If the callee isn't a string function, let another checker handle it.
2290   if (!Callback)
2291     return false;
2292 
2293   // Check and evaluate the call.
2294   const auto *CE = cast<CallExpr>(Call.getOriginExpr());
2295   (this->*Callback)(C, CE);
2296 
2297   // If the evaluate call resulted in no change, chain to the next eval call
2298   // handler.
2299   // Note, the custom CString evaluation calls assume that basic safety
2300   // properties are held. However, if the user chooses to turn off some of these
2301   // checks, we ignore the issues and leave the call evaluation to a generic
2302   // handler.
2303   return C.isDifferent();
2304 }
2305 
2306 void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
2307   // Record string length for char a[] = "abc";
2308   ProgramStateRef state = C.getState();
2309 
2310   for (const auto *I : DS->decls()) {
2311     const VarDecl *D = dyn_cast<VarDecl>(I);
2312     if (!D)
2313       continue;
2314 
2315     // FIXME: Handle array fields of structs.
2316     if (!D->getType()->isArrayType())
2317       continue;
2318 
2319     const Expr *Init = D->getInit();
2320     if (!Init)
2321       continue;
2322     if (!isa<StringLiteral>(Init))
2323       continue;
2324 
2325     Loc VarLoc = state->getLValue(D, C.getLocationContext());
2326     const MemRegion *MR = VarLoc.getAsRegion();
2327     if (!MR)
2328       continue;
2329 
2330     SVal StrVal = C.getSVal(Init);
2331     assert(StrVal.isValid() && "Initializer string is unknown or undefined");
2332     DefinedOrUnknownSVal strLength =
2333       getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
2334 
2335     state = state->set<CStringLength>(MR, strLength);
2336   }
2337 
2338   C.addTransition(state);
2339 }
2340 
2341 ProgramStateRef
2342 CStringChecker::checkRegionChanges(ProgramStateRef state,
2343     const InvalidatedSymbols *,
2344     ArrayRef<const MemRegion *> ExplicitRegions,
2345     ArrayRef<const MemRegion *> Regions,
2346     const LocationContext *LCtx,
2347     const CallEvent *Call) const {
2348   CStringLengthTy Entries = state->get<CStringLength>();
2349   if (Entries.isEmpty())
2350     return state;
2351 
2352   llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
2353   llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
2354 
2355   // First build sets for the changed regions and their super-regions.
2356   for (ArrayRef<const MemRegion *>::iterator
2357       I = Regions.begin(), E = Regions.end(); I != E; ++I) {
2358     const MemRegion *MR = *I;
2359     Invalidated.insert(MR);
2360 
2361     SuperRegions.insert(MR);
2362     while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
2363       MR = SR->getSuperRegion();
2364       SuperRegions.insert(MR);
2365     }
2366   }
2367 
2368   CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2369 
2370   // Then loop over the entries in the current state.
2371   for (CStringLengthTy::iterator I = Entries.begin(),
2372       E = Entries.end(); I != E; ++I) {
2373     const MemRegion *MR = I.getKey();
2374 
2375     // Is this entry for a super-region of a changed region?
2376     if (SuperRegions.count(MR)) {
2377       Entries = F.remove(Entries, MR);
2378       continue;
2379     }
2380 
2381     // Is this entry for a sub-region of a changed region?
2382     const MemRegion *Super = MR;
2383     while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2384       Super = SR->getSuperRegion();
2385       if (Invalidated.count(Super)) {
2386         Entries = F.remove(Entries, MR);
2387         break;
2388       }
2389     }
2390   }
2391 
2392   return state->set<CStringLength>(Entries);
2393 }
2394 
2395 void CStringChecker::checkLiveSymbols(ProgramStateRef state,
2396     SymbolReaper &SR) const {
2397   // Mark all symbols in our string length map as valid.
2398   CStringLengthTy Entries = state->get<CStringLength>();
2399 
2400   for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2401       I != E; ++I) {
2402     SVal Len = I.getData();
2403 
2404     for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2405         se = Len.symbol_end(); si != se; ++si)
2406       SR.markInUse(*si);
2407   }
2408 }
2409 
2410 void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2411     CheckerContext &C) const {
2412   ProgramStateRef state = C.getState();
2413   CStringLengthTy Entries = state->get<CStringLength>();
2414   if (Entries.isEmpty())
2415     return;
2416 
2417   CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2418   for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2419       I != E; ++I) {
2420     SVal Len = I.getData();
2421     if (SymbolRef Sym = Len.getAsSymbol()) {
2422       if (SR.isDead(Sym))
2423         Entries = F.remove(Entries, I.getKey());
2424     }
2425   }
2426 
2427   state = state->set<CStringLength>(Entries);
2428   C.addTransition(state);
2429 }
2430 
2431 void ento::registerCStringModeling(CheckerManager &Mgr) {
2432   Mgr.registerChecker<CStringChecker>();
2433 }
2434 
2435 bool ento::shouldRegisterCStringModeling(const LangOptions &LO) {
2436   return true;
2437 }
2438 
2439 #define REGISTER_CHECKER(name)                                                 \
2440   void ento::register##name(CheckerManager &mgr) {                             \
2441     CStringChecker *checker = mgr.getChecker<CStringChecker>();                \
2442     checker->Filter.Check##name = true;                                        \
2443     checker->Filter.CheckName##name = mgr.getCurrentCheckerName();             \
2444   }                                                                            \
2445                                                                                \
2446   bool ento::shouldRegister##name(const LangOptions &LO) { return true; }
2447 
2448 REGISTER_CHECKER(CStringNullArg)
2449 REGISTER_CHECKER(CStringOutOfBounds)
2450 REGISTER_CHECKER(CStringBufferOverlap)
2451 REGISTER_CHECKER(CStringNotNullTerm)
2452