[PATCH] arm64/sysreg: refactor deprecated strncpy

From: Justin Stitt
Date: Thu Aug 10 2023 - 14:40:34 EST


`strncpy` is deprecated for use on NUL-terminated destination strings
[1]. Which seems to be the case here due to the forceful setting of `buf`'s
tail to 0.

A suitable replacement is `strscpy` [2] due to the fact that it
guarantees NUL-termination on its destination buffer argument which is
_not_ the case for `strncpy`!

In this case, there is some behavior being used in conjunction with
`strncpy` that `strscpy` already implements. This means we can drop some
of the extra stuff like `... -1` and `buf[len] = 0`

This should have no functional change and yet uses a more robust and
less ambiguous interface whilst reducing code complexity.

Link: www.kernel.org/doc/html/latest/process/deprecated.html#strncpy-on-nul-terminated-strings[1]
Link: https://manpages.debian.org/testing/linux-manual-4.8/strscpy.9.en.html [2]
Link: https://github.com/KSPP/linux/issues/90
Cc: linux-hardening@xxxxxxxxxxxxxxx

Signed-off-by: Justin Stitt <justinstitt@xxxxxxxxxx>
---
For reference, see a part of `strscpy`'s implementation here:

| /* Hit buffer length without finding a NUL; force NUL-termination. */
| if (res)
| dest[res-1] = '\0';

Note: compile tested
---
arch/arm64/kernel/idreg-override.c | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/arch/arm64/kernel/idreg-override.c b/arch/arm64/kernel/idreg-override.c
index 2fe2491b692c..482dc5c71e90 100644
--- a/arch/arm64/kernel/idreg-override.c
+++ b/arch/arm64/kernel/idreg-override.c
@@ -262,9 +262,8 @@ static __init void __parse_cmdline(const char *cmdline, bool parse_aliases)
if (!len)
return;

- len = min(len, ARRAY_SIZE(buf) - 1);
- strncpy(buf, cmdline, len);
- buf[len] = 0;
+ len = min(len, ARRAY_SIZE(buf));
+ strscpy(buf, cmdline, len);

if (strcmp(buf, "--") == 0)
return;

---
base-commit: 52a93d39b17dc7eb98b6aa3edb93943248e03b2f
change-id: 20230810-strncpy-arch-arm64-1f3d328bd9b8

Best regards,
--
Justin Stitt <justinstitt@xxxxxxxxxx>