From: Alejandro Colomar Date: Tue, 5 Dec 2023 12:46:23 +0000 (+0100) Subject: lib/: exit_if_null(): Add macro to exit(3) on error X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=90da3213e80a8033d8672715a8c2807540d4c7d6;p=thirdparty%2Fshadow.git lib/: exit_if_null(): Add macro to exit(3) on error Writing an x*() variant function of several functions is unnecessary. It's simpler to write a generic exit_if_null() macro that can be chained with any other calls. With such a macro, the x*() variants can be implemented as one-liner macros that are much easier to read: For example: #define xmalloc(size) exit_if_null(malloc(size)) If an error is detected, log an error, and exit(13). About why 13, I don't really know. It's just what was used previously in xmalloc(). Signed-off-by: Alejandro Colomar --- diff --git a/lib/Makefile.am b/lib/Makefile.am index dc701148e..45d9b1ec2 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -90,6 +90,8 @@ libshadow_la_SOURCES = \ defines.h \ encrypt.c \ env.c \ + exit_if_null.c \ + exit_if_null.h \ exitcodes.h \ faillog.h \ failure.c \ diff --git a/lib/exit_if_null.c b/lib/exit_if_null.c new file mode 100644 index 000000000..9d68eaf54 --- /dev/null +++ b/lib/exit_if_null.c @@ -0,0 +1,10 @@ +// SPDX-FileCopyrightText: 2023-2025, Alejandro Colomar +// SPDX-License-Identifier: BSD-3-Clause + + +#include "config.h" + +#include "exit_if_null.h" + + +extern inline void exit_if_null_(void *p); diff --git a/lib/exit_if_null.h b/lib/exit_if_null.h new file mode 100644 index 000000000..93b6e4756 --- /dev/null +++ b/lib/exit_if_null.h @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: 2023-2025, Alejandro Colomar +// SPDX-License-Identifier: BSD-3-Clause + + +#ifndef SHADOW_INCLUDE_LIB_EXIT_IF_NULL_H_ +#define SHADOW_INCLUDE_LIB_EXIT_IF_NULL_H_ + + +#include "config.h" + +#include +#include +#include +#include +#include + +#include "shadowlog.h" + + +/* + * This macro is used for implementing x*() variants of functions that + * allocate memory, such as xstrdup() for wrapping strdup(3). The macro + * returns the input pointer transparently, with the same type, but + * calls exit(3) if the input is a null pointer (thus, if the allocation + * failed). + */ +#define exit_if_null(p) \ +({ \ + __auto_type p_ = p; \ + \ + exit_if_null_(p_); \ + p_; \ +}) + + +inline void exit_if_null_(void *p); + + +inline void +exit_if_null_(void *p) +{ + if (p == NULL) { + fprintf(log_get_logfd(), "%s: %s\n", + log_get_progname(), strerror(errno)); + exit(13); + } +} + + +#endif // include guard