e38cb5
commit c6fad4fa149485a307207f707e5851216f190fc8
e38cb5
Author: Florian Weimer <fweimer@redhat.com>
e38cb5
Date:   Thu Mar 19 18:32:28 2020 -0300
e38cb5
e38cb5
    stdio: Remove memory leak from multibyte convertion [BZ#25691]
e38cb5
    
e38cb5
    This is an updated version of a previous patch [1] with the
e38cb5
    following changes:
e38cb5
    
e38cb5
      - Use compiler overflow builtins on done_add_func function.
e38cb5
      - Define the scratch +utstring_converted_wide_string using
e38cb5
        CHAR_T.
e38cb5
      - Added a testcase and mention the bug report.
e38cb5
    
e38cb5
    Both default and wide printf functions might leak memory when
e38cb5
    manipulate multibyte characters conversion depending of the size
e38cb5
    of the input (whether __libc_use_alloca trigger or not the fallback
e38cb5
    heap allocation).
e38cb5
    
e38cb5
    This patch fixes it by removing the extra memory allocation on
e38cb5
    string formatting with conversion parts.
e38cb5
    
e38cb5
    The testcase uses input argument size that trigger memory leaks
e38cb5
    on unpatched code (using a scratch buffer the threashold to use
e38cb5
    heap allocation is lower).
e38cb5
    
e38cb5
    Checked on x86_64-linux-gnu and i686-linux-gnu.
e38cb5
    
e38cb5
    Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
e38cb5
    
e38cb5
    [1] https://sourceware.org/pipermail/libc-alpha/2017-June/082098.html
e38cb5
    
e38cb5
    (cherry picked from commit 3cc4a8367c23582b7db14cf4e150e4068b7fd461)
e38cb5
e38cb5
diff --git a/stdio-common/vfprintf.c b/stdio-common/vfprintf.c
e38cb5
index ae412e4b8444aea2..dab56b6ba2c7bdbe 100644
e38cb5
--- a/stdio-common/vfprintf.c
e38cb5
+++ b/stdio-common/vfprintf.c
e38cb5
@@ -31,6 +31,7 @@
e38cb5
 #include <locale/localeinfo.h>
e38cb5
 #include <stdio.h>
e38cb5
 #include <scratch_buffer.h>
e38cb5
+#include <intprops.h>
e38cb5
 
e38cb5
 /* This code is shared between the standard stdio implementation found
e38cb5
    in GNU C library and the libio implementation originally found in
e38cb5
@@ -64,23 +65,40 @@
e38cb5
     } while (0)
e38cb5
 #define UNBUFFERED_P(S) ((S)->_flags & _IO_UNBUFFERED)
e38cb5
 
e38cb5
-#define done_add(val) \
e38cb5
-  do {									      \
e38cb5
-    unsigned int _val = val;						      \
e38cb5
-    assert ((unsigned int) done < (unsigned int) INT_MAX);		      \
e38cb5
-    if (__glibc_unlikely (INT_MAX - done < _val))			      \
e38cb5
-      {									      \
e38cb5
-	done = -1;							      \
e38cb5
-	 __set_errno (EOVERFLOW);					      \
e38cb5
-	goto all_done;							      \
e38cb5
-      }									      \
e38cb5
-    done += _val;							      \
e38cb5
-  } while (0)
e38cb5
+/* Add LENGTH to DONE.  Return the new value of DONE, or -1 on
e38cb5
+   overflow (and set errno accordingly).  */
e38cb5
+static inline int
e38cb5
+done_add_func (size_t length, int done)
e38cb5
+{
e38cb5
+  if (done < 0)
e38cb5
+    return done;
e38cb5
+  int ret;
e38cb5
+  if (INT_ADD_WRAPV (done, length, &ret))
e38cb5
+    {
e38cb5
+      __set_errno (EOVERFLOW);
e38cb5
+      return -1;
e38cb5
+    }
e38cb5
+  return ret;
e38cb5
+}
e38cb5
+
e38cb5
+#define done_add(val)							\
e38cb5
+  do									\
e38cb5
+    {									\
e38cb5
+      /* Ensure that VAL has a type similar to int.  */			\
e38cb5
+      _Static_assert (sizeof (val) == sizeof (int), "value int size");	\
e38cb5
+      _Static_assert ((__typeof__ (val)) -1 < 0, "value signed");	\
e38cb5
+      done = done_add_func ((val), done);				\
e38cb5
+      if (done < 0)							\
e38cb5
+	goto all_done;							\
e38cb5
+    }									\
e38cb5
+  while (0)
e38cb5
 
e38cb5
 #ifndef COMPILE_WPRINTF
e38cb5
 # define vfprintf	_IO_vfprintf_internal
e38cb5
 # define CHAR_T		char
e38cb5
+# define CHAR_T		char
e38cb5
 # define UCHAR_T	unsigned char
e38cb5
+# define OTHER_CHAR_T   wchar_t
e38cb5
 # define INT_T		int
e38cb5
 typedef const char *THOUSANDS_SEP_T;
e38cb5
 # define L_(Str)	Str
e38cb5
@@ -88,22 +106,10 @@ typedef const char *THOUSANDS_SEP_T;
e38cb5
 # define STR_LEN(Str)	strlen (Str)
e38cb5
 
e38cb5
 # define PUT(F, S, N)	_IO_sputn ((F), (S), (N))
e38cb5
-# define PAD(Padchar) \
e38cb5
-  do {									      \
e38cb5
-    if (width > 0)							      \
e38cb5
-      {									      \
e38cb5
-	ssize_t written = _IO_padn (s, (Padchar), width);		      \
e38cb5
-	if (__glibc_unlikely (written != width))			      \
e38cb5
-	  {								      \
e38cb5
-	    done = -1;							      \
e38cb5
-	    goto all_done;						      \
e38cb5
-	  }								      \
e38cb5
-	done_add (written);						      \
e38cb5
-      }									      \
e38cb5
-  } while (0)
e38cb5
 # define PUTC(C, F)	_IO_putc_unlocked (C, F)
e38cb5
 # define ORIENT		if (_IO_vtable_offset (s) == 0 && _IO_fwide (s, -1) != -1)\
e38cb5
 			  return -1
e38cb5
+# define CONVERT_FROM_OTHER_STRING __wcsrtombs
e38cb5
 #else
e38cb5
 # define vfprintf	_IO_vfwprintf
e38cb5
 # define CHAR_T		wchar_t
e38cb5
@@ -118,21 +124,11 @@ typedef wchar_t THOUSANDS_SEP_T;
e38cb5
 # include <_itowa.h>
e38cb5
 
e38cb5
 # define PUT(F, S, N)	_IO_sputn ((F), (S), (N))
e38cb5
-# define PAD(Padchar) \
e38cb5
-  do {									      \
e38cb5
-    if (width > 0)							      \
e38cb5
-      {									      \
e38cb5
-	ssize_t written = _IO_wpadn (s, (Padchar), width);		      \
e38cb5
-	if (__glibc_unlikely (written != width))			      \
e38cb5
-	  {								      \
e38cb5
-	    done = -1;							      \
e38cb5
-	    goto all_done;						      \
e38cb5
-	  }								      \
e38cb5
-	done_add (written);						      \
e38cb5
-      }									      \
e38cb5
-  } while (0)
e38cb5
 # define PUTC(C, F)	_IO_putwc_unlocked (C, F)
e38cb5
 # define ORIENT		if (_IO_fwide (s, 1) != 1) return -1
e38cb5
+# define CONVERT_FROM_OTHER_STRING __mbsrtowcs
e38cb5
+# define CHAR_T		wchar_t
e38cb5
+# define OTHER_CHAR_T   char
e38cb5
 
e38cb5
 # undef _itoa
e38cb5
 # define _itoa(Val, Buf, Base, Case) _itowa (Val, Buf, Base, Case)
e38cb5
@@ -141,6 +137,33 @@ typedef wchar_t THOUSANDS_SEP_T;
e38cb5
 # define EOF WEOF
e38cb5
 #endif
e38cb5
 
e38cb5
+static inline int
e38cb5
+pad_func (FILE *s, CHAR_T padchar, int width, int done)
e38cb5
+{
e38cb5
+  if (width > 0)
e38cb5
+    {
e38cb5
+      ssize_t written;
e38cb5
+#ifndef COMPILE_WPRINTF
e38cb5
+      written = _IO_padn (s, padchar, width);
e38cb5
+#else
e38cb5
+      written = _IO_wpadn (s, padchar, width);
e38cb5
+#endif
e38cb5
+      if (__glibc_unlikely (written != width))
e38cb5
+	return -1;
e38cb5
+      return done_add_func (width, done);
e38cb5
+    }
e38cb5
+  return done;
e38cb5
+}
e38cb5
+
e38cb5
+#define PAD(Padchar)							\
e38cb5
+  do									\
e38cb5
+    {									\
e38cb5
+      done = pad_func (s, (Padchar), width, done);			\
e38cb5
+      if (done < 0)							\
e38cb5
+	goto all_done;							\
e38cb5
+    }									\
e38cb5
+  while (0)
e38cb5
+
e38cb5
 #include "_i18n_number.h"
e38cb5
 
e38cb5
 /* Include the shared code for parsing the format string.  */
e38cb5
@@ -160,24 +183,115 @@ typedef wchar_t THOUSANDS_SEP_T;
e38cb5
     }									      \
