From e2fcf5f92c2405f30dac3e083d0aafcc98596983 Mon Sep 17 00:00:00 2001 From: Sergey Lyubka Date: Mon, 30 May 2022 18:40:44 +0100 Subject: [PATCH] Fix #1565 - mg_snprintf %.*s with zero len printing --- mongoose.c | 5 +++-- src/str.c | 5 +++-- test/unit_test.c | 1 + 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/mongoose.c b/mongoose.c index 0e249e4c..dfff4278 100644 --- a/mongoose.c +++ b/mongoose.c @@ -4918,7 +4918,7 @@ size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list ap) { size_t i = 0, n = 0; while (fmt[i] != '\0') { if (fmt[i] == '%') { - size_t j, k, x = 0, is_long = 0, w = 0 /* width */, pr = 0 /* prec */; + size_t j, k, x = 0, is_long = 0, w = 0 /* width */, pr = ~0U /* prec */; char pad = ' ', minus = 0, c = fmt[++i]; if (c == '#') x++, c = fmt[++i]; if (c == '-') minus++, c = fmt[++i]; @@ -4930,6 +4930,7 @@ size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list ap) { pr = (size_t) va_arg(ap, int); c = fmt[++i]; } else { + pr = 0; while (is_digit(c)) pr *= 10, pr += (size_t) (c - '0'), c = fmt[++i]; } } @@ -4968,7 +4969,7 @@ size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list ap) { n++; } else if (c == 's') { char *p = va_arg(ap, char *); - if (pr == 0) pr = p == NULL ? 0 : strlen(p); + if (pr == ~0U) pr = p == NULL ? 0 : strlen(p); for (j = 0; !minus && pr < w && j + pr < w; j++) n += mg_copys(buf, len, n, &pad, 1); n += mg_copys(buf, len, n, p, pr); diff --git a/src/str.c b/src/str.c index cb5693bf..b6fb5b04 100644 --- a/src/str.c +++ b/src/str.c @@ -286,7 +286,7 @@ size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list ap) { size_t i = 0, n = 0; while (fmt[i] != '\0') { if (fmt[i] == '%') { - size_t j, k, x = 0, is_long = 0, w = 0 /* width */, pr = 0 /* prec */; + size_t j, k, x = 0, is_long = 0, w = 0 /* width */, pr = ~0U /* prec */; char pad = ' ', minus = 0, c = fmt[++i]; if (c == '#') x++, c = fmt[++i]; if (c == '-') minus++, c = fmt[++i]; @@ -298,6 +298,7 @@ size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list ap) { pr = (size_t) va_arg(ap, int); c = fmt[++i]; } else { + pr = 0; while (is_digit(c)) pr *= 10, pr += (size_t) (c - '0'), c = fmt[++i]; } } @@ -336,7 +337,7 @@ size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list ap) { n++; } else if (c == 's') { char *p = va_arg(ap, char *); - if (pr == 0) pr = p == NULL ? 0 : strlen(p); + if (pr == ~0U) pr = p == NULL ? 0 : strlen(p); for (j = 0; !minus && pr < w && j + pr < w; j++) n += mg_copys(buf, len, n, &pad, 1); n += mg_copys(buf, len, n, p, pr); diff --git a/test/unit_test.c b/test/unit_test.c index fa64b4f8..8ad5b1c5 100644 --- a/test/unit_test.c +++ b/test/unit_test.c @@ -1329,6 +1329,7 @@ static void test_str(void) { ASSERT(sn("%d", 0)); ASSERT(sn("%d", 1)); ASSERT(sn("%d", -1)); + ASSERT(sn("%.*s", 0, "ab")); ASSERT(sn("%.*s", 1, "ab")); ASSERT(sn("%.1s", "ab")); ASSERT(sn("%.99s", "a"));