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