summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorThomas Weißschuh <thomas.weissschuh@linutronix.de>2025-04-11 11:00:50 +0200
committerThomas Weißschuh <linux@weissschuh.net>2025-04-22 10:59:03 +0200
commit9f4a2e28bc4714487d9a0c85af2a87c07155c552 (patch)
tree173388bd89ec4c082b8f2c2410c6a20e49027eb3
parentf7b3eeffd402c5eec32be9c3bfdeb3ec03e87cf3 (diff)
tools/nolibc: allow limiting of printf destination size
snprintf() allows limiting the output buffer, while still returning the number of all bytes that would have been written. Implement the limitation logic in preparation for snprintf(). Signed-off-by: Thomas Weißschuh <thomas.weissschuh@linutronix.de> Acked-by: Willy Tarreau <w@1wt.eu>
-rw-r--r--tools/include/nolibc/stdio.h16
1 files changed, 10 insertions, 6 deletions
diff --git a/tools/include/nolibc/stdio.h b/tools/include/nolibc/stdio.h
index 5c893b4903a3..b17b473bd875 100644
--- a/tools/include/nolibc/stdio.h
+++ b/tools/include/nolibc/stdio.h
@@ -215,13 +215,13 @@ char *fgets(char *s, int size, FILE *stream)
*/
typedef int (*__nolibc_printf_cb)(intptr_t state, const char *buf, size_t size);
-static __attribute__((unused, format(printf, 3, 0)))
-int __nolibc_printf(__nolibc_printf_cb cb, intptr_t state, const char *fmt, va_list args)
+static __attribute__((unused, format(printf, 4, 0)))
+int __nolibc_printf(__nolibc_printf_cb cb, intptr_t state, size_t n, const char *fmt, va_list args)
{
char escape, lpref, c;
unsigned long long v;
unsigned int written;
- size_t len, ofs;
+ size_t len, ofs, w;
char tmpbuf[21];
const char *outstr;
@@ -306,8 +306,12 @@ int __nolibc_printf(__nolibc_printf_cb cb, intptr_t state, const char *fmt, va_l
outstr = fmt;
len = ofs - 1;
flush_str:
- if (cb(state, outstr, len) != 0)
- break;
+ if (n) {
+ w = len < n ? len : n;
+ n -= w;
+ if (cb(state, outstr, w) != 0)
+ break;
+ }
written += len;
do_escape:
@@ -331,7 +335,7 @@ static int __nolibc_fprintf_cb(intptr_t state, const char *buf, size_t size)
static __attribute__((unused, format(printf, 2, 0)))
int vfprintf(FILE *stream, const char *fmt, va_list args)
{
- return __nolibc_printf(__nolibc_fprintf_cb, (intptr_t)stream, fmt, args);
+ return __nolibc_printf(__nolibc_fprintf_cb, (intptr_t)stream, SIZE_MAX, fmt, args);
}
static __attribute__((unused, format(printf, 1, 0)))