Re: [PATCH] RISC-V: cpu: refactor deprecated strncpy

From: Jessica Clarke
Date: Tue Aug 01 2023 - 19:02:30 EST

On 1 Aug 2023, at 22:14, Justin Stitt <justinstitt@xxxxxxxxxx> wrote:
> `strncpy` is deprecated for use on NUL-terminated destination strings [1].
> 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`!
> The `sv_type` buffer is declared with a size of 16 which is then
> followed by some `strncpy` calls to populate the buffer with one of:
> "sv32", "sv57", "sv48", "sv39" or "none". Hard-coding the max length as 5 is
> error-prone and involves counting the number of characters (and
> hopefully not forgetting to count the NUL-byte) in the raw string.
> Using a pre-determined max length in combination with `strscpy` provides
> a cleaner, less error-prone as well as a less ambiguous implementation.
> `strscpy` guarantees that it's destination buffer is NUL-terminated even
> if it's source argument exceeds the max length as defined by the third
> argument.

I would imagine you’d want a BUG_ON() rather than silent truncation if
that ever happened (well, silent if you ignore it then printing the
truncated string).

Though really you just want a static_strcpy that looks at sizeof* for
source and destination and fails to build if it doesn’t fit; there’s no
reason this needs to be found at run time.

(* and __builtin_types_compatible_p(char[], ...))