From 063179a55bdacb3d7b9f6ef66d44907078a73a45 Mon Sep 17 00:00:00 2001 From: Alexey Izbyshev Date: Tue, 30 May 2023 00:05:54 +0300 Subject: [PATCH 2/3] mbsnrtowcs: fix wrong state rollback if no characters are converted Mail-Followup-To: musl@lists.openwall.com mbsnrtowcs always resets the conversion state to zero if mbrtowc can't parse a complete multibyte sequence due to reaching the length limit. However, if mbsnrtowcs started in a non-initial state and hasn't produced even a single wide character, the state should be rolled back to its original value instead. --- src/multibyte/mbsnrtowcs.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/multibyte/mbsnrtowcs.c b/src/multibyte/mbsnrtowcs.c index 375e01d7..c3c1f709 100644 --- a/src/multibyte/mbsnrtowcs.c +++ b/src/multibyte/mbsnrtowcs.c @@ -3,12 +3,14 @@ size_t mbsnrtowcs(wchar_t *restrict wcs, const char **restrict src, size_t n, size_t wn, mbstate_t *restrict st) { static unsigned internal_state; + unsigned st0; size_t l, cnt=0, n2; wchar_t *ws, wbuf[256]; const char *s = *src; const char *tmp_s; if (!st) st = (void *)&internal_state; + st0 = *(unsigned *)st; if (!wcs) ws = wbuf, wn = sizeof wbuf / sizeof *wbuf; else ws = wcs; @@ -45,7 +47,7 @@ size_t mbsnrtowcs(wchar_t *restrict wcs, const char **restrict src, size_t n, si break; } /* have to roll back partial character */ - *(unsigned *)st = 0; + *(unsigned *)st = (s == *src ? st0 : 0); break; } s += l; n -= l; -- 2.39.2