1 //= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines CStringChecker, which is an assortment of checks on calls
11 // to functions in <string.h>.
13 //===----------------------------------------------------------------------===//
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"
26 using namespace clang;
30 class CStringChecker : public Checker< eval::Call,
31 check::PreStmt<DeclStmt>,
36 mutable OwningPtr<BugType> BT_Null,
42 mutable const char *CurrentFunctionDescription;
45 /// The filter is used to filter out the diagnostics which are not enabled by
47 struct CStringChecksFilter {
48 DefaultBool CheckCStringNullArg;
49 DefaultBool CheckCStringOutOfBounds;
50 DefaultBool CheckCStringBufferOverlap;
51 DefaultBool CheckCStringNotNullTerm;
54 CStringChecksFilter Filter;
56 static void *getTag() { static int tag; return &tag; }
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;
65 checkRegionChanges(ProgramStateRef state,
66 const StoreManager::InvalidatedSymbols *,
67 ArrayRef<const MemRegion *> ExplicitRegions,
68 ArrayRef<const MemRegion *> Regions,
69 const CallEvent *Call) const;
71 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
72 const CallExpr *) const;
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,
83 bool Restricted = false,
84 bool IsMempcpy = false) const;
86 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
88 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
89 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
90 void evalstrLengthCommon(CheckerContext &C,
92 bool IsStrnlen = false) const;
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,
101 bool isAppending) const;
103 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
104 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
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,
112 bool isBounded = false,
113 bool ignoreCase = false) const;
116 std::pair<ProgramStateRef , ProgramStateRef >
117 static assumeZero(CheckerContext &C,
118 ProgramStateRef state, SVal V, QualType Ty);
120 static ProgramStateRef setCStringLength(ProgramStateRef state,
123 static SVal getCStringLengthForRegion(CheckerContext &C,
124 ProgramStateRef &state,
128 SVal getCStringLength(CheckerContext &C,
129 ProgramStateRef &state,
132 bool hypothetical = false) const;
134 const StringLiteral *getCStringLiteral(CheckerContext &C,
135 ProgramStateRef &state,
139 static ProgramStateRef InvalidateBuffer(CheckerContext &C,
140 ProgramStateRef state,
141 const Expr *Ex, SVal V);
143 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
144 const MemRegion *MR);
147 ProgramStateRef checkNonNull(CheckerContext &C,
148 ProgramStateRef state,
151 ProgramStateRef CheckLocation(CheckerContext &C,
152 ProgramStateRef state,
155 const char *message = NULL) const;
156 ProgramStateRef CheckBufferAccess(CheckerContext &C,
157 ProgramStateRef state,
159 const Expr *FirstBuf,
160 const Expr *SecondBuf,
161 const char *firstMessage = NULL,
162 const char *secondMessage = NULL,
163 bool WarnAboutSize = false) const;
165 ProgramStateRef CheckBufferAccess(CheckerContext &C,
166 ProgramStateRef state,
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,
175 ProgramStateRef CheckOverlap(CheckerContext &C,
176 ProgramStateRef state,
179 const Expr *Second) const;
180 void emitOverlapBug(CheckerContext &C,
181 ProgramStateRef state,
183 const Stmt *Second) const;
185 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
186 ProgramStateRef state,
191 } //end anonymous namespace
193 REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
195 //===----------------------------------------------------------------------===//
196 // Individual checks and utility methods.
197 //===----------------------------------------------------------------------===//
199 std::pair<ProgramStateRef , ProgramStateRef >
200 CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
202 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
204 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
206 SValBuilder &svalBuilder = C.getSValBuilder();
207 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
208 return state->assume(svalBuilder.evalEQ(state, *val, zero));
211 ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
212 ProgramStateRef state,
213 const Expr *S, SVal l) const {
214 // If a previous check has failed, propagate the failure.
218 ProgramStateRef stateNull, stateNonNull;
219 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
221 if (stateNull && !stateNonNull) {
222 if (!Filter.CheckCStringNullArg)
225 ExplodedNode *N = C.generateSink(stateNull);
230 BT_Null.reset(new BuiltinBug("Unix API",
231 "Null pointer argument in call to byte string function"));
234 llvm::raw_svector_ostream os(buf);
235 assert(CurrentFunctionDescription);
236 os << "Null pointer argument in call to " << CurrentFunctionDescription;
238 // Generate a report for this bug.
239 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
240 BugReport *report = new BugReport(*BT, os.str(), N);
242 report->addRange(S->getSourceRange());
243 bugreporter::trackNullOrUndefValue(N, S, *report);
244 C.emitReport(report);
248 // From here on, assume that the value is non-null.
249 assert(stateNonNull);
253 // FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
254 ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
255 ProgramStateRef state,
256 const Expr *S, SVal l,
257 const char *warningMsg) const {
258 // If a previous check has failed, propagate the failure.
262 // Check for out of bound array element access.
263 const MemRegion *R = l.getAsRegion();
267 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
271 assert(ER->getValueType() == C.getASTContext().CharTy &&
272 "CheckLocation should only be called with char* ElementRegions");
274 // Get the size of the array.
275 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
276 SValBuilder &svalBuilder = C.getSValBuilder();
278 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
279 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
281 // Get the index of the accessed element.
282 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
284 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
285 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
286 if (StOutBound && !StInBound) {
287 ExplodedNode *N = C.generateSink(StOutBound);
292 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
293 "Byte string function accesses out-of-bound array element"));
295 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
297 // Generate a report for this bug.
300 report = new BugReport(*BT, warningMsg, N);
302 assert(CurrentFunctionDescription);
303 assert(CurrentFunctionDescription[0] != '\0');
306 llvm::raw_svector_ostream os(buf);
307 os << (char)toupper(CurrentFunctionDescription[0])
308 << &CurrentFunctionDescription[1]
309 << " accesses out-of-bound array element";
310 report = new BugReport(*BT, os.str(), N);
313 // FIXME: It would be nice to eventually make this diagnostic more clear,
314 // e.g., by referencing the original declaration or by saying *why* this
315 // reference is outside the range.
317 report->addRange(S->getSourceRange());
318 C.emitReport(report);
322 // Array bound check succeeded. From this point forward the array bound
323 // should always succeed.
327 ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
328 ProgramStateRef state,
330 const Expr *FirstBuf,
331 const Expr *SecondBuf,
332 const char *firstMessage,
333 const char *secondMessage,
334 bool WarnAboutSize) const {
335 // If a previous check has failed, propagate the failure.
339 SValBuilder &svalBuilder = C.getSValBuilder();
340 ASTContext &Ctx = svalBuilder.getContext();
341 const LocationContext *LCtx = C.getLocationContext();
343 QualType sizeTy = Size->getType();
344 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
346 // Check that the first buffer is non-null.
347 SVal BufVal = state->getSVal(FirstBuf, LCtx);
348 state = checkNonNull(C, state, FirstBuf, BufVal);
352 // If out-of-bounds checking is turned off, skip the rest.
353 if (!Filter.CheckCStringOutOfBounds)
356 // Get the access length and make sure it is known.
357 // FIXME: This assumes the caller has already checked that the access length
358 // is positive. And that it's unsigned.
359 SVal LengthVal = state->getSVal(Size, LCtx);
360 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
364 // Compute the offset of the last element to be accessed: size-1.
365 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
366 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
367 *Length, One, sizeTy));
369 // Check that the first buffer is sufficiently long.
370 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
371 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
372 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
374 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
376 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
378 // If the buffer isn't large enough, abort.
383 // If there's a second buffer, check it as well.
385 BufVal = state->getSVal(SecondBuf, LCtx);
386 state = checkNonNull(C, state, SecondBuf, BufVal);
390 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
391 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
392 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
394 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
396 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
400 // Large enough or not, return this state!
404 ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
405 ProgramStateRef state,
408 const Expr *Second) const {
409 if (!Filter.CheckCStringBufferOverlap)
412 // Do a simple check for overlap: if the two arguments are from the same
413 // buffer, see if the end of the first is greater than the start of the second
416 // If a previous check has failed, propagate the failure.
420 ProgramStateRef stateTrue, stateFalse;
422 // Get the buffer values and make sure they're known locations.
423 const LocationContext *LCtx = C.getLocationContext();
424 SVal firstVal = state->getSVal(First, LCtx);
425 SVal secondVal = state->getSVal(Second, LCtx);
427 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
431 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
435 // Are the two values the same?
436 SValBuilder &svalBuilder = C.getSValBuilder();
437 llvm::tie(stateTrue, stateFalse) =
438 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
440 if (stateTrue && !stateFalse) {
441 // If the values are known to be equal, that's automatically an overlap.
442 emitOverlapBug(C, stateTrue, First, Second);
446 // assume the two expressions are not equal.
450 // Which value comes first?
451 QualType cmpTy = svalBuilder.getConditionType();
452 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
453 *firstLoc, *secondLoc, cmpTy);
454 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
458 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
461 // If we don't know which one comes first, we can't perform this test.
464 // Switch the values so that firstVal is before secondVal.
465 Loc *tmpLoc = firstLoc;
466 firstLoc = secondLoc;
469 // Switch the Exprs as well, so that they still correspond.
470 const Expr *tmpExpr = First;
476 // Get the length, and make sure it too is known.
477 SVal LengthVal = state->getSVal(Size, LCtx);
478 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
482 // Convert the first buffer's start address to char*.
483 // Bail out if the cast fails.
484 ASTContext &Ctx = svalBuilder.getContext();
485 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
486 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
488 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
492 // Compute the end of the first buffer. Bail out if THAT fails.
493 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
494 *FirstStartLoc, *Length, CharPtrTy);
495 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
499 // Is the end of the first buffer past the start of the second buffer?
500 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
501 *FirstEndLoc, *secondLoc, cmpTy);
502 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
506 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
508 if (stateTrue && !stateFalse) {
510 emitOverlapBug(C, stateTrue, First, Second);
514 // assume the two expressions don't overlap.
519 void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
520 const Stmt *First, const Stmt *Second) const {
521 ExplodedNode *N = C.generateSink(state);
526 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
528 // Generate a report for this bug.
530 new BugReport(*BT_Overlap,
531 "Arguments must not be overlapping buffers", N);
532 report->addRange(First->getSourceRange());
533 report->addRange(Second->getSourceRange());
535 C.emitReport(report);
538 ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
539 ProgramStateRef state,
541 NonLoc right) const {
542 // If out-of-bounds checking is turned off, skip the rest.
543 if (!Filter.CheckCStringOutOfBounds)
546 // If a previous check has failed, propagate the failure.
550 SValBuilder &svalBuilder = C.getSValBuilder();
551 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
553 QualType sizeTy = svalBuilder.getContext().getSizeType();
554 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
555 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
558 if (isa<nonloc::ConcreteInt>(right)) {
559 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
562 // Try switching the operands. (The order of these two assignments is
564 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
569 if (NonLoc *maxMinusRightNL = dyn_cast<NonLoc>(&maxMinusRight)) {
570 QualType cmpTy = svalBuilder.getConditionType();
571 // If left > max - right, we have an overflow.
572 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
573 *maxMinusRightNL, cmpTy);
575 ProgramStateRef stateOverflow, stateOkay;
576 llvm::tie(stateOverflow, stateOkay) =
577 state->assume(cast<DefinedOrUnknownSVal>(willOverflow));
579 if (stateOverflow && !stateOkay) {
580 // We have an overflow. Emit a bug report.
581 ExplodedNode *N = C.generateSink(stateOverflow);
585 if (!BT_AdditionOverflow)
586 BT_AdditionOverflow.reset(new BuiltinBug("API",
587 "Sum of expressions causes overflow"));
589 // This isn't a great error message, but this should never occur in real
590 // code anyway -- you'd have to create a buffer longer than a size_t can
591 // represent, which is sort of a contradiction.
592 const char *warning =
593 "This expression will create a string whose length is too big to "
594 "be represented as a size_t";
596 // Generate a report for this bug.
597 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
598 C.emitReport(report);
603 // From now on, assume an overflow didn't occur.
611 ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
614 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
616 MR = MR->StripCasts();
618 switch (MR->getKind()) {
619 case MemRegion::StringRegionKind:
620 // FIXME: This can happen if we strcpy() into a string region. This is
621 // undefined [C99 6.4.5p6], but we should still warn about it.
624 case MemRegion::SymbolicRegionKind:
625 case MemRegion::AllocaRegionKind:
626 case MemRegion::VarRegionKind:
627 case MemRegion::FieldRegionKind:
628 case MemRegion::ObjCIvarRegionKind:
629 // These are the types we can currently track string lengths for.
632 case MemRegion::ElementRegionKind:
633 // FIXME: Handle element regions by upper-bounding the parent region's
638 // Other regions (mostly non-data) can't have a reliable C string length.
639 // For now, just ignore the change.
640 // FIXME: These are rare but not impossible. We should output some kind of
641 // warning for things like strcpy((char[]){'a', 0}, "b");
645 if (strLength.isUnknown())
646 return state->remove<CStringLength>(MR);
648 return state->set<CStringLength>(MR, strLength);
651 SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
652 ProgramStateRef &state,
657 // If there's a recorded length, go ahead and return it.
658 const SVal *Recorded = state->get<CStringLength>(MR);
663 // Otherwise, get a new symbol and update the state.
664 SValBuilder &svalBuilder = C.getSValBuilder();
665 QualType sizeTy = svalBuilder.getContext().getSizeType();
666 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
671 state = state->set<CStringLength>(MR, strLength);
676 SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
677 const Expr *Ex, SVal Buf,
678 bool hypothetical) const {
679 const MemRegion *MR = Buf.getAsRegion();
681 // If we can't get a region, see if it's something we /know/ isn't a
682 // C string. In the context of locations, the only time we can issue such
683 // a warning is for labels.
684 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
685 if (!Filter.CheckCStringNotNullTerm)
686 return UndefinedVal();
688 if (ExplodedNode *N = C.addTransition(state)) {
690 BT_NotCString.reset(new BuiltinBug("Unix API",
691 "Argument is not a null-terminated string."));
693 SmallString<120> buf;
694 llvm::raw_svector_ostream os(buf);
695 assert(CurrentFunctionDescription);
696 os << "Argument to " << CurrentFunctionDescription
697 << " is the address of the label '" << Label->getLabel()->getName()
698 << "', which is not a null-terminated string";
700 // Generate a report for this bug.
701 BugReport *report = new BugReport(*BT_NotCString,
704 report->addRange(Ex->getSourceRange());
705 C.emitReport(report);
707 return UndefinedVal();
711 // If it's not a region and not a label, give up.
715 // If we have a region, strip casts from it and see if we can figure out
716 // its length. For anything we can't figure out, just return UnknownVal.
717 MR = MR->StripCasts();
719 switch (MR->getKind()) {
720 case MemRegion::StringRegionKind: {
721 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
722 // so we can assume that the byte length is the correct C string length.
723 SValBuilder &svalBuilder = C.getSValBuilder();
724 QualType sizeTy = svalBuilder.getContext().getSizeType();
725 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
726 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
728 case MemRegion::SymbolicRegionKind:
729 case MemRegion::AllocaRegionKind:
730 case MemRegion::VarRegionKind:
731 case MemRegion::FieldRegionKind:
732 case MemRegion::ObjCIvarRegionKind:
733 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
734 case MemRegion::CompoundLiteralRegionKind:
735 // FIXME: Can we track this? Is it necessary?
737 case MemRegion::ElementRegionKind:
738 // FIXME: How can we handle this? It's not good enough to subtract the
739 // offset from the base string length; consider "123\x00567" and &a[5].
742 // Other regions (mostly non-data) can't have a reliable C string length.
743 // In this case, an error is emitted and UndefinedVal is returned.
744 // The caller should always be prepared to handle this case.
745 if (!Filter.CheckCStringNotNullTerm)
746 return UndefinedVal();
748 if (ExplodedNode *N = C.addTransition(state)) {
750 BT_NotCString.reset(new BuiltinBug("Unix API",
751 "Argument is not a null-terminated string."));
753 SmallString<120> buf;
754 llvm::raw_svector_ostream os(buf);
756 assert(CurrentFunctionDescription);
757 os << "Argument to " << CurrentFunctionDescription << " is ";
759 if (SummarizeRegion(os, C.getASTContext(), MR))
760 os << ", which is not a null-terminated string";
762 os << "not a null-terminated string";
764 // Generate a report for this bug.
765 BugReport *report = new BugReport(*BT_NotCString,
768 report->addRange(Ex->getSourceRange());
769 C.emitReport(report);
772 return UndefinedVal();
776 const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
777 ProgramStateRef &state, const Expr *expr, SVal val) const {
779 // Get the memory region pointed to by the val.
780 const MemRegion *bufRegion = val.getAsRegion();
784 // Strip casts off the memory region.
785 bufRegion = bufRegion->StripCasts();
787 // Cast the memory region to a string region.
788 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
792 // Return the actual string in the string region.
793 return strRegion->getStringLiteral();
796 ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
797 ProgramStateRef state,
798 const Expr *E, SVal V) {
799 Loc *L = dyn_cast<Loc>(&V);
803 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
804 // some assumptions about the value that CFRefCount can't. Even so, it should
805 // probably be refactored.
806 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
807 const MemRegion *R = MR->getRegion()->StripCasts();
809 // Are we dealing with an ElementRegion? If so, we should be invalidating
811 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
812 R = ER->getSuperRegion();
813 // FIXME: What about layers of ElementRegions?
816 // Invalidate this region.
817 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
818 return state->invalidateRegions(R, E, C.blockCount(), LCtx);
821 // If we have a non-region value by chance, just remove the binding.
822 // FIXME: is this necessary or correct? This handles the non-Region
823 // cases. Is it ever valid to store to these?
824 return state->killBinding(*L);
827 bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
828 const MemRegion *MR) {
829 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
831 switch (MR->getKind()) {
832 case MemRegion::FunctionTextRegionKind: {
833 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
835 os << "the address of the function '" << *FD << '\'';
837 os << "the address of a function";
840 case MemRegion::BlockTextRegionKind:
843 case MemRegion::BlockDataRegionKind:
846 case MemRegion::CXXThisRegionKind:
847 case MemRegion::CXXTempObjectRegionKind:
848 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
850 case MemRegion::VarRegionKind:
851 os << "a variable of type" << TVR->getValueType().getAsString();
853 case MemRegion::FieldRegionKind:
854 os << "a field of type " << TVR->getValueType().getAsString();
856 case MemRegion::ObjCIvarRegionKind:
857 os << "an instance variable of type " << TVR->getValueType().getAsString();
864 //===----------------------------------------------------------------------===//
865 // evaluation of individual function calls.
866 //===----------------------------------------------------------------------===//
868 void CStringChecker::evalCopyCommon(CheckerContext &C,
870 ProgramStateRef state,
871 const Expr *Size, const Expr *Dest,
872 const Expr *Source, bool Restricted,
873 bool IsMempcpy) const {
874 CurrentFunctionDescription = "memory copy function";
876 // See if the size argument is zero.
877 const LocationContext *LCtx = C.getLocationContext();
878 SVal sizeVal = state->getSVal(Size, LCtx);
879 QualType sizeTy = Size->getType();
881 ProgramStateRef stateZeroSize, stateNonZeroSize;
882 llvm::tie(stateZeroSize, stateNonZeroSize) =
883 assumeZero(C, state, sizeVal, sizeTy);
885 // Get the value of the Dest.
886 SVal destVal = state->getSVal(Dest, LCtx);
888 // If the size is zero, there won't be any actual memory access, so
889 // just bind the return value to the destination buffer and return.
890 if (stateZeroSize && !stateNonZeroSize) {
891 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
892 C.addTransition(stateZeroSize);
896 // If the size can be nonzero, we have to check the other arguments.
897 if (stateNonZeroSize) {
898 state = stateNonZeroSize;
900 // Ensure the destination is not null. If it is NULL there will be a
901 // NULL pointer dereference.
902 state = checkNonNull(C, state, Dest, destVal);
906 // Get the value of the Src.
907 SVal srcVal = state->getSVal(Source, LCtx);
909 // Ensure the source is not null. If it is NULL there will be a
910 // NULL pointer dereference.
911 state = checkNonNull(C, state, Source, srcVal);
915 // Ensure the accesses are valid and that the buffers do not overlap.
916 const char * const writeWarning =
917 "Memory copy function overflows destination buffer";
918 state = CheckBufferAccess(C, state, Size, Dest, Source,
919 writeWarning, /* sourceWarning = */ NULL);
921 state = CheckOverlap(C, state, Size, Dest, Source);
926 // If this is mempcpy, get the byte after the last byte copied and
929 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
930 assert(destRegVal && "Destination should be a known MemRegionVal here");
932 // Get the length to copy.
933 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&sizeVal);
936 // Get the byte after the last byte copied.
937 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
942 // The byte after the last byte copied is the return value.
943 state = state->BindExpr(CE, LCtx, lastElement);
945 // If we don't know how much we copied, we can at least
946 // conjure a return value for later.
947 SVal result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx,
949 state = state->BindExpr(CE, LCtx, result);
953 // All other copies return the destination buffer.
954 // (Well, bcopy() has a void return type, but this won't hurt.)
955 state = state->BindExpr(CE, LCtx, destVal);
958 // Invalidate the destination.
959 // FIXME: Even if we can't perfectly model the copy, we should see if we
960 // can use LazyCompoundVals to copy the source values into the destination.
961 // This would probably remove any existing bindings past the end of the
962 // copied region, but that's still an improvement over blank invalidation.
963 state = InvalidateBuffer(C, state, Dest,
964 state->getSVal(Dest, C.getLocationContext()));
965 C.addTransition(state);
970 void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
971 if (CE->getNumArgs() < 3)
974 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
975 // The return value is the address of the destination buffer.
976 const Expr *Dest = CE->getArg(0);
977 ProgramStateRef state = C.getState();
979 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
982 void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
983 if (CE->getNumArgs() < 3)
986 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
987 // The return value is a pointer to the byte following the last written byte.
988 const Expr *Dest = CE->getArg(0);
989 ProgramStateRef state = C.getState();
991 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
994 void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
995 if (CE->getNumArgs() < 3)
998 // void *memmove(void *dst, const void *src, size_t n);
999 // The return value is the address of the destination buffer.
1000 const Expr *Dest = CE->getArg(0);
1001 ProgramStateRef state = C.getState();
1003 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
1006 void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
1007 if (CE->getNumArgs() < 3)
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));
1015 void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
1016 if (CE->getNumArgs() < 3)
1019 // int memcmp(const void *s1, const void *s2, size_t n);
1020 CurrentFunctionDescription = "memory comparison function";
1022 const Expr *Left = CE->getArg(0);
1023 const Expr *Right = CE->getArg(1);
1024 const Expr *Size = CE->getArg(2);
1026 ProgramStateRef state = C.getState();
1027 SValBuilder &svalBuilder = C.getSValBuilder();
1029 // See if the size argument is zero.
1030 const LocationContext *LCtx = C.getLocationContext();
1031 SVal sizeVal = state->getSVal(Size, LCtx);
1032 QualType sizeTy = Size->getType();
1034 ProgramStateRef stateZeroSize, stateNonZeroSize;
1035 llvm::tie(stateZeroSize, stateNonZeroSize) =
1036 assumeZero(C, state, sizeVal, sizeTy);
1038 // If the size can be zero, the result will be 0 in that case, and we don't
1039 // have to check either of the buffers.
1040 if (stateZeroSize) {
1041 state = stateZeroSize;
1042 state = state->BindExpr(CE, LCtx,
1043 svalBuilder.makeZeroVal(CE->getType()));
1044 C.addTransition(state);
1047 // If the size can be nonzero, we have to check the other arguments.
1048 if (stateNonZeroSize) {
1049 state = stateNonZeroSize;
1050 // If we know the two buffers are the same, we know the result is 0.
1051 // First, get the two buffers' addresses. Another checker will have already
1052 // made sure they're not undefined.
1053 DefinedOrUnknownSVal LV =
1054 cast<DefinedOrUnknownSVal>(state->getSVal(Left, LCtx));
1055 DefinedOrUnknownSVal RV =
1056 cast<DefinedOrUnknownSVal>(state->getSVal(Right, LCtx));
1058 // See if they are the same.
1059 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1060 ProgramStateRef StSameBuf, StNotSameBuf;
1061 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1063 // If the two arguments might be the same buffer, we know the result is 0,
1064 // and we only need to check one size.
1067 state = CheckBufferAccess(C, state, Size, Left);
1069 state = StSameBuf->BindExpr(CE, LCtx,
1070 svalBuilder.makeZeroVal(CE->getType()));
1071 C.addTransition(state);
1075 // If the two arguments might be different buffers, we have to check the
1076 // size of both of them.
1078 state = StNotSameBuf;
1079 state = CheckBufferAccess(C, state, Size, Left, Right);
1081 // The return value is the comparison result, which we don't know.
1082 SVal CmpV = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
1083 state = state->BindExpr(CE, LCtx, CmpV);
1084 C.addTransition(state);
1090 void CStringChecker::evalstrLength(CheckerContext &C,
1091 const CallExpr *CE) const {
1092 if (CE->getNumArgs() < 1)
1095 // size_t strlen(const char *s);
1096 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1099 void CStringChecker::evalstrnLength(CheckerContext &C,
1100 const CallExpr *CE) const {
1101 if (CE->getNumArgs() < 2)
1104 // size_t strnlen(const char *s, size_t maxlen);
1105 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1108 void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
1109 bool IsStrnlen) const {
1110 CurrentFunctionDescription = "string length function";
1111 ProgramStateRef state = C.getState();
1112 const LocationContext *LCtx = C.getLocationContext();
1115 const Expr *maxlenExpr = CE->getArg(1);
1116 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1118 ProgramStateRef stateZeroSize, stateNonZeroSize;
1119 llvm::tie(stateZeroSize, stateNonZeroSize) =
1120 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1122 // If the size can be zero, the result will be 0 in that case, and we don't
1123 // have to check the string itself.
1124 if (stateZeroSize) {
1125 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
1126 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
1127 C.addTransition(stateZeroSize);
1130 // If the size is GUARANTEED to be zero, we're done!
1131 if (!stateNonZeroSize)
1134 // Otherwise, record the assumption that the size is nonzero.
1135 state = stateNonZeroSize;
1138 // Check that the string argument is non-null.
1139 const Expr *Arg = CE->getArg(0);
1140 SVal ArgVal = state->getSVal(Arg, LCtx);
1142 state = checkNonNull(C, state, Arg, ArgVal);
1147 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
1149 // If the argument isn't a valid C string, there's no valid state to
1151 if (strLength.isUndef())
1154 DefinedOrUnknownSVal result = UnknownVal();
1156 // If the check is for strnlen() then bind the return value to no more than
1157 // the maxlen value.
1159 QualType cmpTy = C.getSValBuilder().getConditionType();
1161 // It's a little unfortunate to be getting this again,
1162 // but it's not that expensive...
1163 const Expr *maxlenExpr = CE->getArg(1);
1164 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1166 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1167 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
1169 if (strLengthNL && maxlenValNL) {
1170 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
1172 // Check if the strLength is greater than the maxlen.
1173 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
1174 state->assume(cast<DefinedOrUnknownSVal>
1175 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1180 if (stateStringTooLong && !stateStringNotTooLong) {
1181 // If the string is longer than maxlen, return maxlen.
1182 result = *maxlenValNL;
1183 } else if (stateStringNotTooLong && !stateStringTooLong) {
1184 // If the string is shorter than maxlen, return its length.
1185 result = *strLengthNL;
1189 if (result.isUnknown()) {
1190 // If we don't have enough information for a comparison, there's
1191 // no guarantee the full string length will actually be returned.
1192 // All we know is the return value is the min of the string length
1193 // and the limit. This is better than nothing.
1194 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
1195 NonLoc *resultNL = cast<NonLoc>(&result);
1198 state = state->assume(cast<DefinedOrUnknownSVal>
1199 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1206 state = state->assume(cast<DefinedOrUnknownSVal>
1207 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1215 // This is a plain strlen(), not strnlen().
1216 result = cast<DefinedOrUnknownSVal>(strLength);
1218 // If we don't know the length of the string, conjure a return
1219 // value, so it can be used in constraints, at least.
1220 if (result.isUnknown()) {
1221 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
1225 // Bind the return value.
1226 assert(!result.isUnknown() && "Should have conjured a value by now");
1227 state = state->BindExpr(CE, LCtx, result);
1228 C.addTransition(state);
1231 void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
1232 if (CE->getNumArgs() < 2)
1235 // char *strcpy(char *restrict dst, const char *restrict src);
1236 evalStrcpyCommon(C, CE,
1237 /* returnEnd = */ false,
1238 /* isBounded = */ false,
1239 /* isAppending = */ false);
1242 void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
1243 if (CE->getNumArgs() < 3)
1246 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
1247 evalStrcpyCommon(C, CE,
1248 /* returnEnd = */ false,
1249 /* isBounded = */ true,
1250 /* isAppending = */ false);
1253 void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
1254 if (CE->getNumArgs() < 2)
1257 // char *stpcpy(char *restrict dst, const char *restrict src);
1258 evalStrcpyCommon(C, CE,
1259 /* returnEnd = */ true,
1260 /* isBounded = */ false,
1261 /* isAppending = */ false);
1264 void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
1265 if (CE->getNumArgs() < 2)
1268 //char *strcat(char *restrict s1, const char *restrict s2);
1269 evalStrcpyCommon(C, CE,
1270 /* returnEnd = */ false,
1271 /* isBounded = */ false,
1272 /* isAppending = */ true);
1275 void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
1276 if (CE->getNumArgs() < 3)
1279 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1280 evalStrcpyCommon(C, CE,
1281 /* returnEnd = */ false,
1282 /* isBounded = */ true,
1283 /* isAppending = */ true);
1286 void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
1287 bool returnEnd, bool isBounded,
1288 bool isAppending) const {
1289 CurrentFunctionDescription = "string copy function";
1290 ProgramStateRef state = C.getState();
1291 const LocationContext *LCtx = C.getLocationContext();
1293 // Check that the destination is non-null.
1294 const Expr *Dst = CE->getArg(0);
1295 SVal DstVal = state->getSVal(Dst, LCtx);
1297 state = checkNonNull(C, state, Dst, DstVal);
1301 // Check that the source is non-null.
1302 const Expr *srcExpr = CE->getArg(1);
1303 SVal srcVal = state->getSVal(srcExpr, LCtx);
1304 state = checkNonNull(C, state, srcExpr, srcVal);
1308 // Get the string length of the source.
1309 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
1311 // If the source isn't a valid C string, give up.
1312 if (strLength.isUndef())
1315 SValBuilder &svalBuilder = C.getSValBuilder();
1316 QualType cmpTy = svalBuilder.getConditionType();
1317 QualType sizeTy = svalBuilder.getContext().getSizeType();
1319 // These two values allow checking two kinds of errors:
1320 // - actual overflows caused by a source that doesn't fit in the destination
1321 // - potential overflows caused by a bound that could exceed the destination
1322 SVal amountCopied = UnknownVal();
1323 SVal maxLastElementIndex = UnknownVal();
1324 const char *boundWarning = NULL;
1326 // If the function is strncpy, strncat, etc... it is bounded.
1328 // Get the max number of characters to copy.
1329 const Expr *lenExpr = CE->getArg(2);
1330 SVal lenVal = state->getSVal(lenExpr, LCtx);
1332 // Protect against misdeclared strncpy().
1333 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
1335 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1336 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1338 // If we know both values, we might be able to figure out how much
1340 if (strLengthNL && lenValNL) {
1341 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
1343 // Check if the max number to copy is less than the length of the src.
1344 // If the bound is equal to the source length, strncpy won't null-
1345 // terminate the result!
1346 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) =
1347 state->assume(cast<DefinedOrUnknownSVal>
1348 (svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL,
1349 *lenValNL, cmpTy)));
1351 if (stateSourceTooLong && !stateSourceNotTooLong) {
1352 // Max number to copy is less than the length of the src, so the actual
1353 // strLength copied is the max number arg.
1354 state = stateSourceTooLong;
1355 amountCopied = lenVal;
1357 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1358 // The source buffer entirely fits in the bound.
1359 state = stateSourceNotTooLong;
1360 amountCopied = strLength;
1364 // We still want to know if the bound is known to be too large.
1367 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1369 // Get the string length of the destination. If the destination is
1370 // memory that can't have a string length, we shouldn't be copying
1372 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1373 if (dstStrLength.isUndef())
1376 if (NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength)) {
1377 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1381 boundWarning = "Size argument is greater than the free space in the "
1382 "destination buffer";
1386 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1387 // (Yes, strncpy and strncat differ in how they treat termination.
1388 // strncat ALWAYS terminates, but strncpy doesn't.)
1390 // We need a special case for when the copy size is zero, in which
1391 // case strncpy will do no work at all. Our bounds check uses n-1
1392 // as the last element accessed, so n == 0 is problematic.
1393 ProgramStateRef StateZeroSize, StateNonZeroSize;
1394 llvm::tie(StateZeroSize, StateNonZeroSize) =
1395 assumeZero(C, state, *lenValNL, sizeTy);
1397 // If the size is known to be zero, we're done.
1398 if (StateZeroSize && !StateNonZeroSize) {
1399 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1400 C.addTransition(StateZeroSize);
1404 // Otherwise, go ahead and figure out the last element we'll touch.
1405 // We don't record the non-zero assumption here because we can't
1406 // be sure. We won't warn on a possible zero.
1407 NonLoc one = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
1408 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1410 boundWarning = "Size argument is greater than the length of the "
1411 "destination buffer";
1415 // If we couldn't pin down the copy length, at least bound it.
1416 // FIXME: We should actually run this code path for append as well, but
1417 // right now it creates problems with constraints (since we can end up
1418 // trying to pass constraints from symbol to symbol).
1419 if (amountCopied.isUnknown() && !isAppending) {
1420 // Try to get a "hypothetical" string length symbol, which we can later
1421 // set as a real value if that turns out to be the case.
1422 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1423 assert(!amountCopied.isUndef());
1425 if (NonLoc *amountCopiedNL = dyn_cast<NonLoc>(&amountCopied)) {
1427 // amountCopied <= lenVal
1428 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1432 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanBound),
1439 // amountCopied <= strlen(source)
1440 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1444 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanSrc),
1453 // The function isn't bounded. The amount copied should match the length
1454 // of the source buffer.
1455 amountCopied = strLength;
1460 // This represents the number of characters copied into the destination
1461 // buffer. (It may not actually be the strlen if the destination buffer
1462 // is not terminated.)
1463 SVal finalStrLength = UnknownVal();
1465 // If this is an appending function (strcat, strncat...) then set the
1466 // string length to strlen(src) + strlen(dst) since the buffer will
1467 // ultimately contain both.
1469 // Get the string length of the destination. If the destination is memory
1470 // that can't have a string length, we shouldn't be copying into it anyway.
1471 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1472 if (dstStrLength.isUndef())
1475 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&amountCopied);
1476 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1478 // If we know both string lengths, we might know the final string length.
1479 if (srcStrLengthNL && dstStrLengthNL) {
1480 // Make sure the two lengths together don't overflow a size_t.
1481 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1485 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1486 *dstStrLengthNL, sizeTy);
1489 // If we couldn't get a single value for the final string length,
1490 // we can at least bound it by the individual lengths.
1491 if (finalStrLength.isUnknown()) {
1492 // Try to get a "hypothetical" string length symbol, which we can later
1493 // set as a real value if that turns out to be the case.
1494 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1495 assert(!finalStrLength.isUndef());
1497 if (NonLoc *finalStrLengthNL = dyn_cast<NonLoc>(&finalStrLength)) {
1498 if (srcStrLengthNL) {
1499 // finalStrLength >= srcStrLength
1500 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1504 state = state->assume(cast<DefinedOrUnknownSVal>(sourceInResult),
1510 if (dstStrLengthNL) {
1511 // finalStrLength >= dstStrLength
1512 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1516 state = state->assume(cast<DefinedOrUnknownSVal>(destInResult),
1525 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1526 // the final string length will match the input string length.
1527 finalStrLength = amountCopied;
1530 // The final result of the function will either be a pointer past the last
1531 // copied element, or a pointer to the start of the destination buffer.
1532 SVal Result = (returnEnd ? UnknownVal() : DstVal);
1536 // If the destination is a MemRegion, try to check for a buffer overflow and
1537 // record the new string length.
1538 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
1539 QualType ptrTy = Dst->getType();
1541 // If we have an exact value on a bounded copy, use that to check for
1542 // overflows, rather than our estimate about how much is actually copied.
1544 if (NonLoc *maxLastNL = dyn_cast<NonLoc>(&maxLastElementIndex)) {
1545 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1547 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1554 // Then, if the final length is known...
1555 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&finalStrLength)) {
1556 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1557 *knownStrLength, ptrTy);
1559 // ...and we haven't checked the bound, we'll check the actual copy.
1560 if (!boundWarning) {
1561 const char * const warningMsg =
1562 "String copy function overflows destination buffer";
1563 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1568 // If this is a stpcpy-style copy, the last element is the return value.
1570 Result = lastElement;
1573 // Invalidate the destination. This must happen before we set the C string
1574 // length because invalidation will clear the length.
1575 // FIXME: Even if we can't perfectly model the copy, we should see if we
1576 // can use LazyCompoundVals to copy the source values into the destination.
1577 // This would probably remove any existing bindings past the end of the
1578 // string, but that's still an improvement over blank invalidation.
1579 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
1581 // Set the C string length of the destination, if we know it.
1582 if (isBounded && !isAppending) {
1583 // strncpy is annoying in that it doesn't guarantee to null-terminate
1584 // the result string. If the original string didn't fit entirely inside
1585 // the bound (including the null-terminator), we don't know how long the
1587 if (amountCopied != strLength)
1588 finalStrLength = UnknownVal();
1590 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
1595 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1596 // overflow, we still need a result. Conjure a return value.
1597 if (returnEnd && Result.isUnknown()) {
1598 Result = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
1601 // Set the return value.
1602 state = state->BindExpr(CE, LCtx, Result);
1603 C.addTransition(state);
1606 void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1607 if (CE->getNumArgs() < 2)
1610 //int strcmp(const char *s1, const char *s2);
1611 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
1614 void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
1615 if (CE->getNumArgs() < 3)
1618 //int strncmp(const char *s1, const char *s2, size_t n);
1619 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1622 void CStringChecker::evalStrcasecmp(CheckerContext &C,
1623 const CallExpr *CE) const {
1624 if (CE->getNumArgs() < 2)
1627 //int strcasecmp(const char *s1, const char *s2);
1628 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
1631 void CStringChecker::evalStrncasecmp(CheckerContext &C,
1632 const CallExpr *CE) const {
1633 if (CE->getNumArgs() < 3)
1636 //int strncasecmp(const char *s1, const char *s2, size_t n);
1637 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1640 void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
1641 bool isBounded, bool ignoreCase) const {
1642 CurrentFunctionDescription = "string comparison function";
1643 ProgramStateRef state = C.getState();
1644 const LocationContext *LCtx = C.getLocationContext();
1646 // Check that the first string is non-null
1647 const Expr *s1 = CE->getArg(0);
1648 SVal s1Val = state->getSVal(s1, LCtx);
1649 state = checkNonNull(C, state, s1, s1Val);
1653 // Check that the second string is non-null.
1654 const Expr *s2 = CE->getArg(1);
1655 SVal s2Val = state->getSVal(s2, LCtx);
1656 state = checkNonNull(C, state, s2, s2Val);
1660 // Get the string length of the first string or give up.
1661 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1662 if (s1Length.isUndef())
1665 // Get the string length of the second string or give up.
1666 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1667 if (s2Length.isUndef())
1670 // If we know the two buffers are the same, we know the result is 0.
1671 // First, get the two buffers' addresses. Another checker will have already
1672 // made sure they're not undefined.
1673 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(s1Val);
1674 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(s2Val);
1676 // See if they are the same.
1677 SValBuilder &svalBuilder = C.getSValBuilder();
1678 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1679 ProgramStateRef StSameBuf, StNotSameBuf;
1680 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1682 // If the two arguments might be the same buffer, we know the result is 0,
1683 // and we only need to check one size.
1685 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1686 svalBuilder.makeZeroVal(CE->getType()));
1687 C.addTransition(StSameBuf);
1689 // If the two arguments are GUARANTEED to be the same, we're done!
1694 assert(StNotSameBuf);
1695 state = StNotSameBuf;
1697 // At this point we can go about comparing the two buffers.
1698 // For now, we only do this if they're both known string literals.
1700 // Attempt to extract string literals from both expressions.
1701 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1702 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1703 bool canComputeResult = false;
1705 if (s1StrLiteral && s2StrLiteral) {
1706 StringRef s1StrRef = s1StrLiteral->getString();
1707 StringRef s2StrRef = s2StrLiteral->getString();
1710 // Get the max number of characters to compare.
1711 const Expr *lenExpr = CE->getArg(2);
1712 SVal lenVal = state->getSVal(lenExpr, LCtx);
1714 // If the length is known, we can get the right substrings.
1715 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1716 // Create substrings of each to compare the prefix.
1717 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1718 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1719 canComputeResult = true;
1722 // This is a normal, unbounded strcmp.
1723 canComputeResult = true;
1726 if (canComputeResult) {
1727 // Real strcmp stops at null characters.
1728 size_t s1Term = s1StrRef.find('\0');
1729 if (s1Term != StringRef::npos)
1730 s1StrRef = s1StrRef.substr(0, s1Term);
1732 size_t s2Term = s2StrRef.find('\0');
1733 if (s2Term != StringRef::npos)
1734 s2StrRef = s2StrRef.substr(0, s2Term);
1736 // Use StringRef's comparison methods to compute the actual result.
1740 // Compare string 1 to string 2 the same way strcasecmp() does.
1741 result = s1StrRef.compare_lower(s2StrRef);
1743 // Compare string 1 to string 2 the same way strcmp() does.
1744 result = s1StrRef.compare(s2StrRef);
1747 // Build the SVal of the comparison and bind the return value.
1748 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
1749 state = state->BindExpr(CE, LCtx, resultVal);
1753 if (!canComputeResult) {
1754 // Conjure a symbolic value. It's the best we can do.
1755 SVal resultVal = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
1756 state = state->BindExpr(CE, LCtx, resultVal);
1759 // Record this as a possible path.
1760 C.addTransition(state);
1763 //===----------------------------------------------------------------------===//
1764 // The driver method, and other Checker callbacks.
1765 //===----------------------------------------------------------------------===//
1767 bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
1768 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1773 FnCheck evalFunction = 0;
1774 if (C.isCLibraryFunction(FDecl, "memcpy"))
1775 evalFunction = &CStringChecker::evalMemcpy;
1776 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1777 evalFunction = &CStringChecker::evalMempcpy;
1778 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1779 evalFunction = &CStringChecker::evalMemcmp;
1780 else if (C.isCLibraryFunction(FDecl, "memmove"))
1781 evalFunction = &CStringChecker::evalMemmove;
1782 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1783 evalFunction = &CStringChecker::evalStrcpy;
1784 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1785 evalFunction = &CStringChecker::evalStrncpy;
1786 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1787 evalFunction = &CStringChecker::evalStpcpy;
1788 else if (C.isCLibraryFunction(FDecl, "strcat"))
1789 evalFunction = &CStringChecker::evalStrcat;
1790 else if (C.isCLibraryFunction(FDecl, "strncat"))
1791 evalFunction = &CStringChecker::evalStrncat;
1792 else if (C.isCLibraryFunction(FDecl, "strlen"))
1793 evalFunction = &CStringChecker::evalstrLength;
1794 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1795 evalFunction = &CStringChecker::evalstrnLength;
1796 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1797 evalFunction = &CStringChecker::evalStrcmp;
1798 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1799 evalFunction = &CStringChecker::evalStrncmp;
1800 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1801 evalFunction = &CStringChecker::evalStrcasecmp;
1802 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1803 evalFunction = &CStringChecker::evalStrncasecmp;
1804 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1805 evalFunction = &CStringChecker::evalBcopy;
1806 else if (C.isCLibraryFunction(FDecl, "bcmp"))
1807 evalFunction = &CStringChecker::evalMemcmp;
1809 // If the callee isn't a string function, let another checker handle it.
1813 // Make sure each function sets its own description.
1814 // (But don't bother in a release build.)
1815 assert(!(CurrentFunctionDescription = NULL));
1817 // Check and evaluate the call.
1818 (this->*evalFunction)(C, CE);
1820 // If the evaluate call resulted in no change, chain to the next eval call
1822 // Note, the custom CString evaluation calls assume that basic safety
1823 // properties are held. However, if the user chooses to turn off some of these
1824 // checks, we ignore the issues and leave the call evaluation to a generic
1826 if (!C.isDifferent())
1832 void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
1833 // Record string length for char a[] = "abc";
1834 ProgramStateRef state = C.getState();
1836 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1838 const VarDecl *D = dyn_cast<VarDecl>(*I);
1842 // FIXME: Handle array fields of structs.
1843 if (!D->getType()->isArrayType())
1846 const Expr *Init = D->getInit();
1849 if (!isa<StringLiteral>(Init))
1852 Loc VarLoc = state->getLValue(D, C.getLocationContext());
1853 const MemRegion *MR = VarLoc.getAsRegion();
1857 SVal StrVal = state->getSVal(Init, C.getLocationContext());
1858 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
1859 DefinedOrUnknownSVal strLength
1860 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
1862 state = state->set<CStringLength>(MR, strLength);
1865 C.addTransition(state);
1868 bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
1869 CStringLengthTy Entries = state->get<CStringLength>();
1870 return !Entries.isEmpty();
1874 CStringChecker::checkRegionChanges(ProgramStateRef state,
1875 const StoreManager::InvalidatedSymbols *,
1876 ArrayRef<const MemRegion *> ExplicitRegions,
1877 ArrayRef<const MemRegion *> Regions,
1878 const CallEvent *Call) const {
1879 CStringLengthTy Entries = state->get<CStringLength>();
1880 if (Entries.isEmpty())
1883 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1884 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1886 // First build sets for the changed regions and their super-regions.
1887 for (ArrayRef<const MemRegion *>::iterator
1888 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1889 const MemRegion *MR = *I;
1890 Invalidated.insert(MR);
1892 SuperRegions.insert(MR);
1893 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1894 MR = SR->getSuperRegion();
1895 SuperRegions.insert(MR);
1899 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
1901 // Then loop over the entries in the current state.
1902 for (CStringLengthTy::iterator I = Entries.begin(),
1903 E = Entries.end(); I != E; ++I) {
1904 const MemRegion *MR = I.getKey();
1906 // Is this entry for a super-region of a changed region?
1907 if (SuperRegions.count(MR)) {
1908 Entries = F.remove(Entries, MR);
1912 // Is this entry for a sub-region of a changed region?
1913 const MemRegion *Super = MR;
1914 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1915 Super = SR->getSuperRegion();
1916 if (Invalidated.count(Super)) {
1917 Entries = F.remove(Entries, MR);
1923 return state->set<CStringLength>(Entries);
1926 void CStringChecker::checkLiveSymbols(ProgramStateRef state,
1927 SymbolReaper &SR) const {
1928 // Mark all symbols in our string length map as valid.
1929 CStringLengthTy Entries = state->get<CStringLength>();
1931 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
1933 SVal Len = I.getData();
1935 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
1936 se = Len.symbol_end(); si != se; ++si)
1941 void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1942 CheckerContext &C) const {
1943 if (!SR.hasDeadSymbols())
1946 ProgramStateRef state = C.getState();
1947 CStringLengthTy Entries = state->get<CStringLength>();
1948 if (Entries.isEmpty())
1951 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
1952 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
1954 SVal Len = I.getData();
1955 if (SymbolRef Sym = Len.getAsSymbol()) {
1957 Entries = F.remove(Entries, I.getKey());
1961 state = state->set<CStringLength>(Entries);
1962 C.addTransition(state);
1965 #define REGISTER_CHECKER(name) \
1966 void ento::register##name(CheckerManager &mgr) {\
1967 static CStringChecker *TheChecker = 0; \
1968 if (TheChecker == 0) \
1969 TheChecker = mgr.registerChecker<CStringChecker>(); \
1970 TheChecker->Filter.Check##name = true; \
1973 REGISTER_CHECKER(CStringNullArg)
1974 REGISTER_CHECKER(CStringOutOfBounds)
1975 REGISTER_CHECKER(CStringBufferOverlap)
1976 REGISTER_CHECKER(CStringNotNullTerm)
1978 void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
1979 registerCStringNullArg(Mgr);