downgrade memory unlock failures to info level and fix function name in log output
[sqlcipher.git] / src / utf.c
blob216864f5c779486f56e7af63ea3fe1c1d72ef4a5
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.
11 *************************************************************************
12 ** This file contains routines used to translate between UTF-8,
13 ** UTF-16, UTF-16BE, and UTF-16LE.
15 ** Notes on UTF-8:
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
24 ** Notes on UTF-16: (with wwww+1==uuuuu)
26 ** Word-0 Word-1 Value
27 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
28 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
31 ** BOM or Byte Order Mark:
32 ** 0xff 0xfe little-endian utf-16 follows
33 ** 0xfe 0xff big-endian utf-16 follows
36 #include "sqliteInt.h"
37 #include <assert.h>
38 #include "vdbeInt.h"
40 #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
42 ** The following constant value is used by the SQLITE_BIGENDIAN and
43 ** SQLITE_LITTLEENDIAN macros.
45 const int sqlite3one = 1;
46 #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
49 ** This lookup table is used to help decode the first byte of
50 ** a multi-byte UTF8 character.
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,
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 } \
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 } \
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); \
109 ** Translate a single UTF-8 character. Return the unicode value.
111 ** During translation, assume that the byte that zTerm points
112 ** is a 0x00.
114 ** Write a pointer to the next unread byte back into *pzNext.
116 ** Notes On Invalid UTF-8:
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.
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.
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.
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.
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++)); \
142 if( c<0x80 \
143 || (c&0xFFFFF800)==0xD800 \
144 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
146 u32 sqlite3Utf8Read(
147 const unsigned char **pz /* Pointer to string from which to read char */
149 unsigned int c;
151 /* Same as READ_UTF8() above but without the zTerm parameter.
152 ** For this routine, we assume the UTF8 string is always zero-terminated.
154 c = *((*pz)++);
155 if( c>=0xc0 ){
156 c = sqlite3Utf8Trans1[c-0xc0];
157 while( (*(*pz) & 0xc0)==0x80 ){
158 c = (c<<6) + (0x3f & *((*pz)++));
160 if( c<0x80
161 || (c&0xFFFFF800)==0xD800
162 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
164 return c;
168 ** Read a single UTF8 character out of buffer z[], but reading no
169 ** more than n characters from the buffer. z[] is not zero-terminated.
171 ** Return the number of bytes used to construct the character.
173 ** Invalid UTF8 might generate a strange result. No effort is made
174 ** to detect invalid UTF8.
176 ** At most 4 bytes will be read out of z[]. The return value will always
177 ** be between 1 and 4.
179 int sqlite3Utf8ReadLimited(
180 const u8 *z,
181 int n,
182 u32 *piOut
184 u32 c;
185 int i = 1;
186 assert( n>0 );
187 c = z[0];
188 if( c>=0xc0 ){
189 c = sqlite3Utf8Trans1[c-0xc0];
190 if( n>4 ) n = 4;
191 while( i<n && (z[i] & 0xc0)==0x80 ){
192 c = (c<<6) + (0x3f & z[i]);
193 i++;
196 *piOut = c;
197 return i;
202 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
203 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
205 /* #define TRANSLATE_TRACE 1 */
207 #ifndef SQLITE_OMIT_UTF16
209 ** This routine transforms the internal text encoding used by pMem to
210 ** desiredEnc. It is an error if the string is already of the desired
211 ** encoding, or if *pMem does not contain a string value.
213 SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
214 sqlite3_int64 len; /* Maximum length of output string in bytes */
215 unsigned char *zOut; /* Output buffer */
216 unsigned char *zIn; /* Input iterator */
217 unsigned char *zTerm; /* End of input */
218 unsigned char *z; /* Output iterator */
219 unsigned int c;
221 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
222 assert( pMem->flags&MEM_Str );
223 assert( pMem->enc!=desiredEnc );
224 assert( pMem->enc!=0 );
225 assert( pMem->n>=0 );
227 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
229 StrAccum acc;
230 char zBuf[1000];
231 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
232 sqlite3VdbeMemPrettyPrint(pMem, &acc);
233 fprintf(stderr, "INPUT: %s\n", sqlite3StrAccumFinish(&acc));
235 #endif
237 /* If the translation is between UTF-16 little and big endian, then
238 ** all that is required is to swap the byte order. This case is handled
239 ** differently from the others.
241 if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
242 u8 temp;
243 int rc;
244 rc = sqlite3VdbeMemMakeWriteable(pMem);
245 if( rc!=SQLITE_OK ){
246 assert( rc==SQLITE_NOMEM );
247 return SQLITE_NOMEM_BKPT;
249 zIn = (u8*)pMem->z;
250 zTerm = &zIn[pMem->n&~1];
251 while( zIn<zTerm ){
252 temp = *zIn;
253 *zIn = *(zIn+1);
254 zIn++;
255 *zIn++ = temp;
257 pMem->enc = desiredEnc;
258 goto translate_out;
261 /* Set len to the maximum number of bytes required in the output buffer. */
262 if( desiredEnc==SQLITE_UTF8 ){
263 /* When converting from UTF-16, the maximum growth results from
264 ** translating a 2-byte character to a 4-byte UTF-8 character.
265 ** A single byte is required for the output string
266 ** nul-terminator.
268 pMem->n &= ~1;
269 len = 2 * (sqlite3_int64)pMem->n + 1;
270 }else{
271 /* When converting from UTF-8 to UTF-16 the maximum growth is caused
272 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
273 ** character. Two bytes are required in the output buffer for the
274 ** nul-terminator.
276 len = 2 * (sqlite3_int64)pMem->n + 2;
279 /* Set zIn to point at the start of the input buffer and zTerm to point 1
280 ** byte past the end.
282 ** Variable zOut is set to point at the output buffer, space obtained
283 ** from sqlite3_malloc().
285 zIn = (u8*)pMem->z;
286 zTerm = &zIn[pMem->n];
287 zOut = sqlite3DbMallocRaw(pMem->db, len);
288 if( !zOut ){
289 return SQLITE_NOMEM_BKPT;
291 z = zOut;
293 if( pMem->enc==SQLITE_UTF8 ){
294 if( desiredEnc==SQLITE_UTF16LE ){
295 /* UTF-8 -> UTF-16 Little-endian */
296 while( zIn<zTerm ){
297 READ_UTF8(zIn, zTerm, c);
298 WRITE_UTF16LE(z, c);
300 }else{
301 assert( desiredEnc==SQLITE_UTF16BE );
302 /* UTF-8 -> UTF-16 Big-endian */
303 while( zIn<zTerm ){
304 READ_UTF8(zIn, zTerm, c);
305 WRITE_UTF16BE(z, c);
308 pMem->n = (int)(z - zOut);
309 *z++ = 0;
310 }else{
311 assert( desiredEnc==SQLITE_UTF8 );
312 if( pMem->enc==SQLITE_UTF16LE ){
313 /* UTF-16 Little-endian -> UTF-8 */
314 while( zIn<zTerm ){
315 c = *(zIn++);
316 c += (*(zIn++))<<8;
317 if( c>=0xd800 && c<0xe000 ){
318 #ifdef SQLITE_REPLACE_INVALID_UTF
319 if( c>=0xdc00 || zIn>=zTerm ){
320 c = 0xfffd;
321 }else{
322 int c2 = *(zIn++);
323 c2 += (*(zIn++))<<8;
324 if( c2<0xdc00 || c2>=0xe000 ){
325 zIn -= 2;
326 c = 0xfffd;
327 }else{
328 c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;
331 #else
332 if( zIn<zTerm ){
333 int c2 = (*zIn++);
334 c2 += ((*zIn++)<<8);
335 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);
337 #endif
339 WRITE_UTF8(z, c);
341 }else{
342 /* UTF-16 Big-endian -> UTF-8 */
343 while( zIn<zTerm ){
344 c = (*(zIn++))<<8;
345 c += *(zIn++);
346 if( c>=0xd800 && c<0xe000 ){
347 #ifdef SQLITE_REPLACE_INVALID_UTF
348 if( c>=0xdc00 || zIn>=zTerm ){
349 c = 0xfffd;
350 }else{
351 int c2 = (*(zIn++))<<8;
352 c2 += *(zIn++);
353 if( c2<0xdc00 || c2>=0xe000 ){
354 zIn -= 2;
355 c = 0xfffd;
356 }else{
357 c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;
360 #else
361 if( zIn<zTerm ){
362 int c2 = ((*zIn++)<<8);
363 c2 += (*zIn++);
364 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);
366 #endif
368 WRITE_UTF8(z, c);
371 pMem->n = (int)(z - zOut);
373 *z = 0;
374 assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
376 c = MEM_Str|MEM_Term|(pMem->flags&(MEM_AffMask|MEM_Subtype));
377 sqlite3VdbeMemRelease(pMem);
378 pMem->flags = c;
379 pMem->enc = desiredEnc;
380 pMem->z = (char*)zOut;
381 pMem->zMalloc = pMem->z;
382 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
384 translate_out:
385 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
387 StrAccum acc;
388 char zBuf[1000];
389 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
390 sqlite3VdbeMemPrettyPrint(pMem, &acc);
391 fprintf(stderr, "OUTPUT: %s\n", sqlite3StrAccumFinish(&acc));
393 #endif
394 return SQLITE_OK;
396 #endif /* SQLITE_OMIT_UTF16 */
398 #ifndef SQLITE_OMIT_UTF16
400 ** This routine checks for a byte-order mark at the beginning of the
401 ** UTF-16 string stored in *pMem. If one is present, it is removed and
402 ** the encoding of the Mem adjusted. This routine does not do any
403 ** byte-swapping, it just sets Mem.enc appropriately.
405 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
406 ** changed by this function.
408 int sqlite3VdbeMemHandleBom(Mem *pMem){
409 int rc = SQLITE_OK;
410 u8 bom = 0;
412 assert( pMem->n>=0 );
413 if( pMem->n>1 ){
414 u8 b1 = *(u8 *)pMem->z;
415 u8 b2 = *(((u8 *)pMem->z) + 1);
416 if( b1==0xFE && b2==0xFF ){
417 bom = SQLITE_UTF16BE;
419 if( b1==0xFF && b2==0xFE ){
420 bom = SQLITE_UTF16LE;
424 if( bom ){
425 rc = sqlite3VdbeMemMakeWriteable(pMem);
426 if( rc==SQLITE_OK ){
427 pMem->n -= 2;
428 memmove(pMem->z, &pMem->z[2], pMem->n);
429 pMem->z[pMem->n] = '\0';
430 pMem->z[pMem->n+1] = '\0';
431 pMem->flags |= MEM_Term;
432 pMem->enc = bom;
435 return rc;
437 #endif /* SQLITE_OMIT_UTF16 */
440 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
441 ** return the number of unicode characters in pZ up to (but not including)
442 ** the first 0x00 byte. If nByte is not less than zero, return the
443 ** number of unicode characters in the first nByte of pZ (or up to
444 ** the first 0x00, whichever comes first).
446 int sqlite3Utf8CharLen(const char *zIn, int nByte){
447 int r = 0;
448 const u8 *z = (const u8*)zIn;
449 const u8 *zTerm;
450 if( nByte>=0 ){
451 zTerm = &z[nByte];
452 }else{
453 zTerm = (const u8*)(-1);
455 assert( z<=zTerm );
456 while( *z!=0 && z<zTerm ){
457 SQLITE_SKIP_UTF8(z);
458 r++;
460 return r;
463 /* This test function is not currently used by the automated test-suite.
464 ** Hence it is only available in debug builds.
466 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
468 ** Translate UTF-8 to UTF-8.
470 ** This has the effect of making sure that the string is well-formed
471 ** UTF-8. Miscoded characters are removed.
473 ** The translation is done in-place and aborted if the output
474 ** overruns the input.
476 int sqlite3Utf8To8(unsigned char *zIn){
477 unsigned char *zOut = zIn;
478 unsigned char *zStart = zIn;
479 u32 c;
481 while( zIn[0] && zOut<=zIn ){
482 c = sqlite3Utf8Read((const u8**)&zIn);
483 if( c!=0xfffd ){
484 WRITE_UTF8(zOut, c);
487 *zOut = 0;
488 return (int)(zOut - zStart);
490 #endif
492 #ifndef SQLITE_OMIT_UTF16
494 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
495 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
496 ** be freed by the calling function.
498 ** NULL is returned if there is an allocation error.
500 char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
501 Mem m;
502 memset(&m, 0, sizeof(m));
503 m.db = db;
504 sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
505 sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
506 if( db->mallocFailed ){
507 sqlite3VdbeMemRelease(&m);
508 m.z = 0;
510 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
511 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
512 assert( m.z || db->mallocFailed );
513 return m.z;
517 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
518 ** Return the number of bytes in the first nChar unicode characters
519 ** in pZ. nChar must be non-negative.
521 int sqlite3Utf16ByteLen(const void *zIn, int nChar){
522 int c;
523 unsigned char const *z = zIn;
524 int n = 0;
526 if( SQLITE_UTF16NATIVE==SQLITE_UTF16LE ) z++;
527 while( n<nChar ){
528 c = z[0];
529 z += 2;
530 if( c>=0xd8 && c<0xdc && z[0]>=0xdc && z[0]<0xe0 ) z += 2;
531 n++;
533 return (int)(z-(unsigned char const *)zIn)
534 - (SQLITE_UTF16NATIVE==SQLITE_UTF16LE);
537 #if defined(SQLITE_TEST)
539 ** This routine is called from the TCL test function "translate_selftest".
540 ** It checks that the primitives for serializing and deserializing
541 ** characters in each encoding are inverses of each other.
543 void sqlite3UtfSelfTest(void){
544 unsigned int i, t;
545 unsigned char zBuf[20];
546 unsigned char *z;
547 int n;
548 unsigned int c;
550 for(i=0; i<0x00110000; i++){
551 z = zBuf;
552 WRITE_UTF8(z, i);
553 n = (int)(z-zBuf);
554 assert( n>0 && n<=4 );
555 z[0] = 0;
556 z = zBuf;
557 c = sqlite3Utf8Read((const u8**)&z);
558 t = i;
559 if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
560 if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
561 assert( c==t );
562 assert( (z-zBuf)==n );
565 #endif /* SQLITE_TEST */
566 #endif /* SQLITE_OMIT_UTF16 */