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