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