================
@@ -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));
----------------
nicovank wrote:

```suggestion
      hasAnyOperatorName("*", "/"),
      hasOperands(hasType(isInteger()), SizeofLikeScaleExpr));
```

https://github.com/llvm/llvm-project/pull/106061
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to