[LTP] [PATCH 1/6] lib: tst_buffers: Add bufs .str and tst_aprintf()
Cyril Hrubis
chrubis@suse.cz
Fri Aug 11 13:56:41 CEST 2023
Signed-off-by: Cyril Hrubis <chrubis@suse.cz>
---
include/tst_buffers.h | 11 +++++++++++
lib/tst_buffers.c | 28 +++++++++++++++++++++++++---
2 files changed, 36 insertions(+), 3 deletions(-)
diff --git a/include/tst_buffers.h b/include/tst_buffers.h
index d19ac8cf0..b5f355f0f 100644
--- a/include/tst_buffers.h
+++ b/include/tst_buffers.h
@@ -25,6 +25,11 @@ struct tst_buffers {
* Array of iov buffer sizes terminated by -1.
*/
int *iov_sizes;
+ /*
+ * If size and iov_sizes is NULL this is the string we want to strdup()
+ * into the buffer.
+ */
+ char *str;
};
/*
@@ -46,6 +51,12 @@ char *tst_strdup(const char *str);
*/
void *tst_alloc(size_t size);
+/*
+ * Printf into a guarded buffer.
+ */
+char *tst_aprintf(const char *fmt, ...)
+ __attribute__((format (printf, 1, 2)));
+
/*
* Allocates iovec structure including the buffers.
*
diff --git a/lib/tst_buffers.c b/lib/tst_buffers.c
index b8b597a12..b0bd359eb 100644
--- a/lib/tst_buffers.c
+++ b/lib/tst_buffers.c
@@ -5,6 +5,7 @@
#include <sys/mman.h>
#include <stdlib.h>
+#include <stdio.h>
#define TST_NO_DEFAULT_MAIN
#include "tst_test.h"
@@ -76,6 +77,25 @@ void *tst_alloc(size_t size)
return ret + map->buf_shift;
}
+char *tst_aprintf(const char *fmt, ...)
+{
+ va_list va;
+ int len;
+ char *ret;
+
+ va_start(va, fmt);
+ len = vsnprintf(NULL, 0, fmt, va)+1;
+ va_end(va);
+
+ ret = tst_alloc(len);
+
+ va_start(va, fmt);
+ vsprintf(ret, fmt, va);
+ va_end(va);
+
+ return ret;
+}
+
static int count_iovec(int *sizes)
{
int ret = 0;
@@ -115,15 +135,17 @@ void tst_buffers_alloc(struct tst_buffers bufs[])
for (i = 0; bufs[i].ptr; i++) {
if (bufs[i].size)
*((void**)bufs[i].ptr) = tst_alloc(bufs[i].size);
- else
+ else if (bufs[i].iov_sizes)
*((void**)bufs[i].ptr) = tst_iovec_alloc(bufs[i].iov_sizes);
+ else
+ *((void**)bufs[i].ptr) = tst_strdup(bufs[i].str);
}
}
char *tst_strdup(const char *str)
{
- size_t len = strlen(str);
- char *ret = tst_alloc(len + 1);
+ char *ret = tst_alloc(strlen(str) + 1);
+
return strcpy(ret, str);
}
--
2.41.0
More information about the ltp
mailing list