Skip to contentSkip to conversation

Add ENDOF(), and use it to fix off-by-one bugs

PATCH Superseded Alejandro Colomar 7 participants 54 messages Sep 25, 2025 – Feb 8 1 message not in the archive

Subsystems (8)
lore
Share & tools
lore
#0 lore raw

cover Add ENDOF(), and use it to fix off-by-one bugs

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(-)
Signature · 1 line
2.51.0
#1 lore raw

PATCH 1/3 array_size.h: Add ENDOF()

This macro is useful to calculate the second argument to sprintf_trunc_end(), avoiding off-by-one bugs.

Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Al Viro <[email protected]>

Message-ID: <37b1088dbd01a21d2f9d460aa510726119b3bcb0.1752193588.git.alx@kernel.org>

---
 include/linux/array_size.h | 6 ++++++
 1 file changed, 6 insertions(+)
include/linux/array_size.h +6 -0
index 06d7d83196ca..781bdb70d939 100644
@@ -10,4 +10,10 @@
  */
 #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
+ * @a: array
+ */
+#define ENDOF(a)  (a + ARRAY_SIZE(a))
+
 #endif  /* _LINUX_ARRAY_SIZE_H */
Signature · 1 line
2.51.0
#2 lore raw

Re: [PATCH v1 1/3] array_size.h: Add ENDOF()

Quoted 2 lines · Alejandro Colomar

This macro is useful to calculate the second argument to sprintf_trunc_end(), avoiding off-by-one bugs.

D'oh! This commit message needs updating. Please amend with:

This macro is useful to calculate the end of an array (that is, a pointer to one after its last element), avoiding off-by-one bugs.

Cheers,
Alex

Quoted 32 lines
Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Al Viro <[email protected]>

Message-ID: <37b1088dbd01a21d2f9d460aa510726119b3bcb0.1752193588.git.alx@kernel.org>

---
 include/linux/array_size.h | 6 ++++++
 1 file changed, 6 insertions(+)
include/linux/array_size.h +6 -0
index 06d7d83196ca..781bdb70d939 100644
@@ -10,4 +10,10 @@
  */
 #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
+ * @a: array
+ */
+#define ENDOF(a)  (a + ARRAY_SIZE(a))
+
 #endif  /* _LINUX_ARRAY_SIZE_H */
Signature · 1 line
2.51.0
Signature · 2 lines
<https://www.alejandro-colomar.es>
Use port 80 (that is, <...:80/>).
#3 lore raw

PATCH 2/3 mm: Fix benign off-by-one bugs

