[PATCH v1 0/3] Add ENDOF(), and use it to fix off-by-one bugs

Alejandro Colomar posted 3 patches 4 months, 2 weeks ago
include/linux/array_size.h | 6 ++++++
kernel/kcsan/kcsan_test.c  | 4 ++--
mm/kfence/kfence_test.c    | 4 ++--
mm/kmsan/kmsan_test.c      | 2 +-
4 files changed, 11 insertions(+), 5 deletions(-)
[PATCH v1 0/3] Add ENDOF(), and use it to fix off-by-one bugs
Posted by Alejandro Colomar 4 months, 2 weeks ago
Hi!

I've split some of the patches from the string patch set, as these are
obvious bug fixes that are trivial to accept.

I've reset the version number of the patch set to 1, to not conflict
with the version numbering of the string series.


Have a lovely day!
Alex

Alejandro Colomar (3):
  array_size.h: Add ENDOF()
  mm: Fix benign off-by-one bugs
  kernel: Fix off-by-one benign bugs

 include/linux/array_size.h | 6 ++++++
 kernel/kcsan/kcsan_test.c  | 4 ++--
 mm/kfence/kfence_test.c    | 4 ++--
 mm/kmsan/kmsan_test.c      | 2 +-
 4 files changed, 11 insertions(+), 5 deletions(-)

-- 
2.51.0
[PATCH v5 0/4] Add ARRAY_END(), and use it to fix off-by-one bugs
Posted by Alejandro Colomar 1 month, 4 weeks ago
Add ARRAY_END(), and use it to fix off-by-one bugs

ARRAY_END() is a macro to calculate a pointer to one past the last
element of an array argument.  This is a very common pointer, which is
used to iterate over all elements of an array:

        for (T *p = a; p < ARRAY_END(a); p++)
                ...

Of course, this pointer should never be dereferenced.  A pointer one
past the last element of an array should not be dereferenced; it's
perfectly fine to hold such a pointer --and a good thing to do--, but
the only thing it should be used for is comparing it with other pointers
derived from the same array.

Due to how special these pointers are, it would be good to use
consistent naming.  It's common to name such a pointer 'end' --in fact,
we have many such cases in the kernel--.  C++ even standardized this
name with std::end().  Let's try naming such pointers 'end', and try
also avoid using 'end' for pointers that are not the result of
ARRAY_END().

It has been incorrectly suggested that these pointers are dangerous, and
that they should never be used, suggesting to use something like

	#define ARRAY_LAST(a)  ((a) + ARRAY_SIZE(a) - 1)

	for (T *p = a; p <= ARRAY_LAST(a); p++)
		...

This is bogus, as it doesn't scale down to arrays of 0 elements.  In the
case of an array of 0 elements, ARRAY_LAST() would underflow the
pointer, which not only it can't be dereferenced, it can't even be held
(it produces Undefined Behavior).  That would be a footgun.  Such arrays
don't exist per the ISO C standard; however, GCC supports them as an
extension (with partial support, though; GCC has a few bugs which need
to be fixed).

This patch set fixes a few places where it was intended to use the array
end (that is, one past the last element), but accidentally a pointer to
the last element was used instead, thus wasting one byte.

It also replaces other places where the array end was correctly
calculated with ARRAY_SIZE(), by using the simpler ARRAY_END().

Also, there was one drivers/ file that already defined this macro.  We
remove that definition, to not conflict with this one.

Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: Alexander Potapenko <glider@google.com>
Cc: Dmitry Vyukov <dvyukov@google.com>
Cc: Jann Horn <jannh@google.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: "Maciej W. Rozycki" <macro@orcam.me.uk>
In-Reply-To: <cover.1758806023.git.alx@kernel.org>

---

Hi,

I've rebased v5 on top of v6.18.  The patches are identical (see
range-diff below).  I've tested them again, to make sure they're fine,
although I'm not sure I have enabled all configs to build all of this
code.  Please make sure everything builds, or let me know if (and how)
I should test anything else.

Some details of the .config I used for testing:
	$ cat .config | grep KUNIT_TEST | grep -v -e ^# -e CRYPTO
	CONFIG_KCSAN_KUNIT_TEST=y
	CONFIG_KFENCE_KUNIT_TEST=y

From v6.18:
	$ sudo dmesg | grep -inC2 kfence | sed 's/^...//' > tmp/kfence_master;

From this branch:
	$ sudo dmesg | grep -inC2 kfence | sed 's/^...//' > tmp/kfence_endof;

Results:
	$ diff -U0 \
		<(cat tmp/kfence_master \
			| sed 's/0x[0-9a-f]*/0x????/g' \
			| sed 's/[[:digit:]]\.[[:digit:]]\+/?.?/g' \
			| sed 's/#[[:digit:]]\+/#???/g' \
			| sed 's/././') \
		<(cat tmp/kfence_endof \
			| sed 's/0x[0-9a-f]*/0x????/g' \
			| sed 's/[[:digit:]]\.[[:digit:]]\+/?.?/g' \
			| sed 's/#[[:digit:]]\+/#???/g' \
			| sed 's/././');
	--- /dev/fd/63	2025-12-10 23:45:12.512438818 +0100
	+++ /dev/fd/62	2025-12-10 23:45:12.516438854 +0100
	@@ -17 +17 @@
	-.-[  68?.?] allocated by task 2516 on cpu 21 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2515 on cpu 8 at 68?.?s (?.?s ago):
	@@ -31 +31 @@
	-.-[  68?.?] allocated by task 2516 on cpu 0 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2515 on cpu 1 at 68?.?s (?.?s ago):
	@@ -45 +45 @@
	-.-[  68?.?] allocated by task 2518 on cpu 10 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2517 on cpu 4 at 68?.?s (?.?s ago):
	@@ -59 +59 @@
	-.-[  68?.?] allocated by task 2518 on cpu 2 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2517 on cpu 4 at 68?.?s (?.?s ago):
	@@ -73 +73 @@
	-.-[  68?.?] allocated by task 2520 on cpu 10 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2519 on cpu 14 at 68?.?s (?.?s ago):
	@@ -87 +87 @@
	-.-[  68?.?] allocated by task 2522 on cpu 10 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2521 on cpu 14 at 68?.?s (?.?s ago):
	@@ -101 +101 @@
	-.-[  68?.?] allocated by task 2524 on cpu 10 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2523 on cpu 14 at 68?.?s (?.?s ago):
	@@ -115 +115 @@
	-.-[  68?.?] allocated by task 2526 on cpu 15 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2525 on cpu 18 at 68?.?s (?.?s ago):
	@@ -129 +129 @@
	-.-[  68?.?] allocated by task 2532 on cpu 8 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2531 on cpu 15 at 68?.?s (?.?s ago):
	@@ -143 +143 @@
	-.-[  68?.?] allocated by task 2534 on cpu 8 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2533 on cpu 15 at 68?.?s (?.?s ago):
	@@ -157 +157 @@
	-.-[  68?.?] allocated by task 2536 on cpu 8 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2535 on cpu 15 at 68?.?s (?.?s ago):
	@@ -171 +171 @@
	-.-[  68?.?] allocated by task 2538 on cpu 14 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2537 on cpu 15 at 68?.?s (?.?s ago):
	@@ -185 +185 @@
	-.-[  68?.?] allocated by task 2540 on cpu 8 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2539 on cpu 3 at 68?.?s (?.?s ago):
	@@ -199 +199 @@
	-.-[  68?.?] allocated by task 2540 on cpu 8 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2539 on cpu 3 at 68?.?s (?.?s ago):
	@@ -213 +213 @@
	-.-[  68?.?] allocated by task 2542 on cpu 8 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2541 on cpu 15 at 68?.?s (?.?s ago):
	@@ -227 +227 @@
	-.-[  68?.?] allocated by task 2542 on cpu 1 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2541 on cpu 1 at 68?.?s (?.?s ago):
	@@ -241 +241 @@
	-.-[  68?.?] allocated by task 2552 on cpu 23 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2551 on cpu 11 at 68?.?s (?.?s ago):
	@@ -255 +255 @@
	-.-[  68?.?] allocated by task 2554 on cpu 1 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2553 on cpu 5 at 68?.?s (?.?s ago):
	@@ -275 +275 @@
	-.-[  68?.?] allocated by task 2564 on cpu 9 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2563 on cpu 13 at 68?.?s (?.?s ago):
	@@ -289 +289 @@
	-.-[  68?.?] allocated by task 2566 on cpu 9 at 68?.?s (?.?s ago):
	+.-[  68?.?] allocated by task 2565 on cpu 15 at 68?.?s (?.?s ago):


Have a lovely night!
Alex


Alejandro Colomar (4):
  array_size.h: Add ARRAY_END()
  mm: Fix benign off-by-one bugs
  kernel: Fix off-by-one benign bugs
  mm: Use ARRAY_END() instead of open-coding it

 drivers/block/floppy.c     | 2 --
 include/linux/array_size.h | 6 ++++++
 kernel/kcsan/kcsan_test.c  | 4 ++--
 mm/kfence/kfence_test.c    | 4 ++--
 mm/kmemleak.c              | 2 +-
 mm/kmsan/kmsan_test.c      | 2 +-
 mm/memcontrol-v1.c         | 4 ++--
 7 files changed, 14 insertions(+), 10 deletions(-)

Range-diff against v4:
1:  9f87d6208a6c = 1:  5973cfb67419 array_size.h: Add ARRAY_END()
2:  ac55d92551e4 = 2:  9c38dd009c17 mm: Fix benign off-by-one bugs
3:  ca8dec7f5bc9 = 3:  b4a945a4d40b kernel: Fix off-by-one benign bugs
4:  980c8fe8a6de = 4:  e7bde864b039 mm: Use ARRAY_END() instead of open-coding it
-- 
2.51.0
[PATCH v5 1/4] array_size.h: Add ARRAY_END()
Posted by Alejandro Colomar 1 month, 4 weeks ago
ARRAY_END() returns a pointer one past the end of the last element in
the array argument.  This pointer is useful for iterating over the
elements of an array:

	for (T *p = a, p < ARRAY_END(a); p++)
		...

Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: "Maciej W. Rozycki" <macro@orcam.me.uk>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
Message-ID: <37b1088dbd01a21d2f9d460aa510726119b3bcb0.1752193588.git.alx@kernel.org>
---
 drivers/block/floppy.c     | 2 --
 include/linux/array_size.h | 6 ++++++
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/drivers/block/floppy.c b/drivers/block/floppy.c
index 5336c3c5ca36..69661840397e 100644
--- a/drivers/block/floppy.c
+++ b/drivers/block/floppy.c
@@ -4802,8 +4802,6 @@ static void floppy_release_allocated_regions(int fdc, const struct io_region *p)
 	}
 }
 
