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