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