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