[clang-tools-extra] [clang-tidy] Extend `bugprone-sizeof-expression` with matching `P +- sizeof(T)` and `P +- N * sizeof(T)` cases, add `cert-arr39-c` alias (PR #106061)
Nicolas van Kempen via cfe-commits
cfe-commits at lists.llvm.org
Wed Aug 28 22:05:34 PDT 2024
================
@@ -285,6 +288,50 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder *Finder) {
hasRHS(ignoringParenImpCasts(SizeOfExpr.bind("sizeof-ptr-div-expr"))))
.bind("sizeof-in-ptr-arithmetic-div"),
this);
+
+ // SEI CERT ARR39-C. Do not add or subtract a scaled integer to a pointer.
+ // Detect sizeof, alignof and offsetof usage in pointer arithmetics where
+ // they are used to scale the numeric distance, which is scaled again by
+ // the pointer arithmetic operator. This can result in forming invalid
+ // offsets.
+ //
+ // Examples, where P is a pointer, N is some integer (both compile-time and
+ // run-time): P + sizeof(T), P + sizeof(*P), P + N * sizeof(*P).
+ //
+ // This check does not warn on cases where the pointee type is "1 byte",
+ // as those cases can often come from generics and also do not constitute a
+ // problem because the size does not affect the scale used.
+ const auto PtrArithmeticIgnoredPointeeTypes = qualType(anyOf(
+ asString("char"), asString("unsigned char"), asString("signed char"),
+ asString("int8_t"), asString("uint8_t"), asString("std::byte"),
+ asString("const char"), asString("const unsigned char"),
+ asString("const signed char"), asString("const int8_t"),
+ asString("const uint8_t"), asString("const std::byte")));
+ const auto InterestingPtrTyForPtrArithmetic = pointerType(pointee(
+ qualType(unless(PtrArithmeticIgnoredPointeeTypes)).bind("pointee-type")));
+ const auto SizeofLikeScaleExpr =
+ expr(anyOf(unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf)),
+ unaryExprOrTypeTraitExpr(ofKind(UETT_AlignOf)),
+ offsetOfExpr()))
+ .bind("sizeof-in-ptr-arithmetic-scale-expr");
+ const auto PtrArithmeticIntegerScaleExpr = binaryOperator(
+ hasAnyOperatorName("*", "/"), hasEitherOperand(hasType(isInteger())),
+ hasEitherOperand(SizeofLikeScaleExpr));
+ const auto PtrArithmeticScaledIntegerExpr =
+ expr(anyOf(SizeofLikeScaleExpr, PtrArithmeticIntegerScaleExpr));
+
+ Finder->addMatcher(
+ expr(anyOf(
+ binaryOperator(
+ hasAnyOperatorName("+", "-"),
+ hasEitherOperand(hasType(InterestingPtrTyForPtrArithmetic)),
+ hasEitherOperand(PtrArithmeticScaledIntegerExpr))
----------------
nicovank wrote:
```suggestion
hasOperands(hasType(InterestingPtrTyForPtrArithmetic), PtrArithmeticScaledIntegerExpr)
```
https://github.com/llvm/llvm-project/pull/106061
More information about the cfe-commits
mailing list