[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")));
----------------
nicovank wrote:
This is redundant since there is the condition `PointeeSize != 1` anyway. My 2 cents is to not explicitly have ignored types and instead keep ignoring anything that has size 1. Less special cases, more robust.
Maybe the condition can be turned into a matcher, not sure if that's better performance-wise, I think it's fine as-is as a `check` condition.
https://github.com/llvm/llvm-project/pull/106061
More information about the cfe-commits
mailing list