In reply to Alejandro Colomar

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.

Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Jann Horn <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Al Viro <[email protected]>

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(-)
mm/kfence/kfence_test.c +2 -2
index 00034e37bc9f..1ad81e6b27ea 100644
@@ -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 = ENDOF(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 = ENDOF(expect[1]);
 
 	switch (r->type) {
 	case KFENCE_ERROR_OOB:
mm/kmsan/kmsan_test.c +1 -1
index c6c5b2bbede0..758405d8b7a7 100644
@@ -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 = ENDOF(expected_header);
 
 	cur += scnprintf(cur, end - cur, "BUG: KMSAN: %s", r->error_type);
 
Signature · 1 line
2.51.0
#4 lore raw

Re: [PATCH v1 2/3] mm: Fix benign off-by-one bugs

kernel test robot noticed the following build errors:

Hi Alejandro,

kernel test robot noticed the following build errors:

[auto build test ERROR on akpm-mm/mm-everything]
[also build test ERROR on kees/for-next/pstore kees/for-next/kspp linus/master linux/master v6.18-rc5 next-20251110] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Alejandro-Colomar/array_size-h-Add-ARRAY_END/20251110-075203
base:   https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-everything
patch link:    https://lore.kernel.org/r/87445e701574058b142e036c3b8a0f505086ab64.1758806023.git.alx%40kernel.org
patch subject: [PATCH v1 2/3] mm: Fix benign off-by-one bugs
config: loongarch-randconfig-001-20251110 (https://download.01.org/0day-ci/archive/20251111/[email protected]/config)
compiler: clang version 22.0.0git (https://github.com/llvm/llvm-project 996639d6ebb86ff15a8c99b67f1c2e2117636ae7)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251111/[email protected]/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 <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

>> mm/kfence/kfence_test.c:113:8: error: call to undeclared function 'ENDOF'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
     113 |         end = ENDOF(expect[0]);
         |               ^
>> mm/kfence/kfence_test.c:113:6: error: incompatible integer to pointer conversion assigning to 'const char *' from 'int' [-Wint-conversion]
     113 |         end = ENDOF(expect[0]);
         |             ^ ~~~~~~~~~~~~~~~~
   mm/kfence/kfence_test.c:143:6: error: incompatible integer to pointer conversion assigning to 'const char *' from 'int' [-Wint-conversion]
     143 |         end = ENDOF(expect[1]);
         |             ^ ~~~~~~~~~~~~~~~~

3 errors generated.

vim +/ENDOF +113 mm/kfence/kfence_test.c

    94	
    95	/* Check observed report matches information in @r. */
    96	static bool report_matches(const struct expect_report *r)
    97	{
    98		unsigned long addr = (unsigned long)r->addr;
    99		bool ret = false;
   100		unsigned long flags;
   101		typeof(observed.lines) expect;
   102		const char *end;
   103		char *cur;
   104	
   105		/* Doubled-checked locking. */
   106		if (!report_available())
   107			return false;
   108	
   109		/* Generate expected report contents. */
   110	
   111		/* Title */
   112		cur = expect[0];
 > 113		end = ENDOF(expect[0]);

114 switch (r->type) {
115 case KFENCE_ERROR_OOB:
116 cur += scnprintf(cur, end - cur, "BUG: KFENCE: out-of-bounds %s",
117 get_access_type(r));
118 break;
119 case KFENCE_ERROR_UAF:
120 cur += scnprintf(cur, end - cur, "BUG: KFENCE: use-after-free %s",
121 get_access_type(r));
122 break;
123 case KFENCE_ERROR_CORRUPTION:
124 cur += scnprintf(cur, end - cur, "BUG: KFENCE: memory corruption");
125 break;
126 case KFENCE_ERROR_INVALID:
127 cur += scnprintf(cur, end - cur, "BUG: KFENCE: invalid %s",
128 get_access_type(r));
129 break;
130 case KFENCE_ERROR_INVALID_FREE:
131 cur += scnprintf(cur, end - cur, "BUG: KFENCE: invalid free");
132 break;
133 }
134
135 scnprintf(cur, end - cur, " in %pS", r->fn);
136 /* The exact offset won't match, remove it; also strip module name. */
137 cur = strchr(expect[0], '+');
138 if (cur)
139 *cur = '\0';
140
141 /* Access information */
142 cur = expect[1];
143 end = ENDOF(expect[1]);
144
145 switch (r->type) {
146 case KFENCE_ERROR_OOB:
147 cur += scnprintf(cur, end - cur, "Out-of-bounds %s at", get_access_type(r));
148 addr = arch_kfence_test_address(addr);
149 break;
150 case KFENCE_ERROR_UAF:
151 cur += scnprintf(cur, end - cur, "Use-after-free %s at", get_access_type(r));
152 addr = arch_kfence_test_address(addr);
153 break;
154 case KFENCE_ERROR_CORRUPTION:
155 cur += scnprintf(cur, end - cur, "Corrupted memory at");
156 break;
157 case KFENCE_ERROR_INVALID:
158 cur += scnprintf(cur, end - cur, "Invalid %s at", get_access_type(r));
159 addr = arch_kfence_test_address(addr);
160 break;
161 case KFENCE_ERROR_INVALID_FREE:
162 cur += scnprintf(cur, end - cur, "Invalid free of");
163 break;
164 }
165
166 cur += scnprintf(cur, end - cur, " 0x%p", (void *)addr);
167
168 spin_lock_irqsave(&observed.lock, flags);
169 if (!report_available())
170 goto out; /* A new report is being captured. */
171
172 /* Finally match expected output to what we actually observed. */
173 ret = strstr(observed.lines[0], expect[0]) && strstr(observed.lines[1], expect[1]);
174 out:
175 spin_unlock_irqrestore(&observed.lock, flags);
176 return ret;
177 }
178

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#5 lore raw

Re: [PATCH v1 2/3] mm: Fix benign off-by-one bugs

Hi,

Quoted 1 line · kernel test robot

kernel test robot noticed the following build errors:

[...]

Quoted 10 lines
Quoted 1 line
Quoted 1 line

mm/kfence/kfence_test.c:113:8: error: call to undeclared function 'ENDOF'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]

     113 |         end = ENDOF(expect[0]);
         |               ^
Quoted 1 line
Quoted 1 line

mm/kfence/kfence_test.c:113:6: error: incompatible integer to pointer conversion assigning to 'const char *' from 'int' [-Wint-conversion]

     113 |         end = ENDOF(expect[0]);
         |             ^ ~~~~~~~~~~~~~~~~
   mm/kfence/kfence_test.c:143:6: error: incompatible integer to pointer conversion assigning to 'const char *' from 'int' [-Wint-conversion]
     143 |         end = ENDOF(expect[1]);
         |             ^ ~~~~~~~~~~~~~~~~

3 errors generated.

I'm pretty sure I tested this some months ago. I'll test again...

Have a lovely night!
Alex

Signature · 2 lines
<https://www.alejandro-colomar.es>
Use port 80 (that is, <...:80/>).
#6 lore raw

Re: [PATCH v1 2/3] mm: Fix benign off-by-one bugs

In reply to Alejandro Colomar
kernel test robot noticed the following build errors:

Hi Alejandro,

kernel test robot noticed the following build errors:

[auto build test ERROR on akpm-mm/mm-everything]
[also build test ERROR on kees/for-next/pstore kees/for-next/kspp linus/master linux/master v6.18-rc5 next-20251110] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Alejandro-Colomar/array_size-h-Add-ARRAY_END/20251110-075203
base:   https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-everything
patch link:    https://lore.kernel.org/r/87445e701574058b142e036c3b8a0f505086ab64.1758806023.git.alx%40kernel.org
patch subject: [PATCH v1 2/3] mm: Fix benign off-by-one bugs
config: i386-allmodconfig (https://download.01.org/0day-ci/archive/20251111/[email protected]/config)
compiler: gcc-14 (Debian 14.2.0-19) 14.2.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251111/[email protected]/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 <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

mm/kfence/kfence_test.c: In function 'report_matches':

>> mm/kfence/kfence_test.c:113:15: error: implicit declaration of function 'ENDOF' [-Wimplicit-function-declaration]
     113 |         end = ENDOF(expect[0]);
         |               ^~~~~
>> mm/kfence/kfence_test.c:113:13: error: assignment to 'const char *' from 'int' makes pointer from integer without a cast [-Wint-conversion]
     113 |         end = ENDOF(expect[0]);
         |             ^
   mm/kfence/kfence_test.c:143:13: error: assignment to 'const char *' from 'int' makes pointer from integer without a cast [-Wint-conversion]
     143 |         end = ENDOF(expect[1]);
         |             ^

vim +/ENDOF +113 mm/kfence/kfence_test.c

    94	
    95	/* Check observed report matches information in @r. */
    96	static bool report_matches(const struct expect_report *r)
    97	{
    98		unsigned long addr = (unsigned long)r->addr;
    99		bool ret = false;
   100		unsigned long flags;
   101		typeof(observed.lines) expect;
   102		const char *end;
   103		char *cur;
   104	
   105		/* Doubled-checked locking. */
   106		if (!report_available())
   107			return false;
   108	
   109		/* Generate expected report contents. */
   110	
   111		/* Title */
   112		cur = expect[0];
 > 113		end = ENDOF(expect[0]);

114 switch (r->type) {
115 case KFENCE_ERROR_OOB:
116 cur += scnprintf(cur, end - cur, "BUG: KFENCE: out-of-bounds %s",
117 get_access_type(r));
118 break;
119 case KFENCE_ERROR_UAF:
120 cur += scnprintf(cur, end - cur, "BUG: KFENCE: use-after-free %s",
121 get_access_type(r));
122 break;
123 case KFENCE_ERROR_CORRUPTION:
124 cur += scnprintf(cur, end - cur, "BUG: KFENCE: memory corruption");
125 break;
126 case KFENCE_ERROR_INVALID:
127 cur += scnprintf(cur, end - cur, "BUG: KFENCE: invalid %s",
128 get_access_type(r));
129 break;
130 case KFENCE_ERROR_INVALID_FREE:
131 cur += scnprintf(cur, end - cur, "BUG: KFENCE: invalid free");
132 break;
133 }
134
135 scnprintf(cur, end - cur, " in %pS", r->fn);
136 /* The exact offset won't match, remove it; also strip module name. */
137 cur = strchr(expect[0], '+');
138 if (cur)
139 *cur = '\0';
140
141 /* Access information */
142 cur = expect[1];
143 end = ENDOF(expect[1]);
144
145 switch (r->type) {
146 case KFENCE_ERROR_OOB:
147 cur += scnprintf(cur, end - cur, "Out-of-bounds %s at", get_access_type(r));
148 addr = arch_kfence_test_address(addr);
149 break;
150 case KFENCE_ERROR_UAF:
151 cur += scnprintf(cur, end - cur, "Use-after-free %s at", get_access_type(r));
152 addr = arch_kfence_test_address(addr);
153 break;
154 case KFENCE_ERROR_CORRUPTION:
155 cur += scnprintf(cur, end - cur, "Corrupted memory at");
156 break;
157 case KFENCE_ERROR_INVALID:
158 cur += scnprintf(cur, end - cur, "Invalid %s at", get_access_type(r));
159 addr = arch_kfence_test_address(addr);
160 break;
161 case KFENCE_ERROR_INVALID_FREE:
162 cur += scnprintf(cur, end - cur, "Invalid free of");
163 break;
164 }
165
166 cur += scnprintf(cur, end - cur, " 0x%p", (void *)addr);
167
168 spin_lock_irqsave(&observed.lock, flags);
169 if (!report_available())
170 goto out; /* A new report is being captured. */
171
172 /* Finally match expected output to what we actually observed. */
173 ret = strstr(observed.lines[0], expect[0]) && strstr(observed.lines[1], expect[1]);
174 out:
175 spin_unlock_irqrestore(&observed.lock, flags);
176 return ret;
177 }
178

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#7 lore raw

Re: [PATCH v1 2/3] mm: Fix benign off-by-one bugs

In reply to Alejandro Colomar
kernel test robot noticed the following build warnings:

Hi Alejandro,

kernel test robot noticed the following build warnings:

[auto build test WARNING on akpm-mm/mm-everything]
[also build test WARNING on kees/for-next/pstore kees/for-next/kspp linus/master linux/master v6.18-rc5 next-20251111] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Alejandro-Colomar/array_size-h-Add-ARRAY_END/20251110-075203
base:   https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-everything
patch link:    https://lore.kernel.org/r/87445e701574058b142e036c3b8a0f505086ab64.1758806023.git.alx%40kernel.org
patch subject: [PATCH v1 2/3] mm: Fix benign off-by-one bugs
config: arm64-randconfig-002-20251111 (https://download.01.org/0day-ci/archive/20251111/[email protected]/config)
compiler: aarch64-linux-gcc (GCC) 11.5.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251111/[email protected]/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 <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

mm/kfence/kfence_test.c: In function 'report_matches':
mm/kfence/kfence_test.c:113:15: error: implicit declaration of function 'ENDOF' [-Werror=implicit-function-declaration]

     113 |         end = ENDOF(expect[0]);
         |               ^~~~~
>> mm/kfence/kfence_test.c:113:13: warning: assignment to 'const char *' from 'int' makes pointer from integer without a cast [-Wint-conversion]
     113 |         end = ENDOF(expect[0]);
         |             ^
   mm/kfence/kfence_test.c:143:13: warning: assignment to 'const char *' from 'int' makes pointer from integer without a cast [-Wint-conversion]
     143 |         end = ENDOF(expect[1]);
         |             ^

cc1: some warnings being treated as errors

vim +113 mm/kfence/kfence_test.c

    94	
    95	/* Check observed report matches information in @r. */
    96	static bool report_matches(const struct expect_report *r)
    97	{
    98		unsigned long addr = (unsigned long)r->addr;
    99		bool ret = false;
   100		unsigned long flags;
   101		typeof(observed.lines) expect;
   102		const char *end;
   103		char *cur;
   104	
   105		/* Doubled-checked locking. */
   106		if (!report_available())
   107			return false;
   108	
   109		/* Generate expected report contents. */
   110	
   111		/* Title */
   112		cur = expect[0];
 > 113		end = ENDOF(expect[0]);

114 switch (r->type) {
115 case KFENCE_ERROR_OOB:
116 cur += scnprintf(cur, end - cur, "BUG: KFENCE: out-of-bounds %s",
117 get_access_type(r));
118 break;
119 case KFENCE_ERROR_UAF:
120 cur += scnprintf(cur, end - cur, "BUG: KFENCE: use-after-free %s",
121 get_access_type(r));
122 break;
123 case KFENCE_ERROR_CORRUPTION:
124 cur += scnprintf(cur, end - cur, "BUG: KFENCE: memory corruption");
125 break;
126 case KFENCE_ERROR_INVALID:
127 cur += scnprintf(cur, end - cur, "BUG: KFENCE: invalid %s",
128 get_access_type(r));
129 break;
130 case KFENCE_ERROR_INVALID_FREE:
131 cur += scnprintf(cur, end - cur, "BUG: KFENCE: invalid free");
132 break;
133 }
134
135 scnprintf(cur, end - cur, " in %pS", r->fn);
136 /* The exact offset won't match, remove it; also strip module name. */
137 cur = strchr(expect[0], '+');
138 if (cur)
139 *cur = '\0';
140
141 /* Access information */
142 cur = expect[1];
143 end = ENDOF(expect[1]);
144
145 switch (r->type) {
146 case KFENCE_ERROR_OOB:
147 cur += scnprintf(cur, end - cur, "Out-of-bounds %s at", get_access_type(r));
148 addr = arch_kfence_test_address(addr);
149 break;
150 case KFENCE_ERROR_UAF:
151 cur += scnprintf(cur, end - cur, "Use-after-free %s at", get_access_type(r));
152 addr = arch_kfence_test_address(addr);
153 break;
154 case KFENCE_ERROR_CORRUPTION:
155 cur += scnprintf(cur, end - cur, "Corrupted memory at");
156 break;
157 case KFENCE_ERROR_INVALID:
158 cur += scnprintf(cur, end - cur, "Invalid %s at", get_access_type(r));
159 addr = arch_kfence_test_address(addr);
160 break;
161 case KFENCE_ERROR_INVALID_FREE:
162 cur += scnprintf(cur, end - cur, "Invalid free of");
163 break;
164 }
165
166 cur += scnprintf(cur, end - cur, " 0x%p", (void *)addr);
167
168 spin_lock_irqsave(&observed.lock, flags);
169 if (!report_available())
170 goto out; /* A new report is being captured. */
171
172 /* Finally match expected output to what we actually observed. */
173 ret = strstr(observed.lines[0], expect[0]) && strstr(observed.lines[1], expect[1]);
174 out:
175 spin_unlock_irqrestore(&observed.lock, flags);
176 return ret;
177 }
178

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#8 lore raw

PATCH 3/3 kernel: Fix off-by-one benign bugs

In reply to Alejandro Colomar

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 <[email protected]>
Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Jann Horn <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Al Viro <[email protected]>
---
 kernel/kcsan/kcsan_test.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/kcsan/kcsan_test.c +2 -2
index c2871180edcc..621a60a86b39 100644
@@ -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 = ENDOF(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 = ENDOF(expect[1]);
 	if (!r->access[1].fn)
 		cur += scnprintf(cur, end - cur, "race at unknown origin, with ");
 
Signature · 1 line
2.51.0
maintainer
#9 lore raw
In reply to Alejandro Colomar
Quoted 5 lines · On Thu, 25 Sep 2025 15:20:28 +0200 Alejandro Colomar <[email protected]> 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.

#10 lore raw
Quoted 3 lines · Andrew Morton

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

Signature · 1 line
Kees Cook

A message that is not in the archive (sent off-list or not yet received): CAHk-=wg2M+v5wFQLK3u3DuchpCbuHF8Z7_if3=foECVRXF+8vg@mail.gmail.com

#12 lore raw
Quoted 6 lines · Linus Torvalds
Quoted 2 lines · On Thu, Sep 25, 2025, 17:00 Kees Cook <[email protected]> wrote:

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

That's not an invalid pointer. At all.

Sorry, I mean to say that it points _to_ an invalid location. The pointer is not valid to dereference, but its _value_ has meaning (relative to another pointer).

I can have an opinion about the relative safety of holding pointers that can't be safely dereferenced, though. :) But yes, I've long since lost the argument that C should avoid these kinds of past-the-end tokens.

-Kees

Signature · 1 line
Kees Cook
#13 lore raw
Quoted 4 lines · Kees Cook

I can have an opinion about the relative safety of holding pointers that can't be safely dereferenced, though. :) But yes, I've long since lost the argument that C should avoid these kinds of past-the-end tokens.

The thing is, the "start+len" model is actually *safer* than the "start+len-1" model.

It's safer because it's simpler and doesn't involve the whole "subtract one" (and then when you have the "past the end" it's also easy to calculate "how much is left").

So it's simpler, and it's explicitly supported by the standard.

It's also more strictly correct, because "start+len-1" is technically not a valid pointer at all. The C standard makes the "past the end" case explicitly valid, but not the "before the beginning".

Now, I'm the last person to say that the C standard is always correct
- there's a lot of garbage in there, but in this case it also happens to match the notion of "this works".

Because the "pointer to the last byte" model DOES NOT WORK.

In C, NULL is actually a valid pointer for zero-sized elements.

Yes, really.

The C standard says that "malloc(0)" can return NULL, without it being an error. So the tuple "NULL, 0" is actually a perfectly valid "pointer and length" pair, and one that you may actually get thanks to how malloc() works.

Obviously you cannot dereference a zero-sized object, but zero-sized objects aren't "wrong" per se.

Now, I happen to believe that the "return NULL for zero sized allocations" it's not a great model (it also makes error checking more complicated). So the kernel kmalloc() function actually returns a different pointer that cannot be dereferenced (grep for ZERO_SIZE_PTR).

But my point is that "ptr+len" actually *works* for that case.

The "ptr+len-1" loop thing you gave as an example not only is invalid C for zero-sized cases, it simply does not even work at all for the NULL case.

Your example loop of how things should work IS WRONG.

Yes, it happens to work as long as you never have zero-sized things, but it really is a bad pattern.

This is not "opinion". This is just a plain fact about how C works. "start+len" is well-defined. "start+len-1" is NOT.

Linus

#14 lore raw
Quoted 2 lines · Linus Torvalds

The thing is, the "start+len" model is actually *safer* than the "start+len-1" model.

Sure. But start + len is a vector: "start" is a pointer, and "len" is a size. No problems at all.

Quoted 2 lines

Obviously you cannot dereference a zero-sized object, but zero-sized objects aren't "wrong" per se.

Right, totally agreed. I'm a big fan of zero-sized objects which are useful in all kinds of situations (e.g. empty flexible arrays). And as you're saying, a zero-sized object shares the same representation:
start + len where len is 0.

What I dislike is having this vector collapsed into a pointer because it loses its explicit start/len information, and becomes ambiguous. And worse we have nothing that says "this pointer isn't safe to dereference".

All the bounds safety work we've been doing lately is mostly centered around finding ways to retain the "len" part of dynamically sized object pointers so we can reconstruct the vector unambiguously.

Anyway, yay for vectors. :)

-Kees

Signature · 1 line
Kees Cook
#15 lore raw

Hi Kees,

Quoted 10 lines · Kees Cook
Quoted 2 lines · Linus Torvalds

The thing is, the "start+len" model is actually *safer* than the "start+len-1" model.

Sure. But start + len is a vector: "start" is a pointer, and "len" is a size. No problems at all.

Quoted 2 lines

Obviously you cannot dereference a zero-sized object, but zero-sized objects aren't "wrong" per se.

Quoted 8 lines

Right, totally agreed. I'm a big fan of zero-sized objects which are useful in all kinds of situations (e.g. empty flexible arrays). And as you're saying, a zero-sized object shares the same representation:
start + len where len is 0.

What I dislike is having this vector collapsed into a pointer because it loses its explicit start/len information, and becomes ambiguous. And worse we have nothing that says "this pointer isn't safe to dereference".

The word END should be understood as "this isn't safe to dereference".

I'm not inventing anything new; it's something standard in a way, as C++'s std::end is precisely that (and no, I don't like C++, but this name is quite consistent everywhere, including the kernel itself).

Quoted 3 lines

All the bounds safety work we've been doing lately is mostly centered around finding ways to retain the "len" part of dynamically sized object pointers so we can reconstruct the vector unambiguously.

END is useful in cases where you don't care about the begining. It's useful as a way to know where an array ends, regardless of how much we've advanced in its contents.

Have a lovely day!
Alex

P.S.: Please let me know if this patch set is suitable for applying, or if I need to provide a better cover letter, or if I need to do anything else.

Quoted 7 lines

Anyway, yay for vectors. :)

-Kees

Signature · 1 line
Kees Cook
Signature · 2 lines
<https://www.alejandro-colomar.es>
Use port 80 (that is, <...:80/>).
#16 lore raw
In reply to Linus Torvalds

Hi Linus, Kees, Andrew,

Quoted 7 lines · Kees Cook
Quoted 3 lines · Andrew Morton

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.

The name END has some conventions. It's not arbitrarily chosen.

The C standard is quite consistent in referring to the last addressable element of an array as the LAST element.

For what we're dealing with, which is a pointer to one after that thing, the C standard is also consistent in calling it 'one past the last element'. It doesn't have a single-word term, though.

However, C++ does have a single term: 'std::end'.

And many projects, when having to come up with a single-word term for this thing, natural evolution shows it converges to 'end'. Even in the kernel, as your local pointer variables are actually called 'end' and not 'beyond'.

Quoted 3 lines

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

This last is correctly used, as a term, but quite dangerous, as Linus points out.

LASTOF() would be something quite more dangerous than ENDOF(). First of all, because it's not guaranteed to exist, as Linus points out. LASTOF() applied to a zero-length array would be Undefined Behavior straight away. That's indeed why we have guarantees that the end always exists and can be held.

Quoted 2 lines

for (u8 *c = first; c <= last; c++)

Secondly, loops with <= are weird and error prone.

Quoted 5 lines

putc(*c);
// c would now be invalid but has left scope so it cannot be used

--
Kees Cook

Quoted 19 lines · Linus Torvalds
Quoted 4 lines · Kees Cook

I can have an opinion about the relative safety of holding pointers that can't be safely dereferenced, though. :) But yes, I've long since lost the argument that C should avoid these kinds of past-the-end tokens.

The thing is, the "start+len" model is actually *safer* than the "start+len-1" model.

It's safer because it's simpler and doesn't involve the whole "subtract one" (and then when you have the "past the end" it's also easy to calculate "how much is left").

So it's simpler, and it's explicitly supported by the standard.

It's also more strictly correct, because "start+len-1" is technically not a valid pointer at all. The C standard makes the "past the end" case explicitly valid, but not the "before the beginning".

Quoted 5 lines

Now, I'm the last person to say that the C standard is always correct
- there's a lot of garbage in there, but in this case it also happens to match the notion of "this works".

Because the "pointer to the last byte" model DOES NOT WORK.

So far, fully agree.

Quoted 1 line

In C, NULL is actually a valid pointer for zero-sized elements.

This is only valid since very recently.

Remember that 'NULL - NULL' is (or was) Undefined Behavior. That operation doesn't result in 0, per the standard. NULL < NULL is (or was) also Undefined Behavior.

Consider this innocent loop:

	end = ptr + size; 

	for (p = ptr; p < end; p++)
		*p = 0;

If ptr were NULL (trying to represent a zero-size array), we'd at least incur in one NULL < NULL operation.

However, a unique pointer, as returned by glibc malloc(0), would be a valid pointer, and p<p would be perfectly valid. p-p would also perfectly result in 0. Of course you can't access p[i] for any i>=0, but that's true of any object. If you have an array of 2, you can't access p[i] for any i>=2. Everything is consistent with unique pointers.

So, the whole model of malloc(0) returning NULL as successfully allocating 0 bytes is broken.

Recently, the committee decided that memcpy(3) would accept NULL if the size is 0, and I'm not sure if they also defined the behavior for any of NULL < NULL or NULL - NULL. I'd still be careful using NULL to represent a zero-size array.

Quoted 6 lines

Yes, really.

The C standard says that "malloc(0)" can return NULL, without it being an error. So the tuple "NULL, 0" is actually a perfectly valid "pointer and length" pair, and one that you may actually get thanks to how malloc() works.

This is something I want to change. malloc(0) returning NULL is terrible. realloc(p,0) returning NULL is even more terrible. And by terrible, I mean it has caused remote-code-execution exploits.

<https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3621.txt>

Quoted 15 lines

Obviously you cannot dereference a zero-sized object, but zero-sized objects aren't "wrong" per se.

Now, I happen to believe that the "return NULL for zero sized allocations" it's not a great model (it also makes error checking more complicated). So the kernel kmalloc() function actually returns a different pointer that cannot be dereferenced (grep for ZERO_SIZE_PTR).

But my point is that "ptr+len" actually *works* for that case.

The "ptr+len-1" loop thing you gave as an example not only is invalid C for zero-sized cases, it simply does not even work at all for the NULL case.

Quoted 7 lines

Your example loop of how things should work IS WRONG.

Yes, it happens to work as long as you never have zero-sized things, but it really is a bad pattern.

This is not "opinion". This is just a plain fact about how C works. "start+len" is well-defined. "start+len-1" is NOT.

Agree.

Have a lovely day!
Alex

Quoted 2 lines

Linus

Signature · 2 lines
<https://www.alejandro-colomar.es>
Use port 80 (that is, <...:80/>).
#17 lore raw
In reply to Andrew Morton

Hi Andrew,

Quoted 20 lines · Andrew Morton
Quoted 5 lines · On Thu, 25 Sep 2025 15:20:28 +0200 Alejandro Colomar <[email protected]> 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,

Quoted 5 lines

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.

Quoted 3 lines

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.

Quoted 3 lines

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

Signature · 2 lines
<https://www.alejandro-colomar.es>
Use port 80 (that is, <...:80/>).
#18 lore raw

v2 cover Add ARRAY_END(), and use it to fix off-by-one bugs

In reply to Alejandro Colomar

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 <[email protected]>

## 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 <[email protected]>
Cc: Christopher Bazley <[email protected]>
@@ 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

Signature · 1 line
2.51.0
#19 lore raw

PATCH v2 1/4 array_size.h: Add ARRAY_END()

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 <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Al Viro <[email protected]>

Message-ID: <37b1088dbd01a21d2f9d460aa510726119b3bcb0.1752193588.git.alx@kernel.org>

---
 include/linux/array_size.h | 6 ++++++
 1 file changed, 6 insertions(+)
include/linux/array_size.h +6 -0
index 06d7d83196ca..62382973078e 100644
@@ -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 */
Signature · 1 line
2.51.0
#20 lore raw

Re: [PATCH v2 1/4] array_size.h: Add ARRAY_END()

kernel test robot noticed the following build warnings:

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/[email protected]/config)
compiler: alpha-linux-gcc (GCC) 15.1.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251109/[email protected]/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 <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

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

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#21 lore raw

