[Mesa-dev] [PATCH v6 1/3] util: Add util_strlcpy

Gustaw Smolarczyk wielkiegie at gmail.com
Wed Jul 5 07:43:57 UTC 2017


2017-07-05 8:57 GMT+02:00 Robert Foss <robert.foss at collabora.com>:
> Add local strlcpy implementation.
>
> Signed-off-by: Robert Foss <robert.foss at collabora.com>
> ---
> Changes since v5:
>   Actually include changes from v5 in patch
>
> Changes since v4:
>   Gustaw Smolarczyk <wielkiegie at gmail.com>
>    - Make util_strlcpy have the same behaviour as strlcpy
>
> Changes since v3:
>   Matt Turner <mattst88 at gmail.com>
>    - Change name of util_strncpy to util_strlcpy
>
> Changes since v2:
>   Brian Paul <brianp at vmware.com>
>     - Patch added
>
>
>  src/util/u_string.h | 9 +++++++++
>  1 file changed, 9 insertions(+)
>
> diff --git a/src/util/u_string.h b/src/util/u_string.h
> index e88e13f42c..bbabcbc7cb 100644
> --- a/src/util/u_string.h
> +++ b/src/util/u_string.h
> @@ -48,6 +48,15 @@
>  extern "C" {
>  #endif
>
> +static inline size_t
> +util_strlcpy(char *dst, const char *src, size_t n)
> +{
> +   strncpy(dst, src, n);
> +   dst[n-1] = '\0';
> +
> +   return strnlen(src, n);

I don't think you can use strnlen here. strlcpy returns the number of
characters in src without any restrictions. If src happens not to be
null-terminated, it is already undefined behavior (and strnlen won't
necessarily help if src is just before an unmapped page and n is
sufficiently large). In general, you shouldn't use strn* functions
when working with null-terminated strings.

You might also use strlen+memcpy instead of strncpy+strlen to
potentially achieve higher performance (strlen and memcpy are probably
ones of the most optimized functions in any runtime). Maybe something
like this:

static inline size_t
util_strlcpy(char *dst, const char *src, size_t n)
{
   const size_t src_len = strlen(src);

   if (src_len < n) {
      memcpy(dst, src, src_len + 1);
   } else {
      memcpy(dst, src, n - 1);
      dst[n - 1] = '\0';
   }

   return src_len;
}

> +}
> +
>  #ifdef _GNU_SOURCE
>
>  #define util_strchrnul strchrnul
> --
> 2.11.0
>


More information about the mesa-dev mailing list