From: Alejandro Colomar Date: Wed, 15 Nov 2023 21:31:02 +0000 (+0100) Subject: lib/strncpy.h: Add STRNCPY() wrapper for strncpy(3) X-Git-Tag: 4.15.0-rc1~121 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=225530b7e111adf7481c3e3ac172b386194c231c;p=thirdparty%2Fshadow.git lib/strncpy.h: Add STRNCPY() wrapper for strncpy(3) This wrapper calculates the destination buffer's size, to avoid errors in the size calculation. A curious fact: this macro did exist in Version 7 Unix (with a slightly different name). I found it by chance, investigating the origins of strncpy(3) and strncat(3) in V7, after Branden suggested me to do so, related to recent discussions about string_copying(7). alx@debian:~/src/unix/unix/Research-V7$ grepc SCPYN . ./usr/src/cmd/login.c:#define SCPYN(a, b) strncpy(a, b, sizeof(a)) Our implementation is slightly better, because using nitems() we're protected against passing a pointer instead of an array, and it's also conceptually more appropriate: for wide characters, it would be #define WCSNCPY(dst, src) wcsncpy(dst, src, NITEMS(dst)) Cc: "G. Branden Robinson" Signed-off-by: Alejandro Colomar --- diff --git a/lib/Makefile.am b/lib/Makefile.am index 96dfefe2e..bfe13c33b 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -141,6 +141,7 @@ libshadow_la_SOURCES = \ stpecpy.h \ stpeprintf.c \ stpeprintf.h \ + strncpy.h \ strtcpy.c \ strtcpy.h \ strtoday.c \ diff --git a/lib/strncpy.h b/lib/strncpy.h new file mode 100644 index 000000000..fc6fcc963 --- /dev/null +++ b/lib/strncpy.h @@ -0,0 +1,21 @@ +/* + * SPDX-FileCopyrightText: 2023, Alejandro Colomar + * SPDX-License-Identifier: BSD-3-Clause + */ + + +#ifndef SHADOW_INCLUDE_LIB_STRNCPY_H_ +#define SHADOW_INCLUDE_LIB_STRNCPY_H_ + + +#include + +#include + +#include "sizeof.h" + + +#define STRNCPY(dst, src) strncpy(dst, src, NITEMS(dst)) + + +#endif // include guard