Re: kernfs: Prefer strscpy over strlcpy calls

From: Linus Torvalds
Date: Wed May 10 2023 - 01:42:41 EST


On Tue, May 9, 2023 at 5:30 PM Azeem Shaikh <azeemshaikh38@xxxxxxxxx> wrote:
>
> +/* strscpy_mock_strlcpy - imitates strlcpy API but uses strscpy underneath. */
> +static size_t strscpy_mock_strlcpy(char *dest, const char *src, size_t count)
> +{
> + strscpy(dest, src, count);
> + return strlen(src);

Absolutely not.

This makes the whole exercise pointless.

The reason to use strscpy() is to *avoid* doing the strlen() on the
source, and limit things to the limited size.

If you need to do the strlen(), then use strlcpy(). It's a broken
interface, but creating this kind of horror wrapper that does the same
thing as strlcpy() is worse than just using the regular version.

So the strscpy() conversion should *only* be done if the caller
doesn't care about the difference in return values (or done *together*
with changing the caller to use the nicer strscpy() return value).

It's also worth noting that 'strscpy()' not only returns a negative
error value when the string doesn't fit - it will also possibly do the
copy one word at a time, and may write extra zeroes at the end of the
destination (all within the given size, of course).

So strscpy() is _different_ from strlcpy(), and the conversion should
not be done unless those differences are ok.

Linus