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