From ac0d957f26a8214835df6cfcd0bfcd89d6ce863e Mon Sep 17 00:00:00 2001 From: Jussi Kivilinna Date: Fri, 17 Mar 2017 17:32:44 -0600 Subject: [PATCH] libc: printf: fix precision for string formatting. Fixes use of format precision to truncate input string. --- libc/stdio/lib_libvsprintf.c | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/libc/stdio/lib_libvsprintf.c b/libc/stdio/lib_libvsprintf.c index 894f040453..1a3501c704 100644 --- a/libc/stdio/lib_libvsprintf.c +++ b/libc/stdio/lib_libvsprintf.c @@ -1171,9 +1171,7 @@ int lib_vsprintf(FAR struct lib_outstream_s *obj, FAR const IPTR char *src, FAR char *ptmp; #ifndef CONFIG_NOPRINTF_FIELDWIDTH int width; -#ifdef CONFIG_LIBC_FLOATINGPOINT int trunc; -#endif uint8_t fmt; #endif uint8_t flags; @@ -1215,9 +1213,7 @@ int lib_vsprintf(FAR struct lib_outstream_s *obj, FAR const IPTR char *src, #ifndef CONFIG_NOPRINTF_FIELDWIDTH fmt = FMT_RJUST; width = 0; -#ifdef CONFIG_LIBC_FLOATINGPOINT trunc = 0; -#endif #endif /* Process each format qualifier. */ @@ -1265,10 +1261,8 @@ int lib_vsprintf(FAR struct lib_outstream_s *obj, FAR const IPTR char *src, int value = va_arg(ap, int); if (IS_HASDOT(flags)) { -#ifdef CONFIG_LIBC_FLOATINGPOINT trunc = value; SET_HASASTERISKTRUNC(flags); -#endif } else { @@ -1307,9 +1301,7 @@ int lib_vsprintf(FAR struct lib_outstream_s *obj, FAR const IPTR char *src, if (IS_HASDOT(flags)) { -#ifdef CONFIG_LIBC_FLOATINGPOINT trunc = n; -#endif } else { @@ -1361,6 +1353,7 @@ int lib_vsprintf(FAR struct lib_outstream_s *obj, FAR const IPTR char *src, { #ifndef CONFIG_NOPRINTF_FIELDWIDTH int swidth; + int left; #endif /* Get the string to output */ @@ -1375,13 +1368,21 @@ int lib_vsprintf(FAR struct lib_outstream_s *obj, FAR const IPTR char *src, */ #ifndef CONFIG_NOPRINTF_FIELDWIDTH - swidth = strlen(ptmp); + swidth = (IS_HASDOT(flags) && trunc >= 0) + ? strnlen(ptmp, trunc) : strlen(ptmp); prejustify(obj, fmt, 0, width, swidth); + left = swidth; #endif /* Concatenate the string into the output */ while (*ptmp) { +#ifndef CONFIG_NOPRINTF_FIELDWIDTH + if (left-- <= 0) + { + break; + } +#endif obj->put(obj, *ptmp); ptmp++; }