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