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