Glibc may provide a safe nitems(), and also __must_be_array()

From: Alejandro Colomar
Date: Mon Sep 28 2020 - 05:48:36 EST


Hi Rusty,

I have a few related questions about the kernel.
I have never written kernel code, so maybe you have some configuration
that I don't know, but I've seen a few things that look a bit weird.

1)

The kernel has ARRAY_SIZE() in <linux/kernel.h>,
but still a lot of files either use the raw sizeof division, or
define a simple ARRAY_SIZE() (sometimes with that name,
and sometimes with a different name) without using __must_be_array()
(and therefore being unsafe).

Is there any reason for any of those files to not use the definition in
<linux/kernel.h>, or should all of them be fixed to use it?

2)

Glibc may provide __must_be_array() in the near future.
I designed it so that it should be 100% compatible with the one in
<linux/compiler.h>. It will be provided in <sys/param.h>.

I'd add a
#if !defined(__must_be_array) [...] #endif
enclosing its definition in <linux/compiler.h>,
to avoid possible redefinitions.

3)

Does the kernel always compile against glibc?

If that's the case, the kernel could include <sys/param.h> to get the
definitions of __must_be_array() and nitems(), couldn't it
(if/when they merge the patch I sent, of course)?

If not, I'd like to know which other libraries are possible, and I'd
like to patch them to also have nitems() and __must_be_array().

4)

I'd like to know your thoughts about the following macro for getting
array sizes in bytes safely:

#define array_bytes(arr) (sizeof(arr) + __must_be_array(arr))

I already have a patch prepared for glibc, in case they merge nitems().

It would help get rid once and for all of a whole class of bugs,
and at the same time allow for the sintactic sugar of
arrays in function parameters:

https://lkml.org/lkml/2015/9/3/428


I'll be happy to write any patches for the kernel that are neccessary
related to these things.


Thanks,

Alex