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