xref: /sqlite-3.40.0/src/util.c (revision ef5ecb41)
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.100 2004/06/09 14:01:53 drh Exp $
18 */
19 #include "sqliteInt.h"
20 #include <stdarg.h>
21 #include <ctype.h>
22 
23 /*
24 ** If malloc() ever fails, this global variable gets set to 1.
25 ** This causes the library to abort and never again function.
26 */
27 int sqlite3_malloc_failed = 0;
28 
29 /*
30 ** If SQLITE_DEBUG is defined, then use versions of malloc() and
31 ** free() that track memory usage and check for buffer overruns.
32 */
33 #ifdef SQLITE_DEBUG
34 
35 /*
36 ** For keeping track of the number of mallocs and frees.   This
37 ** is used to check for memory leaks.
38 */
39 int sqlite3_nMalloc;         /* Number of sqliteMalloc() calls */
40 int sqlite3_nFree;           /* Number of sqliteFree() calls */
41 int sqlite3_iMallocFail;     /* Fail sqliteMalloc() after this many calls */
42 #if SQLITE_DEBUG>1
43 static int memcnt = 0;
44 #endif
45 
46 /*
47 ** Number of 32-bit guard words
48 */
49 #define N_GUARD 1
50 
51 /*
52 ** Allocate new memory and set it to zero.  Return NULL if
53 ** no memory is available.
54 */
55 void *sqlite3Malloc_(int n, int bZero, char *zFile, int line){
56   void *p;
57   int *pi;
58   int i, k;
59   if( sqlite3_iMallocFail>=0 ){
60     sqlite3_iMallocFail--;
61     if( sqlite3_iMallocFail==0 ){
62       sqlite3_malloc_failed++;
63 #if SQLITE_DEBUG>1
64       fprintf(stderr,"**** failed to allocate %d bytes at %s:%d\n",
65               n, zFile,line);
66 #endif
67       sqlite3_iMallocFail--;
68       return 0;
69     }
70   }
71   if( n==0 ) return 0;
72   k = (n+sizeof(int)-1)/sizeof(int);
73   pi = malloc( (N_GUARD*2+1+k)*sizeof(int));
74   if( pi==0 ){
75     sqlite3_malloc_failed++;
76     return 0;
77   }
78   sqlite3_nMalloc++;
79   for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
80   pi[N_GUARD] = n;
81   for(i=0; i<N_GUARD; i++) pi[k+1+N_GUARD+i] = 0xdead3344;
82   p = &pi[N_GUARD+1];
83   memset(p, bZero==0, n);
84 #if SQLITE_DEBUG>1
85   fprintf(stderr,"%06d malloc %d bytes at 0x%x from %s:%d\n",
86       ++memcnt, n, (int)p, zFile,line);
87 #endif
88   return p;
89 }
90 
91 /*
92 ** Check to see if the given pointer was obtained from sqliteMalloc()
93 ** and is able to hold at least N bytes.  Raise an exception if this
94 ** is not the case.
95 **
96 ** This routine is used for testing purposes only.
97 */
98 void sqlite3CheckMemory(void *p, int N){
99   int *pi = p;
100   int n, i, k;
101   pi -= N_GUARD+1;
102   for(i=0; i<N_GUARD; i++){
103     assert( pi[i]==0xdead1122 );
104   }
105   n = pi[N_GUARD];
106   assert( N>=0 && N<n );
107   k = (n+sizeof(int)-1)/sizeof(int);
108   for(i=0; i<N_GUARD; i++){
109     assert( pi[k+N_GUARD+1+i]==0xdead3344 );
110   }
111 }
112 
113 /*
114 ** Free memory previously obtained from sqliteMalloc()
115 */
116 void sqlite3Free_(void *p, char *zFile, int line){
117   if( p ){
118     int *pi, i, k, n;
119     pi = p;
120     pi -= N_GUARD+1;
121     sqlite3_nFree++;
122     for(i=0; i<N_GUARD; i++){
123       if( pi[i]!=0xdead1122 ){
124         fprintf(stderr,"Low-end memory corruption at 0x%x\n", (int)p);
125         return;
126       }
127     }
128     n = pi[N_GUARD];
129     k = (n+sizeof(int)-1)/sizeof(int);
130     for(i=0; i<N_GUARD; i++){
131       if( pi[k+N_GUARD+1+i]!=0xdead3344 ){
132         fprintf(stderr,"High-end memory corruption at 0x%x\n", (int)p);
133         return;
134       }
135     }
136     memset(pi, 0xff, (k+N_GUARD*2+1)*sizeof(int));
137 #if SQLITE_DEBUG>1
138     fprintf(stderr,"%06d free %d bytes at 0x%x from %s:%d\n",
139          ++memcnt, n, (int)p, zFile,line);
140 #endif
141     free(pi);
142   }
143 }
144 
145 /*
146 ** Resize a prior allocation.  If p==0, then this routine
147 ** works just like sqliteMalloc().  If n==0, then this routine
148 ** works just like sqliteFree().
149 */
150 void *sqlite3Realloc_(void *oldP, int n, char *zFile, int line){
151   int *oldPi, *pi, i, k, oldN, oldK;
152   void *p;
153   if( oldP==0 ){
154     return sqlite3Malloc_(n,1,zFile,line);
155   }
156   if( n==0 ){
157     sqlite3Free_(oldP,zFile,line);
158     return 0;
159   }
160   oldPi = oldP;
161   oldPi -= N_GUARD+1;
162   if( oldPi[0]!=0xdead1122 ){
163     fprintf(stderr,"Low-end memory corruption in realloc at 0x%x\n", (int)oldP);
164     return 0;
165   }
166   oldN = oldPi[N_GUARD];
167   oldK = (oldN+sizeof(int)-1)/sizeof(int);
168   for(i=0; i<N_GUARD; i++){
169     if( oldPi[oldK+N_GUARD+1+i]!=0xdead3344 ){
170       fprintf(stderr,"High-end memory corruption in realloc at 0x%x\n",
171               (int)oldP);
172       return 0;
173     }
174   }
175   k = (n + sizeof(int) - 1)/sizeof(int);
176   pi = malloc( (k+N_GUARD*2+1)*sizeof(int) );
177   if( pi==0 ){
178     sqlite3_malloc_failed++;
179     return 0;
180   }
181   for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
182   pi[N_GUARD] = n;
183   for(i=0; i<N_GUARD; i++) pi[k+N_GUARD+1+i] = 0xdead3344;
184   p = &pi[N_GUARD+1];
185   memcpy(p, oldP, n>oldN ? oldN : n);
186   if( n>oldN ){
187     memset(&((char*)p)[oldN], 0, n-oldN);
188   }
189   memset(oldPi, 0xab, (oldK+N_GUARD+2)*sizeof(int));
190   free(oldPi);
191 #if SQLITE_DEBUG>1
192   fprintf(stderr,"%06d realloc %d to %d bytes at 0x%x to 0x%x at %s:%d\n",
193     ++memcnt, oldN, n, (int)oldP, (int)p, zFile, line);
194 #endif
195   return p;
196 }
197 
198 /*
199 ** Make a duplicate of a string into memory obtained from malloc()
200 ** Free the original string using sqliteFree().
201 **
202 ** This routine is called on all strings that are passed outside of
203 ** the SQLite library.  That way clients can free the string using free()
204 ** rather than having to call sqliteFree().
205 */
206 void sqlite3StrRealloc(char **pz){
207   char *zNew;
208   if( pz==0 || *pz==0 ) return;
209   zNew = malloc( strlen(*pz) + 1 );
210   if( zNew==0 ){
211     sqlite3_malloc_failed++;
212     sqliteFree(*pz);
213     *pz = 0;
214   }
215   strcpy(zNew, *pz);
216   sqliteFree(*pz);
217   *pz = zNew;
218 }
219 
220 /*
221 ** Make a copy of a string in memory obtained from sqliteMalloc()
222 */
223 char *sqlite3StrDup_(const char *z, char *zFile, int line){
224   char *zNew;
225   if( z==0 ) return 0;
226   zNew = sqlite3Malloc_(strlen(z)+1, 0, zFile, line);
227   if( zNew ) strcpy(zNew, z);
228   return zNew;
229 }
230 char *sqlite3StrNDup_(const char *z, int n, char *zFile, int line){
231   char *zNew;
232   if( z==0 ) return 0;
233   zNew = sqlite3Malloc_(n+1, 0, zFile, line);
234   if( zNew ){
235     memcpy(zNew, z, n);
236     zNew[n] = 0;
237   }
238   return zNew;
239 }
240 #endif /* SQLITE_DEBUG */
241 
242 /*
243 ** The following versions of malloc() and free() are for use in a
244 ** normal build.
245 */
246 #if !defined(SQLITE_DEBUG)
247 
248 /*
249 ** Allocate new memory and set it to zero.  Return NULL if
250 ** no memory is available.  See also sqliteMallocRaw().
251 */
252 void *sqliteMalloc(int n){
253   void *p;
254   if( (p = malloc(n))==0 ){
255     if( n>0 ) sqlite3_malloc_failed++;
256   }else{
257     memset(p, 0, n);
258   }
259   return p;
260 }
261 
262 /*
263 ** Allocate new memory but do not set it to zero.  Return NULL if
264 ** no memory is available.  See also sqliteMalloc().
265 */
266 void *sqliteMallocRaw(int n){
267   void *p;
268   if( (p = malloc(n))==0 ){
269     if( n>0 ) sqlite3_malloc_failed++;
270   }
271   return p;
272 }
273 
274 /*
275 ** Free memory previously obtained from sqliteMalloc()
276 */
277 void sqliteFree(void *p){
278   if( p ){
279     free(p);
280   }
281 }
282 
283 /*
284 ** Resize a prior allocation.  If p==0, then this routine
285 ** works just like sqliteMalloc().  If n==0, then this routine
286 ** works just like sqliteFree().
287 */
288 void *sqliteRealloc(void *p, int n){
289   void *p2;
290   if( p==0 ){
291     return sqliteMalloc(n);
292   }
293   if( n==0 ){
294     sqliteFree(p);
295     return 0;
296   }
297   p2 = realloc(p, n);
298   if( p2==0 ){
299     sqlite3_malloc_failed++;
300   }
301   return p2;
302 }
303 
304 /*
305 ** Make a copy of a string in memory obtained from sqliteMalloc()
306 */
307 char *sqliteStrDup(const char *z){
308   char *zNew;
309   if( z==0 ) return 0;
310   zNew = sqliteMallocRaw(strlen(z)+1);
311   if( zNew ) strcpy(zNew, z);
312   return zNew;
313 }
314 char *sqliteStrNDup(const char *z, int n){
315   char *zNew;
316   if( z==0 ) return 0;
317   zNew = sqliteMallocRaw(n+1);
318   if( zNew ){
319     memcpy(zNew, z, n);
320     zNew[n] = 0;
321   }
322   return zNew;
323 }
324 #endif /* !defined(SQLITE_DEBUG) */
325 
326 /*
327 ** Create a string from the 2nd and subsequent arguments (up to the
328 ** first NULL argument), store the string in memory obtained from
329 ** sqliteMalloc() and make the pointer indicated by the 1st argument
330 ** point to that string.  The 1st argument must either be NULL or
331 ** point to memory obtained from sqliteMalloc().
332 */
333 void sqlite3SetString(char **pz, const char *zFirst, ...){
334   va_list ap;
335   int nByte;
336   const char *z;
337   char *zResult;
338 
339   if( pz==0 ) return;
340   nByte = strlen(zFirst) + 1;
341   va_start(ap, zFirst);
342   while( (z = va_arg(ap, const char*))!=0 ){
343     nByte += strlen(z);
344   }
345   va_end(ap);
346   sqliteFree(*pz);
347   *pz = zResult = sqliteMallocRaw( nByte );
348   if( zResult==0 ){
349     return;
350   }
351   strcpy(zResult, zFirst);
352   zResult += strlen(zResult);
353   va_start(ap, zFirst);
354   while( (z = va_arg(ap, const char*))!=0 ){
355     strcpy(zResult, z);
356     zResult += strlen(zResult);
357   }
358   va_end(ap);
359 #ifdef SQLITE_DEBUG
360 #if SQLITE_DEBUG>1
361   fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
362 #endif
363 #endif
364 }
365 
366 /*
367 ** Works like sqlite3SetString, but each string is now followed by
368 ** a length integer which specifies how much of the source string
369 ** to copy (in bytes).  -1 means use the whole string.  The 1st
370 ** argument must either be NULL or point to memory obtained from
371 ** sqliteMalloc().
372 */
373 void sqlite3SetNString(char **pz, ...){
374   va_list ap;
375   int nByte;
376   const char *z;
377   char *zResult;
378   int n;
379 
380   if( pz==0 ) return;
381   nByte = 0;
382   va_start(ap, pz);
383   while( (z = va_arg(ap, const char*))!=0 ){
384     n = va_arg(ap, int);
385     if( n<=0 ) n = strlen(z);
386     nByte += n;
387   }
388   va_end(ap);
389   sqliteFree(*pz);
390   *pz = zResult = sqliteMallocRaw( nByte + 1 );
391   if( zResult==0 ) return;
392   va_start(ap, pz);
393   while( (z = va_arg(ap, const char*))!=0 ){
394     n = va_arg(ap, int);
395     if( n<=0 ) n = strlen(z);
396     memcpy(zResult, z, n);
397     zResult += n;
398   }
399   *zResult = 0;
400 #ifdef SQLITE_DEBUG
401 #if SQLITE_DEBUG>1
402   fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
403 #endif
404 #endif
405   va_end(ap);
406 }
407 
408 /*
409 ** Set the most recent error code and error string for the sqlite
410 ** handle "db". The error code is set to "err_code".
411 **
412 ** If it is not NULL, string zFormat specifies the format of the
413 ** error string in the style of the printf functions: The following
414 ** format characters are allowed:
415 **
416 **      %s      Insert a string
417 **      %z      A string that should be freed after use
418 **      %d      Insert an integer
419 **      %T      Insert a token
420 **      %S      Insert the first element of a SrcList
421 **
422 ** zFormat and any string tokens that follow it are assumed to be
423 ** encoded in UTF-8.
424 **
425 ** To clear the most recent error for slqite handle "db", sqlite3Error
426 ** should be called with err_code set to SQLITE_OK and zFormat set
427 ** to NULL.
428 */
429 void sqlite3Error(sqlite *db, int err_code, const char *zFormat, ...){
430   /* Free any existing error message. */
431   if( db->zErrMsg ){
432     sqliteFree(db->zErrMsg);
433     db->zErrMsg = 0;
434   }
435   if( db->zErrMsg16 ){
436     sqliteFree(db->zErrMsg16);
437     db->zErrMsg16 = 0;
438   }
439 
440   /* Set the new error code and error message. */
441   db->errCode = err_code;
442   if( zFormat ){
443     va_list ap;
444     va_start(ap, zFormat);
445     db->zErrMsg = sqlite3VMPrintf(zFormat, ap);
446     va_end(ap);
447   }
448 }
449 
450 /*
451 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
452 ** The following formatting characters are allowed:
453 **
454 **      %s      Insert a string
455 **      %z      A string that should be freed after use
456 **      %d      Insert an integer
457 **      %T      Insert a token
458 **      %S      Insert the first element of a SrcList
459 */
460 void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
461   va_list ap;
462   pParse->nErr++;
463   sqliteFree(pParse->zErrMsg);
464   va_start(ap, zFormat);
465   pParse->zErrMsg = sqlite3VMPrintf(zFormat, ap);
466   va_end(ap);
467 }
468 
469 /*
470 ** Convert an SQL-style quoted string into a normal string by removing
471 ** the quote characters.  The conversion is done in-place.  If the
472 ** input does not begin with a quote character, then this routine
473 ** is a no-op.
474 **
475 ** 2002-Feb-14: This routine is extended to remove MS-Access style
476 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
477 ** "a-b-c".
478 */
479 void sqlite3Dequote(char *z){
480   int quote;
481   int i, j;
482   if( z==0 ) return;
483   quote = z[0];
484   switch( quote ){
485     case '\'':  break;
486     case '"':   break;
487     case '[':   quote = ']';  break;
488     default:    return;
489   }
490   for(i=1, j=0; z[i]; i++){
491     if( z[i]==quote ){
492       if( z[i+1]==quote ){
493         z[j++] = quote;
494         i++;
495       }else{
496         z[j++] = 0;
497         break;
498       }
499     }else{
500       z[j++] = z[i];
501     }
502   }
503 }
504 
505 /* An array to map all upper-case characters into their corresponding
506 ** lower-case character.
507 */
508 static unsigned char UpperToLower[] = {
509       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
510      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
511      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
512      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
513     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
514     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
515     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
516     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
517     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
518     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
519     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
520     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
521     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
522     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
523     252,253,254,255
524 };
525 
526 /*
527 ** This function computes a hash on the name of a keyword.
528 ** Case is not significant.
529 */
530 int sqlite3HashNoCase(const char *z, int n){
531   int h = 0;
532   if( n<=0 ) n = strlen(z);
533   while( n > 0  ){
534     h = (h<<3) ^ h ^ UpperToLower[(unsigned char)*z++];
535     n--;
536   }
537   return h & 0x7fffffff;
538 }
539 
540 /*
541 ** Some systems have stricmp().  Others have strcasecmp().  Because
542 ** there is no consistency, we will define our own.
543 */
544 int sqlite3StrICmp(const char *zLeft, const char *zRight){
545   register unsigned char *a, *b;
546   a = (unsigned char *)zLeft;
547   b = (unsigned char *)zRight;
548   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
549   return *a - *b;
550 }
551 int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
552   register unsigned char *a, *b;
553   a = (unsigned char *)zLeft;
554   b = (unsigned char *)zRight;
555   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
556   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
557 }
558 
559 /*
560 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
561 ** string contains any character which is not part of a number. If
562 ** the string is numeric and contains the '.' character, set *realnum
563 ** to TRUE (otherwise FALSE).
564 **
565 ** Am empty string is considered non-numeric.
566 */
567 int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
568   int incr = (enc==TEXT_Utf8?1:2);
569   if( enc==TEXT_Utf16be ) z++;
570   if( *z=='-' || *z=='+' ) z += incr;
571   if( !isdigit(*z) ){
572     return 0;
573   }
574   z += incr;
575   if( realnum ) *realnum = 0;
576   while( isdigit(*z) ){ z += incr; }
577   if( *z=='.' ){
578     z += incr;
579     if( !isdigit(*z) ) return 0;
580     while( isdigit(*z) ){ z += incr; }
581     if( realnum ) *realnum = 1;
582   }
583   if( *z=='e' || *z=='E' ){
584     z += incr;
585     if( *z=='+' || *z=='-' ) z += incr;
586     if( !isdigit(*z) ) return 0;
587     while( isdigit(*z) ){ z += incr; }
588     if( realnum ) *realnum = 1;
589   }
590   return *z==0;
591 }
592 
593 /*
594 ** The string z[] is an ascii representation of a real number.
595 ** Convert this string to a double.
596 **
597 ** This routine assumes that z[] really is a valid number.  If it
598 ** is not, the result is undefined.
599 **
600 ** This routine is used instead of the library atof() function because
601 ** the library atof() might want to use "," as the decimal point instead
602 ** of "." depending on how locale is set.  But that would cause problems
603 ** for SQL.  So this routine always uses "." regardless of locale.
604 */
605 double sqlite3AtoF(const char *z, const char **pzEnd){
606   int sign = 1;
607   LONGDOUBLE_TYPE v1 = 0.0;
608   if( *z=='-' ){
609     sign = -1;
610     z++;
611   }else if( *z=='+' ){
612     z++;
613   }
614   while( isdigit(*z) ){
615     v1 = v1*10.0 + (*z - '0');
616     z++;
617   }
618   if( *z=='.' ){
619     LONGDOUBLE_TYPE divisor = 1.0;
620     z++;
621     while( isdigit(*z) ){
622       v1 = v1*10.0 + (*z - '0');
623       divisor *= 10.0;
624       z++;
625     }
626     v1 /= divisor;
627   }
628   if( *z=='e' || *z=='E' ){
629     int esign = 1;
630     int eval = 0;
631     LONGDOUBLE_TYPE scale = 1.0;
632     z++;
633     if( *z=='-' ){
634       esign = -1;
635       z++;
636     }else if( *z=='+' ){
637       z++;
638     }
639     while( isdigit(*z) ){
640       eval = eval*10 + *z - '0';
641       z++;
642     }
643     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
644     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
645     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
646     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
647     if( esign<0 ){
648       v1 /= scale;
649     }else{
650       v1 *= scale;
651     }
652   }
653   if( pzEnd ) *pzEnd = z;
654   return sign<0 ? -v1 : v1;
655 }
656 
657 /*
658 ** Return TRUE if zNum is a 64-bit signed integer and write
659 ** the value of the integer into *pNum.  If zNum is not an integer
660 ** or is an integer that is too large to be expressed with 64 bits,
661 ** then return false.  If n>0 and the integer is string is not
662 ** exactly n bytes long, return false.
663 **
664 ** When this routine was originally written it dealt with only
665 ** 32-bit numbers.  At that time, it was much faster than the
666 ** atoi() library routine in RedHat 7.2.
667 */
668 int sqlite3atoi64(const char *zNum, i64 *pNum){
669   i64 v = 0;
670   int neg;
671   int i, c;
672   if( *zNum=='-' ){
673     neg = 1;
674     zNum++;
675   }else if( *zNum=='+' ){
676     neg = 0;
677     zNum++;
678   }else{
679     neg = 0;
680   }
681   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
682     v = v*10 + c - '0';
683   }
684   *pNum = neg ? -v : v;
685   return c==0 && i>0 &&
686       (i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0));
687 }
688 
689 /*
690 ** The string zNum represents an integer.  There might be some other
691 ** information following the integer too, but that part is ignored.
692 ** If the integer that the prefix of zNum represents will fit in a
693 ** 32-bit signed integer, return TRUE.  Otherwise return FALSE.
694 **
695 ** This routine returns FALSE for the string -2147483648 even that
696 ** that number will, in theory fit in a 32-bit integer.  But positive
697 ** 2147483648 will not fit in 32 bits.  So it seems safer to return
698 ** false.
699 */
700 static int sqlite3FitsIn32Bits(const char *zNum){
701   int i, c;
702   if( *zNum=='-' || *zNum=='+' ) zNum++;
703   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
704   return i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0);
705 }
706 
707 /*
708 ** If zNum represents an integer that will fit in 32-bits, then set
709 ** *pValue to that integer and return true.  Otherwise return false.
710 */
711 int sqlite3GetInt32(const char *zNum, int *pValue){
712   if( sqlite3FitsIn32Bits(zNum) ){
713     *pValue = atoi(zNum);
714     return 1;
715   }
716   return 0;
717 }
718 
719 /*
720 ** The string zNum represents an integer.  There might be some other
721 ** information following the integer too, but that part is ignored.
722 ** If the integer that the prefix of zNum represents will fit in a
723 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
724 **
725 ** This routine returns FALSE for the string -9223372036854775808 even that
726 ** that number will, in theory fit in a 64-bit integer.  Positive
727 ** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
728 ** false.
729 */
730 int sqlite3FitsIn64Bits(const char *zNum){
731   int i, c;
732   if( *zNum=='-' || *zNum=='+' ) zNum++;
733   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
734   return i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0);
735 }
736 
737 /*
738 ** If zNum represents an integer that will fit in 64-bits, then set
739 ** *pValue to that integer and return true.  Otherwise return false.
740 */
741 int sqlite3GetInt64(const char *zNum, i64 *pValue){
742   if( sqlite3FitsIn64Bits(zNum) ){
743     sqlite3atoi64(zNum, pValue);
744     return 1;
745   }
746   return 0;
747 }
748 
749 /* This comparison routine is what we use for comparison operations
750 ** between numeric values in an SQL expression.  "Numeric" is a little
751 ** bit misleading here.  What we mean is that the strings have a
752 ** type of "numeric" from the point of view of SQL.  The strings
753 ** do not necessarily contain numbers.  They could contain text.
754 **
755 ** If the input strings both look like actual numbers then they
756 ** compare in numerical order.  Numerical strings are always less
757 ** than non-numeric strings so if one input string looks like a
758 ** number and the other does not, then the one that looks like
759 ** a number is the smaller.  Non-numeric strings compare in
760 ** lexigraphical order (the same order as strcmp()).
761 */
762 int sqlite3Compare(const char *atext, const char *btext){
763   int result;
764   int isNumA, isNumB;
765   if( atext==0 ){
766     return -1;
767   }else if( btext==0 ){
768     return 1;
769   }
770   isNumA = sqlite3IsNumber(atext, 0, TEXT_Utf8);
771   isNumB = sqlite3IsNumber(btext, 0, TEXT_Utf8);
772   if( isNumA ){
773     if( !isNumB ){
774       result = -1;
775     }else{
776       double rA, rB;
777       rA = sqlite3AtoF(atext, 0);
778       rB = sqlite3AtoF(btext, 0);
779       if( rA<rB ){
780         result = -1;
781       }else if( rA>rB ){
782         result = +1;
783       }else{
784         result = 0;
785       }
786     }
787   }else if( isNumB ){
788     result = +1;
789   }else {
790     result = strcmp(atext, btext);
791   }
792   return result;
793 }
794 
795 /*
796 ** This routine is used for sorting.  Each key is a list of one or more
797 ** null-terminated elements.  The list is terminated by two nulls in
798 ** a row.  For example, the following text is a key with three elements
799 **
800 **            Aone\000Dtwo\000Athree\000\000
801 **
802 ** All elements begin with one of the characters "+-AD" and end with "\000"
803 ** with zero or more text elements in between.  Except, NULL elements
804 ** consist of the special two-character sequence "N\000".
805 **
806 ** Both arguments will have the same number of elements.  This routine
807 ** returns negative, zero, or positive if the first argument is less
808 ** than, equal to, or greater than the first.  (Result is a-b).
809 **
810 ** Each element begins with one of the characters "+", "-", "A", "D".
811 ** This character determines the sort order and collating sequence:
812 **
813 **     +      Sort numerically in ascending order
814 **     -      Sort numerically in descending order
815 **     A      Sort as strings in ascending order
816 **     D      Sort as strings in descending order.
817 **
818 ** For the "+" and "-" sorting, pure numeric strings (strings for which the
819 ** isNum() function above returns TRUE) always compare less than strings
820 ** that are not pure numerics.  Non-numeric strings compare in memcmp()
821 ** order.  This is the same sort order as the sqlite3Compare() function
822 ** above generates.
823 **
824 ** The last point is a change from version 2.6.3 to version 2.7.0.  In
825 ** version 2.6.3 and earlier, substrings of digits compare in numerical
826 ** and case was used only to break a tie.
827 **
828 ** Elements that begin with 'A' or 'D' compare in memcmp() order regardless
829 ** of whether or not they look like a number.
830 **
831 ** Note that the sort order imposed by the rules above is the same
832 ** from the ordering defined by the "<", "<=", ">", and ">=" operators
833 ** of expressions and for indices.  This was not the case for version
834 ** 2.6.3 and earlier.
835 */
836 int sqlite3SortCompare(const char *a, const char *b){
837   int res = 0;
838   int isNumA, isNumB;
839   int dir = 0;
840 
841   while( res==0 && *a && *b ){
842     if( a[0]=='N' || b[0]=='N' ){
843       if( a[0]==b[0] ){
844         a += 2;
845         b += 2;
846         continue;
847       }
848       if( a[0]=='N' ){
849         dir = b[0];
850         res = -1;
851       }else{
852         dir = a[0];
853         res = +1;
854       }
855       break;
856     }
857     assert( a[0]==b[0] );
858     if( (dir=a[0])=='A' || a[0]=='D' ){
859       res = strcmp(&a[1],&b[1]);
860       if( res ) break;
861     }else{
862       isNumA = sqlite3IsNumber(&a[1], 0, TEXT_Utf8);
863       isNumB = sqlite3IsNumber(&b[1], 0, TEXT_Utf8);
864       if( isNumA ){
865         double rA, rB;
866         if( !isNumB ){
867           res = -1;
868           break;
869         }
870         rA = sqlite3AtoF(&a[1], 0);
871         rB = sqlite3AtoF(&b[1], 0);
872         if( rA<rB ){
873           res = -1;
874           break;
875         }
876         if( rA>rB ){
877           res = +1;
878           break;
879         }
880       }else if( isNumB ){
881         res = +1;
882         break;
883       }else{
884         res = strcmp(&a[1],&b[1]);
885         if( res ) break;
886       }
887     }
888     a += strlen(&a[1]) + 2;
889     b += strlen(&b[1]) + 2;
890   }
891   if( dir=='-' || dir=='D' ) res = -res;
892   return res;
893 }
894 
895 #if 1  /* We are now always UTF-8 */
896 /*
897 ** X is a pointer to the first byte of a UTF-8 character.  Increment
898 ** X so that it points to the next character.  This only works right
899 ** if X points to a well-formed UTF-8 string.
900 */
901 #define sqliteNextChar(X)  while( (0xc0&*++(X))==0x80 ){}
902 #define sqliteCharVal(X)   sqlite3ReadUtf8(X)
903 
904 #else /* !defined(SQLITE_UTF8) */
905 /*
906 ** For iso8859 encoding, the next character is just the next byte.
907 */
908 #define sqliteNextChar(X)  (++(X));
909 #define sqliteCharVal(X)   ((int)*(X))
910 
911 #endif /* defined(SQLITE_UTF8) */
912 
913 
914 #if 1  /* We are now always UTF-8 */
915 /*
916 ** Convert the UTF-8 character to which z points into a 31-bit
917 ** UCS character.  This only works right if z points to a well-formed
918 ** UTF-8 string.
919 */
920 int sqlite3ReadUtf8(const unsigned char *z){
921   int c;
922   static const int initVal[] = {
923       0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,
924      15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25,  26,  27,  28,  29,
925      30,  31,  32,  33,  34,  35,  36,  37,  38,  39,  40,  41,  42,  43,  44,
926      45,  46,  47,  48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,  59,
927      60,  61,  62,  63,  64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,
928      75,  76,  77,  78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,
929      90,  91,  92,  93,  94,  95,  96,  97,  98,  99, 100, 101, 102, 103, 104,
930     105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
931     120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
932     135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
933     150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
934     165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
935     180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,   0,   1,   2,
936       3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,  15,  16,  17,
937      18,  19,  20,  21,  22,  23,  24,  25,  26,  27,  28,  29,  30,  31,   0,
938       1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,  15,
939       0,   1,   2,   3,   4,   5,   6,   7,   0,   1,   2,   3,   0,   1, 254,
940     255,
941   };
942   c = initVal[*(z++)];
943   while( (0xc0&*z)==0x80 ){
944     c = (c<<6) | (0x3f&*(z++));
945   }
946   return c;
947 }
948 #endif
949 
950 /*
951 ** Compare two UTF-8 strings for equality where the first string can
952 ** potentially be a "glob" expression.  Return true (1) if they
953 ** are the same and false (0) if they are different.
954 **
955 ** Globbing rules:
956 **
957 **      '*'       Matches any sequence of zero or more characters.
958 **
959 **      '?'       Matches exactly one character.
960 **
961 **     [...]      Matches one character from the enclosed list of
962 **                characters.
963 **
964 **     [^...]     Matches one character not in the enclosed list.
965 **
966 ** With the [...] and [^...] matching, a ']' character can be included
967 ** in the list by making it the first character after '[' or '^'.  A
968 ** range of characters can be specified using '-'.  Example:
969 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
970 ** it the last character in the list.
971 **
972 ** This routine is usually quick, but can be N**2 in the worst case.
973 **
974 ** Hints: to match '*' or '?', put them in "[]".  Like this:
975 **
976 **         abc[*]xyz        Matches "abc*xyz" only
977 */
978 int
979 sqlite3GlobCompare(const unsigned char *zPattern, const unsigned char *zString){
980   register int c;
981   int invert;
982   int seen;
983   int c2;
984 
985   while( (c = *zPattern)!=0 ){
986     switch( c ){
987       case '*':
988         while( (c=zPattern[1]) == '*' || c == '?' ){
989           if( c=='?' ){
990             if( *zString==0 ) return 0;
991             sqliteNextChar(zString);
992           }
993           zPattern++;
994         }
995         if( c==0 ) return 1;
996         if( c=='[' ){
997           while( *zString && sqlite3GlobCompare(&zPattern[1],zString)==0 ){
998             sqliteNextChar(zString);
999           }
1000           return *zString!=0;
1001         }else{
1002           while( (c2 = *zString)!=0 ){
1003             while( c2 != 0 && c2 != c ){ c2 = *++zString; }
1004             if( c2==0 ) return 0;
1005             if( sqlite3GlobCompare(&zPattern[1],zString) ) return 1;
1006             sqliteNextChar(zString);
1007           }
1008           return 0;
1009         }
1010       case '?': {
1011         if( *zString==0 ) return 0;
1012         sqliteNextChar(zString);
1013         zPattern++;
1014         break;
1015       }
1016       case '[': {
1017         int prior_c = 0;
1018         seen = 0;
1019         invert = 0;
1020         c = sqliteCharVal(zString);
1021         if( c==0 ) return 0;
1022         c2 = *++zPattern;
1023         if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
1024         if( c2==']' ){
1025           if( c==']' ) seen = 1;
1026           c2 = *++zPattern;
1027         }
1028         while( (c2 = sqliteCharVal(zPattern))!=0 && c2!=']' ){
1029           if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
1030             zPattern++;
1031             c2 = sqliteCharVal(zPattern);
1032             if( c>=prior_c && c<=c2 ) seen = 1;
1033             prior_c = 0;
1034           }else if( c==c2 ){
1035             seen = 1;
1036             prior_c = c2;
1037           }else{
1038             prior_c = c2;
1039           }
1040           sqliteNextChar(zPattern);
1041         }
1042         if( c2==0 || (seen ^ invert)==0 ) return 0;
1043         sqliteNextChar(zString);
1044         zPattern++;
1045         break;
1046       }
1047       default: {
1048         if( c != *zString ) return 0;
1049         zPattern++;
1050         zString++;
1051         break;
1052       }
1053     }
1054   }
1055   return *zString==0;
1056 }
1057 
1058 /*
1059 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
1060 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
1061 ** when this routine is called.
1062 **
1063 ** This routine is a attempt to detect if two threads use the
1064 ** same sqlite* pointer at the same time.  There is a race
1065 ** condition so it is possible that the error is not detected.
1066 ** But usually the problem will be seen.  The result will be an
1067 ** error which can be used to debug the application that is
1068 ** using SQLite incorrectly.
1069 **
1070 ** Ticket #202:  If db->magic is not a valid open value, take care not
1071 ** to modify the db structure at all.  It could be that db is a stale
1072 ** pointer.  In other words, it could be that there has been a prior
1073 ** call to sqlite3_close(db) and db has been deallocated.  And we do
1074 ** not want to write into deallocated memory.
1075 */
1076 int sqlite3SafetyOn(sqlite *db){
1077   if( db->magic==SQLITE_MAGIC_OPEN ){
1078     db->magic = SQLITE_MAGIC_BUSY;
1079     return 0;
1080   }else if( db->magic==SQLITE_MAGIC_BUSY || db->magic==SQLITE_MAGIC_ERROR
1081              || db->want_to_close ){
1082     db->magic = SQLITE_MAGIC_ERROR;
1083     db->flags |= SQLITE_Interrupt;
1084   }
1085   return 1;
1086 }
1087 
1088 /*
1089 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
1090 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
1091 ** when this routine is called.
1092 */
1093 int sqlite3SafetyOff(sqlite *db){
1094   if( db->magic==SQLITE_MAGIC_BUSY ){
1095     db->magic = SQLITE_MAGIC_OPEN;
1096     return 0;
1097   }else if( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ERROR
1098              || db->want_to_close ){
1099     db->magic = SQLITE_MAGIC_ERROR;
1100     db->flags |= SQLITE_Interrupt;
1101   }
1102   return 1;
1103 }
1104 
1105 /*
1106 ** Check to make sure we are not currently executing an sqlite3_exec().
1107 ** If we are currently in an sqlite3_exec(), return true and set
1108 ** sqlite.magic to SQLITE_MAGIC_ERROR.  This will cause a complete
1109 ** shutdown of the database.
1110 **
1111 ** This routine is used to try to detect when API routines are called
1112 ** at the wrong time or in the wrong sequence.
1113 */
1114 int sqlite3SafetyCheck(sqlite *db){
1115   if( db->pVdbe!=0 ){
1116     db->magic = SQLITE_MAGIC_ERROR;
1117     return 1;
1118   }
1119   return 0;
1120 }
1121 
1122 /*
1123 ** The variable-length integer encoding is as follows:
1124 **
1125 ** KEY:
1126 **         A = 0xxxxxxx    7 bits of data and one flag bit
1127 **         B = 1xxxxxxx    7 bits of data and one flag bit
1128 **         C = xxxxxxxx    8 bits of data
1129 **
1130 **  7 bits - A
1131 ** 14 bits - BA
1132 ** 21 bits - BBA
1133 ** 28 bits - BBBA
1134 ** 35 bits - BBBBA
1135 ** 42 bits - BBBBBA
1136 ** 49 bits - BBBBBBA
1137 ** 56 bits - BBBBBBBA
1138 ** 64 bits - BBBBBBBBC
1139 */
1140 
1141 /*
1142 ** Write a 64-bit variable-length integer to memory starting at p[0].
1143 ** The length of data write will be between 1 and 9 bytes.  The number
1144 ** of bytes written is returned.
1145 **
1146 ** A variable-length integer consists of the lower 7 bits of each byte
1147 ** for all bytes that have the 8th bit set and one byte with the 8th
1148 ** bit clear.  Except, if we get to the 9th byte, it stores the full
1149 ** 8 bits and is the last byte.
1150 */
1151 int sqlite3PutVarint(unsigned char *p, u64 v){
1152   int i, j, n;
1153   u8 buf[10];
1154   if( v & 0xff00000000000000 ){
1155     p[8] = v;
1156     v >>= 8;
1157     for(i=7; i>=0; i--){
1158       p[i] = (v & 0x7f) | 0x80;
1159       v >>= 7;
1160     }
1161     return 9;
1162   }
1163   n = 0;
1164   do{
1165     buf[n++] = (v & 0x7f) | 0x80;
1166     v >>= 7;
1167   }while( v!=0 );
1168   buf[0] &= 0x7f;
1169   assert( n<=9 );
1170   for(i=0, j=n-1; j>=0; j--, i++){
1171     p[i] = buf[j];
1172   }
1173   return n;
1174 }
1175 
1176 /*
1177 ** Read a 64-bit variable-length integer from memory starting at p[0].
1178 ** Return the number of bytes read.  The value is stored in *v.
1179 */
1180 int sqlite3GetVarint(const unsigned char *p, u64 *v){
1181   u32 x;
1182   u64 x64;
1183   int n;
1184   unsigned char c;
1185   if( ((c = p[0]) & 0x80)==0 ){
1186     *v = c;
1187     return 1;
1188   }
1189   x = c & 0x7f;
1190   if( ((c = p[1]) & 0x80)==0 ){
1191     *v = (x<<7) | c;
1192     return 2;
1193   }
1194   x = (x<<7) | (c&0x7f);
1195   if( ((c = p[2]) & 0x80)==0 ){
1196     *v = (x<<7) | c;
1197     return 3;
1198   }
1199   x = (x<<7) | (c&0x7f);
1200   if( ((c = p[3]) & 0x80)==0 ){
1201     *v = (x<<7) | c;
1202     return 4;
1203   }
1204   x64 = (x<<7) | (c&0x7f);
1205   n = 4;
1206   do{
1207     c = p[n++];
1208     if( n==9 ){
1209       x64 = (x64<<8) | c;
1210       break;
1211     }
1212     x64 = (x64<<7) | (c&0x7f);
1213   }while( (c & 0x80)!=0 );
1214   *v = x64;
1215   return n;
1216 }
1217 
1218 /*
1219 ** Read a 32-bit variable-length integer from memory starting at p[0].
1220 ** Return the number of bytes read.  The value is stored in *v.
1221 */
1222 int sqlite3GetVarint32(const unsigned char *p, u32 *v){
1223   u32 x;
1224   int n;
1225   unsigned char c;
1226   if( ((c = p[0]) & 0x80)==0 ){
1227     *v = c;
1228     return 1;
1229   }
1230   x = c & 0x7f;
1231   if( ((c = p[1]) & 0x80)==0 ){
1232     *v = (x<<7) | c;
1233     return 2;
1234   }
1235   x = (x<<7) | (c&0x7f);
1236   if( ((c = p[2]) & 0x80)==0 ){
1237     *v = (x<<7) | c;
1238     return 3;
1239   }
1240   x = (x<<7) | (c&0x7f);
1241   if( ((c = p[3]) & 0x80)==0 ){
1242     *v = (x<<7) | c;
1243     return 4;
1244   }
1245   n = 4;
1246   do{
1247     x = (x<<7) | ((c = p[n++])&0x7f);
1248   }while( (c & 0x80)!=0 && n<9 );
1249   *v = x;
1250   return n;
1251 }
1252 
1253 /*
1254 ** Return the number of bytes that will be needed to store the given
1255 ** 64-bit integer.
1256 */
1257 int sqlite3VarintLen(u64 v){
1258   int i = 0;
1259   do{
1260     i++;
1261     v >>= 7;
1262   }while( v!=0 && i<9 );
1263   return i;
1264 }
1265 
1266 void *sqlite3HexToBlob(const char *z){
1267   char *zBlob;
1268   int i;
1269   int n = strlen(z);
1270   if( n%2 ) return 0;
1271 
1272   zBlob = (char *)sqliteMalloc(n/2);
1273 
1274   for(i=0; i<n; i++){
1275     u8 c;
1276 
1277     if     ( z[i]>47 && z[i]<58 ) c = (z[i]-48)<<4;
1278     else if( z[i]>64 && z[i]<71 ) c = (z[i]-55)<<4;
1279     else if( z[i]>96 && z[i]<103 ) c = (z[i]-87)<<4;
1280     else {
1281       sqliteFree(zBlob);
1282       return 0;
1283     }
1284     i++;
1285     if     ( z[i]>47 && z[i]<58 ) c += (z[i]-48);
1286     else if( z[i]>64 && z[i]<71 ) c += (z[i]-55);
1287     else if( z[i]>96 && z[i]<103 ) c += (z[i]-87);
1288     else {
1289       sqliteFree(zBlob);
1290       return 0;
1291     }
1292 
1293     zBlob[i/2] = c;
1294   }
1295   return zBlob;
1296 }
1297