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