-#define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))
-
 static int floppy_request_regions(int fdc)
 {
 	const struct io_region *p;
diff --git a/include/linux/array_size.h b/include/linux/array_size.h
index 06d7d83196ca..0c4fec98822e 100644
--- a/include/linux/array_size.h
+++ b/include/linux/array_size.h
@@ -10,4 +10,10 @@
  */
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
 
+/**
+ * ARRAY_END - get a pointer to one past the last element in array @arr
+ * @arr: array
+ */
+#define ARRAY_END(arr)  (&(arr)[ARRAY_SIZE(arr)])
+
 #endif  /* _LINUX_ARRAY_SIZE_H */
-- 
2.51.0
[PATCH v5 2/4] mm: Fix benign off-by-one bugs
Posted by Alejandro Colomar 1 month, 4 weeks ago
We were wasting a byte due to an off-by-one bug.  s[c]nprintf()
doesn't write more than $2 bytes including the null byte, so trying to
pass 'size-1' there is wasting one byte.

Acked-by: Marco Elver <elver@google.com>
Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Dmitry Vyukov <dvyukov@google.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Jann Horn <jannh@google.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
Message-ID: <515445ae064d4b8599899bf0d8b480dadd2ff843.1752182685.git.alx@kernel.org>
---
 mm/kfence/kfence_test.c | 4 ++--
 mm/kmsan/kmsan_test.c   | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/mm/kfence/kfence_test.c b/mm/kfence/kfence_test.c
index 00034e37bc9f..5725a367246d 100644
--- a/mm/kfence/kfence_test.c
+++ b/mm/kfence/kfence_test.c
@@ -110,7 +110,7 @@ static bool report_matches(const struct expect_report *r)
 
 	/* Title */
 	cur = expect[0];
-	end = &expect[0][sizeof(expect[0]) - 1];
+	end = ARRAY_END(expect[0]);
 	switch (r->type) {
 	case KFENCE_ERROR_OOB:
 		cur += scnprintf(cur, end - cur, "BUG: KFENCE: out-of-bounds %s",
@@ -140,7 +140,7 @@ static bool report_matches(const struct expect_report *r)
 
 	/* Access information */
 	cur = expect[1];
-	end = &expect[1][sizeof(expect[1]) - 1];
+	end = ARRAY_END(expect[1]);
 
 	switch (r->type) {
 	case KFENCE_ERROR_OOB:
diff --git a/mm/kmsan/kmsan_test.c b/mm/kmsan/kmsan_test.c
index 902ec48b1e3e..b5ad5dfb2c00 100644
--- a/mm/kmsan/kmsan_test.c
+++ b/mm/kmsan/kmsan_test.c
@@ -105,7 +105,7 @@ static bool report_matches(const struct expect_report *r)
 
 	/* Title */
 	cur = expected_header;
-	end = &expected_header[sizeof(expected_header) - 1];
+	end = ARRAY_END(expected_header);
 
 	cur += scnprintf(cur, end - cur, "BUG: KMSAN: %s", r->error_type);
 
-- 
2.51.0
[PATCH v5 3/4] kernel: Fix off-by-one benign bugs
Posted by Alejandro Colomar 1 month, 4 weeks ago
We were wasting a byte due to an off-by-one bug.  s[c]nprintf()
doesn't write more than $2 bytes including the null byte, so trying to
pass 'size-1' there is wasting one byte.

This is essentially the same as the previous commit, in a different
file.

Cc: Marco Elver <elver@google.com>
Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Dmitry Vyukov <dvyukov@google.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Jann Horn <jannh@google.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
---
 kernel/kcsan/kcsan_test.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/kernel/kcsan/kcsan_test.c b/kernel/kcsan/kcsan_test.c
index 219d22857c98..8ef8167be745 100644
--- a/kernel/kcsan/kcsan_test.c
+++ b/kernel/kcsan/kcsan_test.c
@@ -176,7 +176,7 @@ static bool __report_matches(const struct expect_report *r)
 
 	/* Title */
 	cur = expect[0];
-	end = &expect[0][sizeof(expect[0]) - 1];
+	end = ARRAY_END(expect[0]);
 	cur += scnprintf(cur, end - cur, "BUG: KCSAN: %s in ",
 			 is_assert ? "assert: race" : "data-race");
 	if (r->access[1].fn) {
@@ -200,7 +200,7 @@ static bool __report_matches(const struct expect_report *r)
 
 	/* Access 1 */
 	cur = expect[1];
-	end = &expect[1][sizeof(expect[1]) - 1];
+	end = ARRAY_END(expect[1]);
 	if (!r->access[1].fn)
 		cur += scnprintf(cur, end - cur, "race at unknown origin, with ");
 
-- 
2.51.0
[PATCH v5 4/4] mm: Use ARRAY_END() instead of open-coding it
Posted by Alejandro Colomar 1 month, 4 weeks ago
Cc: Kees Cook <kees@kernel.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
---
 mm/kmemleak.c      | 2 +-
 mm/memcontrol-v1.c | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/mm/kmemleak.c b/mm/kmemleak.c
index 1ac56ceb29b6..fe33f2edfe07 100644
--- a/mm/kmemleak.c
+++ b/mm/kmemleak.c
@@ -510,7 +510,7 @@ static void mem_pool_free(struct kmemleak_object *object)
 {
 	unsigned long flags;
 
-	if (object < mem_pool || object >= mem_pool + ARRAY_SIZE(mem_pool)) {
+	if (object < mem_pool || object >= ARRAY_END(mem_pool)) {
 		kmem_cache_free(object_cache, object);
 		return;
 	}
diff --git a/mm/memcontrol-v1.c b/mm/memcontrol-v1.c
index 6eed14bff742..b2f37bd939fa 100644
--- a/mm/memcontrol-v1.c
+++ b/mm/memcontrol-v1.c
@@ -1794,7 +1794,7 @@ static int memcg_numa_stat_show(struct seq_file *m, void *v)
 
 	mem_cgroup_flush_stats(memcg);
 
-	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
+	for (stat = stats; stat < ARRAY_END(stats); stat++) {
 		seq_printf(m, "%s=%lu", stat->name,
 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
 						   false));
@@ -1805,7 +1805,7 @@ static int memcg_numa_stat_show(struct seq_file *m, void *v)
 		seq_putc(m, '\n');
 	}
 
-	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
+	for (stat = stats; stat < ARRAY_END(stats); stat++) {
 
 		seq_printf(m, "hierarchical_%s=%lu", stat->name,
 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
-- 
2.51.0
Re: [PATCH v5 4/4] mm: Use ARRAY_END() instead of open-coding it
Posted by Kees Cook 1 month, 4 weeks ago

On December 11, 2025 7:46:49 AM GMT+09:00, Alejandro Colomar <alx@kernel.org> wrote:
>Cc: Kees Cook <kees@kernel.org>
>Cc: Linus Torvalds <torvalds@linux-foundation.org>
>Signed-off-by: Alejandro Colomar <alx@kernel.org>

Hm, this seems to be missing a commit log body?

Are there other open-coded instances that could be replaced? This seems like a great task for a coccinelle script.

-Kees

>---
> mm/kmemleak.c      | 2 +-
> mm/memcontrol-v1.c | 4 ++--
> 2 files changed, 3 insertions(+), 3 deletions(-)
>
>diff --git a/mm/kmemleak.c b/mm/kmemleak.c
>index 1ac56ceb29b6..fe33f2edfe07 100644
>--- a/mm/kmemleak.c
>+++ b/mm/kmemleak.c
>@@ -510,7 +510,7 @@ static void mem_pool_free(struct kmemleak_object *object)
> {
> 	unsigned long flags;
> 
>-	if (object < mem_pool || object >= mem_pool + ARRAY_SIZE(mem_pool)) {
>+	if (object < mem_pool || object >= ARRAY_END(mem_pool)) {
> 		kmem_cache_free(object_cache, object);
> 		return;
> 	}
>diff --git a/mm/memcontrol-v1.c b/mm/memcontrol-v1.c
>index 6eed14bff742..b2f37bd939fa 100644
>--- a/mm/memcontrol-v1.c
>+++ b/mm/memcontrol-v1.c
>@@ -1794,7 +1794,7 @@ static int memcg_numa_stat_show(struct seq_file *m, void *v)
> 
> 	mem_cgroup_flush_stats(memcg);
> 
>-	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
>+	for (stat = stats; stat < ARRAY_END(stats); stat++) {
> 		seq_printf(m, "%s=%lu", stat->name,
> 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
> 						   false));
>@@ -1805,7 +1805,7 @@ static int memcg_numa_stat_show(struct seq_file *m, void *v)
> 		seq_putc(m, '\n');
> 	}
> 
>-	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
>+	for (stat = stats; stat < ARRAY_END(stats); stat++) {
> 
> 		seq_printf(m, "hierarchical_%s=%lu", stat->name,
> 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,

-- 
Kees Cook
Re: [PATCH v5 4/4] mm: Use ARRAY_END() instead of open-coding it
Posted by Alejandro Colomar 1 month, 4 weeks ago
Hi Kees,

On Thu, Dec 11, 2025 at 08:18:56AM +0900, Kees Cook wrote:
> 
> 
> On December 11, 2025 7:46:49 AM GMT+09:00, Alejandro Colomar <alx@kernel.org> wrote:
> >Cc: Kees Cook <kees@kernel.org>
> >Cc: Linus Torvalds <torvalds@linux-foundation.org>
> >Signed-off-by: Alejandro Colomar <alx@kernel.org>
> 
> Hm, this seems to be missing a commit log body?

Actually, there's not much to it.  The patch uses ARRAY_END() where it
was being open-coded.  There aren't any bugs in this code, so it's
purely cosmetic (and of course, to prevent future issues, in case the
code is modified).  Maybe I could say precisely that.  What would you
say here?

> Are there other open-coded instances that could be replaced? This seems like a great task for a coccinelle script.

There are many, but I wanted to keep them out of this initial patch set,
to make it easy to apply.  When this one is applied, I could work on a
second round that replaces more of them with coccinelle.  This is just
for showing that this is beneficial, and to make sure that you ask for
more.  :)

Also, it's easier if there are few maintainers that would block an
initial patch set.  If restrict the patch set to a few files, I don't
have to deal with many of them.  Once I get used to this, I'll deal with
all of them.

> 
> -Kees

Have a lovely night!
Alex

> 
> >---
> > mm/kmemleak.c      | 2 +-
> > mm/memcontrol-v1.c | 4 ++--
> > 2 files changed, 3 insertions(+), 3 deletions(-)
> >
> >diff --git a/mm/kmemleak.c b/mm/kmemleak.c
> >index 1ac56ceb29b6..fe33f2edfe07 100644
> >--- a/mm/kmemleak.c
> >+++ b/mm/kmemleak.c
> >@@ -510,7 +510,7 @@ static void mem_pool_free(struct kmemleak_object *object)
> > {
> > 	unsigned long flags;
> > 
> >-	if (object < mem_pool || object >= mem_pool + ARRAY_SIZE(mem_pool)) {
> >+	if (object < mem_pool || object >= ARRAY_END(mem_pool)) {
> > 		kmem_cache_free(object_cache, object);
> > 		return;
> > 	}
> >diff --git a/mm/memcontrol-v1.c b/mm/memcontrol-v1.c
> >index 6eed14bff742..b2f37bd939fa 100644
> >--- a/mm/memcontrol-v1.c
> >+++ b/mm/memcontrol-v1.c
> >@@ -1794,7 +1794,7 @@ static int memcg_numa_stat_show(struct seq_file *m, void *v)
> > 
> > 	mem_cgroup_flush_stats(memcg);
> > 
> >-	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
> >+	for (stat = stats; stat < ARRAY_END(stats); stat++) {
> > 		seq_printf(m, "%s=%lu", stat->name,
> > 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
> > 						   false));
> >@@ -1805,7 +1805,7 @@ static int memcg_numa_stat_show(struct seq_file *m, void *v)
> > 		seq_putc(m, '\n');
> > 	}
> > 
> >-	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
> >+	for (stat = stats; stat < ARRAY_END(stats); stat++) {
> > 
> > 		seq_printf(m, "hierarchical_%s=%lu", stat->name,
> > 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
> 
> -- 
> Kees Cook

-- 
<https://www.alejandro-colomar.es>
Re: [PATCH v5 4/4] mm: Use ARRAY_END() instead of open-coding it
Posted by Kees Cook 1 month, 4 weeks ago
On Thu, Dec 11, 2025 at 01:21:59AM +0100, Alejandro Colomar wrote:
> Hi Kees,
> 
> On Thu, Dec 11, 2025 at 08:18:56AM +0900, Kees Cook wrote:
> > 
> > 
> > On December 11, 2025 7:46:49 AM GMT+09:00, Alejandro Colomar <alx@kernel.org> wrote:
> > >Cc: Kees Cook <kees@kernel.org>
> > >Cc: Linus Torvalds <torvalds@linux-foundation.org>
> > >Signed-off-by: Alejandro Colomar <alx@kernel.org>
> > 
> > Hm, this seems to be missing a commit log body?
> 
> Actually, there's not much to it.  The patch uses ARRAY_END() where it
> was being open-coded.  There aren't any bugs in this code, so it's
> purely cosmetic (and of course, to prevent future issues, in case the
> code is modified).  Maybe I could say precisely that.  What would you
> say here?

Yup, that would be perfect. A what/why, even a single sentence, is a
minimum for commit log bodies.

> > Are there other open-coded instances that could be replaced? This seems like a great task for a coccinelle script.
> 
> There are many, but I wanted to keep them out of this initial patch set,
> to make it easy to apply.  When this one is applied, I could work on a
> second round that replaces more of them with coccinelle.  This is just
> for showing that this is beneficial, and to make sure that you ask for
> more.  :)
> 
> Also, it's easier if there are few maintainers that would block an
> initial patch set.  If restrict the patch set to a few files, I don't
> have to deal with many of them.  Once I get used to this, I'll deal with
> all of them.

Sounds good!

-Kees

-- 
Kees Cook
Re: [PATCH v5 4/4] mm: Use ARRAY_END() instead of open-coding it
Posted by Alejandro Colomar 1 month, 2 weeks ago
Hi Kees, Andrew,

On Wed, Dec 10, 2025 at 05:37:13PM -0800, Kees Cook wrote:
> > > Are there other open-coded instances that could be replaced? This seems like a great task for a coccinelle script.
> > 
> > There are many, but I wanted to keep them out of this initial patch set,
> > to make it easy to apply.  When this one is applied, I could work on a
> > second round that replaces more of them with coccinelle.  This is just
> > for showing that this is beneficial, and to make sure that you ask for
> > more.  :)
> > 
> > Also, it's easier if there are few maintainers that would block an
> > initial patch set.  If restrict the patch set to a few files, I don't
> > have to deal with many of them.  Once I get used to this, I'll deal with
> > all of them.
> 
> Sounds good!

Now that the first patch set has been merged, I'm working on a second
round.

I've written a semantic patch:

	$ cat src/spatch/array_end.sp 
	@@
	expression a;
	@@

	- a + ARRAY_SIZE(a)
	+ ARRAY_END(a)

	@@
	expression a;
	@@

	- ARRAY_SIZE(a) + a
	+ ARRAY_END(a)

	@@
	expression a;
	@@

	- &a[0] + ARRAY_SIZE(a)
	+ ARRAY_END(a)

	@@
	expression a;
	@@

	- ARRAY_SIZE(a) + &a[0]
	+ ARRAY_END(a)

	@@
	expression a;
	@@

	- &a[ARRAY_SIZE(a)]
	+ ARRAY_END(a)

Apart from the cases covered by this semantic patch, I've found one case
which needs manual intervention (I don't know if a semantic patch can
handle this case):

	diff --git i/fs/proc/base.c w/fs/proc/base.c
	index c5114e9a0323..e99c8cad49c3 100644
	--- i/fs/proc/base.c
	+++ w/fs/proc/base.c
	@@ -2876,7 +2876,7 @@ static struct dentry *proc_##LSM##_attr_dir_lookup(struct inode *dir, \
	 { \
		return proc_pident_lookup(dir, dentry, \
					  LSM##_attr_dir_stuff, \
	-                                 LSM##_attr_dir_stuff + ARRAY_SIZE(LSM##_attr_dir_stuff)); \
	+                                 ARRAY_END(LSM##_attr_dir_stuff)); \
	 } \
	 \
	 static const struct inode_operations proc_##LSM##_attr_dir_inode_ops = { \

Anyway, I made sure there's only one of these.  There are no similar
cases in the kernel.

Here's a summary of what the semantic patch finds:

 arch/arm/kernel/hibernate.c                               | 2 +-
 arch/arm/kernel/reboot.c                                  | 2 +-
 arch/arm/mach-omap1/clock_data.c                          | 2 +-
 arch/arm64/kvm/sys_regs.c                                 | 2 +-
 arch/mips/fw/sni/sniprom.c                                | 2 +-
 arch/mips/include/asm/sgiarcs.h                           | 2 +-
 arch/riscv/purgatory/purgatory.c                          | 2 +-
 arch/s390/purgatory/purgatory.c                           | 2 +-
 arch/x86/kernel/cpu/hypervisor.c                          | 2 +-
 arch/x86/purgatory/purgatory.c                            | 2 +-
 block/bio.c                                               | 2 +-
 crypto/adiantum.c                                         | 2 +-
 drivers/base/regmap/regmap-spi-avmm.c                     | 2 +-
 drivers/cpufreq/sa1110-cpufreq.c                          | 2 +-
 drivers/firmware/efi/libstub/vsprintf.c                   | 2 +-
 drivers/gpu/drm/i915/selftests/i915_vma.c                 | 2 +-
 drivers/gpu/drm/xe/xe_guc_ads.c                           | 2 +-
 drivers/md/bcache/btree.c                                 | 6 +++---
 drivers/md/bcache/util.h                                  | 2 +-
 drivers/md/dm-raid.c                                      | 6 +++---
 drivers/mtd/devices/mtd_dataflash.c                       | 2 +-
 drivers/net/ethernet/marvell/mvneta.c                     | 2 +-
 drivers/net/ethernet/marvell/mvpp2/mvpp2_main.c           | 2 +-
 drivers/net/ethernet/sfc/falcon/nic.c                     | 8 ++++----
 drivers/net/ethernet/sfc/nic.c                            | 8 ++++----
 drivers/net/ethernet/sfc/siena/nic.c                      | 8 ++++----
 drivers/net/wireless/intel/iwlwifi/mei/net.c              | 4 ++--
 drivers/net/wireless/intel/iwlwifi/mvm/mac80211.c         | 3 +--
 drivers/tty/serial/msm_serial.c                           | 2 +-
 fs/erofs/zdata.c                                          | 4 ++--
 fs/proc/base.c                                            | 6 +++---
 fs/proc/namespaces.c                                      | 2 +-
 kernel/bpf/log.c                                          | 2 +-
 lib/crypto/tests/hash-test-template.h                     | 4 ++--
 mm/kmemleak.c                                             | 2 +-
 mm/memcontrol-v1.c                                        | 4 ++--
 net/ipv4/tcp_input.c                                      | 4 ++--
 tools/bpf/bpftool/tracelog.c                              | 2 +-
 tools/testing/selftests/bpf/prog_tests/select_reuseport.c | 4 ++--
 tools/testing/selftests/bpf/prog_tests/sk_lookup.c        | 8 ++++----
 tools/testing/selftests/bpf/prog_tests/sockmap_listen.c   | 8 ++++----
 tools/testing/selftests/bpf/prog_tests/sockmap_redir.c    | 8 ++++----
 42 files changed, 72 insertions(+), 73 deletions(-)

I applied the semantic patch as

            $ time find * -type f \
            | grep '\.[ch]$' \
            | xargs grep -l ARRAY_SIZE \
            | xargs grep -L '^#define ARRAY_END' \
            | xargs grep -l \
		-e '+ *ARRAY_SIZE' \
		-e 'ARRAY_SIZE(.*) *+' \
		-e '&.*ARRAY_SIZE' \
            | xargs spatch --sp-file ~/src/spatch/array_end.sp --in-place;

How should I proceed with this?  Should I send separate patches for each
subtree?  Or should I just send the semantic patch and let maintainers
run it?  Or should I senda big patch?

Also, I don't know if all of those files are able to use
include/linux/array_size.h.  Do tools/ need a separate definition?


Have a lovely day!
Alex

-- 
<https://www.alejandro-colomar.es>
Re: [PATCH v5 4/4] mm: Use ARRAY_END() instead of open-coding it
Posted by Kees Cook 1 month, 2 weeks ago
On Sun, Dec 21, 2025 at 03:07:14PM +0100, Alejandro Colomar wrote:
> Hi Kees, Andrew,
> 
> On Wed, Dec 10, 2025 at 05:37:13PM -0800, Kees Cook wrote:
> > > > Are there other open-coded instances that could be replaced? This seems like a great task for a coccinelle script.
> > > 
> > > There are many, but I wanted to keep them out of this initial patch set,
> > > to make it easy to apply.  When this one is applied, I could work on a
> > > second round that replaces more of them with coccinelle.  This is just
> > > for showing that this is beneficial, and to make sure that you ask for
> > > more.  :)
> > > 
> > > Also, it's easier if there are few maintainers that would block an
> > > initial patch set.  If restrict the patch set to a few files, I don't
> > > have to deal with many of them.  Once I get used to this, I'll deal with
> > > all of them.
> > 
> > Sounds good!
> 
> Now that the first patch set has been merged, I'm working on a second
> round.
> 
> I've written a semantic patch:
> 
> 	$ cat src/spatch/array_end.sp 
> 	@@
> 	expression a;
> 	@@
> 
> 	- a + ARRAY_SIZE(a)
> 	+ ARRAY_END(a)
> 
> 	@@
> 	expression a;
> 	@@
> 
> 	- ARRAY_SIZE(a) + a
> 	+ ARRAY_END(a)

I think you can add parens which will be silently removed but gain you
the commutative behavior:

@@
expression a;
@@

- (ARRAY_SIZE(a) + a)
+ ARRAY_END(a)

I *think* that'll cover "a + ARRAY_SIZE(a)" too.

Anyway, looks good! You could send it directly to Linus at the end of
the next rc1, and he may take it. If not, you'll want to split the patch
up and send to subsystems after ARRAY_END is in Linus's tree. I use this
tool to split a large single patch into per-subsystem patches:
https://github.com/kees/kernel-tools/blob/trunk/split-on-maintainer

-- 
Kees Cook
Re: [PATCH v5 4/4] mm: Use ARRAY_END() instead of open-coding it
Posted by Alejandro Colomar 1 month, 2 weeks ago
Hi Kees,

On Mon, Dec 22, 2025 at 03:21:21PM -0800, Kees Cook wrote:
> > Now that the first patch set has been merged, I'm working on a second
> > round.
> > 
> > I've written a semantic patch:
> > 
> > 	$ cat src/spatch/array_end.sp 
> > 	@@
> > 	expression a;
> > 	@@
> > 
> > 	- a + ARRAY_SIZE(a)
> > 	+ ARRAY_END(a)
> > 
> > 	@@
> > 	expression a;
> > 	@@
> > 
> > 	- ARRAY_SIZE(a) + a
> > 	+ ARRAY_END(a)
> 
> I think you can add parens which will be silently removed but gain you
> the commutative behavior:

Ahhh, thanks!  I was wondering how I could get commutative behavior.

> @@
> expression a;
> @@
> 
> - (ARRAY_SIZE(a) + a)
> + ARRAY_END(a)
> 
> I *think* that'll cover "a + ARRAY_SIZE(a)" too.

Yup, it works.  :)

> Anyway, looks good!

Thanks!

> You could send it directly to Linus at the end of
> the next rc1, and he may take it.

I'll send a draft before that, just for you to review the actual patch.

> If not, you'll want to split the patch
> up and send to subsystems after ARRAY_END is in Linus's tree. I use this
> tool to split a large single patch into per-subsystem patches:
> https://github.com/kees/kernel-tools/blob/trunk/split-on-maintainer

Okay.  I can do both, anyway.


Have a lovely night!
Alex

-- 
<https://www.alejandro-colomar.es>
[PATCH v6 0/4] Add ARRAY_END(), and use it to fix off-by-one bugs
Posted by Alejandro Colomar 1 month, 4 weeks ago
Add ARRAY_END(), and use it to fix off-by-one bugs

ARRAY_END() is a macro to calculate a pointer to one past the last
element of an array argument.  This is a very common pointer, which is
used to iterate over all elements of an array:

        for (T *p = a; p < ARRAY_END(a); p++)
                ...

Of course, this pointer should never be dereferenced.  A pointer one
past the last element of an array should not be dereferenced; it's
perfectly fine to hold such a pointer --and a good thing to do--, but
the only thing it should be used for is comparing it with other pointers
derived from the same array.

Due to how special these pointers are, it would be good to use
consistent naming.  It's common to name such a pointer 'end' --in fact,
we have many such cases in the kernel--.  C++ even standardized this
name with std::end().  Let's try naming such pointers 'end', and try
also avoid using 'end' for pointers that are not the result of
ARRAY_END().

It has been incorrectly suggested that these pointers are dangerous, and
that they should never be used, suggesting to use something like

	#define ARRAY_LAST(a)  ((a) + ARRAY_SIZE(a) - 1)

	for (T *p = a; p <= ARRAY_LAST(a); p++)
		...

This is bogus, as it doesn't scale down to arrays of 0 elements.  In the
case of an array of 0 elements, ARRAY_LAST() would underflow the
pointer, which not only it can't be dereferenced, it can't even be held
(it produces Undefined Behavior).  That would be a footgun.  Such arrays
don't exist per the ISO C standard; however, GCC supports them as an
extension (with partial support, though; GCC has a few bugs which need
to be fixed).

This patch set fixes a few places where it was intended to use the array
end (that is, one past the last element), but accidentally a pointer to
the last element was used instead, thus wasting one byte.

It also replaces other places where the array end was correctly
calculated with ARRAY_SIZE(), by using the simpler ARRAY_END().

Also, there was one drivers/ file that already defined this macro.  We
remove that definition, to not conflict with this one.

Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: Alexander Potapenko <glider@google.com>
Cc: Dmitry Vyukov <dvyukov@google.com>
Cc: Jann Horn <jannh@google.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: "Maciej W. Rozycki" <macro@orcam.me.uk>
In-Reply-To: <cover.1758806023.git.alx@kernel.org>

---

Hi,

v6 adds a commit log to the last commit.  Everything else is unchanged.
See range-diff below.


Have a lovely day!
Alex

Alejandro Colomar (4):
  array_size.h: Add ARRAY_END()
  mm: Fix benign off-by-one bugs
  kernel: Fix off-by-one benign bugs
  mm: Use ARRAY_END() instead of open-coding it

 drivers/block/floppy.c     | 2 --
 include/linux/array_size.h | 6 ++++++
 kernel/kcsan/kcsan_test.c  | 4 ++--
 mm/kfence/kfence_test.c    | 4 ++--
 mm/kmemleak.c              | 2 +-
 mm/kmsan/kmsan_test.c      | 2 +-
 mm/memcontrol-v1.c         | 4 ++--
 7 files changed, 14 insertions(+), 10 deletions(-)

Range-diff against v5:
1:  5973cfb67419 = 1:  5973cfb67419 array_size.h: Add ARRAY_END()
2:  9c38dd009c17 = 2:  9c38dd009c17 mm: Fix benign off-by-one bugs
3:  b4a945a4d40b = 3:  b4a945a4d40b kernel: Fix off-by-one benign bugs
4:  e7bde864b039 ! 4:  2335917d1238 mm: Use ARRAY_END() instead of open-coding it
    @@ Metadata
      ## Commit message ##
         mm: Use ARRAY_END() instead of open-coding it
     
    +    There aren't any bugs in this code; it's purely cosmetic.
    +
    +    By using ARRAY_END(), we prevent future issues, in case the code is
    +    modified; it has less moving parts.  Also, it should be more readable
    +    (and perhaps more importantly, greppable), as there are several ways of
    +    writing an expression that gets the end of an array, which are unified
    +    by this API name.
    +
         Cc: Kees Cook <kees@kernel.org>
         Cc: Linus Torvalds <torvalds@linux-foundation.org>
         Signed-off-by: Alejandro Colomar <alx@kernel.org>
-- 
2.51.0
[PATCH v6 1/4] array_size.h: Add ARRAY_END()
Posted by Alejandro Colomar 1 month, 4 weeks ago
ARRAY_END() returns a pointer one past the end of the last element in
the array argument.  This pointer is useful for iterating over the
elements of an array:

	for (T *p = a, p < ARRAY_END(a); p++)
		...

Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: "Maciej W. Rozycki" <macro@orcam.me.uk>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
Message-ID: <37b1088dbd01a21d2f9d460aa510726119b3bcb0.1752193588.git.alx@kernel.org>
---
 drivers/block/floppy.c     | 2 --
 include/linux/array_size.h | 6 ++++++
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/drivers/block/floppy.c b/drivers/block/floppy.c
index 5336c3c5ca36..69661840397e 100644
--- a/drivers/block/floppy.c
+++ b/drivers/block/floppy.c
@@ -4802,8 +4802,6 @@ static void floppy_release_allocated_regions(int fdc, const struct io_region *p)
 	}
 }
 
-#define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))
-
 static int floppy_request_regions(int fdc)
 {
 	const struct io_region *p;
diff --git a/include/linux/array_size.h b/include/linux/array_size.h
index 06d7d83196ca..0c4fec98822e 100644
--- a/include/linux/array_size.h
+++ b/include/linux/array_size.h
@@ -10,4 +10,10 @@
  */
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
 
+/**
+ * ARRAY_END - get a pointer to one past the last element in array @arr
+ * @arr: array
+ */
+#define ARRAY_END(arr)  (&(arr)[ARRAY_SIZE(arr)])
+
 #endif  /* _LINUX_ARRAY_SIZE_H */
-- 
2.51.0
[PATCH v6 2/4] mm: Fix benign off-by-one bugs
Posted by Alejandro Colomar 1 month, 4 weeks ago
We were wasting a byte due to an off-by-one bug.  s[c]nprintf()
doesn't write more than $2 bytes including the null byte, so trying to
pass 'size-1' there is wasting one byte.

Acked-by: Marco Elver <elver@google.com>
Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Dmitry Vyukov <dvyukov@google.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Jann Horn <jannh@google.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
Message-ID: <515445ae064d4b8599899bf0d8b480dadd2ff843.1752182685.git.alx@kernel.org>
---
 mm/kfence/kfence_test.c | 4 ++--
 mm/kmsan/kmsan_test.c   | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/mm/kfence/kfence_test.c b/mm/kfence/kfence_test.c
index 00034e37bc9f..5725a367246d 100644
--- a/mm/kfence/kfence_test.c
+++ b/mm/kfence/kfence_test.c
@@ -110,7 +110,7 @@ static bool report_matches(const struct expect_report *r)
 
 	/* Title */
 	cur = expect[0];
-	end = &expect[0][sizeof(expect[0]) - 1];
+	end = ARRAY_END(expect[0]);
 	switch (r->type) {
 	case KFENCE_ERROR_OOB:
 		cur += scnprintf(cur, end - cur, "BUG: KFENCE: out-of-bounds %s",
@@ -140,7 +140,7 @@ static bool report_matches(const struct expect_report *r)
 
 	/* Access information */
 	cur = expect[1];
-	end = &expect[1][sizeof(expect[1]) - 1];
+	end = ARRAY_END(expect[1]);
 
 	switch (r->type) {
 	case KFENCE_ERROR_OOB:
diff --git a/mm/kmsan/kmsan_test.c b/mm/kmsan/kmsan_test.c
index 902ec48b1e3e..b5ad5dfb2c00 100644
--- a/mm/kmsan/kmsan_test.c
+++ b/mm/kmsan/kmsan_test.c
@@ -105,7 +105,7 @@ static bool report_matches(const struct expect_report *r)
 
 	/* Title */
 	cur = expected_header;
-	end = &expected_header[sizeof(expected_header) - 1];
+	end = ARRAY_END(expected_header);
 
 	cur += scnprintf(cur, end - cur, "BUG: KMSAN: %s", r->error_type);
 
-- 
2.51.0
[PATCH v6 3/4] kernel: Fix off-by-one benign bugs
Posted by Alejandro Colomar 1 month, 4 weeks ago
We were wasting a byte due to an off-by-one bug.  s[c]nprintf()
doesn't write more than $2 bytes including the null byte, so trying to
pass 'size-1' there is wasting one byte.

This is essentially the same as the previous commit, in a different
file.

Cc: Marco Elver <elver@google.com>
Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Dmitry Vyukov <dvyukov@google.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Jann Horn <jannh@google.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
---
 kernel/kcsan/kcsan_test.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/kernel/kcsan/kcsan_test.c b/kernel/kcsan/kcsan_test.c
index 219d22857c98..8ef8167be745 100644
--- a/kernel/kcsan/kcsan_test.c
+++ b/kernel/kcsan/kcsan_test.c
@@ -176,7 +176,7 @@ static bool __report_matches(const struct expect_report *r)
 
 	/* Title */
 	cur = expect[0];
-	end = &expect[0][sizeof(expect[0]) - 1];
+	end = ARRAY_END(expect[0]);
 	cur += scnprintf(cur, end - cur, "BUG: KCSAN: %s in ",
 			 is_assert ? "assert: race" : "data-race");
 	if (r->access[1].fn) {
@@ -200,7 +200,7 @@ static bool __report_matches(const struct expect_report *r)
 
 	/* Access 1 */
 	cur = expect[1];
-	end = &expect[1][sizeof(expect[1]) - 1];
+	end = ARRAY_END(expect[1]);
 	if (!r->access[1].fn)
 		cur += scnprintf(cur, end - cur, "race at unknown origin, with ");
 
-- 
2.51.0
[PATCH v6 4/4] mm: Use ARRAY_END() instead of open-coding it
Posted by Alejandro Colomar 1 month, 4 weeks ago
There aren't any bugs in this code; it's purely cosmetic.

By using ARRAY_END(), we prevent future issues, in case the code is
modified; it has less moving parts.  Also, it should be more readable
(and perhaps more importantly, greppable), as there are several ways of
writing an expression that gets the end of an array, which are unified
by this API name.

Cc: Kees Cook <kees@kernel.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
---
 mm/kmemleak.c      | 2 +-
 mm/memcontrol-v1.c | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/mm/kmemleak.c b/mm/kmemleak.c
index 1ac56ceb29b6..fe33f2edfe07 100644
--- a/mm/kmemleak.c
+++ b/mm/kmemleak.c
@@ -510,7 +510,7 @@ static void mem_pool_free(struct kmemleak_object *object)
 {
 	unsigned long flags;
 
-	if (object < mem_pool || object >= mem_pool + ARRAY_SIZE(mem_pool)) {
+	if (object < mem_pool || object >= ARRAY_END(mem_pool)) {
 		kmem_cache_free(object_cache, object);
 		return;
 	}
diff --git a/mm/memcontrol-v1.c b/mm/memcontrol-v1.c
index 6eed14bff742..b2f37bd939fa 100644
--- a/mm/memcontrol-v1.c
+++ b/mm/memcontrol-v1.c
@@ -1794,7 +1794,7 @@ static int memcg_numa_stat_show(struct seq_file *m, void *v)
 
 	mem_cgroup_flush_stats(memcg);
 
-	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
+	for (stat = stats; stat < ARRAY_END(stats); stat++) {
 		seq_printf(m, "%s=%lu", stat->name,
 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
 						   false));
@@ -1805,7 +1805,7 @@ static int memcg_numa_stat_show(struct seq_file *m, void *v)
 		seq_putc(m, '\n');
 	}
 
-	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
+	for (stat = stats; stat < ARRAY_END(stats); stat++) {
 
 		seq_printf(m, "hierarchical_%s=%lu", stat->name,
 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
-- 
2.51.0
[PATCH v4 0/4] Add ARRAY_END(), and use it to fix off-by-one bugs
Posted by Alejandro Colomar 2 months, 4 weeks ago
ARRAY_END() is a macro to calculate a pointer to one past the last
element of an array argument.  This is a very common pointer, which is
used to iterate over all elements of an array:

        for (T *p = a; p < ARRAY_END(a); p++)
                ...

Of course, this pointer should never be dereferenced.  A pointer one
past the last element of an array should not be dereferenced; it's
perfectly fine to hold such a pointer --and a good thing to do--, but
the only thing it should be used for is comparing it with other pointers
derived from the same array.

Due to how special these pointers are, it would be good to use
consistent naming.  It's common to name such a pointer 'end' --in fact,
we have many such cases in the kernel--.  C++ even standardized this
name with std::end().  Let's try naming such pointers 'end', and try
also avoid using 'end' for pointers that are not the result of
ARRAY_END().

It has been incorrectly suggested that these pointers are dangerous, and
that they should never be used, suggesting to use something like

	#define ARRAY_LAST(a)  ((a) + ARRAY_SIZE(a) - 1)

	for (T *p = a; p <= ARRAY_LAST(a); p++)
		...

This is bogus, as it doesn't scale down to arrays of 0 elements.  In the
case of an array of 0 elements, ARRAY_LAST() would underflow the
pointer, which not only it can't be dereferenced, it can't even be held
(it produces Undefined Behavior).  That would be a footgun.  Such arrays
don't exist per the ISO C standard; however, GCC supports them as an
extension (with partial support, though; GCC has a few bugs which need
to be fixed).

This patch set fixes a few places where it was intended to use the array
end (that is, one past the last element), but accidentally a pointer to
the last element was used instead, thus wasting one byte.

It also replaces other places where the array end was correctly
calculated with ARRAY_SIZE(), by using the simpler ARRAY_END().

Also, there was one drivers/ file that already defined this macro.  We
remove that definition, to not conflict with this one.

---

Hi,

v4:

-  Use 'arr' as the macro parameter, for consistency with ARRAY_SIZE().
   [Reported-by: "Maciej W. Rozycki" <macro@orcam.me.uk>]


Have a lovely night!
Alex


Alejandro Colomar (4):
  array_size.h: Add ARRAY_END()
  mm: Fix benign off-by-one bugs
  kernel: Fix off-by-one benign bugs
  mm: Use ARRAY_END() instead of open-coding it

 drivers/block/floppy.c     | 2 --
 include/linux/array_size.h | 6 ++++++
 kernel/kcsan/kcsan_test.c  | 4 ++--
 mm/kfence/kfence_test.c    | 4 ++--
 mm/kmemleak.c              | 2 +-
 mm/kmsan/kmsan_test.c      | 2 +-
 mm/memcontrol-v1.c         | 4 ++--
 7 files changed, 14 insertions(+), 10 deletions(-)

Range-diff against v3:
1:  2cb4ddff93b3 ! 1:  9f87d6208a6c array_size.h: Add ARRAY_END()
    @@ Commit message
         Cc: Michal Hocko <mhocko@suse.com>
         Cc: Linus Torvalds <torvalds@linux-foundation.org>
         Cc: Al Viro <viro@zeniv.linux.org.uk>
    +    Cc: "Maciej W. Rozycki" <macro@orcam.me.uk>
         Signed-off-by: Alejandro Colomar <alx@kernel.org>
         Message-ID: <37b1088dbd01a21d2f9d460aa510726119b3bcb0.1752193588.git.alx@kernel.org>
     
    @@ include/linux/array_size.h
      #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
      
     +/**
    -+ * ARRAY_END - get a pointer to one past the last element in array @a
    -+ * @a: array
    ++ * ARRAY_END - get a pointer to one past the last element in array @arr
    ++ * @arr: array
     + */
    -+#define ARRAY_END(a)  (&(a)[ARRAY_SIZE(a)])
    ++#define ARRAY_END(arr)  (&(arr)[ARRAY_SIZE(arr)])
     +
      #endif  /* _LINUX_ARRAY_SIZE_H */
2:  831155f02bec = 2:  ac55d92551e4 mm: Fix benign off-by-one bugs
3:  d8128f0c8b9f = 3:  ca8dec7f5bc9 kernel: Fix off-by-one benign bugs
4:  9646a1d194a5 = 4:  980c8fe8a6de mm: Use ARRAY_END() instead of open-coding it

base-commit: 6146a0f1dfae5d37442a9ddcba012add260bceb0
-- 
2.51.0
Re: [PATCH v1 0/3] Add ENDOF(), and use it to fix off-by-one bugs
Posted by Andrew Morton 4 months, 2 weeks ago
On Thu, 25 Sep 2025 15:20:28 +0200 Alejandro Colomar <alx@kernel.org> wrote:

> I've split some of the patches from the string patch set, as these are
> obvious bug fixes that are trivial to accept.
> 
> I've reset the version number of the patch set to 1, to not conflict
> with the version numbering of the string series.

fyi, there's nothing here which is usable in an introductory [0/N]
cover letter.

Documentation/process/submitting-patches.rst should explain the
conventions here, but it is presently silent.

The [0/N] is an overview of the whole patchset - why it was created,
what value it provides to our users and perhaps to kernel developers
themselves.  It discusses alternative approaches, possible drawbacks,
prior work, all that stuff.  And it provides a high-level description
of the proposed implementation,

Potentially lots of words, and it's quite important.  In the case of
your patchset, it's one short sentence (sorry).

The words you did include are short-term development things, unsuitable
for inclusion in the permanent kernel record.  Such material *is*
important and useful, but should be added after the "^---$" separator,
to tell everyone that this material isn't for permanent inclusion.

Patchset seems reasonable, I guess.  But I'm not loving "ENDOF".  End
of what - is that like __etext?  "ARRAY_END" matches "ARRAY_SIZE" quite
nicely, no?  And it much better describes what the thing does.
Re: [PATCH v1 0/3] Add ENDOF(), and use it to fix off-by-one bugs
Posted by Alejandro Colomar 4 months, 2 weeks ago
Hi Andrew,

On Thu, Sep 25, 2025 at 01:48:14PM -0700, Andrew Morton wrote:
> On Thu, 25 Sep 2025 15:20:28 +0200 Alejandro Colomar <alx@kernel.org> wrote:
> 
> > I've split some of the patches from the string patch set, as these are
> > obvious bug fixes that are trivial to accept.
> > 
> > I've reset the version number of the patch set to 1, to not conflict
> > with the version numbering of the string series.
> 
> fyi, there's nothing here which is usable in an introductory [0/N]
> cover letter.
> 
> Documentation/process/submitting-patches.rst should explain the
> conventions here, but it is presently silent.
> 
> The [0/N] is an overview of the whole patchset - why it was created,
> what value it provides to our users and perhaps to kernel developers
> themselves.  It discusses alternative approaches, possible drawbacks,
> prior work, all that stuff.  And it provides a high-level description
> of the proposed implementation,
> 
> Potentially lots of words, and it's quite important.  In the case of
> your patchset, it's one short sentence (sorry).
> 
> The words you did include are short-term development things, unsuitable
> for inclusion in the permanent kernel record.

Thanks!  I'll keep it in mind.  BTW, I didn't know the cover letters
were stored anywhere.  By 'the permanent kernel record' you mean that
cover letters are stored in a merge commit message or something like
that?  It would be useful to have that documented.  I didn't know.

I can send a v2 with a better cover letter, if you want.

>  Such material *is*
> important and useful, but should be added after the "^---$" separator,
> to tell everyone that this material isn't for permanent inclusion.

Okay, I'll keep that in mind.

> Patchset seems reasonable, I guess.  But I'm not loving "ENDOF".  End
> of what - is that like __etext?  "ARRAY_END" matches "ARRAY_SIZE" quite
> nicely, no?  And it much better describes what the thing does.

ENDOF() matches countof(), which is the standard name for ARRAY_SIZE().

<https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3550.pdf#subsubsection.0.6.5.4.5>
<https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3550.pdf#section.0.7.21>

I've never loved ARRAY_SIZE, as I have a macro sizeof_array() which
gives me the size of an array in bytes (and guarantees that the input is
an array).  The name nelementsof() --or the shorter NELEMS()-- seems
more appropriate, IMO, since what it returns is "the number of elements
of an array".  However, the C Committee hated it so much that I couldn't
get them to standardize it.  I'm content enough with countof().


Have a lovely day!
Alex

-- 
<https://www.alejandro-colomar.es>
Use port 80 (that is, <...:80/>).
Re: [PATCH v1 0/3] Add ENDOF(), and use it to fix off-by-one bugs
Posted by Kees Cook 4 months, 2 weeks ago
On Thu, Sep 25, 2025 at 01:48:14PM -0700, Andrew Morton wrote:
> Patchset seems reasonable, I guess.  But I'm not loving "ENDOF".  End
> of what - is that like __etext?  "ARRAY_END" matches "ARRAY_SIZE" quite
> nicely, no?  And it much better describes what the thing does.

And it's really ARRAY_BEYOND. ;) I don't really like having APIs that
require holding pointers that are actively invalid, either.

u8 array[10];
u8 *first = array; // valid address
u8 *last = &array[ARRAY_SIZE(array) - 1]; // valid address

for (u8 *c = first; c <= last; c++)
  putc(*c);
// c would now be invalid but has left scope so it cannot be used

-- 
Kees Cook
[PATCH v2 0/4] Add ARRAY_END(), and use it to fix off-by-one bugs
Posted by Alejandro Colomar 3 months ago
ARRAY_END() is a macro to calculate a pointer to one past the last
element of an array argument.  This is a very common pointer, which is
used to iterate over all elements of an array:

	for (T *p = a; p < ARRAY_END(a); p++)
		...

Of course, this pointer should never be dereferenced.  A pointer one
past the last element of an array should not be dereferenced; it's
perfectly fine to hold such a pointer --and a good thing to do--, but
the only thing it should be used for is comparing it with other pointers
derived from the same array.

Due to how special these pointers are, it would be good to use
consistent naming.  It's common to name such a pointer 'end' --in fact,
we have many such cases in the kernel--.  C++ even standardized this
name with std::end().  Let's try naming such pointers 'end', and try
also avoid using 'end' for pointers that are not the result of
ARRAY_END().

It has been incorrectly suggested that these pointers are dangerous, and
that they should never be used, suggesting to use

	a + ARRAY_SIZE(a) - 1

instead, with <= instead of <.  This is bogus, as it doesn't scale down
to arrays of 0 elements.  Such arrays don't exist per the C standard;
however, GCC supports them as an extension (with partial support,
though; GCC has a few bugs which need to be fixed).

---

Hi!

This v2 has the following changes compared to v1:

-  Rebase on top of v6.18-rc4.
-  Rename ENDOF() => ARRAY_END(), for consistency with ARRAY_SIZE().
   [Reported-by: Andrew Morton]
-  Add a useful cover letter.  [Reported-by: Andrew Morton]
-  Add a fourth commit, replacing all cases of a+ARRAY_SIZE(a) in mm/ by
   ARRAY_END(a).

See the range-diff below.


Have a lovely day!
Alex


Alejandro Colomar (4):
  array_size.h: Add ARRAY_END()
  mm: Fix benign off-by-one bugs
  kernel: Fix off-by-one benign bugs
  mm: Use ARRAY_END() instead of open-coding it

 include/linux/array_size.h | 6 ++++++
 kernel/kcsan/kcsan_test.c  | 4 ++--
 mm/kfence/kfence_test.c    | 4 ++--
 mm/kmemleak.c              | 2 +-
 mm/kmsan/kmsan_test.c      | 2 +-
 mm/memcontrol-v1.c         | 4 ++--
 6 files changed, 14 insertions(+), 8 deletions(-)

Range-diff against v1:
1:  90ab26558138 ! 1:  35255c1ceb54 array_size.h: Add ENDOF()
    @@ Metadata
     Author: Alejandro Colomar <alx@kernel.org>
     
      ## Commit message ##
    -    array_size.h: Add ENDOF()
    +    array_size.h: Add ARRAY_END()
     
    -    This macro is useful to calculate the second argument to
    -    sprintf_trunc_end(), avoiding off-by-one bugs.
    +    ARRAY_END() returns a pointer one past the end of the last element in
    +    the array argument.  This pointer is useful for iterating over the
    +    elements of an array:
    +
    +            for (T *p = a, p < ENDOF(a); p++)
    +                    ...
     
         Cc: Kees Cook <kees@kernel.org>
         Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
    @@ include/linux/array_size.h
      #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
      
     +/**
    -+ * ENDOF - get a pointer to one past the last element in array @a
    ++ * ARRAY_END - get a pointer to one past the last element in array @a
     + * @a: array
     + */
    -+#define ENDOF(a)  (a + ARRAY_SIZE(a))
    ++#define ARRAY_END(a)  (a + ARRAY_SIZE(a))
     +
      #endif  /* _LINUX_ARRAY_SIZE_H */
2:  ec7553aa4747 ! 2:  acd8bcbb05d3 mm: Fix benign off-by-one bugs
    @@ mm/kfence/kfence_test.c: static bool report_matches(const struct expect_report *
        /* Title */
        cur = expect[0];
     -  end = &expect[0][sizeof(expect[0]) - 1];
    -+  end = ENDOF(expect[0]);
    ++  end = ARRAY_END(expect[0]);
        switch (r->type) {
        case KFENCE_ERROR_OOB:
                cur += scnprintf(cur, end - cur, "BUG: KFENCE: out-of-bounds %s",
    @@ mm/kfence/kfence_test.c: static bool report_matches(const struct expect_report *
        /* Access information */
        cur = expect[1];
     -  end = &expect[1][sizeof(expect[1]) - 1];
    -+  end = ENDOF(expect[1]);
    ++  end = ARRAY_END(expect[1]);
      
        switch (r->type) {
        case KFENCE_ERROR_OOB:
    @@ mm/kmsan/kmsan_test.c: static bool report_matches(const struct expect_report *r)
        /* Title */
        cur = expected_header;
     -  end = &expected_header[sizeof(expected_header) - 1];
    -+  end = ENDOF(expected_header);
    ++  end = ARRAY_END(expected_header);
      
        cur += scnprintf(cur, end - cur, "BUG: KMSAN: %s", r->error_type);
      
3:  c94e42e85c13 ! 3:  781cce547eb2 kernel: Fix off-by-one benign bugs
    @@ kernel/kcsan/kcsan_test.c: static bool __report_matches(const struct expect_repo
        /* Title */
        cur = expect[0];
     -  end = &expect[0][sizeof(expect[0]) - 1];
    -+  end = ENDOF(expect[0]);
    ++  end = ARRAY_END(expect[0]);
        cur += scnprintf(cur, end - cur, "BUG: KCSAN: %s in ",
                         is_assert ? "assert: race" : "data-race");
        if (r->access[1].fn) {
    @@ kernel/kcsan/kcsan_test.c: static bool __report_matches(const struct expect_repo
        /* Access 1 */
        cur = expect[1];
     -  end = &expect[1][sizeof(expect[1]) - 1];
    -+  end = ENDOF(expect[1]);
    ++  end = ARRAY_END(expect[1]);
        if (!r->access[1].fn)
                cur += scnprintf(cur, end - cur, "race at unknown origin, with ");
      
-:  ------------ > 4:  094878542457 mm: Use ARRAY_END() instead of open-coding it

base-commit: 6146a0f1dfae5d37442a9ddcba012add260bceb0
-- 
2.51.0
[PATCH v2 1/4] array_size.h: Add ARRAY_END()
Posted by Alejandro Colomar 3 months ago
ARRAY_END() returns a pointer one past the end of the last element in
the array argument.  This pointer is useful for iterating over the
elements of an array:

	for (T *p = a, p < ENDOF(a); p++)
		...

Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
Message-ID: <37b1088dbd01a21d2f9d460aa510726119b3bcb0.1752193588.git.alx@kernel.org>
---
 include/linux/array_size.h | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/include/linux/array_size.h b/include/linux/array_size.h
index 06d7d83196ca..62382973078e 100644
--- a/include/linux/array_size.h
+++ b/include/linux/array_size.h
@@ -10,4 +10,10 @@
  */
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
 
+/**
+ * ARRAY_END - get a pointer to one past the last element in array @a
+ * @a: array
+ */
+#define ARRAY_END(a)  (a + ARRAY_SIZE(a))
+
 #endif  /* _LINUX_ARRAY_SIZE_H */
-- 
2.51.0
Re: [PATCH v2 1/4] array_size.h: Add ARRAY_END()
Posted by kernel test robot 3 months ago
Hi Alejandro,

kernel test robot noticed the following build warnings:

[auto build test WARNING on 6146a0f1dfae5d37442a9ddcba012add260bceb0]

url:    https://github.com/intel-lab-lkp/linux/commits/Alejandro-Colomar/array_size-h-Add-ARRAY_END/20251109-062234
base:   6146a0f1dfae5d37442a9ddcba012add260bceb0
patch link:    https://lore.kernel.org/r/35255c1ceb54518779a45351dcd79a3c1910818a.1762637046.git.alx%40kernel.org
patch subject: [PATCH v2 1/4] array_size.h: Add ARRAY_END()
config: x86_64-randconfig-001-20251109 (https://download.01.org/0day-ci/archive/20251109/202511092053.40sHnHlA-lkp@intel.com/config)
compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251109/202511092053.40sHnHlA-lkp@intel.com/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of
the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <lkp@intel.com>
| Closes: https://lore.kernel.org/oe-kbuild-all/202511092053.40sHnHlA-lkp@intel.com/

All warnings (new ones prefixed by >>):

>> drivers/block/floppy.c:4805:9: warning: 'ARRAY_END' macro redefined [-Wmacro-redefined]
    4805 | #define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))
         |         ^
   include/linux/array_size.h:17:9: note: previous definition is here
      17 | #define ARRAY_END(a)  (a + ARRAY_SIZE(a))
         |         ^
   1 warning generated.


vim +/ARRAY_END +4805 drivers/block/floppy.c

5a74db06cc8d36 Philippe De Muyter 2009-02-18  4804  
5a74db06cc8d36 Philippe De Muyter 2009-02-18 @4805  #define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))
5a74db06cc8d36 Philippe De Muyter 2009-02-18  4806  

-- 
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
Re: [PATCH v2 1/4] array_size.h: Add ARRAY_END()
Posted by kernel test robot 3 months ago
Hi Alejandro,

kernel test robot noticed the following build warnings:

[auto build test WARNING on 6146a0f1dfae5d37442a9ddcba012add260bceb0]

url:    https://github.com/intel-lab-lkp/linux/commits/Alejandro-Colomar/array_size-h-Add-ARRAY_END/20251109-062234
base:   6146a0f1dfae5d37442a9ddcba012add260bceb0
patch link:    https://lore.kernel.org/r/35255c1ceb54518779a45351dcd79a3c1910818a.1762637046.git.alx%40kernel.org
patch subject: [PATCH v2 1/4] array_size.h: Add ARRAY_END()
config: alpha-defconfig (https://download.01.org/0day-ci/archive/20251109/202511091804.XUQA4dOK-lkp@intel.com/config)
compiler: alpha-linux-gcc (GCC) 15.1.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251109/202511091804.XUQA4dOK-lkp@intel.com/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of
the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <lkp@intel.com>
| Closes: https://lore.kernel.org/oe-kbuild-all/202511091804.XUQA4dOK-lkp@intel.com/

All warnings (new ones prefixed by >>):

>> drivers/block/floppy.c:4805:9: warning: 'ARRAY_END' redefined
    4805 | #define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))
         |         ^~~~~~~~~
   In file included from include/linux/string.h:6,
                    from include/linux/bitmap.h:13,
                    from include/linux/nodemask.h:91,
                    from include/linux/numa.h:6,
                    from include/linux/async.h:13,
                    from drivers/block/floppy.c:166:
   include/linux/array_size.h:17:9: note: this is the location of the previous definition
      17 | #define ARRAY_END(a)  (a + ARRAY_SIZE(a))
         |         ^~~~~~~~~


vim +/ARRAY_END +4805 drivers/block/floppy.c

5a74db06cc8d36 Philippe De Muyter 2009-02-18  4804  
5a74db06cc8d36 Philippe De Muyter 2009-02-18 @4805  #define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))
5a74db06cc8d36 Philippe De Muyter 2009-02-18  4806  

-- 
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
Re: [PATCH v2 1/4] array_size.h: Add ARRAY_END()
Posted by Alejandro Colomar 3 months ago
Hi,

On Sun, Nov 09, 2025 at 06:43:46PM +0800, kernel test robot wrote:
> Hi Alejandro,
> 
> kernel test robot noticed the following build warnings:
> 
> [auto build test WARNING on 6146a0f1dfae5d37442a9ddcba012add260bceb0]
> 
> url:    https://github.com/intel-lab-lkp/linux/commits/Alejandro-Colomar/array_size-h-Add-ARRAY_END/20251109-062234
> base:   6146a0f1dfae5d37442a9ddcba012add260bceb0
> patch link:    https://lore.kernel.org/r/35255c1ceb54518779a45351dcd79a3c1910818a.1762637046.git.alx%40kernel.org
> patch subject: [PATCH v2 1/4] array_size.h: Add ARRAY_END()
> config: alpha-defconfig (https://download.01.org/0day-ci/archive/20251109/202511091804.XUQA4dOK-lkp@intel.com/config)
> compiler: alpha-linux-gcc (GCC) 15.1.0
> reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251109/202511091804.XUQA4dOK-lkp@intel.com/reproduce)
> 
> If you fix the issue in a separate patch/commit (i.e. not just a new version of
> the same patch/commit), kindly add following tags
> | Reported-by: kernel test robot <lkp@intel.com>
> | Closes: https://lore.kernel.org/oe-kbuild-all/202511091804.XUQA4dOK-lkp@intel.com/
> 
> All warnings (new ones prefixed by >>):
> 
> >> drivers/block/floppy.c:4805:9: warning: 'ARRAY_END' redefined
>     4805 | #define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))
>          |         ^~~~~~~~~

Hmmm, nice!  There's already an ARRAY_END() there.  I'll remove that
definition.

BTW, this reminds me that I forgot to parenthesize 'a' in my
implementation.  Do you have any preference on the implementation?
I could use either of

	(&((a)[ARRAY_SIZE(a)]))

	((a) + ARRAY_SIZE(a))


Have a lovely day!
Alex

>    In file included from include/linux/string.h:6,
>                     from include/linux/bitmap.h:13,
>                     from include/linux/nodemask.h:91,
>                     from include/linux/numa.h:6,
>                     from include/linux/async.h:13,
>                     from drivers/block/floppy.c:166:
>    include/linux/array_size.h:17:9: note: this is the location of the previous definition
>       17 | #define ARRAY_END(a)  (a + ARRAY_SIZE(a))
>          |         ^~~~~~~~~
> 
> 
> vim +/ARRAY_END +4805 drivers/block/floppy.c
> 
> 5a74db06cc8d36 Philippe De Muyter 2009-02-18  4804  
> 5a74db06cc8d36 Philippe De Muyter 2009-02-18 @4805  #define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))
> 5a74db06cc8d36 Philippe De Muyter 2009-02-18  4806  
> 
> -- 
> 0-DAY CI Kernel Test Service
> https://github.com/intel/lkp-tests/wiki

-- 
<https://www.alejandro-colomar.es>
Use port 80 (that is, <...:80/>).
[PATCH v2 2/4] mm: Fix benign off-by-one bugs
Posted by Alejandro Colomar 3 months ago
We were wasting a byte due to an off-by-one bug.  s[c]nprintf()
doesn't write more than $2 bytes including the null byte, so trying to
pass 'size-1' there is wasting one byte.

Acked-by: Marco Elver <elver@google.com>
Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Dmitry Vyukov <dvyukov@google.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Jann Horn <jannh@google.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
Message-ID: <515445ae064d4b8599899bf0d8b480dadd2ff843.1752182685.git.alx@kernel.org>
---
 mm/kfence/kfence_test.c | 4 ++--
 mm/kmsan/kmsan_test.c   | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/mm/kfence/kfence_test.c b/mm/kfence/kfence_test.c
index 00034e37bc9f..5725a367246d 100644
--- a/mm/kfence/kfence_test.c
+++ b/mm/kfence/kfence_test.c
@@ -110,7 +110,7 @@ static bool report_matches(const struct expect_report *r)
 
 	/* Title */
 	cur = expect[0];
-	end = &expect[0][sizeof(expect[0]) - 1];
+	end = ARRAY_END(expect[0]);
 	switch (r->type) {
 	case KFENCE_ERROR_OOB:
 		cur += scnprintf(cur, end - cur, "BUG: KFENCE: out-of-bounds %s",
@@ -140,7 +140,7 @@ static bool report_matches(const struct expect_report *r)
 
 	/* Access information */
 	cur = expect[1];
-	end = &expect[1][sizeof(expect[1]) - 1];
+	end = ARRAY_END(expect[1]);
 
 	switch (r->type) {
 	case KFENCE_ERROR_OOB:
diff --git a/mm/kmsan/kmsan_test.c b/mm/kmsan/kmsan_test.c
index 902ec48b1e3e..b5ad5dfb2c00 100644
--- a/mm/kmsan/kmsan_test.c
+++ b/mm/kmsan/kmsan_test.c
@@ -105,7 +105,7 @@ static bool report_matches(const struct expect_report *r)
 
 	/* Title */
 	cur = expected_header;
-	end = &expected_header[sizeof(expected_header) - 1];
+	end = ARRAY_END(expected_header);
 
 	cur += scnprintf(cur, end - cur, "BUG: KMSAN: %s", r->error_type);
 
-- 
2.51.0
[PATCH v2 3/4] kernel: Fix off-by-one benign bugs
Posted by Alejandro Colomar 3 months ago
We were wasting a byte due to an off-by-one bug.  s[c]nprintf()
doesn't write more than $2 bytes including the null byte, so trying to
pass 'size-1' there is wasting one byte.

This is essentially the same as the previous commit, in a different
file.

Cc: Marco Elver <elver@google.com>
Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Dmitry Vyukov <dvyukov@google.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Jann Horn <jannh@google.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
---
 kernel/kcsan/kcsan_test.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/kernel/kcsan/kcsan_test.c b/kernel/kcsan/kcsan_test.c
index 219d22857c98..8ef8167be745 100644
--- a/kernel/kcsan/kcsan_test.c
+++ b/kernel/kcsan/kcsan_test.c
@@ -176,7 +176,7 @@ static bool __report_matches(const struct expect_report *r)
 
 	/* Title */
 	cur = expect[0];
-	end = &expect[0][sizeof(expect[0]) - 1];
+	end = ARRAY_END(expect[0]);
 	cur += scnprintf(cur, end - cur, "BUG: KCSAN: %s in ",
 			 is_assert ? "assert: race" : "data-race");
 	if (r->access[1].fn) {
@@ -200,7 +200,7 @@ static bool __report_matches(const struct expect_report *r)
 
 	/* Access 1 */
 	cur = expect[1];
-	end = &expect[1][sizeof(expect[1]) - 1];
+	end = ARRAY_END(expect[1]);
 	if (!r->access[1].fn)
 		cur += scnprintf(cur, end - cur, "race at unknown origin, with ");
 
-- 
2.51.0
[PATCH v2 4/4] mm: Use ARRAY_END() instead of open-coding it
Posted by Alejandro Colomar 3 months ago
Cc: Kees Cook <kees@kernel.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
---
 mm/kmemleak.c      | 2 +-
 mm/memcontrol-v1.c | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/mm/kmemleak.c b/mm/kmemleak.c
index 1ac56ceb29b6..fe33f2edfe07 100644
--- a/mm/kmemleak.c
+++ b/mm/kmemleak.c
@@ -510,7 +510,7 @@ static void mem_pool_free(struct kmemleak_object *object)
 {
 	unsigned long flags;
 
-	if (object < mem_pool || object >= mem_pool + ARRAY_SIZE(mem_pool)) {
+	if (object < mem_pool || object >= ARRAY_END(mem_pool)) {
 		kmem_cache_free(object_cache, object);
 		return;
 	}
diff --git a/mm/memcontrol-v1.c b/mm/memcontrol-v1.c
index 6eed14bff742..b2f37bd939fa 100644
--- a/mm/memcontrol-v1.c
+++ b/mm/memcontrol-v1.c
@@ -1794,7 +1794,7 @@ static int memcg_numa_stat_show(struct seq_file *m, void *v)
 
 	mem_cgroup_flush_stats(memcg);
 
-	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
+	for (stat = stats; stat < ARRAY_END(stats); stat++) {
 		seq_printf(m, "%s=%lu", stat->name,
 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
 						   false));
@@ -1805,7 +1805,7 @@ static int memcg_numa_stat_show(struct seq_file *m, void *v)
 		seq_putc(m, '\n');
 	}
 
-	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
+	for (stat = stats; stat < ARRAY_END(stats); stat++) {
 
 		seq_printf(m, "hierarchical_%s=%lu", stat->name,
 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
-- 
2.51.0
[PATCH v3 0/4] Add ARRAY_END(), and use it to fix off-by-one bugs
Posted by Alejandro Colomar 2 months, 4 weeks ago
ARRAY_END() is a macro to calculate a pointer to one past the last
element of an array argument.  This is a very common pointer, which is
used to iterate over all elements of an array:

        for (T *p = a; p < ARRAY_END(a); p++)
                ...

Of course, this pointer should never be dereferenced.  A pointer one
past the last element of an array should not be dereferenced; it's
perfectly fine to hold such a pointer --and a good thing to do--, but
the only thing it should be used for is comparing it with other pointers
derived from the same array.

Due to how special these pointers are, it would be good to use
consistent naming.  It's common to name such a pointer 'end' --in fact,
we have many such cases in the kernel--.  C++ even standardized this
name with std::end().  Let's try naming such pointers 'end', and try
also avoid using 'end' for pointers that are not the result of
ARRAY_END().

It has been incorrectly suggested that these pointers are dangerous, and
that they should never be used, suggesting to use something like

	#define ARRAY_LAST(a)  ((a) + ARRAY_SIZE(a) - 1)

	for (T *p = a; p <= ARRAY_LAST(a); p++)
		...

This is bogus, as it doesn't scale down to arrays of 0 elements.  In the
case of an array of 0 elements, ARRAY_LAST() would underflow the
pointer, which not only it can't be dereferenced, it can't even be held.
That would be a footgun.  Such arrays don't exist per the C standard;
however, GCC supports them as an extension (with partial support,
though; GCC has a few bugs which need to be fixed).

This patch set fixes a few places where it was intended to use the array
end (that is, one past the last element), but accidentally a pointer to
the last element was used instead, thus wasting one byte.

It also replaces other places where the array end was correctly
calculated with ARRAY_SIZE(), by using the simpler ARRAY_END().

Also, there was one drivers/ file that already defined this macro.  We
remove that definition, to not conflict with this one.

---

Hi!

Changes in v3:

-  Fix commit message.
-  Remove old definition from "drivers/block/floppy.c".
   [Reported-by: kernel test robot <lkp@intel.com>]
-  Use definition of ARRAY_END() with array notation.  There's work in
   the C committee to make array notation slightly safer than pointer
   arithmetic.


Have a lovely night!
Alex


Alejandro Colomar (4):
  array_size.h: Add ARRAY_END()
  mm: Fix benign off-by-one bugs
  kernel: Fix off-by-one benign bugs
  mm: Use ARRAY_END() instead of open-coding it

 drivers/block/floppy.c     | 2 --
 include/linux/array_size.h | 6 ++++++
 kernel/kcsan/kcsan_test.c  | 4 ++--
 mm/kfence/kfence_test.c    | 4 ++--
 mm/kmemleak.c              | 2 +-
 mm/kmsan/kmsan_test.c      | 2 +-
 mm/memcontrol-v1.c         | 4 ++--
 7 files changed, 14 insertions(+), 10 deletions(-)

Range-diff against v2:
1:  35255c1ceb54 ! 1:  2cb4ddff93b3 array_size.h: Add ARRAY_END()
    @@ Commit message
         the array argument.  This pointer is useful for iterating over the
         elements of an array:
     
    -            for (T *p = a, p < ENDOF(a); p++)
    +            for (T *p = a, p < ARRAY_END(a); p++)
                         ...
     
         Cc: Kees Cook <kees@kernel.org>
    @@ Commit message
         Signed-off-by: Alejandro Colomar <alx@kernel.org>
         Message-ID: <37b1088dbd01a21d2f9d460aa510726119b3bcb0.1752193588.git.alx@kernel.org>
     
    + ## drivers/block/floppy.c ##
    +@@ drivers/block/floppy.c: static void floppy_release_allocated_regions(int fdc, const struct io_region *p)
    + 	}
    + }
    + 
    +-#define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))
    +-
    + static int floppy_request_regions(int fdc)
    + {
    + 	const struct io_region *p;
    +
      ## include/linux/array_size.h ##
     @@
       */
    @@ include/linux/array_size.h
     + * ARRAY_END - get a pointer to one past the last element in array @a
     + * @a: array
     + */
    -+#define ARRAY_END(a)  (a + ARRAY_SIZE(a))
    ++#define ARRAY_END(a)  (&(a)[ARRAY_SIZE(a)])
     +
      #endif  /* _LINUX_ARRAY_SIZE_H */
2:  acd8bcbb05d3 = 2:  831155f02bec mm: Fix benign off-by-one bugs
3:  781cce547eb2 = 3:  d8128f0c8b9f kernel: Fix off-by-one benign bugs
4:  094878542457 = 4:  9646a1d194a5 mm: Use ARRAY_END() instead of open-coding it
-- 
2.51.0
[PATCH v3 1/4] array_size.h: Add ARRAY_END()
Posted by Alejandro Colomar 2 months, 4 weeks ago
ARRAY_END() returns a pointer one past the end of the last element in
the array argument.  This pointer is useful for iterating over the
elements of an array:

	for (T *p = a, p < ARRAY_END(a); p++)
		...

Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
Message-ID: <37b1088dbd01a21d2f9d460aa510726119b3bcb0.1752193588.git.alx@kernel.org>
---
 drivers/block/floppy.c     | 2 --
 include/linux/array_size.h | 6 ++++++
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/drivers/block/floppy.c b/drivers/block/floppy.c
index 5336c3c5ca36..69661840397e 100644
--- a/drivers/block/floppy.c
+++ b/drivers/block/floppy.c
@@ -4802,8 +4802,6 @@ static void floppy_release_allocated_regions(int fdc, const struct io_region *p)
 	}
 }
 
-#define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))
-
 static int floppy_request_regions(int fdc)
 {
 	const struct io_region *p;
diff --git a/include/linux/array_size.h b/include/linux/array_size.h
index 06d7d83196ca..b5775b8f13de 100644
--- a/include/linux/array_size.h
+++ b/include/linux/array_size.h
@@ -10,4 +10,10 @@
  */
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
 
+/**
+ * ARRAY_END - get a pointer to one past the last element in array @a
+ * @a: array
+ */
+#define ARRAY_END(a)  (&(a)[ARRAY_SIZE(a)])
+
 #endif  /* _LINUX_ARRAY_SIZE_H */
-- 
2.51.0
Re: [PATCH v3 1/4] array_size.h: Add ARRAY_END()
Posted by Maciej W. Rozycki 2 months, 4 weeks ago
On Sun, 9 Nov 2025, Alejandro Colomar wrote:

> diff --git a/include/linux/array_size.h b/include/linux/array_size.h
> index 06d7d83196ca..b5775b8f13de 100644
> --- a/include/linux/array_size.h
> +++ b/include/linux/array_size.h
> @@ -10,4 +10,10 @@
>   */
>  #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
>  
> +/**
> + * ARRAY_END - get a pointer to one past the last element in array @a
> + * @a: array
> + */
> +#define ARRAY_END(a)  (&(a)[ARRAY_SIZE(a)])

 Why `a' rather than `arr' as with the other macro?

  Maciej
Re: [PATCH v3 1/4] array_size.h: Add ARRAY_END()
Posted by Alejandro Colomar 2 months, 4 weeks ago
Hi Maciej,

On Sun, Nov 09, 2025 at 07:05:40PM +0000, Maciej W. Rozycki wrote:
> On Sun, 9 Nov 2025, Alejandro Colomar wrote:
> 
> > diff --git a/include/linux/array_size.h b/include/linux/array_size.h
> > index 06d7d83196ca..b5775b8f13de 100644
> > --- a/include/linux/array_size.h
> > +++ b/include/linux/array_size.h
> > @@ -10,4 +10,10 @@
> >   */
> >  #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
> >  
> > +/**
> > + * ARRAY_END - get a pointer to one past the last element in array @a
> > + * @a: array
> > + */
> > +#define ARRAY_END(a)  (&(a)[ARRAY_SIZE(a)])
> 
>  Why `a' rather than `arr' as with the other macro?

It's simpler, and equally informative.  I wish ARRAY_SIZE() would have
also used 'a'.  On the other hand, consistency is important.  I'll make
it 'arr'.

Thanks!


Have a lovely night!
Alex


> 
>   Maciej

-- 
<https://www.alejandro-colomar.es>
Use port 80 (that is, <...:80/>).
[PATCH v3 2/4] mm: Fix benign off-by-one bugs
Posted by Alejandro Colomar 2 months, 4 weeks ago
We were wasting a byte due to an off-by-one bug.  s[c]nprintf()
doesn't write more than $2 bytes including the null byte, so trying to
pass 'size-1' there is wasting one byte.

Acked-by: Marco Elver <elver@google.com>
Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Dmitry Vyukov <dvyukov@google.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Jann Horn <jannh@google.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
Message-ID: <515445ae064d4b8599899bf0d8b480dadd2ff843.1752182685.git.alx@kernel.org>
---
 mm/kfence/kfence_test.c | 4 ++--
 mm/kmsan/kmsan_test.c   | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/mm/kfence/kfence_test.c b/mm/kfence/kfence_test.c
index 00034e37bc9f..5725a367246d 100644
--- a/mm/kfence/kfence_test.c
+++ b/mm/kfence/kfence_test.c
@@ -110,7 +110,7 @@ static bool report_matches(const struct expect_report *r)
 
 	/* Title */
 	cur = expect[0];
-	end = &expect[0][sizeof(expect[0]) - 1];
+	end = ARRAY_END(expect[0]);
 	switch (r->type) {
 	case KFENCE_ERROR_OOB:
 		cur += scnprintf(cur, end - cur, "BUG: KFENCE: out-of-bounds %s",
@@ -140,7 +140,7 @@ static bool report_matches(const struct expect_report *r)
 
 	/* Access information */
 	cur = expect[1];
-	end = &expect[1][sizeof(expect[1]) - 1];
+	end = ARRAY_END(expect[1]);
 
 	switch (r->type) {
 	case KFENCE_ERROR_OOB:
diff --git a/mm/kmsan/kmsan_test.c b/mm/kmsan/kmsan_test.c
index 902ec48b1e3e..b5ad5dfb2c00 100644
--- a/mm/kmsan/kmsan_test.c
+++ b/mm/kmsan/kmsan_test.c
@@ -105,7 +105,7 @@ static bool report_matches(const struct expect_report *r)
 
 	/* Title */
 	cur = expected_header;
-	end = &expected_header[sizeof(expected_header) - 1];
+	end = ARRAY_END(expected_header);
 
 	cur += scnprintf(cur, end - cur, "BUG: KMSAN: %s", r->error_type);
 
-- 
2.51.0
[PATCH v3 3/4] kernel: Fix off-by-one benign bugs
Posted by Alejandro Colomar 2 months, 4 weeks ago
We were wasting a byte due to an off-by-one bug.  s[c]nprintf()
doesn't write more than $2 bytes including the null byte, so trying to
pass 'size-1' there is wasting one byte.

This is essentially the same as the previous commit, in a different
file.

Cc: Marco Elver <elver@google.com>
Cc: Kees Cook <kees@kernel.org>
Cc: Christopher Bazley <chris.bazley.wg14@gmail.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Dmitry Vyukov <dvyukov@google.com>
Cc: Alexander Potapenko <glider@google.com>
Cc: Jann Horn <jannh@google.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Rasmus Villemoes <linux@rasmusvillemoes.dk>
Cc: Marco Elver <elver@google.com>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
---
 kernel/kcsan/kcsan_test.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/kernel/kcsan/kcsan_test.c b/kernel/kcsan/kcsan_test.c
index 219d22857c98..8ef8167be745 100644
--- a/kernel/kcsan/kcsan_test.c
+++ b/kernel/kcsan/kcsan_test.c
@@ -176,7 +176,7 @@ static bool __report_matches(const struct expect_report *r)
 
 	/* Title */
 	cur = expect[0];
-	end = &expect[0][sizeof(expect[0]) - 1];
+	end = ARRAY_END(expect[0]);
 	cur += scnprintf(cur, end - cur, "BUG: KCSAN: %s in ",
 			 is_assert ? "assert: race" : "data-race");
 	if (r->access[1].fn) {
@@ -200,7 +200,7 @@ static bool __report_matches(const struct expect_report *r)
 
 	/* Access 1 */
 	cur = expect[1];
-	end = &expect[1][sizeof(expect[1]) - 1];
+	end = ARRAY_END(expect[1]);
 	if (!r->access[1].fn)
 		cur += scnprintf(cur, end - cur, "race at unknown origin, with ");
 
-- 
2.51.0
[PATCH v3 4/4] mm: Use ARRAY_END() instead of open-coding it
Posted by Alejandro Colomar 2 months, 4 weeks ago
Cc: Kees Cook <kees@kernel.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
---
 mm/kmemleak.c      | 2 +-
 mm/memcontrol-v1.c | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/mm/kmemleak.c b/mm/kmemleak.c
index 1ac56ceb29b6..fe33f2edfe07 100644
--- a/mm/kmemleak.c
+++ b/mm/kmemleak.c
@@ -510,7 +510,7 @@ static void mem_pool_free(struct kmemleak_object *object)
 {
 	unsigned long flags;
 
-	if (object < mem_pool || object >= mem_pool + ARRAY_SIZE(mem_pool)) {
+	if (object < mem_pool || object >= ARRAY_END(mem_pool)) {
 		kmem_cache_free(object_cache, object);
 		return;
 	}
diff --git a/mm/memcontrol-v1.c b/mm/memcontrol-v1.c
index 6eed14bff742..b2f37bd939fa 100644
--- a/mm/memcontrol-v1.c
+++ b/mm/memcontrol-v1.c
@@ -1794,7 +1794,7 @@ static int memcg_numa_stat_show(struct seq_file *m, void *v)
 
 	mem_cgroup_flush_stats(memcg);
 
-	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
+	for (stat = stats; stat < ARRAY_END(stats); stat++) {
 		seq_printf(m, "%s=%lu", stat->name,
 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
 						   false));
@@ -1805,7 +1805,7 @@ static int memcg_numa_stat_show(struct seq_file *m, void *v)
 		seq_putc(m, '\n');
 	}
 
-	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
+	for (stat = stats; stat < ARRAY_END(stats); stat++) {
 
 		seq_printf(m, "hierarchical_%s=%lu", stat->name,
 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
-- 
2.51.0