xref: /sqlite-3.40.0/src/util.c (revision 78d41832)
1 /*
2 ** 2001 September 15
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 ** Utility functions used throughout sqlite.
13 **
14 ** This file contains functions for allocating memory, comparing
15 ** strings, and stuff like that.
16 **
17 ** $Id: util.c,v 1.245 2008/12/10 22:15:00 drh Exp $
18 */
19 #include "sqliteInt.h"
20 #include <stdarg.h>
21 #include <ctype.h>
22 
23 
24 /*
25 ** Return true if the floating point value is Not a Number (NaN).
26 */
27 int sqlite3IsNaN(double x){
28   /* This NaN test sometimes fails if compiled on GCC with -ffast-math.
29   ** On the other hand, the use of -ffast-math comes with the following
30   ** warning:
31   **
32   **      This option [-ffast-math] should never be turned on by any
33   **      -O option since it can result in incorrect output for programs
34   **      which depend on an exact implementation of IEEE or ISO
35   **      rules/specifications for math functions.
36   **
37   ** Under MSVC, this NaN test may fail if compiled with a floating-
38   ** point precision mode other than /fp:precise.  From the MSDN
39   ** documentation:
40   **
41   **      The compiler [with /fp:precise] will properly handle comparisons
42   **      involving NaN. For example, x != x evaluates to true if x is NaN
43   **      ...
44   */
45 #ifdef __FAST_MATH__
46 # error SQLite will not work correctly with the -ffast-math option of GCC.
47 #endif
48   volatile double y = x;
49   volatile double z = y;
50   return y!=z;
51 }
52 
53 /*
54 ** Compute a string length that is limited to what can be stored in
55 ** lower 30 bits of a 32-bit signed integer.
56 */
57 int sqlite3Strlen30(const char *z){
58   const char *z2 = z;
59   while( *z2 ){ z2++; }
60   return 0x3fffffff & (int)(z2 - z);
61 }
62 
63 /*
64 ** Return the length of a string, except do not allow the string length
65 ** to exceed the SQLITE_LIMIT_LENGTH setting.
66 */
67 int sqlite3Strlen(sqlite3 *db, const char *z){
68   const char *z2 = z;
69   int len;
70   int x;
71   while( *z2 ){ z2++; }
72   x = (int)(z2 - z);
73   len = 0x7fffffff & x;
74   if( len!=x || len > db->aLimit[SQLITE_LIMIT_LENGTH] ){
75     return db->aLimit[SQLITE_LIMIT_LENGTH];
76   }else{
77     return len;
78   }
79 }
80 
81 /*
82 ** Set the most recent error code and error string for the sqlite
83 ** handle "db". The error code is set to "err_code".
84 **
85 ** If it is not NULL, string zFormat specifies the format of the
86 ** error string in the style of the printf functions: The following
87 ** format characters are allowed:
88 **
89 **      %s      Insert a string
90 **      %z      A string that should be freed after use
91 **      %d      Insert an integer
92 **      %T      Insert a token
93 **      %S      Insert the first element of a SrcList
94 **
95 ** zFormat and any string tokens that follow it are assumed to be
96 ** encoded in UTF-8.
97 **
98 ** To clear the most recent error for sqlite handle "db", sqlite3Error
99 ** should be called with err_code set to SQLITE_OK and zFormat set
100 ** to NULL.
101 */
102 void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
103   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
104     db->errCode = err_code;
105     if( zFormat ){
106       char *z;
107       va_list ap;
108       va_start(ap, zFormat);
109       z = sqlite3VMPrintf(db, zFormat, ap);
110       va_end(ap);
111       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
112     }else{
113       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
114     }
115   }
116 }
117 
118 /*
119 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
120 ** The following formatting characters are allowed:
121 **
122 **      %s      Insert a string
123 **      %z      A string that should be freed after use
124 **      %d      Insert an integer
125 **      %T      Insert a token
126 **      %S      Insert the first element of a SrcList
127 **
128 ** This function should be used to report any error that occurs whilst
129 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
130 ** last thing the sqlite3_prepare() function does is copy the error
131 ** stored by this function into the database handle using sqlite3Error().
132 ** Function sqlite3Error() should be used during statement execution
133 ** (sqlite3_step() etc.).
134 */
135 void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
136   va_list ap;
137   sqlite3 *db = pParse->db;
138   pParse->nErr++;
139   sqlite3DbFree(db, pParse->zErrMsg);
140   va_start(ap, zFormat);
141   pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
142   va_end(ap);
143   if( pParse->rc==SQLITE_OK ){
144     pParse->rc = SQLITE_ERROR;
145   }
146 }
147 
148 /*
149 ** Clear the error message in pParse, if any
150 */
151 void sqlite3ErrorClear(Parse *pParse){
152   sqlite3DbFree(pParse->db, pParse->zErrMsg);
153   pParse->zErrMsg = 0;
154   pParse->nErr = 0;
155 }
156 
157 /*
158 ** Convert an SQL-style quoted string into a normal string by removing
159 ** the quote characters.  The conversion is done in-place.  If the
160 ** input does not begin with a quote character, then this routine
161 ** is a no-op.
162 **
163 ** 2002-Feb-14: This routine is extended to remove MS-Access style
164 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
165 ** "a-b-c".
166 */
167 void sqlite3Dequote(char *z){
168   char quote;
169   int i, j;
170   if( z==0 ) return;
171   quote = z[0];
172   switch( quote ){
173     case '\'':  break;
174     case '"':   break;
175     case '`':   break;                /* For MySQL compatibility */
176     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
177     default:    return;
178   }
179   for(i=1, j=0; z[i]; i++){
180     if( z[i]==quote ){
181       if( z[i+1]==quote ){
182         z[j++] = quote;
183         i++;
184       }else{
185         z[j++] = 0;
186         break;
187       }
188     }else{
189       z[j++] = z[i];
190     }
191   }
192 }
193 
194 /* Convenient short-hand */
195 #define UpperToLower sqlite3UpperToLower
196 
197 /*
198 ** Some systems have stricmp().  Others have strcasecmp().  Because
199 ** there is no consistency, we will define our own.
200 */
201 int sqlite3StrICmp(const char *zLeft, const char *zRight){
202   register unsigned char *a, *b;
203   a = (unsigned char *)zLeft;
204   b = (unsigned char *)zRight;
205   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
206   return UpperToLower[*a] - UpperToLower[*b];
207 }
208 int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
209   register unsigned char *a, *b;
210   a = (unsigned char *)zLeft;
211   b = (unsigned char *)zRight;
212   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
213   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
214 }
215 
216 /*
217 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
218 ** string contains any character which is not part of a number. If
219 ** the string is numeric and contains the '.' character, set *realnum
220 ** to TRUE (otherwise FALSE).
221 **
222 ** An empty string is considered non-numeric.
223 */
224 int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
225   int incr = (enc==SQLITE_UTF8?1:2);
226   if( enc==SQLITE_UTF16BE ) z++;
227   if( *z=='-' || *z=='+' ) z += incr;
228   if( !isdigit(*(u8*)z) ){
229     return 0;
230   }
231   z += incr;
232   if( realnum ) *realnum = 0;
233   while( isdigit(*(u8*)z) ){ z += incr; }
234   if( *z=='.' ){
235     z += incr;
236     if( !isdigit(*(u8*)z) ) return 0;
237     while( isdigit(*(u8*)z) ){ z += incr; }
238     if( realnum ) *realnum = 1;
239   }
240   if( *z=='e' || *z=='E' ){
241     z += incr;
242     if( *z=='+' || *z=='-' ) z += incr;
243     if( !isdigit(*(u8*)z) ) return 0;
244     while( isdigit(*(u8*)z) ){ z += incr; }
245     if( realnum ) *realnum = 1;
246   }
247   return *z==0;
248 }
249 
250 /*
251 ** The string z[] is an ascii representation of a real number.
252 ** Convert this string to a double.
253 **
254 ** This routine assumes that z[] really is a valid number.  If it
255 ** is not, the result is undefined.
256 **
257 ** This routine is used instead of the library atof() function because
258 ** the library atof() might want to use "," as the decimal point instead
259 ** of "." depending on how locale is set.  But that would cause problems
260 ** for SQL.  So this routine always uses "." regardless of locale.
261 */
262 int sqlite3AtoF(const char *z, double *pResult){
263 #ifndef SQLITE_OMIT_FLOATING_POINT
264   int sign = 1;
265   const char *zBegin = z;
266   LONGDOUBLE_TYPE v1 = 0.0;
267   int nSignificant = 0;
268   while( isspace(*(u8*)z) ) z++;
269   if( *z=='-' ){
270     sign = -1;
271     z++;
272   }else if( *z=='+' ){
273     z++;
274   }
275   while( z[0]=='0' ){
276     z++;
277   }
278   while( isdigit(*(u8*)z) ){
279     v1 = v1*10.0 + (*z - '0');
280     z++;
281     nSignificant++;
282   }
283   if( *z=='.' ){
284     LONGDOUBLE_TYPE divisor = 1.0;
285     z++;
286     if( nSignificant==0 ){
287       while( z[0]=='0' ){
288         divisor *= 10.0;
289         z++;
290       }
291     }
292     while( isdigit(*(u8*)z) ){
293       if( nSignificant<18 ){
294         v1 = v1*10.0 + (*z - '0');
295         divisor *= 10.0;
296         nSignificant++;
297       }
298       z++;
299     }
300     v1 /= divisor;
301   }
302   if( *z=='e' || *z=='E' ){
303     int esign = 1;
304     int eval = 0;
305     LONGDOUBLE_TYPE scale = 1.0;
306     z++;
307     if( *z=='-' ){
308       esign = -1;
309       z++;
310     }else if( *z=='+' ){
311       z++;
312     }
313     while( isdigit(*(u8*)z) ){
314       eval = eval*10 + *z - '0';
315       z++;
316     }
317     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
318     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
319     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
320     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
321     if( esign<0 ){
322       v1 /= scale;
323     }else{
324       v1 *= scale;
325     }
326   }
327   *pResult = (double)(sign<0 ? -v1 : v1);
328   return (int)(z - zBegin);
329 #else
330   return sqlite3Atoi64(z, pResult);
331 #endif /* SQLITE_OMIT_FLOATING_POINT */
332 }
333 
334 /*
335 ** Compare the 19-character string zNum against the text representation
336 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
337 ** if zNum is less than, equal to, or greater than the string.
338 **
339 ** Unlike memcmp() this routine is guaranteed to return the difference
340 ** in the values of the last digit if the only difference is in the
341 ** last digit.  So, for example,
342 **
343 **      compare2pow63("9223372036854775800")
344 **
345 ** will return -8.
346 */
347 static int compare2pow63(const char *zNum){
348   int c;
349   c = memcmp(zNum,"922337203685477580",18);
350   if( c==0 ){
351     c = zNum[18] - '8';
352   }
353   return c;
354 }
355 
356 
357 /*
358 ** Return TRUE if zNum is a 64-bit signed integer and write
359 ** the value of the integer into *pNum.  If zNum is not an integer
360 ** or is an integer that is too large to be expressed with 64 bits,
361 ** then return false.
362 **
363 ** When this routine was originally written it dealt with only
364 ** 32-bit numbers.  At that time, it was much faster than the
365 ** atoi() library routine in RedHat 7.2.
366 */
367 int sqlite3Atoi64(const char *zNum, i64 *pNum){
368   i64 v = 0;
369   int neg;
370   int i, c;
371   const char *zStart;
372   while( isspace(*(u8*)zNum) ) zNum++;
373   if( *zNum=='-' ){
374     neg = 1;
375     zNum++;
376   }else if( *zNum=='+' ){
377     neg = 0;
378     zNum++;
379   }else{
380     neg = 0;
381   }
382   zStart = zNum;
383   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
384   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
385     v = v*10 + c - '0';
386   }
387   *pNum = neg ? -v : v;
388   if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
389     /* zNum is empty or contains non-numeric text or is longer
390     ** than 19 digits (thus guaranting that it is too large) */
391     return 0;
392   }else if( i<19 ){
393     /* Less than 19 digits, so we know that it fits in 64 bits */
394     return 1;
395   }else{
396     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
397     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
398     ** is 2^63. */
399     return compare2pow63(zNum)<neg;
400   }
401 }
402 
403 /*
404 ** The string zNum represents an integer.  There might be some other
405 ** information following the integer too, but that part is ignored.
406 ** If the integer that the prefix of zNum represents will fit in a
407 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
408 **
409 ** This routine returns FALSE for the string -9223372036854775808 even that
410 ** that number will, in theory fit in a 64-bit integer.  Positive
411 ** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
412 ** false.
413 */
414 int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
415   int i, c;
416   int neg = 0;
417   if( *zNum=='-' ){
418     neg = 1;
419     zNum++;
420   }else if( *zNum=='+' ){
421     zNum++;
422   }
423   if( negFlag ) neg = 1-neg;
424   while( *zNum=='0' ){
425     zNum++;   /* Skip leading zeros.  Ticket #2454 */
426   }
427   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
428   if( i<19 ){
429     /* Guaranteed to fit if less than 19 digits */
430     return 1;
431   }else if( i>19 ){
432     /* Guaranteed to be too big if greater than 19 digits */
433     return 0;
434   }else{
435     /* Compare against 2^63. */
436     return compare2pow63(zNum)<neg;
437   }
438 }
439 
440 /*
441 ** If zNum represents an integer that will fit in 32-bits, then set
442 ** *pValue to that integer and return true.  Otherwise return false.
443 **
444 ** Any non-numeric characters that following zNum are ignored.
445 ** This is different from sqlite3Atoi64() which requires the
446 ** input number to be zero-terminated.
447 */
448 int sqlite3GetInt32(const char *zNum, int *pValue){
449   sqlite_int64 v = 0;
450   int i, c;
451   int neg = 0;
452   if( zNum[0]=='-' ){
453     neg = 1;
454     zNum++;
455   }else if( zNum[0]=='+' ){
456     zNum++;
457   }
458   while( zNum[0]=='0' ) zNum++;
459   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
460     v = v*10 + c;
461   }
462 
463   /* The longest decimal representation of a 32 bit integer is 10 digits:
464   **
465   **             1234567890
466   **     2^31 -> 2147483648
467   */
468   if( i>10 ){
469     return 0;
470   }
471   if( v-neg>2147483647 ){
472     return 0;
473   }
474   if( neg ){
475     v = -v;
476   }
477   *pValue = (int)v;
478   return 1;
479 }
480 
481 /*
482 ** The variable-length integer encoding is as follows:
483 **
484 ** KEY:
485 **         A = 0xxxxxxx    7 bits of data and one flag bit
486 **         B = 1xxxxxxx    7 bits of data and one flag bit
487 **         C = xxxxxxxx    8 bits of data
488 **
489 **  7 bits - A
490 ** 14 bits - BA
491 ** 21 bits - BBA
492 ** 28 bits - BBBA
493 ** 35 bits - BBBBA
494 ** 42 bits - BBBBBA
495 ** 49 bits - BBBBBBA
496 ** 56 bits - BBBBBBBA
497 ** 64 bits - BBBBBBBBC
498 */
499 
500 /*
501 ** Write a 64-bit variable-length integer to memory starting at p[0].
502 ** The length of data write will be between 1 and 9 bytes.  The number
503 ** of bytes written is returned.
504 **
505 ** A variable-length integer consists of the lower 7 bits of each byte
506 ** for all bytes that have the 8th bit set and one byte with the 8th
507 ** bit clear.  Except, if we get to the 9th byte, it stores the full
508 ** 8 bits and is the last byte.
509 */
510 int sqlite3PutVarint(unsigned char *p, u64 v){
511   int i, j, n;
512   u8 buf[10];
513   if( v & (((u64)0xff000000)<<32) ){
514     p[8] = (u8)v;
515     v >>= 8;
516     for(i=7; i>=0; i--){
517       p[i] = (u8)((v & 0x7f) | 0x80);
518       v >>= 7;
519     }
520     return 9;
521   }
522   n = 0;
523   do{
524     buf[n++] = (u8)((v & 0x7f) | 0x80);
525     v >>= 7;
526   }while( v!=0 );
527   buf[0] &= 0x7f;
528   assert( n<=9 );
529   for(i=0, j=n-1; j>=0; j--, i++){
530     p[i] = buf[j];
531   }
532   return n;
533 }
534 
535 /*
536 ** This routine is a faster version of sqlite3PutVarint() that only
537 ** works for 32-bit positive integers and which is optimized for
538 ** the common case of small integers.  A MACRO version, putVarint32,
539 ** is provided which inlines the single-byte case.  All code should use
540 ** the MACRO version as this function assumes the single-byte case has
541 ** already been handled.
542 */
543 int sqlite3PutVarint32(unsigned char *p, u32 v){
544 #ifndef putVarint32
545   if( (v & ~0x7f)==0 ){
546     p[0] = v;
547     return 1;
548   }
549 #endif
550   if( (v & ~0x3fff)==0 ){
551     p[0] = (u8)((v>>7) | 0x80);
552     p[1] = (u8)(v & 0x7f);
553     return 2;
554   }
555   return sqlite3PutVarint(p, v);
556 }
557 
558 /*
559 ** Read a 64-bit variable-length integer from memory starting at p[0].
560 ** Return the number of bytes read.  The value is stored in *v.
561 */
562 u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
563   u32 a,b,s;
564 
565   a = *p;
566   /* a: p0 (unmasked) */
567   if (!(a&0x80))
568   {
569     *v = a;
570     return 1;
571   }
572 
573   p++;
574   b = *p;
575   /* b: p1 (unmasked) */
576   if (!(b&0x80))
577   {
578     a &= 0x7f;
579     a = a<<7;
580     a |= b;
581     *v = a;
582     return 2;
583   }
584 
585   p++;
586   a = a<<14;
587   a |= *p;
588   /* a: p0<<14 | p2 (unmasked) */
589   if (!(a&0x80))
590   {
591     a &= (0x7f<<14)|(0x7f);
592     b &= 0x7f;
593     b = b<<7;
594     a |= b;
595     *v = a;
596     return 3;
597   }
598 
599   /* CSE1 from below */
600   a &= (0x7f<<14)|(0x7f);
601   p++;
602   b = b<<14;
603   b |= *p;
604   /* b: p1<<14 | p3 (unmasked) */
605   if (!(b&0x80))
606   {
607     b &= (0x7f<<14)|(0x7f);
608     /* moved CSE1 up */
609     /* a &= (0x7f<<14)|(0x7f); */
610     a = a<<7;
611     a |= b;
612     *v = a;
613     return 4;
614   }
615 
616   /* a: p0<<14 | p2 (masked) */
617   /* b: p1<<14 | p3 (unmasked) */
618   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
619   /* moved CSE1 up */
620   /* a &= (0x7f<<14)|(0x7f); */
621   b &= (0x7f<<14)|(0x7f);
622   s = a;
623   /* s: p0<<14 | p2 (masked) */
624 
625   p++;
626   a = a<<14;
627   a |= *p;
628   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
629   if (!(a&0x80))
630   {
631     /* we can skip these cause they were (effectively) done above in calc'ing s */
632     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
633     /* b &= (0x7f<<14)|(0x7f); */
634     b = b<<7;
635     a |= b;
636     s = s>>18;
637     *v = ((u64)s)<<32 | a;
638     return 5;
639   }
640 
641   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
642   s = s<<7;
643   s |= b;
644   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
645 
646   p++;
647   b = b<<14;
648   b |= *p;
649   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
650   if (!(b&0x80))
651   {
652     /* we can skip this cause it was (effectively) done above in calc'ing s */
653     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
654     a &= (0x7f<<14)|(0x7f);
655     a = a<<7;
656     a |= b;
657     s = s>>18;
658     *v = ((u64)s)<<32 | a;
659     return 6;
660   }
661 
662   p++;
663   a = a<<14;
664   a |= *p;
665   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
666   if (!(a&0x80))
667   {
668     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
669     b &= (0x7f<<14)|(0x7f);
670     b = b<<7;
671     a |= b;
672     s = s>>11;
673     *v = ((u64)s)<<32 | a;
674     return 7;
675   }
676 
677   /* CSE2 from below */
678   a &= (0x7f<<14)|(0x7f);
679   p++;
680   b = b<<14;
681   b |= *p;
682   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
683   if (!(b&0x80))
684   {
685     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
686     /* moved CSE2 up */
687     /* a &= (0x7f<<14)|(0x7f); */
688     a = a<<7;
689     a |= b;
690     s = s>>4;
691     *v = ((u64)s)<<32 | a;
692     return 8;
693   }
694 
695   p++;
696   a = a<<15;
697   a |= *p;
698   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
699 
700   /* moved CSE2 up */
701   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
702   b &= (0x7f<<14)|(0x7f);
703   b = b<<8;
704   a |= b;
705 
706   s = s<<4;
707   b = p[-4];
708   b &= 0x7f;
709   b = b>>3;
710   s |= b;
711 
712   *v = ((u64)s)<<32 | a;
713 
714   return 9;
715 }
716 
717 /*
718 ** Read a 32-bit variable-length integer from memory starting at p[0].
719 ** Return the number of bytes read.  The value is stored in *v.
720 ** A MACRO version, getVarint32, is provided which inlines the
721 ** single-byte case.  All code should use the MACRO version as
722 ** this function assumes the single-byte case has already been handled.
723 */
724 u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
725   u32 a,b;
726 
727   a = *p;
728   /* a: p0 (unmasked) */
729 #ifndef getVarint32
730   if (!(a&0x80))
731   {
732     *v = a;
733     return 1;
734   }
735 #endif
736 
737   p++;
738   b = *p;
739   /* b: p1 (unmasked) */
740   if (!(b&0x80))
741   {
742     a &= 0x7f;
743     a = a<<7;
744     *v = a | b;
745     return 2;
746   }
747 
748   p++;
749   a = a<<14;
750   a |= *p;
751   /* a: p0<<14 | p2 (unmasked) */
752   if (!(a&0x80))
753   {
754     a &= (0x7f<<14)|(0x7f);
755     b &= 0x7f;
756     b = b<<7;
757     *v = a | b;
758     return 3;
759   }
760 
761   p++;
762   b = b<<14;
763   b |= *p;
764   /* b: p1<<14 | p3 (unmasked) */
765   if (!(b&0x80))
766   {
767     b &= (0x7f<<14)|(0x7f);
768     a &= (0x7f<<14)|(0x7f);
769     a = a<<7;
770     *v = a | b;
771     return 4;
772   }
773 
774   p++;
775   a = a<<14;
776   a |= *p;
777   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
778   if (!(a&0x80))
779   {
780     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
781     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
782     b = b<<7;
783     *v = a | b;
784     return 5;
785   }
786 
787   /* We can only reach this point when reading a corrupt database
788   ** file.  In that case we are not in any hurry.  Use the (relatively
789   ** slow) general-purpose sqlite3GetVarint() routine to extract the
790   ** value. */
791   {
792     u64 v64;
793     u8 n;
794 
795     p -= 4;
796     n = sqlite3GetVarint(p, &v64);
797     assert( n>5 && n<=9 );
798     *v = (u32)v64;
799     return n;
800   }
801 }
802 
803 /*
804 ** Return the number of bytes that will be needed to store the given
805 ** 64-bit integer.
806 */
807 int sqlite3VarintLen(u64 v){
808   int i = 0;
809   do{
810     i++;
811     v >>= 7;
812   }while( v!=0 && i<9 );
813   return i;
814 }
815 
816 
817 /*
818 ** Read or write a four-byte big-endian integer value.
819 */
820 u32 sqlite3Get4byte(const u8 *p){
821   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
822 }
823 void sqlite3Put4byte(unsigned char *p, u32 v){
824   p[0] = (u8)(v>>24);
825   p[1] = (u8)(v>>16);
826   p[2] = (u8)(v>>8);
827   p[3] = (u8)v;
828 }
829 
830 
831 
832 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
833 /*
834 ** Translate a single byte of Hex into an integer.
835 ** This routinen only works if h really is a valid hexadecimal
836 ** character:  0..9a..fA..F
837 */
838 static u8 hexToInt(int h){
839   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
840 #ifdef SQLITE_ASCII
841   h += 9*(1&(h>>6));
842 #endif
843 #ifdef SQLITE_EBCDIC
844   h += 9*(1&~(h>>4));
845 #endif
846   return (u8)(h & 0xf);
847 }
848 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
849 
850 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
851 /*
852 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
853 ** value.  Return a pointer to its binary value.  Space to hold the
854 ** binary value has been obtained from malloc and must be freed by
855 ** the calling routine.
856 */
857 void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
858   char *zBlob;
859   int i;
860 
861   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
862   n--;
863   if( zBlob ){
864     for(i=0; i<n; i+=2){
865       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
866     }
867     zBlob[i/2] = 0;
868   }
869   return zBlob;
870 }
871 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
872 
873 
874 /*
875 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
876 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
877 ** when this routine is called.
878 **
879 ** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
880 ** value indicates that the database connection passed into the API is
881 ** open and is not being used by another thread.  By changing the value
882 ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
883 ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
884 ** when the API exits.
885 **
886 ** This routine is a attempt to detect if two threads use the
887 ** same sqlite* pointer at the same time.  There is a race
888 ** condition so it is possible that the error is not detected.
889 ** But usually the problem will be seen.  The result will be an
890 ** error which can be used to debug the application that is
891 ** using SQLite incorrectly.
892 **
893 ** Ticket #202:  If db->magic is not a valid open value, take care not
894 ** to modify the db structure at all.  It could be that db is a stale
895 ** pointer.  In other words, it could be that there has been a prior
896 ** call to sqlite3_close(db) and db has been deallocated.  And we do
897 ** not want to write into deallocated memory.
898 */
899 #ifdef SQLITE_DEBUG
900 int sqlite3SafetyOn(sqlite3 *db){
901   if( db->magic==SQLITE_MAGIC_OPEN ){
902     db->magic = SQLITE_MAGIC_BUSY;
903     assert( sqlite3_mutex_held(db->mutex) );
904     return 0;
905   }else if( db->magic==SQLITE_MAGIC_BUSY ){
906     db->magic = SQLITE_MAGIC_ERROR;
907     db->u1.isInterrupted = 1;
908   }
909   return 1;
910 }
911 #endif
912 
913 /*
914 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
915 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
916 ** when this routine is called.
917 */
918 #ifdef SQLITE_DEBUG
919 int sqlite3SafetyOff(sqlite3 *db){
920   if( db->magic==SQLITE_MAGIC_BUSY ){
921     db->magic = SQLITE_MAGIC_OPEN;
922     assert( sqlite3_mutex_held(db->mutex) );
923     return 0;
924   }else{
925     db->magic = SQLITE_MAGIC_ERROR;
926     db->u1.isInterrupted = 1;
927     return 1;
928   }
929 }
930 #endif
931 
932 /*
933 ** Check to make sure we have a valid db pointer.  This test is not
934 ** foolproof but it does provide some measure of protection against
935 ** misuse of the interface such as passing in db pointers that are
936 ** NULL or which have been previously closed.  If this routine returns
937 ** 1 it means that the db pointer is valid and 0 if it should not be
938 ** dereferenced for any reason.  The calling function should invoke
939 ** SQLITE_MISUSE immediately.
940 **
941 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
942 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
943 ** open properly and is not fit for general use but which can be
944 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
945 */
946 int sqlite3SafetyCheckOk(sqlite3 *db){
947   u32 magic;
948   if( db==0 ) return 0;
949   magic = db->magic;
950   if( magic!=SQLITE_MAGIC_OPEN &&
951       magic!=SQLITE_MAGIC_BUSY ) return 0;
952   return 1;
953 }
954 int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
955   u32 magic;
956   if( db==0 ) return 0;
957   magic = db->magic;
958   if( magic!=SQLITE_MAGIC_SICK &&
959       magic!=SQLITE_MAGIC_OPEN &&
960       magic!=SQLITE_MAGIC_BUSY ) return 0;
961   return 1;
962 }
963