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