From 1becad43298e74ba73bc66f9d44523e5d121c667 Mon Sep 17 00:00:00 2001 From: jvoisin Date: Mon, 20 May 2024 14:48:35 +0200 Subject: Add vasprintf/asprintf The only hardening being done here is to set the char** parameter to thos functions to NULL in case of an error, to prevent it from being used should people forget to check return values. This is already done on some BSD, as well as in Rocky Linux. --- tests/Makefile | 8 +++++--- tests/test_asprintf.c | 20 ++++++++++++++++++++ tests/test_vasprintf.c | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 tests/test_asprintf.c create mode 100644 tests/test_vasprintf.c (limited to 'tests') diff --git a/tests/Makefile b/tests/Makefile index c18898e..32b17b0 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -1,4 +1,4 @@ -CFLAGS+=-I../include/ -D_FORTIFY_SOURCE=3 -static -O2 -DPEDANTIC_CHECKS +CFLAGS+=-I../include/ -D_FORTIFY_SOURCE=3 -static -O2 -DPEDANTIC_CHECKS -Wno-format COMPTIME_TARGETS= \ test_memcpy_overwrite_under \ @@ -12,6 +12,7 @@ RUNTIME_TARGETS= \ test_FD_SET_negative \ test_FD_ISSET_SETSIZE \ test_FD_ISSET_negative \ + test_asprintf \ test_bcopy_dynamic_read \ test_bcopy_dynamic_write \ test_bcopy_static_read \ @@ -126,11 +127,12 @@ RUNTIME_TARGETS= \ test_ttyname_r_dynamic \ test_ttyname_r_static \ test_umask \ + test_vasprintf \ + test_vfprintf \ + test_vprintf \ test_vsnprintf_dynamic \ test_vsnprintf_static \ test_vsprintf \ - test_vfprintf \ - test_vprintf \ test_wcscat_static_write \ test_wcscpy_static_write \ test_wcsncat_static_write \ diff --git a/tests/test_asprintf.c b/tests/test_asprintf.c new file mode 100644 index 0000000..a02d110 --- /dev/null +++ b/tests/test_asprintf.c @@ -0,0 +1,20 @@ +#define _GNU_SOURCE +#include "common.h" + +#include +#include +#include + +int main(int argc, char** argv) { + char* buf; + asprintf(&buf, "total: %d+%d=%d", 1, 2, 3); + puts(buf); + free(buf); + +#ifndef __clang__ + asprintf(&buf, "total: %", 1); + assert(buf == NULL); +#endif + + return 0; +} diff --git a/tests/test_vasprintf.c b/tests/test_vasprintf.c new file mode 100644 index 0000000..2f71714 --- /dev/null +++ b/tests/test_vasprintf.c @@ -0,0 +1,36 @@ +#define _GNU_SOURCE +#include "common.h" + +#include +#include +#include +#include + +void test(const char *fmt, ...) +{ + char* buf; + va_list args; + va_start(args, fmt); + vasprintf(&buf, fmt, args); + va_end(args); + puts(buf); + free(buf); +} + +void test2(const char *fmt, ...) +{ + char* buf; + va_list args; + va_start(args, fmt); + vasprintf(&buf, fmt, args); + va_end(args); + assert(buf == NULL); +} + +int main(int argc, char** argv) { + test("Total: %d+%d=%d", 1, 2, 3); +#ifndef __clang__ + test2("Total: %", 1, 2, 3); +#endif + return 0; +} -- cgit v1.3