xref: /dragonfly/lib/libc/locale/utf8.c (revision 2513f15e)
1 /*-
2  * Copyright (c) 2002-2004 Tim J. Robbins
3  * All rights reserved.
4  *
5  * Copyright (c) 2011 The FreeBSD Foundation
6  * All rights reserved.
7  * Portions of this software were developed by David Chisnall
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  * $FreeBSD: head/lib/libc/locale/utf8.c 227753 2011-11-20 14:45:42Z theraven $
32  */
33 
34 #include <sys/param.h>
35 
36 #include <errno.h>
37 #include <limits.h>
38 #include <runetype.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <wchar.h>
42 #include "mblocal.h"
43 
44 extern int __mb_sb_limit;
45 
46 static size_t	_UTF8_mbrtowc(wchar_t * __restrict, const char * __restrict,
47 		    size_t, mbstate_t * __restrict);
48 static int	_UTF8_mbsinit(const mbstate_t *);
49 static size_t	_UTF8_mbsnrtowcs(wchar_t * __restrict,
50 		    const char ** __restrict, size_t, size_t,
51 		    mbstate_t * __restrict);
52 static size_t	_UTF8_wcrtomb(char * __restrict, wchar_t,
53 		    mbstate_t * __restrict);
54 static size_t	_UTF8_wcsnrtombs(char * __restrict, const wchar_t ** __restrict,
55 		    size_t, size_t, mbstate_t * __restrict);
56 
57 typedef struct {
58 	wchar_t	ch;
59 	int	want;
60 	wchar_t	lbound;
61 } _UTF8State;
62 
63 int
64 _UTF8_init(struct xlocale_ctype *l, _RuneLocale *rl)
65 {
66 
67 	l->__mbrtowc = _UTF8_mbrtowc;
68 	l->__wcrtomb = _UTF8_wcrtomb;
69 	l->__mbsinit = _UTF8_mbsinit;
70 	l->__mbsnrtowcs = _UTF8_mbsnrtowcs;
71 	l->__wcsnrtombs = _UTF8_wcsnrtombs;
72 	l->runes = rl;
73 	l->__mb_cur_max = 6;
74 	/*
75 	 * UCS-4 encoding used as the internal representation, so
76 	 * slots 0x0080-0x00FF are occuped and must be excluded
77 	 * from the single byte ctype by setting the limit.
78 	 */
79 	l->__mb_sb_limit = 128;
80 
81 	return (0);
82 }
83 
84 static int
85 _UTF8_mbsinit(const mbstate_t *ps)
86 {
87 
88 	return (ps == NULL || ((const _UTF8State *)ps)->want == 0);
89 }
90 
91 static size_t
92 _UTF8_mbrtowc(wchar_t * __restrict pwc, const char * __restrict s, size_t n,
93     mbstate_t * __restrict ps)
94 {
95 	_UTF8State *us;
96 	int ch, i, mask, want;
97 	wchar_t lbound, wch;
98 
99 	us = (_UTF8State *)ps;
100 
101 	if (us->want < 0 || us->want > 6) {
102 		errno = EINVAL;
103 		return ((size_t)-1);
104 	}
105 
106 	if (s == NULL) {
107 		s = "";
108 		n = 1;
109 		pwc = NULL;
110 	}
111 
112 	if (n == 0)
113 		/* Incomplete multibyte sequence */
114 		return ((size_t)-2);
115 
116 	if (us->want == 0 && ((ch = (unsigned char)*s) & ~0x7f) == 0) {
117 		/* Fast path for plain ASCII characters. */
118 		if (pwc != NULL)
119 			*pwc = ch;
120 		return (ch != '\0' ? 1 : 0);
121 	}
122 
123 	if (us->want == 0) {
124 		/*
125 		 * Determine the number of octets that make up this character
126 		 * from the first octet, and a mask that extracts the
127 		 * interesting bits of the first octet. We already know
128 		 * the character is at least two bytes long.
129 		 *
130 		 * We also specify a lower bound for the character code to
131 		 * detect redundant, non-"shortest form" encodings. For
132 		 * example, the sequence C0 80 is _not_ a legal representation
133 		 * of the null character. This enforces a 1-to-1 mapping
134 		 * between character codes and their multibyte representations.
135 		 */
136 		ch = (unsigned char)*s;
137 		if ((ch & 0x80) == 0) {
138 			mask = 0x7f;
139 			want = 1;
140 			lbound = 0;
141 		} else if ((ch & 0xe0) == 0xc0) {
142 			mask = 0x1f;
143 			want = 2;
144 			lbound = 0x80;
145 		} else if ((ch & 0xf0) == 0xe0) {
146 			mask = 0x0f;
147 			want = 3;
148 			lbound = 0x800;
149 		} else if ((ch & 0xf8) == 0xf0) {
150 			mask = 0x07;
151 			want = 4;
152 			lbound = 0x10000;
153 		} else if ((ch & 0xfc) == 0xf8) {
154 			mask = 0x03;
155 			want = 5;
156 			lbound = 0x200000;
157 		} else if ((ch & 0xfe) == 0xfc) {
158 			mask = 0x01;
159 			want = 6;
160 			lbound = 0x4000000;
161 		} else {
162 			/*
163 			 * Malformed input; input is not UTF-8.
164 			 */
165 			errno = EILSEQ;
166 			return ((size_t)-1);
167 		}
168 	} else {
169 		want = us->want;
170 		lbound = us->lbound;
171 	}
172 
173 	/*
174 	 * Decode the octet sequence representing the character in chunks
175 	 * of 6 bits, most significant first.
176 	 */
177 	if (us->want == 0)
178 		wch = (unsigned char)*s++ & mask;
179 	else
180 		wch = us->ch;
181 	for (i = (us->want == 0) ? 1 : 0; i < MIN(want, n); i++) {
182 		if ((*s & 0xc0) != 0x80) {
183 			/*
184 			 * Malformed input; bad characters in the middle
185 			 * of a character.
186 			 */
187 			errno = EILSEQ;
188 			return ((size_t)-1);
189 		}
190 		wch <<= 6;
191 		wch |= *s++ & 0x3f;
192 	}
193 	if (i < want) {
194 		/* Incomplete multibyte sequence. */
195 		us->want = want - i;
196 		us->lbound = lbound;
197 		us->ch = wch;
198 		return ((size_t)-2);
199 	}
200 	if (wch < lbound) {
201 		/*
202 		 * Malformed input; redundant encoding.
203 		 */
204 		errno = EILSEQ;
205 		return ((size_t)-1);
206 	}
207 	if (pwc != NULL)
208 		*pwc = wch;
209 	us->want = 0;
210 	return (wch == L'\0' ? 0 : want);
211 }
212 
213 static size_t
214 _UTF8_mbsnrtowcs(wchar_t * __restrict dst, const char ** __restrict src,
215     size_t nms, size_t len, mbstate_t * __restrict ps)
216 {
217 	_UTF8State *us;
218 	const char *s;
219 	size_t nchr;
220 	wchar_t wc;
221 	size_t nb;
222 
223 	us = (_UTF8State *)ps;
224 
225 	s = *src;
226 	nchr = 0;
227 
228 	if (dst == NULL) {
229 		/*
230 		 * The fast path in the loop below is not safe if an ASCII
231 		 * character appears as anything but the first byte of a
232 		 * multibyte sequence. Check now to avoid doing it in the loop.
233 		 */
234 		if (nms > 0 && us->want > 0 && (signed char)*s > 0) {
235 			errno = EILSEQ;
236 			return ((size_t)-1);
237 		}
238 		for (;;) {
239 			if (nms > 0 && (signed char)*s > 0)
240 				/*
241 				 * Fast path for plain ASCII characters
242 				 * excluding NUL.
243 				 */
244 				nb = 1;
245 			else if ((nb = _UTF8_mbrtowc(&wc, s, nms, ps)) ==
246 			    (size_t)-1)
247 				/* Invalid sequence - mbrtowc() sets errno. */
248 				return ((size_t)-1);
249 			else if (nb == 0 || nb == (size_t)-2)
250 				return (nchr);
251 			s += nb;
252 			nms -= nb;
253 			nchr++;
254 		}
255 		/*NOTREACHED*/
256 	}
257 
258 	/*
259 	 * The fast path in the loop below is not safe if an ASCII
260 	 * character appears as anything but the first byte of a
261 	 * multibyte sequence. Check now to avoid doing it in the loop.
262 	 */
263 	if (nms > 0 && len > 0 && us->want > 0 && (signed char)*s > 0) {
264 		errno = EILSEQ;
265 		return ((size_t)-1);
266 	}
267 	while (len-- > 0) {
268 		if (nms > 0 && (signed char)*s > 0) {
269 			/*
270 			 * Fast path for plain ASCII characters
271 			 * excluding NUL.
272 			 */
273 			*dst = (wchar_t)*s;
274 			nb = 1;
275 		} else if ((nb = _UTF8_mbrtowc(dst, s, nms, ps)) ==
276 		    (size_t)-1) {
277 			*src = s;
278 			return ((size_t)-1);
279 		} else if (nb == (size_t)-2) {
280 			*src = s + nms;
281 			return (nchr);
282 		} else if (nb == 0) {
283 			*src = NULL;
284 			return (nchr);
285 		}
286 		s += nb;
287 		nms -= nb;
288 		nchr++;
289 		dst++;
290 	}
291 	*src = s;
292 	return (nchr);
293 }
294 
295 static size_t
296 _UTF8_wcrtomb(char * __restrict s, wchar_t wc, mbstate_t * __restrict ps)
297 {
298 	_UTF8State *us;
299 	unsigned char lead;
300 	int i, len;
301 
302 	us = (_UTF8State *)ps;
303 
304 	if (us->want != 0) {
305 		errno = EINVAL;
306 		return ((size_t)-1);
307 	}
308 
309 	if (s == NULL)
310 		/* Reset to initial shift state (no-op) */
311 		return (1);
312 
313 	if ((wc & ~0x7f) == 0) {
314 		/* Fast path for plain ASCII characters. */
315 		*s = (char)wc;
316 		return (1);
317 	}
318 
319 	/*
320 	 * Determine the number of octets needed to represent this character.
321 	 * We always output the shortest sequence possible. Also specify the
322 	 * first few bits of the first octet, which contains the information
323 	 * about the sequence length.
324 	 */
325 	if ((wc & ~0x7f) == 0) {
326 		lead = 0;
327 		len = 1;
328 	} else if ((wc & ~0x7ff) == 0) {
329 		lead = 0xc0;
330 		len = 2;
331 	} else if ((wc & ~0xffff) == 0) {
332 		lead = 0xe0;
333 		len = 3;
334 	} else if ((wc & ~0x1fffff) == 0) {
335 		lead = 0xf0;
336 		len = 4;
337 	} else if ((wc & ~0x3ffffff) == 0) {
338 		lead = 0xf8;
339 		len = 5;
340 	} else if ((wc & ~0x7fffffff) == 0) {
341 		lead = 0xfc;
342 		len = 6;
343 	} else {
344 		errno = EILSEQ;
345 		return ((size_t)-1);
346 	}
347 
348 	/*
349 	 * Output the octets representing the character in chunks
350 	 * of 6 bits, least significant last. The first octet is
351 	 * a special case because it contains the sequence length
352 	 * information.
353 	 */
354 	for (i = len - 1; i > 0; i--) {
355 		s[i] = (wc & 0x3f) | 0x80;
356 		wc >>= 6;
357 	}
358 	*s = (wc & 0xff) | lead;
359 
360 	return (len);
361 }
362 
363 static size_t
364 _UTF8_wcsnrtombs(char * __restrict dst, const wchar_t ** __restrict src,
365     size_t nwc, size_t len, mbstate_t * __restrict ps)
366 {
367 	_UTF8State *us;
368 	char buf[MB_LEN_MAX];
369 	const wchar_t *s;
370 	size_t nbytes;
371 	size_t nb;
372 
373 	us = (_UTF8State *)ps;
374 
375 	if (us->want != 0) {
376 		errno = EINVAL;
377 		return ((size_t)-1);
378 	}
379 
380 	s = *src;
381 	nbytes = 0;
382 
383 	if (dst == NULL) {
384 		while (nwc-- > 0) {
385 			if (0 <= *s && *s < 0x80)
386 				/* Fast path for plain ASCII characters. */
387 				nb = 1;
388 			else if ((nb = _UTF8_wcrtomb(buf, *s, ps)) ==
389 			    (size_t)-1)
390 				/* Invalid character - wcrtomb() sets errno. */
391 				return ((size_t)-1);
392 			if (*s == L'\0')
393 				return (nbytes + nb - 1);
394 			s++;
395 			nbytes += nb;
396 		}
397 		return (nbytes);
398 	}
399 
400 	while (len > 0 && nwc-- > 0) {
401 		if (0 <= *s && *s < 0x80) {
402 			/* Fast path for plain ASCII characters. */
403 			nb = 1;
404 			*dst = *s;
405 		} else if (len > (size_t)MB_CUR_MAX) {
406 			/* Enough space to translate in-place. */
407 			if ((nb = _UTF8_wcrtomb(dst, *s, ps)) == (size_t)-1) {
408 				*src = s;
409 				return ((size_t)-1);
410 			}
411 		} else {
412 			/*
413 			 * May not be enough space; use temp. buffer.
414 			 */
415 			if ((nb = _UTF8_wcrtomb(buf, *s, ps)) == (size_t)-1) {
416 				*src = s;
417 				return ((size_t)-1);
418 			}
419 			if (nb > (int)len)
420 				/* MB sequence for character won't fit. */
421 				break;
422 			memcpy(dst, buf, nb);
423 		}
424 		if (*s == L'\0') {
425 			*src = NULL;
426 			return (nbytes + nb - 1);
427 		}
428 		s++;
429 		dst += nb;
430 		len -= nb;
431 		nbytes += nb;
432 	}
433 	*src = s;
434 	return (nbytes);
435 }
436