xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp (revision c19843714c5a8bbd9d28302daf8364c0a7ff12f9)
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 returnPtr = true) 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                    /* returnPtr = */ false);
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                    /* returnPtr = */ false);
1443 }
1444 
1445 void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
1446                                       bool returnEnd, bool isBounded,
1447                                       bool isAppending, bool returnPtr) 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   state = CheckOverlap(C, state, isBounded ? CE->getArg(2) : CE->getArg(1), Dst, srcExpr);
1486 
1487   if (!state)
1488     return;
1489 
1490   // If the function is strncpy, strncat, etc... it is bounded.
1491   if (isBounded) {
1492     // Get the max number of characters to copy.
1493     const Expr *lenExpr = CE->getArg(2);
1494     SVal lenVal = state->getSVal(lenExpr, LCtx);
1495 
1496     // Protect against misdeclared strncpy().
1497     lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
1498 
1499     Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1500     Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
1501 
1502     // If we know both values, we might be able to figure out how much
1503     // we're copying.
1504     if (strLengthNL && lenValNL) {
1505       ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
1506 
1507       // Check if the max number to copy is less than the length of the src.
1508       // If the bound is equal to the source length, strncpy won't null-
1509       // terminate the result!
1510       std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
1511           svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1512               .castAs<DefinedOrUnknownSVal>());
1513 
1514       if (stateSourceTooLong && !stateSourceNotTooLong) {
1515         // Max number to copy is less than the length of the src, so the actual
1516         // strLength copied is the max number arg.
1517         state = stateSourceTooLong;
1518         amountCopied = lenVal;
1519 
1520       } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1521         // The source buffer entirely fits in the bound.
1522         state = stateSourceNotTooLong;
1523         amountCopied = strLength;
1524       }
1525     }
1526 
1527     // We still want to know if the bound is known to be too large.
1528     if (lenValNL) {
1529       if (isAppending) {
1530         // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1531 
1532         // Get the string length of the destination. If the destination is
1533         // memory that can't have a string length, we shouldn't be copying
1534         // into it anyway.
1535         SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1536         if (dstStrLength.isUndef())
1537           return;
1538 
1539         if (Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>()) {
1540           maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1541                                                         *lenValNL,
1542                                                         *dstStrLengthNL,
1543                                                         sizeTy);
1544           boundWarning = "Size argument is greater than the free space in the "
1545                          "destination buffer";
1546         }
1547 
1548       } else {
1549         // For strncpy, this is just checking that lenVal <= sizeof(dst)
1550         // (Yes, strncpy and strncat differ in how they treat termination.
1551         // strncat ALWAYS terminates, but strncpy doesn't.)
1552 
1553         // We need a special case for when the copy size is zero, in which
1554         // case strncpy will do no work at all. Our bounds check uses n-1
1555         // as the last element accessed, so n == 0 is problematic.
1556         ProgramStateRef StateZeroSize, StateNonZeroSize;
1557         std::tie(StateZeroSize, StateNonZeroSize) =
1558           assumeZero(C, state, *lenValNL, sizeTy);
1559 
1560         // If the size is known to be zero, we're done.
1561         if (StateZeroSize && !StateNonZeroSize) {
1562           StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1563           C.addTransition(StateZeroSize);
1564           return;
1565         }
1566 
1567         // Otherwise, go ahead and figure out the last element we'll touch.
1568         // We don't record the non-zero assumption here because we can't
1569         // be sure. We won't warn on a possible zero.
1570         NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
1571         maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1572                                                       one, sizeTy);
1573         boundWarning = "Size argument is greater than the length of the "
1574                        "destination buffer";
1575       }
1576     }
1577 
1578     // If we couldn't pin down the copy length, at least bound it.
1579     // FIXME: We should actually run this code path for append as well, but
1580     // right now it creates problems with constraints (since we can end up
1581     // trying to pass constraints from symbol to symbol).
1582     if (amountCopied.isUnknown() && !isAppending) {
1583       // Try to get a "hypothetical" string length symbol, which we can later
1584       // set as a real value if that turns out to be the case.
1585       amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1586       assert(!amountCopied.isUndef());
1587 
1588       if (Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>()) {
1589         if (lenValNL) {
1590           // amountCopied <= lenVal
1591           SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1592                                                              *amountCopiedNL,
1593                                                              *lenValNL,
1594                                                              cmpTy);
1595           state = state->assume(
1596               copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
1597           if (!state)
1598             return;
1599         }
1600 
1601         if (strLengthNL) {
1602           // amountCopied <= strlen(source)
1603           SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1604                                                            *amountCopiedNL,
1605                                                            *strLengthNL,
1606                                                            cmpTy);
1607           state = state->assume(
1608               copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
1609           if (!state)
1610             return;
1611         }
1612       }
1613     }
1614 
1615   } else {
1616     // The function isn't bounded. The amount copied should match the length
1617     // of the source buffer.
1618     amountCopied = strLength;
1619   }
1620 
1621   assert(state);
1622 
1623   // This represents the number of characters copied into the destination
1624   // buffer. (It may not actually be the strlen if the destination buffer
1625   // is not terminated.)
1626   SVal finalStrLength = UnknownVal();
1627 
1628   // If this is an appending function (strcat, strncat...) then set the
1629   // string length to strlen(src) + strlen(dst) since the buffer will
1630   // ultimately contain both.
1631   if (isAppending) {
1632     // Get the string length of the destination. If the destination is memory
1633     // that can't have a string length, we shouldn't be copying into it anyway.
1634     SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1635     if (dstStrLength.isUndef())
1636       return;
1637 
1638     Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
1639     Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
1640 
1641     // If we know both string lengths, we might know the final string length.
1642     if (srcStrLengthNL && dstStrLengthNL) {
1643       // Make sure the two lengths together don't overflow a size_t.
1644       state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1645       if (!state)
1646         return;
1647 
1648       finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1649                                                *dstStrLengthNL, sizeTy);
1650     }
1651 
1652     // If we couldn't get a single value for the final string length,
1653     // we can at least bound it by the individual lengths.
1654     if (finalStrLength.isUnknown()) {
1655       // Try to get a "hypothetical" string length symbol, which we can later
1656       // set as a real value if that turns out to be the case.
1657       finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1658       assert(!finalStrLength.isUndef());
1659 
1660       if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
1661         if (srcStrLengthNL) {
1662           // finalStrLength >= srcStrLength
1663           SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1664                                                         *finalStrLengthNL,
1665                                                         *srcStrLengthNL,
1666                                                         cmpTy);
1667           state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
1668                                 true);
1669           if (!state)
1670             return;
1671         }
1672 
1673         if (dstStrLengthNL) {
1674           // finalStrLength >= dstStrLength
1675           SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1676                                                       *finalStrLengthNL,
1677                                                       *dstStrLengthNL,
1678                                                       cmpTy);
1679           state =
1680               state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
1681           if (!state)
1682             return;
1683         }
1684       }
1685     }
1686 
1687   } else {
1688     // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1689     // the final string length will match the input string length.
1690     finalStrLength = amountCopied;
1691   }
1692 
1693   SVal Result;
1694 
1695   if (returnPtr) {
1696     // The final result of the function will either be a pointer past the last
1697     // copied element, or a pointer to the start of the destination buffer.
1698     Result = (returnEnd ? UnknownVal() : DstVal);
1699   } else {
1700     Result = finalStrLength;
1701   }
1702 
1703   assert(state);
1704 
1705   // If the destination is a MemRegion, try to check for a buffer overflow and
1706   // record the new string length.
1707   if (Optional<loc::MemRegionVal> dstRegVal =
1708       DstVal.getAs<loc::MemRegionVal>()) {
1709     QualType ptrTy = Dst->getType();
1710 
1711     // If we have an exact value on a bounded copy, use that to check for
1712     // overflows, rather than our estimate about how much is actually copied.
1713     if (boundWarning) {
1714       if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
1715         SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1716             *maxLastNL, ptrTy);
1717         state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1718             boundWarning);
1719         if (!state)
1720           return;
1721       }
1722     }
1723 
1724     // Then, if the final length is known...
1725     if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
1726       SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1727           *knownStrLength, ptrTy);
1728 
1729       // ...and we haven't checked the bound, we'll check the actual copy.
1730       if (!boundWarning) {
1731         const char * const warningMsg =
1732           "String copy function overflows destination buffer";
1733         state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1734         if (!state)
1735           return;
1736       }
1737 
1738       // If this is a stpcpy-style copy, the last element is the return value.
1739       if (returnPtr && returnEnd)
1740         Result = lastElement;
1741     }
1742 
1743     // Invalidate the destination (regular invalidation without pointer-escaping
1744     // the address of the top-level region). This must happen before we set the
1745     // C string length because invalidation will clear the length.
1746     // FIXME: Even if we can't perfectly model the copy, we should see if we
1747     // can use LazyCompoundVals to copy the source values into the destination.
1748     // This would probably remove any existing bindings past the end of the
1749     // string, but that's still an improvement over blank invalidation.
1750     state = InvalidateBuffer(C, state, Dst, *dstRegVal,
1751         /*IsSourceBuffer*/false, nullptr);
1752 
1753     // Invalidate the source (const-invalidation without const-pointer-escaping
1754     // the address of the top-level region).
1755     state = InvalidateBuffer(C, state, srcExpr, srcVal, /*IsSourceBuffer*/true,
1756         nullptr);
1757 
1758     // Set the C string length of the destination, if we know it.
1759     if (isBounded && !isAppending) {
1760       // strncpy is annoying in that it doesn't guarantee to null-terminate
1761       // the result string. If the original string didn't fit entirely inside
1762       // the bound (including the null-terminator), we don't know how long the
1763       // result is.
1764       if (amountCopied != strLength)
1765         finalStrLength = UnknownVal();
1766     }
1767     state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
1768   }
1769 
1770   assert(state);
1771 
1772   if (returnPtr) {
1773     // If this is a stpcpy-style copy, but we were unable to check for a buffer
1774     // overflow, we still need a result. Conjure a return value.
1775     if (returnEnd && Result.isUnknown()) {
1776       Result = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
1777     }
1778   }
1779   // Set the return value.
1780   state = state->BindExpr(CE, LCtx, Result);
1781   C.addTransition(state);
1782 }
1783 
1784 void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1785   if (CE->getNumArgs() < 2)
1786     return;
1787 
1788   //int strcmp(const char *s1, const char *s2);
1789   evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
1790 }
1791 
1792 void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
1793   if (CE->getNumArgs() < 3)
1794     return;
1795 
1796   //int strncmp(const char *s1, const char *s2, size_t n);
1797   evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1798 }
1799 
1800 void CStringChecker::evalStrcasecmp(CheckerContext &C,
1801     const CallExpr *CE) const {
1802   if (CE->getNumArgs() < 2)
1803     return;
1804 
1805   //int strcasecmp(const char *s1, const char *s2);
1806   evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
1807 }
1808 
1809 void CStringChecker::evalStrncasecmp(CheckerContext &C,
1810     const CallExpr *CE) const {
1811   if (CE->getNumArgs() < 3)
1812     return;
1813 
1814   //int strncasecmp(const char *s1, const char *s2, size_t n);
1815   evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1816 }
1817 
1818 void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
1819     bool isBounded, bool ignoreCase) const {
1820   CurrentFunctionDescription = "string comparison function";
1821   ProgramStateRef state = C.getState();
1822   const LocationContext *LCtx = C.getLocationContext();
1823 
1824   // Check that the first string is non-null
1825   const Expr *s1 = CE->getArg(0);
1826   SVal s1Val = state->getSVal(s1, LCtx);
1827   state = checkNonNull(C, state, s1, s1Val);
1828   if (!state)
1829     return;
1830 
1831   // Check that the second string is non-null.
1832   const Expr *s2 = CE->getArg(1);
1833   SVal s2Val = state->getSVal(s2, LCtx);
1834   state = checkNonNull(C, state, s2, s2Val);
1835   if (!state)
1836     return;
1837 
1838   // Get the string length of the first string or give up.
1839   SVal s1Length = getCStringLength(C, state, s1, s1Val);
1840   if (s1Length.isUndef())
1841     return;
1842 
1843   // Get the string length of the second string or give up.
1844   SVal s2Length = getCStringLength(C, state, s2, s2Val);
1845   if (s2Length.isUndef())
1846     return;
1847 
1848   // If we know the two buffers are the same, we know the result is 0.
1849   // First, get the two buffers' addresses. Another checker will have already
1850   // made sure they're not undefined.
1851   DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1852   DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
1853 
1854   // See if they are the same.
1855   SValBuilder &svalBuilder = C.getSValBuilder();
1856   DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1857   ProgramStateRef StSameBuf, StNotSameBuf;
1858   std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1859 
1860   // If the two arguments might be the same buffer, we know the result is 0,
1861   // and we only need to check one size.
1862   if (StSameBuf) {
1863     StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1864         svalBuilder.makeZeroVal(CE->getType()));
1865     C.addTransition(StSameBuf);
1866 
1867     // If the two arguments are GUARANTEED to be the same, we're done!
1868     if (!StNotSameBuf)
1869       return;
1870   }
1871 
1872   assert(StNotSameBuf);
1873   state = StNotSameBuf;
1874 
1875   // At this point we can go about comparing the two buffers.
1876   // For now, we only do this if they're both known string literals.
1877 
1878   // Attempt to extract string literals from both expressions.
1879   const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1880   const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1881   bool canComputeResult = false;
1882   SVal resultVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1883       C.blockCount());
1884 
1885   if (s1StrLiteral && s2StrLiteral) {
1886     StringRef s1StrRef = s1StrLiteral->getString();
1887     StringRef s2StrRef = s2StrLiteral->getString();
1888 
1889     if (isBounded) {
1890       // Get the max number of characters to compare.
1891       const Expr *lenExpr = CE->getArg(2);
1892       SVal lenVal = state->getSVal(lenExpr, LCtx);
1893 
1894       // If the length is known, we can get the right substrings.
1895       if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1896         // Create substrings of each to compare the prefix.
1897         s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1898         s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1899         canComputeResult = true;
1900       }
1901     } else {
1902       // This is a normal, unbounded strcmp.
1903       canComputeResult = true;
1904     }
1905 
1906     if (canComputeResult) {
1907       // Real strcmp stops at null characters.
1908       size_t s1Term = s1StrRef.find('\0');
1909       if (s1Term != StringRef::npos)
1910         s1StrRef = s1StrRef.substr(0, s1Term);
1911 
1912       size_t s2Term = s2StrRef.find('\0');
1913       if (s2Term != StringRef::npos)
1914         s2StrRef = s2StrRef.substr(0, s2Term);
1915 
1916       // Use StringRef's comparison methods to compute the actual result.
1917       int compareRes = ignoreCase ? s1StrRef.compare_lower(s2StrRef)
1918         : s1StrRef.compare(s2StrRef);
1919 
1920       // The strcmp function returns an integer greater than, equal to, or less
1921       // than zero, [c11, p7.24.4.2].
1922       if (compareRes == 0) {
1923         resultVal = svalBuilder.makeIntVal(compareRes, CE->getType());
1924       }
1925       else {
1926         DefinedSVal zeroVal = svalBuilder.makeIntVal(0, CE->getType());
1927         // Constrain strcmp's result range based on the result of StringRef's
1928         // comparison methods.
1929         BinaryOperatorKind op = (compareRes == 1) ? BO_GT : BO_LT;
1930         SVal compareWithZero =
1931           svalBuilder.evalBinOp(state, op, resultVal, zeroVal,
1932               svalBuilder.getConditionType());
1933         DefinedSVal compareWithZeroVal = compareWithZero.castAs<DefinedSVal>();
1934         state = state->assume(compareWithZeroVal, true);
1935       }
1936     }
1937   }
1938 
1939   state = state->BindExpr(CE, LCtx, resultVal);
1940 
1941   // Record this as a possible path.
1942   C.addTransition(state);
1943 }
1944 
1945 void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
1946   //char *strsep(char **stringp, const char *delim);
1947   if (CE->getNumArgs() < 2)
1948     return;
1949 
1950   // Sanity: does the search string parameter match the return type?
1951   const Expr *SearchStrPtr = CE->getArg(0);
1952   QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
1953   if (CharPtrTy.isNull() ||
1954       CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
1955     return;
1956 
1957   CurrentFunctionDescription = "strsep()";
1958   ProgramStateRef State = C.getState();
1959   const LocationContext *LCtx = C.getLocationContext();
1960 
1961   // Check that the search string pointer is non-null (though it may point to
1962   // a null string).
1963   SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
1964   State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
1965   if (!State)
1966     return;
1967 
1968   // Check that the delimiter string is non-null.
1969   const Expr *DelimStr = CE->getArg(1);
1970   SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
1971   State = checkNonNull(C, State, DelimStr, DelimStrVal);
1972   if (!State)
1973     return;
1974 
1975   SValBuilder &SVB = C.getSValBuilder();
1976   SVal Result;
1977   if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
1978     // Get the current value of the search string pointer, as a char*.
1979     Result = State->getSVal(*SearchStrLoc, CharPtrTy);
1980 
1981     // Invalidate the search string, representing the change of one delimiter
1982     // character to NUL.
1983     State = InvalidateBuffer(C, State, SearchStrPtr, Result,
1984         /*IsSourceBuffer*/false, nullptr);
1985 
1986     // Overwrite the search string pointer. The new value is either an address
1987     // further along in the same string, or NULL if there are no more tokens.
1988     State = State->bindLoc(*SearchStrLoc,
1989         SVB.conjureSymbolVal(getTag(),
1990           CE,
1991           LCtx,
1992           CharPtrTy,
1993           C.blockCount()),
1994         LCtx);
1995   } else {
1996     assert(SearchStrVal.isUnknown());
1997     // Conjure a symbolic value. It's the best we can do.
1998     Result = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
1999   }
2000 
2001   // Set the return value, and finish.
2002   State = State->BindExpr(CE, LCtx, Result);
2003   C.addTransition(State);
2004 }
2005 
2006 // These should probably be moved into a C++ standard library checker.
2007 void CStringChecker::evalStdCopy(CheckerContext &C, const CallExpr *CE) const {
2008   evalStdCopyCommon(C, CE);
2009 }
2010 
2011 void CStringChecker::evalStdCopyBackward(CheckerContext &C,
2012     const CallExpr *CE) const {
2013   evalStdCopyCommon(C, CE);
2014 }
2015 
2016 void CStringChecker::evalStdCopyCommon(CheckerContext &C,
2017     const CallExpr *CE) const {
2018   if (CE->getNumArgs() < 3)
2019     return;
2020 
2021   ProgramStateRef State = C.getState();
2022 
2023   const LocationContext *LCtx = C.getLocationContext();
2024 
2025   // template <class _InputIterator, class _OutputIterator>
2026   // _OutputIterator
2027   // copy(_InputIterator __first, _InputIterator __last,
2028   //        _OutputIterator __result)
2029 
2030   // Invalidate the destination buffer
2031   const Expr *Dst = CE->getArg(2);
2032   SVal DstVal = State->getSVal(Dst, LCtx);
2033   State = InvalidateBuffer(C, State, Dst, DstVal, /*IsSource=*/false,
2034       /*Size=*/nullptr);
2035 
2036   SValBuilder &SVB = C.getSValBuilder();
2037 
2038   SVal ResultVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
2039   State = State->BindExpr(CE, LCtx, ResultVal);
2040 
2041   C.addTransition(State);
2042 }
2043 
2044 void CStringChecker::evalMemset(CheckerContext &C, const CallExpr *CE) const {
2045   if (CE->getNumArgs() != 3)
2046     return;
2047 
2048   CurrentFunctionDescription = "memory set function";
2049 
2050   const Expr *Mem = CE->getArg(0);
2051   const Expr *Size = CE->getArg(2);
2052   ProgramStateRef State = C.getState();
2053 
2054   // See if the size argument is zero.
2055   const LocationContext *LCtx = C.getLocationContext();
2056   SVal SizeVal = State->getSVal(Size, LCtx);
2057   QualType SizeTy = Size->getType();
2058 
2059   ProgramStateRef StateZeroSize, StateNonZeroSize;
2060   std::tie(StateZeroSize, StateNonZeroSize) =
2061     assumeZero(C, State, SizeVal, SizeTy);
2062 
2063   // Get the value of the memory area.
2064   SVal MemVal = State->getSVal(Mem, LCtx);
2065 
2066   // If the size is zero, there won't be any actual memory access, so
2067   // just bind the return value to the Mem buffer and return.
2068   if (StateZeroSize && !StateNonZeroSize) {
2069     StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, MemVal);
2070     C.addTransition(StateZeroSize);
2071     return;
2072   }
2073 
2074   // Ensure the memory area is not null.
2075   // If it is NULL there will be a NULL pointer dereference.
2076   State = checkNonNull(C, StateNonZeroSize, Mem, MemVal);
2077   if (!State)
2078     return;
2079 
2080   State = CheckBufferAccess(C, State, Size, Mem);
2081   if (!State)
2082     return;
2083   State = InvalidateBuffer(C, State, Mem, C.getSVal(Mem),
2084       /*IsSourceBuffer*/false, Size);
2085   if (!State)
2086     return;
2087 
2088   State = State->BindExpr(CE, LCtx, MemVal);
2089   C.addTransition(State);
2090 }
2091 
2092 static bool isCPPStdLibraryFunction(const FunctionDecl *FD, StringRef Name) {
2093   IdentifierInfo *II = FD->getIdentifier();
2094   if (!II)
2095     return false;
2096 
2097   if (!AnalysisDeclContext::isInStdNamespace(FD))
2098     return false;
2099 
2100   if (II->getName().equals(Name))
2101     return true;
2102 
2103   return false;
2104 }
2105 //===----------------------------------------------------------------------===//
2106 // The driver method, and other Checker callbacks.
2107 //===----------------------------------------------------------------------===//
2108 
2109 bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
2110   const FunctionDecl *FDecl = C.getCalleeDecl(CE);
2111 
2112   if (!FDecl)
2113     return false;
2114 
2115   // FIXME: Poorly-factored string switches are slow.
2116   FnCheck evalFunction = nullptr;
2117   if (C.isCLibraryFunction(FDecl, "memcpy"))
2118     evalFunction =  &CStringChecker::evalMemcpy;
2119   else if (C.isCLibraryFunction(FDecl, "mempcpy"))
2120     evalFunction =  &CStringChecker::evalMempcpy;
2121   else if (C.isCLibraryFunction(FDecl, "memcmp"))
2122     evalFunction =  &CStringChecker::evalMemcmp;
2123   else if (C.isCLibraryFunction(FDecl, "memmove"))
2124     evalFunction =  &CStringChecker::evalMemmove;
2125   else if (C.isCLibraryFunction(FDecl, "memset"))
2126     evalFunction =  &CStringChecker::evalMemset;
2127   else if (C.isCLibraryFunction(FDecl, "strcpy"))
2128     evalFunction =  &CStringChecker::evalStrcpy;
2129   else if (C.isCLibraryFunction(FDecl, "strncpy"))
2130     evalFunction =  &CStringChecker::evalStrncpy;
2131   else if (C.isCLibraryFunction(FDecl, "stpcpy"))
2132     evalFunction =  &CStringChecker::evalStpcpy;
2133   else if (C.isCLibraryFunction(FDecl, "strlcpy"))
2134     evalFunction =  &CStringChecker::evalStrlcpy;
2135   else if (C.isCLibraryFunction(FDecl, "strcat"))
2136     evalFunction =  &CStringChecker::evalStrcat;
2137   else if (C.isCLibraryFunction(FDecl, "strncat"))
2138     evalFunction =  &CStringChecker::evalStrncat;
2139   else if (C.isCLibraryFunction(FDecl, "strlcat"))
2140     evalFunction =  &CStringChecker::evalStrlcat;
2141   else if (C.isCLibraryFunction(FDecl, "strlen"))
2142     evalFunction =  &CStringChecker::evalstrLength;
2143   else if (C.isCLibraryFunction(FDecl, "strnlen"))
2144     evalFunction =  &CStringChecker::evalstrnLength;
2145   else if (C.isCLibraryFunction(FDecl, "strcmp"))
2146     evalFunction =  &CStringChecker::evalStrcmp;
2147   else if (C.isCLibraryFunction(FDecl, "strncmp"))
2148     evalFunction =  &CStringChecker::evalStrncmp;
2149   else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
2150     evalFunction =  &CStringChecker::evalStrcasecmp;
2151   else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
2152     evalFunction =  &CStringChecker::evalStrncasecmp;
2153   else if (C.isCLibraryFunction(FDecl, "strsep"))
2154     evalFunction =  &CStringChecker::evalStrsep;
2155   else if (C.isCLibraryFunction(FDecl, "bcopy"))
2156     evalFunction =  &CStringChecker::evalBcopy;
2157   else if (C.isCLibraryFunction(FDecl, "bcmp"))
2158     evalFunction =  &CStringChecker::evalMemcmp;
2159   else if (isCPPStdLibraryFunction(FDecl, "copy"))
2160     evalFunction =  &CStringChecker::evalStdCopy;
2161   else if (isCPPStdLibraryFunction(FDecl, "copy_backward"))
2162     evalFunction =  &CStringChecker::evalStdCopyBackward;
2163 
2164   // If the callee isn't a string function, let another checker handle it.
2165   if (!evalFunction)
2166     return false;
2167 
2168   // Check and evaluate the call.
2169   (this->*evalFunction)(C, CE);
2170 
2171   // If the evaluate call resulted in no change, chain to the next eval call
2172   // handler.
2173   // Note, the custom CString evaluation calls assume that basic safety
2174   // properties are held. However, if the user chooses to turn off some of these
2175   // checks, we ignore the issues and leave the call evaluation to a generic
2176   // handler.
2177   return C.isDifferent();
2178 }
2179 
2180 void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
2181   // Record string length for char a[] = "abc";
2182   ProgramStateRef state = C.getState();
2183 
2184   for (const auto *I : DS->decls()) {
2185     const VarDecl *D = dyn_cast<VarDecl>(I);
2186     if (!D)
2187       continue;
2188 
2189     // FIXME: Handle array fields of structs.
2190     if (!D->getType()->isArrayType())
2191       continue;
2192 
2193     const Expr *Init = D->getInit();
2194     if (!Init)
2195       continue;
2196     if (!isa<StringLiteral>(Init))
2197       continue;
2198 
2199     Loc VarLoc = state->getLValue(D, C.getLocationContext());
2200     const MemRegion *MR = VarLoc.getAsRegion();
2201     if (!MR)
2202       continue;
2203 
2204     SVal StrVal = C.getSVal(Init);
2205     assert(StrVal.isValid() && "Initializer string is unknown or undefined");
2206     DefinedOrUnknownSVal strLength =
2207       getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
2208 
2209     state = state->set<CStringLength>(MR, strLength);
2210   }
2211 
2212   C.addTransition(state);
2213 }
2214 
2215 ProgramStateRef
2216 CStringChecker::checkRegionChanges(ProgramStateRef state,
2217     const InvalidatedSymbols *,
2218     ArrayRef<const MemRegion *> ExplicitRegions,
2219     ArrayRef<const MemRegion *> Regions,
2220     const LocationContext *LCtx,
2221     const CallEvent *Call) const {
2222   CStringLengthTy Entries = state->get<CStringLength>();
2223   if (Entries.isEmpty())
2224     return state;
2225 
2226   llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
2227   llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
2228 
2229   // First build sets for the changed regions and their super-regions.
2230   for (ArrayRef<const MemRegion *>::iterator
2231       I = Regions.begin(), E = Regions.end(); I != E; ++I) {
2232     const MemRegion *MR = *I;
2233     Invalidated.insert(MR);
2234 
2235     SuperRegions.insert(MR);
2236     while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
2237       MR = SR->getSuperRegion();
2238       SuperRegions.insert(MR);
2239     }
2240   }
2241 
2242   CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2243 
2244   // Then loop over the entries in the current state.
2245   for (CStringLengthTy::iterator I = Entries.begin(),
2246       E = Entries.end(); I != E; ++I) {
2247     const MemRegion *MR = I.getKey();
2248 
2249     // Is this entry for a super-region of a changed region?
2250     if (SuperRegions.count(MR)) {
2251       Entries = F.remove(Entries, MR);
2252       continue;
2253     }
2254 
2255     // Is this entry for a sub-region of a changed region?
2256     const MemRegion *Super = MR;
2257     while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2258       Super = SR->getSuperRegion();
2259       if (Invalidated.count(Super)) {
2260         Entries = F.remove(Entries, MR);
2261         break;
2262       }
2263     }
2264   }
2265 
2266   return state->set<CStringLength>(Entries);
2267 }
2268 
2269 void CStringChecker::checkLiveSymbols(ProgramStateRef state,
2270     SymbolReaper &SR) const {
2271   // Mark all symbols in our string length map as valid.
2272   CStringLengthTy Entries = state->get<CStringLength>();
2273 
2274   for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2275       I != E; ++I) {
2276     SVal Len = I.getData();
2277 
2278     for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2279         se = Len.symbol_end(); si != se; ++si)
2280       SR.markInUse(*si);
2281   }
2282 }
2283 
2284 void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2285     CheckerContext &C) const {
2286   if (!SR.hasDeadSymbols())
2287     return;
2288 
2289   ProgramStateRef state = C.getState();
2290   CStringLengthTy Entries = state->get<CStringLength>();
2291   if (Entries.isEmpty())
2292     return;
2293 
2294   CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2295   for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2296       I != E; ++I) {
2297     SVal Len = I.getData();
2298     if (SymbolRef Sym = Len.getAsSymbol()) {
2299       if (SR.isDead(Sym))
2300         Entries = F.remove(Entries, I.getKey());
2301     }
2302   }
2303 
2304   state = state->set<CStringLength>(Entries);
2305   C.addTransition(state);
2306 }
2307 
2308 #define REGISTER_CHECKER(name)                                                 \
2309   void ento::register##name(CheckerManager &mgr) {                             \
2310     CStringChecker *checker = mgr.registerChecker<CStringChecker>();           \
2311     checker->Filter.Check##name = true;                                        \
2312     checker->Filter.CheckName##name = mgr.getCurrentCheckName();               \
2313   }
2314 
2315   REGISTER_CHECKER(CStringNullArg)
2316   REGISTER_CHECKER(CStringOutOfBounds)
2317   REGISTER_CHECKER(CStringBufferOverlap)
2318 REGISTER_CHECKER(CStringNotNullTerm)
2319 
2320   void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
2321     registerCStringNullArg(Mgr);
2322   }
2323