000001  /*
000002  ** 2001 September 15
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  ** Utility functions used throughout sqlite.
000013  **
000014  ** This file contains functions for allocating memory, comparing
000015  ** strings, and stuff like that.
000016  **
000017  */
000018  #include "sqliteInt.h"
000019  #include <stdarg.h>
000020  #include <math.h>
000021  
000022  /*
000023  ** Routine needed to support the testcase() macro.
000024  */
000025  #ifdef SQLITE_COVERAGE_TEST
000026  void sqlite3Coverage(int x){
000027    static unsigned dummy = 0;
000028    dummy += (unsigned)x;
000029  }
000030  #endif
000031  
000032  /*
000033  ** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
000034  ** or to bypass normal error detection during testing in order to let 
000035  ** execute proceed futher downstream.
000036  **
000037  ** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0).  The
000038  ** sqlite3FaultSim() function only returns non-zero during testing.
000039  **
000040  ** During testing, if the test harness has set a fault-sim callback using
000041  ** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then
000042  ** each call to sqlite3FaultSim() is relayed to that application-supplied
000043  ** callback and the integer return value form the application-supplied
000044  ** callback is returned by sqlite3FaultSim().
000045  **
000046  ** The integer argument to sqlite3FaultSim() is a code to identify which
000047  ** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()
000048  ** should have a unique code.  To prevent legacy testing applications from
000049  ** breaking, the codes should not be changed or reused.
000050  */
000051  #ifndef SQLITE_UNTESTABLE
000052  int sqlite3FaultSim(int iTest){
000053    int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
000054    return xCallback ? xCallback(iTest) : SQLITE_OK;
000055  }
000056  #endif
000057  
000058  #ifndef SQLITE_OMIT_FLOATING_POINT
000059  /*
000060  ** Return true if the floating point value is Not a Number (NaN).
000061  */
000062  int sqlite3IsNaN(double x){
000063    u64 y;
000064    memcpy(&y,&x,sizeof(y));
000065    return IsNaN(y);
000066  }
000067  #endif /* SQLITE_OMIT_FLOATING_POINT */
000068  
000069  /*
000070  ** Compute a string length that is limited to what can be stored in
000071  ** lower 30 bits of a 32-bit signed integer.
000072  **
000073  ** The value returned will never be negative.  Nor will it ever be greater
000074  ** than the actual length of the string.  For very long strings (greater
000075  ** than 1GiB) the value returned might be less than the true string length.
000076  */
000077  int sqlite3Strlen30(const char *z){
000078    if( z==0 ) return 0;
000079    return 0x3fffffff & (int)strlen(z);
000080  }
000081  
000082  /*
000083  ** Return the declared type of a column.  Or return zDflt if the column 
000084  ** has no declared type.
000085  **
000086  ** The column type is an extra string stored after the zero-terminator on
000087  ** the column name if and only if the COLFLAG_HASTYPE flag is set.
000088  */
000089  char *sqlite3ColumnType(Column *pCol, char *zDflt){
000090    if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
000091    return pCol->zName + strlen(pCol->zName) + 1;
000092  }
000093  
000094  /*
000095  ** Helper function for sqlite3Error() - called rarely.  Broken out into
000096  ** a separate routine to avoid unnecessary register saves on entry to
000097  ** sqlite3Error().
000098  */
000099  static SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){
000100    if( db->pErr ) sqlite3ValueSetNull(db->pErr);
000101    sqlite3SystemError(db, err_code);
000102  }
000103  
000104  /*
000105  ** Set the current error code to err_code and clear any prior error message.
000106  ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
000107  ** that would be appropriate.
000108  */
000109  void sqlite3Error(sqlite3 *db, int err_code){
000110    assert( db!=0 );
000111    db->errCode = err_code;
000112    if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
000113  }
000114  
000115  /*
000116  ** Load the sqlite3.iSysErrno field if that is an appropriate thing
000117  ** to do based on the SQLite error code in rc.
000118  */
000119  void sqlite3SystemError(sqlite3 *db, int rc){
000120    if( rc==SQLITE_IOERR_NOMEM ) return;
000121    rc &= 0xff;
000122    if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
000123      db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
000124    }
000125  }
000126  
000127  /*
000128  ** Set the most recent error code and error string for the sqlite
000129  ** handle "db". The error code is set to "err_code".
000130  **
000131  ** If it is not NULL, string zFormat specifies the format of the
000132  ** error string in the style of the printf functions: The following
000133  ** format characters are allowed:
000134  **
000135  **      %s      Insert a string
000136  **      %z      A string that should be freed after use
000137  **      %d      Insert an integer
000138  **      %T      Insert a token
000139  **      %S      Insert the first element of a SrcList
000140  **
000141  ** zFormat and any string tokens that follow it are assumed to be
000142  ** encoded in UTF-8.
000143  **
000144  ** To clear the most recent error for sqlite handle "db", sqlite3Error
000145  ** should be called with err_code set to SQLITE_OK and zFormat set
000146  ** to NULL.
000147  */
000148  void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
000149    assert( db!=0 );
000150    db->errCode = err_code;
000151    sqlite3SystemError(db, err_code);
000152    if( zFormat==0 ){
000153      sqlite3Error(db, err_code);
000154    }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
000155      char *z;
000156      va_list ap;
000157      va_start(ap, zFormat);
000158      z = sqlite3VMPrintf(db, zFormat, ap);
000159      va_end(ap);
000160      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
000161    }
000162  }
000163  
000164  /*
000165  ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
000166  ** The following formatting characters are allowed:
000167  **
000168  **      %s      Insert a string
000169  **      %z      A string that should be freed after use
000170  **      %d      Insert an integer
000171  **      %T      Insert a token
000172  **      %S      Insert the first element of a SrcList
000173  **
000174  ** This function should be used to report any error that occurs while
000175  ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
000176  ** last thing the sqlite3_prepare() function does is copy the error
000177  ** stored by this function into the database handle using sqlite3Error().
000178  ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
000179  ** during statement execution (sqlite3_step() etc.).
000180  */
000181  void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
000182    char *zMsg;
000183    va_list ap;
000184    sqlite3 *db = pParse->db;
000185    va_start(ap, zFormat);
000186    zMsg = sqlite3VMPrintf(db, zFormat, ap);
000187    va_end(ap);
000188    if( db->suppressErr ){
000189      sqlite3DbFree(db, zMsg);
000190    }else{
000191      pParse->nErr++;
000192      sqlite3DbFree(db, pParse->zErrMsg);
000193      pParse->zErrMsg = zMsg;
000194      pParse->rc = SQLITE_ERROR;
000195      pParse->pWith = 0;
000196    }
000197  }
000198  
000199  /*
000200  ** If database connection db is currently parsing SQL, then transfer
000201  ** error code errCode to that parser if the parser has not already
000202  ** encountered some other kind of error.
000203  */
000204  int sqlite3ErrorToParser(sqlite3 *db, int errCode){
000205    Parse *pParse;
000206    if( db==0 || (pParse = db->pParse)==0 ) return errCode;
000207    pParse->rc = errCode;
000208    pParse->nErr++;
000209    return errCode;
000210  }
000211  
000212  /*
000213  ** Convert an SQL-style quoted string into a normal string by removing
000214  ** the quote characters.  The conversion is done in-place.  If the
000215  ** input does not begin with a quote character, then this routine
000216  ** is a no-op.
000217  **
000218  ** The input string must be zero-terminated.  A new zero-terminator
000219  ** is added to the dequoted string.
000220  **
000221  ** The return value is -1 if no dequoting occurs or the length of the
000222  ** dequoted string, exclusive of the zero terminator, if dequoting does
000223  ** occur.
000224  **
000225  ** 2002-02-14: This routine is extended to remove MS-Access style
000226  ** brackets from around identifiers.  For example:  "[a-b-c]" becomes
000227  ** "a-b-c".
000228  */
000229  void sqlite3Dequote(char *z){
000230    char quote;
000231    int i, j;
000232    if( z==0 ) return;
000233    quote = z[0];
000234    if( !sqlite3Isquote(quote) ) return;
000235    if( quote=='[' ) quote = ']';
000236    for(i=1, j=0;; i++){
000237      assert( z[i] );
000238      if( z[i]==quote ){
000239        if( z[i+1]==quote ){
000240          z[j++] = quote;
000241          i++;
000242        }else{
000243          break;
000244        }
000245      }else{
000246        z[j++] = z[i];
000247      }
000248    }
000249    z[j] = 0;
000250  }
000251  void sqlite3DequoteExpr(Expr *p){
000252    assert( sqlite3Isquote(p->u.zToken[0]) );
000253    p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
000254    sqlite3Dequote(p->u.zToken);
000255  }
000256  
000257  /*
000258  ** Generate a Token object from a string
000259  */
000260  void sqlite3TokenInit(Token *p, char *z){
000261    p->z = z;
000262    p->n = sqlite3Strlen30(z);
000263  }
000264  
000265  /* Convenient short-hand */
000266  #define UpperToLower sqlite3UpperToLower
000267  
000268  /*
000269  ** Some systems have stricmp().  Others have strcasecmp().  Because
000270  ** there is no consistency, we will define our own.
000271  **
000272  ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
000273  ** sqlite3_strnicmp() APIs allow applications and extensions to compare
000274  ** the contents of two buffers containing UTF-8 strings in a
000275  ** case-independent fashion, using the same definition of "case
000276  ** independence" that SQLite uses internally when comparing identifiers.
000277  */
000278  int sqlite3_stricmp(const char *zLeft, const char *zRight){
000279    if( zLeft==0 ){
000280      return zRight ? -1 : 0;
000281    }else if( zRight==0 ){
000282      return 1;
000283    }
000284    return sqlite3StrICmp(zLeft, zRight);
000285  }
000286  int sqlite3StrICmp(const char *zLeft, const char *zRight){
000287    unsigned char *a, *b;
000288    int c, x;
000289    a = (unsigned char *)zLeft;
000290    b = (unsigned char *)zRight;
000291    for(;;){
000292      c = *a;
000293      x = *b;
000294      if( c==x ){
000295        if( c==0 ) break;
000296      }else{
000297        c = (int)UpperToLower[c] - (int)UpperToLower[x];
000298        if( c ) break;
000299      }
000300      a++;
000301      b++;
000302    }
000303    return c;
000304  }
000305  int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
000306    register unsigned char *a, *b;
000307    if( zLeft==0 ){
000308      return zRight ? -1 : 0;
000309    }else if( zRight==0 ){
000310      return 1;
000311    }
000312    a = (unsigned char *)zLeft;
000313    b = (unsigned char *)zRight;
000314    while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
000315    return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
000316  }
000317  
000318  /*
000319  ** Compute 10 to the E-th power.  Examples:  E==1 results in 10.
000320  ** E==2 results in 100.  E==50 results in 1.0e50.
000321  **
000322  ** This routine only works for values of E between 1 and 341.
000323  */
000324  static LONGDOUBLE_TYPE sqlite3Pow10(int E){
000325  #if defined(_MSC_VER)
000326    static const LONGDOUBLE_TYPE x[] = {
000327      1.0e+001L,
000328      1.0e+002L,
000329      1.0e+004L,
000330      1.0e+008L,
000331      1.0e+016L,
000332      1.0e+032L,
000333      1.0e+064L,
000334      1.0e+128L,
000335      1.0e+256L
000336    };
000337    LONGDOUBLE_TYPE r = 1.0;
000338    int i;
000339    assert( E>=0 && E<=307 );
000340    for(i=0; E!=0; i++, E >>=1){
000341      if( E & 1 ) r *= x[i];
000342    }
000343    return r;
000344  #else
000345    LONGDOUBLE_TYPE x = 10.0;
000346    LONGDOUBLE_TYPE r = 1.0;
000347    while(1){
000348      if( E & 1 ) r *= x;
000349      E >>= 1;
000350      if( E==0 ) break;
000351      x *= x;
000352    }
000353    return r; 
000354  #endif
000355  }
000356  
000357  /*
000358  ** The string z[] is an text representation of a real number.
000359  ** Convert this string to a double and write it into *pResult.
000360  **
000361  ** The string z[] is length bytes in length (bytes, not characters) and
000362  ** uses the encoding enc.  The string is not necessarily zero-terminated.
000363  **
000364  ** Return TRUE if the result is a valid real number (or integer) and FALSE
000365  ** if the string is empty or contains extraneous text.  More specifically
000366  ** return
000367  **      1          =>  The input string is a pure integer
000368  **      2 or more  =>  The input has a decimal point or eNNN clause
000369  **      0 or less  =>  The input string is not a valid number
000370  **     -1          =>  Not a valid number, but has a valid prefix which 
000371  **                     includes a decimal point and/or an eNNN clause
000372  **
000373  ** Valid numbers are in one of these formats:
000374  **
000375  **    [+-]digits[E[+-]digits]
000376  **    [+-]digits.[digits][E[+-]digits]
000377  **    [+-].digits[E[+-]digits]
000378  **
000379  ** Leading and trailing whitespace is ignored for the purpose of determining
000380  ** validity.
000381  **
000382  ** If some prefix of the input string is a valid number, this routine
000383  ** returns FALSE but it still converts the prefix and writes the result
000384  ** into *pResult.
000385  */
000386  #if defined(_MSC_VER)
000387  #pragma warning(disable : 4756)
000388  #endif
000389  int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
000390  #ifndef SQLITE_OMIT_FLOATING_POINT
000391    int incr;
000392    const char *zEnd;
000393    /* sign * significand * (10 ^ (esign * exponent)) */
000394    int sign = 1;    /* sign of significand */
000395    i64 s = 0;       /* significand */
000396    int d = 0;       /* adjust exponent for shifting decimal point */
000397    int esign = 1;   /* sign of exponent */
000398    int e = 0;       /* exponent */
000399    int eValid = 1;  /* True exponent is either not used or is well-formed */
000400    double result;
000401    int nDigit = 0;  /* Number of digits processed */
000402    int eType = 1;   /* 1: pure integer,  2+: fractional  -1 or less: bad UTF16 */
000403  
000404    assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
000405    *pResult = 0.0;   /* Default return value, in case of an error */
000406    if( length==0 ) return 0;
000407  
000408    if( enc==SQLITE_UTF8 ){
000409      incr = 1;
000410      zEnd = z + length;
000411    }else{
000412      int i;
000413      incr = 2;
000414      assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
000415      testcase( enc==SQLITE_UTF16LE );
000416      testcase( enc==SQLITE_UTF16BE );
000417      for(i=3-enc; i<length && z[i]==0; i+=2){}
000418      if( i<length ) eType = -100;
000419      zEnd = &z[i^1];
000420      z += (enc&1);
000421    }
000422  
000423    /* skip leading spaces */
000424    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
000425    if( z>=zEnd ) return 0;
000426  
000427    /* get sign of significand */
000428    if( *z=='-' ){
000429      sign = -1;
000430      z+=incr;
000431    }else if( *z=='+' ){
000432      z+=incr;
000433    }
000434  
000435    /* copy max significant digits to significand */
000436    while( z<zEnd && sqlite3Isdigit(*z) ){
000437      s = s*10 + (*z - '0');
000438      z+=incr; nDigit++;
000439      if( s>=((LARGEST_INT64-9)/10) ){
000440        /* skip non-significant significand digits
000441        ** (increase exponent by d to shift decimal left) */
000442        while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; d++; }
000443      }
000444    }
000445    if( z>=zEnd ) goto do_atof_calc;
000446  
000447    /* if decimal point is present */
000448    if( *z=='.' ){
000449      z+=incr;
000450      eType++;
000451      /* copy digits from after decimal to significand
000452      ** (decrease exponent by d to shift decimal right) */
000453      while( z<zEnd && sqlite3Isdigit(*z) ){
000454        if( s<((LARGEST_INT64-9)/10) ){
000455          s = s*10 + (*z - '0');
000456          d--;
000457          nDigit++;
000458        }
000459        z+=incr;
000460      }
000461    }
000462    if( z>=zEnd ) goto do_atof_calc;
000463  
000464    /* if exponent is present */
000465    if( *z=='e' || *z=='E' ){
000466      z+=incr;
000467      eValid = 0;
000468      eType++;
000469  
000470      /* This branch is needed to avoid a (harmless) buffer overread.  The 
000471      ** special comment alerts the mutation tester that the correct answer
000472      ** is obtained even if the branch is omitted */
000473      if( z>=zEnd ) goto do_atof_calc;              /*PREVENTS-HARMLESS-OVERREAD*/
000474  
000475      /* get sign of exponent */
000476      if( *z=='-' ){
000477        esign = -1;
000478        z+=incr;
000479      }else if( *z=='+' ){
000480        z+=incr;
000481      }
000482      /* copy digits to exponent */
000483      while( z<zEnd && sqlite3Isdigit(*z) ){
000484        e = e<10000 ? (e*10 + (*z - '0')) : 10000;
000485        z+=incr;
000486        eValid = 1;
000487      }
000488    }
000489  
000490    /* skip trailing spaces */
000491    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
000492  
000493  do_atof_calc:
000494    /* adjust exponent by d, and update sign */
000495    e = (e*esign) + d;
000496    if( e<0 ) {
000497      esign = -1;
000498      e *= -1;
000499    } else {
000500      esign = 1;
000501    }
000502  
000503    if( s==0 ) {
000504      /* In the IEEE 754 standard, zero is signed. */
000505      result = sign<0 ? -(double)0 : (double)0;
000506    } else {
000507      /* Attempt to reduce exponent.
000508      **
000509      ** Branches that are not required for the correct answer but which only
000510      ** help to obtain the correct answer faster are marked with special
000511      ** comments, as a hint to the mutation tester.
000512      */
000513      while( e>0 ){                                       /*OPTIMIZATION-IF-TRUE*/
000514        if( esign>0 ){
000515          if( s>=(LARGEST_INT64/10) ) break;             /*OPTIMIZATION-IF-FALSE*/
000516          s *= 10;
000517        }else{
000518          if( s%10!=0 ) break;                           /*OPTIMIZATION-IF-FALSE*/
000519          s /= 10;
000520        }
000521        e--;
000522      }
000523  
000524      /* adjust the sign of significand */
000525      s = sign<0 ? -s : s;
000526  
000527      if( e==0 ){                                         /*OPTIMIZATION-IF-TRUE*/
000528        result = (double)s;
000529      }else{
000530        /* attempt to handle extremely small/large numbers better */
000531        if( e>307 ){                                      /*OPTIMIZATION-IF-TRUE*/
000532          if( e<342 ){                                    /*OPTIMIZATION-IF-TRUE*/
000533            LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
000534            if( esign<0 ){
000535              result = s / scale;
000536              result /= 1.0e+308;
000537            }else{
000538              result = s * scale;
000539              result *= 1.0e+308;
000540            }
000541          }else{ assert( e>=342 );
000542            if( esign<0 ){
000543              result = 0.0*s;
000544            }else{
000545  #ifdef INFINITY
000546              result = INFINITY*s;
000547  #else
000548              result = 1e308*1e308*s;  /* Infinity */
000549  #endif
000550            }
000551          }
000552        }else{
000553          LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
000554          if( esign<0 ){
000555            result = s / scale;
000556          }else{
000557            result = s * scale;
000558          }
000559        }
000560      }
000561    }
000562  
000563    /* store the result */
000564    *pResult = result;
000565  
000566    /* return true if number and no extra non-whitespace chracters after */
000567    if( z==zEnd && nDigit>0 && eValid && eType>0 ){
000568      return eType;
000569    }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){
000570      return -1;
000571    }else{
000572      return 0;
000573    }
000574  #else
000575    return !sqlite3Atoi64(z, pResult, length, enc);
000576  #endif /* SQLITE_OMIT_FLOATING_POINT */
000577  }
000578  #if defined(_MSC_VER)
000579  #pragma warning(default : 4756)
000580  #endif
000581  
000582  /*
000583  ** Compare the 19-character string zNum against the text representation
000584  ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
000585  ** if zNum is less than, equal to, or greater than the string.
000586  ** Note that zNum must contain exactly 19 characters.
000587  **
000588  ** Unlike memcmp() this routine is guaranteed to return the difference
000589  ** in the values of the last digit if the only difference is in the
000590  ** last digit.  So, for example,
000591  **
000592  **      compare2pow63("9223372036854775800", 1)
000593  **
000594  ** will return -8.
000595  */
000596  static int compare2pow63(const char *zNum, int incr){
000597    int c = 0;
000598    int i;
000599                      /* 012345678901234567 */
000600    const char *pow63 = "922337203685477580";
000601    for(i=0; c==0 && i<18; i++){
000602      c = (zNum[i*incr]-pow63[i])*10;
000603    }
000604    if( c==0 ){
000605      c = zNum[18*incr] - '8';
000606      testcase( c==(-1) );
000607      testcase( c==0 );
000608      testcase( c==(+1) );
000609    }
000610    return c;
000611  }
000612  
000613  /*
000614  ** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
000615  ** routine does *not* accept hexadecimal notation.
000616  **
000617  ** Returns:
000618  **
000619  **    -1    Not even a prefix of the input text looks like an integer
000620  **     0    Successful transformation.  Fits in a 64-bit signed integer.
000621  **     1    Excess non-space text after the integer value
000622  **     2    Integer too large for a 64-bit signed integer or is malformed
000623  **     3    Special case of 9223372036854775808
000624  **
000625  ** length is the number of bytes in the string (bytes, not characters).
000626  ** The string is not necessarily zero-terminated.  The encoding is
000627  ** given by enc.
000628  */
000629  int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
000630    int incr;
000631    u64 u = 0;
000632    int neg = 0; /* assume positive */
000633    int i;
000634    int c = 0;
000635    int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
000636    int rc;          /* Baseline return code */
000637    const char *zStart;
000638    const char *zEnd = zNum + length;
000639    assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
000640    if( enc==SQLITE_UTF8 ){
000641      incr = 1;
000642    }else{
000643      incr = 2;
000644      assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
000645      for(i=3-enc; i<length && zNum[i]==0; i+=2){}
000646      nonNum = i<length;
000647      zEnd = &zNum[i^1];
000648      zNum += (enc&1);
000649    }
000650    while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
000651    if( zNum<zEnd ){
000652      if( *zNum=='-' ){
000653        neg = 1;
000654        zNum+=incr;
000655      }else if( *zNum=='+' ){
000656        zNum+=incr;
000657      }
000658    }
000659    zStart = zNum;
000660    while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
000661    for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
000662      u = u*10 + c - '0';
000663    }
000664    testcase( i==18*incr );
000665    testcase( i==19*incr );
000666    testcase( i==20*incr );
000667    if( u>LARGEST_INT64 ){
000668      /* This test and assignment is needed only to suppress UB warnings
000669      ** from clang and -fsanitize=undefined.  This test and assignment make
000670      ** the code a little larger and slower, and no harm comes from omitting
000671      ** them, but we must appaise the undefined-behavior pharisees. */
000672      *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
000673    }else if( neg ){
000674      *pNum = -(i64)u;
000675    }else{
000676      *pNum = (i64)u;
000677    }
000678    rc = 0;
000679    if( i==0 && zStart==zNum ){    /* No digits */
000680      rc = -1;
000681    }else if( nonNum ){            /* UTF16 with high-order bytes non-zero */
000682      rc = 1;
000683    }else if( &zNum[i]<zEnd ){     /* Extra bytes at the end */
000684      int jj = i;
000685      do{
000686        if( !sqlite3Isspace(zNum[jj]) ){
000687          rc = 1;          /* Extra non-space text after the integer */
000688          break;
000689        }
000690        jj += incr;
000691      }while( &zNum[jj]<zEnd );
000692    }
000693    if( i<19*incr ){
000694      /* Less than 19 digits, so we know that it fits in 64 bits */
000695      assert( u<=LARGEST_INT64 );
000696      return rc;
000697    }else{
000698      /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
000699      c = i>19*incr ? 1 : compare2pow63(zNum, incr);
000700      if( c<0 ){
000701        /* zNum is less than 9223372036854775808 so it fits */
000702        assert( u<=LARGEST_INT64 );
000703        return rc;
000704      }else{
000705        *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
000706        if( c>0 ){
000707          /* zNum is greater than 9223372036854775808 so it overflows */
000708          return 2;
000709        }else{
000710          /* zNum is exactly 9223372036854775808.  Fits if negative.  The
000711          ** special case 2 overflow if positive */
000712          assert( u-1==LARGEST_INT64 );
000713          return neg ? rc : 3;
000714        }
000715      }
000716    }
000717  }
000718  
000719  /*
000720  ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
000721  ** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
000722  ** whereas sqlite3Atoi64() does not.
000723  **
000724  ** Returns:
000725  **
000726  **     0    Successful transformation.  Fits in a 64-bit signed integer.
000727  **     1    Excess text after the integer value
000728  **     2    Integer too large for a 64-bit signed integer or is malformed
000729  **     3    Special case of 9223372036854775808
000730  */
000731  int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
000732  #ifndef SQLITE_OMIT_HEX_INTEGER
000733    if( z[0]=='0'
000734     && (z[1]=='x' || z[1]=='X')
000735    ){
000736      u64 u = 0;
000737      int i, k;
000738      for(i=2; z[i]=='0'; i++){}
000739      for(k=i; sqlite3Isxdigit(z[k]); k++){
000740        u = u*16 + sqlite3HexToInt(z[k]);
000741      }
000742      memcpy(pOut, &u, 8);
000743      return (z[k]==0 && k-i<=16) ? 0 : 2;
000744    }else
000745  #endif /* SQLITE_OMIT_HEX_INTEGER */
000746    {
000747      return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
000748    }
000749  }
000750  
000751  /*
000752  ** If zNum represents an integer that will fit in 32-bits, then set
000753  ** *pValue to that integer and return true.  Otherwise return false.
000754  **
000755  ** This routine accepts both decimal and hexadecimal notation for integers.
000756  **
000757  ** Any non-numeric characters that following zNum are ignored.
000758  ** This is different from sqlite3Atoi64() which requires the
000759  ** input number to be zero-terminated.
000760  */
000761  int sqlite3GetInt32(const char *zNum, int *pValue){
000762    sqlite_int64 v = 0;
000763    int i, c;
000764    int neg = 0;
000765    if( zNum[0]=='-' ){
000766      neg = 1;
000767      zNum++;
000768    }else if( zNum[0]=='+' ){
000769      zNum++;
000770    }
000771  #ifndef SQLITE_OMIT_HEX_INTEGER
000772    else if( zNum[0]=='0'
000773          && (zNum[1]=='x' || zNum[1]=='X')
000774          && sqlite3Isxdigit(zNum[2])
000775    ){
000776      u32 u = 0;
000777      zNum += 2;
000778      while( zNum[0]=='0' ) zNum++;
000779      for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
000780        u = u*16 + sqlite3HexToInt(zNum[i]);
000781      }
000782      if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
000783        memcpy(pValue, &u, 4);
000784        return 1;
000785      }else{
000786        return 0;
000787      }
000788    }
000789  #endif
000790    if( !sqlite3Isdigit(zNum[0]) ) return 0;
000791    while( zNum[0]=='0' ) zNum++;
000792    for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
000793      v = v*10 + c;
000794    }
000795  
000796    /* The longest decimal representation of a 32 bit integer is 10 digits:
000797    **
000798    **             1234567890
000799    **     2^31 -> 2147483648
000800    */
000801    testcase( i==10 );
000802    if( i>10 ){
000803      return 0;
000804    }
000805    testcase( v-neg==2147483647 );
000806    if( v-neg>2147483647 ){
000807      return 0;
000808    }
000809    if( neg ){
000810      v = -v;
000811    }
000812    *pValue = (int)v;
000813    return 1;
000814  }
000815  
000816  /*
000817  ** Return a 32-bit integer value extracted from a string.  If the
000818  ** string is not an integer, just return 0.
000819  */
000820  int sqlite3Atoi(const char *z){
000821    int x = 0;
000822    if( z ) sqlite3GetInt32(z, &x);
000823    return x;
000824  }
000825  
000826  /*
000827  ** The variable-length integer encoding is as follows:
000828  **
000829  ** KEY:
000830  **         A = 0xxxxxxx    7 bits of data and one flag bit
000831  **         B = 1xxxxxxx    7 bits of data and one flag bit
000832  **         C = xxxxxxxx    8 bits of data
000833  **
000834  **  7 bits - A
000835  ** 14 bits - BA
000836  ** 21 bits - BBA
000837  ** 28 bits - BBBA
000838  ** 35 bits - BBBBA
000839  ** 42 bits - BBBBBA
000840  ** 49 bits - BBBBBBA
000841  ** 56 bits - BBBBBBBA
000842  ** 64 bits - BBBBBBBBC
000843  */
000844  
000845  /*
000846  ** Write a 64-bit variable-length integer to memory starting at p[0].
000847  ** The length of data write will be between 1 and 9 bytes.  The number
000848  ** of bytes written is returned.
000849  **
000850  ** A variable-length integer consists of the lower 7 bits of each byte
000851  ** for all bytes that have the 8th bit set and one byte with the 8th
000852  ** bit clear.  Except, if we get to the 9th byte, it stores the full
000853  ** 8 bits and is the last byte.
000854  */
000855  static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
000856    int i, j, n;
000857    u8 buf[10];
000858    if( v & (((u64)0xff000000)<<32) ){
000859      p[8] = (u8)v;
000860      v >>= 8;
000861      for(i=7; i>=0; i--){
000862        p[i] = (u8)((v & 0x7f) | 0x80);
000863        v >>= 7;
000864      }
000865      return 9;
000866    }    
000867    n = 0;
000868    do{
000869      buf[n++] = (u8)((v & 0x7f) | 0x80);
000870      v >>= 7;
000871    }while( v!=0 );
000872    buf[0] &= 0x7f;
000873    assert( n<=9 );
000874    for(i=0, j=n-1; j>=0; j--, i++){
000875      p[i] = buf[j];
000876    }
000877    return n;
000878  }
000879  int sqlite3PutVarint(unsigned char *p, u64 v){
000880    if( v<=0x7f ){
000881      p[0] = v&0x7f;
000882      return 1;
000883    }
000884    if( v<=0x3fff ){
000885      p[0] = ((v>>7)&0x7f)|0x80;
000886      p[1] = v&0x7f;
000887      return 2;
000888    }
000889    return putVarint64(p,v);
000890  }
000891  
000892  /*
000893  ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
000894  ** are defined here rather than simply putting the constant expressions
000895  ** inline in order to work around bugs in the RVT compiler.
000896  **
000897  ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
000898  **
000899  ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
000900  */
000901  #define SLOT_2_0     0x001fc07f
000902  #define SLOT_4_2_0   0xf01fc07f
000903  
000904  
000905  /*
000906  ** Read a 64-bit variable-length integer from memory starting at p[0].
000907  ** Return the number of bytes read.  The value is stored in *v.
000908  */
000909  u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
000910    u32 a,b,s;
000911  
000912    if( ((signed char*)p)[0]>=0 ){
000913      *v = *p;
000914      return 1;
000915    }
000916    if( ((signed char*)p)[1]>=0 ){
000917      *v = ((u32)(p[0]&0x7f)<<7) | p[1];
000918      return 2;
000919    }
000920  
000921    /* Verify that constants are precomputed correctly */
000922    assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
000923    assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
000924  
000925    a = ((u32)p[0])<<14;
000926    b = p[1];
000927    p += 2;
000928    a |= *p;
000929    /* a: p0<<14 | p2 (unmasked) */
000930    if (!(a&0x80))
000931    {
000932      a &= SLOT_2_0;
000933      b &= 0x7f;
000934      b = b<<7;
000935      a |= b;
000936      *v = a;
000937      return 3;
000938    }
000939  
000940    /* CSE1 from below */
000941    a &= SLOT_2_0;
000942    p++;
000943    b = b<<14;
000944    b |= *p;
000945    /* b: p1<<14 | p3 (unmasked) */
000946    if (!(b&0x80))
000947    {
000948      b &= SLOT_2_0;
000949      /* moved CSE1 up */
000950      /* a &= (0x7f<<14)|(0x7f); */
000951      a = a<<7;
000952      a |= b;
000953      *v = a;
000954      return 4;
000955    }
000956  
000957    /* a: p0<<14 | p2 (masked) */
000958    /* b: p1<<14 | p3 (unmasked) */
000959    /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
000960    /* moved CSE1 up */
000961    /* a &= (0x7f<<14)|(0x7f); */
000962    b &= SLOT_2_0;
000963    s = a;
000964    /* s: p0<<14 | p2 (masked) */
000965  
000966    p++;
000967    a = a<<14;
000968    a |= *p;
000969    /* a: p0<<28 | p2<<14 | p4 (unmasked) */
000970    if (!(a&0x80))
000971    {
000972      /* we can skip these cause they were (effectively) done above
000973      ** while calculating s */
000974      /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
000975      /* b &= (0x7f<<14)|(0x7f); */
000976      b = b<<7;
000977      a |= b;
000978      s = s>>18;
000979      *v = ((u64)s)<<32 | a;
000980      return 5;
000981    }
000982  
000983    /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
000984    s = s<<7;
000985    s |= b;
000986    /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
000987  
000988    p++;
000989    b = b<<14;
000990    b |= *p;
000991    /* b: p1<<28 | p3<<14 | p5 (unmasked) */
000992    if (!(b&0x80))
000993    {
000994      /* we can skip this cause it was (effectively) done above in calc'ing s */
000995      /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
000996      a &= SLOT_2_0;
000997      a = a<<7;
000998      a |= b;
000999      s = s>>18;
001000      *v = ((u64)s)<<32 | a;
001001      return 6;
001002    }
001003  
001004    p++;
001005    a = a<<14;
001006    a |= *p;
001007    /* a: p2<<28 | p4<<14 | p6 (unmasked) */
001008    if (!(a&0x80))
001009    {
001010      a &= SLOT_4_2_0;
001011      b &= SLOT_2_0;
001012      b = b<<7;
001013      a |= b;
001014      s = s>>11;
001015      *v = ((u64)s)<<32 | a;
001016      return 7;
001017    }
001018  
001019    /* CSE2 from below */
001020    a &= SLOT_2_0;
001021    p++;
001022    b = b<<14;
001023    b |= *p;
001024    /* b: p3<<28 | p5<<14 | p7 (unmasked) */
001025    if (!(b&0x80))
001026    {
001027      b &= SLOT_4_2_0;
001028      /* moved CSE2 up */
001029      /* a &= (0x7f<<14)|(0x7f); */
001030      a = a<<7;
001031      a |= b;
001032      s = s>>4;
001033      *v = ((u64)s)<<32 | a;
001034      return 8;
001035    }
001036  
001037    p++;
001038    a = a<<15;
001039    a |= *p;
001040    /* a: p4<<29 | p6<<15 | p8 (unmasked) */
001041  
001042    /* moved CSE2 up */
001043    /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
001044    b &= SLOT_2_0;
001045    b = b<<8;
001046    a |= b;
001047  
001048    s = s<<4;
001049    b = p[-4];
001050    b &= 0x7f;
001051    b = b>>3;
001052    s |= b;
001053  
001054    *v = ((u64)s)<<32 | a;
001055  
001056    return 9;
001057  }
001058  
001059  /*
001060  ** Read a 32-bit variable-length integer from memory starting at p[0].
001061  ** Return the number of bytes read.  The value is stored in *v.
001062  **
001063  ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
001064  ** integer, then set *v to 0xffffffff.
001065  **
001066  ** A MACRO version, getVarint32, is provided which inlines the 
001067  ** single-byte case.  All code should use the MACRO version as 
001068  ** this function assumes the single-byte case has already been handled.
001069  */
001070  u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
001071    u32 a,b;
001072  
001073    /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
001074    ** by the getVarin32() macro */
001075    a = *p;
001076    /* a: p0 (unmasked) */
001077  #ifndef getVarint32
001078    if (!(a&0x80))
001079    {
001080      /* Values between 0 and 127 */
001081      *v = a;
001082      return 1;
001083    }
001084  #endif
001085  
001086    /* The 2-byte case */
001087    p++;
001088    b = *p;
001089    /* b: p1 (unmasked) */
001090    if (!(b&0x80))
001091    {
001092      /* Values between 128 and 16383 */
001093      a &= 0x7f;
001094      a = a<<7;
001095      *v = a | b;
001096      return 2;
001097    }
001098  
001099    /* The 3-byte case */
001100    p++;
001101    a = a<<14;
001102    a |= *p;
001103    /* a: p0<<14 | p2 (unmasked) */
001104    if (!(a&0x80))
001105    {
001106      /* Values between 16384 and 2097151 */
001107      a &= (0x7f<<14)|(0x7f);
001108      b &= 0x7f;
001109      b = b<<7;
001110      *v = a | b;
001111      return 3;
001112    }
001113  
001114    /* A 32-bit varint is used to store size information in btrees.
001115    ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
001116    ** A 3-byte varint is sufficient, for example, to record the size
001117    ** of a 1048569-byte BLOB or string.
001118    **
001119    ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
001120    ** rare larger cases can be handled by the slower 64-bit varint
001121    ** routine.
001122    */
001123  #if 1
001124    {
001125      u64 v64;
001126      u8 n;
001127  
001128      p -= 2;
001129      n = sqlite3GetVarint(p, &v64);
001130      assert( n>3 && n<=9 );
001131      if( (v64 & SQLITE_MAX_U32)!=v64 ){
001132        *v = 0xffffffff;
001133      }else{
001134        *v = (u32)v64;
001135      }
001136      return n;
001137    }
001138  
001139  #else
001140    /* For following code (kept for historical record only) shows an
001141    ** unrolling for the 3- and 4-byte varint cases.  This code is
001142    ** slightly faster, but it is also larger and much harder to test.
001143    */
001144    p++;
001145    b = b<<14;
001146    b |= *p;
001147    /* b: p1<<14 | p3 (unmasked) */
001148    if (!(b&0x80))
001149    {
001150      /* Values between 2097152 and 268435455 */
001151      b &= (0x7f<<14)|(0x7f);
001152      a &= (0x7f<<14)|(0x7f);
001153      a = a<<7;
001154      *v = a | b;
001155      return 4;
001156    }
001157  
001158    p++;
001159    a = a<<14;
001160    a |= *p;
001161    /* a: p0<<28 | p2<<14 | p4 (unmasked) */
001162    if (!(a&0x80))
001163    {
001164      /* Values  between 268435456 and 34359738367 */
001165      a &= SLOT_4_2_0;
001166      b &= SLOT_4_2_0;
001167      b = b<<7;
001168      *v = a | b;
001169      return 5;
001170    }
001171  
001172    /* We can only reach this point when reading a corrupt database
001173    ** file.  In that case we are not in any hurry.  Use the (relatively
001174    ** slow) general-purpose sqlite3GetVarint() routine to extract the
001175    ** value. */
001176    {
001177      u64 v64;
001178      u8 n;
001179  
001180      p -= 4;
001181      n = sqlite3GetVarint(p, &v64);
001182      assert( n>5 && n<=9 );
001183      *v = (u32)v64;
001184      return n;
001185    }
001186  #endif
001187  }
001188  
001189  /*
001190  ** Return the number of bytes that will be needed to store the given
001191  ** 64-bit integer.
001192  */
001193  int sqlite3VarintLen(u64 v){
001194    int i;
001195    for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
001196    return i;
001197  }
001198  
001199  
001200  /*
001201  ** Read or write a four-byte big-endian integer value.
001202  */
001203  u32 sqlite3Get4byte(const u8 *p){
001204  #if SQLITE_BYTEORDER==4321
001205    u32 x;
001206    memcpy(&x,p,4);
001207    return x;
001208  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
001209    u32 x;
001210    memcpy(&x,p,4);
001211    return __builtin_bswap32(x);
001212  #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
001213    u32 x;
001214    memcpy(&x,p,4);
001215    return _byteswap_ulong(x);
001216  #else
001217    testcase( p[0]&0x80 );
001218    return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
001219  #endif
001220  }
001221  void sqlite3Put4byte(unsigned char *p, u32 v){
001222  #if SQLITE_BYTEORDER==4321
001223    memcpy(p,&v,4);
001224  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
001225    u32 x = __builtin_bswap32(v);
001226    memcpy(p,&x,4);
001227  #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
001228    u32 x = _byteswap_ulong(v);
001229    memcpy(p,&x,4);
001230  #else
001231    p[0] = (u8)(v>>24);
001232    p[1] = (u8)(v>>16);
001233    p[2] = (u8)(v>>8);
001234    p[3] = (u8)v;
001235  #endif
001236  }
001237  
001238  
001239  
001240  /*
001241  ** Translate a single byte of Hex into an integer.
001242  ** This routine only works if h really is a valid hexadecimal
001243  ** character:  0..9a..fA..F
001244  */
001245  u8 sqlite3HexToInt(int h){
001246    assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
001247  #ifdef SQLITE_ASCII
001248    h += 9*(1&(h>>6));
001249  #endif
001250  #ifdef SQLITE_EBCDIC
001251    h += 9*(1&~(h>>4));
001252  #endif
001253    return (u8)(h & 0xf);
001254  }
001255  
001256  #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
001257  /*
001258  ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
001259  ** value.  Return a pointer to its binary value.  Space to hold the
001260  ** binary value has been obtained from malloc and must be freed by
001261  ** the calling routine.
001262  */
001263  void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
001264    char *zBlob;
001265    int i;
001266  
001267    zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
001268    n--;
001269    if( zBlob ){
001270      for(i=0; i<n; i+=2){
001271        zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
001272      }
001273      zBlob[i/2] = 0;
001274    }
001275    return zBlob;
001276  }
001277  #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
001278  
001279  /*
001280  ** Log an error that is an API call on a connection pointer that should
001281  ** not have been used.  The "type" of connection pointer is given as the
001282  ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
001283  */
001284  static void logBadConnection(const char *zType){
001285    sqlite3_log(SQLITE_MISUSE, 
001286       "API call with %s database connection pointer",
001287       zType
001288    );
001289  }
001290  
001291  /*
001292  ** Check to make sure we have a valid db pointer.  This test is not
001293  ** foolproof but it does provide some measure of protection against
001294  ** misuse of the interface such as passing in db pointers that are
001295  ** NULL or which have been previously closed.  If this routine returns
001296  ** 1 it means that the db pointer is valid and 0 if it should not be
001297  ** dereferenced for any reason.  The calling function should invoke
001298  ** SQLITE_MISUSE immediately.
001299  **
001300  ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
001301  ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
001302  ** open properly and is not fit for general use but which can be
001303  ** used as an argument to sqlite3_errmsg() or sqlite3_close().
001304  */
001305  int sqlite3SafetyCheckOk(sqlite3 *db){
001306    u32 magic;
001307    if( db==0 ){
001308      logBadConnection("NULL");
001309      return 0;
001310    }
001311    magic = db->magic;
001312    if( magic!=SQLITE_MAGIC_OPEN ){
001313      if( sqlite3SafetyCheckSickOrOk(db) ){
001314        testcase( sqlite3GlobalConfig.xLog!=0 );
001315        logBadConnection("unopened");
001316      }
001317      return 0;
001318    }else{
001319      return 1;
001320    }
001321  }
001322  int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
001323    u32 magic;
001324    magic = db->magic;
001325    if( magic!=SQLITE_MAGIC_SICK &&
001326        magic!=SQLITE_MAGIC_OPEN &&
001327        magic!=SQLITE_MAGIC_BUSY ){
001328      testcase( sqlite3GlobalConfig.xLog!=0 );
001329      logBadConnection("invalid");
001330      return 0;
001331    }else{
001332      return 1;
001333    }
001334  }
001335  
001336  /*
001337  ** Attempt to add, substract, or multiply the 64-bit signed value iB against
001338  ** the other 64-bit signed integer at *pA and store the result in *pA.
001339  ** Return 0 on success.  Or if the operation would have resulted in an
001340  ** overflow, leave *pA unchanged and return 1.
001341  */
001342  int sqlite3AddInt64(i64 *pA, i64 iB){
001343  #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
001344    return __builtin_add_overflow(*pA, iB, pA);
001345  #else
001346    i64 iA = *pA;
001347    testcase( iA==0 ); testcase( iA==1 );
001348    testcase( iB==-1 ); testcase( iB==0 );
001349    if( iB>=0 ){
001350      testcase( iA>0 && LARGEST_INT64 - iA == iB );
001351      testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
001352      if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
001353    }else{
001354      testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
001355      testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
001356      if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
001357    }
001358    *pA += iB;
001359    return 0; 
001360  #endif
001361  }
001362  int sqlite3SubInt64(i64 *pA, i64 iB){
001363  #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
001364    return __builtin_sub_overflow(*pA, iB, pA);
001365  #else
001366    testcase( iB==SMALLEST_INT64+1 );
001367    if( iB==SMALLEST_INT64 ){
001368      testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
001369      if( (*pA)>=0 ) return 1;
001370      *pA -= iB;
001371      return 0;
001372    }else{
001373      return sqlite3AddInt64(pA, -iB);
001374    }
001375  #endif
001376  }
001377  int sqlite3MulInt64(i64 *pA, i64 iB){
001378  #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
001379    return __builtin_mul_overflow(*pA, iB, pA);
001380  #else
001381    i64 iA = *pA;
001382    if( iB>0 ){
001383      if( iA>LARGEST_INT64/iB ) return 1;
001384      if( iA<SMALLEST_INT64/iB ) return 1;
001385    }else if( iB<0 ){
001386      if( iA>0 ){
001387        if( iB<SMALLEST_INT64/iA ) return 1;
001388      }else if( iA<0 ){
001389        if( iB==SMALLEST_INT64 ) return 1;
001390        if( iA==SMALLEST_INT64 ) return 1;
001391        if( -iA>LARGEST_INT64/-iB ) return 1;
001392      }
001393    }
001394    *pA = iA*iB;
001395    return 0;
001396  #endif
001397  }
001398  
001399  /*
001400  ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
001401  ** if the integer has a value of -2147483648, return +2147483647
001402  */
001403  int sqlite3AbsInt32(int x){
001404    if( x>=0 ) return x;
001405    if( x==(int)0x80000000 ) return 0x7fffffff;
001406    return -x;
001407  }
001408  
001409  #ifdef SQLITE_ENABLE_8_3_NAMES
001410  /*
001411  ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
001412  ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
001413  ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
001414  ** three characters, then shorten the suffix on z[] to be the last three
001415  ** characters of the original suffix.
001416  **
001417  ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
001418  ** do the suffix shortening regardless of URI parameter.
001419  **
001420  ** Examples:
001421  **
001422  **     test.db-journal    =>   test.nal
001423  **     test.db-wal        =>   test.wal
001424  **     test.db-shm        =>   test.shm
001425  **     test.db-mj7f3319fa =>   test.9fa
001426  */
001427  void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
001428  #if SQLITE_ENABLE_8_3_NAMES<2
001429    if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
001430  #endif
001431    {
001432      int i, sz;
001433      sz = sqlite3Strlen30(z);
001434      for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
001435      if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
001436    }
001437  }
001438  #endif
001439  
001440  /* 
001441  ** Find (an approximate) sum of two LogEst values.  This computation is
001442  ** not a simple "+" operator because LogEst is stored as a logarithmic
001443  ** value.
001444  ** 
001445  */
001446  LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
001447    static const unsigned char x[] = {
001448       10, 10,                         /* 0,1 */
001449        9, 9,                          /* 2,3 */
001450        8, 8,                          /* 4,5 */
001451        7, 7, 7,                       /* 6,7,8 */
001452        6, 6, 6,                       /* 9,10,11 */
001453        5, 5, 5,                       /* 12-14 */
001454        4, 4, 4, 4,                    /* 15-18 */
001455        3, 3, 3, 3, 3, 3,              /* 19-24 */
001456        2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
001457    };
001458    if( a>=b ){
001459      if( a>b+49 ) return a;
001460      if( a>b+31 ) return a+1;
001461      return a+x[a-b];
001462    }else{
001463      if( b>a+49 ) return b;
001464      if( b>a+31 ) return b+1;
001465      return b+x[b-a];
001466    }
001467  }
001468  
001469  /*
001470  ** Convert an integer into a LogEst.  In other words, compute an
001471  ** approximation for 10*log2(x).
001472  */
001473  LogEst sqlite3LogEst(u64 x){
001474    static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
001475    LogEst y = 40;
001476    if( x<8 ){
001477      if( x<2 ) return 0;
001478      while( x<8 ){  y -= 10; x <<= 1; }
001479    }else{
001480  #if GCC_VERSION>=5004000
001481      int i = 60 - __builtin_clzll(x);
001482      y += i*10;
001483      x >>= i;
001484  #else
001485      while( x>255 ){ y += 40; x >>= 4; }  /*OPTIMIZATION-IF-TRUE*/
001486      while( x>15 ){  y += 10; x >>= 1; }
001487  #endif
001488    }
001489    return a[x&7] + y - 10;
001490  }
001491  
001492  #ifndef SQLITE_OMIT_VIRTUALTABLE
001493  /*
001494  ** Convert a double into a LogEst
001495  ** In other words, compute an approximation for 10*log2(x).
001496  */
001497  LogEst sqlite3LogEstFromDouble(double x){
001498    u64 a;
001499    LogEst e;
001500    assert( sizeof(x)==8 && sizeof(a)==8 );
001501    if( x<=1 ) return 0;
001502    if( x<=2000000000 ) return sqlite3LogEst((u64)x);
001503    memcpy(&a, &x, 8);
001504    e = (a>>52) - 1022;
001505    return e*10;
001506  }
001507  #endif /* SQLITE_OMIT_VIRTUALTABLE */
001508  
001509  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
001510      defined(SQLITE_ENABLE_STAT4) || \
001511      defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
001512  /*
001513  ** Convert a LogEst into an integer.
001514  **
001515  ** Note that this routine is only used when one or more of various
001516  ** non-standard compile-time options is enabled.
001517  */
001518  u64 sqlite3LogEstToInt(LogEst x){
001519    u64 n;
001520    n = x%10;
001521    x /= 10;
001522    if( n>=5 ) n -= 2;
001523    else if( n>=1 ) n -= 1;
001524  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
001525      defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
001526    if( x>60 ) return (u64)LARGEST_INT64;
001527  #else
001528    /* If only SQLITE_ENABLE_STAT4 is on, then the largest input
001529    ** possible to this routine is 310, resulting in a maximum x of 31 */
001530    assert( x<=60 );
001531  #endif
001532    return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
001533  }
001534  #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
001535  
001536  /*
001537  ** Add a new name/number pair to a VList.  This might require that the
001538  ** VList object be reallocated, so return the new VList.  If an OOM
001539  ** error occurs, the original VList returned and the
001540  ** db->mallocFailed flag is set.
001541  **
001542  ** A VList is really just an array of integers.  To destroy a VList,
001543  ** simply pass it to sqlite3DbFree().
001544  **
001545  ** The first integer is the number of integers allocated for the whole
001546  ** VList.  The second integer is the number of integers actually used.
001547  ** Each name/number pair is encoded by subsequent groups of 3 or more
001548  ** integers.
001549  **
001550  ** Each name/number pair starts with two integers which are the numeric
001551  ** value for the pair and the size of the name/number pair, respectively.
001552  ** The text name overlays one or more following integers.  The text name
001553  ** is always zero-terminated.
001554  **
001555  ** Conceptually:
001556  **
001557  **    struct VList {
001558  **      int nAlloc;   // Number of allocated slots 
001559  **      int nUsed;    // Number of used slots 
001560  **      struct VListEntry {
001561  **        int iValue;    // Value for this entry
001562  **        int nSlot;     // Slots used by this entry
001563  **        // ... variable name goes here
001564  **      } a[0];
001565  **    }
001566  **
001567  ** During code generation, pointers to the variable names within the
001568  ** VList are taken.  When that happens, nAlloc is set to zero as an 
001569  ** indication that the VList may never again be enlarged, since the
001570  ** accompanying realloc() would invalidate the pointers.
001571  */
001572  VList *sqlite3VListAdd(
001573    sqlite3 *db,           /* The database connection used for malloc() */
001574    VList *pIn,            /* The input VList.  Might be NULL */
001575    const char *zName,     /* Name of symbol to add */
001576    int nName,             /* Bytes of text in zName */
001577    int iVal               /* Value to associate with zName */
001578  ){
001579    int nInt;              /* number of sizeof(int) objects needed for zName */
001580    char *z;               /* Pointer to where zName will be stored */
001581    int i;                 /* Index in pIn[] where zName is stored */
001582  
001583    nInt = nName/4 + 3;
001584    assert( pIn==0 || pIn[0]>=3 );  /* Verify ok to add new elements */
001585    if( pIn==0 || pIn[1]+nInt > pIn[0] ){
001586      /* Enlarge the allocation */
001587      sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt;
001588      VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
001589      if( pOut==0 ) return pIn;
001590      if( pIn==0 ) pOut[1] = 2;
001591      pIn = pOut;
001592      pIn[0] = nAlloc;
001593    }
001594    i = pIn[1];
001595    pIn[i] = iVal;
001596    pIn[i+1] = nInt;
001597    z = (char*)&pIn[i+2];
001598    pIn[1] = i+nInt;
001599    assert( pIn[1]<=pIn[0] );
001600    memcpy(z, zName, nName);
001601    z[nName] = 0;
001602    return pIn;
001603  }
001604  
001605  /*
001606  ** Return a pointer to the name of a variable in the given VList that
001607  ** has the value iVal.  Or return a NULL if there is no such variable in
001608  ** the list
001609  */
001610  const char *sqlite3VListNumToName(VList *pIn, int iVal){
001611    int i, mx;
001612    if( pIn==0 ) return 0;
001613    mx = pIn[1];
001614    i = 2;
001615    do{
001616      if( pIn[i]==iVal ) return (char*)&pIn[i+2];
001617      i += pIn[i+1];
001618    }while( i<mx );
001619    return 0;
001620  }
001621  
001622  /*
001623  ** Return the number of the variable named zName, if it is in VList.
001624  ** or return 0 if there is no such variable.
001625  */
001626  int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
001627    int i, mx;
001628    if( pIn==0 ) return 0;
001629    mx = pIn[1];
001630    i = 2;
001631    do{
001632      const char *z = (const char*)&pIn[i+2];
001633      if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
001634      i += pIn[i+1];
001635    }while( i<mx );
001636    return 0;
001637  }