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/Basic/CharInfo.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
31 class CStringChecker : public Checker< eval::Call,
32 check::PreStmt<DeclStmt>,
37 mutable std::unique_ptr<BugType> BT_Null, BT_Bounds, BT_Overlap,
38 BT_NotCString, BT_AdditionOverflow;
40 mutable const char *CurrentFunctionDescription;
43 /// The filter is used to filter out the diagnostics which are not enabled by
45 struct CStringChecksFilter {
46 DefaultBool CheckCStringNullArg;
47 DefaultBool CheckCStringOutOfBounds;
48 DefaultBool CheckCStringBufferOverlap;
49 DefaultBool CheckCStringNotNullTerm;
51 CheckName CheckNameCStringNullArg;
52 CheckName CheckNameCStringOutOfBounds;
53 CheckName CheckNameCStringBufferOverlap;
54 CheckName CheckNameCStringNotNullTerm;
57 CStringChecksFilter Filter;
59 static void *getTag() { static int tag; return &tag; }
61 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
62 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
63 void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
64 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
67 checkRegionChanges(ProgramStateRef state,
68 const InvalidatedSymbols *,
69 ArrayRef<const MemRegion *> ExplicitRegions,
70 ArrayRef<const MemRegion *> Regions,
71 const LocationContext *LCtx,
72 const CallEvent *Call) const;
74 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
75 const CallExpr *) const;
77 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
78 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
79 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
80 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
81 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
82 ProgramStateRef state,
86 bool Restricted = false,
87 bool IsMempcpy = false) const;
89 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
91 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
92 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
93 void evalstrLengthCommon(CheckerContext &C,
95 bool IsStrnlen = false) const;
97 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
98 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
99 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
100 void evalStrcpyCommon(CheckerContext &C,
104 bool isAppending) const;
106 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
107 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
109 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
110 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
111 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
112 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
113 void evalStrcmpCommon(CheckerContext &C,
115 bool isBounded = false,
116 bool ignoreCase = false) const;
118 void evalStrsep(CheckerContext &C, const CallExpr *CE) const;
120 void evalStdCopy(CheckerContext &C, const CallExpr *CE) const;
121 void evalStdCopyBackward(CheckerContext &C, const CallExpr *CE) const;
122 void evalStdCopyCommon(CheckerContext &C, const CallExpr *CE) const;
123 void evalMemset(CheckerContext &C, const CallExpr *CE) const;
126 std::pair<ProgramStateRef , ProgramStateRef >
127 static assumeZero(CheckerContext &C,
128 ProgramStateRef state, SVal V, QualType Ty);
130 static ProgramStateRef setCStringLength(ProgramStateRef state,
133 static SVal getCStringLengthForRegion(CheckerContext &C,
134 ProgramStateRef &state,
138 SVal getCStringLength(CheckerContext &C,
139 ProgramStateRef &state,
142 bool hypothetical = false) const;
144 const StringLiteral *getCStringLiteral(CheckerContext &C,
145 ProgramStateRef &state,
149 static ProgramStateRef InvalidateBuffer(CheckerContext &C,
150 ProgramStateRef state,
151 const Expr *Ex, SVal V,
155 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
156 const MemRegion *MR);
159 ProgramStateRef checkNonNull(CheckerContext &C,
160 ProgramStateRef state,
163 ProgramStateRef CheckLocation(CheckerContext &C,
164 ProgramStateRef state,
167 const char *message = nullptr) const;
168 ProgramStateRef CheckBufferAccess(CheckerContext &C,
169 ProgramStateRef state,
171 const Expr *FirstBuf,
172 const Expr *SecondBuf,
173 const char *firstMessage = nullptr,
174 const char *secondMessage = nullptr,
175 bool WarnAboutSize = false) const;
177 ProgramStateRef CheckBufferAccess(CheckerContext &C,
178 ProgramStateRef state,
181 const char *message = nullptr,
182 bool WarnAboutSize = false) const {
183 // This is a convenience override.
184 return CheckBufferAccess(C, state, Size, Buf, nullptr, message, nullptr,
187 ProgramStateRef CheckOverlap(CheckerContext &C,
188 ProgramStateRef state,
191 const Expr *Second) const;
192 void emitOverlapBug(CheckerContext &C,
193 ProgramStateRef state,
195 const Stmt *Second) const;
197 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
198 ProgramStateRef state,
202 // Return true if the destination buffer of the copy function may be in bound.
203 // Expects SVal of Size to be positive and unsigned.
204 // Expects SVal of FirstBuf to be a FieldRegion.
205 static bool IsFirstBufInBound(CheckerContext &C,
206 ProgramStateRef state,
207 const Expr *FirstBuf,
211 } //end anonymous namespace
213 REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
215 //===----------------------------------------------------------------------===//
216 // Individual checks and utility methods.
217 //===----------------------------------------------------------------------===//
219 std::pair<ProgramStateRef , ProgramStateRef >
220 CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
222 Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
224 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
226 SValBuilder &svalBuilder = C.getSValBuilder();
227 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
228 return state->assume(svalBuilder.evalEQ(state, *val, zero));
231 ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
232 ProgramStateRef state,
233 const Expr *S, SVal l) const {
234 // If a previous check has failed, propagate the failure.
238 ProgramStateRef stateNull, stateNonNull;
239 std::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
241 if (stateNull && !stateNonNull) {
242 if (!Filter.CheckCStringNullArg)
245 ExplodedNode *N = C.generateErrorNode(stateNull);
250 BT_Null.reset(new BuiltinBug(
251 Filter.CheckNameCStringNullArg, categories::UnixAPI,
252 "Null pointer argument in call to byte string function"));
255 llvm::raw_svector_ostream os(buf);
256 assert(CurrentFunctionDescription);
257 os << "Null pointer argument in call to " << CurrentFunctionDescription;
259 // Generate a report for this bug.
260 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
261 auto report = llvm::make_unique<BugReport>(*BT, os.str(), N);
263 report->addRange(S->getSourceRange());
264 bugreporter::trackNullOrUndefValue(N, S, *report);
265 C.emitReport(std::move(report));
269 // From here on, assume that the value is non-null.
270 assert(stateNonNull);
274 // FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
275 ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
276 ProgramStateRef state,
277 const Expr *S, SVal l,
278 const char *warningMsg) const {
279 // If a previous check has failed, propagate the failure.
283 // Check for out of bound array element access.
284 const MemRegion *R = l.getAsRegion();
288 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
292 if (ER->getValueType() != C.getASTContext().CharTy)
295 // Get the size of the array.
296 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
297 SValBuilder &svalBuilder = C.getSValBuilder();
299 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
300 DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>();
302 // Get the index of the accessed element.
303 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
305 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
306 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
307 if (StOutBound && !StInBound) {
308 ExplodedNode *N = C.generateErrorNode(StOutBound);
313 BT_Bounds.reset(new BuiltinBug(
314 Filter.CheckNameCStringOutOfBounds, "Out-of-bound array access",
315 "Byte string function accesses out-of-bound array element"));
317 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
319 // Generate a report for this bug.
320 std::unique_ptr<BugReport> report;
322 report = llvm::make_unique<BugReport>(*BT, warningMsg, N);
324 assert(CurrentFunctionDescription);
325 assert(CurrentFunctionDescription[0] != '\0');
328 llvm::raw_svector_ostream os(buf);
329 os << toUppercase(CurrentFunctionDescription[0])
330 << &CurrentFunctionDescription[1]
331 << " accesses out-of-bound array element";
332 report = llvm::make_unique<BugReport>(*BT, os.str(), N);
335 // FIXME: It would be nice to eventually make this diagnostic more clear,
336 // e.g., by referencing the original declaration or by saying *why* this
337 // reference is outside the range.
339 report->addRange(S->getSourceRange());
340 C.emitReport(std::move(report));
344 // Array bound check succeeded. From this point forward the array bound
345 // should always succeed.
349 ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
350 ProgramStateRef state,
352 const Expr *FirstBuf,
353 const Expr *SecondBuf,
354 const char *firstMessage,
355 const char *secondMessage,
356 bool WarnAboutSize) const {
357 // If a previous check has failed, propagate the failure.
361 SValBuilder &svalBuilder = C.getSValBuilder();
362 ASTContext &Ctx = svalBuilder.getContext();
363 const LocationContext *LCtx = C.getLocationContext();
365 QualType sizeTy = Size->getType();
366 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
368 // Check that the first buffer is non-null.
369 SVal BufVal = state->getSVal(FirstBuf, LCtx);
370 state = checkNonNull(C, state, FirstBuf, BufVal);
374 // If out-of-bounds checking is turned off, skip the rest.
375 if (!Filter.CheckCStringOutOfBounds)
378 // Get the access length and make sure it is known.
379 // FIXME: This assumes the caller has already checked that the access length
380 // is positive. And that it's unsigned.
381 SVal LengthVal = state->getSVal(Size, LCtx);
382 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
386 // Compute the offset of the last element to be accessed: size-1.
387 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
388 NonLoc LastOffset = svalBuilder
389 .evalBinOpNN(state, BO_Sub, *Length, One, sizeTy).castAs<NonLoc>();
391 // Check that the first buffer is sufficiently long.
392 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
393 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
394 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
396 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
398 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
400 // If the buffer isn't large enough, abort.
405 // If there's a second buffer, check it as well.
407 BufVal = state->getSVal(SecondBuf, LCtx);
408 state = checkNonNull(C, state, SecondBuf, BufVal);
412 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
413 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
414 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
416 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
418 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
422 // Large enough or not, return this state!
426 ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
427 ProgramStateRef state,
430 const Expr *Second) const {
431 if (!Filter.CheckCStringBufferOverlap)
434 // Do a simple check for overlap: if the two arguments are from the same
435 // buffer, see if the end of the first is greater than the start of the second
438 // If a previous check has failed, propagate the failure.
442 ProgramStateRef stateTrue, stateFalse;
444 // Get the buffer values and make sure they're known locations.
445 const LocationContext *LCtx = C.getLocationContext();
446 SVal firstVal = state->getSVal(First, LCtx);
447 SVal secondVal = state->getSVal(Second, LCtx);
449 Optional<Loc> firstLoc = firstVal.getAs<Loc>();
453 Optional<Loc> secondLoc = secondVal.getAs<Loc>();
457 // Are the two values the same?
458 SValBuilder &svalBuilder = C.getSValBuilder();
459 std::tie(stateTrue, stateFalse) =
460 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
462 if (stateTrue && !stateFalse) {
463 // If the values are known to be equal, that's automatically an overlap.
464 emitOverlapBug(C, stateTrue, First, Second);
468 // assume the two expressions are not equal.
472 // Which value comes first?
473 QualType cmpTy = svalBuilder.getConditionType();
474 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
475 *firstLoc, *secondLoc, cmpTy);
476 Optional<DefinedOrUnknownSVal> reverseTest =
477 reverse.getAs<DefinedOrUnknownSVal>();
481 std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
484 // If we don't know which one comes first, we can't perform this test.
487 // Switch the values so that firstVal is before secondVal.
488 std::swap(firstLoc, secondLoc);
490 // Switch the Exprs as well, so that they still correspond.
491 std::swap(First, Second);
495 // Get the length, and make sure it too is known.
496 SVal LengthVal = state->getSVal(Size, LCtx);
497 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
501 // Convert the first buffer's start address to char*.
502 // Bail out if the cast fails.
503 ASTContext &Ctx = svalBuilder.getContext();
504 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
505 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
507 Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
511 // Compute the end of the first buffer. Bail out if THAT fails.
512 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
513 *FirstStartLoc, *Length, CharPtrTy);
514 Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
518 // Is the end of the first buffer past the start of the second buffer?
519 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
520 *FirstEndLoc, *secondLoc, cmpTy);
521 Optional<DefinedOrUnknownSVal> OverlapTest =
522 Overlap.getAs<DefinedOrUnknownSVal>();
526 std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
528 if (stateTrue && !stateFalse) {
530 emitOverlapBug(C, stateTrue, First, Second);
534 // assume the two expressions don't overlap.
539 void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
540 const Stmt *First, const Stmt *Second) const {
541 ExplodedNode *N = C.generateErrorNode(state);
546 BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
547 categories::UnixAPI, "Improper arguments"));
549 // Generate a report for this bug.
550 auto report = llvm::make_unique<BugReport>(
551 *BT_Overlap, "Arguments must not be overlapping buffers", N);
552 report->addRange(First->getSourceRange());
553 report->addRange(Second->getSourceRange());
555 C.emitReport(std::move(report));
558 ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
559 ProgramStateRef state,
561 NonLoc right) const {
562 // If out-of-bounds checking is turned off, skip the rest.
563 if (!Filter.CheckCStringOutOfBounds)
566 // If a previous check has failed, propagate the failure.
570 SValBuilder &svalBuilder = C.getSValBuilder();
571 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
573 QualType sizeTy = svalBuilder.getContext().getSizeType();
574 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
575 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
578 if (right.getAs<nonloc::ConcreteInt>()) {
579 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
582 // Try switching the operands. (The order of these two assignments is
584 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
589 if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
590 QualType cmpTy = svalBuilder.getConditionType();
591 // If left > max - right, we have an overflow.
592 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
593 *maxMinusRightNL, cmpTy);
595 ProgramStateRef stateOverflow, stateOkay;
596 std::tie(stateOverflow, stateOkay) =
597 state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
599 if (stateOverflow && !stateOkay) {
600 // We have an overflow. Emit a bug report.
601 ExplodedNode *N = C.generateErrorNode(stateOverflow);
605 if (!BT_AdditionOverflow)
606 BT_AdditionOverflow.reset(
607 new BuiltinBug(Filter.CheckNameCStringOutOfBounds, "API",
608 "Sum of expressions causes overflow"));
610 // This isn't a great error message, but this should never occur in real
611 // code anyway -- you'd have to create a buffer longer than a size_t can
612 // represent, which is sort of a contradiction.
613 const char *warning =
614 "This expression will create a string whose length is too big to "
615 "be represented as a size_t";
617 // Generate a report for this bug.
619 llvm::make_unique<BugReport>(*BT_AdditionOverflow, warning, N));
624 // From now on, assume an overflow didn't occur.
632 ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
635 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
637 MR = MR->StripCasts();
639 switch (MR->getKind()) {
640 case MemRegion::StringRegionKind:
641 // FIXME: This can happen if we strcpy() into a string region. This is
642 // undefined [C99 6.4.5p6], but we should still warn about it.
645 case MemRegion::SymbolicRegionKind:
646 case MemRegion::AllocaRegionKind:
647 case MemRegion::VarRegionKind:
648 case MemRegion::FieldRegionKind:
649 case MemRegion::ObjCIvarRegionKind:
650 // These are the types we can currently track string lengths for.
653 case MemRegion::ElementRegionKind:
654 // FIXME: Handle element regions by upper-bounding the parent region's
659 // Other regions (mostly non-data) can't have a reliable C string length.
660 // For now, just ignore the change.
661 // FIXME: These are rare but not impossible. We should output some kind of
662 // warning for things like strcpy((char[]){'a', 0}, "b");
666 if (strLength.isUnknown())
667 return state->remove<CStringLength>(MR);
669 return state->set<CStringLength>(MR, strLength);
672 SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
673 ProgramStateRef &state,
678 // If there's a recorded length, go ahead and return it.
679 const SVal *Recorded = state->get<CStringLength>(MR);
684 // Otherwise, get a new symbol and update the state.
685 SValBuilder &svalBuilder = C.getSValBuilder();
686 QualType sizeTy = svalBuilder.getContext().getSizeType();
687 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
689 C.getLocationContext(),
693 if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
694 // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
695 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
696 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
697 llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
698 const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
700 NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
701 SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
703 state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
705 state = state->set<CStringLength>(MR, strLength);
711 SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
712 const Expr *Ex, SVal Buf,
713 bool hypothetical) const {
714 const MemRegion *MR = Buf.getAsRegion();
716 // If we can't get a region, see if it's something we /know/ isn't a
717 // C string. In the context of locations, the only time we can issue such
718 // a warning is for labels.
719 if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
720 if (!Filter.CheckCStringNotNullTerm)
721 return UndefinedVal();
723 if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) {
725 BT_NotCString.reset(new BuiltinBug(
726 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
727 "Argument is not a null-terminated string."));
729 SmallString<120> buf;
730 llvm::raw_svector_ostream os(buf);
731 assert(CurrentFunctionDescription);
732 os << "Argument to " << CurrentFunctionDescription
733 << " is the address of the label '" << Label->getLabel()->getName()
734 << "', which is not a null-terminated string";
736 // Generate a report for this bug.
737 auto report = llvm::make_unique<BugReport>(*BT_NotCString, os.str(), N);
739 report->addRange(Ex->getSourceRange());
740 C.emitReport(std::move(report));
742 return UndefinedVal();
746 // If it's not a region and not a label, give up.
750 // If we have a region, strip casts from it and see if we can figure out
751 // its length. For anything we can't figure out, just return UnknownVal.
752 MR = MR->StripCasts();
754 switch (MR->getKind()) {
755 case MemRegion::StringRegionKind: {
756 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
757 // so we can assume that the byte length is the correct C string length.
758 SValBuilder &svalBuilder = C.getSValBuilder();
759 QualType sizeTy = svalBuilder.getContext().getSizeType();
760 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
761 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
763 case MemRegion::SymbolicRegionKind:
764 case MemRegion::AllocaRegionKind:
765 case MemRegion::VarRegionKind:
766 case MemRegion::FieldRegionKind:
767 case MemRegion::ObjCIvarRegionKind:
768 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
769 case MemRegion::CompoundLiteralRegionKind:
770 // FIXME: Can we track this? Is it necessary?
772 case MemRegion::ElementRegionKind:
773 // FIXME: How can we handle this? It's not good enough to subtract the
774 // offset from the base string length; consider "123\x00567" and &a[5].
777 // Other regions (mostly non-data) can't have a reliable C string length.
778 // In this case, an error is emitted and UndefinedVal is returned.
779 // The caller should always be prepared to handle this case.
780 if (!Filter.CheckCStringNotNullTerm)
781 return UndefinedVal();
783 if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) {
785 BT_NotCString.reset(new BuiltinBug(
786 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
787 "Argument is not a null-terminated string."));
789 SmallString<120> buf;
790 llvm::raw_svector_ostream os(buf);
792 assert(CurrentFunctionDescription);
793 os << "Argument to " << CurrentFunctionDescription << " is ";
795 if (SummarizeRegion(os, C.getASTContext(), MR))
796 os << ", which is not a null-terminated string";
798 os << "not a null-terminated string";
800 // Generate a report for this bug.
801 auto report = llvm::make_unique<BugReport>(*BT_NotCString, os.str(), N);
803 report->addRange(Ex->getSourceRange());
804 C.emitReport(std::move(report));
807 return UndefinedVal();
811 const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
812 ProgramStateRef &state, const Expr *expr, SVal val) const {
814 // Get the memory region pointed to by the val.
815 const MemRegion *bufRegion = val.getAsRegion();
819 // Strip casts off the memory region.
820 bufRegion = bufRegion->StripCasts();
822 // Cast the memory region to a string region.
823 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
827 // Return the actual string in the string region.
828 return strRegion->getStringLiteral();
831 bool CStringChecker::IsFirstBufInBound(CheckerContext &C,
832 ProgramStateRef state,
833 const Expr *FirstBuf,
835 // If we do not know that the buffer is long enough we return 'true'.
836 // Otherwise the parent region of this field region would also get
837 // invalidated, which would lead to warnings based on an unknown state.
839 // Originally copied from CheckBufferAccess and CheckLocation.
840 SValBuilder &svalBuilder = C.getSValBuilder();
841 ASTContext &Ctx = svalBuilder.getContext();
842 const LocationContext *LCtx = C.getLocationContext();
844 QualType sizeTy = Size->getType();
845 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
846 SVal BufVal = state->getSVal(FirstBuf, LCtx);
848 SVal LengthVal = state->getSVal(Size, LCtx);
849 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
851 return true; // cf top comment.
853 // Compute the offset of the last element to be accessed: size-1.
854 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
856 svalBuilder.evalBinOpNN(state, BO_Sub, *Length, One, sizeTy)
859 // Check that the first buffer is sufficiently long.
860 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
861 Optional<Loc> BufLoc = BufStart.getAs<Loc>();
863 return true; // cf top comment.
866 svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc, LastOffset, PtrTy);
868 // Check for out of bound array element access.
869 const MemRegion *R = BufEnd.getAsRegion();
871 return true; // cf top comment.
873 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
875 return true; // cf top comment.
877 // FIXME: Does this crash when a non-standard definition
878 // of a library function is encountered?
879 assert(ER->getValueType() == C.getASTContext().CharTy &&
880 "IsFirstBufInBound should only be called with char* ElementRegions");
882 // Get the size of the array.
883 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
885 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
886 DefinedOrUnknownSVal ExtentSize = Extent.castAs<DefinedOrUnknownSVal>();
888 // Get the index of the accessed element.
889 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
891 ProgramStateRef StInBound = state->assumeInBound(Idx, ExtentSize, true);
893 return static_cast<bool>(StInBound);
896 ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
897 ProgramStateRef state,
898 const Expr *E, SVal V,
901 Optional<Loc> L = V.getAs<Loc>();
905 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
906 // some assumptions about the value that CFRefCount can't. Even so, it should
907 // probably be refactored.
908 if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
909 const MemRegion *R = MR->getRegion()->StripCasts();
911 // Are we dealing with an ElementRegion? If so, we should be invalidating
913 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
914 R = ER->getSuperRegion();
915 // FIXME: What about layers of ElementRegions?
918 // Invalidate this region.
919 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
921 bool CausesPointerEscape = false;
922 RegionAndSymbolInvalidationTraits ITraits;
923 // Invalidate and escape only indirect regions accessible through the source
925 if (IsSourceBuffer) {
926 ITraits.setTrait(R->getBaseRegion(),
927 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
928 ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
929 CausesPointerEscape = true;
931 const MemRegion::Kind& K = R->getKind();
932 if (K == MemRegion::FieldRegionKind)
933 if (Size && IsFirstBufInBound(C, state, E, Size)) {
934 // If destination buffer is a field region and access is in bound,
935 // do not invalidate its super region.
938 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
942 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
943 CausesPointerEscape, nullptr, nullptr,
947 // If we have a non-region value by chance, just remove the binding.
948 // FIXME: is this necessary or correct? This handles the non-Region
949 // cases. Is it ever valid to store to these?
950 return state->killBinding(*L);
953 bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
954 const MemRegion *MR) {
955 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
957 switch (MR->getKind()) {
958 case MemRegion::FunctionCodeRegionKind: {
959 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
961 os << "the address of the function '" << *FD << '\'';
963 os << "the address of a function";
966 case MemRegion::BlockCodeRegionKind:
969 case MemRegion::BlockDataRegionKind:
972 case MemRegion::CXXThisRegionKind:
973 case MemRegion::CXXTempObjectRegionKind:
974 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
976 case MemRegion::VarRegionKind:
977 os << "a variable of type" << TVR->getValueType().getAsString();
979 case MemRegion::FieldRegionKind:
980 os << "a field of type " << TVR->getValueType().getAsString();
982 case MemRegion::ObjCIvarRegionKind:
983 os << "an instance variable of type " << TVR->getValueType().getAsString();
990 //===----------------------------------------------------------------------===//
991 // evaluation of individual function calls.
992 //===----------------------------------------------------------------------===//
994 void CStringChecker::evalCopyCommon(CheckerContext &C,
996 ProgramStateRef state,
997 const Expr *Size, const Expr *Dest,
998 const Expr *Source, bool Restricted,
999 bool IsMempcpy) const {
1000 CurrentFunctionDescription = "memory copy function";
1002 // See if the size argument is zero.
1003 const LocationContext *LCtx = C.getLocationContext();
1004 SVal sizeVal = state->getSVal(Size, LCtx);
1005 QualType sizeTy = Size->getType();
1007 ProgramStateRef stateZeroSize, stateNonZeroSize;
1008 std::tie(stateZeroSize, stateNonZeroSize) =
1009 assumeZero(C, state, sizeVal, sizeTy);
1011 // Get the value of the Dest.
1012 SVal destVal = state->getSVal(Dest, LCtx);
1014 // If the size is zero, there won't be any actual memory access, so
1015 // just bind the return value to the destination buffer and return.
1016 if (stateZeroSize && !stateNonZeroSize) {
1017 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
1018 C.addTransition(stateZeroSize);
1022 // If the size can be nonzero, we have to check the other arguments.
1023 if (stateNonZeroSize) {
1024 state = stateNonZeroSize;
1026 // Ensure the destination is not null. If it is NULL there will be a
1027 // NULL pointer dereference.
1028 state = checkNonNull(C, state, Dest, destVal);
1032 // Get the value of the Src.
1033 SVal srcVal = state->getSVal(Source, LCtx);
1035 // Ensure the source is not null. If it is NULL there will be a
1036 // NULL pointer dereference.
1037 state = checkNonNull(C, state, Source, srcVal);
1041 // Ensure the accesses are valid and that the buffers do not overlap.
1042 const char * const writeWarning =
1043 "Memory copy function overflows destination buffer";
1044 state = CheckBufferAccess(C, state, Size, Dest, Source,
1045 writeWarning, /* sourceWarning = */ nullptr);
1047 state = CheckOverlap(C, state, Size, Dest, Source);
1052 // If this is mempcpy, get the byte after the last byte copied and
1055 // Get the byte after the last byte copied.
1056 SValBuilder &SvalBuilder = C.getSValBuilder();
1057 ASTContext &Ctx = SvalBuilder.getContext();
1058 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
1059 SVal DestRegCharVal =
1060 SvalBuilder.evalCast(destVal, CharPtrTy, Dest->getType());
1061 SVal lastElement = C.getSValBuilder().evalBinOp(
1062 state, BO_Add, DestRegCharVal, sizeVal, Dest->getType());
1063 // If we don't know how much we copied, we can at least
1064 // conjure a return value for later.
1065 if (lastElement.isUnknown())
1066 lastElement = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1069 // The byte after the last byte copied is the return value.
1070 state = state->BindExpr(CE, LCtx, lastElement);
1072 // All other copies return the destination buffer.
1073 // (Well, bcopy() has a void return type, but this won't hurt.)
1074 state = state->BindExpr(CE, LCtx, destVal);
1077 // Invalidate the destination (regular invalidation without pointer-escaping
1078 // the address of the top-level region).
1079 // FIXME: Even if we can't perfectly model the copy, we should see if we
1080 // can use LazyCompoundVals to copy the source values into the destination.
1081 // This would probably remove any existing bindings past the end of the
1082 // copied region, but that's still an improvement over blank invalidation.
1083 state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest),
1084 /*IsSourceBuffer*/false, Size);
1086 // Invalidate the source (const-invalidation without const-pointer-escaping
1087 // the address of the top-level region).
1088 state = InvalidateBuffer(C, state, Source, C.getSVal(Source),
1089 /*IsSourceBuffer*/true, nullptr);
1091 C.addTransition(state);
1096 void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
1097 if (CE->getNumArgs() < 3)
1100 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
1101 // The return value is the address of the destination buffer.
1102 const Expr *Dest = CE->getArg(0);
1103 ProgramStateRef state = C.getState();
1105 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
1108 void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
1109 if (CE->getNumArgs() < 3)
1112 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1113 // The return value is a pointer to the byte following the last written byte.
1114 const Expr *Dest = CE->getArg(0);
1115 ProgramStateRef state = C.getState();
1117 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
1120 void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
1121 if (CE->getNumArgs() < 3)
1124 // void *memmove(void *dst, const void *src, size_t n);
1125 // The return value is the address of the destination buffer.
1126 const Expr *Dest = CE->getArg(0);
1127 ProgramStateRef state = C.getState();
1129 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
1132 void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
1133 if (CE->getNumArgs() < 3)
1136 // void bcopy(const void *src, void *dst, size_t n);
1137 evalCopyCommon(C, CE, C.getState(),
1138 CE->getArg(2), CE->getArg(1), CE->getArg(0));
1141 void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
1142 if (CE->getNumArgs() < 3)
1145 // int memcmp(const void *s1, const void *s2, size_t n);
1146 CurrentFunctionDescription = "memory comparison function";
1148 const Expr *Left = CE->getArg(0);
1149 const Expr *Right = CE->getArg(1);
1150 const Expr *Size = CE->getArg(2);
1152 ProgramStateRef state = C.getState();
1153 SValBuilder &svalBuilder = C.getSValBuilder();
1155 // See if the size argument is zero.
1156 const LocationContext *LCtx = C.getLocationContext();
1157 SVal sizeVal = state->getSVal(Size, LCtx);
1158 QualType sizeTy = Size->getType();
1160 ProgramStateRef stateZeroSize, stateNonZeroSize;
1161 std::tie(stateZeroSize, stateNonZeroSize) =
1162 assumeZero(C, state, sizeVal, sizeTy);
1164 // If the size can be zero, the result will be 0 in that case, and we don't
1165 // have to check either of the buffers.
1166 if (stateZeroSize) {
1167 state = stateZeroSize;
1168 state = state->BindExpr(CE, LCtx,
1169 svalBuilder.makeZeroVal(CE->getType()));
1170 C.addTransition(state);
1173 // If the size can be nonzero, we have to check the other arguments.
1174 if (stateNonZeroSize) {
1175 state = stateNonZeroSize;
1176 // If we know the two buffers are the same, we know the result is 0.
1177 // First, get the two buffers' addresses. Another checker will have already
1178 // made sure they're not undefined.
1179 DefinedOrUnknownSVal LV =
1180 state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
1181 DefinedOrUnknownSVal RV =
1182 state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
1184 // See if they are the same.
1185 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1186 ProgramStateRef StSameBuf, StNotSameBuf;
1187 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1189 // If the two arguments might be the same buffer, we know the result is 0,
1190 // and we only need to check one size.
1193 state = CheckBufferAccess(C, state, Size, Left);
1195 state = StSameBuf->BindExpr(CE, LCtx,
1196 svalBuilder.makeZeroVal(CE->getType()));
1197 C.addTransition(state);
1201 // If the two arguments might be different buffers, we have to check the
1202 // size of both of them.
1204 state = StNotSameBuf;
1205 state = CheckBufferAccess(C, state, Size, Left, Right);
1207 // The return value is the comparison result, which we don't know.
1208 SVal CmpV = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1210 state = state->BindExpr(CE, LCtx, CmpV);
1211 C.addTransition(state);
1217 void CStringChecker::evalstrLength(CheckerContext &C,
1218 const CallExpr *CE) const {
1219 if (CE->getNumArgs() < 1)
1222 // size_t strlen(const char *s);
1223 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1226 void CStringChecker::evalstrnLength(CheckerContext &C,
1227 const CallExpr *CE) const {
1228 if (CE->getNumArgs() < 2)
1231 // size_t strnlen(const char *s, size_t maxlen);
1232 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1235 void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
1236 bool IsStrnlen) const {
1237 CurrentFunctionDescription = "string length function";
1238 ProgramStateRef state = C.getState();
1239 const LocationContext *LCtx = C.getLocationContext();
1242 const Expr *maxlenExpr = CE->getArg(1);
1243 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1245 ProgramStateRef stateZeroSize, stateNonZeroSize;
1246 std::tie(stateZeroSize, stateNonZeroSize) =
1247 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1249 // If the size can be zero, the result will be 0 in that case, and we don't
1250 // have to check the string itself.
1251 if (stateZeroSize) {
1252 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
1253 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
1254 C.addTransition(stateZeroSize);
1257 // If the size is GUARANTEED to be zero, we're done!
1258 if (!stateNonZeroSize)
1261 // Otherwise, record the assumption that the size is nonzero.
1262 state = stateNonZeroSize;
1265 // Check that the string argument is non-null.
1266 const Expr *Arg = CE->getArg(0);
1267 SVal ArgVal = state->getSVal(Arg, LCtx);
1269 state = checkNonNull(C, state, Arg, ArgVal);
1274 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
1276 // If the argument isn't a valid C string, there's no valid state to
1278 if (strLength.isUndef())
1281 DefinedOrUnknownSVal result = UnknownVal();
1283 // If the check is for strnlen() then bind the return value to no more than
1284 // the maxlen value.
1286 QualType cmpTy = C.getSValBuilder().getConditionType();
1288 // It's a little unfortunate to be getting this again,
1289 // but it's not that expensive...
1290 const Expr *maxlenExpr = CE->getArg(1);
1291 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1293 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1294 Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
1296 if (strLengthNL && maxlenValNL) {
1297 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
1299 // Check if the strLength is greater than the maxlen.
1300 std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
1302 .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1303 .castAs<DefinedOrUnknownSVal>());
1305 if (stateStringTooLong && !stateStringNotTooLong) {
1306 // If the string is longer than maxlen, return maxlen.
1307 result = *maxlenValNL;
1308 } else if (stateStringNotTooLong && !stateStringTooLong) {
1309 // If the string is shorter than maxlen, return its length.
1310 result = *strLengthNL;
1314 if (result.isUnknown()) {
1315 // If we don't have enough information for a comparison, there's
1316 // no guarantee the full string length will actually be returned.
1317 // All we know is the return value is the min of the string length
1318 // and the limit. This is better than nothing.
1319 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1321 NonLoc resultNL = result.castAs<NonLoc>();
1324 state = state->assume(C.getSValBuilder().evalBinOpNN(
1325 state, BO_LE, resultNL, *strLengthNL, cmpTy)
1326 .castAs<DefinedOrUnknownSVal>(), true);
1330 state = state->assume(C.getSValBuilder().evalBinOpNN(
1331 state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1332 .castAs<DefinedOrUnknownSVal>(), true);
1337 // This is a plain strlen(), not strnlen().
1338 result = strLength.castAs<DefinedOrUnknownSVal>();
1340 // If we don't know the length of the string, conjure a return
1341 // value, so it can be used in constraints, at least.
1342 if (result.isUnknown()) {
1343 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1348 // Bind the return value.
1349 assert(!result.isUnknown() && "Should have conjured a value by now");
1350 state = state->BindExpr(CE, LCtx, result);
1351 C.addTransition(state);
1354 void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
1355 if (CE->getNumArgs() < 2)
1358 // char *strcpy(char *restrict dst, const char *restrict src);
1359 evalStrcpyCommon(C, CE,
1360 /* returnEnd = */ false,
1361 /* isBounded = */ false,
1362 /* isAppending = */ false);
1365 void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
1366 if (CE->getNumArgs() < 3)
1369 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
1370 evalStrcpyCommon(C, CE,
1371 /* returnEnd = */ false,
1372 /* isBounded = */ true,
1373 /* isAppending = */ false);
1376 void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
1377 if (CE->getNumArgs() < 2)
1380 // char *stpcpy(char *restrict dst, const char *restrict src);
1381 evalStrcpyCommon(C, CE,
1382 /* returnEnd = */ true,
1383 /* isBounded = */ false,
1384 /* isAppending = */ false);
1387 void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
1388 if (CE->getNumArgs() < 2)
1391 //char *strcat(char *restrict s1, const char *restrict s2);
1392 evalStrcpyCommon(C, CE,
1393 /* returnEnd = */ false,
1394 /* isBounded = */ false,
1395 /* isAppending = */ true);
1398 void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
1399 if (CE->getNumArgs() < 3)
1402 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1403 evalStrcpyCommon(C, CE,
1404 /* returnEnd = */ false,
1405 /* isBounded = */ true,
1406 /* isAppending = */ true);
1409 void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
1410 bool returnEnd, bool isBounded,
1411 bool isAppending) const {
1412 CurrentFunctionDescription = "string copy function";
1413 ProgramStateRef state = C.getState();
1414 const LocationContext *LCtx = C.getLocationContext();
1416 // Check that the destination is non-null.
1417 const Expr *Dst = CE->getArg(0);
1418 SVal DstVal = state->getSVal(Dst, LCtx);
1420 state = checkNonNull(C, state, Dst, DstVal);
1424 // Check that the source is non-null.
1425 const Expr *srcExpr = CE->getArg(1);
1426 SVal srcVal = state->getSVal(srcExpr, LCtx);
1427 state = checkNonNull(C, state, srcExpr, srcVal);
1431 // Get the string length of the source.
1432 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
1434 // If the source isn't a valid C string, give up.
1435 if (strLength.isUndef())
1438 SValBuilder &svalBuilder = C.getSValBuilder();
1439 QualType cmpTy = svalBuilder.getConditionType();
1440 QualType sizeTy = svalBuilder.getContext().getSizeType();
1442 // These two values allow checking two kinds of errors:
1443 // - actual overflows caused by a source that doesn't fit in the destination
1444 // - potential overflows caused by a bound that could exceed the destination
1445 SVal amountCopied = UnknownVal();
1446 SVal maxLastElementIndex = UnknownVal();
1447 const char *boundWarning = nullptr;
1449 // If the function is strncpy, strncat, etc... it is bounded.
1451 // Get the max number of characters to copy.
1452 const Expr *lenExpr = CE->getArg(2);
1453 SVal lenVal = state->getSVal(lenExpr, LCtx);
1455 // Protect against misdeclared strncpy().
1456 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
1458 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1459 Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
1461 // If we know both values, we might be able to figure out how much
1463 if (strLengthNL && lenValNL) {
1464 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
1466 // Check if the max number to copy is less than the length of the src.
1467 // If the bound is equal to the source length, strncpy won't null-
1468 // terminate the result!
1469 std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
1470 svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1471 .castAs<DefinedOrUnknownSVal>());
1473 if (stateSourceTooLong && !stateSourceNotTooLong) {
1474 // Max number to copy is less than the length of the src, so the actual
1475 // strLength copied is the max number arg.
1476 state = stateSourceTooLong;
1477 amountCopied = lenVal;
1479 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1480 // The source buffer entirely fits in the bound.
1481 state = stateSourceNotTooLong;
1482 amountCopied = strLength;
1486 // We still want to know if the bound is known to be too large.
1489 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1491 // Get the string length of the destination. If the destination is
1492 // memory that can't have a string length, we shouldn't be copying
1494 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1495 if (dstStrLength.isUndef())
1498 if (Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>()) {
1499 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1503 boundWarning = "Size argument is greater than the free space in the "
1504 "destination buffer";
1508 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1509 // (Yes, strncpy and strncat differ in how they treat termination.
1510 // strncat ALWAYS terminates, but strncpy doesn't.)
1512 // We need a special case for when the copy size is zero, in which
1513 // case strncpy will do no work at all. Our bounds check uses n-1
1514 // as the last element accessed, so n == 0 is problematic.
1515 ProgramStateRef StateZeroSize, StateNonZeroSize;
1516 std::tie(StateZeroSize, StateNonZeroSize) =
1517 assumeZero(C, state, *lenValNL, sizeTy);
1519 // If the size is known to be zero, we're done.
1520 if (StateZeroSize && !StateNonZeroSize) {
1521 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1522 C.addTransition(StateZeroSize);
1526 // Otherwise, go ahead and figure out the last element we'll touch.
1527 // We don't record the non-zero assumption here because we can't
1528 // be sure. We won't warn on a possible zero.
1529 NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
1530 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1532 boundWarning = "Size argument is greater than the length of the "
1533 "destination buffer";
1537 // If we couldn't pin down the copy length, at least bound it.
1538 // FIXME: We should actually run this code path for append as well, but
1539 // right now it creates problems with constraints (since we can end up
1540 // trying to pass constraints from symbol to symbol).
1541 if (amountCopied.isUnknown() && !isAppending) {
1542 // Try to get a "hypothetical" string length symbol, which we can later
1543 // set as a real value if that turns out to be the case.
1544 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1545 assert(!amountCopied.isUndef());
1547 if (Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>()) {
1549 // amountCopied <= lenVal
1550 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1554 state = state->assume(
1555 copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
1561 // amountCopied <= strlen(source)
1562 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1566 state = state->assume(
1567 copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
1575 // The function isn't bounded. The amount copied should match the length
1576 // of the source buffer.
1577 amountCopied = strLength;
1582 // This represents the number of characters copied into the destination
1583 // buffer. (It may not actually be the strlen if the destination buffer
1584 // is not terminated.)
1585 SVal finalStrLength = UnknownVal();
1587 // If this is an appending function (strcat, strncat...) then set the
1588 // string length to strlen(src) + strlen(dst) since the buffer will
1589 // ultimately contain both.
1591 // Get the string length of the destination. If the destination is memory
1592 // that can't have a string length, we shouldn't be copying into it anyway.
1593 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1594 if (dstStrLength.isUndef())
1597 Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
1598 Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
1600 // If we know both string lengths, we might know the final string length.
1601 if (srcStrLengthNL && dstStrLengthNL) {
1602 // Make sure the two lengths together don't overflow a size_t.
1603 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1607 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1608 *dstStrLengthNL, sizeTy);
1611 // If we couldn't get a single value for the final string length,
1612 // we can at least bound it by the individual lengths.
1613 if (finalStrLength.isUnknown()) {
1614 // Try to get a "hypothetical" string length symbol, which we can later
1615 // set as a real value if that turns out to be the case.
1616 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1617 assert(!finalStrLength.isUndef());
1619 if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
1620 if (srcStrLengthNL) {
1621 // finalStrLength >= srcStrLength
1622 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1626 state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
1632 if (dstStrLengthNL) {
1633 // finalStrLength >= dstStrLength
1634 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1639 state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
1647 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1648 // the final string length will match the input string length.
1649 finalStrLength = amountCopied;
1652 // The final result of the function will either be a pointer past the last
1653 // copied element, or a pointer to the start of the destination buffer.
1654 SVal Result = (returnEnd ? UnknownVal() : DstVal);
1658 // If the destination is a MemRegion, try to check for a buffer overflow and
1659 // record the new string length.
1660 if (Optional<loc::MemRegionVal> dstRegVal =
1661 DstVal.getAs<loc::MemRegionVal>()) {
1662 QualType ptrTy = Dst->getType();
1664 // If we have an exact value on a bounded copy, use that to check for
1665 // overflows, rather than our estimate about how much is actually copied.
1667 if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
1668 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1670 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1677 // Then, if the final length is known...
1678 if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
1679 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1680 *knownStrLength, ptrTy);
1682 // ...and we haven't checked the bound, we'll check the actual copy.
1683 if (!boundWarning) {
1684 const char * const warningMsg =
1685 "String copy function overflows destination buffer";
1686 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1691 // If this is a stpcpy-style copy, the last element is the return value.
1693 Result = lastElement;
1696 // Invalidate the destination (regular invalidation without pointer-escaping
1697 // the address of the top-level region). This must happen before we set the
1698 // C string length because invalidation will clear the length.
1699 // FIXME: Even if we can't perfectly model the copy, we should see if we
1700 // can use LazyCompoundVals to copy the source values into the destination.
1701 // This would probably remove any existing bindings past the end of the
1702 // string, but that's still an improvement over blank invalidation.
1703 state = InvalidateBuffer(C, state, Dst, *dstRegVal,
1704 /*IsSourceBuffer*/false, nullptr);
1706 // Invalidate the source (const-invalidation without const-pointer-escaping
1707 // the address of the top-level region).
1708 state = InvalidateBuffer(C, state, srcExpr, srcVal, /*IsSourceBuffer*/true,
1711 // Set the C string length of the destination, if we know it.
1712 if (isBounded && !isAppending) {
1713 // strncpy is annoying in that it doesn't guarantee to null-terminate
1714 // the result string. If the original string didn't fit entirely inside
1715 // the bound (including the null-terminator), we don't know how long the
1717 if (amountCopied != strLength)
1718 finalStrLength = UnknownVal();
1720 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
1725 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1726 // overflow, we still need a result. Conjure a return value.
1727 if (returnEnd && Result.isUnknown()) {
1728 Result = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
1731 // Set the return value.
1732 state = state->BindExpr(CE, LCtx, Result);
1733 C.addTransition(state);
1736 void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1737 if (CE->getNumArgs() < 2)
1740 //int strcmp(const char *s1, const char *s2);
1741 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
1744 void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
1745 if (CE->getNumArgs() < 3)
1748 //int strncmp(const char *s1, const char *s2, size_t n);
1749 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1752 void CStringChecker::evalStrcasecmp(CheckerContext &C,
1753 const CallExpr *CE) const {
1754 if (CE->getNumArgs() < 2)
1757 //int strcasecmp(const char *s1, const char *s2);
1758 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
1761 void CStringChecker::evalStrncasecmp(CheckerContext &C,
1762 const CallExpr *CE) const {
1763 if (CE->getNumArgs() < 3)
1766 //int strncasecmp(const char *s1, const char *s2, size_t n);
1767 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1770 void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
1771 bool isBounded, bool ignoreCase) const {
1772 CurrentFunctionDescription = "string comparison function";
1773 ProgramStateRef state = C.getState();
1774 const LocationContext *LCtx = C.getLocationContext();
1776 // Check that the first string is non-null
1777 const Expr *s1 = CE->getArg(0);
1778 SVal s1Val = state->getSVal(s1, LCtx);
1779 state = checkNonNull(C, state, s1, s1Val);
1783 // Check that the second string is non-null.
1784 const Expr *s2 = CE->getArg(1);
1785 SVal s2Val = state->getSVal(s2, LCtx);
1786 state = checkNonNull(C, state, s2, s2Val);
1790 // Get the string length of the first string or give up.
1791 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1792 if (s1Length.isUndef())
1795 // Get the string length of the second string or give up.
1796 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1797 if (s2Length.isUndef())
1800 // If we know the two buffers are the same, we know the result is 0.
1801 // First, get the two buffers' addresses. Another checker will have already
1802 // made sure they're not undefined.
1803 DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1804 DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
1806 // See if they are the same.
1807 SValBuilder &svalBuilder = C.getSValBuilder();
1808 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1809 ProgramStateRef StSameBuf, StNotSameBuf;
1810 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1812 // If the two arguments might be the same buffer, we know the result is 0,
1813 // and we only need to check one size.
1815 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1816 svalBuilder.makeZeroVal(CE->getType()));
1817 C.addTransition(StSameBuf);
1819 // If the two arguments are GUARANTEED to be the same, we're done!
1824 assert(StNotSameBuf);
1825 state = StNotSameBuf;
1827 // At this point we can go about comparing the two buffers.
1828 // For now, we only do this if they're both known string literals.
1830 // Attempt to extract string literals from both expressions.
1831 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1832 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1833 bool canComputeResult = false;
1834 SVal resultVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1837 if (s1StrLiteral && s2StrLiteral) {
1838 StringRef s1StrRef = s1StrLiteral->getString();
1839 StringRef s2StrRef = s2StrLiteral->getString();
1842 // Get the max number of characters to compare.
1843 const Expr *lenExpr = CE->getArg(2);
1844 SVal lenVal = state->getSVal(lenExpr, LCtx);
1846 // If the length is known, we can get the right substrings.
1847 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1848 // Create substrings of each to compare the prefix.
1849 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1850 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1851 canComputeResult = true;
1854 // This is a normal, unbounded strcmp.
1855 canComputeResult = true;
1858 if (canComputeResult) {
1859 // Real strcmp stops at null characters.
1860 size_t s1Term = s1StrRef.find('\0');
1861 if (s1Term != StringRef::npos)
1862 s1StrRef = s1StrRef.substr(0, s1Term);
1864 size_t s2Term = s2StrRef.find('\0');
1865 if (s2Term != StringRef::npos)
1866 s2StrRef = s2StrRef.substr(0, s2Term);
1868 // Use StringRef's comparison methods to compute the actual result.
1869 int compareRes = ignoreCase ? s1StrRef.compare_lower(s2StrRef)
1870 : s1StrRef.compare(s2StrRef);
1872 // The strcmp function returns an integer greater than, equal to, or less
1873 // than zero, [c11, p7.24.4.2].
1874 if (compareRes == 0) {
1875 resultVal = svalBuilder.makeIntVal(compareRes, CE->getType());
1878 DefinedSVal zeroVal = svalBuilder.makeIntVal(0, CE->getType());
1879 // Constrain strcmp's result range based on the result of StringRef's
1880 // comparison methods.
1881 BinaryOperatorKind op = (compareRes == 1) ? BO_GT : BO_LT;
1882 SVal compareWithZero =
1883 svalBuilder.evalBinOp(state, op, resultVal, zeroVal,
1884 svalBuilder.getConditionType());
1885 DefinedSVal compareWithZeroVal = compareWithZero.castAs<DefinedSVal>();
1886 state = state->assume(compareWithZeroVal, true);
1891 state = state->BindExpr(CE, LCtx, resultVal);
1893 // Record this as a possible path.
1894 C.addTransition(state);
1897 void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
1898 //char *strsep(char **stringp, const char *delim);
1899 if (CE->getNumArgs() < 2)
1902 // Sanity: does the search string parameter match the return type?
1903 const Expr *SearchStrPtr = CE->getArg(0);
1904 QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
1905 if (CharPtrTy.isNull() ||
1906 CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
1909 CurrentFunctionDescription = "strsep()";
1910 ProgramStateRef State = C.getState();
1911 const LocationContext *LCtx = C.getLocationContext();
1913 // Check that the search string pointer is non-null (though it may point to
1915 SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
1916 State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
1920 // Check that the delimiter string is non-null.
1921 const Expr *DelimStr = CE->getArg(1);
1922 SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
1923 State = checkNonNull(C, State, DelimStr, DelimStrVal);
1927 SValBuilder &SVB = C.getSValBuilder();
1929 if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
1930 // Get the current value of the search string pointer, as a char*.
1931 Result = State->getSVal(*SearchStrLoc, CharPtrTy);
1933 // Invalidate the search string, representing the change of one delimiter
1934 // character to NUL.
1935 State = InvalidateBuffer(C, State, SearchStrPtr, Result,
1936 /*IsSourceBuffer*/false, nullptr);
1938 // Overwrite the search string pointer. The new value is either an address
1939 // further along in the same string, or NULL if there are no more tokens.
1940 State = State->bindLoc(*SearchStrLoc,
1941 SVB.conjureSymbolVal(getTag(),
1948 assert(SearchStrVal.isUnknown());
1949 // Conjure a symbolic value. It's the best we can do.
1950 Result = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
1953 // Set the return value, and finish.
1954 State = State->BindExpr(CE, LCtx, Result);
1955 C.addTransition(State);
1958 // These should probably be moved into a C++ standard library checker.
1959 void CStringChecker::evalStdCopy(CheckerContext &C, const CallExpr *CE) const {
1960 evalStdCopyCommon(C, CE);
1963 void CStringChecker::evalStdCopyBackward(CheckerContext &C,
1964 const CallExpr *CE) const {
1965 evalStdCopyCommon(C, CE);
1968 void CStringChecker::evalStdCopyCommon(CheckerContext &C,
1969 const CallExpr *CE) const {
1970 if (CE->getNumArgs() < 3)
1973 ProgramStateRef State = C.getState();
1975 const LocationContext *LCtx = C.getLocationContext();
1977 // template <class _InputIterator, class _OutputIterator>
1979 // copy(_InputIterator __first, _InputIterator __last,
1980 // _OutputIterator __result)
1982 // Invalidate the destination buffer
1983 const Expr *Dst = CE->getArg(2);
1984 SVal DstVal = State->getSVal(Dst, LCtx);
1985 State = InvalidateBuffer(C, State, Dst, DstVal, /*IsSource=*/false,
1988 SValBuilder &SVB = C.getSValBuilder();
1990 SVal ResultVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
1991 State = State->BindExpr(CE, LCtx, ResultVal);
1993 C.addTransition(State);
1996 void CStringChecker::evalMemset(CheckerContext &C, const CallExpr *CE) const {
1997 if (CE->getNumArgs() != 3)
2000 CurrentFunctionDescription = "memory set function";
2002 const Expr *Mem = CE->getArg(0);
2003 const Expr *Size = CE->getArg(2);
2004 ProgramStateRef State = C.getState();
2006 // See if the size argument is zero.
2007 const LocationContext *LCtx = C.getLocationContext();
2008 SVal SizeVal = State->getSVal(Size, LCtx);
2009 QualType SizeTy = Size->getType();
2011 ProgramStateRef StateZeroSize, StateNonZeroSize;
2012 std::tie(StateZeroSize, StateNonZeroSize) =
2013 assumeZero(C, State, SizeVal, SizeTy);
2015 // Get the value of the memory area.
2016 SVal MemVal = State->getSVal(Mem, LCtx);
2018 // If the size is zero, there won't be any actual memory access, so
2019 // just bind the return value to the Mem buffer and return.
2020 if (StateZeroSize && !StateNonZeroSize) {
2021 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, MemVal);
2022 C.addTransition(StateZeroSize);
2026 // Ensure the memory area is not null.
2027 // If it is NULL there will be a NULL pointer dereference.
2028 State = checkNonNull(C, StateNonZeroSize, Mem, MemVal);
2032 State = CheckBufferAccess(C, State, Size, Mem);
2035 State = InvalidateBuffer(C, State, Mem, C.getSVal(Mem),
2036 /*IsSourceBuffer*/false, Size);
2040 State = State->BindExpr(CE, LCtx, MemVal);
2041 C.addTransition(State);
2044 static bool isCPPStdLibraryFunction(const FunctionDecl *FD, StringRef Name) {
2045 IdentifierInfo *II = FD->getIdentifier();
2049 if (!AnalysisDeclContext::isInStdNamespace(FD))
2052 if (II->getName().equals(Name))
2057 //===----------------------------------------------------------------------===//
2058 // The driver method, and other Checker callbacks.
2059 //===----------------------------------------------------------------------===//
2061 bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
2062 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
2067 // FIXME: Poorly-factored string switches are slow.
2068 FnCheck evalFunction = nullptr;
2069 if (C.isCLibraryFunction(FDecl, "memcpy"))
2070 evalFunction = &CStringChecker::evalMemcpy;
2071 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
2072 evalFunction = &CStringChecker::evalMempcpy;
2073 else if (C.isCLibraryFunction(FDecl, "memcmp"))
2074 evalFunction = &CStringChecker::evalMemcmp;
2075 else if (C.isCLibraryFunction(FDecl, "memmove"))
2076 evalFunction = &CStringChecker::evalMemmove;
2077 else if (C.isCLibraryFunction(FDecl, "memset"))
2078 evalFunction = &CStringChecker::evalMemset;
2079 else if (C.isCLibraryFunction(FDecl, "strcpy"))
2080 evalFunction = &CStringChecker::evalStrcpy;
2081 else if (C.isCLibraryFunction(FDecl, "strncpy"))
2082 evalFunction = &CStringChecker::evalStrncpy;
2083 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
2084 evalFunction = &CStringChecker::evalStpcpy;
2085 else if (C.isCLibraryFunction(FDecl, "strcat"))
2086 evalFunction = &CStringChecker::evalStrcat;
2087 else if (C.isCLibraryFunction(FDecl, "strncat"))
2088 evalFunction = &CStringChecker::evalStrncat;
2089 else if (C.isCLibraryFunction(FDecl, "strlen"))
2090 evalFunction = &CStringChecker::evalstrLength;
2091 else if (C.isCLibraryFunction(FDecl, "strnlen"))
2092 evalFunction = &CStringChecker::evalstrnLength;
2093 else if (C.isCLibraryFunction(FDecl, "strcmp"))
2094 evalFunction = &CStringChecker::evalStrcmp;
2095 else if (C.isCLibraryFunction(FDecl, "strncmp"))
2096 evalFunction = &CStringChecker::evalStrncmp;
2097 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
2098 evalFunction = &CStringChecker::evalStrcasecmp;
2099 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
2100 evalFunction = &CStringChecker::evalStrncasecmp;
2101 else if (C.isCLibraryFunction(FDecl, "strsep"))
2102 evalFunction = &CStringChecker::evalStrsep;
2103 else if (C.isCLibraryFunction(FDecl, "bcopy"))
2104 evalFunction = &CStringChecker::evalBcopy;
2105 else if (C.isCLibraryFunction(FDecl, "bcmp"))
2106 evalFunction = &CStringChecker::evalMemcmp;
2107 else if (isCPPStdLibraryFunction(FDecl, "copy"))
2108 evalFunction = &CStringChecker::evalStdCopy;
2109 else if (isCPPStdLibraryFunction(FDecl, "copy_backward"))
2110 evalFunction = &CStringChecker::evalStdCopyBackward;
2112 // If the callee isn't a string function, let another checker handle it.
2116 // Check and evaluate the call.
2117 (this->*evalFunction)(C, CE);
2119 // If the evaluate call resulted in no change, chain to the next eval call
2121 // Note, the custom CString evaluation calls assume that basic safety
2122 // properties are held. However, if the user chooses to turn off some of these
2123 // checks, we ignore the issues and leave the call evaluation to a generic
2125 return C.isDifferent();
2128 void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
2129 // Record string length for char a[] = "abc";
2130 ProgramStateRef state = C.getState();
2132 for (const auto *I : DS->decls()) {
2133 const VarDecl *D = dyn_cast<VarDecl>(I);
2137 // FIXME: Handle array fields of structs.
2138 if (!D->getType()->isArrayType())
2141 const Expr *Init = D->getInit();
2144 if (!isa<StringLiteral>(Init))
2147 Loc VarLoc = state->getLValue(D, C.getLocationContext());
2148 const MemRegion *MR = VarLoc.getAsRegion();
2152 SVal StrVal = state->getSVal(Init, C.getLocationContext());
2153 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
2154 DefinedOrUnknownSVal strLength =
2155 getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
2157 state = state->set<CStringLength>(MR, strLength);
2160 C.addTransition(state);
2164 CStringChecker::checkRegionChanges(ProgramStateRef state,
2165 const InvalidatedSymbols *,
2166 ArrayRef<const MemRegion *> ExplicitRegions,
2167 ArrayRef<const MemRegion *> Regions,
2168 const LocationContext *LCtx,
2169 const CallEvent *Call) const {
2170 CStringLengthTy Entries = state->get<CStringLength>();
2171 if (Entries.isEmpty())
2174 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
2175 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
2177 // First build sets for the changed regions and their super-regions.
2178 for (ArrayRef<const MemRegion *>::iterator
2179 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
2180 const MemRegion *MR = *I;
2181 Invalidated.insert(MR);
2183 SuperRegions.insert(MR);
2184 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
2185 MR = SR->getSuperRegion();
2186 SuperRegions.insert(MR);
2190 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2192 // Then loop over the entries in the current state.
2193 for (CStringLengthTy::iterator I = Entries.begin(),
2194 E = Entries.end(); I != E; ++I) {
2195 const MemRegion *MR = I.getKey();
2197 // Is this entry for a super-region of a changed region?
2198 if (SuperRegions.count(MR)) {
2199 Entries = F.remove(Entries, MR);
2203 // Is this entry for a sub-region of a changed region?
2204 const MemRegion *Super = MR;
2205 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2206 Super = SR->getSuperRegion();
2207 if (Invalidated.count(Super)) {
2208 Entries = F.remove(Entries, MR);
2214 return state->set<CStringLength>(Entries);
2217 void CStringChecker::checkLiveSymbols(ProgramStateRef state,
2218 SymbolReaper &SR) const {
2219 // Mark all symbols in our string length map as valid.
2220 CStringLengthTy Entries = state->get<CStringLength>();
2222 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2224 SVal Len = I.getData();
2226 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2227 se = Len.symbol_end(); si != se; ++si)
2232 void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2233 CheckerContext &C) const {
2234 if (!SR.hasDeadSymbols())
2237 ProgramStateRef state = C.getState();
2238 CStringLengthTy Entries = state->get<CStringLength>();
2239 if (Entries.isEmpty())
2242 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2243 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2245 SVal Len = I.getData();
2246 if (SymbolRef Sym = Len.getAsSymbol()) {
2248 Entries = F.remove(Entries, I.getKey());
2252 state = state->set<CStringLength>(Entries);
2253 C.addTransition(state);
2256 #define REGISTER_CHECKER(name) \
2257 void ento::register##name(CheckerManager &mgr) { \
2258 CStringChecker *checker = mgr.registerChecker<CStringChecker>(); \
2259 checker->Filter.Check##name = true; \
2260 checker->Filter.CheckName##name = mgr.getCurrentCheckName(); \
2263 REGISTER_CHECKER(CStringNullArg)
2264 REGISTER_CHECKER(CStringOutOfBounds)
2265 REGISTER_CHECKER(CStringBufferOverlap)
2266 REGISTER_CHECKER(CStringNotNullTerm)
2268 void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
2269 registerCStringNullArg(Mgr);