xref: /sqlite-3.40.0/src/util.c (revision 2b5fbb28)
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 */
18 #include "sqliteInt.h"
19 #include <stdarg.h>
20 #ifndef SQLITE_OMIT_FLOATING_POINT
21 #include <math.h>
22 #endif
23 
24 /*
25 ** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
26 ** or to bypass normal error detection during testing in order to let
27 ** execute proceed futher downstream.
28 **
29 ** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0).  The
30 ** sqlite3FaultSim() function only returns non-zero during testing.
31 **
32 ** During testing, if the test harness has set a fault-sim callback using
33 ** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then
34 ** each call to sqlite3FaultSim() is relayed to that application-supplied
35 ** callback and the integer return value form the application-supplied
36 ** callback is returned by sqlite3FaultSim().
37 **
38 ** The integer argument to sqlite3FaultSim() is a code to identify which
39 ** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()
40 ** should have a unique code.  To prevent legacy testing applications from
41 ** breaking, the codes should not be changed or reused.
42 */
43 #ifndef SQLITE_UNTESTABLE
44 int sqlite3FaultSim(int iTest){
45   int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
46   return xCallback ? xCallback(iTest) : SQLITE_OK;
47 }
48 #endif
49 
50 #ifndef SQLITE_OMIT_FLOATING_POINT
51 /*
52 ** Return true if the floating point value is Not a Number (NaN).
53 **
54 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
55 ** Otherwise, we have our own implementation that works on most systems.
56 */
57 int sqlite3IsNaN(double x){
58   int rc;   /* The value return */
59 #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
60   u64 y;
61   memcpy(&y,&x,sizeof(y));
62   rc = IsNaN(y);
63 #else
64   rc = isnan(x);
65 #endif /* HAVE_ISNAN */
66   testcase( rc );
67   return rc;
68 }
69 #endif /* SQLITE_OMIT_FLOATING_POINT */
70 
71 /*
72 ** Compute a string length that is limited to what can be stored in
73 ** lower 30 bits of a 32-bit signed integer.
74 **
75 ** The value returned will never be negative.  Nor will it ever be greater
76 ** than the actual length of the string.  For very long strings (greater
77 ** than 1GiB) the value returned might be less than the true string length.
78 */
79 int sqlite3Strlen30(const char *z){
80   if( z==0 ) return 0;
81   return 0x3fffffff & (int)strlen(z);
82 }
83 
84 /*
85 ** Return the declared type of a column.  Or return zDflt if the column
86 ** has no declared type.
87 **
88 ** The column type is an extra string stored after the zero-terminator on
89 ** the column name if and only if the COLFLAG_HASTYPE flag is set.
90 */
91 char *sqlite3ColumnType(Column *pCol, char *zDflt){
92   if( pCol->colFlags & COLFLAG_HASTYPE ){
93     return pCol->zCnName + strlen(pCol->zCnName) + 1;
94   }else if( pCol->eCType ){
95     assert( pCol->eCType<=SQLITE_N_STDTYPE );
96     return (char*)sqlite3StdType[pCol->eCType-1];
97   }else{
98     return zDflt;
99   }
100 }
101 
102 /*
103 ** Helper function for sqlite3Error() - called rarely.  Broken out into
104 ** a separate routine to avoid unnecessary register saves on entry to
105 ** sqlite3Error().
106 */
107 static SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){
108   if( db->pErr ) sqlite3ValueSetNull(db->pErr);
109   sqlite3SystemError(db, err_code);
110 }
111 
112 /*
113 ** Set the current error code to err_code and clear any prior error message.
114 ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
115 ** that would be appropriate.
116 */
117 void sqlite3Error(sqlite3 *db, int err_code){
118   assert( db!=0 );
119   db->errCode = err_code;
120   if( err_code || db->pErr ){
121     sqlite3ErrorFinish(db, err_code);
122   }else{
123     db->errByteOffset = -1;
124   }
125 }
126 
127 /*
128 ** The equivalent of sqlite3Error(db, SQLITE_OK).  Clear the error state
129 ** and error message.
130 */
131 void sqlite3ErrorClear(sqlite3 *db){
132   assert( db!=0 );
133   db->errCode = SQLITE_OK;
134   db->errByteOffset = -1;
135   if( db->pErr ) sqlite3ValueSetNull(db->pErr);
136 }
137 
138 /*
139 ** Load the sqlite3.iSysErrno field if that is an appropriate thing
140 ** to do based on the SQLite error code in rc.
141 */
142 void sqlite3SystemError(sqlite3 *db, int rc){
143   if( rc==SQLITE_IOERR_NOMEM ) return;
144   rc &= 0xff;
145   if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
146     db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
147   }
148 }
149 
150 /*
151 ** Set the most recent error code and error string for the sqlite
152 ** handle "db". The error code is set to "err_code".
153 **
154 ** If it is not NULL, string zFormat specifies the format of the
155 ** error string.  zFormat and any string tokens that follow it are
156 ** assumed to be encoded in UTF-8.
157 **
158 ** To clear the most recent error for sqlite handle "db", sqlite3Error
159 ** should be called with err_code set to SQLITE_OK and zFormat set
160 ** to NULL.
161 */
162 void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
163   assert( db!=0 );
164   db->errCode = err_code;
165   sqlite3SystemError(db, err_code);
166   if( zFormat==0 ){
167     sqlite3Error(db, err_code);
168   }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
169     char *z;
170     va_list ap;
171     va_start(ap, zFormat);
172     z = sqlite3VMPrintf(db, zFormat, ap);
173     va_end(ap);
174     sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
175   }
176 }
177 
178 /*
179 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
180 **
181 ** This function should be used to report any error that occurs while
182 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
183 ** last thing the sqlite3_prepare() function does is copy the error
184 ** stored by this function into the database handle using sqlite3Error().
185 ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
186 ** during statement execution (sqlite3_step() etc.).
187 */
188 void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
189   char *zMsg;
190   va_list ap;
191   sqlite3 *db = pParse->db;
192   db->errByteOffset = -2;
193   va_start(ap, zFormat);
194   zMsg = sqlite3VMPrintf(db, zFormat, ap);
195   va_end(ap);
196   if( db->errByteOffset<-1 ) db->errByteOffset = -1;
197   if( db->suppressErr ){
198     sqlite3DbFree(db, zMsg);
199   }else{
200     pParse->nErr++;
201     sqlite3DbFree(db, pParse->zErrMsg);
202     pParse->zErrMsg = zMsg;
203     pParse->rc = SQLITE_ERROR;
204     pParse->pWith = 0;
205   }
206 }
207 
208 /*
209 ** If database connection db is currently parsing SQL, then transfer
210 ** error code errCode to that parser if the parser has not already
211 ** encountered some other kind of error.
212 */
213 int sqlite3ErrorToParser(sqlite3 *db, int errCode){
214   Parse *pParse;
215   if( db==0 || (pParse = db->pParse)==0 ) return errCode;
216   pParse->rc = errCode;
217   pParse->nErr++;
218   return errCode;
219 }
220 
221 /*
222 ** Convert an SQL-style quoted string into a normal string by removing
223 ** the quote characters.  The conversion is done in-place.  If the
224 ** input does not begin with a quote character, then this routine
225 ** is a no-op.
226 **
227 ** The input string must be zero-terminated.  A new zero-terminator
228 ** is added to the dequoted string.
229 **
230 ** The return value is -1 if no dequoting occurs or the length of the
231 ** dequoted string, exclusive of the zero terminator, if dequoting does
232 ** occur.
233 **
234 ** 2002-02-14: This routine is extended to remove MS-Access style
235 ** brackets from around identifiers.  For example:  "[a-b-c]" becomes
236 ** "a-b-c".
237 */
238 void sqlite3Dequote(char *z){
239   char quote;
240   int i, j;
241   if( z==0 ) return;
242   quote = z[0];
243   if( !sqlite3Isquote(quote) ) return;
244   if( quote=='[' ) quote = ']';
245   for(i=1, j=0;; i++){
246     assert( z[i] );
247     if( z[i]==quote ){
248       if( z[i+1]==quote ){
249         z[j++] = quote;
250         i++;
251       }else{
252         break;
253       }
254     }else{
255       z[j++] = z[i];
256     }
257   }
258   z[j] = 0;
259 }
260 void sqlite3DequoteExpr(Expr *p){
261   assert( !ExprHasProperty(p, EP_IntValue) );
262   assert( sqlite3Isquote(p->u.zToken[0]) );
263   p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
264   sqlite3Dequote(p->u.zToken);
265 }
266 
267 /*
268 ** If the input token p is quoted, try to adjust the token to remove
269 ** the quotes.  This is not always possible:
270 **
271 **     "abc"     ->   abc
272 **     "ab""cd"  ->   (not possible because of the interior "")
273 **
274 ** Remove the quotes if possible.  This is a optimization.  The overall
275 ** system should still return the correct answer even if this routine
276 ** is always a no-op.
277 */
278 void sqlite3DequoteToken(Token *p){
279   unsigned int i;
280   if( p->n<2 ) return;
281   if( !sqlite3Isquote(p->z[0]) ) return;
282   for(i=1; i<p->n-1; i++){
283     if( sqlite3Isquote(p->z[i]) ) return;
284   }
285   p->n -= 2;
286   p->z++;
287 }
288 
289 /*
290 ** Generate a Token object from a string
291 */
292 void sqlite3TokenInit(Token *p, char *z){
293   p->z = z;
294   p->n = sqlite3Strlen30(z);
295 }
296 
297 /* Convenient short-hand */
298 #define UpperToLower sqlite3UpperToLower
299 
300 /*
301 ** Some systems have stricmp().  Others have strcasecmp().  Because
302 ** there is no consistency, we will define our own.
303 **
304 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
305 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
306 ** the contents of two buffers containing UTF-8 strings in a
307 ** case-independent fashion, using the same definition of "case
308 ** independence" that SQLite uses internally when comparing identifiers.
309 */
310 int sqlite3_stricmp(const char *zLeft, const char *zRight){
311   if( zLeft==0 ){
312     return zRight ? -1 : 0;
313   }else if( zRight==0 ){
314     return 1;
315   }
316   return sqlite3StrICmp(zLeft, zRight);
317 }
318 int sqlite3StrICmp(const char *zLeft, const char *zRight){
319   unsigned char *a, *b;
320   int c, x;
321   a = (unsigned char *)zLeft;
322   b = (unsigned char *)zRight;
323   for(;;){
324     c = *a;
325     x = *b;
326     if( c==x ){
327       if( c==0 ) break;
328     }else{
329       c = (int)UpperToLower[c] - (int)UpperToLower[x];
330       if( c ) break;
331     }
332     a++;
333     b++;
334   }
335   return c;
336 }
337 int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
338   register unsigned char *a, *b;
339   if( zLeft==0 ){
340     return zRight ? -1 : 0;
341   }else if( zRight==0 ){
342     return 1;
343   }
344   a = (unsigned char *)zLeft;
345   b = (unsigned char *)zRight;
346   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
347   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
348 }
349 
350 /*
351 ** Compute an 8-bit hash on a string that is insensitive to case differences
352 */
353 u8 sqlite3StrIHash(const char *z){
354   u8 h = 0;
355   if( z==0 ) return 0;
356   while( z[0] ){
357     h += UpperToLower[(unsigned char)z[0]];
358     z++;
359   }
360   return h;
361 }
362 
363 /*
364 ** Compute 10 to the E-th power.  Examples:  E==1 results in 10.
365 ** E==2 results in 100.  E==50 results in 1.0e50.
366 **
367 ** This routine only works for values of E between 1 and 341.
368 */
369 static LONGDOUBLE_TYPE sqlite3Pow10(int E){
370 #if defined(_MSC_VER)
371   static const LONGDOUBLE_TYPE x[] = {
372     1.0e+001L,
373     1.0e+002L,
374     1.0e+004L,
375     1.0e+008L,
376     1.0e+016L,
377     1.0e+032L,
378     1.0e+064L,
379     1.0e+128L,
380     1.0e+256L
381   };
382   LONGDOUBLE_TYPE r = 1.0;
383   int i;
384   assert( E>=0 && E<=307 );
385   for(i=0; E!=0; i++, E >>=1){
386     if( E & 1 ) r *= x[i];
387   }
388   return r;
389 #else
390   LONGDOUBLE_TYPE x = 10.0;
391   LONGDOUBLE_TYPE r = 1.0;
392   while(1){
393     if( E & 1 ) r *= x;
394     E >>= 1;
395     if( E==0 ) break;
396     x *= x;
397   }
398   return r;
399 #endif
400 }
401 
402 /*
403 ** The string z[] is an text representation of a real number.
404 ** Convert this string to a double and write it into *pResult.
405 **
406 ** The string z[] is length bytes in length (bytes, not characters) and
407 ** uses the encoding enc.  The string is not necessarily zero-terminated.
408 **
409 ** Return TRUE if the result is a valid real number (or integer) and FALSE
410 ** if the string is empty or contains extraneous text.  More specifically
411 ** return
412 **      1          =>  The input string is a pure integer
413 **      2 or more  =>  The input has a decimal point or eNNN clause
414 **      0 or less  =>  The input string is not a valid number
415 **     -1          =>  Not a valid number, but has a valid prefix which
416 **                     includes a decimal point and/or an eNNN clause
417 **
418 ** Valid numbers are in one of these formats:
419 **
420 **    [+-]digits[E[+-]digits]
421 **    [+-]digits.[digits][E[+-]digits]
422 **    [+-].digits[E[+-]digits]
423 **
424 ** Leading and trailing whitespace is ignored for the purpose of determining
425 ** validity.
426 **
427 ** If some prefix of the input string is a valid number, this routine
428 ** returns FALSE but it still converts the prefix and writes the result
429 ** into *pResult.
430 */
431 #if defined(_MSC_VER)
432 #pragma warning(disable : 4756)
433 #endif
434 int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
435 #ifndef SQLITE_OMIT_FLOATING_POINT
436   int incr;
437   const char *zEnd;
438   /* sign * significand * (10 ^ (esign * exponent)) */
439   int sign = 1;    /* sign of significand */
440   i64 s = 0;       /* significand */
441   int d = 0;       /* adjust exponent for shifting decimal point */
442   int esign = 1;   /* sign of exponent */
443   int e = 0;       /* exponent */
444   int eValid = 1;  /* True exponent is either not used or is well-formed */
445   double result;
446   int nDigit = 0;  /* Number of digits processed */
447   int eType = 1;   /* 1: pure integer,  2+: fractional  -1 or less: bad UTF16 */
448 
449   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
450   *pResult = 0.0;   /* Default return value, in case of an error */
451   if( length==0 ) return 0;
452 
453   if( enc==SQLITE_UTF8 ){
454     incr = 1;
455     zEnd = z + length;
456   }else{
457     int i;
458     incr = 2;
459     length &= ~1;
460     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
461     testcase( enc==SQLITE_UTF16LE );
462     testcase( enc==SQLITE_UTF16BE );
463     for(i=3-enc; i<length && z[i]==0; i+=2){}
464     if( i<length ) eType = -100;
465     zEnd = &z[i^1];
466     z += (enc&1);
467   }
468 
469   /* skip leading spaces */
470   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
471   if( z>=zEnd ) return 0;
472 
473   /* get sign of significand */
474   if( *z=='-' ){
475     sign = -1;
476     z+=incr;
477   }else if( *z=='+' ){
478     z+=incr;
479   }
480 
481   /* copy max significant digits to significand */
482   while( z<zEnd && sqlite3Isdigit(*z) ){
483     s = s*10 + (*z - '0');
484     z+=incr; nDigit++;
485     if( s>=((LARGEST_INT64-9)/10) ){
486       /* skip non-significant significand digits
487       ** (increase exponent by d to shift decimal left) */
488       while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; d++; }
489     }
490   }
491   if( z>=zEnd ) goto do_atof_calc;
492 
493   /* if decimal point is present */
494   if( *z=='.' ){
495     z+=incr;
496     eType++;
497     /* copy digits from after decimal to significand
498     ** (decrease exponent by d to shift decimal right) */
499     while( z<zEnd && sqlite3Isdigit(*z) ){
500       if( s<((LARGEST_INT64-9)/10) ){
501         s = s*10 + (*z - '0');
502         d--;
503         nDigit++;
504       }
505       z+=incr;
506     }
507   }
508   if( z>=zEnd ) goto do_atof_calc;
509 
510   /* if exponent is present */
511   if( *z=='e' || *z=='E' ){
512     z+=incr;
513     eValid = 0;
514     eType++;
515 
516     /* This branch is needed to avoid a (harmless) buffer overread.  The
517     ** special comment alerts the mutation tester that the correct answer
518     ** is obtained even if the branch is omitted */
519     if( z>=zEnd ) goto do_atof_calc;              /*PREVENTS-HARMLESS-OVERREAD*/
520 
521     /* get sign of exponent */
522     if( *z=='-' ){
523       esign = -1;
524       z+=incr;
525     }else if( *z=='+' ){
526       z+=incr;
527     }
528     /* copy digits to exponent */
529     while( z<zEnd && sqlite3Isdigit(*z) ){
530       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
531       z+=incr;
532       eValid = 1;
533     }
534   }
535 
536   /* skip trailing spaces */
537   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
538 
539 do_atof_calc:
540   /* adjust exponent by d, and update sign */
541   e = (e*esign) + d;
542   if( e<0 ) {
543     esign = -1;
544     e *= -1;
545   } else {
546     esign = 1;
547   }
548 
549   if( s==0 ) {
550     /* In the IEEE 754 standard, zero is signed. */
551     result = sign<0 ? -(double)0 : (double)0;
552   } else {
553     /* Attempt to reduce exponent.
554     **
555     ** Branches that are not required for the correct answer but which only
556     ** help to obtain the correct answer faster are marked with special
557     ** comments, as a hint to the mutation tester.
558     */
559     while( e>0 ){                                       /*OPTIMIZATION-IF-TRUE*/
560       if( esign>0 ){
561         if( s>=(LARGEST_INT64/10) ) break;             /*OPTIMIZATION-IF-FALSE*/
562         s *= 10;
563       }else{
564         if( s%10!=0 ) break;                           /*OPTIMIZATION-IF-FALSE*/
565         s /= 10;
566       }
567       e--;
568     }
569 
570     /* adjust the sign of significand */
571     s = sign<0 ? -s : s;
572 
573     if( e==0 ){                                         /*OPTIMIZATION-IF-TRUE*/
574       result = (double)s;
575     }else{
576       /* attempt to handle extremely small/large numbers better */
577       if( e>307 ){                                      /*OPTIMIZATION-IF-TRUE*/
578         if( e<342 ){                                    /*OPTIMIZATION-IF-TRUE*/
579           LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
580           if( esign<0 ){
581             result = s / scale;
582             result /= 1.0e+308;
583           }else{
584             result = s * scale;
585             result *= 1.0e+308;
586           }
587         }else{ assert( e>=342 );
588           if( esign<0 ){
589             result = 0.0*s;
590           }else{
591 #ifdef INFINITY
592             result = INFINITY*s;
593 #else
594             result = 1e308*1e308*s;  /* Infinity */
595 #endif
596           }
597         }
598       }else{
599         LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
600         if( esign<0 ){
601           result = s / scale;
602         }else{
603           result = s * scale;
604         }
605       }
606     }
607   }
608 
609   /* store the result */
610   *pResult = result;
611 
612   /* return true if number and no extra non-whitespace chracters after */
613   if( z==zEnd && nDigit>0 && eValid && eType>0 ){
614     return eType;
615   }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){
616     return -1;
617   }else{
618     return 0;
619   }
620 #else
621   return !sqlite3Atoi64(z, pResult, length, enc);
622 #endif /* SQLITE_OMIT_FLOATING_POINT */
623 }
624 #if defined(_MSC_VER)
625 #pragma warning(default : 4756)
626 #endif
627 
628 /*
629 ** Render an signed 64-bit integer as text.  Store the result in zOut[].
630 **
631 ** The caller must ensure that zOut[] is at least 21 bytes in size.
632 */
633 void sqlite3Int64ToText(i64 v, char *zOut){
634   int i;
635   u64 x;
636   char zTemp[22];
637   if( v<0 ){
638     x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v;
639   }else{
640     x = v;
641   }
642   i = sizeof(zTemp)-2;
643   zTemp[sizeof(zTemp)-1] = 0;
644   do{
645     zTemp[i--] = (x%10) + '0';
646     x = x/10;
647   }while( x );
648   if( v<0 ) zTemp[i--] = '-';
649   memcpy(zOut, &zTemp[i+1], sizeof(zTemp)-1-i);
650 }
651 
652 /*
653 ** Compare the 19-character string zNum against the text representation
654 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
655 ** if zNum is less than, equal to, or greater than the string.
656 ** Note that zNum must contain exactly 19 characters.
657 **
658 ** Unlike memcmp() this routine is guaranteed to return the difference
659 ** in the values of the last digit if the only difference is in the
660 ** last digit.  So, for example,
661 **
662 **      compare2pow63("9223372036854775800", 1)
663 **
664 ** will return -8.
665 */
666 static int compare2pow63(const char *zNum, int incr){
667   int c = 0;
668   int i;
669                     /* 012345678901234567 */
670   const char *pow63 = "922337203685477580";
671   for(i=0; c==0 && i<18; i++){
672     c = (zNum[i*incr]-pow63[i])*10;
673   }
674   if( c==0 ){
675     c = zNum[18*incr] - '8';
676     testcase( c==(-1) );
677     testcase( c==0 );
678     testcase( c==(+1) );
679   }
680   return c;
681 }
682 
683 /*
684 ** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
685 ** routine does *not* accept hexadecimal notation.
686 **
687 ** Returns:
688 **
689 **    -1    Not even a prefix of the input text looks like an integer
690 **     0    Successful transformation.  Fits in a 64-bit signed integer.
691 **     1    Excess non-space text after the integer value
692 **     2    Integer too large for a 64-bit signed integer or is malformed
693 **     3    Special case of 9223372036854775808
694 **
695 ** length is the number of bytes in the string (bytes, not characters).
696 ** The string is not necessarily zero-terminated.  The encoding is
697 ** given by enc.
698 */
699 int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
700   int incr;
701   u64 u = 0;
702   int neg = 0; /* assume positive */
703   int i;
704   int c = 0;
705   int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
706   int rc;          /* Baseline return code */
707   const char *zStart;
708   const char *zEnd = zNum + length;
709   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
710   if( enc==SQLITE_UTF8 ){
711     incr = 1;
712   }else{
713     incr = 2;
714     length &= ~1;
715     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
716     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
717     nonNum = i<length;
718     zEnd = &zNum[i^1];
719     zNum += (enc&1);
720   }
721   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
722   if( zNum<zEnd ){
723     if( *zNum=='-' ){
724       neg = 1;
725       zNum+=incr;
726     }else if( *zNum=='+' ){
727       zNum+=incr;
728     }
729   }
730   zStart = zNum;
731   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
732   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
733     u = u*10 + c - '0';
734   }
735   testcase( i==18*incr );
736   testcase( i==19*incr );
737   testcase( i==20*incr );
738   if( u>LARGEST_INT64 ){
739     /* This test and assignment is needed only to suppress UB warnings
740     ** from clang and -fsanitize=undefined.  This test and assignment make
741     ** the code a little larger and slower, and no harm comes from omitting
742     ** them, but we must appaise the undefined-behavior pharisees. */
743     *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
744   }else if( neg ){
745     *pNum = -(i64)u;
746   }else{
747     *pNum = (i64)u;
748   }
749   rc = 0;
750   if( i==0 && zStart==zNum ){    /* No digits */
751     rc = -1;
752   }else if( nonNum ){            /* UTF16 with high-order bytes non-zero */
753     rc = 1;
754   }else if( &zNum[i]<zEnd ){     /* Extra bytes at the end */
755     int jj = i;
756     do{
757       if( !sqlite3Isspace(zNum[jj]) ){
758         rc = 1;          /* Extra non-space text after the integer */
759         break;
760       }
761       jj += incr;
762     }while( &zNum[jj]<zEnd );
763   }
764   if( i<19*incr ){
765     /* Less than 19 digits, so we know that it fits in 64 bits */
766     assert( u<=LARGEST_INT64 );
767     return rc;
768   }else{
769     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
770     c = i>19*incr ? 1 : compare2pow63(zNum, incr);
771     if( c<0 ){
772       /* zNum is less than 9223372036854775808 so it fits */
773       assert( u<=LARGEST_INT64 );
774       return rc;
775     }else{
776       *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
777       if( c>0 ){
778         /* zNum is greater than 9223372036854775808 so it overflows */
779         return 2;
780       }else{
781         /* zNum is exactly 9223372036854775808.  Fits if negative.  The
782         ** special case 2 overflow if positive */
783         assert( u-1==LARGEST_INT64 );
784         return neg ? rc : 3;
785       }
786     }
787   }
788 }
789 
790 /*
791 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
792 ** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
793 ** whereas sqlite3Atoi64() does not.
794 **
795 ** Returns:
796 **
797 **     0    Successful transformation.  Fits in a 64-bit signed integer.
798 **     1    Excess text after the integer value
799 **     2    Integer too large for a 64-bit signed integer or is malformed
800 **     3    Special case of 9223372036854775808
801 */
802 int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
803 #ifndef SQLITE_OMIT_HEX_INTEGER
804   if( z[0]=='0'
805    && (z[1]=='x' || z[1]=='X')
806   ){
807     u64 u = 0;
808     int i, k;
809     for(i=2; z[i]=='0'; i++){}
810     for(k=i; sqlite3Isxdigit(z[k]); k++){
811       u = u*16 + sqlite3HexToInt(z[k]);
812     }
813     memcpy(pOut, &u, 8);
814     return (z[k]==0 && k-i<=16) ? 0 : 2;
815   }else
816 #endif /* SQLITE_OMIT_HEX_INTEGER */
817   {
818     return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
819   }
820 }
821 
822 /*
823 ** If zNum represents an integer that will fit in 32-bits, then set
824 ** *pValue to that integer and return true.  Otherwise return false.
825 **
826 ** This routine accepts both decimal and hexadecimal notation for integers.
827 **
828 ** Any non-numeric characters that following zNum are ignored.
829 ** This is different from sqlite3Atoi64() which requires the
830 ** input number to be zero-terminated.
831 */
832 int sqlite3GetInt32(const char *zNum, int *pValue){
833   sqlite_int64 v = 0;
834   int i, c;
835   int neg = 0;
836   if( zNum[0]=='-' ){
837     neg = 1;
838     zNum++;
839   }else if( zNum[0]=='+' ){
840     zNum++;
841   }
842 #ifndef SQLITE_OMIT_HEX_INTEGER
843   else if( zNum[0]=='0'
844         && (zNum[1]=='x' || zNum[1]=='X')
845         && sqlite3Isxdigit(zNum[2])
846   ){
847     u32 u = 0;
848     zNum += 2;
849     while( zNum[0]=='0' ) zNum++;
850     for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
851       u = u*16 + sqlite3HexToInt(zNum[i]);
852     }
853     if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
854       memcpy(pValue, &u, 4);
855       return 1;
856     }else{
857       return 0;
858     }
859   }
860 #endif
861   if( !sqlite3Isdigit(zNum[0]) ) return 0;
862   while( zNum[0]=='0' ) zNum++;
863   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
864     v = v*10 + c;
865   }
866 
867   /* The longest decimal representation of a 32 bit integer is 10 digits:
868   **
869   **             1234567890
870   **     2^31 -> 2147483648
871   */
872   testcase( i==10 );
873   if( i>10 ){
874     return 0;
875   }
876   testcase( v-neg==2147483647 );
877   if( v-neg>2147483647 ){
878     return 0;
879   }
880   if( neg ){
881     v = -v;
882   }
883   *pValue = (int)v;
884   return 1;
885 }
886 
887 /*
888 ** Return a 32-bit integer value extracted from a string.  If the
889 ** string is not an integer, just return 0.
890 */
891 int sqlite3Atoi(const char *z){
892   int x = 0;
893   sqlite3GetInt32(z, &x);
894   return x;
895 }
896 
897 /*
898 ** Try to convert z into an unsigned 32-bit integer.  Return true on
899 ** success and false if there is an error.
900 **
901 ** Only decimal notation is accepted.
902 */
903 int sqlite3GetUInt32(const char *z, u32 *pI){
904   u64 v = 0;
905   int i;
906   for(i=0; sqlite3Isdigit(z[i]); i++){
907     v = v*10 + z[i] - '0';
908     if( v>4294967296LL ){ *pI = 0; return 0; }
909   }
910   if( i==0 || z[i]!=0 ){ *pI = 0; return 0; }
911   *pI = (u32)v;
912   return 1;
913 }
914 
915 /*
916 ** The variable-length integer encoding is as follows:
917 **
918 ** KEY:
919 **         A = 0xxxxxxx    7 bits of data and one flag bit
920 **         B = 1xxxxxxx    7 bits of data and one flag bit
921 **         C = xxxxxxxx    8 bits of data
922 **
923 **  7 bits - A
924 ** 14 bits - BA
925 ** 21 bits - BBA
926 ** 28 bits - BBBA
927 ** 35 bits - BBBBA
928 ** 42 bits - BBBBBA
929 ** 49 bits - BBBBBBA
930 ** 56 bits - BBBBBBBA
931 ** 64 bits - BBBBBBBBC
932 */
933 
934 /*
935 ** Write a 64-bit variable-length integer to memory starting at p[0].
936 ** The length of data write will be between 1 and 9 bytes.  The number
937 ** of bytes written is returned.
938 **
939 ** A variable-length integer consists of the lower 7 bits of each byte
940 ** for all bytes that have the 8th bit set and one byte with the 8th
941 ** bit clear.  Except, if we get to the 9th byte, it stores the full
942 ** 8 bits and is the last byte.
943 */
944 static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
945   int i, j, n;
946   u8 buf[10];
947   if( v & (((u64)0xff000000)<<32) ){
948     p[8] = (u8)v;
949     v >>= 8;
950     for(i=7; i>=0; i--){
951       p[i] = (u8)((v & 0x7f) | 0x80);
952       v >>= 7;
953     }
954     return 9;
955   }
956   n = 0;
957   do{
958     buf[n++] = (u8)((v & 0x7f) | 0x80);
959     v >>= 7;
960   }while( v!=0 );
961   buf[0] &= 0x7f;
962   assert( n<=9 );
963   for(i=0, j=n-1; j>=0; j--, i++){
964     p[i] = buf[j];
965   }
966   return n;
967 }
968 int sqlite3PutVarint(unsigned char *p, u64 v){
969   if( v<=0x7f ){
970     p[0] = v&0x7f;
971     return 1;
972   }
973   if( v<=0x3fff ){
974     p[0] = ((v>>7)&0x7f)|0x80;
975     p[1] = v&0x7f;
976     return 2;
977   }
978   return putVarint64(p,v);
979 }
980 
981 /*
982 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
983 ** are defined here rather than simply putting the constant expressions
984 ** inline in order to work around bugs in the RVT compiler.
985 **
986 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
987 **
988 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
989 */
990 #define SLOT_2_0     0x001fc07f
991 #define SLOT_4_2_0   0xf01fc07f
992 
993 
994 /*
995 ** Read a 64-bit variable-length integer from memory starting at p[0].
996 ** Return the number of bytes read.  The value is stored in *v.
997 */
998 u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
999   u32 a,b,s;
1000 
1001   if( ((signed char*)p)[0]>=0 ){
1002     *v = *p;
1003     return 1;
1004   }
1005   if( ((signed char*)p)[1]>=0 ){
1006     *v = ((u32)(p[0]&0x7f)<<7) | p[1];
1007     return 2;
1008   }
1009 
1010   /* Verify that constants are precomputed correctly */
1011   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
1012   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
1013 
1014   a = ((u32)p[0])<<14;
1015   b = p[1];
1016   p += 2;
1017   a |= *p;
1018   /* a: p0<<14 | p2 (unmasked) */
1019   if (!(a&0x80))
1020   {
1021     a &= SLOT_2_0;
1022     b &= 0x7f;
1023     b = b<<7;
1024     a |= b;
1025     *v = a;
1026     return 3;
1027   }
1028 
1029   /* CSE1 from below */
1030   a &= SLOT_2_0;
1031   p++;
1032   b = b<<14;
1033   b |= *p;
1034   /* b: p1<<14 | p3 (unmasked) */
1035   if (!(b&0x80))
1036   {
1037     b &= SLOT_2_0;
1038     /* moved CSE1 up */
1039     /* a &= (0x7f<<14)|(0x7f); */
1040     a = a<<7;
1041     a |= b;
1042     *v = a;
1043     return 4;
1044   }
1045 
1046   /* a: p0<<14 | p2 (masked) */
1047   /* b: p1<<14 | p3 (unmasked) */
1048   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
1049   /* moved CSE1 up */
1050   /* a &= (0x7f<<14)|(0x7f); */
1051   b &= SLOT_2_0;
1052   s = a;
1053   /* s: p0<<14 | p2 (masked) */
1054 
1055   p++;
1056   a = a<<14;
1057   a |= *p;
1058   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
1059   if (!(a&0x80))
1060   {
1061     /* we can skip these cause they were (effectively) done above
1062     ** while calculating s */
1063     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
1064     /* b &= (0x7f<<14)|(0x7f); */
1065     b = b<<7;
1066     a |= b;
1067     s = s>>18;
1068     *v = ((u64)s)<<32 | a;
1069     return 5;
1070   }
1071 
1072   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
1073   s = s<<7;
1074   s |= b;
1075   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
1076 
1077   p++;
1078   b = b<<14;
1079   b |= *p;
1080   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
1081   if (!(b&0x80))
1082   {
1083     /* we can skip this cause it was (effectively) done above in calc'ing s */
1084     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
1085     a &= SLOT_2_0;
1086     a = a<<7;
1087     a |= b;
1088     s = s>>18;
1089     *v = ((u64)s)<<32 | a;
1090     return 6;
1091   }
1092 
1093   p++;
1094   a = a<<14;
1095   a |= *p;
1096   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
1097   if (!(a&0x80))
1098   {
1099     a &= SLOT_4_2_0;
1100     b &= SLOT_2_0;
1101     b = b<<7;
1102     a |= b;
1103     s = s>>11;
1104     *v = ((u64)s)<<32 | a;
1105     return 7;
1106   }
1107 
1108   /* CSE2 from below */
1109   a &= SLOT_2_0;
1110   p++;
1111   b = b<<14;
1112   b |= *p;
1113   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
1114   if (!(b&0x80))
1115   {
1116     b &= SLOT_4_2_0;
1117     /* moved CSE2 up */
1118     /* a &= (0x7f<<14)|(0x7f); */
1119     a = a<<7;
1120     a |= b;
1121     s = s>>4;
1122     *v = ((u64)s)<<32 | a;
1123     return 8;
1124   }
1125 
1126   p++;
1127   a = a<<15;
1128   a |= *p;
1129   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
1130 
1131   /* moved CSE2 up */
1132   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
1133   b &= SLOT_2_0;
1134   b = b<<8;
1135   a |= b;
1136 
1137   s = s<<4;
1138   b = p[-4];
1139   b &= 0x7f;
1140   b = b>>3;
1141   s |= b;
1142 
1143   *v = ((u64)s)<<32 | a;
1144 
1145   return 9;
1146 }
1147 
1148 /*
1149 ** Read a 32-bit variable-length integer from memory starting at p[0].
1150 ** Return the number of bytes read.  The value is stored in *v.
1151 **
1152 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
1153 ** integer, then set *v to 0xffffffff.
1154 **
1155 ** A MACRO version, getVarint32, is provided which inlines the
1156 ** single-byte case.  All code should use the MACRO version as
1157 ** this function assumes the single-byte case has already been handled.
1158 */
1159 u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
1160   u32 a,b;
1161 
1162   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
1163   ** by the getVarin32() macro */
1164   a = *p;
1165   /* a: p0 (unmasked) */
1166 #ifndef getVarint32
1167   if (!(a&0x80))
1168   {
1169     /* Values between 0 and 127 */
1170     *v = a;
1171     return 1;
1172   }
1173 #endif
1174 
1175   /* The 2-byte case */
1176   p++;
1177   b = *p;
1178   /* b: p1 (unmasked) */
1179   if (!(b&0x80))
1180   {
1181     /* Values between 128 and 16383 */
1182     a &= 0x7f;
1183     a = a<<7;
1184     *v = a | b;
1185     return 2;
1186   }
1187 
1188   /* The 3-byte case */
1189   p++;
1190   a = a<<14;
1191   a |= *p;
1192   /* a: p0<<14 | p2 (unmasked) */
1193   if (!(a&0x80))
1194   {
1195     /* Values between 16384 and 2097151 */
1196     a &= (0x7f<<14)|(0x7f);
1197     b &= 0x7f;
1198     b = b<<7;
1199     *v = a | b;
1200     return 3;
1201   }
1202 
1203   /* A 32-bit varint is used to store size information in btrees.
1204   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
1205   ** A 3-byte varint is sufficient, for example, to record the size
1206   ** of a 1048569-byte BLOB or string.
1207   **
1208   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
1209   ** rare larger cases can be handled by the slower 64-bit varint
1210   ** routine.
1211   */
1212 #if 1
1213   {
1214     u64 v64;
1215     u8 n;
1216 
1217     n = sqlite3GetVarint(p-2, &v64);
1218     assert( n>3 && n<=9 );
1219     if( (v64 & SQLITE_MAX_U32)!=v64 ){
1220       *v = 0xffffffff;
1221     }else{
1222       *v = (u32)v64;
1223     }
1224     return n;
1225   }
1226 
1227 #else
1228   /* For following code (kept for historical record only) shows an
1229   ** unrolling for the 3- and 4-byte varint cases.  This code is
1230   ** slightly faster, but it is also larger and much harder to test.
1231   */
1232   p++;
1233   b = b<<14;
1234   b |= *p;
1235   /* b: p1<<14 | p3 (unmasked) */
1236   if (!(b&0x80))
1237   {
1238     /* Values between 2097152 and 268435455 */
1239     b &= (0x7f<<14)|(0x7f);
1240     a &= (0x7f<<14)|(0x7f);
1241     a = a<<7;
1242     *v = a | b;
1243     return 4;
1244   }
1245 
1246   p++;
1247   a = a<<14;
1248   a |= *p;
1249   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
1250   if (!(a&0x80))
1251   {
1252     /* Values  between 268435456 and 34359738367 */
1253     a &= SLOT_4_2_0;
1254     b &= SLOT_4_2_0;
1255     b = b<<7;
1256     *v = a | b;
1257     return 5;
1258   }
1259 
1260   /* We can only reach this point when reading a corrupt database
1261   ** file.  In that case we are not in any hurry.  Use the (relatively
1262   ** slow) general-purpose sqlite3GetVarint() routine to extract the
1263   ** value. */
1264   {
1265     u64 v64;
1266     u8 n;
1267 
1268     p -= 4;
1269     n = sqlite3GetVarint(p, &v64);
1270     assert( n>5 && n<=9 );
1271     *v = (u32)v64;
1272     return n;
1273   }
1274 #endif
1275 }
1276 
1277 /*
1278 ** Return the number of bytes that will be needed to store the given
1279 ** 64-bit integer.
1280 */
1281 int sqlite3VarintLen(u64 v){
1282   int i;
1283   for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
1284   return i;
1285 }
1286 
1287 
1288 /*
1289 ** Read or write a four-byte big-endian integer value.
1290 */
1291 u32 sqlite3Get4byte(const u8 *p){
1292 #if SQLITE_BYTEORDER==4321
1293   u32 x;
1294   memcpy(&x,p,4);
1295   return x;
1296 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
1297   u32 x;
1298   memcpy(&x,p,4);
1299   return __builtin_bswap32(x);
1300 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
1301   u32 x;
1302   memcpy(&x,p,4);
1303   return _byteswap_ulong(x);
1304 #else
1305   testcase( p[0]&0x80 );
1306   return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
1307 #endif
1308 }
1309 void sqlite3Put4byte(unsigned char *p, u32 v){
1310 #if SQLITE_BYTEORDER==4321
1311   memcpy(p,&v,4);
1312 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
1313   u32 x = __builtin_bswap32(v);
1314   memcpy(p,&x,4);
1315 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
1316   u32 x = _byteswap_ulong(v);
1317   memcpy(p,&x,4);
1318 #else
1319   p[0] = (u8)(v>>24);
1320   p[1] = (u8)(v>>16);
1321   p[2] = (u8)(v>>8);
1322   p[3] = (u8)v;
1323 #endif
1324 }
1325 
1326 
1327 
1328 /*
1329 ** Translate a single byte of Hex into an integer.
1330 ** This routine only works if h really is a valid hexadecimal
1331 ** character:  0..9a..fA..F
1332 */
1333 u8 sqlite3HexToInt(int h){
1334   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
1335 #ifdef SQLITE_ASCII
1336   h += 9*(1&(h>>6));
1337 #endif
1338 #ifdef SQLITE_EBCDIC
1339   h += 9*(1&~(h>>4));
1340 #endif
1341   return (u8)(h & 0xf);
1342 }
1343 
1344 #if !defined(SQLITE_OMIT_BLOB_LITERAL)
1345 /*
1346 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
1347 ** value.  Return a pointer to its binary value.  Space to hold the
1348 ** binary value has been obtained from malloc and must be freed by
1349 ** the calling routine.
1350 */
1351 void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
1352   char *zBlob;
1353   int i;
1354 
1355   zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
1356   n--;
1357   if( zBlob ){
1358     for(i=0; i<n; i+=2){
1359       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
1360     }
1361     zBlob[i/2] = 0;
1362   }
1363   return zBlob;
1364 }
1365 #endif /* !SQLITE_OMIT_BLOB_LITERAL */
1366 
1367 /*
1368 ** Log an error that is an API call on a connection pointer that should
1369 ** not have been used.  The "type" of connection pointer is given as the
1370 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
1371 */
1372 static void logBadConnection(const char *zType){
1373   sqlite3_log(SQLITE_MISUSE,
1374      "API call with %s database connection pointer",
1375      zType
1376   );
1377 }
1378 
1379 /*
1380 ** Check to make sure we have a valid db pointer.  This test is not
1381 ** foolproof but it does provide some measure of protection against
1382 ** misuse of the interface such as passing in db pointers that are
1383 ** NULL or which have been previously closed.  If this routine returns
1384 ** 1 it means that the db pointer is valid and 0 if it should not be
1385 ** dereferenced for any reason.  The calling function should invoke
1386 ** SQLITE_MISUSE immediately.
1387 **
1388 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
1389 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
1390 ** open properly and is not fit for general use but which can be
1391 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
1392 */
1393 int sqlite3SafetyCheckOk(sqlite3 *db){
1394   u8 eOpenState;
1395   if( db==0 ){
1396     logBadConnection("NULL");
1397     return 0;
1398   }
1399   eOpenState = db->eOpenState;
1400   if( eOpenState!=SQLITE_STATE_OPEN ){
1401     if( sqlite3SafetyCheckSickOrOk(db) ){
1402       testcase( sqlite3GlobalConfig.xLog!=0 );
1403       logBadConnection("unopened");
1404     }
1405     return 0;
1406   }else{
1407     return 1;
1408   }
1409 }
1410 int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
1411   u8 eOpenState;
1412   eOpenState = db->eOpenState;
1413   if( eOpenState!=SQLITE_STATE_SICK &&
1414       eOpenState!=SQLITE_STATE_OPEN &&
1415       eOpenState!=SQLITE_STATE_BUSY ){
1416     testcase( sqlite3GlobalConfig.xLog!=0 );
1417     logBadConnection("invalid");
1418     return 0;
1419   }else{
1420     return 1;
1421   }
1422 }
1423 
1424 /*
1425 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
1426 ** the other 64-bit signed integer at *pA and store the result in *pA.
1427 ** Return 0 on success.  Or if the operation would have resulted in an
1428 ** overflow, leave *pA unchanged and return 1.
1429 */
1430 int sqlite3AddInt64(i64 *pA, i64 iB){
1431 #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
1432   return __builtin_add_overflow(*pA, iB, pA);
1433 #else
1434   i64 iA = *pA;
1435   testcase( iA==0 ); testcase( iA==1 );
1436   testcase( iB==-1 ); testcase( iB==0 );
1437   if( iB>=0 ){
1438     testcase( iA>0 && LARGEST_INT64 - iA == iB );
1439     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
1440     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
1441   }else{
1442     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
1443     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
1444     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
1445   }
1446   *pA += iB;
1447   return 0;
1448 #endif
1449 }
1450 int sqlite3SubInt64(i64 *pA, i64 iB){
1451 #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
1452   return __builtin_sub_overflow(*pA, iB, pA);
1453 #else
1454   testcase( iB==SMALLEST_INT64+1 );
1455   if( iB==SMALLEST_INT64 ){
1456     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
1457     if( (*pA)>=0 ) return 1;
1458     *pA -= iB;
1459     return 0;
1460   }else{
1461     return sqlite3AddInt64(pA, -iB);
1462   }
1463 #endif
1464 }
1465 int sqlite3MulInt64(i64 *pA, i64 iB){
1466 #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
1467   return __builtin_mul_overflow(*pA, iB, pA);
1468 #else
1469   i64 iA = *pA;
1470   if( iB>0 ){
1471     if( iA>LARGEST_INT64/iB ) return 1;
1472     if( iA<SMALLEST_INT64/iB ) return 1;
1473   }else if( iB<0 ){
1474     if( iA>0 ){
1475       if( iB<SMALLEST_INT64/iA ) return 1;
1476     }else if( iA<0 ){
1477       if( iB==SMALLEST_INT64 ) return 1;
1478       if( iA==SMALLEST_INT64 ) return 1;
1479       if( -iA>LARGEST_INT64/-iB ) return 1;
1480     }
1481   }
1482   *pA = iA*iB;
1483   return 0;
1484 #endif
1485 }
1486 
1487 /*
1488 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or
1489 ** if the integer has a value of -2147483648, return +2147483647
1490 */
1491 int sqlite3AbsInt32(int x){
1492   if( x>=0 ) return x;
1493   if( x==(int)0x80000000 ) return 0x7fffffff;
1494   return -x;
1495 }
1496 
1497 #ifdef SQLITE_ENABLE_8_3_NAMES
1498 /*
1499 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
1500 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
1501 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
1502 ** three characters, then shorten the suffix on z[] to be the last three
1503 ** characters of the original suffix.
1504 **
1505 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
1506 ** do the suffix shortening regardless of URI parameter.
1507 **
1508 ** Examples:
1509 **
1510 **     test.db-journal    =>   test.nal
1511 **     test.db-wal        =>   test.wal
1512 **     test.db-shm        =>   test.shm
1513 **     test.db-mj7f3319fa =>   test.9fa
1514 */
1515 void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
1516 #if SQLITE_ENABLE_8_3_NAMES<2
1517   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
1518 #endif
1519   {
1520     int i, sz;
1521     sz = sqlite3Strlen30(z);
1522     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
1523     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
1524   }
1525 }
1526 #endif
1527 
1528 /*
1529 ** Find (an approximate) sum of two LogEst values.  This computation is
1530 ** not a simple "+" operator because LogEst is stored as a logarithmic
1531 ** value.
1532 **
1533 */
1534 LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
1535   static const unsigned char x[] = {
1536      10, 10,                         /* 0,1 */
1537       9, 9,                          /* 2,3 */
1538       8, 8,                          /* 4,5 */
1539       7, 7, 7,                       /* 6,7,8 */
1540       6, 6, 6,                       /* 9,10,11 */
1541       5, 5, 5,                       /* 12-14 */
1542       4, 4, 4, 4,                    /* 15-18 */
1543       3, 3, 3, 3, 3, 3,              /* 19-24 */
1544       2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
1545   };
1546   if( a>=b ){
1547     if( a>b+49 ) return a;
1548     if( a>b+31 ) return a+1;
1549     return a+x[a-b];
1550   }else{
1551     if( b>a+49 ) return b;
1552     if( b>a+31 ) return b+1;
1553     return b+x[b-a];
1554   }
1555 }
1556 
1557 /*
1558 ** Convert an integer into a LogEst.  In other words, compute an
1559 ** approximation for 10*log2(x).
1560 */
1561 LogEst sqlite3LogEst(u64 x){
1562   static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
1563   LogEst y = 40;
1564   if( x<8 ){
1565     if( x<2 ) return 0;
1566     while( x<8 ){  y -= 10; x <<= 1; }
1567   }else{
1568 #if GCC_VERSION>=5004000
1569     int i = 60 - __builtin_clzll(x);
1570     y += i*10;
1571     x >>= i;
1572 #else
1573     while( x>255 ){ y += 40; x >>= 4; }  /*OPTIMIZATION-IF-TRUE*/
1574     while( x>15 ){  y += 10; x >>= 1; }
1575 #endif
1576   }
1577   return a[x&7] + y - 10;
1578 }
1579 
1580 /*
1581 ** Convert a double into a LogEst
1582 ** In other words, compute an approximation for 10*log2(x).
1583 */
1584 LogEst sqlite3LogEstFromDouble(double x){
1585   u64 a;
1586   LogEst e;
1587   assert( sizeof(x)==8 && sizeof(a)==8 );
1588   if( x<=1 ) return 0;
1589   if( x<=2000000000 ) return sqlite3LogEst((u64)x);
1590   memcpy(&a, &x, 8);
1591   e = (a>>52) - 1022;
1592   return e*10;
1593 }
1594 
1595 /*
1596 ** Convert a LogEst into an integer.
1597 */
1598 u64 sqlite3LogEstToInt(LogEst x){
1599   u64 n;
1600   n = x%10;
1601   x /= 10;
1602   if( n>=5 ) n -= 2;
1603   else if( n>=1 ) n -= 1;
1604   if( x>60 ) return (u64)LARGEST_INT64;
1605   return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
1606 }
1607 
1608 /*
1609 ** Add a new name/number pair to a VList.  This might require that the
1610 ** VList object be reallocated, so return the new VList.  If an OOM
1611 ** error occurs, the original VList returned and the
1612 ** db->mallocFailed flag is set.
1613 **
1614 ** A VList is really just an array of integers.  To destroy a VList,
1615 ** simply pass it to sqlite3DbFree().
1616 **
1617 ** The first integer is the number of integers allocated for the whole
1618 ** VList.  The second integer is the number of integers actually used.
1619 ** Each name/number pair is encoded by subsequent groups of 3 or more
1620 ** integers.
1621 **
1622 ** Each name/number pair starts with two integers which are the numeric
1623 ** value for the pair and the size of the name/number pair, respectively.
1624 ** The text name overlays one or more following integers.  The text name
1625 ** is always zero-terminated.
1626 **
1627 ** Conceptually:
1628 **
1629 **    struct VList {
1630 **      int nAlloc;   // Number of allocated slots
1631 **      int nUsed;    // Number of used slots
1632 **      struct VListEntry {
1633 **        int iValue;    // Value for this entry
1634 **        int nSlot;     // Slots used by this entry
1635 **        // ... variable name goes here
1636 **      } a[0];
1637 **    }
1638 **
1639 ** During code generation, pointers to the variable names within the
1640 ** VList are taken.  When that happens, nAlloc is set to zero as an
1641 ** indication that the VList may never again be enlarged, since the
1642 ** accompanying realloc() would invalidate the pointers.
1643 */
1644 VList *sqlite3VListAdd(
1645   sqlite3 *db,           /* The database connection used for malloc() */
1646   VList *pIn,            /* The input VList.  Might be NULL */
1647   const char *zName,     /* Name of symbol to add */
1648   int nName,             /* Bytes of text in zName */
1649   int iVal               /* Value to associate with zName */
1650 ){
1651   int nInt;              /* number of sizeof(int) objects needed for zName */
1652   char *z;               /* Pointer to where zName will be stored */
1653   int i;                 /* Index in pIn[] where zName is stored */
1654 
1655   nInt = nName/4 + 3;
1656   assert( pIn==0 || pIn[0]>=3 );  /* Verify ok to add new elements */
1657   if( pIn==0 || pIn[1]+nInt > pIn[0] ){
1658     /* Enlarge the allocation */
1659     sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt;
1660     VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
1661     if( pOut==0 ) return pIn;
1662     if( pIn==0 ) pOut[1] = 2;
1663     pIn = pOut;
1664     pIn[0] = nAlloc;
1665   }
1666   i = pIn[1];
1667   pIn[i] = iVal;
1668   pIn[i+1] = nInt;
1669   z = (char*)&pIn[i+2];
1670   pIn[1] = i+nInt;
1671   assert( pIn[1]<=pIn[0] );
1672   memcpy(z, zName, nName);
1673   z[nName] = 0;
1674   return pIn;
1675 }
1676 
1677 /*
1678 ** Return a pointer to the name of a variable in the given VList that
1679 ** has the value iVal.  Or return a NULL if there is no such variable in
1680 ** the list
1681 */
1682 const char *sqlite3VListNumToName(VList *pIn, int iVal){
1683   int i, mx;
1684   if( pIn==0 ) return 0;
1685   mx = pIn[1];
1686   i = 2;
1687   do{
1688     if( pIn[i]==iVal ) return (char*)&pIn[i+2];
1689     i += pIn[i+1];
1690   }while( i<mx );
1691   return 0;
1692 }
1693 
1694 /*
1695 ** Return the number of the variable named zName, if it is in VList.
1696 ** or return 0 if there is no such variable.
1697 */
1698 int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
1699   int i, mx;
1700   if( pIn==0 ) return 0;
1701   mx = pIn[1];
1702   i = 2;
1703   do{
1704     const char *z = (const char*)&pIn[i+2];
1705     if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
1706     i += pIn[i+1];
1707   }while( i<mx );
1708   return 0;
1709 }
1710