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