summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAlejandro Colomar <alx@kernel.org>2023-08-26 01:27:12 +0200
committerAlejandro Colomar <alx@kernel.org>2023-10-20 21:05:33 +0200
commit83c8a2d3fa10e26569bee58fc4bdba428a92c786 (patch)
tree32c89cfff99f05ec70ee8a68d5378da688b858ac
parent7c93e1cdce2a334dc346c7aa564b13cae6d88eb7 (diff)
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 <ipedrosa@redhat.com> Signed-off-by: Alejandro Colomar <alx@kernel.org>
-rw-r--r--lib/Makefile.am2
-rw-r--r--lib/sprintf.c19
-rw-r--r--lib/sprintf.h55
3 files changed, 76 insertions, 0 deletions
diff --git a/lib/Makefile.am b/lib/Makefile.am
index 897f0602..d6b639c6 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 00000000..fee58ca9
--- /dev/null
+++ b/lib/sprintf.c
@@ -0,0 +1,19 @@
+/*
+ * SPDX-FileCopyrightText: 2023, Alejandro Colomar <alx@kernel.org>
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+#include <config.h>
+
+#ident "$Id$"
+
+#include "sprintf.h"
+
+#include <stdarg.h>
+#include <stddef.h>
+#include <stdio.h>
+
+
+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 00000000..a1219f35
--- /dev/null
+++ b/lib/sprintf.h
@@ -0,0 +1,55 @@
+/*
+ * SPDX-FileCopyrightText: 2023, Alejandro Colomar <alx@kernel.org>
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+
+#ifndef SHADOW_INCLUDE_LIB_SPRINTF_H_
+#define SHADOW_INCLUDE_LIB_SPRINTF_H_
+
+
+#include <config.h>
+
+#include <stdarg.h>
+#include <stddef.h>
+#include <stdio.h>
+
+#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