Re: [PATCH next 2/3] fortify: Optimise strnlen()

David Laight
2026-04-01T13:48:24Z

On Tue, 31 Mar 2026 16:51:26 -0700
Kees Cook <kees@kernel.org> wrote:

> On Tue, Mar 31, 2026 at 11:09:14PM +0100, David Laight wrote:
> > Any uses should be replaced by __builtin_strlen().
>
> When I looked at this before, __builtin_strlen() flip to run-time strlen
> on non-constant strings, which is why I had to jump through all the
> hoops to avoid calling it in those cases.
>

It should be fine provided that you check that the result is constant.
So doing:
size_t len = __builtin_strlen(p);
if (__builtin_constant_p(len))
...
should never generate a run-time call to strlen().
(Probably the optimiser throws the call away because it knows it has
no side effects.)

I did notice that:
if (__builtin_constant_p(__builtin_strlen(p)))
...
is true less often (more so with clang than gcc).
I suspect than an early compiler pass generates 'no' rather than 'maybe'
when used inside an inlined function.

There is also something odd going on with one of the 'bot' builds.
I've compiled x86 allmodconfig with clang-18, no warning or link fails.
But I've not tried the specific config being tested.
The link for reproducing the error isn't entirely helpful.

Looking into that error I noticed that clang fails to optimise the
strscpy(tmp_cmdline, boot_command_line, COMMAND_LINE_SIZE) in
init/main.c:setup_boot_config() to a memcpy().
That means it calls strnlen() and then strscpy() - two scans to find
the length is also silly.
(At some point early on that code needs to call a real function to
do all the work instead of inlining everything into the caller.)

David