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