xref: /sqlite-3.40.0/src/util.c (revision 4dcbdbff)
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.141 2005/07/20 14:31:53 drh Exp $
18 */
19 #include "sqliteInt.h"
20 #include <stdarg.h>
21 #include <ctype.h>
22 
23 #if SQLITE_MEMDEBUG>2 && defined(__GLIBC__)
24 #include <execinfo.h>
25 void print_stack_trace(){
26   void *bt[30];
27   int i;
28   int n = backtrace(bt, 30);
29 
30   fprintf(stderr, "STACK: ");
31   for(i=0; i<n;i++){
32     fprintf(stderr, "%p ", bt[i]);
33   }
34   fprintf(stderr, "\n");
35 }
36 #else
37 #define print_stack_trace()
38 #endif
39 
40 /*
41 ** If malloc() ever fails, this global variable gets set to 1.
42 ** This causes the library to abort and never again function.
43 */
44 int sqlite3_malloc_failed = 0;
45 
46 /*
47 ** If SQLITE_MEMDEBUG is defined, then use versions of malloc() and
48 ** free() that track memory usage and check for buffer overruns.
49 */
50 #ifdef SQLITE_MEMDEBUG
51 
52 /*
53 ** For keeping track of the number of mallocs and frees.   This
54 ** is used to check for memory leaks.  The iMallocFail and iMallocReset
55 ** values are used to simulate malloc() failures during testing in
56 ** order to verify that the library correctly handles an out-of-memory
57 ** condition.
58 */
59 int sqlite3_nMalloc;         /* Number of sqliteMalloc() calls */
60 int sqlite3_nFree;           /* Number of sqliteFree() calls */
61 int sqlite3_memUsed;         /* Total memory obtained from malloc */
62 int sqlite3_memMax;          /* Mem usage high-water mark */
63 int sqlite3_iMallocFail;     /* Fail sqliteMalloc() after this many calls */
64 int sqlite3_iMallocReset = -1; /* When iMallocFail reaches 0, set to this */
65 #if SQLITE_MEMDEBUG>1
66 static int memcnt = 0;
67 #endif
68 
69 /*
70 ** Number of 32-bit guard words.  This should probably be a multiple of
71 ** 2 since on 64-bit machines we want the value returned by sqliteMalloc()
72 ** to be 8-byte aligned.
73 */
74 #define N_GUARD 2
75 
76 /*
77 ** Allocate new memory and set it to zero.  Return NULL if
78 ** no memory is available.
79 */
80 void *sqlite3Malloc_(int n, int bZero, char *zFile, int line){
81   void *p;
82   int *pi;
83   int i, k;
84   if( sqlite3_iMallocFail>=0 ){
85     sqlite3_iMallocFail--;
86     if( sqlite3_iMallocFail==0 ){
87       sqlite3_malloc_failed++;
88 #if SQLITE_MEMDEBUG>1
89       fprintf(stderr,"**** failed to allocate %d bytes at %s:%d\n",
90               n, zFile,line);
91 #endif
92       sqlite3_iMallocFail = sqlite3_iMallocReset;
93       return 0;
94     }
95   }
96   if( n==0 ) return 0;
97   sqlite3_memUsed += n;
98   if( sqlite3_memMax<sqlite3_memUsed ) sqlite3_memMax = sqlite3_memUsed;
99   k = (n+sizeof(int)-1)/sizeof(int);
100   pi = malloc( (N_GUARD*2+1+k)*sizeof(int));
101   if( pi==0 ){
102     if( n>0 ) sqlite3_malloc_failed++;
103     return 0;
104   }
105   sqlite3_nMalloc++;
106   for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
107   pi[N_GUARD] = n;
108   for(i=0; i<N_GUARD; i++) pi[k+1+N_GUARD+i] = 0xdead3344;
109   p = &pi[N_GUARD+1];
110   memset(p, bZero==0, n);
111 #if SQLITE_MEMDEBUG>1
112   print_stack_trace();
113   fprintf(stderr,"%06d malloc %d bytes at 0x%x from %s:%d\n",
114       ++memcnt, n, (int)p, zFile,line);
115 #endif
116   return p;
117 }
118 
119 /*
120 ** This version of malloc is always a real function, never a macro
121 */
122 void *sqlite3MallocX(int n){
123   return sqlite3Malloc_(n, 0, __FILE__, __LINE__);
124 }
125 
126 /*
127 ** Check to see if the given pointer was obtained from sqliteMalloc()
128 ** and is able to hold at least N bytes.  Raise an exception if this
129 ** is not the case.
130 **
131 ** This routine is used for testing purposes only.
132 */
133 void sqlite3CheckMemory(void *p, int N){
134   int *pi = p;
135   int n, i, k;
136   pi -= N_GUARD+1;
137   for(i=0; i<N_GUARD; i++){
138     assert( pi[i]==0xdead1122 );
139   }
140   n = pi[N_GUARD];
141   assert( N>=0 && N<n );
142   k = (n+sizeof(int)-1)/sizeof(int);
143   for(i=0; i<N_GUARD; i++){
144     assert( pi[k+N_GUARD+1+i]==0xdead3344 );
145   }
146 }
147 
148 /*
149 ** Free memory previously obtained from sqliteMalloc()
150 */
151 void sqlite3Free_(void *p, char *zFile, int line){
152   if( p ){
153     int *pi, i, k, n;
154     pi = p;
155     pi -= N_GUARD+1;
156     sqlite3_nFree++;
157     for(i=0; i<N_GUARD; i++){
158       if( pi[i]!=0xdead1122 ){
159         fprintf(stderr,"Low-end memory corruption at 0x%x\n", (int)p);
160         return;
161       }
162     }
163     n = pi[N_GUARD];
164     sqlite3_memUsed -= n;
165     k = (n+sizeof(int)-1)/sizeof(int);
166     for(i=0; i<N_GUARD; i++){
167       if( pi[k+N_GUARD+1+i]!=0xdead3344 ){
168         fprintf(stderr,"High-end memory corruption at 0x%x\n", (int)p);
169         return;
170       }
171     }
172     memset(pi, 0xff, (k+N_GUARD*2+1)*sizeof(int));
173 #if SQLITE_MEMDEBUG>1
174     fprintf(stderr,"%06d free %d bytes at 0x%x from %s:%d\n",
175          ++memcnt, n, (int)p, zFile,line);
176 #endif
177     free(pi);
178   }
179 }
180 
181 /*
182 ** Resize a prior allocation.  If p==0, then this routine
183 ** works just like sqliteMalloc().  If n==0, then this routine
184 ** works just like sqliteFree().
185 */
186 void *sqlite3Realloc_(void *oldP, int n, char *zFile, int line){
187   int *oldPi, *pi, i, k, oldN, oldK;
188   void *p;
189   if( oldP==0 ){
190     return sqlite3Malloc_(n,1,zFile,line);
191   }
192   if( n==0 ){
193     sqlite3Free_(oldP,zFile,line);
194     return 0;
195   }
196   oldPi = oldP;
197   oldPi -= N_GUARD+1;
198   if( oldPi[0]!=0xdead1122 ){
199     fprintf(stderr,"Low-end memory corruption in realloc at 0x%x\n", (int)oldP);
200     return 0;
201   }
202   oldN = oldPi[N_GUARD];
203   sqlite3_memUsed -= oldN;
204   oldK = (oldN+sizeof(int)-1)/sizeof(int);
205   for(i=0; i<N_GUARD; i++){
206     if( oldPi[oldK+N_GUARD+1+i]!=0xdead3344 ){
207       fprintf(stderr,"High-end memory corruption in realloc at 0x%x\n",
208               (int)oldP);
209       return 0;
210     }
211   }
212   k = (n + sizeof(int) - 1)/sizeof(int);
213   pi = malloc( (k+N_GUARD*2+1)*sizeof(int) );
214   if( pi==0 ){
215     if( n>0 ) sqlite3_malloc_failed++;
216     return 0;
217   }
218   for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
219   pi[N_GUARD] = n;
220   sqlite3_memUsed += n;
221   if( sqlite3_memMax<sqlite3_memUsed ) sqlite3_memMax = sqlite3_memUsed;
222   for(i=0; i<N_GUARD; i++) pi[k+N_GUARD+1+i] = 0xdead3344;
223   p = &pi[N_GUARD+1];
224   memcpy(p, oldP, n>oldN ? oldN : n);
225   if( n>oldN ){
226     memset(&((char*)p)[oldN], 0x55, n-oldN);
227   }
228   memset(oldPi, 0xab, (oldK+N_GUARD+2)*sizeof(int));
229   free(oldPi);
230 #if SQLITE_MEMDEBUG>1
231   print_stack_trace();
232   fprintf(stderr,"%06d realloc %d to %d bytes at 0x%x to 0x%x at %s:%d\n",
233     ++memcnt, oldN, n, (int)oldP, (int)p, zFile, line);
234 #endif
235   return p;
236 }
237 
238 /*
239 ** Make a copy of a string in memory obtained from sqliteMalloc()
240 */
241 char *sqlite3StrDup_(const char *z, char *zFile, int line){
242   char *zNew;
243   if( z==0 ) return 0;
244   zNew = sqlite3Malloc_(strlen(z)+1, 0, zFile, line);
245   if( zNew ) strcpy(zNew, z);
246   return zNew;
247 }
248 char *sqlite3StrNDup_(const char *z, int n, char *zFile, int line){
249   char *zNew;
250   if( z==0 ) return 0;
251   zNew = sqlite3Malloc_(n+1, 0, zFile, line);
252   if( zNew ){
253     memcpy(zNew, z, n);
254     zNew[n] = 0;
255   }
256   return zNew;
257 }
258 
259 /*
260 ** A version of sqliteFree that is always a function, not a macro.
261 */
262 void sqlite3FreeX(void *p){
263   sqliteFree(p);
264 }
265 #endif /* SQLITE_MEMDEBUG */
266 
267 /*
268 ** The following versions of malloc() and free() are for use in a
269 ** normal build.
270 */
271 #if !defined(SQLITE_MEMDEBUG)
272 
273 /*
274 ** Allocate new memory and set it to zero.  Return NULL if
275 ** no memory is available.  See also sqliteMallocRaw().
276 */
277 void *sqlite3Malloc(int n){
278   void *p;
279   if( n==0 ) return 0;
280   if( (p = malloc(n))==0 ){
281     if( n>0 ) sqlite3_malloc_failed++;
282   }else{
283     memset(p, 0, n);
284   }
285   return p;
286 }
287 
288 /*
289 ** Allocate new memory but do not set it to zero.  Return NULL if
290 ** no memory is available.  See also sqliteMalloc().
291 */
292 void *sqlite3MallocRaw(int n){
293   void *p;
294   if( n==0 ) return 0;
295   if( (p = malloc(n))==0 ){
296     if( n>0 ) sqlite3_malloc_failed++;
297   }
298   return p;
299 }
300 
301 /*
302 ** Free memory previously obtained from sqliteMalloc()
303 */
304 void sqlite3FreeX(void *p){
305   if( p ){
306     free(p);
307   }
308 }
309 
310 /*
311 ** Resize a prior allocation.  If p==0, then this routine
312 ** works just like sqliteMalloc().  If n==0, then this routine
313 ** works just like sqliteFree().
314 */
315 void *sqlite3Realloc(void *p, int n){
316   void *p2;
317   if( p==0 ){
318     return sqliteMalloc(n);
319   }
320   if( n==0 ){
321     sqliteFree(p);
322     return 0;
323   }
324   p2 = realloc(p, n);
325   if( p2==0 ){
326     if( n>0 ) sqlite3_malloc_failed++;
327   }
328   return p2;
329 }
330 
331 /*
332 ** Make a copy of a string in memory obtained from sqliteMalloc()
333 */
334 char *sqlite3StrDup(const char *z){
335   char *zNew;
336   if( z==0 ) return 0;
337   zNew = sqliteMallocRaw(strlen(z)+1);
338   if( zNew ) strcpy(zNew, z);
339   return zNew;
340 }
341 char *sqlite3StrNDup(const char *z, int n){
342   char *zNew;
343   if( z==0 ) return 0;
344   zNew = sqliteMallocRaw(n+1);
345   if( zNew ){
346     memcpy(zNew, z, n);
347     zNew[n] = 0;
348   }
349   return zNew;
350 }
351 #endif /* !defined(SQLITE_MEMDEBUG) */
352 
353 /*
354 ** Create a string from the 2nd and subsequent arguments (up to the
355 ** first NULL argument), store the string in memory obtained from
356 ** sqliteMalloc() and make the pointer indicated by the 1st argument
357 ** point to that string.  The 1st argument must either be NULL or
358 ** point to memory obtained from sqliteMalloc().
359 */
360 void sqlite3SetString(char **pz, ...){
361   va_list ap;
362   int nByte;
363   const char *z;
364   char *zResult;
365 
366   if( pz==0 ) return;
367   nByte = 1;
368   va_start(ap, pz);
369   while( (z = va_arg(ap, const char*))!=0 ){
370     nByte += strlen(z);
371   }
372   va_end(ap);
373   sqliteFree(*pz);
374   *pz = zResult = sqliteMallocRaw( nByte );
375   if( zResult==0 ){
376     return;
377   }
378   *zResult = 0;
379   va_start(ap, pz);
380   while( (z = va_arg(ap, const char*))!=0 ){
381     strcpy(zResult, z);
382     zResult += strlen(zResult);
383   }
384   va_end(ap);
385 #ifdef SQLITE_MEMDEBUG
386 #if SQLITE_MEMDEBUG>1
387   fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
388 #endif
389 #endif
390 }
391 
392 /*
393 ** Set the most recent error code and error string for the sqlite
394 ** handle "db". The error code is set to "err_code".
395 **
396 ** If it is not NULL, string zFormat specifies the format of the
397 ** error string in the style of the printf functions: The following
398 ** format characters are allowed:
399 **
400 **      %s      Insert a string
401 **      %z      A string that should be freed after use
402 **      %d      Insert an integer
403 **      %T      Insert a token
404 **      %S      Insert the first element of a SrcList
405 **
406 ** zFormat and any string tokens that follow it are assumed to be
407 ** encoded in UTF-8.
408 **
409 ** To clear the most recent error for sqlite handle "db", sqlite3Error
410 ** should be called with err_code set to SQLITE_OK and zFormat set
411 ** to NULL.
412 */
413 void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
414   if( db && (db->pErr || (db->pErr = sqlite3ValueNew())) ){
415     db->errCode = err_code;
416     if( zFormat ){
417       char *z;
418       va_list ap;
419       va_start(ap, zFormat);
420       z = sqlite3VMPrintf(zFormat, ap);
421       va_end(ap);
422       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, sqlite3FreeX);
423     }else{
424       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
425     }
426   }
427 }
428 
429 /*
430 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
431 ** The following formatting characters are allowed:
432 **
433 **      %s      Insert a string
434 **      %z      A string that should be freed after use
435 **      %d      Insert an integer
436 **      %T      Insert a token
437 **      %S      Insert the first element of a SrcList
438 **
439 ** This function should be used to report any error that occurs whilst
440 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
441 ** last thing the sqlite3_prepare() function does is copy the error
442 ** stored by this function into the database handle using sqlite3Error().
443 ** Function sqlite3Error() should be used during statement execution
444 ** (sqlite3_step() etc.).
445 */
446 void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
447   va_list ap;
448   pParse->nErr++;
449   sqliteFree(pParse->zErrMsg);
450   va_start(ap, zFormat);
451   pParse->zErrMsg = sqlite3VMPrintf(zFormat, ap);
452   va_end(ap);
453 }
454 
455 /*
456 ** Convert an SQL-style quoted string into a normal string by removing
457 ** the quote characters.  The conversion is done in-place.  If the
458 ** input does not begin with a quote character, then this routine
459 ** is a no-op.
460 **
461 ** 2002-Feb-14: This routine is extended to remove MS-Access style
462 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
463 ** "a-b-c".
464 */
465 void sqlite3Dequote(char *z){
466   int quote;
467   int i, j;
468   if( z==0 ) return;
469   quote = z[0];
470   switch( quote ){
471     case '\'':  break;
472     case '"':   break;
473     case '[':   quote = ']';  break;
474     default:    return;
475   }
476   for(i=1, j=0; z[i]; i++){
477     if( z[i]==quote ){
478       if( z[i+1]==quote ){
479         z[j++] = quote;
480         i++;
481       }else{
482         z[j++] = 0;
483         break;
484       }
485     }else{
486       z[j++] = z[i];
487     }
488   }
489 }
490 
491 /* An array to map all upper-case characters into their corresponding
492 ** lower-case character.
493 */
494 const unsigned char sqlite3UpperToLower[] = {
495       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
496      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
497      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
498      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
499     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
500     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
501     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
502     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
503     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
504     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
505     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
506     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
507     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
508     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
509     252,253,254,255
510 };
511 #define UpperToLower sqlite3UpperToLower
512 
513 /*
514 ** Some systems have stricmp().  Others have strcasecmp().  Because
515 ** there is no consistency, we will define our own.
516 */
517 int sqlite3StrICmp(const char *zLeft, const char *zRight){
518   register unsigned char *a, *b;
519   a = (unsigned char *)zLeft;
520   b = (unsigned char *)zRight;
521   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
522   return UpperToLower[*a] - UpperToLower[*b];
523 }
524 int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
525   register unsigned char *a, *b;
526   a = (unsigned char *)zLeft;
527   b = (unsigned char *)zRight;
528   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
529   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
530 }
531 
532 /*
533 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
534 ** string contains any character which is not part of a number. If
535 ** the string is numeric and contains the '.' character, set *realnum
536 ** to TRUE (otherwise FALSE).
537 **
538 ** An empty string is considered non-numeric.
539 */
540 int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
541   int incr = (enc==SQLITE_UTF8?1:2);
542   if( enc==SQLITE_UTF16BE ) z++;
543   if( *z=='-' || *z=='+' ) z += incr;
544   if( !isdigit(*(u8*)z) ){
545     return 0;
546   }
547   z += incr;
548   if( realnum ) *realnum = 0;
549   while( isdigit(*(u8*)z) ){ z += incr; }
550   if( *z=='.' ){
551     z += incr;
552     if( !isdigit(*(u8*)z) ) return 0;
553     while( isdigit(*(u8*)z) ){ z += incr; }
554     if( realnum ) *realnum = 1;
555   }
556   if( *z=='e' || *z=='E' ){
557     z += incr;
558     if( *z=='+' || *z=='-' ) z += incr;
559     if( !isdigit(*(u8*)z) ) return 0;
560     while( isdigit(*(u8*)z) ){ z += incr; }
561     if( realnum ) *realnum = 1;
562   }
563   return *z==0;
564 }
565 
566 /*
567 ** The string z[] is an ascii representation of a real number.
568 ** Convert this string to a double.
569 **
570 ** This routine assumes that z[] really is a valid number.  If it
571 ** is not, the result is undefined.
572 **
573 ** This routine is used instead of the library atof() function because
574 ** the library atof() might want to use "," as the decimal point instead
575 ** of "." depending on how locale is set.  But that would cause problems
576 ** for SQL.  So this routine always uses "." regardless of locale.
577 */
578 int sqlite3AtoF(const char *z, double *pResult){
579   int sign = 1;
580   const char *zBegin = z;
581   LONGDOUBLE_TYPE v1 = 0.0;
582   if( *z=='-' ){
583     sign = -1;
584     z++;
585   }else if( *z=='+' ){
586     z++;
587   }
588   while( isdigit(*(u8*)z) ){
589     v1 = v1*10.0 + (*z - '0');
590     z++;
591   }
592   if( *z=='.' ){
593     LONGDOUBLE_TYPE divisor = 1.0;
594     z++;
595     while( isdigit(*(u8*)z) ){
596       v1 = v1*10.0 + (*z - '0');
597       divisor *= 10.0;
598       z++;
599     }
600     v1 /= divisor;
601   }
602   if( *z=='e' || *z=='E' ){
603     int esign = 1;
604     int eval = 0;
605     LONGDOUBLE_TYPE scale = 1.0;
606     z++;
607     if( *z=='-' ){
608       esign = -1;
609       z++;
610     }else if( *z=='+' ){
611       z++;
612     }
613     while( isdigit(*(u8*)z) ){
614       eval = eval*10 + *z - '0';
615       z++;
616     }
617     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
618     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
619     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
620     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
621     if( esign<0 ){
622       v1 /= scale;
623     }else{
624       v1 *= scale;
625     }
626   }
627   *pResult = sign<0 ? -v1 : v1;
628   return z - zBegin;
629 }
630 
631 /*
632 ** Return TRUE if zNum is a 64-bit signed integer and write
633 ** the value of the integer into *pNum.  If zNum is not an integer
634 ** or is an integer that is too large to be expressed with 64 bits,
635 ** then return false.  If n>0 and the integer is string is not
636 ** exactly n bytes long, return false.
637 **
638 ** When this routine was originally written it dealt with only
639 ** 32-bit numbers.  At that time, it was much faster than the
640 ** atoi() library routine in RedHat 7.2.
641 */
642 int sqlite3atoi64(const char *zNum, i64 *pNum){
643   i64 v = 0;
644   int neg;
645   int i, c;
646   if( *zNum=='-' ){
647     neg = 1;
648     zNum++;
649   }else if( *zNum=='+' ){
650     neg = 0;
651     zNum++;
652   }else{
653     neg = 0;
654   }
655   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
656     v = v*10 + c - '0';
657   }
658   *pNum = neg ? -v : v;
659   return c==0 && i>0 &&
660       (i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0));
661 }
662 
663 /*
664 ** The string zNum represents an integer.  There might be some other
665 ** information following the integer too, but that part is ignored.
666 ** If the integer that the prefix of zNum represents will fit in a
667 ** 32-bit signed integer, return TRUE.  Otherwise return FALSE.
668 **
669 ** This routine returns FALSE for the string -2147483648 even that
670 ** that number will in fact fit in a 32-bit integer.  But positive
671 ** 2147483648 will not fit in 32 bits.  So it seems safer to return
672 ** false.
673 */
674 static int sqlite3FitsIn32Bits(const char *zNum){
675   int i, c;
676   if( *zNum=='-' || *zNum=='+' ) zNum++;
677   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
678   return i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0);
679 }
680 
681 /*
682 ** If zNum represents an integer that will fit in 32-bits, then set
683 ** *pValue to that integer and return true.  Otherwise return false.
684 */
685 int sqlite3GetInt32(const char *zNum, int *pValue){
686   if( sqlite3FitsIn32Bits(zNum) ){
687     *pValue = atoi(zNum);
688     return 1;
689   }
690   return 0;
691 }
692 
693 /*
694 ** The string zNum represents an integer.  There might be some other
695 ** information following the integer too, but that part is ignored.
696 ** If the integer that the prefix of zNum represents will fit in a
697 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
698 **
699 ** This routine returns FALSE for the string -9223372036854775808 even that
700 ** that number will, in theory fit in a 64-bit integer.  Positive
701 ** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
702 ** false.
703 */
704 int sqlite3FitsIn64Bits(const char *zNum){
705   int i, c;
706   if( *zNum=='-' || *zNum=='+' ) zNum++;
707   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
708   return i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0);
709 }
710 
711 
712 /*
713 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
714 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
715 ** when this routine is called.
716 **
717 ** This routine is a attempt to detect if two threads use the
718 ** same sqlite* pointer at the same time.  There is a race
719 ** condition so it is possible that the error is not detected.
720 ** But usually the problem will be seen.  The result will be an
721 ** error which can be used to debug the application that is
722 ** using SQLite incorrectly.
723 **
724 ** Ticket #202:  If db->magic is not a valid open value, take care not
725 ** to modify the db structure at all.  It could be that db is a stale
726 ** pointer.  In other words, it could be that there has been a prior
727 ** call to sqlite3_close(db) and db has been deallocated.  And we do
728 ** not want to write into deallocated memory.
729 */
730 int sqlite3SafetyOn(sqlite3 *db){
731   if( db->magic==SQLITE_MAGIC_OPEN ){
732     db->magic = SQLITE_MAGIC_BUSY;
733     return 0;
734   }else if( db->magic==SQLITE_MAGIC_BUSY || db->magic==SQLITE_MAGIC_ERROR ){
735     db->magic = SQLITE_MAGIC_ERROR;
736     db->flags |= SQLITE_Interrupt;
737   }
738   return 1;
739 }
740 
741 /*
742 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
743 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
744 ** when this routine is called.
745 */
746 int sqlite3SafetyOff(sqlite3 *db){
747   if( db->magic==SQLITE_MAGIC_BUSY ){
748     db->magic = SQLITE_MAGIC_OPEN;
749     return 0;
750   }else if( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ERROR ){
751     db->magic = SQLITE_MAGIC_ERROR;
752     db->flags |= SQLITE_Interrupt;
753   }
754   return 1;
755 }
756 
757 /*
758 ** Check to make sure we have a valid db pointer.  This test is not
759 ** foolproof but it does provide some measure of protection against
760 ** misuse of the interface such as passing in db pointers that are
761 ** NULL or which have been previously closed.  If this routine returns
762 ** TRUE it means that the db pointer is invalid and should not be
763 ** dereferenced for any reason.  The calling function should invoke
764 ** SQLITE_MISUSE immediately.
765 */
766 int sqlite3SafetyCheck(sqlite3 *db){
767   int magic;
768   if( db==0 ) return 1;
769   magic = db->magic;
770   if( magic!=SQLITE_MAGIC_CLOSED &&
771          magic!=SQLITE_MAGIC_OPEN &&
772          magic!=SQLITE_MAGIC_BUSY ) return 1;
773   return 0;
774 }
775 
776 /*
777 ** The variable-length integer encoding is as follows:
778 **
779 ** KEY:
780 **         A = 0xxxxxxx    7 bits of data and one flag bit
781 **         B = 1xxxxxxx    7 bits of data and one flag bit
782 **         C = xxxxxxxx    8 bits of data
783 **
784 **  7 bits - A
785 ** 14 bits - BA
786 ** 21 bits - BBA
787 ** 28 bits - BBBA
788 ** 35 bits - BBBBA
789 ** 42 bits - BBBBBA
790 ** 49 bits - BBBBBBA
791 ** 56 bits - BBBBBBBA
792 ** 64 bits - BBBBBBBBC
793 */
794 
795 /*
796 ** Write a 64-bit variable-length integer to memory starting at p[0].
797 ** The length of data write will be between 1 and 9 bytes.  The number
798 ** of bytes written is returned.
799 **
800 ** A variable-length integer consists of the lower 7 bits of each byte
801 ** for all bytes that have the 8th bit set and one byte with the 8th
802 ** bit clear.  Except, if we get to the 9th byte, it stores the full
803 ** 8 bits and is the last byte.
804 */
805 int sqlite3PutVarint(unsigned char *p, u64 v){
806   int i, j, n;
807   u8 buf[10];
808   if( v & (((u64)0xff000000)<<32) ){
809     p[8] = v;
810     v >>= 8;
811     for(i=7; i>=0; i--){
812       p[i] = (v & 0x7f) | 0x80;
813       v >>= 7;
814     }
815     return 9;
816   }
817   n = 0;
818   do{
819     buf[n++] = (v & 0x7f) | 0x80;
820     v >>= 7;
821   }while( v!=0 );
822   buf[0] &= 0x7f;
823   assert( n<=9 );
824   for(i=0, j=n-1; j>=0; j--, i++){
825     p[i] = buf[j];
826   }
827   return n;
828 }
829 
830 /*
831 ** Read a 64-bit variable-length integer from memory starting at p[0].
832 ** Return the number of bytes read.  The value is stored in *v.
833 */
834 int sqlite3GetVarint(const unsigned char *p, u64 *v){
835   u32 x;
836   u64 x64;
837   int n;
838   unsigned char c;
839   if( ((c = p[0]) & 0x80)==0 ){
840     *v = c;
841     return 1;
842   }
843   x = c & 0x7f;
844   if( ((c = p[1]) & 0x80)==0 ){
845     *v = (x<<7) | c;
846     return 2;
847   }
848   x = (x<<7) | (c&0x7f);
849   if( ((c = p[2]) & 0x80)==0 ){
850     *v = (x<<7) | c;
851     return 3;
852   }
853   x = (x<<7) | (c&0x7f);
854   if( ((c = p[3]) & 0x80)==0 ){
855     *v = (x<<7) | c;
856     return 4;
857   }
858   x64 = (x<<7) | (c&0x7f);
859   n = 4;
860   do{
861     c = p[n++];
862     if( n==9 ){
863       x64 = (x64<<8) | c;
864       break;
865     }
866     x64 = (x64<<7) | (c&0x7f);
867   }while( (c & 0x80)!=0 );
868   *v = x64;
869   return n;
870 }
871 
872 /*
873 ** Read a 32-bit variable-length integer from memory starting at p[0].
874 ** Return the number of bytes read.  The value is stored in *v.
875 */
876 int sqlite3GetVarint32(const unsigned char *p, u32 *v){
877   u32 x;
878   int n;
879   unsigned char c;
880   if( ((signed char*)p)[0]>=0 ){
881     *v = p[0];
882     return 1;
883   }
884   x = p[0] & 0x7f;
885   if( ((signed char*)p)[1]>=0 ){
886     *v = (x<<7) | p[1];
887     return 2;
888   }
889   x = (x<<7) | (p[1] & 0x7f);
890   n = 2;
891   do{
892     x = (x<<7) | ((c = p[n++])&0x7f);
893   }while( (c & 0x80)!=0 && n<9 );
894   *v = x;
895   return n;
896 }
897 
898 /*
899 ** Return the number of bytes that will be needed to store the given
900 ** 64-bit integer.
901 */
902 int sqlite3VarintLen(u64 v){
903   int i = 0;
904   do{
905     i++;
906     v >>= 7;
907   }while( v!=0 && i<9 );
908   return i;
909 }
910 
911 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC) \
912     || defined(SQLITE_TEST)
913 /*
914 ** Translate a single byte of Hex into an integer.
915 */
916 static int hexToInt(int h){
917   if( h>='0' && h<='9' ){
918     return h - '0';
919   }else if( h>='a' && h<='f' ){
920     return h - 'a' + 10;
921   }else{
922     assert( h>='A' && h<='F' );
923     return h - 'A' + 10;
924   }
925 }
926 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC || SQLITE_TEST */
927 
928 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
929 /*
930 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
931 ** value.  Return a pointer to its binary value.  Space to hold the
932 ** binary value has been obtained from malloc and must be freed by
933 ** the calling routine.
934 */
935 void *sqlite3HexToBlob(const char *z){
936   char *zBlob;
937   int i;
938   int n = strlen(z);
939   if( n%2 ) return 0;
940 
941   zBlob = (char *)sqliteMalloc(n/2);
942   for(i=0; i<n; i+=2){
943     zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
944   }
945   return zBlob;
946 }
947 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
948 
949 #if defined(SQLITE_TEST)
950 /*
951 ** Convert text generated by the "%p" conversion format back into
952 ** a pointer.
953 */
954 void *sqlite3TextToPtr(const char *z){
955   void *p;
956   u64 v;
957   u32 v2;
958   if( z[0]=='0' && z[1]=='x' ){
959     z += 2;
960   }
961   v = 0;
962   while( *z ){
963     v = (v<<4) + hexToInt(*z);
964     z++;
965   }
966   if( sizeof(p)==sizeof(v) ){
967     p = *(void**)&v;
968   }else{
969     assert( sizeof(p)==sizeof(v2) );
970     v2 = (u32)v;
971     p = *(void**)&v2;
972   }
973   return p;
974 }
975 #endif
976