memzero.[ch]: Define memzero() and strzero() as inline functions

There's no need to have these as macros, so use functions, which are a
lot safer: there's no need to worry about multiple evaluation of args,
and there's also more type safety.  Compiler warnings are also simpler,
as they don't dump all the nested macros.

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>
This commit is contained in:
Alejandro Colomar
2023-07-30 13:30:47 +02:00
committed by Iker Pedrosa
parent fca2fd65c0
commit 2daa6cc65d
3 changed files with 37 additions and 8 deletions

View File

@@ -85,6 +85,7 @@ libshadow_la_SOURCES = \
mail.c \
mempcpy.c \
mempcpy.h \
memzero.c \
memzero.h \
motd.c \
myname.c \

17
lib/memzero.c Normal file
View File

@@ -0,0 +1,17 @@
/*
* SPDX-FileCopyrightText: 2023, Alejandro Colomar <alx@kernel.org>
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <config.h>
#ident "$Id$"
#include <stddef.h>
#include "memzero.h"
extern inline void memzero(void *ptr, size_t size);
extern inline void strzero(char *s);

View File

@@ -1,5 +1,6 @@
/*
* SPDX-FileCopyrightText: 2022-2023, Christian Göttsche <cgzones@googlemail.com>
* SPDX-FileCopyrightText: 2023, Alejandro Colomar <alx@kernel.org>
* SPDX-License-Identifier: BSD-3-Clause
*/
@@ -15,19 +16,29 @@
#include <strings.h>
#ifdef HAVE_MEMSET_EXPLICIT
# define memzero(ptr, size) memset_explicit((ptr), 0, (size))
#elif defined HAVE_EXPLICIT_BZERO
# define memzero(ptr, size) explicit_bzero((ptr), (size))
#else
static inline void memzero(void *ptr, size_t size)
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
ptr = memset(ptr, '\0', size);
__asm__ __volatile__ ("" : : "r"(ptr) : "memory");
}
#endif
}
#define strzero(s) memzero(s, strlen(s)) /* warning: evaluates twice */
inline void
strzero(char *s)
{
memzero(s, strlen(s));
}
#endif // include guard