Re: [PATCH next 2/3] fortify: Optimise strnlen()
From: David Laight
Date: Fri Apr 03 2026 - 04:55:44 EST
On Tue, 31 Mar 2026 16:51:26 -0700
Kees Cook <kees@xxxxxxxxxx> 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.
>
Thinks further.
Can you remember anywhere where:
len = __builtin_strlen(x);
if (__builtin_constant_p(len))
...
actually called strlen() for a non-constant string.
I did do some tests and it was always optimised away.
I might try getting all this code to use a renamed strlen() and
then scan the entire kernel for references to strlen() itself.
There might be a small number of valid ones, but I'd expect most
would come from the compiler.
(Or get the compiler to generate 'rep scasb' and look for that.)
I suspect it might be enough to check that both str and str[0]
are constant before calling __builtin_strlen() and then check
the returned length is constant.
All the checks might be needed for:
str = cond ? "four" : "f\0ur";
since the compile might realise that str[0] is always 'f' and
str[4] always 0 - but strlen differs.
However I suspect that __builtin_constant_p(array[index]) currently
requires that both the array and index are constant.
So testing array[0] is equivalent.
Given it needs all the separate paths, writing strscpy with:
if (__builtin_constant_p(src[0]) {
len = __builtin_strlen(src);
if (__builtin_constant_p(len)) {
/* code for constant length */
return xxx;
}
}
/* code for non-constant length */
One thing I did notice is that for:
char src[32];
char dst[32];
void func(void)
{
strscpy(dst, src, 32);
}
it seems to generate a call to strnlen() followed by a call to
strscpy_sized().
That seems wrong, since all three lengths are 32 it should be
safe to just call strscpy_sized().
And having done the strnlen() it ought to use memcpy().
But, really most of that ought to be moved into the called function.
So you want:
int strcpy_sized(char *dst, const char *src, size_t dst_len, size_t src_len);
where the wrapper fills in src_len.
David