e38cb5
   while (0)
e38cb5
 
e38cb5
-#define outstring(String, Len)						      \
e38cb5
-  do									      \
e38cb5
-    {									      \
e38cb5
-      assert ((size_t) done <= (size_t) INT_MAX);			      \
e38cb5
-      if ((size_t) PUT (s, (String), (Len)) != (size_t) (Len))		      \
e38cb5
-	{								      \
e38cb5
-	  done = -1;							      \
e38cb5
-	  goto all_done;						      \
e38cb5
-	}								      \
e38cb5
-      if (__glibc_unlikely (INT_MAX - done < (Len)))			      \
e38cb5
-      {									      \
e38cb5
-	done = -1;							      \
e38cb5
-	 __set_errno (EOVERFLOW);					      \
e38cb5
-	goto all_done;							      \
e38cb5
-      }									      \
e38cb5
-      done += (Len);							      \
e38cb5
-    }									      \
e38cb5
-  while (0)
e38cb5
+static inline int
e38cb5
+outstring_func (FILE *s, const UCHAR_T *string, size_t length, int done)
e38cb5
+{
e38cb5
+  assert ((size_t) done <= (size_t) INT_MAX);
e38cb5
+  if ((size_t) PUT (s, string, length) != (size_t) (length))
e38cb5
+    return -1;
e38cb5
+  return done_add_func (length, done);
e38cb5
+}
e38cb5
+
e38cb5
+#define outstring(String, Len)						\
e38cb5
+  do									\
e38cb5
+    {									\
e38cb5
+      const void *string_ = (String);					\
e38cb5
+      done = outstring_func (s, string_, (Len), done);			\
e38cb5
+      if (done < 0)							\
e38cb5
+	goto all_done;							\
e38cb5
+    }									\
e38cb5
+   while (0)
e38cb5
+
e38cb5
+/* Write the string SRC to S.  If PREC is non-negative, write at most
e38cb5
+   PREC bytes.  If LEFT is true, perform left justification.  */
e38cb5
+static int
e38cb5
+outstring_converted_wide_string (FILE *s, const OTHER_CHAR_T *src, int prec,
e38cb5
+				 int width, bool left, int done)
e38cb5
+{
e38cb5
+  /* Use a small buffer to combine processing of multiple characters.
e38cb5
+     CONVERT_FROM_OTHER_STRING expects the buffer size in (wide)
e38cb5
+     characters, and buf_length counts that.  */
e38cb5
+  enum { buf_length = 256 / sizeof (CHAR_T) };
e38cb5
+  CHAR_T buf[buf_length];
e38cb5
+  _Static_assert (sizeof (buf) > MB_LEN_MAX,
e38cb5
+		  "buffer is large enough for a single multi-byte character");
e38cb5
+
e38cb5
+  /* Add the initial padding if needed.  */
e38cb5
+  if (width > 0 && !left)
e38cb5
+    {
e38cb5
+      /* Make a first pass to find the output width, so that we can
e38cb5
+	 add the required padding.  */
e38cb5
+      mbstate_t mbstate = { 0 };
e38cb5
+      const OTHER_CHAR_T *src_copy = src;
e38cb5
+      size_t total_written;
e38cb5
+      if (prec < 0)
e38cb5
+	total_written = CONVERT_FROM_OTHER_STRING
e38cb5
+	  (NULL, &src_copy, 0, &mbstate);
e38cb5
+      else
e38cb5
+	{
e38cb5
+	  /* The source might not be null-terminated.  Enforce the
e38cb5
+	     limit manually, based on the output length.  */
e38cb5
+	  total_written = 0;
e38cb5
+	  size_t limit = prec;
e38cb5
+	  while (limit > 0 && src_copy != NULL)
e38cb5
+	    {
e38cb5
+	      size_t write_limit = buf_length;
e38cb5
+	      if (write_limit > limit)
e38cb5
+		write_limit = limit;
e38cb5
+	      size_t written = CONVERT_FROM_OTHER_STRING
e38cb5
+		(buf, &src_copy, write_limit, &mbstate);
e38cb5
+	      if (written == (size_t) -1)
e38cb5
+		return -1;
e38cb5
+	      if (written == 0)
e38cb5
+		break;
e38cb5
+	      total_written += written;
e38cb5
+	      limit -= written;
e38cb5
+	    }
e38cb5
+	}
e38cb5
+
e38cb5
+      /* Output initial padding.  */
e38cb5
+      if (total_written < width)
e38cb5
+	{
e38cb5
+	  done = pad_func (s, L_(' '), width - total_written, done);
e38cb5
+	  if (done < 0)
e38cb5
+	    return done;
e38cb5
+	}
e38cb5
+    }
e38cb5
+
e38cb5
+  /* Convert the input string, piece by piece.  */
e38cb5
+  size_t total_written = 0;
e38cb5
+  {
e38cb5
+    mbstate_t mbstate = { 0 };
e38cb5
+    /* If prec is negative, remaining is not decremented, otherwise,
e38cb5
+      it serves as the write limit.  */
e38cb5
+    size_t remaining = -1;
e38cb5
+    if (prec >= 0)
e38cb5
+      remaining = prec;
e38cb5
+    while (remaining > 0 && src != NULL)
e38cb5
+      {
e38cb5
+	size_t write_limit = buf_length;
e38cb5
+	if (remaining < write_limit)
e38cb5
+	  write_limit = remaining;
e38cb5
+	size_t written = CONVERT_FROM_OTHER_STRING
e38cb5
+	  (buf, &src, write_limit, &mbstate);
e38cb5
+	if (written == (size_t) -1)
e38cb5
+	  return -1;
e38cb5
+	if (written == 0)
e38cb5
+	  break;
e38cb5
+	done = outstring_func (s, (const UCHAR_T *) buf, written, done);
e38cb5
+	if (done < 0)
e38cb5
+	  return done;
e38cb5
+	total_written += written;
e38cb5
+	if (prec >= 0)
e38cb5
+	  remaining -= written;
e38cb5
+      }
e38cb5
+  }
e38cb5
+
e38cb5
+  /* Add final padding.  */
e38cb5
+  if (width > 0 && left && total_written < width)
e38cb5
+    return pad_func (s, L_(' '), width - total_written, done);
e38cb5
+  return done;
e38cb5
+}
e38cb5
 
