compiler.h: Introduce __must_be_noncstr()

In preparation for adding more type checking to the memtostr/strtomem*()
helpers, introduce the ability to check for the "nonstring" attribute.
This is the reverse of what was added to strscpy*() in commit 559048d156
("string: Check for "nonstring" attribute on strscpy() arguments").

Note that __annotated() must be explicitly tested for, as GCC added
__builtin_has_attribute() after it added the "nonstring" attribute. Do
so here to avoid the !__annotated() test triggering build failures
when __builtin_has_attribute() was missing but __nonstring was defined.
(I've opted to squash this fix into this patch so we don't end up with
a possible bisection target that would leave the kernel unbuildable.)

Reported-by: Venkat Rao Bagalkote <venkat88@linux.vnet.ibm.com>
Reported-by: Stephen Rothwell <sfr@canb.auug.org.au>
Reported-by: Christophe Leroy <christophe.leroy@csgroup.eu>
Reported-by: Michael Kelley <mhklinux@outlook.com>
Closes: https://lore.kernel.org/all/adbe8dd1-a725-4811-ae7e-76fe770cf096@linux.vnet.ibm.com/
Tested-by: Michael Kelley <mhklinux@outlook.com>
Signed-off-by: Kees Cook <kees@kernel.org>
This commit is contained in:
Kees Cook
2025-02-06 14:54:11 -08:00
parent 4c2d8a6a54
commit 9f25b1fb1c
2 changed files with 23 additions and 4 deletions

View File

@@ -206,9 +206,25 @@ void ftrace_likely_update(struct ftrace_likely_data *f, int val,
#define __must_be_byte_array(a) __BUILD_BUG_ON_ZERO_MSG(!__is_byte_array(a), \
"must be byte array")
/*
* If the "nonstring" attribute isn't available, we have to return true
* so the __must_*() checks pass when "nonstring" isn't supported.
*/
#if __has_attribute(__nonstring__) && defined(__annotated)
#define __is_cstr(a) (!__annotated(a, nonstring))
#define __is_noncstr(a) (__annotated(a, nonstring))
#else
#define __is_cstr(a) (true)
#define __is_noncstr(a) (true)
#endif
/* Require C Strings (i.e. NUL-terminated) lack the "nonstring" attribute. */
#define __must_be_cstr(p) \
__BUILD_BUG_ON_ZERO_MSG(__annotated(p, nonstring), "must be cstr (NUL-terminated)")
__BUILD_BUG_ON_ZERO_MSG(!__is_cstr(p), \
"must be C-string (NUL-terminated)")
#define __must_be_noncstr(p) \
__BUILD_BUG_ON_ZERO_MSG(!__is_noncstr(p), \
"must be non-C-string (not NUL-terminated)")
#endif /* __KERNEL__ */