Re: [PATCH v1 1/2] string: Add strprefix(), and deprecate str_has_prefix()

From: Steven Rostedt

Date: Thu Nov 05 2026 - 13:38:52 EST


On Thu, 5 Nov 2026 12:13:03 +0100
Alejandro Colomar <alx@xxxxxxxxxx> wrote:

> As Bartosz reported, str_has_prefix() has a bug: it can't differentiate
> between an empty prefix matching an empty string from a non-matching
> prefix. This is a fundamental design flaw in this API, and not
> something that can be fixed.
>
> As always, this is a consequence of choosing sizes instead of pointers.
> Sizes are often the wrong choice. In this specific case, pointers are
> more capable of differentiating these cases, as NULL is a special
> sentinel value that doesn't need to overload a valid value.
>
> Let's implement strprefix(), a function that returns a pointer
> right after the prefix if found, and a null pointer if not found.
>
> We'll slowly migrate existing code from str_has_prefix() to strprefix().
>
> Reported-by: Bartosz Golaszewski <bartosz.golaszewski@xxxxxxxxxxxxxxxx>

Is there a link to the report? Please add that.

>
> +/**
> + * strprefix - string prefix
> + * @s: The string to be tested
> + * @prefix: The string to see if @s starts with
> + *

Needs a better description. Feel free to use the one for str_has_prefix().


> + * Returns:
> + * * @s+strlen(@prefix) if @s starts with @prefix
> + * * NULL if @s does not start with @prefix
> + */
> +static __always_inline char *strprefix(const char *s, const char *prefix)
> +{
> + size_t len = strlen(prefix);
> + return strncmp(s, prefix, len) == 0 ? (char *) s + len : NULL;
> +}
> +
> /**
> * str_has_prefix - Test if a string has a given prefix
> * @str: The string to test
> * @prefix: The string to see if @str starts with
> *
> + * DEPRECATED: Use strprefix()

No, it is still useful. Converting trace_event_filter() to strprefix()
would be very painful, and likely error prone.

> + *
> * A common way to test a prefix of a string is to do:
> * strncmp(str, prefix, sizeof(prefix) - 1)
> *
> * But this can lead to bugs due to typos, or if prefix is a pointer
> - * and not a constant. Instead use str_has_prefix().
> + * and not a constant. Instead use strprefix().

The above can be replaced with:

* This is useful for testing for a prefix and returning the length.
* If you only need to test the prefix and perhaps get the pointer to the
* position of the string after the prefix, then use strprefix().

-- Steve


> *
> * Returns:
> * * strlen(@prefix) if @str starts with @prefix