1 //= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This defines CStringChecker, which is an assortment of checks on calls
10 // to functions in <string.h>.
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15 #include "InterCheckerAPI.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18 #include "clang/StaticAnalyzer/Core/Checker.h"
19 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.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 CallEvent &Call, 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;
76 CallDescriptionMap<FnCheck> Callbacks = {
77 {{CDF_MaybeBuiltin, "memcpy", 3}, &CStringChecker::evalMemcpy},
78 {{CDF_MaybeBuiltin, "mempcpy", 3}, &CStringChecker::evalMempcpy},
79 {{CDF_MaybeBuiltin, "memcmp", 3}, &CStringChecker::evalMemcmp},
80 {{CDF_MaybeBuiltin, "memmove", 3}, &CStringChecker::evalMemmove},
81 {{CDF_MaybeBuiltin, "memset", 3}, &CStringChecker::evalMemset},
82 {{CDF_MaybeBuiltin, "explicit_memset", 3}, &CStringChecker::evalMemset},
83 {{CDF_MaybeBuiltin, "strcpy", 2}, &CStringChecker::evalStrcpy},
84 {{CDF_MaybeBuiltin, "strncpy", 3}, &CStringChecker::evalStrncpy},
85 {{CDF_MaybeBuiltin, "stpcpy", 2}, &CStringChecker::evalStpcpy},
86 {{CDF_MaybeBuiltin, "strlcpy", 3}, &CStringChecker::evalStrlcpy},
87 {{CDF_MaybeBuiltin, "strcat", 2}, &CStringChecker::evalStrcat},
88 {{CDF_MaybeBuiltin, "strncat", 3}, &CStringChecker::evalStrncat},
89 {{CDF_MaybeBuiltin, "strlcat", 3}, &CStringChecker::evalStrlcat},
90 {{CDF_MaybeBuiltin, "strlen", 1}, &CStringChecker::evalstrLength},
91 {{CDF_MaybeBuiltin, "strnlen", 2}, &CStringChecker::evalstrnLength},
92 {{CDF_MaybeBuiltin, "strcmp", 2}, &CStringChecker::evalStrcmp},
93 {{CDF_MaybeBuiltin, "strncmp", 3}, &CStringChecker::evalStrncmp},
94 {{CDF_MaybeBuiltin, "strcasecmp", 2}, &CStringChecker::evalStrcasecmp},
95 {{CDF_MaybeBuiltin, "strncasecmp", 3}, &CStringChecker::evalStrncasecmp},
96 {{CDF_MaybeBuiltin, "strsep", 2}, &CStringChecker::evalStrsep},
97 {{CDF_MaybeBuiltin, "bcopy", 3}, &CStringChecker::evalBcopy},
98 {{CDF_MaybeBuiltin, "bcmp", 3}, &CStringChecker::evalMemcmp},
99 {{CDF_MaybeBuiltin, "bzero", 2}, &CStringChecker::evalBzero},
100 {{CDF_MaybeBuiltin, "explicit_bzero", 2}, &CStringChecker::evalBzero},
103 // These require a bit of special handling.
104 CallDescription StdCopy{{"std", "copy"}, 3},
105 StdCopyBackward{{"std", "copy_backward"}, 3};
107 FnCheck identifyCall(const CallEvent &Call, CheckerContext &C) const;
108 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
109 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
110 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
111 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
112 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
113 ProgramStateRef state,
117 bool Restricted = false,
118 bool IsMempcpy = false) const;
120 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
122 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
123 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
124 void evalstrLengthCommon(CheckerContext &C,
126 bool IsStrnlen = false) const;
128 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
129 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
130 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
131 void evalStrlcpy(CheckerContext &C, const CallExpr *CE) const;
132 void evalStrcpyCommon(CheckerContext &C,
137 bool returnPtr = true) const;
139 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
140 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
141 void evalStrlcat(CheckerContext &C, const CallExpr *CE) const;
143 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
144 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
145 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
146 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
147 void evalStrcmpCommon(CheckerContext &C,
149 bool isBounded = false,
150 bool ignoreCase = false) const;
152 void evalStrsep(CheckerContext &C, const CallExpr *CE) const;
154 void evalStdCopy(CheckerContext &C, const CallExpr *CE) const;
155 void evalStdCopyBackward(CheckerContext &C, const CallExpr *CE) const;
156 void evalStdCopyCommon(CheckerContext &C, const CallExpr *CE) const;
157 void evalMemset(CheckerContext &C, const CallExpr *CE) const;
158 void evalBzero(CheckerContext &C, const CallExpr *CE) const;
161 std::pair<ProgramStateRef , ProgramStateRef >
162 static assumeZero(CheckerContext &C,
163 ProgramStateRef state, SVal V, QualType Ty);
165 static ProgramStateRef setCStringLength(ProgramStateRef state,
168 static SVal getCStringLengthForRegion(CheckerContext &C,
169 ProgramStateRef &state,
173 SVal getCStringLength(CheckerContext &C,
174 ProgramStateRef &state,
177 bool hypothetical = false) const;
179 const StringLiteral *getCStringLiteral(CheckerContext &C,
180 ProgramStateRef &state,
184 static ProgramStateRef InvalidateBuffer(CheckerContext &C,
185 ProgramStateRef state,
186 const Expr *Ex, SVal V,
190 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
191 const MemRegion *MR);
193 static bool memsetAux(const Expr *DstBuffer, SVal CharE,
194 const Expr *Size, CheckerContext &C,
195 ProgramStateRef &State);
198 ProgramStateRef checkNonNull(CheckerContext &C,
199 ProgramStateRef state,
202 ProgramStateRef CheckLocation(CheckerContext &C,
203 ProgramStateRef state,
206 const char *message = nullptr) const;
207 ProgramStateRef CheckBufferAccess(CheckerContext &C,
208 ProgramStateRef state,
210 const Expr *FirstBuf,
211 const Expr *SecondBuf,
212 const char *firstMessage = nullptr,
213 const char *secondMessage = nullptr,
214 bool WarnAboutSize = false) const;
216 ProgramStateRef CheckBufferAccess(CheckerContext &C,
217 ProgramStateRef state,
220 const char *message = nullptr,
221 bool WarnAboutSize = false) const {
222 // This is a convenience overload.
223 return CheckBufferAccess(C, state, Size, Buf, nullptr, message, nullptr,
226 ProgramStateRef CheckOverlap(CheckerContext &C,
227 ProgramStateRef state,
230 const Expr *Second) const;
231 void emitOverlapBug(CheckerContext &C,
232 ProgramStateRef state,
234 const Stmt *Second) const;
236 void emitNullArgBug(CheckerContext &C, ProgramStateRef State, const Stmt *S,
237 StringRef WarningMsg) const;
238 void emitOutOfBoundsBug(CheckerContext &C, ProgramStateRef State,
239 const Stmt *S, StringRef WarningMsg) const;
240 void emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
241 const Stmt *S, StringRef WarningMsg) const;
242 void emitAdditionOverflowBug(CheckerContext &C, ProgramStateRef State) const;
244 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
245 ProgramStateRef state,
249 // Return true if the destination buffer of the copy function may be in bound.
250 // Expects SVal of Size to be positive and unsigned.
251 // Expects SVal of FirstBuf to be a FieldRegion.
252 static bool IsFirstBufInBound(CheckerContext &C,
253 ProgramStateRef state,
254 const Expr *FirstBuf,
258 } //end anonymous namespace
260 REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
262 //===----------------------------------------------------------------------===//
263 // Individual checks and utility methods.
264 //===----------------------------------------------------------------------===//
266 std::pair<ProgramStateRef , ProgramStateRef >
267 CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
269 Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
271 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
273 SValBuilder &svalBuilder = C.getSValBuilder();
274 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
275 return state->assume(svalBuilder.evalEQ(state, *val, zero));
278 ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
279 ProgramStateRef state,
280 const Expr *S, SVal l) const {
281 // If a previous check has failed, propagate the failure.
285 ProgramStateRef stateNull, stateNonNull;
286 std::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
288 if (stateNull && !stateNonNull) {
289 if (Filter.CheckCStringNullArg) {
291 llvm::raw_svector_ostream os(buf);
292 assert(CurrentFunctionDescription);
293 os << "Null pointer argument in call to " << CurrentFunctionDescription;
295 emitNullArgBug(C, stateNull, S, os.str());
300 // From here on, assume that the value is non-null.
301 assert(stateNonNull);
305 // FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
306 ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
307 ProgramStateRef state,
308 const Expr *S, SVal l,
309 const char *warningMsg) const {
310 // If a previous check has failed, propagate the failure.
314 // Check for out of bound array element access.
315 const MemRegion *R = l.getAsRegion();
319 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
323 if (ER->getValueType() != C.getASTContext().CharTy)
326 // Get the size of the array.
327 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
328 SValBuilder &svalBuilder = C.getSValBuilder();
330 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
331 DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>();
333 // Get the index of the accessed element.
334 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
336 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
337 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
338 if (StOutBound && !StInBound) {
339 // These checks are either enabled by the CString out-of-bounds checker
340 // explicitly or implicitly by the Malloc checker.
341 // In the latter case we only do modeling but do not emit warning.
342 if (!Filter.CheckCStringOutOfBounds)
344 // Emit a bug report.
346 emitOutOfBoundsBug(C, StOutBound, S, warningMsg);
348 assert(CurrentFunctionDescription);
349 assert(CurrentFunctionDescription[0] != '\0');
352 llvm::raw_svector_ostream os(buf);
353 os << toUppercase(CurrentFunctionDescription[0])
354 << &CurrentFunctionDescription[1]
355 << " accesses out-of-bound array element";
356 emitOutOfBoundsBug(C, StOutBound, S, os.str());
361 // Array bound check succeeded. From this point forward the array bound
362 // should always succeed.
366 ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
367 ProgramStateRef state,
369 const Expr *FirstBuf,
370 const Expr *SecondBuf,
371 const char *firstMessage,
372 const char *secondMessage,
373 bool WarnAboutSize) const {
374 // If a previous check has failed, propagate the failure.
378 SValBuilder &svalBuilder = C.getSValBuilder();
379 ASTContext &Ctx = svalBuilder.getContext();
380 const LocationContext *LCtx = C.getLocationContext();
382 QualType sizeTy = Size->getType();
383 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
385 // Check that the first buffer is non-null.
386 SVal BufVal = C.getSVal(FirstBuf);
387 state = checkNonNull(C, state, FirstBuf, BufVal);
391 // If out-of-bounds checking is turned off, skip the rest.
392 if (!Filter.CheckCStringOutOfBounds)
395 // Get the access length and make sure it is known.
396 // FIXME: This assumes the caller has already checked that the access length
397 // is positive. And that it's unsigned.
398 SVal LengthVal = C.getSVal(Size);
399 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
403 // Compute the offset of the last element to be accessed: size-1.
404 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
405 SVal Offset = svalBuilder.evalBinOpNN(state, BO_Sub, *Length, One, sizeTy);
406 if (Offset.isUnknown())
408 NonLoc LastOffset = Offset.castAs<NonLoc>();
410 // Check that the first buffer is sufficiently long.
411 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
412 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
413 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
415 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
417 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
419 // If the buffer isn't large enough, abort.
424 // If there's a second buffer, check it as well.
426 BufVal = state->getSVal(SecondBuf, LCtx);
427 state = checkNonNull(C, state, SecondBuf, BufVal);
431 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
432 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
433 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
435 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
437 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
441 // Large enough or not, return this state!
445 ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
446 ProgramStateRef state,
449 const Expr *Second) const {
450 if (!Filter.CheckCStringBufferOverlap)
453 // Do a simple check for overlap: if the two arguments are from the same
454 // buffer, see if the end of the first is greater than the start of the second
457 // If a previous check has failed, propagate the failure.
461 ProgramStateRef stateTrue, stateFalse;
463 // Get the buffer values and make sure they're known locations.
464 const LocationContext *LCtx = C.getLocationContext();
465 SVal firstVal = state->getSVal(First, LCtx);
466 SVal secondVal = state->getSVal(Second, LCtx);
468 Optional<Loc> firstLoc = firstVal.getAs<Loc>();
472 Optional<Loc> secondLoc = secondVal.getAs<Loc>();
476 // Are the two values the same?
477 SValBuilder &svalBuilder = C.getSValBuilder();
478 std::tie(stateTrue, stateFalse) =
479 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
481 if (stateTrue && !stateFalse) {
482 // If the values are known to be equal, that's automatically an overlap.
483 emitOverlapBug(C, stateTrue, First, Second);
487 // assume the two expressions are not equal.
491 // Which value comes first?
492 QualType cmpTy = svalBuilder.getConditionType();
493 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
494 *firstLoc, *secondLoc, cmpTy);
495 Optional<DefinedOrUnknownSVal> reverseTest =
496 reverse.getAs<DefinedOrUnknownSVal>();
500 std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
503 // If we don't know which one comes first, we can't perform this test.
506 // Switch the values so that firstVal is before secondVal.
507 std::swap(firstLoc, secondLoc);
509 // Switch the Exprs as well, so that they still correspond.
510 std::swap(First, Second);
514 // Get the length, and make sure it too is known.
515 SVal LengthVal = state->getSVal(Size, LCtx);
516 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
520 // Convert the first buffer's start address to char*.
521 // Bail out if the cast fails.
522 ASTContext &Ctx = svalBuilder.getContext();
523 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
524 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
526 Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
530 // Compute the end of the first buffer. Bail out if THAT fails.
531 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
532 *FirstStartLoc, *Length, CharPtrTy);
533 Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
537 // Is the end of the first buffer past the start of the second buffer?
538 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
539 *FirstEndLoc, *secondLoc, cmpTy);
540 Optional<DefinedOrUnknownSVal> OverlapTest =
541 Overlap.getAs<DefinedOrUnknownSVal>();
545 std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
547 if (stateTrue && !stateFalse) {
549 emitOverlapBug(C, stateTrue, First, Second);
553 // assume the two expressions don't overlap.
558 void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
559 const Stmt *First, const Stmt *Second) const {
560 ExplodedNode *N = C.generateErrorNode(state);
565 BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
566 categories::UnixAPI, "Improper arguments"));
568 // Generate a report for this bug.
569 auto report = llvm::make_unique<BugReport>(
570 *BT_Overlap, "Arguments must not be overlapping buffers", N);
571 report->addRange(First->getSourceRange());
572 report->addRange(Second->getSourceRange());
574 C.emitReport(std::move(report));
577 void CStringChecker::emitNullArgBug(CheckerContext &C, ProgramStateRef State,
578 const Stmt *S, StringRef WarningMsg) const {
579 if (ExplodedNode *N = C.generateErrorNode(State)) {
581 BT_Null.reset(new BuiltinBug(
582 Filter.CheckNameCStringNullArg, categories::UnixAPI,
583 "Null pointer argument in call to byte string function"));
585 BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Null.get());
586 auto Report = llvm::make_unique<BugReport>(*BT, WarningMsg, N);
587 Report->addRange(S->getSourceRange());
588 if (const auto *Ex = dyn_cast<Expr>(S))
589 bugreporter::trackExpressionValue(N, Ex, *Report);
590 C.emitReport(std::move(Report));
594 void CStringChecker::emitOutOfBoundsBug(CheckerContext &C,
595 ProgramStateRef State, const Stmt *S,
596 StringRef WarningMsg) const {
597 if (ExplodedNode *N = C.generateErrorNode(State)) {
599 BT_Bounds.reset(new BuiltinBug(
600 Filter.CheckCStringOutOfBounds ? Filter.CheckNameCStringOutOfBounds
601 : Filter.CheckNameCStringNullArg,
602 "Out-of-bound array access",
603 "Byte string function accesses out-of-bound array element"));
605 BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Bounds.get());
607 // FIXME: It would be nice to eventually make this diagnostic more clear,
608 // e.g., by referencing the original declaration or by saying *why* this
609 // reference is outside the range.
610 auto Report = llvm::make_unique<BugReport>(*BT, WarningMsg, N);
611 Report->addRange(S->getSourceRange());
612 C.emitReport(std::move(Report));
616 void CStringChecker::emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
618 StringRef WarningMsg) const {
619 if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
621 BT_NotCString.reset(new BuiltinBug(
622 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
623 "Argument is not a null-terminated string."));
625 auto Report = llvm::make_unique<BugReport>(*BT_NotCString, WarningMsg, N);
627 Report->addRange(S->getSourceRange());
628 C.emitReport(std::move(Report));
632 void CStringChecker::emitAdditionOverflowBug(CheckerContext &C,
633 ProgramStateRef State) const {
634 if (ExplodedNode *N = C.generateErrorNode(State)) {
637 new BuiltinBug(Filter.CheckNameCStringOutOfBounds, "API",
638 "Sum of expressions causes overflow."));
640 // This isn't a great error message, but this should never occur in real
641 // code anyway -- you'd have to create a buffer longer than a size_t can
642 // represent, which is sort of a contradiction.
643 const char *WarningMsg =
644 "This expression will create a string whose length is too big to "
645 "be represented as a size_t";
647 auto Report = llvm::make_unique<BugReport>(*BT_NotCString, WarningMsg, N);
648 C.emitReport(std::move(Report));
652 ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
653 ProgramStateRef state,
655 NonLoc right) const {
656 // If out-of-bounds checking is turned off, skip the rest.
657 if (!Filter.CheckCStringOutOfBounds)
660 // If a previous check has failed, propagate the failure.
664 SValBuilder &svalBuilder = C.getSValBuilder();
665 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
667 QualType sizeTy = svalBuilder.getContext().getSizeType();
668 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
669 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
672 if (right.getAs<nonloc::ConcreteInt>()) {
673 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
676 // Try switching the operands. (The order of these two assignments is
678 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
683 if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
684 QualType cmpTy = svalBuilder.getConditionType();
685 // If left > max - right, we have an overflow.
686 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
687 *maxMinusRightNL, cmpTy);
689 ProgramStateRef stateOverflow, stateOkay;
690 std::tie(stateOverflow, stateOkay) =
691 state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
693 if (stateOverflow && !stateOkay) {
694 // We have an overflow. Emit a bug report.
695 emitAdditionOverflowBug(C, stateOverflow);
699 // From now on, assume an overflow didn't occur.
707 ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
710 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
712 MR = MR->StripCasts();
714 switch (MR->getKind()) {
715 case MemRegion::StringRegionKind:
716 // FIXME: This can happen if we strcpy() into a string region. This is
717 // undefined [C99 6.4.5p6], but we should still warn about it.
720 case MemRegion::SymbolicRegionKind:
721 case MemRegion::AllocaRegionKind:
722 case MemRegion::VarRegionKind:
723 case MemRegion::FieldRegionKind:
724 case MemRegion::ObjCIvarRegionKind:
725 // These are the types we can currently track string lengths for.
728 case MemRegion::ElementRegionKind:
729 // FIXME: Handle element regions by upper-bounding the parent region's
734 // Other regions (mostly non-data) can't have a reliable C string length.
735 // For now, just ignore the change.
736 // FIXME: These are rare but not impossible. We should output some kind of
737 // warning for things like strcpy((char[]){'a', 0}, "b");
741 if (strLength.isUnknown())
742 return state->remove<CStringLength>(MR);
744 return state->set<CStringLength>(MR, strLength);
747 SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
748 ProgramStateRef &state,
753 // If there's a recorded length, go ahead and return it.
754 const SVal *Recorded = state->get<CStringLength>(MR);
759 // Otherwise, get a new symbol and update the state.
760 SValBuilder &svalBuilder = C.getSValBuilder();
761 QualType sizeTy = svalBuilder.getContext().getSizeType();
762 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
764 C.getLocationContext(),
768 if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
769 // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
770 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
771 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
772 llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
773 const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
775 NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
776 SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
778 state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
780 state = state->set<CStringLength>(MR, strLength);
786 SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
787 const Expr *Ex, SVal Buf,
788 bool hypothetical) const {
789 const MemRegion *MR = Buf.getAsRegion();
791 // If we can't get a region, see if it's something we /know/ isn't a
792 // C string. In the context of locations, the only time we can issue such
793 // a warning is for labels.
794 if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
795 if (Filter.CheckCStringNotNullTerm) {
796 SmallString<120> buf;
797 llvm::raw_svector_ostream os(buf);
798 assert(CurrentFunctionDescription);
799 os << "Argument to " << CurrentFunctionDescription
800 << " is the address of the label '" << Label->getLabel()->getName()
801 << "', which is not a null-terminated string";
803 emitNotCStringBug(C, state, Ex, os.str());
805 return UndefinedVal();
808 // If it's not a region and not a label, give up.
812 // If we have a region, strip casts from it and see if we can figure out
813 // its length. For anything we can't figure out, just return UnknownVal.
814 MR = MR->StripCasts();
816 switch (MR->getKind()) {
817 case MemRegion::StringRegionKind: {
818 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
819 // so we can assume that the byte length is the correct C string length.
820 SValBuilder &svalBuilder = C.getSValBuilder();
821 QualType sizeTy = svalBuilder.getContext().getSizeType();
822 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
823 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
825 case MemRegion::SymbolicRegionKind:
826 case MemRegion::AllocaRegionKind:
827 case MemRegion::VarRegionKind:
828 case MemRegion::FieldRegionKind:
829 case MemRegion::ObjCIvarRegionKind:
830 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
831 case MemRegion::CompoundLiteralRegionKind:
832 // FIXME: Can we track this? Is it necessary?
834 case MemRegion::ElementRegionKind:
835 // FIXME: How can we handle this? It's not good enough to subtract the
836 // offset from the base string length; consider "123\x00567" and &a[5].
839 // Other regions (mostly non-data) can't have a reliable C string length.
840 // In this case, an error is emitted and UndefinedVal is returned.
841 // The caller should always be prepared to handle this case.
842 if (Filter.CheckCStringNotNullTerm) {
843 SmallString<120> buf;
844 llvm::raw_svector_ostream os(buf);
846 assert(CurrentFunctionDescription);
847 os << "Argument to " << CurrentFunctionDescription << " is ";
849 if (SummarizeRegion(os, C.getASTContext(), MR))
850 os << ", which is not a null-terminated string";
852 os << "not a null-terminated string";
854 emitNotCStringBug(C, state, Ex, os.str());
856 return UndefinedVal();
860 const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
861 ProgramStateRef &state, const Expr *expr, SVal val) const {
863 // Get the memory region pointed to by the val.
864 const MemRegion *bufRegion = val.getAsRegion();
868 // Strip casts off the memory region.
869 bufRegion = bufRegion->StripCasts();
871 // Cast the memory region to a string region.
872 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
876 // Return the actual string in the string region.
877 return strRegion->getStringLiteral();
880 bool CStringChecker::IsFirstBufInBound(CheckerContext &C,
881 ProgramStateRef state,
882 const Expr *FirstBuf,
884 // If we do not know that the buffer is long enough we return 'true'.
885 // Otherwise the parent region of this field region would also get
886 // invalidated, which would lead to warnings based on an unknown state.
888 // Originally copied from CheckBufferAccess and CheckLocation.
889 SValBuilder &svalBuilder = C.getSValBuilder();
890 ASTContext &Ctx = svalBuilder.getContext();
891 const LocationContext *LCtx = C.getLocationContext();
893 QualType sizeTy = Size->getType();
894 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
895 SVal BufVal = state->getSVal(FirstBuf, LCtx);
897 SVal LengthVal = state->getSVal(Size, LCtx);
898 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
900 return true; // cf top comment.
902 // Compute the offset of the last element to be accessed: size-1.
903 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
904 SVal Offset = svalBuilder.evalBinOpNN(state, BO_Sub, *Length, One, sizeTy);
905 if (Offset.isUnknown())
906 return true; // cf top comment
907 NonLoc LastOffset = Offset.castAs<NonLoc>();
909 // Check that the first buffer is sufficiently long.
910 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
911 Optional<Loc> BufLoc = BufStart.getAs<Loc>();
913 return true; // cf top comment.
916 svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc, LastOffset, PtrTy);
918 // Check for out of bound array element access.
919 const MemRegion *R = BufEnd.getAsRegion();
921 return true; // cf top comment.
923 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
925 return true; // cf top comment.
927 // FIXME: Does this crash when a non-standard definition
928 // of a library function is encountered?
929 assert(ER->getValueType() == C.getASTContext().CharTy &&
930 "IsFirstBufInBound should only be called with char* ElementRegions");
932 // Get the size of the array.
933 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
935 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
936 DefinedOrUnknownSVal ExtentSize = Extent.castAs<DefinedOrUnknownSVal>();
938 // Get the index of the accessed element.
939 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
941 ProgramStateRef StInBound = state->assumeInBound(Idx, ExtentSize, true);
943 return static_cast<bool>(StInBound);
946 ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
947 ProgramStateRef state,
948 const Expr *E, SVal V,
951 Optional<Loc> L = V.getAs<Loc>();
955 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
956 // some assumptions about the value that CFRefCount can't. Even so, it should
957 // probably be refactored.
958 if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
959 const MemRegion *R = MR->getRegion()->StripCasts();
961 // Are we dealing with an ElementRegion? If so, we should be invalidating
963 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
964 R = ER->getSuperRegion();
965 // FIXME: What about layers of ElementRegions?
968 // Invalidate this region.
969 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
971 bool CausesPointerEscape = false;
972 RegionAndSymbolInvalidationTraits ITraits;
973 // Invalidate and escape only indirect regions accessible through the source
975 if (IsSourceBuffer) {
976 ITraits.setTrait(R->getBaseRegion(),
977 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
978 ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
979 CausesPointerEscape = true;
981 const MemRegion::Kind& K = R->getKind();
982 if (K == MemRegion::FieldRegionKind)
983 if (Size && IsFirstBufInBound(C, state, E, Size)) {
984 // If destination buffer is a field region and access is in bound,
985 // do not invalidate its super region.
988 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
992 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
993 CausesPointerEscape, nullptr, nullptr,
997 // If we have a non-region value by chance, just remove the binding.
998 // FIXME: is this necessary or correct? This handles the non-Region
999 // cases. Is it ever valid to store to these?
1000 return state->killBinding(*L);
1003 bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
1004 const MemRegion *MR) {
1005 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
1007 switch (MR->getKind()) {
1008 case MemRegion::FunctionCodeRegionKind: {
1009 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1011 os << "the address of the function '" << *FD << '\'';
1013 os << "the address of a function";
1016 case MemRegion::BlockCodeRegionKind:
1019 case MemRegion::BlockDataRegionKind:
1022 case MemRegion::CXXThisRegionKind:
1023 case MemRegion::CXXTempObjectRegionKind:
1024 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
1026 case MemRegion::VarRegionKind:
1027 os << "a variable of type" << TVR->getValueType().getAsString();
1029 case MemRegion::FieldRegionKind:
1030 os << "a field of type " << TVR->getValueType().getAsString();
1032 case MemRegion::ObjCIvarRegionKind:
1033 os << "an instance variable of type " << TVR->getValueType().getAsString();
1040 bool CStringChecker::memsetAux(const Expr *DstBuffer, SVal CharVal,
1041 const Expr *Size, CheckerContext &C,
1042 ProgramStateRef &State) {
1043 SVal MemVal = C.getSVal(DstBuffer);
1044 SVal SizeVal = C.getSVal(Size);
1045 const MemRegion *MR = MemVal.getAsRegion();
1049 // We're about to model memset by producing a "default binding" in the Store.
1050 // Our current implementation - RegionStore - doesn't support default bindings
1051 // that don't cover the whole base region. So we should first get the offset
1052 // and the base region to figure out whether the offset of buffer is 0.
1053 RegionOffset Offset = MR->getAsOffset();
1054 const MemRegion *BR = Offset.getRegion();
1056 Optional<NonLoc> SizeNL = SizeVal.getAs<NonLoc>();
1060 SValBuilder &svalBuilder = C.getSValBuilder();
1061 ASTContext &Ctx = C.getASTContext();
1063 // void *memset(void *dest, int ch, size_t count);
1064 // For now we can only handle the case of offset is 0 and concrete char value.
1065 if (Offset.isValid() && !Offset.hasSymbolicOffset() &&
1066 Offset.getOffset() == 0) {
1067 // Get the base region's extent.
1068 auto *SubReg = cast<SubRegion>(BR);
1069 DefinedOrUnknownSVal Extent = SubReg->getExtent(svalBuilder);
1071 ProgramStateRef StateWholeReg, StateNotWholeReg;
1072 std::tie(StateWholeReg, StateNotWholeReg) =
1073 State->assume(svalBuilder.evalEQ(State, Extent, *SizeNL));
1075 // With the semantic of 'memset()', we should convert the CharVal to
1077 CharVal = svalBuilder.evalCast(CharVal, Ctx.UnsignedCharTy, Ctx.IntTy);
1079 ProgramStateRef StateNullChar, StateNonNullChar;
1080 std::tie(StateNullChar, StateNonNullChar) =
1081 assumeZero(C, State, CharVal, Ctx.UnsignedCharTy);
1083 if (StateWholeReg && !StateNotWholeReg && StateNullChar &&
1084 !StateNonNullChar) {
1085 // If the 'memset()' acts on the whole region of destination buffer and
1086 // the value of the second argument of 'memset()' is zero, bind the second
1087 // argument's value to the destination buffer with 'default binding'.
1088 // FIXME: Since there is no perfect way to bind the non-zero character, we
1089 // can only deal with zero value here. In the future, we need to deal with
1090 // the binding of non-zero value in the case of whole region.
1091 State = State->bindDefaultZero(svalBuilder.makeLoc(BR),
1092 C.getLocationContext());
1094 // If the destination buffer's extent is not equal to the value of
1095 // third argument, just invalidate buffer.
1096 State = InvalidateBuffer(C, State, DstBuffer, MemVal,
1097 /*IsSourceBuffer*/ false, Size);
1100 if (StateNullChar && !StateNonNullChar) {
1101 // If the value of the second argument of 'memset()' is zero, set the
1102 // string length of destination buffer to 0 directly.
1103 State = setCStringLength(State, MR,
1104 svalBuilder.makeZeroVal(Ctx.getSizeType()));
1105 } else if (!StateNullChar && StateNonNullChar) {
1106 SVal NewStrLen = svalBuilder.getMetadataSymbolVal(
1107 CStringChecker::getTag(), MR, DstBuffer, Ctx.getSizeType(),
1108 C.getLocationContext(), C.blockCount());
1110 // If the value of second argument is not zero, then the string length
1111 // is at least the size argument.
1112 SVal NewStrLenGESize = svalBuilder.evalBinOp(
1113 State, BO_GE, NewStrLen, SizeVal, svalBuilder.getConditionType());
1115 State = setCStringLength(
1116 State->assume(NewStrLenGESize.castAs<DefinedOrUnknownSVal>(), true),
1120 // If the offset is not zero and char value is not concrete, we can do
1121 // nothing but invalidate the buffer.
1122 State = InvalidateBuffer(C, State, DstBuffer, MemVal,
1123 /*IsSourceBuffer*/ false, Size);
1128 //===----------------------------------------------------------------------===//
1129 // evaluation of individual function calls.
1130 //===----------------------------------------------------------------------===//
1132 void CStringChecker::evalCopyCommon(CheckerContext &C,
1134 ProgramStateRef state,
1135 const Expr *Size, const Expr *Dest,
1136 const Expr *Source, bool Restricted,
1137 bool IsMempcpy) const {
1138 CurrentFunctionDescription = "memory copy function";
1140 // See if the size argument is zero.
1141 const LocationContext *LCtx = C.getLocationContext();
1142 SVal sizeVal = state->getSVal(Size, LCtx);
1143 QualType sizeTy = Size->getType();
1145 ProgramStateRef stateZeroSize, stateNonZeroSize;
1146 std::tie(stateZeroSize, stateNonZeroSize) =
1147 assumeZero(C, state, sizeVal, sizeTy);
1149 // Get the value of the Dest.
1150 SVal destVal = state->getSVal(Dest, LCtx);
1152 // If the size is zero, there won't be any actual memory access, so
1153 // just bind the return value to the destination buffer and return.
1154 if (stateZeroSize && !stateNonZeroSize) {
1155 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
1156 C.addTransition(stateZeroSize);
1160 // If the size can be nonzero, we have to check the other arguments.
1161 if (stateNonZeroSize) {
1162 state = stateNonZeroSize;
1164 // Ensure the destination is not null. If it is NULL there will be a
1165 // NULL pointer dereference.
1166 state = checkNonNull(C, state, Dest, destVal);
1170 // Get the value of the Src.
1171 SVal srcVal = state->getSVal(Source, LCtx);
1173 // Ensure the source is not null. If it is NULL there will be a
1174 // NULL pointer dereference.
1175 state = checkNonNull(C, state, Source, srcVal);
1179 // Ensure the accesses are valid and that the buffers do not overlap.
1180 const char * const writeWarning =
1181 "Memory copy function overflows destination buffer";
1182 state = CheckBufferAccess(C, state, Size, Dest, Source,
1183 writeWarning, /* sourceWarning = */ nullptr);
1185 state = CheckOverlap(C, state, Size, Dest, Source);
1190 // If this is mempcpy, get the byte after the last byte copied and
1193 // Get the byte after the last byte copied.
1194 SValBuilder &SvalBuilder = C.getSValBuilder();
1195 ASTContext &Ctx = SvalBuilder.getContext();
1196 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
1197 SVal DestRegCharVal =
1198 SvalBuilder.evalCast(destVal, CharPtrTy, Dest->getType());
1199 SVal lastElement = C.getSValBuilder().evalBinOp(
1200 state, BO_Add, DestRegCharVal, sizeVal, Dest->getType());
1201 // If we don't know how much we copied, we can at least
1202 // conjure a return value for later.
1203 if (lastElement.isUnknown())
1204 lastElement = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1207 // The byte after the last byte copied is the return value.
1208 state = state->BindExpr(CE, LCtx, lastElement);
1210 // All other copies return the destination buffer.
1211 // (Well, bcopy() has a void return type, but this won't hurt.)
1212 state = state->BindExpr(CE, LCtx, destVal);
1215 // Invalidate the destination (regular invalidation without pointer-escaping
1216 // the address of the top-level region).
1217 // FIXME: Even if we can't perfectly model the copy, we should see if we
1218 // can use LazyCompoundVals to copy the source values into the destination.
1219 // This would probably remove any existing bindings past the end of the
1220 // copied region, but that's still an improvement over blank invalidation.
1221 state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest),
1222 /*IsSourceBuffer*/false, Size);
1224 // Invalidate the source (const-invalidation without const-pointer-escaping
1225 // the address of the top-level region).
1226 state = InvalidateBuffer(C, state, Source, C.getSVal(Source),
1227 /*IsSourceBuffer*/true, nullptr);
1229 C.addTransition(state);
1234 void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
1235 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
1236 // The return value is the address of the destination buffer.
1237 const Expr *Dest = CE->getArg(0);
1238 ProgramStateRef state = C.getState();
1240 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
1243 void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
1244 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1245 // The return value is a pointer to the byte following the last written byte.
1246 const Expr *Dest = CE->getArg(0);
1247 ProgramStateRef state = C.getState();
1249 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
1252 void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
1253 // void *memmove(void *dst, const void *src, size_t n);
1254 // The return value is the address of the destination buffer.
1255 const Expr *Dest = CE->getArg(0);
1256 ProgramStateRef state = C.getState();
1258 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
1261 void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
1262 // void bcopy(const void *src, void *dst, size_t n);
1263 evalCopyCommon(C, CE, C.getState(),
1264 CE->getArg(2), CE->getArg(1), CE->getArg(0));
1267 void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
1268 // int memcmp(const void *s1, const void *s2, size_t n);
1269 CurrentFunctionDescription = "memory comparison function";
1271 const Expr *Left = CE->getArg(0);
1272 const Expr *Right = CE->getArg(1);
1273 const Expr *Size = CE->getArg(2);
1275 ProgramStateRef state = C.getState();
1276 SValBuilder &svalBuilder = C.getSValBuilder();
1278 // See if the size argument is zero.
1279 const LocationContext *LCtx = C.getLocationContext();
1280 SVal sizeVal = state->getSVal(Size, LCtx);
1281 QualType sizeTy = Size->getType();
1283 ProgramStateRef stateZeroSize, stateNonZeroSize;
1284 std::tie(stateZeroSize, stateNonZeroSize) =
1285 assumeZero(C, state, sizeVal, sizeTy);
1287 // If the size can be zero, the result will be 0 in that case, and we don't
1288 // have to check either of the buffers.
1289 if (stateZeroSize) {
1290 state = stateZeroSize;
1291 state = state->BindExpr(CE, LCtx,
1292 svalBuilder.makeZeroVal(CE->getType()));
1293 C.addTransition(state);
1296 // If the size can be nonzero, we have to check the other arguments.
1297 if (stateNonZeroSize) {
1298 state = stateNonZeroSize;
1299 // If we know the two buffers are the same, we know the result is 0.
1300 // First, get the two buffers' addresses. Another checker will have already
1301 // made sure they're not undefined.
1302 DefinedOrUnknownSVal LV =
1303 state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
1304 DefinedOrUnknownSVal RV =
1305 state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
1307 // See if they are the same.
1308 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1309 ProgramStateRef StSameBuf, StNotSameBuf;
1310 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1312 // If the two arguments might be the same buffer, we know the result is 0,
1313 // and we only need to check one size.
1316 state = CheckBufferAccess(C, state, Size, Left);
1318 state = StSameBuf->BindExpr(CE, LCtx,
1319 svalBuilder.makeZeroVal(CE->getType()));
1320 C.addTransition(state);
1324 // If the two arguments might be different buffers, we have to check the
1325 // size of both of them.
1327 state = StNotSameBuf;
1328 state = CheckBufferAccess(C, state, Size, Left, Right);
1330 // The return value is the comparison result, which we don't know.
1331 SVal CmpV = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1333 state = state->BindExpr(CE, LCtx, CmpV);
1334 C.addTransition(state);
1340 void CStringChecker::evalstrLength(CheckerContext &C,
1341 const CallExpr *CE) const {
1342 // size_t strlen(const char *s);
1343 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1346 void CStringChecker::evalstrnLength(CheckerContext &C,
1347 const CallExpr *CE) const {
1348 // size_t strnlen(const char *s, size_t maxlen);
1349 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1352 void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
1353 bool IsStrnlen) const {
1354 CurrentFunctionDescription = "string length function";
1355 ProgramStateRef state = C.getState();
1356 const LocationContext *LCtx = C.getLocationContext();
1359 const Expr *maxlenExpr = CE->getArg(1);
1360 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1362 ProgramStateRef stateZeroSize, stateNonZeroSize;
1363 std::tie(stateZeroSize, stateNonZeroSize) =
1364 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1366 // If the size can be zero, the result will be 0 in that case, and we don't
1367 // have to check the string itself.
1368 if (stateZeroSize) {
1369 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
1370 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
1371 C.addTransition(stateZeroSize);
1374 // If the size is GUARANTEED to be zero, we're done!
1375 if (!stateNonZeroSize)
1378 // Otherwise, record the assumption that the size is nonzero.
1379 state = stateNonZeroSize;
1382 // Check that the string argument is non-null.
1383 const Expr *Arg = CE->getArg(0);
1384 SVal ArgVal = state->getSVal(Arg, LCtx);
1386 state = checkNonNull(C, state, Arg, ArgVal);
1391 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
1393 // If the argument isn't a valid C string, there's no valid state to
1395 if (strLength.isUndef())
1398 DefinedOrUnknownSVal result = UnknownVal();
1400 // If the check is for strnlen() then bind the return value to no more than
1401 // the maxlen value.
1403 QualType cmpTy = C.getSValBuilder().getConditionType();
1405 // It's a little unfortunate to be getting this again,
1406 // but it's not that expensive...
1407 const Expr *maxlenExpr = CE->getArg(1);
1408 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1410 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1411 Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
1413 if (strLengthNL && maxlenValNL) {
1414 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
1416 // Check if the strLength is greater than the maxlen.
1417 std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
1419 .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1420 .castAs<DefinedOrUnknownSVal>());
1422 if (stateStringTooLong && !stateStringNotTooLong) {
1423 // If the string is longer than maxlen, return maxlen.
1424 result = *maxlenValNL;
1425 } else if (stateStringNotTooLong && !stateStringTooLong) {
1426 // If the string is shorter than maxlen, return its length.
1427 result = *strLengthNL;
1431 if (result.isUnknown()) {
1432 // If we don't have enough information for a comparison, there's
1433 // no guarantee the full string length will actually be returned.
1434 // All we know is the return value is the min of the string length
1435 // and the limit. This is better than nothing.
1436 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1438 NonLoc resultNL = result.castAs<NonLoc>();
1441 state = state->assume(C.getSValBuilder().evalBinOpNN(
1442 state, BO_LE, resultNL, *strLengthNL, cmpTy)
1443 .castAs<DefinedOrUnknownSVal>(), true);
1447 state = state->assume(C.getSValBuilder().evalBinOpNN(
1448 state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1449 .castAs<DefinedOrUnknownSVal>(), true);
1454 // This is a plain strlen(), not strnlen().
1455 result = strLength.castAs<DefinedOrUnknownSVal>();
1457 // If we don't know the length of the string, conjure a return
1458 // value, so it can be used in constraints, at least.
1459 if (result.isUnknown()) {
1460 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1465 // Bind the return value.
1466 assert(!result.isUnknown() && "Should have conjured a value by now");
1467 state = state->BindExpr(CE, LCtx, result);
1468 C.addTransition(state);
1471 void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
1472 // char *strcpy(char *restrict dst, const char *restrict src);
1473 evalStrcpyCommon(C, CE,
1474 /* returnEnd = */ false,
1475 /* isBounded = */ false,
1476 /* isAppending = */ false);
1479 void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
1480 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
1481 evalStrcpyCommon(C, CE,
1482 /* returnEnd = */ false,
1483 /* isBounded = */ true,
1484 /* isAppending = */ false);
1487 void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
1488 // char *stpcpy(char *restrict dst, const char *restrict src);
1489 evalStrcpyCommon(C, CE,
1490 /* returnEnd = */ true,
1491 /* isBounded = */ false,
1492 /* isAppending = */ false);
1495 void CStringChecker::evalStrlcpy(CheckerContext &C, const CallExpr *CE) const {
1496 // char *strlcpy(char *dst, const char *src, size_t n);
1497 evalStrcpyCommon(C, CE,
1498 /* returnEnd = */ true,
1499 /* isBounded = */ true,
1500 /* isAppending = */ false,
1501 /* returnPtr = */ false);
1504 void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
1505 //char *strcat(char *restrict s1, const char *restrict s2);
1506 evalStrcpyCommon(C, CE,
1507 /* returnEnd = */ false,
1508 /* isBounded = */ false,
1509 /* isAppending = */ true);
1512 void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
1513 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1514 evalStrcpyCommon(C, CE,
1515 /* returnEnd = */ false,
1516 /* isBounded = */ true,
1517 /* isAppending = */ true);
1520 void CStringChecker::evalStrlcat(CheckerContext &C, const CallExpr *CE) const {
1521 // FIXME: strlcat() uses a different rule for bound checking, i.e. 'n' means
1522 // a different thing as compared to strncat(). This currently causes
1523 // false positives in the alpha string bound checker.
1525 //char *strlcat(char *s1, const char *s2, size_t n);
1526 evalStrcpyCommon(C, CE,
1527 /* returnEnd = */ false,
1528 /* isBounded = */ true,
1529 /* isAppending = */ true,
1530 /* returnPtr = */ false);
1533 void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
1534 bool returnEnd, bool isBounded,
1535 bool isAppending, bool returnPtr) const {
1536 CurrentFunctionDescription = "string copy function";
1537 ProgramStateRef state = C.getState();
1538 const LocationContext *LCtx = C.getLocationContext();
1540 // Check that the destination is non-null.
1541 const Expr *Dst = CE->getArg(0);
1542 SVal DstVal = state->getSVal(Dst, LCtx);
1544 state = checkNonNull(C, state, Dst, DstVal);
1548 // Check that the source is non-null.
1549 const Expr *srcExpr = CE->getArg(1);
1550 SVal srcVal = state->getSVal(srcExpr, LCtx);
1551 state = checkNonNull(C, state, srcExpr, srcVal);
1555 // Get the string length of the source.
1556 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
1558 // If the source isn't a valid C string, give up.
1559 if (strLength.isUndef())
1562 SValBuilder &svalBuilder = C.getSValBuilder();
1563 QualType cmpTy = svalBuilder.getConditionType();
1564 QualType sizeTy = svalBuilder.getContext().getSizeType();
1566 // These two values allow checking two kinds of errors:
1567 // - actual overflows caused by a source that doesn't fit in the destination
1568 // - potential overflows caused by a bound that could exceed the destination
1569 SVal amountCopied = UnknownVal();
1570 SVal maxLastElementIndex = UnknownVal();
1571 const char *boundWarning = nullptr;
1573 state = CheckOverlap(C, state, isBounded ? CE->getArg(2) : CE->getArg(1), Dst, srcExpr);
1578 // If the function is strncpy, strncat, etc... it is bounded.
1580 // Get the max number of characters to copy.
1581 const Expr *lenExpr = CE->getArg(2);
1582 SVal lenVal = state->getSVal(lenExpr, LCtx);
1584 // Protect against misdeclared strncpy().
1585 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
1587 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1588 Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
1590 // If we know both values, we might be able to figure out how much
1592 if (strLengthNL && lenValNL) {
1593 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
1595 // Check if the max number to copy is less than the length of the src.
1596 // If the bound is equal to the source length, strncpy won't null-
1597 // terminate the result!
1598 std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
1599 svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1600 .castAs<DefinedOrUnknownSVal>());
1602 if (stateSourceTooLong && !stateSourceNotTooLong) {
1603 // Max number to copy is less than the length of the src, so the actual
1604 // strLength copied is the max number arg.
1605 state = stateSourceTooLong;
1606 amountCopied = lenVal;
1608 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1609 // The source buffer entirely fits in the bound.
1610 state = stateSourceNotTooLong;
1611 amountCopied = strLength;
1615 // We still want to know if the bound is known to be too large.
1618 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1620 // Get the string length of the destination. If the destination is
1621 // memory that can't have a string length, we shouldn't be copying
1623 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1624 if (dstStrLength.isUndef())
1627 if (Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>()) {
1628 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1632 boundWarning = "Size argument is greater than the free space in the "
1633 "destination buffer";
1637 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1638 // (Yes, strncpy and strncat differ in how they treat termination.
1639 // strncat ALWAYS terminates, but strncpy doesn't.)
1641 // We need a special case for when the copy size is zero, in which
1642 // case strncpy will do no work at all. Our bounds check uses n-1
1643 // as the last element accessed, so n == 0 is problematic.
1644 ProgramStateRef StateZeroSize, StateNonZeroSize;
1645 std::tie(StateZeroSize, StateNonZeroSize) =
1646 assumeZero(C, state, *lenValNL, sizeTy);
1648 // If the size is known to be zero, we're done.
1649 if (StateZeroSize && !StateNonZeroSize) {
1651 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1653 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, *lenValNL);
1655 C.addTransition(StateZeroSize);
1659 // Otherwise, go ahead and figure out the last element we'll touch.
1660 // We don't record the non-zero assumption here because we can't
1661 // be sure. We won't warn on a possible zero.
1662 NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
1663 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1665 boundWarning = "Size argument is greater than the length of the "
1666 "destination buffer";
1670 // If we couldn't pin down the copy length, at least bound it.
1671 // FIXME: We should actually run this code path for append as well, but
1672 // right now it creates problems with constraints (since we can end up
1673 // trying to pass constraints from symbol to symbol).
1674 if (amountCopied.isUnknown() && !isAppending) {
1675 // Try to get a "hypothetical" string length symbol, which we can later
1676 // set as a real value if that turns out to be the case.
1677 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1678 assert(!amountCopied.isUndef());
1680 if (Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>()) {
1682 // amountCopied <= lenVal
1683 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1687 state = state->assume(
1688 copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
1694 // amountCopied <= strlen(source)
1695 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1699 state = state->assume(
1700 copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
1708 // The function isn't bounded. The amount copied should match the length
1709 // of the source buffer.
1710 amountCopied = strLength;
1715 // This represents the number of characters copied into the destination
1716 // buffer. (It may not actually be the strlen if the destination buffer
1717 // is not terminated.)
1718 SVal finalStrLength = UnknownVal();
1720 // If this is an appending function (strcat, strncat...) then set the
1721 // string length to strlen(src) + strlen(dst) since the buffer will
1722 // ultimately contain both.
1724 // Get the string length of the destination. If the destination is memory
1725 // that can't have a string length, we shouldn't be copying into it anyway.
1726 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1727 if (dstStrLength.isUndef())
1730 Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
1731 Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
1733 // If we know both string lengths, we might know the final string length.
1734 if (srcStrLengthNL && dstStrLengthNL) {
1735 // Make sure the two lengths together don't overflow a size_t.
1736 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1740 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1741 *dstStrLengthNL, sizeTy);
1744 // If we couldn't get a single value for the final string length,
1745 // we can at least bound it by the individual lengths.
1746 if (finalStrLength.isUnknown()) {
1747 // Try to get a "hypothetical" string length symbol, which we can later
1748 // set as a real value if that turns out to be the case.
1749 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1750 assert(!finalStrLength.isUndef());
1752 if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
1753 if (srcStrLengthNL) {
1754 // finalStrLength >= srcStrLength
1755 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1759 state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
1765 if (dstStrLengthNL) {
1766 // finalStrLength >= dstStrLength
1767 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1772 state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
1780 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1781 // the final string length will match the input string length.
1782 finalStrLength = amountCopied;
1788 // The final result of the function will either be a pointer past the last
1789 // copied element, or a pointer to the start of the destination buffer.
1790 Result = (returnEnd ? UnknownVal() : DstVal);
1792 Result = finalStrLength;
1797 // If the destination is a MemRegion, try to check for a buffer overflow and
1798 // record the new string length.
1799 if (Optional<loc::MemRegionVal> dstRegVal =
1800 DstVal.getAs<loc::MemRegionVal>()) {
1801 QualType ptrTy = Dst->getType();
1803 // If we have an exact value on a bounded copy, use that to check for
1804 // overflows, rather than our estimate about how much is actually copied.
1806 if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
1807 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1809 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1816 // Then, if the final length is known...
1817 if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
1818 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1819 *knownStrLength, ptrTy);
1821 // ...and we haven't checked the bound, we'll check the actual copy.
1822 if (!boundWarning) {
1823 const char * const warningMsg =
1824 "String copy function overflows destination buffer";
1825 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1830 // If this is a stpcpy-style copy, the last element is the return value.
1831 if (returnPtr && returnEnd)
1832 Result = lastElement;
1835 // Invalidate the destination (regular invalidation without pointer-escaping
1836 // the address of the top-level region). This must happen before we set the
1837 // C string length because invalidation will clear the length.
1838 // FIXME: Even if we can't perfectly model the copy, we should see if we
1839 // can use LazyCompoundVals to copy the source values into the destination.
1840 // This would probably remove any existing bindings past the end of the
1841 // string, but that's still an improvement over blank invalidation.
1842 state = InvalidateBuffer(C, state, Dst, *dstRegVal,
1843 /*IsSourceBuffer*/false, nullptr);
1845 // Invalidate the source (const-invalidation without const-pointer-escaping
1846 // the address of the top-level region).
1847 state = InvalidateBuffer(C, state, srcExpr, srcVal, /*IsSourceBuffer*/true,
1850 // Set the C string length of the destination, if we know it.
1851 if (isBounded && !isAppending) {
1852 // strncpy is annoying in that it doesn't guarantee to null-terminate
1853 // the result string. If the original string didn't fit entirely inside
1854 // the bound (including the null-terminator), we don't know how long the
1856 if (amountCopied != strLength)
1857 finalStrLength = UnknownVal();
1859 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
1865 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1866 // overflow, we still need a result. Conjure a return value.
1867 if (returnEnd && Result.isUnknown()) {
1868 Result = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
1871 // Set the return value.
1872 state = state->BindExpr(CE, LCtx, Result);
1873 C.addTransition(state);
1876 void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1877 //int strcmp(const char *s1, const char *s2);
1878 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
1881 void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
1882 //int strncmp(const char *s1, const char *s2, size_t n);
1883 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1886 void CStringChecker::evalStrcasecmp(CheckerContext &C,
1887 const CallExpr *CE) const {
1888 //int strcasecmp(const char *s1, const char *s2);
1889 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
1892 void CStringChecker::evalStrncasecmp(CheckerContext &C,
1893 const CallExpr *CE) const {
1894 //int strncasecmp(const char *s1, const char *s2, size_t n);
1895 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1898 void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
1899 bool isBounded, bool ignoreCase) const {
1900 CurrentFunctionDescription = "string comparison function";
1901 ProgramStateRef state = C.getState();
1902 const LocationContext *LCtx = C.getLocationContext();
1904 // Check that the first string is non-null
1905 const Expr *s1 = CE->getArg(0);
1906 SVal s1Val = state->getSVal(s1, LCtx);
1907 state = checkNonNull(C, state, s1, s1Val);
1911 // Check that the second string is non-null.
1912 const Expr *s2 = CE->getArg(1);
1913 SVal s2Val = state->getSVal(s2, LCtx);
1914 state = checkNonNull(C, state, s2, s2Val);
1918 // Get the string length of the first string or give up.
1919 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1920 if (s1Length.isUndef())
1923 // Get the string length of the second string or give up.
1924 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1925 if (s2Length.isUndef())
1928 // If we know the two buffers are the same, we know the result is 0.
1929 // First, get the two buffers' addresses. Another checker will have already
1930 // made sure they're not undefined.
1931 DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1932 DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
1934 // See if they are the same.
1935 SValBuilder &svalBuilder = C.getSValBuilder();
1936 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1937 ProgramStateRef StSameBuf, StNotSameBuf;
1938 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1940 // If the two arguments might be the same buffer, we know the result is 0,
1941 // and we only need to check one size.
1943 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1944 svalBuilder.makeZeroVal(CE->getType()));
1945 C.addTransition(StSameBuf);
1947 // If the two arguments are GUARANTEED to be the same, we're done!
1952 assert(StNotSameBuf);
1953 state = StNotSameBuf;
1955 // At this point we can go about comparing the two buffers.
1956 // For now, we only do this if they're both known string literals.
1958 // Attempt to extract string literals from both expressions.
1959 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1960 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1961 bool canComputeResult = false;
1962 SVal resultVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1965 if (s1StrLiteral && s2StrLiteral) {
1966 StringRef s1StrRef = s1StrLiteral->getString();
1967 StringRef s2StrRef = s2StrLiteral->getString();
1970 // Get the max number of characters to compare.
1971 const Expr *lenExpr = CE->getArg(2);
1972 SVal lenVal = state->getSVal(lenExpr, LCtx);
1974 // If the length is known, we can get the right substrings.
1975 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1976 // Create substrings of each to compare the prefix.
1977 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1978 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1979 canComputeResult = true;
1982 // This is a normal, unbounded strcmp.
1983 canComputeResult = true;
1986 if (canComputeResult) {
1987 // Real strcmp stops at null characters.
1988 size_t s1Term = s1StrRef.find('\0');
1989 if (s1Term != StringRef::npos)
1990 s1StrRef = s1StrRef.substr(0, s1Term);
1992 size_t s2Term = s2StrRef.find('\0');
1993 if (s2Term != StringRef::npos)
1994 s2StrRef = s2StrRef.substr(0, s2Term);
1996 // Use StringRef's comparison methods to compute the actual result.
1997 int compareRes = ignoreCase ? s1StrRef.compare_lower(s2StrRef)
1998 : s1StrRef.compare(s2StrRef);
2000 // The strcmp function returns an integer greater than, equal to, or less
2001 // than zero, [c11, p7.24.4.2].
2002 if (compareRes == 0) {
2003 resultVal = svalBuilder.makeIntVal(compareRes, CE->getType());
2006 DefinedSVal zeroVal = svalBuilder.makeIntVal(0, CE->getType());
2007 // Constrain strcmp's result range based on the result of StringRef's
2008 // comparison methods.
2009 BinaryOperatorKind op = (compareRes == 1) ? BO_GT : BO_LT;
2010 SVal compareWithZero =
2011 svalBuilder.evalBinOp(state, op, resultVal, zeroVal,
2012 svalBuilder.getConditionType());
2013 DefinedSVal compareWithZeroVal = compareWithZero.castAs<DefinedSVal>();
2014 state = state->assume(compareWithZeroVal, true);
2019 state = state->BindExpr(CE, LCtx, resultVal);
2021 // Record this as a possible path.
2022 C.addTransition(state);
2025 void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
2026 //char *strsep(char **stringp, const char *delim);
2027 // Sanity: does the search string parameter match the return type?
2028 const Expr *SearchStrPtr = CE->getArg(0);
2029 QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
2030 if (CharPtrTy.isNull() ||
2031 CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
2034 CurrentFunctionDescription = "strsep()";
2035 ProgramStateRef State = C.getState();
2036 const LocationContext *LCtx = C.getLocationContext();
2038 // Check that the search string pointer is non-null (though it may point to
2040 SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
2041 State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
2045 // Check that the delimiter string is non-null.
2046 const Expr *DelimStr = CE->getArg(1);
2047 SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
2048 State = checkNonNull(C, State, DelimStr, DelimStrVal);
2052 SValBuilder &SVB = C.getSValBuilder();
2054 if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
2055 // Get the current value of the search string pointer, as a char*.
2056 Result = State->getSVal(*SearchStrLoc, CharPtrTy);
2058 // Invalidate the search string, representing the change of one delimiter
2059 // character to NUL.
2060 State = InvalidateBuffer(C, State, SearchStrPtr, Result,
2061 /*IsSourceBuffer*/false, nullptr);
2063 // Overwrite the search string pointer. The new value is either an address
2064 // further along in the same string, or NULL if there are no more tokens.
2065 State = State->bindLoc(*SearchStrLoc,
2066 SVB.conjureSymbolVal(getTag(),
2073 assert(SearchStrVal.isUnknown());
2074 // Conjure a symbolic value. It's the best we can do.
2075 Result = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
2078 // Set the return value, and finish.
2079 State = State->BindExpr(CE, LCtx, Result);
2080 C.addTransition(State);
2083 // These should probably be moved into a C++ standard library checker.
2084 void CStringChecker::evalStdCopy(CheckerContext &C, const CallExpr *CE) const {
2085 evalStdCopyCommon(C, CE);
2088 void CStringChecker::evalStdCopyBackward(CheckerContext &C,
2089 const CallExpr *CE) const {
2090 evalStdCopyCommon(C, CE);
2093 void CStringChecker::evalStdCopyCommon(CheckerContext &C,
2094 const CallExpr *CE) const {
2095 if (!CE->getArg(2)->getType()->isPointerType())
2098 ProgramStateRef State = C.getState();
2100 const LocationContext *LCtx = C.getLocationContext();
2102 // template <class _InputIterator, class _OutputIterator>
2104 // copy(_InputIterator __first, _InputIterator __last,
2105 // _OutputIterator __result)
2107 // Invalidate the destination buffer
2108 const Expr *Dst = CE->getArg(2);
2109 SVal DstVal = State->getSVal(Dst, LCtx);
2110 State = InvalidateBuffer(C, State, Dst, DstVal, /*IsSource=*/false,
2113 SValBuilder &SVB = C.getSValBuilder();
2115 SVal ResultVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
2116 State = State->BindExpr(CE, LCtx, ResultVal);
2118 C.addTransition(State);
2121 void CStringChecker::evalMemset(CheckerContext &C, const CallExpr *CE) const {
2122 CurrentFunctionDescription = "memory set function";
2124 const Expr *Mem = CE->getArg(0);
2125 const Expr *CharE = CE->getArg(1);
2126 const Expr *Size = CE->getArg(2);
2127 ProgramStateRef State = C.getState();
2129 // See if the size argument is zero.
2130 const LocationContext *LCtx = C.getLocationContext();
2131 SVal SizeVal = State->getSVal(Size, LCtx);
2132 QualType SizeTy = Size->getType();
2134 ProgramStateRef StateZeroSize, StateNonZeroSize;
2135 std::tie(StateZeroSize, StateNonZeroSize) =
2136 assumeZero(C, State, SizeVal, SizeTy);
2138 // Get the value of the memory area.
2139 SVal MemVal = State->getSVal(Mem, LCtx);
2141 // If the size is zero, there won't be any actual memory access, so
2142 // just bind the return value to the Mem buffer and return.
2143 if (StateZeroSize && !StateNonZeroSize) {
2144 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, MemVal);
2145 C.addTransition(StateZeroSize);
2149 // Ensure the memory area is not null.
2150 // If it is NULL there will be a NULL pointer dereference.
2151 State = checkNonNull(C, StateNonZeroSize, Mem, MemVal);
2155 State = CheckBufferAccess(C, State, Size, Mem);
2159 // According to the values of the arguments, bind the value of the second
2160 // argument to the destination buffer and set string length, or just
2161 // invalidate the destination buffer.
2162 if (!memsetAux(Mem, C.getSVal(CharE), Size, C, State))
2165 State = State->BindExpr(CE, LCtx, MemVal);
2166 C.addTransition(State);
2169 void CStringChecker::evalBzero(CheckerContext &C, const CallExpr *CE) const {
2170 CurrentFunctionDescription = "memory clearance function";
2172 const Expr *Mem = CE->getArg(0);
2173 const Expr *Size = CE->getArg(1);
2174 SVal Zero = C.getSValBuilder().makeZeroVal(C.getASTContext().IntTy);
2176 ProgramStateRef State = C.getState();
2178 // See if the size argument is zero.
2179 SVal SizeVal = C.getSVal(Size);
2180 QualType SizeTy = Size->getType();
2182 ProgramStateRef StateZeroSize, StateNonZeroSize;
2183 std::tie(StateZeroSize, StateNonZeroSize) =
2184 assumeZero(C, State, SizeVal, SizeTy);
2186 // If the size is zero, there won't be any actual memory access,
2187 // In this case we just return.
2188 if (StateZeroSize && !StateNonZeroSize) {
2189 C.addTransition(StateZeroSize);
2193 // Get the value of the memory area.
2194 SVal MemVal = C.getSVal(Mem);
2196 // Ensure the memory area is not null.
2197 // If it is NULL there will be a NULL pointer dereference.
2198 State = checkNonNull(C, StateNonZeroSize, Mem, MemVal);
2202 State = CheckBufferAccess(C, State, Size, Mem);
2206 if (!memsetAux(Mem, Zero, Size, C, State))
2209 C.addTransition(State);
2212 //===----------------------------------------------------------------------===//
2213 // The driver method, and other Checker callbacks.
2214 //===----------------------------------------------------------------------===//
2216 CStringChecker::FnCheck CStringChecker::identifyCall(const CallEvent &Call,
2217 CheckerContext &C) const {
2218 const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
2222 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
2226 if (Call.isCalled(StdCopy)) {
2227 return &CStringChecker::evalStdCopy;
2228 } else if (Call.isCalled(StdCopyBackward)) {
2229 return &CStringChecker::evalStdCopyBackward;
2232 // Pro-actively check that argument types are safe to do arithmetic upon.
2233 // We do not want to crash if someone accidentally passes a structure
2234 // into, say, a C++ overload of any of these functions. We could not check
2235 // that for std::copy because they may have arguments of other types.
2236 for (auto I : CE->arguments()) {
2237 QualType T = I->getType();
2238 if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
2242 const FnCheck *Callback = Callbacks.lookup(Call);
2249 bool CStringChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
2250 FnCheck Callback = identifyCall(Call, C);
2252 // If the callee isn't a string function, let another checker handle it.
2256 // Check and evaluate the call.
2257 const auto *CE = cast<CallExpr>(Call.getOriginExpr());
2258 (this->*Callback)(C, CE);
2260 // If the evaluate call resulted in no change, chain to the next eval call
2262 // Note, the custom CString evaluation calls assume that basic safety
2263 // properties are held. However, if the user chooses to turn off some of these
2264 // checks, we ignore the issues and leave the call evaluation to a generic
2266 return C.isDifferent();
2269 void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
2270 // Record string length for char a[] = "abc";
2271 ProgramStateRef state = C.getState();
2273 for (const auto *I : DS->decls()) {
2274 const VarDecl *D = dyn_cast<VarDecl>(I);
2278 // FIXME: Handle array fields of structs.
2279 if (!D->getType()->isArrayType())
2282 const Expr *Init = D->getInit();
2285 if (!isa<StringLiteral>(Init))
2288 Loc VarLoc = state->getLValue(D, C.getLocationContext());
2289 const MemRegion *MR = VarLoc.getAsRegion();
2293 SVal StrVal = C.getSVal(Init);
2294 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
2295 DefinedOrUnknownSVal strLength =
2296 getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
2298 state = state->set<CStringLength>(MR, strLength);
2301 C.addTransition(state);
2305 CStringChecker::checkRegionChanges(ProgramStateRef state,
2306 const InvalidatedSymbols *,
2307 ArrayRef<const MemRegion *> ExplicitRegions,
2308 ArrayRef<const MemRegion *> Regions,
2309 const LocationContext *LCtx,
2310 const CallEvent *Call) const {
2311 CStringLengthTy Entries = state->get<CStringLength>();
2312 if (Entries.isEmpty())
2315 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
2316 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
2318 // First build sets for the changed regions and their super-regions.
2319 for (ArrayRef<const MemRegion *>::iterator
2320 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
2321 const MemRegion *MR = *I;
2322 Invalidated.insert(MR);
2324 SuperRegions.insert(MR);
2325 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
2326 MR = SR->getSuperRegion();
2327 SuperRegions.insert(MR);
2331 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2333 // Then loop over the entries in the current state.
2334 for (CStringLengthTy::iterator I = Entries.begin(),
2335 E = Entries.end(); I != E; ++I) {
2336 const MemRegion *MR = I.getKey();
2338 // Is this entry for a super-region of a changed region?
2339 if (SuperRegions.count(MR)) {
2340 Entries = F.remove(Entries, MR);
2344 // Is this entry for a sub-region of a changed region?
2345 const MemRegion *Super = MR;
2346 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2347 Super = SR->getSuperRegion();
2348 if (Invalidated.count(Super)) {
2349 Entries = F.remove(Entries, MR);
2355 return state->set<CStringLength>(Entries);
2358 void CStringChecker::checkLiveSymbols(ProgramStateRef state,
2359 SymbolReaper &SR) const {
2360 // Mark all symbols in our string length map as valid.
2361 CStringLengthTy Entries = state->get<CStringLength>();
2363 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2365 SVal Len = I.getData();
2367 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2368 se = Len.symbol_end(); si != se; ++si)
2373 void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2374 CheckerContext &C) const {
2375 ProgramStateRef state = C.getState();
2376 CStringLengthTy Entries = state->get<CStringLength>();
2377 if (Entries.isEmpty())
2380 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2381 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2383 SVal Len = I.getData();
2384 if (SymbolRef Sym = Len.getAsSymbol()) {
2386 Entries = F.remove(Entries, I.getKey());
2390 state = state->set<CStringLength>(Entries);
2391 C.addTransition(state);
2394 void ento::registerCStringModeling(CheckerManager &Mgr) {
2395 Mgr.registerChecker<CStringChecker>();
2398 bool ento::shouldRegisterCStringModeling(const LangOptions &LO) {
2402 #define REGISTER_CHECKER(name) \
2403 void ento::register##name(CheckerManager &mgr) { \
2404 CStringChecker *checker = mgr.getChecker<CStringChecker>(); \
2405 checker->Filter.Check##name = true; \
2406 checker->Filter.CheckName##name = mgr.getCurrentCheckName(); \
2409 bool ento::shouldRegister##name(const LangOptions &LO) { \
2413 REGISTER_CHECKER(CStringNullArg)
2414 REGISTER_CHECKER(CStringOutOfBounds)
2415 REGISTER_CHECKER(CStringBufferOverlap)
2416 REGISTER_CHECKER(CStringNotNullTerm)