000001  /*
000002  ** 2003 September 6
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  ** This file contains code used for creating, destroying, and populating
000013  ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
000014  */
000015  #include "sqliteInt.h"
000016  #include "vdbeInt.h"
000017  
000018  /* Forward references */
000019  static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);
000020  static void vdbeFreeOpArray(sqlite3 *, Op *, int);
000021  
000022  /*
000023  ** Create a new virtual database engine.
000024  */
000025  Vdbe *sqlite3VdbeCreate(Parse *pParse){
000026    sqlite3 *db = pParse->db;
000027    Vdbe *p;
000028    p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
000029    if( p==0 ) return 0;
000030    memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
000031    p->db = db;
000032    if( db->pVdbe ){
000033      db->pVdbe->ppVPrev = &p->pVNext;
000034    }
000035    p->pVNext = db->pVdbe;
000036    p->ppVPrev = &db->pVdbe;
000037    db->pVdbe = p;
000038    assert( p->eVdbeState==VDBE_INIT_STATE );
000039    p->pParse = pParse;
000040    pParse->pVdbe = p;
000041    assert( pParse->aLabel==0 );
000042    assert( pParse->nLabel==0 );
000043    assert( p->nOpAlloc==0 );
000044    assert( pParse->szOpAlloc==0 );
000045    sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
000046    return p;
000047  }
000048  
000049  /*
000050  ** Return the Parse object that owns a Vdbe object.
000051  */
000052  Parse *sqlite3VdbeParser(Vdbe *p){
000053    return p->pParse;
000054  }
000055  
000056  /*
000057  ** Change the error string stored in Vdbe.zErrMsg
000058  */
000059  void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
000060    va_list ap;
000061    sqlite3DbFree(p->db, p->zErrMsg);
000062    va_start(ap, zFormat);
000063    p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
000064    va_end(ap);
000065  }
000066  
000067  /*
000068  ** Remember the SQL string for a prepared statement.
000069  */
000070  void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
000071    if( p==0 ) return;
000072    p->prepFlags = prepFlags;
000073    if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
000074      p->expmask = 0;
000075    }
000076    assert( p->zSql==0 );
000077    p->zSql = sqlite3DbStrNDup(p->db, z, n);
000078  }
000079  
000080  #ifdef SQLITE_ENABLE_NORMALIZE
000081  /*
000082  ** Add a new element to the Vdbe->pDblStr list.
000083  */
000084  void sqlite3VdbeAddDblquoteStr(sqlite3 *db, Vdbe *p, const char *z){
000085    if( p ){
000086      int n = sqlite3Strlen30(z);
000087      DblquoteStr *pStr = sqlite3DbMallocRawNN(db,
000088                              sizeof(*pStr)+n+1-sizeof(pStr->z));
000089      if( pStr ){
000090        pStr->pNextStr = p->pDblStr;
000091        p->pDblStr = pStr;
000092        memcpy(pStr->z, z, n+1);
000093      }
000094    }
000095  }
000096  #endif
000097  
000098  #ifdef SQLITE_ENABLE_NORMALIZE
000099  /*
000100  ** zId of length nId is a double-quoted identifier.  Check to see if
000101  ** that identifier is really used as a string literal.
000102  */
000103  int sqlite3VdbeUsesDoubleQuotedString(
000104    Vdbe *pVdbe,            /* The prepared statement */
000105    const char *zId         /* The double-quoted identifier, already dequoted */
000106  ){
000107    DblquoteStr *pStr;
000108    assert( zId!=0 );
000109    if( pVdbe->pDblStr==0 ) return 0;
000110    for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){
000111      if( strcmp(zId, pStr->z)==0 ) return 1;
000112    }
000113    return 0;
000114  }
000115  #endif
000116  
000117  /*
000118  ** Swap byte-code between two VDBE structures.
000119  **
000120  ** This happens after pB was previously run and returned
000121  ** SQLITE_SCHEMA.  The statement was then reprepared in pA.
000122  ** This routine transfers the new bytecode in pA over to pB
000123  ** so that pB can be run again.  The old pB byte code is
000124  ** moved back to pA so that it will be cleaned up when pA is
000125  ** finalized.
000126  */
000127  void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
000128    Vdbe tmp, *pTmp, **ppTmp;
000129    char *zTmp;
000130    assert( pA->db==pB->db );
000131    tmp = *pA;
000132    *pA = *pB;
000133    *pB = tmp;
000134    pTmp = pA->pVNext;
000135    pA->pVNext = pB->pVNext;
000136    pB->pVNext = pTmp;
000137    ppTmp = pA->ppVPrev;
000138    pA->ppVPrev = pB->ppVPrev;
000139    pB->ppVPrev = ppTmp;
000140    zTmp = pA->zSql;
000141    pA->zSql = pB->zSql;
000142    pB->zSql = zTmp;
000143  #ifdef SQLITE_ENABLE_NORMALIZE
000144    zTmp = pA->zNormSql;
000145    pA->zNormSql = pB->zNormSql;
000146    pB->zNormSql = zTmp;
000147  #endif
000148    pB->expmask = pA->expmask;
000149    pB->prepFlags = pA->prepFlags;
000150    memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
000151    pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
000152  }
000153  
000154  /*
000155  ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
000156  ** than its current size. nOp is guaranteed to be less than or equal
000157  ** to 1024/sizeof(Op).
000158  **
000159  ** If an out-of-memory error occurs while resizing the array, return
000160  ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
000161  ** unchanged (this is so that any opcodes already allocated can be
000162  ** correctly deallocated along with the rest of the Vdbe).
000163  */
000164  static int growOpArray(Vdbe *v, int nOp){
000165    VdbeOp *pNew;
000166    Parse *p = v->pParse;
000167  
000168    /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
000169    ** more frequent reallocs and hence provide more opportunities for
000170    ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
000171    ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
000172    ** by the minimum* amount required until the size reaches 512.  Normal
000173    ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
000174    ** size of the op array or add 1KB of space, whichever is smaller. */
000175  #ifdef SQLITE_TEST_REALLOC_STRESS
000176    sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc
000177                          : (sqlite3_int64)v->nOpAlloc+nOp);
000178  #else
000179    sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc
000180                          : (sqlite3_int64)(1024/sizeof(Op)));
000181    UNUSED_PARAMETER(nOp);
000182  #endif
000183  
000184    /* Ensure that the size of a VDBE does not grow too large */
000185    if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
000186      sqlite3OomFault(p->db);
000187      return SQLITE_NOMEM;
000188    }
000189  
000190    assert( nOp<=(int)(1024/sizeof(Op)) );
000191    assert( nNew>=(v->nOpAlloc+nOp) );
000192    pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
000193    if( pNew ){
000194      p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
000195      v->nOpAlloc = p->szOpAlloc/sizeof(Op);
000196      v->aOp = pNew;
000197    }
000198    return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
000199  }
000200  
000201  #ifdef SQLITE_DEBUG
000202  /* This routine is just a convenient place to set a breakpoint that will
000203  ** fire after each opcode is inserted and displayed using
000204  ** "PRAGMA vdbe_addoptrace=on".  Parameters "pc" (program counter) and
000205  ** pOp are available to make the breakpoint conditional.
000206  **
000207  ** Other useful labels for breakpoints include:
000208  **   test_trace_breakpoint(pc,pOp)
000209  **   sqlite3CorruptError(lineno)
000210  **   sqlite3MisuseError(lineno)
000211  **   sqlite3CantopenError(lineno)
000212  */
000213  static void test_addop_breakpoint(int pc, Op *pOp){
000214    static u64 n = 0;
000215    (void)pc;
000216    (void)pOp;
000217    n++;
000218    if( n==LARGEST_UINT64 ) abort(); /* so that n is used, preventing a warning */
000219  }
000220  #endif
000221  
000222  /*
000223  ** Slow paths for sqlite3VdbeAddOp3() and sqlite3VdbeAddOp4Int() for the
000224  ** unusual case when we need to increase the size of the Vdbe.aOp[] array
000225  ** before adding the new opcode.
000226  */
000227  static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
000228    assert( p->nOpAlloc<=p->nOp );
000229    if( growOpArray(p, 1) ) return 1;
000230    assert( p->nOpAlloc>p->nOp );
000231    return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
000232  }
000233  static SQLITE_NOINLINE int addOp4IntSlow(
000234    Vdbe *p,            /* Add the opcode to this VM */
000235    int op,             /* The new opcode */
000236    int p1,             /* The P1 operand */
000237    int p2,             /* The P2 operand */
000238    int p3,             /* The P3 operand */
000239    int p4              /* The P4 operand as an integer */
000240  ){
000241    int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
000242    if( p->db->mallocFailed==0 ){
000243      VdbeOp *pOp = &p->aOp[addr];
000244      pOp->p4type = P4_INT32;
000245      pOp->p4.i = p4;
000246    }
000247    return addr;
000248  }
000249  
000250  
000251  /*
000252  ** Add a new instruction to the list of instructions current in the
000253  ** VDBE.  Return the address of the new instruction.
000254  **
000255  ** Parameters:
000256  **
000257  **    p               Pointer to the VDBE
000258  **
000259  **    op              The opcode for this instruction
000260  **
000261  **    p1, p2, p3, p4  Operands
000262  */
000263  int sqlite3VdbeAddOp0(Vdbe *p, int op){
000264    return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
000265  }
000266  int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
000267    return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
000268  }
000269  int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
000270    return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
000271  }
000272  int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
000273    int i;
000274    VdbeOp *pOp;
000275  
000276    i = p->nOp;
000277    assert( p->eVdbeState==VDBE_INIT_STATE );
000278    assert( op>=0 && op<0xff );
000279    if( p->nOpAlloc<=i ){
000280      return growOp3(p, op, p1, p2, p3);
000281    }
000282    assert( p->aOp!=0 );
000283    p->nOp++;
000284    pOp = &p->aOp[i];
000285    assert( pOp!=0 );
000286    pOp->opcode = (u8)op;
000287    pOp->p5 = 0;
000288    pOp->p1 = p1;
000289    pOp->p2 = p2;
000290    pOp->p3 = p3;
000291    pOp->p4.p = 0;
000292    pOp->p4type = P4_NOTUSED;
000293  
000294    /* Replicate this logic in sqlite3VdbeAddOp4Int()
000295    ** vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv   */
000296  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
000297    pOp->zComment = 0;
000298  #endif
000299  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
000300    pOp->nExec = 0;
000301    pOp->nCycle = 0;
000302  #endif
000303  #ifdef SQLITE_DEBUG
000304    if( p->db->flags & SQLITE_VdbeAddopTrace ){
000305      sqlite3VdbePrintOp(0, i, &p->aOp[i]);
000306      test_addop_breakpoint(i, &p->aOp[i]);
000307    }
000308  #endif
000309  #ifdef SQLITE_VDBE_COVERAGE
000310    pOp->iSrcLine = 0;
000311  #endif
000312    /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
000313    ** Replicate in sqlite3VdbeAddOp4Int() */
000314  
000315    return i;
000316  }
000317  int sqlite3VdbeAddOp4Int(
000318    Vdbe *p,            /* Add the opcode to this VM */
000319    int op,             /* The new opcode */
000320    int p1,             /* The P1 operand */
000321    int p2,             /* The P2 operand */
000322    int p3,             /* The P3 operand */
000323    int p4              /* The P4 operand as an integer */
000324  ){
000325    int i;
000326    VdbeOp *pOp;
000327  
000328    i = p->nOp;
000329    if( p->nOpAlloc<=i ){
000330      return addOp4IntSlow(p, op, p1, p2, p3, p4);
000331    }
000332    p->nOp++;
000333    pOp = &p->aOp[i];
000334    assert( pOp!=0 );
000335    pOp->opcode = (u8)op;
000336    pOp->p5 = 0;
000337    pOp->p1 = p1;
000338    pOp->p2 = p2;
000339    pOp->p3 = p3;
000340    pOp->p4.i = p4;
000341    pOp->p4type = P4_INT32;
000342  
000343    /* Replicate this logic in sqlite3VdbeAddOp3()
000344    ** vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv   */
000345  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
000346    pOp->zComment = 0;
000347  #endif
000348  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
000349    pOp->nExec = 0;
000350    pOp->nCycle = 0;
000351  #endif
000352  #ifdef SQLITE_DEBUG
000353    if( p->db->flags & SQLITE_VdbeAddopTrace ){
000354      sqlite3VdbePrintOp(0, i, &p->aOp[i]);
000355      test_addop_breakpoint(i, &p->aOp[i]);
000356    }
000357  #endif
000358  #ifdef SQLITE_VDBE_COVERAGE
000359    pOp->iSrcLine = 0;
000360  #endif
000361    /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
000362    ** Replicate in sqlite3VdbeAddOp3() */
000363  
000364    return i;
000365  }
000366  
000367  /* Generate code for an unconditional jump to instruction iDest
000368  */
000369  int sqlite3VdbeGoto(Vdbe *p, int iDest){
000370    return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
000371  }
000372  
000373  /* Generate code to cause the string zStr to be loaded into
000374  ** register iDest
000375  */
000376  int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
000377    return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
000378  }
000379  
000380  /*
000381  ** Generate code that initializes multiple registers to string or integer
000382  ** constants.  The registers begin with iDest and increase consecutively.
000383  ** One register is initialized for each characgter in zTypes[].  For each
000384  ** "s" character in zTypes[], the register is a string if the argument is
000385  ** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
000386  ** in zTypes[], the register is initialized to an integer.
000387  **
000388  ** If the input string does not end with "X" then an OP_ResultRow instruction
000389  ** is generated for the values inserted.
000390  */
000391  void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
000392    va_list ap;
000393    int i;
000394    char c;
000395    va_start(ap, zTypes);
000396    for(i=0; (c = zTypes[i])!=0; i++){
000397      if( c=='s' ){
000398        const char *z = va_arg(ap, const char*);
000399        sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
000400      }else if( c=='i' ){
000401        sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
000402      }else{
000403        goto skip_op_resultrow;
000404      }
000405    }
000406    sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
000407  skip_op_resultrow:
000408    va_end(ap);
000409  }
000410  
000411  /*
000412  ** Add an opcode that includes the p4 value as a pointer.
000413  */
000414  int sqlite3VdbeAddOp4(
000415    Vdbe *p,            /* Add the opcode to this VM */
000416    int op,             /* The new opcode */
000417    int p1,             /* The P1 operand */
000418    int p2,             /* The P2 operand */
000419    int p3,             /* The P3 operand */
000420    const char *zP4,    /* The P4 operand */
000421    int p4type          /* P4 operand type */
000422  ){
000423    int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
000424    sqlite3VdbeChangeP4(p, addr, zP4, p4type);
000425    return addr;
000426  }
000427  
000428  /*
000429  ** Add an OP_Function or OP_PureFunc opcode.
000430  **
000431  ** The eCallCtx argument is information (typically taken from Expr.op2)
000432  ** that describes the calling context of the function.  0 means a general
000433  ** function call.  NC_IsCheck means called by a check constraint,
000434  ** NC_IdxExpr means called as part of an index expression.  NC_PartIdx
000435  ** means in the WHERE clause of a partial index.  NC_GenCol means called
000436  ** while computing a generated column value.  0 is the usual case.
000437  */
000438  int sqlite3VdbeAddFunctionCall(
000439    Parse *pParse,        /* Parsing context */
000440    int p1,               /* Constant argument mask */
000441    int p2,               /* First argument register */
000442    int p3,               /* Register into which results are written */
000443    int nArg,             /* Number of argument */
000444    const FuncDef *pFunc, /* The function to be invoked */
000445    int eCallCtx          /* Calling context */
000446  ){
000447    Vdbe *v = pParse->pVdbe;
000448    int nByte;
000449    int addr;
000450    sqlite3_context *pCtx;
000451    assert( v );
000452    nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*);
000453    pCtx = sqlite3DbMallocRawNN(pParse->db, nByte);
000454    if( pCtx==0 ){
000455      assert( pParse->db->mallocFailed );
000456      freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);
000457      return 0;
000458    }
000459    pCtx->pOut = 0;
000460    pCtx->pFunc = (FuncDef*)pFunc;
000461    pCtx->pVdbe = 0;
000462    pCtx->isError = 0;
000463    pCtx->argc = nArg;
000464    pCtx->iOp = sqlite3VdbeCurrentAddr(v);
000465    addr = sqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function,
000466                             p1, p2, p3, (char*)pCtx, P4_FUNCCTX);
000467    sqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef);
000468    sqlite3MayAbort(pParse);
000469    return addr;
000470  }
000471  
000472  /*
000473  ** Add an opcode that includes the p4 value with a P4_INT64 or
000474  ** P4_REAL type.
000475  */
000476  int sqlite3VdbeAddOp4Dup8(
000477    Vdbe *p,            /* Add the opcode to this VM */
000478    int op,             /* The new opcode */
000479    int p1,             /* The P1 operand */
000480    int p2,             /* The P2 operand */
000481    int p3,             /* The P3 operand */
000482    const u8 *zP4,      /* The P4 operand */
000483    int p4type          /* P4 operand type */
000484  ){
000485    char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
000486    if( p4copy ) memcpy(p4copy, zP4, 8);
000487    return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
000488  }
000489  
000490  #ifndef SQLITE_OMIT_EXPLAIN
000491  /*
000492  ** Return the address of the current EXPLAIN QUERY PLAN baseline.
000493  ** 0 means "none".
000494  */
000495  int sqlite3VdbeExplainParent(Parse *pParse){
000496    VdbeOp *pOp;
000497    if( pParse->addrExplain==0 ) return 0;
000498    pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
000499    return pOp->p2;
000500  }
000501  
000502  /*
000503  ** Set a debugger breakpoint on the following routine in order to
000504  ** monitor the EXPLAIN QUERY PLAN code generation.
000505  */
000506  #if defined(SQLITE_DEBUG)
000507  void sqlite3ExplainBreakpoint(const char *z1, const char *z2){
000508    (void)z1;
000509    (void)z2;
000510  }
000511  #endif
000512  
000513  /*
000514  ** Add a new OP_Explain opcode.
000515  **
000516  ** If the bPush flag is true, then make this opcode the parent for
000517  ** subsequent Explains until sqlite3VdbeExplainPop() is called.
000518  */
000519  int sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
000520    int addr = 0;
000521  #if !defined(SQLITE_DEBUG)
000522    /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.
000523    ** But omit them (for performance) during production builds */
000524    if( pParse->explain==2 || IS_STMT_SCANSTATUS(pParse->db) )
000525  #endif
000526    {
000527      char *zMsg;
000528      Vdbe *v;
000529      va_list ap;
000530      int iThis;
000531      va_start(ap, zFmt);
000532      zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
000533      va_end(ap);
000534      v = pParse->pVdbe;
000535      iThis = v->nOp;
000536      addr = sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
000537                        zMsg, P4_DYNAMIC);
000538      sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetLastOp(v)->p4.z);
000539      if( bPush){
000540        pParse->addrExplain = iThis;
000541      }
000542      sqlite3VdbeScanStatus(v, iThis, -1, -1, 0, 0);
000543    }
000544    return addr;
000545  }
000546  
000547  /*
000548  ** Pop the EXPLAIN QUERY PLAN stack one level.
000549  */
000550  void sqlite3VdbeExplainPop(Parse *pParse){
000551    sqlite3ExplainBreakpoint("POP", 0);
000552    pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
000553  }
000554  #endif /* SQLITE_OMIT_EXPLAIN */
000555  
000556  /*
000557  ** Add an OP_ParseSchema opcode.  This routine is broken out from
000558  ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
000559  ** as having been used.
000560  **
000561  ** The zWhere string must have been obtained from sqlite3_malloc().
000562  ** This routine will take ownership of the allocated memory.
000563  */
000564  void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere, u16 p5){
000565    int j;
000566    sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
000567    sqlite3VdbeChangeP5(p, p5);
000568    for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
000569    sqlite3MayAbort(p->pParse);
000570  }
000571  
000572  /* Insert the end of a co-routine
000573  */
000574  void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
000575    sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
000576  
000577    /* Clear the temporary register cache, thereby ensuring that each
000578    ** co-routine has its own independent set of registers, because co-routines
000579    ** might expect their registers to be preserved across an OP_Yield, and
000580    ** that could cause problems if two or more co-routines are using the same
000581    ** temporary register.
000582    */
000583    v->pParse->nTempReg = 0;
000584    v->pParse->nRangeReg = 0;
000585  }
000586  
000587  /*
000588  ** Create a new symbolic label for an instruction that has yet to be
000589  ** coded.  The symbolic label is really just a negative number.  The
000590  ** label can be used as the P2 value of an operation.  Later, when
000591  ** the label is resolved to a specific address, the VDBE will scan
000592  ** through its operation list and change all values of P2 which match
000593  ** the label into the resolved address.
000594  **
000595  ** The VDBE knows that a P2 value is a label because labels are
000596  ** always negative and P2 values are suppose to be non-negative.
000597  ** Hence, a negative P2 value is a label that has yet to be resolved.
000598  ** (Later:) This is only true for opcodes that have the OPFLG_JUMP
000599  ** property.
000600  **
000601  ** Variable usage notes:
000602  **
000603  **     Parse.aLabel[x]     Stores the address that the x-th label resolves
000604  **                         into.  For testing (SQLITE_DEBUG), unresolved
000605  **                         labels stores -1, but that is not required.
000606  **     Parse.nLabelAlloc   Number of slots allocated to Parse.aLabel[]
000607  **     Parse.nLabel        The *negative* of the number of labels that have
000608  **                         been issued.  The negative is stored because
000609  **                         that gives a performance improvement over storing
000610  **                         the equivalent positive value.
000611  */
000612  int sqlite3VdbeMakeLabel(Parse *pParse){
000613    return --pParse->nLabel;
000614  }
000615  
000616  /*
000617  ** Resolve label "x" to be the address of the next instruction to
000618  ** be inserted.  The parameter "x" must have been obtained from
000619  ** a prior call to sqlite3VdbeMakeLabel().
000620  */
000621  static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
000622    int nNewSize = 10 - p->nLabel;
000623    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
000624                       nNewSize*sizeof(p->aLabel[0]));
000625    if( p->aLabel==0 ){
000626      p->nLabelAlloc = 0;
000627    }else{
000628  #ifdef SQLITE_DEBUG
000629      int i;
000630      for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;
000631  #endif
000632      if( nNewSize>=100 && (nNewSize/100)>(p->nLabelAlloc/100) ){
000633        sqlite3ProgressCheck(p);
000634      }
000635      p->nLabelAlloc = nNewSize;
000636      p->aLabel[j] = v->nOp;
000637    }
000638  }
000639  void sqlite3VdbeResolveLabel(Vdbe *v, int x){
000640    Parse *p = v->pParse;
000641    int j = ADDR(x);
000642    assert( v->eVdbeState==VDBE_INIT_STATE );
000643    assert( j<-p->nLabel );
000644    assert( j>=0 );
000645  #ifdef SQLITE_DEBUG
000646    if( p->db->flags & SQLITE_VdbeAddopTrace ){
000647      printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
000648    }
000649  #endif
000650    if( p->nLabelAlloc + p->nLabel < 0 ){
000651      resizeResolveLabel(p,v,j);
000652    }else{
000653      assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
000654      p->aLabel[j] = v->nOp;
000655    }
000656  }
000657  
000658  /*
000659  ** Mark the VDBE as one that can only be run one time.
000660  */
000661  void sqlite3VdbeRunOnlyOnce(Vdbe *p){
000662    sqlite3VdbeAddOp2(p, OP_Expire, 1, 1);
000663  }
000664  
000665  /*
000666  ** Mark the VDBE as one that can be run multiple times.
000667  */
000668  void sqlite3VdbeReusable(Vdbe *p){
000669    int i;
000670    for(i=1; ALWAYS(i<p->nOp); i++){
000671      if( ALWAYS(p->aOp[i].opcode==OP_Expire) ){
000672        p->aOp[1].opcode = OP_Noop;
000673        break;
000674      }
000675    }
000676  }
000677  
000678  #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
000679  
000680  /*
000681  ** The following type and function are used to iterate through all opcodes
000682  ** in a Vdbe main program and each of the sub-programs (triggers) it may
000683  ** invoke directly or indirectly. It should be used as follows:
000684  **
000685  **   Op *pOp;
000686  **   VdbeOpIter sIter;
000687  **
000688  **   memset(&sIter, 0, sizeof(sIter));
000689  **   sIter.v = v;                            // v is of type Vdbe*
000690  **   while( (pOp = opIterNext(&sIter)) ){
000691  **     // Do something with pOp
000692  **   }
000693  **   sqlite3DbFree(v->db, sIter.apSub);
000694  **
000695  */
000696  typedef struct VdbeOpIter VdbeOpIter;
000697  struct VdbeOpIter {
000698    Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
000699    SubProgram **apSub;        /* Array of subprograms */
000700    int nSub;                  /* Number of entries in apSub */
000701    int iAddr;                 /* Address of next instruction to return */
000702    int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
000703  };
000704  static Op *opIterNext(VdbeOpIter *p){
000705    Vdbe *v = p->v;
000706    Op *pRet = 0;
000707    Op *aOp;
000708    int nOp;
000709  
000710    if( p->iSub<=p->nSub ){
000711  
000712      if( p->iSub==0 ){
000713        aOp = v->aOp;
000714        nOp = v->nOp;
000715      }else{
000716        aOp = p->apSub[p->iSub-1]->aOp;
000717        nOp = p->apSub[p->iSub-1]->nOp;
000718      }
000719      assert( p->iAddr<nOp );
000720  
000721      pRet = &aOp[p->iAddr];
000722      p->iAddr++;
000723      if( p->iAddr==nOp ){
000724        p->iSub++;
000725        p->iAddr = 0;
000726      }
000727   
000728      if( pRet->p4type==P4_SUBPROGRAM ){
000729        int nByte = (p->nSub+1)*sizeof(SubProgram*);
000730        int j;
000731        for(j=0; j<p->nSub; j++){
000732          if( p->apSub[j]==pRet->p4.pProgram ) break;
000733        }
000734        if( j==p->nSub ){
000735          p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
000736          if( !p->apSub ){
000737            pRet = 0;
000738          }else{
000739            p->apSub[p->nSub++] = pRet->p4.pProgram;
000740          }
000741        }
000742      }
000743    }
000744  
000745    return pRet;
000746  }
000747  
000748  /*
000749  ** Check if the program stored in the VM associated with pParse may
000750  ** throw an ABORT exception (causing the statement, but not entire transaction
000751  ** to be rolled back). This condition is true if the main program or any
000752  ** sub-programs contains any of the following:
000753  **
000754  **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
000755  **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
000756  **   *  OP_Destroy
000757  **   *  OP_VUpdate
000758  **   *  OP_VCreate
000759  **   *  OP_VRename
000760  **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
000761  **   *  OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
000762  **      (for CREATE TABLE AS SELECT ...)
000763  **
000764  ** Then check that the value of Parse.mayAbort is true if an
000765  ** ABORT may be thrown, or false otherwise. Return true if it does
000766  ** match, or false otherwise. This function is intended to be used as
000767  ** part of an assert statement in the compiler. Similar to:
000768  **
000769  **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
000770  */
000771  int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
000772    int hasAbort = 0;
000773    int hasFkCounter = 0;
000774    int hasCreateTable = 0;
000775    int hasCreateIndex = 0;
000776    int hasInitCoroutine = 0;
000777    Op *pOp;
000778    VdbeOpIter sIter;
000779  
000780    if( v==0 ) return 0;
000781    memset(&sIter, 0, sizeof(sIter));
000782    sIter.v = v;
000783  
000784    while( (pOp = opIterNext(&sIter))!=0 ){
000785      int opcode = pOp->opcode;
000786      if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
000787       || opcode==OP_VDestroy
000788       || opcode==OP_VCreate
000789       || opcode==OP_ParseSchema
000790       || opcode==OP_Function || opcode==OP_PureFunc
000791       || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
000792        && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
000793      ){
000794        hasAbort = 1;
000795        break;
000796      }
000797      if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
000798      if( mayAbort ){
000799        /* hasCreateIndex may also be set for some DELETE statements that use
000800        ** OP_Clear. So this routine may end up returning true in the case
000801        ** where a "DELETE FROM tbl" has a statement-journal but does not
000802        ** require one. This is not so bad - it is an inefficiency, not a bug. */
000803        if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;
000804        if( opcode==OP_Clear ) hasCreateIndex = 1;
000805      }
000806      if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
000807  #ifndef SQLITE_OMIT_FOREIGN_KEY
000808      if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
000809        hasFkCounter = 1;
000810      }
000811  #endif
000812    }
000813    sqlite3DbFree(v->db, sIter.apSub);
000814  
000815    /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
000816    ** If malloc failed, then the while() loop above may not have iterated
000817    ** through all opcodes and hasAbort may be set incorrectly. Return
000818    ** true for this case to prevent the assert() in the callers frame
000819    ** from failing.  */
000820    return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
000821          || (hasCreateTable && hasInitCoroutine) || hasCreateIndex
000822    );
000823  }
000824  #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
000825  
000826  #ifdef SQLITE_DEBUG
000827  /*
000828  ** Increment the nWrite counter in the VDBE if the cursor is not an
000829  ** ephemeral cursor, or if the cursor argument is NULL.
000830  */
000831  void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
000832    if( pC==0
000833     || (pC->eCurType!=CURTYPE_SORTER
000834         && pC->eCurType!=CURTYPE_PSEUDO
000835         && !pC->isEphemeral)
000836    ){
000837      p->nWrite++;
000838    }
000839  }
000840  #endif
000841  
000842  #ifdef SQLITE_DEBUG
000843  /*
000844  ** Assert if an Abort at this point in time might result in a corrupt
000845  ** database.
000846  */
000847  void sqlite3VdbeAssertAbortable(Vdbe *p){
000848    assert( p->nWrite==0 || p->usesStmtJournal );
000849  }
000850  #endif
000851  
000852  /*
000853  ** This routine is called after all opcodes have been inserted.  It loops
000854  ** through all the opcodes and fixes up some details.
000855  **
000856  ** (1) For each jump instruction with a negative P2 value (a label)
000857  **     resolve the P2 value to an actual address.
000858  **
000859  ** (2) Compute the maximum number of arguments used by any SQL function
000860  **     and store that value in *pMaxFuncArgs.
000861  **
000862  ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
000863  **     indicate what the prepared statement actually does.
000864  **
000865  ** (4) (discontinued)
000866  **
000867  ** (5) Reclaim the memory allocated for storing labels.
000868  **
000869  ** This routine will only function correctly if the mkopcodeh.tcl generator
000870  ** script numbers the opcodes correctly.  Changes to this routine must be
000871  ** coordinated with changes to mkopcodeh.tcl.
000872  */
000873  static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
000874    int nMaxArgs = *pMaxFuncArgs;
000875    Op *pOp;
000876    Parse *pParse = p->pParse;
000877    int *aLabel = pParse->aLabel;
000878  
000879    assert( pParse->db->mallocFailed==0 ); /* tag-20230419-1 */
000880    p->readOnly = 1;
000881    p->bIsReader = 0;
000882    pOp = &p->aOp[p->nOp-1];
000883    assert( p->aOp[0].opcode==OP_Init );
000884    while( 1 /* Loop terminates when it reaches the OP_Init opcode */ ){
000885      /* Only JUMP opcodes and the short list of special opcodes in the switch
000886      ** below need to be considered.  The mkopcodeh.tcl generator script groups
000887      ** all these opcodes together near the front of the opcode list.  Skip
000888      ** any opcode that does not need processing by virtual of the fact that
000889      ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
000890      */
000891      if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
000892        /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
000893        ** cases from this switch! */
000894        switch( pOp->opcode ){
000895          case OP_Transaction: {
000896            if( pOp->p2!=0 ) p->readOnly = 0;
000897            /* no break */ deliberate_fall_through
000898          }
000899          case OP_AutoCommit:
000900          case OP_Savepoint: {
000901            p->bIsReader = 1;
000902            break;
000903          }
000904  #ifndef SQLITE_OMIT_WAL
000905          case OP_Checkpoint:
000906  #endif
000907          case OP_Vacuum:
000908          case OP_JournalMode: {
000909            p->readOnly = 0;
000910            p->bIsReader = 1;
000911            break;
000912          }
000913          case OP_Init: {
000914            assert( pOp->p2>=0 );
000915            goto resolve_p2_values_loop_exit;
000916          }
000917  #ifndef SQLITE_OMIT_VIRTUALTABLE
000918          case OP_VUpdate: {
000919            if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
000920            break;
000921          }
000922          case OP_VFilter: {
000923            int n;
000924            assert( (pOp - p->aOp) >= 3 );
000925            assert( pOp[-1].opcode==OP_Integer );
000926            n = pOp[-1].p1;
000927            if( n>nMaxArgs ) nMaxArgs = n;
000928            /* Fall through into the default case */
000929            /* no break */ deliberate_fall_through
000930          }
000931  #endif
000932          default: {
000933            if( pOp->p2<0 ){
000934              /* The mkopcodeh.tcl script has so arranged things that the only
000935              ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
000936              ** have non-negative values for P2. */
000937              assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
000938              assert( ADDR(pOp->p2)<-pParse->nLabel );
000939              assert( aLabel!=0 );  /* True because of tag-20230419-1 */
000940              pOp->p2 = aLabel[ADDR(pOp->p2)];
000941            }
000942  
000943            /* OPFLG_JUMP opcodes never have P2==0, though OPFLG_JUMP0 opcodes
000944            ** might */
000945            assert( pOp->p2>0 
000946                    || (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP0)!=0 );
000947  
000948            /* Jumps never go off the end of the bytecode array */
000949            assert( pOp->p2<p->nOp
000950                    || (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)==0 );
000951            break;
000952          }
000953        }
000954        /* The mkopcodeh.tcl script has so arranged things that the only
000955        ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
000956        ** have non-negative values for P2. */
000957        assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
000958      }
000959      assert( pOp>p->aOp );   
000960      pOp--;
000961    }
000962  resolve_p2_values_loop_exit:
000963    if( aLabel ){
000964      sqlite3DbNNFreeNN(p->db, pParse->aLabel);
000965      pParse->aLabel = 0;
000966    }
000967    pParse->nLabel = 0;
000968    *pMaxFuncArgs = nMaxArgs;
000969    assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
000970  }
000971  
000972  #ifdef SQLITE_DEBUG
000973  /*
000974  ** Check to see if a subroutine contains a jump to a location outside of
000975  ** the subroutine.  If a jump outside the subroutine is detected, add code
000976  ** that will cause the program to halt with an error message.
000977  **
000978  ** The subroutine consists of opcodes between iFirst and iLast.  Jumps to
000979  ** locations within the subroutine are acceptable.  iRetReg is a register
000980  ** that contains the return address.  Jumps to outside the range of iFirst
000981  ** through iLast are also acceptable as long as the jump destination is
000982  ** an OP_Return to iReturnAddr.
000983  **
000984  ** A jump to an unresolved label means that the jump destination will be
000985  ** beyond the current address.  That is normally a jump to an early
000986  ** termination and is consider acceptable.
000987  **
000988  ** This routine only runs during debug builds.  The purpose is (of course)
000989  ** to detect invalid escapes out of a subroutine.  The OP_Halt opcode
000990  ** is generated rather than an assert() or other error, so that ".eqp full"
000991  ** will still work to show the original bytecode, to aid in debugging.
000992  */
000993  void sqlite3VdbeNoJumpsOutsideSubrtn(
000994    Vdbe *v,          /* The byte-code program under construction */
000995    int iFirst,       /* First opcode of the subroutine */
000996    int iLast,        /* Last opcode of the subroutine */
000997    int iRetReg       /* Subroutine return address register */
000998  ){
000999    VdbeOp *pOp;
001000    Parse *pParse;
001001    int i;
001002    sqlite3_str *pErr = 0;
001003    assert( v!=0 );
001004    pParse = v->pParse;
001005    assert( pParse!=0 );
001006    if( pParse->nErr ) return;
001007    assert( iLast>=iFirst );
001008    assert( iLast<v->nOp );
001009    pOp = &v->aOp[iFirst];
001010    for(i=iFirst; i<=iLast; i++, pOp++){
001011      if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 ){
001012        int iDest = pOp->p2;   /* Jump destination */
001013        if( iDest==0 ) continue;
001014        if( pOp->opcode==OP_Gosub ) continue;
001015        if( pOp->p3==20230325 && pOp->opcode==OP_NotNull ){
001016          /* This is a deliberately taken illegal branch.  tag-20230325-2 */
001017          continue;
001018        }
001019        if( iDest<0 ){
001020          int j = ADDR(iDest);
001021          assert( j>=0 );
001022          if( j>=-pParse->nLabel || pParse->aLabel[j]<0 ){
001023            continue;
001024          }
001025          iDest = pParse->aLabel[j];
001026        }
001027        if( iDest<iFirst || iDest>iLast ){
001028          int j = iDest;
001029          for(; j<v->nOp; j++){
001030            VdbeOp *pX = &v->aOp[j];
001031            if( pX->opcode==OP_Return ){
001032              if( pX->p1==iRetReg ) break;
001033              continue;
001034            }
001035            if( pX->opcode==OP_Noop ) continue;
001036            if( pX->opcode==OP_Explain ) continue;
001037            if( pErr==0 ){
001038              pErr = sqlite3_str_new(0);
001039            }else{
001040              sqlite3_str_appendchar(pErr, 1, '\n');
001041            }
001042            sqlite3_str_appendf(pErr,
001043                "Opcode at %d jumps to %d which is outside the "
001044                "subroutine at %d..%d",
001045                i, iDest, iFirst, iLast);
001046            break;
001047          }
001048        }
001049      }
001050    }
001051    if( pErr ){
001052      char *zErr = sqlite3_str_finish(pErr);
001053      sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_INTERNAL, OE_Abort, 0, zErr, 0);
001054      sqlite3_free(zErr);
001055      sqlite3MayAbort(pParse);
001056    }
001057  }
001058  #endif /* SQLITE_DEBUG */
001059  
001060  /*
001061  ** Return the address of the next instruction to be inserted.
001062  */
001063  int sqlite3VdbeCurrentAddr(Vdbe *p){
001064    assert( p->eVdbeState==VDBE_INIT_STATE );
001065    return p->nOp;
001066  }
001067  
001068  /*
001069  ** Verify that at least N opcode slots are available in p without
001070  ** having to malloc for more space (except when compiled using
001071  ** SQLITE_TEST_REALLOC_STRESS).  This interface is used during testing
001072  ** to verify that certain calls to sqlite3VdbeAddOpList() can never
001073  ** fail due to a OOM fault and hence that the return value from
001074  ** sqlite3VdbeAddOpList() will always be non-NULL.
001075  */
001076  #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
001077  void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
001078    assert( p->nOp + N <= p->nOpAlloc );
001079  }
001080  #endif
001081  
001082  /*
001083  ** Verify that the VM passed as the only argument does not contain
001084  ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
001085  ** by code in pragma.c to ensure that the implementation of certain
001086  ** pragmas comports with the flags specified in the mkpragmatab.tcl
001087  ** script.
001088  */
001089  #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
001090  void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
001091    int i;
001092    for(i=0; i<p->nOp; i++){
001093      assert( p->aOp[i].opcode!=OP_ResultRow );
001094    }
001095  }
001096  #endif
001097  
001098  /*
001099  ** Generate code (a single OP_Abortable opcode) that will
001100  ** verify that the VDBE program can safely call Abort in the current
001101  ** context.
001102  */
001103  #if defined(SQLITE_DEBUG)
001104  void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
001105    if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
001106  }
001107  #endif
001108  
001109  /*
001110  ** This function returns a pointer to the array of opcodes associated with
001111  ** the Vdbe passed as the first argument. It is the callers responsibility
001112  ** to arrange for the returned array to be eventually freed using the
001113  ** vdbeFreeOpArray() function.
001114  **
001115  ** Before returning, *pnOp is set to the number of entries in the returned
001116  ** array. Also, *pnMaxArg is set to the larger of its current value and
001117  ** the number of entries in the Vdbe.apArg[] array required to execute the
001118  ** returned program.
001119  */
001120  VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
001121    VdbeOp *aOp = p->aOp;
001122    assert( aOp && !p->db->mallocFailed );
001123  
001124    /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
001125    assert( DbMaskAllZero(p->btreeMask) );
001126  
001127    resolveP2Values(p, pnMaxArg);
001128    *pnOp = p->nOp;
001129    p->aOp = 0;
001130    return aOp;
001131  }
001132  
001133  /*
001134  ** Add a whole list of operations to the operation stack.  Return a
001135  ** pointer to the first operation inserted.
001136  **
001137  ** Non-zero P2 arguments to jump instructions are automatically adjusted
001138  ** so that the jump target is relative to the first operation inserted.
001139  */
001140  VdbeOp *sqlite3VdbeAddOpList(
001141    Vdbe *p,                     /* Add opcodes to the prepared statement */
001142    int nOp,                     /* Number of opcodes to add */
001143    VdbeOpList const *aOp,       /* The opcodes to be added */
001144    int iLineno                  /* Source-file line number of first opcode */
001145  ){
001146    int i;
001147    VdbeOp *pOut, *pFirst;
001148    assert( nOp>0 );
001149    assert( p->eVdbeState==VDBE_INIT_STATE );
001150    if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
001151      return 0;
001152    }
001153    pFirst = pOut = &p->aOp[p->nOp];
001154    for(i=0; i<nOp; i++, aOp++, pOut++){
001155      pOut->opcode = aOp->opcode;
001156      pOut->p1 = aOp->p1;
001157      pOut->p2 = aOp->p2;
001158      assert( aOp->p2>=0 );
001159      if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
001160        pOut->p2 += p->nOp;
001161      }
001162      pOut->p3 = aOp->p3;
001163      pOut->p4type = P4_NOTUSED;
001164      pOut->p4.p = 0;
001165      pOut->p5 = 0;
001166  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
001167      pOut->zComment = 0;
001168  #endif
001169  #ifdef SQLITE_VDBE_COVERAGE
001170      pOut->iSrcLine = iLineno+i;
001171  #else
001172      (void)iLineno;
001173  #endif
001174  #ifdef SQLITE_DEBUG
001175      if( p->db->flags & SQLITE_VdbeAddopTrace ){
001176        sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
001177      }
001178  #endif
001179    }
001180    p->nOp += nOp;
001181    return pFirst;
001182  }
001183  
001184  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
001185  /*
001186  ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
001187  */
001188  void sqlite3VdbeScanStatus(
001189    Vdbe *p,                        /* VM to add scanstatus() to */
001190    int addrExplain,                /* Address of OP_Explain (or 0) */
001191    int addrLoop,                   /* Address of loop counter */
001192    int addrVisit,                  /* Address of rows visited counter */
001193    LogEst nEst,                    /* Estimated number of output rows */
001194    const char *zName               /* Name of table or index being scanned */
001195  ){
001196    if( IS_STMT_SCANSTATUS(p->db) ){
001197      sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);
001198      ScanStatus *aNew;
001199      aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
001200      if( aNew ){
001201        ScanStatus *pNew = &aNew[p->nScan++];
001202        memset(pNew, 0, sizeof(ScanStatus));
001203        pNew->addrExplain = addrExplain;
001204        pNew->addrLoop = addrLoop;
001205        pNew->addrVisit = addrVisit;
001206        pNew->nEst = nEst;
001207        pNew->zName = sqlite3DbStrDup(p->db, zName);
001208        p->aScan = aNew;
001209      }
001210    }
001211  }
001212  
001213  /*
001214  ** Add the range of instructions from addrStart to addrEnd (inclusive) to
001215  ** the set of those corresponding to the sqlite3_stmt_scanstatus() counters
001216  ** associated with the OP_Explain instruction at addrExplain. The
001217  ** sum of the sqlite3Hwtime() values for each of these instructions
001218  ** will be returned for SQLITE_SCANSTAT_NCYCLE requests.
001219  */
001220  void sqlite3VdbeScanStatusRange(
001221    Vdbe *p,
001222    int addrExplain,
001223    int addrStart,
001224    int addrEnd
001225  ){
001226    if( IS_STMT_SCANSTATUS(p->db) ){
001227      ScanStatus *pScan = 0;
001228      int ii;
001229      for(ii=p->nScan-1; ii>=0; ii--){
001230        pScan = &p->aScan[ii];
001231        if( pScan->addrExplain==addrExplain ) break;
001232        pScan = 0;
001233      }
001234      if( pScan ){
001235        if( addrEnd<0 ) addrEnd = sqlite3VdbeCurrentAddr(p)-1;
001236        for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
001237          if( pScan->aAddrRange[ii]==0 ){
001238            pScan->aAddrRange[ii] = addrStart;
001239            pScan->aAddrRange[ii+1] = addrEnd;
001240            break;
001241          }
001242        }
001243      }
001244    }
001245  }
001246  
001247  /*
001248  ** Set the addresses for the SQLITE_SCANSTAT_NLOOP and SQLITE_SCANSTAT_NROW
001249  ** counters for the query element associated with the OP_Explain at
001250  ** addrExplain.
001251  */
001252  void sqlite3VdbeScanStatusCounters(
001253    Vdbe *p,
001254    int addrExplain,
001255    int addrLoop,
001256    int addrVisit
001257  ){
001258    if( IS_STMT_SCANSTATUS(p->db) ){
001259      ScanStatus *pScan = 0;
001260      int ii;
001261      for(ii=p->nScan-1; ii>=0; ii--){
001262        pScan = &p->aScan[ii];
001263        if( pScan->addrExplain==addrExplain ) break;
001264        pScan = 0;
001265      }
001266      if( pScan ){
001267        if( addrLoop>0 ) pScan->addrLoop = addrLoop;
001268        if( addrVisit>0 ) pScan->addrVisit = addrVisit;
001269      }
001270    }
001271  }
001272  #endif /* defined(SQLITE_ENABLE_STMT_SCANSTATUS) */
001273  
001274  
001275  /*
001276  ** Change the value of the opcode, or P1, P2, P3, or P5 operands
001277  ** for a specific instruction.
001278  */
001279  void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){
001280    assert( addr>=0 );
001281    sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
001282  }
001283  void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
001284    assert( addr>=0 );
001285    sqlite3VdbeGetOp(p,addr)->p1 = val;
001286  }
001287  void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
001288    assert( addr>=0 || p->db->mallocFailed );
001289    sqlite3VdbeGetOp(p,addr)->p2 = val;
001290  }
001291  void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
001292    assert( addr>=0 );
001293    sqlite3VdbeGetOp(p,addr)->p3 = val;
001294  }
001295  void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
001296    assert( p->nOp>0 || p->db->mallocFailed );
001297    if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
001298  }
001299  
001300  /*
001301  ** If the previous opcode is an OP_Column that delivers results
001302  ** into register iDest, then add the OPFLAG_TYPEOFARG flag to that
001303  ** opcode.
001304  */
001305  void sqlite3VdbeTypeofColumn(Vdbe *p, int iDest){
001306    VdbeOp *pOp = sqlite3VdbeGetLastOp(p);
001307    if( pOp->p3==iDest && pOp->opcode==OP_Column ){
001308      pOp->p5 |= OPFLAG_TYPEOFARG;
001309    }
001310  }
001311  
001312  /*
001313  ** Change the P2 operand of instruction addr so that it points to
001314  ** the address of the next instruction to be coded.
001315  */
001316  void sqlite3VdbeJumpHere(Vdbe *p, int addr){
001317    sqlite3VdbeChangeP2(p, addr, p->nOp);
001318  }
001319  
001320  /*
001321  ** Change the P2 operand of the jump instruction at addr so that
001322  ** the jump lands on the next opcode.  Or if the jump instruction was
001323  ** the previous opcode (and is thus a no-op) then simply back up
001324  ** the next instruction counter by one slot so that the jump is
001325  ** overwritten by the next inserted opcode.
001326  **
001327  ** This routine is an optimization of sqlite3VdbeJumpHere() that
001328  ** strives to omit useless byte-code like this:
001329  **
001330  **        7   Once 0 8 0
001331  **        8   ...
001332  */
001333  void sqlite3VdbeJumpHereOrPopInst(Vdbe *p, int addr){
001334    if( addr==p->nOp-1 ){
001335      assert( p->aOp[addr].opcode==OP_Once
001336           || p->aOp[addr].opcode==OP_If
001337           || p->aOp[addr].opcode==OP_FkIfZero );
001338      assert( p->aOp[addr].p4type==0 );
001339  #ifdef SQLITE_VDBE_COVERAGE
001340      sqlite3VdbeGetLastOp(p)->iSrcLine = 0;  /* Erase VdbeCoverage() macros */
001341  #endif
001342      p->nOp--;
001343    }else{
001344      sqlite3VdbeChangeP2(p, addr, p->nOp);
001345    }
001346  }
001347  
001348  
001349  /*
001350  ** If the input FuncDef structure is ephemeral, then free it.  If
001351  ** the FuncDef is not ephemeral, then do nothing.
001352  */
001353  static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
001354    assert( db!=0 );
001355    if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
001356      sqlite3DbNNFreeNN(db, pDef);
001357    }
001358  }
001359  
001360  /*
001361  ** Delete a P4 value if necessary.
001362  */
001363  static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
001364    if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
001365    sqlite3DbNNFreeNN(db, p);
001366  }
001367  static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
001368    assert( db!=0 );
001369    freeEphemeralFunction(db, p->pFunc);
001370    sqlite3DbNNFreeNN(db, p);
001371  }
001372  static void freeP4(sqlite3 *db, int p4type, void *p4){
001373    assert( db );
001374    switch( p4type ){
001375      case P4_FUNCCTX: {
001376        freeP4FuncCtx(db, (sqlite3_context*)p4);
001377        break;
001378      }
001379      case P4_REAL:
001380      case P4_INT64:
001381      case P4_DYNAMIC:
001382      case P4_INTARRAY: {
001383        if( p4 ) sqlite3DbNNFreeNN(db, p4);
001384        break;
001385      }
001386      case P4_KEYINFO: {
001387        if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
001388        break;
001389      }
001390  #ifdef SQLITE_ENABLE_CURSOR_HINTS
001391      case P4_EXPR: {
001392        sqlite3ExprDelete(db, (Expr*)p4);
001393        break;
001394      }
001395  #endif
001396      case P4_FUNCDEF: {
001397        freeEphemeralFunction(db, (FuncDef*)p4);
001398        break;
001399      }
001400      case P4_MEM: {
001401        if( db->pnBytesFreed==0 ){
001402          sqlite3ValueFree((sqlite3_value*)p4);
001403        }else{
001404          freeP4Mem(db, (Mem*)p4);
001405        }
001406        break;
001407      }
001408      case P4_VTAB : {
001409        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
001410        break;
001411      }
001412      case P4_TABLEREF: {
001413        if( db->pnBytesFreed==0 ) sqlite3DeleteTable(db, (Table*)p4);
001414        break;
001415      }
001416      case P4_SUBRTNSIG: {
001417        SubrtnSig *pSig = (SubrtnSig*)p4;
001418        sqlite3DbFree(db, pSig->zAff);
001419        sqlite3DbFree(db, pSig);
001420        break;
001421      }
001422    }
001423  }
001424  
001425  /*
001426  ** Free the space allocated for aOp and any p4 values allocated for the
001427  ** opcodes contained within. If aOp is not NULL it is assumed to contain
001428  ** nOp entries.
001429  */
001430  static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
001431    assert( nOp>=0 );
001432    assert( db!=0 );
001433    if( aOp ){
001434      Op *pOp = &aOp[nOp-1];
001435      while(1){  /* Exit via break */
001436        if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
001437  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
001438        sqlite3DbFree(db, pOp->zComment);
001439  #endif    
001440        if( pOp==aOp ) break;
001441        pOp--;
001442      }
001443      sqlite3DbNNFreeNN(db, aOp);
001444    }
001445  }
001446  
001447  /*
001448  ** Link the SubProgram object passed as the second argument into the linked
001449  ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
001450  ** objects when the VM is no longer required.
001451  */
001452  void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
001453    p->pNext = pVdbe->pProgram;
001454    pVdbe->pProgram = p;
001455  }
001456  
001457  /*
001458  ** Return true if the given Vdbe has any SubPrograms.
001459  */
001460  int sqlite3VdbeHasSubProgram(Vdbe *pVdbe){
001461    return pVdbe->pProgram!=0;
001462  }
001463  
001464  /*
001465  ** Change the opcode at addr into OP_Noop
001466  */
001467  int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
001468    VdbeOp *pOp;
001469    if( p->db->mallocFailed ) return 0;
001470    assert( addr>=0 && addr<p->nOp );
001471    pOp = &p->aOp[addr];
001472    freeP4(p->db, pOp->p4type, pOp->p4.p);
001473    pOp->p4type = P4_NOTUSED;
001474    pOp->p4.z = 0;
001475    pOp->opcode = OP_Noop;
001476    return 1;
001477  }
001478  
001479  /*
001480  ** If the last opcode is "op" and it is not a jump destination,
001481  ** then remove it.  Return true if and only if an opcode was removed.
001482  */
001483  int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
001484    if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
001485      return sqlite3VdbeChangeToNoop(p, p->nOp-1);
001486    }else{
001487      return 0;
001488    }
001489  }
001490  
001491  #ifdef SQLITE_DEBUG
001492  /*
001493  ** Generate an OP_ReleaseReg opcode to indicate that a range of
001494  ** registers, except any identified by mask, are no longer in use.
001495  */
001496  void sqlite3VdbeReleaseRegisters(
001497    Parse *pParse,       /* Parsing context */
001498    int iFirst,          /* Index of first register to be released */
001499    int N,               /* Number of registers to release */
001500    u32 mask,            /* Mask of registers to NOT release */
001501    int bUndefine        /* If true, mark registers as undefined */
001502  ){
001503    if( N==0 || OptimizationDisabled(pParse->db, SQLITE_ReleaseReg) ) return;
001504    assert( pParse->pVdbe );
001505    assert( iFirst>=1 );
001506    assert( iFirst+N-1<=pParse->nMem );
001507    if( N<=31 && mask!=0 ){
001508      while( N>0 && (mask&1)!=0 ){
001509        mask >>= 1;
001510        iFirst++;
001511        N--;
001512      }
001513      while( N>0 && N<=32 && (mask & MASKBIT32(N-1))!=0 ){
001514        mask &= ~MASKBIT32(N-1);
001515        N--;
001516      }
001517    }
001518    if( N>0 ){
001519      sqlite3VdbeAddOp3(pParse->pVdbe, OP_ReleaseReg, iFirst, N, *(int*)&mask);
001520      if( bUndefine ) sqlite3VdbeChangeP5(pParse->pVdbe, 1);
001521    }
001522  }
001523  #endif /* SQLITE_DEBUG */
001524  
001525  /*
001526  ** Change the value of the P4 operand for a specific instruction.
001527  ** This routine is useful when a large program is loaded from a
001528  ** static array using sqlite3VdbeAddOpList but we want to make a
001529  ** few minor changes to the program.
001530  **
001531  ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
001532  ** the string is made into memory obtained from sqlite3_malloc().
001533  ** A value of n==0 means copy bytes of zP4 up to and including the
001534  ** first null byte.  If n>0 then copy n+1 bytes of zP4.
001535  **
001536  ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
001537  ** to a string or structure that is guaranteed to exist for the lifetime of
001538  ** the Vdbe. In these cases we can just copy the pointer.
001539  **
001540  ** If addr<0 then change P4 on the most recently inserted instruction.
001541  */
001542  static void SQLITE_NOINLINE vdbeChangeP4Full(
001543    Vdbe *p,
001544    Op *pOp,
001545    const char *zP4,
001546    int n
001547  ){
001548    if( pOp->p4type ){
001549      assert( pOp->p4type > P4_FREE_IF_LE );
001550      pOp->p4type = 0;
001551      pOp->p4.p = 0;
001552    }
001553    if( n<0 ){
001554      sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
001555    }else{
001556      if( n==0 ) n = sqlite3Strlen30(zP4);
001557      pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
001558      pOp->p4type = P4_DYNAMIC;
001559    }
001560  }
001561  void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
001562    Op *pOp;
001563    sqlite3 *db;
001564    assert( p!=0 );
001565    db = p->db;
001566    assert( p->eVdbeState==VDBE_INIT_STATE );
001567    assert( p->aOp!=0 || db->mallocFailed );
001568    if( db->mallocFailed ){
001569      if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
001570      return;
001571    }
001572    assert( p->nOp>0 );
001573    assert( addr<p->nOp );
001574    if( addr<0 ){
001575      addr = p->nOp - 1;
001576    }
001577    pOp = &p->aOp[addr];
001578    if( n>=0 || pOp->p4type ){
001579      vdbeChangeP4Full(p, pOp, zP4, n);
001580      return;
001581    }
001582    if( n==P4_INT32 ){
001583      /* Note: this cast is safe, because the origin data point was an int
001584      ** that was cast to a (const char *). */
001585      pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
001586      pOp->p4type = P4_INT32;
001587    }else if( zP4!=0 ){
001588      assert( n<0 );
001589      pOp->p4.p = (void*)zP4;
001590      pOp->p4type = (signed char)n;
001591      if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
001592    }
001593  }
001594  
001595  /*
001596  ** Change the P4 operand of the most recently coded instruction
001597  ** to the value defined by the arguments.  This is a high-speed
001598  ** version of sqlite3VdbeChangeP4().
001599  **
001600  ** The P4 operand must not have been previously defined.  And the new
001601  ** P4 must not be P4_INT32.  Use sqlite3VdbeChangeP4() in either of
001602  ** those cases.
001603  */
001604  void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
001605    VdbeOp *pOp;
001606    assert( n!=P4_INT32 && n!=P4_VTAB );
001607    assert( n<=0 );
001608    if( p->db->mallocFailed ){
001609      freeP4(p->db, n, pP4);
001610    }else{
001611      assert( pP4!=0 || n==P4_DYNAMIC );
001612      assert( p->nOp>0 );
001613      pOp = &p->aOp[p->nOp-1];
001614      assert( pOp->p4type==P4_NOTUSED );
001615      pOp->p4type = n;
001616      pOp->p4.p = pP4;
001617    }
001618  }
001619  
001620  /*
001621  ** Set the P4 on the most recently added opcode to the KeyInfo for the
001622  ** index given.
001623  */
001624  void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
001625    Vdbe *v = pParse->pVdbe;
001626    KeyInfo *pKeyInfo;
001627    assert( v!=0 );
001628    assert( pIdx!=0 );
001629    pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
001630    if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
001631  }
001632  
001633  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
001634  /*
001635  ** Change the comment on the most recently coded instruction.  Or
001636  ** insert a No-op and add the comment to that new instruction.  This
001637  ** makes the code easier to read during debugging.  None of this happens
001638  ** in a production build.
001639  */
001640  static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
001641    assert( p->nOp>0 || p->aOp==0 );
001642    assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->pParse->nErr>0 );
001643    if( p->nOp ){
001644      assert( p->aOp );
001645      sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
001646      p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
001647    }
001648  }
001649  void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
001650    va_list ap;
001651    if( p ){
001652      va_start(ap, zFormat);
001653      vdbeVComment(p, zFormat, ap);
001654      va_end(ap);
001655    }
001656  }
001657  void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
001658    va_list ap;
001659    if( p ){
001660      sqlite3VdbeAddOp0(p, OP_Noop);
001661      va_start(ap, zFormat);
001662      vdbeVComment(p, zFormat, ap);
001663      va_end(ap);
001664    }
001665  }
001666  #endif  /* NDEBUG */
001667  
001668  #ifdef SQLITE_VDBE_COVERAGE
001669  /*
001670  ** Set the value if the iSrcLine field for the previously coded instruction.
001671  */
001672  void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
001673    sqlite3VdbeGetLastOp(v)->iSrcLine = iLine;
001674  }
001675  #endif /* SQLITE_VDBE_COVERAGE */
001676  
001677  /*
001678  ** Return the opcode for a given address.  The address must be non-negative.
001679  ** See sqlite3VdbeGetLastOp() to get the most recently added opcode.
001680  **
001681  ** If a memory allocation error has occurred prior to the calling of this
001682  ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
001683  ** is readable but not writable, though it is cast to a writable value.
001684  ** The return of a dummy opcode allows the call to continue functioning
001685  ** after an OOM fault without having to check to see if the return from
001686  ** this routine is a valid pointer.  But because the dummy.opcode is 0,
001687  ** dummy will never be written to.  This is verified by code inspection and
001688  ** by running with Valgrind.
001689  */
001690  VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
001691    /* C89 specifies that the constant "dummy" will be initialized to all
001692    ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
001693    static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
001694    assert( p->eVdbeState==VDBE_INIT_STATE );
001695    assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
001696    if( p->db->mallocFailed ){
001697      return (VdbeOp*)&dummy;
001698    }else{
001699      return &p->aOp[addr];
001700    }
001701  }
001702  
001703  /* Return the most recently added opcode
001704  */
001705  VdbeOp *sqlite3VdbeGetLastOp(Vdbe *p){
001706    return sqlite3VdbeGetOp(p, p->nOp - 1);
001707  }
001708  
001709  #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
001710  /*
001711  ** Return an integer value for one of the parameters to the opcode pOp
001712  ** determined by character c.
001713  */
001714  static int translateP(char c, const Op *pOp){
001715    if( c=='1' ) return pOp->p1;
001716    if( c=='2' ) return pOp->p2;
001717    if( c=='3' ) return pOp->p3;
001718    if( c=='4' ) return pOp->p4.i;
001719    return pOp->p5;
001720  }
001721  
001722  /*
001723  ** Compute a string for the "comment" field of a VDBE opcode listing.
001724  **
001725  ** The Synopsis: field in comments in the vdbe.c source file gets converted
001726  ** to an extra string that is appended to the sqlite3OpcodeName().  In the
001727  ** absence of other comments, this synopsis becomes the comment on the opcode.
001728  ** Some translation occurs:
001729  **
001730  **       "PX"      ->  "r[X]"
001731  **       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
001732  **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
001733  **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
001734  */
001735  char *sqlite3VdbeDisplayComment(
001736    sqlite3 *db,       /* Optional - Oom error reporting only */
001737    const Op *pOp,     /* The opcode to be commented */
001738    const char *zP4    /* Previously obtained value for P4 */
001739  ){
001740    const char *zOpName;
001741    const char *zSynopsis;
001742    int nOpName;
001743    int ii;
001744    char zAlt[50];
001745    StrAccum x;
001746  
001747    sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
001748    zOpName = sqlite3OpcodeName(pOp->opcode);
001749    nOpName = sqlite3Strlen30(zOpName);
001750    if( zOpName[nOpName+1] ){
001751      int seenCom = 0;
001752      char c;
001753      zSynopsis = zOpName + nOpName + 1;
001754      if( strncmp(zSynopsis,"IF ",3)==0 ){
001755        sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
001756        zSynopsis = zAlt;
001757      }
001758      for(ii=0; (c = zSynopsis[ii])!=0; ii++){
001759        if( c=='P' ){
001760          c = zSynopsis[++ii];
001761          if( c=='4' ){
001762            sqlite3_str_appendall(&x, zP4);
001763          }else if( c=='X' ){
001764            if( pOp->zComment && pOp->zComment[0] ){
001765              sqlite3_str_appendall(&x, pOp->zComment);
001766              seenCom = 1;
001767              break;
001768            }
001769          }else{
001770            int v1 = translateP(c, pOp);
001771            int v2;
001772            if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
001773              ii += 3;
001774              v2 = translateP(zSynopsis[ii], pOp);
001775              if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
001776                ii += 2;
001777                v2++;
001778              }
001779              if( v2<2 ){
001780                sqlite3_str_appendf(&x, "%d", v1);
001781              }else{
001782                sqlite3_str_appendf(&x, "%d..%d", v1, v1+v2-1);
001783              }
001784            }else if( strncmp(zSynopsis+ii+1, "@NP", 3)==0 ){
001785              sqlite3_context *pCtx = pOp->p4.pCtx;
001786              if( pOp->p4type!=P4_FUNCCTX || pCtx->argc==1 ){
001787                sqlite3_str_appendf(&x, "%d", v1);
001788              }else if( pCtx->argc>1 ){
001789                sqlite3_str_appendf(&x, "%d..%d", v1, v1+pCtx->argc-1);
001790              }else if( x.accError==0 ){
001791                assert( x.nChar>2 );
001792                x.nChar -= 2;
001793                ii++;
001794              }
001795              ii += 3;
001796            }else{
001797              sqlite3_str_appendf(&x, "%d", v1);
001798              if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
001799                ii += 4;
001800              }
001801            }
001802          }
001803        }else{
001804          sqlite3_str_appendchar(&x, 1, c);
001805        }
001806      }
001807      if( !seenCom && pOp->zComment ){
001808        sqlite3_str_appendf(&x, "; %s", pOp->zComment);
001809      }
001810    }else if( pOp->zComment ){
001811      sqlite3_str_appendall(&x, pOp->zComment);
001812    }
001813    if( (x.accError & SQLITE_NOMEM)!=0 && db!=0 ){
001814      sqlite3OomFault(db);
001815    }
001816    return sqlite3StrAccumFinish(&x);
001817  }
001818  #endif /* SQLITE_ENABLE_EXPLAIN_COMMENTS */
001819  
001820  #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
001821  /*
001822  ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
001823  ** that can be displayed in the P4 column of EXPLAIN output.
001824  */
001825  static void displayP4Expr(StrAccum *p, Expr *pExpr){
001826    const char *zOp = 0;
001827    switch( pExpr->op ){
001828      case TK_STRING:
001829        assert( !ExprHasProperty(pExpr, EP_IntValue) );
001830        sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
001831        break;
001832      case TK_INTEGER:
001833        sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
001834        break;
001835      case TK_NULL:
001836        sqlite3_str_appendf(p, "NULL");
001837        break;
001838      case TK_REGISTER: {
001839        sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
001840        break;
001841      }
001842      case TK_COLUMN: {
001843        if( pExpr->iColumn<0 ){
001844          sqlite3_str_appendf(p, "rowid");
001845        }else{
001846          sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
001847        }
001848        break;
001849      }
001850      case TK_LT:      zOp = "LT";      break;
001851      case TK_LE:      zOp = "LE";      break;
001852      case TK_GT:      zOp = "GT";      break;
001853      case TK_GE:      zOp = "GE";      break;
001854      case TK_NE:      zOp = "NE";      break;
001855      case TK_EQ:      zOp = "EQ";      break;
001856      case TK_IS:      zOp = "IS";      break;
001857      case TK_ISNOT:   zOp = "ISNOT";   break;
001858      case TK_AND:     zOp = "AND";     break;
001859      case TK_OR:      zOp = "OR";      break;
001860      case TK_PLUS:    zOp = "ADD";     break;
001861      case TK_STAR:    zOp = "MUL";     break;
001862      case TK_MINUS:   zOp = "SUB";     break;
001863      case TK_REM:     zOp = "REM";     break;
001864      case TK_BITAND:  zOp = "BITAND";  break;
001865      case TK_BITOR:   zOp = "BITOR";   break;
001866      case TK_SLASH:   zOp = "DIV";     break;
001867      case TK_LSHIFT:  zOp = "LSHIFT";  break;
001868      case TK_RSHIFT:  zOp = "RSHIFT";  break;
001869      case TK_CONCAT:  zOp = "CONCAT";  break;
001870      case TK_UMINUS:  zOp = "MINUS";   break;
001871      case TK_UPLUS:   zOp = "PLUS";    break;
001872      case TK_BITNOT:  zOp = "BITNOT";  break;
001873      case TK_NOT:     zOp = "NOT";     break;
001874      case TK_ISNULL:  zOp = "ISNULL";  break;
001875      case TK_NOTNULL: zOp = "NOTNULL"; break;
001876  
001877      default:
001878        sqlite3_str_appendf(p, "%s", "expr");
001879        break;
001880    }
001881  
001882    if( zOp ){
001883      sqlite3_str_appendf(p, "%s(", zOp);
001884      displayP4Expr(p, pExpr->pLeft);
001885      if( pExpr->pRight ){
001886        sqlite3_str_append(p, ",", 1);
001887        displayP4Expr(p, pExpr->pRight);
001888      }
001889      sqlite3_str_append(p, ")", 1);
001890    }
001891  }
001892  #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
001893  
001894  
001895  #if VDBE_DISPLAY_P4
001896  /*
001897  ** Compute a string that describes the P4 parameter for an opcode.
001898  ** Use zTemp for any required temporary buffer space.
001899  */
001900  char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){
001901    char *zP4 = 0;
001902    StrAccum x;
001903  
001904    sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
001905    switch( pOp->p4type ){
001906      case P4_KEYINFO: {
001907        int j;
001908        KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
001909        assert( pKeyInfo->aSortFlags!=0 );
001910        sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
001911        for(j=0; j<pKeyInfo->nKeyField; j++){
001912          CollSeq *pColl = pKeyInfo->aColl[j];
001913          const char *zColl = pColl ? pColl->zName : "";
001914          if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
001915          sqlite3_str_appendf(&x, ",%s%s%s",
001916                 (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "",
001917                 (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "",
001918                 zColl);
001919        }
001920        sqlite3_str_append(&x, ")", 1);
001921        break;
001922      }
001923  #ifdef SQLITE_ENABLE_CURSOR_HINTS
001924      case P4_EXPR: {
001925        displayP4Expr(&x, pOp->p4.pExpr);
001926        break;
001927      }
001928  #endif
001929      case P4_COLLSEQ: {
001930        static const char *const encnames[] = {"?", "8", "16LE", "16BE"};
001931        CollSeq *pColl = pOp->p4.pColl;
001932        assert( pColl->enc<4 );
001933        sqlite3_str_appendf(&x, "%.18s-%s", pColl->zName,
001934                            encnames[pColl->enc]);
001935        break;
001936      }
001937      case P4_FUNCDEF: {
001938        FuncDef *pDef = pOp->p4.pFunc;
001939        sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
001940        break;
001941      }
001942      case P4_FUNCCTX: {
001943        FuncDef *pDef = pOp->p4.pCtx->pFunc;
001944        sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
001945        break;
001946      }
001947      case P4_INT64: {
001948        sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
001949        break;
001950      }
001951      case P4_INT32: {
001952        sqlite3_str_appendf(&x, "%d", pOp->p4.i);
001953        break;
001954      }
001955      case P4_REAL: {
001956        sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
001957        break;
001958      }
001959      case P4_MEM: {
001960        Mem *pMem = pOp->p4.pMem;
001961        if( pMem->flags & MEM_Str ){
001962          zP4 = pMem->z;
001963        }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
001964          sqlite3_str_appendf(&x, "%lld", pMem->u.i);
001965        }else if( pMem->flags & MEM_Real ){
001966          sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
001967        }else if( pMem->flags & MEM_Null ){
001968          zP4 = "NULL";
001969        }else{
001970          assert( pMem->flags & MEM_Blob );
001971          zP4 = "(blob)";
001972        }
001973        break;
001974      }
001975  #ifndef SQLITE_OMIT_VIRTUALTABLE
001976      case P4_VTAB: {
001977        sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
001978        sqlite3_str_appendf(&x, "vtab:%p", pVtab);
001979        break;
001980      }
001981  #endif
001982      case P4_INTARRAY: {
001983        u32 i;
001984        u32 *ai = pOp->p4.ai;
001985        u32 n = ai[0];   /* The first element of an INTARRAY is always the
001986                         ** count of the number of elements to follow */
001987        for(i=1; i<=n; i++){
001988          sqlite3_str_appendf(&x, "%c%u", (i==1 ? '[' : ','), ai[i]);
001989        }
001990        sqlite3_str_append(&x, "]", 1);
001991        break;
001992      }
001993      case P4_SUBPROGRAM: {
001994        zP4 = "program";
001995        break;
001996      }
001997      case P4_TABLE: {
001998        zP4 = pOp->p4.pTab->zName;
001999        break;
002000      }
002001      case P4_SUBRTNSIG: {
002002        SubrtnSig *pSig = pOp->p4.pSubrtnSig;
002003        sqlite3_str_appendf(&x, "subrtnsig:%d,%s", pSig->selId, pSig->zAff);
002004        break;
002005      }
002006      default: {
002007        zP4 = pOp->p4.z;
002008      }
002009    }
002010    if( zP4 ) sqlite3_str_appendall(&x, zP4);
002011    if( (x.accError & SQLITE_NOMEM)!=0 ){
002012      sqlite3OomFault(db);
002013    }
002014    return sqlite3StrAccumFinish(&x);
002015  }
002016  #endif /* VDBE_DISPLAY_P4 */
002017  
002018  /*
002019  ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
002020  **
002021  ** The prepared statements need to know in advance the complete set of
002022  ** attached databases that will be use.  A mask of these databases
002023  ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
002024  ** p->btreeMask of databases that will require a lock.
002025  */
002026  void sqlite3VdbeUsesBtree(Vdbe *p, int i){
002027    assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
002028    assert( i<(int)sizeof(p->btreeMask)*8 );
002029    DbMaskSet(p->btreeMask, i);
002030    if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
002031      DbMaskSet(p->lockMask, i);
002032    }
002033  }
002034  
002035  #if !defined(SQLITE_OMIT_SHARED_CACHE)
002036  /*
002037  ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
002038  ** this routine obtains the mutex associated with each BtShared structure
002039  ** that may be accessed by the VM passed as an argument. In doing so it also
002040  ** sets the BtShared.db member of each of the BtShared structures, ensuring
002041  ** that the correct busy-handler callback is invoked if required.
002042  **
002043  ** If SQLite is not threadsafe but does support shared-cache mode, then
002044  ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
002045  ** of all of BtShared structures accessible via the database handle
002046  ** associated with the VM.
002047  **
002048  ** If SQLite is not threadsafe and does not support shared-cache mode, this
002049  ** function is a no-op.
002050  **
002051  ** The p->btreeMask field is a bitmask of all btrees that the prepared
002052  ** statement p will ever use.  Let N be the number of bits in p->btreeMask
002053  ** corresponding to btrees that use shared cache.  Then the runtime of
002054  ** this routine is N*N.  But as N is rarely more than 1, this should not
002055  ** be a problem.
002056  */
002057  void sqlite3VdbeEnter(Vdbe *p){
002058    int i;
002059    sqlite3 *db;
002060    Db *aDb;
002061    int nDb;
002062    if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
002063    db = p->db;
002064    aDb = db->aDb;
002065    nDb = db->nDb;
002066    for(i=0; i<nDb; i++){
002067      if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
002068        sqlite3BtreeEnter(aDb[i].pBt);
002069      }
002070    }
002071  }
002072  #endif
002073  
002074  #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
002075  /*
002076  ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
002077  */
002078  static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
002079    int i;
002080    sqlite3 *db;
002081    Db *aDb;
002082    int nDb;
002083    db = p->db;
002084    aDb = db->aDb;
002085    nDb = db->nDb;
002086    for(i=0; i<nDb; i++){
002087      if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
002088        sqlite3BtreeLeave(aDb[i].pBt);
002089      }
002090    }
002091  }
002092  void sqlite3VdbeLeave(Vdbe *p){
002093    if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
002094    vdbeLeave(p);
002095  }
002096  #endif
002097  
002098  #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
002099  /*
002100  ** Print a single opcode.  This routine is used for debugging only.
002101  */
002102  void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
002103    char *zP4;
002104    char *zCom;
002105    sqlite3 dummyDb;
002106    static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
002107    if( pOut==0 ) pOut = stdout;
002108    sqlite3BeginBenignMalloc();
002109    dummyDb.mallocFailed = 1;
002110    zP4 = sqlite3VdbeDisplayP4(&dummyDb, pOp);
002111  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
002112    zCom = sqlite3VdbeDisplayComment(0, pOp, zP4);
002113  #else
002114    zCom = 0;
002115  #endif
002116    /* NB:  The sqlite3OpcodeName() function is implemented by code created
002117    ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
002118    ** information from the vdbe.c source text */
002119    fprintf(pOut, zFormat1, pc,
002120        sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3,
002121        zP4 ? zP4 : "", pOp->p5,
002122        zCom ? zCom : ""
002123    );
002124    fflush(pOut);
002125    sqlite3_free(zP4);
002126    sqlite3_free(zCom);
002127    sqlite3EndBenignMalloc();
002128  }
002129  #endif
002130  
002131  /*
002132  ** Initialize an array of N Mem element.
002133  **
002134  ** This is a high-runner, so only those fields that really do need to
002135  ** be initialized are set.  The Mem structure is organized so that
002136  ** the fields that get initialized are nearby and hopefully on the same
002137  ** cache line.
002138  **
002139  **    Mem.flags = flags
002140  **    Mem.db = db
002141  **    Mem.szMalloc = 0
002142  **
002143  ** All other fields of Mem can safely remain uninitialized for now.  They
002144  ** will be initialized before use.
002145  */
002146  static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
002147    if( N>0 ){
002148      do{
002149        p->flags = flags;
002150        p->db = db;
002151        p->szMalloc = 0;
002152  #ifdef SQLITE_DEBUG
002153        p->pScopyFrom = 0;
002154  #endif
002155        p++;
002156      }while( (--N)>0 );
002157    }
002158  }
002159  
002160  /*
002161  ** Release auxiliary memory held in an array of N Mem elements.
002162  **
002163  ** After this routine returns, all Mem elements in the array will still
002164  ** be valid.  Those Mem elements that were not holding auxiliary resources
002165  ** will be unchanged.  Mem elements which had something freed will be
002166  ** set to MEM_Undefined.
002167  */
002168  static void releaseMemArray(Mem *p, int N){
002169    if( p && N ){
002170      Mem *pEnd = &p[N];
002171      sqlite3 *db = p->db;
002172      if( db->pnBytesFreed ){
002173        do{
002174          if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
002175        }while( (++p)<pEnd );
002176        return;
002177      }
002178      do{
002179        assert( (&p[1])==pEnd || p[0].db==p[1].db );
002180        assert( sqlite3VdbeCheckMemInvariants(p) );
002181  
002182        /* This block is really an inlined version of sqlite3VdbeMemRelease()
002183        ** that takes advantage of the fact that the memory cell value is
002184        ** being set to NULL after releasing any dynamic resources.
002185        **
002186        ** The justification for duplicating code is that according to
002187        ** callgrind, this causes a certain test case to hit the CPU 4.7
002188        ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
002189        ** sqlite3MemRelease() were called from here. With -O2, this jumps
002190        ** to 6.6 percent. The test case is inserting 1000 rows into a table
002191        ** with no indexes using a single prepared INSERT statement, bind()
002192        ** and reset(). Inserts are grouped into a transaction.
002193        */
002194        testcase( p->flags & MEM_Agg );
002195        testcase( p->flags & MEM_Dyn );
002196        if( p->flags&(MEM_Agg|MEM_Dyn) ){
002197          testcase( (p->flags & MEM_Dyn)!=0 && p->xDel==sqlite3VdbeFrameMemDel );
002198          sqlite3VdbeMemRelease(p);
002199          p->flags = MEM_Undefined;
002200        }else if( p->szMalloc ){
002201          sqlite3DbNNFreeNN(db, p->zMalloc);
002202          p->szMalloc = 0;
002203          p->flags = MEM_Undefined;
002204        }
002205  #ifdef SQLITE_DEBUG
002206        else{
002207          p->flags = MEM_Undefined;
002208        }
002209  #endif
002210      }while( (++p)<pEnd );
002211    }
002212  }
002213  
002214  #ifdef SQLITE_DEBUG
002215  /*
002216  ** Verify that pFrame is a valid VdbeFrame pointer.  Return true if it is
002217  ** and false if something is wrong.
002218  **
002219  ** This routine is intended for use inside of assert() statements only.
002220  */
002221  int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){
002222    if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
002223    return 1;
002224  }
002225  #endif
002226  
002227  
002228  /*
002229  ** This is a destructor on a Mem object (which is really an sqlite3_value)
002230  ** that deletes the Frame object that is attached to it as a blob.
002231  **
002232  ** This routine does not delete the Frame right away.  It merely adds the
002233  ** frame to a list of frames to be deleted when the Vdbe halts.
002234  */
002235  void sqlite3VdbeFrameMemDel(void *pArg){
002236    VdbeFrame *pFrame = (VdbeFrame*)pArg;
002237    assert( sqlite3VdbeFrameIsValid(pFrame) );
002238    pFrame->pParent = pFrame->v->pDelFrame;
002239    pFrame->v->pDelFrame = pFrame;
002240  }
002241  
002242  #if defined(SQLITE_ENABLE_BYTECODE_VTAB) || !defined(SQLITE_OMIT_EXPLAIN)
002243  /*
002244  ** Locate the next opcode to be displayed in EXPLAIN or EXPLAIN
002245  ** QUERY PLAN output.
002246  **
002247  ** Return SQLITE_ROW on success.  Return SQLITE_DONE if there are no
002248  ** more opcodes to be displayed.
002249  */
002250  int sqlite3VdbeNextOpcode(
002251    Vdbe *p,         /* The statement being explained */
002252    Mem *pSub,       /* Storage for keeping track of subprogram nesting */
002253    int eMode,       /* 0: normal.  1: EQP.  2:  TablesUsed */
002254    int *piPc,       /* IN/OUT: Current rowid.  Overwritten with next rowid */
002255    int *piAddr,     /* OUT: Write index into (*paOp)[] here */
002256    Op **paOp        /* OUT: Write the opcode array here */
002257  ){
002258    int nRow;                            /* Stop when row count reaches this */
002259    int nSub = 0;                        /* Number of sub-vdbes seen so far */
002260    SubProgram **apSub = 0;              /* Array of sub-vdbes */
002261    int i;                               /* Next instruction address */
002262    int rc = SQLITE_OK;                  /* Result code */
002263    Op *aOp = 0;                         /* Opcode array */
002264    int iPc;                             /* Rowid.  Copy of value in *piPc */
002265  
002266    /* When the number of output rows reaches nRow, that means the
002267    ** listing has finished and sqlite3_step() should return SQLITE_DONE.
002268    ** nRow is the sum of the number of rows in the main program, plus
002269    ** the sum of the number of rows in all trigger subprograms encountered
002270    ** so far.  The nRow value will increase as new trigger subprograms are
002271    ** encountered, but p->pc will eventually catch up to nRow.
002272    */
002273    nRow = p->nOp;
002274    if( pSub!=0 ){
002275      if( pSub->flags&MEM_Blob ){
002276        /* pSub is initiallly NULL.  It is initialized to a BLOB by
002277        ** the P4_SUBPROGRAM processing logic below */
002278        nSub = pSub->n/sizeof(Vdbe*);
002279        apSub = (SubProgram **)pSub->z;
002280      }
002281      for(i=0; i<nSub; i++){
002282        nRow += apSub[i]->nOp;
002283      }
002284    }
002285    iPc = *piPc;
002286    while(1){  /* Loop exits via break */
002287      i = iPc++;
002288      if( i>=nRow ){
002289        p->rc = SQLITE_OK;
002290        rc = SQLITE_DONE;
002291        break;
002292      }
002293      if( i<p->nOp ){
002294        /* The rowid is small enough that we are still in the
002295        ** main program. */
002296        aOp = p->aOp;
002297      }else{
002298        /* We are currently listing subprograms.  Figure out which one and
002299        ** pick up the appropriate opcode. */
002300        int j;
002301        i -= p->nOp;
002302        assert( apSub!=0 );
002303        assert( nSub>0 );
002304        for(j=0; i>=apSub[j]->nOp; j++){
002305          i -= apSub[j]->nOp;
002306          assert( i<apSub[j]->nOp || j+1<nSub );
002307        }
002308        aOp = apSub[j]->aOp;
002309      }
002310  
002311      /* When an OP_Program opcode is encounter (the only opcode that has
002312      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
002313      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
002314      ** has not already been seen.
002315      */
002316      if( pSub!=0 && aOp[i].p4type==P4_SUBPROGRAM ){
002317        int nByte = (nSub+1)*sizeof(SubProgram*);
002318        int j;
002319        for(j=0; j<nSub; j++){
002320          if( apSub[j]==aOp[i].p4.pProgram ) break;
002321        }
002322        if( j==nSub ){
002323          p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
002324          if( p->rc!=SQLITE_OK ){
002325            rc = SQLITE_ERROR;
002326            break;
002327          }
002328          apSub = (SubProgram **)pSub->z;
002329          apSub[nSub++] = aOp[i].p4.pProgram;
002330          MemSetTypeFlag(pSub, MEM_Blob);
002331          pSub->n = nSub*sizeof(SubProgram*);
002332          nRow += aOp[i].p4.pProgram->nOp;
002333        }
002334      }
002335      if( eMode==0 ) break;
002336  #ifdef SQLITE_ENABLE_BYTECODE_VTAB
002337      if( eMode==2 ){
002338        Op *pOp = aOp + i;
002339        if( pOp->opcode==OP_OpenRead ) break;
002340        if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;
002341        if( pOp->opcode==OP_ReopenIdx ) break;     
002342      }else
002343  #endif
002344      {
002345        assert( eMode==1 );
002346        if( aOp[i].opcode==OP_Explain ) break;
002347        if( aOp[i].opcode==OP_Init && iPc>1 ) break;
002348      }
002349    }
002350    *piPc = iPc;
002351    *piAddr = i;
002352    *paOp = aOp;
002353    return rc;
002354  }
002355  #endif /* SQLITE_ENABLE_BYTECODE_VTAB || !SQLITE_OMIT_EXPLAIN */
002356  
002357  
002358  /*
002359  ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
002360  ** allocated by the OP_Program opcode in sqlite3VdbeExec().
002361  */
002362  void sqlite3VdbeFrameDelete(VdbeFrame *p){
002363    int i;
002364    Mem *aMem = VdbeFrameMem(p);
002365    VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
002366    assert( sqlite3VdbeFrameIsValid(p) );
002367    for(i=0; i<p->nChildCsr; i++){
002368      if( apCsr[i] ) sqlite3VdbeFreeCursorNN(p->v, apCsr[i]);
002369    }
002370    releaseMemArray(aMem, p->nChildMem);
002371    sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
002372    sqlite3DbFree(p->v->db, p);
002373  }
002374  
002375  #ifndef SQLITE_OMIT_EXPLAIN
002376  /*
002377  ** Give a listing of the program in the virtual machine.
002378  **
002379  ** The interface is the same as sqlite3VdbeExec().  But instead of
002380  ** running the code, it invokes the callback once for each instruction.
002381  ** This feature is used to implement "EXPLAIN".
002382  **
002383  ** When p->explain==1, each instruction is listed.  When
002384  ** p->explain==2, only OP_Explain instructions are listed and these
002385  ** are shown in a different format.  p->explain==2 is used to implement
002386  ** EXPLAIN QUERY PLAN.
002387  ** 2018-04-24:  In p->explain==2 mode, the OP_Init opcodes of triggers
002388  ** are also shown, so that the boundaries between the main program and
002389  ** each trigger are clear.
002390  **
002391  ** When p->explain==1, first the main program is listed, then each of
002392  ** the trigger subprograms are listed one by one.
002393  */
002394  int sqlite3VdbeList(
002395    Vdbe *p                   /* The VDBE */
002396  ){
002397    Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
002398    sqlite3 *db = p->db;                 /* The database connection */
002399    int i;                               /* Loop counter */
002400    int rc = SQLITE_OK;                  /* Return code */
002401    Mem *pMem = &p->aMem[1];             /* First Mem of result set */
002402    int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
002403    Op *aOp;                             /* Array of opcodes */
002404    Op *pOp;                             /* Current opcode */
002405  
002406    assert( p->explain );
002407    assert( p->eVdbeState==VDBE_RUN_STATE );
002408    assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
002409  
002410    /* Even though this opcode does not use dynamic strings for
002411    ** the result, result columns may become dynamic if the user calls
002412    ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
002413    */
002414    releaseMemArray(pMem, 8);
002415  
002416    if( p->rc==SQLITE_NOMEM ){
002417      /* This happens if a malloc() inside a call to sqlite3_column_text() or
002418      ** sqlite3_column_text16() failed.  */
002419      sqlite3OomFault(db);
002420      return SQLITE_ERROR;
002421    }
002422  
002423    if( bListSubprogs ){
002424      /* The first 8 memory cells are used for the result set.  So we will
002425      ** commandeer the 9th cell to use as storage for an array of pointers
002426      ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
002427      ** cells.  */
002428      assert( p->nMem>9 );
002429      pSub = &p->aMem[9];
002430    }else{
002431      pSub = 0;
002432    }
002433  
002434    /* Figure out which opcode is next to display */
002435    rc = sqlite3VdbeNextOpcode(p, pSub, p->explain==2, &p->pc, &i, &aOp);
002436  
002437    if( rc==SQLITE_OK ){
002438      pOp = aOp + i;
002439      if( AtomicLoad(&db->u1.isInterrupted) ){
002440        p->rc = SQLITE_INTERRUPT;
002441        rc = SQLITE_ERROR;
002442        sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
002443      }else{
002444        char *zP4 = sqlite3VdbeDisplayP4(db, pOp);
002445        if( p->explain==2 ){
002446          sqlite3VdbeMemSetInt64(pMem, pOp->p1);
002447          sqlite3VdbeMemSetInt64(pMem+1, pOp->p2);
002448          sqlite3VdbeMemSetInt64(pMem+2, pOp->p3);
002449          sqlite3VdbeMemSetStr(pMem+3, zP4, -1, SQLITE_UTF8, sqlite3_free);
002450          assert( p->nResColumn==4 );
002451        }else{
002452          sqlite3VdbeMemSetInt64(pMem+0, i);
002453          sqlite3VdbeMemSetStr(pMem+1, (char*)sqlite3OpcodeName(pOp->opcode),
002454                               -1, SQLITE_UTF8, SQLITE_STATIC);
002455          sqlite3VdbeMemSetInt64(pMem+2, pOp->p1);
002456          sqlite3VdbeMemSetInt64(pMem+3, pOp->p2);
002457          sqlite3VdbeMemSetInt64(pMem+4, pOp->p3);
002458          /* pMem+5 for p4 is done last */
002459          sqlite3VdbeMemSetInt64(pMem+6, pOp->p5);
002460  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
002461          {
002462            char *zCom = sqlite3VdbeDisplayComment(db, pOp, zP4);
002463            sqlite3VdbeMemSetStr(pMem+7, zCom, -1, SQLITE_UTF8, sqlite3_free);
002464          }
002465  #else
002466          sqlite3VdbeMemSetNull(pMem+7);
002467  #endif
002468          sqlite3VdbeMemSetStr(pMem+5, zP4, -1, SQLITE_UTF8, sqlite3_free);
002469          assert( p->nResColumn==8 );
002470        }
002471        p->pResultRow = pMem;
002472        if( db->mallocFailed ){
002473          p->rc = SQLITE_NOMEM;
002474          rc = SQLITE_ERROR;
002475        }else{
002476          p->rc = SQLITE_OK;
002477          rc = SQLITE_ROW;
002478        }
002479      }
002480    }
002481    return rc;
002482  }
002483  #endif /* SQLITE_OMIT_EXPLAIN */
002484  
002485  #ifdef SQLITE_DEBUG
002486  /*
002487  ** Print the SQL that was used to generate a VDBE program.
002488  */
002489  void sqlite3VdbePrintSql(Vdbe *p){
002490    const char *z = 0;
002491    if( p->zSql ){
002492      z = p->zSql;
002493    }else if( p->nOp>=1 ){
002494      const VdbeOp *pOp = &p->aOp[0];
002495      if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
002496        z = pOp->p4.z;
002497        while( sqlite3Isspace(*z) ) z++;
002498      }
002499    }
002500    if( z ) printf("SQL: [%s]\n", z);
002501  }
002502  #endif
002503  
002504  #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
002505  /*
002506  ** Print an IOTRACE message showing SQL content.
002507  */
002508  void sqlite3VdbeIOTraceSql(Vdbe *p){
002509    int nOp = p->nOp;
002510    VdbeOp *pOp;
002511    if( sqlite3IoTrace==0 ) return;
002512    if( nOp<1 ) return;
002513    pOp = &p->aOp[0];
002514    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
002515      int i, j;
002516      char z[1000];
002517      sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
002518      for(i=0; sqlite3Isspace(z[i]); i++){}
002519      for(j=0; z[i]; i++){
002520        if( sqlite3Isspace(z[i]) ){
002521          if( z[i-1]!=' ' ){
002522            z[j++] = ' ';
002523          }
002524        }else{
002525          z[j++] = z[i];
002526        }
002527      }
002528      z[j] = 0;
002529      sqlite3IoTrace("SQL %s\n", z);
002530    }
002531  }
002532  #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
002533  
002534  /* An instance of this object describes bulk memory available for use
002535  ** by subcomponents of a prepared statement.  Space is allocated out
002536  ** of a ReusableSpace object by the allocSpace() routine below.
002537  */
002538  struct ReusableSpace {
002539    u8 *pSpace;            /* Available memory */
002540    sqlite3_int64 nFree;   /* Bytes of available memory */
002541    sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */
002542  };
002543  
002544  /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
002545  ** from the ReusableSpace object.  Return a pointer to the allocated
002546  ** memory on success.  If insufficient memory is available in the
002547  ** ReusableSpace object, increase the ReusableSpace.nNeeded
002548  ** value by the amount needed and return NULL.
002549  **
002550  ** If pBuf is not initially NULL, that means that the memory has already
002551  ** been allocated by a prior call to this routine, so just return a copy
002552  ** of pBuf and leave ReusableSpace unchanged.
002553  **
002554  ** This allocator is employed to repurpose unused slots at the end of the
002555  ** opcode array of prepared state for other memory needs of the prepared
002556  ** statement.
002557  */
002558  static void *allocSpace(
002559    struct ReusableSpace *p,  /* Bulk memory available for allocation */
002560    void *pBuf,               /* Pointer to a prior allocation */
002561    sqlite3_int64 nByte       /* Bytes of memory needed. */
002562  ){
002563    assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
002564    if( pBuf==0 ){
002565      nByte = ROUND8P(nByte);
002566      if( nByte <= p->nFree ){
002567        p->nFree -= nByte;
002568        pBuf = &p->pSpace[p->nFree];
002569      }else{
002570        p->nNeeded += nByte;
002571      }
002572    }
002573    assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
002574    return pBuf;
002575  }
002576  
002577  /*
002578  ** Rewind the VDBE back to the beginning in preparation for
002579  ** running it.
002580  */
002581  void sqlite3VdbeRewind(Vdbe *p){
002582  #if defined(SQLITE_DEBUG)
002583    int i;
002584  #endif
002585    assert( p!=0 );
002586    assert( p->eVdbeState==VDBE_INIT_STATE
002587         || p->eVdbeState==VDBE_READY_STATE
002588         || p->eVdbeState==VDBE_HALT_STATE );
002589  
002590    /* There should be at least one opcode.
002591    */
002592    assert( p->nOp>0 );
002593  
002594    p->eVdbeState = VDBE_READY_STATE;
002595  
002596  #ifdef SQLITE_DEBUG
002597    for(i=0; i<p->nMem; i++){
002598      assert( p->aMem[i].db==p->db );
002599    }
002600  #endif
002601    p->pc = -1;
002602    p->rc = SQLITE_OK;
002603    p->errorAction = OE_Abort;
002604    p->nChange = 0;
002605    p->cacheCtr = 1;
002606    p->minWriteFileFormat = 255;
002607    p->iStatement = 0;
002608    p->nFkConstraint = 0;
002609  #ifdef VDBE_PROFILE
002610    for(i=0; i<p->nOp; i++){
002611      p->aOp[i].nExec = 0;
002612      p->aOp[i].nCycle = 0;
002613    }
002614  #endif
002615  }
002616  
002617  /*
002618  ** Prepare a virtual machine for execution for the first time after
002619  ** creating the virtual machine.  This involves things such
002620  ** as allocating registers and initializing the program counter.
002621  ** After the VDBE has be prepped, it can be executed by one or more
002622  ** calls to sqlite3VdbeExec(). 
002623  **
002624  ** This function may be called exactly once on each virtual machine.
002625  ** After this routine is called the VM has been "packaged" and is ready
002626  ** to run.  After this routine is called, further calls to
002627  ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
002628  ** the Vdbe from the Parse object that helped generate it so that the
002629  ** the Vdbe becomes an independent entity and the Parse object can be
002630  ** destroyed.
002631  **
002632  ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
002633  ** to its initial state after it has been run.
002634  */
002635  void sqlite3VdbeMakeReady(
002636    Vdbe *p,                       /* The VDBE */
002637    Parse *pParse                  /* Parsing context */
002638  ){
002639    sqlite3 *db;                   /* The database connection */
002640    int nVar;                      /* Number of parameters */
002641    int nMem;                      /* Number of VM memory registers */
002642    int nCursor;                   /* Number of cursors required */
002643    int nArg;                      /* Number of arguments in subprograms */
002644    int n;                         /* Loop counter */
002645    struct ReusableSpace x;        /* Reusable bulk memory */
002646  
002647    assert( p!=0 );
002648    assert( p->nOp>0 );
002649    assert( pParse!=0 );
002650    assert( p->eVdbeState==VDBE_INIT_STATE );
002651    assert( pParse==p->pParse );
002652    p->pVList = pParse->pVList;
002653    pParse->pVList =  0;
002654    db = p->db;
002655    assert( db->mallocFailed==0 );
002656    nVar = pParse->nVar;
002657    nMem = pParse->nMem;
002658    nCursor = pParse->nTab;
002659    nArg = pParse->nMaxArg;
002660   
002661    /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
002662    ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
002663    ** space at the end of aMem[] for cursors 1 and greater.
002664    ** See also: allocateCursor().
002665    */
002666    nMem += nCursor;
002667    if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
002668  
002669    /* Figure out how much reusable memory is available at the end of the
002670    ** opcode array.  This extra memory will be reallocated for other elements
002671    ** of the prepared statement.
002672    */
002673    n = ROUND8P(sizeof(Op)*p->nOp);             /* Bytes of opcode memory used */
002674    x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
002675    assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
002676    x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */
002677    assert( x.nFree>=0 );
002678    assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
002679  
002680    resolveP2Values(p, &nArg);
002681    p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
002682    if( pParse->explain ){
002683      if( nMem<10 ) nMem = 10;
002684      p->explain = pParse->explain;
002685      p->nResColumn = 12 - 4*p->explain;
002686    }
002687    p->expired = 0;
002688  
002689    /* Memory for registers, parameters, cursor, etc, is allocated in one or two
002690    ** passes.  On the first pass, we try to reuse unused memory at the
002691    ** end of the opcode array.  If we are unable to satisfy all memory
002692    ** requirements by reusing the opcode array tail, then the second
002693    ** pass will fill in the remainder using a fresh memory allocation. 
002694    **
002695    ** This two-pass approach that reuses as much memory as possible from
002696    ** the leftover memory at the end of the opcode array.  This can significantly
002697    ** reduce the amount of memory held by a prepared statement.
002698    */
002699    x.nNeeded = 0;
002700    p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
002701    p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
002702    p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
002703    p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
002704    if( x.nNeeded ){
002705      x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
002706      x.nFree = x.nNeeded;
002707      if( !db->mallocFailed ){
002708        p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
002709        p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
002710        p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
002711        p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
002712      }
002713    }
002714  
002715    if( db->mallocFailed ){
002716      p->nVar = 0;
002717      p->nCursor = 0;
002718      p->nMem = 0;
002719    }else{
002720      p->nCursor = nCursor;
002721      p->nVar = (ynVar)nVar;
002722      initMemArray(p->aVar, nVar, db, MEM_Null);
002723      p->nMem = nMem;
002724      initMemArray(p->aMem, nMem, db, MEM_Undefined);
002725      memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
002726    }
002727    sqlite3VdbeRewind(p);
002728  }
002729  
002730  /*
002731  ** Close a VDBE cursor and release all the resources that cursor
002732  ** happens to hold.
002733  */
002734  void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
002735    if( pCx ) sqlite3VdbeFreeCursorNN(p,pCx);
002736  }
002737  static SQLITE_NOINLINE void freeCursorWithCache(Vdbe *p, VdbeCursor *pCx){
002738    VdbeTxtBlbCache *pCache = pCx->pCache;
002739    assert( pCx->colCache );
002740    pCx->colCache = 0;
002741    pCx->pCache = 0;
002742    if( pCache->pCValue ){
002743      sqlite3RCStrUnref(pCache->pCValue);
002744      pCache->pCValue = 0;
002745    }
002746    sqlite3DbFree(p->db, pCache);
002747    sqlite3VdbeFreeCursorNN(p, pCx);
002748  }
002749  void sqlite3VdbeFreeCursorNN(Vdbe *p, VdbeCursor *pCx){
002750    if( pCx->colCache ){
002751      freeCursorWithCache(p, pCx);
002752      return;
002753    }
002754    switch( pCx->eCurType ){
002755      case CURTYPE_SORTER: {
002756        sqlite3VdbeSorterClose(p->db, pCx);
002757        break;
002758      }
002759      case CURTYPE_BTREE: {
002760        assert( pCx->uc.pCursor!=0 );
002761        sqlite3BtreeCloseCursor(pCx->uc.pCursor);
002762        break;
002763      }
002764  #ifndef SQLITE_OMIT_VIRTUALTABLE
002765      case CURTYPE_VTAB: {
002766        sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
002767        const sqlite3_module *pModule = pVCur->pVtab->pModule;
002768        assert( pVCur->pVtab->nRef>0 );
002769        pVCur->pVtab->nRef--;
002770        pModule->xClose(pVCur);
002771        break;
002772      }
002773  #endif
002774    }
002775  }
002776  
002777  /*
002778  ** Close all cursors in the current frame.
002779  */
002780  static void closeCursorsInFrame(Vdbe *p){
002781    int i;
002782    for(i=0; i<p->nCursor; i++){
002783      VdbeCursor *pC = p->apCsr[i];
002784      if( pC ){
002785        sqlite3VdbeFreeCursorNN(p, pC);
002786        p->apCsr[i] = 0;
002787      }
002788    }
002789  }
002790  
002791  /*
002792  ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
002793  ** is used, for example, when a trigger sub-program is halted to restore
002794  ** control to the main program.
002795  */
002796  int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
002797    Vdbe *v = pFrame->v;
002798    closeCursorsInFrame(v);
002799    v->aOp = pFrame->aOp;
002800    v->nOp = pFrame->nOp;
002801    v->aMem = pFrame->aMem;
002802    v->nMem = pFrame->nMem;
002803    v->apCsr = pFrame->apCsr;
002804    v->nCursor = pFrame->nCursor;
002805    v->db->lastRowid = pFrame->lastRowid;
002806    v->nChange = pFrame->nChange;
002807    v->db->nChange = pFrame->nDbChange;
002808    sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
002809    v->pAuxData = pFrame->pAuxData;
002810    pFrame->pAuxData = 0;
002811    return pFrame->pc;
002812  }
002813  
002814  /*
002815  ** Close all cursors.
002816  **
002817  ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
002818  ** cell array. This is necessary as the memory cell array may contain
002819  ** pointers to VdbeFrame objects, which may in turn contain pointers to
002820  ** open cursors.
002821  */
002822  static void closeAllCursors(Vdbe *p){
002823    if( p->pFrame ){
002824      VdbeFrame *pFrame;
002825      for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
002826      sqlite3VdbeFrameRestore(pFrame);
002827      p->pFrame = 0;
002828      p->nFrame = 0;
002829    }
002830    assert( p->nFrame==0 );
002831    closeCursorsInFrame(p);
002832    releaseMemArray(p->aMem, p->nMem);
002833    while( p->pDelFrame ){
002834      VdbeFrame *pDel = p->pDelFrame;
002835      p->pDelFrame = pDel->pParent;
002836      sqlite3VdbeFrameDelete(pDel);
002837    }
002838  
002839    /* Delete any auxdata allocations made by the VM */
002840    if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
002841    assert( p->pAuxData==0 );
002842  }
002843  
002844  /*
002845  ** Set the number of result columns that will be returned by this SQL
002846  ** statement. This is now set at compile time, rather than during
002847  ** execution of the vdbe program so that sqlite3_column_count() can
002848  ** be called on an SQL statement before sqlite3_step().
002849  */
002850  void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
002851    int n;
002852    sqlite3 *db = p->db;
002853  
002854    if( p->nResAlloc ){
002855      releaseMemArray(p->aColName, p->nResAlloc*COLNAME_N);
002856      sqlite3DbFree(db, p->aColName);
002857    }
002858    n = nResColumn*COLNAME_N;
002859    p->nResColumn = p->nResAlloc = (u16)nResColumn;
002860    p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
002861    if( p->aColName==0 ) return;
002862    initMemArray(p->aColName, n, db, MEM_Null);
002863  }
002864  
002865  /*
002866  ** Set the name of the idx'th column to be returned by the SQL statement.
002867  ** zName must be a pointer to a nul terminated string.
002868  **
002869  ** This call must be made after a call to sqlite3VdbeSetNumCols().
002870  **
002871  ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
002872  ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
002873  ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
002874  */
002875  int sqlite3VdbeSetColName(
002876    Vdbe *p,                         /* Vdbe being configured */
002877    int idx,                         /* Index of column zName applies to */
002878    int var,                         /* One of the COLNAME_* constants */
002879    const char *zName,               /* Pointer to buffer containing name */
002880    void (*xDel)(void*)              /* Memory management strategy for zName */
002881  ){
002882    int rc;
002883    Mem *pColName;
002884    assert( idx<p->nResAlloc );
002885    assert( var<COLNAME_N );
002886    if( p->db->mallocFailed ){
002887      assert( !zName || xDel!=SQLITE_DYNAMIC );
002888      return SQLITE_NOMEM_BKPT;
002889    }
002890    assert( p->aColName!=0 );
002891    pColName = &(p->aColName[idx+var*p->nResAlloc]);
002892    rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
002893    assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
002894    return rc;
002895  }
002896  
002897  /*
002898  ** A read or write transaction may or may not be active on database handle
002899  ** db. If a transaction is active, commit it. If there is a
002900  ** write-transaction spanning more than one database file, this routine
002901  ** takes care of the super-journal trickery.
002902  */
002903  static int vdbeCommit(sqlite3 *db, Vdbe *p){
002904    int i;
002905    int nTrans = 0;  /* Number of databases with an active write-transaction
002906                     ** that are candidates for a two-phase commit using a
002907                     ** super-journal */
002908    int rc = SQLITE_OK;
002909    int needXcommit = 0;
002910  
002911  #ifdef SQLITE_OMIT_VIRTUALTABLE
002912    /* With this option, sqlite3VtabSync() is defined to be simply
002913    ** SQLITE_OK so p is not used.
002914    */
002915    UNUSED_PARAMETER(p);
002916  #endif
002917  
002918    /* Before doing anything else, call the xSync() callback for any
002919    ** virtual module tables written in this transaction. This has to
002920    ** be done before determining whether a super-journal file is
002921    ** required, as an xSync() callback may add an attached database
002922    ** to the transaction.
002923    */
002924    rc = sqlite3VtabSync(db, p);
002925  
002926    /* This loop determines (a) if the commit hook should be invoked and
002927    ** (b) how many database files have open write transactions, not
002928    ** including the temp database. (b) is important because if more than
002929    ** one database file has an open write transaction, a super-journal
002930    ** file is required for an atomic commit.
002931    */
002932    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
002933      Btree *pBt = db->aDb[i].pBt;
002934      if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
002935        /* Whether or not a database might need a super-journal depends upon
002936        ** its journal mode (among other things).  This matrix determines which
002937        ** journal modes use a super-journal and which do not */
002938        static const u8 aMJNeeded[] = {
002939          /* DELETE   */  1,
002940          /* PERSIST   */ 1,
002941          /* OFF       */ 0,
002942          /* TRUNCATE  */ 1,
002943          /* MEMORY    */ 0,
002944          /* WAL       */ 0
002945        };
002946        Pager *pPager;   /* Pager associated with pBt */
002947        needXcommit = 1;
002948        sqlite3BtreeEnter(pBt);
002949        pPager = sqlite3BtreePager(pBt);
002950        if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
002951         && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
002952         && sqlite3PagerIsMemdb(pPager)==0
002953        ){
002954          assert( i!=1 );
002955          nTrans++;
002956        }
002957        rc = sqlite3PagerExclusiveLock(pPager);
002958        sqlite3BtreeLeave(pBt);
002959      }
002960    }
002961    if( rc!=SQLITE_OK ){
002962      return rc;
002963    }
002964  
002965    /* If there are any write-transactions at all, invoke the commit hook */
002966    if( needXcommit && db->xCommitCallback ){
002967      rc = db->xCommitCallback(db->pCommitArg);
002968      if( rc ){
002969        return SQLITE_CONSTRAINT_COMMITHOOK;
002970      }
002971    }
002972  
002973    /* The simple case - no more than one database file (not counting the
002974    ** TEMP database) has a transaction active.   There is no need for the
002975    ** super-journal.
002976    **
002977    ** If the return value of sqlite3BtreeGetFilename() is a zero length
002978    ** string, it means the main database is :memory: or a temp file.  In
002979    ** that case we do not support atomic multi-file commits, so use the
002980    ** simple case then too.
002981    */
002982    if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
002983     || nTrans<=1
002984    ){
002985      for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
002986        Btree *pBt = db->aDb[i].pBt;
002987        if( pBt ){
002988          rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
002989        }
002990      }
002991  
002992      /* Do the commit only if all databases successfully complete phase 1.
002993      ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
002994      ** IO error while deleting or truncating a journal file. It is unlikely,
002995      ** but could happen. In this case abandon processing and return the error.
002996      */
002997      for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
002998        Btree *pBt = db->aDb[i].pBt;
002999        if( pBt ){
003000          rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
003001        }
003002      }
003003      if( rc==SQLITE_OK ){
003004        sqlite3VtabCommit(db);
003005      }
003006    }
003007  
003008    /* The complex case - There is a multi-file write-transaction active.
003009    ** This requires a super-journal file to ensure the transaction is
003010    ** committed atomically.
003011    */
003012  #ifndef SQLITE_OMIT_DISKIO
003013    else{
003014      sqlite3_vfs *pVfs = db->pVfs;
003015      char *zSuper = 0;   /* File-name for the super-journal */
003016      char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
003017      sqlite3_file *pSuperJrnl = 0;
003018      i64 offset = 0;
003019      int res;
003020      int retryCount = 0;
003021      int nMainFile;
003022  
003023      /* Select a super-journal file name */
003024      nMainFile = sqlite3Strlen30(zMainFile);
003025      zSuper = sqlite3MPrintf(db, "%.4c%s%.16c", 0,zMainFile,0);
003026      if( zSuper==0 ) return SQLITE_NOMEM_BKPT;
003027      zSuper += 4;
003028      do {
003029        u32 iRandom;
003030        if( retryCount ){
003031          if( retryCount>100 ){
003032            sqlite3_log(SQLITE_FULL, "MJ delete: %s", zSuper);
003033            sqlite3OsDelete(pVfs, zSuper, 0);
003034            break;
003035          }else if( retryCount==1 ){
003036            sqlite3_log(SQLITE_FULL, "MJ collide: %s", zSuper);
003037          }
003038        }
003039        retryCount++;
003040        sqlite3_randomness(sizeof(iRandom), &iRandom);
003041        sqlite3_snprintf(13, &zSuper[nMainFile], "-mj%06X9%02X",
003042                                 (iRandom>>8)&0xffffff, iRandom&0xff);
003043        /* The antipenultimate character of the super-journal name must
003044        ** be "9" to avoid name collisions when using 8+3 filenames. */
003045        assert( zSuper[sqlite3Strlen30(zSuper)-3]=='9' );
003046        sqlite3FileSuffix3(zMainFile, zSuper);
003047        rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
003048      }while( rc==SQLITE_OK && res );
003049      if( rc==SQLITE_OK ){
003050        /* Open the super-journal. */
003051        rc = sqlite3OsOpenMalloc(pVfs, zSuper, &pSuperJrnl,
003052            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
003053            SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_SUPER_JOURNAL, 0
003054        );
003055      }
003056      if( rc!=SQLITE_OK ){
003057        sqlite3DbFree(db, zSuper-4);
003058        return rc;
003059      }
003060  
003061      /* Write the name of each database file in the transaction into the new
003062      ** super-journal file. If an error occurs at this point close
003063      ** and delete the super-journal file. All the individual journal files
003064      ** still have 'null' as the super-journal pointer, so they will roll
003065      ** back independently if a failure occurs.
003066      */
003067      for(i=0; i<db->nDb; i++){
003068        Btree *pBt = db->aDb[i].pBt;
003069        if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
003070          char const *zFile = sqlite3BtreeGetJournalname(pBt);
003071          if( zFile==0 ){
003072            continue;  /* Ignore TEMP and :memory: databases */
003073          }
003074          assert( zFile[0]!=0 );
003075          rc = sqlite3OsWrite(pSuperJrnl, zFile, sqlite3Strlen30(zFile)+1,offset);
003076          offset += sqlite3Strlen30(zFile)+1;
003077          if( rc!=SQLITE_OK ){
003078            sqlite3OsCloseFree(pSuperJrnl);
003079            sqlite3OsDelete(pVfs, zSuper, 0);
003080            sqlite3DbFree(db, zSuper-4);
003081            return rc;
003082          }
003083        }
003084      }
003085  
003086      /* Sync the super-journal file. If the IOCAP_SEQUENTIAL device
003087      ** flag is set this is not required.
003088      */
003089      if( 0==(sqlite3OsDeviceCharacteristics(pSuperJrnl)&SQLITE_IOCAP_SEQUENTIAL)
003090       && SQLITE_OK!=(rc = sqlite3OsSync(pSuperJrnl, SQLITE_SYNC_NORMAL))
003091      ){
003092        sqlite3OsCloseFree(pSuperJrnl);
003093        sqlite3OsDelete(pVfs, zSuper, 0);
003094        sqlite3DbFree(db, zSuper-4);
003095        return rc;
003096      }
003097  
003098      /* Sync all the db files involved in the transaction. The same call
003099      ** sets the super-journal pointer in each individual journal. If
003100      ** an error occurs here, do not delete the super-journal file.
003101      **
003102      ** If the error occurs during the first call to
003103      ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
003104      ** super-journal file will be orphaned. But we cannot delete it,
003105      ** in case the super-journal file name was written into the journal
003106      ** file before the failure occurred.
003107      */
003108      for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
003109        Btree *pBt = db->aDb[i].pBt;
003110        if( pBt ){
003111          rc = sqlite3BtreeCommitPhaseOne(pBt, zSuper);
003112        }
003113      }
003114      sqlite3OsCloseFree(pSuperJrnl);
003115      assert( rc!=SQLITE_BUSY );
003116      if( rc!=SQLITE_OK ){
003117        sqlite3DbFree(db, zSuper-4);
003118        return rc;
003119      }
003120  
003121      /* Delete the super-journal file. This commits the transaction. After
003122      ** doing this the directory is synced again before any individual
003123      ** transaction files are deleted.
003124      */
003125      rc = sqlite3OsDelete(pVfs, zSuper, 1);
003126      sqlite3DbFree(db, zSuper-4);
003127      zSuper = 0;
003128      if( rc ){
003129        return rc;
003130      }
003131  
003132      /* All files and directories have already been synced, so the following
003133      ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
003134      ** deleting or truncating journals. If something goes wrong while
003135      ** this is happening we don't really care. The integrity of the
003136      ** transaction is already guaranteed, but some stray 'cold' journals
003137      ** may be lying around. Returning an error code won't help matters.
003138      */
003139      disable_simulated_io_errors();
003140      sqlite3BeginBenignMalloc();
003141      for(i=0; i<db->nDb; i++){
003142        Btree *pBt = db->aDb[i].pBt;
003143        if( pBt ){
003144          sqlite3BtreeCommitPhaseTwo(pBt, 1);
003145        }
003146      }
003147      sqlite3EndBenignMalloc();
003148      enable_simulated_io_errors();
003149  
003150      sqlite3VtabCommit(db);
003151    }
003152  #endif
003153  
003154    return rc;
003155  }
003156  
003157  /*
003158  ** This routine checks that the sqlite3.nVdbeActive count variable
003159  ** matches the number of vdbe's in the list sqlite3.pVdbe that are
003160  ** currently active. An assertion fails if the two counts do not match.
003161  ** This is an internal self-check only - it is not an essential processing
003162  ** step.
003163  **
003164  ** This is a no-op if NDEBUG is defined.
003165  */
003166  #ifndef NDEBUG
003167  static void checkActiveVdbeCnt(sqlite3 *db){
003168    Vdbe *p;
003169    int cnt = 0;
003170    int nWrite = 0;
003171    int nRead = 0;
003172    p = db->pVdbe;
003173    while( p ){
003174      if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
003175        cnt++;
003176        if( p->readOnly==0 ) nWrite++;
003177        if( p->bIsReader ) nRead++;
003178      }
003179      p = p->pVNext;
003180    }
003181    assert( cnt==db->nVdbeActive );
003182    assert( nWrite==db->nVdbeWrite );
003183    assert( nRead==db->nVdbeRead );
003184  }
003185  #else
003186  #define checkActiveVdbeCnt(x)
003187  #endif
003188  
003189  /*
003190  ** If the Vdbe passed as the first argument opened a statement-transaction,
003191  ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
003192  ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
003193  ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
003194  ** statement transaction is committed.
003195  **
003196  ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
003197  ** Otherwise SQLITE_OK.
003198  */
003199  static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
003200    sqlite3 *const db = p->db;
003201    int rc = SQLITE_OK;
003202    int i;
003203    const int iSavepoint = p->iStatement-1;
003204  
003205    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
003206    assert( db->nStatement>0 );
003207    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
003208  
003209    for(i=0; i<db->nDb; i++){
003210      int rc2 = SQLITE_OK;
003211      Btree *pBt = db->aDb[i].pBt;
003212      if( pBt ){
003213        if( eOp==SAVEPOINT_ROLLBACK ){
003214          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
003215        }
003216        if( rc2==SQLITE_OK ){
003217          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
003218        }
003219        if( rc==SQLITE_OK ){
003220          rc = rc2;
003221        }
003222      }
003223    }
003224    db->nStatement--;
003225    p->iStatement = 0;
003226  
003227    if( rc==SQLITE_OK ){
003228      if( eOp==SAVEPOINT_ROLLBACK ){
003229        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
003230      }
003231      if( rc==SQLITE_OK ){
003232        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
003233      }
003234    }
003235  
003236    /* If the statement transaction is being rolled back, also restore the
003237    ** database handles deferred constraint counter to the value it had when
003238    ** the statement transaction was opened.  */
003239    if( eOp==SAVEPOINT_ROLLBACK ){
003240      db->nDeferredCons = p->nStmtDefCons;
003241      db->nDeferredImmCons = p->nStmtDefImmCons;
003242    }
003243    return rc;
003244  }
003245  int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
003246    if( p->db->nStatement && p->iStatement ){
003247      return vdbeCloseStatement(p, eOp);
003248    }
003249    return SQLITE_OK;
003250  }
003251  
003252  
003253  /*
003254  ** This function is called when a transaction opened by the database
003255  ** handle associated with the VM passed as an argument is about to be
003256  ** committed. If there are outstanding deferred foreign key constraint
003257  ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
003258  **
003259  ** If there are outstanding FK violations and this function returns
003260  ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
003261  ** and write an error message to it. Then return SQLITE_ERROR.
003262  */
003263  #ifndef SQLITE_OMIT_FOREIGN_KEY
003264  int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
003265    sqlite3 *db = p->db;
003266    if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
003267     || (!deferred && p->nFkConstraint>0)
003268    ){
003269      p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
003270      p->errorAction = OE_Abort;
003271      sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
003272      if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ) return SQLITE_ERROR;
003273      return SQLITE_CONSTRAINT_FOREIGNKEY;
003274    }
003275    return SQLITE_OK;
003276  }
003277  #endif
003278  
003279  /*
003280  ** This routine is called the when a VDBE tries to halt.  If the VDBE
003281  ** has made changes and is in autocommit mode, then commit those
003282  ** changes.  If a rollback is needed, then do the rollback.
003283  **
003284  ** This routine is the only way to move the sqlite3eOpenState of a VM from
003285  ** SQLITE_STATE_RUN to SQLITE_STATE_HALT.  It is harmless to
003286  ** call this on a VM that is in the SQLITE_STATE_HALT state.
003287  **
003288  ** Return an error code.  If the commit could not complete because of
003289  ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
003290  ** means the close did not happen and needs to be repeated.
003291  */
003292  int sqlite3VdbeHalt(Vdbe *p){
003293    int rc;                         /* Used to store transient return codes */
003294    sqlite3 *db = p->db;
003295  
003296    /* This function contains the logic that determines if a statement or
003297    ** transaction will be committed or rolled back as a result of the
003298    ** execution of this virtual machine.
003299    **
003300    ** If any of the following errors occur:
003301    **
003302    **     SQLITE_NOMEM
003303    **     SQLITE_IOERR
003304    **     SQLITE_FULL
003305    **     SQLITE_INTERRUPT
003306    **
003307    ** Then the internal cache might have been left in an inconsistent
003308    ** state.  We need to rollback the statement transaction, if there is
003309    ** one, or the complete transaction if there is no statement transaction.
003310    */
003311  
003312    assert( p->eVdbeState==VDBE_RUN_STATE );
003313    if( db->mallocFailed ){
003314      p->rc = SQLITE_NOMEM_BKPT;
003315    }
003316    closeAllCursors(p);
003317    checkActiveVdbeCnt(db);
003318  
003319    /* No commit or rollback needed if the program never started or if the
003320    ** SQL statement does not read or write a database file.  */
003321    if( p->bIsReader ){
003322      int mrc;   /* Primary error code from p->rc */
003323      int eStatementOp = 0;
003324      int isSpecialError;            /* Set to true if a 'special' error */
003325  
003326      /* Lock all btrees used by the statement */
003327      sqlite3VdbeEnter(p);
003328  
003329      /* Check for one of the special errors */
003330      if( p->rc ){
003331        mrc = p->rc & 0xff;
003332        isSpecialError = mrc==SQLITE_NOMEM
003333                      || mrc==SQLITE_IOERR
003334                      || mrc==SQLITE_INTERRUPT
003335                      || mrc==SQLITE_FULL;
003336      }else{
003337        mrc = isSpecialError = 0;
003338      }
003339      if( isSpecialError ){
003340        /* If the query was read-only and the error code is SQLITE_INTERRUPT,
003341        ** no rollback is necessary. Otherwise, at least a savepoint
003342        ** transaction must be rolled back to restore the database to a
003343        ** consistent state.
003344        **
003345        ** Even if the statement is read-only, it is important to perform
003346        ** a statement or transaction rollback operation. If the error
003347        ** occurred while writing to the journal, sub-journal or database
003348        ** file as part of an effort to free up cache space (see function
003349        ** pagerStress() in pager.c), the rollback is required to restore
003350        ** the pager to a consistent state.
003351        */
003352        if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
003353          if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
003354            eStatementOp = SAVEPOINT_ROLLBACK;
003355          }else{
003356            /* We are forced to roll back the active transaction. Before doing
003357            ** so, abort any other statements this handle currently has active.
003358            */
003359            sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
003360            sqlite3CloseSavepoints(db);
003361            db->autoCommit = 1;
003362            p->nChange = 0;
003363          }
003364        }
003365      }
003366  
003367      /* Check for immediate foreign key violations. */
003368      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
003369        (void)sqlite3VdbeCheckFk(p, 0);
003370      }
003371  
003372      /* If the auto-commit flag is set and this is the only active writer
003373      ** VM, then we do either a commit or rollback of the current transaction.
003374      **
003375      ** Note: This block also runs if one of the special errors handled
003376      ** above has occurred.
003377      */
003378      if( !sqlite3VtabInSync(db)
003379       && db->autoCommit
003380       && db->nVdbeWrite==(p->readOnly==0)
003381      ){
003382        if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
003383          rc = sqlite3VdbeCheckFk(p, 1);
003384          if( rc!=SQLITE_OK ){
003385            if( NEVER(p->readOnly) ){
003386              sqlite3VdbeLeave(p);
003387              return SQLITE_ERROR;
003388            }
003389            rc = SQLITE_CONSTRAINT_FOREIGNKEY;
003390          }else if( db->flags & SQLITE_CorruptRdOnly ){
003391            rc = SQLITE_CORRUPT;
003392            db->flags &= ~SQLITE_CorruptRdOnly;
003393          }else{
003394            /* The auto-commit flag is true, the vdbe program was successful
003395            ** or hit an 'OR FAIL' constraint and there are no deferred foreign
003396            ** key constraints to hold up the transaction. This means a commit
003397            ** is required. */
003398            rc = vdbeCommit(db, p);
003399          }
003400          if( rc==SQLITE_BUSY && p->readOnly ){
003401            sqlite3VdbeLeave(p);
003402            return SQLITE_BUSY;
003403          }else if( rc!=SQLITE_OK ){
003404            sqlite3SystemError(db, rc);
003405            p->rc = rc;
003406            sqlite3RollbackAll(db, SQLITE_OK);
003407            p->nChange = 0;
003408          }else{
003409            db->nDeferredCons = 0;
003410            db->nDeferredImmCons = 0;
003411            db->flags &= ~(u64)SQLITE_DeferFKs;
003412            sqlite3CommitInternalChanges(db);
003413          }
003414        }else if( p->rc==SQLITE_SCHEMA && db->nVdbeActive>1 ){
003415          p->nChange = 0;
003416        }else{
003417          sqlite3RollbackAll(db, SQLITE_OK);
003418          p->nChange = 0;
003419        }
003420        db->nStatement = 0;
003421      }else if( eStatementOp==0 ){
003422        if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
003423          eStatementOp = SAVEPOINT_RELEASE;
003424        }else if( p->errorAction==OE_Abort ){
003425          eStatementOp = SAVEPOINT_ROLLBACK;
003426        }else{
003427          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
003428          sqlite3CloseSavepoints(db);
003429          db->autoCommit = 1;
003430          p->nChange = 0;
003431        }
003432      }
003433   
003434      /* If eStatementOp is non-zero, then a statement transaction needs to
003435      ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
003436      ** do so. If this operation returns an error, and the current statement
003437      ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
003438      ** current statement error code.
003439      */
003440      if( eStatementOp ){
003441        rc = sqlite3VdbeCloseStatement(p, eStatementOp);
003442        if( rc ){
003443          if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
003444            p->rc = rc;
003445            sqlite3DbFree(db, p->zErrMsg);
003446            p->zErrMsg = 0;
003447          }
003448          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
003449          sqlite3CloseSavepoints(db);
003450          db->autoCommit = 1;
003451          p->nChange = 0;
003452        }
003453      }
003454   
003455      /* If this was an INSERT, UPDATE or DELETE and no statement transaction
003456      ** has been rolled back, update the database connection change-counter.
003457      */
003458      if( p->changeCntOn ){
003459        if( eStatementOp!=SAVEPOINT_ROLLBACK ){
003460          sqlite3VdbeSetChanges(db, p->nChange);
003461        }else{
003462          sqlite3VdbeSetChanges(db, 0);
003463        }
003464        p->nChange = 0;
003465      }
003466  
003467      /* Release the locks */
003468      sqlite3VdbeLeave(p);
003469    }
003470  
003471    /* We have successfully halted and closed the VM.  Record this fact. */
003472    db->nVdbeActive--;
003473    if( !p->readOnly ) db->nVdbeWrite--;
003474    if( p->bIsReader ) db->nVdbeRead--;
003475    assert( db->nVdbeActive>=db->nVdbeRead );
003476    assert( db->nVdbeRead>=db->nVdbeWrite );
003477    assert( db->nVdbeWrite>=0 );
003478    p->eVdbeState = VDBE_HALT_STATE;
003479    checkActiveVdbeCnt(db);
003480    if( db->mallocFailed ){
003481      p->rc = SQLITE_NOMEM_BKPT;
003482    }
003483  
003484    /* If the auto-commit flag is set to true, then any locks that were held
003485    ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
003486    ** to invoke any required unlock-notify callbacks.
003487    */
003488    if( db->autoCommit ){
003489      sqlite3ConnectionUnlocked(db);
003490    }
003491  
003492    assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
003493    return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
003494  }
003495  
003496  
003497  /*
003498  ** Each VDBE holds the result of the most recent sqlite3_step() call
003499  ** in p->rc.  This routine sets that result back to SQLITE_OK.
003500  */
003501  void sqlite3VdbeResetStepResult(Vdbe *p){
003502    p->rc = SQLITE_OK;
003503  }
003504  
003505  /*
003506  ** Copy the error code and error message belonging to the VDBE passed
003507  ** as the first argument to its database handle (so that they will be
003508  ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
003509  **
003510  ** This function does not clear the VDBE error code or message, just
003511  ** copies them to the database handle.
003512  */
003513  int sqlite3VdbeTransferError(Vdbe *p){
003514    sqlite3 *db = p->db;
003515    int rc = p->rc;
003516    if( p->zErrMsg ){
003517      db->bBenignMalloc++;
003518      sqlite3BeginBenignMalloc();
003519      if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
003520      sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
003521      sqlite3EndBenignMalloc();
003522      db->bBenignMalloc--;
003523    }else if( db->pErr ){
003524      sqlite3ValueSetNull(db->pErr);
003525    }
003526    db->errCode = rc;
003527    db->errByteOffset = -1;
003528    return rc;
003529  }
003530  
003531  #ifdef SQLITE_ENABLE_SQLLOG
003532  /*
003533  ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
003534  ** invoke it.
003535  */
003536  static void vdbeInvokeSqllog(Vdbe *v){
003537    if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
003538      char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
003539      assert( v->db->init.busy==0 );
003540      if( zExpanded ){
003541        sqlite3GlobalConfig.xSqllog(
003542            sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
003543        );
003544        sqlite3DbFree(v->db, zExpanded);
003545      }
003546    }
003547  }
003548  #else
003549  # define vdbeInvokeSqllog(x)
003550  #endif
003551  
003552  /*
003553  ** Clean up a VDBE after execution but do not delete the VDBE just yet.
003554  ** Write any error messages into *pzErrMsg.  Return the result code.
003555  **
003556  ** After this routine is run, the VDBE should be ready to be executed
003557  ** again.
003558  **
003559  ** To look at it another way, this routine resets the state of the
003560  ** virtual machine from VDBE_RUN_STATE or VDBE_HALT_STATE back to
003561  ** VDBE_READY_STATE.
003562  */
003563  int sqlite3VdbeReset(Vdbe *p){
003564  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
003565    int i;
003566  #endif
003567  
003568    sqlite3 *db;
003569    db = p->db;
003570  
003571    /* If the VM did not run to completion or if it encountered an
003572    ** error, then it might not have been halted properly.  So halt
003573    ** it now.
003574    */
003575    if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
003576  
003577    /* If the VDBE has been run even partially, then transfer the error code
003578    ** and error message from the VDBE into the main database structure.  But
003579    ** if the VDBE has just been set to run but has not actually executed any
003580    ** instructions yet, leave the main database error information unchanged.
003581    */
003582    if( p->pc>=0 ){
003583      vdbeInvokeSqllog(p);
003584      if( db->pErr || p->zErrMsg ){
003585        sqlite3VdbeTransferError(p);
003586      }else{
003587        db->errCode = p->rc;
003588      }
003589    }
003590  
003591    /* Reset register contents and reclaim error message memory.
003592    */
003593  #ifdef SQLITE_DEBUG
003594    /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
003595    ** Vdbe.aMem[] arrays have already been cleaned up.  */
003596    if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
003597    if( p->aMem ){
003598      for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
003599    }
003600  #endif
003601    if( p->zErrMsg ){
003602      sqlite3DbFree(db, p->zErrMsg);
003603      p->zErrMsg = 0;
003604    }
003605    p->pResultRow = 0;
003606  #ifdef SQLITE_DEBUG
003607    p->nWrite = 0;
003608  #endif
003609  
003610    /* Save profiling information from this VDBE run.
003611    */
003612  #ifdef VDBE_PROFILE
003613    {
003614      FILE *out = fopen("vdbe_profile.out", "a");
003615      if( out ){
003616        fprintf(out, "---- ");
003617        for(i=0; i<p->nOp; i++){
003618          fprintf(out, "%02x", p->aOp[i].opcode);
003619        }
003620        fprintf(out, "\n");
003621        if( p->zSql ){
003622          char c, pc = 0;
003623          fprintf(out, "-- ");
003624          for(i=0; (c = p->zSql[i])!=0; i++){
003625            if( pc=='\n' ) fprintf(out, "-- ");
003626            putc(c, out);
003627            pc = c;
003628          }
003629          if( pc!='\n' ) fprintf(out, "\n");
003630        }
003631        for(i=0; i<p->nOp; i++){
003632          char zHdr[100];
003633          i64 cnt = p->aOp[i].nExec;
003634          i64 cycles = p->aOp[i].nCycle;
003635          sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
003636             cnt,
003637             cycles,
003638             cnt>0 ? cycles/cnt : 0
003639          );
003640          fprintf(out, "%s", zHdr);
003641          sqlite3VdbePrintOp(out, i, &p->aOp[i]);
003642        }
003643        fclose(out);
003644      }
003645    }
003646  #endif
003647    return p->rc & db->errMask;
003648  }
003649  
003650  /*
003651  ** Clean up and delete a VDBE after execution.  Return an integer which is
003652  ** the result code.  Write any error message text into *pzErrMsg.
003653  */
003654  int sqlite3VdbeFinalize(Vdbe *p){
003655    int rc = SQLITE_OK;
003656    assert( VDBE_RUN_STATE>VDBE_READY_STATE );
003657    assert( VDBE_HALT_STATE>VDBE_READY_STATE );
003658    assert( VDBE_INIT_STATE<VDBE_READY_STATE );
003659    if( p->eVdbeState>=VDBE_READY_STATE ){
003660      rc = sqlite3VdbeReset(p);
003661      assert( (rc & p->db->errMask)==rc );
003662    }
003663    sqlite3VdbeDelete(p);
003664    return rc;
003665  }
003666  
003667  /*
003668  ** If parameter iOp is less than zero, then invoke the destructor for
003669  ** all auxiliary data pointers currently cached by the VM passed as
003670  ** the first argument.
003671  **
003672  ** Or, if iOp is greater than or equal to zero, then the destructor is
003673  ** only invoked for those auxiliary data pointers created by the user
003674  ** function invoked by the OP_Function opcode at instruction iOp of
003675  ** VM pVdbe, and only then if:
003676  **
003677  **    * the associated function parameter is the 32nd or later (counting
003678  **      from left to right), or
003679  **
003680  **    * the corresponding bit in argument mask is clear (where the first
003681  **      function parameter corresponds to bit 0 etc.).
003682  */
003683  void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
003684    while( *pp ){
003685      AuxData *pAux = *pp;
003686      if( (iOp<0)
003687       || (pAux->iAuxOp==iOp
003688            && pAux->iAuxArg>=0
003689            && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
003690      ){
003691        testcase( pAux->iAuxArg==31 );
003692        if( pAux->xDeleteAux ){
003693          pAux->xDeleteAux(pAux->pAux);
003694        }
003695        *pp = pAux->pNextAux;
003696        sqlite3DbFree(db, pAux);
003697      }else{
003698        pp= &pAux->pNextAux;
003699      }
003700    }
003701  }
003702  
003703  /*
003704  ** Free all memory associated with the Vdbe passed as the second argument,
003705  ** except for object itself, which is preserved.
003706  **
003707  ** The difference between this function and sqlite3VdbeDelete() is that
003708  ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
003709  ** the database connection and frees the object itself.
003710  */
003711  static void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
003712    SubProgram *pSub, *pNext;
003713    assert( db!=0 );
003714    assert( p->db==0 || p->db==db );
003715    if( p->aColName ){
003716      releaseMemArray(p->aColName, p->nResAlloc*COLNAME_N);
003717      sqlite3DbNNFreeNN(db, p->aColName);
003718    }
003719    for(pSub=p->pProgram; pSub; pSub=pNext){
003720      pNext = pSub->pNext;
003721      vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
003722      sqlite3DbFree(db, pSub);
003723    }
003724    if( p->eVdbeState!=VDBE_INIT_STATE ){
003725      releaseMemArray(p->aVar, p->nVar);
003726      if( p->pVList ) sqlite3DbNNFreeNN(db, p->pVList);
003727      if( p->pFree ) sqlite3DbNNFreeNN(db, p->pFree);
003728    }
003729    vdbeFreeOpArray(db, p->aOp, p->nOp);
003730    if( p->zSql ) sqlite3DbNNFreeNN(db, p->zSql);
003731  #ifdef SQLITE_ENABLE_NORMALIZE
003732    sqlite3DbFree(db, p->zNormSql);
003733    {
003734      DblquoteStr *pThis, *pNxt;
003735      for(pThis=p->pDblStr; pThis; pThis=pNxt){
003736        pNxt = pThis->pNextStr;
003737        sqlite3DbFree(db, pThis);
003738      }
003739    }
003740  #endif
003741  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
003742    {
003743      int i;
003744      for(i=0; i<p->nScan; i++){
003745        sqlite3DbFree(db, p->aScan[i].zName);
003746      }
003747      sqlite3DbFree(db, p->aScan);
003748    }
003749  #endif
003750  }
003751  
003752  /*
003753  ** Delete an entire VDBE.
003754  */
003755  void sqlite3VdbeDelete(Vdbe *p){
003756    sqlite3 *db;
003757  
003758    assert( p!=0 );
003759    db = p->db;
003760    assert( db!=0 );
003761    assert( sqlite3_mutex_held(db->mutex) );
003762    sqlite3VdbeClearObject(db, p);
003763    if( db->pnBytesFreed==0 ){
003764      assert( p->ppVPrev!=0 );
003765      *p->ppVPrev = p->pVNext;
003766      if( p->pVNext ){
003767        p->pVNext->ppVPrev = p->ppVPrev;
003768      }
003769    }
003770    sqlite3DbNNFreeNN(db, p);
003771  }
003772  
003773  /*
003774  ** The cursor "p" has a pending seek operation that has not yet been
003775  ** carried out.  Seek the cursor now.  If an error occurs, return
003776  ** the appropriate error code.
003777  */
003778  int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor *p){
003779    int res, rc;
003780  #ifdef SQLITE_TEST
003781    extern int sqlite3_search_count;
003782  #endif
003783    assert( p->deferredMoveto );
003784    assert( p->isTable );
003785    assert( p->eCurType==CURTYPE_BTREE );
003786    rc = sqlite3BtreeTableMoveto(p->uc.pCursor, p->movetoTarget, 0, &res);
003787    if( rc ) return rc;
003788    if( res!=0 ) return SQLITE_CORRUPT_BKPT;
003789  #ifdef SQLITE_TEST
003790    sqlite3_search_count++;
003791  #endif
003792    p->deferredMoveto = 0;
003793    p->cacheStatus = CACHE_STALE;
003794    return SQLITE_OK;
003795  }
003796  
003797  /*
003798  ** Something has moved cursor "p" out of place.  Maybe the row it was
003799  ** pointed to was deleted out from under it.  Or maybe the btree was
003800  ** rebalanced.  Whatever the cause, try to restore "p" to the place it
003801  ** is supposed to be pointing.  If the row was deleted out from under the
003802  ** cursor, set the cursor to point to a NULL row.
003803  */
003804  int SQLITE_NOINLINE sqlite3VdbeHandleMovedCursor(VdbeCursor *p){
003805    int isDifferentRow, rc;
003806    assert( p->eCurType==CURTYPE_BTREE );
003807    assert( p->uc.pCursor!=0 );
003808    assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
003809    rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
003810    p->cacheStatus = CACHE_STALE;
003811    if( isDifferentRow ) p->nullRow = 1;
003812    return rc;
003813  }
003814  
003815  /*
003816  ** Check to ensure that the cursor is valid.  Restore the cursor
003817  ** if need be.  Return any I/O error from the restore operation.
003818  */
003819  int sqlite3VdbeCursorRestore(VdbeCursor *p){
003820    assert( p->eCurType==CURTYPE_BTREE || IsNullCursor(p) );
003821    if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
003822      return sqlite3VdbeHandleMovedCursor(p);
003823    }
003824    return SQLITE_OK;
003825  }
003826  
003827  /*
003828  ** The following functions:
003829  **
003830  ** sqlite3VdbeSerialType()
003831  ** sqlite3VdbeSerialTypeLen()
003832  ** sqlite3VdbeSerialLen()
003833  ** sqlite3VdbeSerialPut()  <--- in-lined into OP_MakeRecord as of 2022-04-02
003834  ** sqlite3VdbeSerialGet()
003835  **
003836  ** encapsulate the code that serializes values for storage in SQLite
003837  ** data and index records. Each serialized value consists of a
003838  ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
003839  ** integer, stored as a varint.
003840  **
003841  ** In an SQLite index record, the serial type is stored directly before
003842  ** the blob of data that it corresponds to. In a table record, all serial
003843  ** types are stored at the start of the record, and the blobs of data at
003844  ** the end. Hence these functions allow the caller to handle the
003845  ** serial-type and data blob separately.
003846  **
003847  ** The following table describes the various storage classes for data:
003848  **
003849  **   serial type        bytes of data      type
003850  **   --------------     ---------------    ---------------
003851  **      0                     0            NULL
003852  **      1                     1            signed integer
003853  **      2                     2            signed integer
003854  **      3                     3            signed integer
003855  **      4                     4            signed integer
003856  **      5                     6            signed integer
003857  **      6                     8            signed integer
003858  **      7                     8            IEEE float
003859  **      8                     0            Integer constant 0
003860  **      9                     0            Integer constant 1
003861  **     10,11                               reserved for expansion
003862  **    N>=12 and even       (N-12)/2        BLOB
003863  **    N>=13 and odd        (N-13)/2        text
003864  **
003865  ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
003866  ** of SQLite will not understand those serial types.
003867  */
003868  
003869  #if 0 /* Inlined into the OP_MakeRecord opcode */
003870  /*
003871  ** Return the serial-type for the value stored in pMem.
003872  **
003873  ** This routine might convert a large MEM_IntReal value into MEM_Real.
003874  **
003875  ** 2019-07-11:  The primary user of this subroutine was the OP_MakeRecord
003876  ** opcode in the byte-code engine.  But by moving this routine in-line, we
003877  ** can omit some redundant tests and make that opcode a lot faster.  So
003878  ** this routine is now only used by the STAT3 logic and STAT3 support has
003879  ** ended.  The code is kept here for historical reference only.
003880  */
003881  u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
003882    int flags = pMem->flags;
003883    u32 n;
003884  
003885    assert( pLen!=0 );
003886    if( flags&MEM_Null ){
003887      *pLen = 0;
003888      return 0;
003889    }
003890    if( flags&(MEM_Int|MEM_IntReal) ){
003891      /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
003892  #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
003893      i64 i = pMem->u.i;
003894      u64 u;
003895      testcase( flags & MEM_Int );
003896      testcase( flags & MEM_IntReal );
003897      if( i<0 ){
003898        u = ~i;
003899      }else{
003900        u = i;
003901      }
003902      if( u<=127 ){
003903        if( (i&1)==i && file_format>=4 ){
003904          *pLen = 0;
003905          return 8+(u32)u;
003906        }else{
003907          *pLen = 1;
003908          return 1;
003909        }
003910      }
003911      if( u<=32767 ){ *pLen = 2; return 2; }
003912      if( u<=8388607 ){ *pLen = 3; return 3; }
003913      if( u<=2147483647 ){ *pLen = 4; return 4; }
003914      if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
003915      *pLen = 8;
003916      if( flags&MEM_IntReal ){
003917        /* If the value is IntReal and is going to take up 8 bytes to store
003918        ** as an integer, then we might as well make it an 8-byte floating
003919        ** point value */
003920        pMem->u.r = (double)pMem->u.i;
003921        pMem->flags &= ~MEM_IntReal;
003922        pMem->flags |= MEM_Real;
003923        return 7;
003924      }
003925      return 6;
003926    }
003927    if( flags&MEM_Real ){
003928      *pLen = 8;
003929      return 7;
003930    }
003931    assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
003932    assert( pMem->n>=0 );
003933    n = (u32)pMem->n;
003934    if( flags & MEM_Zero ){
003935      n += pMem->u.nZero;
003936    }
003937    *pLen = n;
003938    return ((n*2) + 12 + ((flags&MEM_Str)!=0));
003939  }
003940  #endif /* inlined into OP_MakeRecord */
003941  
003942  /*
003943  ** The sizes for serial types less than 128
003944  */
003945  const u8 sqlite3SmallTypeSizes[128] = {
003946          /*  0   1   2   3   4   5   6   7   8   9 */  
003947  /*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
003948  /*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
003949  /*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
003950  /*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
003951  /*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
003952  /*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
003953  /*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
003954  /*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
003955  /*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
003956  /*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
003957  /* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
003958  /* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
003959  /* 120 */  54, 54, 55, 55, 56, 56, 57, 57
003960  };
003961  
003962  /*
003963  ** Return the length of the data corresponding to the supplied serial-type.
003964  */
003965  u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
003966    if( serial_type>=128 ){
003967      return (serial_type-12)/2;
003968    }else{
003969      assert( serial_type<12
003970              || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
003971      return sqlite3SmallTypeSizes[serial_type];
003972    }
003973  }
003974  u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
003975    assert( serial_type<128 );
003976    return sqlite3SmallTypeSizes[serial_type]; 
003977  }
003978  
003979  /*
003980  ** If we are on an architecture with mixed-endian floating
003981  ** points (ex: ARM7) then swap the lower 4 bytes with the
003982  ** upper 4 bytes.  Return the result.
003983  **
003984  ** For most architectures, this is a no-op.
003985  **
003986  ** (later):  It is reported to me that the mixed-endian problem
003987  ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
003988  ** that early versions of GCC stored the two words of a 64-bit
003989  ** float in the wrong order.  And that error has been propagated
003990  ** ever since.  The blame is not necessarily with GCC, though.
003991  ** GCC might have just copying the problem from a prior compiler.
003992  ** I am also told that newer versions of GCC that follow a different
003993  ** ABI get the byte order right.
003994  **
003995  ** Developers using SQLite on an ARM7 should compile and run their
003996  ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
003997  ** enabled, some asserts below will ensure that the byte order of
003998  ** floating point values is correct.
003999  **
004000  ** (2007-08-30)  Frank van Vugt has studied this problem closely
004001  ** and has send his findings to the SQLite developers.  Frank
004002  ** writes that some Linux kernels offer floating point hardware
004003  ** emulation that uses only 32-bit mantissas instead of a full
004004  ** 48-bits as required by the IEEE standard.  (This is the
004005  ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
004006  ** byte swapping becomes very complicated.  To avoid problems,
004007  ** the necessary byte swapping is carried out using a 64-bit integer
004008  ** rather than a 64-bit float.  Frank assures us that the code here
004009  ** works for him.  We, the developers, have no way to independently
004010  ** verify this, but Frank seems to know what he is talking about
004011  ** so we trust him.
004012  */
004013  #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
004014  u64 sqlite3FloatSwap(u64 in){
004015    union {
004016      u64 r;
004017      u32 i[2];
004018    } u;
004019    u32 t;
004020  
004021    u.r = in;
004022    t = u.i[0];
004023    u.i[0] = u.i[1];
004024    u.i[1] = t;
004025    return u.r;
004026  }
004027  #endif /* SQLITE_MIXED_ENDIAN_64BIT_FLOAT */
004028  
004029  
004030  /* Input "x" is a sequence of unsigned characters that represent a
004031  ** big-endian integer.  Return the equivalent native integer
004032  */
004033  #define ONE_BYTE_INT(x)    ((i8)(x)[0])
004034  #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
004035  #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
004036  #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
004037  #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
004038  
004039  /*
004040  ** Deserialize the data blob pointed to by buf as serial type serial_type
004041  ** and store the result in pMem.
004042  **
004043  ** This function is implemented as two separate routines for performance.
004044  ** The few cases that require local variables are broken out into a separate
004045  ** routine so that in most cases the overhead of moving the stack pointer
004046  ** is avoided.
004047  */
004048  static void serialGet(
004049    const unsigned char *buf,     /* Buffer to deserialize from */
004050    u32 serial_type,              /* Serial type to deserialize */
004051    Mem *pMem                     /* Memory cell to write value into */
004052  ){
004053    u64 x = FOUR_BYTE_UINT(buf);
004054    u32 y = FOUR_BYTE_UINT(buf+4);
004055    x = (x<<32) + y;
004056    if( serial_type==6 ){
004057      /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
004058      ** twos-complement integer. */
004059      pMem->u.i = *(i64*)&x;
004060      pMem->flags = MEM_Int;
004061      testcase( pMem->u.i<0 );
004062    }else{
004063      /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
004064      ** floating point number. */
004065  #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
004066      /* Verify that integers and floating point values use the same
004067      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
004068      ** defined that 64-bit floating point values really are mixed
004069      ** endian.
004070      */
004071      static const u64 t1 = ((u64)0x3ff00000)<<32;
004072      static const double r1 = 1.0;
004073      u64 t2 = t1;
004074      swapMixedEndianFloat(t2);
004075      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
004076  #endif
004077      assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
004078      swapMixedEndianFloat(x);
004079      memcpy(&pMem->u.r, &x, sizeof(x));
004080      pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;
004081    }
004082  }
004083  static int serialGet7(
004084    const unsigned char *buf,     /* Buffer to deserialize from */
004085    Mem *pMem                     /* Memory cell to write value into */
004086  ){
004087    u64 x = FOUR_BYTE_UINT(buf);
004088    u32 y = FOUR_BYTE_UINT(buf+4);
004089    x = (x<<32) + y;
004090    assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
004091    swapMixedEndianFloat(x);
004092    memcpy(&pMem->u.r, &x, sizeof(x));
004093    if( IsNaN(x) ){
004094      pMem->flags = MEM_Null;
004095      return 1;
004096    }
004097    pMem->flags = MEM_Real;
004098    return 0;
004099  }
004100  void sqlite3VdbeSerialGet(
004101    const unsigned char *buf,     /* Buffer to deserialize from */
004102    u32 serial_type,              /* Serial type to deserialize */
004103    Mem *pMem                     /* Memory cell to write value into */
004104  ){
004105    switch( serial_type ){
004106      case 10: { /* Internal use only: NULL with virtual table
004107                 ** UPDATE no-change flag set */
004108        pMem->flags = MEM_Null|MEM_Zero;
004109        pMem->n = 0;
004110        pMem->u.nZero = 0;
004111        return;
004112      }
004113      case 11:   /* Reserved for future use */
004114      case 0: {  /* Null */
004115        /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
004116        pMem->flags = MEM_Null;
004117        return;
004118      }
004119      case 1: {
004120        /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
004121        ** integer. */
004122        pMem->u.i = ONE_BYTE_INT(buf);
004123        pMem->flags = MEM_Int;
004124        testcase( pMem->u.i<0 );
004125        return;
004126      }
004127      case 2: { /* 2-byte signed integer */
004128        /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
004129        ** twos-complement integer. */
004130        pMem->u.i = TWO_BYTE_INT(buf);
004131        pMem->flags = MEM_Int;
004132        testcase( pMem->u.i<0 );
004133        return;
004134      }
004135      case 3: { /* 3-byte signed integer */
004136        /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
004137        ** twos-complement integer. */
004138        pMem->u.i = THREE_BYTE_INT(buf);
004139        pMem->flags = MEM_Int;
004140        testcase( pMem->u.i<0 );
004141        return;
004142      }
004143      case 4: { /* 4-byte signed integer */
004144        /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
004145        ** twos-complement integer. */
004146        pMem->u.i = FOUR_BYTE_INT(buf);
004147  #ifdef __HP_cc
004148        /* Work around a sign-extension bug in the HP compiler for HP/UX */
004149        if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
004150  #endif
004151        pMem->flags = MEM_Int;
004152        testcase( pMem->u.i<0 );
004153        return;
004154      }
004155      case 5: { /* 6-byte signed integer */
004156        /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
004157        ** twos-complement integer. */
004158        pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
004159        pMem->flags = MEM_Int;
004160        testcase( pMem->u.i<0 );
004161        return;
004162      }
004163      case 6:   /* 8-byte signed integer */
004164      case 7: { /* IEEE floating point */
004165        /* These use local variables, so do them in a separate routine
004166        ** to avoid having to move the frame pointer in the common case */
004167        serialGet(buf,serial_type,pMem);
004168        return;
004169      }
004170      case 8:    /* Integer 0 */
004171      case 9: {  /* Integer 1 */
004172        /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
004173        /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
004174        pMem->u.i = serial_type-8;
004175        pMem->flags = MEM_Int;
004176        return;
004177      }
004178      default: {
004179        /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
004180        ** length.
004181        ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
004182        ** (N-13)/2 bytes in length. */
004183        static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
004184        pMem->z = (char *)buf;
004185        pMem->n = (serial_type-12)/2;
004186        pMem->flags = aFlag[serial_type&1];
004187        return;
004188      }
004189    }
004190    return;
004191  }
004192  /*
004193  ** This routine is used to allocate sufficient space for an UnpackedRecord
004194  ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
004195  ** the first argument is a pointer to KeyInfo structure pKeyInfo.
004196  **
004197  ** The space is either allocated using sqlite3DbMallocRaw() or from within
004198  ** the unaligned buffer passed via the second and third arguments (presumably
004199  ** stack space). If the former, then *ppFree is set to a pointer that should
004200  ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
004201  ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
004202  ** before returning.
004203  **
004204  ** If an OOM error occurs, NULL is returned.
004205  */
004206  UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
004207    KeyInfo *pKeyInfo               /* Description of the record */
004208  ){
004209    UnpackedRecord *p;              /* Unpacked record to return */
004210    int nByte;                      /* Number of bytes required for *p */
004211    nByte = ROUND8P(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
004212    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
004213    if( !p ) return 0;
004214    p->aMem = (Mem*)&((char*)p)[ROUND8P(sizeof(UnpackedRecord))];
004215    assert( pKeyInfo->aSortFlags!=0 );
004216    p->pKeyInfo = pKeyInfo;
004217    p->nField = pKeyInfo->nKeyField + 1;
004218    return p;
004219  }
004220  
004221  /*
004222  ** Given the nKey-byte encoding of a record in pKey[], populate the
004223  ** UnpackedRecord structure indicated by the fourth argument with the
004224  ** contents of the decoded record.
004225  */
004226  void sqlite3VdbeRecordUnpack(
004227    KeyInfo *pKeyInfo,     /* Information about the record format */
004228    int nKey,              /* Size of the binary record */
004229    const void *pKey,      /* The binary record */
004230    UnpackedRecord *p      /* Populate this structure before returning. */
004231  ){
004232    const unsigned char *aKey = (const unsigned char *)pKey;
004233    u32 d;
004234    u32 idx;                        /* Offset in aKey[] to read from */
004235    u16 u;                          /* Unsigned loop counter */
004236    u32 szHdr;
004237    Mem *pMem = p->aMem;
004238  
004239    p->default_rc = 0;
004240    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
004241    idx = getVarint32(aKey, szHdr);
004242    d = szHdr;
004243    u = 0;
004244    while( idx<szHdr && d<=(u32)nKey ){
004245      u32 serial_type;
004246  
004247      idx += getVarint32(&aKey[idx], serial_type);
004248      pMem->enc = pKeyInfo->enc;
004249      pMem->db = pKeyInfo->db;
004250      /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
004251      pMem->szMalloc = 0;
004252      pMem->z = 0;
004253      sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
004254      d += sqlite3VdbeSerialTypeLen(serial_type);
004255      pMem++;
004256      if( (++u)>=p->nField ) break;
004257    }
004258    if( d>(u32)nKey && u ){
004259      assert( CORRUPT_DB );
004260      /* In a corrupt record entry, the last pMem might have been set up using
004261      ** uninitialized memory. Overwrite its value with NULL, to prevent
004262      ** warnings from MSAN. */
004263      sqlite3VdbeMemSetNull(pMem-1);
004264    }
004265    assert( u<=pKeyInfo->nKeyField + 1 );
004266    p->nField = u;
004267  }
004268  
004269  #ifdef SQLITE_DEBUG
004270  /*
004271  ** This function compares two index or table record keys in the same way
004272  ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
004273  ** this function deserializes and compares values using the
004274  ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
004275  ** in assert() statements to ensure that the optimized code in
004276  ** sqlite3VdbeRecordCompare() returns results with these two primitives.
004277  **
004278  ** Return true if the result of comparison is equivalent to desiredResult.
004279  ** Return false if there is a disagreement.
004280  */
004281  static int vdbeRecordCompareDebug(
004282    int nKey1, const void *pKey1, /* Left key */
004283    const UnpackedRecord *pPKey2, /* Right key */
004284    int desiredResult             /* Correct answer */
004285  ){
004286    u32 d1;            /* Offset into aKey[] of next data element */
004287    u32 idx1;          /* Offset into aKey[] of next header element */
004288    u32 szHdr1;        /* Number of bytes in header */
004289    int i = 0;
004290    int rc = 0;
004291    const unsigned char *aKey1 = (const unsigned char *)pKey1;
004292    KeyInfo *pKeyInfo;
004293    Mem mem1;
004294  
004295    pKeyInfo = pPKey2->pKeyInfo;
004296    if( pKeyInfo->db==0 ) return 1;
004297    mem1.enc = pKeyInfo->enc;
004298    mem1.db = pKeyInfo->db;
004299    /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
004300    VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
004301  
004302    /* Compilers may complain that mem1.u.i is potentially uninitialized.
004303    ** We could initialize it, as shown here, to silence those complaints.
004304    ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
004305    ** the unnecessary initialization has a measurable negative performance
004306    ** impact, since this routine is a very high runner.  And so, we choose
004307    ** to ignore the compiler warnings and leave this variable uninitialized.
004308    */
004309    /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
004310   
004311    idx1 = getVarint32(aKey1, szHdr1);
004312    if( szHdr1>98307 ) return SQLITE_CORRUPT;
004313    d1 = szHdr1;
004314    assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
004315    assert( pKeyInfo->aSortFlags!=0 );
004316    assert( pKeyInfo->nKeyField>0 );
004317    assert( idx1<=szHdr1 || CORRUPT_DB );
004318    do{
004319      u32 serial_type1;
004320  
004321      /* Read the serial types for the next element in each key. */
004322      idx1 += getVarint32( aKey1+idx1, serial_type1 );
004323  
004324      /* Verify that there is enough key space remaining to avoid
004325      ** a buffer overread.  The "d1+serial_type1+2" subexpression will
004326      ** always be greater than or equal to the amount of required key space.
004327      ** Use that approximation to avoid the more expensive call to
004328      ** sqlite3VdbeSerialTypeLen() in the common case.
004329      */
004330      if( d1+(u64)serial_type1+2>(u64)nKey1
004331       && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1
004332      ){
004333        if( serial_type1>=1
004334         && serial_type1<=7
004335         && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)<=(u64)nKey1+8
004336         && CORRUPT_DB
004337        ){
004338          return 1;  /* corrupt record not detected by
004339                     ** sqlite3VdbeRecordCompareWithSkip().  Return true
004340                     ** to avoid firing the assert() */
004341        }
004342        break;
004343      }
004344  
004345      /* Extract the values to be compared.
004346      */
004347      sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
004348      d1 += sqlite3VdbeSerialTypeLen(serial_type1);
004349  
004350      /* Do the comparison
004351      */
004352      rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
004353                             pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
004354      if( rc!=0 ){
004355        assert( mem1.szMalloc==0 );  /* See comment below */
004356        if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
004357         && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null))
004358        ){
004359          rc = -rc;
004360        }
004361        if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){
004362          rc = -rc;  /* Invert the result for DESC sort order. */
004363        }
004364        goto debugCompareEnd;
004365      }
004366      i++;
004367    }while( idx1<szHdr1 && i<pPKey2->nField );
004368  
004369    /* No memory allocation is ever used on mem1.  Prove this using
004370    ** the following assert().  If the assert() fails, it indicates a
004371    ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
004372    */
004373    assert( mem1.szMalloc==0 );
004374  
004375    /* rc==0 here means that one of the keys ran out of fields and
004376    ** all the fields up to that point were equal. Return the default_rc
004377    ** value.  */
004378    rc = pPKey2->default_rc;
004379  
004380  debugCompareEnd:
004381    if( desiredResult==0 && rc==0 ) return 1;
004382    if( desiredResult<0 && rc<0 ) return 1;
004383    if( desiredResult>0 && rc>0 ) return 1;
004384    if( CORRUPT_DB ) return 1;
004385    if( pKeyInfo->db->mallocFailed ) return 1;
004386    return 0;
004387  }
004388  #endif
004389  
004390  #ifdef SQLITE_DEBUG
004391  /*
004392  ** Count the number of fields (a.k.a. columns) in the record given by
004393  ** pKey,nKey.  The verify that this count is less than or equal to the
004394  ** limit given by pKeyInfo->nAllField.
004395  **
004396  ** If this constraint is not satisfied, it means that the high-speed
004397  ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
004398  ** not work correctly.  If this assert() ever fires, it probably means
004399  ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
004400  ** incorrectly.
004401  */
004402  static void vdbeAssertFieldCountWithinLimits(
004403    int nKey, const void *pKey,   /* The record to verify */
004404    const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
004405  ){
004406    int nField = 0;
004407    u32 szHdr;
004408    u32 idx;
004409    u32 notUsed;
004410    const unsigned char *aKey = (const unsigned char*)pKey;
004411  
004412    if( CORRUPT_DB ) return;
004413    idx = getVarint32(aKey, szHdr);
004414    assert( nKey>=0 );
004415    assert( szHdr<=(u32)nKey );
004416    while( idx<szHdr ){
004417      idx += getVarint32(aKey+idx, notUsed);
004418      nField++;
004419    }
004420    assert( nField <= pKeyInfo->nAllField );
004421  }
004422  #else
004423  # define vdbeAssertFieldCountWithinLimits(A,B,C)
004424  #endif
004425  
004426  /*
004427  ** Both *pMem1 and *pMem2 contain string values. Compare the two values
004428  ** using the collation sequence pColl. As usual, return a negative , zero
004429  ** or positive value if *pMem1 is less than, equal to or greater than
004430  ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
004431  */
004432  static int vdbeCompareMemString(
004433    const Mem *pMem1,
004434    const Mem *pMem2,
004435    const CollSeq *pColl,
004436    u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
004437  ){
004438    if( pMem1->enc==pColl->enc ){
004439      /* The strings are already in the correct encoding.  Call the
004440       ** comparison function directly */
004441      return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
004442    }else{
004443      int rc;
004444      const void *v1, *v2;
004445      Mem c1;
004446      Mem c2;
004447      sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
004448      sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
004449      sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
004450      sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
004451      v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
004452      v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
004453      if( (v1==0 || v2==0) ){
004454        if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
004455        rc = 0;
004456      }else{
004457        rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
004458      }
004459      sqlite3VdbeMemReleaseMalloc(&c1);
004460      sqlite3VdbeMemReleaseMalloc(&c2);
004461      return rc;
004462    }
004463  }
004464  
004465  /*
004466  ** The input pBlob is guaranteed to be a Blob that is not marked
004467  ** with MEM_Zero.  Return true if it could be a zero-blob.
004468  */
004469  static int isAllZero(const char *z, int n){
004470    int i;
004471    for(i=0; i<n; i++){
004472      if( z[i] ) return 0;
004473    }
004474    return 1;
004475  }
004476  
004477  /*
004478  ** Compare two blobs.  Return negative, zero, or positive if the first
004479  ** is less than, equal to, or greater than the second, respectively.
004480  ** If one blob is a prefix of the other, then the shorter is the lessor.
004481  */
004482  SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
004483    int c;
004484    int n1 = pB1->n;
004485    int n2 = pB2->n;
004486  
004487    /* It is possible to have a Blob value that has some non-zero content
004488    ** followed by zero content.  But that only comes up for Blobs formed
004489    ** by the OP_MakeRecord opcode, and such Blobs never get passed into
004490    ** sqlite3MemCompare(). */
004491    assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
004492    assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
004493  
004494    if( (pB1->flags|pB2->flags) & MEM_Zero ){
004495      if( pB1->flags & pB2->flags & MEM_Zero ){
004496        return pB1->u.nZero - pB2->u.nZero;
004497      }else if( pB1->flags & MEM_Zero ){
004498        if( !isAllZero(pB2->z, pB2->n) ) return -1;
004499        return pB1->u.nZero - n2;
004500      }else{
004501        if( !isAllZero(pB1->z, pB1->n) ) return +1;
004502        return n1 - pB2->u.nZero;
004503      }
004504    }
004505    c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
004506    if( c ) return c;
004507    return n1 - n2;
004508  }
004509  
004510  /* The following two functions are used only within testcase() to prove
004511  ** test coverage.  These functions do no exist for production builds.
004512  ** We must use separate SQLITE_NOINLINE functions here, since otherwise
004513  ** optimizer code movement causes gcov to become very confused.
004514  */
004515  #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
004516  static int SQLITE_NOINLINE doubleLt(double a, double b){ return a<b; }
004517  static int SQLITE_NOINLINE doubleEq(double a, double b){ return a==b; }
004518  #endif
004519  
004520  /*
004521  ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
004522  ** number.  Return negative, zero, or positive if the first (i64) is less than,
004523  ** equal to, or greater than the second (double).
004524  */
004525  int sqlite3IntFloatCompare(i64 i, double r){
004526    if( sqlite3IsNaN(r) ){
004527      /* SQLite considers NaN to be a NULL. And all integer values are greater
004528      ** than NULL */
004529      return 1;
004530    }else{
004531      i64 y;
004532      if( r<-9223372036854775808.0 ) return +1;
004533      if( r>=9223372036854775808.0 ) return -1;
004534      y = (i64)r;
004535      if( i<y ) return -1;
004536      if( i>y ) return +1;
004537      testcase( doubleLt(((double)i),r) );
004538      testcase( doubleLt(r,((double)i)) );
004539      testcase( doubleEq(r,((double)i)) );
004540      return (((double)i)<r) ? -1 : (((double)i)>r);
004541    }
004542  }
004543  
004544  /*
004545  ** Compare the values contained by the two memory cells, returning
004546  ** negative, zero or positive if pMem1 is less than, equal to, or greater
004547  ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
004548  ** and reals) sorted numerically, followed by text ordered by the collating
004549  ** sequence pColl and finally blob's ordered by memcmp().
004550  **
004551  ** Two NULL values are considered equal by this function.
004552  */
004553  int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
004554    int f1, f2;
004555    int combined_flags;
004556  
004557    f1 = pMem1->flags;
004558    f2 = pMem2->flags;
004559    combined_flags = f1|f2;
004560    assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
004561  
004562    /* If one value is NULL, it is less than the other. If both values
004563    ** are NULL, return 0.
004564    */
004565    if( combined_flags&MEM_Null ){
004566      return (f2&MEM_Null) - (f1&MEM_Null);
004567    }
004568  
004569    /* At least one of the two values is a number
004570    */
004571    if( combined_flags&(MEM_Int|MEM_Real|MEM_IntReal) ){
004572      testcase( combined_flags & MEM_Int );
004573      testcase( combined_flags & MEM_Real );
004574      testcase( combined_flags & MEM_IntReal );
004575      if( (f1 & f2 & (MEM_Int|MEM_IntReal))!=0 ){
004576        testcase( f1 & f2 & MEM_Int );
004577        testcase( f1 & f2 & MEM_IntReal );
004578        if( pMem1->u.i < pMem2->u.i ) return -1;
004579        if( pMem1->u.i > pMem2->u.i ) return +1;
004580        return 0;
004581      }
004582      if( (f1 & f2 & MEM_Real)!=0 ){
004583        if( pMem1->u.r < pMem2->u.r ) return -1;
004584        if( pMem1->u.r > pMem2->u.r ) return +1;
004585        return 0;
004586      }
004587      if( (f1&(MEM_Int|MEM_IntReal))!=0 ){
004588        testcase( f1 & MEM_Int );
004589        testcase( f1 & MEM_IntReal );
004590        if( (f2&MEM_Real)!=0 ){
004591          return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
004592        }else if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
004593          if( pMem1->u.i < pMem2->u.i ) return -1;
004594          if( pMem1->u.i > pMem2->u.i ) return +1;
004595          return 0;
004596        }else{
004597          return -1;
004598        }
004599      }
004600      if( (f1&MEM_Real)!=0 ){
004601        if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
004602          testcase( f2 & MEM_Int );
004603          testcase( f2 & MEM_IntReal );
004604          return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
004605        }else{
004606          return -1;
004607        }
004608      }
004609      return +1;
004610    }
004611  
004612    /* If one value is a string and the other is a blob, the string is less.
004613    ** If both are strings, compare using the collating functions.
004614    */
004615    if( combined_flags&MEM_Str ){
004616      if( (f1 & MEM_Str)==0 ){
004617        return 1;
004618      }
004619      if( (f2 & MEM_Str)==0 ){
004620        return -1;
004621      }
004622  
004623      assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
004624      assert( pMem1->enc==SQLITE_UTF8 ||
004625              pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
004626  
004627      /* The collation sequence must be defined at this point, even if
004628      ** the user deletes the collation sequence after the vdbe program is
004629      ** compiled (this was not always the case).
004630      */
004631      assert( !pColl || pColl->xCmp );
004632  
004633      if( pColl ){
004634        return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
004635      }
004636      /* If a NULL pointer was passed as the collate function, fall through
004637      ** to the blob case and use memcmp().  */
004638    }
004639  
004640    /* Both values must be blobs.  Compare using memcmp().  */
004641    return sqlite3BlobCompare(pMem1, pMem2);
004642  }
004643  
004644  
004645  /*
004646  ** The first argument passed to this function is a serial-type that
004647  ** corresponds to an integer - all values between 1 and 9 inclusive
004648  ** except 7. The second points to a buffer containing an integer value
004649  ** serialized according to serial_type. This function deserializes
004650  ** and returns the value.
004651  */
004652  static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
004653    u32 y;
004654    assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
004655    switch( serial_type ){
004656      case 0:
004657      case 1:
004658        testcase( aKey[0]&0x80 );
004659        return ONE_BYTE_INT(aKey);
004660      case 2:
004661        testcase( aKey[0]&0x80 );
004662        return TWO_BYTE_INT(aKey);
004663      case 3:
004664        testcase( aKey[0]&0x80 );
004665        return THREE_BYTE_INT(aKey);
004666      case 4: {
004667        testcase( aKey[0]&0x80 );
004668        y = FOUR_BYTE_UINT(aKey);
004669        return (i64)*(int*)&y;
004670      }
004671      case 5: {
004672        testcase( aKey[0]&0x80 );
004673        return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
004674      }
004675      case 6: {
004676        u64 x = FOUR_BYTE_UINT(aKey);
004677        testcase( aKey[0]&0x80 );
004678        x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
004679        return (i64)*(i64*)&x;
004680      }
004681    }
004682  
004683    return (serial_type - 8);
004684  }
004685  
004686  /*
004687  ** This function compares the two table rows or index records
004688  ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
004689  ** or positive integer if key1 is less than, equal to or
004690  ** greater than key2.  The {nKey1, pKey1} key must be a blob
004691  ** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
004692  ** key must be a parsed key such as obtained from
004693  ** sqlite3VdbeParseRecord.
004694  **
004695  ** If argument bSkip is non-zero, it is assumed that the caller has already
004696  ** determined that the first fields of the keys are equal.
004697  **
004698  ** Key1 and Key2 do not have to contain the same number of fields. If all
004699  ** fields that appear in both keys are equal, then pPKey2->default_rc is
004700  ** returned.
004701  **
004702  ** If database corruption is discovered, set pPKey2->errCode to
004703  ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
004704  ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
004705  ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
004706  */
004707  int sqlite3VdbeRecordCompareWithSkip(
004708    int nKey1, const void *pKey1,   /* Left key */
004709    UnpackedRecord *pPKey2,         /* Right key */
004710    int bSkip                       /* If true, skip the first field */
004711  ){
004712    u32 d1;                         /* Offset into aKey[] of next data element */
004713    int i;                          /* Index of next field to compare */
004714    u32 szHdr1;                     /* Size of record header in bytes */
004715    u32 idx1;                       /* Offset of first type in header */
004716    int rc = 0;                     /* Return value */
004717    Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
004718    KeyInfo *pKeyInfo;
004719    const unsigned char *aKey1 = (const unsigned char *)pKey1;
004720    Mem mem1;
004721  
004722    /* If bSkip is true, then the caller has already determined that the first
004723    ** two elements in the keys are equal. Fix the various stack variables so
004724    ** that this routine begins comparing at the second field. */
004725    if( bSkip ){
004726      u32 s1 = aKey1[1];
004727      if( s1<0x80 ){
004728        idx1 = 2;
004729      }else{
004730        idx1 = 1 + sqlite3GetVarint32(&aKey1[1], &s1);
004731      }
004732      szHdr1 = aKey1[0];
004733      d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
004734      i = 1;
004735      pRhs++;
004736    }else{
004737      if( (szHdr1 = aKey1[0])<0x80 ){
004738        idx1 = 1;
004739      }else{
004740        idx1 = sqlite3GetVarint32(aKey1, &szHdr1);
004741      }
004742      d1 = szHdr1;
004743      i = 0;
004744    }
004745    if( d1>(unsigned)nKey1 ){
004746      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
004747      return 0;  /* Corruption */
004748    }
004749  
004750    VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
004751    assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
004752         || CORRUPT_DB );
004753    assert( pPKey2->pKeyInfo->aSortFlags!=0 );
004754    assert( pPKey2->pKeyInfo->nKeyField>0 );
004755    assert( idx1<=szHdr1 || CORRUPT_DB );
004756    while( 1 /*exit-by-break*/ ){
004757      u32 serial_type;
004758  
004759      /* RHS is an integer */
004760      if( pRhs->flags & (MEM_Int|MEM_IntReal) ){
004761        testcase( pRhs->flags & MEM_Int );
004762        testcase( pRhs->flags & MEM_IntReal );
004763        serial_type = aKey1[idx1];
004764        testcase( serial_type==12 );
004765        if( serial_type>=10 ){
004766          rc = serial_type==10 ? -1 : +1;
004767        }else if( serial_type==0 ){
004768          rc = -1;
004769        }else if( serial_type==7 ){
004770          serialGet7(&aKey1[d1], &mem1);
004771          rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
004772        }else{
004773          i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
004774          i64 rhs = pRhs->u.i;
004775          if( lhs<rhs ){
004776            rc = -1;
004777          }else if( lhs>rhs ){
004778            rc = +1;
004779          }
004780        }
004781      }
004782  
004783      /* RHS is real */
004784      else if( pRhs->flags & MEM_Real ){
004785        serial_type = aKey1[idx1];
004786        if( serial_type>=10 ){
004787          /* Serial types 12 or greater are strings and blobs (greater than
004788          ** numbers). Types 10 and 11 are currently "reserved for future
004789          ** use", so it doesn't really matter what the results of comparing
004790          ** them to numeric values are.  */
004791          rc = serial_type==10 ? -1 : +1;
004792        }else if( serial_type==0 ){
004793          rc = -1;
004794        }else{
004795          if( serial_type==7 ){
004796            if( serialGet7(&aKey1[d1], &mem1) ){
004797              rc = -1;  /* mem1 is a NaN */
004798            }else if( mem1.u.r<pRhs->u.r ){
004799              rc = -1;
004800            }else if( mem1.u.r>pRhs->u.r ){
004801              rc = +1;
004802            }else{
004803              assert( rc==0 );
004804            }
004805          }else{
004806            sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
004807            rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
004808          }
004809        }
004810      }
004811  
004812      /* RHS is a string */
004813      else if( pRhs->flags & MEM_Str ){
004814        getVarint32NR(&aKey1[idx1], serial_type);
004815        testcase( serial_type==12 );
004816        if( serial_type<12 ){
004817          rc = -1;
004818        }else if( !(serial_type & 0x01) ){
004819          rc = +1;
004820        }else{
004821          mem1.n = (serial_type - 12) / 2;
004822          testcase( (d1+mem1.n)==(unsigned)nKey1 );
004823          testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
004824          if( (d1+mem1.n) > (unsigned)nKey1
004825           || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
004826          ){
004827            pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
004828            return 0;                /* Corruption */
004829          }else if( pKeyInfo->aColl[i] ){
004830            mem1.enc = pKeyInfo->enc;
004831            mem1.db = pKeyInfo->db;
004832            mem1.flags = MEM_Str;
004833            mem1.z = (char*)&aKey1[d1];
004834            rc = vdbeCompareMemString(
004835                &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
004836            );
004837          }else{
004838            int nCmp = MIN(mem1.n, pRhs->n);
004839            rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
004840            if( rc==0 ) rc = mem1.n - pRhs->n;
004841          }
004842        }
004843      }
004844  
004845      /* RHS is a blob */
004846      else if( pRhs->flags & MEM_Blob ){
004847        assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
004848        getVarint32NR(&aKey1[idx1], serial_type);
004849        testcase( serial_type==12 );
004850        if( serial_type<12 || (serial_type & 0x01) ){
004851          rc = -1;
004852        }else{
004853          int nStr = (serial_type - 12) / 2;
004854          testcase( (d1+nStr)==(unsigned)nKey1 );
004855          testcase( (d1+nStr+1)==(unsigned)nKey1 );
004856          if( (d1+nStr) > (unsigned)nKey1 ){
004857            pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
004858            return 0;                /* Corruption */
004859          }else if( pRhs->flags & MEM_Zero ){
004860            if( !isAllZero((const char*)&aKey1[d1],nStr) ){
004861              rc = 1;
004862            }else{
004863              rc = nStr - pRhs->u.nZero;
004864            }
004865          }else{
004866            int nCmp = MIN(nStr, pRhs->n);
004867            rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
004868            if( rc==0 ) rc = nStr - pRhs->n;
004869          }
004870        }
004871      }
004872  
004873      /* RHS is null */
004874      else{
004875        serial_type = aKey1[idx1];
004876        if( serial_type==0
004877         || serial_type==10
004878         || (serial_type==7 && serialGet7(&aKey1[d1], &mem1)!=0)
004879        ){
004880          assert( rc==0 );
004881        }else{
004882          rc = 1;
004883        }
004884      }
004885  
004886      if( rc!=0 ){
004887        int sortFlags = pPKey2->pKeyInfo->aSortFlags[i];
004888        if( sortFlags ){
004889          if( (sortFlags & KEYINFO_ORDER_BIGNULL)==0
004890           || ((sortFlags & KEYINFO_ORDER_DESC)
004891             !=(serial_type==0 || (pRhs->flags&MEM_Null)))
004892          ){
004893            rc = -rc;
004894          }
004895        }
004896        assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
004897        assert( mem1.szMalloc==0 );  /* See comment below */
004898        return rc;
004899      }
004900  
004901      i++;
004902      if( i==pPKey2->nField ) break;
004903      pRhs++;
004904      d1 += sqlite3VdbeSerialTypeLen(serial_type);
004905      if( d1>(unsigned)nKey1 ) break;
004906      idx1 += sqlite3VarintLen(serial_type);
004907      if( idx1>=(unsigned)szHdr1 ){
004908        pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
004909        return 0;  /* Corrupt index */
004910      }
004911    }
004912  
004913    /* No memory allocation is ever used on mem1.  Prove this using
004914    ** the following assert().  If the assert() fails, it indicates a
004915    ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
004916    assert( mem1.szMalloc==0 );
004917  
004918    /* rc==0 here means that one or both of the keys ran out of fields and
004919    ** all the fields up to that point were equal. Return the default_rc
004920    ** value.  */
004921    assert( CORRUPT_DB
004922         || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
004923         || pPKey2->pKeyInfo->db->mallocFailed
004924    );
004925    pPKey2->eqSeen = 1;
004926    return pPKey2->default_rc;
004927  }
004928  int sqlite3VdbeRecordCompare(
004929    int nKey1, const void *pKey1,   /* Left key */
004930    UnpackedRecord *pPKey2          /* Right key */
004931  ){
004932    return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
004933  }
004934  
004935  
004936  /*
004937  ** This function is an optimized version of sqlite3VdbeRecordCompare()
004938  ** that (a) the first field of pPKey2 is an integer, and (b) the
004939  ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
004940  ** byte (i.e. is less than 128).
004941  **
004942  ** To avoid concerns about buffer overreads, this routine is only used
004943  ** on schemas where the maximum valid header size is 63 bytes or less.
004944  */
004945  static int vdbeRecordCompareInt(
004946    int nKey1, const void *pKey1, /* Left key */
004947    UnpackedRecord *pPKey2        /* Right key */
004948  ){
004949    const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
004950    int serial_type = ((const u8*)pKey1)[1];
004951    int res;
004952    u32 y;
004953    u64 x;
004954    i64 v;
004955    i64 lhs;
004956  
004957    vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
004958    assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
004959    switch( serial_type ){
004960      case 1: { /* 1-byte signed integer */
004961        lhs = ONE_BYTE_INT(aKey);
004962        testcase( lhs<0 );
004963        break;
004964      }
004965      case 2: { /* 2-byte signed integer */
004966        lhs = TWO_BYTE_INT(aKey);
004967        testcase( lhs<0 );
004968        break;
004969      }
004970      case 3: { /* 3-byte signed integer */
004971        lhs = THREE_BYTE_INT(aKey);
004972        testcase( lhs<0 );
004973        break;
004974      }
004975      case 4: { /* 4-byte signed integer */
004976        y = FOUR_BYTE_UINT(aKey);
004977        lhs = (i64)*(int*)&y;
004978        testcase( lhs<0 );
004979        break;
004980      }
004981      case 5: { /* 6-byte signed integer */
004982        lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
004983        testcase( lhs<0 );
004984        break;
004985      }
004986      case 6: { /* 8-byte signed integer */
004987        x = FOUR_BYTE_UINT(aKey);
004988        x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
004989        lhs = *(i64*)&x;
004990        testcase( lhs<0 );
004991        break;
004992      }
004993      case 8:
004994        lhs = 0;
004995        break;
004996      case 9:
004997        lhs = 1;
004998        break;
004999  
005000      /* This case could be removed without changing the results of running
005001      ** this code. Including it causes gcc to generate a faster switch
005002      ** statement (since the range of switch targets now starts at zero and
005003      ** is contiguous) but does not cause any duplicate code to be generated
005004      ** (as gcc is clever enough to combine the two like cases). Other
005005      ** compilers might be similar.  */
005006      case 0: case 7:
005007        return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
005008  
005009      default:
005010        return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
005011    }
005012  
005013    assert( pPKey2->u.i == pPKey2->aMem[0].u.i );
005014    v = pPKey2->u.i;
005015    if( v>lhs ){
005016      res = pPKey2->r1;
005017    }else if( v<lhs ){
005018      res = pPKey2->r2;
005019    }else if( pPKey2->nField>1 ){
005020      /* The first fields of the two keys are equal. Compare the trailing
005021      ** fields.  */
005022      res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
005023    }else{
005024      /* The first fields of the two keys are equal and there are no trailing
005025      ** fields. Return pPKey2->default_rc in this case. */
005026      res = pPKey2->default_rc;
005027      pPKey2->eqSeen = 1;
005028    }
005029  
005030    assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
005031    return res;
005032  }
005033  
005034  /*
005035  ** This function is an optimized version of sqlite3VdbeRecordCompare()
005036  ** that (a) the first field of pPKey2 is a string, that (b) the first field
005037  ** uses the collation sequence BINARY and (c) that the size-of-header varint
005038  ** at the start of (pKey1/nKey1) fits in a single byte.
005039  */
005040  static int vdbeRecordCompareString(
005041    int nKey1, const void *pKey1, /* Left key */
005042    UnpackedRecord *pPKey2        /* Right key */
005043  ){
005044    const u8 *aKey1 = (const u8*)pKey1;
005045    int serial_type;
005046    int res;
005047  
005048    assert( pPKey2->aMem[0].flags & MEM_Str );
005049    assert( pPKey2->aMem[0].n == pPKey2->n );
005050    assert( pPKey2->aMem[0].z == pPKey2->u.z );
005051    vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
005052    serial_type = (signed char)(aKey1[1]);
005053  
005054  vrcs_restart:
005055    if( serial_type<12 ){
005056      if( serial_type<0 ){
005057        sqlite3GetVarint32(&aKey1[1], (u32*)&serial_type);
005058        if( serial_type>=12 ) goto vrcs_restart;
005059        assert( CORRUPT_DB );
005060      }
005061      res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
005062    }else if( !(serial_type & 0x01) ){
005063      res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
005064    }else{
005065      int nCmp;
005066      int nStr;
005067      int szHdr = aKey1[0];
005068  
005069      nStr = (serial_type-12) / 2;
005070      if( (szHdr + nStr) > nKey1 ){
005071        pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
005072        return 0;    /* Corruption */
005073      }
005074      nCmp = MIN( pPKey2->n, nStr );
005075      res = memcmp(&aKey1[szHdr], pPKey2->u.z, nCmp);
005076  
005077      if( res>0 ){
005078        res = pPKey2->r2;
005079      }else if( res<0 ){
005080        res = pPKey2->r1;
005081      }else{
005082        res = nStr - pPKey2->n;
005083        if( res==0 ){
005084          if( pPKey2->nField>1 ){
005085            res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
005086          }else{
005087            res = pPKey2->default_rc;
005088            pPKey2->eqSeen = 1;
005089          }
005090        }else if( res>0 ){
005091          res = pPKey2->r2;
005092        }else{
005093          res = pPKey2->r1;
005094        }
005095      }
005096    }
005097  
005098    assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
005099         || CORRUPT_DB
005100         || pPKey2->pKeyInfo->db->mallocFailed
005101    );
005102    return res;
005103  }
005104  
005105  /*
005106  ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
005107  ** suitable for comparing serialized records to the unpacked record passed
005108  ** as the only argument.
005109  */
005110  RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
005111    /* varintRecordCompareInt() and varintRecordCompareString() both assume
005112    ** that the size-of-header varint that occurs at the start of each record
005113    ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
005114    ** also assumes that it is safe to overread a buffer by at least the
005115    ** maximum possible legal header size plus 8 bytes. Because there is
005116    ** guaranteed to be at least 74 (but not 136) bytes of padding following each
005117    ** buffer passed to varintRecordCompareInt() this makes it convenient to
005118    ** limit the size of the header to 64 bytes in cases where the first field
005119    ** is an integer.
005120    **
005121    ** The easiest way to enforce this limit is to consider only records with
005122    ** 13 fields or less. If the first field is an integer, the maximum legal
005123    ** header size is (12*5 + 1 + 1) bytes.  */
005124    if( p->pKeyInfo->nAllField<=13 ){
005125      int flags = p->aMem[0].flags;
005126      if( p->pKeyInfo->aSortFlags[0] ){
005127        if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){
005128          return sqlite3VdbeRecordCompare;
005129        }
005130        p->r1 = 1;
005131        p->r2 = -1;
005132      }else{
005133        p->r1 = -1;
005134        p->r2 = 1;
005135      }
005136      if( (flags & MEM_Int) ){
005137        p->u.i = p->aMem[0].u.i;
005138        return vdbeRecordCompareInt;
005139      }
005140      testcase( flags & MEM_Real );
005141      testcase( flags & MEM_Null );
005142      testcase( flags & MEM_Blob );
005143      if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0
005144       && p->pKeyInfo->aColl[0]==0
005145      ){
005146        assert( flags & MEM_Str );
005147        p->u.z = p->aMem[0].z;
005148        p->n = p->aMem[0].n;
005149        return vdbeRecordCompareString;
005150      }
005151    }
005152  
005153    return sqlite3VdbeRecordCompare;
005154  }
005155  
005156  /*
005157  ** pCur points at an index entry created using the OP_MakeRecord opcode.
005158  ** Read the rowid (the last field in the record) and store it in *rowid.
005159  ** Return SQLITE_OK if everything works, or an error code otherwise.
005160  **
005161  ** pCur might be pointing to text obtained from a corrupt database file.
005162  ** So the content cannot be trusted.  Do appropriate checks on the content.
005163  */
005164  int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
005165    i64 nCellKey = 0;
005166    int rc;
005167    u32 szHdr;        /* Size of the header */
005168    u32 typeRowid;    /* Serial type of the rowid */
005169    u32 lenRowid;     /* Size of the rowid */
005170    Mem m, v;
005171  
005172    /* Get the size of the index entry.  Only indices entries of less
005173    ** than 2GiB are support - anything large must be database corruption.
005174    ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
005175    ** this code can safely assume that nCellKey is 32-bits 
005176    */
005177    assert( sqlite3BtreeCursorIsValid(pCur) );
005178    nCellKey = sqlite3BtreePayloadSize(pCur);
005179    assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
005180  
005181    /* Read in the complete content of the index entry */
005182    sqlite3VdbeMemInit(&m, db, 0);
005183    rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
005184    if( rc ){
005185      return rc;
005186    }
005187  
005188    /* The index entry must begin with a header size */
005189    getVarint32NR((u8*)m.z, szHdr);
005190    testcase( szHdr==3 );
005191    testcase( szHdr==(u32)m.n );
005192    testcase( szHdr>0x7fffffff );
005193    assert( m.n>=0 );
005194    if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
005195      goto idx_rowid_corruption;
005196    }
005197  
005198    /* The last field of the index should be an integer - the ROWID.
005199    ** Verify that the last entry really is an integer. */
005200    getVarint32NR((u8*)&m.z[szHdr-1], typeRowid);
005201    testcase( typeRowid==1 );
005202    testcase( typeRowid==2 );
005203    testcase( typeRowid==3 );
005204    testcase( typeRowid==4 );
005205    testcase( typeRowid==5 );
005206    testcase( typeRowid==6 );
005207    testcase( typeRowid==8 );
005208    testcase( typeRowid==9 );
005209    if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
005210      goto idx_rowid_corruption;
005211    }
005212    lenRowid = sqlite3SmallTypeSizes[typeRowid];
005213    testcase( (u32)m.n==szHdr+lenRowid );
005214    if( unlikely((u32)m.n<szHdr+lenRowid) ){
005215      goto idx_rowid_corruption;
005216    }
005217  
005218    /* Fetch the integer off the end of the index record */
005219    sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
005220    *rowid = v.u.i;
005221    sqlite3VdbeMemReleaseMalloc(&m);
005222    return SQLITE_OK;
005223  
005224    /* Jump here if database corruption is detected after m has been
005225    ** allocated.  Free the m object and return SQLITE_CORRUPT. */
005226  idx_rowid_corruption:
005227    testcase( m.szMalloc!=0 );
005228    sqlite3VdbeMemReleaseMalloc(&m);
005229    return SQLITE_CORRUPT_BKPT;
005230  }
005231  
005232  /*
005233  ** Compare the key of the index entry that cursor pC is pointing to against
005234  ** the key string in pUnpacked.  Write into *pRes a number
005235  ** that is negative, zero, or positive if pC is less than, equal to,
005236  ** or greater than pUnpacked.  Return SQLITE_OK on success.
005237  **
005238  ** pUnpacked is either created without a rowid or is truncated so that it
005239  ** omits the rowid at the end.  The rowid at the end of the index entry
005240  ** is ignored as well.  Hence, this routine only compares the prefixes
005241  ** of the keys prior to the final rowid, not the entire key.
005242  */
005243  int sqlite3VdbeIdxKeyCompare(
005244    sqlite3 *db,                     /* Database connection */
005245    VdbeCursor *pC,                  /* The cursor to compare against */
005246    UnpackedRecord *pUnpacked,       /* Unpacked version of key */
005247    int *res                         /* Write the comparison result here */
005248  ){
005249    i64 nCellKey = 0;
005250    int rc;
005251    BtCursor *pCur;
005252    Mem m;
005253  
005254    assert( pC->eCurType==CURTYPE_BTREE );
005255    pCur = pC->uc.pCursor;
005256    assert( sqlite3BtreeCursorIsValid(pCur) );
005257    nCellKey = sqlite3BtreePayloadSize(pCur);
005258    /* nCellKey will always be between 0 and 0xffffffff because of the way
005259    ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
005260    if( nCellKey<=0 || nCellKey>0x7fffffff ){
005261      *res = 0;
005262      return SQLITE_CORRUPT_BKPT;
005263    }
005264    sqlite3VdbeMemInit(&m, db, 0);
005265    rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
005266    if( rc ){
005267      return rc;
005268    }
005269    *res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);
005270    sqlite3VdbeMemReleaseMalloc(&m);
005271    return SQLITE_OK;
005272  }
005273  
005274  /*
005275  ** This routine sets the value to be returned by subsequent calls to
005276  ** sqlite3_changes() on the database handle 'db'.
005277  */
005278  void sqlite3VdbeSetChanges(sqlite3 *db, i64 nChange){
005279    assert( sqlite3_mutex_held(db->mutex) );
005280    db->nChange = nChange;
005281    db->nTotalChange += nChange;
005282  }
005283  
005284  /*
005285  ** Set a flag in the vdbe to update the change counter when it is finalised
005286  ** or reset.
005287  */
005288  void sqlite3VdbeCountChanges(Vdbe *v){
005289    v->changeCntOn = 1;
005290  }
005291  
005292  /*
005293  ** Mark every prepared statement associated with a database connection
005294  ** as expired.
005295  **
005296  ** An expired statement means that recompilation of the statement is
005297  ** recommend.  Statements expire when things happen that make their
005298  ** programs obsolete.  Removing user-defined functions or collating
005299  ** sequences, or changing an authorization function are the types of
005300  ** things that make prepared statements obsolete.
005301  **
005302  ** If iCode is 1, then expiration is advisory.  The statement should
005303  ** be reprepared before being restarted, but if it is already running
005304  ** it is allowed to run to completion.
005305  **
005306  ** Internally, this function just sets the Vdbe.expired flag on all
005307  ** prepared statements.  The flag is set to 1 for an immediate expiration
005308  ** and set to 2 for an advisory expiration.
005309  */
005310  void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){
005311    Vdbe *p;
005312    for(p = db->pVdbe; p; p=p->pVNext){
005313      p->expired = iCode+1;
005314    }
005315  }
005316  
005317  /*
005318  ** Return the database associated with the Vdbe.
005319  */
005320  sqlite3 *sqlite3VdbeDb(Vdbe *v){
005321    return v->db;
005322  }
005323  
005324  /*
005325  ** Return the SQLITE_PREPARE flags for a Vdbe.
005326  */
005327  u8 sqlite3VdbePrepareFlags(Vdbe *v){
005328    return v->prepFlags;
005329  }
005330  
005331  /*
005332  ** Return a pointer to an sqlite3_value structure containing the value bound
005333  ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
005334  ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
005335  ** constants) to the value before returning it.
005336  **
005337  ** The returned value must be freed by the caller using sqlite3ValueFree().
005338  */
005339  sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
005340    assert( iVar>0 );
005341    if( v ){
005342      Mem *pMem = &v->aVar[iVar-1];
005343      assert( (v->db->flags & SQLITE_EnableQPSG)==0 
005344           || (v->db->mDbFlags & DBFLAG_InternalFunc)!=0 );
005345      if( 0==(pMem->flags & MEM_Null) ){
005346        sqlite3_value *pRet = sqlite3ValueNew(v->db);
005347        if( pRet ){
005348          sqlite3VdbeMemCopy((Mem *)pRet, pMem);
005349          sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
005350        }
005351        return pRet;
005352      }
005353    }
005354    return 0;
005355  }
005356  
005357  /*
005358  ** Configure SQL variable iVar so that binding a new value to it signals
005359  ** to sqlite3_reoptimize() that re-preparing the statement may result
005360  ** in a better query plan.
005361  */
005362  void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
005363    assert( iVar>0 );
005364    assert( (v->db->flags & SQLITE_EnableQPSG)==0 
005365         || (v->db->mDbFlags & DBFLAG_InternalFunc)!=0 );
005366    if( iVar>=32 ){
005367      v->expmask |= 0x80000000;
005368    }else{
005369      v->expmask |= ((u32)1 << (iVar-1));
005370    }
005371  }
005372  
005373  /*
005374  ** Cause a function to throw an error if it was call from OP_PureFunc
005375  ** rather than OP_Function.
005376  **
005377  ** OP_PureFunc means that the function must be deterministic, and should
005378  ** throw an error if it is given inputs that would make it non-deterministic.
005379  ** This routine is invoked by date/time functions that use non-deterministic
005380  ** features such as 'now'.
005381  */
005382  int sqlite3NotPureFunc(sqlite3_context *pCtx){
005383    const VdbeOp *pOp;
005384  #ifdef SQLITE_ENABLE_STAT4
005385    if( pCtx->pVdbe==0 ) return 1;
005386  #endif
005387    pOp = pCtx->pVdbe->aOp + pCtx->iOp;
005388    if( pOp->opcode==OP_PureFunc ){
005389      const char *zContext;
005390      char *zMsg;
005391      if( pOp->p5 & NC_IsCheck ){
005392        zContext = "a CHECK constraint";
005393      }else if( pOp->p5 & NC_GenCol ){
005394        zContext = "a generated column";
005395      }else{
005396        zContext = "an index";
005397      }
005398      zMsg = sqlite3_mprintf("non-deterministic use of %s() in %s",
005399                             pCtx->pFunc->zName, zContext);
005400      sqlite3_result_error(pCtx, zMsg, -1);
005401      sqlite3_free(zMsg);
005402      return 0;
005403    }
005404    return 1;
005405  }
005406  
005407  #if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
005408  /*
005409  ** This Walker callback is used to help verify that calls to
005410  ** sqlite3BtreeCursorHint() with opcode BTREE_HINT_RANGE have
005411  ** byte-code register values correctly initialized.
005412  */
005413  int sqlite3CursorRangeHintExprCheck(Walker *pWalker, Expr *pExpr){
005414    if( pExpr->op==TK_REGISTER ){
005415      assert( (pWalker->u.aMem[pExpr->iTable].flags & MEM_Undefined)==0 );
005416    }
005417    return WRC_Continue;
005418  }
005419  #endif /* SQLITE_ENABLE_CURSOR_HINTS && SQLITE_DEBUG */
005420  
005421  #ifndef SQLITE_OMIT_VIRTUALTABLE
005422  /*
005423  ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
005424  ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
005425  ** in memory obtained from sqlite3DbMalloc).
005426  */
005427  void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
005428    if( pVtab->zErrMsg ){
005429      sqlite3 *db = p->db;
005430      sqlite3DbFree(db, p->zErrMsg);
005431      p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
005432      sqlite3_free(pVtab->zErrMsg);
005433      pVtab->zErrMsg = 0;
005434    }
005435  }
005436  #endif /* SQLITE_OMIT_VIRTUALTABLE */
005437  
005438  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
005439  
005440  /*
005441  ** If the second argument is not NULL, release any allocations associated
005442  ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
005443  ** structure itself, using sqlite3DbFree().
005444  **
005445  ** This function is used to free UnpackedRecord structures allocated by
005446  ** the vdbeUnpackRecord() function found in vdbeapi.c.
005447  */
005448  static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
005449    assert( db!=0 );
005450    if( p ){
005451      int i;
005452      for(i=0; i<nField; i++){
005453        Mem *pMem = &p->aMem[i];
005454        if( pMem->zMalloc ) sqlite3VdbeMemReleaseMalloc(pMem);
005455      }
005456      sqlite3DbNNFreeNN(db, p);
005457    }
005458  }
005459  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
005460  
005461  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
005462  /*
005463  ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
005464  ** then cursor passed as the second argument should point to the row about
005465  ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
005466  ** the required value will be read from the row the cursor points to.
005467  */
005468  void sqlite3VdbePreUpdateHook(
005469    Vdbe *v,                        /* Vdbe pre-update hook is invoked by */
005470    VdbeCursor *pCsr,               /* Cursor to grab old.* values from */
005471    int op,                         /* SQLITE_INSERT, UPDATE or DELETE */
005472    const char *zDb,                /* Database name */
005473    Table *pTab,                    /* Modified table */
005474    i64 iKey1,                      /* Initial key value */
005475    int iReg,                       /* Register for new.* record */
005476    int iBlobWrite
005477  ){
005478    sqlite3 *db = v->db;
005479    i64 iKey2;
005480    PreUpdate preupdate;
005481    const char *zTbl = pTab->zName;
005482    static const u8 fakeSortOrder = 0;
005483  #ifdef SQLITE_DEBUG
005484    int nRealCol;
005485    if( pTab->tabFlags & TF_WithoutRowid ){
005486      nRealCol = sqlite3PrimaryKeyIndex(pTab)->nColumn;
005487    }else if( pTab->tabFlags & TF_HasVirtual ){
005488      nRealCol = pTab->nNVCol;
005489    }else{
005490      nRealCol = pTab->nCol;
005491    }
005492  #endif
005493  
005494    assert( db->pPreUpdate==0 );
005495    memset(&preupdate, 0, sizeof(PreUpdate));
005496    if( HasRowid(pTab)==0 ){
005497      iKey1 = iKey2 = 0;
005498      preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
005499    }else{
005500      if( op==SQLITE_UPDATE ){
005501        iKey2 = v->aMem[iReg].u.i;
005502      }else{
005503        iKey2 = iKey1;
005504      }
005505    }
005506  
005507    assert( pCsr!=0 );
005508    assert( pCsr->eCurType==CURTYPE_BTREE );
005509    assert( pCsr->nField==nRealCol
005510         || (pCsr->nField==nRealCol+1 && op==SQLITE_DELETE && iReg==-1)
005511    );
005512  
005513    preupdate.v = v;
005514    preupdate.pCsr = pCsr;
005515    preupdate.op = op;
005516    preupdate.iNewReg = iReg;
005517    preupdate.keyinfo.db = db;
005518    preupdate.keyinfo.enc = ENC(db);
005519    preupdate.keyinfo.nKeyField = pTab->nCol;
005520    preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder;
005521    preupdate.iKey1 = iKey1;
005522    preupdate.iKey2 = iKey2;
005523    preupdate.pTab = pTab;
005524    preupdate.iBlobWrite = iBlobWrite;
005525  
005526    db->pPreUpdate = &preupdate;
005527    db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
005528    db->pPreUpdate = 0;
005529    sqlite3DbFree(db, preupdate.aRecord);
005530    vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
005531    vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
005532    if( preupdate.aNew ){
005533      int i;
005534      for(i=0; i<pCsr->nField; i++){
005535        sqlite3VdbeMemRelease(&preupdate.aNew[i]);
005536      }
005537      sqlite3DbNNFreeNN(db, preupdate.aNew);
005538    }
005539    if( preupdate.apDflt ){
005540      int i;
005541      for(i=0; i<pTab->nCol; i++){
005542        sqlite3ValueFree(preupdate.apDflt[i]);
005543      }
005544      sqlite3DbFree(db, preupdate.apDflt);
005545    }
005546  }
005547  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */