Re: [PATCH] builtin: implement __builtin_strlen() for constants

Linus Torvalds <[email protected]>
Newsgroups org.kernel.vger.linux-sparse,org.kernel.vger.linux-media
Message-ID <CAHk-=wgKcf_dP0_7yTqL+JKc03mhFgqFHkN7jXLUrOy=WjWZUA@mail.gmail.com>
On Wed, 15 Oct 2025 at 06:09, Dan Carpenter <[email protected]> wrote:
>
> People are adding compile time asserts to check whether strings are
> the expected length.  In GCC and Clang strlen("foo") is expanded at
> compile time so this works, but in Sparse it triggers a "bad constant
> expression" warning.  Implement expand_strlen() to handle string
> literals.

Ack.

Except it's not quite right.

Try this:

    int i(void)
    {
        return __builtin_strlen("hello\0hi");
    }

and you'll see that it returns 8, even though the correct string length is 5.

So you should add a

    #include <string.h>

at the top, and do something like

-       expr->value = arg->string->length - 1;
+       expr->value = strlen(arg->string->data);

in there instead, because constant strings can have embedded NUL characters.

           Linus
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.