1 /*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 #define LOG_TAG "unicode"
17 // # #include <android-base/macros.h>
18
19 #ifndef FALLTHROUGH_INTENDED
20 #define FALLTHROUGH_INTENDED [[clang::fallthrough]] // NOLINT
21 #endif
22
23 #include <limits.h>
24 #include <utils/Unicode.h>
25 #include <log/log.h>
26 #if defined(_WIN32)
27 # undef nhtol
28 # undef htonl
29 # undef nhtos
30 # undef htons
31 # define ntohl(x) ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
32 # define htonl(x) ntohl(x)
33 # define ntohs(x) ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
34 # define htons(x) ntohs(x)
35 #else
36 # include <netinet/in.h>
37 #endif
38 extern "C" {
39 static const char32_t kByteMask = 0x000000BF;
40 static const char32_t kByteMark = 0x00000080;
41 // Surrogates aren't valid for UTF-32 characters, so define some
42 // constants that will let us screen them out.
43 static const char32_t kUnicodeSurrogateHighStart = 0x0000D800;
44 // Unused, here for completeness:
45 // static const char32_t kUnicodeSurrogateHighEnd = 0x0000DBFF;
46 // static const char32_t kUnicodeSurrogateLowStart = 0x0000DC00;
47 static const char32_t kUnicodeSurrogateLowEnd = 0x0000DFFF;
48 static const char32_t kUnicodeSurrogateStart = kUnicodeSurrogateHighStart;
49 static const char32_t kUnicodeSurrogateEnd = kUnicodeSurrogateLowEnd;
50 static const char32_t kUnicodeMaxCodepoint = 0x0010FFFF;
51 // Mask used to set appropriate bits in first byte of UTF-8 sequence,
52 // indexed by number of bytes in the sequence.
53 // 0xxxxxxx
54 // -> (00-7f) 7bit. Bit mask for the first byte is 0x00000000
55 // 110yyyyx 10xxxxxx
56 // -> (c0-df)(80-bf) 11bit. Bit mask is 0x000000C0
57 // 1110yyyy 10yxxxxx 10xxxxxx
58 // -> (e0-ef)(80-bf)(80-bf) 16bit. Bit mask is 0x000000E0
59 // 11110yyy 10yyxxxx 10xxxxxx 10xxxxxx
60 // -> (f0-f7)(80-bf)(80-bf)(80-bf) 21bit. Bit mask is 0x000000F0
61 static const char32_t kFirstByteMark[] = {
62 0x00000000, 0x00000000, 0x000000C0, 0x000000E0, 0x000000F0
63 };
64 // --------------------------------------------------------------------------
65 // UTF-32
66 // --------------------------------------------------------------------------
67 /**
68 * Return number of UTF-8 bytes required for the character. If the character
69 * is invalid, return size of 0.
70 */
utf32_codepoint_utf8_length(char32_t srcChar)71 static inline size_t utf32_codepoint_utf8_length(char32_t srcChar)
72 {
73 // Figure out how many bytes the result will require.
74 if (srcChar < 0x00000080) {
75 return 1;
76 } else if (srcChar < 0x00000800) {
77 return 2;
78 } else if (srcChar < 0x00010000) {
79 if ((srcChar < kUnicodeSurrogateStart) || (srcChar > kUnicodeSurrogateEnd)) {
80 return 3;
81 } else {
82 // Surrogates are invalid UTF-32 characters.
83 return 0;
84 }
85 }
86 // Max code point for Unicode is 0x0010FFFF.
87 else if (srcChar <= kUnicodeMaxCodepoint) {
88 return 4;
89 } else {
90 // Invalid UTF-32 character.
91 return 0;
92 }
93 }
94 // Write out the source character to <dstP>.
utf32_codepoint_to_utf8(uint8_t * dstP,char32_t srcChar,size_t bytes)95 static inline void utf32_codepoint_to_utf8(uint8_t* dstP, char32_t srcChar, size_t bytes)
96 {
97 dstP += bytes;
98 switch (bytes)
99 { /* note: everything falls through. */
100 case 4: *--dstP = (uint8_t)((srcChar | kByteMark) & kByteMask); srcChar >>= 6;
101 FALLTHROUGH_INTENDED;
102 case 3: *--dstP = (uint8_t)((srcChar | kByteMark) & kByteMask); srcChar >>= 6;
103 FALLTHROUGH_INTENDED;
104 case 2: *--dstP = (uint8_t)((srcChar | kByteMark) & kByteMask); srcChar >>= 6;
105 FALLTHROUGH_INTENDED;
106 case 1: *--dstP = (uint8_t)(srcChar | kFirstByteMark[bytes]);
107 }
108 }
strlen32(const char32_t * s)109 size_t strlen32(const char32_t *s)
110 {
111 const char32_t *ss = s;
112 while ( *ss )
113 ss++;
114 return ss-s;
115 }
strnlen32(const char32_t * s,size_t maxlen)116 size_t strnlen32(const char32_t *s, size_t maxlen)
117 {
118 const char32_t *ss = s;
119 while ((maxlen > 0) && *ss) {
120 ss++;
121 maxlen--;
122 }
123 return ss-s;
124 }
utf32_at_internal(const char * cur,size_t * num_read)125 static inline int32_t utf32_at_internal(const char* cur, size_t *num_read)
126 {
127 const char first_char = *cur;
128 if ((first_char & 0x80) == 0) { // ASCII
129 *num_read = 1;
130 return *cur;
131 }
132 cur++;
133 char32_t mask, to_ignore_mask;
134 size_t num_to_read = 0;
135 char32_t utf32 = first_char;
136 for (num_to_read = 1, mask = 0x40, to_ignore_mask = 0xFFFFFF80;
137 (first_char & mask);
138 num_to_read++, to_ignore_mask |= mask, mask >>= 1) {
139 // 0x3F == 00111111
140 utf32 = (utf32 << 6) + (*cur++ & 0x3F);
141 }
142 to_ignore_mask |= mask;
143 utf32 &= ~(to_ignore_mask << (6 * (num_to_read - 1)));
144 *num_read = num_to_read;
145 return static_cast<int32_t>(utf32);
146 }
utf32_from_utf8_at(const char * src,size_t src_len,size_t index,size_t * next_index)147 int32_t utf32_from_utf8_at(const char *src, size_t src_len, size_t index, size_t *next_index)
148 {
149 if (index >= src_len) {
150 return -1;
151 }
152 size_t dummy_index;
153 if (next_index == nullptr) {
154 next_index = &dummy_index;
155 }
156 size_t num_read;
157 int32_t ret = utf32_at_internal(src + index, &num_read);
158 if (ret >= 0) {
159 *next_index = index + num_read;
160 }
161 return ret;
162 }
utf32_to_utf8_length(const char32_t * src,size_t src_len)163 ssize_t utf32_to_utf8_length(const char32_t *src, size_t src_len)
164 {
165 if (src == nullptr || src_len == 0) {
166 return -1;
167 }
168 size_t ret = 0;
169 const char32_t *end = src + src_len;
170 while (src < end) {
171 size_t char_len = utf32_codepoint_utf8_length(*src++);
172 if (SSIZE_MAX - char_len < ret) {
173 // If this happens, we would overflow the ssize_t type when
174 // returning from this function, so we cannot express how
175 // long this string is in an ssize_t.
176 android_errorWriteLog(0x534e4554, "37723026");
177 return -1;
178 }
179 ret += char_len;
180 }
181 return ret;
182 }
utf32_to_utf8(const char32_t * src,size_t src_len,char * dst,size_t dst_len)183 void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst, size_t dst_len)
184 {
185 if (src == nullptr || src_len == 0 || dst == nullptr) {
186 return;
187 }
188 const char32_t *cur_utf32 = src;
189 const char32_t *end_utf32 = src + src_len;
190 char *cur = dst;
191 while (cur_utf32 < end_utf32) {
192 size_t len = utf32_codepoint_utf8_length(*cur_utf32);
193 LOG_ALWAYS_FATAL_IF(dst_len < len, "%zu < %zu", dst_len, len);
194 utf32_codepoint_to_utf8((uint8_t *)cur, *cur_utf32++, len);
195 cur += len;
196 dst_len -= len;
197 }
198 LOG_ALWAYS_FATAL_IF(dst_len < 1, "dst_len < 1: %zu < 1", dst_len);
199 *cur = '\0';
200 }
201 // --------------------------------------------------------------------------
202 // UTF-16
203 // --------------------------------------------------------------------------
strcmp16(const char16_t * s1,const char16_t * s2)204 int strcmp16(const char16_t *s1, const char16_t *s2)
205 {
206 char16_t ch;
207 int d = 0;
208 while ( 1 ) {
209 d = (int)(ch = *s1++) - (int)*s2++;
210 if ( d || !ch )
211 break;
212 }
213 return d;
214 }
strncmp16(const char16_t * s1,const char16_t * s2,size_t n)215 int strncmp16(const char16_t *s1, const char16_t *s2, size_t n)
216 {
217 char16_t ch;
218 int d = 0;
219 if (n == 0) {
220 return 0;
221 }
222 do {
223 d = (int)(ch = *s1++) - (int)*s2++;
224 if ( d || !ch ) {
225 break;
226 }
227 } while (--n);
228 return d;
229 }
strcpy16(char16_t * dst,const char16_t * src)230 char16_t *strcpy16(char16_t *dst, const char16_t *src)
231 {
232 char16_t *q = dst;
233 const char16_t *p = src;
234 char16_t ch;
235 do {
236 *q++ = ch = *p++;
237 } while ( ch );
238 return dst;
239 }
strlen16(const char16_t * s)240 size_t strlen16(const char16_t *s)
241 {
242 const char16_t *ss = s;
243 while ( *ss )
244 ss++;
245 return ss-s;
246 }
strnlen16(const char16_t * s,size_t maxlen)247 size_t strnlen16(const char16_t *s, size_t maxlen)
248 {
249 const char16_t *ss = s;
250 /* Important: the maxlen test must precede the reference through ss;
251 since the byte beyond the maximum may segfault */
252 while ((maxlen > 0) && *ss) {
253 ss++;
254 maxlen--;
255 }
256 return ss-s;
257 }
strstr16(const char16_t * src,const char16_t * target)258 char16_t* strstr16(const char16_t* src, const char16_t* target)
259 {
260 const char16_t needle = *target;
261 if (needle == '\0') return (char16_t*)src;
262 const size_t target_len = strlen16(++target);
263 do {
264 do {
265 if (*src == '\0') {
266 return nullptr;
267 }
268 } while (*src++ != needle);
269 } while (strncmp16(src, target, target_len) != 0);
270 src--;
271 return (char16_t*)src;
272 }
strzcmp16(const char16_t * s1,size_t n1,const char16_t * s2,size_t n2)273 int strzcmp16(const char16_t *s1, size_t n1, const char16_t *s2, size_t n2)
274 {
275 const char16_t* e1 = s1+n1;
276 const char16_t* e2 = s2+n2;
277 while (s1 < e1 && s2 < e2) {
278 const int d = (int)*s1++ - (int)*s2++;
279 if (d) {
280 return d;
281 }
282 }
283 return n1 < n2
284 ? (0 - (int)*s2)
285 : (n1 > n2
286 ? ((int)*s1 - 0)
287 : 0);
288 }
utf16_to_utf8(const char16_t * src,size_t src_len,char * dst,size_t dst_len)289 void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst, size_t dst_len)
290 {
291 if (src == nullptr || src_len == 0 || dst == nullptr) {
292 return;
293 }
294 const char16_t* cur_utf16 = src;
295 const char16_t* const end_utf16 = src + src_len;
296 char *cur = dst;
297 while (cur_utf16 < end_utf16) {
298 char32_t utf32;
299 // surrogate pairs
300 if((*cur_utf16 & 0xFC00) == 0xD800 && (cur_utf16 + 1) < end_utf16
301 && (*(cur_utf16 + 1) & 0xFC00) == 0xDC00) {
302 utf32 = (*cur_utf16++ - 0xD800) << 10;
303 utf32 |= *cur_utf16++ - 0xDC00;
304 utf32 += 0x10000;
305 } else {
306 utf32 = (char32_t) *cur_utf16++;
307 }
308 const size_t len = utf32_codepoint_utf8_length(utf32);
309 LOG_ALWAYS_FATAL_IF(dst_len < len, "%zu < %zu", dst_len, len);
310 utf32_codepoint_to_utf8((uint8_t*)cur, utf32, len);
311 cur += len;
312 dst_len -= len;
313 }
314 LOG_ALWAYS_FATAL_IF(dst_len < 1, "%zu < 1", dst_len);
315 *cur = '\0';
316 }
317 // --------------------------------------------------------------------------
318 // UTF-8
319 // --------------------------------------------------------------------------
utf8_length(const char * src)320 ssize_t utf8_length(const char *src)
321 {
322 const char *cur = src;
323 size_t ret = 0;
324 while (*cur != '\0') {
325 const char first_char = *cur++;
326 if ((first_char & 0x80) == 0) { // ASCII
327 ret += 1;
328 continue;
329 }
330 // (UTF-8's character must not be like 10xxxxxx,
331 // but 110xxxxx, 1110xxxx, ... or 1111110x)
332 if ((first_char & 0x40) == 0) {
333 return -1;
334 }
335 int32_t mask, to_ignore_mask;
336 size_t num_to_read = 0;
337 char32_t utf32 = 0;
338 for (num_to_read = 1, mask = 0x40, to_ignore_mask = 0x80;
339 num_to_read < 5 && (first_char & mask);
340 num_to_read++, to_ignore_mask |= mask, mask >>= 1) {
341 if ((*cur & 0xC0) != 0x80) { // must be 10xxxxxx
342 return -1;
343 }
344 // 0x3F == 00111111
345 utf32 = (utf32 << 6) + (*cur++ & 0x3F);
346 }
347 // "first_char" must be (110xxxxx - 11110xxx)
348 if (num_to_read == 5) {
349 return -1;
350 }
351 to_ignore_mask |= mask;
352 utf32 |= ((~to_ignore_mask) & first_char) << (6 * (num_to_read - 1));
353 if (utf32 > kUnicodeMaxCodepoint) {
354 return -1;
355 }
356 ret += num_to_read;
357 }
358 return ret;
359 }
utf16_to_utf8_length(const char16_t * src,size_t src_len)360 ssize_t utf16_to_utf8_length(const char16_t *src, size_t src_len)
361 {
362 if (src == nullptr || src_len == 0) {
363 return -1;
364 }
365 size_t ret = 0;
366 const char16_t* const end = src + src_len;
367 while (src < end) {
368 size_t char_len;
369 if ((*src & 0xFC00) == 0xD800 && (src + 1) < end
370 && (*(src + 1) & 0xFC00) == 0xDC00) {
371 // surrogate pairs are always 4 bytes.
372 char_len = 4;
373 src += 2;
374 } else {
375 char_len = utf32_codepoint_utf8_length((char32_t)*src++);
376 }
377 if (SSIZE_MAX - char_len < ret) {
378 // If this happens, we would overflow the ssize_t type when
379 // returning from this function, so we cannot express how
380 // long this string is in an ssize_t.
381 android_errorWriteLog(0x534e4554, "37723026");
382 return -1;
383 }
384 ret += char_len;
385 }
386 return ret;
387 }
388 /**
389 * Returns 1-4 based on the number of leading bits.
390 *
391 * 1111 -> 4
392 * 1110 -> 3
393 * 110x -> 2
394 * 10xx -> 1
395 * 0xxx -> 1
396 */
utf8_codepoint_len(uint8_t ch)397 static inline size_t utf8_codepoint_len(uint8_t ch)
398 {
399 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
400 }
utf8_shift_and_mask(uint32_t * codePoint,const uint8_t byte)401 static inline void utf8_shift_and_mask(uint32_t* codePoint, const uint8_t byte)
402 {
403 *codePoint <<= 6;
404 *codePoint |= 0x3F & byte;
405 }
utf8_to_utf32_length(const char * src,size_t src_len)406 size_t utf8_to_utf32_length(const char *src, size_t src_len)
407 {
408 if (src == nullptr || src_len == 0) {
409 return 0;
410 }
411 size_t ret = 0;
412 const char* cur;
413 const char* end;
414 size_t num_to_skip;
415 for (cur = src, end = src + src_len, num_to_skip = 1;
416 cur < end;
417 cur += num_to_skip, ret++) {
418 const char first_char = *cur;
419 num_to_skip = 1;
420 if ((first_char & 0x80) == 0) { // ASCII
421 continue;
422 }
423 int32_t mask;
424 for (mask = 0x40; (first_char & mask); num_to_skip++, mask >>= 1) {
425 }
426 }
427 return ret;
428 }
utf8_to_utf32(const char * src,size_t src_len,char32_t * dst)429 void utf8_to_utf32(const char* src, size_t src_len, char32_t* dst)
430 {
431 if (src == nullptr || src_len == 0 || dst == nullptr) {
432 return;
433 }
434 const char* cur = src;
435 const char* const end = src + src_len;
436 char32_t* cur_utf32 = dst;
437 while (cur < end) {
438 size_t num_read;
439 *cur_utf32++ = static_cast<char32_t>(utf32_at_internal(cur, &num_read));
440 cur += num_read;
441 }
442 *cur_utf32 = 0;
443 }
utf8_to_utf32_codepoint(const uint8_t * src,size_t length)444 static inline uint32_t utf8_to_utf32_codepoint(const uint8_t *src, size_t length)
445 {
446 uint32_t unicode;
447 switch (length)
448 {
449 case 1:
450 return src[0];
451 case 2:
452 unicode = src[0] & 0x1f;
453 utf8_shift_and_mask(&unicode, src[1]);
454 return unicode;
455 case 3:
456 unicode = src[0] & 0x0f;
457 utf8_shift_and_mask(&unicode, src[1]);
458 utf8_shift_and_mask(&unicode, src[2]);
459 return unicode;
460 case 4:
461 unicode = src[0] & 0x07;
462 utf8_shift_and_mask(&unicode, src[1]);
463 utf8_shift_and_mask(&unicode, src[2]);
464 utf8_shift_and_mask(&unicode, src[3]);
465 return unicode;
466 default:
467 return 0xffff;
468 }
469 //printf("Char at %p: len=%d, utf-16=%p\n", src, length, (void*)result);
470 }
utf8_to_utf16_length(const uint8_t * u8str,size_t u8len,bool overreadIsFatal)471 ssize_t utf8_to_utf16_length(const uint8_t* u8str, size_t u8len, bool overreadIsFatal)
472 {
473 const uint8_t* const u8end = u8str + u8len;
474 const uint8_t* u8cur = u8str;
475 /* Validate that the UTF-8 is the correct len */
476 size_t u16measuredLen = 0;
477 while (u8cur < u8end) {
478 u16measuredLen++;
479 int u8charLen = utf8_codepoint_len(*u8cur);
480 // Malformed utf8, some characters are beyond the end.
481 // Cases:
482 // If u8charLen == 1, this becomes u8cur >= u8end, which cannot happen as u8cur < u8end,
483 // then this condition fail and we continue, as expected.
484 // If u8charLen == 2, this becomes u8cur + 1 >= u8end, which fails only if
485 // u8cur == u8end - 1, that is, there was only one remaining character to read but we need
486 // 2 of them. This condition holds and we return -1, as expected.
487 if (u8cur + u8charLen - 1 >= u8end) {
488 if (overreadIsFatal) {
489 LOG_ALWAYS_FATAL("Attempt to overread computing length of utf8 string");
490 } else {
491 return -1;
492 }
493 }
494 uint32_t codepoint = utf8_to_utf32_codepoint(u8cur, u8charLen);
495 if (codepoint > 0xFFFF) u16measuredLen++; // this will be a surrogate pair in utf16
496 u8cur += u8charLen;
497 }
498 /**
499 * Make sure that we ended where we thought we would and the output UTF-16
500 * will be exactly how long we were told it would be.
501 */
502 if (u8cur != u8end) {
503 return -1;
504 }
505 return u16measuredLen;
506 }
utf8_to_utf16(const uint8_t * u8str,size_t u8len,char16_t * u16str,size_t u16len)507 char16_t* utf8_to_utf16(const uint8_t* u8str, size_t u8len, char16_t* u16str, size_t u16len) {
508 // A value > SSIZE_MAX is probably a negative value returned as an error and casted.
509 LOG_ALWAYS_FATAL_IF(u16len == 0 || u16len > SSIZE_MAX, "u16len is %zu", u16len);
510 char16_t* end = utf8_to_utf16_no_null_terminator(u8str, u8len, u16str, u16len - 1);
511 *end = 0;
512 return end;
513 }
utf8_to_utf16_no_null_terminator(const uint8_t * src,size_t srcLen,char16_t * dst,size_t dstLen)514 char16_t* utf8_to_utf16_no_null_terminator(
515 const uint8_t* src, size_t srcLen, char16_t* dst, size_t dstLen) {
516 if (dstLen == 0) {
517 return dst;
518 }
519 // A value > SSIZE_MAX is probably a negative value returned as an error and casted.
520 LOG_ALWAYS_FATAL_IF(dstLen > SSIZE_MAX, "dstLen is %zu", dstLen);
521 const uint8_t* const u8end = src + srcLen;
522 const uint8_t* u8cur = src;
523 const char16_t* const u16end = dst + dstLen;
524 char16_t* u16cur = dst;
525 while (u8cur < u8end && u16cur < u16end) {
526 size_t u8len = utf8_codepoint_len(*u8cur);
527 uint32_t codepoint = utf8_to_utf32_codepoint(u8cur, u8len);
528 // Convert the UTF32 codepoint to one or more UTF16 codepoints
529 if (codepoint <= 0xFFFF) {
530 // Single UTF16 character
531 *u16cur++ = (char16_t) codepoint;
532 } else {
533 // Multiple UTF16 characters with surrogates
534 codepoint = codepoint - 0x10000;
535 *u16cur++ = (char16_t) ((codepoint >> 10) + 0xD800);
536 if (u16cur >= u16end) {
537 // Ooops... not enough room for this surrogate pair.
538 return u16cur-1;
539 }
540 *u16cur++ = (char16_t) ((codepoint & 0x3FF) + 0xDC00);
541 }
542 u8cur += u8len;
543 }
544 return u16cur;
545 }
546 }
547