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