xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp (revision 5066858bcd0b3f264fee42faba2f4ce6f85cb911)
1 //= CStringChecker.h - Checks calls to C string functions ----------*- C++ -*-//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This defines CStringChecker, which is an assortment of checks on calls
11 // to functions in <string.h>.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ClangSACheckers.h"
16 #include "clang/StaticAnalyzer/Core/Checker.h"
17 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h"
21 #include "llvm/ADT/StringSwitch.h"
22 
23 using namespace clang;
24 using namespace ento;
25 
26 namespace {
27 class CStringChecker : public Checker< eval::Call,
28                                          check::PreStmt<DeclStmt>,
29                                          check::LiveSymbols,
30                                          check::DeadSymbols,
31                                          check::RegionChanges
32                                          > {
33   mutable llvm::OwningPtr<BugType> BT_Null, BT_Bounds, BT_BoundsWrite,
34                                    BT_Overlap, BT_NotCString;
35 public:
36   static void *getTag() { static int tag; return &tag; }
37 
38   bool evalCall(const CallExpr *CE, CheckerContext &C) const;
39   void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
40   void checkLiveSymbols(const GRState *state, SymbolReaper &SR) const;
41   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
42   bool wantsRegionChangeUpdate(const GRState *state) const;
43 
44   const GRState *checkRegionChanges(const GRState *state,
45                                     const StoreManager::InvalidatedSymbols *,
46                                     const MemRegion * const *Begin,
47                                     const MemRegion * const *End) const;
48 
49   typedef void (CStringChecker::*FnCheck)(CheckerContext &,
50                                           const CallExpr *) const;
51 
52   void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
53   void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
54   void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
55   void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
56   void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
57                       const GRState *state,
58                       const Expr *Size, const Expr *Source, const Expr *Dest,
59                       bool Restricted = false,
60                       bool IsMempcpy = false) const;
61 
62   void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
63 
64   void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
65   void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
66   void evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
67                            bool IsStrnlen = false) const;
68 
69   void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
70   void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
71   void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
72   void evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, bool returnEnd,
73                         bool isBounded, bool isAppending) const;
74 
75   void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
76   void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
77 
78   void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
79   void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
80   void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
81   void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
82   void evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
83                         bool isBounded = false, bool ignoreCase = false) const;
84 
85   // Utility methods
86   std::pair<const GRState*, const GRState*>
87   static assumeZero(CheckerContext &C,
88                     const GRState *state, SVal V, QualType Ty);
89 
90   static const GRState *setCStringLength(const GRState *state,
91                                          const MemRegion *MR, SVal strLength);
92   static SVal getCStringLengthForRegion(CheckerContext &C,
93                                         const GRState *&state,
94                                         const Expr *Ex, const MemRegion *MR);
95   SVal getCStringLength(CheckerContext &C, const GRState *&state,
96                         const Expr *Ex, SVal Buf) const;
97 
98   const StringLiteral *getCStringLiteral(CheckerContext &C,
99                                          const GRState *&state,
100                                          const Expr *expr,
101                                          SVal val) const;
102 
103   static const GRState *InvalidateBuffer(CheckerContext &C,
104                                          const GRState *state,
105                                          const Expr *Ex, SVal V);
106 
107   static bool SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
108                               const MemRegion *MR);
109 
110   // Re-usable checks
111   const GRState *checkNonNull(CheckerContext &C, const GRState *state,
112                                const Expr *S, SVal l) const;
113   const GRState *CheckLocation(CheckerContext &C, const GRState *state,
114                                const Expr *S, SVal l,
115                                bool IsDestination = false) const;
116   const GRState *CheckBufferAccess(CheckerContext &C, const GRState *state,
117                                    const Expr *Size,
118                                    const Expr *FirstBuf,
119                                    const Expr *SecondBuf = NULL,
120                                    bool FirstIsDestination = false) const;
121   const GRState *CheckOverlap(CheckerContext &C, const GRState *state,
122                               const Expr *Size, const Expr *First,
123                               const Expr *Second) const;
124   void emitOverlapBug(CheckerContext &C, const GRState *state,
125                       const Stmt *First, const Stmt *Second) const;
126 };
127 
128 class CStringLength {
129 public:
130   typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
131 };
132 } //end anonymous namespace
133 
134 namespace clang {
135 namespace ento {
136   template <>
137   struct GRStateTrait<CStringLength>
138     : public GRStatePartialTrait<CStringLength::EntryMap> {
139     static void *GDMIndex() { return CStringChecker::getTag(); }
140   };
141 }
142 }
143 
144 //===----------------------------------------------------------------------===//
145 // Individual checks and utility methods.
146 //===----------------------------------------------------------------------===//
147 
148 std::pair<const GRState*, const GRState*>
149 CStringChecker::assumeZero(CheckerContext &C, const GRState *state, SVal V,
150                            QualType Ty) {
151   DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
152   if (!val)
153     return std::pair<const GRState*, const GRState *>(state, state);
154 
155   SValBuilder &svalBuilder = C.getSValBuilder();
156   DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
157   return state->assume(svalBuilder.evalEQ(state, *val, zero));
158 }
159 
160 const GRState *CStringChecker::checkNonNull(CheckerContext &C,
161                                             const GRState *state,
162                                             const Expr *S, SVal l) const {
163   // If a previous check has failed, propagate the failure.
164   if (!state)
165     return NULL;
166 
167   const GRState *stateNull, *stateNonNull;
168   llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
169 
170   if (stateNull && !stateNonNull) {
171     ExplodedNode *N = C.generateSink(stateNull);
172     if (!N)
173       return NULL;
174 
175     if (!BT_Null)
176       BT_Null.reset(new BuiltinBug("API",
177         "Null pointer argument in call to byte string function"));
178 
179     // Generate a report for this bug.
180     BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
181     EnhancedBugReport *report = new EnhancedBugReport(*BT,
182                                                       BT->getDescription(), N);
183 
184     report->addRange(S->getSourceRange());
185     report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, S);
186     C.EmitReport(report);
187     return NULL;
188   }
189 
190   // From here on, assume that the value is non-null.
191   assert(stateNonNull);
192   return stateNonNull;
193 }
194 
195 // FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
196 const GRState *CStringChecker::CheckLocation(CheckerContext &C,
197                                              const GRState *state,
198                                              const Expr *S, SVal l,
199                                              bool IsDestination) const {
200   // If a previous check has failed, propagate the failure.
201   if (!state)
202     return NULL;
203 
204   // Check for out of bound array element access.
205   const MemRegion *R = l.getAsRegion();
206   if (!R)
207     return state;
208 
209   const ElementRegion *ER = dyn_cast<ElementRegion>(R);
210   if (!ER)
211     return state;
212 
213   assert(ER->getValueType() == C.getASTContext().CharTy &&
214     "CheckLocation should only be called with char* ElementRegions");
215 
216   // Get the size of the array.
217   const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
218   SValBuilder &svalBuilder = C.getSValBuilder();
219   SVal Extent = svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
220   DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
221 
222   // Get the index of the accessed element.
223   DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
224 
225   const GRState *StInBound = state->assumeInBound(Idx, Size, true);
226   const GRState *StOutBound = state->assumeInBound(Idx, Size, false);
227   if (StOutBound && !StInBound) {
228     ExplodedNode *N = C.generateSink(StOutBound);
229     if (!N)
230       return NULL;
231 
232     BuiltinBug *BT;
233     if (IsDestination) {
234       if (!BT_BoundsWrite) {
235         BT_BoundsWrite.reset(new BuiltinBug("Out-of-bound array access",
236           "Byte string function overflows destination buffer"));
237       }
238       BT = static_cast<BuiltinBug*>(BT_BoundsWrite.get());
239     } else {
240       if (!BT_Bounds) {
241         BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
242           "Byte string function accesses out-of-bound array element"));
243       }
244       BT = static_cast<BuiltinBug*>(BT_Bounds.get());
245     }
246 
247     // FIXME: It would be nice to eventually make this diagnostic more clear,
248     // e.g., by referencing the original declaration or by saying *why* this
249     // reference is outside the range.
250 
251     // Generate a report for this bug.
252     RangedBugReport *report = new RangedBugReport(*BT, BT->getDescription(), N);
253 
254     report->addRange(S->getSourceRange());
255     C.EmitReport(report);
256     return NULL;
257   }
258 
259   // Array bound check succeeded.  From this point forward the array bound
260   // should always succeed.
261   return StInBound;
262 }
263 
264 const GRState *CStringChecker::CheckBufferAccess(CheckerContext &C,
265                                                  const GRState *state,
266                                                  const Expr *Size,
267                                                  const Expr *FirstBuf,
268                                                  const Expr *SecondBuf,
269                                                 bool FirstIsDestination) const {
270   // If a previous check has failed, propagate the failure.
271   if (!state)
272     return NULL;
273 
274   SValBuilder &svalBuilder = C.getSValBuilder();
275   ASTContext &Ctx = C.getASTContext();
276 
277   QualType sizeTy = Size->getType();
278   QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
279 
280   // Check that the first buffer is non-null.
281   SVal BufVal = state->getSVal(FirstBuf);
282   state = checkNonNull(C, state, FirstBuf, BufVal);
283   if (!state)
284     return NULL;
285 
286   // Get the access length and make sure it is known.
287   SVal LengthVal = state->getSVal(Size);
288   NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
289   if (!Length)
290     return state;
291 
292   // Compute the offset of the last element to be accessed: size-1.
293   NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
294   NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
295                                                     *Length, One, sizeTy));
296 
297   // Check that the first buffer is sufficiently long.
298   SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
299   if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
300     SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
301                                           LastOffset, PtrTy);
302     state = CheckLocation(C, state, FirstBuf, BufEnd, FirstIsDestination);
303 
304     // If the buffer isn't large enough, abort.
305     if (!state)
306       return NULL;
307   }
308 
309   // If there's a second buffer, check it as well.
310   if (SecondBuf) {
311     BufVal = state->getSVal(SecondBuf);
312     state = checkNonNull(C, state, SecondBuf, BufVal);
313     if (!state)
314       return NULL;
315 
316     BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
317     if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
318       SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
319                                             LastOffset, PtrTy);
320       state = CheckLocation(C, state, SecondBuf, BufEnd);
321     }
322   }
323 
324   // Large enough or not, return this state!
325   return state;
326 }
327 
328 const GRState *CStringChecker::CheckOverlap(CheckerContext &C,
329                                             const GRState *state,
330                                             const Expr *Size,
331                                             const Expr *First,
332                                             const Expr *Second) const {
333   // Do a simple check for overlap: if the two arguments are from the same
334   // buffer, see if the end of the first is greater than the start of the second
335   // or vice versa.
336 
337   // If a previous check has failed, propagate the failure.
338   if (!state)
339     return NULL;
340 
341   const GRState *stateTrue, *stateFalse;
342 
343   // Get the buffer values and make sure they're known locations.
344   SVal firstVal = state->getSVal(First);
345   SVal secondVal = state->getSVal(Second);
346 
347   Loc *firstLoc = dyn_cast<Loc>(&firstVal);
348   if (!firstLoc)
349     return state;
350 
351   Loc *secondLoc = dyn_cast<Loc>(&secondVal);
352   if (!secondLoc)
353     return state;
354 
355   // Are the two values the same?
356   SValBuilder &svalBuilder = C.getSValBuilder();
357   llvm::tie(stateTrue, stateFalse) =
358     state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
359 
360   if (stateTrue && !stateFalse) {
361     // If the values are known to be equal, that's automatically an overlap.
362     emitOverlapBug(C, stateTrue, First, Second);
363     return NULL;
364   }
365 
366   // assume the two expressions are not equal.
367   assert(stateFalse);
368   state = stateFalse;
369 
370   // Which value comes first?
371   ASTContext &Ctx = svalBuilder.getContext();
372   QualType cmpTy = Ctx.IntTy;
373   SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
374                                          *firstLoc, *secondLoc, cmpTy);
375   DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
376   if (!reverseTest)
377     return state;
378 
379   llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
380   if (stateTrue) {
381     if (stateFalse) {
382       // If we don't know which one comes first, we can't perform this test.
383       return state;
384     } else {
385       // Switch the values so that firstVal is before secondVal.
386       Loc *tmpLoc = firstLoc;
387       firstLoc = secondLoc;
388       secondLoc = tmpLoc;
389 
390       // Switch the Exprs as well, so that they still correspond.
391       const Expr *tmpExpr = First;
392       First = Second;
393       Second = tmpExpr;
394     }
395   }
396 
397   // Get the length, and make sure it too is known.
398   SVal LengthVal = state->getSVal(Size);
399   NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
400   if (!Length)
401     return state;
402 
403   // Convert the first buffer's start address to char*.
404   // Bail out if the cast fails.
405   QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
406   SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy, First->getType());
407   Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
408   if (!FirstStartLoc)
409     return state;
410 
411   // Compute the end of the first buffer. Bail out if THAT fails.
412   SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
413                                  *FirstStartLoc, *Length, CharPtrTy);
414   Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
415   if (!FirstEndLoc)
416     return state;
417 
418   // Is the end of the first buffer past the start of the second buffer?
419   SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
420                                 *FirstEndLoc, *secondLoc, cmpTy);
421   DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
422   if (!OverlapTest)
423     return state;
424 
425   llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
426 
427   if (stateTrue && !stateFalse) {
428     // Overlap!
429     emitOverlapBug(C, stateTrue, First, Second);
430     return NULL;
431   }
432 
433   // assume the two expressions don't overlap.
434   assert(stateFalse);
435   return stateFalse;
436 }
437 
438 void CStringChecker::emitOverlapBug(CheckerContext &C, const GRState *state,
439                                   const Stmt *First, const Stmt *Second) const {
440   ExplodedNode *N = C.generateSink(state);
441   if (!N)
442     return;
443 
444   if (!BT_Overlap)
445     BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
446 
447   // Generate a report for this bug.
448   RangedBugReport *report =
449     new RangedBugReport(*BT_Overlap,
450       "Arguments must not be overlapping buffers", N);
451   report->addRange(First->getSourceRange());
452   report->addRange(Second->getSourceRange());
453 
454   C.EmitReport(report);
455 }
456 
457 const GRState *CStringChecker::setCStringLength(const GRState *state,
458                                                 const MemRegion *MR,
459                                                 SVal strLength) {
460   assert(!strLength.isUndef() && "Attempt to set an undefined string length");
461   if (strLength.isUnknown())
462     return state;
463 
464   MR = MR->StripCasts();
465 
466   switch (MR->getKind()) {
467   case MemRegion::StringRegionKind:
468     // FIXME: This can happen if we strcpy() into a string region. This is
469     // undefined [C99 6.4.5p6], but we should still warn about it.
470     return state;
471 
472   case MemRegion::SymbolicRegionKind:
473   case MemRegion::AllocaRegionKind:
474   case MemRegion::VarRegionKind:
475   case MemRegion::FieldRegionKind:
476   case MemRegion::ObjCIvarRegionKind:
477     return state->set<CStringLength>(MR, strLength);
478 
479   case MemRegion::ElementRegionKind:
480     // FIXME: Handle element regions by upper-bounding the parent region's
481     // string length.
482     return state;
483 
484   default:
485     // Other regions (mostly non-data) can't have a reliable C string length.
486     // For now, just ignore the change.
487     // FIXME: These are rare but not impossible. We should output some kind of
488     // warning for things like strcpy((char[]){'a', 0}, "b");
489     return state;
490   }
491 }
492 
493 SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
494                                                const GRState *&state,
495                                                const Expr *Ex,
496                                                const MemRegion *MR) {
497   // If there's a recorded length, go ahead and return it.
498   const SVal *Recorded = state->get<CStringLength>(MR);
499   if (Recorded)
500     return *Recorded;
501 
502   // Otherwise, get a new symbol and update the state.
503   unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
504   SValBuilder &svalBuilder = C.getSValBuilder();
505   QualType sizeTy = svalBuilder.getContext().getSizeType();
506   SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
507                                                     MR, Ex, sizeTy, Count);
508   state = state->set<CStringLength>(MR, strLength);
509   return strLength;
510 }
511 
512 SVal CStringChecker::getCStringLength(CheckerContext &C, const GRState *&state,
513                                       const Expr *Ex, SVal Buf) const {
514   const MemRegion *MR = Buf.getAsRegion();
515   if (!MR) {
516     // If we can't get a region, see if it's something we /know/ isn't a
517     // C string. In the context of locations, the only time we can issue such
518     // a warning is for labels.
519     if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
520       if (ExplodedNode *N = C.generateNode(state)) {
521         if (!BT_NotCString)
522           BT_NotCString.reset(new BuiltinBug("API",
523             "Argument is not a null-terminated string."));
524 
525         llvm::SmallString<120> buf;
526         llvm::raw_svector_ostream os(buf);
527         os << "Argument to byte string function is the address of the label '"
528            << Label->getLabel()->getName()
529            << "', which is not a null-terminated string";
530 
531         // Generate a report for this bug.
532         EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
533                                                           os.str(), N);
534 
535         report->addRange(Ex->getSourceRange());
536         C.EmitReport(report);
537       }
538 
539       return UndefinedVal();
540     }
541 
542     // If it's not a region and not a label, give up.
543     return UnknownVal();
544   }
545 
546   // If we have a region, strip casts from it and see if we can figure out
547   // its length. For anything we can't figure out, just return UnknownVal.
548   MR = MR->StripCasts();
549 
550   switch (MR->getKind()) {
551   case MemRegion::StringRegionKind: {
552     // Modifying the contents of string regions is undefined [C99 6.4.5p6],
553     // so we can assume that the byte length is the correct C string length.
554     SValBuilder &svalBuilder = C.getSValBuilder();
555     QualType sizeTy = svalBuilder.getContext().getSizeType();
556     const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
557     return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
558   }
559   case MemRegion::SymbolicRegionKind:
560   case MemRegion::AllocaRegionKind:
561   case MemRegion::VarRegionKind:
562   case MemRegion::FieldRegionKind:
563   case MemRegion::ObjCIvarRegionKind:
564     return getCStringLengthForRegion(C, state, Ex, MR);
565   case MemRegion::CompoundLiteralRegionKind:
566     // FIXME: Can we track this? Is it necessary?
567     return UnknownVal();
568   case MemRegion::ElementRegionKind:
569     // FIXME: How can we handle this? It's not good enough to subtract the
570     // offset from the base string length; consider "123\x00567" and &a[5].
571     return UnknownVal();
572   default:
573     // Other regions (mostly non-data) can't have a reliable C string length.
574     // In this case, an error is emitted and UndefinedVal is returned.
575     // The caller should always be prepared to handle this case.
576     if (ExplodedNode *N = C.generateNode(state)) {
577       if (!BT_NotCString)
578         BT_NotCString.reset(new BuiltinBug("API",
579           "Argument is not a null-terminated string."));
580 
581       llvm::SmallString<120> buf;
582       llvm::raw_svector_ostream os(buf);
583 
584       os << "Argument to byte string function is ";
585 
586       if (SummarizeRegion(os, C.getASTContext(), MR))
587         os << ", which is not a null-terminated string";
588       else
589         os << "not a null-terminated string";
590 
591       // Generate a report for this bug.
592       EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
593                                                         os.str(), N);
594 
595       report->addRange(Ex->getSourceRange());
596       C.EmitReport(report);
597     }
598 
599     return UndefinedVal();
600   }
601 }
602 
603 const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
604   const GRState *&state, const Expr *expr, SVal val) const {
605 
606   // Get the memory region pointed to by the val.
607   const MemRegion *bufRegion = val.getAsRegion();
608   if (!bufRegion)
609     return NULL;
610 
611   // Strip casts off the memory region.
612   bufRegion = bufRegion->StripCasts();
613 
614   // Cast the memory region to a string region.
615   const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
616   if (!strRegion)
617     return NULL;
618 
619   // Return the actual string in the string region.
620   return strRegion->getStringLiteral();
621 }
622 
623 const GRState *CStringChecker::InvalidateBuffer(CheckerContext &C,
624                                                 const GRState *state,
625                                                 const Expr *E, SVal V) {
626   Loc *L = dyn_cast<Loc>(&V);
627   if (!L)
628     return state;
629 
630   // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
631   // some assumptions about the value that CFRefCount can't. Even so, it should
632   // probably be refactored.
633   if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
634     const MemRegion *R = MR->getRegion()->StripCasts();
635 
636     // Are we dealing with an ElementRegion?  If so, we should be invalidating
637     // the super-region.
638     if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
639       R = ER->getSuperRegion();
640       // FIXME: What about layers of ElementRegions?
641     }
642 
643     // Invalidate this region.
644     unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
645     return state->invalidateRegion(R, E, Count, NULL);
646   }
647 
648   // If we have a non-region value by chance, just remove the binding.
649   // FIXME: is this necessary or correct? This handles the non-Region
650   //  cases.  Is it ever valid to store to these?
651   return state->unbindLoc(*L);
652 }
653 
654 bool CStringChecker::SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
655                                      const MemRegion *MR) {
656   const TypedRegion *TR = dyn_cast<TypedRegion>(MR);
657   if (!TR)
658     return false;
659 
660   switch (TR->getKind()) {
661   case MemRegion::FunctionTextRegionKind: {
662     const FunctionDecl *FD = cast<FunctionTextRegion>(TR)->getDecl();
663     if (FD)
664       os << "the address of the function '" << FD << "'";
665     else
666       os << "the address of a function";
667     return true;
668   }
669   case MemRegion::BlockTextRegionKind:
670     os << "block text";
671     return true;
672   case MemRegion::BlockDataRegionKind:
673     os << "a block";
674     return true;
675   case MemRegion::CXXThisRegionKind:
676   case MemRegion::CXXTempObjectRegionKind:
677     os << "a C++ temp object of type " << TR->getValueType().getAsString();
678     return true;
679   case MemRegion::VarRegionKind:
680     os << "a variable of type" << TR->getValueType().getAsString();
681     return true;
682   case MemRegion::FieldRegionKind:
683     os << "a field of type " << TR->getValueType().getAsString();
684     return true;
685   case MemRegion::ObjCIvarRegionKind:
686     os << "an instance variable of type " << TR->getValueType().getAsString();
687     return true;
688   default:
689     return false;
690   }
691 }
692 
693 //===----------------------------------------------------------------------===//
694 // evaluation of individual function calls.
695 //===----------------------------------------------------------------------===//
696 
697 void CStringChecker::evalCopyCommon(CheckerContext &C,
698                                     const CallExpr *CE,
699                                     const GRState *state,
700                                     const Expr *Size, const Expr *Dest,
701                                     const Expr *Source, bool Restricted,
702                                     bool IsMempcpy) const {
703   // See if the size argument is zero.
704   SVal sizeVal = state->getSVal(Size);
705   QualType sizeTy = Size->getType();
706 
707   const GRState *stateZeroSize, *stateNonZeroSize;
708   llvm::tie(stateZeroSize, stateNonZeroSize) = assumeZero(C, state, sizeVal, sizeTy);
709 
710   // Get the value of the Dest.
711   SVal destVal = state->getSVal(Dest);
712 
713   // If the size is zero, there won't be any actual memory access, so
714   // just bind the return value to the destination buffer and return.
715   if (stateZeroSize) {
716     C.addTransition(stateZeroSize);
717     if (IsMempcpy)
718       state->BindExpr(CE, destVal);
719     else
720       state->BindExpr(CE, sizeVal);
721     return;
722   }
723 
724   // If the size can be nonzero, we have to check the other arguments.
725   if (stateNonZeroSize) {
726 
727     // Ensure the destination is not null. If it is NULL there will be a
728     // NULL pointer dereference.
729     state = checkNonNull(C, state, Dest, destVal);
730     if (!state)
731       return;
732 
733     // Get the value of the Src.
734     SVal srcVal = state->getSVal(Source);
735 
736     // Ensure the source is not null. If it is NULL there will be a
737     // NULL pointer dereference.
738     state = checkNonNull(C, state, Source, srcVal);
739     if (!state)
740       return;
741 
742     // Ensure the buffers do not overlap.
743     state = stateNonZeroSize;
744     state = CheckBufferAccess(C, state, Size, Dest, Source,
745                               /* FirstIsDst = */ true);
746     if (Restricted)
747       state = CheckOverlap(C, state, Size, Dest, Source);
748 
749     if (state) {
750 
751       // If this is mempcpy, get the byte after the last byte copied and
752       // bind the expr.
753       if (IsMempcpy) {
754         loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
755 
756         // Get the length to copy.
757         SVal lenVal = state->getSVal(Size);
758         NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&lenVal);
759 
760         // Get the byte after the last byte copied.
761         SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
762                                                           *destRegVal,
763                                                           *lenValNonLoc,
764                                                           Dest->getType());
765 
766         // The byte after the last byte copied is the return value.
767         state = state->BindExpr(CE, lastElement);
768       }
769 
770       // Invalidate the destination.
771       // FIXME: Even if we can't perfectly model the copy, we should see if we
772       // can use LazyCompoundVals to copy the source values into the destination.
773       // This would probably remove any existing bindings past the end of the
774       // copied region, but that's still an improvement over blank invalidation.
775       state = InvalidateBuffer(C, state, Dest, state->getSVal(Dest));
776       C.addTransition(state);
777     }
778   }
779 }
780 
781 
782 void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
783   // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
784   // The return value is the address of the destination buffer.
785   const Expr *Dest = CE->getArg(0);
786   const GRState *state = C.getState();
787   state = state->BindExpr(CE, state->getSVal(Dest));
788   evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
789 }
790 
791 void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
792   // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
793   // The return value is a pointer to the byte following the last written byte.
794   const Expr *Dest = CE->getArg(0);
795   const GRState *state = C.getState();
796 
797   evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
798 }
799 
800 void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
801   // void *memmove(void *dst, const void *src, size_t n);
802   // The return value is the address of the destination buffer.
803   const Expr *Dest = CE->getArg(0);
804   const GRState *state = C.getState();
805   state = state->BindExpr(CE, state->getSVal(Dest));
806   evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
807 }
808 
809 void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
810   // void bcopy(const void *src, void *dst, size_t n);
811   evalCopyCommon(C, CE, C.getState(),
812                  CE->getArg(2), CE->getArg(1), CE->getArg(0));
813 }
814 
815 void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
816   // int memcmp(const void *s1, const void *s2, size_t n);
817   const Expr *Left = CE->getArg(0);
818   const Expr *Right = CE->getArg(1);
819   const Expr *Size = CE->getArg(2);
820 
821   const GRState *state = C.getState();
822   SValBuilder &svalBuilder = C.getSValBuilder();
823 
824   // See if the size argument is zero.
825   SVal sizeVal = state->getSVal(Size);
826   QualType sizeTy = Size->getType();
827 
828   const GRState *stateZeroSize, *stateNonZeroSize;
829   llvm::tie(stateZeroSize, stateNonZeroSize) =
830     assumeZero(C, state, sizeVal, sizeTy);
831 
832   // If the size can be zero, the result will be 0 in that case, and we don't
833   // have to check either of the buffers.
834   if (stateZeroSize) {
835     state = stateZeroSize;
836     state = state->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
837     C.addTransition(state);
838   }
839 
840   // If the size can be nonzero, we have to check the other arguments.
841   if (stateNonZeroSize) {
842     state = stateNonZeroSize;
843     // If we know the two buffers are the same, we know the result is 0.
844     // First, get the two buffers' addresses. Another checker will have already
845     // made sure they're not undefined.
846     DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(state->getSVal(Left));
847     DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(state->getSVal(Right));
848 
849     // See if they are the same.
850     DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
851     const GRState *StSameBuf, *StNotSameBuf;
852     llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
853 
854     // If the two arguments might be the same buffer, we know the result is zero,
855     // and we only need to check one size.
856     if (StSameBuf) {
857       state = StSameBuf;
858       state = CheckBufferAccess(C, state, Size, Left);
859       if (state) {
860         state = StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
861         C.addTransition(state);
862       }
863     }
864 
865     // If the two arguments might be different buffers, we have to check the
866     // size of both of them.
867     if (StNotSameBuf) {
868       state = StNotSameBuf;
869       state = CheckBufferAccess(C, state, Size, Left, Right);
870       if (state) {
871         // The return value is the comparison result, which we don't know.
872         unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
873         SVal CmpV = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
874         state = state->BindExpr(CE, CmpV);
875         C.addTransition(state);
876       }
877     }
878   }
879 }
880 
881 void CStringChecker::evalstrLength(CheckerContext &C,
882                                    const CallExpr *CE) const {
883   // size_t strlen(const char *s);
884   evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
885 }
886 
887 void CStringChecker::evalstrnLength(CheckerContext &C,
888                                     const CallExpr *CE) const {
889   // size_t strnlen(const char *s, size_t maxlen);
890   evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
891 }
892 
893 void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
894                                          bool IsStrnlen) const {
895   const GRState *state = C.getState();
896   const Expr *Arg = CE->getArg(0);
897   SVal ArgVal = state->getSVal(Arg);
898 
899   // Check that the argument is non-null.
900   state = checkNonNull(C, state, Arg, ArgVal);
901 
902   if (state) {
903     SVal strLength = getCStringLength(C, state, Arg, ArgVal);
904 
905     // If the argument isn't a valid C string, there's no valid state to
906     // transition to.
907     if (strLength.isUndef())
908       return;
909 
910     // If the check is for strnlen() then bind the return value to no more than
911     // the maxlen value.
912     if (IsStrnlen) {
913       const Expr *maxlenExpr = CE->getArg(1);
914       SVal maxlenVal = state->getSVal(maxlenExpr);
915 
916       NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
917       NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
918 
919       QualType cmpTy = C.getSValBuilder().getContext().IntTy;
920       const GRState *stateTrue, *stateFalse;
921 
922       // Check if the strLength is greater than or equal to the maxlen
923       llvm::tie(stateTrue, stateFalse) =
924         state->assume(cast<DefinedOrUnknownSVal>
925                       (C.getSValBuilder().evalBinOpNN(state, BO_GE,
926                                                       *strLengthNL, *maxlenValNL,
927                                                       cmpTy)));
928 
929       // If the strLength is greater than or equal to the maxlen, set strLength
930       // to maxlen
931       if (stateTrue && !stateFalse) {
932         strLength = maxlenVal;
933       }
934     }
935 
936     // If getCStringLength couldn't figure out the length, conjure a return
937     // value, so it can be used in constraints, at least.
938     if (strLength.isUnknown()) {
939       unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
940       strLength = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
941     }
942 
943     // Bind the return value.
944     state = state->BindExpr(CE, strLength);
945     C.addTransition(state);
946   }
947 }
948 
949 void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
950   // char *strcpy(char *restrict dst, const char *restrict src);
951   evalStrcpyCommon(C, CE,
952                    /* returnEnd = */ false,
953                    /* isBounded = */ false,
954                    /* isAppending = */ false);
955 }
956 
957 void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
958   // char *strcpy(char *restrict dst, const char *restrict src);
959   evalStrcpyCommon(C, CE,
960                    /* returnEnd = */ false,
961                    /* isBounded = */ true,
962                    /* isAppending = */ false);
963 }
964 
965 void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
966   // char *stpcpy(char *restrict dst, const char *restrict src);
967   evalStrcpyCommon(C, CE,
968                    /* returnEnd = */ true,
969                    /* isBounded = */ false,
970                    /* isAppending = */ false);
971 }
972 
973 void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
974   //char *strcat(char *restrict s1, const char *restrict s2);
975   evalStrcpyCommon(C, CE,
976                    /* returnEnd = */ false,
977                    /* isBounded = */ false,
978                    /* isAppending = */ true);
979 }
980 
981 void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
982   //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
983   evalStrcpyCommon(C, CE,
984                    /* returnEnd = */ false,
985                    /* isBounded = */ true,
986                    /* isAppending = */ true);
987 }
988 
989 void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
990                                       bool returnEnd, bool isBounded,
991                                       bool isAppending) const {
992   const GRState *state = C.getState();
993 
994   // Check that the destination is non-null.
995   const Expr *Dst = CE->getArg(0);
996   SVal DstVal = state->getSVal(Dst);
997 
998   state = checkNonNull(C, state, Dst, DstVal);
999   if (!state)
1000     return;
1001 
1002   // Check that the source is non-null.
1003   const Expr *srcExpr = CE->getArg(1);
1004   SVal srcVal = state->getSVal(srcExpr);
1005   state = checkNonNull(C, state, srcExpr, srcVal);
1006   if (!state)
1007     return;
1008 
1009   // Get the string length of the source.
1010   SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
1011 
1012   // If the source isn't a valid C string, give up.
1013   if (strLength.isUndef())
1014     return;
1015 
1016   // If the function is strncpy, strncat, etc... it is bounded.
1017   if (isBounded) {
1018     // Get the max number of characters to copy.
1019     const Expr *lenExpr = CE->getArg(2);
1020     SVal lenVal = state->getSVal(lenExpr);
1021 
1022     // Cast the length to a NonLoc SVal. If it is not a NonLoc then give up.
1023     NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1024     if (!strLengthNL)
1025       return;
1026 
1027     // Cast the max length to a NonLoc SVal. If it is not a NonLoc then give up.
1028     NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1029     if (!lenValNL)
1030       return;
1031 
1032     QualType cmpTy = C.getSValBuilder().getContext().IntTy;
1033     const GRState *stateTrue, *stateFalse;
1034 
1035     // Check if the max number to copy is less than the length of the src.
1036     llvm::tie(stateTrue, stateFalse) =
1037       state->assume(cast<DefinedOrUnknownSVal>
1038                     (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1039                                                     *strLengthNL, *lenValNL,
1040                                                     cmpTy)));
1041 
1042     if (stateTrue) {
1043       // Max number to copy is less than the length of the src, so the actual
1044       // strLength copied is the max number arg.
1045       strLength = lenVal;
1046     }
1047   }
1048 
1049   // If this is an appending function (strcat, strncat...) then set the
1050   // string length to strlen(src) + strlen(dst) since the buffer will
1051   // ultimately contain both.
1052   if (isAppending) {
1053     // Get the string length of the destination, or give up.
1054     SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1055     if (dstStrLength.isUndef())
1056       return;
1057 
1058     NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&strLength);
1059     NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1060 
1061     // If src or dst cast to NonLoc is NULL, give up.
1062     if ((!srcStrLengthNL) || (!dstStrLengthNL))
1063       return;
1064 
1065     QualType addTy = C.getSValBuilder().getContext().getSizeType();
1066 
1067     strLength = C.getSValBuilder().evalBinOpNN(state, BO_Add,
1068                                                *srcStrLengthNL, *dstStrLengthNL,
1069                                                addTy);
1070   }
1071 
1072   SVal Result = (returnEnd ? UnknownVal() : DstVal);
1073 
1074   // If the destination is a MemRegion, try to check for a buffer overflow and
1075   // record the new string length.
1076   if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
1077     // If the length is known, we can check for an overflow.
1078     if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&strLength)) {
1079       SVal lastElement =
1080         C.getSValBuilder().evalBinOpLN(state, BO_Add, *dstRegVal,
1081                                        *knownStrLength, Dst->getType());
1082 
1083       state = CheckLocation(C, state, Dst, lastElement, /* IsDst = */ true);
1084       if (!state)
1085         return;
1086 
1087       // If this is a stpcpy-style copy, the last element is the return value.
1088       if (returnEnd)
1089         Result = lastElement;
1090     }
1091 
1092     // Invalidate the destination. This must happen before we set the C string
1093     // length because invalidation will clear the length.
1094     // FIXME: Even if we can't perfectly model the copy, we should see if we
1095     // can use LazyCompoundVals to copy the source values into the destination.
1096     // This would probably remove any existing bindings past the end of the
1097     // string, but that's still an improvement over blank invalidation.
1098     state = InvalidateBuffer(C, state, Dst, *dstRegVal);
1099 
1100     // Set the C string length of the destination.
1101     state = setCStringLength(state, dstRegVal->getRegion(), strLength);
1102   }
1103 
1104   // If this is a stpcpy-style copy, but we were unable to check for a buffer
1105   // overflow, we still need a result. Conjure a return value.
1106   if (returnEnd && Result.isUnknown()) {
1107     SValBuilder &svalBuilder = C.getSValBuilder();
1108     unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
1109     strLength = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
1110   }
1111 
1112   // Set the return value.
1113   state = state->BindExpr(CE, Result);
1114   C.addTransition(state);
1115 }
1116 
1117 void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1118   //int strcmp(const char *restrict s1, const char *restrict s2);
1119   evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
1120 }
1121 
1122 void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
1123   //int strncmp(const char *restrict s1, const char *restrict s2, size_t n);
1124   evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1125 }
1126 
1127 void CStringChecker::evalStrcasecmp(CheckerContext &C,
1128                                     const CallExpr *CE) const {
1129   //int strcasecmp(const char *restrict s1, const char *restrict s2);
1130   evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
1131 }
1132 
1133 void CStringChecker::evalStrncasecmp(CheckerContext &C,
1134                                      const CallExpr *CE) const {
1135   //int strncasecmp(const char *restrict s1, const char *restrict s2, size_t n);
1136   evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1137 }
1138 
1139 void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
1140                                       bool isBounded, bool ignoreCase) const {
1141   const GRState *state = C.getState();
1142 
1143   // Check that the first string is non-null
1144   const Expr *s1 = CE->getArg(0);
1145   SVal s1Val = state->getSVal(s1);
1146   state = checkNonNull(C, state, s1, s1Val);
1147   if (!state)
1148     return;
1149 
1150   // Check that the second string is non-null.
1151   const Expr *s2 = CE->getArg(1);
1152   SVal s2Val = state->getSVal(s2);
1153   state = checkNonNull(C, state, s2, s2Val);
1154   if (!state)
1155     return;
1156 
1157   // Get the string length of the first string or give up.
1158   SVal s1Length = getCStringLength(C, state, s1, s1Val);
1159   if (s1Length.isUndef())
1160     return;
1161 
1162   // Get the string length of the second string or give up.
1163   SVal s2Length = getCStringLength(C, state, s2, s2Val);
1164   if (s2Length.isUndef())
1165     return;
1166 
1167   // Get the string literal of the first string.
1168   const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1169   if (!s1StrLiteral)
1170     return;
1171   llvm::StringRef s1StrRef = s1StrLiteral->getString();
1172 
1173   // Get the string literal of the second string.
1174   const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1175   if (!s2StrLiteral)
1176     return;
1177   llvm::StringRef s2StrRef = s2StrLiteral->getString();
1178 
1179   int result;
1180   if (isBounded) {
1181     // Get the max number of characters to compare.
1182     const Expr *lenExpr = CE->getArg(2);
1183     SVal lenVal = state->getSVal(lenExpr);
1184 
1185     // Dynamically cast the length to a ConcreteInt. If it is not a ConcreteInt
1186     // then give up, otherwise get the value and use it as the bounds.
1187     nonloc::ConcreteInt *CI = dyn_cast<nonloc::ConcreteInt>(&lenVal);
1188     if (!CI)
1189       return;
1190     llvm::APSInt lenInt(CI->getValue());
1191 
1192     // Create substrings of each to compare the prefix.
1193     s1StrRef = s1StrRef.substr(0, (size_t)lenInt.getLimitedValue());
1194     s2StrRef = s2StrRef.substr(0, (size_t)lenInt.getLimitedValue());
1195   }
1196 
1197   if (ignoreCase) {
1198     // Compare string 1 to string 2 the same way strcasecmp() does.
1199     result = s1StrRef.compare_lower(s2StrRef);
1200   } else {
1201     // Compare string 1 to string 2 the same way strcmp() does.
1202     result = s1StrRef.compare(s2StrRef);
1203   }
1204 
1205   // Build the SVal of the comparison to bind the return value.
1206   SValBuilder &svalBuilder = C.getSValBuilder();
1207   QualType intTy = svalBuilder.getContext().IntTy;
1208   SVal resultVal = svalBuilder.makeIntVal(result, intTy);
1209 
1210   // Bind the return value of the expression.
1211   // Set the return value.
1212   state = state->BindExpr(CE, resultVal);
1213   C.addTransition(state);
1214 }
1215 
1216 //===----------------------------------------------------------------------===//
1217 // The driver method, and other Checker callbacks.
1218 //===----------------------------------------------------------------------===//
1219 
1220 bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
1221   // Get the callee.  All the functions we care about are C functions
1222   // with simple identifiers.
1223   const GRState *state = C.getState();
1224   const Expr *Callee = CE->getCallee();
1225   const FunctionDecl *FD = state->getSVal(Callee).getAsFunctionDecl();
1226 
1227   if (!FD)
1228     return false;
1229 
1230   // Get the name of the callee. If it's a builtin, strip off the prefix.
1231   IdentifierInfo *II = FD->getIdentifier();
1232   if (!II)   // if no identifier, not a simple C function
1233     return false;
1234   llvm::StringRef Name = II->getName();
1235   if (Name.startswith("__builtin_"))
1236     Name = Name.substr(10);
1237 
1238   FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
1239     .Cases("memcpy", "__memcpy_chk", &CStringChecker::evalMemcpy)
1240     .Case("mempcpy", &CStringChecker::evalMempcpy)
1241     .Cases("memcmp", "bcmp", &CStringChecker::evalMemcmp)
1242     .Cases("memmove", "__memmove_chk", &CStringChecker::evalMemmove)
1243     .Cases("strcpy", "__strcpy_chk", &CStringChecker::evalStrcpy)
1244     //.Cases("strncpy", "__strncpy_chk", &CStringChecker::evalStrncpy)
1245     .Cases("stpcpy", "__stpcpy_chk", &CStringChecker::evalStpcpy)
1246     .Cases("strcat", "__strcat_chk", &CStringChecker::evalStrcat)
1247     .Cases("strncat", "__strncat_chk", &CStringChecker::evalStrncat)
1248     .Case("strlen", &CStringChecker::evalstrLength)
1249     .Case("strnlen", &CStringChecker::evalstrnLength)
1250     .Case("strcmp", &CStringChecker::evalStrcmp)
1251     .Case("strncmp", &CStringChecker::evalStrncmp)
1252     .Case("strcasecmp", &CStringChecker::evalStrcasecmp)
1253     .Case("strncasecmp", &CStringChecker::evalStrncasecmp)
1254     .Case("bcopy", &CStringChecker::evalBcopy)
1255     .Default(NULL);
1256 
1257   // If the callee isn't a string function, let another checker handle it.
1258   if (!evalFunction)
1259     return false;
1260 
1261   // Check and evaluate the call.
1262   (this->*evalFunction)(C, CE);
1263   return true;
1264 }
1265 
1266 void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
1267   // Record string length for char a[] = "abc";
1268   const GRState *state = C.getState();
1269 
1270   for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1271        I != E; ++I) {
1272     const VarDecl *D = dyn_cast<VarDecl>(*I);
1273     if (!D)
1274       continue;
1275 
1276     // FIXME: Handle array fields of structs.
1277     if (!D->getType()->isArrayType())
1278       continue;
1279 
1280     const Expr *Init = D->getInit();
1281     if (!Init)
1282       continue;
1283     if (!isa<StringLiteral>(Init))
1284       continue;
1285 
1286     Loc VarLoc = state->getLValue(D, C.getPredecessor()->getLocationContext());
1287     const MemRegion *MR = VarLoc.getAsRegion();
1288     if (!MR)
1289       continue;
1290 
1291     SVal StrVal = state->getSVal(Init);
1292     assert(StrVal.isValid() && "Initializer string is unknown or undefined");
1293     DefinedOrUnknownSVal strLength
1294       = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
1295 
1296     state = state->set<CStringLength>(MR, strLength);
1297   }
1298 
1299   C.addTransition(state);
1300 }
1301 
1302 bool CStringChecker::wantsRegionChangeUpdate(const GRState *state) const {
1303   CStringLength::EntryMap Entries = state->get<CStringLength>();
1304   return !Entries.isEmpty();
1305 }
1306 
1307 const GRState *
1308 CStringChecker::checkRegionChanges(const GRState *state,
1309                                    const StoreManager::InvalidatedSymbols *,
1310                                    const MemRegion * const *Begin,
1311                                    const MemRegion * const *End) const {
1312   CStringLength::EntryMap Entries = state->get<CStringLength>();
1313   if (Entries.isEmpty())
1314     return state;
1315 
1316   llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1317   llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1318 
1319   // First build sets for the changed regions and their super-regions.
1320   for ( ; Begin != End; ++Begin) {
1321     const MemRegion *MR = *Begin;
1322     Invalidated.insert(MR);
1323 
1324     SuperRegions.insert(MR);
1325     while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1326       MR = SR->getSuperRegion();
1327       SuperRegions.insert(MR);
1328     }
1329   }
1330 
1331   CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1332 
1333   // Then loop over the entries in the current state.
1334   for (CStringLength::EntryMap::iterator I = Entries.begin(),
1335        E = Entries.end(); I != E; ++I) {
1336     const MemRegion *MR = I.getKey();
1337 
1338     // Is this entry for a super-region of a changed region?
1339     if (SuperRegions.count(MR)) {
1340       Entries = F.remove(Entries, MR);
1341       continue;
1342     }
1343 
1344     // Is this entry for a sub-region of a changed region?
1345     const MemRegion *Super = MR;
1346     while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1347       Super = SR->getSuperRegion();
1348       if (Invalidated.count(Super)) {
1349         Entries = F.remove(Entries, MR);
1350         break;
1351       }
1352     }
1353   }
1354 
1355   return state->set<CStringLength>(Entries);
1356 }
1357 
1358 void CStringChecker::checkLiveSymbols(const GRState *state,
1359                                       SymbolReaper &SR) const {
1360   // Mark all symbols in our string length map as valid.
1361   CStringLength::EntryMap Entries = state->get<CStringLength>();
1362 
1363   for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1364        I != E; ++I) {
1365     SVal Len = I.getData();
1366     if (SymbolRef Sym = Len.getAsSymbol())
1367       SR.markInUse(Sym);
1368   }
1369 }
1370 
1371 void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1372                                       CheckerContext &C) const {
1373   if (!SR.hasDeadSymbols())
1374     return;
1375 
1376   const GRState *state = C.getState();
1377   CStringLength::EntryMap Entries = state->get<CStringLength>();
1378   if (Entries.isEmpty())
1379     return;
1380 
1381   CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1382   for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1383        I != E; ++I) {
1384     SVal Len = I.getData();
1385     if (SymbolRef Sym = Len.getAsSymbol()) {
1386       if (SR.isDead(Sym))
1387         Entries = F.remove(Entries, I.getKey());
1388     }
1389   }
1390 
1391   state = state->set<CStringLength>(Entries);
1392   C.generateNode(state);
1393 }
1394 
1395 void ento::registerCStringChecker(CheckerManager &mgr) {
1396   mgr.registerChecker<CStringChecker>();
1397 }
1398