Re: [PATCH v2 1/4] array_size.h: Add ARRAY_END()

Hi,

Quoted 19 lines · kernel test robot

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/[email protected]/config)
compiler: alpha-linux-gcc (GCC) 15.1.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251109/[email protected]/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 <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

Quoted 5 lines

All warnings (new ones prefixed by >>):

Quoted 1 line
Quoted 1 line

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

Quoted 20 lines

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

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
Signature · 2 lines
<https://www.alejandro-colomar.es>
Use port 80 (that is, <...:80/>).
#22 lore raw

Re: [PATCH v2 1/4] array_size.h: Add ARRAY_END()

In reply to Alejandro Colomar
kernel test robot noticed the following build warnings:

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/[email protected]/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/[email protected]/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 <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

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

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#23 lore raw

PATCH v2 2/4 mm: Fix benign off-by-one bugs

In reply to Alejandro Colomar

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.

Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Jann Horn <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Al Viro <[email protected]>

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(-)
mm/kfence/kfence_test.c +2 -2
index 00034e37bc9f..5725a367246d 100644
@@ -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:
mm/kmsan/kmsan_test.c +1 -1
index 902ec48b1e3e..b5ad5dfb2c00 100644
@@ -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);
 
Signature · 1 line
2.51.0
#24 lore raw

