tech-kern archive

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

Re: Usage of strncpy in the kernel



At Mon, 6 Jan 2025 03:00:16 +0000, David Holland <dholland-tech%netbsd.org@localhost> wrote:
Subject: Re: Usage of strncpy in the kernel
>
> On Sun, Jan 05, 2025 at 06:01:56PM -0800, Greg A. Woods wrote:
>  > > > > I used the "l" because like strlcpy they (should) check all the
>  > > > > lengths and won't overrun.
>  > > >
>  > > > I think you may be confusing strlcpy() and strlcat().
>  > >
>  > > Huh? The difference between strcpy and strlcpy is the "l" and the
>  > > length checking.
>  >
>  > As I said, there is no "length" checking in strlcpy() _unless_ perhaps
>  > one confuses truncation checking with length checking, but even then the
>  > truncation checking is left to the caller and it is only tangentially
>  > related to the 'size' parameter.
>
> The _point_ of strlcpy is that it checks the _destination_ length,
> like plain strcpy doesn't.

That's the _myth_ of strlcpy(), but I'm not seeing it.

Perhaps you could explain what you mean by "checks the destination
length", and how it does that differently than strncpy(), and perhaps
show the line(s) of code in /usr/src/common/lib/libc/string/strlcpy.c
which do this check.

Note too I've been comparing strlcpy() to strncpy(), not strcpy(), since
obviously the latter doesn't accept any 'size' parameter.  Apples to
apples.

In my understanding both from reading the source of both strlcpy() and
strncpy() that both simply blindly trust the 'size' parameter and copy
up to that many bytes into the memory object pointed to by the 'dst'
parameter.  There's no way for either one to "check" the length of that
memory object.  If strlcpy() "checks" the length of the destination
object then surely strncpy() must do exactly the same "check", e.g. if
both are called with the same arguments (modulo +/-1 for the 'size'
parameter).

In hindsight I might have called strlcpy(), given its current
specification and implementation, something like strscpy(); with the 's'
for "size" (i.e. it wants the buffer 's'ize, not a string 'l'ength).
The automatic NUL-termination doesn't really need any special indication
in the name because that's what the other 'str' functions do/expect if
they don't have an 'n' in their name.

Myths are powerful, but they don't guarantee better safety.  All
strlcpy() does extra is guarantee NUL-termination, a step that some
programmers apparently forget, possibly because their thinking is
clouded by myths about C strings vs char arrays.

--
					Greg A. Woods <gwoods%acm.org@localhost>

Kelowna, BC     +1 250 762-7675           RoboHack <woods%robohack.ca@localhost>
Planix, Inc. <woods%planix.com@localhost>     Avoncote Farms <woods%avoncote.ca@localhost>

Attachment: pgpk2YZcc_tni.pgp
Description: OpenPGP Digital Signature



Home | Main Index | Thread Index | Old Index