From b61d676c5ce01ac6aef9a3563129af0429db41b5 Mon Sep 17 00:00:00 2001 From: Alexey Izbyshev Date: Mon, 29 May 2023 21:37:47 +0300 Subject: [PATCH 1/3] mbsnrtowcs: fix observable reuse of mbrtowc's internal state Mail-Followup-To: musl@lists.openwall.com mbsnrtowcs can pass the caller-provided conversion state to mbsrtowcs and to mbrtowc even if it is NULL. For mbsrtowcs it's fine because it doesn't have any internal state, but mbrtowc does, and POSIX doesn't allow other standard functions to observably modify it. Moreover, if mbrtowc call returns -2, mbsnrtowcs currently dereferences NULL and crashes. Fix these issues by adding the internal conversion state to mbsnrtowcs. --- src/multibyte/mbsnrtowcs.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/multibyte/mbsnrtowcs.c b/src/multibyte/mbsnrtowcs.c index 931192e2..375e01d7 100644 --- a/src/multibyte/mbsnrtowcs.c +++ b/src/multibyte/mbsnrtowcs.c @@ -2,11 +2,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; 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; + if (!wcs) ws = wbuf, wn = sizeof wbuf / sizeof *wbuf; else ws = wcs; -- 2.39.2