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