e38cb5
 /* For handling long_double and longlong we use the same flag.  If
e38cb5
    `long' and `long long' are effectively the same type define it to
e38cb5
@@ -975,7 +1089,6 @@ static const uint8_t jump_table[] =
e38cb5
     LABEL (form_string):						      \
e38cb5
       {									      \
e38cb5
 	size_t len;							      \
e38cb5
-	int string_malloced;						      \
e38cb5
 									      \
e38cb5
 	/* The string argument could in fact be `char *' or `wchar_t *'.      \
e38cb5
 	   But this should not make a difference here.  */		      \
e38cb5
@@ -987,7 +1100,6 @@ static const uint8_t jump_table[] =
e38cb5
 	/* Entry point for printing other strings.  */			      \
e38cb5
       LABEL (print_string):						      \
e38cb5
 									      \
e38cb5
-	string_malloced = 0;						      \
e38cb5
 	if (string == NULL)						      \
e38cb5
 	  {								      \
e38cb5
 	    /* Write "(null)" if there's space.  */			      \
e38cb5
@@ -1004,41 +1116,12 @@ static const uint8_t jump_table[] =
e38cb5
 	  }								      \
e38cb5
 	else if (!is_long && spec != L_('S'))				      \
e38cb5
 	  {								      \
e38cb5
-	    /* This is complicated.  We have to transform the multibyte	      \
e38cb5
-	       string into a wide character string.  */			      \
e38cb5
-	    const char *mbs = (const char *) string;			      \
e38cb5
-	    mbstate_t mbstate;						      \
e38cb5
-									      \
e38cb5
-	    len = prec != -1 ? __strnlen (mbs, (size_t) prec) : strlen (mbs); \
e38cb5
-									      \
e38cb5
-	    /* Allocate dynamically an array which definitely is long	      \
e38cb5
-	       enough for the wide character version.  Each byte in the	      \
e38cb5
-	       multi-byte string can produce at most one wide character.  */  \
e38cb5
-	    if (__glibc_unlikely (len > SIZE_MAX / sizeof (wchar_t)))	      \
e38cb5
-	      {								      \
e38cb5
-		__set_errno (EOVERFLOW);				      \
e38cb5
-		done = -1;						      \
e38cb5
-		goto all_done;						      \
e38cb5
-	      }								      \
e38cb5
-	    else if (__libc_use_alloca (len * sizeof (wchar_t)))	      \
e38cb5
-	      string = (CHAR_T *) alloca (len * sizeof (wchar_t));	      \
e38cb5
-	    else if ((string = (CHAR_T *) malloc (len * sizeof (wchar_t)))    \
e38cb5
-		     == NULL)						      \
e38cb5
-	      {								      \
e38cb5
-		done = -1;						      \
e38cb5
-		goto all_done;						      \
e38cb5
-	      }								      \
e38cb5
-	    else							      \
e38cb5
-	      string_malloced = 1;					      \
e38cb5
-									      \
e38cb5
-	    memset (&mbstate, '\0', sizeof (mbstate_t));		      \
e38cb5
-	    len = __mbsrtowcs (string, &mbs, len, &mbstate);		      \
e38cb5
-	    if (len == (size_t) -1)					      \
e38cb5
-	      {								      \
e38cb5
-		/* Illegal multibyte character.  */			      \
e38cb5
-		done = -1;						      \
e38cb5
-		goto all_done;						      \
e38cb5
-	      }								      \
e38cb5
+	    done = outstring_converted_wide_string			      \
e38cb5
+	      (s, (const char *) string, prec, width, left, done);	      \
e38cb5
+	    if (done < 0)						      \
e38cb5
+	      goto all_done;						      \
e38cb5
+	    /* The padding has already been written.  */		      \
e38cb5
+	    break;							      \
e38cb5
 	  }								      \
