[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <38428d5e-ead2-bf18-e198-cecd4caeb3e7@gmail.com>
Date: Sun, 27 Jun 2021 21:46:38 +0200
From: "Alejandro Colomar (man-pages)" <alx.manpages@...il.com>
To: glibc <libc-alpha@...rceware.org>
Cc: tech@...nbsd.org, Christoph Hellwig <hch@....de>,
"linux-kernel@...r.kernel.org" <linux-kernel@...r.kernel.org>
Subject: Re: [RFC] strcpys(): New function for copying strings safely
On 6/27/21 9:26 PM, Alejandro Colomar (man-pages) wrote:
>
> It is designed so that usage requires the minimum number of lines of
> code for complete usage (including error handling checks):
>
> [[
> // When we already checked that 'size' is >= 1
> // and truncation is not an issue:
>
> strcpys_np(size, dest, src, NULL);
Also, given how unlikely this case is, I have in my code:
`[[gnu::warn_unused_result]]`
I forgot to talk about it in the definition I sent. I would put that
attribute in the glibc definition, if this is added to glibc.
To ignore it, a simple cast of the result to `(void)` should be enough
(or a more complex macro, like `UNUSED(strcpys_np(...));`).
>
> [[
>
> #include <string.h>
> #include <sys/types.h>
>
>
> [[gnu::nonnull]]
> ssize_t strscpy_np(ssize_t size,
> char dest[static restrict size],
> const char src[static restrict size])
> {
> ssize_t len;
>
> if (size <= 0)
> return -1;
>
> len = strnlen(src, size - 1);
> memcpy(dest, src, len);
> dest[len] = '\0';
>
> return len;
> }
>
> [[gnu::nonnull(2, 3)]]
[[gnu::warn_unused_result]]
> int strcpys_np(ssize_t size,
> char dest[static restrict size],
> const char src[static restrict size],
> ssize_t *restrict len)
> {
> ssize_t l;
>
> l = strscpy_np(size, dest, src);
> if (len)
> *len = l;
>
> if (l == -1)
> return -1;
> if (l >= size)
> return 1;
> return 0;
> }
>
> ]]
--
Alejandro Colomar
Linux man-pages comaintainer; https://www.kernel.org/doc/man-pages/
http://www.alejandro-colomar.es/
Powered by blists - more mailing lists