Re: Usage of strncpy in the kernel

David Holland <[email protected]>
Newsgroups gmane.os.netbsd.devel.kernel
Message-ID <[email protected]>
On Sat, Jan 04, 2025 at 01:47:02PM +0100, Roland Illig wrote:
 > > On 2025-01-04 11:14, David Holland wrote:
 > >> maybe something like
 > >>
 > >> strlcpy_tofixed(char *dest, size_t destlen, const char *src);
 > >> strlcpy_fromfixed(char *dest, size_t destmax, const char *src, size_t srclen);
 > >>
 > >> and
 > >>
 > >> strlcpy_zerofill(char *dest, const char *src, size_t destmax);
 > 
 > I like these proposals, as their names clearly communicate their
 > purpose, and when looking at the code during an audit, I can quickly see
 > that the copying takes place correctly, by looking at only a single
 > function call. The functions should not be called "strlcpy" though, as
 > that implies that they perform a strlen(src). 

?

I used the "l" because like strlcpy they (should) check all the
lengths and won't overrun.

 > Simply calling them "strcpy" should suffice. The size_t parameters
 > should all be called "size" instead of "len" or "max".

There's a distinction there (length of a fixed-sized field vs. max
size of a buffer) that shouldn't be discarded. It's a cue to the
consumer of the interface; not necessarily a strong one but any little
bit can sometimes be that hint that makes you go "wait a sec".

"len" vs. "size" is endlessly debatable, especially for char, but I
tend to favor "length" for strings (and "num" or maybe "count" for
arrays) because it's clearer about what the units are.


FWIW, the general problem with size is as follows:

   void foo(long *ptr, unsigned size);

Is that size in size_t units (that is, bytes) or longs? Either of
these is unambiguous and should therefore be preferred:

   void foo(long *ptr, unsigned num);
   void foo(long *ptr, unsigned bytes);

Similarly if you have void bar (wchar_t *ptr, unsigned size) it could
reasonably be interpreted as either bytes or wchars, while "len" is
unambiguous.

-- 
David A. Holland
[email protected]
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.