From d6105aba5fd791e8d3f069e771517cdb947b5604 Mon Sep 17 00:00:00 2001 From: jvoisin Date: Thu, 30 Apr 2026 18:06:56 +0200 Subject: Fix mbsnrtowcs mbsnrtowcs writes up to __wn wide characters into wchar_t *__d. The destination capacity is __b / sizeof(wchar_t) wide characters, but the else branch clamps __n (source byte limit) to __b (destination byte size). __wn (the actual output count) is passed through unclamped. Example: __b=8 (dest holds 2 wchar_t), __n=100, __wn=25. The else branch applies (25 <= 100/4), clamps source to 8 bytes, but passes __wn=25 — the function can write 25 wchar_t (100 bytes) into an 8-byte buffer. The first branch is also wrong: it divides __b (bytes) by sizeof(wchar_t) to get wchar_t capacity, which is correct for the destination — but the condition __wn > __n / sizeof(wchar_t) uses integer division that can produce incorrect routing between branches. The fix mirrors the already-correct mbsrtowcs pattern: clamp __wn (the output wide-char count) to the destination's wchar_t capacity, and pass __n (source byte limit) through unchanged. --- tests/test_mbsnrtowcs_dynamic.c | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 tests/test_mbsnrtowcs_dynamic.c (limited to 'tests/test_mbsnrtowcs_dynamic.c') diff --git a/tests/test_mbsnrtowcs_dynamic.c b/tests/test_mbsnrtowcs_dynamic.c new file mode 100644 index 0000000..77b9082 --- /dev/null +++ b/tests/test_mbsnrtowcs_dynamic.c @@ -0,0 +1,28 @@ +#include "common.h" + +#include +#include + +int main(int argc, char** argv) { + wchar_t buffer[4] = {0}; + const char *src = "ABCDEFGHIJ"; + const char *srcp = src; + mbstate_t st; + memset(&st, 0, sizeof(st)); + + /* Safe: convert up to 2 source bytes into at most 2 wide chars */ + srcp = src; + mbsnrtowcs(buffer, &srcp, 2, 2, &st); + + /* Unsafe: ask to write argc (10) wide chars into 4-element buffer. + * Before the fix, the else branch clamped source bytes instead of + * the output wide-char count, allowing destination overflow. */ + CHK_FAIL_START + srcp = src; + memset(&st, 0, sizeof(st)); + mbsnrtowcs(buffer, &srcp, 10, argc, &st); + CHK_FAIL_END + + printf("%ls\n", buffer); + return ret; +} -- cgit v1.3