From: Alejandro Colomar Date: Fri, 25 Aug 2023 23:27:12 +0000 (+0200) Subject: lib/sprintf.[ch]: Add x[v]asprintf() X-Git-Tag: 4.15.0-rc1~154 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=83c8a2d3fa10e26569bee58fc4bdba428a92c786;p=thirdparty%2Fshadow.git lib/sprintf.[ch]: Add x[v]asprintf() As other x...() wrappers around functions that allocate, these wrappers are like [v]asprintf(3), but exit on failure. Reviewed-by: Iker Pedrosa Signed-off-by: Alejandro Colomar --- diff --git a/lib/Makefile.am b/lib/Makefile.am index 897f0602f..d6b639c60 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -133,6 +133,8 @@ libshadow_la_SOURCES = \ shell.c \ sizeof.h \ spawn.c \ + sprintf.c \ + sprintf.h \ sssd.c \ sssd.h \ stpecpy.c \ diff --git a/lib/sprintf.c b/lib/sprintf.c new file mode 100644 index 000000000..fee58ca9e --- /dev/null +++ b/lib/sprintf.c @@ -0,0 +1,19 @@ +/* + * SPDX-FileCopyrightText: 2023, Alejandro Colomar + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +#ident "$Id$" + +#include "sprintf.h" + +#include +#include +#include + + +extern inline int xasprintf(char **restrict s, const char *restrict fmt, ...); +extern inline int xvasprintf(char **restrict s, const char *restrict fmt, + va_list ap); diff --git a/lib/sprintf.h b/lib/sprintf.h new file mode 100644 index 000000000..a1219f35d --- /dev/null +++ b/lib/sprintf.h @@ -0,0 +1,55 @@ +/* + * SPDX-FileCopyrightText: 2023, Alejandro Colomar + * SPDX-License-Identifier: BSD-3-Clause + */ + + +#ifndef SHADOW_INCLUDE_LIB_SPRINTF_H_ +#define SHADOW_INCLUDE_LIB_SPRINTF_H_ + + +#include + +#include +#include +#include + +#include "defines.h" + + +format_attr(printf, 2, 3) +inline int xasprintf(char **restrict s, const char *restrict fmt, ...); +format_attr(printf, 2, 0) +inline int xvasprintf(char **restrict s, const char *restrict fmt, va_list ap); + + +inline int +xasprintf(char **restrict s, const char *restrict fmt, ...) +{ + int len; + va_list ap; + + va_start(ap, fmt); + len = xvasprintf(s, fmt, ap); + va_end(ap); + + return len; +} + + +inline int +xvasprintf(char **restrict s, const char *restrict fmt, va_list ap) +{ + int len; + + len = vasprintf(s, fmt, ap); + if (len == -1) { + perror("asprintf"); + exit(EXIT_FAILURE); + } + + return len; +} + + +#endif // include guard