tech-kern archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

re: Usage of strncpy in the kernel



Martin Husemann writes:
> On Fri, Jan 03, 2025 at 03:45:07PM +0100, Roland Illig wrote:
> > No, strlcpy is fine for string handling, as it expects (null-terminated)
> > strings and also produces them.
> > 
> > It's only strncpy (and probably strncat) that are problematic, as these
> > two are hard to use correctly for handling strings.
>
> The question is wether the source strings are 0 terminated or not.
>
> If they are, strlcpy() is good. If they are not guaranteed to be (like
> sometimes when copying from fixed size descriptors) you need to use
> strncpy() and manually terminate the result.
>
> You can not swap them randomly, they serve different purposes.
> See the last WARNING: section in strlcpy(3).

the warning above this one is also pretty important for some
kernel uses, particularly if the buffer is gonna be written
back to userland.

it's very disappointing to me that strlcpy() didn't keep the
'cleans whole buffer' feature of strncpy().  it has been the
source of at least one bug that i recall, when a strncpy to
strlcpy conversion was passed to copyout().

the problem cases Roland found should be considered carefully
before simply converting to strlcpy(), and we are not going to
remove strncpy() generally.  there are many APIs we do not use
C strings in, and strncpy() is the right method there.  eg,
all the ones where device name (char[16]) is used (note that
these are all ugly and the '16' is usually a magic number, it
would be really keen if someone were to fix this :)


.mrg.


Home | Main Index | Thread Index | Old Index