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 "clang/StaticAnalyzer/Core/Checker.h"
17 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
21 #include "llvm/ADT/StringSwitch.h"
23 using namespace clang;
27 class CStringChecker : public Checker< eval::Call,
28 check::PreStmt<DeclStmt>,
33 mutable llvm::OwningPtr<BugType> BT_Null, BT_Bounds,
34 BT_Overlap, BT_NotCString,
36 mutable const char *CurrentFunctionDescription;
39 static void *getTag() { static int tag; return &tag; }
41 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
42 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
43 void checkLiveSymbols(const ProgramState *state, SymbolReaper &SR) const;
44 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
45 bool wantsRegionChangeUpdate(const ProgramState *state) const;
48 checkRegionChanges(const ProgramState *state,
49 const StoreManager::InvalidatedSymbols *,
50 ArrayRef<const MemRegion *> ExplicitRegions,
51 ArrayRef<const MemRegion *> Regions) const;
53 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
54 const CallExpr *) const;
56 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
57 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
58 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
59 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
60 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
61 const ProgramState *state,
65 bool Restricted = false,
66 bool IsMempcpy = false) const;
68 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
70 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
71 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
72 void evalstrLengthCommon(CheckerContext &C,
74 bool IsStrnlen = false) const;
76 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
77 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
78 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
79 void evalStrcpyCommon(CheckerContext &C,
83 bool isAppending) const;
85 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
86 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
88 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
89 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
90 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
91 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
92 void evalStrcmpCommon(CheckerContext &C,
94 bool isBounded = false,
95 bool ignoreCase = false) const;
98 std::pair<const ProgramState*, const ProgramState*>
99 static assumeZero(CheckerContext &C,
100 const ProgramState *state, SVal V, QualType Ty);
102 static const ProgramState *setCStringLength(const ProgramState *state,
105 static SVal getCStringLengthForRegion(CheckerContext &C,
106 const ProgramState *&state,
110 SVal getCStringLength(CheckerContext &C,
111 const ProgramState *&state,
114 bool hypothetical = false) const;
116 const StringLiteral *getCStringLiteral(CheckerContext &C,
117 const ProgramState *&state,
121 static const ProgramState *InvalidateBuffer(CheckerContext &C,
122 const ProgramState *state,
123 const Expr *Ex, SVal V);
125 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
126 const MemRegion *MR);
129 const ProgramState *checkNonNull(CheckerContext &C,
130 const ProgramState *state,
133 const ProgramState *CheckLocation(CheckerContext &C,
134 const ProgramState *state,
137 const char *message = NULL) const;
138 const ProgramState *CheckBufferAccess(CheckerContext &C,
139 const ProgramState *state,
141 const Expr *FirstBuf,
142 const Expr *SecondBuf,
143 const char *firstMessage = NULL,
144 const char *secondMessage = NULL,
145 bool WarnAboutSize = false) const;
147 const ProgramState *CheckBufferAccess(CheckerContext &C,
148 const ProgramState *state,
151 const char *message = NULL,
152 bool WarnAboutSize = false) const {
153 // This is a convenience override.
154 return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
157 const ProgramState *CheckOverlap(CheckerContext &C,
158 const ProgramState *state,
161 const Expr *Second) const;
162 void emitOverlapBug(CheckerContext &C,
163 const ProgramState *state,
165 const Stmt *Second) const;
167 const ProgramState *checkAdditionOverflow(CheckerContext &C,
168 const ProgramState *state,
173 class CStringLength {
175 typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
177 } //end anonymous namespace
182 struct ProgramStateTrait<CStringLength>
183 : public ProgramStatePartialTrait<CStringLength::EntryMap> {
184 static void *GDMIndex() { return CStringChecker::getTag(); }
189 //===----------------------------------------------------------------------===//
190 // Individual checks and utility methods.
191 //===----------------------------------------------------------------------===//
193 std::pair<const ProgramState*, const ProgramState*>
194 CStringChecker::assumeZero(CheckerContext &C, const ProgramState *state, SVal V,
196 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
198 return std::pair<const ProgramState*, const ProgramState *>(state, state);
200 SValBuilder &svalBuilder = C.getSValBuilder();
201 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
202 return state->assume(svalBuilder.evalEQ(state, *val, zero));
205 const ProgramState *CStringChecker::checkNonNull(CheckerContext &C,
206 const ProgramState *state,
207 const Expr *S, SVal l) const {
208 // If a previous check has failed, propagate the failure.
212 const ProgramState *stateNull, *stateNonNull;
213 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
215 if (stateNull && !stateNonNull) {
216 ExplodedNode *N = C.generateSink(stateNull);
221 BT_Null.reset(new BuiltinBug("API",
222 "Null pointer argument in call to byte string function"));
224 llvm::SmallString<80> buf;
225 llvm::raw_svector_ostream os(buf);
226 assert(CurrentFunctionDescription);
227 os << "Null pointer argument in call to " << CurrentFunctionDescription;
229 // Generate a report for this bug.
230 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
231 BugReport *report = new BugReport(*BT, os.str(), N);
233 report->addRange(S->getSourceRange());
234 report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, S));
235 C.EmitReport(report);
239 // From here on, assume that the value is non-null.
240 assert(stateNonNull);
244 // FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
245 const ProgramState *CStringChecker::CheckLocation(CheckerContext &C,
246 const ProgramState *state,
247 const Expr *S, SVal l,
248 const char *warningMsg) const {
249 // If a previous check has failed, propagate the failure.
253 // Check for out of bound array element access.
254 const MemRegion *R = l.getAsRegion();
258 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
262 assert(ER->getValueType() == C.getASTContext().CharTy &&
263 "CheckLocation should only be called with char* ElementRegions");
265 // Get the size of the array.
266 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
267 SValBuilder &svalBuilder = C.getSValBuilder();
269 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
270 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
272 // Get the index of the accessed element.
273 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
275 const ProgramState *StInBound = state->assumeInBound(Idx, Size, true);
276 const ProgramState *StOutBound = state->assumeInBound(Idx, Size, false);
277 if (StOutBound && !StInBound) {
278 ExplodedNode *N = C.generateSink(StOutBound);
283 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
284 "Byte string function accesses out-of-bound array element"));
286 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
288 // Generate a report for this bug.
291 report = new BugReport(*BT, warningMsg, N);
293 assert(CurrentFunctionDescription);
294 assert(CurrentFunctionDescription[0] != '\0');
296 llvm::SmallString<80> buf;
297 llvm::raw_svector_ostream os(buf);
298 os << (char)toupper(CurrentFunctionDescription[0])
299 << &CurrentFunctionDescription[1]
300 << " accesses out-of-bound array element";
301 report = new BugReport(*BT, os.str(), N);
304 // FIXME: It would be nice to eventually make this diagnostic more clear,
305 // e.g., by referencing the original declaration or by saying *why* this
306 // reference is outside the range.
308 report->addRange(S->getSourceRange());
309 C.EmitReport(report);
313 // Array bound check succeeded. From this point forward the array bound
314 // should always succeed.
318 const ProgramState *CStringChecker::CheckBufferAccess(CheckerContext &C,
319 const ProgramState *state,
321 const Expr *FirstBuf,
322 const Expr *SecondBuf,
323 const char *firstMessage,
324 const char *secondMessage,
325 bool WarnAboutSize) const {
326 // If a previous check has failed, propagate the failure.
330 SValBuilder &svalBuilder = C.getSValBuilder();
331 ASTContext &Ctx = svalBuilder.getContext();
333 QualType sizeTy = Size->getType();
334 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
336 // Check that the first buffer is non-null.
337 SVal BufVal = state->getSVal(FirstBuf);
338 state = checkNonNull(C, state, FirstBuf, BufVal);
342 // Get the access length and make sure it is known.
343 // FIXME: This assumes the caller has already checked that the access length
344 // is positive. And that it's unsigned.
345 SVal LengthVal = state->getSVal(Size);
346 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
350 // Compute the offset of the last element to be accessed: size-1.
351 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
352 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
353 *Length, One, sizeTy));
355 // Check that the first buffer is sufficiently long.
356 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
357 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
358 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
360 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
362 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
364 // If the buffer isn't large enough, abort.
369 // If there's a second buffer, check it as well.
371 BufVal = state->getSVal(SecondBuf);
372 state = checkNonNull(C, state, SecondBuf, BufVal);
376 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
377 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
378 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
380 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
382 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
386 // Large enough or not, return this state!
390 const ProgramState *CStringChecker::CheckOverlap(CheckerContext &C,
391 const ProgramState *state,
394 const Expr *Second) const {
395 // Do a simple check for overlap: if the two arguments are from the same
396 // buffer, see if the end of the first is greater than the start of the second
399 // If a previous check has failed, propagate the failure.
403 const ProgramState *stateTrue, *stateFalse;
405 // Get the buffer values and make sure they're known locations.
406 SVal firstVal = state->getSVal(First);
407 SVal secondVal = state->getSVal(Second);
409 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
413 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
417 // Are the two values the same?
418 SValBuilder &svalBuilder = C.getSValBuilder();
419 llvm::tie(stateTrue, stateFalse) =
420 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
422 if (stateTrue && !stateFalse) {
423 // If the values are known to be equal, that's automatically an overlap.
424 emitOverlapBug(C, stateTrue, First, Second);
428 // assume the two expressions are not equal.
432 // Which value comes first?
433 QualType cmpTy = svalBuilder.getConditionType();
434 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
435 *firstLoc, *secondLoc, cmpTy);
436 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
440 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
443 // If we don't know which one comes first, we can't perform this test.
446 // Switch the values so that firstVal is before secondVal.
447 Loc *tmpLoc = firstLoc;
448 firstLoc = secondLoc;
451 // Switch the Exprs as well, so that they still correspond.
452 const Expr *tmpExpr = First;
458 // Get the length, and make sure it too is known.
459 SVal LengthVal = state->getSVal(Size);
460 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
464 // Convert the first buffer's start address to char*.
465 // Bail out if the cast fails.
466 ASTContext &Ctx = svalBuilder.getContext();
467 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
468 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
470 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
474 // Compute the end of the first buffer. Bail out if THAT fails.
475 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
476 *FirstStartLoc, *Length, CharPtrTy);
477 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
481 // Is the end of the first buffer past the start of the second buffer?
482 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
483 *FirstEndLoc, *secondLoc, cmpTy);
484 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
488 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
490 if (stateTrue && !stateFalse) {
492 emitOverlapBug(C, stateTrue, First, Second);
496 // assume the two expressions don't overlap.
501 void CStringChecker::emitOverlapBug(CheckerContext &C, const ProgramState *state,
502 const Stmt *First, const Stmt *Second) const {
503 ExplodedNode *N = C.generateSink(state);
508 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
510 // Generate a report for this bug.
512 new BugReport(*BT_Overlap,
513 "Arguments must not be overlapping buffers", N);
514 report->addRange(First->getSourceRange());
515 report->addRange(Second->getSourceRange());
517 C.EmitReport(report);
520 const ProgramState *CStringChecker::checkAdditionOverflow(CheckerContext &C,
521 const ProgramState *state,
523 NonLoc right) const {
524 // If a previous check has failed, propagate the failure.
528 SValBuilder &svalBuilder = C.getSValBuilder();
529 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
531 QualType sizeTy = svalBuilder.getContext().getSizeType();
532 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
533 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
535 SVal maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
538 if (maxMinusRight.isUnknownOrUndef()) {
539 // Try switching the operands. (The order of these two assignments is
541 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
546 if (NonLoc *maxMinusRightNL = dyn_cast<NonLoc>(&maxMinusRight)) {
547 QualType cmpTy = svalBuilder.getConditionType();
548 // If left > max - right, we have an overflow.
549 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
550 *maxMinusRightNL, cmpTy);
552 const ProgramState *stateOverflow, *stateOkay;
553 llvm::tie(stateOverflow, stateOkay) =
554 state->assume(cast<DefinedOrUnknownSVal>(willOverflow));
556 if (stateOverflow && !stateOkay) {
557 // We have an overflow. Emit a bug report.
558 ExplodedNode *N = C.generateSink(stateOverflow);
562 if (!BT_AdditionOverflow)
563 BT_AdditionOverflow.reset(new BuiltinBug("API",
564 "Sum of expressions causes overflow"));
566 // This isn't a great error message, but this should never occur in real
567 // code anyway -- you'd have to create a buffer longer than a size_t can
568 // represent, which is sort of a contradiction.
569 const char *warning =
570 "This expression will create a string whose length is too big to "
571 "be represented as a size_t";
573 // Generate a report for this bug.
574 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
575 C.EmitReport(report);
580 // From now on, assume an overflow didn't occur.
588 const ProgramState *CStringChecker::setCStringLength(const ProgramState *state,
591 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
593 MR = MR->StripCasts();
595 switch (MR->getKind()) {
596 case MemRegion::StringRegionKind:
597 // FIXME: This can happen if we strcpy() into a string region. This is
598 // undefined [C99 6.4.5p6], but we should still warn about it.
601 case MemRegion::SymbolicRegionKind:
602 case MemRegion::AllocaRegionKind:
603 case MemRegion::VarRegionKind:
604 case MemRegion::FieldRegionKind:
605 case MemRegion::ObjCIvarRegionKind:
606 // These are the types we can currently track string lengths for.
609 case MemRegion::ElementRegionKind:
610 // FIXME: Handle element regions by upper-bounding the parent region's
615 // Other regions (mostly non-data) can't have a reliable C string length.
616 // For now, just ignore the change.
617 // FIXME: These are rare but not impossible. We should output some kind of
618 // warning for things like strcpy((char[]){'a', 0}, "b");
622 if (strLength.isUnknown())
623 return state->remove<CStringLength>(MR);
625 return state->set<CStringLength>(MR, strLength);
628 SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
629 const ProgramState *&state,
634 // If there's a recorded length, go ahead and return it.
635 const SVal *Recorded = state->get<CStringLength>(MR);
640 // Otherwise, get a new symbol and update the state.
641 unsigned Count = C.getCurrentBlockCount();
642 SValBuilder &svalBuilder = C.getSValBuilder();
643 QualType sizeTy = svalBuilder.getContext().getSizeType();
644 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
645 MR, Ex, sizeTy, Count);
648 state = state->set<CStringLength>(MR, strLength);
653 SVal CStringChecker::getCStringLength(CheckerContext &C, const ProgramState *&state,
654 const Expr *Ex, SVal Buf,
655 bool hypothetical) const {
656 const MemRegion *MR = Buf.getAsRegion();
658 // If we can't get a region, see if it's something we /know/ isn't a
659 // C string. In the context of locations, the only time we can issue such
660 // a warning is for labels.
661 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
662 if (ExplodedNode *N = C.generateNode(state)) {
664 BT_NotCString.reset(new BuiltinBug("API",
665 "Argument is not a null-terminated string."));
667 llvm::SmallString<120> buf;
668 llvm::raw_svector_ostream os(buf);
669 assert(CurrentFunctionDescription);
670 os << "Argument to " << CurrentFunctionDescription
671 << " is the address of the label '" << Label->getLabel()->getName()
672 << "', which is not a null-terminated string";
674 // Generate a report for this bug.
675 BugReport *report = new BugReport(*BT_NotCString,
678 report->addRange(Ex->getSourceRange());
679 C.EmitReport(report);
682 return UndefinedVal();
685 // If it's not a region and not a label, give up.
689 // If we have a region, strip casts from it and see if we can figure out
690 // its length. For anything we can't figure out, just return UnknownVal.
691 MR = MR->StripCasts();
693 switch (MR->getKind()) {
694 case MemRegion::StringRegionKind: {
695 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
696 // so we can assume that the byte length is the correct C string length.
697 SValBuilder &svalBuilder = C.getSValBuilder();
698 QualType sizeTy = svalBuilder.getContext().getSizeType();
699 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
700 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
702 case MemRegion::SymbolicRegionKind:
703 case MemRegion::AllocaRegionKind:
704 case MemRegion::VarRegionKind:
705 case MemRegion::FieldRegionKind:
706 case MemRegion::ObjCIvarRegionKind:
707 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
708 case MemRegion::CompoundLiteralRegionKind:
709 // FIXME: Can we track this? Is it necessary?
711 case MemRegion::ElementRegionKind:
712 // FIXME: How can we handle this? It's not good enough to subtract the
713 // offset from the base string length; consider "123\x00567" and &a[5].
716 // Other regions (mostly non-data) can't have a reliable C string length.
717 // In this case, an error is emitted and UndefinedVal is returned.
718 // The caller should always be prepared to handle this case.
719 if (ExplodedNode *N = C.generateNode(state)) {
721 BT_NotCString.reset(new BuiltinBug("API",
722 "Argument is not a null-terminated string."));
724 llvm::SmallString<120> buf;
725 llvm::raw_svector_ostream os(buf);
727 assert(CurrentFunctionDescription);
728 os << "Argument to " << CurrentFunctionDescription << " is ";
730 if (SummarizeRegion(os, C.getASTContext(), MR))
731 os << ", which is not a null-terminated string";
733 os << "not a null-terminated string";
735 // Generate a report for this bug.
736 BugReport *report = new BugReport(*BT_NotCString,
739 report->addRange(Ex->getSourceRange());
740 C.EmitReport(report);
743 return UndefinedVal();
747 const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
748 const ProgramState *&state, const Expr *expr, SVal val) const {
750 // Get the memory region pointed to by the val.
751 const MemRegion *bufRegion = val.getAsRegion();
755 // Strip casts off the memory region.
756 bufRegion = bufRegion->StripCasts();
758 // Cast the memory region to a string region.
759 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
763 // Return the actual string in the string region.
764 return strRegion->getStringLiteral();
767 const ProgramState *CStringChecker::InvalidateBuffer(CheckerContext &C,
768 const ProgramState *state,
769 const Expr *E, SVal V) {
770 Loc *L = dyn_cast<Loc>(&V);
774 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
775 // some assumptions about the value that CFRefCount can't. Even so, it should
776 // probably be refactored.
777 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
778 const MemRegion *R = MR->getRegion()->StripCasts();
780 // Are we dealing with an ElementRegion? If so, we should be invalidating
782 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
783 R = ER->getSuperRegion();
784 // FIXME: What about layers of ElementRegions?
787 // Invalidate this region.
788 unsigned Count = C.getCurrentBlockCount();
789 return state->invalidateRegions(R, E, Count);
792 // If we have a non-region value by chance, just remove the binding.
793 // FIXME: is this necessary or correct? This handles the non-Region
794 // cases. Is it ever valid to store to these?
795 return state->unbindLoc(*L);
798 bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
799 const MemRegion *MR) {
800 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
802 switch (MR->getKind()) {
803 case MemRegion::FunctionTextRegionKind: {
804 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
806 os << "the address of the function '" << *FD << '\'';
808 os << "the address of a function";
811 case MemRegion::BlockTextRegionKind:
814 case MemRegion::BlockDataRegionKind:
817 case MemRegion::CXXThisRegionKind:
818 case MemRegion::CXXTempObjectRegionKind:
819 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
821 case MemRegion::VarRegionKind:
822 os << "a variable of type" << TVR->getValueType().getAsString();
824 case MemRegion::FieldRegionKind:
825 os << "a field of type " << TVR->getValueType().getAsString();
827 case MemRegion::ObjCIvarRegionKind:
828 os << "an instance variable of type " << TVR->getValueType().getAsString();
835 //===----------------------------------------------------------------------===//
836 // evaluation of individual function calls.
837 //===----------------------------------------------------------------------===//
839 void CStringChecker::evalCopyCommon(CheckerContext &C,
841 const ProgramState *state,
842 const Expr *Size, const Expr *Dest,
843 const Expr *Source, bool Restricted,
844 bool IsMempcpy) const {
845 CurrentFunctionDescription = "memory copy function";
847 // See if the size argument is zero.
848 SVal sizeVal = state->getSVal(Size);
849 QualType sizeTy = Size->getType();
851 const ProgramState *stateZeroSize, *stateNonZeroSize;
852 llvm::tie(stateZeroSize, stateNonZeroSize) =
853 assumeZero(C, state, sizeVal, sizeTy);
855 // Get the value of the Dest.
856 SVal destVal = state->getSVal(Dest);
858 // If the size is zero, there won't be any actual memory access, so
859 // just bind the return value to the destination buffer and return.
861 stateZeroSize = stateZeroSize->BindExpr(CE, destVal);
862 C.addTransition(stateZeroSize);
865 // If the size can be nonzero, we have to check the other arguments.
866 if (stateNonZeroSize) {
867 state = stateNonZeroSize;
869 // Ensure the destination is not null. If it is NULL there will be a
870 // NULL pointer dereference.
871 state = checkNonNull(C, state, Dest, destVal);
875 // Get the value of the Src.
876 SVal srcVal = state->getSVal(Source);
878 // Ensure the source is not null. If it is NULL there will be a
879 // NULL pointer dereference.
880 state = checkNonNull(C, state, Source, srcVal);
884 // Ensure the accesses are valid and that the buffers do not overlap.
885 const char * const writeWarning =
886 "Memory copy function overflows destination buffer";
887 state = CheckBufferAccess(C, state, Size, Dest, Source,
888 writeWarning, /* sourceWarning = */ NULL);
890 state = CheckOverlap(C, state, Size, Dest, Source);
895 // If this is mempcpy, get the byte after the last byte copied and
898 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
899 assert(destRegVal && "Destination should be a known MemRegionVal here");
901 // Get the length to copy.
902 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&sizeVal);
905 // Get the byte after the last byte copied.
906 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
911 // The byte after the last byte copied is the return value.
912 state = state->BindExpr(CE, lastElement);
914 // If we don't know how much we copied, we can at least
915 // conjure a return value for later.
916 unsigned Count = C.getCurrentBlockCount();
918 C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
919 state = state->BindExpr(CE, result);
923 // All other copies return the destination buffer.
924 // (Well, bcopy() has a void return type, but this won't hurt.)
925 state = state->BindExpr(CE, destVal);
928 // Invalidate the destination.
929 // FIXME: Even if we can't perfectly model the copy, we should see if we
930 // can use LazyCompoundVals to copy the source values into the destination.
931 // This would probably remove any existing bindings past the end of the
932 // copied region, but that's still an improvement over blank invalidation.
933 state = InvalidateBuffer(C, state, Dest, state->getSVal(Dest));
934 C.addTransition(state);
939 void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
940 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
941 // The return value is the address of the destination buffer.
942 const Expr *Dest = CE->getArg(0);
943 const ProgramState *state = C.getState();
945 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
948 void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
949 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
950 // The return value is a pointer to the byte following the last written byte.
951 const Expr *Dest = CE->getArg(0);
952 const ProgramState *state = C.getState();
954 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
957 void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
958 // void *memmove(void *dst, const void *src, size_t n);
959 // The return value is the address of the destination buffer.
960 const Expr *Dest = CE->getArg(0);
961 const ProgramState *state = C.getState();
963 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
966 void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
967 // void bcopy(const void *src, void *dst, size_t n);
968 evalCopyCommon(C, CE, C.getState(),
969 CE->getArg(2), CE->getArg(1), CE->getArg(0));
972 void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
973 // int memcmp(const void *s1, const void *s2, size_t n);
974 CurrentFunctionDescription = "memory comparison function";
976 const Expr *Left = CE->getArg(0);
977 const Expr *Right = CE->getArg(1);
978 const Expr *Size = CE->getArg(2);
980 const ProgramState *state = C.getState();
981 SValBuilder &svalBuilder = C.getSValBuilder();
983 // See if the size argument is zero.
984 SVal sizeVal = state->getSVal(Size);
985 QualType sizeTy = Size->getType();
987 const ProgramState *stateZeroSize, *stateNonZeroSize;
988 llvm::tie(stateZeroSize, stateNonZeroSize) =
989 assumeZero(C, state, sizeVal, sizeTy);
991 // If the size can be zero, the result will be 0 in that case, and we don't
992 // have to check either of the buffers.
994 state = stateZeroSize;
995 state = state->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
996 C.addTransition(state);
999 // If the size can be nonzero, we have to check the other arguments.
1000 if (stateNonZeroSize) {
1001 state = stateNonZeroSize;
1002 // If we know the two buffers are the same, we know the result is 0.
1003 // First, get the two buffers' addresses. Another checker will have already
1004 // made sure they're not undefined.
1005 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(state->getSVal(Left));
1006 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(state->getSVal(Right));
1008 // See if they are the same.
1009 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1010 const ProgramState *StSameBuf, *StNotSameBuf;
1011 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1013 // If the two arguments might be the same buffer, we know the result is 0,
1014 // and we only need to check one size.
1017 state = CheckBufferAccess(C, state, Size, Left);
1019 state = StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
1020 C.addTransition(state);
1024 // If the two arguments might be different buffers, we have to check the
1025 // size of both of them.
1027 state = StNotSameBuf;
1028 state = CheckBufferAccess(C, state, Size, Left, Right);
1030 // The return value is the comparison result, which we don't know.
1031 unsigned Count = C.getCurrentBlockCount();
1032 SVal CmpV = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
1033 state = state->BindExpr(CE, CmpV);
1034 C.addTransition(state);
1040 void CStringChecker::evalstrLength(CheckerContext &C,
1041 const CallExpr *CE) const {
1042 // size_t strlen(const char *s);
1043 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1046 void CStringChecker::evalstrnLength(CheckerContext &C,
1047 const CallExpr *CE) const {
1048 // size_t strnlen(const char *s, size_t maxlen);
1049 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1052 void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
1053 bool IsStrnlen) const {
1054 CurrentFunctionDescription = "string length function";
1055 const ProgramState *state = C.getState();
1058 const Expr *maxlenExpr = CE->getArg(1);
1059 SVal maxlenVal = state->getSVal(maxlenExpr);
1061 const ProgramState *stateZeroSize, *stateNonZeroSize;
1062 llvm::tie(stateZeroSize, stateNonZeroSize) =
1063 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1065 // If the size can be zero, the result will be 0 in that case, and we don't
1066 // have to check the string itself.
1067 if (stateZeroSize) {
1068 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
1069 stateZeroSize = stateZeroSize->BindExpr(CE, zero);
1070 C.addTransition(stateZeroSize);
1073 // If the size is GUARANTEED to be zero, we're done!
1074 if (!stateNonZeroSize)
1077 // Otherwise, record the assumption that the size is nonzero.
1078 state = stateNonZeroSize;
1081 // Check that the string argument is non-null.
1082 const Expr *Arg = CE->getArg(0);
1083 SVal ArgVal = state->getSVal(Arg);
1085 state = checkNonNull(C, state, Arg, ArgVal);
1090 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
1092 // If the argument isn't a valid C string, there's no valid state to
1094 if (strLength.isUndef())
1097 DefinedOrUnknownSVal result = UnknownVal();
1099 // If the check is for strnlen() then bind the return value to no more than
1100 // the maxlen value.
1102 QualType cmpTy = C.getSValBuilder().getConditionType();
1104 // It's a little unfortunate to be getting this again,
1105 // but it's not that expensive...
1106 const Expr *maxlenExpr = CE->getArg(1);
1107 SVal maxlenVal = state->getSVal(maxlenExpr);
1109 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1110 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
1112 if (strLengthNL && maxlenValNL) {
1113 const ProgramState *stateStringTooLong, *stateStringNotTooLong;
1115 // Check if the strLength is greater than the maxlen.
1116 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
1117 state->assume(cast<DefinedOrUnknownSVal>
1118 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1123 if (stateStringTooLong && !stateStringNotTooLong) {
1124 // If the string is longer than maxlen, return maxlen.
1125 result = *maxlenValNL;
1126 } else if (stateStringNotTooLong && !stateStringTooLong) {
1127 // If the string is shorter than maxlen, return its length.
1128 result = *strLengthNL;
1132 if (result.isUnknown()) {
1133 // If we don't have enough information for a comparison, there's
1134 // no guarantee the full string length will actually be returned.
1135 // All we know is the return value is the min of the string length
1136 // and the limit. This is better than nothing.
1137 unsigned Count = C.getCurrentBlockCount();
1138 result = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
1139 NonLoc *resultNL = cast<NonLoc>(&result);
1142 state = state->assume(cast<DefinedOrUnknownSVal>
1143 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1150 state = state->assume(cast<DefinedOrUnknownSVal>
1151 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1159 // This is a plain strlen(), not strnlen().
1160 result = cast<DefinedOrUnknownSVal>(strLength);
1162 // If we don't know the length of the string, conjure a return
1163 // value, so it can be used in constraints, at least.
1164 if (result.isUnknown()) {
1165 unsigned Count = C.getCurrentBlockCount();
1166 result = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
1170 // Bind the return value.
1171 assert(!result.isUnknown() && "Should have conjured a value by now");
1172 state = state->BindExpr(CE, result);
1173 C.addTransition(state);
1176 void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
1177 // char *strcpy(char *restrict dst, const char *restrict src);
1178 evalStrcpyCommon(C, CE,
1179 /* returnEnd = */ false,
1180 /* isBounded = */ false,
1181 /* isAppending = */ false);
1184 void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
1185 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
1186 evalStrcpyCommon(C, CE,
1187 /* returnEnd = */ false,
1188 /* isBounded = */ true,
1189 /* isAppending = */ false);
1192 void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
1193 // char *stpcpy(char *restrict dst, const char *restrict src);
1194 evalStrcpyCommon(C, CE,
1195 /* returnEnd = */ true,
1196 /* isBounded = */ false,
1197 /* isAppending = */ false);
1200 void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
1201 //char *strcat(char *restrict s1, const char *restrict s2);
1202 evalStrcpyCommon(C, CE,
1203 /* returnEnd = */ false,
1204 /* isBounded = */ false,
1205 /* isAppending = */ true);
1208 void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
1209 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1210 evalStrcpyCommon(C, CE,
1211 /* returnEnd = */ false,
1212 /* isBounded = */ true,
1213 /* isAppending = */ true);
1216 void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
1217 bool returnEnd, bool isBounded,
1218 bool isAppending) const {
1219 CurrentFunctionDescription = "string copy function";
1220 const ProgramState *state = C.getState();
1222 // Check that the destination is non-null.
1223 const Expr *Dst = CE->getArg(0);
1224 SVal DstVal = state->getSVal(Dst);
1226 state = checkNonNull(C, state, Dst, DstVal);
1230 // Check that the source is non-null.
1231 const Expr *srcExpr = CE->getArg(1);
1232 SVal srcVal = state->getSVal(srcExpr);
1233 state = checkNonNull(C, state, srcExpr, srcVal);
1237 // Get the string length of the source.
1238 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
1240 // If the source isn't a valid C string, give up.
1241 if (strLength.isUndef())
1244 SValBuilder &svalBuilder = C.getSValBuilder();
1245 QualType cmpTy = svalBuilder.getConditionType();
1246 QualType sizeTy = svalBuilder.getContext().getSizeType();
1248 // These two values allow checking two kinds of errors:
1249 // - actual overflows caused by a source that doesn't fit in the destination
1250 // - potential overflows caused by a bound that could exceed the destination
1251 SVal amountCopied = UnknownVal();
1252 SVal maxLastElementIndex = UnknownVal();
1253 const char *boundWarning = NULL;
1255 // If the function is strncpy, strncat, etc... it is bounded.
1257 // Get the max number of characters to copy.
1258 const Expr *lenExpr = CE->getArg(2);
1259 SVal lenVal = state->getSVal(lenExpr);
1261 // Protect against misdeclared strncpy().
1262 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
1264 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1265 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1267 // If we know both values, we might be able to figure out how much
1269 if (strLengthNL && lenValNL) {
1270 const ProgramState *stateSourceTooLong, *stateSourceNotTooLong;
1272 // Check if the max number to copy is less than the length of the src.
1273 // If the bound is equal to the source length, strncpy won't null-
1274 // terminate the result!
1275 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) =
1276 state->assume(cast<DefinedOrUnknownSVal>
1277 (svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL,
1278 *lenValNL, cmpTy)));
1280 if (stateSourceTooLong && !stateSourceNotTooLong) {
1281 // Max number to copy is less than the length of the src, so the actual
1282 // strLength copied is the max number arg.
1283 state = stateSourceTooLong;
1284 amountCopied = lenVal;
1286 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1287 // The source buffer entirely fits in the bound.
1288 state = stateSourceNotTooLong;
1289 amountCopied = strLength;
1293 // We still want to know if the bound is known to be too large.
1296 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1298 // Get the string length of the destination. If the destination is
1299 // memory that can't have a string length, we shouldn't be copying
1301 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1302 if (dstStrLength.isUndef())
1305 if (NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength)) {
1306 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1310 boundWarning = "Size argument is greater than the free space in the "
1311 "destination buffer";
1315 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1316 // (Yes, strncpy and strncat differ in how they treat termination.
1317 // strncat ALWAYS terminates, but strncpy doesn't.)
1318 NonLoc one = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
1319 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1321 boundWarning = "Size argument is greater than the length of the "
1322 "destination buffer";
1326 // If we couldn't pin down the copy length, at least bound it.
1327 // FIXME: We should actually run this code path for append as well, but
1328 // right now it creates problems with constraints (since we can end up
1329 // trying to pass constraints from symbol to symbol).
1330 if (amountCopied.isUnknown() && !isAppending) {
1331 // Try to get a "hypothetical" string length symbol, which we can later
1332 // set as a real value if that turns out to be the case.
1333 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1334 assert(!amountCopied.isUndef());
1336 if (NonLoc *amountCopiedNL = dyn_cast<NonLoc>(&amountCopied)) {
1338 // amountCopied <= lenVal
1339 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1343 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanBound),
1350 // amountCopied <= strlen(source)
1351 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1355 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanSrc),
1364 // The function isn't bounded. The amount copied should match the length
1365 // of the source buffer.
1366 amountCopied = strLength;
1371 // This represents the number of characters copied into the destination
1372 // buffer. (It may not actually be the strlen if the destination buffer
1373 // is not terminated.)
1374 SVal finalStrLength = UnknownVal();
1376 // If this is an appending function (strcat, strncat...) then set the
1377 // string length to strlen(src) + strlen(dst) since the buffer will
1378 // ultimately contain both.
1380 // Get the string length of the destination. If the destination is memory
1381 // that can't have a string length, we shouldn't be copying into it anyway.
1382 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1383 if (dstStrLength.isUndef())
1386 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&amountCopied);
1387 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1389 // If we know both string lengths, we might know the final string length.
1390 if (srcStrLengthNL && dstStrLengthNL) {
1391 // Make sure the two lengths together don't overflow a size_t.
1392 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1396 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1397 *dstStrLengthNL, sizeTy);
1400 // If we couldn't get a single value for the final string length,
1401 // we can at least bound it by the individual lengths.
1402 if (finalStrLength.isUnknown()) {
1403 // Try to get a "hypothetical" string length symbol, which we can later
1404 // set as a real value if that turns out to be the case.
1405 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1406 assert(!finalStrLength.isUndef());
1408 if (NonLoc *finalStrLengthNL = dyn_cast<NonLoc>(&finalStrLength)) {
1409 if (srcStrLengthNL) {
1410 // finalStrLength >= srcStrLength
1411 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1415 state = state->assume(cast<DefinedOrUnknownSVal>(sourceInResult),
1421 if (dstStrLengthNL) {
1422 // finalStrLength >= dstStrLength
1423 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1427 state = state->assume(cast<DefinedOrUnknownSVal>(destInResult),
1436 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1437 // the final string length will match the input string length.
1438 finalStrLength = amountCopied;
1441 // The final result of the function will either be a pointer past the last
1442 // copied element, or a pointer to the start of the destination buffer.
1443 SVal Result = (returnEnd ? UnknownVal() : DstVal);
1447 // If the destination is a MemRegion, try to check for a buffer overflow and
1448 // record the new string length.
1449 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
1450 QualType ptrTy = Dst->getType();
1452 // If we have an exact value on a bounded copy, use that to check for
1453 // overflows, rather than our estimate about how much is actually copied.
1455 if (NonLoc *maxLastNL = dyn_cast<NonLoc>(&maxLastElementIndex)) {
1456 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1458 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1465 // Then, if the final length is known...
1466 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&finalStrLength)) {
1467 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1468 *knownStrLength, ptrTy);
1470 // ...and we haven't checked the bound, we'll check the actual copy.
1471 if (!boundWarning) {
1472 const char * const warningMsg =
1473 "String copy function overflows destination buffer";
1474 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1479 // If this is a stpcpy-style copy, the last element is the return value.
1481 Result = lastElement;
1484 // Invalidate the destination. This must happen before we set the C string
1485 // length because invalidation will clear the length.
1486 // FIXME: Even if we can't perfectly model the copy, we should see if we
1487 // can use LazyCompoundVals to copy the source values into the destination.
1488 // This would probably remove any existing bindings past the end of the
1489 // string, but that's still an improvement over blank invalidation.
1490 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
1492 // Set the C string length of the destination, if we know it.
1493 if (isBounded && !isAppending) {
1494 // strncpy is annoying in that it doesn't guarantee to null-terminate
1495 // the result string. If the original string didn't fit entirely inside
1496 // the bound (including the null-terminator), we don't know how long the
1498 if (amountCopied != strLength)
1499 finalStrLength = UnknownVal();
1501 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
1506 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1507 // overflow, we still need a result. Conjure a return value.
1508 if (returnEnd && Result.isUnknown()) {
1509 unsigned Count = C.getCurrentBlockCount();
1510 Result = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
1513 // Set the return value.
1514 state = state->BindExpr(CE, Result);
1515 C.addTransition(state);
1518 void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1519 //int strcmp(const char *s1, const char *s2);
1520 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
1523 void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
1524 //int strncmp(const char *s1, const char *s2, size_t n);
1525 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1528 void CStringChecker::evalStrcasecmp(CheckerContext &C,
1529 const CallExpr *CE) const {
1530 //int strcasecmp(const char *s1, const char *s2);
1531 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
1534 void CStringChecker::evalStrncasecmp(CheckerContext &C,
1535 const CallExpr *CE) const {
1536 //int strncasecmp(const char *s1, const char *s2, size_t n);
1537 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1540 void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
1541 bool isBounded, bool ignoreCase) const {
1542 CurrentFunctionDescription = "string comparison function";
1543 const ProgramState *state = C.getState();
1545 // Check that the first string is non-null
1546 const Expr *s1 = CE->getArg(0);
1547 SVal s1Val = state->getSVal(s1);
1548 state = checkNonNull(C, state, s1, s1Val);
1552 // Check that the second string is non-null.
1553 const Expr *s2 = CE->getArg(1);
1554 SVal s2Val = state->getSVal(s2);
1555 state = checkNonNull(C, state, s2, s2Val);
1559 // Get the string length of the first string or give up.
1560 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1561 if (s1Length.isUndef())
1564 // Get the string length of the second string or give up.
1565 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1566 if (s2Length.isUndef())
1569 // If we know the two buffers are the same, we know the result is 0.
1570 // First, get the two buffers' addresses. Another checker will have already
1571 // made sure they're not undefined.
1572 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(s1Val);
1573 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(s2Val);
1575 // See if they are the same.
1576 SValBuilder &svalBuilder = C.getSValBuilder();
1577 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1578 const ProgramState *StSameBuf, *StNotSameBuf;
1579 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1581 // If the two arguments might be the same buffer, we know the result is 0,
1582 // and we only need to check one size.
1584 StSameBuf = StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
1585 C.addTransition(StSameBuf);
1587 // If the two arguments are GUARANTEED to be the same, we're done!
1592 assert(StNotSameBuf);
1593 state = StNotSameBuf;
1595 // At this point we can go about comparing the two buffers.
1596 // For now, we only do this if they're both known string literals.
1598 // Attempt to extract string literals from both expressions.
1599 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1600 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1601 bool canComputeResult = false;
1603 if (s1StrLiteral && s2StrLiteral) {
1604 StringRef s1StrRef = s1StrLiteral->getString();
1605 StringRef s2StrRef = s2StrLiteral->getString();
1608 // Get the max number of characters to compare.
1609 const Expr *lenExpr = CE->getArg(2);
1610 SVal lenVal = state->getSVal(lenExpr);
1612 // If the length is known, we can get the right substrings.
1613 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1614 // Create substrings of each to compare the prefix.
1615 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1616 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1617 canComputeResult = true;
1620 // This is a normal, unbounded strcmp.
1621 canComputeResult = true;
1624 if (canComputeResult) {
1625 // Real strcmp stops at null characters.
1626 size_t s1Term = s1StrRef.find('\0');
1627 if (s1Term != StringRef::npos)
1628 s1StrRef = s1StrRef.substr(0, s1Term);
1630 size_t s2Term = s2StrRef.find('\0');
1631 if (s2Term != StringRef::npos)
1632 s2StrRef = s2StrRef.substr(0, s2Term);
1634 // Use StringRef's comparison methods to compute the actual result.
1638 // Compare string 1 to string 2 the same way strcasecmp() does.
1639 result = s1StrRef.compare_lower(s2StrRef);
1641 // Compare string 1 to string 2 the same way strcmp() does.
1642 result = s1StrRef.compare(s2StrRef);
1645 // Build the SVal of the comparison and bind the return value.
1646 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
1647 state = state->BindExpr(CE, resultVal);
1651 if (!canComputeResult) {
1652 // Conjure a symbolic value. It's the best we can do.
1653 unsigned Count = C.getCurrentBlockCount();
1654 SVal resultVal = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
1655 state = state->BindExpr(CE, resultVal);
1658 // Record this as a possible path.
1659 C.addTransition(state);
1662 //===----------------------------------------------------------------------===//
1663 // The driver method, and other Checker callbacks.
1664 //===----------------------------------------------------------------------===//
1666 bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
1667 // Get the callee. All the functions we care about are C functions
1668 // with simple identifiers.
1669 const ProgramState *state = C.getState();
1670 const Expr *Callee = CE->getCallee();
1671 const FunctionDecl *FD = state->getSVal(Callee).getAsFunctionDecl();
1676 // Get the name of the callee. If it's a builtin, strip off the prefix.
1677 IdentifierInfo *II = FD->getIdentifier();
1678 if (!II) // if no identifier, not a simple C function
1680 StringRef Name = II->getName();
1681 if (Name.startswith("__builtin_"))
1682 Name = Name.substr(10);
1684 FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
1685 .Cases("memcpy", "__memcpy_chk", &CStringChecker::evalMemcpy)
1686 .Cases("mempcpy", "__mempcpy_chk", &CStringChecker::evalMempcpy)
1687 .Cases("memcmp", "bcmp", &CStringChecker::evalMemcmp)
1688 .Cases("memmove", "__memmove_chk", &CStringChecker::evalMemmove)
1689 .Cases("strcpy", "__strcpy_chk", &CStringChecker::evalStrcpy)
1690 .Cases("strncpy", "__strncpy_chk", &CStringChecker::evalStrncpy)
1691 .Cases("stpcpy", "__stpcpy_chk", &CStringChecker::evalStpcpy)
1692 .Cases("strcat", "__strcat_chk", &CStringChecker::evalStrcat)
1693 .Cases("strncat", "__strncat_chk", &CStringChecker::evalStrncat)
1694 .Case("strlen", &CStringChecker::evalstrLength)
1695 .Case("strnlen", &CStringChecker::evalstrnLength)
1696 .Case("strcmp", &CStringChecker::evalStrcmp)
1697 .Case("strncmp", &CStringChecker::evalStrncmp)
1698 .Case("strcasecmp", &CStringChecker::evalStrcasecmp)
1699 .Case("strncasecmp", &CStringChecker::evalStrncasecmp)
1700 .Case("bcopy", &CStringChecker::evalBcopy)
1703 // If the callee isn't a string function, let another checker handle it.
1707 // Make sure each function sets its own description.
1708 // (But don't bother in a release build.)
1709 assert(!(CurrentFunctionDescription = NULL));
1711 // Check and evaluate the call.
1712 (this->*evalFunction)(C, CE);
1716 void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
1717 // Record string length for char a[] = "abc";
1718 const ProgramState *state = C.getState();
1720 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1722 const VarDecl *D = dyn_cast<VarDecl>(*I);
1726 // FIXME: Handle array fields of structs.
1727 if (!D->getType()->isArrayType())
1730 const Expr *Init = D->getInit();
1733 if (!isa<StringLiteral>(Init))
1736 Loc VarLoc = state->getLValue(D, C.getPredecessor()->getLocationContext());
1737 const MemRegion *MR = VarLoc.getAsRegion();
1741 SVal StrVal = state->getSVal(Init);
1742 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
1743 DefinedOrUnknownSVal strLength
1744 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
1746 state = state->set<CStringLength>(MR, strLength);
1749 C.addTransition(state);
1752 bool CStringChecker::wantsRegionChangeUpdate(const ProgramState *state) const {
1753 CStringLength::EntryMap Entries = state->get<CStringLength>();
1754 return !Entries.isEmpty();
1757 const ProgramState *
1758 CStringChecker::checkRegionChanges(const ProgramState *state,
1759 const StoreManager::InvalidatedSymbols *,
1760 ArrayRef<const MemRegion *> ExplicitRegions,
1761 ArrayRef<const MemRegion *> Regions) const {
1762 CStringLength::EntryMap Entries = state->get<CStringLength>();
1763 if (Entries.isEmpty())
1766 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1767 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1769 // First build sets for the changed regions and their super-regions.
1770 for (ArrayRef<const MemRegion *>::iterator
1771 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1772 const MemRegion *MR = *I;
1773 Invalidated.insert(MR);
1775 SuperRegions.insert(MR);
1776 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1777 MR = SR->getSuperRegion();
1778 SuperRegions.insert(MR);
1782 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1784 // Then loop over the entries in the current state.
1785 for (CStringLength::EntryMap::iterator I = Entries.begin(),
1786 E = Entries.end(); I != E; ++I) {
1787 const MemRegion *MR = I.getKey();
1789 // Is this entry for a super-region of a changed region?
1790 if (SuperRegions.count(MR)) {
1791 Entries = F.remove(Entries, MR);
1795 // Is this entry for a sub-region of a changed region?
1796 const MemRegion *Super = MR;
1797 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1798 Super = SR->getSuperRegion();
1799 if (Invalidated.count(Super)) {
1800 Entries = F.remove(Entries, MR);
1806 return state->set<CStringLength>(Entries);
1809 void CStringChecker::checkLiveSymbols(const ProgramState *state,
1810 SymbolReaper &SR) const {
1811 // Mark all symbols in our string length map as valid.
1812 CStringLength::EntryMap Entries = state->get<CStringLength>();
1814 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1816 SVal Len = I.getData();
1818 for (SVal::symbol_iterator si = Len.symbol_begin(), se = Len.symbol_end();
1824 void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1825 CheckerContext &C) const {
1826 if (!SR.hasDeadSymbols())
1829 const ProgramState *state = C.getState();
1830 CStringLength::EntryMap Entries = state->get<CStringLength>();
1831 if (Entries.isEmpty())
1834 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1835 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1837 SVal Len = I.getData();
1838 if (SymbolRef Sym = Len.getAsSymbol()) {
1840 Entries = F.remove(Entries, I.getKey());
1844 state = state->set<CStringLength>(Entries);
1845 C.generateNode(state);
1848 void ento::registerCStringChecker(CheckerManager &mgr) {
1849 mgr.registerChecker<CStringChecker>();