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