xref: /sqlite-3.40.0/src/utf.c (revision 8a29dfde)
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.61 2008/03/28 15:44:10 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 int sqlite3Utf8Read(
158   const unsigned char *z,         /* First byte of UTF-8 character */
159   const unsigned char *zTerm,     /* Pretend this byte is 0x00 */
160   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
161 ){
162   int c = *(z++);
163   if( c>=0xc0 ){
164     c = sqlite3UtfTrans1[c-0xc0];
165     while( z!=zTerm && (*z & 0xc0)==0x80 ){
166       c = (c<<6) + (0x3f & *(z++));
167     }
168     if( c<0x80
169         || (c&0xFFFFF800)==0xD800
170         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
171   }
172   *pzNext = z;
173   return c;
174 }
175 
176 
177 
178 /*
179 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
180 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
181 */
182 /* #define TRANSLATE_TRACE 1 */
183 
184 #ifndef SQLITE_OMIT_UTF16
185 /*
186 ** This routine transforms the internal text encoding used by pMem to
187 ** desiredEnc. It is an error if the string is already of the desired
188 ** encoding, or if *pMem does not contain a string value.
189 */
190 int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
191   int len;                    /* Maximum length of output string in bytes */
192   unsigned char *zOut;                  /* Output buffer */
193   unsigned char *zIn;                   /* Input iterator */
194   unsigned char *zTerm;                 /* End of input */
195   unsigned char *z;                     /* Output iterator */
196   unsigned int c;
197 
198   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
199   assert( pMem->flags&MEM_Str );
200   assert( pMem->enc!=desiredEnc );
201   assert( pMem->enc!=0 );
202   assert( pMem->n>=0 );
203 
204 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
205   {
206     char zBuf[100];
207     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
208     fprintf(stderr, "INPUT:  %s\n", zBuf);
209   }
210 #endif
211 
212   /* If the translation is between UTF-16 little and big endian, then
213   ** all that is required is to swap the byte order. This case is handled
214   ** differently from the others.
215   */
216   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
217     u8 temp;
218     int rc;
219     rc = sqlite3VdbeMemMakeWriteable(pMem);
220     if( rc!=SQLITE_OK ){
221       assert( rc==SQLITE_NOMEM );
222       return SQLITE_NOMEM;
223     }
224     zIn = (u8*)pMem->z;
225     zTerm = &zIn[pMem->n];
226     while( zIn<zTerm ){
227       temp = *zIn;
228       *zIn = *(zIn+1);
229       zIn++;
230       *zIn++ = temp;
231     }
232     pMem->enc = desiredEnc;
233     goto translate_out;
234   }
235 
236   /* Set len to the maximum number of bytes required in the output buffer. */
237   if( desiredEnc==SQLITE_UTF8 ){
238     /* When converting from UTF-16, the maximum growth results from
239     ** translating a 2-byte character to a 4-byte UTF-8 character.
240     ** A single byte is required for the output string
241     ** nul-terminator.
242     */
243     len = pMem->n * 2 + 1;
244   }else{
245     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
246     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
247     ** character. Two bytes are required in the output buffer for the
248     ** nul-terminator.
249     */
250     len = pMem->n * 2 + 2;
251   }
252 
253   /* Set zIn to point at the start of the input buffer and zTerm to point 1
254   ** byte past the end.
255   **
256   ** Variable zOut is set to point at the output buffer, space obtained
257   ** from sqlite3_malloc().
258   */
259   zIn = (u8*)pMem->z;
260   zTerm = &zIn[pMem->n];
261   zOut = sqlite3DbMallocRaw(pMem->db, len);
262   if( !zOut ){
263     return SQLITE_NOMEM;
264   }
265   z = zOut;
266 
267   if( pMem->enc==SQLITE_UTF8 ){
268     if( desiredEnc==SQLITE_UTF16LE ){
269       /* UTF-8 -> UTF-16 Little-endian */
270       while( zIn<zTerm ){
271         c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
272         WRITE_UTF16LE(z, c);
273       }
274     }else{
275       assert( desiredEnc==SQLITE_UTF16BE );
276       /* UTF-8 -> UTF-16 Big-endian */
277       while( zIn<zTerm ){
278         c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
279         WRITE_UTF16BE(z, c);
280       }
281     }
282     pMem->n = z - zOut;
283     *z++ = 0;
284   }else{
285     assert( desiredEnc==SQLITE_UTF8 );
286     if( pMem->enc==SQLITE_UTF16LE ){
287       /* UTF-16 Little-endian -> UTF-8 */
288       while( zIn<zTerm ){
289         READ_UTF16LE(zIn, c);
290         WRITE_UTF8(z, c);
291       }
292     }else{
293       /* UTF-16 Little-endian -> UTF-8 */
294       while( zIn<zTerm ){
295         READ_UTF16BE(zIn, c);
296         WRITE_UTF8(z, c);
297       }
298     }
299     pMem->n = z - zOut;
300   }
301   *z = 0;
302   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
303 
304   sqlite3VdbeMemRelease(pMem);
305   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
306   pMem->enc = desiredEnc;
307   pMem->flags |= (MEM_Term|MEM_Dyn);
308   pMem->z = (char*)zOut;
309   pMem->zMalloc = pMem->z;
310 
311 translate_out:
312 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
313   {
314     char zBuf[100];
315     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
316     fprintf(stderr, "OUTPUT: %s\n", zBuf);
317   }
318 #endif
319   return SQLITE_OK;
320 }
321 
322 /*
323 ** This routine checks for a byte-order mark at the beginning of the
324 ** UTF-16 string stored in *pMem. If one is present, it is removed and
325 ** the encoding of the Mem adjusted. This routine does not do any
326 ** byte-swapping, it just sets Mem.enc appropriately.
327 **
328 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
329 ** changed by this function.
330 */
331 int sqlite3VdbeMemHandleBom(Mem *pMem){
332   int rc = SQLITE_OK;
333   u8 bom = 0;
334 
335   if( pMem->n<0 || pMem->n>1 ){
336     u8 b1 = *(u8 *)pMem->z;
337     u8 b2 = *(((u8 *)pMem->z) + 1);
338     if( b1==0xFE && b2==0xFF ){
339       bom = SQLITE_UTF16BE;
340     }
341     if( b1==0xFF && b2==0xFE ){
342       bom = SQLITE_UTF16LE;
343     }
344   }
345 
346   if( bom ){
347     rc = sqlite3VdbeMemMakeWriteable(pMem);
348     if( rc==SQLITE_OK ){
349       pMem->n -= 2;
350       memmove(pMem->z, &pMem->z[2], pMem->n);
351       pMem->z[pMem->n] = '\0';
352       pMem->z[pMem->n+1] = '\0';
353       pMem->flags |= MEM_Term;
354       pMem->enc = bom;
355     }
356   }
357   return rc;
358 }
359 #endif /* SQLITE_OMIT_UTF16 */
360 
361 /*
362 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
363 ** return the number of unicode characters in pZ up to (but not including)
364 ** the first 0x00 byte. If nByte is not less than zero, return the
365 ** number of unicode characters in the first nByte of pZ (or up to
366 ** the first 0x00, whichever comes first).
367 */
368 int sqlite3Utf8CharLen(const char *zIn, int nByte){
369   int r = 0;
370   const u8 *z = (const u8*)zIn;
371   const u8 *zTerm;
372   if( nByte>=0 ){
373     zTerm = &z[nByte];
374   }else{
375     zTerm = (const u8*)(-1);
376   }
377   assert( z<=zTerm );
378   while( *z!=0 && z<zTerm ){
379     SQLITE_SKIP_UTF8(z);
380     r++;
381   }
382   return r;
383 }
384 
385 /* This test function is not currently used by the automated test-suite.
386 ** Hence it is only available in debug builds.
387 */
388 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
389 /*
390 ** Translate UTF-8 to UTF-8.
391 **
392 ** This has the effect of making sure that the string is well-formed
393 ** UTF-8.  Miscoded characters are removed.
394 **
395 ** The translation is done in-place (since it is impossible for the
396 ** correct UTF-8 encoding to be longer than a malformed encoding).
397 */
398 int sqlite3Utf8To8(unsigned char *zIn){
399   unsigned char *zOut = zIn;
400   unsigned char *zStart = zIn;
401   unsigned char *zTerm;
402   u32 c;
403 
404   while( zIn[0] ){
405     c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
406     if( c!=0xfffd ){
407       WRITE_UTF8(zOut, c);
408     }
409   }
410   *zOut = 0;
411   return zOut - zStart;
412 }
413 #endif
414 
415 #ifndef SQLITE_OMIT_UTF16
416 /*
417 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
418 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
419 ** be freed by the calling function.
420 **
421 ** NULL is returned if there is an allocation error.
422 */
423 char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
424   Mem m;
425   memset(&m, 0, sizeof(m));
426   m.db = db;
427   sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
428   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
429   if( db->mallocFailed ){
430     sqlite3VdbeMemRelease(&m);
431     m.z = 0;
432   }
433   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
434   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
435   return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
436 }
437 
438 /*
439 ** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
440 ** return the number of bytes up to (but not including), the first pair
441 ** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
442 ** then return the number of bytes in the first nChar unicode characters
443 ** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
444 */
445 int sqlite3Utf16ByteLen(const void *zIn, int nChar){
446   unsigned int c = 1;
447   char const *z = zIn;
448   int n = 0;
449   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
450     /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
451     ** and in other parts of this file means that at one branch will
452     ** not be covered by coverage testing on any single host. But coverage
453     ** will be complete if the tests are run on both a little-endian and
454     ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
455     ** macros are constant at compile time the compiler can determine
456     ** which branch will be followed. It is therefore assumed that no runtime
457     ** penalty is paid for this "if" statement.
458     */
459     while( c && ((nChar<0) || n<nChar) ){
460       READ_UTF16BE(z, c);
461       n++;
462     }
463   }else{
464     while( c && ((nChar<0) || n<nChar) ){
465       READ_UTF16LE(z, c);
466       n++;
467     }
468   }
469   return (z-(char const *)zIn)-((c==0)?2:0);
470 }
471 
472 #if defined(SQLITE_TEST)
473 /*
474 ** This routine is called from the TCL test function "translate_selftest".
475 ** It checks that the primitives for serializing and deserializing
476 ** characters in each encoding are inverses of each other.
477 */
478 void sqlite3UtfSelfTest(){
479   unsigned int i, t;
480   unsigned char zBuf[20];
481   unsigned char *z;
482   unsigned char *zTerm;
483   int n;
484   unsigned int c;
485 
486   for(i=0; i<0x00110000; i++){
487     z = zBuf;
488     WRITE_UTF8(z, i);
489     n = z-zBuf;
490     z[0] = 0;
491     zTerm = z;
492     z = zBuf;
493     c = sqlite3Utf8Read(z, zTerm, (const u8**)&z);
494     t = i;
495     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
496     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
497     assert( c==t );
498     assert( (z-zBuf)==n );
499   }
500   for(i=0; i<0x00110000; i++){
501     if( i>=0xD800 && i<0xE000 ) continue;
502     z = zBuf;
503     WRITE_UTF16LE(z, i);
504     n = z-zBuf;
505     z[0] = 0;
506     z = zBuf;
507     READ_UTF16LE(z, c);
508     assert( c==i );
509     assert( (z-zBuf)==n );
510   }
511   for(i=0; i<0x00110000; i++){
512     if( i>=0xD800 && i<0xE000 ) continue;
513     z = zBuf;
514     WRITE_UTF16BE(z, i);
515     n = z-zBuf;
516     z[0] = 0;
517     z = zBuf;
518     READ_UTF16BE(z, c);
519     assert( c==i );
520     assert( (z-zBuf)==n );
521   }
522 }
523 #endif /* SQLITE_TEST */
524 #endif /* SQLITE_OMIT_UTF16 */
525