It was blessed by POSIX.1-2001, and GCC says that it won't go away, possibly ever. memset(3) is dangerous, as the 2nd and 3rd arguments can be accidentally swapped --who remembers what's the order of the 2nd and 3rd parameters to memset(3) without checking the manual page or some code that uses it?--. Some recent compilers may be able to catch that via some warnings, but those are not infalible. And even if compiler warnings could always catch that, the time lost in fixing or checking the docs is lost for no clear gain. Having a sane API that is unambiguous is the Right Thing (tm); and that API is bzero(3). If someone doesn't believe memset(3) is error-prone, please read the book "Unix Network Programming", Volume 1, 3rd Edition by Stevens, et al., Section 1.2. See a stackoverflow reference in the link below[1]. bzero(3) had a bad fame in the bad old days, because some ancient systems (I'm talking of many decades ago) shipped a broken version of bzero(3). We can assume that all systems in which current shadow utils can be built, have a working version of bzero(3) --if not, please fix your broken system; don't blame the programmer--. One reason that some use today to avoid bzero(3) in favor of memset(3) is that memset(3) is more often used; but that's a circular reasoning. Even if bzero(3) wasn't supported by the system, it would need to be invented. It's the right API. Another reason that some argue is that POSIX.1-2008 removed the specification of bzero(3). That's not a problem, because GCC will probably support it forever, and even if it didn't, we can redefine it like we do with memzero(). bzero(3) is just a one-liner wrapper around memset(3). Link: [1] <https://stackoverflow.com/a/17097978> Cc: Christian Göttsche <cgzones@googlemail.com> Cc: Serge Hallyn <serge@hallyn.com> Cc: Iker Pedrosa <ipedrosa@redhat.com> Signed-off-by: Alejandro Colomar <alx@kernel.org>
50 lines
872 B
C
50 lines
872 B
C
/*
|
|
* SPDX-FileCopyrightText: 2022-2023, Christian Göttsche <cgzones@googlemail.com>
|
|
* SPDX-FileCopyrightText: 2023, Alejandro Colomar <alx@kernel.org>
|
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
*/
|
|
|
|
|
|
#ifndef SHADOW_INCLUDE_LIBMISC_MEMZERO_H_
|
|
#define SHADOW_INCLUDE_LIBMISC_MEMZERO_H_
|
|
|
|
|
|
#include <config.h>
|
|
|
|
#include <stddef.h>
|
|
#include <string.h>
|
|
#include <strings.h>
|
|
|
|
#include "sizeof.h"
|
|
|
|
|
|
#define MEMZERO(arr) memzero(arr, SIZEOF_ARRAY(arr))
|
|
|
|
|
|
inline void memzero(void *ptr, size_t size);
|
|
inline void strzero(char *s);
|
|
|
|
|
|
inline void
|
|
memzero(void *ptr, size_t size)
|
|
{
|
|
#if defined(HAVE_MEMSET_EXPLICIT)
|
|
memset_explicit(ptr, 0, size);
|
|
#elif defined(HAVE_EXPLICIT_BZERO)
|
|
explicit_bzero(ptr, size);
|
|
#else
|
|
bzero(ptr, size);
|
|
__asm__ __volatile__ ("" : : "r"(ptr) : "memory");
|
|
#endif
|
|
}
|
|
|
|
|
|
inline void
|
|
strzero(char *s)
|
|
{
|
|
memzero(s, strlen(s));
|
|
}
|
|
|
|
|
|
#endif // include guard
|