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

From: Rasmus Villemoes
Date: Wed Aug 22 2018 - 07:40:54 EST


On 2018-08-22 13:07, Joe Perches wrote:
> 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.
>

True. I dislike the more conventional #undef strchr approach, because
that would mean any other function in string.c that calls strchr and
happens to be defined after strchr() would not be 'instrumented'. It's
more a principle than a practical thing because, well, none of the
instrumented functions happen to be used by other functions in string.c.

Rasmus