Bug 19411 - mbrtoc16 and mbrtowc: UB when n is larger than input size
Summary: mbrtoc16 and mbrtowc: UB when n is larger than input size
Status: NEW
Alias: None
Product: glibc
Classification: Unclassified
Component: string (show other bugs)
Version: 2.22
: P2 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
Depends on:
Reported: 2015-12-28 14:08 UTC by Alexander Cherepanov
Modified: 2015-12-28 14:08 UTC (History)
0 users

See Also:
Last reconfirmed:


Note You need to log in before you can comment on or make changes to this bug.
Description Alexander Cherepanov 2015-12-28 14:08:45 UTC
The functions

size_t mbrtowc (wchar_t *pwc, const char *s, size_t n, mbstate_t *ps)
size_t mbrtoc16 (char16_t *pc16, const char *s, size_t n, mbstate_t *ps)

have a limit n on the number of processed bytes but it seems that the source array s is not required to contain n accessible bytes. At least the commit


added checks for pointer wrapping into mbrtowc and a test case with n=SIZE_MAX (the test case uses mbtowc which in turn passes everything to __mbrtowc).

The check looks like this:

 endbuf = inbuf + n;
 if (__glibc_unlikely (endbuf < inbuf))


This code is invalid. The sum "inbuf + n" is undefined by the C standard when the result doesn't point into the same array. Then, checks for pointer wrapping like "endbuf < inbuf" are already "miscompiled" by clang and, I guess, could be expected to be broken by gcc in the future.

Similar to pr19391.