PATCH v2 3/4 kernel: Fix off-by-one benign bugs

In reply to Alejandro Colomar

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 <[email protected]>
Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Jann Horn <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Al Viro <[email protected]>
---
 kernel/kcsan/kcsan_test.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/kcsan/kcsan_test.c +2 -2
index 219d22857c98..8ef8167be745 100644
@@ -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 ");
 
Signature · 1 line
2.51.0
#25 lore raw

PATCH v2 4/4 mm: Use ARRAY_END() instead of open-coding it

In reply to Alejandro Colomar
---
 mm/kmemleak.c      | 2 +-
 mm/memcontrol-v1.c | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)
mm/kmemleak.c +1 -1
index 1ac56ceb29b6..fe33f2edfe07 100644
@@ -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;
 	}
mm/memcontrol-v1.c +2 -2
index 6eed14bff742..b2f37bd939fa 100644
@@ -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,
Signature · 1 line
2.51.0
#26 lore raw

v3 cover Add ARRAY_END(), and use it to fix off-by-one bugs

In reply to Alejandro Colomar

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 <[email protected]>]
- 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 <[email protected]>
@@ Commit message

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
Signature · 1 line
2.51.0
#27 lore raw

PATCH v3 1/4 array_size.h: Add ARRAY_END()

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 <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Al Viro <[email protected]>

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(-)
drivers/block/floppy.c +0 -2
index 5336c3c5ca36..69661840397e 100644
@@ -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;
include/linux/array_size.h +6 -0
index 06d7d83196ca..b5775b8f13de 100644
@@ -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 */
Signature · 1 line
2.51.0
#28 lore raw

