xref: /sqlite-3.40.0/src/utf.c (revision 78d41832)
1 /*
2 ** 2004 April 13
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains routines used to translate between UTF-8,
13 ** UTF-16, UTF-16BE, and UTF-16LE.
14 **
15 ** $Id: utf.c,v 1.70 2008/12/10 22:30:25 shane Exp $
16 **
17 ** Notes on UTF-8:
18 **
19 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
20 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
21 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
22 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
23 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
24 **
25 **
26 ** Notes on UTF-16:  (with wwww+1==uuuuu)
27 **
28 **      Word-0               Word-1          Value
29 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
30 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
31 **
32 **
33 ** BOM or Byte Order Mark:
34 **     0xff 0xfe   little-endian utf-16 follows
35 **     0xfe 0xff   big-endian utf-16 follows
36 **
37 */
38 #include "sqliteInt.h"
39 #include <assert.h>
40 #include "vdbeInt.h"
41 
42 #ifndef SQLITE_AMALGAMATION
43 /*
44 ** The following constant value is used by the SQLITE_BIGENDIAN and
45 ** SQLITE_LITTLEENDIAN macros.
46 */
47 const int sqlite3one = 1;
48 #endif /* SQLITE_AMALGAMATION */
49 
50 /*
51 ** This lookup table is used to help decode the first byte of
52 ** a multi-byte UTF8 character.
53 */
54 static const unsigned char sqlite3Utf8Trans1[] = {
55   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
56   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
57   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
58   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
59   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
60   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
61   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
62   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
63 };
64 
65 
66 #define WRITE_UTF8(zOut, c) {                          \
67   if( c<0x00080 ){                                     \
68     *zOut++ = (u8)(c&0xFF);                            \
69   }                                                    \
70   else if( c<0x00800 ){                                \
71     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
72     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
73   }                                                    \
74   else if( c<0x10000 ){                                \
75     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
76     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
77     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
78   }else{                                               \
79     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
80     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
81     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
82     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
83   }                                                    \
84 }
85 
86 #define WRITE_UTF16LE(zOut, c) {                                    \
87   if( c<=0xFFFF ){                                                  \
88     *zOut++ = (u8)(c&0x00FF);                                       \
89     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
90   }else{                                                            \
91     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
92     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
93     *zOut++ = (u8)(c&0x00FF);                                       \
94     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
95   }                                                                 \
96 }
97 
98 #define WRITE_UTF16BE(zOut, c) {                                    \
99   if( c<=0xFFFF ){                                                  \
100     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
101     *zOut++ = (u8)(c&0x00FF);                                       \
102   }else{                                                            \
103     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
104     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
105     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
106     *zOut++ = (u8)(c&0x00FF);                                       \
107   }                                                                 \
108 }
109 
110 #define READ_UTF16LE(zIn, c){                                         \
111   c = (*zIn++);                                                       \
112   c += ((*zIn++)<<8);                                                 \
113   if( c>=0xD800 && c<0xE000 ){                                       \
114     int c2 = (*zIn++);                                                \
115     c2 += ((*zIn++)<<8);                                              \
116     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
117     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
118   }                                                                   \
119 }
120 
121 #define READ_UTF16BE(zIn, c){                                         \
122   c = ((*zIn++)<<8);                                                  \
123   c += (*zIn++);                                                      \
124   if( c>=0xD800 && c<0xE000 ){                                       \
125     int c2 = ((*zIn++)<<8);                                           \
126     c2 += (*zIn++);                                                   \
127     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
128     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
129   }                                                                   \
130 }
131 
132 /*
133 ** Translate a single UTF-8 character.  Return the unicode value.
134 **
135 ** During translation, assume that the byte that zTerm points
136 ** is a 0x00.
137 **
138 ** Write a pointer to the next unread byte back into *pzNext.
139 **
140 ** Notes On Invalid UTF-8:
141 **
142 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
143 **     be encoded as a multi-byte character.  Any multi-byte character that
144 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
145 **
146 **  *  This routine never allows a UTF16 surrogate value to be encoded.
147 **     If a multi-byte character attempts to encode a value between
148 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
149 **
150 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
151 **     byte of a character are interpreted as single-byte characters
152 **     and rendered as themselves even though they are technically
153 **     invalid characters.
154 **
155 **  *  This routine accepts an infinite number of different UTF8 encodings
156 **     for unicode values 0x80 and greater.  It do not change over-length
157 **     encodings to 0xfffd as some systems recommend.
158 */
159 #define READ_UTF8(zIn, zTerm, c)                           \
160   c = *(zIn++);                                            \
161   if( c>=0xc0 ){                                           \
162     c = sqlite3Utf8Trans1[c-0xc0];                         \
163     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
164       c = (c<<6) + (0x3f & *(zIn++));                      \
165     }                                                      \
166     if( c<0x80                                             \
167         || (c&0xFFFFF800)==0xD800                          \
168         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
169   }
170 int sqlite3Utf8Read(
171   const unsigned char *z,         /* First byte of UTF-8 character */
172   const unsigned char *zTerm,     /* Pretend this byte is 0x00 */
173   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
174 ){
175   int c;
176   READ_UTF8(z, zTerm, c);
177   *pzNext = z;
178   return c;
179 }
180 
181 
182 
183 
184 /*
185 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
186 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
187 */
188 /* #define TRANSLATE_TRACE 1 */
189 
190 #ifndef SQLITE_OMIT_UTF16
191 /*
192 ** This routine transforms the internal text encoding used by pMem to
193 ** desiredEnc. It is an error if the string is already of the desired
194 ** encoding, or if *pMem does not contain a string value.
195 */
196 int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
197   int len;                    /* Maximum length of output string in bytes */
198   unsigned char *zOut;                  /* Output buffer */
199   unsigned char *zIn;                   /* Input iterator */
200   unsigned char *zTerm;                 /* End of input */
201   unsigned char *z;                     /* Output iterator */
202   unsigned int c;
203 
204   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
205   assert( pMem->flags&MEM_Str );
206   assert( pMem->enc!=desiredEnc );
207   assert( pMem->enc!=0 );
208   assert( pMem->n>=0 );
209 
210 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
211   {
212     char zBuf[100];
213     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
214     fprintf(stderr, "INPUT:  %s\n", zBuf);
215   }
216 #endif
217 
218   /* If the translation is between UTF-16 little and big endian, then
219   ** all that is required is to swap the byte order. This case is handled
220   ** differently from the others.
221   */
222   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
223     u8 temp;
224     int rc;
225     rc = sqlite3VdbeMemMakeWriteable(pMem);
226     if( rc!=SQLITE_OK ){
227       assert( rc==SQLITE_NOMEM );
228       return SQLITE_NOMEM;
229     }
230     zIn = (u8*)pMem->z;
231     zTerm = &zIn[pMem->n&~1];
232     while( zIn<zTerm ){
233       temp = *zIn;
234       *zIn = *(zIn+1);
235       zIn++;
236       *zIn++ = temp;
237     }
238     pMem->enc = desiredEnc;
239     goto translate_out;
240   }
241 
242   /* Set len to the maximum number of bytes required in the output buffer. */
243   if( desiredEnc==SQLITE_UTF8 ){
244     /* When converting from UTF-16, the maximum growth results from
245     ** translating a 2-byte character to a 4-byte UTF-8 character.
246     ** A single byte is required for the output string
247     ** nul-terminator.
248     */
249     pMem->n &= ~1;
250     len = pMem->n * 2 + 1;
251   }else{
252     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
253     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
254     ** character. Two bytes are required in the output buffer for the
255     ** nul-terminator.
256     */
257     len = pMem->n * 2 + 2;
258   }
259 
260   /* Set zIn to point at the start of the input buffer and zTerm to point 1
261   ** byte past the end.
262   **
263   ** Variable zOut is set to point at the output buffer, space obtained
264   ** from sqlite3_malloc().
265   */
266   zIn = (u8*)pMem->z;
267   zTerm = &zIn[pMem->n];
268   zOut = sqlite3DbMallocRaw(pMem->db, len);
269   if( !zOut ){
270     return SQLITE_NOMEM;
271   }
272   z = zOut;
273 
274   if( pMem->enc==SQLITE_UTF8 ){
275     if( desiredEnc==SQLITE_UTF16LE ){
276       /* UTF-8 -> UTF-16 Little-endian */
277       while( zIn<zTerm ){
278         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
279         READ_UTF8(zIn, zTerm, c);
280         WRITE_UTF16LE(z, c);
281       }
282     }else{
283       assert( desiredEnc==SQLITE_UTF16BE );
284       /* UTF-8 -> UTF-16 Big-endian */
285       while( zIn<zTerm ){
286         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
287         READ_UTF8(zIn, zTerm, c);
288         WRITE_UTF16BE(z, c);
289       }
290     }
291     pMem->n = (int)(z - zOut);
292     *z++ = 0;
293   }else{
294     assert( desiredEnc==SQLITE_UTF8 );
295     if( pMem->enc==SQLITE_UTF16LE ){
296       /* UTF-16 Little-endian -> UTF-8 */
297       while( zIn<zTerm ){
298         READ_UTF16LE(zIn, c);
299         WRITE_UTF8(z, c);
300       }
301     }else{
302       /* UTF-16 Big-endian -> UTF-8 */
303       while( zIn<zTerm ){
304         READ_UTF16BE(zIn, c);
305         WRITE_UTF8(z, c);
306       }
307     }
308     pMem->n = (int)(z - zOut);
309   }
310   *z = 0;
311   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
312 
313   sqlite3VdbeMemRelease(pMem);
314   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
315   pMem->enc = desiredEnc;
316   pMem->flags |= (MEM_Term|MEM_Dyn);
317   pMem->z = (char*)zOut;
318   pMem->zMalloc = pMem->z;
319 
320 translate_out:
321 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
322   {
323     char zBuf[100];
324     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
325     fprintf(stderr, "OUTPUT: %s\n", zBuf);
326   }
327 #endif
328   return SQLITE_OK;
329 }
330 
331 /*
332 ** This routine checks for a byte-order mark at the beginning of the
333 ** UTF-16 string stored in *pMem. If one is present, it is removed and
334 ** the encoding of the Mem adjusted. This routine does not do any
335 ** byte-swapping, it just sets Mem.enc appropriately.
336 **
337 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
338 ** changed by this function.
339 */
340 int sqlite3VdbeMemHandleBom(Mem *pMem){
341   int rc = SQLITE_OK;
342   u8 bom = 0;
343 
344   if( pMem->n<0 || pMem->n>1 ){
345     u8 b1 = *(u8 *)pMem->z;
346     u8 b2 = *(((u8 *)pMem->z) + 1);
347     if( b1==0xFE && b2==0xFF ){
348       bom = SQLITE_UTF16BE;
349     }
350     if( b1==0xFF && b2==0xFE ){
351       bom = SQLITE_UTF16LE;
352     }
353   }
354 
355   if( bom ){
356     rc = sqlite3VdbeMemMakeWriteable(pMem);
357     if( rc==SQLITE_OK ){
358       pMem->n -= 2;
359       memmove(pMem->z, &pMem->z[2], pMem->n);
360       pMem->z[pMem->n] = '\0';
361       pMem->z[pMem->n+1] = '\0';
362       pMem->flags |= MEM_Term;
363       pMem->enc = bom;
364     }
365   }
366   return rc;
367 }
368 #endif /* SQLITE_OMIT_UTF16 */
369 
370 /*
371 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
372 ** return the number of unicode characters in pZ up to (but not including)
373 ** the first 0x00 byte. If nByte is not less than zero, return the
374 ** number of unicode characters in the first nByte of pZ (or up to
375 ** the first 0x00, whichever comes first).
376 */
377 int sqlite3Utf8CharLen(const char *zIn, int nByte){
378   int r = 0;
379   const u8 *z = (const u8*)zIn;
380   const u8 *zTerm;
381   if( nByte>=0 ){
382     zTerm = &z[nByte];
383   }else{
384     zTerm = (const u8*)(-1);
385   }
386   assert( z<=zTerm );
387   while( *z!=0 && z<zTerm ){
388     SQLITE_SKIP_UTF8(z);
389     r++;
390   }
391   return r;
392 }
393 
394 /* This test function is not currently used by the automated test-suite.
395 ** Hence it is only available in debug builds.
396 */
397 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
398 /*
399 ** Translate UTF-8 to UTF-8.
400 **
401 ** This has the effect of making sure that the string is well-formed
402 ** UTF-8.  Miscoded characters are removed.
403 **
404 ** The translation is done in-place (since it is impossible for the
405 ** correct UTF-8 encoding to be longer than a malformed encoding).
406 */
407 int sqlite3Utf8To8(unsigned char *zIn){
408   unsigned char *zOut = zIn;
409   unsigned char *zStart = zIn;
410   unsigned char *zTerm = &zIn[sqlite3Strlen30((char *)zIn)];
411   u32 c;
412 
413   while( zIn[0] ){
414     c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
415     if( c!=0xfffd ){
416       WRITE_UTF8(zOut, c);
417     }
418   }
419   *zOut = 0;
420   return zOut - zStart;
421 }
422 #endif
423 
424 #ifndef SQLITE_OMIT_UTF16
425 /*
426 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
427 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
428 ** be freed by the calling function.
429 **
430 ** NULL is returned if there is an allocation error.
431 */
432 char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
433   Mem m;
434   memset(&m, 0, sizeof(m));
435   m.db = db;
436   sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
437   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
438   if( db->mallocFailed ){
439     sqlite3VdbeMemRelease(&m);
440     m.z = 0;
441   }
442   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
443   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
444   return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
445 }
446 
447 /*
448 ** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
449 ** return the number of bytes up to (but not including), the first pair
450 ** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
451 ** then return the number of bytes in the first nChar unicode characters
452 ** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
453 */
454 int sqlite3Utf16ByteLen(const void *zIn, int nChar){
455   unsigned int c = 1;
456   char const *z = zIn;
457   int n = 0;
458   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
459     /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
460     ** and in other parts of this file means that at one branch will
461     ** not be covered by coverage testing on any single host. But coverage
462     ** will be complete if the tests are run on both a little-endian and
463     ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
464     ** macros are constant at compile time the compiler can determine
465     ** which branch will be followed. It is therefore assumed that no runtime
466     ** penalty is paid for this "if" statement.
467     */
468     while( c && ((nChar<0) || n<nChar) ){
469       READ_UTF16BE(z, c);
470       n++;
471     }
472   }else{
473     while( c && ((nChar<0) || n<nChar) ){
474       READ_UTF16LE(z, c);
475       n++;
476     }
477   }
478   return (int)(z-(char const *)zIn)-((c==0)?2:0);
479 }
480 
481 #if defined(SQLITE_TEST)
482 /*
483 ** This routine is called from the TCL test function "translate_selftest".
484 ** It checks that the primitives for serializing and deserializing
485 ** characters in each encoding are inverses of each other.
486 */
487 void sqlite3UtfSelfTest(void){
488   unsigned int i, t;
489   unsigned char zBuf[20];
490   unsigned char *z;
491   unsigned char *zTerm;
492   int n;
493   unsigned int c;
494 
495   for(i=0; i<0x00110000; i++){
496     z = zBuf;
497     WRITE_UTF8(z, i);
498     n = (int)(z-zBuf);
499     assert( n>0 && n<=4 );
500     z[0] = 0;
501     zTerm = z;
502     z = zBuf;
503     c = sqlite3Utf8Read(z, zTerm, (const u8**)&z);
504     t = i;
505     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
506     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
507     assert( c==t );
508     assert( (z-zBuf)==n );
509   }
510   for(i=0; i<0x00110000; i++){
511     if( i>=0xD800 && i<0xE000 ) continue;
512     z = zBuf;
513     WRITE_UTF16LE(z, i);
514     n = (int)(z-zBuf);
515     assert( n>0 && n<=4 );
516     z[0] = 0;
517     z = zBuf;
518     READ_UTF16LE(z, c);
519     assert( c==i );
520     assert( (z-zBuf)==n );
521   }
522   for(i=0; i<0x00110000; i++){
523     if( i>=0xD800 && i<0xE000 ) continue;
524     z = zBuf;
525     WRITE_UTF16BE(z, i);
526     n = (int)(z-zBuf);
527     assert( n>0 && n<=4 );
528     z[0] = 0;
529     z = zBuf;
530     READ_UTF16BE(z, c);
531     assert( c==i );
532     assert( (z-zBuf)==n );
533   }
534 }
535 #endif /* SQLITE_TEST */
536 #endif /* SQLITE_OMIT_UTF16 */
537