[PATCH] newlib: mbtowc: reject UTF-16 surrogates with a 32-bit wchar_t

Bernie Innocenti bernie@codewiz.org
Sat Oct 17 15:27:33 GMT 2026


UTF-8 does not encode U+D800..U+DFFF (RFC 3629), and the UTF-8 test
expects ED A0 80..ED BF BF to be invalid, but the three-byte path
decoded them.  Reject them where wchar_t is 32 bits.  With a 16-bit
wchar_t, as on Cygwin, lone surrogates still go through, so file
names that contain them keep round-tripping.

Assisted-by: Claude:claude-opus-5-5 claude-code
Signed-off-by: Bernie Innocenti <bernie@codewiz.org>
---
 newlib/libc/stdlib/mbtowc_r.c | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/newlib/libc/stdlib/mbtowc_r.c b/newlib/libc/stdlib/mbtowc_r.c
index cab8333d7..b51ed901d 100644
--- a/newlib/libc/stdlib/mbtowc_r.c
+++ b/newlib/libc/stdlib/mbtowc_r.c
@@ -610,6 +610,15 @@ __utf8_mbtowc (struct _reent *r,
 	  _REENT_ERRNO(r) = EILSEQ;
 	  return -1;
 	}
+      if (state->__value.__wchb[0] == 0xed && ch >= 0xa0
+	  && sizeof(wchar_t) == 4)
+	{
+	  /* UTF-16 surrogate, which UTF-8 does not encode (RFC 3629).
+	     With a 16-bit wchar_t, lone surrogates go through, so that
+	     file names containing them round-trip on Cygwin.  */
+	  _REENT_ERRNO(r) = EILSEQ;
+	  return -1;
+	}
       if (ch < 0x80 || ch > 0xbf)
 	{
 	  _REENT_ERRNO(r) = EILSEQ;
-- 
2.56.0



More information about the Newlib mailing list