[cocci] [PATCH v1 1/1] scripts/coccinelle: Add script for using ARRAY_END()

Alejandro Colomar <[email protected]> Fri, 6 Mar 2026 00:20:24 +0100
Newsgroups fr.inria.cocci
Message-ID <f1c9dff525752dc5a839760269a1c96d6e0870b4.1772752564.git.alx@kernel.org>
Recently, we added an ARRAY_END() macro to simplify finding a pointer
one past the last element in an array.  Such a pointer is often called
the 'end', and thus the macro name.

This script makes it easy to find more places where that macro should be
used.

See also:
436debc9cad8 ("array_size.h: add ARRAY_END()")
8118f197b7b7 ("mm: fix benign off-by-one bugs")
a9e5620c9a9e ("kernel: fix off-by-one benign bugs")
61e9210e2392 ("mm: use ARRAY_END() instead of open-coding it")

Cc: Kees Cook <[email protected]>
Cc: Julia Lawall <[email protected]>
Cc: Nicolas Palix <[email protected]>
Signed-off-by: Alejandro Colomar <[email protected]>
---
 scripts/coccinelle/misc/array_end.cocci | 93 +++++++++++++++++++++++++
 1 file changed, 93 insertions(+)
 create mode 100644 scripts/coccinelle/misc/array_end.cocci

diff --git a/scripts/coccinelle/misc/array_end.cocci b/scripts/coccinelle/misc/array_end.cocci
new file mode 100644
index 00000000..2474b7e6
--- /dev/null
+++ b/scripts/coccinelle/misc/array_end.cocci
@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/// Use ARRAY_END instead of an expression derived from ARRAY_SIZE
+//
+// Confidence: ???
+// Copyright: 2026, Alejandro Colomar <[email protected]>
+// Comments:
+// Options: --no-includes --include-headers
+
+virtual patch
+virtual context
+virtual org
+virtual report
+
+@i@
+@@
+
+#include <linux/kernel.h>
+
+//----------------------------------------------------------
+//  For context mode
+//----------------------------------------------------------
+
+@depends on i&&context@
+type T;
+T[] a;
+expression b;
+@@
+(
+* (a + ARRAY_SIZE(a))
+|
+* (&a[0] + ARRAY_SIZE(a))
+|
+* (&a[ARRAY_SIZE(a)])
+|
+* (&a[ARRAY_SIZE(a) - b])
+)
+
+//----------------------------------------------------------
+//  For patch mode
+//----------------------------------------------------------
+
+@depends on i&&patch@
+type T;
+T[] a;
+expression b;
+@@
+(
+- (a + ARRAY_SIZE(a))
++ ARRAY_END(a)
+|
+- (&a[0] + ARRAY_SIZE(a))
++ ARRAY_END(a)
+|
+- (&a[ARRAY_SIZE(a)])
++ ARRAY_END(a)
+|
+- (&a[ARRAY_SIZE(a) - b])
++ ARRAY_END(a) - b
+)
+
+//----------------------------------------------------------
+//  For org and report mode
+//----------------------------------------------------------
+
+@r depends on (org || report)@
+type T;
+T[] a;
+expression b;
+position p;
+@@
+(
+ (a@p + ARRAY_SIZE(a))
+|
+ (&a[0]@p + ARRAY_SIZE(a))
+|
+ (&a[ARRAY_SIZE(a)]@p)
+|
+ (&a[ARRAY_SIZE(a)@p - b])
+)
+
+@script:python depends on org@
+p << r.p;
+@@
+
+coccilib.org.print_todo(p[0], "WARNING should use ARRAY_END")
+
+@script:python depends on report@
+p << r.p;
+@@
+
+msg="WARNING: Use ARRAY_END"
+coccilib.report.print_report(p[0], msg)
+
-- 
2.53.0