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