Re: [PATCH v3 1/4] array_size.h: Add ARRAY_END()

include/linux/array_size.h line 17

Quoted 13 lines · Alejandro Colomar
include/linux/array_size.h +5 -0
index 06d7d83196ca..b5775b8f13de 100644
@@ -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

#29 lore raw

Re: [PATCH v3 1/4] array_size.h: Add ARRAY_END()

Hi Maciej,

Quoted 10 lines · Maciej W. Rozycki
Quoted 8 lines · Alejandro Colomar
include/linux/array_size.h +0 -0
index 06d7d83196ca..b5775b8f13de 100644
@@ -10,4 +10,10 @@
  */
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
 
Quoted 7 lines

include/linux/array_size.h line 17

Quoted 5 lines
include/linux/array_size.h +5 -0
+/**
+ * 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

Quoted 2 lines

Maciej

Signature · 2 lines
<https://www.alejandro-colomar.es>
Use port 80 (that is, <...:80/>).
#30 lore raw

PATCH v3 2/4 mm: Fix benign off-by-one bugs

In reply to Alejandro Colomar

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.

Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Jann Horn <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Al Viro <[email protected]>

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(-)
mm/kfence/kfence_test.c +2 -2
index 00034e37bc9f..5725a367246d 100644
@@ -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:
mm/kmsan/kmsan_test.c +1 -1
index 902ec48b1e3e..b5ad5dfb2c00 100644
@@ -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);
 
Signature · 1 line
2.51.0
#31 lore raw

PATCH v3 3/4 kernel: Fix off-by-one benign bugs

In reply to Alejandro Colomar

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 <[email protected]>
Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Jann Horn <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Al Viro <[email protected]>
---
 kernel/kcsan/kcsan_test.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/kcsan/kcsan_test.c +2 -2
index 219d22857c98..8ef8167be745 100644
@@ -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 ");
 
Signature · 1 line
2.51.0
#32 lore raw

PATCH v3 4/4 mm: Use ARRAY_END() instead of open-coding it

In reply to Alejandro Colomar
---
 mm/kmemleak.c      | 2 +-
 mm/memcontrol-v1.c | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)
mm/kmemleak.c +1 -1
index 1ac56ceb29b6..fe33f2edfe07 100644
@@ -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;
 	}
mm/memcontrol-v1.c +2 -2
index 6eed14bff742..b2f37bd939fa 100644
@@ -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,
Signature · 1 line
2.51.0
#33 lore raw

v4 cover Add ARRAY_END(), and use it to fix off-by-one bugs

In reply to Alejandro Colomar

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" <[email protected]>]

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 <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Al Viro <[email protected]>
+ Cc: "Maciej W. Rozycki" <[email protected]>

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

Signature · 1 line
2.51.0
#34 lore raw

PATCH v4 1/4 array_size.h: Add ARRAY_END()

In reply to Alejandro Colomar

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 <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Al Viro <[email protected]>
Cc "Maciej W. Rozycki" <[email protected]>

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(-)
drivers/block/floppy.c +0 -2
index 5336c3c5ca36..69661840397e 100644
@@ -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;
include/linux/array_size.h +6 -0
index 06d7d83196ca..0c4fec98822e 100644
@@ -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 */
Signature · 1 line
2.51.0
#35 lore raw

