Re: [PATCH 1/4] string: try to find const-laundering bugs

From: Joe Perches
Date: Wed Aug 22 2018 - 07:08:02 EST


On Wed, 2018-08-22 at 13:00 +0200, Rasmus Villemoes wrote:
> This wraps strchr and friends in macros that ensure the return value has
> type const char* if the passed-in string (which the return value points
> into) also has type const char*. The (s)+0 thing is to force a const
> char[] (e.g. a string literal) to decay to a const char* for the
> __same_type comparison.
[]
> diff --git a/include/linux/string.h b/include/linux/string.h
[]
> +#define strchr(s, c) ( \
> + __builtin_choose_expr(__same_type((s) + 0, const char *), \
> + (const char *)strchr(s, c), \
> + strchr(s, c)))
> +#endif
[]
> diff --git a/lib/string.c b/lib/string.c
[]
> @@ -367,7 +367,7 @@ EXPORT_SYMBOL(strncmp);
> * @s: The string to be searched
> * @c: The character to search for
> */
> -char *strchr(const char *s, int c)
> +char *(strchr)(const char *s, int c)

I've tried to use this macro/function wrapping
a few times before, but it seems that it's fairly
unusual in the kernel. I believe there may not
be any current uses of that style.

A comment explaining the form might be useful.