e38cb5
 	else								      \
e38cb5
 	  {								      \
e38cb5
@@ -1061,8 +1144,6 @@ static const uint8_t jump_table[] =
e38cb5
 	outstring (string, len);					      \
e38cb5
 	if (left)							      \
e38cb5
 	  PAD (L' ');							      \
e38cb5
-	if (__glibc_unlikely (string_malloced))				      \
e38cb5
-	  free (string);						      \
e38cb5
       }									      \
e38cb5
       break;
e38cb5
 #else
e38cb5
@@ -1111,7 +1192,6 @@ static const uint8_t jump_table[] =
e38cb5
     LABEL (form_string):						      \
e38cb5
       {									      \
e38cb5
 	size_t len;							      \
e38cb5
-	int string_malloced;						      \
e38cb5
 									      \
e38cb5
 	/* The string argument could in fact be `char *' or `wchar_t *'.      \
e38cb5
 	   But this should not make a difference here.  */		      \
e38cb5
@@ -1123,7 +1203,6 @@ static const uint8_t jump_table[] =
e38cb5
 	/* Entry point for printing other strings.  */			      \
e38cb5
       LABEL (print_string):						      \
e38cb5
 									      \
e38cb5
-	string_malloced = 0;						      \
e38cb5
 	if (string == NULL)						      \
e38cb5
 	  {								      \
e38cb5
 	    /* Write "(null)" if there's space.  */			      \
e38cb5
@@ -1149,51 +1228,12 @@ static const uint8_t jump_table[] =
e38cb5
 	  }								      \
e38cb5
 	else								      \
e38cb5
 	  {								      \
e38cb5
-	    const wchar_t *s2 = (const wchar_t *) string;		      \
e38cb5
-	    mbstate_t mbstate;						      \
e38cb5
-									      \
e38cb5
-	    memset (&mbstate, '\0', sizeof (mbstate_t));		      \
e38cb5
-									      \
e38cb5
-	    if (prec >= 0)						      \
e38cb5
-	      {								      \
e38cb5
-		/* The string `s2' might not be NUL terminated.  */	      \
e38cb5
-		if (__libc_use_alloca (prec))				      \
e38cb5
-		  string = (char *) alloca (prec);			      \
e38cb5
-		else if ((string = (char *) malloc (prec)) == NULL)	      \
e38cb5
-		  {							      \
e38cb5
-		    done = -1;						      \
e38cb5
-		    goto all_done;					      \
e38cb5
-		  }							      \
e38cb5
-		else							      \
e38cb5
-		  string_malloced = 1;					      \
e38cb5
-		len = __wcsrtombs (string, &s2, prec, &mbstate);	      \
e38cb5
-	      }								      \
e38cb5
-	    else							      \
e38cb5
-	      {								      \
e38cb5
-		len = __wcsrtombs (NULL, &s2, 0, &mbstate);		      \
e38cb5
-		if (len != (size_t) -1)					      \
e38cb5
-		  {							      \
e38cb5
-		    assert (__mbsinit (&mbstate));			      \
e38cb5
-		    s2 = (const wchar_t *) string;			      \
e38cb5
-		    if (__libc_use_alloca (len + 1))			      \
e38cb5
-		      string = (char *) alloca (len + 1);		      \
e38cb5
-		    else if ((string = (char *) malloc (len + 1)) == NULL)    \
e38cb5
-		      {							      \
e38cb5
-			done = -1;					      \
e38cb5
-			goto all_done;					      \
e38cb5
-		      }							      \
e38cb5
-		    else						      \
e38cb5
-		      string_malloced = 1;				      \
e38cb5
-		    (void) __wcsrtombs (string, &s2, len + 1, &mbstate);      \
e38cb5
-		  }							      \
e38cb5
-	      }								      \
e38cb5
-									      \
e38cb5
-	    if (len == (size_t) -1)					      \
e38cb5
-	      {								      \
e38cb5
-		/* Illegal wide-character string.  */			      \
e38cb5
-		done = -1;						      \
e38cb5
-		goto all_done;						      \
e38cb5
-	      }								      \
e38cb5
+	    done = outstring_converted_wide_string			      \
e38cb5
+	      (s, (const wchar_t *) string, prec, width, left, done);	      \
e38cb5
+	    if (done < 0)						      \
e38cb5
+	      goto all_done;						      \
e38cb5
+	    /* The padding has already been written.  */		      \
e38cb5
+	    break;							      \
e38cb5
 	  }								      \
e38cb5
 									      \
e38cb5
 	if ((width -= len) < 0)						      \
e38cb5
@@ -1207,8 +1247,6 @@ static const uint8_t jump_table[] =
e38cb5
 	outstring (string, len);					      \
e38cb5
 	if (left)							      \
e38cb5
 	  PAD (' ');							      \
e38cb5
-	if (__glibc_unlikely (string_malloced))			              \
e38cb5
-	  free (string);						      \
e38cb5
       }									      \
e38cb5
       break;
e38cb5
 #endif