PATCH v4 2/4 mm: Fix benign off-by-one bugs

In reply to Alejandro Colomar

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.

Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Jann Horn <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Al Viro <[email protected]>

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(-)
mm/kfence/kfence_test.c +2 -2
index 00034e37bc9f..5725a367246d 100644
@@ -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:
mm/kmsan/kmsan_test.c +1 -1
index 902ec48b1e3e..b5ad5dfb2c00 100644
@@ -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);
 
Signature · 1 line
2.51.0
#36 lore raw

PATCH v4 3/4 kernel: Fix off-by-one benign bugs

In reply to Alejandro Colomar

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 <[email protected]>
Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Jann Horn <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Al Viro <[email protected]>
---
 kernel/kcsan/kcsan_test.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/kcsan/kcsan_test.c +2 -2
index 219d22857c98..8ef8167be745 100644
@@ -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 ");
 
Signature · 1 line
2.51.0
#37 lore raw

PATCH v4 4/4 mm: Use ARRAY_END() instead of open-coding it

In reply to Alejandro Colomar
---
 mm/kmemleak.c      | 2 +-
 mm/memcontrol-v1.c | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)
mm/kmemleak.c +1 -1
index 1ac56ceb29b6..fe33f2edfe07 100644
@@ -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;
 	}
mm/memcontrol-v1.c +2 -2
index 6eed14bff742..b2f37bd939fa 100644
@@ -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,
Signature · 1 line
2.51.0
#38 lore raw

