Re: [PATCH] scsi: hpsa: Replace deprecated strncpy() with strscpy()
From: Bart Van Assche
Date: Thu Feb 13 2025 - 12:40:55 EST
On 2/13/25 3:24 AM, Thorsten Blum wrote:
This subtle difference between strncpy() and strscpy() regarding the
number of bytes copied isn't really documented anywhere, is it? The
documentation I came across so far seems to focus mostly on the
different return values of the two functions.
From the description of commit 9022ed0e7e65 ("strscpy: write destination
buffer only once"):
So strscpy not only guarantees NUL-termination (unlike strncpy), it
also
doesn't do unnecessary padding at the destination. But at the same
time
also avoids byte-at-a-time reads and writes by _allowing_ some
extra NUL
writes - within the size, of course - so that the whole copy can be
done
with word operations.
It is also stable in the face of a mutable source string: it explicitly
does not read the source buffer multiple times (so an implementation
using "strnlen()+memcpy()" would be wrong), and does not read the
source
buffer past the size (like the mis-design that is strlcpy does).
Finally, the return value is designed to be simple and unambiguous: if
the string cannot be copied fully, it returns an actual negative error,
making error handling clearer and simpler (and the caller already knows
the size of the buffer). Otherwise it returns the string length of the
result.
More information is available in the description of commit 30c44659f4a3
("Merge branch 'strscpy' of
git://git.kernel.org/pub/scm/linux/kernel/git/cmetcalf/linux-tile").
Thanks,
Bart.