xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This defines CStringChecker, which is an assortment of checks on calls
107330f729Sjoerg // to functions in <string.h>.
117330f729Sjoerg //
127330f729Sjoerg //===----------------------------------------------------------------------===//
137330f729Sjoerg 
147330f729Sjoerg #include "InterCheckerAPI.h"
157330f729Sjoerg #include "clang/Basic/CharInfo.h"
16*e038c9c4Sjoerg #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
177330f729Sjoerg #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
187330f729Sjoerg #include "clang/StaticAnalyzer/Core/Checker.h"
197330f729Sjoerg #include "clang/StaticAnalyzer/Core/CheckerManager.h"
207330f729Sjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
217330f729Sjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22*e038c9c4Sjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
237330f729Sjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
247330f729Sjoerg #include "llvm/ADT/STLExtras.h"
257330f729Sjoerg #include "llvm/ADT/SmallString.h"
26*e038c9c4Sjoerg #include "llvm/ADT/StringExtras.h"
277330f729Sjoerg #include "llvm/Support/raw_ostream.h"
287330f729Sjoerg 
297330f729Sjoerg using namespace clang;
307330f729Sjoerg using namespace ento;
317330f729Sjoerg 
327330f729Sjoerg namespace {
33*e038c9c4Sjoerg struct AnyArgExpr {
34*e038c9c4Sjoerg   // FIXME: Remove constructor in C++17 to turn it into an aggregate.
AnyArgExpr__anonf9b4f3e80111::AnyArgExpr35*e038c9c4Sjoerg   AnyArgExpr(const Expr *Expression, unsigned ArgumentIndex)
36*e038c9c4Sjoerg       : Expression{Expression}, ArgumentIndex{ArgumentIndex} {}
37*e038c9c4Sjoerg   const Expr *Expression;
38*e038c9c4Sjoerg   unsigned ArgumentIndex;
39*e038c9c4Sjoerg };
40*e038c9c4Sjoerg 
41*e038c9c4Sjoerg struct SourceArgExpr : AnyArgExpr {
42*e038c9c4Sjoerg   using AnyArgExpr::AnyArgExpr; // FIXME: Remove using in C++17.
43*e038c9c4Sjoerg };
44*e038c9c4Sjoerg 
45*e038c9c4Sjoerg struct DestinationArgExpr : AnyArgExpr {
46*e038c9c4Sjoerg   using AnyArgExpr::AnyArgExpr; // FIXME: Same.
47*e038c9c4Sjoerg };
48*e038c9c4Sjoerg 
49*e038c9c4Sjoerg struct SizeArgExpr : AnyArgExpr {
50*e038c9c4Sjoerg   using AnyArgExpr::AnyArgExpr; // FIXME: Same.
51*e038c9c4Sjoerg };
52*e038c9c4Sjoerg 
53*e038c9c4Sjoerg using ErrorMessage = SmallString<128>;
54*e038c9c4Sjoerg enum class AccessKind { write, read };
55*e038c9c4Sjoerg 
createOutOfBoundErrorMsg(StringRef FunctionDescription,AccessKind Access)56*e038c9c4Sjoerg static ErrorMessage createOutOfBoundErrorMsg(StringRef FunctionDescription,
57*e038c9c4Sjoerg                                              AccessKind Access) {
58*e038c9c4Sjoerg   ErrorMessage Message;
59*e038c9c4Sjoerg   llvm::raw_svector_ostream Os(Message);
60*e038c9c4Sjoerg 
61*e038c9c4Sjoerg   // Function classification like: Memory copy function
62*e038c9c4Sjoerg   Os << toUppercase(FunctionDescription.front())
63*e038c9c4Sjoerg      << &FunctionDescription.data()[1];
64*e038c9c4Sjoerg 
65*e038c9c4Sjoerg   if (Access == AccessKind::write) {
66*e038c9c4Sjoerg     Os << " overflows the destination buffer";
67*e038c9c4Sjoerg   } else { // read access
68*e038c9c4Sjoerg     Os << " accesses out-of-bound array element";
69*e038c9c4Sjoerg   }
70*e038c9c4Sjoerg 
71*e038c9c4Sjoerg   return Message;
72*e038c9c4Sjoerg }
73*e038c9c4Sjoerg 
74*e038c9c4Sjoerg enum class ConcatFnKind { none = 0, strcat = 1, strlcat = 2 };
757330f729Sjoerg class CStringChecker : public Checker< eval::Call,
767330f729Sjoerg                                          check::PreStmt<DeclStmt>,
777330f729Sjoerg                                          check::LiveSymbols,
787330f729Sjoerg                                          check::DeadSymbols,
797330f729Sjoerg                                          check::RegionChanges
807330f729Sjoerg                                          > {
817330f729Sjoerg   mutable std::unique_ptr<BugType> BT_Null, BT_Bounds, BT_Overlap,
827330f729Sjoerg       BT_NotCString, BT_AdditionOverflow;
837330f729Sjoerg 
847330f729Sjoerg   mutable const char *CurrentFunctionDescription;
857330f729Sjoerg 
867330f729Sjoerg public:
877330f729Sjoerg   /// The filter is used to filter out the diagnostics which are not enabled by
887330f729Sjoerg   /// the user.
897330f729Sjoerg   struct CStringChecksFilter {
907330f729Sjoerg     DefaultBool CheckCStringNullArg;
917330f729Sjoerg     DefaultBool CheckCStringOutOfBounds;
927330f729Sjoerg     DefaultBool CheckCStringBufferOverlap;
937330f729Sjoerg     DefaultBool CheckCStringNotNullTerm;
947330f729Sjoerg 
957330f729Sjoerg     CheckerNameRef CheckNameCStringNullArg;
967330f729Sjoerg     CheckerNameRef CheckNameCStringOutOfBounds;
977330f729Sjoerg     CheckerNameRef CheckNameCStringBufferOverlap;
987330f729Sjoerg     CheckerNameRef CheckNameCStringNotNullTerm;
997330f729Sjoerg   };
1007330f729Sjoerg 
1017330f729Sjoerg   CStringChecksFilter Filter;
1027330f729Sjoerg 
getTag()1037330f729Sjoerg   static void *getTag() { static int tag; return &tag; }
1047330f729Sjoerg 
1057330f729Sjoerg   bool evalCall(const CallEvent &Call, CheckerContext &C) const;
1067330f729Sjoerg   void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
1077330f729Sjoerg   void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
1087330f729Sjoerg   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
1097330f729Sjoerg 
1107330f729Sjoerg   ProgramStateRef
1117330f729Sjoerg     checkRegionChanges(ProgramStateRef state,
1127330f729Sjoerg                        const InvalidatedSymbols *,
1137330f729Sjoerg                        ArrayRef<const MemRegion *> ExplicitRegions,
1147330f729Sjoerg                        ArrayRef<const MemRegion *> Regions,
1157330f729Sjoerg                        const LocationContext *LCtx,
1167330f729Sjoerg                        const CallEvent *Call) const;
1177330f729Sjoerg 
1187330f729Sjoerg   typedef void (CStringChecker::*FnCheck)(CheckerContext &,
1197330f729Sjoerg                                           const CallExpr *) const;
1207330f729Sjoerg   CallDescriptionMap<FnCheck> Callbacks = {
1217330f729Sjoerg       {{CDF_MaybeBuiltin, "memcpy", 3}, &CStringChecker::evalMemcpy},
1227330f729Sjoerg       {{CDF_MaybeBuiltin, "mempcpy", 3}, &CStringChecker::evalMempcpy},
1237330f729Sjoerg       {{CDF_MaybeBuiltin, "memcmp", 3}, &CStringChecker::evalMemcmp},
1247330f729Sjoerg       {{CDF_MaybeBuiltin, "memmove", 3}, &CStringChecker::evalMemmove},
1257330f729Sjoerg       {{CDF_MaybeBuiltin, "memset", 3}, &CStringChecker::evalMemset},
1267330f729Sjoerg       {{CDF_MaybeBuiltin, "explicit_memset", 3}, &CStringChecker::evalMemset},
1277330f729Sjoerg       {{CDF_MaybeBuiltin, "strcpy", 2}, &CStringChecker::evalStrcpy},
1287330f729Sjoerg       {{CDF_MaybeBuiltin, "strncpy", 3}, &CStringChecker::evalStrncpy},
1297330f729Sjoerg       {{CDF_MaybeBuiltin, "stpcpy", 2}, &CStringChecker::evalStpcpy},
1307330f729Sjoerg       {{CDF_MaybeBuiltin, "strlcpy", 3}, &CStringChecker::evalStrlcpy},
1317330f729Sjoerg       {{CDF_MaybeBuiltin, "strcat", 2}, &CStringChecker::evalStrcat},
1327330f729Sjoerg       {{CDF_MaybeBuiltin, "strncat", 3}, &CStringChecker::evalStrncat},
1337330f729Sjoerg       {{CDF_MaybeBuiltin, "strlcat", 3}, &CStringChecker::evalStrlcat},
1347330f729Sjoerg       {{CDF_MaybeBuiltin, "strlen", 1}, &CStringChecker::evalstrLength},
1357330f729Sjoerg       {{CDF_MaybeBuiltin, "strnlen", 2}, &CStringChecker::evalstrnLength},
1367330f729Sjoerg       {{CDF_MaybeBuiltin, "strcmp", 2}, &CStringChecker::evalStrcmp},
1377330f729Sjoerg       {{CDF_MaybeBuiltin, "strncmp", 3}, &CStringChecker::evalStrncmp},
1387330f729Sjoerg       {{CDF_MaybeBuiltin, "strcasecmp", 2}, &CStringChecker::evalStrcasecmp},
1397330f729Sjoerg       {{CDF_MaybeBuiltin, "strncasecmp", 3}, &CStringChecker::evalStrncasecmp},
1407330f729Sjoerg       {{CDF_MaybeBuiltin, "strsep", 2}, &CStringChecker::evalStrsep},
1417330f729Sjoerg       {{CDF_MaybeBuiltin, "bcopy", 3}, &CStringChecker::evalBcopy},
1427330f729Sjoerg       {{CDF_MaybeBuiltin, "bcmp", 3}, &CStringChecker::evalMemcmp},
1437330f729Sjoerg       {{CDF_MaybeBuiltin, "bzero", 2}, &CStringChecker::evalBzero},
1447330f729Sjoerg       {{CDF_MaybeBuiltin, "explicit_bzero", 2}, &CStringChecker::evalBzero},
1457330f729Sjoerg   };
1467330f729Sjoerg 
1477330f729Sjoerg   // These require a bit of special handling.
1487330f729Sjoerg   CallDescription StdCopy{{"std", "copy"}, 3},
1497330f729Sjoerg       StdCopyBackward{{"std", "copy_backward"}, 3};
1507330f729Sjoerg 
1517330f729Sjoerg   FnCheck identifyCall(const CallEvent &Call, CheckerContext &C) const;
1527330f729Sjoerg   void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
1537330f729Sjoerg   void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
1547330f729Sjoerg   void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
1557330f729Sjoerg   void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
1567330f729Sjoerg   void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
157*e038c9c4Sjoerg                       ProgramStateRef state, SizeArgExpr Size,
158*e038c9c4Sjoerg                       DestinationArgExpr Dest, SourceArgExpr Source,
159*e038c9c4Sjoerg                       bool Restricted, bool IsMempcpy) const;
1607330f729Sjoerg 
1617330f729Sjoerg   void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
1627330f729Sjoerg 
1637330f729Sjoerg   void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
1647330f729Sjoerg   void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
1657330f729Sjoerg   void evalstrLengthCommon(CheckerContext &C,
1667330f729Sjoerg                            const CallExpr *CE,
1677330f729Sjoerg                            bool IsStrnlen = false) const;
1687330f729Sjoerg 
1697330f729Sjoerg   void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
1707330f729Sjoerg   void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
1717330f729Sjoerg   void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
1727330f729Sjoerg   void evalStrlcpy(CheckerContext &C, const CallExpr *CE) const;
173*e038c9c4Sjoerg   void evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, bool ReturnEnd,
174*e038c9c4Sjoerg                         bool IsBounded, ConcatFnKind appendK,
1757330f729Sjoerg                         bool returnPtr = true) const;
1767330f729Sjoerg 
1777330f729Sjoerg   void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
1787330f729Sjoerg   void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
1797330f729Sjoerg   void evalStrlcat(CheckerContext &C, const CallExpr *CE) const;
1807330f729Sjoerg 
1817330f729Sjoerg   void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
1827330f729Sjoerg   void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
1837330f729Sjoerg   void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
1847330f729Sjoerg   void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
1857330f729Sjoerg   void evalStrcmpCommon(CheckerContext &C,
1867330f729Sjoerg                         const CallExpr *CE,
187*e038c9c4Sjoerg                         bool IsBounded = false,
188*e038c9c4Sjoerg                         bool IgnoreCase = false) const;
1897330f729Sjoerg 
1907330f729Sjoerg   void evalStrsep(CheckerContext &C, const CallExpr *CE) const;
1917330f729Sjoerg 
1927330f729Sjoerg   void evalStdCopy(CheckerContext &C, const CallExpr *CE) const;
1937330f729Sjoerg   void evalStdCopyBackward(CheckerContext &C, const CallExpr *CE) const;
1947330f729Sjoerg   void evalStdCopyCommon(CheckerContext &C, const CallExpr *CE) const;
1957330f729Sjoerg   void evalMemset(CheckerContext &C, const CallExpr *CE) const;
1967330f729Sjoerg   void evalBzero(CheckerContext &C, const CallExpr *CE) const;
1977330f729Sjoerg 
1987330f729Sjoerg   // Utility methods
1997330f729Sjoerg   std::pair<ProgramStateRef , ProgramStateRef >
2007330f729Sjoerg   static assumeZero(CheckerContext &C,
2017330f729Sjoerg                     ProgramStateRef state, SVal V, QualType Ty);
2027330f729Sjoerg 
2037330f729Sjoerg   static ProgramStateRef setCStringLength(ProgramStateRef state,
2047330f729Sjoerg                                               const MemRegion *MR,
2057330f729Sjoerg                                               SVal strLength);
2067330f729Sjoerg   static SVal getCStringLengthForRegion(CheckerContext &C,
2077330f729Sjoerg                                         ProgramStateRef &state,
2087330f729Sjoerg                                         const Expr *Ex,
2097330f729Sjoerg                                         const MemRegion *MR,
2107330f729Sjoerg                                         bool hypothetical);
2117330f729Sjoerg   SVal getCStringLength(CheckerContext &C,
2127330f729Sjoerg                         ProgramStateRef &state,
2137330f729Sjoerg                         const Expr *Ex,
2147330f729Sjoerg                         SVal Buf,
2157330f729Sjoerg                         bool hypothetical = false) const;
2167330f729Sjoerg 
2177330f729Sjoerg   const StringLiteral *getCStringLiteral(CheckerContext &C,
2187330f729Sjoerg                                          ProgramStateRef &state,
2197330f729Sjoerg                                          const Expr *expr,
2207330f729Sjoerg                                          SVal val) const;
2217330f729Sjoerg 
2227330f729Sjoerg   static ProgramStateRef InvalidateBuffer(CheckerContext &C,
2237330f729Sjoerg                                           ProgramStateRef state,
2247330f729Sjoerg                                           const Expr *Ex, SVal V,
2257330f729Sjoerg                                           bool IsSourceBuffer,
2267330f729Sjoerg                                           const Expr *Size);
2277330f729Sjoerg 
2287330f729Sjoerg   static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
2297330f729Sjoerg                               const MemRegion *MR);
2307330f729Sjoerg 
2317330f729Sjoerg   static bool memsetAux(const Expr *DstBuffer, SVal CharE,
2327330f729Sjoerg                         const Expr *Size, CheckerContext &C,
2337330f729Sjoerg                         ProgramStateRef &State);
2347330f729Sjoerg 
2357330f729Sjoerg   // Re-usable checks
236*e038c9c4Sjoerg   ProgramStateRef checkNonNull(CheckerContext &C, ProgramStateRef State,
237*e038c9c4Sjoerg                                AnyArgExpr Arg, SVal l) const;
238*e038c9c4Sjoerg   ProgramStateRef CheckLocation(CheckerContext &C, ProgramStateRef state,
239*e038c9c4Sjoerg                                 AnyArgExpr Buffer, SVal Element,
240*e038c9c4Sjoerg                                 AccessKind Access) const;
241*e038c9c4Sjoerg   ProgramStateRef CheckBufferAccess(CheckerContext &C, ProgramStateRef State,
242*e038c9c4Sjoerg                                     AnyArgExpr Buffer, SizeArgExpr Size,
243*e038c9c4Sjoerg                                     AccessKind Access) const;
244*e038c9c4Sjoerg   ProgramStateRef CheckOverlap(CheckerContext &C, ProgramStateRef state,
245*e038c9c4Sjoerg                                SizeArgExpr Size, AnyArgExpr First,
246*e038c9c4Sjoerg                                AnyArgExpr Second) const;
2477330f729Sjoerg   void emitOverlapBug(CheckerContext &C,
2487330f729Sjoerg                       ProgramStateRef state,
2497330f729Sjoerg                       const Stmt *First,
2507330f729Sjoerg                       const Stmt *Second) const;
2517330f729Sjoerg 
2527330f729Sjoerg   void emitNullArgBug(CheckerContext &C, ProgramStateRef State, const Stmt *S,
2537330f729Sjoerg                       StringRef WarningMsg) const;
2547330f729Sjoerg   void emitOutOfBoundsBug(CheckerContext &C, ProgramStateRef State,
2557330f729Sjoerg                           const Stmt *S, StringRef WarningMsg) const;
2567330f729Sjoerg   void emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
2577330f729Sjoerg                          const Stmt *S, StringRef WarningMsg) const;
2587330f729Sjoerg   void emitAdditionOverflowBug(CheckerContext &C, ProgramStateRef State) const;
2597330f729Sjoerg 
2607330f729Sjoerg   ProgramStateRef checkAdditionOverflow(CheckerContext &C,
2617330f729Sjoerg                                             ProgramStateRef state,
2627330f729Sjoerg                                             NonLoc left,
2637330f729Sjoerg                                             NonLoc right) const;
2647330f729Sjoerg 
2657330f729Sjoerg   // Return true if the destination buffer of the copy function may be in bound.
2667330f729Sjoerg   // Expects SVal of Size to be positive and unsigned.
2677330f729Sjoerg   // Expects SVal of FirstBuf to be a FieldRegion.
2687330f729Sjoerg   static bool IsFirstBufInBound(CheckerContext &C,
2697330f729Sjoerg                                 ProgramStateRef state,
2707330f729Sjoerg                                 const Expr *FirstBuf,
2717330f729Sjoerg                                 const Expr *Size);
2727330f729Sjoerg };
2737330f729Sjoerg 
2747330f729Sjoerg } //end anonymous namespace
2757330f729Sjoerg 
REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength,const MemRegion *,SVal)2767330f729Sjoerg REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
2777330f729Sjoerg 
2787330f729Sjoerg //===----------------------------------------------------------------------===//
2797330f729Sjoerg // Individual checks and utility methods.
2807330f729Sjoerg //===----------------------------------------------------------------------===//
2817330f729Sjoerg 
2827330f729Sjoerg std::pair<ProgramStateRef , ProgramStateRef >
2837330f729Sjoerg CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
2847330f729Sjoerg                            QualType Ty) {
2857330f729Sjoerg   Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
2867330f729Sjoerg   if (!val)
2877330f729Sjoerg     return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
2887330f729Sjoerg 
2897330f729Sjoerg   SValBuilder &svalBuilder = C.getSValBuilder();
2907330f729Sjoerg   DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
2917330f729Sjoerg   return state->assume(svalBuilder.evalEQ(state, *val, zero));
2927330f729Sjoerg }
2937330f729Sjoerg 
checkNonNull(CheckerContext & C,ProgramStateRef State,AnyArgExpr Arg,SVal l) const2947330f729Sjoerg ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
295*e038c9c4Sjoerg                                              ProgramStateRef State,
296*e038c9c4Sjoerg                                              AnyArgExpr Arg, SVal l) const {
2977330f729Sjoerg   // If a previous check has failed, propagate the failure.
298*e038c9c4Sjoerg   if (!State)
2997330f729Sjoerg     return nullptr;
3007330f729Sjoerg 
3017330f729Sjoerg   ProgramStateRef stateNull, stateNonNull;
302*e038c9c4Sjoerg   std::tie(stateNull, stateNonNull) =
303*e038c9c4Sjoerg       assumeZero(C, State, l, Arg.Expression->getType());
3047330f729Sjoerg 
3057330f729Sjoerg   if (stateNull && !stateNonNull) {
3067330f729Sjoerg     if (Filter.CheckCStringNullArg) {
3077330f729Sjoerg       SmallString<80> buf;
3087330f729Sjoerg       llvm::raw_svector_ostream OS(buf);
3097330f729Sjoerg       assert(CurrentFunctionDescription);
310*e038c9c4Sjoerg       OS << "Null pointer passed as " << (Arg.ArgumentIndex + 1)
311*e038c9c4Sjoerg          << llvm::getOrdinalSuffix(Arg.ArgumentIndex + 1) << " argument to "
312*e038c9c4Sjoerg          << CurrentFunctionDescription;
3137330f729Sjoerg 
314*e038c9c4Sjoerg       emitNullArgBug(C, stateNull, Arg.Expression, OS.str());
3157330f729Sjoerg     }
3167330f729Sjoerg     return nullptr;
3177330f729Sjoerg   }
3187330f729Sjoerg 
3197330f729Sjoerg   // From here on, assume that the value is non-null.
3207330f729Sjoerg   assert(stateNonNull);
3217330f729Sjoerg   return stateNonNull;
3227330f729Sjoerg }
3237330f729Sjoerg 
3247330f729Sjoerg // FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
CheckLocation(CheckerContext & C,ProgramStateRef state,AnyArgExpr Buffer,SVal Element,AccessKind Access) const3257330f729Sjoerg ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
3267330f729Sjoerg                                               ProgramStateRef state,
327*e038c9c4Sjoerg                                               AnyArgExpr Buffer, SVal Element,
328*e038c9c4Sjoerg                                               AccessKind Access) const {
329*e038c9c4Sjoerg 
3307330f729Sjoerg   // If a previous check has failed, propagate the failure.
3317330f729Sjoerg   if (!state)
3327330f729Sjoerg     return nullptr;
3337330f729Sjoerg 
3347330f729Sjoerg   // Check for out of bound array element access.
335*e038c9c4Sjoerg   const MemRegion *R = Element.getAsRegion();
3367330f729Sjoerg   if (!R)
3377330f729Sjoerg     return state;
3387330f729Sjoerg 
339*e038c9c4Sjoerg   const auto *ER = dyn_cast<ElementRegion>(R);
3407330f729Sjoerg   if (!ER)
3417330f729Sjoerg     return state;
3427330f729Sjoerg 
3437330f729Sjoerg   if (ER->getValueType() != C.getASTContext().CharTy)
3447330f729Sjoerg     return state;
3457330f729Sjoerg 
3467330f729Sjoerg   // Get the size of the array.
347*e038c9c4Sjoerg   const auto *superReg = cast<SubRegion>(ER->getSuperRegion());
348*e038c9c4Sjoerg   DefinedOrUnknownSVal Size =
349*e038c9c4Sjoerg       getDynamicExtent(state, superReg, C.getSValBuilder());
3507330f729Sjoerg 
3517330f729Sjoerg   // Get the index of the accessed element.
3527330f729Sjoerg   DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
3537330f729Sjoerg 
3547330f729Sjoerg   ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
3557330f729Sjoerg   ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
3567330f729Sjoerg   if (StOutBound && !StInBound) {
3577330f729Sjoerg     // These checks are either enabled by the CString out-of-bounds checker
3587330f729Sjoerg     // explicitly or implicitly by the Malloc checker.
3597330f729Sjoerg     // In the latter case we only do modeling but do not emit warning.
3607330f729Sjoerg     if (!Filter.CheckCStringOutOfBounds)
3617330f729Sjoerg       return nullptr;
3627330f729Sjoerg 
363*e038c9c4Sjoerg     // Emit a bug report.
364*e038c9c4Sjoerg     ErrorMessage Message =
365*e038c9c4Sjoerg         createOutOfBoundErrorMsg(CurrentFunctionDescription, Access);
366*e038c9c4Sjoerg     emitOutOfBoundsBug(C, StOutBound, Buffer.Expression, Message);
3677330f729Sjoerg     return nullptr;
3687330f729Sjoerg   }
3697330f729Sjoerg 
3707330f729Sjoerg   // Array bound check succeeded.  From this point forward the array bound
3717330f729Sjoerg   // should always succeed.
3727330f729Sjoerg   return StInBound;
3737330f729Sjoerg }
3747330f729Sjoerg 
CheckBufferAccess(CheckerContext & C,ProgramStateRef State,AnyArgExpr Buffer,SizeArgExpr Size,AccessKind Access) const3757330f729Sjoerg ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
376*e038c9c4Sjoerg                                                   ProgramStateRef State,
377*e038c9c4Sjoerg                                                   AnyArgExpr Buffer,
378*e038c9c4Sjoerg                                                   SizeArgExpr Size,
379*e038c9c4Sjoerg                                                   AccessKind Access) const {
3807330f729Sjoerg   // If a previous check has failed, propagate the failure.
381*e038c9c4Sjoerg   if (!State)
3827330f729Sjoerg     return nullptr;
3837330f729Sjoerg 
3847330f729Sjoerg   SValBuilder &svalBuilder = C.getSValBuilder();
3857330f729Sjoerg   ASTContext &Ctx = svalBuilder.getContext();
3867330f729Sjoerg 
387*e038c9c4Sjoerg   QualType SizeTy = Size.Expression->getType();
3887330f729Sjoerg   QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
3897330f729Sjoerg 
3907330f729Sjoerg   // Check that the first buffer is non-null.
391*e038c9c4Sjoerg   SVal BufVal = C.getSVal(Buffer.Expression);
392*e038c9c4Sjoerg   State = checkNonNull(C, State, Buffer, BufVal);
393*e038c9c4Sjoerg   if (!State)
3947330f729Sjoerg     return nullptr;
3957330f729Sjoerg 
3967330f729Sjoerg   // If out-of-bounds checking is turned off, skip the rest.
3977330f729Sjoerg   if (!Filter.CheckCStringOutOfBounds)
398*e038c9c4Sjoerg     return State;
3997330f729Sjoerg 
4007330f729Sjoerg   // Get the access length and make sure it is known.
4017330f729Sjoerg   // FIXME: This assumes the caller has already checked that the access length
4027330f729Sjoerg   // is positive. And that it's unsigned.
403*e038c9c4Sjoerg   SVal LengthVal = C.getSVal(Size.Expression);
4047330f729Sjoerg   Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
4057330f729Sjoerg   if (!Length)
406*e038c9c4Sjoerg     return State;
4077330f729Sjoerg 
4087330f729Sjoerg   // Compute the offset of the last element to be accessed: size-1.
409*e038c9c4Sjoerg   NonLoc One = svalBuilder.makeIntVal(1, SizeTy).castAs<NonLoc>();
410*e038c9c4Sjoerg   SVal Offset = svalBuilder.evalBinOpNN(State, BO_Sub, *Length, One, SizeTy);
4117330f729Sjoerg   if (Offset.isUnknown())
4127330f729Sjoerg     return nullptr;
4137330f729Sjoerg   NonLoc LastOffset = Offset.castAs<NonLoc>();
4147330f729Sjoerg 
4157330f729Sjoerg   // Check that the first buffer is sufficiently long.
416*e038c9c4Sjoerg   SVal BufStart =
417*e038c9c4Sjoerg       svalBuilder.evalCast(BufVal, PtrTy, Buffer.Expression->getType());
4187330f729Sjoerg   if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
4197330f729Sjoerg 
420*e038c9c4Sjoerg     SVal BufEnd =
421*e038c9c4Sjoerg         svalBuilder.evalBinOpLN(State, BO_Add, *BufLoc, LastOffset, PtrTy);
422*e038c9c4Sjoerg 
423*e038c9c4Sjoerg     State = CheckLocation(C, State, Buffer, BufEnd, Access);
4247330f729Sjoerg 
4257330f729Sjoerg     // If the buffer isn't large enough, abort.
426*e038c9c4Sjoerg     if (!State)
4277330f729Sjoerg       return nullptr;
4287330f729Sjoerg   }
4297330f729Sjoerg 
4307330f729Sjoerg   // Large enough or not, return this state!
431*e038c9c4Sjoerg   return State;
4327330f729Sjoerg }
4337330f729Sjoerg 
CheckOverlap(CheckerContext & C,ProgramStateRef state,SizeArgExpr Size,AnyArgExpr First,AnyArgExpr Second) const4347330f729Sjoerg ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
4357330f729Sjoerg                                              ProgramStateRef state,
436*e038c9c4Sjoerg                                              SizeArgExpr Size, AnyArgExpr First,
437*e038c9c4Sjoerg                                              AnyArgExpr Second) const {
4387330f729Sjoerg   if (!Filter.CheckCStringBufferOverlap)
4397330f729Sjoerg     return state;
4407330f729Sjoerg 
4417330f729Sjoerg   // Do a simple check for overlap: if the two arguments are from the same
4427330f729Sjoerg   // buffer, see if the end of the first is greater than the start of the second
4437330f729Sjoerg   // or vice versa.
4447330f729Sjoerg 
4457330f729Sjoerg   // If a previous check has failed, propagate the failure.
4467330f729Sjoerg   if (!state)
4477330f729Sjoerg     return nullptr;
4487330f729Sjoerg 
4497330f729Sjoerg   ProgramStateRef stateTrue, stateFalse;
4507330f729Sjoerg 
4517330f729Sjoerg   // Get the buffer values and make sure they're known locations.
4527330f729Sjoerg   const LocationContext *LCtx = C.getLocationContext();
453*e038c9c4Sjoerg   SVal firstVal = state->getSVal(First.Expression, LCtx);
454*e038c9c4Sjoerg   SVal secondVal = state->getSVal(Second.Expression, LCtx);
4557330f729Sjoerg 
4567330f729Sjoerg   Optional<Loc> firstLoc = firstVal.getAs<Loc>();
4577330f729Sjoerg   if (!firstLoc)
4587330f729Sjoerg     return state;
4597330f729Sjoerg 
4607330f729Sjoerg   Optional<Loc> secondLoc = secondVal.getAs<Loc>();
4617330f729Sjoerg   if (!secondLoc)
4627330f729Sjoerg     return state;
4637330f729Sjoerg 
4647330f729Sjoerg   // Are the two values the same?
4657330f729Sjoerg   SValBuilder &svalBuilder = C.getSValBuilder();
4667330f729Sjoerg   std::tie(stateTrue, stateFalse) =
4677330f729Sjoerg       state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
4687330f729Sjoerg 
4697330f729Sjoerg   if (stateTrue && !stateFalse) {
4707330f729Sjoerg     // If the values are known to be equal, that's automatically an overlap.
471*e038c9c4Sjoerg     emitOverlapBug(C, stateTrue, First.Expression, Second.Expression);
4727330f729Sjoerg     return nullptr;
4737330f729Sjoerg   }
4747330f729Sjoerg 
4757330f729Sjoerg   // assume the two expressions are not equal.
4767330f729Sjoerg   assert(stateFalse);
4777330f729Sjoerg   state = stateFalse;
4787330f729Sjoerg 
4797330f729Sjoerg   // Which value comes first?
4807330f729Sjoerg   QualType cmpTy = svalBuilder.getConditionType();
481*e038c9c4Sjoerg   SVal reverse =
482*e038c9c4Sjoerg       svalBuilder.evalBinOpLL(state, BO_GT, *firstLoc, *secondLoc, cmpTy);
4837330f729Sjoerg   Optional<DefinedOrUnknownSVal> reverseTest =
4847330f729Sjoerg       reverse.getAs<DefinedOrUnknownSVal>();
4857330f729Sjoerg   if (!reverseTest)
4867330f729Sjoerg     return state;
4877330f729Sjoerg 
4887330f729Sjoerg   std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
4897330f729Sjoerg   if (stateTrue) {
4907330f729Sjoerg     if (stateFalse) {
4917330f729Sjoerg       // If we don't know which one comes first, we can't perform this test.
4927330f729Sjoerg       return state;
4937330f729Sjoerg     } else {
4947330f729Sjoerg       // Switch the values so that firstVal is before secondVal.
4957330f729Sjoerg       std::swap(firstLoc, secondLoc);
4967330f729Sjoerg 
4977330f729Sjoerg       // Switch the Exprs as well, so that they still correspond.
4987330f729Sjoerg       std::swap(First, Second);
4997330f729Sjoerg     }
5007330f729Sjoerg   }
5017330f729Sjoerg 
5027330f729Sjoerg   // Get the length, and make sure it too is known.
503*e038c9c4Sjoerg   SVal LengthVal = state->getSVal(Size.Expression, LCtx);
5047330f729Sjoerg   Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
5057330f729Sjoerg   if (!Length)
5067330f729Sjoerg     return state;
5077330f729Sjoerg 
5087330f729Sjoerg   // Convert the first buffer's start address to char*.
5097330f729Sjoerg   // Bail out if the cast fails.
5107330f729Sjoerg   ASTContext &Ctx = svalBuilder.getContext();
5117330f729Sjoerg   QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
512*e038c9c4Sjoerg   SVal FirstStart =
513*e038c9c4Sjoerg       svalBuilder.evalCast(*firstLoc, CharPtrTy, First.Expression->getType());
5147330f729Sjoerg   Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
5157330f729Sjoerg   if (!FirstStartLoc)
5167330f729Sjoerg     return state;
5177330f729Sjoerg 
5187330f729Sjoerg   // Compute the end of the first buffer. Bail out if THAT fails.
519*e038c9c4Sjoerg   SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add, *FirstStartLoc,
520*e038c9c4Sjoerg                                           *Length, CharPtrTy);
5217330f729Sjoerg   Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
5227330f729Sjoerg   if (!FirstEndLoc)
5237330f729Sjoerg     return state;
5247330f729Sjoerg 
5257330f729Sjoerg   // Is the end of the first buffer past the start of the second buffer?
526*e038c9c4Sjoerg   SVal Overlap =
527*e038c9c4Sjoerg       svalBuilder.evalBinOpLL(state, BO_GT, *FirstEndLoc, *secondLoc, cmpTy);
5287330f729Sjoerg   Optional<DefinedOrUnknownSVal> OverlapTest =
5297330f729Sjoerg       Overlap.getAs<DefinedOrUnknownSVal>();
5307330f729Sjoerg   if (!OverlapTest)
5317330f729Sjoerg     return state;
5327330f729Sjoerg 
5337330f729Sjoerg   std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
5347330f729Sjoerg 
5357330f729Sjoerg   if (stateTrue && !stateFalse) {
5367330f729Sjoerg     // Overlap!
537*e038c9c4Sjoerg     emitOverlapBug(C, stateTrue, First.Expression, Second.Expression);
5387330f729Sjoerg     return nullptr;
5397330f729Sjoerg   }
5407330f729Sjoerg 
5417330f729Sjoerg   // assume the two expressions don't overlap.
5427330f729Sjoerg   assert(stateFalse);
5437330f729Sjoerg   return stateFalse;
5447330f729Sjoerg }
5457330f729Sjoerg 
emitOverlapBug(CheckerContext & C,ProgramStateRef state,const Stmt * First,const Stmt * Second) const5467330f729Sjoerg void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
5477330f729Sjoerg                                   const Stmt *First, const Stmt *Second) const {
5487330f729Sjoerg   ExplodedNode *N = C.generateErrorNode(state);
5497330f729Sjoerg   if (!N)
5507330f729Sjoerg     return;
5517330f729Sjoerg 
5527330f729Sjoerg   if (!BT_Overlap)
5537330f729Sjoerg     BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
5547330f729Sjoerg                                  categories::UnixAPI, "Improper arguments"));
5557330f729Sjoerg 
5567330f729Sjoerg   // Generate a report for this bug.
5577330f729Sjoerg   auto report = std::make_unique<PathSensitiveBugReport>(
5587330f729Sjoerg       *BT_Overlap, "Arguments must not be overlapping buffers", N);
5597330f729Sjoerg   report->addRange(First->getSourceRange());
5607330f729Sjoerg   report->addRange(Second->getSourceRange());
5617330f729Sjoerg 
5627330f729Sjoerg   C.emitReport(std::move(report));
5637330f729Sjoerg }
5647330f729Sjoerg 
emitNullArgBug(CheckerContext & C,ProgramStateRef State,const Stmt * S,StringRef WarningMsg) const5657330f729Sjoerg void CStringChecker::emitNullArgBug(CheckerContext &C, ProgramStateRef State,
5667330f729Sjoerg                                     const Stmt *S, StringRef WarningMsg) const {
5677330f729Sjoerg   if (ExplodedNode *N = C.generateErrorNode(State)) {
5687330f729Sjoerg     if (!BT_Null)
5697330f729Sjoerg       BT_Null.reset(new BuiltinBug(
5707330f729Sjoerg           Filter.CheckNameCStringNullArg, categories::UnixAPI,
5717330f729Sjoerg           "Null pointer argument in call to byte string function"));
5727330f729Sjoerg 
5737330f729Sjoerg     BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Null.get());
5747330f729Sjoerg     auto Report = std::make_unique<PathSensitiveBugReport>(*BT, WarningMsg, N);
5757330f729Sjoerg     Report->addRange(S->getSourceRange());
5767330f729Sjoerg     if (const auto *Ex = dyn_cast<Expr>(S))
5777330f729Sjoerg       bugreporter::trackExpressionValue(N, Ex, *Report);
5787330f729Sjoerg     C.emitReport(std::move(Report));
5797330f729Sjoerg   }
5807330f729Sjoerg }
5817330f729Sjoerg 
emitOutOfBoundsBug(CheckerContext & C,ProgramStateRef State,const Stmt * S,StringRef WarningMsg) const5827330f729Sjoerg void CStringChecker::emitOutOfBoundsBug(CheckerContext &C,
5837330f729Sjoerg                                         ProgramStateRef State, const Stmt *S,
5847330f729Sjoerg                                         StringRef WarningMsg) const {
5857330f729Sjoerg   if (ExplodedNode *N = C.generateErrorNode(State)) {
5867330f729Sjoerg     if (!BT_Bounds)
5877330f729Sjoerg       BT_Bounds.reset(new BuiltinBug(
5887330f729Sjoerg           Filter.CheckCStringOutOfBounds ? Filter.CheckNameCStringOutOfBounds
5897330f729Sjoerg                                          : Filter.CheckNameCStringNullArg,
5907330f729Sjoerg           "Out-of-bound array access",
5917330f729Sjoerg           "Byte string function accesses out-of-bound array element"));
5927330f729Sjoerg 
5937330f729Sjoerg     BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Bounds.get());
5947330f729Sjoerg 
5957330f729Sjoerg     // FIXME: It would be nice to eventually make this diagnostic more clear,
5967330f729Sjoerg     // e.g., by referencing the original declaration or by saying *why* this
5977330f729Sjoerg     // reference is outside the range.
5987330f729Sjoerg     auto Report = std::make_unique<PathSensitiveBugReport>(*BT, WarningMsg, N);
5997330f729Sjoerg     Report->addRange(S->getSourceRange());
6007330f729Sjoerg     C.emitReport(std::move(Report));
6017330f729Sjoerg   }
6027330f729Sjoerg }
6037330f729Sjoerg 
emitNotCStringBug(CheckerContext & C,ProgramStateRef State,const Stmt * S,StringRef WarningMsg) const6047330f729Sjoerg void CStringChecker::emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
6057330f729Sjoerg                                        const Stmt *S,
6067330f729Sjoerg                                        StringRef WarningMsg) const {
6077330f729Sjoerg   if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
6087330f729Sjoerg     if (!BT_NotCString)
6097330f729Sjoerg       BT_NotCString.reset(new BuiltinBug(
6107330f729Sjoerg           Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
6117330f729Sjoerg           "Argument is not a null-terminated string."));
6127330f729Sjoerg 
6137330f729Sjoerg     auto Report =
6147330f729Sjoerg         std::make_unique<PathSensitiveBugReport>(*BT_NotCString, WarningMsg, N);
6157330f729Sjoerg 
6167330f729Sjoerg     Report->addRange(S->getSourceRange());
6177330f729Sjoerg     C.emitReport(std::move(Report));
6187330f729Sjoerg   }
6197330f729Sjoerg }
6207330f729Sjoerg 
emitAdditionOverflowBug(CheckerContext & C,ProgramStateRef State) const6217330f729Sjoerg void CStringChecker::emitAdditionOverflowBug(CheckerContext &C,
6227330f729Sjoerg                                              ProgramStateRef State) const {
6237330f729Sjoerg   if (ExplodedNode *N = C.generateErrorNode(State)) {
6247330f729Sjoerg     if (!BT_NotCString)
6257330f729Sjoerg       BT_NotCString.reset(
6267330f729Sjoerg           new BuiltinBug(Filter.CheckNameCStringOutOfBounds, "API",
6277330f729Sjoerg                          "Sum of expressions causes overflow."));
6287330f729Sjoerg 
6297330f729Sjoerg     // This isn't a great error message, but this should never occur in real
6307330f729Sjoerg     // code anyway -- you'd have to create a buffer longer than a size_t can
6317330f729Sjoerg     // represent, which is sort of a contradiction.
6327330f729Sjoerg     const char *WarningMsg =
6337330f729Sjoerg         "This expression will create a string whose length is too big to "
6347330f729Sjoerg         "be represented as a size_t";
6357330f729Sjoerg 
6367330f729Sjoerg     auto Report =
6377330f729Sjoerg         std::make_unique<PathSensitiveBugReport>(*BT_NotCString, WarningMsg, N);
6387330f729Sjoerg     C.emitReport(std::move(Report));
6397330f729Sjoerg   }
6407330f729Sjoerg }
6417330f729Sjoerg 
checkAdditionOverflow(CheckerContext & C,ProgramStateRef state,NonLoc left,NonLoc right) const6427330f729Sjoerg ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
6437330f729Sjoerg                                                      ProgramStateRef state,
6447330f729Sjoerg                                                      NonLoc left,
6457330f729Sjoerg                                                      NonLoc right) const {
6467330f729Sjoerg   // If out-of-bounds checking is turned off, skip the rest.
6477330f729Sjoerg   if (!Filter.CheckCStringOutOfBounds)
6487330f729Sjoerg     return state;
6497330f729Sjoerg 
6507330f729Sjoerg   // If a previous check has failed, propagate the failure.
6517330f729Sjoerg   if (!state)
6527330f729Sjoerg     return nullptr;
6537330f729Sjoerg 
6547330f729Sjoerg   SValBuilder &svalBuilder = C.getSValBuilder();
6557330f729Sjoerg   BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
6567330f729Sjoerg 
6577330f729Sjoerg   QualType sizeTy = svalBuilder.getContext().getSizeType();
6587330f729Sjoerg   const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
6597330f729Sjoerg   NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
6607330f729Sjoerg 
6617330f729Sjoerg   SVal maxMinusRight;
6627330f729Sjoerg   if (right.getAs<nonloc::ConcreteInt>()) {
6637330f729Sjoerg     maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
6647330f729Sjoerg                                                  sizeTy);
6657330f729Sjoerg   } else {
6667330f729Sjoerg     // Try switching the operands. (The order of these two assignments is
6677330f729Sjoerg     // important!)
6687330f729Sjoerg     maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
6697330f729Sjoerg                                             sizeTy);
6707330f729Sjoerg     left = right;
6717330f729Sjoerg   }
6727330f729Sjoerg 
6737330f729Sjoerg   if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
6747330f729Sjoerg     QualType cmpTy = svalBuilder.getConditionType();
6757330f729Sjoerg     // If left > max - right, we have an overflow.
6767330f729Sjoerg     SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
6777330f729Sjoerg                                                 *maxMinusRightNL, cmpTy);
6787330f729Sjoerg 
6797330f729Sjoerg     ProgramStateRef stateOverflow, stateOkay;
6807330f729Sjoerg     std::tie(stateOverflow, stateOkay) =
6817330f729Sjoerg       state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
6827330f729Sjoerg 
6837330f729Sjoerg     if (stateOverflow && !stateOkay) {
6847330f729Sjoerg       // We have an overflow. Emit a bug report.
6857330f729Sjoerg       emitAdditionOverflowBug(C, stateOverflow);
6867330f729Sjoerg       return nullptr;
6877330f729Sjoerg     }
6887330f729Sjoerg 
6897330f729Sjoerg     // From now on, assume an overflow didn't occur.
6907330f729Sjoerg     assert(stateOkay);
6917330f729Sjoerg     state = stateOkay;
6927330f729Sjoerg   }
6937330f729Sjoerg 
6947330f729Sjoerg   return state;
6957330f729Sjoerg }
6967330f729Sjoerg 
setCStringLength(ProgramStateRef state,const MemRegion * MR,SVal strLength)6977330f729Sjoerg ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
6987330f729Sjoerg                                                 const MemRegion *MR,
6997330f729Sjoerg                                                 SVal strLength) {
7007330f729Sjoerg   assert(!strLength.isUndef() && "Attempt to set an undefined string length");
7017330f729Sjoerg 
7027330f729Sjoerg   MR = MR->StripCasts();
7037330f729Sjoerg 
7047330f729Sjoerg   switch (MR->getKind()) {
7057330f729Sjoerg   case MemRegion::StringRegionKind:
7067330f729Sjoerg     // FIXME: This can happen if we strcpy() into a string region. This is
7077330f729Sjoerg     // undefined [C99 6.4.5p6], but we should still warn about it.
7087330f729Sjoerg     return state;
7097330f729Sjoerg 
7107330f729Sjoerg   case MemRegion::SymbolicRegionKind:
7117330f729Sjoerg   case MemRegion::AllocaRegionKind:
712*e038c9c4Sjoerg   case MemRegion::NonParamVarRegionKind:
713*e038c9c4Sjoerg   case MemRegion::ParamVarRegionKind:
7147330f729Sjoerg   case MemRegion::FieldRegionKind:
7157330f729Sjoerg   case MemRegion::ObjCIvarRegionKind:
7167330f729Sjoerg     // These are the types we can currently track string lengths for.
7177330f729Sjoerg     break;
7187330f729Sjoerg 
7197330f729Sjoerg   case MemRegion::ElementRegionKind:
7207330f729Sjoerg     // FIXME: Handle element regions by upper-bounding the parent region's
7217330f729Sjoerg     // string length.
7227330f729Sjoerg     return state;
7237330f729Sjoerg 
7247330f729Sjoerg   default:
7257330f729Sjoerg     // Other regions (mostly non-data) can't have a reliable C string length.
7267330f729Sjoerg     // For now, just ignore the change.
7277330f729Sjoerg     // FIXME: These are rare but not impossible. We should output some kind of
7287330f729Sjoerg     // warning for things like strcpy((char[]){'a', 0}, "b");
7297330f729Sjoerg     return state;
7307330f729Sjoerg   }
7317330f729Sjoerg 
7327330f729Sjoerg   if (strLength.isUnknown())
7337330f729Sjoerg     return state->remove<CStringLength>(MR);
7347330f729Sjoerg 
7357330f729Sjoerg   return state->set<CStringLength>(MR, strLength);
7367330f729Sjoerg }
7377330f729Sjoerg 
getCStringLengthForRegion(CheckerContext & C,ProgramStateRef & state,const Expr * Ex,const MemRegion * MR,bool hypothetical)7387330f729Sjoerg SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
7397330f729Sjoerg                                                ProgramStateRef &state,
7407330f729Sjoerg                                                const Expr *Ex,
7417330f729Sjoerg                                                const MemRegion *MR,
7427330f729Sjoerg                                                bool hypothetical) {
7437330f729Sjoerg   if (!hypothetical) {
7447330f729Sjoerg     // If there's a recorded length, go ahead and return it.
7457330f729Sjoerg     const SVal *Recorded = state->get<CStringLength>(MR);
7467330f729Sjoerg     if (Recorded)
7477330f729Sjoerg       return *Recorded;
7487330f729Sjoerg   }
7497330f729Sjoerg 
7507330f729Sjoerg   // Otherwise, get a new symbol and update the state.
7517330f729Sjoerg   SValBuilder &svalBuilder = C.getSValBuilder();
7527330f729Sjoerg   QualType sizeTy = svalBuilder.getContext().getSizeType();
7537330f729Sjoerg   SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
7547330f729Sjoerg                                                     MR, Ex, sizeTy,
7557330f729Sjoerg                                                     C.getLocationContext(),
7567330f729Sjoerg                                                     C.blockCount());
7577330f729Sjoerg 
7587330f729Sjoerg   if (!hypothetical) {
7597330f729Sjoerg     if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
7607330f729Sjoerg       // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
7617330f729Sjoerg       BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
7627330f729Sjoerg       const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
7637330f729Sjoerg       llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
7647330f729Sjoerg       const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
7657330f729Sjoerg                                                         fourInt);
7667330f729Sjoerg       NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
7677330f729Sjoerg       SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
7687330f729Sjoerg                                                 maxLength, sizeTy);
7697330f729Sjoerg       state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
7707330f729Sjoerg     }
7717330f729Sjoerg     state = state->set<CStringLength>(MR, strLength);
7727330f729Sjoerg   }
7737330f729Sjoerg 
7747330f729Sjoerg   return strLength;
7757330f729Sjoerg }
7767330f729Sjoerg 
getCStringLength(CheckerContext & C,ProgramStateRef & state,const Expr * Ex,SVal Buf,bool hypothetical) const7777330f729Sjoerg SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
7787330f729Sjoerg                                       const Expr *Ex, SVal Buf,
7797330f729Sjoerg                                       bool hypothetical) const {
7807330f729Sjoerg   const MemRegion *MR = Buf.getAsRegion();
7817330f729Sjoerg   if (!MR) {
7827330f729Sjoerg     // If we can't get a region, see if it's something we /know/ isn't a
7837330f729Sjoerg     // C string. In the context of locations, the only time we can issue such
7847330f729Sjoerg     // a warning is for labels.
7857330f729Sjoerg     if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
7867330f729Sjoerg       if (Filter.CheckCStringNotNullTerm) {
7877330f729Sjoerg         SmallString<120> buf;
7887330f729Sjoerg         llvm::raw_svector_ostream os(buf);
7897330f729Sjoerg         assert(CurrentFunctionDescription);
7907330f729Sjoerg         os << "Argument to " << CurrentFunctionDescription
7917330f729Sjoerg            << " is the address of the label '" << Label->getLabel()->getName()
7927330f729Sjoerg            << "', which is not a null-terminated string";
7937330f729Sjoerg 
7947330f729Sjoerg         emitNotCStringBug(C, state, Ex, os.str());
7957330f729Sjoerg       }
7967330f729Sjoerg       return UndefinedVal();
7977330f729Sjoerg     }
7987330f729Sjoerg 
7997330f729Sjoerg     // If it's not a region and not a label, give up.
8007330f729Sjoerg     return UnknownVal();
8017330f729Sjoerg   }
8027330f729Sjoerg 
8037330f729Sjoerg   // If we have a region, strip casts from it and see if we can figure out
8047330f729Sjoerg   // its length. For anything we can't figure out, just return UnknownVal.
8057330f729Sjoerg   MR = MR->StripCasts();
8067330f729Sjoerg 
8077330f729Sjoerg   switch (MR->getKind()) {
8087330f729Sjoerg   case MemRegion::StringRegionKind: {
8097330f729Sjoerg     // Modifying the contents of string regions is undefined [C99 6.4.5p6],
8107330f729Sjoerg     // so we can assume that the byte length is the correct C string length.
8117330f729Sjoerg     SValBuilder &svalBuilder = C.getSValBuilder();
8127330f729Sjoerg     QualType sizeTy = svalBuilder.getContext().getSizeType();
8137330f729Sjoerg     const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
8147330f729Sjoerg     return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
8157330f729Sjoerg   }
8167330f729Sjoerg   case MemRegion::SymbolicRegionKind:
8177330f729Sjoerg   case MemRegion::AllocaRegionKind:
818*e038c9c4Sjoerg   case MemRegion::NonParamVarRegionKind:
819*e038c9c4Sjoerg   case MemRegion::ParamVarRegionKind:
8207330f729Sjoerg   case MemRegion::FieldRegionKind:
8217330f729Sjoerg   case MemRegion::ObjCIvarRegionKind:
8227330f729Sjoerg     return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
8237330f729Sjoerg   case MemRegion::CompoundLiteralRegionKind:
8247330f729Sjoerg     // FIXME: Can we track this? Is it necessary?
8257330f729Sjoerg     return UnknownVal();
8267330f729Sjoerg   case MemRegion::ElementRegionKind:
8277330f729Sjoerg     // FIXME: How can we handle this? It's not good enough to subtract the
8287330f729Sjoerg     // offset from the base string length; consider "123\x00567" and &a[5].
8297330f729Sjoerg     return UnknownVal();
8307330f729Sjoerg   default:
8317330f729Sjoerg     // Other regions (mostly non-data) can't have a reliable C string length.
8327330f729Sjoerg     // In this case, an error is emitted and UndefinedVal is returned.
8337330f729Sjoerg     // The caller should always be prepared to handle this case.
8347330f729Sjoerg     if (Filter.CheckCStringNotNullTerm) {
8357330f729Sjoerg       SmallString<120> buf;
8367330f729Sjoerg       llvm::raw_svector_ostream os(buf);
8377330f729Sjoerg 
8387330f729Sjoerg       assert(CurrentFunctionDescription);
8397330f729Sjoerg       os << "Argument to " << CurrentFunctionDescription << " is ";
8407330f729Sjoerg 
8417330f729Sjoerg       if (SummarizeRegion(os, C.getASTContext(), MR))
8427330f729Sjoerg         os << ", which is not a null-terminated string";
8437330f729Sjoerg       else
8447330f729Sjoerg         os << "not a null-terminated string";
8457330f729Sjoerg 
8467330f729Sjoerg       emitNotCStringBug(C, state, Ex, os.str());
8477330f729Sjoerg     }
8487330f729Sjoerg     return UndefinedVal();
8497330f729Sjoerg   }
8507330f729Sjoerg }
8517330f729Sjoerg 
getCStringLiteral(CheckerContext & C,ProgramStateRef & state,const Expr * expr,SVal val) const8527330f729Sjoerg const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
8537330f729Sjoerg   ProgramStateRef &state, const Expr *expr, SVal val) const {
8547330f729Sjoerg 
8557330f729Sjoerg   // Get the memory region pointed to by the val.
8567330f729Sjoerg   const MemRegion *bufRegion = val.getAsRegion();
8577330f729Sjoerg   if (!bufRegion)
8587330f729Sjoerg     return nullptr;
8597330f729Sjoerg 
8607330f729Sjoerg   // Strip casts off the memory region.
8617330f729Sjoerg   bufRegion = bufRegion->StripCasts();
8627330f729Sjoerg 
8637330f729Sjoerg   // Cast the memory region to a string region.
8647330f729Sjoerg   const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
8657330f729Sjoerg   if (!strRegion)
8667330f729Sjoerg     return nullptr;
8677330f729Sjoerg 
8687330f729Sjoerg   // Return the actual string in the string region.
8697330f729Sjoerg   return strRegion->getStringLiteral();
8707330f729Sjoerg }
8717330f729Sjoerg 
IsFirstBufInBound(CheckerContext & C,ProgramStateRef state,const Expr * FirstBuf,const Expr * Size)8727330f729Sjoerg bool CStringChecker::IsFirstBufInBound(CheckerContext &C,
8737330f729Sjoerg                                        ProgramStateRef state,
8747330f729Sjoerg                                        const Expr *FirstBuf,
8757330f729Sjoerg                                        const Expr *Size) {
8767330f729Sjoerg   // If we do not know that the buffer is long enough we return 'true'.
8777330f729Sjoerg   // Otherwise the parent region of this field region would also get
8787330f729Sjoerg   // invalidated, which would lead to warnings based on an unknown state.
8797330f729Sjoerg 
8807330f729Sjoerg   // Originally copied from CheckBufferAccess and CheckLocation.
8817330f729Sjoerg   SValBuilder &svalBuilder = C.getSValBuilder();
8827330f729Sjoerg   ASTContext &Ctx = svalBuilder.getContext();
8837330f729Sjoerg   const LocationContext *LCtx = C.getLocationContext();
8847330f729Sjoerg 
8857330f729Sjoerg   QualType sizeTy = Size->getType();
8867330f729Sjoerg   QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
8877330f729Sjoerg   SVal BufVal = state->getSVal(FirstBuf, LCtx);
8887330f729Sjoerg 
8897330f729Sjoerg   SVal LengthVal = state->getSVal(Size, LCtx);
8907330f729Sjoerg   Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
8917330f729Sjoerg   if (!Length)
8927330f729Sjoerg     return true; // cf top comment.
8937330f729Sjoerg 
8947330f729Sjoerg   // Compute the offset of the last element to be accessed: size-1.
8957330f729Sjoerg   NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
8967330f729Sjoerg   SVal Offset = svalBuilder.evalBinOpNN(state, BO_Sub, *Length, One, sizeTy);
8977330f729Sjoerg   if (Offset.isUnknown())
8987330f729Sjoerg     return true; // cf top comment
8997330f729Sjoerg   NonLoc LastOffset = Offset.castAs<NonLoc>();
9007330f729Sjoerg 
9017330f729Sjoerg   // Check that the first buffer is sufficiently long.
9027330f729Sjoerg   SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
9037330f729Sjoerg   Optional<Loc> BufLoc = BufStart.getAs<Loc>();
9047330f729Sjoerg   if (!BufLoc)
9057330f729Sjoerg     return true; // cf top comment.
9067330f729Sjoerg 
9077330f729Sjoerg   SVal BufEnd =
9087330f729Sjoerg       svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc, LastOffset, PtrTy);
9097330f729Sjoerg 
9107330f729Sjoerg   // Check for out of bound array element access.
9117330f729Sjoerg   const MemRegion *R = BufEnd.getAsRegion();
9127330f729Sjoerg   if (!R)
9137330f729Sjoerg     return true; // cf top comment.
9147330f729Sjoerg 
9157330f729Sjoerg   const ElementRegion *ER = dyn_cast<ElementRegion>(R);
9167330f729Sjoerg   if (!ER)
9177330f729Sjoerg     return true; // cf top comment.
9187330f729Sjoerg 
9197330f729Sjoerg   // FIXME: Does this crash when a non-standard definition
9207330f729Sjoerg   // of a library function is encountered?
9217330f729Sjoerg   assert(ER->getValueType() == C.getASTContext().CharTy &&
9227330f729Sjoerg          "IsFirstBufInBound should only be called with char* ElementRegions");
9237330f729Sjoerg 
9247330f729Sjoerg   // Get the size of the array.
9257330f729Sjoerg   const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
926*e038c9c4Sjoerg   DefinedOrUnknownSVal SizeDV = getDynamicExtent(state, superReg, svalBuilder);
9277330f729Sjoerg 
9287330f729Sjoerg   // Get the index of the accessed element.
9297330f729Sjoerg   DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
9307330f729Sjoerg 
931*e038c9c4Sjoerg   ProgramStateRef StInBound = state->assumeInBound(Idx, SizeDV, true);
9327330f729Sjoerg 
9337330f729Sjoerg   return static_cast<bool>(StInBound);
9347330f729Sjoerg }
9357330f729Sjoerg 
InvalidateBuffer(CheckerContext & C,ProgramStateRef state,const Expr * E,SVal V,bool IsSourceBuffer,const Expr * Size)9367330f729Sjoerg ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
9377330f729Sjoerg                                                  ProgramStateRef state,
9387330f729Sjoerg                                                  const Expr *E, SVal V,
9397330f729Sjoerg                                                  bool IsSourceBuffer,
9407330f729Sjoerg                                                  const Expr *Size) {
9417330f729Sjoerg   Optional<Loc> L = V.getAs<Loc>();
9427330f729Sjoerg   if (!L)
9437330f729Sjoerg     return state;
9447330f729Sjoerg 
9457330f729Sjoerg   // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
9467330f729Sjoerg   // some assumptions about the value that CFRefCount can't. Even so, it should
9477330f729Sjoerg   // probably be refactored.
9487330f729Sjoerg   if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
9497330f729Sjoerg     const MemRegion *R = MR->getRegion()->StripCasts();
9507330f729Sjoerg 
9517330f729Sjoerg     // Are we dealing with an ElementRegion?  If so, we should be invalidating
9527330f729Sjoerg     // the super-region.
9537330f729Sjoerg     if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
9547330f729Sjoerg       R = ER->getSuperRegion();
9557330f729Sjoerg       // FIXME: What about layers of ElementRegions?
9567330f729Sjoerg     }
9577330f729Sjoerg 
9587330f729Sjoerg     // Invalidate this region.
9597330f729Sjoerg     const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
9607330f729Sjoerg 
9617330f729Sjoerg     bool CausesPointerEscape = false;
9627330f729Sjoerg     RegionAndSymbolInvalidationTraits ITraits;
9637330f729Sjoerg     // Invalidate and escape only indirect regions accessible through the source
9647330f729Sjoerg     // buffer.
9657330f729Sjoerg     if (IsSourceBuffer) {
9667330f729Sjoerg       ITraits.setTrait(R->getBaseRegion(),
9677330f729Sjoerg                        RegionAndSymbolInvalidationTraits::TK_PreserveContents);
9687330f729Sjoerg       ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
9697330f729Sjoerg       CausesPointerEscape = true;
9707330f729Sjoerg     } else {
9717330f729Sjoerg       const MemRegion::Kind& K = R->getKind();
9727330f729Sjoerg       if (K == MemRegion::FieldRegionKind)
9737330f729Sjoerg         if (Size && IsFirstBufInBound(C, state, E, Size)) {
9747330f729Sjoerg           // If destination buffer is a field region and access is in bound,
9757330f729Sjoerg           // do not invalidate its super region.
9767330f729Sjoerg           ITraits.setTrait(
9777330f729Sjoerg               R,
9787330f729Sjoerg               RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
9797330f729Sjoerg         }
9807330f729Sjoerg     }
9817330f729Sjoerg 
9827330f729Sjoerg     return state->invalidateRegions(R, E, C.blockCount(), LCtx,
9837330f729Sjoerg                                     CausesPointerEscape, nullptr, nullptr,
9847330f729Sjoerg                                     &ITraits);
9857330f729Sjoerg   }
9867330f729Sjoerg 
9877330f729Sjoerg   // If we have a non-region value by chance, just remove the binding.
9887330f729Sjoerg   // FIXME: is this necessary or correct? This handles the non-Region
9897330f729Sjoerg   //  cases.  Is it ever valid to store to these?
9907330f729Sjoerg   return state->killBinding(*L);
9917330f729Sjoerg }
9927330f729Sjoerg 
SummarizeRegion(raw_ostream & os,ASTContext & Ctx,const MemRegion * MR)9937330f729Sjoerg bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
9947330f729Sjoerg                                      const MemRegion *MR) {
9957330f729Sjoerg   switch (MR->getKind()) {
9967330f729Sjoerg   case MemRegion::FunctionCodeRegionKind: {
997*e038c9c4Sjoerg     if (const auto *FD = cast<FunctionCodeRegion>(MR)->getDecl())
9987330f729Sjoerg       os << "the address of the function '" << *FD << '\'';
9997330f729Sjoerg     else
10007330f729Sjoerg       os << "the address of a function";
10017330f729Sjoerg     return true;
10027330f729Sjoerg   }
10037330f729Sjoerg   case MemRegion::BlockCodeRegionKind:
10047330f729Sjoerg     os << "block text";
10057330f729Sjoerg     return true;
10067330f729Sjoerg   case MemRegion::BlockDataRegionKind:
10077330f729Sjoerg     os << "a block";
10087330f729Sjoerg     return true;
10097330f729Sjoerg   case MemRegion::CXXThisRegionKind:
10107330f729Sjoerg   case MemRegion::CXXTempObjectRegionKind:
1011*e038c9c4Sjoerg     os << "a C++ temp object of type "
1012*e038c9c4Sjoerg        << cast<TypedValueRegion>(MR)->getValueType().getAsString();
10137330f729Sjoerg     return true;
1014*e038c9c4Sjoerg   case MemRegion::NonParamVarRegionKind:
1015*e038c9c4Sjoerg     os << "a variable of type"
1016*e038c9c4Sjoerg        << cast<TypedValueRegion>(MR)->getValueType().getAsString();
1017*e038c9c4Sjoerg     return true;
1018*e038c9c4Sjoerg   case MemRegion::ParamVarRegionKind:
1019*e038c9c4Sjoerg     os << "a parameter of type"
1020*e038c9c4Sjoerg        << cast<TypedValueRegion>(MR)->getValueType().getAsString();
10217330f729Sjoerg     return true;
10227330f729Sjoerg   case MemRegion::FieldRegionKind:
1023*e038c9c4Sjoerg     os << "a field of type "
1024*e038c9c4Sjoerg        << cast<TypedValueRegion>(MR)->getValueType().getAsString();
10257330f729Sjoerg     return true;
10267330f729Sjoerg   case MemRegion::ObjCIvarRegionKind:
1027*e038c9c4Sjoerg     os << "an instance variable of type "
1028*e038c9c4Sjoerg        << cast<TypedValueRegion>(MR)->getValueType().getAsString();
10297330f729Sjoerg     return true;
10307330f729Sjoerg   default:
10317330f729Sjoerg     return false;
10327330f729Sjoerg   }
10337330f729Sjoerg }
10347330f729Sjoerg 
memsetAux(const Expr * DstBuffer,SVal CharVal,const Expr * Size,CheckerContext & C,ProgramStateRef & State)10357330f729Sjoerg bool CStringChecker::memsetAux(const Expr *DstBuffer, SVal CharVal,
10367330f729Sjoerg                                const Expr *Size, CheckerContext &C,
10377330f729Sjoerg                                ProgramStateRef &State) {
10387330f729Sjoerg   SVal MemVal = C.getSVal(DstBuffer);
10397330f729Sjoerg   SVal SizeVal = C.getSVal(Size);
10407330f729Sjoerg   const MemRegion *MR = MemVal.getAsRegion();
10417330f729Sjoerg   if (!MR)
10427330f729Sjoerg     return false;
10437330f729Sjoerg 
10447330f729Sjoerg   // We're about to model memset by producing a "default binding" in the Store.
10457330f729Sjoerg   // Our current implementation - RegionStore - doesn't support default bindings
10467330f729Sjoerg   // that don't cover the whole base region. So we should first get the offset
10477330f729Sjoerg   // and the base region to figure out whether the offset of buffer is 0.
10487330f729Sjoerg   RegionOffset Offset = MR->getAsOffset();
10497330f729Sjoerg   const MemRegion *BR = Offset.getRegion();
10507330f729Sjoerg 
10517330f729Sjoerg   Optional<NonLoc> SizeNL = SizeVal.getAs<NonLoc>();
10527330f729Sjoerg   if (!SizeNL)
10537330f729Sjoerg     return false;
10547330f729Sjoerg 
10557330f729Sjoerg   SValBuilder &svalBuilder = C.getSValBuilder();
10567330f729Sjoerg   ASTContext &Ctx = C.getASTContext();
10577330f729Sjoerg 
10587330f729Sjoerg   // void *memset(void *dest, int ch, size_t count);
10597330f729Sjoerg   // For now we can only handle the case of offset is 0 and concrete char value.
10607330f729Sjoerg   if (Offset.isValid() && !Offset.hasSymbolicOffset() &&
10617330f729Sjoerg       Offset.getOffset() == 0) {
1062*e038c9c4Sjoerg     // Get the base region's size.
1063*e038c9c4Sjoerg     DefinedOrUnknownSVal SizeDV = getDynamicExtent(State, BR, svalBuilder);
10647330f729Sjoerg 
10657330f729Sjoerg     ProgramStateRef StateWholeReg, StateNotWholeReg;
10667330f729Sjoerg     std::tie(StateWholeReg, StateNotWholeReg) =
1067*e038c9c4Sjoerg         State->assume(svalBuilder.evalEQ(State, SizeDV, *SizeNL));
10687330f729Sjoerg 
10697330f729Sjoerg     // With the semantic of 'memset()', we should convert the CharVal to
10707330f729Sjoerg     // unsigned char.
10717330f729Sjoerg     CharVal = svalBuilder.evalCast(CharVal, Ctx.UnsignedCharTy, Ctx.IntTy);
10727330f729Sjoerg 
10737330f729Sjoerg     ProgramStateRef StateNullChar, StateNonNullChar;
10747330f729Sjoerg     std::tie(StateNullChar, StateNonNullChar) =
10757330f729Sjoerg         assumeZero(C, State, CharVal, Ctx.UnsignedCharTy);
10767330f729Sjoerg 
10777330f729Sjoerg     if (StateWholeReg && !StateNotWholeReg && StateNullChar &&
10787330f729Sjoerg         !StateNonNullChar) {
10797330f729Sjoerg       // If the 'memset()' acts on the whole region of destination buffer and
10807330f729Sjoerg       // the value of the second argument of 'memset()' is zero, bind the second
10817330f729Sjoerg       // argument's value to the destination buffer with 'default binding'.
10827330f729Sjoerg       // FIXME: Since there is no perfect way to bind the non-zero character, we
10837330f729Sjoerg       // can only deal with zero value here. In the future, we need to deal with
10847330f729Sjoerg       // the binding of non-zero value in the case of whole region.
10857330f729Sjoerg       State = State->bindDefaultZero(svalBuilder.makeLoc(BR),
10867330f729Sjoerg                                      C.getLocationContext());
10877330f729Sjoerg     } else {
10887330f729Sjoerg       // If the destination buffer's extent is not equal to the value of
10897330f729Sjoerg       // third argument, just invalidate buffer.
10907330f729Sjoerg       State = InvalidateBuffer(C, State, DstBuffer, MemVal,
10917330f729Sjoerg                                /*IsSourceBuffer*/ false, Size);
10927330f729Sjoerg     }
10937330f729Sjoerg 
10947330f729Sjoerg     if (StateNullChar && !StateNonNullChar) {
10957330f729Sjoerg       // If the value of the second argument of 'memset()' is zero, set the
10967330f729Sjoerg       // string length of destination buffer to 0 directly.
10977330f729Sjoerg       State = setCStringLength(State, MR,
10987330f729Sjoerg                                svalBuilder.makeZeroVal(Ctx.getSizeType()));
10997330f729Sjoerg     } else if (!StateNullChar && StateNonNullChar) {
11007330f729Sjoerg       SVal NewStrLen = svalBuilder.getMetadataSymbolVal(
11017330f729Sjoerg           CStringChecker::getTag(), MR, DstBuffer, Ctx.getSizeType(),
11027330f729Sjoerg           C.getLocationContext(), C.blockCount());
11037330f729Sjoerg 
11047330f729Sjoerg       // If the value of second argument is not zero, then the string length
11057330f729Sjoerg       // is at least the size argument.
11067330f729Sjoerg       SVal NewStrLenGESize = svalBuilder.evalBinOp(
11077330f729Sjoerg           State, BO_GE, NewStrLen, SizeVal, svalBuilder.getConditionType());
11087330f729Sjoerg 
11097330f729Sjoerg       State = setCStringLength(
11107330f729Sjoerg           State->assume(NewStrLenGESize.castAs<DefinedOrUnknownSVal>(), true),
11117330f729Sjoerg           MR, NewStrLen);
11127330f729Sjoerg     }
11137330f729Sjoerg   } else {
11147330f729Sjoerg     // If the offset is not zero and char value is not concrete, we can do
11157330f729Sjoerg     // nothing but invalidate the buffer.
11167330f729Sjoerg     State = InvalidateBuffer(C, State, DstBuffer, MemVal,
11177330f729Sjoerg                              /*IsSourceBuffer*/ false, Size);
11187330f729Sjoerg   }
11197330f729Sjoerg   return true;
11207330f729Sjoerg }
11217330f729Sjoerg 
11227330f729Sjoerg //===----------------------------------------------------------------------===//
11237330f729Sjoerg // evaluation of individual function calls.
11247330f729Sjoerg //===----------------------------------------------------------------------===//
11257330f729Sjoerg 
evalCopyCommon(CheckerContext & C,const CallExpr * CE,ProgramStateRef state,SizeArgExpr Size,DestinationArgExpr Dest,SourceArgExpr Source,bool Restricted,bool IsMempcpy) const1126*e038c9c4Sjoerg void CStringChecker::evalCopyCommon(CheckerContext &C, const CallExpr *CE,
1127*e038c9c4Sjoerg                                     ProgramStateRef state, SizeArgExpr Size,
1128*e038c9c4Sjoerg                                     DestinationArgExpr Dest,
1129*e038c9c4Sjoerg                                     SourceArgExpr Source, bool Restricted,
11307330f729Sjoerg                                     bool IsMempcpy) const {
11317330f729Sjoerg   CurrentFunctionDescription = "memory copy function";
11327330f729Sjoerg 
11337330f729Sjoerg   // See if the size argument is zero.
11347330f729Sjoerg   const LocationContext *LCtx = C.getLocationContext();
1135*e038c9c4Sjoerg   SVal sizeVal = state->getSVal(Size.Expression, LCtx);
1136*e038c9c4Sjoerg   QualType sizeTy = Size.Expression->getType();
11377330f729Sjoerg 
11387330f729Sjoerg   ProgramStateRef stateZeroSize, stateNonZeroSize;
11397330f729Sjoerg   std::tie(stateZeroSize, stateNonZeroSize) =
11407330f729Sjoerg       assumeZero(C, state, sizeVal, sizeTy);
11417330f729Sjoerg 
11427330f729Sjoerg   // Get the value of the Dest.
1143*e038c9c4Sjoerg   SVal destVal = state->getSVal(Dest.Expression, LCtx);
11447330f729Sjoerg 
11457330f729Sjoerg   // If the size is zero, there won't be any actual memory access, so
11467330f729Sjoerg   // just bind the return value to the destination buffer and return.
11477330f729Sjoerg   if (stateZeroSize && !stateNonZeroSize) {
11487330f729Sjoerg     stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
11497330f729Sjoerg     C.addTransition(stateZeroSize);
11507330f729Sjoerg     return;
11517330f729Sjoerg   }
11527330f729Sjoerg 
11537330f729Sjoerg   // If the size can be nonzero, we have to check the other arguments.
11547330f729Sjoerg   if (stateNonZeroSize) {
11557330f729Sjoerg     state = stateNonZeroSize;
11567330f729Sjoerg 
11577330f729Sjoerg     // Ensure the destination is not null. If it is NULL there will be a
11587330f729Sjoerg     // NULL pointer dereference.
1159*e038c9c4Sjoerg     state = checkNonNull(C, state, Dest, destVal);
11607330f729Sjoerg     if (!state)
11617330f729Sjoerg       return;
11627330f729Sjoerg 
11637330f729Sjoerg     // Get the value of the Src.
1164*e038c9c4Sjoerg     SVal srcVal = state->getSVal(Source.Expression, LCtx);
11657330f729Sjoerg 
11667330f729Sjoerg     // Ensure the source is not null. If it is NULL there will be a
11677330f729Sjoerg     // NULL pointer dereference.
1168*e038c9c4Sjoerg     state = checkNonNull(C, state, Source, srcVal);
11697330f729Sjoerg     if (!state)
11707330f729Sjoerg       return;
11717330f729Sjoerg 
11727330f729Sjoerg     // Ensure the accesses are valid and that the buffers do not overlap.
1173*e038c9c4Sjoerg     state = CheckBufferAccess(C, state, Dest, Size, AccessKind::write);
1174*e038c9c4Sjoerg     state = CheckBufferAccess(C, state, Source, Size, AccessKind::read);
1175*e038c9c4Sjoerg 
11767330f729Sjoerg     if (Restricted)
11777330f729Sjoerg       state = CheckOverlap(C, state, Size, Dest, Source);
11787330f729Sjoerg 
11797330f729Sjoerg     if (!state)
11807330f729Sjoerg       return;
11817330f729Sjoerg 
11827330f729Sjoerg     // If this is mempcpy, get the byte after the last byte copied and
11837330f729Sjoerg     // bind the expr.
11847330f729Sjoerg     if (IsMempcpy) {
11857330f729Sjoerg       // Get the byte after the last byte copied.
11867330f729Sjoerg       SValBuilder &SvalBuilder = C.getSValBuilder();
11877330f729Sjoerg       ASTContext &Ctx = SvalBuilder.getContext();
11887330f729Sjoerg       QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
11897330f729Sjoerg       SVal DestRegCharVal =
1190*e038c9c4Sjoerg           SvalBuilder.evalCast(destVal, CharPtrTy, Dest.Expression->getType());
11917330f729Sjoerg       SVal lastElement = C.getSValBuilder().evalBinOp(
1192*e038c9c4Sjoerg           state, BO_Add, DestRegCharVal, sizeVal, Dest.Expression->getType());
11937330f729Sjoerg       // If we don't know how much we copied, we can at least
11947330f729Sjoerg       // conjure a return value for later.
11957330f729Sjoerg       if (lastElement.isUnknown())
11967330f729Sjoerg         lastElement = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
11977330f729Sjoerg                                                           C.blockCount());
11987330f729Sjoerg 
11997330f729Sjoerg       // The byte after the last byte copied is the return value.
12007330f729Sjoerg       state = state->BindExpr(CE, LCtx, lastElement);
12017330f729Sjoerg     } else {
12027330f729Sjoerg       // All other copies return the destination buffer.
12037330f729Sjoerg       // (Well, bcopy() has a void return type, but this won't hurt.)
12047330f729Sjoerg       state = state->BindExpr(CE, LCtx, destVal);
12057330f729Sjoerg     }
12067330f729Sjoerg 
12077330f729Sjoerg     // Invalidate the destination (regular invalidation without pointer-escaping
12087330f729Sjoerg     // the address of the top-level region).
12097330f729Sjoerg     // FIXME: Even if we can't perfectly model the copy, we should see if we
12107330f729Sjoerg     // can use LazyCompoundVals to copy the source values into the destination.
12117330f729Sjoerg     // This would probably remove any existing bindings past the end of the
12127330f729Sjoerg     // copied region, but that's still an improvement over blank invalidation.
1213*e038c9c4Sjoerg     state =
1214*e038c9c4Sjoerg         InvalidateBuffer(C, state, Dest.Expression, C.getSVal(Dest.Expression),
1215*e038c9c4Sjoerg                          /*IsSourceBuffer*/ false, Size.Expression);
12167330f729Sjoerg 
12177330f729Sjoerg     // Invalidate the source (const-invalidation without const-pointer-escaping
12187330f729Sjoerg     // the address of the top-level region).
1219*e038c9c4Sjoerg     state = InvalidateBuffer(C, state, Source.Expression,
1220*e038c9c4Sjoerg                              C.getSVal(Source.Expression),
12217330f729Sjoerg                              /*IsSourceBuffer*/ true, nullptr);
12227330f729Sjoerg 
12237330f729Sjoerg     C.addTransition(state);
12247330f729Sjoerg   }
12257330f729Sjoerg }
12267330f729Sjoerg 
evalMemcpy(CheckerContext & C,const CallExpr * CE) const12277330f729Sjoerg void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
12287330f729Sjoerg   // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
12297330f729Sjoerg   // The return value is the address of the destination buffer.
1230*e038c9c4Sjoerg   DestinationArgExpr Dest = {CE->getArg(0), 0};
1231*e038c9c4Sjoerg   SourceArgExpr Src = {CE->getArg(1), 1};
1232*e038c9c4Sjoerg   SizeArgExpr Size = {CE->getArg(2), 2};
12337330f729Sjoerg 
1234*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
1235*e038c9c4Sjoerg 
1236*e038c9c4Sjoerg   constexpr bool IsRestricted = true;
1237*e038c9c4Sjoerg   constexpr bool IsMempcpy = false;
1238*e038c9c4Sjoerg   evalCopyCommon(C, CE, State, Size, Dest, Src, IsRestricted, IsMempcpy);
12397330f729Sjoerg }
12407330f729Sjoerg 
evalMempcpy(CheckerContext & C,const CallExpr * CE) const12417330f729Sjoerg void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
12427330f729Sjoerg   // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
12437330f729Sjoerg   // The return value is a pointer to the byte following the last written byte.
1244*e038c9c4Sjoerg   DestinationArgExpr Dest = {CE->getArg(0), 0};
1245*e038c9c4Sjoerg   SourceArgExpr Src = {CE->getArg(1), 1};
1246*e038c9c4Sjoerg   SizeArgExpr Size = {CE->getArg(2), 2};
12477330f729Sjoerg 
1248*e038c9c4Sjoerg   constexpr bool IsRestricted = true;
1249*e038c9c4Sjoerg   constexpr bool IsMempcpy = true;
1250*e038c9c4Sjoerg   evalCopyCommon(C, CE, C.getState(), Size, Dest, Src, IsRestricted, IsMempcpy);
12517330f729Sjoerg }
12527330f729Sjoerg 
evalMemmove(CheckerContext & C,const CallExpr * CE) const12537330f729Sjoerg void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
12547330f729Sjoerg   // void *memmove(void *dst, const void *src, size_t n);
12557330f729Sjoerg   // The return value is the address of the destination buffer.
1256*e038c9c4Sjoerg   DestinationArgExpr Dest = {CE->getArg(0), 0};
1257*e038c9c4Sjoerg   SourceArgExpr Src = {CE->getArg(1), 1};
1258*e038c9c4Sjoerg   SizeArgExpr Size = {CE->getArg(2), 2};
12597330f729Sjoerg 
1260*e038c9c4Sjoerg   constexpr bool IsRestricted = false;
1261*e038c9c4Sjoerg   constexpr bool IsMempcpy = false;
1262*e038c9c4Sjoerg   evalCopyCommon(C, CE, C.getState(), Size, Dest, Src, IsRestricted, IsMempcpy);
12637330f729Sjoerg }
12647330f729Sjoerg 
evalBcopy(CheckerContext & C,const CallExpr * CE) const12657330f729Sjoerg void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
12667330f729Sjoerg   // void bcopy(const void *src, void *dst, size_t n);
1267*e038c9c4Sjoerg   SourceArgExpr Src(CE->getArg(0), 0);
1268*e038c9c4Sjoerg   DestinationArgExpr Dest = {CE->getArg(1), 1};
1269*e038c9c4Sjoerg   SizeArgExpr Size = {CE->getArg(2), 2};
1270*e038c9c4Sjoerg 
1271*e038c9c4Sjoerg   constexpr bool IsRestricted = false;
1272*e038c9c4Sjoerg   constexpr bool IsMempcpy = false;
1273*e038c9c4Sjoerg   evalCopyCommon(C, CE, C.getState(), Size, Dest, Src, IsRestricted, IsMempcpy);
12747330f729Sjoerg }
12757330f729Sjoerg 
evalMemcmp(CheckerContext & C,const CallExpr * CE) const12767330f729Sjoerg void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
12777330f729Sjoerg   // int memcmp(const void *s1, const void *s2, size_t n);
12787330f729Sjoerg   CurrentFunctionDescription = "memory comparison function";
12797330f729Sjoerg 
1280*e038c9c4Sjoerg   AnyArgExpr Left = {CE->getArg(0), 0};
1281*e038c9c4Sjoerg   AnyArgExpr Right = {CE->getArg(1), 1};
1282*e038c9c4Sjoerg   SizeArgExpr Size = {CE->getArg(2), 2};
12837330f729Sjoerg 
1284*e038c9c4Sjoerg   ProgramStateRef State = C.getState();
1285*e038c9c4Sjoerg   SValBuilder &Builder = C.getSValBuilder();
1286*e038c9c4Sjoerg   const LocationContext *LCtx = C.getLocationContext();
12877330f729Sjoerg 
12887330f729Sjoerg   // See if the size argument is zero.
1289*e038c9c4Sjoerg   SVal sizeVal = State->getSVal(Size.Expression, LCtx);
1290*e038c9c4Sjoerg   QualType sizeTy = Size.Expression->getType();
12917330f729Sjoerg 
12927330f729Sjoerg   ProgramStateRef stateZeroSize, stateNonZeroSize;
12937330f729Sjoerg   std::tie(stateZeroSize, stateNonZeroSize) =
1294*e038c9c4Sjoerg       assumeZero(C, State, sizeVal, sizeTy);
12957330f729Sjoerg 
12967330f729Sjoerg   // If the size can be zero, the result will be 0 in that case, and we don't
12977330f729Sjoerg   // have to check either of the buffers.
12987330f729Sjoerg   if (stateZeroSize) {
1299*e038c9c4Sjoerg     State = stateZeroSize;
1300*e038c9c4Sjoerg     State = State->BindExpr(CE, LCtx, Builder.makeZeroVal(CE->getType()));
1301*e038c9c4Sjoerg     C.addTransition(State);
13027330f729Sjoerg   }
13037330f729Sjoerg 
13047330f729Sjoerg   // If the size can be nonzero, we have to check the other arguments.
13057330f729Sjoerg   if (stateNonZeroSize) {
1306*e038c9c4Sjoerg     State = stateNonZeroSize;
13077330f729Sjoerg     // If we know the two buffers are the same, we know the result is 0.
13087330f729Sjoerg     // First, get the two buffers' addresses. Another checker will have already
13097330f729Sjoerg     // made sure they're not undefined.
13107330f729Sjoerg     DefinedOrUnknownSVal LV =
1311*e038c9c4Sjoerg         State->getSVal(Left.Expression, LCtx).castAs<DefinedOrUnknownSVal>();
13127330f729Sjoerg     DefinedOrUnknownSVal RV =
1313*e038c9c4Sjoerg         State->getSVal(Right.Expression, LCtx).castAs<DefinedOrUnknownSVal>();
13147330f729Sjoerg 
13157330f729Sjoerg     // See if they are the same.
1316*e038c9c4Sjoerg     ProgramStateRef SameBuffer, NotSameBuffer;
1317*e038c9c4Sjoerg     std::tie(SameBuffer, NotSameBuffer) =
1318*e038c9c4Sjoerg         State->assume(Builder.evalEQ(State, LV, RV));
13197330f729Sjoerg 
1320*e038c9c4Sjoerg     // If the two arguments are the same buffer, we know the result is 0,
13217330f729Sjoerg     // and we only need to check one size.
1322*e038c9c4Sjoerg     if (SameBuffer && !NotSameBuffer) {
1323*e038c9c4Sjoerg       State = SameBuffer;
1324*e038c9c4Sjoerg       State = CheckBufferAccess(C, State, Left, Size, AccessKind::read);
1325*e038c9c4Sjoerg       if (State) {
1326*e038c9c4Sjoerg         State =
1327*e038c9c4Sjoerg             SameBuffer->BindExpr(CE, LCtx, Builder.makeZeroVal(CE->getType()));
1328*e038c9c4Sjoerg         C.addTransition(State);
13297330f729Sjoerg       }
1330*e038c9c4Sjoerg       return;
13317330f729Sjoerg     }
13327330f729Sjoerg 
1333*e038c9c4Sjoerg     // If the two arguments might be different buffers, we have to check
1334*e038c9c4Sjoerg     // the size of both of them.
1335*e038c9c4Sjoerg     assert(NotSameBuffer);
1336*e038c9c4Sjoerg     State = CheckBufferAccess(C, State, Right, Size, AccessKind::read);
1337*e038c9c4Sjoerg     State = CheckBufferAccess(C, State, Left, Size, AccessKind::read);
1338*e038c9c4Sjoerg     if (State) {
13397330f729Sjoerg       // The return value is the comparison result, which we don't know.
1340*e038c9c4Sjoerg       SVal CmpV = Builder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
1341*e038c9c4Sjoerg       State = State->BindExpr(CE, LCtx, CmpV);
1342*e038c9c4Sjoerg       C.addTransition(State);
13437330f729Sjoerg     }
13447330f729Sjoerg   }
13457330f729Sjoerg }
13467330f729Sjoerg 
evalstrLength(CheckerContext & C,const CallExpr * CE) const13477330f729Sjoerg void CStringChecker::evalstrLength(CheckerContext &C,
13487330f729Sjoerg                                    const CallExpr *CE) const {
13497330f729Sjoerg   // size_t strlen(const char *s);
13507330f729Sjoerg   evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
13517330f729Sjoerg }
13527330f729Sjoerg 
evalstrnLength(CheckerContext & C,const CallExpr * CE) const13537330f729Sjoerg void CStringChecker::evalstrnLength(CheckerContext &C,
13547330f729Sjoerg                                     const CallExpr *CE) const {
13557330f729Sjoerg   // size_t strnlen(const char *s, size_t maxlen);
13567330f729Sjoerg   evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
13577330f729Sjoerg }
13587330f729Sjoerg 
evalstrLengthCommon(CheckerContext & C,const CallExpr * CE,bool IsStrnlen) const13597330f729Sjoerg void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
13607330f729Sjoerg                                          bool IsStrnlen) const {
13617330f729Sjoerg   CurrentFunctionDescription = "string length function";
13627330f729Sjoerg   ProgramStateRef state = C.getState();
13637330f729Sjoerg   const LocationContext *LCtx = C.getLocationContext();
13647330f729Sjoerg 
13657330f729Sjoerg   if (IsStrnlen) {
13667330f729Sjoerg     const Expr *maxlenExpr = CE->getArg(1);
13677330f729Sjoerg     SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
13687330f729Sjoerg 
13697330f729Sjoerg     ProgramStateRef stateZeroSize, stateNonZeroSize;
13707330f729Sjoerg     std::tie(stateZeroSize, stateNonZeroSize) =
13717330f729Sjoerg       assumeZero(C, state, maxlenVal, maxlenExpr->getType());
13727330f729Sjoerg 
13737330f729Sjoerg     // If the size can be zero, the result will be 0 in that case, and we don't
13747330f729Sjoerg     // have to check the string itself.
13757330f729Sjoerg     if (stateZeroSize) {
13767330f729Sjoerg       SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
13777330f729Sjoerg       stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
13787330f729Sjoerg       C.addTransition(stateZeroSize);
13797330f729Sjoerg     }
13807330f729Sjoerg 
13817330f729Sjoerg     // If the size is GUARANTEED to be zero, we're done!
13827330f729Sjoerg     if (!stateNonZeroSize)
13837330f729Sjoerg       return;
13847330f729Sjoerg 
13857330f729Sjoerg     // Otherwise, record the assumption that the size is nonzero.
13867330f729Sjoerg     state = stateNonZeroSize;
13877330f729Sjoerg   }
13887330f729Sjoerg 
13897330f729Sjoerg   // Check that the string argument is non-null.
1390*e038c9c4Sjoerg   AnyArgExpr Arg = {CE->getArg(0), 0};
1391*e038c9c4Sjoerg   SVal ArgVal = state->getSVal(Arg.Expression, LCtx);
1392*e038c9c4Sjoerg   state = checkNonNull(C, state, Arg, ArgVal);
13937330f729Sjoerg 
13947330f729Sjoerg   if (!state)
13957330f729Sjoerg     return;
13967330f729Sjoerg 
1397*e038c9c4Sjoerg   SVal strLength = getCStringLength(C, state, Arg.Expression, ArgVal);
13987330f729Sjoerg 
13997330f729Sjoerg   // If the argument isn't a valid C string, there's no valid state to
14007330f729Sjoerg   // transition to.
14017330f729Sjoerg   if (strLength.isUndef())
14027330f729Sjoerg     return;
14037330f729Sjoerg 
14047330f729Sjoerg   DefinedOrUnknownSVal result = UnknownVal();
14057330f729Sjoerg 
14067330f729Sjoerg   // If the check is for strnlen() then bind the return value to no more than
14077330f729Sjoerg   // the maxlen value.
14087330f729Sjoerg   if (IsStrnlen) {
14097330f729Sjoerg     QualType cmpTy = C.getSValBuilder().getConditionType();
14107330f729Sjoerg 
14117330f729Sjoerg     // It's a little unfortunate to be getting this again,
14127330f729Sjoerg     // but it's not that expensive...
14137330f729Sjoerg     const Expr *maxlenExpr = CE->getArg(1);
14147330f729Sjoerg     SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
14157330f729Sjoerg 
14167330f729Sjoerg     Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
14177330f729Sjoerg     Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
14187330f729Sjoerg 
14197330f729Sjoerg     if (strLengthNL && maxlenValNL) {
14207330f729Sjoerg       ProgramStateRef stateStringTooLong, stateStringNotTooLong;
14217330f729Sjoerg 
14227330f729Sjoerg       // Check if the strLength is greater than the maxlen.
14237330f729Sjoerg       std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
14247330f729Sjoerg           C.getSValBuilder()
14257330f729Sjoerg               .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
14267330f729Sjoerg               .castAs<DefinedOrUnknownSVal>());
14277330f729Sjoerg 
14287330f729Sjoerg       if (stateStringTooLong && !stateStringNotTooLong) {
14297330f729Sjoerg         // If the string is longer than maxlen, return maxlen.
14307330f729Sjoerg         result = *maxlenValNL;
14317330f729Sjoerg       } else if (stateStringNotTooLong && !stateStringTooLong) {
14327330f729Sjoerg         // If the string is shorter than maxlen, return its length.
14337330f729Sjoerg         result = *strLengthNL;
14347330f729Sjoerg       }
14357330f729Sjoerg     }
14367330f729Sjoerg 
14377330f729Sjoerg     if (result.isUnknown()) {
14387330f729Sjoerg       // If we don't have enough information for a comparison, there's
14397330f729Sjoerg       // no guarantee the full string length will actually be returned.
14407330f729Sjoerg       // All we know is the return value is the min of the string length
14417330f729Sjoerg       // and the limit. This is better than nothing.
14427330f729Sjoerg       result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
14437330f729Sjoerg                                                    C.blockCount());
14447330f729Sjoerg       NonLoc resultNL = result.castAs<NonLoc>();
14457330f729Sjoerg 
14467330f729Sjoerg       if (strLengthNL) {
14477330f729Sjoerg         state = state->assume(C.getSValBuilder().evalBinOpNN(
14487330f729Sjoerg                                   state, BO_LE, resultNL, *strLengthNL, cmpTy)
14497330f729Sjoerg                                   .castAs<DefinedOrUnknownSVal>(), true);
14507330f729Sjoerg       }
14517330f729Sjoerg 
14527330f729Sjoerg       if (maxlenValNL) {
14537330f729Sjoerg         state = state->assume(C.getSValBuilder().evalBinOpNN(
14547330f729Sjoerg                                   state, BO_LE, resultNL, *maxlenValNL, cmpTy)
14557330f729Sjoerg                                   .castAs<DefinedOrUnknownSVal>(), true);
14567330f729Sjoerg       }
14577330f729Sjoerg     }
14587330f729Sjoerg 
14597330f729Sjoerg   } else {
14607330f729Sjoerg     // This is a plain strlen(), not strnlen().
14617330f729Sjoerg     result = strLength.castAs<DefinedOrUnknownSVal>();
14627330f729Sjoerg 
14637330f729Sjoerg     // If we don't know the length of the string, conjure a return
14647330f729Sjoerg     // value, so it can be used in constraints, at least.
14657330f729Sjoerg     if (result.isUnknown()) {
14667330f729Sjoerg       result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
14677330f729Sjoerg                                                    C.blockCount());
14687330f729Sjoerg     }
14697330f729Sjoerg   }
14707330f729Sjoerg 
14717330f729Sjoerg   // Bind the return value.
14727330f729Sjoerg   assert(!result.isUnknown() && "Should have conjured a value by now");
14737330f729Sjoerg   state = state->BindExpr(CE, LCtx, result);
14747330f729Sjoerg   C.addTransition(state);
14757330f729Sjoerg }
14767330f729Sjoerg 
evalStrcpy(CheckerContext & C,const CallExpr * CE) const14777330f729Sjoerg void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
14787330f729Sjoerg   // char *strcpy(char *restrict dst, const char *restrict src);
14797330f729Sjoerg   evalStrcpyCommon(C, CE,
1480*e038c9c4Sjoerg                    /* ReturnEnd = */ false,
1481*e038c9c4Sjoerg                    /* IsBounded = */ false,
1482*e038c9c4Sjoerg                    /* appendK = */ ConcatFnKind::none);
14837330f729Sjoerg }
14847330f729Sjoerg 
evalStrncpy(CheckerContext & C,const CallExpr * CE) const14857330f729Sjoerg void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
14867330f729Sjoerg   // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
14877330f729Sjoerg   evalStrcpyCommon(C, CE,
1488*e038c9c4Sjoerg                    /* ReturnEnd = */ false,
1489*e038c9c4Sjoerg                    /* IsBounded = */ true,
1490*e038c9c4Sjoerg                    /* appendK = */ ConcatFnKind::none);
14917330f729Sjoerg }
14927330f729Sjoerg 
evalStpcpy(CheckerContext & C,const CallExpr * CE) const14937330f729Sjoerg void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
14947330f729Sjoerg   // char *stpcpy(char *restrict dst, const char *restrict src);
14957330f729Sjoerg   evalStrcpyCommon(C, CE,
1496*e038c9c4Sjoerg                    /* ReturnEnd = */ true,
1497*e038c9c4Sjoerg                    /* IsBounded = */ false,
1498*e038c9c4Sjoerg                    /* appendK = */ ConcatFnKind::none);
14997330f729Sjoerg }
15007330f729Sjoerg 
evalStrlcpy(CheckerContext & C,const CallExpr * CE) const15017330f729Sjoerg void CStringChecker::evalStrlcpy(CheckerContext &C, const CallExpr *CE) const {
1502*e038c9c4Sjoerg   // size_t strlcpy(char *dest, const char *src, size_t size);
15037330f729Sjoerg   evalStrcpyCommon(C, CE,
1504*e038c9c4Sjoerg                    /* ReturnEnd = */ true,
1505*e038c9c4Sjoerg                    /* IsBounded = */ true,
1506*e038c9c4Sjoerg                    /* appendK = */ ConcatFnKind::none,
15077330f729Sjoerg                    /* returnPtr = */ false);
15087330f729Sjoerg }
15097330f729Sjoerg 
evalStrcat(CheckerContext & C,const CallExpr * CE) const15107330f729Sjoerg void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
15117330f729Sjoerg   // char *strcat(char *restrict s1, const char *restrict s2);
15127330f729Sjoerg   evalStrcpyCommon(C, CE,
1513*e038c9c4Sjoerg                    /* ReturnEnd = */ false,
1514*e038c9c4Sjoerg                    /* IsBounded = */ false,
1515*e038c9c4Sjoerg                    /* appendK = */ ConcatFnKind::strcat);
15167330f729Sjoerg }
15177330f729Sjoerg 
evalStrncat(CheckerContext & C,const CallExpr * CE) const15187330f729Sjoerg void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
15197330f729Sjoerg   //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
15207330f729Sjoerg   evalStrcpyCommon(C, CE,
1521*e038c9c4Sjoerg                    /* ReturnEnd = */ false,
1522*e038c9c4Sjoerg                    /* IsBounded = */ true,
1523*e038c9c4Sjoerg                    /* appendK = */ ConcatFnKind::strcat);
15247330f729Sjoerg }
15257330f729Sjoerg 
evalStrlcat(CheckerContext & C,const CallExpr * CE) const15267330f729Sjoerg void CStringChecker::evalStrlcat(CheckerContext &C, const CallExpr *CE) const {
1527*e038c9c4Sjoerg   // size_t strlcat(char *dst, const char *src, size_t size);
1528*e038c9c4Sjoerg   // It will append at most size - strlen(dst) - 1 bytes,
1529*e038c9c4Sjoerg   // NULL-terminating the result.
15307330f729Sjoerg   evalStrcpyCommon(C, CE,
1531*e038c9c4Sjoerg                    /* ReturnEnd = */ false,
1532*e038c9c4Sjoerg                    /* IsBounded = */ true,
1533*e038c9c4Sjoerg                    /* appendK = */ ConcatFnKind::strlcat,
15347330f729Sjoerg                    /* returnPtr = */ false);
15357330f729Sjoerg }
15367330f729Sjoerg 
evalStrcpyCommon(CheckerContext & C,const CallExpr * CE,bool ReturnEnd,bool IsBounded,ConcatFnKind appendK,bool returnPtr) const15377330f729Sjoerg void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
1538*e038c9c4Sjoerg                                       bool ReturnEnd, bool IsBounded,
1539*e038c9c4Sjoerg                                       ConcatFnKind appendK,
1540*e038c9c4Sjoerg                                       bool returnPtr) const {
1541*e038c9c4Sjoerg   if (appendK == ConcatFnKind::none)
15427330f729Sjoerg     CurrentFunctionDescription = "string copy function";
1543*e038c9c4Sjoerg   else
1544*e038c9c4Sjoerg     CurrentFunctionDescription = "string concatenation function";
1545*e038c9c4Sjoerg 
15467330f729Sjoerg   ProgramStateRef state = C.getState();
15477330f729Sjoerg   const LocationContext *LCtx = C.getLocationContext();
15487330f729Sjoerg 
15497330f729Sjoerg   // Check that the destination is non-null.
1550*e038c9c4Sjoerg   DestinationArgExpr Dst = {CE->getArg(0), 0};
1551*e038c9c4Sjoerg   SVal DstVal = state->getSVal(Dst.Expression, LCtx);
1552*e038c9c4Sjoerg   state = checkNonNull(C, state, Dst, DstVal);
15537330f729Sjoerg   if (!state)
15547330f729Sjoerg     return;
15557330f729Sjoerg 
15567330f729Sjoerg   // Check that the source is non-null.
1557*e038c9c4Sjoerg   SourceArgExpr srcExpr = {CE->getArg(1), 1};
1558*e038c9c4Sjoerg   SVal srcVal = state->getSVal(srcExpr.Expression, LCtx);
1559*e038c9c4Sjoerg   state = checkNonNull(C, state, srcExpr, srcVal);
15607330f729Sjoerg   if (!state)
15617330f729Sjoerg     return;
15627330f729Sjoerg 
15637330f729Sjoerg   // Get the string length of the source.
1564*e038c9c4Sjoerg   SVal strLength = getCStringLength(C, state, srcExpr.Expression, srcVal);
1565*e038c9c4Sjoerg   Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1566*e038c9c4Sjoerg 
1567*e038c9c4Sjoerg   // Get the string length of the destination buffer.
1568*e038c9c4Sjoerg   SVal dstStrLength = getCStringLength(C, state, Dst.Expression, DstVal);
1569*e038c9c4Sjoerg   Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
15707330f729Sjoerg 
15717330f729Sjoerg   // If the source isn't a valid C string, give up.
15727330f729Sjoerg   if (strLength.isUndef())
15737330f729Sjoerg     return;
15747330f729Sjoerg 
15757330f729Sjoerg   SValBuilder &svalBuilder = C.getSValBuilder();
15767330f729Sjoerg   QualType cmpTy = svalBuilder.getConditionType();
15777330f729Sjoerg   QualType sizeTy = svalBuilder.getContext().getSizeType();
15787330f729Sjoerg 
15797330f729Sjoerg   // These two values allow checking two kinds of errors:
15807330f729Sjoerg   // - actual overflows caused by a source that doesn't fit in the destination
15817330f729Sjoerg   // - potential overflows caused by a bound that could exceed the destination
15827330f729Sjoerg   SVal amountCopied = UnknownVal();
15837330f729Sjoerg   SVal maxLastElementIndex = UnknownVal();
15847330f729Sjoerg   const char *boundWarning = nullptr;
15857330f729Sjoerg 
1586*e038c9c4Sjoerg   // FIXME: Why do we choose the srcExpr if the access has no size?
1587*e038c9c4Sjoerg   //  Note that the 3rd argument of the call would be the size parameter.
1588*e038c9c4Sjoerg   SizeArgExpr SrcExprAsSizeDummy = {srcExpr.Expression, srcExpr.ArgumentIndex};
1589*e038c9c4Sjoerg   state = CheckOverlap(
1590*e038c9c4Sjoerg       C, state,
1591*e038c9c4Sjoerg       (IsBounded ? SizeArgExpr{CE->getArg(2), 2} : SrcExprAsSizeDummy), Dst,
1592*e038c9c4Sjoerg       srcExpr);
15937330f729Sjoerg 
15947330f729Sjoerg   if (!state)
15957330f729Sjoerg     return;
15967330f729Sjoerg 
15977330f729Sjoerg   // If the function is strncpy, strncat, etc... it is bounded.
1598*e038c9c4Sjoerg   if (IsBounded) {
15997330f729Sjoerg     // Get the max number of characters to copy.
1600*e038c9c4Sjoerg     SizeArgExpr lenExpr = {CE->getArg(2), 2};
1601*e038c9c4Sjoerg     SVal lenVal = state->getSVal(lenExpr.Expression, LCtx);
16027330f729Sjoerg 
16037330f729Sjoerg     // Protect against misdeclared strncpy().
1604*e038c9c4Sjoerg     lenVal =
1605*e038c9c4Sjoerg         svalBuilder.evalCast(lenVal, sizeTy, lenExpr.Expression->getType());
16067330f729Sjoerg 
16077330f729Sjoerg     Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
16087330f729Sjoerg 
16097330f729Sjoerg     // If we know both values, we might be able to figure out how much
16107330f729Sjoerg     // we're copying.
16117330f729Sjoerg     if (strLengthNL && lenValNL) {
1612*e038c9c4Sjoerg       switch (appendK) {
1613*e038c9c4Sjoerg       case ConcatFnKind::none:
1614*e038c9c4Sjoerg       case ConcatFnKind::strcat: {
16157330f729Sjoerg         ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
16167330f729Sjoerg         // Check if the max number to copy is less than the length of the src.
16177330f729Sjoerg         // If the bound is equal to the source length, strncpy won't null-
16187330f729Sjoerg         // terminate the result!
16197330f729Sjoerg         std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
1620*e038c9c4Sjoerg             svalBuilder
1621*e038c9c4Sjoerg                 .evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
16227330f729Sjoerg                 .castAs<DefinedOrUnknownSVal>());
16237330f729Sjoerg 
16247330f729Sjoerg         if (stateSourceTooLong && !stateSourceNotTooLong) {
1625*e038c9c4Sjoerg           // Max number to copy is less than the length of the src, so the
1626*e038c9c4Sjoerg           // actual strLength copied is the max number arg.
16277330f729Sjoerg           state = stateSourceTooLong;
16287330f729Sjoerg           amountCopied = lenVal;
16297330f729Sjoerg 
16307330f729Sjoerg         } else if (!stateSourceTooLong && stateSourceNotTooLong) {
16317330f729Sjoerg           // The source buffer entirely fits in the bound.
16327330f729Sjoerg           state = stateSourceNotTooLong;
16337330f729Sjoerg           amountCopied = strLength;
16347330f729Sjoerg         }
1635*e038c9c4Sjoerg         break;
1636*e038c9c4Sjoerg       }
1637*e038c9c4Sjoerg       case ConcatFnKind::strlcat:
1638*e038c9c4Sjoerg         if (!dstStrLengthNL)
1639*e038c9c4Sjoerg           return;
1640*e038c9c4Sjoerg 
1641*e038c9c4Sjoerg         // amountCopied = min (size - dstLen - 1 , srcLen)
1642*e038c9c4Sjoerg         SVal freeSpace = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1643*e038c9c4Sjoerg                                                  *dstStrLengthNL, sizeTy);
1644*e038c9c4Sjoerg         if (!freeSpace.getAs<NonLoc>())
1645*e038c9c4Sjoerg           return;
1646*e038c9c4Sjoerg         freeSpace =
1647*e038c9c4Sjoerg             svalBuilder.evalBinOp(state, BO_Sub, freeSpace,
1648*e038c9c4Sjoerg                                   svalBuilder.makeIntVal(1, sizeTy), sizeTy);
1649*e038c9c4Sjoerg         Optional<NonLoc> freeSpaceNL = freeSpace.getAs<NonLoc>();
1650*e038c9c4Sjoerg 
1651*e038c9c4Sjoerg         // While unlikely, it is possible that the subtraction is
1652*e038c9c4Sjoerg         // too complex to compute, let's check whether it succeeded.
1653*e038c9c4Sjoerg         if (!freeSpaceNL)
1654*e038c9c4Sjoerg           return;
1655*e038c9c4Sjoerg         SVal hasEnoughSpace = svalBuilder.evalBinOpNN(
1656*e038c9c4Sjoerg             state, BO_LE, *strLengthNL, *freeSpaceNL, cmpTy);
1657*e038c9c4Sjoerg 
1658*e038c9c4Sjoerg         ProgramStateRef TrueState, FalseState;
1659*e038c9c4Sjoerg         std::tie(TrueState, FalseState) =
1660*e038c9c4Sjoerg             state->assume(hasEnoughSpace.castAs<DefinedOrUnknownSVal>());
1661*e038c9c4Sjoerg 
1662*e038c9c4Sjoerg         // srcStrLength <= size - dstStrLength -1
1663*e038c9c4Sjoerg         if (TrueState && !FalseState) {
1664*e038c9c4Sjoerg           amountCopied = strLength;
16657330f729Sjoerg         }
16667330f729Sjoerg 
1667*e038c9c4Sjoerg         // srcStrLength > size - dstStrLength -1
1668*e038c9c4Sjoerg         if (!TrueState && FalseState) {
1669*e038c9c4Sjoerg           amountCopied = freeSpace;
1670*e038c9c4Sjoerg         }
1671*e038c9c4Sjoerg 
1672*e038c9c4Sjoerg         if (TrueState && FalseState)
1673*e038c9c4Sjoerg           amountCopied = UnknownVal();
1674*e038c9c4Sjoerg         break;
1675*e038c9c4Sjoerg       }
1676*e038c9c4Sjoerg     }
16777330f729Sjoerg     // We still want to know if the bound is known to be too large.
16787330f729Sjoerg     if (lenValNL) {
1679*e038c9c4Sjoerg       switch (appendK) {
1680*e038c9c4Sjoerg       case ConcatFnKind::strcat:
16817330f729Sjoerg         // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
16827330f729Sjoerg 
16837330f729Sjoerg         // Get the string length of the destination. If the destination is
16847330f729Sjoerg         // memory that can't have a string length, we shouldn't be copying
16857330f729Sjoerg         // into it anyway.
16867330f729Sjoerg         if (dstStrLength.isUndef())
16877330f729Sjoerg           return;
16887330f729Sjoerg 
1689*e038c9c4Sjoerg         if (dstStrLengthNL) {
1690*e038c9c4Sjoerg           maxLastElementIndex = svalBuilder.evalBinOpNN(
1691*e038c9c4Sjoerg               state, BO_Add, *lenValNL, *dstStrLengthNL, sizeTy);
1692*e038c9c4Sjoerg 
16937330f729Sjoerg           boundWarning = "Size argument is greater than the free space in the "
16947330f729Sjoerg                          "destination buffer";
16957330f729Sjoerg         }
1696*e038c9c4Sjoerg         break;
1697*e038c9c4Sjoerg       case ConcatFnKind::none:
1698*e038c9c4Sjoerg       case ConcatFnKind::strlcat:
1699*e038c9c4Sjoerg         // For strncpy and strlcat, this is just checking
1700*e038c9c4Sjoerg         //  that lenVal <= sizeof(dst).
17017330f729Sjoerg         // (Yes, strncpy and strncat differ in how they treat termination.
17027330f729Sjoerg         // strncat ALWAYS terminates, but strncpy doesn't.)
17037330f729Sjoerg 
17047330f729Sjoerg         // We need a special case for when the copy size is zero, in which
17057330f729Sjoerg         // case strncpy will do no work at all. Our bounds check uses n-1
17067330f729Sjoerg         // as the last element accessed, so n == 0 is problematic.
17077330f729Sjoerg         ProgramStateRef StateZeroSize, StateNonZeroSize;
17087330f729Sjoerg         std::tie(StateZeroSize, StateNonZeroSize) =
17097330f729Sjoerg             assumeZero(C, state, *lenValNL, sizeTy);
17107330f729Sjoerg 
17117330f729Sjoerg         // If the size is known to be zero, we're done.
17127330f729Sjoerg         if (StateZeroSize && !StateNonZeroSize) {
17137330f729Sjoerg           if (returnPtr) {
17147330f729Sjoerg             StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
17157330f729Sjoerg           } else {
1716*e038c9c4Sjoerg             if (appendK == ConcatFnKind::none) {
1717*e038c9c4Sjoerg               // strlcpy returns strlen(src)
1718*e038c9c4Sjoerg               StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, strLength);
1719*e038c9c4Sjoerg             } else {
1720*e038c9c4Sjoerg               // strlcat returns strlen(src) + strlen(dst)
1721*e038c9c4Sjoerg               SVal retSize = svalBuilder.evalBinOp(
1722*e038c9c4Sjoerg                   state, BO_Add, strLength, dstStrLength, sizeTy);
1723*e038c9c4Sjoerg               StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, retSize);
1724*e038c9c4Sjoerg             }
17257330f729Sjoerg           }
17267330f729Sjoerg           C.addTransition(StateZeroSize);
17277330f729Sjoerg           return;
17287330f729Sjoerg         }
17297330f729Sjoerg 
17307330f729Sjoerg         // Otherwise, go ahead and figure out the last element we'll touch.
17317330f729Sjoerg         // We don't record the non-zero assumption here because we can't
17327330f729Sjoerg         // be sure. We won't warn on a possible zero.
17337330f729Sjoerg         NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
1734*e038c9c4Sjoerg         maxLastElementIndex =
1735*e038c9c4Sjoerg             svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL, one, sizeTy);
17367330f729Sjoerg         boundWarning = "Size argument is greater than the length of the "
17377330f729Sjoerg                        "destination buffer";
1738*e038c9c4Sjoerg         break;
17397330f729Sjoerg       }
17407330f729Sjoerg     }
17417330f729Sjoerg   } else {
17427330f729Sjoerg     // The function isn't bounded. The amount copied should match the length
17437330f729Sjoerg     // of the source buffer.
17447330f729Sjoerg     amountCopied = strLength;
17457330f729Sjoerg   }
17467330f729Sjoerg 
17477330f729Sjoerg   assert(state);
17487330f729Sjoerg 
17497330f729Sjoerg   // This represents the number of characters copied into the destination
17507330f729Sjoerg   // buffer. (It may not actually be the strlen if the destination buffer
17517330f729Sjoerg   // is not terminated.)
17527330f729Sjoerg   SVal finalStrLength = UnknownVal();
1753*e038c9c4Sjoerg   SVal strlRetVal = UnknownVal();
1754*e038c9c4Sjoerg 
1755*e038c9c4Sjoerg   if (appendK == ConcatFnKind::none && !returnPtr) {
1756*e038c9c4Sjoerg     // strlcpy returns the sizeof(src)
1757*e038c9c4Sjoerg     strlRetVal = strLength;
1758*e038c9c4Sjoerg   }
17597330f729Sjoerg 
17607330f729Sjoerg   // If this is an appending function (strcat, strncat...) then set the
17617330f729Sjoerg   // string length to strlen(src) + strlen(dst) since the buffer will
17627330f729Sjoerg   // ultimately contain both.
1763*e038c9c4Sjoerg   if (appendK != ConcatFnKind::none) {
17647330f729Sjoerg     // Get the string length of the destination. If the destination is memory
17657330f729Sjoerg     // that can't have a string length, we shouldn't be copying into it anyway.
17667330f729Sjoerg     if (dstStrLength.isUndef())
17677330f729Sjoerg       return;
17687330f729Sjoerg 
1769*e038c9c4Sjoerg     if (appendK == ConcatFnKind::strlcat && dstStrLengthNL && strLengthNL) {
1770*e038c9c4Sjoerg       strlRetVal = svalBuilder.evalBinOpNN(state, BO_Add, *strLengthNL,
1771*e038c9c4Sjoerg                                            *dstStrLengthNL, sizeTy);
1772*e038c9c4Sjoerg     }
1773*e038c9c4Sjoerg 
1774*e038c9c4Sjoerg     Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>();
17757330f729Sjoerg 
17767330f729Sjoerg     // If we know both string lengths, we might know the final string length.
1777*e038c9c4Sjoerg     if (amountCopiedNL && dstStrLengthNL) {
17787330f729Sjoerg       // Make sure the two lengths together don't overflow a size_t.
1779*e038c9c4Sjoerg       state = checkAdditionOverflow(C, state, *amountCopiedNL, *dstStrLengthNL);
17807330f729Sjoerg       if (!state)
17817330f729Sjoerg         return;
17827330f729Sjoerg 
1783*e038c9c4Sjoerg       finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *amountCopiedNL,
17847330f729Sjoerg                                                *dstStrLengthNL, sizeTy);
17857330f729Sjoerg     }
17867330f729Sjoerg 
17877330f729Sjoerg     // If we couldn't get a single value for the final string length,
17887330f729Sjoerg     // we can at least bound it by the individual lengths.
17897330f729Sjoerg     if (finalStrLength.isUnknown()) {
17907330f729Sjoerg       // Try to get a "hypothetical" string length symbol, which we can later
17917330f729Sjoerg       // set as a real value if that turns out to be the case.
17927330f729Sjoerg       finalStrLength = getCStringLength(C, state, CE, DstVal, true);
17937330f729Sjoerg       assert(!finalStrLength.isUndef());
17947330f729Sjoerg 
17957330f729Sjoerg       if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
1796*e038c9c4Sjoerg         if (amountCopiedNL && appendK == ConcatFnKind::none) {
1797*e038c9c4Sjoerg           // we overwrite dst string with the src
17987330f729Sjoerg           // finalStrLength >= srcStrLength
1799*e038c9c4Sjoerg           SVal sourceInResult = svalBuilder.evalBinOpNN(
1800*e038c9c4Sjoerg               state, BO_GE, *finalStrLengthNL, *amountCopiedNL, cmpTy);
18017330f729Sjoerg           state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
18027330f729Sjoerg                                 true);
18037330f729Sjoerg           if (!state)
18047330f729Sjoerg             return;
18057330f729Sjoerg         }
18067330f729Sjoerg 
1807*e038c9c4Sjoerg         if (dstStrLengthNL && appendK != ConcatFnKind::none) {
1808*e038c9c4Sjoerg           // we extend the dst string with the src
18097330f729Sjoerg           // finalStrLength >= dstStrLength
18107330f729Sjoerg           SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
18117330f729Sjoerg                                                       *finalStrLengthNL,
18127330f729Sjoerg                                                       *dstStrLengthNL,
18137330f729Sjoerg                                                       cmpTy);
18147330f729Sjoerg           state =
18157330f729Sjoerg               state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
18167330f729Sjoerg           if (!state)
18177330f729Sjoerg             return;
18187330f729Sjoerg         }
18197330f729Sjoerg       }
18207330f729Sjoerg     }
18217330f729Sjoerg 
18227330f729Sjoerg   } else {
18237330f729Sjoerg     // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
18247330f729Sjoerg     // the final string length will match the input string length.
18257330f729Sjoerg     finalStrLength = amountCopied;
18267330f729Sjoerg   }
18277330f729Sjoerg 
18287330f729Sjoerg   SVal Result;
18297330f729Sjoerg 
18307330f729Sjoerg   if (returnPtr) {
18317330f729Sjoerg     // The final result of the function will either be a pointer past the last
18327330f729Sjoerg     // copied element, or a pointer to the start of the destination buffer.
1833*e038c9c4Sjoerg     Result = (ReturnEnd ? UnknownVal() : DstVal);
18347330f729Sjoerg   } else {
1835*e038c9c4Sjoerg     if (appendK == ConcatFnKind::strlcat || appendK == ConcatFnKind::none)
1836*e038c9c4Sjoerg       //strlcpy, strlcat
1837*e038c9c4Sjoerg       Result = strlRetVal;
1838*e038c9c4Sjoerg     else
18397330f729Sjoerg       Result = finalStrLength;
18407330f729Sjoerg   }
18417330f729Sjoerg 
18427330f729Sjoerg   assert(state);
18437330f729Sjoerg 
18447330f729Sjoerg   // If the destination is a MemRegion, try to check for a buffer overflow and
18457330f729Sjoerg   // record the new string length.
18467330f729Sjoerg   if (Optional<loc::MemRegionVal> dstRegVal =
18477330f729Sjoerg       DstVal.getAs<loc::MemRegionVal>()) {
1848*e038c9c4Sjoerg     QualType ptrTy = Dst.Expression->getType();
18497330f729Sjoerg 
18507330f729Sjoerg     // If we have an exact value on a bounded copy, use that to check for
18517330f729Sjoerg     // overflows, rather than our estimate about how much is actually copied.
18527330f729Sjoerg     if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
1853*e038c9c4Sjoerg       SVal maxLastElement =
1854*e038c9c4Sjoerg           svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal, *maxLastNL, ptrTy);
1855*e038c9c4Sjoerg 
1856*e038c9c4Sjoerg       state = CheckLocation(C, state, Dst, maxLastElement, AccessKind::write);
18577330f729Sjoerg       if (!state)
18587330f729Sjoerg         return;
18597330f729Sjoerg     }
18607330f729Sjoerg 
18617330f729Sjoerg     // Then, if the final length is known...
18627330f729Sjoerg     if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
18637330f729Sjoerg       SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
18647330f729Sjoerg           *knownStrLength, ptrTy);
18657330f729Sjoerg 
18667330f729Sjoerg       // ...and we haven't checked the bound, we'll check the actual copy.
18677330f729Sjoerg       if (!boundWarning) {
1868*e038c9c4Sjoerg         state = CheckLocation(C, state, Dst, lastElement, AccessKind::write);
18697330f729Sjoerg         if (!state)
18707330f729Sjoerg           return;
18717330f729Sjoerg       }
18727330f729Sjoerg 
18737330f729Sjoerg       // If this is a stpcpy-style copy, the last element is the return value.
1874*e038c9c4Sjoerg       if (returnPtr && ReturnEnd)
18757330f729Sjoerg         Result = lastElement;
18767330f729Sjoerg     }
18777330f729Sjoerg 
18787330f729Sjoerg     // Invalidate the destination (regular invalidation without pointer-escaping
18797330f729Sjoerg     // the address of the top-level region). This must happen before we set the
18807330f729Sjoerg     // C string length because invalidation will clear the length.
18817330f729Sjoerg     // FIXME: Even if we can't perfectly model the copy, we should see if we
18827330f729Sjoerg     // can use LazyCompoundVals to copy the source values into the destination.
18837330f729Sjoerg     // This would probably remove any existing bindings past the end of the
18847330f729Sjoerg     // string, but that's still an improvement over blank invalidation.
1885*e038c9c4Sjoerg     state = InvalidateBuffer(C, state, Dst.Expression, *dstRegVal,
18867330f729Sjoerg                              /*IsSourceBuffer*/ false, nullptr);
18877330f729Sjoerg 
18887330f729Sjoerg     // Invalidate the source (const-invalidation without const-pointer-escaping
18897330f729Sjoerg     // the address of the top-level region).
1890*e038c9c4Sjoerg     state = InvalidateBuffer(C, state, srcExpr.Expression, srcVal,
1891*e038c9c4Sjoerg                              /*IsSourceBuffer*/ true, nullptr);
18927330f729Sjoerg 
18937330f729Sjoerg     // Set the C string length of the destination, if we know it.
1894*e038c9c4Sjoerg     if (IsBounded && (appendK == ConcatFnKind::none)) {
18957330f729Sjoerg       // strncpy is annoying in that it doesn't guarantee to null-terminate
18967330f729Sjoerg       // the result string. If the original string didn't fit entirely inside
18977330f729Sjoerg       // the bound (including the null-terminator), we don't know how long the
18987330f729Sjoerg       // result is.
18997330f729Sjoerg       if (amountCopied != strLength)
19007330f729Sjoerg         finalStrLength = UnknownVal();
19017330f729Sjoerg     }
19027330f729Sjoerg     state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
19037330f729Sjoerg   }
19047330f729Sjoerg 
19057330f729Sjoerg   assert(state);
19067330f729Sjoerg 
19077330f729Sjoerg   if (returnPtr) {
19087330f729Sjoerg     // If this is a stpcpy-style copy, but we were unable to check for a buffer
19097330f729Sjoerg     // overflow, we still need a result. Conjure a return value.
1910*e038c9c4Sjoerg     if (ReturnEnd && Result.isUnknown()) {
19117330f729Sjoerg       Result = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
19127330f729Sjoerg     }
19137330f729Sjoerg   }
19147330f729Sjoerg   // Set the return value.
19157330f729Sjoerg   state = state->BindExpr(CE, LCtx, Result);
19167330f729Sjoerg   C.addTransition(state);
19177330f729Sjoerg }
19187330f729Sjoerg 
evalStrcmp(CheckerContext & C,const CallExpr * CE) const19197330f729Sjoerg void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
19207330f729Sjoerg   //int strcmp(const char *s1, const char *s2);
1921*e038c9c4Sjoerg   evalStrcmpCommon(C, CE, /* IsBounded = */ false, /* IgnoreCase = */ false);
19227330f729Sjoerg }
19237330f729Sjoerg 
evalStrncmp(CheckerContext & C,const CallExpr * CE) const19247330f729Sjoerg void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
19257330f729Sjoerg   //int strncmp(const char *s1, const char *s2, size_t n);
1926*e038c9c4Sjoerg   evalStrcmpCommon(C, CE, /* IsBounded = */ true, /* IgnoreCase = */ false);
19277330f729Sjoerg }
19287330f729Sjoerg 
evalStrcasecmp(CheckerContext & C,const CallExpr * CE) const19297330f729Sjoerg void CStringChecker::evalStrcasecmp(CheckerContext &C,
19307330f729Sjoerg     const CallExpr *CE) const {
19317330f729Sjoerg   //int strcasecmp(const char *s1, const char *s2);
1932*e038c9c4Sjoerg   evalStrcmpCommon(C, CE, /* IsBounded = */ false, /* IgnoreCase = */ true);
19337330f729Sjoerg }
19347330f729Sjoerg 
evalStrncasecmp(CheckerContext & C,const CallExpr * CE) const19357330f729Sjoerg void CStringChecker::evalStrncasecmp(CheckerContext &C,
19367330f729Sjoerg     const CallExpr *CE) const {
19377330f729Sjoerg   //int strncasecmp(const char *s1, const char *s2, size_t n);
1938*e038c9c4Sjoerg   evalStrcmpCommon(C, CE, /* IsBounded = */ true, /* IgnoreCase = */ true);
19397330f729Sjoerg }
19407330f729Sjoerg 
evalStrcmpCommon(CheckerContext & C,const CallExpr * CE,bool IsBounded,bool IgnoreCase) const19417330f729Sjoerg void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
1942*e038c9c4Sjoerg     bool IsBounded, bool IgnoreCase) const {
19437330f729Sjoerg   CurrentFunctionDescription = "string comparison function";
19447330f729Sjoerg   ProgramStateRef state = C.getState();
19457330f729Sjoerg   const LocationContext *LCtx = C.getLocationContext();
19467330f729Sjoerg 
19477330f729Sjoerg   // Check that the first string is non-null
1948*e038c9c4Sjoerg   AnyArgExpr Left = {CE->getArg(0), 0};
1949*e038c9c4Sjoerg   SVal LeftVal = state->getSVal(Left.Expression, LCtx);
1950*e038c9c4Sjoerg   state = checkNonNull(C, state, Left, LeftVal);
19517330f729Sjoerg   if (!state)
19527330f729Sjoerg     return;
19537330f729Sjoerg 
19547330f729Sjoerg   // Check that the second string is non-null.
1955*e038c9c4Sjoerg   AnyArgExpr Right = {CE->getArg(1), 1};
1956*e038c9c4Sjoerg   SVal RightVal = state->getSVal(Right.Expression, LCtx);
1957*e038c9c4Sjoerg   state = checkNonNull(C, state, Right, RightVal);
19587330f729Sjoerg   if (!state)
19597330f729Sjoerg     return;
19607330f729Sjoerg 
19617330f729Sjoerg   // Get the string length of the first string or give up.
1962*e038c9c4Sjoerg   SVal LeftLength = getCStringLength(C, state, Left.Expression, LeftVal);
1963*e038c9c4Sjoerg   if (LeftLength.isUndef())
19647330f729Sjoerg     return;
19657330f729Sjoerg 
19667330f729Sjoerg   // Get the string length of the second string or give up.
1967*e038c9c4Sjoerg   SVal RightLength = getCStringLength(C, state, Right.Expression, RightVal);
1968*e038c9c4Sjoerg   if (RightLength.isUndef())
19697330f729Sjoerg     return;
19707330f729Sjoerg 
19717330f729Sjoerg   // If we know the two buffers are the same, we know the result is 0.
19727330f729Sjoerg   // First, get the two buffers' addresses. Another checker will have already
19737330f729Sjoerg   // made sure they're not undefined.
1974*e038c9c4Sjoerg   DefinedOrUnknownSVal LV = LeftVal.castAs<DefinedOrUnknownSVal>();
1975*e038c9c4Sjoerg   DefinedOrUnknownSVal RV = RightVal.castAs<DefinedOrUnknownSVal>();
19767330f729Sjoerg 
19777330f729Sjoerg   // See if they are the same.
19787330f729Sjoerg   SValBuilder &svalBuilder = C.getSValBuilder();
19797330f729Sjoerg   DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
19807330f729Sjoerg   ProgramStateRef StSameBuf, StNotSameBuf;
19817330f729Sjoerg   std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
19827330f729Sjoerg 
19837330f729Sjoerg   // If the two arguments might be the same buffer, we know the result is 0,
19847330f729Sjoerg   // and we only need to check one size.
19857330f729Sjoerg   if (StSameBuf) {
19867330f729Sjoerg     StSameBuf = StSameBuf->BindExpr(CE, LCtx,
19877330f729Sjoerg         svalBuilder.makeZeroVal(CE->getType()));
19887330f729Sjoerg     C.addTransition(StSameBuf);
19897330f729Sjoerg 
19907330f729Sjoerg     // If the two arguments are GUARANTEED to be the same, we're done!
19917330f729Sjoerg     if (!StNotSameBuf)
19927330f729Sjoerg       return;
19937330f729Sjoerg   }
19947330f729Sjoerg 
19957330f729Sjoerg   assert(StNotSameBuf);
19967330f729Sjoerg   state = StNotSameBuf;
19977330f729Sjoerg 
19987330f729Sjoerg   // At this point we can go about comparing the two buffers.
19997330f729Sjoerg   // For now, we only do this if they're both known string literals.
20007330f729Sjoerg 
20017330f729Sjoerg   // Attempt to extract string literals from both expressions.
2002*e038c9c4Sjoerg   const StringLiteral *LeftStrLiteral =
2003*e038c9c4Sjoerg       getCStringLiteral(C, state, Left.Expression, LeftVal);
2004*e038c9c4Sjoerg   const StringLiteral *RightStrLiteral =
2005*e038c9c4Sjoerg       getCStringLiteral(C, state, Right.Expression, RightVal);
20067330f729Sjoerg   bool canComputeResult = false;
20077330f729Sjoerg   SVal resultVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
20087330f729Sjoerg       C.blockCount());
20097330f729Sjoerg 
2010*e038c9c4Sjoerg   if (LeftStrLiteral && RightStrLiteral) {
2011*e038c9c4Sjoerg     StringRef LeftStrRef = LeftStrLiteral->getString();
2012*e038c9c4Sjoerg     StringRef RightStrRef = RightStrLiteral->getString();
20137330f729Sjoerg 
2014*e038c9c4Sjoerg     if (IsBounded) {
20157330f729Sjoerg       // Get the max number of characters to compare.
20167330f729Sjoerg       const Expr *lenExpr = CE->getArg(2);
20177330f729Sjoerg       SVal lenVal = state->getSVal(lenExpr, LCtx);
20187330f729Sjoerg 
20197330f729Sjoerg       // If the length is known, we can get the right substrings.
20207330f729Sjoerg       if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
20217330f729Sjoerg         // Create substrings of each to compare the prefix.
2022*e038c9c4Sjoerg         LeftStrRef = LeftStrRef.substr(0, (size_t)len->getZExtValue());
2023*e038c9c4Sjoerg         RightStrRef = RightStrRef.substr(0, (size_t)len->getZExtValue());
20247330f729Sjoerg         canComputeResult = true;
20257330f729Sjoerg       }
20267330f729Sjoerg     } else {
20277330f729Sjoerg       // This is a normal, unbounded strcmp.
20287330f729Sjoerg       canComputeResult = true;
20297330f729Sjoerg     }
20307330f729Sjoerg 
20317330f729Sjoerg     if (canComputeResult) {
20327330f729Sjoerg       // Real strcmp stops at null characters.
2033*e038c9c4Sjoerg       size_t s1Term = LeftStrRef.find('\0');
20347330f729Sjoerg       if (s1Term != StringRef::npos)
2035*e038c9c4Sjoerg         LeftStrRef = LeftStrRef.substr(0, s1Term);
20367330f729Sjoerg 
2037*e038c9c4Sjoerg       size_t s2Term = RightStrRef.find('\0');
20387330f729Sjoerg       if (s2Term != StringRef::npos)
2039*e038c9c4Sjoerg         RightStrRef = RightStrRef.substr(0, s2Term);
20407330f729Sjoerg 
20417330f729Sjoerg       // Use StringRef's comparison methods to compute the actual result.
2042*e038c9c4Sjoerg       int compareRes = IgnoreCase ? LeftStrRef.compare_lower(RightStrRef)
2043*e038c9c4Sjoerg                                   : LeftStrRef.compare(RightStrRef);
20447330f729Sjoerg 
20457330f729Sjoerg       // The strcmp function returns an integer greater than, equal to, or less
20467330f729Sjoerg       // than zero, [c11, p7.24.4.2].
20477330f729Sjoerg       if (compareRes == 0) {
20487330f729Sjoerg         resultVal = svalBuilder.makeIntVal(compareRes, CE->getType());
20497330f729Sjoerg       }
20507330f729Sjoerg       else {
20517330f729Sjoerg         DefinedSVal zeroVal = svalBuilder.makeIntVal(0, CE->getType());
20527330f729Sjoerg         // Constrain strcmp's result range based on the result of StringRef's
20537330f729Sjoerg         // comparison methods.
20547330f729Sjoerg         BinaryOperatorKind op = (compareRes == 1) ? BO_GT : BO_LT;
20557330f729Sjoerg         SVal compareWithZero =
20567330f729Sjoerg           svalBuilder.evalBinOp(state, op, resultVal, zeroVal,
20577330f729Sjoerg               svalBuilder.getConditionType());
20587330f729Sjoerg         DefinedSVal compareWithZeroVal = compareWithZero.castAs<DefinedSVal>();
20597330f729Sjoerg         state = state->assume(compareWithZeroVal, true);
20607330f729Sjoerg       }
20617330f729Sjoerg     }
20627330f729Sjoerg   }
20637330f729Sjoerg 
20647330f729Sjoerg   state = state->BindExpr(CE, LCtx, resultVal);
20657330f729Sjoerg 
20667330f729Sjoerg   // Record this as a possible path.
20677330f729Sjoerg   C.addTransition(state);
20687330f729Sjoerg }
20697330f729Sjoerg 
evalStrsep(CheckerContext & C,const CallExpr * CE) const20707330f729Sjoerg void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
20717330f729Sjoerg   //char *strsep(char **stringp, const char *delim);
20727330f729Sjoerg   // Sanity: does the search string parameter match the return type?
2073*e038c9c4Sjoerg   SourceArgExpr SearchStrPtr = {CE->getArg(0), 0};
2074*e038c9c4Sjoerg 
2075*e038c9c4Sjoerg   QualType CharPtrTy = SearchStrPtr.Expression->getType()->getPointeeType();
20767330f729Sjoerg   if (CharPtrTy.isNull() ||
20777330f729Sjoerg       CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
20787330f729Sjoerg     return;
20797330f729Sjoerg 
20807330f729Sjoerg   CurrentFunctionDescription = "strsep()";
20817330f729Sjoerg   ProgramStateRef State = C.getState();
20827330f729Sjoerg   const LocationContext *LCtx = C.getLocationContext();
20837330f729Sjoerg 
20847330f729Sjoerg   // Check that the search string pointer is non-null (though it may point to
20857330f729Sjoerg   // a null string).
2086*e038c9c4Sjoerg   SVal SearchStrVal = State->getSVal(SearchStrPtr.Expression, LCtx);
2087*e038c9c4Sjoerg   State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
20887330f729Sjoerg   if (!State)
20897330f729Sjoerg     return;
20907330f729Sjoerg 
20917330f729Sjoerg   // Check that the delimiter string is non-null.
2092*e038c9c4Sjoerg   AnyArgExpr DelimStr = {CE->getArg(1), 1};
2093*e038c9c4Sjoerg   SVal DelimStrVal = State->getSVal(DelimStr.Expression, LCtx);
2094*e038c9c4Sjoerg   State = checkNonNull(C, State, DelimStr, DelimStrVal);
20957330f729Sjoerg   if (!State)
20967330f729Sjoerg     return;
20977330f729Sjoerg 
20987330f729Sjoerg   SValBuilder &SVB = C.getSValBuilder();
20997330f729Sjoerg   SVal Result;
21007330f729Sjoerg   if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
21017330f729Sjoerg     // Get the current value of the search string pointer, as a char*.
21027330f729Sjoerg     Result = State->getSVal(*SearchStrLoc, CharPtrTy);
21037330f729Sjoerg 
21047330f729Sjoerg     // Invalidate the search string, representing the change of one delimiter
21057330f729Sjoerg     // character to NUL.
2106*e038c9c4Sjoerg     State = InvalidateBuffer(C, State, SearchStrPtr.Expression, Result,
21077330f729Sjoerg                              /*IsSourceBuffer*/ false, nullptr);
21087330f729Sjoerg 
21097330f729Sjoerg     // Overwrite the search string pointer. The new value is either an address
21107330f729Sjoerg     // further along in the same string, or NULL if there are no more tokens.
21117330f729Sjoerg     State = State->bindLoc(*SearchStrLoc,
21127330f729Sjoerg         SVB.conjureSymbolVal(getTag(),
21137330f729Sjoerg           CE,
21147330f729Sjoerg           LCtx,
21157330f729Sjoerg           CharPtrTy,
21167330f729Sjoerg           C.blockCount()),
21177330f729Sjoerg         LCtx);
21187330f729Sjoerg   } else {
21197330f729Sjoerg     assert(SearchStrVal.isUnknown());
21207330f729Sjoerg     // Conjure a symbolic value. It's the best we can do.
21217330f729Sjoerg     Result = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
21227330f729Sjoerg   }
21237330f729Sjoerg 
21247330f729Sjoerg   // Set the return value, and finish.
21257330f729Sjoerg   State = State->BindExpr(CE, LCtx, Result);
21267330f729Sjoerg   C.addTransition(State);
21277330f729Sjoerg }
21287330f729Sjoerg 
21297330f729Sjoerg // These should probably be moved into a C++ standard library checker.
evalStdCopy(CheckerContext & C,const CallExpr * CE) const21307330f729Sjoerg void CStringChecker::evalStdCopy(CheckerContext &C, const CallExpr *CE) const {
21317330f729Sjoerg   evalStdCopyCommon(C, CE);
21327330f729Sjoerg }
21337330f729Sjoerg 
evalStdCopyBackward(CheckerContext & C,const CallExpr * CE) const21347330f729Sjoerg void CStringChecker::evalStdCopyBackward(CheckerContext &C,
21357330f729Sjoerg     const CallExpr *CE) const {
21367330f729Sjoerg   evalStdCopyCommon(C, CE);
21377330f729Sjoerg }
21387330f729Sjoerg 
evalStdCopyCommon(CheckerContext & C,const CallExpr * CE) const21397330f729Sjoerg void CStringChecker::evalStdCopyCommon(CheckerContext &C,
21407330f729Sjoerg     const CallExpr *CE) const {
21417330f729Sjoerg   if (!CE->getArg(2)->getType()->isPointerType())
21427330f729Sjoerg     return;
21437330f729Sjoerg 
21447330f729Sjoerg   ProgramStateRef State = C.getState();
21457330f729Sjoerg 
21467330f729Sjoerg   const LocationContext *LCtx = C.getLocationContext();
21477330f729Sjoerg 
21487330f729Sjoerg   // template <class _InputIterator, class _OutputIterator>
21497330f729Sjoerg   // _OutputIterator
21507330f729Sjoerg   // copy(_InputIterator __first, _InputIterator __last,
21517330f729Sjoerg   //        _OutputIterator __result)
21527330f729Sjoerg 
21537330f729Sjoerg   // Invalidate the destination buffer
21547330f729Sjoerg   const Expr *Dst = CE->getArg(2);
21557330f729Sjoerg   SVal DstVal = State->getSVal(Dst, LCtx);
21567330f729Sjoerg   State = InvalidateBuffer(C, State, Dst, DstVal, /*IsSource=*/false,
21577330f729Sjoerg       /*Size=*/nullptr);
21587330f729Sjoerg 
21597330f729Sjoerg   SValBuilder &SVB = C.getSValBuilder();
21607330f729Sjoerg 
21617330f729Sjoerg   SVal ResultVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
21627330f729Sjoerg   State = State->BindExpr(CE, LCtx, ResultVal);
21637330f729Sjoerg 
21647330f729Sjoerg   C.addTransition(State);
21657330f729Sjoerg }
21667330f729Sjoerg 
evalMemset(CheckerContext & C,const CallExpr * CE) const21677330f729Sjoerg void CStringChecker::evalMemset(CheckerContext &C, const CallExpr *CE) const {
2168*e038c9c4Sjoerg   // void *memset(void *s, int c, size_t n);
21697330f729Sjoerg   CurrentFunctionDescription = "memory set function";
21707330f729Sjoerg 
2171*e038c9c4Sjoerg   DestinationArgExpr Buffer = {CE->getArg(0), 0};
2172*e038c9c4Sjoerg   AnyArgExpr CharE = {CE->getArg(1), 1};
2173*e038c9c4Sjoerg   SizeArgExpr Size = {CE->getArg(2), 2};
2174*e038c9c4Sjoerg 
21757330f729Sjoerg   ProgramStateRef State = C.getState();
21767330f729Sjoerg 
21777330f729Sjoerg   // See if the size argument is zero.
21787330f729Sjoerg   const LocationContext *LCtx = C.getLocationContext();
2179*e038c9c4Sjoerg   SVal SizeVal = C.getSVal(Size.Expression);
2180*e038c9c4Sjoerg   QualType SizeTy = Size.Expression->getType();
21817330f729Sjoerg 
2182*e038c9c4Sjoerg   ProgramStateRef ZeroSize, NonZeroSize;
2183*e038c9c4Sjoerg   std::tie(ZeroSize, NonZeroSize) = assumeZero(C, State, SizeVal, SizeTy);
21847330f729Sjoerg 
21857330f729Sjoerg   // Get the value of the memory area.
2186*e038c9c4Sjoerg   SVal BufferPtrVal = C.getSVal(Buffer.Expression);
21877330f729Sjoerg 
21887330f729Sjoerg   // If the size is zero, there won't be any actual memory access, so
2189*e038c9c4Sjoerg   // just bind the return value to the buffer and return.
2190*e038c9c4Sjoerg   if (ZeroSize && !NonZeroSize) {
2191*e038c9c4Sjoerg     ZeroSize = ZeroSize->BindExpr(CE, LCtx, BufferPtrVal);
2192*e038c9c4Sjoerg     C.addTransition(ZeroSize);
21937330f729Sjoerg     return;
21947330f729Sjoerg   }
21957330f729Sjoerg 
21967330f729Sjoerg   // Ensure the memory area is not null.
21977330f729Sjoerg   // If it is NULL there will be a NULL pointer dereference.
2198*e038c9c4Sjoerg   State = checkNonNull(C, NonZeroSize, Buffer, BufferPtrVal);
21997330f729Sjoerg   if (!State)
22007330f729Sjoerg     return;
22017330f729Sjoerg 
2202*e038c9c4Sjoerg   State = CheckBufferAccess(C, State, Buffer, Size, AccessKind::write);
22037330f729Sjoerg   if (!State)
22047330f729Sjoerg     return;
22057330f729Sjoerg 
22067330f729Sjoerg   // According to the values of the arguments, bind the value of the second
22077330f729Sjoerg   // argument to the destination buffer and set string length, or just
22087330f729Sjoerg   // invalidate the destination buffer.
2209*e038c9c4Sjoerg   if (!memsetAux(Buffer.Expression, C.getSVal(CharE.Expression),
2210*e038c9c4Sjoerg                  Size.Expression, C, State))
22117330f729Sjoerg     return;
22127330f729Sjoerg 
2213*e038c9c4Sjoerg   State = State->BindExpr(CE, LCtx, BufferPtrVal);
22147330f729Sjoerg   C.addTransition(State);
22157330f729Sjoerg }
22167330f729Sjoerg 
evalBzero(CheckerContext & C,const CallExpr * CE) const22177330f729Sjoerg void CStringChecker::evalBzero(CheckerContext &C, const CallExpr *CE) const {
22187330f729Sjoerg   CurrentFunctionDescription = "memory clearance function";
22197330f729Sjoerg 
2220*e038c9c4Sjoerg   DestinationArgExpr Buffer = {CE->getArg(0), 0};
2221*e038c9c4Sjoerg   SizeArgExpr Size = {CE->getArg(1), 1};
22227330f729Sjoerg   SVal Zero = C.getSValBuilder().makeZeroVal(C.getASTContext().IntTy);
22237330f729Sjoerg 
22247330f729Sjoerg   ProgramStateRef State = C.getState();
22257330f729Sjoerg 
22267330f729Sjoerg   // See if the size argument is zero.
2227*e038c9c4Sjoerg   SVal SizeVal = C.getSVal(Size.Expression);
2228*e038c9c4Sjoerg   QualType SizeTy = Size.Expression->getType();
22297330f729Sjoerg 
22307330f729Sjoerg   ProgramStateRef StateZeroSize, StateNonZeroSize;
22317330f729Sjoerg   std::tie(StateZeroSize, StateNonZeroSize) =
22327330f729Sjoerg     assumeZero(C, State, SizeVal, SizeTy);
22337330f729Sjoerg 
22347330f729Sjoerg   // If the size is zero, there won't be any actual memory access,
22357330f729Sjoerg   // In this case we just return.
22367330f729Sjoerg   if (StateZeroSize && !StateNonZeroSize) {
22377330f729Sjoerg     C.addTransition(StateZeroSize);
22387330f729Sjoerg     return;
22397330f729Sjoerg   }
22407330f729Sjoerg 
22417330f729Sjoerg   // Get the value of the memory area.
2242*e038c9c4Sjoerg   SVal MemVal = C.getSVal(Buffer.Expression);
22437330f729Sjoerg 
22447330f729Sjoerg   // Ensure the memory area is not null.
22457330f729Sjoerg   // If it is NULL there will be a NULL pointer dereference.
2246*e038c9c4Sjoerg   State = checkNonNull(C, StateNonZeroSize, Buffer, MemVal);
22477330f729Sjoerg   if (!State)
22487330f729Sjoerg     return;
22497330f729Sjoerg 
2250*e038c9c4Sjoerg   State = CheckBufferAccess(C, State, Buffer, Size, AccessKind::write);
22517330f729Sjoerg   if (!State)
22527330f729Sjoerg     return;
22537330f729Sjoerg 
2254*e038c9c4Sjoerg   if (!memsetAux(Buffer.Expression, Zero, Size.Expression, C, State))
22557330f729Sjoerg     return;
22567330f729Sjoerg 
22577330f729Sjoerg   C.addTransition(State);
22587330f729Sjoerg }
22597330f729Sjoerg 
22607330f729Sjoerg //===----------------------------------------------------------------------===//
22617330f729Sjoerg // The driver method, and other Checker callbacks.
22627330f729Sjoerg //===----------------------------------------------------------------------===//
22637330f729Sjoerg 
identifyCall(const CallEvent & Call,CheckerContext & C) const22647330f729Sjoerg CStringChecker::FnCheck CStringChecker::identifyCall(const CallEvent &Call,
22657330f729Sjoerg                                                      CheckerContext &C) const {
22667330f729Sjoerg   const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
22677330f729Sjoerg   if (!CE)
22687330f729Sjoerg     return nullptr;
22697330f729Sjoerg 
22707330f729Sjoerg   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
22717330f729Sjoerg   if (!FD)
22727330f729Sjoerg     return nullptr;
22737330f729Sjoerg 
22747330f729Sjoerg   if (Call.isCalled(StdCopy)) {
22757330f729Sjoerg     return &CStringChecker::evalStdCopy;
22767330f729Sjoerg   } else if (Call.isCalled(StdCopyBackward)) {
22777330f729Sjoerg     return &CStringChecker::evalStdCopyBackward;
22787330f729Sjoerg   }
22797330f729Sjoerg 
22807330f729Sjoerg   // Pro-actively check that argument types are safe to do arithmetic upon.
22817330f729Sjoerg   // We do not want to crash if someone accidentally passes a structure
22827330f729Sjoerg   // into, say, a C++ overload of any of these functions. We could not check
22837330f729Sjoerg   // that for std::copy because they may have arguments of other types.
22847330f729Sjoerg   for (auto I : CE->arguments()) {
22857330f729Sjoerg     QualType T = I->getType();
22867330f729Sjoerg     if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
22877330f729Sjoerg       return nullptr;
22887330f729Sjoerg   }
22897330f729Sjoerg 
22907330f729Sjoerg   const FnCheck *Callback = Callbacks.lookup(Call);
22917330f729Sjoerg   if (Callback)
22927330f729Sjoerg     return *Callback;
22937330f729Sjoerg 
22947330f729Sjoerg   return nullptr;
22957330f729Sjoerg }
22967330f729Sjoerg 
evalCall(const CallEvent & Call,CheckerContext & C) const22977330f729Sjoerg bool CStringChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
22987330f729Sjoerg   FnCheck Callback = identifyCall(Call, C);
22997330f729Sjoerg 
23007330f729Sjoerg   // If the callee isn't a string function, let another checker handle it.
23017330f729Sjoerg   if (!Callback)
23027330f729Sjoerg     return false;
23037330f729Sjoerg 
23047330f729Sjoerg   // Check and evaluate the call.
23057330f729Sjoerg   const auto *CE = cast<CallExpr>(Call.getOriginExpr());
23067330f729Sjoerg   (this->*Callback)(C, CE);
23077330f729Sjoerg 
23087330f729Sjoerg   // If the evaluate call resulted in no change, chain to the next eval call
23097330f729Sjoerg   // handler.
23107330f729Sjoerg   // Note, the custom CString evaluation calls assume that basic safety
23117330f729Sjoerg   // properties are held. However, if the user chooses to turn off some of these
23127330f729Sjoerg   // checks, we ignore the issues and leave the call evaluation to a generic
23137330f729Sjoerg   // handler.
23147330f729Sjoerg   return C.isDifferent();
23157330f729Sjoerg }
23167330f729Sjoerg 
checkPreStmt(const DeclStmt * DS,CheckerContext & C) const23177330f729Sjoerg void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
23187330f729Sjoerg   // Record string length for char a[] = "abc";
23197330f729Sjoerg   ProgramStateRef state = C.getState();
23207330f729Sjoerg 
23217330f729Sjoerg   for (const auto *I : DS->decls()) {
23227330f729Sjoerg     const VarDecl *D = dyn_cast<VarDecl>(I);
23237330f729Sjoerg     if (!D)
23247330f729Sjoerg       continue;
23257330f729Sjoerg 
23267330f729Sjoerg     // FIXME: Handle array fields of structs.
23277330f729Sjoerg     if (!D->getType()->isArrayType())
23287330f729Sjoerg       continue;
23297330f729Sjoerg 
23307330f729Sjoerg     const Expr *Init = D->getInit();
23317330f729Sjoerg     if (!Init)
23327330f729Sjoerg       continue;
23337330f729Sjoerg     if (!isa<StringLiteral>(Init))
23347330f729Sjoerg       continue;
23357330f729Sjoerg 
23367330f729Sjoerg     Loc VarLoc = state->getLValue(D, C.getLocationContext());
23377330f729Sjoerg     const MemRegion *MR = VarLoc.getAsRegion();
23387330f729Sjoerg     if (!MR)
23397330f729Sjoerg       continue;
23407330f729Sjoerg 
23417330f729Sjoerg     SVal StrVal = C.getSVal(Init);
23427330f729Sjoerg     assert(StrVal.isValid() && "Initializer string is unknown or undefined");
23437330f729Sjoerg     DefinedOrUnknownSVal strLength =
23447330f729Sjoerg       getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
23457330f729Sjoerg 
23467330f729Sjoerg     state = state->set<CStringLength>(MR, strLength);
23477330f729Sjoerg   }
23487330f729Sjoerg 
23497330f729Sjoerg   C.addTransition(state);
23507330f729Sjoerg }
23517330f729Sjoerg 
23527330f729Sjoerg ProgramStateRef
checkRegionChanges(ProgramStateRef state,const InvalidatedSymbols *,ArrayRef<const MemRegion * > ExplicitRegions,ArrayRef<const MemRegion * > Regions,const LocationContext * LCtx,const CallEvent * Call) const23537330f729Sjoerg CStringChecker::checkRegionChanges(ProgramStateRef state,
23547330f729Sjoerg     const InvalidatedSymbols *,
23557330f729Sjoerg     ArrayRef<const MemRegion *> ExplicitRegions,
23567330f729Sjoerg     ArrayRef<const MemRegion *> Regions,
23577330f729Sjoerg     const LocationContext *LCtx,
23587330f729Sjoerg     const CallEvent *Call) const {
23597330f729Sjoerg   CStringLengthTy Entries = state->get<CStringLength>();
23607330f729Sjoerg   if (Entries.isEmpty())
23617330f729Sjoerg     return state;
23627330f729Sjoerg 
23637330f729Sjoerg   llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
23647330f729Sjoerg   llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
23657330f729Sjoerg 
23667330f729Sjoerg   // First build sets for the changed regions and their super-regions.
23677330f729Sjoerg   for (ArrayRef<const MemRegion *>::iterator
23687330f729Sjoerg       I = Regions.begin(), E = Regions.end(); I != E; ++I) {
23697330f729Sjoerg     const MemRegion *MR = *I;
23707330f729Sjoerg     Invalidated.insert(MR);
23717330f729Sjoerg 
23727330f729Sjoerg     SuperRegions.insert(MR);
23737330f729Sjoerg     while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
23747330f729Sjoerg       MR = SR->getSuperRegion();
23757330f729Sjoerg       SuperRegions.insert(MR);
23767330f729Sjoerg     }
23777330f729Sjoerg   }
23787330f729Sjoerg 
23797330f729Sjoerg   CStringLengthTy::Factory &F = state->get_context<CStringLength>();
23807330f729Sjoerg 
23817330f729Sjoerg   // Then loop over the entries in the current state.
23827330f729Sjoerg   for (CStringLengthTy::iterator I = Entries.begin(),
23837330f729Sjoerg       E = Entries.end(); I != E; ++I) {
23847330f729Sjoerg     const MemRegion *MR = I.getKey();
23857330f729Sjoerg 
23867330f729Sjoerg     // Is this entry for a super-region of a changed region?
23877330f729Sjoerg     if (SuperRegions.count(MR)) {
23887330f729Sjoerg       Entries = F.remove(Entries, MR);
23897330f729Sjoerg       continue;
23907330f729Sjoerg     }
23917330f729Sjoerg 
23927330f729Sjoerg     // Is this entry for a sub-region of a changed region?
23937330f729Sjoerg     const MemRegion *Super = MR;
23947330f729Sjoerg     while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
23957330f729Sjoerg       Super = SR->getSuperRegion();
23967330f729Sjoerg       if (Invalidated.count(Super)) {
23977330f729Sjoerg         Entries = F.remove(Entries, MR);
23987330f729Sjoerg         break;
23997330f729Sjoerg       }
24007330f729Sjoerg     }
24017330f729Sjoerg   }
24027330f729Sjoerg 
24037330f729Sjoerg   return state->set<CStringLength>(Entries);
24047330f729Sjoerg }
24057330f729Sjoerg 
checkLiveSymbols(ProgramStateRef state,SymbolReaper & SR) const24067330f729Sjoerg void CStringChecker::checkLiveSymbols(ProgramStateRef state,
24077330f729Sjoerg     SymbolReaper &SR) const {
24087330f729Sjoerg   // Mark all symbols in our string length map as valid.
24097330f729Sjoerg   CStringLengthTy Entries = state->get<CStringLength>();
24107330f729Sjoerg 
24117330f729Sjoerg   for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
24127330f729Sjoerg       I != E; ++I) {
24137330f729Sjoerg     SVal Len = I.getData();
24147330f729Sjoerg 
24157330f729Sjoerg     for (SymExpr::symbol_iterator si = Len.symbol_begin(),
24167330f729Sjoerg         se = Len.symbol_end(); si != se; ++si)
24177330f729Sjoerg       SR.markInUse(*si);
24187330f729Sjoerg   }
24197330f729Sjoerg }
24207330f729Sjoerg 
checkDeadSymbols(SymbolReaper & SR,CheckerContext & C) const24217330f729Sjoerg void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
24227330f729Sjoerg     CheckerContext &C) const {
24237330f729Sjoerg   ProgramStateRef state = C.getState();
24247330f729Sjoerg   CStringLengthTy Entries = state->get<CStringLength>();
24257330f729Sjoerg   if (Entries.isEmpty())
24267330f729Sjoerg     return;
24277330f729Sjoerg 
24287330f729Sjoerg   CStringLengthTy::Factory &F = state->get_context<CStringLength>();
24297330f729Sjoerg   for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
24307330f729Sjoerg       I != E; ++I) {
24317330f729Sjoerg     SVal Len = I.getData();
24327330f729Sjoerg     if (SymbolRef Sym = Len.getAsSymbol()) {
24337330f729Sjoerg       if (SR.isDead(Sym))
24347330f729Sjoerg         Entries = F.remove(Entries, I.getKey());
24357330f729Sjoerg     }
24367330f729Sjoerg   }
24377330f729Sjoerg 
24387330f729Sjoerg   state = state->set<CStringLength>(Entries);
24397330f729Sjoerg   C.addTransition(state);
24407330f729Sjoerg }
24417330f729Sjoerg 
registerCStringModeling(CheckerManager & Mgr)24427330f729Sjoerg void ento::registerCStringModeling(CheckerManager &Mgr) {
24437330f729Sjoerg   Mgr.registerChecker<CStringChecker>();
24447330f729Sjoerg }
24457330f729Sjoerg 
shouldRegisterCStringModeling(const CheckerManager & mgr)2446*e038c9c4Sjoerg bool ento::shouldRegisterCStringModeling(const CheckerManager &mgr) {
24477330f729Sjoerg   return true;
24487330f729Sjoerg }
24497330f729Sjoerg 
24507330f729Sjoerg #define REGISTER_CHECKER(name)                                                 \
24517330f729Sjoerg   void ento::register##name(CheckerManager &mgr) {                             \
24527330f729Sjoerg     CStringChecker *checker = mgr.getChecker<CStringChecker>();                \
24537330f729Sjoerg     checker->Filter.Check##name = true;                                        \
24547330f729Sjoerg     checker->Filter.CheckName##name = mgr.getCurrentCheckerName();             \
24557330f729Sjoerg   }                                                                            \
24567330f729Sjoerg                                                                                \
2457*e038c9c4Sjoerg   bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
24587330f729Sjoerg 
24597330f729Sjoerg REGISTER_CHECKER(CStringNullArg)
24607330f729Sjoerg REGISTER_CHECKER(CStringOutOfBounds)
24617330f729Sjoerg REGISTER_CHECKER(CStringBufferOverlap)
24627330f729Sjoerg REGISTER_CHECKER(CStringNotNullTerm)
2463