v5 cover Add ARRAY_END(), and use it to fix off-by-one bugs

In reply to Alejandro Colomar

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 <[email protected]>
Cc: Christopher Bazley <[email protected]>
Cc: Rasmus Villemoes <[email protected]>
Cc: Marco Elver <[email protected]>
Cc: Michal Hocko <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Alexander Potapenko <[email protected]>
Cc: Dmitry Vyukov <[email protected]>
Cc: Jann Horn <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: "Maciej W. Rozycki" <[email protected]>
In-Reply-To: <[email protected]>

---

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
Signature · 1 line
2.51.0
#39 lore raw

PATCH v5 1/4 array_size.h: Add ARRAY_END()

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 <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Al Viro <[email protected]>
Cc "Maciej W. Rozycki" <[email protected]>

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(-)
drivers/block/floppy.c +0 -2
index 5336c3c5ca36..69661840397e 100644
@@ -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;
include/linux/array_size.h +6 -0
index 06d7d83196ca..0c4fec98822e 100644
@@ -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 */
Signature · 1 line
2.51.0
#40 lore raw

PATCH v5 2/4 mm: Fix benign off-by-one bugs

In reply to Alejandro Colomar

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.

Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Jann Horn <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Al Viro <[email protected]>

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(-)
mm/kfence/kfence_test.c +2 -2
index 00034e37bc9f..5725a367246d 100644
@@ -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:
mm/kmsan/kmsan_test.c +1 -1
index 902ec48b1e3e..b5ad5dfb2c00 100644
@@ -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);
 
Signature · 1 line
2.51.0
#41 lore raw

PATCH v5 3/4 kernel: Fix off-by-one benign bugs

In reply to Alejandro Colomar

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 <[email protected]>
Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Jann Horn <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Al Viro <[email protected]>
---
 kernel/kcsan/kcsan_test.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/kcsan/kcsan_test.c +2 -2
index 219d22857c98..8ef8167be745 100644
@@ -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 ");
 
Signature · 1 line
2.51.0
#42 lore raw

PATCH v5 4/4 mm: Use ARRAY_END() instead of open-coding it

In reply to Alejandro Colomar
---
 mm/kmemleak.c      | 2 +-
 mm/memcontrol-v1.c | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)
mm/kmemleak.c +1 -1
index 1ac56ceb29b6..fe33f2edfe07 100644
@@ -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;
 	}
mm/memcontrol-v1.c +2 -2
index 6eed14bff742..b2f37bd939fa 100644
@@ -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,
Signature · 1 line
2.51.0
#43 lore raw

Re: [PATCH v5 4/4] mm: Use ARRAY_END() instead of open-coding it

Quoted 3 lines · Alejandro Colomar

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

Quoted 40 lines

---
mm/kmemleak.c | 2 +-
mm/memcontrol-v1.c | 4 ++--

