fix incorrect range checks in wcsrtombs
[musl] / src / multibyte / wcsnrtombs.c
1 /* 
2  * This code was written by Rich Felker in 2010; no copyright is claimed.
3  * This code is in the public domain. Attribution is appreciated but
4  * unnecessary.
5  */
6
7 #include <stdlib.h>
8 #include <inttypes.h>
9 #include <wchar.h>
10 #include <errno.h>
11
12 #include "internal.h"
13
14 size_t wcsnrtombs(char *restrict dst, const wchar_t **restrict wcs, size_t wn, size_t n, mbstate_t *restrict st)
15 {
16         size_t l, cnt=0, n2;
17         char *s, buf[256];
18         const wchar_t *ws = *wcs;
19
20         if (!dst) s = buf, n = sizeof buf;
21         else s = dst;
22
23         while ( ws && n && ( (n2=wn)>=n || n2>32 ) ) {
24                 if (n2>=n) n2=n;
25                 wn -= n2;
26                 l = wcsrtombs(s, &ws, n2, 0);
27                 if (!(l+1)) {
28                         cnt = l;
29                         n = 0;
30                         break;
31                 }
32                 if (s != buf) {
33                         s += l;
34                         n -= l;
35                 }
36                 cnt += l;
37         }
38         if (ws) while (n && wn) {
39                 l = wcrtomb(s, *ws, 0);
40                 if ((l+1)<=1) {
41                         if (!l) ws = 0;
42                         else cnt = l;
43                         break;
44                 }
45                 ws++; wn--;
46                 /* safe - this loop runs fewer than sizeof(buf) times */
47                 s+=l; n-=l;
48                 cnt++;
49         }
50         if (dst) *wcs = ws;
51         return cnt;
52 }