000001  /*
000002  ** 2004 May 26
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  **
000013  ** This file contains code use to manipulate "Mem" structure.  A "Mem"
000014  ** stores a single value in the VDBE.  Mem is an opaque structure visible
000015  ** only within the VDBE.  Interface routines refer to a Mem using the
000016  ** name sqlite_value
000017  */
000018  #include "sqliteInt.h"
000019  #include "vdbeInt.h"
000020  
000021  /* True if X is a power of two.  0 is considered a power of two here.
000022  ** In other words, return true if X has at most one bit set.
000023  */
000024  #define ISPOWEROF2(X)  (((X)&((X)-1))==0)
000025  
000026  #ifdef SQLITE_DEBUG
000027  /*
000028  ** Check invariants on a Mem object.
000029  **
000030  ** This routine is intended for use inside of assert() statements, like
000031  ** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
000032  */
000033  int sqlite3VdbeCheckMemInvariants(Mem *p){
000034    /* If MEM_Dyn is set then Mem.xDel!=0.  
000035    ** Mem.xDel might not be initialized if MEM_Dyn is clear.
000036    */
000037    assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
000038  
000039    /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
000040    ** ensure that if Mem.szMalloc>0 then it is safe to do
000041    ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
000042    ** That saves a few cycles in inner loops. */
000043    assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
000044  
000045    /* Cannot have more than one of MEM_Int, MEM_Real, or MEM_IntReal */
000046    assert( ISPOWEROF2(p->flags & (MEM_Int|MEM_Real|MEM_IntReal)) );
000047  
000048    if( p->flags & MEM_Null ){
000049      /* Cannot be both MEM_Null and some other type */
000050      assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );
000051  
000052      /* If MEM_Null is set, then either the value is a pure NULL (the usual
000053      ** case) or it is a pointer set using sqlite3_bind_pointer() or
000054      ** sqlite3_result_pointer().  If a pointer, then MEM_Term must also be
000055      ** set.
000056      */
000057      if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
000058        /* This is a pointer type.  There may be a flag to indicate what to
000059        ** do with the pointer. */
000060        assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
000061                ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
000062                ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
000063  
000064        /* No other bits set */
000065        assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind
000066                             |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
000067      }else{
000068        /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
000069        ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
000070      }
000071    }else{
000072      /* The MEM_Cleared bit is only allowed on NULLs */
000073      assert( (p->flags & MEM_Cleared)==0 );
000074    }
000075  
000076    /* The szMalloc field holds the correct memory allocation size */
000077    assert( p->szMalloc==0
000078         || (p->flags==MEM_Undefined 
000079             && p->szMalloc<=sqlite3DbMallocSize(p->db,p->zMalloc))
000080         || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc));
000081  
000082    /* If p holds a string or blob, the Mem.z must point to exactly
000083    ** one of the following:
000084    **
000085    **   (1) Memory in Mem.zMalloc and managed by the Mem object
000086    **   (2) Memory to be freed using Mem.xDel
000087    **   (3) An ephemeral string or blob
000088    **   (4) A static string or blob
000089    */
000090    if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
000091      assert( 
000092        ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
000093        ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
000094        ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
000095        ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
000096      );
000097    }
000098    return 1;
000099  }
000100  #endif
000101  
000102  /*
000103  ** Render a Mem object which is one of MEM_Int, MEM_Real, or MEM_IntReal
000104  ** into a buffer.
000105  */
000106  static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){
000107    StrAccum acc;
000108    assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) );
000109    assert( sz>22 );
000110    if( p->flags & MEM_Int ){
000111  #if GCC_VERSION>=7000000
000112      /* Work-around for GCC bug
000113      ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96270 */
000114      i64 x;
000115      assert( (p->flags&MEM_Int)*2==sizeof(x) );
000116      memcpy(&x, (char*)&p->u, (p->flags&MEM_Int)*2);
000117      p->n = sqlite3Int64ToText(x, zBuf);
000118  #else
000119      p->n = sqlite3Int64ToText(p->u.i, zBuf);
000120  #endif
000121    }else{
000122      sqlite3StrAccumInit(&acc, 0, zBuf, sz, 0);
000123      sqlite3_str_appendf(&acc, "%!.15g", 
000124           (p->flags & MEM_IntReal)!=0 ? (double)p->u.i : p->u.r);
000125      assert( acc.zText==zBuf && acc.mxAlloc<=0 );
000126      zBuf[acc.nChar] = 0; /* Fast version of sqlite3StrAccumFinish(&acc) */
000127      p->n = acc.nChar;
000128    }
000129  }
000130  
000131  #ifdef SQLITE_DEBUG
000132  /*
000133  ** Validity checks on pMem.  pMem holds a string.
000134  **
000135  ** (1) Check that string value of pMem agrees with its integer or real value.
000136  ** (2) Check that the string is correctly zero terminated
000137  **
000138  ** A single int or real value always converts to the same strings.  But
000139  ** many different strings can be converted into the same int or real.
000140  ** If a table contains a numeric value and an index is based on the
000141  ** corresponding string value, then it is important that the string be
000142  ** derived from the numeric value, not the other way around, to ensure
000143  ** that the index and table are consistent.  See ticket
000144  ** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
000145  ** an example.
000146  **
000147  ** This routine looks at pMem to verify that if it has both a numeric
000148  ** representation and a string representation then the string rep has
000149  ** been derived from the numeric and not the other way around.  It returns
000150  ** true if everything is ok and false if there is a problem.
000151  **
000152  ** This routine is for use inside of assert() statements only.
000153  */
000154  int sqlite3VdbeMemValidStrRep(Mem *p){
000155    Mem tmp;
000156    char zBuf[100];
000157    char *z;
000158    int i, j, incr;
000159    if( (p->flags & MEM_Str)==0 ) return 1;
000160    if( p->db && p->db->mallocFailed ) return 1;
000161    if( p->flags & MEM_Term ){
000162      /* Insure that the string is properly zero-terminated.  Pay particular
000163      ** attention to the case where p->n is odd */
000164      if( p->szMalloc>0 && p->z==p->zMalloc ){
000165        assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 );
000166        assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 );
000167      }
000168      assert( p->z[p->n]==0 );
000169      assert( p->enc==SQLITE_UTF8 || p->z[(p->n+1)&~1]==0 );
000170      assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 );
000171    }
000172    if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1;
000173    memcpy(&tmp, p, sizeof(tmp));
000174    vdbeMemRenderNum(sizeof(zBuf), zBuf, &tmp);
000175    z = p->z;
000176    i = j = 0;
000177    incr = 1;
000178    if( p->enc!=SQLITE_UTF8 ){
000179      incr = 2;
000180      if( p->enc==SQLITE_UTF16BE ) z++;
000181    }
000182    while( zBuf[j] ){
000183      if( zBuf[j++]!=z[i] ) return 0;
000184      i += incr;
000185    }
000186    return 1;
000187  }
000188  #endif /* SQLITE_DEBUG */
000189  
000190  /*
000191  ** If pMem is an object with a valid string representation, this routine
000192  ** ensures the internal encoding for the string representation is
000193  ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
000194  **
000195  ** If pMem is not a string object, or the encoding of the string
000196  ** representation is already stored using the requested encoding, then this
000197  ** routine is a no-op.
000198  **
000199  ** SQLITE_OK is returned if the conversion is successful (or not required).
000200  ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
000201  ** between formats.
000202  */
000203  int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
000204  #ifndef SQLITE_OMIT_UTF16
000205    int rc;
000206  #endif
000207    assert( pMem!=0 );
000208    assert( !sqlite3VdbeMemIsRowSet(pMem) );
000209    assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
000210             || desiredEnc==SQLITE_UTF16BE );
000211    if( !(pMem->flags&MEM_Str) ){
000212      pMem->enc = desiredEnc;
000213      return SQLITE_OK;
000214    }
000215    if( pMem->enc==desiredEnc ){
000216      return SQLITE_OK;
000217    }
000218    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
000219  #ifdef SQLITE_OMIT_UTF16
000220    return SQLITE_ERROR;
000221  #else
000222  
000223    /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
000224    ** then the encoding of the value may not have changed.
000225    */
000226    rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
000227    assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
000228    assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
000229    assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
000230    return rc;
000231  #endif
000232  }
000233  
000234  /*
000235  ** Make sure pMem->z points to a writable allocation of at least n bytes.
000236  **
000237  ** If the bPreserve argument is true, then copy of the content of
000238  ** pMem->z into the new allocation.  pMem must be either a string or
000239  ** blob if bPreserve is true.  If bPreserve is false, any prior content
000240  ** in pMem->z is discarded.
000241  */
000242  SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
000243    assert( sqlite3VdbeCheckMemInvariants(pMem) );
000244    assert( !sqlite3VdbeMemIsRowSet(pMem) );
000245    testcase( pMem->db==0 );
000246  
000247    /* If the bPreserve flag is set to true, then the memory cell must already
000248    ** contain a valid string or blob value.  */
000249    assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
000250    testcase( bPreserve && pMem->z==0 );
000251  
000252    assert( pMem->szMalloc==0
000253         || (pMem->flags==MEM_Undefined 
000254             && pMem->szMalloc<=sqlite3DbMallocSize(pMem->db,pMem->zMalloc))
000255         || pMem->szMalloc==sqlite3DbMallocSize(pMem->db,pMem->zMalloc));
000256    if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
000257      if( pMem->db ){
000258        pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
000259      }else{
000260        pMem->zMalloc = sqlite3Realloc(pMem->z, n);
000261        if( pMem->zMalloc==0 ) sqlite3_free(pMem->z);
000262        pMem->z = pMem->zMalloc;
000263      }
000264      bPreserve = 0;
000265    }else{
000266      if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
000267      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
000268    }
000269    if( pMem->zMalloc==0 ){
000270      sqlite3VdbeMemSetNull(pMem);
000271      pMem->z = 0;
000272      pMem->szMalloc = 0;
000273      return SQLITE_NOMEM_BKPT;
000274    }else{
000275      pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
000276    }
000277  
000278    if( bPreserve && pMem->z ){
000279      assert( pMem->z!=pMem->zMalloc );
000280      memcpy(pMem->zMalloc, pMem->z, pMem->n);
000281    }
000282    if( (pMem->flags&MEM_Dyn)!=0 ){
000283      assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
000284      pMem->xDel((void *)(pMem->z));
000285    }
000286  
000287    pMem->z = pMem->zMalloc;
000288    pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
000289    return SQLITE_OK;
000290  }
000291  
000292  /*
000293  ** Change the pMem->zMalloc allocation to be at least szNew bytes.
000294  ** If pMem->zMalloc already meets or exceeds the requested size, this
000295  ** routine is a no-op.
000296  **
000297  ** Any prior string or blob content in the pMem object may be discarded.
000298  ** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
000299  ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, MEM_IntReal,
000300  ** and MEM_Null values are preserved.
000301  **
000302  ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
000303  ** if unable to complete the resizing.
000304  */
000305  int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
000306    assert( CORRUPT_DB || szNew>0 );
000307    assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
000308    if( pMem->szMalloc<szNew ){
000309      return sqlite3VdbeMemGrow(pMem, szNew, 0);
000310    }
000311    assert( (pMem->flags & MEM_Dyn)==0 );
000312    pMem->z = pMem->zMalloc;
000313    pMem->flags &= (MEM_Null|MEM_Int|MEM_Real|MEM_IntReal);
000314    return SQLITE_OK;
000315  }
000316  
000317  /*
000318  ** If pMem is already a string, detect if it is a zero-terminated
000319  ** string, or make it into one if possible, and mark it as such.
000320  **
000321  ** This is an optimization.  Correct operation continues even if
000322  ** this routine is a no-op.
000323  */
000324  void sqlite3VdbeMemZeroTerminateIfAble(Mem *pMem){
000325    if( (pMem->flags & (MEM_Str|MEM_Term|MEM_Ephem|MEM_Static))!=MEM_Str ){
000326      /* pMem must be a string, and it cannot be an ephemeral or static string */
000327      return;
000328    }
000329    if( pMem->enc!=SQLITE_UTF8 ) return;
000330    if( NEVER(pMem->z==0) ) return;
000331    if( pMem->flags & MEM_Dyn ){
000332      if( pMem->xDel==sqlite3_free
000333       && sqlite3_msize(pMem->z) >= (u64)(pMem->n+1)
000334      ){
000335        pMem->z[pMem->n] = 0;
000336        pMem->flags |= MEM_Term;
000337        return;
000338      }
000339      if( pMem->xDel==sqlite3RCStrUnref ){
000340        /* Blindly assume that all RCStr objects are zero-terminated */
000341        pMem->flags |= MEM_Term;
000342        return;
000343      }
000344    }else if( pMem->szMalloc >= pMem->n+1 ){
000345      pMem->z[pMem->n] = 0;
000346      pMem->flags |= MEM_Term;
000347      return;
000348    }
000349  }
000350  
000351  /*
000352  ** It is already known that pMem contains an unterminated string.
000353  ** Add the zero terminator.
000354  **
000355  ** Three bytes of zero are added.  In this way, there is guaranteed
000356  ** to be a double-zero byte at an even byte boundary in order to
000357  ** terminate a UTF16 string, even if the initial size of the buffer
000358  ** is an odd number of bytes.
000359  */
000360  static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
000361    if( sqlite3VdbeMemGrow(pMem, pMem->n+3, 1) ){
000362      return SQLITE_NOMEM_BKPT;
000363    }
000364    pMem->z[pMem->n] = 0;
000365    pMem->z[pMem->n+1] = 0;
000366    pMem->z[pMem->n+2] = 0;
000367    pMem->flags |= MEM_Term;
000368    return SQLITE_OK;
000369  }
000370  
000371  /*
000372  ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
000373  ** MEM.zMalloc, where it can be safely written.
000374  **
000375  ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
000376  */
000377  int sqlite3VdbeMemMakeWriteable(Mem *pMem){
000378    assert( pMem!=0 );
000379    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
000380    assert( !sqlite3VdbeMemIsRowSet(pMem) );
000381    if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
000382      if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
000383      if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
000384        int rc = vdbeMemAddTerminator(pMem);
000385        if( rc ) return rc;
000386      }
000387    }
000388    pMem->flags &= ~MEM_Ephem;
000389  #ifdef SQLITE_DEBUG
000390    pMem->pScopyFrom = 0;
000391  #endif
000392  
000393    return SQLITE_OK;
000394  }
000395  
000396  /*
000397  ** If the given Mem* has a zero-filled tail, turn it into an ordinary
000398  ** blob stored in dynamically allocated space.
000399  */
000400  #ifndef SQLITE_OMIT_INCRBLOB
000401  int sqlite3VdbeMemExpandBlob(Mem *pMem){
000402    int nByte;
000403    assert( pMem!=0 );
000404    assert( pMem->flags & MEM_Zero );
000405    assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) );
000406    testcase( sqlite3_value_nochange(pMem) );
000407    assert( !sqlite3VdbeMemIsRowSet(pMem) );
000408    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
000409  
000410    /* Set nByte to the number of bytes required to store the expanded blob. */
000411    nByte = pMem->n + pMem->u.nZero;
000412    if( nByte<=0 ){
000413      if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK;
000414      nByte = 1;
000415    }
000416    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
000417      return SQLITE_NOMEM_BKPT;
000418    }
000419    assert( pMem->z!=0 );
000420    assert( sqlite3DbMallocSize(pMem->db,pMem->z) >= nByte );
000421  
000422    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
000423    pMem->n += pMem->u.nZero;
000424    pMem->flags &= ~(MEM_Zero|MEM_Term);
000425    return SQLITE_OK;
000426  }
000427  #endif
000428  
000429  /*
000430  ** Make sure the given Mem is \u0000 terminated.
000431  */
000432  int sqlite3VdbeMemNulTerminate(Mem *pMem){
000433    assert( pMem!=0 );
000434    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
000435    testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
000436    testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
000437    if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
000438      return SQLITE_OK;   /* Nothing to do */
000439    }else{
000440      return vdbeMemAddTerminator(pMem);
000441    }
000442  }
000443  
000444  /*
000445  ** Add MEM_Str to the set of representations for the given Mem.  This
000446  ** routine is only called if pMem is a number of some kind, not a NULL
000447  ** or a BLOB.
000448  **
000449  ** Existing representations MEM_Int, MEM_Real, or MEM_IntReal are invalidated
000450  ** if bForce is true but are retained if bForce is false.
000451  **
000452  ** A MEM_Null value will never be passed to this function. This function is
000453  ** used for converting values to text for returning to the user (i.e. via
000454  ** sqlite3_value_text()), or for ensuring that values to be used as btree
000455  ** keys are strings. In the former case a NULL pointer is returned the
000456  ** user and the latter is an internal programming error.
000457  */
000458  int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
000459    const int nByte = 32;
000460  
000461    assert( pMem!=0 );
000462    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
000463    assert( !(pMem->flags&MEM_Zero) );
000464    assert( !(pMem->flags&(MEM_Str|MEM_Blob)) );
000465    assert( pMem->flags&(MEM_Int|MEM_Real|MEM_IntReal) );
000466    assert( !sqlite3VdbeMemIsRowSet(pMem) );
000467    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
000468  
000469  
000470    if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
000471      pMem->enc = 0;
000472      return SQLITE_NOMEM_BKPT;
000473    }
000474  
000475    vdbeMemRenderNum(nByte, pMem->z, pMem);
000476    assert( pMem->z!=0 );
000477    assert( pMem->n==(int)sqlite3Strlen30NN(pMem->z) );
000478    pMem->enc = SQLITE_UTF8;
000479    pMem->flags |= MEM_Str|MEM_Term;
000480    if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
000481    sqlite3VdbeChangeEncoding(pMem, enc);
000482    return SQLITE_OK;
000483  }
000484  
000485  /*
000486  ** Memory cell pMem contains the context of an aggregate function.
000487  ** This routine calls the finalize method for that function.  The
000488  ** result of the aggregate is stored back into pMem.
000489  **
000490  ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
000491  ** otherwise.
000492  */
000493  int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
000494    sqlite3_context ctx;
000495    Mem t;
000496    assert( pFunc!=0 );
000497    assert( pMem!=0 );
000498    assert( pMem->db!=0 );
000499    assert( pFunc->xFinalize!=0 );
000500    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
000501    assert( sqlite3_mutex_held(pMem->db->mutex) );
000502    memset(&ctx, 0, sizeof(ctx));
000503    memset(&t, 0, sizeof(t));
000504    t.flags = MEM_Null;
000505    t.db = pMem->db;
000506    ctx.pOut = &t;
000507    ctx.pMem = pMem;
000508    ctx.pFunc = pFunc;
000509    ctx.enc = ENC(t.db);
000510    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
000511    assert( (pMem->flags & MEM_Dyn)==0 );
000512    if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
000513    memcpy(pMem, &t, sizeof(t));
000514    return ctx.isError;
000515  }
000516  
000517  /*
000518  ** Memory cell pAccum contains the context of an aggregate function.
000519  ** This routine calls the xValue method for that function and stores
000520  ** the results in memory cell pMem.
000521  **
000522  ** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK 
000523  ** otherwise.
000524  */
000525  #ifndef SQLITE_OMIT_WINDOWFUNC
000526  int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){
000527    sqlite3_context ctx;
000528    assert( pFunc!=0 );
000529    assert( pFunc->xValue!=0 );
000530    assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
000531    assert( pAccum->db!=0 );
000532    assert( sqlite3_mutex_held(pAccum->db->mutex) );
000533    memset(&ctx, 0, sizeof(ctx));
000534    sqlite3VdbeMemSetNull(pOut);
000535    ctx.pOut = pOut;
000536    ctx.pMem = pAccum;
000537    ctx.pFunc = pFunc;
000538    ctx.enc = ENC(pAccum->db);
000539    pFunc->xValue(&ctx);
000540    return ctx.isError;
000541  }
000542  #endif /* SQLITE_OMIT_WINDOWFUNC */
000543  
000544  /*
000545  ** If the memory cell contains a value that must be freed by
000546  ** invoking the external callback in Mem.xDel, then this routine
000547  ** will free that value.  It also sets Mem.flags to MEM_Null.
000548  **
000549  ** This is a helper routine for sqlite3VdbeMemSetNull() and
000550  ** for sqlite3VdbeMemRelease().  Use those other routines as the
000551  ** entry point for releasing Mem resources.
000552  */
000553  static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
000554    assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
000555    assert( VdbeMemDynamic(p) );
000556    if( p->flags&MEM_Agg ){
000557      sqlite3VdbeMemFinalize(p, p->u.pDef);
000558      assert( (p->flags & MEM_Agg)==0 );
000559      testcase( p->flags & MEM_Dyn );
000560    }
000561    if( p->flags&MEM_Dyn ){
000562      assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
000563      p->xDel((void *)p->z);
000564    }
000565    p->flags = MEM_Null;
000566  }
000567  
000568  /*
000569  ** Release memory held by the Mem p, both external memory cleared
000570  ** by p->xDel and memory in p->zMalloc.
000571  **
000572  ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
000573  ** the unusual case where there really is memory in p that needs
000574  ** to be freed.
000575  */
000576  static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
000577    if( VdbeMemDynamic(p) ){
000578      vdbeMemClearExternAndSetNull(p);
000579    }
000580    if( p->szMalloc ){
000581      sqlite3DbFreeNN(p->db, p->zMalloc);
000582      p->szMalloc = 0;
000583    }
000584    p->z = 0;
000585  }
000586  
000587  /*
000588  ** Release any memory resources held by the Mem.  Both the memory that is
000589  ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
000590  **
000591  ** Use this routine prior to clean up prior to abandoning a Mem, or to
000592  ** reset a Mem back to its minimum memory utilization.
000593  **
000594  ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
000595  ** prior to inserting new content into the Mem.
000596  */
000597  void sqlite3VdbeMemRelease(Mem *p){
000598    assert( sqlite3VdbeCheckMemInvariants(p) );
000599    if( VdbeMemDynamic(p) || p->szMalloc ){
000600      vdbeMemClear(p);
000601    }
000602  }
000603  
000604  /* Like sqlite3VdbeMemRelease() but faster for cases where we
000605  ** know in advance that the Mem is not MEM_Dyn or MEM_Agg.
000606  */
000607  void sqlite3VdbeMemReleaseMalloc(Mem *p){
000608    assert( !VdbeMemDynamic(p) );
000609    if( p->szMalloc ) vdbeMemClear(p);
000610  }
000611  
000612  /*
000613  ** Return some kind of integer value which is the best we can do
000614  ** at representing the value that *pMem describes as an integer.
000615  ** If pMem is an integer, then the value is exact.  If pMem is
000616  ** a floating-point then the value returned is the integer part.
000617  ** If pMem is a string or blob, then we make an attempt to convert
000618  ** it into an integer and return that.  If pMem represents an
000619  ** an SQL-NULL value, return 0.
000620  **
000621  ** If pMem represents a string value, its encoding might be changed.
000622  */
000623  static SQLITE_NOINLINE i64 memIntValue(const Mem *pMem){
000624    i64 value = 0;
000625    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
000626    return value;
000627  }
000628  i64 sqlite3VdbeIntValue(const Mem *pMem){
000629    int flags;
000630    assert( pMem!=0 );
000631    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
000632    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
000633    flags = pMem->flags;
000634    if( flags & (MEM_Int|MEM_IntReal) ){
000635      testcase( flags & MEM_IntReal );
000636      return pMem->u.i;
000637    }else if( flags & MEM_Real ){
000638      return sqlite3RealToI64(pMem->u.r);
000639    }else if( (flags & (MEM_Str|MEM_Blob))!=0 && pMem->z!=0 ){
000640      return memIntValue(pMem);
000641    }else{
000642      return 0;
000643    }
000644  }
000645  
000646  /*
000647  ** Return the best representation of pMem that we can get into a
000648  ** double.  If pMem is already a double or an integer, return its
000649  ** value.  If it is a string or blob, try to convert it to a double.
000650  ** If it is a NULL, return 0.0.
000651  */
000652  static SQLITE_NOINLINE double memRealValue(Mem *pMem){
000653    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
000654    double val = (double)0;
000655    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
000656    return val;
000657  }
000658  double sqlite3VdbeRealValue(Mem *pMem){
000659    assert( pMem!=0 );
000660    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
000661    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
000662    if( pMem->flags & MEM_Real ){
000663      return pMem->u.r;
000664    }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
000665      testcase( pMem->flags & MEM_IntReal );
000666      return (double)pMem->u.i;
000667    }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
000668      return memRealValue(pMem);
000669    }else{
000670      /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
000671      return (double)0;
000672    }
000673  }
000674  
000675  /*
000676  ** Return 1 if pMem represents true, and return 0 if pMem represents false.
000677  ** Return the value ifNull if pMem is NULL.  
000678  */
000679  int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
000680    testcase( pMem->flags & MEM_IntReal );
000681    if( pMem->flags & (MEM_Int|MEM_IntReal) ) return pMem->u.i!=0;
000682    if( pMem->flags & MEM_Null ) return ifNull;
000683    return sqlite3VdbeRealValue(pMem)!=0.0;
000684  }
000685  
000686  /*
000687  ** The MEM structure is already a MEM_Real or MEM_IntReal. Try to 
000688  ** make it a MEM_Int if we can.
000689  */
000690  void sqlite3VdbeIntegerAffinity(Mem *pMem){
000691    assert( pMem!=0 );
000692    assert( pMem->flags & (MEM_Real|MEM_IntReal) );
000693    assert( !sqlite3VdbeMemIsRowSet(pMem) );
000694    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
000695    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
000696  
000697    if( pMem->flags & MEM_IntReal ){
000698      MemSetTypeFlag(pMem, MEM_Int);
000699    }else{
000700      i64 ix = sqlite3RealToI64(pMem->u.r);
000701  
000702      /* Only mark the value as an integer if
000703      **
000704      **    (1) the round-trip conversion real->int->real is a no-op, and
000705      **    (2) The integer is neither the largest nor the smallest
000706      **        possible integer (ticket #3922)
000707      **
000708      ** The second and third terms in the following conditional enforces
000709      ** the second condition under the assumption that addition overflow causes
000710      ** values to wrap around.
000711      */
000712      if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
000713        pMem->u.i = ix;
000714        MemSetTypeFlag(pMem, MEM_Int);
000715      }
000716    }
000717  }
000718  
000719  /*
000720  ** Convert pMem to type integer.  Invalidate any prior representations.
000721  */
000722  int sqlite3VdbeMemIntegerify(Mem *pMem){
000723    assert( pMem!=0 );
000724    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
000725    assert( !sqlite3VdbeMemIsRowSet(pMem) );
000726    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
000727  
000728    pMem->u.i = sqlite3VdbeIntValue(pMem);
000729    MemSetTypeFlag(pMem, MEM_Int);
000730    return SQLITE_OK;
000731  }
000732  
000733  /*
000734  ** Convert pMem so that it is of type MEM_Real.
000735  ** Invalidate any prior representations.
000736  */
000737  int sqlite3VdbeMemRealify(Mem *pMem){
000738    assert( pMem!=0 );
000739    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
000740    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
000741  
000742    pMem->u.r = sqlite3VdbeRealValue(pMem);
000743    MemSetTypeFlag(pMem, MEM_Real);
000744    return SQLITE_OK;
000745  }
000746  
000747  /* Compare a floating point value to an integer.  Return true if the two
000748  ** values are the same within the precision of the floating point value.
000749  **
000750  ** This function assumes that i was obtained by assignment from r1.
000751  **
000752  ** For some versions of GCC on 32-bit machines, if you do the more obvious
000753  ** comparison of "r1==(double)i" you sometimes get an answer of false even
000754  ** though the r1 and (double)i values are bit-for-bit the same.
000755  */
000756  int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
000757    double r2 = (double)i;
000758    return r1==0.0
000759        || (memcmp(&r1, &r2, sizeof(r1))==0
000760            && i >= -2251799813685248LL && i < 2251799813685248LL);
000761  }
000762  
000763  /* Convert a floating point value to its closest integer.  Do so in
000764  ** a way that avoids 'outside the range of representable values' warnings
000765  ** from UBSAN.
000766  */
000767  i64 sqlite3RealToI64(double r){
000768    if( r<-9223372036854774784.0 ) return SMALLEST_INT64;
000769    if( r>+9223372036854774784.0 ) return LARGEST_INT64;
000770    return (i64)r;
000771  }
000772  
000773  /*
000774  ** Convert pMem so that it has type MEM_Real or MEM_Int.
000775  ** Invalidate any prior representations.
000776  **
000777  ** Every effort is made to force the conversion, even if the input
000778  ** is a string that does not look completely like a number.  Convert
000779  ** as much of the string as we can and ignore the rest.
000780  */
000781  int sqlite3VdbeMemNumerify(Mem *pMem){
000782    assert( pMem!=0 );
000783    testcase( pMem->flags & MEM_Int );
000784    testcase( pMem->flags & MEM_Real );
000785    testcase( pMem->flags & MEM_IntReal );
000786    testcase( pMem->flags & MEM_Null );
000787    if( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))==0 ){
000788      int rc;
000789      sqlite3_int64 ix;
000790      assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
000791      assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
000792      rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
000793      if( ((rc==0 || rc==1) && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1)
000794       || sqlite3RealSameAsInt(pMem->u.r, (ix = sqlite3RealToI64(pMem->u.r)))
000795      ){
000796        pMem->u.i = ix;
000797        MemSetTypeFlag(pMem, MEM_Int);
000798      }else{
000799        MemSetTypeFlag(pMem, MEM_Real);
000800      }
000801    }
000802    assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))!=0 );
000803    pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
000804    return SQLITE_OK;
000805  }
000806  
000807  /*
000808  ** Cast the datatype of the value in pMem according to the affinity
000809  ** "aff".  Casting is different from applying affinity in that a cast
000810  ** is forced.  In other words, the value is converted into the desired
000811  ** affinity even if that results in loss of data.  This routine is
000812  ** used (for example) to implement the SQL "cast()" operator.
000813  */
000814  int sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
000815    if( pMem->flags & MEM_Null ) return SQLITE_OK;
000816    switch( aff ){
000817      case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
000818        if( (pMem->flags & MEM_Blob)==0 ){
000819          sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
000820          assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
000821          if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
000822        }else{
000823          pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
000824        }
000825        break;
000826      }
000827      case SQLITE_AFF_NUMERIC: {
000828        sqlite3VdbeMemNumerify(pMem);
000829        break;
000830      }
000831      case SQLITE_AFF_INTEGER: {
000832        sqlite3VdbeMemIntegerify(pMem);
000833        break;
000834      }
000835      case SQLITE_AFF_REAL: {
000836        sqlite3VdbeMemRealify(pMem);
000837        break;
000838      }
000839      default: {
000840        int rc;
000841        assert( aff==SQLITE_AFF_TEXT );
000842        assert( MEM_Str==(MEM_Blob>>3) );
000843        pMem->flags |= (pMem->flags&MEM_Blob)>>3;
000844        sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
000845        assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
000846        pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero);
000847        if( encoding!=SQLITE_UTF8 ) pMem->n &= ~1;
000848        rc = sqlite3VdbeChangeEncoding(pMem, encoding);
000849        if( rc ) return rc;
000850        sqlite3VdbeMemZeroTerminateIfAble(pMem);
000851      }
000852    }
000853    return SQLITE_OK;
000854  }
000855  
000856  /*
000857  ** Initialize bulk memory to be a consistent Mem object.
000858  **
000859  ** The minimum amount of initialization feasible is performed.
000860  */
000861  void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
000862    assert( (flags & ~MEM_TypeMask)==0 );
000863    pMem->flags = flags;
000864    pMem->db = db;
000865    pMem->szMalloc = 0;
000866  }
000867  
000868  
000869  /*
000870  ** Delete any previous value and set the value stored in *pMem to NULL.
000871  **
000872  ** This routine calls the Mem.xDel destructor to dispose of values that
000873  ** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
000874  ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
000875  ** routine to invoke the destructor and deallocates Mem.zMalloc.
000876  **
000877  ** Use this routine to reset the Mem prior to insert a new value.
000878  **
000879  ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
000880  */
000881  void sqlite3VdbeMemSetNull(Mem *pMem){
000882    if( VdbeMemDynamic(pMem) ){
000883      vdbeMemClearExternAndSetNull(pMem);
000884    }else{
000885      pMem->flags = MEM_Null;
000886    }
000887  }
000888  void sqlite3ValueSetNull(sqlite3_value *p){
000889    sqlite3VdbeMemSetNull((Mem*)p); 
000890  }
000891  
000892  /*
000893  ** Delete any previous value and set the value to be a BLOB of length
000894  ** n containing all zeros.
000895  */
000896  #ifndef SQLITE_OMIT_INCRBLOB
000897  void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
000898    sqlite3VdbeMemRelease(pMem);
000899    pMem->flags = MEM_Blob|MEM_Zero;
000900    pMem->n = 0;
000901    if( n<0 ) n = 0;
000902    pMem->u.nZero = n;
000903    pMem->enc = SQLITE_UTF8;
000904    pMem->z = 0;
000905  }
000906  #else
000907  int sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
000908    int nByte = n>0?n:1;
000909    if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
000910      return SQLITE_NOMEM_BKPT;
000911    }
000912    assert( pMem->z!=0 );
000913    assert( sqlite3DbMallocSize(pMem->db, pMem->z)>=nByte );
000914    memset(pMem->z, 0, nByte);
000915    pMem->n = n>0?n:0;
000916    pMem->flags = MEM_Blob;
000917    pMem->enc = SQLITE_UTF8;
000918    return SQLITE_OK;
000919  }
000920  #endif
000921  
000922  /*
000923  ** The pMem is known to contain content that needs to be destroyed prior
000924  ** to a value change.  So invoke the destructor, then set the value to
000925  ** a 64-bit integer.
000926  */
000927  static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
000928    sqlite3VdbeMemSetNull(pMem);
000929    pMem->u.i = val;
000930    pMem->flags = MEM_Int;
000931  }
000932  
000933  /*
000934  ** Delete any previous value and set the value stored in *pMem to val,
000935  ** manifest type INTEGER.
000936  */
000937  void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
000938    if( VdbeMemDynamic(pMem) ){
000939      vdbeReleaseAndSetInt64(pMem, val);
000940    }else{
000941      pMem->u.i = val;
000942      pMem->flags = MEM_Int;
000943    }
000944  }
000945  
000946  /*
000947  ** Set the iIdx'th entry of array aMem[] to contain integer value val.
000948  */
000949  void sqlite3MemSetArrayInt64(sqlite3_value *aMem, int iIdx, i64 val){
000950    sqlite3VdbeMemSetInt64(&aMem[iIdx], val);
000951  }
000952  
000953  /* A no-op destructor */
000954  void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
000955  
000956  /*
000957  ** Set the value stored in *pMem should already be a NULL.
000958  ** Also store a pointer to go with it.
000959  */
000960  void sqlite3VdbeMemSetPointer(
000961    Mem *pMem,
000962    void *pPtr,
000963    const char *zPType,
000964    void (*xDestructor)(void*)
000965  ){
000966    assert( pMem->flags==MEM_Null );
000967    vdbeMemClear(pMem);
000968    pMem->u.zPType = zPType ? zPType : "";
000969    pMem->z = pPtr;
000970    pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
000971    pMem->eSubtype = 'p';
000972    pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
000973  }
000974  
000975  #ifndef SQLITE_OMIT_FLOATING_POINT
000976  /*
000977  ** Delete any previous value and set the value stored in *pMem to val,
000978  ** manifest type REAL.
000979  */
000980  void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
000981    sqlite3VdbeMemSetNull(pMem);
000982    if( !sqlite3IsNaN(val) ){
000983      pMem->u.r = val;
000984      pMem->flags = MEM_Real;
000985    }
000986  }
000987  #endif
000988  
000989  #ifdef SQLITE_DEBUG
000990  /*
000991  ** Return true if the Mem holds a RowSet object.  This routine is intended
000992  ** for use inside of assert() statements.
000993  */
000994  int sqlite3VdbeMemIsRowSet(const Mem *pMem){
000995    return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)
000996           && pMem->xDel==sqlite3RowSetDelete;
000997  }
000998  #endif
000999  
001000  /*
001001  ** Delete any previous value and set the value of pMem to be an
001002  ** empty boolean index.
001003  **
001004  ** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation
001005  ** error occurs.
001006  */
001007  int sqlite3VdbeMemSetRowSet(Mem *pMem){
001008    sqlite3 *db = pMem->db;
001009    RowSet *p;
001010    assert( db!=0 );
001011    assert( !sqlite3VdbeMemIsRowSet(pMem) );
001012    sqlite3VdbeMemRelease(pMem);
001013    p = sqlite3RowSetInit(db);
001014    if( p==0 ) return SQLITE_NOMEM;
001015    pMem->z = (char*)p;
001016    pMem->flags = MEM_Blob|MEM_Dyn;
001017    pMem->xDel = sqlite3RowSetDelete;
001018    return SQLITE_OK;
001019  }
001020  
001021  /*
001022  ** Return true if the Mem object contains a TEXT or BLOB that is
001023  ** too large - whose size exceeds SQLITE_MAX_LENGTH.
001024  */
001025  int sqlite3VdbeMemTooBig(Mem *p){
001026    assert( p->db!=0 );
001027    if( p->flags & (MEM_Str|MEM_Blob) ){
001028      int n = p->n;
001029      if( p->flags & MEM_Zero ){
001030        n += p->u.nZero;
001031      }
001032      return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
001033    }
001034    return 0; 
001035  }
001036  
001037  #ifdef SQLITE_DEBUG
001038  /*
001039  ** This routine prepares a memory cell for modification by breaking
001040  ** its link to a shallow copy and by marking any current shallow
001041  ** copies of this cell as invalid.
001042  **
001043  ** This is used for testing and debugging only - to help ensure that shallow
001044  ** copies (created by OP_SCopy) are not misused.
001045  */
001046  void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
001047    int i;
001048    Mem *pX;
001049    for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){
001050      if( pX->pScopyFrom==pMem ){
001051        u16 mFlags;
001052        if( pVdbe->db->flags & SQLITE_VdbeTrace ){
001053          sqlite3DebugPrintf("Invalidate R[%d] due to change in R[%d]\n",
001054            (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem));
001055        }
001056        /* If pX is marked as a shallow copy of pMem, then try to verify that
001057        ** no significant changes have been made to pX since the OP_SCopy.
001058        ** A significant change would indicated a missed call to this
001059        ** function for pX.  Minor changes, such as adding or removing a
001060        ** dual type, are allowed, as long as the underlying value is the
001061        ** same. */
001062        mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
001063        assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i );
001064        
001065        /* pMem is the register that is changing.  But also mark pX as
001066        ** undefined so that we can quickly detect the shallow-copy error */
001067        pX->flags = MEM_Undefined;
001068        pX->pScopyFrom = 0;
001069      }
001070    }
001071    pMem->pScopyFrom = 0;
001072  }
001073  #endif /* SQLITE_DEBUG */
001074  
001075  /*
001076  ** Make an shallow copy of pFrom into pTo.  Prior contents of
001077  ** pTo are freed.  The pFrom->z field is not duplicated.  If
001078  ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
001079  ** and flags gets srcType (either MEM_Ephem or MEM_Static).
001080  */
001081  static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
001082    vdbeMemClearExternAndSetNull(pTo);
001083    assert( !VdbeMemDynamic(pTo) );
001084    sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
001085  }
001086  void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
001087    assert( !sqlite3VdbeMemIsRowSet(pFrom) );
001088    assert( pTo->db==pFrom->db );
001089    if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
001090    memcpy(pTo, pFrom, MEMCELLSIZE);
001091    if( (pFrom->flags&MEM_Static)==0 ){
001092      pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
001093      assert( srcType==MEM_Ephem || srcType==MEM_Static );
001094      pTo->flags |= srcType;
001095    }
001096  }
001097  
001098  /*
001099  ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
001100  ** freed before the copy is made.
001101  */
001102  int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
001103    int rc = SQLITE_OK;
001104  
001105    assert( !sqlite3VdbeMemIsRowSet(pFrom) );
001106    if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
001107    memcpy(pTo, pFrom, MEMCELLSIZE);
001108    pTo->flags &= ~MEM_Dyn;
001109    if( pTo->flags&(MEM_Str|MEM_Blob) ){
001110      if( 0==(pFrom->flags&MEM_Static) ){
001111        pTo->flags |= MEM_Ephem;
001112        rc = sqlite3VdbeMemMakeWriteable(pTo);
001113      }
001114    }
001115  
001116    return rc;
001117  }
001118  
001119  /*
001120  ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
001121  ** freed. If pFrom contains ephemeral data, a copy is made.
001122  **
001123  ** pFrom contains an SQL NULL when this routine returns.
001124  */
001125  void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
001126    assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
001127    assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
001128    assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
001129  
001130    sqlite3VdbeMemRelease(pTo);
001131    memcpy(pTo, pFrom, sizeof(Mem));
001132    pFrom->flags = MEM_Null;
001133    pFrom->szMalloc = 0;
001134  }
001135  
001136  /*
001137  ** Change the value of a Mem to be a string or a BLOB.
001138  **
001139  ** The memory management strategy depends on the value of the xDel
001140  ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
001141  ** string is copied into a (possibly existing) buffer managed by the 
001142  ** Mem structure. Otherwise, any existing buffer is freed and the
001143  ** pointer copied.
001144  **
001145  ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
001146  ** size limit) then no memory allocation occurs.  If the string can be
001147  ** stored without allocating memory, then it is.  If a memory allocation
001148  ** is required to store the string, then value of pMem is unchanged.  In
001149  ** either case, SQLITE_TOOBIG is returned.
001150  **
001151  ** The "enc" parameter is the text encoding for the string, or zero
001152  ** to store a blob.
001153  **
001154  ** If n is negative, then the string consists of all bytes up to but
001155  ** excluding the first zero character.  The n parameter must be
001156  ** non-negative for blobs.
001157  */
001158  int sqlite3VdbeMemSetStr(
001159    Mem *pMem,          /* Memory cell to set to string value */
001160    const char *z,      /* String pointer */
001161    i64 n,              /* Bytes in string, or negative */
001162    u8 enc,             /* Encoding of z.  0 for BLOBs */
001163    void (*xDel)(void*) /* Destructor function */
001164  ){
001165    i64 nByte = n;      /* New value for pMem->n */
001166    int iLimit;         /* Maximum allowed string or blob size */
001167    u16 flags;          /* New value for pMem->flags */
001168  
001169    assert( pMem!=0 );
001170    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
001171    assert( !sqlite3VdbeMemIsRowSet(pMem) );
001172    assert( enc!=0 || n>=0 );
001173  
001174    /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
001175    if( !z ){
001176      sqlite3VdbeMemSetNull(pMem);
001177      return SQLITE_OK;
001178    }
001179  
001180    if( pMem->db ){
001181      iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
001182    }else{
001183      iLimit = SQLITE_MAX_LENGTH;
001184    }
001185    if( nByte<0 ){
001186      assert( enc!=0 );
001187      if( enc==SQLITE_UTF8 ){
001188        nByte = strlen(z);
001189      }else{
001190        for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
001191      }
001192      flags= MEM_Str|MEM_Term;
001193    }else if( enc==0 ){
001194      flags = MEM_Blob;
001195      enc = SQLITE_UTF8;
001196    }else{
001197      flags = MEM_Str;
001198    }
001199    if( nByte>iLimit ){
001200      if( xDel && xDel!=SQLITE_TRANSIENT ){
001201        if( xDel==SQLITE_DYNAMIC ){
001202          sqlite3DbFree(pMem->db, (void*)z);
001203        }else{
001204          xDel((void*)z);
001205        }
001206      }
001207      sqlite3VdbeMemSetNull(pMem);
001208      return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
001209    }
001210  
001211    /* The following block sets the new values of Mem.z and Mem.xDel. It
001212    ** also sets a flag in local variable "flags" to indicate the memory
001213    ** management (one of MEM_Dyn or MEM_Static).
001214    */
001215    if( xDel==SQLITE_TRANSIENT ){
001216      i64 nAlloc = nByte;
001217      if( flags&MEM_Term ){
001218        nAlloc += (enc==SQLITE_UTF8?1:2);
001219      }
001220      testcase( nAlloc==0 );
001221      testcase( nAlloc==31 );
001222      testcase( nAlloc==32 );
001223      if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){
001224        return SQLITE_NOMEM_BKPT;
001225      }
001226      memcpy(pMem->z, z, nAlloc);
001227    }else{
001228      sqlite3VdbeMemRelease(pMem);
001229      pMem->z = (char *)z;
001230      if( xDel==SQLITE_DYNAMIC ){
001231        pMem->zMalloc = pMem->z;
001232        pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
001233      }else{
001234        pMem->xDel = xDel;
001235        flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
001236      }
001237    }
001238  
001239    pMem->n = (int)(nByte & 0x7fffffff);
001240    pMem->flags = flags;
001241    pMem->enc = enc;
001242  
001243  #ifndef SQLITE_OMIT_UTF16
001244    if( enc>SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
001245      return SQLITE_NOMEM_BKPT;
001246    }
001247  #endif
001248  
001249  
001250    return SQLITE_OK;
001251  }
001252  
001253  /*
001254  ** Move data out of a btree key or data field and into a Mem structure.
001255  ** The data is payload from the entry that pCur is currently pointing
001256  ** to.  offset and amt determine what portion of the data or key to retrieve.
001257  ** The result is written into the pMem element.
001258  **
001259  ** The pMem object must have been initialized.  This routine will use
001260  ** pMem->zMalloc to hold the content from the btree, if possible.  New
001261  ** pMem->zMalloc space will be allocated if necessary.  The calling routine
001262  ** is responsible for making sure that the pMem object is eventually
001263  ** destroyed.
001264  **
001265  ** If this routine fails for any reason (malloc returns NULL or unable
001266  ** to read from the disk) then the pMem is left in an inconsistent state.
001267  */
001268  int sqlite3VdbeMemFromBtree(
001269    BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
001270    u32 offset,       /* Offset from the start of data to return bytes from. */
001271    u32 amt,          /* Number of bytes to return. */
001272    Mem *pMem         /* OUT: Return data in this Mem structure. */
001273  ){
001274    int rc;
001275    pMem->flags = MEM_Null;
001276    if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){
001277      return SQLITE_CORRUPT_BKPT;
001278    }
001279    if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
001280      rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
001281      if( rc==SQLITE_OK ){
001282        pMem->z[amt] = 0;   /* Overrun area used when reading malformed records */
001283        pMem->flags = MEM_Blob;
001284        pMem->n = (int)amt;
001285      }else{
001286        sqlite3VdbeMemRelease(pMem);
001287      }
001288    }
001289    return rc;
001290  }
001291  int sqlite3VdbeMemFromBtreeZeroOffset(
001292    BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
001293    u32 amt,          /* Number of bytes to return. */
001294    Mem *pMem         /* OUT: Return data in this Mem structure. */
001295  ){
001296    u32 available = 0;  /* Number of bytes available on the local btree page */
001297    int rc = SQLITE_OK; /* Return code */
001298  
001299    assert( sqlite3BtreeCursorIsValid(pCur) );
001300    assert( !VdbeMemDynamic(pMem) );
001301  
001302    /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
001303    ** that both the BtShared and database handle mutexes are held. */
001304    assert( !sqlite3VdbeMemIsRowSet(pMem) );
001305    pMem->z = (char *)sqlite3BtreePayloadFetch(pCur, &available);
001306    assert( pMem->z!=0 );
001307  
001308    if( amt<=available ){
001309      pMem->flags = MEM_Blob|MEM_Ephem;
001310      pMem->n = (int)amt;
001311    }else{
001312      rc = sqlite3VdbeMemFromBtree(pCur, 0, amt, pMem);
001313    }
001314  
001315    return rc;
001316  }
001317  
001318  /*
001319  ** The pVal argument is known to be a value other than NULL.
001320  ** Convert it into a string with encoding enc and return a pointer
001321  ** to a zero-terminated version of that string.
001322  */
001323  static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
001324    assert( pVal!=0 );
001325    assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
001326    assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
001327    assert( !sqlite3VdbeMemIsRowSet(pVal) );
001328    assert( (pVal->flags & (MEM_Null))==0 );
001329    if( pVal->flags & (MEM_Blob|MEM_Str) ){
001330      if( ExpandBlob(pVal) ) return 0;
001331      pVal->flags |= MEM_Str;
001332      if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
001333        sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
001334      }
001335      if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
001336        assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
001337        if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
001338          return 0;
001339        }
001340      }
001341      sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
001342    }else{
001343      sqlite3VdbeMemStringify(pVal, enc, 0);
001344      assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
001345    }
001346    assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
001347                || pVal->db->mallocFailed );
001348    if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
001349      assert( sqlite3VdbeMemValidStrRep(pVal) );
001350      return pVal->z;
001351    }else{
001352      return 0;
001353    }
001354  }
001355  
001356  /* This function is only available internally, it is not part of the
001357  ** external API. It works in a similar way to sqlite3_value_text(),
001358  ** except the data returned is in the encoding specified by the second
001359  ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
001360  ** SQLITE_UTF8.
001361  **
001362  ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
001363  ** If that is the case, then the result must be aligned on an even byte
001364  ** boundary.
001365  */
001366  const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
001367    if( !pVal ) return 0;
001368    assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
001369    assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
001370    assert( !sqlite3VdbeMemIsRowSet(pVal) );
001371    if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
001372      assert( sqlite3VdbeMemValidStrRep(pVal) );
001373      return pVal->z;
001374    }
001375    if( pVal->flags&MEM_Null ){
001376      return 0;
001377    }
001378    return valueToText(pVal, enc);
001379  }
001380  
001381  /* Return true if sqlit3_value object pVal is a string or blob value
001382  ** that uses the destructor specified in the second argument.
001383  **
001384  ** TODO:  Maybe someday promote this interface into a published API so
001385  ** that third-party extensions can get access to it?
001386  */
001387  int sqlite3ValueIsOfClass(const sqlite3_value *pVal, void(*xFree)(void*)){
001388    if( ALWAYS(pVal!=0)
001389     && ALWAYS((pVal->flags & (MEM_Str|MEM_Blob))!=0)
001390     && (pVal->flags & MEM_Dyn)!=0
001391     && pVal->xDel==xFree
001392    ){
001393      return 1;
001394    }else{
001395      return 0;
001396    }
001397  }
001398  
001399  /*
001400  ** Create a new sqlite3_value object.
001401  */
001402  sqlite3_value *sqlite3ValueNew(sqlite3 *db){
001403    Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
001404    if( p ){
001405      p->flags = MEM_Null;
001406      p->db = db;
001407    }
001408    return p;
001409  }
001410  
001411  /*
001412  ** Context object passed by sqlite3Stat4ProbeSetValue() through to 
001413  ** valueNew(). See comments above valueNew() for details.
001414  */
001415  struct ValueNewStat4Ctx {
001416    Parse *pParse;
001417    Index *pIdx;
001418    UnpackedRecord **ppRec;
001419    int iVal;
001420  };
001421  
001422  /*
001423  ** Allocate and return a pointer to a new sqlite3_value object. If
001424  ** the second argument to this function is NULL, the object is allocated
001425  ** by calling sqlite3ValueNew().
001426  **
001427  ** Otherwise, if the second argument is non-zero, then this function is 
001428  ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
001429  ** already been allocated, allocate the UnpackedRecord structure that 
001430  ** that function will return to its caller here. Then return a pointer to
001431  ** an sqlite3_value within the UnpackedRecord.a[] array.
001432  */
001433  static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
001434  #ifdef SQLITE_ENABLE_STAT4
001435    if( p ){
001436      UnpackedRecord *pRec = p->ppRec[0];
001437  
001438      if( pRec==0 ){
001439        Index *pIdx = p->pIdx;      /* Index being probed */
001440        int nByte;                  /* Bytes of space to allocate */
001441        int i;                      /* Counter variable */
001442        int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
001443    
001444        nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
001445        pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
001446        if( pRec ){
001447          pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
001448          if( pRec->pKeyInfo ){
001449            assert( pRec->pKeyInfo->nAllField==nCol );
001450            assert( pRec->pKeyInfo->enc==ENC(db) );
001451            pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
001452            for(i=0; i<nCol; i++){
001453              pRec->aMem[i].flags = MEM_Null;
001454              pRec->aMem[i].db = db;
001455            }
001456          }else{
001457            sqlite3DbFreeNN(db, pRec);
001458            pRec = 0;
001459          }
001460        }
001461        if( pRec==0 ) return 0;
001462        p->ppRec[0] = pRec;
001463      }
001464    
001465      pRec->nField = p->iVal+1;
001466      sqlite3VdbeMemSetNull(&pRec->aMem[p->iVal]);
001467      return &pRec->aMem[p->iVal];
001468    }
001469  #else
001470    UNUSED_PARAMETER(p);
001471  #endif /* defined(SQLITE_ENABLE_STAT4) */
001472    return sqlite3ValueNew(db);
001473  }
001474  
001475  /*
001476  ** The expression object indicated by the second argument is guaranteed
001477  ** to be a scalar SQL function. If
001478  **
001479  **   * all function arguments are SQL literals,
001480  **   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
001481  **   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
001482  **
001483  ** then this routine attempts to invoke the SQL function. Assuming no
001484  ** error occurs, output parameter (*ppVal) is set to point to a value 
001485  ** object containing the result before returning SQLITE_OK.
001486  **
001487  ** Affinity aff is applied to the result of the function before returning.
001488  ** If the result is a text value, the sqlite3_value object uses encoding 
001489  ** enc.
001490  **
001491  ** If the conditions above are not met, this function returns SQLITE_OK
001492  ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
001493  ** NULL and an SQLite error code returned.
001494  */
001495  #ifdef SQLITE_ENABLE_STAT4
001496  static int valueFromFunction(
001497    sqlite3 *db,                    /* The database connection */
001498    const Expr *p,                  /* The expression to evaluate */
001499    u8 enc,                         /* Encoding to use */
001500    u8 aff,                         /* Affinity to use */
001501    sqlite3_value **ppVal,          /* Write the new value here */
001502    struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
001503  ){
001504    sqlite3_context ctx;            /* Context object for function invocation */
001505    sqlite3_value **apVal = 0;      /* Function arguments */
001506    int nVal = 0;                   /* Size of apVal[] array */
001507    FuncDef *pFunc = 0;             /* Function definition */
001508    sqlite3_value *pVal = 0;        /* New value */
001509    int rc = SQLITE_OK;             /* Return code */
001510    ExprList *pList = 0;            /* Function arguments */
001511    int i;                          /* Iterator variable */
001512  
001513    assert( pCtx!=0 );
001514    assert( (p->flags & EP_TokenOnly)==0 );
001515    assert( ExprUseXList(p) );
001516    pList = p->x.pList;
001517    if( pList ) nVal = pList->nExpr;
001518    assert( !ExprHasProperty(p, EP_IntValue) );
001519    pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
001520  #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
001521    if( pFunc==0 ) return SQLITE_OK;
001522  #endif
001523    assert( pFunc );
001524    if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
001525     || (pFunc->funcFlags & (SQLITE_FUNC_NEEDCOLL|SQLITE_FUNC_RUNONLY))!=0
001526    ){
001527      return SQLITE_OK;
001528    }
001529  
001530    if( pList ){
001531      apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
001532      if( apVal==0 ){
001533        rc = SQLITE_NOMEM_BKPT;
001534        goto value_from_function_out;
001535      }
001536      for(i=0; i<nVal; i++){
001537        rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
001538        if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
001539      }
001540    }
001541  
001542    pVal = valueNew(db, pCtx);
001543    if( pVal==0 ){
001544      rc = SQLITE_NOMEM_BKPT;
001545      goto value_from_function_out;
001546    }
001547  
001548    memset(&ctx, 0, sizeof(ctx));
001549    ctx.pOut = pVal;
001550    ctx.pFunc = pFunc;
001551    ctx.enc = ENC(db);
001552    pFunc->xSFunc(&ctx, nVal, apVal);
001553    if( ctx.isError ){
001554      rc = ctx.isError;
001555      sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
001556    }else{
001557      sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
001558      assert( rc==SQLITE_OK );
001559      rc = sqlite3VdbeChangeEncoding(pVal, enc);
001560      if( NEVER(rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal)) ){
001561        rc = SQLITE_TOOBIG;
001562        pCtx->pParse->nErr++;
001563      }
001564    }
001565  
001566   value_from_function_out:
001567    if( rc!=SQLITE_OK ){
001568      pVal = 0;
001569      pCtx->pParse->rc = rc;
001570    }
001571    if( apVal ){
001572      for(i=0; i<nVal; i++){
001573        sqlite3ValueFree(apVal[i]);
001574      }
001575      sqlite3DbFreeNN(db, apVal);
001576    }
001577  
001578    *ppVal = pVal;
001579    return rc;
001580  }
001581  #else
001582  # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
001583  #endif /* defined(SQLITE_ENABLE_STAT4) */
001584  
001585  /*
001586  ** Extract a value from the supplied expression in the manner described
001587  ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
001588  ** using valueNew().
001589  **
001590  ** If pCtx is NULL and an error occurs after the sqlite3_value object
001591  ** has been allocated, it is freed before returning. Or, if pCtx is not
001592  ** NULL, it is assumed that the caller will free any allocated object
001593  ** in all cases.
001594  */
001595  static int valueFromExpr(
001596    sqlite3 *db,                    /* The database connection */
001597    const Expr *pExpr,              /* The expression to evaluate */
001598    u8 enc,                         /* Encoding to use */
001599    u8 affinity,                    /* Affinity to use */
001600    sqlite3_value **ppVal,          /* Write the new value here */
001601    struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
001602  ){
001603    int op;
001604    char *zVal = 0;
001605    sqlite3_value *pVal = 0;
001606    int negInt = 1;
001607    const char *zNeg = "";
001608    int rc = SQLITE_OK;
001609  
001610    assert( pExpr!=0 );
001611    while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
001612    if( op==TK_REGISTER ) op = pExpr->op2;
001613  
001614    /* Compressed expressions only appear when parsing the DEFAULT clause
001615    ** on a table column definition, and hence only when pCtx==0.  This
001616    ** check ensures that an EP_TokenOnly expression is never passed down
001617    ** into valueFromFunction(). */
001618    assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
001619  
001620    if( op==TK_CAST ){
001621      u8 aff;
001622      assert( !ExprHasProperty(pExpr, EP_IntValue) );
001623      aff = sqlite3AffinityType(pExpr->u.zToken,0);
001624      rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
001625      testcase( rc!=SQLITE_OK );
001626      if( *ppVal ){
001627  #ifdef SQLITE_ENABLE_STAT4
001628        rc = ExpandBlob(*ppVal);
001629  #else
001630        /* zero-blobs only come from functions, not literal values.  And
001631        ** functions are only processed under STAT4 */
001632        assert( (ppVal[0][0].flags & MEM_Zero)==0 );
001633  #endif
001634        sqlite3VdbeMemCast(*ppVal, aff, enc);
001635        sqlite3ValueApplyAffinity(*ppVal, affinity, enc);
001636      }
001637      return rc;
001638    }
001639  
001640    /* Handle negative integers in a single step.  This is needed in the
001641    ** case when the value is -9223372036854775808. Except - do not do this
001642    ** for hexadecimal literals.  */
001643    if( op==TK_UMINUS ){
001644      Expr *pLeft = pExpr->pLeft;
001645      if( (pLeft->op==TK_INTEGER || pLeft->op==TK_FLOAT) ){
001646        if( ExprHasProperty(pLeft, EP_IntValue)
001647         || pLeft->u.zToken[0]!='0' || (pLeft->u.zToken[1] & ~0x20)!='X'
001648        ){
001649          pExpr = pLeft;
001650          op = pExpr->op;
001651          negInt = -1;
001652          zNeg = "-";
001653        }
001654      }
001655    }
001656  
001657    if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
001658      pVal = valueNew(db, pCtx);
001659      if( pVal==0 ) goto no_mem;
001660      if( ExprHasProperty(pExpr, EP_IntValue) ){
001661        sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
001662      }else{
001663        i64 iVal;
001664        if( op==TK_INTEGER && 0==sqlite3DecOrHexToI64(pExpr->u.zToken, &iVal) ){
001665          sqlite3VdbeMemSetInt64(pVal, iVal*negInt);
001666        }else{
001667          zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
001668          if( zVal==0 ) goto no_mem;
001669          sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
001670        }
001671      }
001672      if( affinity==SQLITE_AFF_BLOB ){
001673        if( op==TK_FLOAT ){
001674          assert( pVal && pVal->z && pVal->flags==(MEM_Str|MEM_Term) );
001675          sqlite3AtoF(pVal->z, &pVal->u.r, pVal->n, SQLITE_UTF8);
001676          pVal->flags = MEM_Real;
001677        }else if( op==TK_INTEGER ){
001678          /* This case is required by -9223372036854775808 and other strings
001679          ** that look like integers but cannot be handled by the
001680          ** sqlite3DecOrHexToI64() call above.  */
001681          sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
001682        }
001683      }else{
001684        sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
001685      }
001686      assert( (pVal->flags & MEM_IntReal)==0 );
001687      if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){
001688        testcase( pVal->flags & MEM_Int );
001689        testcase( pVal->flags & MEM_Real );
001690        pVal->flags &= ~MEM_Str;
001691      }
001692      if( enc!=SQLITE_UTF8 ){
001693        rc = sqlite3VdbeChangeEncoding(pVal, enc);
001694      }
001695    }else if( op==TK_UMINUS ) {
001696      /* This branch happens for multiple negative signs.  Ex: -(-5) */
001697      if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx) 
001698       && pVal!=0
001699      ){
001700        sqlite3VdbeMemNumerify(pVal);
001701        if( pVal->flags & MEM_Real ){
001702          pVal->u.r = -pVal->u.r;
001703        }else if( pVal->u.i==SMALLEST_INT64 ){
001704  #ifndef SQLITE_OMIT_FLOATING_POINT
001705          pVal->u.r = -(double)SMALLEST_INT64;
001706  #else
001707          pVal->u.r = LARGEST_INT64;
001708  #endif
001709          MemSetTypeFlag(pVal, MEM_Real);
001710        }else{
001711          pVal->u.i = -pVal->u.i;
001712        }
001713        sqlite3ValueApplyAffinity(pVal, affinity, enc);
001714      }
001715    }else if( op==TK_NULL ){
001716      pVal = valueNew(db, pCtx);
001717      if( pVal==0 ) goto no_mem;
001718      sqlite3VdbeMemSetNull(pVal);
001719    }
001720  #ifndef SQLITE_OMIT_BLOB_LITERAL
001721    else if( op==TK_BLOB ){
001722      int nVal;
001723      assert( !ExprHasProperty(pExpr, EP_IntValue) );
001724      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
001725      assert( pExpr->u.zToken[1]=='\'' );
001726      pVal = valueNew(db, pCtx);
001727      if( !pVal ) goto no_mem;
001728      zVal = &pExpr->u.zToken[2];
001729      nVal = sqlite3Strlen30(zVal)-1;
001730      assert( zVal[nVal]=='\'' );
001731      sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
001732                           0, SQLITE_DYNAMIC);
001733    }
001734  #endif
001735  #ifdef SQLITE_ENABLE_STAT4
001736    else if( op==TK_FUNCTION && pCtx!=0 ){
001737      rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
001738    }
001739  #endif
001740    else if( op==TK_TRUEFALSE ){
001741      assert( !ExprHasProperty(pExpr, EP_IntValue) );
001742      pVal = valueNew(db, pCtx);
001743      if( pVal ){
001744        pVal->flags = MEM_Int;
001745        pVal->u.i = pExpr->u.zToken[4]==0;
001746        sqlite3ValueApplyAffinity(pVal, affinity, enc);
001747      }
001748    }
001749  
001750    *ppVal = pVal;
001751    return rc;
001752  
001753  no_mem:
001754  #ifdef SQLITE_ENABLE_STAT4
001755    if( pCtx==0 || NEVER(pCtx->pParse->nErr==0) )
001756  #endif
001757      sqlite3OomFault(db);
001758    sqlite3DbFree(db, zVal);
001759    assert( *ppVal==0 );
001760  #ifdef SQLITE_ENABLE_STAT4
001761    if( pCtx==0 ) sqlite3ValueFree(pVal);
001762  #else
001763    assert( pCtx==0 ); sqlite3ValueFree(pVal);
001764  #endif
001765    return SQLITE_NOMEM_BKPT;
001766  }
001767  
001768  /*
001769  ** Create a new sqlite3_value object, containing the value of pExpr.
001770  **
001771  ** This only works for very simple expressions that consist of one constant
001772  ** token (i.e. "5", "5.1", "'a string'"). If the expression can
001773  ** be converted directly into a value, then the value is allocated and
001774  ** a pointer written to *ppVal. The caller is responsible for deallocating
001775  ** the value by passing it to sqlite3ValueFree() later on. If the expression
001776  ** cannot be converted to a value, then *ppVal is set to NULL.
001777  */
001778  int sqlite3ValueFromExpr(
001779    sqlite3 *db,              /* The database connection */
001780    const Expr *pExpr,        /* The expression to evaluate */
001781    u8 enc,                   /* Encoding to use */
001782    u8 affinity,              /* Affinity to use */
001783    sqlite3_value **ppVal     /* Write the new value here */
001784  ){
001785    return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
001786  }
001787  
001788  #ifdef SQLITE_ENABLE_STAT4
001789  /*
001790  ** Attempt to extract a value from pExpr and use it to construct *ppVal.
001791  **
001792  ** If pAlloc is not NULL, then an UnpackedRecord object is created for
001793  ** pAlloc if one does not exist and the new value is added to the
001794  ** UnpackedRecord object.
001795  **
001796  ** A value is extracted in the following cases:
001797  **
001798  **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
001799  **
001800  **  * The expression is a bound variable, and this is a reprepare, or
001801  **
001802  **  * The expression is a literal value.
001803  **
001804  ** On success, *ppVal is made to point to the extracted value.  The caller
001805  ** is responsible for ensuring that the value is eventually freed.
001806  */
001807  static int stat4ValueFromExpr(
001808    Parse *pParse,                  /* Parse context */
001809    Expr *pExpr,                    /* The expression to extract a value from */
001810    u8 affinity,                    /* Affinity to use */
001811    struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
001812    sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
001813  ){
001814    int rc = SQLITE_OK;
001815    sqlite3_value *pVal = 0;
001816    sqlite3 *db = pParse->db;
001817  
001818    /* Skip over any TK_COLLATE nodes */
001819    pExpr = sqlite3ExprSkipCollate(pExpr);
001820  
001821    assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
001822    if( !pExpr ){
001823      pVal = valueNew(db, pAlloc);
001824      if( pVal ){
001825        sqlite3VdbeMemSetNull((Mem*)pVal);
001826      }
001827    }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
001828      Vdbe *v;
001829      int iBindVar = pExpr->iColumn;
001830      sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
001831      if( (v = pParse->pReprepare)!=0 ){
001832        pVal = valueNew(db, pAlloc);
001833        if( pVal ){
001834          rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
001835          sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
001836          pVal->db = pParse->db;
001837        }
001838      }
001839    }else{
001840      rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
001841    }
001842  
001843    assert( pVal==0 || pVal->db==db );
001844    *ppVal = pVal;
001845    return rc;
001846  }
001847  
001848  /*
001849  ** This function is used to allocate and populate UnpackedRecord 
001850  ** structures intended to be compared against sample index keys stored 
001851  ** in the sqlite_stat4 table.
001852  **
001853  ** A single call to this function populates zero or more fields of the
001854  ** record starting with field iVal (fields are numbered from left to
001855  ** right starting with 0). A single field is populated if:
001856  **
001857  **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
001858  **
001859  **  * The expression is a bound variable, and this is a reprepare, or
001860  **
001861  **  * The sqlite3ValueFromExpr() function is able to extract a value 
001862  **    from the expression (i.e. the expression is a literal value).
001863  **
001864  ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
001865  ** vector components that match either of the two latter criteria listed
001866  ** above.
001867  **
001868  ** Before any value is appended to the record, the affinity of the 
001869  ** corresponding column within index pIdx is applied to it. Before
001870  ** this function returns, output parameter *pnExtract is set to the
001871  ** number of values appended to the record.
001872  **
001873  ** When this function is called, *ppRec must either point to an object
001874  ** allocated by an earlier call to this function, or must be NULL. If it
001875  ** is NULL and a value can be successfully extracted, a new UnpackedRecord
001876  ** is allocated (and *ppRec set to point to it) before returning.
001877  **
001878  ** Unless an error is encountered, SQLITE_OK is returned. It is not an
001879  ** error if a value cannot be extracted from pExpr. If an error does
001880  ** occur, an SQLite error code is returned.
001881  */
001882  int sqlite3Stat4ProbeSetValue(
001883    Parse *pParse,                  /* Parse context */
001884    Index *pIdx,                    /* Index being probed */
001885    UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
001886    Expr *pExpr,                    /* The expression to extract a value from */
001887    int nElem,                      /* Maximum number of values to append */
001888    int iVal,                       /* Array element to populate */
001889    int *pnExtract                  /* OUT: Values appended to the record */
001890  ){
001891    int rc = SQLITE_OK;
001892    int nExtract = 0;
001893  
001894    if( pExpr==0 || pExpr->op!=TK_SELECT ){
001895      int i;
001896      struct ValueNewStat4Ctx alloc;
001897  
001898      alloc.pParse = pParse;
001899      alloc.pIdx = pIdx;
001900      alloc.ppRec = ppRec;
001901  
001902      for(i=0; i<nElem; i++){
001903        sqlite3_value *pVal = 0;
001904        Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
001905        u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
001906        alloc.iVal = iVal+i;
001907        rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
001908        if( !pVal ) break;
001909        nExtract++;
001910      }
001911    }
001912  
001913    *pnExtract = nExtract;
001914    return rc;
001915  }
001916  
001917  /*
001918  ** Attempt to extract a value from expression pExpr using the methods
001919  ** as described for sqlite3Stat4ProbeSetValue() above. 
001920  **
001921  ** If successful, set *ppVal to point to a new value object and return 
001922  ** SQLITE_OK. If no value can be extracted, but no other error occurs
001923  ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
001924  ** does occur, return an SQLite error code. The final value of *ppVal
001925  ** is undefined in this case.
001926  */
001927  int sqlite3Stat4ValueFromExpr(
001928    Parse *pParse,                  /* Parse context */
001929    Expr *pExpr,                    /* The expression to extract a value from */
001930    u8 affinity,                    /* Affinity to use */
001931    sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
001932  ){
001933    return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
001934  }
001935  
001936  /*
001937  ** Extract the iCol-th column from the nRec-byte record in pRec.  Write
001938  ** the column value into *ppVal.  If *ppVal is initially NULL then a new
001939  ** sqlite3_value object is allocated.
001940  **
001941  ** If *ppVal is initially NULL then the caller is responsible for 
001942  ** ensuring that the value written into *ppVal is eventually freed.
001943  */
001944  int sqlite3Stat4Column(
001945    sqlite3 *db,                    /* Database handle */
001946    const void *pRec,               /* Pointer to buffer containing record */
001947    int nRec,                       /* Size of buffer pRec in bytes */
001948    int iCol,                       /* Column to extract */
001949    sqlite3_value **ppVal           /* OUT: Extracted value */
001950  ){
001951    u32 t = 0;                      /* a column type code */
001952    u32 nHdr;                       /* Size of the header in the record */
001953    u32 iHdr;                       /* Next unread header byte */
001954    i64 iField;                     /* Next unread data byte */
001955    u32 szField = 0;                /* Size of the current data field */
001956    int i;                          /* Column index */
001957    u8 *a = (u8*)pRec;              /* Typecast byte array */
001958    Mem *pMem = *ppVal;             /* Write result into this Mem object */
001959  
001960    assert( iCol>0 );
001961    iHdr = getVarint32(a, nHdr);
001962    if( nHdr>(u32)nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
001963    iField = nHdr;
001964    for(i=0; i<=iCol; i++){
001965      iHdr += getVarint32(&a[iHdr], t);
001966      testcase( iHdr==nHdr );
001967      testcase( iHdr==nHdr+1 );
001968      if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
001969      szField = sqlite3VdbeSerialTypeLen(t);
001970      iField += szField;
001971    }
001972    testcase( iField==nRec );
001973    testcase( iField==nRec+1 );
001974    if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
001975    if( pMem==0 ){
001976      pMem = *ppVal = sqlite3ValueNew(db);
001977      if( pMem==0 ) return SQLITE_NOMEM_BKPT;
001978    }
001979    sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
001980    pMem->enc = ENC(db);
001981    return SQLITE_OK;
001982  }
001983  
001984  /*
001985  ** Unless it is NULL, the argument must be an UnpackedRecord object returned
001986  ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
001987  ** the object.
001988  */
001989  void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
001990    if( pRec ){
001991      int i;
001992      int nCol = pRec->pKeyInfo->nAllField;
001993      Mem *aMem = pRec->aMem;
001994      sqlite3 *db = aMem[0].db;
001995      for(i=0; i<nCol; i++){
001996        sqlite3VdbeMemRelease(&aMem[i]);
001997      }
001998      sqlite3KeyInfoUnref(pRec->pKeyInfo);
001999      sqlite3DbFreeNN(db, pRec);
002000    }
002001  }
002002  #endif /* ifdef SQLITE_ENABLE_STAT4 */
002003  
002004  /*
002005  ** Change the string value of an sqlite3_value object
002006  */
002007  void sqlite3ValueSetStr(
002008    sqlite3_value *v,     /* Value to be set */
002009    int n,                /* Length of string z */
002010    const void *z,        /* Text of the new string */
002011    u8 enc,               /* Encoding to use */
002012    void (*xDel)(void*)   /* Destructor for the string */
002013  ){
002014    if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
002015  }
002016  
002017  /*
002018  ** Free an sqlite3_value object
002019  */
002020  void sqlite3ValueFree(sqlite3_value *v){
002021    if( !v ) return;
002022    sqlite3VdbeMemRelease((Mem *)v);
002023    sqlite3DbFreeNN(((Mem*)v)->db, v);
002024  }
002025  
002026  /*
002027  ** The sqlite3ValueBytes() routine returns the number of bytes in the
002028  ** sqlite3_value object assuming that it uses the encoding "enc".
002029  ** The valueBytes() routine is a helper function.
002030  */
002031  static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
002032    return valueToText(pVal, enc)!=0 ? pVal->n : 0;
002033  }
002034  int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
002035    Mem *p = (Mem*)pVal;
002036    assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
002037    if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
002038      return p->n;
002039    }
002040    if( (p->flags & MEM_Str)!=0 && enc!=SQLITE_UTF8 && pVal->enc!=SQLITE_UTF8 ){
002041      return p->n;
002042    }
002043    if( (p->flags & MEM_Blob)!=0 ){
002044      if( p->flags & MEM_Zero ){
002045        return p->n + p->u.nZero;
002046      }else{
002047        return p->n;
002048      }
002049    }
002050    if( p->flags & MEM_Null ) return 0;
002051    return valueBytes(pVal, enc);
002052  }