CStringChecker.cpp revision 9c378f705405d37f49795d5e915989de774fe11f
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
23using namespace clang;
24using namespace ento;
25
26namespace {
27class 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,
34                                   BT_Overlap, BT_NotCString,
35                                   BT_AdditionOverflow;
36  mutable const char *CurrentFunctionDescription;
37
38public:
39  static void *getTag() { static int tag; return &tag; }
40
41  bool evalCall(const CallExpr *CE, CheckerContext &C) const;
42  void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
43  void checkLiveSymbols(const GRState *state, SymbolReaper &SR) const;
44  void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
45  bool wantsRegionChangeUpdate(const GRState *state) const;
46
47  const GRState *checkRegionChanges(const GRState *state,
48                                    const StoreManager::InvalidatedSymbols *,
49                                    const MemRegion * const *Begin,
50                                    const MemRegion * const *End) const;
51
52  typedef void (CStringChecker::*FnCheck)(CheckerContext &,
53                                          const CallExpr *) const;
54
55  void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
56  void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
57  void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
58  void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
59  void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
60                      const GRState *state,
61                      const Expr *Size, const Expr *Source, const Expr *Dest,
62                      bool Restricted = false,
63                      bool IsMempcpy = false) const;
64
65  void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
66
67  void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
68  void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
69  void evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
70                           bool IsStrnlen = false) const;
71
72  void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
73  void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
74  void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
75  void evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, bool returnEnd,
76                        bool isBounded, bool isAppending) const;
77
78  void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
79  void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
80
81  void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
82  void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
83  void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
84  void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
85  void evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
86                        bool isBounded = false, bool ignoreCase = false) const;
87
88  // Utility methods
89  std::pair<const GRState*, const GRState*>
90  static assumeZero(CheckerContext &C,
91                    const GRState *state, SVal V, QualType Ty);
92
93  static const GRState *setCStringLength(const GRState *state,
94                                         const MemRegion *MR, SVal strLength);
95  static SVal getCStringLengthForRegion(CheckerContext &C,
96                                        const GRState *&state,
97                                        const Expr *Ex, const MemRegion *MR,
98                                        bool hypothetical);
99  SVal getCStringLength(CheckerContext &C, const GRState *&state,
100                        const Expr *Ex, SVal Buf,
101                        bool hypothetical = false) const;
102
103  const StringLiteral *getCStringLiteral(CheckerContext &C,
104                                         const GRState *&state,
105                                         const Expr *expr,
106                                         SVal val) const;
107
108  static const GRState *InvalidateBuffer(CheckerContext &C,
109                                         const GRState *state,
110                                         const Expr *Ex, SVal V);
111
112  static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
113                              const MemRegion *MR);
114
115  // Re-usable checks
116  const GRState *checkNonNull(CheckerContext &C, const GRState *state,
117                               const Expr *S, SVal l) const;
118  const GRState *CheckLocation(CheckerContext &C, const GRState *state,
119                               const Expr *S, SVal l,
120                               const char *message = NULL) const;
121  const GRState *CheckBufferAccess(CheckerContext &C, const GRState *state,
122                                   const Expr *Size,
123                                   const Expr *FirstBuf,
124                                   const Expr *SecondBuf,
125                                   const char *firstMessage = NULL,
126                                   const char *secondMessage = NULL,
127                                   bool WarnAboutSize = false) const;
128  const GRState *CheckBufferAccess(CheckerContext &C, const GRState *state,
129                                   const Expr *Size, const Expr *Buf,
130                                   const char *message = NULL,
131                                   bool WarnAboutSize = false) const {
132    // This is a convenience override.
133    return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
134                             WarnAboutSize);
135  }
136  const GRState *CheckOverlap(CheckerContext &C, const GRState *state,
137                              const Expr *Size, const Expr *First,
138                              const Expr *Second) const;
139  void emitOverlapBug(CheckerContext &C, const GRState *state,
140                      const Stmt *First, const Stmt *Second) const;
141  const GRState *checkAdditionOverflow(CheckerContext &C, const GRState *state,
142                                       NonLoc left, NonLoc right) const;
143};
144
145class CStringLength {
146public:
147  typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
148};
149} //end anonymous namespace
150
151namespace clang {
152namespace ento {
153  template <>
154  struct GRStateTrait<CStringLength>
155    : public GRStatePartialTrait<CStringLength::EntryMap> {
156    static void *GDMIndex() { return CStringChecker::getTag(); }
157  };
158}
159}
160
161//===----------------------------------------------------------------------===//
162// Individual checks and utility methods.
163//===----------------------------------------------------------------------===//
164
165std::pair<const GRState*, const GRState*>
166CStringChecker::assumeZero(CheckerContext &C, const GRState *state, SVal V,
167                           QualType Ty) {
168  DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
169  if (!val)
170    return std::pair<const GRState*, const GRState *>(state, state);
171
172  SValBuilder &svalBuilder = C.getSValBuilder();
173  DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
174  return state->assume(svalBuilder.evalEQ(state, *val, zero));
175}
176
177const GRState *CStringChecker::checkNonNull(CheckerContext &C,
178                                            const GRState *state,
179                                            const Expr *S, SVal l) const {
180  // If a previous check has failed, propagate the failure.
181  if (!state)
182    return NULL;
183
184  const GRState *stateNull, *stateNonNull;
185  llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
186
187  if (stateNull && !stateNonNull) {
188    ExplodedNode *N = C.generateSink(stateNull);
189    if (!N)
190      return NULL;
191
192    if (!BT_Null)
193      BT_Null.reset(new BuiltinBug("API",
194        "Null pointer argument in call to byte string function"));
195
196    llvm::SmallString<80> buf;
197    llvm::raw_svector_ostream os(buf);
198    assert(CurrentFunctionDescription);
199    os << "Null pointer argument in call to " << CurrentFunctionDescription;
200
201    // Generate a report for this bug.
202    BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
203    EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), N);
204
205    report->addRange(S->getSourceRange());
206    report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, S);
207    C.EmitReport(report);
208    return NULL;
209  }
210
211  // From here on, assume that the value is non-null.
212  assert(stateNonNull);
213  return stateNonNull;
214}
215
216// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
217const GRState *CStringChecker::CheckLocation(CheckerContext &C,
218                                             const GRState *state,
219                                             const Expr *S, SVal l,
220                                             const char *warningMsg) const {
221  // If a previous check has failed, propagate the failure.
222  if (!state)
223    return NULL;
224
225  // Check for out of bound array element access.
226  const MemRegion *R = l.getAsRegion();
227  if (!R)
228    return state;
229
230  const ElementRegion *ER = dyn_cast<ElementRegion>(R);
231  if (!ER)
232    return state;
233
234  assert(ER->getValueType() == C.getASTContext().CharTy &&
235    "CheckLocation should only be called with char* ElementRegions");
236
237  // Get the size of the array.
238  const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
239  SValBuilder &svalBuilder = C.getSValBuilder();
240  SVal Extent =
241    svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
242  DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
243
244  // Get the index of the accessed element.
245  DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
246
247  const GRState *StInBound = state->assumeInBound(Idx, Size, true);
248  const GRState *StOutBound = state->assumeInBound(Idx, Size, false);
249  if (StOutBound && !StInBound) {
250    ExplodedNode *N = C.generateSink(StOutBound);
251    if (!N)
252      return NULL;
253
254    if (!BT_Bounds) {
255      BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
256        "Byte string function accesses out-of-bound array element"));
257    }
258    BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
259
260    // Generate a report for this bug.
261    RangedBugReport *report;
262    if (warningMsg) {
263      report = new RangedBugReport(*BT, warningMsg, N);
264    } else {
265      assert(CurrentFunctionDescription);
266      assert(CurrentFunctionDescription[0] != '\0');
267
268      llvm::SmallString<80> buf;
269      llvm::raw_svector_ostream os(buf);
270      os << (char)toupper(CurrentFunctionDescription[0])
271         << &CurrentFunctionDescription[1]
272         << " accesses out-of-bound array element";
273      report = new RangedBugReport(*BT, os.str(), N);
274    }
275
276    // FIXME: It would be nice to eventually make this diagnostic more clear,
277    // e.g., by referencing the original declaration or by saying *why* this
278    // reference is outside the range.
279
280    report->addRange(S->getSourceRange());
281    C.EmitReport(report);
282    return NULL;
283  }
284
285  // Array bound check succeeded.  From this point forward the array bound
286  // should always succeed.
287  return StInBound;
288}
289
290const GRState *CStringChecker::CheckBufferAccess(CheckerContext &C,
291                                                 const GRState *state,
292                                                 const Expr *Size,
293                                                 const Expr *FirstBuf,
294                                                 const Expr *SecondBuf,
295                                                 const char *firstMessage,
296                                                 const char *secondMessage,
297                                                 bool WarnAboutSize) const {
298  // If a previous check has failed, propagate the failure.
299  if (!state)
300    return NULL;
301
302  SValBuilder &svalBuilder = C.getSValBuilder();
303  ASTContext &Ctx = svalBuilder.getContext();
304
305  QualType sizeTy = Size->getType();
306  QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
307
308  // Check that the first buffer is non-null.
309  SVal BufVal = state->getSVal(FirstBuf);
310  state = checkNonNull(C, state, FirstBuf, BufVal);
311  if (!state)
312    return NULL;
313
314  // Get the access length and make sure it is known.
315  // FIXME: This assumes the caller has already checked that the access length
316  // is positive. And that it's unsigned.
317  SVal LengthVal = state->getSVal(Size);
318  NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
319  if (!Length)
320    return state;
321
322  // Compute the offset of the last element to be accessed: size-1.
323  NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
324  NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
325                                                    *Length, One, sizeTy));
326
327  // Check that the first buffer is sufficiently long.
328  SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
329  if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
330    const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
331
332    SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
333                                          LastOffset, PtrTy);
334    state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
335
336    // If the buffer isn't large enough, abort.
337    if (!state)
338      return NULL;
339  }
340
341  // If there's a second buffer, check it as well.
342  if (SecondBuf) {
343    BufVal = state->getSVal(SecondBuf);
344    state = checkNonNull(C, state, SecondBuf, BufVal);
345    if (!state)
346      return NULL;
347
348    BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
349    if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
350      const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
351
352      SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
353                                            LastOffset, PtrTy);
354      state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
355    }
356  }
357
358  // Large enough or not, return this state!
359  return state;
360}
361
362const GRState *CStringChecker::CheckOverlap(CheckerContext &C,
363                                            const GRState *state,
364                                            const Expr *Size,
365                                            const Expr *First,
366                                            const Expr *Second) const {
367  // Do a simple check for overlap: if the two arguments are from the same
368  // buffer, see if the end of the first is greater than the start of the second
369  // or vice versa.
370
371  // If a previous check has failed, propagate the failure.
372  if (!state)
373    return NULL;
374
375  const GRState *stateTrue, *stateFalse;
376
377  // Get the buffer values and make sure they're known locations.
378  SVal firstVal = state->getSVal(First);
379  SVal secondVal = state->getSVal(Second);
380
381  Loc *firstLoc = dyn_cast<Loc>(&firstVal);
382  if (!firstLoc)
383    return state;
384
385  Loc *secondLoc = dyn_cast<Loc>(&secondVal);
386  if (!secondLoc)
387    return state;
388
389  // Are the two values the same?
390  SValBuilder &svalBuilder = C.getSValBuilder();
391  llvm::tie(stateTrue, stateFalse) =
392    state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
393
394  if (stateTrue && !stateFalse) {
395    // If the values are known to be equal, that's automatically an overlap.
396    emitOverlapBug(C, stateTrue, First, Second);
397    return NULL;
398  }
399
400  // assume the two expressions are not equal.
401  assert(stateFalse);
402  state = stateFalse;
403
404  // Which value comes first?
405  QualType cmpTy = svalBuilder.getConditionType();
406  SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
407                                         *firstLoc, *secondLoc, cmpTy);
408  DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
409  if (!reverseTest)
410    return state;
411
412  llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
413  if (stateTrue) {
414    if (stateFalse) {
415      // If we don't know which one comes first, we can't perform this test.
416      return state;
417    } else {
418      // Switch the values so that firstVal is before secondVal.
419      Loc *tmpLoc = firstLoc;
420      firstLoc = secondLoc;
421      secondLoc = tmpLoc;
422
423      // Switch the Exprs as well, so that they still correspond.
424      const Expr *tmpExpr = First;
425      First = Second;
426      Second = tmpExpr;
427    }
428  }
429
430  // Get the length, and make sure it too is known.
431  SVal LengthVal = state->getSVal(Size);
432  NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
433  if (!Length)
434    return state;
435
436  // Convert the first buffer's start address to char*.
437  // Bail out if the cast fails.
438  ASTContext &Ctx = svalBuilder.getContext();
439  QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
440  SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
441                                         First->getType());
442  Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
443  if (!FirstStartLoc)
444    return state;
445
446  // Compute the end of the first buffer. Bail out if THAT fails.
447  SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
448                                 *FirstStartLoc, *Length, CharPtrTy);
449  Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
450  if (!FirstEndLoc)
451    return state;
452
453  // Is the end of the first buffer past the start of the second buffer?
454  SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
455                                *FirstEndLoc, *secondLoc, cmpTy);
456  DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
457  if (!OverlapTest)
458    return state;
459
460  llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
461
462  if (stateTrue && !stateFalse) {
463    // Overlap!
464    emitOverlapBug(C, stateTrue, First, Second);
465    return NULL;
466  }
467
468  // assume the two expressions don't overlap.
469  assert(stateFalse);
470  return stateFalse;
471}
472
473void CStringChecker::emitOverlapBug(CheckerContext &C, const GRState *state,
474                                  const Stmt *First, const Stmt *Second) const {
475  ExplodedNode *N = C.generateSink(state);
476  if (!N)
477    return;
478
479  if (!BT_Overlap)
480    BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
481
482  // Generate a report for this bug.
483  RangedBugReport *report =
484    new RangedBugReport(*BT_Overlap,
485      "Arguments must not be overlapping buffers", N);
486  report->addRange(First->getSourceRange());
487  report->addRange(Second->getSourceRange());
488
489  C.EmitReport(report);
490}
491
492const GRState *CStringChecker::checkAdditionOverflow(CheckerContext &C,
493                                                     const GRState *state,
494                                                     NonLoc left,
495                                                     NonLoc right) const {
496  // If a previous check has failed, propagate the failure.
497  if (!state)
498    return NULL;
499
500  SValBuilder &svalBuilder = C.getSValBuilder();
501  BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
502
503  QualType sizeTy = svalBuilder.getContext().getSizeType();
504  const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
505  NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
506
507  SVal maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
508                                               sizeTy);
509
510  if (maxMinusRight.isUnknownOrUndef()) {
511    // Try switching the operands. (The order of these two assignments is
512    // important!)
513    maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
514                                            sizeTy);
515    left = right;
516  }
517
518  if (NonLoc *maxMinusRightNL = dyn_cast<NonLoc>(&maxMinusRight)) {
519    QualType cmpTy = svalBuilder.getConditionType();
520    // If left > max - right, we have an overflow.
521    SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
522                                                *maxMinusRightNL, cmpTy);
523
524    const GRState *stateOverflow, *stateOkay;
525    llvm::tie(stateOverflow, stateOkay) =
526      state->assume(cast<DefinedOrUnknownSVal>(willOverflow));
527
528    if (stateOverflow && !stateOkay) {
529      // We have an overflow. Emit a bug report.
530      ExplodedNode *N = C.generateSink(stateOverflow);
531      if (!N)
532        return NULL;
533
534      if (!BT_AdditionOverflow)
535        BT_AdditionOverflow.reset(new BuiltinBug("API",
536          "Sum of expressions causes overflow"));
537
538      // This isn't a great error message, but this should never occur in real
539      // code anyway -- you'd have to create a buffer longer than a size_t can
540      // represent, which is sort of a contradiction.
541      const char *warning =
542        "This expression will create a string whose length is too big to "
543        "be represented as a size_t";
544
545      // Generate a report for this bug.
546      BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
547      C.EmitReport(report);
548
549      return NULL;
550    }
551
552    // From now on, assume an overflow didn't occur.
553    assert(stateOkay);
554    state = stateOkay;
555  }
556
557  return state;
558}
559
560const GRState *CStringChecker::setCStringLength(const GRState *state,
561                                                const MemRegion *MR,
562                                                SVal strLength) {
563  assert(!strLength.isUndef() && "Attempt to set an undefined string length");
564
565  MR = MR->StripCasts();
566
567  switch (MR->getKind()) {
568  case MemRegion::StringRegionKind:
569    // FIXME: This can happen if we strcpy() into a string region. This is
570    // undefined [C99 6.4.5p6], but we should still warn about it.
571    return state;
572
573  case MemRegion::SymbolicRegionKind:
574  case MemRegion::AllocaRegionKind:
575  case MemRegion::VarRegionKind:
576  case MemRegion::FieldRegionKind:
577  case MemRegion::ObjCIvarRegionKind:
578    // These are the types we can currently track string lengths for.
579    break;
580
581  case MemRegion::ElementRegionKind:
582    // FIXME: Handle element regions by upper-bounding the parent region's
583    // string length.
584    return state;
585
586  default:
587    // Other regions (mostly non-data) can't have a reliable C string length.
588    // For now, just ignore the change.
589    // FIXME: These are rare but not impossible. We should output some kind of
590    // warning for things like strcpy((char[]){'a', 0}, "b");
591    return state;
592  }
593
594  if (strLength.isUnknown())
595    return state->remove<CStringLength>(MR);
596
597  return state->set<CStringLength>(MR, strLength);
598}
599
600SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
601                                               const GRState *&state,
602                                               const Expr *Ex,
603                                               const MemRegion *MR,
604                                               bool hypothetical) {
605  if (!hypothetical) {
606    // If there's a recorded length, go ahead and return it.
607    const SVal *Recorded = state->get<CStringLength>(MR);
608    if (Recorded)
609      return *Recorded;
610  }
611
612  // Otherwise, get a new symbol and update the state.
613  unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
614  SValBuilder &svalBuilder = C.getSValBuilder();
615  QualType sizeTy = svalBuilder.getContext().getSizeType();
616  SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
617                                                    MR, Ex, sizeTy, Count);
618
619  if (!hypothetical)
620    state = state->set<CStringLength>(MR, strLength);
621
622  return strLength;
623}
624
625SVal CStringChecker::getCStringLength(CheckerContext &C, const GRState *&state,
626                                      const Expr *Ex, SVal Buf,
627                                      bool hypothetical) const {
628  const MemRegion *MR = Buf.getAsRegion();
629  if (!MR) {
630    // If we can't get a region, see if it's something we /know/ isn't a
631    // C string. In the context of locations, the only time we can issue such
632    // a warning is for labels.
633    if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
634      if (ExplodedNode *N = C.generateNode(state)) {
635        if (!BT_NotCString)
636          BT_NotCString.reset(new BuiltinBug("API",
637            "Argument is not a null-terminated string."));
638
639        llvm::SmallString<120> buf;
640        llvm::raw_svector_ostream os(buf);
641        assert(CurrentFunctionDescription);
642        os << "Argument to " << CurrentFunctionDescription
643           << " is the address of the label '" << Label->getLabel()->getName()
644           << "', which is not a null-terminated string";
645
646        // Generate a report for this bug.
647        EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
648                                                          os.str(), N);
649
650        report->addRange(Ex->getSourceRange());
651        C.EmitReport(report);
652      }
653
654      return UndefinedVal();
655    }
656
657    // If it's not a region and not a label, give up.
658    return UnknownVal();
659  }
660
661  // If we have a region, strip casts from it and see if we can figure out
662  // its length. For anything we can't figure out, just return UnknownVal.
663  MR = MR->StripCasts();
664
665  switch (MR->getKind()) {
666  case MemRegion::StringRegionKind: {
667    // Modifying the contents of string regions is undefined [C99 6.4.5p6],
668    // so we can assume that the byte length is the correct C string length.
669    SValBuilder &svalBuilder = C.getSValBuilder();
670    QualType sizeTy = svalBuilder.getContext().getSizeType();
671    const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
672    return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
673  }
674  case MemRegion::SymbolicRegionKind:
675  case MemRegion::AllocaRegionKind:
676  case MemRegion::VarRegionKind:
677  case MemRegion::FieldRegionKind:
678  case MemRegion::ObjCIvarRegionKind:
679    return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
680  case MemRegion::CompoundLiteralRegionKind:
681    // FIXME: Can we track this? Is it necessary?
682    return UnknownVal();
683  case MemRegion::ElementRegionKind:
684    // FIXME: How can we handle this? It's not good enough to subtract the
685    // offset from the base string length; consider "123\x00567" and &a[5].
686    return UnknownVal();
687  default:
688    // Other regions (mostly non-data) can't have a reliable C string length.
689    // In this case, an error is emitted and UndefinedVal is returned.
690    // The caller should always be prepared to handle this case.
691    if (ExplodedNode *N = C.generateNode(state)) {
692      if (!BT_NotCString)
693        BT_NotCString.reset(new BuiltinBug("API",
694          "Argument is not a null-terminated string."));
695
696      llvm::SmallString<120> buf;
697      llvm::raw_svector_ostream os(buf);
698
699      assert(CurrentFunctionDescription);
700      os << "Argument to " << CurrentFunctionDescription << " is ";
701
702      if (SummarizeRegion(os, C.getASTContext(), MR))
703        os << ", which is not a null-terminated string";
704      else
705        os << "not a null-terminated string";
706
707      // Generate a report for this bug.
708      EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
709                                                        os.str(), N);
710
711      report->addRange(Ex->getSourceRange());
712      C.EmitReport(report);
713    }
714
715    return UndefinedVal();
716  }
717}
718
719const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
720  const GRState *&state, const Expr *expr, SVal val) const {
721
722  // Get the memory region pointed to by the val.
723  const MemRegion *bufRegion = val.getAsRegion();
724  if (!bufRegion)
725    return NULL;
726
727  // Strip casts off the memory region.
728  bufRegion = bufRegion->StripCasts();
729
730  // Cast the memory region to a string region.
731  const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
732  if (!strRegion)
733    return NULL;
734
735  // Return the actual string in the string region.
736  return strRegion->getStringLiteral();
737}
738
739const GRState *CStringChecker::InvalidateBuffer(CheckerContext &C,
740                                                const GRState *state,
741                                                const Expr *E, SVal V) {
742  Loc *L = dyn_cast<Loc>(&V);
743  if (!L)
744    return state;
745
746  // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
747  // some assumptions about the value that CFRefCount can't. Even so, it should
748  // probably be refactored.
749  if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
750    const MemRegion *R = MR->getRegion()->StripCasts();
751
752    // Are we dealing with an ElementRegion?  If so, we should be invalidating
753    // the super-region.
754    if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
755      R = ER->getSuperRegion();
756      // FIXME: What about layers of ElementRegions?
757    }
758
759    // Invalidate this region.
760    unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
761    return state->invalidateRegion(R, E, Count, NULL);
762  }
763
764  // If we have a non-region value by chance, just remove the binding.
765  // FIXME: is this necessary or correct? This handles the non-Region
766  //  cases.  Is it ever valid to store to these?
767  return state->unbindLoc(*L);
768}
769
770bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
771                                     const MemRegion *MR) {
772  const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
773
774  switch (MR->getKind()) {
775  case MemRegion::FunctionTextRegionKind: {
776    const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
777    if (FD)
778      os << "the address of the function '" << FD << "'";
779    else
780      os << "the address of a function";
781    return true;
782  }
783  case MemRegion::BlockTextRegionKind:
784    os << "block text";
785    return true;
786  case MemRegion::BlockDataRegionKind:
787    os << "a block";
788    return true;
789  case MemRegion::CXXThisRegionKind:
790  case MemRegion::CXXTempObjectRegionKind:
791    os << "a C++ temp object of type " << TVR->getValueType().getAsString();
792    return true;
793  case MemRegion::VarRegionKind:
794    os << "a variable of type" << TVR->getValueType().getAsString();
795    return true;
796  case MemRegion::FieldRegionKind:
797    os << "a field of type " << TVR->getValueType().getAsString();
798    return true;
799  case MemRegion::ObjCIvarRegionKind:
800    os << "an instance variable of type " << TVR->getValueType().getAsString();
801    return true;
802  default:
803    return false;
804  }
805}
806
807//===----------------------------------------------------------------------===//
808// evaluation of individual function calls.
809//===----------------------------------------------------------------------===//
810
811void CStringChecker::evalCopyCommon(CheckerContext &C,
812                                    const CallExpr *CE,
813                                    const GRState *state,
814                                    const Expr *Size, const Expr *Dest,
815                                    const Expr *Source, bool Restricted,
816                                    bool IsMempcpy) const {
817  CurrentFunctionDescription = "memory copy function";
818
819  // See if the size argument is zero.
820  SVal sizeVal = state->getSVal(Size);
821  QualType sizeTy = Size->getType();
822
823  const GRState *stateZeroSize, *stateNonZeroSize;
824  llvm::tie(stateZeroSize, stateNonZeroSize) =
825    assumeZero(C, state, sizeVal, sizeTy);
826
827  // Get the value of the Dest.
828  SVal destVal = state->getSVal(Dest);
829
830  // If the size is zero, there won't be any actual memory access, so
831  // just bind the return value to the destination buffer and return.
832  if (stateZeroSize) {
833    stateZeroSize = stateZeroSize->BindExpr(CE, destVal);
834    C.addTransition(stateZeroSize);
835  }
836
837  // If the size can be nonzero, we have to check the other arguments.
838  if (stateNonZeroSize) {
839    state = stateNonZeroSize;
840
841    // Ensure the destination is not null. If it is NULL there will be a
842    // NULL pointer dereference.
843    state = checkNonNull(C, state, Dest, destVal);
844    if (!state)
845      return;
846
847    // Get the value of the Src.
848    SVal srcVal = state->getSVal(Source);
849
850    // Ensure the source is not null. If it is NULL there will be a
851    // NULL pointer dereference.
852    state = checkNonNull(C, state, Source, srcVal);
853    if (!state)
854      return;
855
856    // Ensure the accesses are valid and that the buffers do not overlap.
857    const char * const writeWarning =
858      "Memory copy function overflows destination buffer";
859    state = CheckBufferAccess(C, state, Size, Dest, Source,
860                              writeWarning, /* sourceWarning = */ NULL);
861    if (Restricted)
862      state = CheckOverlap(C, state, Size, Dest, Source);
863
864    if (!state)
865      return;
866
867    // If this is mempcpy, get the byte after the last byte copied and
868    // bind the expr.
869    if (IsMempcpy) {
870      loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
871      assert(destRegVal && "Destination should be a known MemRegionVal here");
872
873      // Get the length to copy.
874      NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&sizeVal);
875
876      if (lenValNonLoc) {
877        // Get the byte after the last byte copied.
878        SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
879                                                          *destRegVal,
880                                                          *lenValNonLoc,
881                                                          Dest->getType());
882
883        // The byte after the last byte copied is the return value.
884        state = state->BindExpr(CE, lastElement);
885      } else {
886        // If we don't know how much we copied, we can at least
887        // conjure a return value for later.
888        unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
889        SVal result =
890          C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
891        state = state->BindExpr(CE, result);
892      }
893
894    } else {
895      // All other copies return the destination buffer.
896      // (Well, bcopy() has a void return type, but this won't hurt.)
897      state = state->BindExpr(CE, destVal);
898    }
899
900    // Invalidate the destination.
901    // FIXME: Even if we can't perfectly model the copy, we should see if we
902    // can use LazyCompoundVals to copy the source values into the destination.
903    // This would probably remove any existing bindings past the end of the
904    // copied region, but that's still an improvement over blank invalidation.
905    state = InvalidateBuffer(C, state, Dest, state->getSVal(Dest));
906    C.addTransition(state);
907  }
908}
909
910
911void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
912  // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
913  // The return value is the address of the destination buffer.
914  const Expr *Dest = CE->getArg(0);
915  const GRState *state = C.getState();
916
917  evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
918}
919
920void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
921  // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
922  // The return value is a pointer to the byte following the last written byte.
923  const Expr *Dest = CE->getArg(0);
924  const GRState *state = C.getState();
925
926  evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
927}
928
929void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
930  // void *memmove(void *dst, const void *src, size_t n);
931  // The return value is the address of the destination buffer.
932  const Expr *Dest = CE->getArg(0);
933  const GRState *state = C.getState();
934
935  evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
936}
937
938void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
939  // void bcopy(const void *src, void *dst, size_t n);
940  evalCopyCommon(C, CE, C.getState(),
941                 CE->getArg(2), CE->getArg(1), CE->getArg(0));
942}
943
944void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
945  // int memcmp(const void *s1, const void *s2, size_t n);
946  CurrentFunctionDescription = "memory comparison function";
947
948  const Expr *Left = CE->getArg(0);
949  const Expr *Right = CE->getArg(1);
950  const Expr *Size = CE->getArg(2);
951
952  const GRState *state = C.getState();
953  SValBuilder &svalBuilder = C.getSValBuilder();
954
955  // See if the size argument is zero.
956  SVal sizeVal = state->getSVal(Size);
957  QualType sizeTy = Size->getType();
958
959  const GRState *stateZeroSize, *stateNonZeroSize;
960  llvm::tie(stateZeroSize, stateNonZeroSize) =
961    assumeZero(C, state, sizeVal, sizeTy);
962
963  // If the size can be zero, the result will be 0 in that case, and we don't
964  // have to check either of the buffers.
965  if (stateZeroSize) {
966    state = stateZeroSize;
967    state = state->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
968    C.addTransition(state);
969  }
970
971  // If the size can be nonzero, we have to check the other arguments.
972  if (stateNonZeroSize) {
973    state = stateNonZeroSize;
974    // If we know the two buffers are the same, we know the result is 0.
975    // First, get the two buffers' addresses. Another checker will have already
976    // made sure they're not undefined.
977    DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(state->getSVal(Left));
978    DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(state->getSVal(Right));
979
980    // See if they are the same.
981    DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
982    const GRState *StSameBuf, *StNotSameBuf;
983    llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
984
985    // If the two arguments might be the same buffer, we know the result is 0,
986    // and we only need to check one size.
987    if (StSameBuf) {
988      state = StSameBuf;
989      state = CheckBufferAccess(C, state, Size, Left);
990      if (state) {
991        state = StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
992        C.addTransition(state);
993      }
994    }
995
996    // If the two arguments might be different buffers, we have to check the
997    // size of both of them.
998    if (StNotSameBuf) {
999      state = StNotSameBuf;
1000      state = CheckBufferAccess(C, state, Size, Left, Right);
1001      if (state) {
1002        // The return value is the comparison result, which we don't know.
1003        unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
1004        SVal CmpV = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
1005        state = state->BindExpr(CE, CmpV);
1006        C.addTransition(state);
1007      }
1008    }
1009  }
1010}
1011
1012void CStringChecker::evalstrLength(CheckerContext &C,
1013                                   const CallExpr *CE) const {
1014  // size_t strlen(const char *s);
1015  evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1016}
1017
1018void CStringChecker::evalstrnLength(CheckerContext &C,
1019                                    const CallExpr *CE) const {
1020  // size_t strnlen(const char *s, size_t maxlen);
1021  evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1022}
1023
1024void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
1025                                         bool IsStrnlen) const {
1026  CurrentFunctionDescription = "string length function";
1027  const GRState *state = C.getState();
1028
1029  if (IsStrnlen) {
1030    const Expr *maxlenExpr = CE->getArg(1);
1031    SVal maxlenVal = state->getSVal(maxlenExpr);
1032
1033    const GRState *stateZeroSize, *stateNonZeroSize;
1034    llvm::tie(stateZeroSize, stateNonZeroSize) =
1035      assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1036
1037    // If the size can be zero, the result will be 0 in that case, and we don't
1038    // have to check the string itself.
1039    if (stateZeroSize) {
1040      SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
1041      stateZeroSize = stateZeroSize->BindExpr(CE, zero);
1042      C.addTransition(stateZeroSize);
1043    }
1044
1045    // If the size is GUARANTEED to be zero, we're done!
1046    if (!stateNonZeroSize)
1047      return;
1048
1049    // Otherwise, record the assumption that the size is nonzero.
1050    state = stateNonZeroSize;
1051  }
1052
1053  // Check that the string argument is non-null.
1054  const Expr *Arg = CE->getArg(0);
1055  SVal ArgVal = state->getSVal(Arg);
1056
1057  state = checkNonNull(C, state, Arg, ArgVal);
1058
1059  if (!state)
1060    return;
1061
1062  SVal strLength = getCStringLength(C, state, Arg, ArgVal);
1063
1064  // If the argument isn't a valid C string, there's no valid state to
1065  // transition to.
1066  if (strLength.isUndef())
1067    return;
1068
1069  DefinedOrUnknownSVal result = UnknownVal();
1070
1071  // If the check is for strnlen() then bind the return value to no more than
1072  // the maxlen value.
1073  if (IsStrnlen) {
1074    QualType cmpTy = C.getSValBuilder().getConditionType();
1075
1076    // It's a little unfortunate to be getting this again,
1077    // but it's not that expensive...
1078    const Expr *maxlenExpr = CE->getArg(1);
1079    SVal maxlenVal = state->getSVal(maxlenExpr);
1080
1081    NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1082    NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
1083
1084    if (strLengthNL && maxlenValNL) {
1085      const GRState *stateStringTooLong, *stateStringNotTooLong;
1086
1087      // Check if the strLength is greater than the maxlen.
1088      llvm::tie(stateStringTooLong, stateStringNotTooLong) =
1089        state->assume(cast<DefinedOrUnknownSVal>
1090                      (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1091                                                      *strLengthNL,
1092                                                      *maxlenValNL,
1093                                                      cmpTy)));
1094
1095      if (stateStringTooLong && !stateStringNotTooLong) {
1096        // If the string is longer than maxlen, return maxlen.
1097        result = *maxlenValNL;
1098      } else if (stateStringNotTooLong && !stateStringTooLong) {
1099        // If the string is shorter than maxlen, return its length.
1100        result = *strLengthNL;
1101      }
1102    }
1103
1104    if (result.isUnknown()) {
1105      // If we don't have enough information for a comparison, there's
1106      // no guarantee the full string length will actually be returned.
1107      // All we know is the return value is the min of the string length
1108      // and the limit. This is better than nothing.
1109      unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
1110      result = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
1111      NonLoc *resultNL = cast<NonLoc>(&result);
1112
1113      if (strLengthNL) {
1114        state = state->assume(cast<DefinedOrUnknownSVal>
1115                              (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1116                                                              *resultNL,
1117                                                              *strLengthNL,
1118                                                              cmpTy)), true);
1119      }
1120
1121      if (maxlenValNL) {
1122        state = state->assume(cast<DefinedOrUnknownSVal>
1123                              (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1124                                                              *resultNL,
1125                                                              *maxlenValNL,
1126                                                              cmpTy)), true);
1127      }
1128    }
1129
1130  } else {
1131    // This is a plain strlen(), not strnlen().
1132    result = cast<DefinedOrUnknownSVal>(strLength);
1133
1134    // If we don't know the length of the string, conjure a return
1135    // value, so it can be used in constraints, at least.
1136    if (result.isUnknown()) {
1137      unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
1138      result = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
1139    }
1140  }
1141
1142  // Bind the return value.
1143  assert(!result.isUnknown() && "Should have conjured a value by now");
1144  state = state->BindExpr(CE, result);
1145  C.addTransition(state);
1146}
1147
1148void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
1149  // char *strcpy(char *restrict dst, const char *restrict src);
1150  evalStrcpyCommon(C, CE,
1151                   /* returnEnd = */ false,
1152                   /* isBounded = */ false,
1153                   /* isAppending = */ false);
1154}
1155
1156void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
1157  // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
1158  evalStrcpyCommon(C, CE,
1159                   /* returnEnd = */ false,
1160                   /* isBounded = */ true,
1161                   /* isAppending = */ false);
1162}
1163
1164void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
1165  // char *stpcpy(char *restrict dst, const char *restrict src);
1166  evalStrcpyCommon(C, CE,
1167                   /* returnEnd = */ true,
1168                   /* isBounded = */ false,
1169                   /* isAppending = */ false);
1170}
1171
1172void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
1173  //char *strcat(char *restrict s1, const char *restrict s2);
1174  evalStrcpyCommon(C, CE,
1175                   /* returnEnd = */ false,
1176                   /* isBounded = */ false,
1177                   /* isAppending = */ true);
1178}
1179
1180void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
1181  //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1182  evalStrcpyCommon(C, CE,
1183                   /* returnEnd = */ false,
1184                   /* isBounded = */ true,
1185                   /* isAppending = */ true);
1186}
1187
1188void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
1189                                      bool returnEnd, bool isBounded,
1190                                      bool isAppending) const {
1191  CurrentFunctionDescription = "string copy function";
1192  const GRState *state = C.getState();
1193
1194  // Check that the destination is non-null.
1195  const Expr *Dst = CE->getArg(0);
1196  SVal DstVal = state->getSVal(Dst);
1197
1198  state = checkNonNull(C, state, Dst, DstVal);
1199  if (!state)
1200    return;
1201
1202  // Check that the source is non-null.
1203  const Expr *srcExpr = CE->getArg(1);
1204  SVal srcVal = state->getSVal(srcExpr);
1205  state = checkNonNull(C, state, srcExpr, srcVal);
1206  if (!state)
1207    return;
1208
1209  // Get the string length of the source.
1210  SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
1211
1212  // If the source isn't a valid C string, give up.
1213  if (strLength.isUndef())
1214    return;
1215
1216  SValBuilder &svalBuilder = C.getSValBuilder();
1217  QualType cmpTy = svalBuilder.getConditionType();
1218  QualType sizeTy = svalBuilder.getContext().getSizeType();
1219
1220  // These two values allow checking two kinds of errors:
1221  // - actual overflows caused by a source that doesn't fit in the destination
1222  // - potential overflows caused by a bound that could exceed the destination
1223  SVal amountCopied = UnknownVal();
1224  SVal maxLastElementIndex = UnknownVal();
1225  const char *boundWarning = NULL;
1226
1227  // If the function is strncpy, strncat, etc... it is bounded.
1228  if (isBounded) {
1229    // Get the max number of characters to copy.
1230    const Expr *lenExpr = CE->getArg(2);
1231    SVal lenVal = state->getSVal(lenExpr);
1232
1233    // Protect against misdeclared strncpy().
1234    lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
1235
1236    NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1237    NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1238
1239    // If we know both values, we might be able to figure out how much
1240    // we're copying.
1241    if (strLengthNL && lenValNL) {
1242      const GRState *stateSourceTooLong, *stateSourceNotTooLong;
1243
1244      // Check if the max number to copy is less than the length of the src.
1245      // If the bound is equal to the source length, strncpy won't null-
1246      // terminate the result!
1247      llvm::tie(stateSourceTooLong, stateSourceNotTooLong) =
1248        state->assume(cast<DefinedOrUnknownSVal>
1249                      (svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL,
1250                                               *lenValNL, cmpTy)));
1251
1252      if (stateSourceTooLong && !stateSourceNotTooLong) {
1253        // Max number to copy is less than the length of the src, so the actual
1254        // strLength copied is the max number arg.
1255        state = stateSourceTooLong;
1256        amountCopied = lenVal;
1257
1258      } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1259        // The source buffer entirely fits in the bound.
1260        state = stateSourceNotTooLong;
1261        amountCopied = strLength;
1262      }
1263    }
1264
1265    // We still want to know if the bound is known to be too large.
1266    if (lenValNL) {
1267      if (isAppending) {
1268        // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1269
1270        // Get the string length of the destination. If the destination is
1271        // memory that can't have a string length, we shouldn't be copying
1272        // into it anyway.
1273        SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1274        if (dstStrLength.isUndef())
1275          return;
1276
1277        if (NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength)) {
1278          maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1279                                                        *lenValNL,
1280                                                        *dstStrLengthNL,
1281                                                        sizeTy);
1282          boundWarning = "Size argument is greater than the free space in the "
1283                         "destination buffer";
1284        }
1285
1286      } else {
1287        // For strncpy, this is just checking that lenVal <= sizeof(dst)
1288        // (Yes, strncpy and strncat differ in how they treat termination.
1289        // strncat ALWAYS terminates, but strncpy doesn't.)
1290        NonLoc one = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
1291        maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1292                                                      one, sizeTy);
1293        boundWarning = "Size argument is greater than the length of the "
1294                       "destination buffer";
1295      }
1296    }
1297
1298    // If we couldn't pin down the copy length, at least bound it.
1299    // FIXME: We should actually run this code path for append as well, but
1300    // right now it creates problems with constraints (since we can end up
1301    // trying to pass constraints from symbol to symbol).
1302    if (amountCopied.isUnknown() && !isAppending) {
1303      // Try to get a "hypothetical" string length symbol, which we can later
1304      // set as a real value if that turns out to be the case.
1305      amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1306      assert(!amountCopied.isUndef());
1307
1308      if (NonLoc *amountCopiedNL = dyn_cast<NonLoc>(&amountCopied)) {
1309        if (lenValNL) {
1310          // amountCopied <= lenVal
1311          SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1312                                                             *amountCopiedNL,
1313                                                             *lenValNL,
1314                                                             cmpTy);
1315          state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanBound),
1316                                true);
1317          if (!state)
1318            return;
1319        }
1320
1321        if (strLengthNL) {
1322          // amountCopied <= strlen(source)
1323          SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1324                                                           *amountCopiedNL,
1325                                                           *strLengthNL,
1326                                                           cmpTy);
1327          state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanSrc),
1328                                true);
1329          if (!state)
1330            return;
1331        }
1332      }
1333    }
1334
1335  } else {
1336    // The function isn't bounded. The amount copied should match the length
1337    // of the source buffer.
1338    amountCopied = strLength;
1339  }
1340
1341  assert(state);
1342
1343  // This represents the number of characters copied into the destination
1344  // buffer. (It may not actually be the strlen if the destination buffer
1345  // is not terminated.)
1346  SVal finalStrLength = UnknownVal();
1347
1348  // If this is an appending function (strcat, strncat...) then set the
1349  // string length to strlen(src) + strlen(dst) since the buffer will
1350  // ultimately contain both.
1351  if (isAppending) {
1352    // Get the string length of the destination. If the destination is memory
1353    // that can't have a string length, we shouldn't be copying into it anyway.
1354    SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1355    if (dstStrLength.isUndef())
1356      return;
1357
1358    NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&amountCopied);
1359    NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1360
1361    // If we know both string lengths, we might know the final string length.
1362    if (srcStrLengthNL && dstStrLengthNL) {
1363      // Make sure the two lengths together don't overflow a size_t.
1364      state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1365      if (!state)
1366        return;
1367
1368      finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1369                                               *dstStrLengthNL, sizeTy);
1370    }
1371
1372    // If we couldn't get a single value for the final string length,
1373    // we can at least bound it by the individual lengths.
1374    if (finalStrLength.isUnknown()) {
1375      // Try to get a "hypothetical" string length symbol, which we can later
1376      // set as a real value if that turns out to be the case.
1377      finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1378      assert(!finalStrLength.isUndef());
1379
1380      if (NonLoc *finalStrLengthNL = dyn_cast<NonLoc>(&finalStrLength)) {
1381        if (srcStrLengthNL) {
1382          // finalStrLength >= srcStrLength
1383          SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1384                                                        *finalStrLengthNL,
1385                                                        *srcStrLengthNL,
1386                                                        cmpTy);
1387          state = state->assume(cast<DefinedOrUnknownSVal>(sourceInResult),
1388                                true);
1389          if (!state)
1390            return;
1391        }
1392
1393        if (dstStrLengthNL) {
1394          // finalStrLength >= dstStrLength
1395          SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1396                                                      *finalStrLengthNL,
1397                                                      *dstStrLengthNL,
1398                                                      cmpTy);
1399          state = state->assume(cast<DefinedOrUnknownSVal>(destInResult),
1400                                true);
1401          if (!state)
1402            return;
1403        }
1404      }
1405    }
1406
1407  } else {
1408    // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1409    // the final string length will match the input string length.
1410    finalStrLength = amountCopied;
1411  }
1412
1413  // The final result of the function will either be a pointer past the last
1414  // copied element, or a pointer to the start of the destination buffer.
1415  SVal Result = (returnEnd ? UnknownVal() : DstVal);
1416
1417  assert(state);
1418
1419  // If the destination is a MemRegion, try to check for a buffer overflow and
1420  // record the new string length.
1421  if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
1422    QualType ptrTy = Dst->getType();
1423
1424    // If we have an exact value on a bounded copy, use that to check for
1425    // overflows, rather than our estimate about how much is actually copied.
1426    if (boundWarning) {
1427      if (NonLoc *maxLastNL = dyn_cast<NonLoc>(&maxLastElementIndex)) {
1428        SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1429                                                      *maxLastNL, ptrTy);
1430        state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1431                              boundWarning);
1432        if (!state)
1433          return;
1434      }
1435    }
1436
1437    // Then, if the final length is known...
1438    if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&finalStrLength)) {
1439      SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1440                                                 *knownStrLength, ptrTy);
1441
1442      // ...and we haven't checked the bound, we'll check the actual copy.
1443      if (!boundWarning) {
1444        const char * const warningMsg =
1445          "String copy function overflows destination buffer";
1446        state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1447        if (!state)
1448          return;
1449      }
1450
1451      // If this is a stpcpy-style copy, the last element is the return value.
1452      if (returnEnd)
1453        Result = lastElement;
1454    }
1455
1456    // Invalidate the destination. This must happen before we set the C string
1457    // length because invalidation will clear the length.
1458    // FIXME: Even if we can't perfectly model the copy, we should see if we
1459    // can use LazyCompoundVals to copy the source values into the destination.
1460    // This would probably remove any existing bindings past the end of the
1461    // string, but that's still an improvement over blank invalidation.
1462    state = InvalidateBuffer(C, state, Dst, *dstRegVal);
1463
1464    // Set the C string length of the destination, if we know it.
1465    if (isBounded && !isAppending) {
1466      // strncpy is annoying in that it doesn't guarantee to null-terminate
1467      // the result string. If the original string didn't fit entirely inside
1468      // the bound (including the null-terminator), we don't know how long the
1469      // result is.
1470      if (amountCopied != strLength)
1471        finalStrLength = UnknownVal();
1472    }
1473    state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
1474  }
1475
1476  assert(state);
1477
1478  // If this is a stpcpy-style copy, but we were unable to check for a buffer
1479  // overflow, we still need a result. Conjure a return value.
1480  if (returnEnd && Result.isUnknown()) {
1481    unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
1482    Result = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
1483  }
1484
1485  // Set the return value.
1486  state = state->BindExpr(CE, Result);
1487  C.addTransition(state);
1488}
1489
1490void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1491  //int strcmp(const char *s1, const char *s2);
1492  evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
1493}
1494
1495void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
1496  //int strncmp(const char *s1, const char *s2, size_t n);
1497  evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1498}
1499
1500void CStringChecker::evalStrcasecmp(CheckerContext &C,
1501                                    const CallExpr *CE) const {
1502  //int strcasecmp(const char *s1, const char *s2);
1503  evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
1504}
1505
1506void CStringChecker::evalStrncasecmp(CheckerContext &C,
1507                                     const CallExpr *CE) const {
1508  //int strncasecmp(const char *s1, const char *s2, size_t n);
1509  evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1510}
1511
1512void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
1513                                      bool isBounded, bool ignoreCase) const {
1514  CurrentFunctionDescription = "string comparison function";
1515  const GRState *state = C.getState();
1516
1517  // Check that the first string is non-null
1518  const Expr *s1 = CE->getArg(0);
1519  SVal s1Val = state->getSVal(s1);
1520  state = checkNonNull(C, state, s1, s1Val);
1521  if (!state)
1522    return;
1523
1524  // Check that the second string is non-null.
1525  const Expr *s2 = CE->getArg(1);
1526  SVal s2Val = state->getSVal(s2);
1527  state = checkNonNull(C, state, s2, s2Val);
1528  if (!state)
1529    return;
1530
1531  // Get the string length of the first string or give up.
1532  SVal s1Length = getCStringLength(C, state, s1, s1Val);
1533  if (s1Length.isUndef())
1534    return;
1535
1536  // Get the string length of the second string or give up.
1537  SVal s2Length = getCStringLength(C, state, s2, s2Val);
1538  if (s2Length.isUndef())
1539    return;
1540
1541  // If we know the two buffers are the same, we know the result is 0.
1542  // First, get the two buffers' addresses. Another checker will have already
1543  // made sure they're not undefined.
1544  DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(s1Val);
1545  DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(s2Val);
1546
1547  // See if they are the same.
1548  SValBuilder &svalBuilder = C.getSValBuilder();
1549  DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1550  const GRState *StSameBuf, *StNotSameBuf;
1551  llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1552
1553  // If the two arguments might be the same buffer, we know the result is 0,
1554  // and we only need to check one size.
1555  if (StSameBuf) {
1556    StSameBuf = StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
1557    C.addTransition(StSameBuf);
1558
1559    // If the two arguments are GUARANTEED to be the same, we're done!
1560    if (!StNotSameBuf)
1561      return;
1562  }
1563
1564  assert(StNotSameBuf);
1565  state = StNotSameBuf;
1566
1567  // At this point we can go about comparing the two buffers.
1568  // For now, we only do this if they're both known string literals.
1569
1570  // Attempt to extract string literals from both expressions.
1571  const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1572  const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1573  bool canComputeResult = false;
1574
1575  if (s1StrLiteral && s2StrLiteral) {
1576    StringRef s1StrRef = s1StrLiteral->getString();
1577    StringRef s2StrRef = s2StrLiteral->getString();
1578
1579    if (isBounded) {
1580      // Get the max number of characters to compare.
1581      const Expr *lenExpr = CE->getArg(2);
1582      SVal lenVal = state->getSVal(lenExpr);
1583
1584      // If the length is known, we can get the right substrings.
1585      if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1586        // Create substrings of each to compare the prefix.
1587        s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1588        s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1589        canComputeResult = true;
1590      }
1591    } else {
1592      // This is a normal, unbounded strcmp.
1593      canComputeResult = true;
1594    }
1595
1596    if (canComputeResult) {
1597      // Real strcmp stops at null characters.
1598      size_t s1Term = s1StrRef.find('\0');
1599      if (s1Term != StringRef::npos)
1600        s1StrRef = s1StrRef.substr(0, s1Term);
1601
1602      size_t s2Term = s2StrRef.find('\0');
1603      if (s2Term != StringRef::npos)
1604        s2StrRef = s2StrRef.substr(0, s2Term);
1605
1606      // Use StringRef's comparison methods to compute the actual result.
1607      int result;
1608
1609      if (ignoreCase) {
1610        // Compare string 1 to string 2 the same way strcasecmp() does.
1611        result = s1StrRef.compare_lower(s2StrRef);
1612      } else {
1613        // Compare string 1 to string 2 the same way strcmp() does.
1614        result = s1StrRef.compare(s2StrRef);
1615      }
1616
1617      // Build the SVal of the comparison and bind the return value.
1618      SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
1619      state = state->BindExpr(CE, resultVal);
1620    }
1621  }
1622
1623  if (!canComputeResult) {
1624    // Conjure a symbolic value. It's the best we can do.
1625    unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
1626    SVal resultVal = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
1627    state = state->BindExpr(CE, resultVal);
1628  }
1629
1630  // Record this as a possible path.
1631  C.addTransition(state);
1632}
1633
1634//===----------------------------------------------------------------------===//
1635// The driver method, and other Checker callbacks.
1636//===----------------------------------------------------------------------===//
1637
1638bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
1639  // Get the callee.  All the functions we care about are C functions
1640  // with simple identifiers.
1641  const GRState *state = C.getState();
1642  const Expr *Callee = CE->getCallee();
1643  const FunctionDecl *FD = state->getSVal(Callee).getAsFunctionDecl();
1644
1645  if (!FD)
1646    return false;
1647
1648  // Get the name of the callee. If it's a builtin, strip off the prefix.
1649  IdentifierInfo *II = FD->getIdentifier();
1650  if (!II)   // if no identifier, not a simple C function
1651    return false;
1652  StringRef Name = II->getName();
1653  if (Name.startswith("__builtin_"))
1654    Name = Name.substr(10);
1655
1656  FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
1657    .Cases("memcpy", "__memcpy_chk", &CStringChecker::evalMemcpy)
1658    .Cases("mempcpy", "__mempcpy_chk", &CStringChecker::evalMempcpy)
1659    .Cases("memcmp", "bcmp", &CStringChecker::evalMemcmp)
1660    .Cases("memmove", "__memmove_chk", &CStringChecker::evalMemmove)
1661    .Cases("strcpy", "__strcpy_chk", &CStringChecker::evalStrcpy)
1662    .Cases("strncpy", "__strncpy_chk", &CStringChecker::evalStrncpy)
1663    .Cases("stpcpy", "__stpcpy_chk", &CStringChecker::evalStpcpy)
1664    .Cases("strcat", "__strcat_chk", &CStringChecker::evalStrcat)
1665    .Cases("strncat", "__strncat_chk", &CStringChecker::evalStrncat)
1666    .Case("strlen", &CStringChecker::evalstrLength)
1667    .Case("strnlen", &CStringChecker::evalstrnLength)
1668    .Case("strcmp", &CStringChecker::evalStrcmp)
1669    .Case("strncmp", &CStringChecker::evalStrncmp)
1670    .Case("strcasecmp", &CStringChecker::evalStrcasecmp)
1671    .Case("strncasecmp", &CStringChecker::evalStrncasecmp)
1672    .Case("bcopy", &CStringChecker::evalBcopy)
1673    .Default(NULL);
1674
1675  // If the callee isn't a string function, let another checker handle it.
1676  if (!evalFunction)
1677    return false;
1678
1679  // Make sure each function sets its own description.
1680  // (But don't bother in a release build.)
1681  assert(!(CurrentFunctionDescription = NULL));
1682
1683  // Check and evaluate the call.
1684  (this->*evalFunction)(C, CE);
1685  return true;
1686}
1687
1688void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
1689  // Record string length for char a[] = "abc";
1690  const GRState *state = C.getState();
1691
1692  for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1693       I != E; ++I) {
1694    const VarDecl *D = dyn_cast<VarDecl>(*I);
1695    if (!D)
1696      continue;
1697
1698    // FIXME: Handle array fields of structs.
1699    if (!D->getType()->isArrayType())
1700      continue;
1701
1702    const Expr *Init = D->getInit();
1703    if (!Init)
1704      continue;
1705    if (!isa<StringLiteral>(Init))
1706      continue;
1707
1708    Loc VarLoc = state->getLValue(D, C.getPredecessor()->getLocationContext());
1709    const MemRegion *MR = VarLoc.getAsRegion();
1710    if (!MR)
1711      continue;
1712
1713    SVal StrVal = state->getSVal(Init);
1714    assert(StrVal.isValid() && "Initializer string is unknown or undefined");
1715    DefinedOrUnknownSVal strLength
1716      = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
1717
1718    state = state->set<CStringLength>(MR, strLength);
1719  }
1720
1721  C.addTransition(state);
1722}
1723
1724bool CStringChecker::wantsRegionChangeUpdate(const GRState *state) const {
1725  CStringLength::EntryMap Entries = state->get<CStringLength>();
1726  return !Entries.isEmpty();
1727}
1728
1729const GRState *
1730CStringChecker::checkRegionChanges(const GRState *state,
1731                                   const StoreManager::InvalidatedSymbols *,
1732                                   const MemRegion * const *Begin,
1733                                   const MemRegion * const *End) const {
1734  CStringLength::EntryMap Entries = state->get<CStringLength>();
1735  if (Entries.isEmpty())
1736    return state;
1737
1738  llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1739  llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1740
1741  // First build sets for the changed regions and their super-regions.
1742  for ( ; Begin != End; ++Begin) {
1743    const MemRegion *MR = *Begin;
1744    Invalidated.insert(MR);
1745
1746    SuperRegions.insert(MR);
1747    while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1748      MR = SR->getSuperRegion();
1749      SuperRegions.insert(MR);
1750    }
1751  }
1752
1753  CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1754
1755  // Then loop over the entries in the current state.
1756  for (CStringLength::EntryMap::iterator I = Entries.begin(),
1757       E = Entries.end(); I != E; ++I) {
1758    const MemRegion *MR = I.getKey();
1759
1760    // Is this entry for a super-region of a changed region?
1761    if (SuperRegions.count(MR)) {
1762      Entries = F.remove(Entries, MR);
1763      continue;
1764    }
1765
1766    // Is this entry for a sub-region of a changed region?
1767    const MemRegion *Super = MR;
1768    while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1769      Super = SR->getSuperRegion();
1770      if (Invalidated.count(Super)) {
1771        Entries = F.remove(Entries, MR);
1772        break;
1773      }
1774    }
1775  }
1776
1777  return state->set<CStringLength>(Entries);
1778}
1779
1780void CStringChecker::checkLiveSymbols(const GRState *state,
1781                                      SymbolReaper &SR) const {
1782  // Mark all symbols in our string length map as valid.
1783  CStringLength::EntryMap Entries = state->get<CStringLength>();
1784
1785  for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1786       I != E; ++I) {
1787    SVal Len = I.getData();
1788
1789    for (SVal::symbol_iterator si = Len.symbol_begin(), se = Len.symbol_end();
1790         si != se; ++si)
1791      SR.markInUse(*si);
1792  }
1793}
1794
1795void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1796                                      CheckerContext &C) const {
1797  if (!SR.hasDeadSymbols())
1798    return;
1799
1800  const GRState *state = C.getState();
1801  CStringLength::EntryMap Entries = state->get<CStringLength>();
1802  if (Entries.isEmpty())
1803    return;
1804
1805  CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1806  for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1807       I != E; ++I) {
1808    SVal Len = I.getData();
1809    if (SymbolRef Sym = Len.getAsSymbol()) {
1810      if (SR.isDead(Sym))
1811        Entries = F.remove(Entries, I.getKey());
1812    }
1813  }
1814
1815  state = state->set<CStringLength>(Entries);
1816  C.generateNode(state);
1817}
1818
1819void ento::registerCStringChecker(CheckerManager &mgr) {
1820  mgr.registerChecker<CStringChecker>();
1821}
1822