[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)

DonĂ¡t Nagy via cfe-commits cfe-commits at lists.llvm.org
Wed Aug 28 05:46:22 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")));
----------------
NagyDonat wrote:

Would it be possible to match the canonical type instead of the qualified one? It's a bit suspicious that you list all the `const` variants but e.g. don't list the `volatile` ones...

https://github.com/llvm/llvm-project/pull/106061


More information about the cfe-commits mailing list