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