2 files changed, 3 insertions(+), 3 deletions(-)
mm/kmemleak.c +1 -1
index 1ac56ceb29b6..fe33f2edfe07 100644
@@ -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;
 	}
mm/memcontrol-v1.c +2 -2
index 6eed14bff742..b2f37bd939fa 100644
@@ -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,
Signature · 1 line
Kees Cook
#44 lore raw

Re: [PATCH v5 4/4] mm: Use ARRAY_END() instead of open-coding it

Hi Kees,

Quoted 8 lines · Kees Cook
Quoted 3 lines · Alejandro Colomar

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?

Quoted 1 line

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.

Quoted 2 lines

-Kees

Have a lovely night!
Alex

Quoted 44 lines
Quoted 41 lines

---
mm/kmemleak.c | 2 +-
mm/memcontrol-v1.c | 4 ++--

2 files changed, 3 insertions(+), 3 deletions(-)
mm/kmemleak.c +1 -1
index 1ac56ceb29b6..fe33f2edfe07 100644
@@ -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;
 	}
mm/memcontrol-v1.c +2 -2
index 6eed14bff742..b2f37bd939fa 100644
@@ -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,
Signature · 1 line
Kees Cook
Signature · 1 line
<https://www.alejandro-colomar.es>
#45 lore raw

Re: [PATCH v5 4/4] mm: Use ARRAY_END() instead of open-coding it

Quoted 10 lines · Alejandro Colomar

Hi Kees,

Quoted 7 lines · Kees Cook
Quoted 3 lines · Alejandro Colomar
Quoted 7 lines
Quoted 1 line

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.

Quoted 8 lines
Quoted 1 line

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. :)

Quoted 4 lines

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

Signature · 1 line
Kees Cook
#46 lore raw

Re: [PATCH v5 4/4] mm: Use ARRAY_END() instead of open-coding it

Hi Kees, Andrew,

Quoted 8 lines · Kees Cook
Quoted 8 lines
Quoted 1 line

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. :)

Quoted 6 lines
Quoted 4 lines

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

Signature · 1 line
<https://www.alejandro-colomar.es>
#47 lore raw

Re: [PATCH v5 4/4] mm: Use ARRAY_END() instead of open-coding it

Quoted 31 lines · Alejandro Colomar

Hi Kees, Andrew,

Quoted 8 lines · Kees Cook
Quoted 8 lines
Quoted 1 line

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. :)

Quoted 6 lines
Quoted 4 lines

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)

Quoted 6 lines

@@
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

Signature · 1 line
Kees Cook
#48 lore raw

Re: [PATCH v5 4/4] mm: Use ARRAY_END() instead of open-coding it

Hi Kees,

Quoted 17 lines · Kees Cook
Quoted 17 lines

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;
	@@
Quoted 5 lines
Quoted 2 lines

- 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.

Quoted 8 lines

@@
expression a;
@@

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

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

Yup, it works. :)

Quoted 1 line

Anyway, looks good!

Thanks!

Quoted 2 lines

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.

Quoted 4 lines

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

Signature · 1 line
<https://www.alejandro-colomar.es>
#49 lore raw

v6 cover Add ARRAY_END(), and use it to fix off-by-one bugs

In reply to Alejandro Colomar

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 <[email protected]>
Cc: Christopher Bazley <[email protected]>
Cc: Rasmus Villemoes <[email protected]>
Cc: Marco Elver <[email protected]>
Cc: Michal Hocko <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Alexander Potapenko <[email protected]>
Cc: Dmitry Vyukov <[email protected]>
Cc: Jann Horn <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: "Maciej W. Rozycki" <[email protected]>
In-Reply-To: <[email protected]>

---

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.
+

Signature · 1 line
2.51.0
#50 lore raw

PATCH v6 1/4 array_size.h: Add ARRAY_END()

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 <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Al Viro <[email protected]>
Cc "Maciej W. Rozycki" <[email protected]>

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(-)
drivers/block/floppy.c +0 -2
index 5336c3c5ca36..69661840397e 100644
@@ -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;
include/linux/array_size.h +6 -0
index 06d7d83196ca..0c4fec98822e 100644
@@ -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 */
Signature · 1 line
2.51.0
#51 lore raw

PATCH v6 2/4 mm: Fix benign off-by-one bugs

In reply to Alejandro Colomar

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.

Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Jann Horn <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Al Viro <[email protected]>

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(-)
mm/kfence/kfence_test.c +2 -2
index 00034e37bc9f..5725a367246d 100644
@@ -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:
mm/kmsan/kmsan_test.c +1 -1
index 902ec48b1e3e..b5ad5dfb2c00 100644
@@ -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);
 
Signature · 1 line
2.51.0
#52 lore raw

PATCH v6 3/4 kernel: Fix off-by-one benign bugs

In reply to Alejandro Colomar

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 <[email protected]>
Cc Kees Cook <[email protected]>
Cc Christopher Bazley <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Alexander Potapenko <[email protected]>
Cc Jann Horn <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Rasmus Villemoes <[email protected]>
Cc Marco Elver <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Al Viro <[email protected]>
---
 kernel/kcsan/kcsan_test.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/kcsan/kcsan_test.c +2 -2
index 219d22857c98..8ef8167be745 100644
@@ -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 ");
 
Signature · 1 line
2.51.0
#53 lore raw

PATCH v6 4/4 mm: Use ARRAY_END() instead of open-coding it

In reply to Alejandro Colomar

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.

---
 mm/kmemleak.c      | 2 +-
 mm/memcontrol-v1.c | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)
mm/kmemleak.c +1 -1
index 1ac56ceb29b6..fe33f2edfe07 100644
@@ -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;
 	}
mm/memcontrol-v1.c +2 -2
index 6eed14bff742..b2f37bd939fa 100644
@@ -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,
Signature · 1 line
2.51.0
Reviewed-by on v6 4/4
#54 lore raw

Re: [PATCH v6 4/4] mm: Use ARRAY_END() instead of open-coding it

Quoted 11 lines · On Thu, 11 Dec 2025 11:44:04 +0100 Alejandro Colomar <[email protected]> wrote:

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.

Thanks,
SJ

[...]