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 CheckerNameRef CheckNameCStringNullArg;
52 CheckerNameRef CheckNameCStringOutOfBounds;
53 CheckerNameRef CheckNameCStringBufferOverlap;
54 CheckerNameRef 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 unsigned IdxOfArg) const;
203 ProgramStateRef CheckLocation(CheckerContext &C,
204 ProgramStateRef state,
207 const char *message = nullptr) const;
208 ProgramStateRef CheckBufferAccess(CheckerContext &C,
209 ProgramStateRef state,
211 const Expr *FirstBuf,
212 const Expr *SecondBuf,
213 const char *firstMessage = nullptr,
214 const char *secondMessage = nullptr,
215 bool WarnAboutSize = false) const;
217 ProgramStateRef CheckBufferAccess(CheckerContext &C,
218 ProgramStateRef state,
221 const char *message = nullptr,
222 bool WarnAboutSize = false) const {
223 // This is a convenience overload.
224 return CheckBufferAccess(C, state, Size, Buf, nullptr, message, nullptr,
227 ProgramStateRef CheckOverlap(CheckerContext &C,
228 ProgramStateRef state,
231 const Expr *Second) const;
232 void emitOverlapBug(CheckerContext &C,
233 ProgramStateRef state,
235 const Stmt *Second) const;
237 void emitNullArgBug(CheckerContext &C, ProgramStateRef State, const Stmt *S,
238 StringRef WarningMsg) const;
239 void emitOutOfBoundsBug(CheckerContext &C, ProgramStateRef State,
240 const Stmt *S, StringRef WarningMsg) const;
241 void emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
242 const Stmt *S, StringRef WarningMsg) const;
243 void emitAdditionOverflowBug(CheckerContext &C, ProgramStateRef State) const;
245 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
246 ProgramStateRef state,
250 // Return true if the destination buffer of the copy function may be in bound.
251 // Expects SVal of Size to be positive and unsigned.
252 // Expects SVal of FirstBuf to be a FieldRegion.
253 static bool IsFirstBufInBound(CheckerContext &C,
254 ProgramStateRef state,
255 const Expr *FirstBuf,
259 } //end anonymous namespace
261 REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
263 //===----------------------------------------------------------------------===//
264 // Individual checks and utility methods.
265 //===----------------------------------------------------------------------===//
267 std::pair<ProgramStateRef , ProgramStateRef >
268 CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
270 Optional<DefinedSVal> val = V.getAs<DefinedSVal>();
272 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
274 SValBuilder &svalBuilder = C.getSValBuilder();
275 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
276 return state->assume(svalBuilder.evalEQ(state, *val, zero));
279 ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
280 ProgramStateRef state,
281 const Expr *S, SVal l,
282 unsigned IdxOfArg) const {
283 // If a previous check has failed, propagate the failure.
287 ProgramStateRef stateNull, stateNonNull;
288 std::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
290 if (stateNull && !stateNonNull) {
291 if (Filter.CheckCStringNullArg) {
293 llvm::raw_svector_ostream OS(buf);
294 assert(CurrentFunctionDescription);
295 OS << "Null pointer argument in call to " << CurrentFunctionDescription
296 << ' ' << IdxOfArg << llvm::getOrdinalSuffix(IdxOfArg)
299 emitNullArgBug(C, stateNull, S, OS.str());
304 // From here on, assume that the value is non-null.
305 assert(stateNonNull);
309 // FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
310 ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
311 ProgramStateRef state,
312 const Expr *S, SVal l,
313 const char *warningMsg) const {
314 // If a previous check has failed, propagate the failure.
318 // Check for out of bound array element access.
319 const MemRegion *R = l.getAsRegion();
323 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
327 if (ER->getValueType() != C.getASTContext().CharTy)
330 // Get the size of the array.
331 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
332 SValBuilder &svalBuilder = C.getSValBuilder();
334 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
335 DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>();
337 // Get the index of the accessed element.
338 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
340 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
341 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
342 if (StOutBound && !StInBound) {
343 // These checks are either enabled by the CString out-of-bounds checker
344 // explicitly or implicitly by the Malloc checker.
345 // In the latter case we only do modeling but do not emit warning.
346 if (!Filter.CheckCStringOutOfBounds)
348 // Emit a bug report.
350 emitOutOfBoundsBug(C, StOutBound, S, warningMsg);
352 assert(CurrentFunctionDescription);
353 assert(CurrentFunctionDescription[0] != '\0');
356 llvm::raw_svector_ostream os(buf);
357 os << toUppercase(CurrentFunctionDescription[0])
358 << &CurrentFunctionDescription[1]
359 << " accesses out-of-bound array element";
360 emitOutOfBoundsBug(C, StOutBound, S, os.str());
365 // Array bound check succeeded. From this point forward the array bound
366 // should always succeed.
370 ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
371 ProgramStateRef state,
373 const Expr *FirstBuf,
374 const Expr *SecondBuf,
375 const char *firstMessage,
376 const char *secondMessage,
377 bool WarnAboutSize) const {
378 // If a previous check has failed, propagate the failure.
382 SValBuilder &svalBuilder = C.getSValBuilder();
383 ASTContext &Ctx = svalBuilder.getContext();
384 const LocationContext *LCtx = C.getLocationContext();
386 QualType sizeTy = Size->getType();
387 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
389 // Check that the first buffer is non-null.
390 SVal BufVal = C.getSVal(FirstBuf);
391 state = checkNonNull(C, state, FirstBuf, BufVal, 1);
395 // If out-of-bounds checking is turned off, skip the rest.
396 if (!Filter.CheckCStringOutOfBounds)
399 // Get the access length and make sure it is known.
400 // FIXME: This assumes the caller has already checked that the access length
401 // is positive. And that it's unsigned.
402 SVal LengthVal = C.getSVal(Size);
403 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
407 // Compute the offset of the last element to be accessed: size-1.
408 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
409 SVal Offset = svalBuilder.evalBinOpNN(state, BO_Sub, *Length, One, sizeTy);
410 if (Offset.isUnknown())
412 NonLoc LastOffset = Offset.castAs<NonLoc>();
414 // Check that the first buffer is sufficiently long.
415 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
416 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
417 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
419 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
421 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
423 // If the buffer isn't large enough, abort.
428 // If there's a second buffer, check it as well.
430 BufVal = state->getSVal(SecondBuf, LCtx);
431 state = checkNonNull(C, state, SecondBuf, BufVal, 2);
435 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
436 if (Optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
437 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
439 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
441 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
445 // Large enough or not, return this state!
449 ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
450 ProgramStateRef state,
453 const Expr *Second) const {
454 if (!Filter.CheckCStringBufferOverlap)
457 // Do a simple check for overlap: if the two arguments are from the same
458 // buffer, see if the end of the first is greater than the start of the second
461 // If a previous check has failed, propagate the failure.
465 ProgramStateRef stateTrue, stateFalse;
467 // Get the buffer values and make sure they're known locations.
468 const LocationContext *LCtx = C.getLocationContext();
469 SVal firstVal = state->getSVal(First, LCtx);
470 SVal secondVal = state->getSVal(Second, LCtx);
472 Optional<Loc> firstLoc = firstVal.getAs<Loc>();
476 Optional<Loc> secondLoc = secondVal.getAs<Loc>();
480 // Are the two values the same?
481 SValBuilder &svalBuilder = C.getSValBuilder();
482 std::tie(stateTrue, stateFalse) =
483 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
485 if (stateTrue && !stateFalse) {
486 // If the values are known to be equal, that's automatically an overlap.
487 emitOverlapBug(C, stateTrue, First, Second);
491 // assume the two expressions are not equal.
495 // Which value comes first?
496 QualType cmpTy = svalBuilder.getConditionType();
497 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
498 *firstLoc, *secondLoc, cmpTy);
499 Optional<DefinedOrUnknownSVal> reverseTest =
500 reverse.getAs<DefinedOrUnknownSVal>();
504 std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
507 // If we don't know which one comes first, we can't perform this test.
510 // Switch the values so that firstVal is before secondVal.
511 std::swap(firstLoc, secondLoc);
513 // Switch the Exprs as well, so that they still correspond.
514 std::swap(First, Second);
518 // Get the length, and make sure it too is known.
519 SVal LengthVal = state->getSVal(Size, LCtx);
520 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
524 // Convert the first buffer's start address to char*.
525 // Bail out if the cast fails.
526 ASTContext &Ctx = svalBuilder.getContext();
527 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
528 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
530 Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
534 // Compute the end of the first buffer. Bail out if THAT fails.
535 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
536 *FirstStartLoc, *Length, CharPtrTy);
537 Optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
541 // Is the end of the first buffer past the start of the second buffer?
542 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
543 *FirstEndLoc, *secondLoc, cmpTy);
544 Optional<DefinedOrUnknownSVal> OverlapTest =
545 Overlap.getAs<DefinedOrUnknownSVal>();
549 std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
551 if (stateTrue && !stateFalse) {
553 emitOverlapBug(C, stateTrue, First, Second);
557 // assume the two expressions don't overlap.
562 void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
563 const Stmt *First, const Stmt *Second) const {
564 ExplodedNode *N = C.generateErrorNode(state);
569 BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
570 categories::UnixAPI, "Improper arguments"));
572 // Generate a report for this bug.
573 auto report = std::make_unique<PathSensitiveBugReport>(
574 *BT_Overlap, "Arguments must not be overlapping buffers", N);
575 report->addRange(First->getSourceRange());
576 report->addRange(Second->getSourceRange());
578 C.emitReport(std::move(report));
581 void CStringChecker::emitNullArgBug(CheckerContext &C, ProgramStateRef State,
582 const Stmt *S, StringRef WarningMsg) const {
583 if (ExplodedNode *N = C.generateErrorNode(State)) {
585 BT_Null.reset(new BuiltinBug(
586 Filter.CheckNameCStringNullArg, categories::UnixAPI,
587 "Null pointer argument in call to byte string function"));
589 BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Null.get());
590 auto Report = std::make_unique<PathSensitiveBugReport>(*BT, WarningMsg, N);
591 Report->addRange(S->getSourceRange());
592 if (const auto *Ex = dyn_cast<Expr>(S))
593 bugreporter::trackExpressionValue(N, Ex, *Report);
594 C.emitReport(std::move(Report));
598 void CStringChecker::emitOutOfBoundsBug(CheckerContext &C,
599 ProgramStateRef State, const Stmt *S,
600 StringRef WarningMsg) const {
601 if (ExplodedNode *N = C.generateErrorNode(State)) {
603 BT_Bounds.reset(new BuiltinBug(
604 Filter.CheckCStringOutOfBounds ? Filter.CheckNameCStringOutOfBounds
605 : Filter.CheckNameCStringNullArg,
606 "Out-of-bound array access",
607 "Byte string function accesses out-of-bound array element"));
609 BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Bounds.get());
611 // FIXME: It would be nice to eventually make this diagnostic more clear,
612 // e.g., by referencing the original declaration or by saying *why* this
613 // reference is outside the range.
614 auto Report = std::make_unique<PathSensitiveBugReport>(*BT, WarningMsg, N);
615 Report->addRange(S->getSourceRange());
616 C.emitReport(std::move(Report));
620 void CStringChecker::emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
622 StringRef WarningMsg) const {
623 if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
625 BT_NotCString.reset(new BuiltinBug(
626 Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
627 "Argument is not a null-terminated string."));
630 std::make_unique<PathSensitiveBugReport>(*BT_NotCString, WarningMsg, N);
632 Report->addRange(S->getSourceRange());
633 C.emitReport(std::move(Report));
637 void CStringChecker::emitAdditionOverflowBug(CheckerContext &C,
638 ProgramStateRef State) const {
639 if (ExplodedNode *N = C.generateErrorNode(State)) {
642 new BuiltinBug(Filter.CheckNameCStringOutOfBounds, "API",
643 "Sum of expressions causes overflow."));
645 // This isn't a great error message, but this should never occur in real
646 // code anyway -- you'd have to create a buffer longer than a size_t can
647 // represent, which is sort of a contradiction.
648 const char *WarningMsg =
649 "This expression will create a string whose length is too big to "
650 "be represented as a size_t";
653 std::make_unique<PathSensitiveBugReport>(*BT_NotCString, WarningMsg, N);
654 C.emitReport(std::move(Report));
658 ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
659 ProgramStateRef state,
661 NonLoc right) const {
662 // If out-of-bounds checking is turned off, skip the rest.
663 if (!Filter.CheckCStringOutOfBounds)
666 // If a previous check has failed, propagate the failure.
670 SValBuilder &svalBuilder = C.getSValBuilder();
671 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
673 QualType sizeTy = svalBuilder.getContext().getSizeType();
674 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
675 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
678 if (right.getAs<nonloc::ConcreteInt>()) {
679 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
682 // Try switching the operands. (The order of these two assignments is
684 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
689 if (Optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
690 QualType cmpTy = svalBuilder.getConditionType();
691 // If left > max - right, we have an overflow.
692 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
693 *maxMinusRightNL, cmpTy);
695 ProgramStateRef stateOverflow, stateOkay;
696 std::tie(stateOverflow, stateOkay) =
697 state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
699 if (stateOverflow && !stateOkay) {
700 // We have an overflow. Emit a bug report.
701 emitAdditionOverflowBug(C, stateOverflow);
705 // From now on, assume an overflow didn't occur.
713 ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
716 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
718 MR = MR->StripCasts();
720 switch (MR->getKind()) {
721 case MemRegion::StringRegionKind:
722 // FIXME: This can happen if we strcpy() into a string region. This is
723 // undefined [C99 6.4.5p6], but we should still warn about it.
726 case MemRegion::SymbolicRegionKind:
727 case MemRegion::AllocaRegionKind:
728 case MemRegion::VarRegionKind:
729 case MemRegion::FieldRegionKind:
730 case MemRegion::ObjCIvarRegionKind:
731 // These are the types we can currently track string lengths for.
734 case MemRegion::ElementRegionKind:
735 // FIXME: Handle element regions by upper-bounding the parent region's
740 // Other regions (mostly non-data) can't have a reliable C string length.
741 // For now, just ignore the change.
742 // FIXME: These are rare but not impossible. We should output some kind of
743 // warning for things like strcpy((char[]){'a', 0}, "b");
747 if (strLength.isUnknown())
748 return state->remove<CStringLength>(MR);
750 return state->set<CStringLength>(MR, strLength);
753 SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
754 ProgramStateRef &state,
759 // If there's a recorded length, go ahead and return it.
760 const SVal *Recorded = state->get<CStringLength>(MR);
765 // Otherwise, get a new symbol and update the state.
766 SValBuilder &svalBuilder = C.getSValBuilder();
767 QualType sizeTy = svalBuilder.getContext().getSizeType();
768 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
770 C.getLocationContext(),
774 if (Optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
775 // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
776 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
777 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
778 llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
779 const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
781 NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
782 SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
784 state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
786 state = state->set<CStringLength>(MR, strLength);
792 SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
793 const Expr *Ex, SVal Buf,
794 bool hypothetical) const {
795 const MemRegion *MR = Buf.getAsRegion();
797 // If we can't get a region, see if it's something we /know/ isn't a
798 // C string. In the context of locations, the only time we can issue such
799 // a warning is for labels.
800 if (Optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
801 if (Filter.CheckCStringNotNullTerm) {
802 SmallString<120> buf;
803 llvm::raw_svector_ostream os(buf);
804 assert(CurrentFunctionDescription);
805 os << "Argument to " << CurrentFunctionDescription
806 << " is the address of the label '" << Label->getLabel()->getName()
807 << "', which is not a null-terminated string";
809 emitNotCStringBug(C, state, Ex, os.str());
811 return UndefinedVal();
814 // If it's not a region and not a label, give up.
818 // If we have a region, strip casts from it and see if we can figure out
819 // its length. For anything we can't figure out, just return UnknownVal.
820 MR = MR->StripCasts();
822 switch (MR->getKind()) {
823 case MemRegion::StringRegionKind: {
824 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
825 // so we can assume that the byte length is the correct C string length.
826 SValBuilder &svalBuilder = C.getSValBuilder();
827 QualType sizeTy = svalBuilder.getContext().getSizeType();
828 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
829 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
831 case MemRegion::SymbolicRegionKind:
832 case MemRegion::AllocaRegionKind:
833 case MemRegion::VarRegionKind:
834 case MemRegion::FieldRegionKind:
835 case MemRegion::ObjCIvarRegionKind:
836 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
837 case MemRegion::CompoundLiteralRegionKind:
838 // FIXME: Can we track this? Is it necessary?
840 case MemRegion::ElementRegionKind:
841 // FIXME: How can we handle this? It's not good enough to subtract the
842 // offset from the base string length; consider "123\x00567" and &a[5].
845 // Other regions (mostly non-data) can't have a reliable C string length.
846 // In this case, an error is emitted and UndefinedVal is returned.
847 // The caller should always be prepared to handle this case.
848 if (Filter.CheckCStringNotNullTerm) {
849 SmallString<120> buf;
850 llvm::raw_svector_ostream os(buf);
852 assert(CurrentFunctionDescription);
853 os << "Argument to " << CurrentFunctionDescription << " is ";
855 if (SummarizeRegion(os, C.getASTContext(), MR))
856 os << ", which is not a null-terminated string";
858 os << "not a null-terminated string";
860 emitNotCStringBug(C, state, Ex, os.str());
862 return UndefinedVal();
866 const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
867 ProgramStateRef &state, const Expr *expr, SVal val) const {
869 // Get the memory region pointed to by the val.
870 const MemRegion *bufRegion = val.getAsRegion();
874 // Strip casts off the memory region.
875 bufRegion = bufRegion->StripCasts();
877 // Cast the memory region to a string region.
878 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
882 // Return the actual string in the string region.
883 return strRegion->getStringLiteral();
886 bool CStringChecker::IsFirstBufInBound(CheckerContext &C,
887 ProgramStateRef state,
888 const Expr *FirstBuf,
890 // If we do not know that the buffer is long enough we return 'true'.
891 // Otherwise the parent region of this field region would also get
892 // invalidated, which would lead to warnings based on an unknown state.
894 // Originally copied from CheckBufferAccess and CheckLocation.
895 SValBuilder &svalBuilder = C.getSValBuilder();
896 ASTContext &Ctx = svalBuilder.getContext();
897 const LocationContext *LCtx = C.getLocationContext();
899 QualType sizeTy = Size->getType();
900 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
901 SVal BufVal = state->getSVal(FirstBuf, LCtx);
903 SVal LengthVal = state->getSVal(Size, LCtx);
904 Optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
906 return true; // cf top comment.
908 // Compute the offset of the last element to be accessed: size-1.
909 NonLoc One = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
910 SVal Offset = svalBuilder.evalBinOpNN(state, BO_Sub, *Length, One, sizeTy);
911 if (Offset.isUnknown())
912 return true; // cf top comment
913 NonLoc LastOffset = Offset.castAs<NonLoc>();
915 // Check that the first buffer is sufficiently long.
916 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
917 Optional<Loc> BufLoc = BufStart.getAs<Loc>();
919 return true; // cf top comment.
922 svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc, LastOffset, PtrTy);
924 // Check for out of bound array element access.
925 const MemRegion *R = BufEnd.getAsRegion();
927 return true; // cf top comment.
929 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
931 return true; // cf top comment.
933 // FIXME: Does this crash when a non-standard definition
934 // of a library function is encountered?
935 assert(ER->getValueType() == C.getASTContext().CharTy &&
936 "IsFirstBufInBound should only be called with char* ElementRegions");
938 // Get the size of the array.
939 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
941 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
942 DefinedOrUnknownSVal ExtentSize = Extent.castAs<DefinedOrUnknownSVal>();
944 // Get the index of the accessed element.
945 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
947 ProgramStateRef StInBound = state->assumeInBound(Idx, ExtentSize, true);
949 return static_cast<bool>(StInBound);
952 ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
953 ProgramStateRef state,
954 const Expr *E, SVal V,
957 Optional<Loc> L = V.getAs<Loc>();
961 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
962 // some assumptions about the value that CFRefCount can't. Even so, it should
963 // probably be refactored.
964 if (Optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
965 const MemRegion *R = MR->getRegion()->StripCasts();
967 // Are we dealing with an ElementRegion? If so, we should be invalidating
969 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
970 R = ER->getSuperRegion();
971 // FIXME: What about layers of ElementRegions?
974 // Invalidate this region.
975 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
977 bool CausesPointerEscape = false;
978 RegionAndSymbolInvalidationTraits ITraits;
979 // Invalidate and escape only indirect regions accessible through the source
981 if (IsSourceBuffer) {
982 ITraits.setTrait(R->getBaseRegion(),
983 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
984 ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
985 CausesPointerEscape = true;
987 const MemRegion::Kind& K = R->getKind();
988 if (K == MemRegion::FieldRegionKind)
989 if (Size && IsFirstBufInBound(C, state, E, Size)) {
990 // If destination buffer is a field region and access is in bound,
991 // do not invalidate its super region.
994 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
998 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
999 CausesPointerEscape, nullptr, nullptr,
1003 // If we have a non-region value by chance, just remove the binding.
1004 // FIXME: is this necessary or correct? This handles the non-Region
1005 // cases. Is it ever valid to store to these?
1006 return state->killBinding(*L);
1009 bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
1010 const MemRegion *MR) {
1011 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
1013 switch (MR->getKind()) {
1014 case MemRegion::FunctionCodeRegionKind: {
1015 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1017 os << "the address of the function '" << *FD << '\'';
1019 os << "the address of a function";
1022 case MemRegion::BlockCodeRegionKind:
1025 case MemRegion::BlockDataRegionKind:
1028 case MemRegion::CXXThisRegionKind:
1029 case MemRegion::CXXTempObjectRegionKind:
1030 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
1032 case MemRegion::VarRegionKind:
1033 os << "a variable of type" << TVR->getValueType().getAsString();
1035 case MemRegion::FieldRegionKind:
1036 os << "a field of type " << TVR->getValueType().getAsString();
1038 case MemRegion::ObjCIvarRegionKind:
1039 os << "an instance variable of type " << TVR->getValueType().getAsString();
1046 bool CStringChecker::memsetAux(const Expr *DstBuffer, SVal CharVal,
1047 const Expr *Size, CheckerContext &C,
1048 ProgramStateRef &State) {
1049 SVal MemVal = C.getSVal(DstBuffer);
1050 SVal SizeVal = C.getSVal(Size);
1051 const MemRegion *MR = MemVal.getAsRegion();
1055 // We're about to model memset by producing a "default binding" in the Store.
1056 // Our current implementation - RegionStore - doesn't support default bindings
1057 // that don't cover the whole base region. So we should first get the offset
1058 // and the base region to figure out whether the offset of buffer is 0.
1059 RegionOffset Offset = MR->getAsOffset();
1060 const MemRegion *BR = Offset.getRegion();
1062 Optional<NonLoc> SizeNL = SizeVal.getAs<NonLoc>();
1066 SValBuilder &svalBuilder = C.getSValBuilder();
1067 ASTContext &Ctx = C.getASTContext();
1069 // void *memset(void *dest, int ch, size_t count);
1070 // For now we can only handle the case of offset is 0 and concrete char value.
1071 if (Offset.isValid() && !Offset.hasSymbolicOffset() &&
1072 Offset.getOffset() == 0) {
1073 // Get the base region's extent.
1074 auto *SubReg = cast<SubRegion>(BR);
1075 DefinedOrUnknownSVal Extent = SubReg->getExtent(svalBuilder);
1077 ProgramStateRef StateWholeReg, StateNotWholeReg;
1078 std::tie(StateWholeReg, StateNotWholeReg) =
1079 State->assume(svalBuilder.evalEQ(State, Extent, *SizeNL));
1081 // With the semantic of 'memset()', we should convert the CharVal to
1083 CharVal = svalBuilder.evalCast(CharVal, Ctx.UnsignedCharTy, Ctx.IntTy);
1085 ProgramStateRef StateNullChar, StateNonNullChar;
1086 std::tie(StateNullChar, StateNonNullChar) =
1087 assumeZero(C, State, CharVal, Ctx.UnsignedCharTy);
1089 if (StateWholeReg && !StateNotWholeReg && StateNullChar &&
1090 !StateNonNullChar) {
1091 // If the 'memset()' acts on the whole region of destination buffer and
1092 // the value of the second argument of 'memset()' is zero, bind the second
1093 // argument's value to the destination buffer with 'default binding'.
1094 // FIXME: Since there is no perfect way to bind the non-zero character, we
1095 // can only deal with zero value here. In the future, we need to deal with
1096 // the binding of non-zero value in the case of whole region.
1097 State = State->bindDefaultZero(svalBuilder.makeLoc(BR),
1098 C.getLocationContext());
1100 // If the destination buffer's extent is not equal to the value of
1101 // third argument, just invalidate buffer.
1102 State = InvalidateBuffer(C, State, DstBuffer, MemVal,
1103 /*IsSourceBuffer*/ false, Size);
1106 if (StateNullChar && !StateNonNullChar) {
1107 // If the value of the second argument of 'memset()' is zero, set the
1108 // string length of destination buffer to 0 directly.
1109 State = setCStringLength(State, MR,
1110 svalBuilder.makeZeroVal(Ctx.getSizeType()));
1111 } else if (!StateNullChar && StateNonNullChar) {
1112 SVal NewStrLen = svalBuilder.getMetadataSymbolVal(
1113 CStringChecker::getTag(), MR, DstBuffer, Ctx.getSizeType(),
1114 C.getLocationContext(), C.blockCount());
1116 // If the value of second argument is not zero, then the string length
1117 // is at least the size argument.
1118 SVal NewStrLenGESize = svalBuilder.evalBinOp(
1119 State, BO_GE, NewStrLen, SizeVal, svalBuilder.getConditionType());
1121 State = setCStringLength(
1122 State->assume(NewStrLenGESize.castAs<DefinedOrUnknownSVal>(), true),
1126 // If the offset is not zero and char value is not concrete, we can do
1127 // nothing but invalidate the buffer.
1128 State = InvalidateBuffer(C, State, DstBuffer, MemVal,
1129 /*IsSourceBuffer*/ false, Size);
1134 //===----------------------------------------------------------------------===//
1135 // evaluation of individual function calls.
1136 //===----------------------------------------------------------------------===//
1138 void CStringChecker::evalCopyCommon(CheckerContext &C,
1140 ProgramStateRef state,
1141 const Expr *Size, const Expr *Dest,
1142 const Expr *Source, bool Restricted,
1143 bool IsMempcpy) const {
1144 CurrentFunctionDescription = "memory copy function";
1146 // See if the size argument is zero.
1147 const LocationContext *LCtx = C.getLocationContext();
1148 SVal sizeVal = state->getSVal(Size, LCtx);
1149 QualType sizeTy = Size->getType();
1151 ProgramStateRef stateZeroSize, stateNonZeroSize;
1152 std::tie(stateZeroSize, stateNonZeroSize) =
1153 assumeZero(C, state, sizeVal, sizeTy);
1155 // Get the value of the Dest.
1156 SVal destVal = state->getSVal(Dest, LCtx);
1158 // If the size is zero, there won't be any actual memory access, so
1159 // just bind the return value to the destination buffer and return.
1160 if (stateZeroSize && !stateNonZeroSize) {
1161 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
1162 C.addTransition(stateZeroSize);
1166 // If the size can be nonzero, we have to check the other arguments.
1167 if (stateNonZeroSize) {
1168 state = stateNonZeroSize;
1170 // Ensure the destination is not null. If it is NULL there will be a
1171 // NULL pointer dereference.
1172 state = checkNonNull(C, state, Dest, destVal, 1);
1176 // Get the value of the Src.
1177 SVal srcVal = state->getSVal(Source, LCtx);
1179 // Ensure the source is not null. If it is NULL there will be a
1180 // NULL pointer dereference.
1181 state = checkNonNull(C, state, Source, srcVal, 2);
1185 // Ensure the accesses are valid and that the buffers do not overlap.
1186 const char * const writeWarning =
1187 "Memory copy function overflows destination buffer";
1188 state = CheckBufferAccess(C, state, Size, Dest, Source,
1189 writeWarning, /* sourceWarning = */ nullptr);
1191 state = CheckOverlap(C, state, Size, Dest, Source);
1196 // If this is mempcpy, get the byte after the last byte copied and
1199 // Get the byte after the last byte copied.
1200 SValBuilder &SvalBuilder = C.getSValBuilder();
1201 ASTContext &Ctx = SvalBuilder.getContext();
1202 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
1203 SVal DestRegCharVal =
1204 SvalBuilder.evalCast(destVal, CharPtrTy, Dest->getType());
1205 SVal lastElement = C.getSValBuilder().evalBinOp(
1206 state, BO_Add, DestRegCharVal, sizeVal, Dest->getType());
1207 // If we don't know how much we copied, we can at least
1208 // conjure a return value for later.
1209 if (lastElement.isUnknown())
1210 lastElement = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1213 // The byte after the last byte copied is the return value.
1214 state = state->BindExpr(CE, LCtx, lastElement);
1216 // All other copies return the destination buffer.
1217 // (Well, bcopy() has a void return type, but this won't hurt.)
1218 state = state->BindExpr(CE, LCtx, destVal);
1221 // Invalidate the destination (regular invalidation without pointer-escaping
1222 // the address of the top-level region).
1223 // FIXME: Even if we can't perfectly model the copy, we should see if we
1224 // can use LazyCompoundVals to copy the source values into the destination.
1225 // This would probably remove any existing bindings past the end of the
1226 // copied region, but that's still an improvement over blank invalidation.
1227 state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest),
1228 /*IsSourceBuffer*/false, Size);
1230 // Invalidate the source (const-invalidation without const-pointer-escaping
1231 // the address of the top-level region).
1232 state = InvalidateBuffer(C, state, Source, C.getSVal(Source),
1233 /*IsSourceBuffer*/true, nullptr);
1235 C.addTransition(state);
1240 void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
1241 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
1242 // The return value is the address of the destination buffer.
1243 const Expr *Dest = CE->getArg(0);
1244 ProgramStateRef state = C.getState();
1246 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
1249 void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
1250 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1251 // The return value is a pointer to the byte following the last written byte.
1252 const Expr *Dest = CE->getArg(0);
1253 ProgramStateRef state = C.getState();
1255 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
1258 void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
1259 // void *memmove(void *dst, const void *src, size_t n);
1260 // The return value is the address of the destination buffer.
1261 const Expr *Dest = CE->getArg(0);
1262 ProgramStateRef state = C.getState();
1264 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
1267 void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
1268 // void bcopy(const void *src, void *dst, size_t n);
1269 evalCopyCommon(C, CE, C.getState(),
1270 CE->getArg(2), CE->getArg(1), CE->getArg(0));
1273 void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
1274 // int memcmp(const void *s1, const void *s2, size_t n);
1275 CurrentFunctionDescription = "memory comparison function";
1277 const Expr *Left = CE->getArg(0);
1278 const Expr *Right = CE->getArg(1);
1279 const Expr *Size = CE->getArg(2);
1281 ProgramStateRef state = C.getState();
1282 SValBuilder &svalBuilder = C.getSValBuilder();
1284 // See if the size argument is zero.
1285 const LocationContext *LCtx = C.getLocationContext();
1286 SVal sizeVal = state->getSVal(Size, LCtx);
1287 QualType sizeTy = Size->getType();
1289 ProgramStateRef stateZeroSize, stateNonZeroSize;
1290 std::tie(stateZeroSize, stateNonZeroSize) =
1291 assumeZero(C, state, sizeVal, sizeTy);
1293 // If the size can be zero, the result will be 0 in that case, and we don't
1294 // have to check either of the buffers.
1295 if (stateZeroSize) {
1296 state = stateZeroSize;
1297 state = state->BindExpr(CE, LCtx,
1298 svalBuilder.makeZeroVal(CE->getType()));
1299 C.addTransition(state);
1302 // If the size can be nonzero, we have to check the other arguments.
1303 if (stateNonZeroSize) {
1304 state = stateNonZeroSize;
1305 // If we know the two buffers are the same, we know the result is 0.
1306 // First, get the two buffers' addresses. Another checker will have already
1307 // made sure they're not undefined.
1308 DefinedOrUnknownSVal LV =
1309 state->getSVal(Left, LCtx).castAs<DefinedOrUnknownSVal>();
1310 DefinedOrUnknownSVal RV =
1311 state->getSVal(Right, LCtx).castAs<DefinedOrUnknownSVal>();
1313 // See if they are the same.
1314 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1315 ProgramStateRef StSameBuf, StNotSameBuf;
1316 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1318 // If the two arguments might be the same buffer, we know the result is 0,
1319 // and we only need to check one size.
1322 state = CheckBufferAccess(C, state, Size, Left);
1324 state = StSameBuf->BindExpr(CE, LCtx,
1325 svalBuilder.makeZeroVal(CE->getType()));
1326 C.addTransition(state);
1330 // If the two arguments might be different buffers, we have to check the
1331 // size of both of them.
1333 state = StNotSameBuf;
1334 state = CheckBufferAccess(C, state, Size, Left, Right);
1336 // The return value is the comparison result, which we don't know.
1337 SVal CmpV = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1339 state = state->BindExpr(CE, LCtx, CmpV);
1340 C.addTransition(state);
1346 void CStringChecker::evalstrLength(CheckerContext &C,
1347 const CallExpr *CE) const {
1348 // size_t strlen(const char *s);
1349 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1352 void CStringChecker::evalstrnLength(CheckerContext &C,
1353 const CallExpr *CE) const {
1354 // size_t strnlen(const char *s, size_t maxlen);
1355 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1358 void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
1359 bool IsStrnlen) const {
1360 CurrentFunctionDescription = "string length function";
1361 ProgramStateRef state = C.getState();
1362 const LocationContext *LCtx = C.getLocationContext();
1365 const Expr *maxlenExpr = CE->getArg(1);
1366 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1368 ProgramStateRef stateZeroSize, stateNonZeroSize;
1369 std::tie(stateZeroSize, stateNonZeroSize) =
1370 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1372 // If the size can be zero, the result will be 0 in that case, and we don't
1373 // have to check the string itself.
1374 if (stateZeroSize) {
1375 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
1376 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
1377 C.addTransition(stateZeroSize);
1380 // If the size is GUARANTEED to be zero, we're done!
1381 if (!stateNonZeroSize)
1384 // Otherwise, record the assumption that the size is nonzero.
1385 state = stateNonZeroSize;
1388 // Check that the string argument is non-null.
1389 const Expr *Arg = CE->getArg(0);
1390 SVal ArgVal = state->getSVal(Arg, LCtx);
1392 state = checkNonNull(C, state, Arg, ArgVal, 1);
1397 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
1399 // If the argument isn't a valid C string, there's no valid state to
1401 if (strLength.isUndef())
1404 DefinedOrUnknownSVal result = UnknownVal();
1406 // If the check is for strnlen() then bind the return value to no more than
1407 // the maxlen value.
1409 QualType cmpTy = C.getSValBuilder().getConditionType();
1411 // It's a little unfortunate to be getting this again,
1412 // but it's not that expensive...
1413 const Expr *maxlenExpr = CE->getArg(1);
1414 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1416 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1417 Optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
1419 if (strLengthNL && maxlenValNL) {
1420 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
1422 // Check if the strLength is greater than the maxlen.
1423 std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
1425 .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1426 .castAs<DefinedOrUnknownSVal>());
1428 if (stateStringTooLong && !stateStringNotTooLong) {
1429 // If the string is longer than maxlen, return maxlen.
1430 result = *maxlenValNL;
1431 } else if (stateStringNotTooLong && !stateStringTooLong) {
1432 // If the string is shorter than maxlen, return its length.
1433 result = *strLengthNL;
1437 if (result.isUnknown()) {
1438 // If we don't have enough information for a comparison, there's
1439 // no guarantee the full string length will actually be returned.
1440 // All we know is the return value is the min of the string length
1441 // and the limit. This is better than nothing.
1442 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1444 NonLoc resultNL = result.castAs<NonLoc>();
1447 state = state->assume(C.getSValBuilder().evalBinOpNN(
1448 state, BO_LE, resultNL, *strLengthNL, cmpTy)
1449 .castAs<DefinedOrUnknownSVal>(), true);
1453 state = state->assume(C.getSValBuilder().evalBinOpNN(
1454 state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1455 .castAs<DefinedOrUnknownSVal>(), true);
1460 // This is a plain strlen(), not strnlen().
1461 result = strLength.castAs<DefinedOrUnknownSVal>();
1463 // If we don't know the length of the string, conjure a return
1464 // value, so it can be used in constraints, at least.
1465 if (result.isUnknown()) {
1466 result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
1471 // Bind the return value.
1472 assert(!result.isUnknown() && "Should have conjured a value by now");
1473 state = state->BindExpr(CE, LCtx, result);
1474 C.addTransition(state);
1477 void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
1478 // char *strcpy(char *restrict dst, const char *restrict src);
1479 evalStrcpyCommon(C, CE,
1480 /* returnEnd = */ false,
1481 /* isBounded = */ false,
1482 /* isAppending = */ false);
1485 void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
1486 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
1487 evalStrcpyCommon(C, CE,
1488 /* returnEnd = */ false,
1489 /* isBounded = */ true,
1490 /* isAppending = */ false);
1493 void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
1494 // char *stpcpy(char *restrict dst, const char *restrict src);
1495 evalStrcpyCommon(C, CE,
1496 /* returnEnd = */ true,
1497 /* isBounded = */ false,
1498 /* isAppending = */ false);
1501 void CStringChecker::evalStrlcpy(CheckerContext &C, const CallExpr *CE) const {
1502 // char *strlcpy(char *dst, const char *src, size_t n);
1503 evalStrcpyCommon(C, CE,
1504 /* returnEnd = */ true,
1505 /* isBounded = */ true,
1506 /* isAppending = */ false,
1507 /* returnPtr = */ false);
1510 void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
1511 //char *strcat(char *restrict s1, const char *restrict s2);
1512 evalStrcpyCommon(C, CE,
1513 /* returnEnd = */ false,
1514 /* isBounded = */ false,
1515 /* isAppending = */ true);
1518 void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
1519 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1520 evalStrcpyCommon(C, CE,
1521 /* returnEnd = */ false,
1522 /* isBounded = */ true,
1523 /* isAppending = */ true);
1526 void CStringChecker::evalStrlcat(CheckerContext &C, const CallExpr *CE) const {
1527 // FIXME: strlcat() uses a different rule for bound checking, i.e. 'n' means
1528 // a different thing as compared to strncat(). This currently causes
1529 // false positives in the alpha string bound checker.
1531 //char *strlcat(char *s1, const char *s2, size_t n);
1532 evalStrcpyCommon(C, CE,
1533 /* returnEnd = */ false,
1534 /* isBounded = */ true,
1535 /* isAppending = */ true,
1536 /* returnPtr = */ false);
1539 void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
1540 bool returnEnd, bool isBounded,
1541 bool isAppending, bool returnPtr) const {
1542 CurrentFunctionDescription = "string copy function";
1543 ProgramStateRef state = C.getState();
1544 const LocationContext *LCtx = C.getLocationContext();
1546 // Check that the destination is non-null.
1547 const Expr *Dst = CE->getArg(0);
1548 SVal DstVal = state->getSVal(Dst, LCtx);
1550 state = checkNonNull(C, state, Dst, DstVal, 1);
1554 // Check that the source is non-null.
1555 const Expr *srcExpr = CE->getArg(1);
1556 SVal srcVal = state->getSVal(srcExpr, LCtx);
1557 state = checkNonNull(C, state, srcExpr, srcVal, 2);
1561 // Get the string length of the source.
1562 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
1564 // If the source isn't a valid C string, give up.
1565 if (strLength.isUndef())
1568 SValBuilder &svalBuilder = C.getSValBuilder();
1569 QualType cmpTy = svalBuilder.getConditionType();
1570 QualType sizeTy = svalBuilder.getContext().getSizeType();
1572 // These two values allow checking two kinds of errors:
1573 // - actual overflows caused by a source that doesn't fit in the destination
1574 // - potential overflows caused by a bound that could exceed the destination
1575 SVal amountCopied = UnknownVal();
1576 SVal maxLastElementIndex = UnknownVal();
1577 const char *boundWarning = nullptr;
1579 state = CheckOverlap(C, state, isBounded ? CE->getArg(2) : CE->getArg(1), Dst, srcExpr);
1584 // If the function is strncpy, strncat, etc... it is bounded.
1586 // Get the max number of characters to copy.
1587 const Expr *lenExpr = CE->getArg(2);
1588 SVal lenVal = state->getSVal(lenExpr, LCtx);
1590 // Protect against misdeclared strncpy().
1591 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
1593 Optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1594 Optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
1596 // If we know both values, we might be able to figure out how much
1598 if (strLengthNL && lenValNL) {
1599 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
1601 // Check if the max number to copy is less than the length of the src.
1602 // If the bound is equal to the source length, strncpy won't null-
1603 // terminate the result!
1604 std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
1605 svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1606 .castAs<DefinedOrUnknownSVal>());
1608 if (stateSourceTooLong && !stateSourceNotTooLong) {
1609 // Max number to copy is less than the length of the src, so the actual
1610 // strLength copied is the max number arg.
1611 state = stateSourceTooLong;
1612 amountCopied = lenVal;
1614 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1615 // The source buffer entirely fits in the bound.
1616 state = stateSourceNotTooLong;
1617 amountCopied = strLength;
1621 // We still want to know if the bound is known to be too large.
1624 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1626 // Get the string length of the destination. If the destination is
1627 // memory that can't have a string length, we shouldn't be copying
1629 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1630 if (dstStrLength.isUndef())
1633 if (Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>()) {
1634 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1638 boundWarning = "Size argument is greater than the free space in the "
1639 "destination buffer";
1643 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1644 // (Yes, strncpy and strncat differ in how they treat termination.
1645 // strncat ALWAYS terminates, but strncpy doesn't.)
1647 // We need a special case for when the copy size is zero, in which
1648 // case strncpy will do no work at all. Our bounds check uses n-1
1649 // as the last element accessed, so n == 0 is problematic.
1650 ProgramStateRef StateZeroSize, StateNonZeroSize;
1651 std::tie(StateZeroSize, StateNonZeroSize) =
1652 assumeZero(C, state, *lenValNL, sizeTy);
1654 // If the size is known to be zero, we're done.
1655 if (StateZeroSize && !StateNonZeroSize) {
1657 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1659 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, *lenValNL);
1661 C.addTransition(StateZeroSize);
1665 // Otherwise, go ahead and figure out the last element we'll touch.
1666 // We don't record the non-zero assumption here because we can't
1667 // be sure. We won't warn on a possible zero.
1668 NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
1669 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1671 boundWarning = "Size argument is greater than the length of the "
1672 "destination buffer";
1676 // If we couldn't pin down the copy length, at least bound it.
1677 // FIXME: We should actually run this code path for append as well, but
1678 // right now it creates problems with constraints (since we can end up
1679 // trying to pass constraints from symbol to symbol).
1680 if (amountCopied.isUnknown() && !isAppending) {
1681 // Try to get a "hypothetical" string length symbol, which we can later
1682 // set as a real value if that turns out to be the case.
1683 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1684 assert(!amountCopied.isUndef());
1686 if (Optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>()) {
1688 // amountCopied <= lenVal
1689 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1693 state = state->assume(
1694 copiedLessThanBound.castAs<DefinedOrUnknownSVal>(), true);
1700 // amountCopied <= strlen(source)
1701 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1705 state = state->assume(
1706 copiedLessThanSrc.castAs<DefinedOrUnknownSVal>(), true);
1714 // The function isn't bounded. The amount copied should match the length
1715 // of the source buffer.
1716 amountCopied = strLength;
1721 // This represents the number of characters copied into the destination
1722 // buffer. (It may not actually be the strlen if the destination buffer
1723 // is not terminated.)
1724 SVal finalStrLength = UnknownVal();
1726 // If this is an appending function (strcat, strncat...) then set the
1727 // string length to strlen(src) + strlen(dst) since the buffer will
1728 // ultimately contain both.
1730 // Get the string length of the destination. If the destination is memory
1731 // that can't have a string length, we shouldn't be copying into it anyway.
1732 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1733 if (dstStrLength.isUndef())
1736 Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>();
1737 Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
1739 // If we know both string lengths, we might know the final string length.
1740 if (srcStrLengthNL && dstStrLengthNL) {
1741 // Make sure the two lengths together don't overflow a size_t.
1742 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1746 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1747 *dstStrLengthNL, sizeTy);
1750 // If we couldn't get a single value for the final string length,
1751 // we can at least bound it by the individual lengths.
1752 if (finalStrLength.isUnknown()) {
1753 // Try to get a "hypothetical" string length symbol, which we can later
1754 // set as a real value if that turns out to be the case.
1755 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1756 assert(!finalStrLength.isUndef());
1758 if (Optional<NonLoc> finalStrLengthNL = finalStrLength.getAs<NonLoc>()) {
1759 if (srcStrLengthNL) {
1760 // finalStrLength >= srcStrLength
1761 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1765 state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
1771 if (dstStrLengthNL) {
1772 // finalStrLength >= dstStrLength
1773 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1778 state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
1786 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1787 // the final string length will match the input string length.
1788 finalStrLength = amountCopied;
1794 // The final result of the function will either be a pointer past the last
1795 // copied element, or a pointer to the start of the destination buffer.
1796 Result = (returnEnd ? UnknownVal() : DstVal);
1798 Result = finalStrLength;
1803 // If the destination is a MemRegion, try to check for a buffer overflow and
1804 // record the new string length.
1805 if (Optional<loc::MemRegionVal> dstRegVal =
1806 DstVal.getAs<loc::MemRegionVal>()) {
1807 QualType ptrTy = Dst->getType();
1809 // If we have an exact value on a bounded copy, use that to check for
1810 // overflows, rather than our estimate about how much is actually copied.
1812 if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
1813 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1815 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1822 // Then, if the final length is known...
1823 if (Optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
1824 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1825 *knownStrLength, ptrTy);
1827 // ...and we haven't checked the bound, we'll check the actual copy.
1828 if (!boundWarning) {
1829 const char * const warningMsg =
1830 "String copy function overflows destination buffer";
1831 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1836 // If this is a stpcpy-style copy, the last element is the return value.
1837 if (returnPtr && returnEnd)
1838 Result = lastElement;
1841 // Invalidate the destination (regular invalidation without pointer-escaping
1842 // the address of the top-level region). This must happen before we set the
1843 // C string length because invalidation will clear the length.
1844 // FIXME: Even if we can't perfectly model the copy, we should see if we
1845 // can use LazyCompoundVals to copy the source values into the destination.
1846 // This would probably remove any existing bindings past the end of the
1847 // string, but that's still an improvement over blank invalidation.
1848 state = InvalidateBuffer(C, state, Dst, *dstRegVal,
1849 /*IsSourceBuffer*/false, nullptr);
1851 // Invalidate the source (const-invalidation without const-pointer-escaping
1852 // the address of the top-level region).
1853 state = InvalidateBuffer(C, state, srcExpr, srcVal, /*IsSourceBuffer*/true,
1856 // Set the C string length of the destination, if we know it.
1857 if (isBounded && !isAppending) {
1858 // strncpy is annoying in that it doesn't guarantee to null-terminate
1859 // the result string. If the original string didn't fit entirely inside
1860 // the bound (including the null-terminator), we don't know how long the
1862 if (amountCopied != strLength)
1863 finalStrLength = UnknownVal();
1865 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
1871 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1872 // overflow, we still need a result. Conjure a return value.
1873 if (returnEnd && Result.isUnknown()) {
1874 Result = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
1877 // Set the return value.
1878 state = state->BindExpr(CE, LCtx, Result);
1879 C.addTransition(state);
1882 void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1883 //int strcmp(const char *s1, const char *s2);
1884 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
1887 void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
1888 //int strncmp(const char *s1, const char *s2, size_t n);
1889 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1892 void CStringChecker::evalStrcasecmp(CheckerContext &C,
1893 const CallExpr *CE) const {
1894 //int strcasecmp(const char *s1, const char *s2);
1895 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
1898 void CStringChecker::evalStrncasecmp(CheckerContext &C,
1899 const CallExpr *CE) const {
1900 //int strncasecmp(const char *s1, const char *s2, size_t n);
1901 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1904 void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
1905 bool isBounded, bool ignoreCase) const {
1906 CurrentFunctionDescription = "string comparison function";
1907 ProgramStateRef state = C.getState();
1908 const LocationContext *LCtx = C.getLocationContext();
1910 // Check that the first string is non-null
1911 const Expr *s1 = CE->getArg(0);
1912 SVal s1Val = state->getSVal(s1, LCtx);
1913 state = checkNonNull(C, state, s1, s1Val, 1);
1917 // Check that the second string is non-null.
1918 const Expr *s2 = CE->getArg(1);
1919 SVal s2Val = state->getSVal(s2, LCtx);
1920 state = checkNonNull(C, state, s2, s2Val, 2);
1924 // Get the string length of the first string or give up.
1925 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1926 if (s1Length.isUndef())
1929 // Get the string length of the second string or give up.
1930 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1931 if (s2Length.isUndef())
1934 // If we know the two buffers are the same, we know the result is 0.
1935 // First, get the two buffers' addresses. Another checker will have already
1936 // made sure they're not undefined.
1937 DefinedOrUnknownSVal LV = s1Val.castAs<DefinedOrUnknownSVal>();
1938 DefinedOrUnknownSVal RV = s2Val.castAs<DefinedOrUnknownSVal>();
1940 // See if they are the same.
1941 SValBuilder &svalBuilder = C.getSValBuilder();
1942 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
1943 ProgramStateRef StSameBuf, StNotSameBuf;
1944 std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
1946 // If the two arguments might be the same buffer, we know the result is 0,
1947 // and we only need to check one size.
1949 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1950 svalBuilder.makeZeroVal(CE->getType()));
1951 C.addTransition(StSameBuf);
1953 // If the two arguments are GUARANTEED to be the same, we're done!
1958 assert(StNotSameBuf);
1959 state = StNotSameBuf;
1961 // At this point we can go about comparing the two buffers.
1962 // For now, we only do this if they're both known string literals.
1964 // Attempt to extract string literals from both expressions.
1965 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1966 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1967 bool canComputeResult = false;
1968 SVal resultVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
1971 if (s1StrLiteral && s2StrLiteral) {
1972 StringRef s1StrRef = s1StrLiteral->getString();
1973 StringRef s2StrRef = s2StrLiteral->getString();
1976 // Get the max number of characters to compare.
1977 const Expr *lenExpr = CE->getArg(2);
1978 SVal lenVal = state->getSVal(lenExpr, LCtx);
1980 // If the length is known, we can get the right substrings.
1981 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1982 // Create substrings of each to compare the prefix.
1983 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1984 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1985 canComputeResult = true;
1988 // This is a normal, unbounded strcmp.
1989 canComputeResult = true;
1992 if (canComputeResult) {
1993 // Real strcmp stops at null characters.
1994 size_t s1Term = s1StrRef.find('\0');
1995 if (s1Term != StringRef::npos)
1996 s1StrRef = s1StrRef.substr(0, s1Term);
1998 size_t s2Term = s2StrRef.find('\0');
1999 if (s2Term != StringRef::npos)
2000 s2StrRef = s2StrRef.substr(0, s2Term);
2002 // Use StringRef's comparison methods to compute the actual result.
2003 int compareRes = ignoreCase ? s1StrRef.compare_lower(s2StrRef)
2004 : s1StrRef.compare(s2StrRef);
2006 // The strcmp function returns an integer greater than, equal to, or less
2007 // than zero, [c11, p7.24.4.2].
2008 if (compareRes == 0) {
2009 resultVal = svalBuilder.makeIntVal(compareRes, CE->getType());
2012 DefinedSVal zeroVal = svalBuilder.makeIntVal(0, CE->getType());
2013 // Constrain strcmp's result range based on the result of StringRef's
2014 // comparison methods.
2015 BinaryOperatorKind op = (compareRes == 1) ? BO_GT : BO_LT;
2016 SVal compareWithZero =
2017 svalBuilder.evalBinOp(state, op, resultVal, zeroVal,
2018 svalBuilder.getConditionType());
2019 DefinedSVal compareWithZeroVal = compareWithZero.castAs<DefinedSVal>();
2020 state = state->assume(compareWithZeroVal, true);
2025 state = state->BindExpr(CE, LCtx, resultVal);
2027 // Record this as a possible path.
2028 C.addTransition(state);
2031 void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
2032 //char *strsep(char **stringp, const char *delim);
2033 // Sanity: does the search string parameter match the return type?
2034 const Expr *SearchStrPtr = CE->getArg(0);
2035 QualType CharPtrTy = SearchStrPtr->getType()->getPointeeType();
2036 if (CharPtrTy.isNull() ||
2037 CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
2040 CurrentFunctionDescription = "strsep()";
2041 ProgramStateRef State = C.getState();
2042 const LocationContext *LCtx = C.getLocationContext();
2044 // Check that the search string pointer is non-null (though it may point to
2046 SVal SearchStrVal = State->getSVal(SearchStrPtr, LCtx);
2047 State = checkNonNull(C, State, SearchStrPtr, SearchStrVal, 1);
2051 // Check that the delimiter string is non-null.
2052 const Expr *DelimStr = CE->getArg(1);
2053 SVal DelimStrVal = State->getSVal(DelimStr, LCtx);
2054 State = checkNonNull(C, State, DelimStr, DelimStrVal, 2);
2058 SValBuilder &SVB = C.getSValBuilder();
2060 if (Optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
2061 // Get the current value of the search string pointer, as a char*.
2062 Result = State->getSVal(*SearchStrLoc, CharPtrTy);
2064 // Invalidate the search string, representing the change of one delimiter
2065 // character to NUL.
2066 State = InvalidateBuffer(C, State, SearchStrPtr, Result,
2067 /*IsSourceBuffer*/false, nullptr);
2069 // Overwrite the search string pointer. The new value is either an address
2070 // further along in the same string, or NULL if there are no more tokens.
2071 State = State->bindLoc(*SearchStrLoc,
2072 SVB.conjureSymbolVal(getTag(),
2079 assert(SearchStrVal.isUnknown());
2080 // Conjure a symbolic value. It's the best we can do.
2081 Result = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
2084 // Set the return value, and finish.
2085 State = State->BindExpr(CE, LCtx, Result);
2086 C.addTransition(State);
2089 // These should probably be moved into a C++ standard library checker.
2090 void CStringChecker::evalStdCopy(CheckerContext &C, const CallExpr *CE) const {
2091 evalStdCopyCommon(C, CE);
2094 void CStringChecker::evalStdCopyBackward(CheckerContext &C,
2095 const CallExpr *CE) const {
2096 evalStdCopyCommon(C, CE);
2099 void CStringChecker::evalStdCopyCommon(CheckerContext &C,
2100 const CallExpr *CE) const {
2101 if (!CE->getArg(2)->getType()->isPointerType())
2104 ProgramStateRef State = C.getState();
2106 const LocationContext *LCtx = C.getLocationContext();
2108 // template <class _InputIterator, class _OutputIterator>
2110 // copy(_InputIterator __first, _InputIterator __last,
2111 // _OutputIterator __result)
2113 // Invalidate the destination buffer
2114 const Expr *Dst = CE->getArg(2);
2115 SVal DstVal = State->getSVal(Dst, LCtx);
2116 State = InvalidateBuffer(C, State, Dst, DstVal, /*IsSource=*/false,
2119 SValBuilder &SVB = C.getSValBuilder();
2121 SVal ResultVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
2122 State = State->BindExpr(CE, LCtx, ResultVal);
2124 C.addTransition(State);
2127 void CStringChecker::evalMemset(CheckerContext &C, const CallExpr *CE) const {
2128 CurrentFunctionDescription = "memory set function";
2130 const Expr *Mem = CE->getArg(0);
2131 const Expr *CharE = CE->getArg(1);
2132 const Expr *Size = CE->getArg(2);
2133 ProgramStateRef State = C.getState();
2135 // See if the size argument is zero.
2136 const LocationContext *LCtx = C.getLocationContext();
2137 SVal SizeVal = State->getSVal(Size, LCtx);
2138 QualType SizeTy = Size->getType();
2140 ProgramStateRef StateZeroSize, StateNonZeroSize;
2141 std::tie(StateZeroSize, StateNonZeroSize) =
2142 assumeZero(C, State, SizeVal, SizeTy);
2144 // Get the value of the memory area.
2145 SVal MemVal = State->getSVal(Mem, LCtx);
2147 // If the size is zero, there won't be any actual memory access, so
2148 // just bind the return value to the Mem buffer and return.
2149 if (StateZeroSize && !StateNonZeroSize) {
2150 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, MemVal);
2151 C.addTransition(StateZeroSize);
2155 // Ensure the memory area is not null.
2156 // If it is NULL there will be a NULL pointer dereference.
2157 State = checkNonNull(C, StateNonZeroSize, Mem, MemVal, 1);
2161 State = CheckBufferAccess(C, State, Size, Mem);
2165 // According to the values of the arguments, bind the value of the second
2166 // argument to the destination buffer and set string length, or just
2167 // invalidate the destination buffer.
2168 if (!memsetAux(Mem, C.getSVal(CharE), Size, C, State))
2171 State = State->BindExpr(CE, LCtx, MemVal);
2172 C.addTransition(State);
2175 void CStringChecker::evalBzero(CheckerContext &C, const CallExpr *CE) const {
2176 CurrentFunctionDescription = "memory clearance function";
2178 const Expr *Mem = CE->getArg(0);
2179 const Expr *Size = CE->getArg(1);
2180 SVal Zero = C.getSValBuilder().makeZeroVal(C.getASTContext().IntTy);
2182 ProgramStateRef State = C.getState();
2184 // See if the size argument is zero.
2185 SVal SizeVal = C.getSVal(Size);
2186 QualType SizeTy = Size->getType();
2188 ProgramStateRef StateZeroSize, StateNonZeroSize;
2189 std::tie(StateZeroSize, StateNonZeroSize) =
2190 assumeZero(C, State, SizeVal, SizeTy);
2192 // If the size is zero, there won't be any actual memory access,
2193 // In this case we just return.
2194 if (StateZeroSize && !StateNonZeroSize) {
2195 C.addTransition(StateZeroSize);
2199 // Get the value of the memory area.
2200 SVal MemVal = C.getSVal(Mem);
2202 // Ensure the memory area is not null.
2203 // If it is NULL there will be a NULL pointer dereference.
2204 State = checkNonNull(C, StateNonZeroSize, Mem, MemVal, 1);
2208 State = CheckBufferAccess(C, State, Size, Mem);
2212 if (!memsetAux(Mem, Zero, Size, C, State))
2215 C.addTransition(State);
2218 //===----------------------------------------------------------------------===//
2219 // The driver method, and other Checker callbacks.
2220 //===----------------------------------------------------------------------===//
2222 CStringChecker::FnCheck CStringChecker::identifyCall(const CallEvent &Call,
2223 CheckerContext &C) const {
2224 const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
2228 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
2232 if (Call.isCalled(StdCopy)) {
2233 return &CStringChecker::evalStdCopy;
2234 } else if (Call.isCalled(StdCopyBackward)) {
2235 return &CStringChecker::evalStdCopyBackward;
2238 // Pro-actively check that argument types are safe to do arithmetic upon.
2239 // We do not want to crash if someone accidentally passes a structure
2240 // into, say, a C++ overload of any of these functions. We could not check
2241 // that for std::copy because they may have arguments of other types.
2242 for (auto I : CE->arguments()) {
2243 QualType T = I->getType();
2244 if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
2248 const FnCheck *Callback = Callbacks.lookup(Call);
2255 bool CStringChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
2256 FnCheck Callback = identifyCall(Call, C);
2258 // If the callee isn't a string function, let another checker handle it.
2262 // Check and evaluate the call.
2263 const auto *CE = cast<CallExpr>(Call.getOriginExpr());
2264 (this->*Callback)(C, CE);
2266 // If the evaluate call resulted in no change, chain to the next eval call
2268 // Note, the custom CString evaluation calls assume that basic safety
2269 // properties are held. However, if the user chooses to turn off some of these
2270 // checks, we ignore the issues and leave the call evaluation to a generic
2272 return C.isDifferent();
2275 void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
2276 // Record string length for char a[] = "abc";
2277 ProgramStateRef state = C.getState();
2279 for (const auto *I : DS->decls()) {
2280 const VarDecl *D = dyn_cast<VarDecl>(I);
2284 // FIXME: Handle array fields of structs.
2285 if (!D->getType()->isArrayType())
2288 const Expr *Init = D->getInit();
2291 if (!isa<StringLiteral>(Init))
2294 Loc VarLoc = state->getLValue(D, C.getLocationContext());
2295 const MemRegion *MR = VarLoc.getAsRegion();
2299 SVal StrVal = C.getSVal(Init);
2300 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
2301 DefinedOrUnknownSVal strLength =
2302 getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
2304 state = state->set<CStringLength>(MR, strLength);
2307 C.addTransition(state);
2311 CStringChecker::checkRegionChanges(ProgramStateRef state,
2312 const InvalidatedSymbols *,
2313 ArrayRef<const MemRegion *> ExplicitRegions,
2314 ArrayRef<const MemRegion *> Regions,
2315 const LocationContext *LCtx,
2316 const CallEvent *Call) const {
2317 CStringLengthTy Entries = state->get<CStringLength>();
2318 if (Entries.isEmpty())
2321 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
2322 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
2324 // First build sets for the changed regions and their super-regions.
2325 for (ArrayRef<const MemRegion *>::iterator
2326 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
2327 const MemRegion *MR = *I;
2328 Invalidated.insert(MR);
2330 SuperRegions.insert(MR);
2331 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
2332 MR = SR->getSuperRegion();
2333 SuperRegions.insert(MR);
2337 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2339 // Then loop over the entries in the current state.
2340 for (CStringLengthTy::iterator I = Entries.begin(),
2341 E = Entries.end(); I != E; ++I) {
2342 const MemRegion *MR = I.getKey();
2344 // Is this entry for a super-region of a changed region?
2345 if (SuperRegions.count(MR)) {
2346 Entries = F.remove(Entries, MR);
2350 // Is this entry for a sub-region of a changed region?
2351 const MemRegion *Super = MR;
2352 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2353 Super = SR->getSuperRegion();
2354 if (Invalidated.count(Super)) {
2355 Entries = F.remove(Entries, MR);
2361 return state->set<CStringLength>(Entries);
2364 void CStringChecker::checkLiveSymbols(ProgramStateRef state,
2365 SymbolReaper &SR) const {
2366 // Mark all symbols in our string length map as valid.
2367 CStringLengthTy Entries = state->get<CStringLength>();
2369 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2371 SVal Len = I.getData();
2373 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
2374 se = Len.symbol_end(); si != se; ++si)
2379 void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2380 CheckerContext &C) const {
2381 ProgramStateRef state = C.getState();
2382 CStringLengthTy Entries = state->get<CStringLength>();
2383 if (Entries.isEmpty())
2386 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2387 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
2389 SVal Len = I.getData();
2390 if (SymbolRef Sym = Len.getAsSymbol()) {
2392 Entries = F.remove(Entries, I.getKey());
2396 state = state->set<CStringLength>(Entries);
2397 C.addTransition(state);
2400 void ento::registerCStringModeling(CheckerManager &Mgr) {
2401 Mgr.registerChecker<CStringChecker>();
2404 bool ento::shouldRegisterCStringModeling(const LangOptions &LO) {
2408 #define REGISTER_CHECKER(name) \
2409 void ento::register##name(CheckerManager &mgr) { \
2410 CStringChecker *checker = mgr.getChecker<CStringChecker>(); \
2411 checker->Filter.Check##name = true; \
2412 checker->Filter.CheckName##name = mgr.getCurrentCheckerName(); \
2415 bool ento::shouldRegister##name(const LangOptions &LO) { return true; }
2417 REGISTER_CHECKER(CStringNullArg)
2418 REGISTER_CHECKER(CStringOutOfBounds)
2419 REGISTER_CHECKER(CStringBufferOverlap)
2420 REGISTER_CHECKER(CStringNotNullTerm)