FreeRDP
Loading...
Searching...
No Matches
unicode_builtin.c
1/*
2 * Copyright 2001-2004 Unicode, Inc.
3 *
4 * Disclaimer
5 *
6 * This source code is provided as is by Unicode, Inc. No claims are
7 * made as to fitness for any particular purpose. No warranties of any
8 * kind are expressed or implied. The recipient agrees to determine
9 * applicability of information provided. If this file has been
10 * purchased on magnetic or optical media from Unicode, Inc., the
11 * sole remedy for any claim will be exchange of defective media
12 * within 90 days of receipt.
13 *
14 * Limitations on Rights to Redistribute This Code
15 *
16 * Unicode, Inc. hereby grants the right to freely use the information
17 * supplied in this file in the creation of products supporting the
18 * Unicode Standard, and to make copies of this file in any form
19 * for internal or external distribution as long as this notice
20 * remains attached.
21 */
22
23/* ---------------------------------------------------------------------
24
25Conversions between UTF32, UTF-16, and UTF-8. Source code file.
26Author: Mark E. Davis, 1994.
27Rev History: Rick McGowan, fixes & updates May 2001.
28Sept 2001: fixed const & error conditions per
29mods suggested by S. Parent & A. Lillich.
30June 2002: Tim Dodd added detection and handling of incomplete
31source sequences, enhanced error detection, added casts
32to eliminate compiler warnings.
33July 2003: slight mods to back out aggressive FFFE detection.
34Jan 2004: updated switches in from-UTF8 conversions.
35Oct 2004: updated to use UNI_MAX_LEGAL_UTF32 in UTF-32 conversions.
36
37See the header file "utf.h" for complete documentation.
38
39------------------------------------------------------------------------ */
40
41#include <winpr/wtypes.h>
42#include <winpr/string.h>
43#include <winpr/assert.h>
44#include <winpr/cast.h>
45
46#include "unicode.h"
47
48#include "../log.h"
49#define TAG WINPR_TAG("unicode")
50
51/*
52 * Character Types:
53 *
54 * UTF8: uint8_t 8 bits
55 * UTF16: uint16_t 16 bits
56 * UTF32: uint32_t 32 bits
57 */
58
59/* Some fundamental constants */
60#define UNI_REPLACEMENT_CHAR (uint32_t)0x0000FFFD
61#define UNI_MAX_BMP (uint32_t)0x0000FFFF
62#define UNI_MAX_UTF16 (uint32_t)0x0010FFFF
63#define UNI_MAX_UTF32 (uint32_t)0x7FFFFFFF
64#define UNI_MAX_LEGAL_UTF32 (uint32_t)0x0010FFFF
65
66typedef enum
67{
68 conversionOK, /* conversion successful */
69 sourceExhausted, /* partial character in source, but hit end */
70 targetExhausted, /* insuff. room in target for conversion */
71 sourceIllegal /* source sequence is illegal/malformed */
72} ConversionResult;
73
74typedef enum
75{
76 strictConversion = 0,
77 lenientConversion
78} ConversionFlags;
79
80static const int halfShift = 10; /* used for shifting by 10 bits */
81
82static const uint32_t halfBase = 0x0010000UL;
83static const uint32_t halfMask = 0x3FFUL;
84
85#define UNI_SUR_HIGH_START (uint32_t)0xD800
86#define UNI_SUR_HIGH_END (uint32_t)0xDBFF
87#define UNI_SUR_LOW_START (uint32_t)0xDC00
88#define UNI_SUR_LOW_END (uint32_t)0xDFFF
89
90/* --------------------------------------------------------------------- */
91
92/*
93 * Index into the table below with the first byte of a UTF-8 sequence to
94 * get the number of trailing bytes that are supposed to follow it.
95 * Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is
96 * left as-is for anyone who may want to do such conversion, which was
97 * allowed in earlier algorithms.
98 */
99static const char trailingBytesForUTF8[256] = {
100 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
101 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
102 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
103 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
106 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
107 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5
108};
109
110/*
111 * Magic values subtracted from a buffer value during UTF8 conversion.
112 * This table contains as many values as there might be trailing bytes
113 * in a UTF-8 sequence.
114 */
115static const uint32_t offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL,
116 0x03C82080UL, 0xFA082080UL, 0x82082080UL };
117
118/*
119 * Once the bits are split out into bytes of UTF-8, this is a mask OR-ed
120 * into the first byte, depending on how many bytes follow. There are
121 * as many entries in this table as there are UTF-8 sequence types.
122 * (I.e., one byte sequence, two byte... etc.). Remember that sequence
123 * for *legal* UTF-8 will be 4 or fewer bytes total.
124 */
125static const uint8_t firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
126
127/* We always need UTF-16LE, even on big endian systems! */
128static WCHAR setWcharFrom(WCHAR w)
129{
130#if defined(__BIG_ENDIAN__)
131 union
132 {
133 WCHAR w;
134 char c[2];
135 } cnv;
136
137 cnv.w = w;
138 const char c = cnv.c[0];
139 cnv.c[0] = cnv.c[1];
140 cnv.c[1] = c;
141 return cnv.w;
142#else
143 return w;
144#endif
145}
146
147/* --------------------------------------------------------------------- */
148
149/* The interface converts a whole buffer to avoid function-call overhead.
150 * Constants have been gathered. Loops & conditionals have been removed as
151 * much as possible for efficiency, in favor of drop-through switches.
152 * (See "Note A" at the bottom of the file for equivalent code.)
153 * If your compiler supports it, the "isLegalUTF8" call can be turned
154 * into an inline function.
155 */
156
157/* --------------------------------------------------------------------- */
158
159static ConversionResult winpr_ConvertUTF16toUTF8_Internal(const uint16_t** sourceStart,
160 const uint16_t* sourceEnd,
161 uint8_t** targetStart,
162 const uint8_t* targetEnd,
163 ConversionFlags flags, size_t* computed)
164{
165 bool computeLength = (!targetEnd) ? true : false;
166 size_t count = 0; /* length-only mode: count, do not advance the null target */
167 const uint16_t* source = *sourceStart;
168 uint8_t* target = *targetStart;
169 ConversionResult result = conversionOK;
170
171 while (source < sourceEnd)
172 {
173 uint32_t ch = 0;
174 unsigned short bytesToWrite = 0;
175 const uint32_t byteMask = 0xBF;
176 const uint32_t byteMark = 0x80;
177 const uint16_t* oldSource =
178 source; /* In case we have to back up because of target overflow. */
179
180 ch = setWcharFrom(*source++);
181
182 /* If we have a surrogate pair, convert to UTF32 first. */
183 if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END)
184 {
185 /* If the 16 bits following the high surrogate are in the source buffer... */
186 if (source < sourceEnd)
187 {
188 uint32_t ch2 = setWcharFrom(*source);
189
190 /* If it's a low surrogate, convert to UTF32. */
191 if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END)
192 {
193 ch = ((ch - UNI_SUR_HIGH_START) << halfShift) + (ch2 - UNI_SUR_LOW_START) +
194 halfBase;
195 ++source;
196 }
197 else if (flags == strictConversion)
198 {
199 /* it's an unpaired high surrogate */
200 --source; /* return to the illegal value itself */
201 result = sourceIllegal;
202 break;
203 }
204 }
205 else
206 {
207 /* We don't have the 16 bits following the high surrogate. */
208 --source; /* return to the high surrogate */
209 result = sourceExhausted;
210 break;
211 }
212 }
213 else if (flags == strictConversion)
214 {
215 /* UTF-16 surrogate values are illegal in UTF-32 */
216 if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END)
217 {
218 --source; /* return to the illegal value itself */
219 result = sourceIllegal;
220 break;
221 }
222 }
223
224 /* Figure out how many bytes the result will require */
225 if (ch < (uint32_t)0x80)
226 {
227 bytesToWrite = 1;
228 }
229 else if (ch < (uint32_t)0x800)
230 {
231 bytesToWrite = 2;
232 }
233 else if (ch < (uint32_t)0x10000)
234 {
235 bytesToWrite = 3;
236 }
237 else if (ch < (uint32_t)0x110000)
238 {
239 bytesToWrite = 4;
240 }
241 else
242 {
243 bytesToWrite = 3;
244 ch = UNI_REPLACEMENT_CHAR;
245 }
246
247 if (computeLength)
248 {
249 count += bytesToWrite;
250 continue;
251 }
252
253 target += bytesToWrite;
254
255 if ((target > targetEnd) && (!computeLength))
256 {
257 source = oldSource; /* Back up source pointer! */
258 target -= bytesToWrite;
259 result = targetExhausted;
260 break;
261 }
262
263 switch (bytesToWrite)
264 {
265 /* note: everything falls through. */
266 case 4:
267 *--target = (uint8_t)((ch | byteMark) & byteMask);
268 ch >>= 6;
269 /* fallthrough */
270 WINPR_FALLTHROUGH
271 case 3:
272 *--target = (uint8_t)((ch | byteMark) & byteMask);
273 ch >>= 6;
274 /* fallthrough */
275 WINPR_FALLTHROUGH
276
277 case 2:
278 *--target = (uint8_t)((ch | byteMark) & byteMask);
279 ch >>= 6;
280 /* fallthrough */
281 WINPR_FALLTHROUGH
282
283 case 1:
284 *--target = (uint8_t)(ch | firstByteMark[bytesToWrite]);
285 break;
286 default:
287 return sourceIllegal;
288 }
289
290 target += bytesToWrite;
291 }
292
293 *sourceStart = source;
294 *targetStart = target;
295 if (computed)
296 *computed = count;
297 return result;
298}
299
300/* --------------------------------------------------------------------- */
301
302/*
303 * Utility routine to tell whether a sequence of bytes is legal UTF-8.
304 * This must be called with the length pre-determined by the first byte.
305 * If not calling this from ConvertUTF8to*, then the length can be set by:
306 * length = trailingBytesForUTF8[*source]+1;
307 * and the sequence is illegal right away if there aren't that many bytes
308 * available.
309 * If presented with a length > 4, this returns false. The Unicode
310 * definition of UTF-8 goes up to 4-byte sequences.
311 */
312
313static bool isLegalUTF8(const uint8_t* source, int length)
314{
315 uint8_t a = 0;
316 const uint8_t* srcptr = source + length;
317
318 switch (length)
319 {
320 default:
321 return false;
322
323 /* Everything else falls through when "true"... */
324 case 4:
325 if ((a = (*--srcptr)) < 0x80 || a > 0xBF)
326 return false;
327 /* fallthrough */
328 WINPR_FALLTHROUGH
329
330 case 3:
331 if ((a = (*--srcptr)) < 0x80 || a > 0xBF)
332 return false;
333 /* fallthrough */
334 WINPR_FALLTHROUGH
335
336 case 2:
337 if ((a = (*--srcptr)) > 0xBF)
338 return false;
339
340 switch (*source)
341 {
342 /* no fall-through in this inner switch */
343 case 0xE0:
344 if (a < 0xA0)
345 return false;
346
347 break;
348
349 case 0xED:
350 if (a > 0x9F)
351 return false;
352
353 break;
354
355 case 0xF0:
356 if (a < 0x90)
357 return false;
358
359 break;
360
361 case 0xF4:
362 if (a > 0x8F)
363 return false;
364
365 break;
366
367 default:
368 if (a < 0x80)
369 return false;
370 break;
371 }
372 /* fallthrough */
373 WINPR_FALLTHROUGH
374
375 case 1:
376 if (*source >= 0x80 && *source < 0xC2)
377 return false;
378 }
379
380 if (*source > 0xF4)
381 return false;
382
383 return true;
384}
385
386/* --------------------------------------------------------------------- */
387
388static ConversionResult winpr_ConvertUTF8toUTF16_Internal(const uint8_t** sourceStart,
389 const uint8_t* sourceEnd,
390 uint16_t** targetStart,
391 const uint16_t* targetEnd,
392 ConversionFlags flags, size_t* computed)
393{
394 bool computeLength = (!targetEnd) ? true : false;
395 size_t count = 0; /* length-only mode: count, do not offset the null target */
396 ConversionResult result = conversionOK;
397 const uint8_t* source = *sourceStart;
398 uint16_t* target = *targetStart;
399
400 while (source < sourceEnd)
401 {
402 uint32_t ch = 0;
403 unsigned short extraBytesToRead =
404 WINPR_ASSERTING_INT_CAST(unsigned short, trailingBytesForUTF8[*source]);
405
406 if ((source + extraBytesToRead) >= sourceEnd)
407 {
408 result = sourceExhausted;
409 break;
410 }
411
412 /* Do this check whether lenient or strict */
413 if (!isLegalUTF8(source, extraBytesToRead + 1))
414 {
415 result = sourceIllegal;
416 break;
417 }
418
419 /*
420 * The cases all fall through. See "Note A" below.
421 */
422 switch (extraBytesToRead)
423 {
424 case 5:
425 ch += *source++;
426 ch <<= 6; /* remember, illegal UTF-8 */
427 /* fallthrough */
428 WINPR_FALLTHROUGH
429
430 case 4:
431 ch += *source++;
432 ch <<= 6; /* remember, illegal UTF-8 */
433 /* fallthrough */
434 WINPR_FALLTHROUGH
435
436 case 3:
437 ch += *source++;
438 ch <<= 6;
439 /* fallthrough */
440 WINPR_FALLTHROUGH
441
442 case 2:
443 ch += *source++;
444 ch <<= 6;
445 /* fallthrough */
446 WINPR_FALLTHROUGH
447
448 case 1:
449 ch += *source++;
450 ch <<= 6;
451 /* fallthrough */
452 WINPR_FALLTHROUGH
453
454 case 0:
455 ch += *source++;
456 break;
457 default:
458 return sourceIllegal;
459 }
460
461 ch -= offsetsFromUTF8[extraBytesToRead];
462
463 if ((target >= targetEnd) && (!computeLength))
464 {
465 source -= (extraBytesToRead + 1); /* Back up source pointer! */
466 result = targetExhausted;
467 break;
468 }
469
470 if (ch <= UNI_MAX_BMP)
471 {
472 /* Target is a character <= 0xFFFF */
473 /* UTF-16 surrogate values are illegal in UTF-32 */
474 if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END)
475 {
476 if (flags == strictConversion)
477 {
478 source -= (extraBytesToRead + 1); /* return to the illegal value itself */
479 result = sourceIllegal;
480 break;
481 }
482 else
483 {
484 if (!computeLength)
485 *target++ = setWcharFrom(UNI_REPLACEMENT_CHAR);
486 else
487 count++;
488 }
489 }
490 else
491 {
492 if (!computeLength)
493 *target++ = setWcharFrom((WCHAR)ch); /* normal case */
494 else
495 count++;
496 }
497 }
498 else if (ch > UNI_MAX_UTF16)
499 {
500 if (flags == strictConversion)
501 {
502 result = sourceIllegal;
503 source -= (extraBytesToRead + 1); /* return to the start */
504 break; /* Bail out; shouldn't continue */
505 }
506 else
507 {
508 if (!computeLength)
509 *target++ = setWcharFrom(UNI_REPLACEMENT_CHAR);
510 else
511 count++;
512 }
513 }
514 else
515 {
516 /* target is a character in range 0xFFFF - 0x10FFFF. */
517 if ((!computeLength) && (target + 1 >= targetEnd))
518 {
519 source -= (extraBytesToRead + 1); /* Back up source pointer! */
520 result = targetExhausted;
521 break;
522 }
523
524 ch -= halfBase;
525
526 if (!computeLength)
527 {
528 *target++ = setWcharFrom((WCHAR)((ch >> halfShift) + UNI_SUR_HIGH_START));
529 *target++ = setWcharFrom((WCHAR)((ch & halfMask) + UNI_SUR_LOW_START));
530 }
531 else
532 count += 2;
533 }
534 }
535
536 *sourceStart = source;
537 *targetStart = target;
538 if (computed)
539 *computed = count;
540 return result;
541}
542
546
547static int winpr_ConvertUTF8toUTF16(const uint8_t* src, int cchSrc, uint16_t* dst, int cchDst)
548{
549 size_t length = 0;
550 uint16_t* dstBeg = nullptr;
551 uint16_t* dstEnd = nullptr;
552 const uint8_t* srcBeg = nullptr;
553 const uint8_t* srcEnd = nullptr;
554 ConversionResult result = sourceIllegal;
555
556 if (cchSrc == -1)
557 cchSrc = (int)strnlen((const char*)src, INT32_MAX - 1) + 1;
558
559 srcBeg = src;
560 srcEnd = &src[cchSrc];
561
562 if (cchDst == 0)
563 {
564 result = winpr_ConvertUTF8toUTF16_Internal(&srcBeg, srcEnd, &dstBeg, dstEnd,
565 strictConversion, &length);
566 }
567 else
568 {
569 dstBeg = dst;
570 dstEnd = &dst[cchDst];
571
572 result = winpr_ConvertUTF8toUTF16_Internal(&srcBeg, srcEnd, &dstBeg, dstEnd,
573 strictConversion, nullptr);
574
575 length = dstBeg - dst;
576 }
577
578 if (result == targetExhausted)
579 {
580 SetLastError(ERROR_INSUFFICIENT_BUFFER);
581 return 0;
582 }
583
584 return (result == conversionOK) ? WINPR_ASSERTING_INT_CAST(int, length) : 0;
585}
586
587static int winpr_ConvertUTF16toUTF8(const uint16_t* src, int cchSrc, uint8_t* dst, int cchDst)
588{
589 size_t length = 0;
590 uint8_t* dstBeg = nullptr;
591 uint8_t* dstEnd = nullptr;
592 const uint16_t* srcBeg = nullptr;
593 const uint16_t* srcEnd = nullptr;
594 ConversionResult result = sourceIllegal;
595
596 if (cchSrc == -1)
597 cchSrc = (int)_wcsnlen((const WCHAR*)src, INT32_MAX - 1) + 1;
598
599 srcBeg = src;
600 srcEnd = &src[cchSrc];
601
602 if (cchDst == 0)
603 {
604 result = winpr_ConvertUTF16toUTF8_Internal(&srcBeg, srcEnd, &dstBeg, dstEnd,
605 strictConversion, &length);
606 }
607 else
608 {
609 dstBeg = dst;
610 dstEnd = &dst[cchDst];
611
612 result = winpr_ConvertUTF16toUTF8_Internal(&srcBeg, srcEnd, &dstBeg, dstEnd,
613 strictConversion, nullptr);
614
615 length = dstBeg - dst;
616 }
617
618 if (result == targetExhausted)
619 {
620 SetLastError(ERROR_INSUFFICIENT_BUFFER);
621 return 0;
622 }
623
624 return (result == conversionOK) ? WINPR_ASSERTING_INT_CAST(int, length) : 0;
625}
626
627/* --------------------------------------------------------------------- */
628
629int int_MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte,
630 LPWSTR lpWideCharStr, int cchWideChar)
631{
632 size_t cbCharLen = (size_t)cbMultiByte;
633
634 WINPR_UNUSED(dwFlags);
635
636 /* If cbMultiByte is 0, the function fails */
637 if ((cbMultiByte == 0) || (cbMultiByte < -1))
638 return 0;
639
640 if (cchWideChar < 0)
641 return -1;
642
643 if (cbMultiByte < 0)
644 {
645 const size_t len = strlen(lpMultiByteStr);
646 if (len >= INT32_MAX)
647 return 0;
648 cbCharLen = (int)len + 1;
649 }
650 else
651 cbCharLen = cbMultiByte;
652
653 WINPR_ASSERT(lpMultiByteStr);
654 switch (CodePage)
655 {
656 case CP_ACP:
657 case CP_UTF8:
658 break;
659
660 default:
661 WLog_ERR(TAG, "Unsupported encoding %u", CodePage);
662 return 0;
663 }
664
665 return winpr_ConvertUTF8toUTF16((const uint8_t*)lpMultiByteStr,
666 WINPR_ASSERTING_INT_CAST(int, cbCharLen),
667 (uint16_t*)lpWideCharStr, cchWideChar);
668}
669
670int int_WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar,
671 LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar,
672 LPBOOL lpUsedDefaultChar)
673{
674 size_t cbCharLen = (size_t)cchWideChar;
675
676 WINPR_UNUSED(dwFlags);
677 /* If cchWideChar is 0, the function fails */
678 if ((cchWideChar == 0) || (cchWideChar < -1))
679 return 0;
680
681 if (cbMultiByte < 0)
682 return -1;
683
684 WINPR_ASSERT(lpWideCharStr);
685 /* If cchWideChar is -1, the string is null-terminated */
686 if (cchWideChar == -1)
687 {
688 const size_t len = _wcslen(lpWideCharStr);
689 if (len >= INT32_MAX)
690 return 0;
691 cbCharLen = (int)len + 1;
692 }
693 else
694 cbCharLen = cchWideChar;
695
696 /*
697 * if cbMultiByte is 0, the function returns the required buffer size
698 * in bytes for lpMultiByteStr and makes no use of the output parameter itself.
699 */
700
701 return winpr_ConvertUTF16toUTF8((const uint16_t*)lpWideCharStr,
702 WINPR_ASSERTING_INT_CAST(int, cbCharLen),
703 (uint8_t*)lpMultiByteStr, cbMultiByte);
704}