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    }
001417  }
001418  
001419  /*
001420  ** Free the space allocated for aOp and any p4 values allocated for the
001421  ** opcodes contained within. If aOp is not NULL it is assumed to contain
001422  ** nOp entries.
001423  */
001424  static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
001425    assert( nOp>=0 );
001426    assert( db!=0 );
001427    if( aOp ){
001428      Op *pOp = &aOp[nOp-1];
001429      while(1){  /* Exit via break */
001430        if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
001431  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
001432        sqlite3DbFree(db, pOp->zComment);
001433  #endif    
001434        if( pOp==aOp ) break;
001435        pOp--;
001436      }
001437      sqlite3DbNNFreeNN(db, aOp);
001438    }
001439  }
001440  
001441  /*
001442  ** Link the SubProgram object passed as the second argument into the linked
001443  ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
001444  ** objects when the VM is no longer required.
001445  */
001446  void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
001447    p->pNext = pVdbe->pProgram;
001448    pVdbe->pProgram = p;
001449  }
001450  
001451  /*
001452  ** Return true if the given Vdbe has any SubPrograms.
001453  */
001454  int sqlite3VdbeHasSubProgram(Vdbe *pVdbe){
001455    return pVdbe->pProgram!=0;
001456  }
001457  
001458  /*
001459  ** Change the opcode at addr into OP_Noop
001460  */
001461  int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
001462    VdbeOp *pOp;
001463    if( p->db->mallocFailed ) return 0;
001464    assert( addr>=0 && addr<p->nOp );
001465    pOp = &p->aOp[addr];
001466    freeP4(p->db, pOp->p4type, pOp->p4.p);
001467    pOp->p4type = P4_NOTUSED;
001468    pOp->p4.z = 0;
001469    pOp->opcode = OP_Noop;
001470    return 1;
001471  }
001472  
001473  /*
001474  ** If the last opcode is "op" and it is not a jump destination,
001475  ** then remove it.  Return true if and only if an opcode was removed.
001476  */
001477  int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
001478    if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
001479      return sqlite3VdbeChangeToNoop(p, p->nOp-1);
001480    }else{
001481      return 0;
001482    }
001483  }
001484  
001485  #ifdef SQLITE_DEBUG
001486  /*
001487  ** Generate an OP_ReleaseReg opcode to indicate that a range of
001488  ** registers, except any identified by mask, are no longer in use.
001489  */
001490  void sqlite3VdbeReleaseRegisters(
001491    Parse *pParse,       /* Parsing context */
001492    int iFirst,          /* Index of first register to be released */
001493    int N,               /* Number of registers to release */
001494    u32 mask,            /* Mask of registers to NOT release */
001495    int bUndefine        /* If true, mark registers as undefined */
001496  ){
001497    if( N==0 || OptimizationDisabled(pParse->db, SQLITE_ReleaseReg) ) return;
001498    assert( pParse->pVdbe );
001499    assert( iFirst>=1 );
001500    assert( iFirst+N-1<=pParse->nMem );
001501    if( N<=31 && mask!=0 ){
001502      while( N>0 && (mask&1)!=0 ){
001503        mask >>= 1;
001504        iFirst++;
001505        N--;
001506      }
001507      while( N>0 && N<=32 && (mask & MASKBIT32(N-1))!=0 ){
001508        mask &= ~MASKBIT32(N-1);
001509        N--;
001510      }
001511    }
001512    if( N>0 ){
001513      sqlite3VdbeAddOp3(pParse->pVdbe, OP_ReleaseReg, iFirst, N, *(int*)&mask);
001514      if( bUndefine ) sqlite3VdbeChangeP5(pParse->pVdbe, 1);
001515    }
001516  }
001517  #endif /* SQLITE_DEBUG */
001518  
001519  /*
001520  ** Change the value of the P4 operand for a specific instruction.
001521  ** This routine is useful when a large program is loaded from a
001522  ** static array using sqlite3VdbeAddOpList but we want to make a
001523  ** few minor changes to the program.
001524  **
001525  ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
001526  ** the string is made into memory obtained from sqlite3_malloc().
001527  ** A value of n==0 means copy bytes of zP4 up to and including the
001528  ** first null byte.  If n>0 then copy n+1 bytes of zP4.
001529  **
001530  ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
001531  ** to a string or structure that is guaranteed to exist for the lifetime of
001532  ** the Vdbe. In these cases we can just copy the pointer.
001533  **
001534  ** If addr<0 then change P4 on the most recently inserted instruction.
001535  */
001536  static void SQLITE_NOINLINE vdbeChangeP4Full(
001537    Vdbe *p,
001538    Op *pOp,
001539    const char *zP4,
001540    int n
001541  ){
001542    if( pOp->p4type ){
001543      assert( pOp->p4type > P4_FREE_IF_LE );
001544      pOp->p4type = 0;
001545      pOp->p4.p = 0;
001546    }
001547    if( n<0 ){
001548      sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
001549    }else{
001550      if( n==0 ) n = sqlite3Strlen30(zP4);
001551      pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
001552      pOp->p4type = P4_DYNAMIC;
001553    }
001554  }
001555  void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
001556    Op *pOp;
001557    sqlite3 *db;
001558    assert( p!=0 );
001559    db = p->db;
001560    assert( p->eVdbeState==VDBE_INIT_STATE );
001561    assert( p->aOp!=0 || db->mallocFailed );
001562    if( db->mallocFailed ){
001563      if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
001564      return;
001565    }
001566    assert( p->nOp>0 );
001567    assert( addr<p->nOp );
001568    if( addr<0 ){
001569      addr = p->nOp - 1;
001570    }
001571    pOp = &p->aOp[addr];
001572    if( n>=0 || pOp->p4type ){
001573      vdbeChangeP4Full(p, pOp, zP4, n);
001574      return;
001575    }
001576    if( n==P4_INT32 ){
001577      /* Note: this cast is safe, because the origin data point was an int
001578      ** that was cast to a (const char *). */
001579      pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
001580      pOp->p4type = P4_INT32;
001581    }else if( zP4!=0 ){
001582      assert( n<0 );
001583      pOp->p4.p = (void*)zP4;
001584      pOp->p4type = (signed char)n;
001585      if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
001586    }
001587  }
001588  
001589  /*
001590  ** Change the P4 operand of the most recently coded instruction
001591  ** to the value defined by the arguments.  This is a high-speed
001592  ** version of sqlite3VdbeChangeP4().
001593  **
001594  ** The P4 operand must not have been previously defined.  And the new
001595  ** P4 must not be P4_INT32.  Use sqlite3VdbeChangeP4() in either of
001596  ** those cases.
001597  */
001598  void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
001599    VdbeOp *pOp;
001600    assert( n!=P4_INT32 && n!=P4_VTAB );
001601    assert( n<=0 );
001602    if( p->db->mallocFailed ){
001603      freeP4(p->db, n, pP4);
001604    }else{
001605      assert( pP4!=0 || n==P4_DYNAMIC );
001606      assert( p->nOp>0 );
001607      pOp = &p->aOp[p->nOp-1];
001608      assert( pOp->p4type==P4_NOTUSED );
001609      pOp->p4type = n;
001610      pOp->p4.p = pP4;
001611    }
001612  }
001613  
001614  /*
001615  ** Set the P4 on the most recently added opcode to the KeyInfo for the
001616  ** index given.
001617  */
001618  void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
001619    Vdbe *v = pParse->pVdbe;
001620    KeyInfo *pKeyInfo;
001621    assert( v!=0 );
001622    assert( pIdx!=0 );
001623    pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
001624    if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
001625  }
001626  
001627  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
001628  /*
001629  ** Change the comment on the most recently coded instruction.  Or
001630  ** insert a No-op and add the comment to that new instruction.  This
001631  ** makes the code easier to read during debugging.  None of this happens
001632  ** in a production build.
001633  */
001634  static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
001635    assert( p->nOp>0 || p->aOp==0 );
001636    assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->pParse->nErr>0 );
001637    if( p->nOp ){
001638      assert( p->aOp );
001639      sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
001640      p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
001641    }
001642  }
001643  void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
001644    va_list ap;
001645    if( p ){
001646      va_start(ap, zFormat);
001647      vdbeVComment(p, zFormat, ap);
001648      va_end(ap);
001649    }
001650  }
001651  void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
001652    va_list ap;
001653    if( p ){
001654      sqlite3VdbeAddOp0(p, OP_Noop);
001655      va_start(ap, zFormat);
001656      vdbeVComment(p, zFormat, ap);
001657      va_end(ap);
001658    }
001659  }
001660  #endif  /* NDEBUG */
001661  
001662  #ifdef SQLITE_VDBE_COVERAGE
001663  /*
001664  ** Set the value if the iSrcLine field for the previously coded instruction.
001665  */
001666  void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
001667    sqlite3VdbeGetLastOp(v)->iSrcLine = iLine;
001668  }
001669  #endif /* SQLITE_VDBE_COVERAGE */
001670  
001671  /*
001672  ** Return the opcode for a given address.  The address must be non-negative.
001673  ** See sqlite3VdbeGetLastOp() to get the most recently added opcode.
001674  **
001675  ** If a memory allocation error has occurred prior to the calling of this
001676  ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
001677  ** is readable but not writable, though it is cast to a writable value.
001678  ** The return of a dummy opcode allows the call to continue functioning
001679  ** after an OOM fault without having to check to see if the return from
001680  ** this routine is a valid pointer.  But because the dummy.opcode is 0,
001681  ** dummy will never be written to.  This is verified by code inspection and
001682  ** by running with Valgrind.
001683  */
001684  VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
001685    /* C89 specifies that the constant "dummy" will be initialized to all
001686    ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
001687    static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
001688    assert( p->eVdbeState==VDBE_INIT_STATE );
001689    assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
001690    if( p->db->mallocFailed ){
001691      return (VdbeOp*)&dummy;
001692    }else{
001693      return &p->aOp[addr];
001694    }
001695  }
001696  
001697  /* Return the most recently added opcode
001698  */
001699  VdbeOp *sqlite3VdbeGetLastOp(Vdbe *p){
001700    return sqlite3VdbeGetOp(p, p->nOp - 1);
001701  }
001702  
001703  #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
001704  /*
001705  ** Return an integer value for one of the parameters to the opcode pOp
001706  ** determined by character c.
001707  */
001708  static int translateP(char c, const Op *pOp){
001709    if( c=='1' ) return pOp->p1;
001710    if( c=='2' ) return pOp->p2;
001711    if( c=='3' ) return pOp->p3;
001712    if( c=='4' ) return pOp->p4.i;
001713    return pOp->p5;
001714  }
001715  
001716  /*
001717  ** Compute a string for the "comment" field of a VDBE opcode listing.
001718  **
001719  ** The Synopsis: field in comments in the vdbe.c source file gets converted
001720  ** to an extra string that is appended to the sqlite3OpcodeName().  In the
001721  ** absence of other comments, this synopsis becomes the comment on the opcode.
001722  ** Some translation occurs:
001723  **
001724  **       "PX"      ->  "r[X]"
001725  **       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
001726  **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
001727  **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
001728  */
001729  char *sqlite3VdbeDisplayComment(
001730    sqlite3 *db,       /* Optional - Oom error reporting only */
001731    const Op *pOp,     /* The opcode to be commented */
001732    const char *zP4    /* Previously obtained value for P4 */
001733  ){
001734    const char *zOpName;
001735    const char *zSynopsis;
001736    int nOpName;
001737    int ii;
001738    char zAlt[50];
001739    StrAccum x;
001740  
001741    sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
001742    zOpName = sqlite3OpcodeName(pOp->opcode);
001743    nOpName = sqlite3Strlen30(zOpName);
001744    if( zOpName[nOpName+1] ){
001745      int seenCom = 0;
001746      char c;
001747      zSynopsis = zOpName + nOpName + 1;
001748      if( strncmp(zSynopsis,"IF ",3)==0 ){
001749        sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
001750        zSynopsis = zAlt;
001751      }
001752      for(ii=0; (c = zSynopsis[ii])!=0; ii++){
001753        if( c=='P' ){
001754          c = zSynopsis[++ii];
001755          if( c=='4' ){
001756            sqlite3_str_appendall(&x, zP4);
001757          }else if( c=='X' ){
001758            if( pOp->zComment && pOp->zComment[0] ){
001759              sqlite3_str_appendall(&x, pOp->zComment);
001760              seenCom = 1;
001761              break;
001762            }
001763          }else{
001764            int v1 = translateP(c, pOp);
001765            int v2;
001766            if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
001767              ii += 3;
001768              v2 = translateP(zSynopsis[ii], pOp);
001769              if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
001770                ii += 2;
001771                v2++;
001772              }
001773              if( v2<2 ){
001774                sqlite3_str_appendf(&x, "%d", v1);
001775              }else{
001776                sqlite3_str_appendf(&x, "%d..%d", v1, v1+v2-1);
001777              }
001778            }else if( strncmp(zSynopsis+ii+1, "@NP", 3)==0 ){
001779              sqlite3_context *pCtx = pOp->p4.pCtx;
001780              if( pOp->p4type!=P4_FUNCCTX || pCtx->argc==1 ){
001781                sqlite3_str_appendf(&x, "%d", v1);
001782              }else if( pCtx->argc>1 ){
001783                sqlite3_str_appendf(&x, "%d..%d", v1, v1+pCtx->argc-1);
001784              }else if( x.accError==0 ){
001785                assert( x.nChar>2 );
001786                x.nChar -= 2;
001787                ii++;
001788              }
001789              ii += 3;
001790            }else{
001791              sqlite3_str_appendf(&x, "%d", v1);
001792              if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
001793                ii += 4;
001794              }
001795            }
001796          }
001797        }else{
001798          sqlite3_str_appendchar(&x, 1, c);
001799        }
001800      }
001801      if( !seenCom && pOp->zComment ){
001802        sqlite3_str_appendf(&x, "; %s", pOp->zComment);
001803      }
001804    }else if( pOp->zComment ){
001805      sqlite3_str_appendall(&x, pOp->zComment);
001806    }
001807    if( (x.accError & SQLITE_NOMEM)!=0 && db!=0 ){
001808      sqlite3OomFault(db);
001809    }
001810    return sqlite3StrAccumFinish(&x);
001811  }
001812  #endif /* SQLITE_ENABLE_EXPLAIN_COMMENTS */
001813  
001814  #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
001815  /*
001816  ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
001817  ** that can be displayed in the P4 column of EXPLAIN output.
001818  */
001819  static void displayP4Expr(StrAccum *p, Expr *pExpr){
001820    const char *zOp = 0;
001821    switch( pExpr->op ){
001822      case TK_STRING:
001823        assert( !ExprHasProperty(pExpr, EP_IntValue) );
001824        sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
001825        break;
001826      case TK_INTEGER:
001827        sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
001828        break;
001829      case TK_NULL:
001830        sqlite3_str_appendf(p, "NULL");
001831        break;
001832      case TK_REGISTER: {
001833        sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
001834        break;
001835      }
001836      case TK_COLUMN: {
001837        if( pExpr->iColumn<0 ){
001838          sqlite3_str_appendf(p, "rowid");
001839        }else{
001840          sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
001841        }
001842        break;
001843      }
001844      case TK_LT:      zOp = "LT";      break;
001845      case TK_LE:      zOp = "LE";      break;
001846      case TK_GT:      zOp = "GT";      break;
001847      case TK_GE:      zOp = "GE";      break;
001848      case TK_NE:      zOp = "NE";      break;
001849      case TK_EQ:      zOp = "EQ";      break;
001850      case TK_IS:      zOp = "IS";      break;
001851      case TK_ISNOT:   zOp = "ISNOT";   break;
001852      case TK_AND:     zOp = "AND";     break;
001853      case TK_OR:      zOp = "OR";      break;
001854      case TK_PLUS:    zOp = "ADD";     break;
001855      case TK_STAR:    zOp = "MUL";     break;
001856      case TK_MINUS:   zOp = "SUB";     break;
001857      case TK_REM:     zOp = "REM";     break;
001858      case TK_BITAND:  zOp = "BITAND";  break;
001859      case TK_BITOR:   zOp = "BITOR";   break;
001860      case TK_SLASH:   zOp = "DIV";     break;
001861      case TK_LSHIFT:  zOp = "LSHIFT";  break;
001862      case TK_RSHIFT:  zOp = "RSHIFT";  break;
001863      case TK_CONCAT:  zOp = "CONCAT";  break;
001864      case TK_UMINUS:  zOp = "MINUS";   break;
001865      case TK_UPLUS:   zOp = "PLUS";    break;
001866      case TK_BITNOT:  zOp = "BITNOT";  break;
001867      case TK_NOT:     zOp = "NOT";     break;
001868      case TK_ISNULL:  zOp = "ISNULL";  break;
001869      case TK_NOTNULL: zOp = "NOTNULL"; break;
001870  
001871      default:
001872        sqlite3_str_appendf(p, "%s", "expr");
001873        break;
001874    }
001875  
001876    if( zOp ){
001877      sqlite3_str_appendf(p, "%s(", zOp);
001878      displayP4Expr(p, pExpr->pLeft);
001879      if( pExpr->pRight ){
001880        sqlite3_str_append(p, ",", 1);
001881        displayP4Expr(p, pExpr->pRight);
001882      }
001883      sqlite3_str_append(p, ")", 1);
001884    }
001885  }
001886  #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
001887  
001888  
001889  #if VDBE_DISPLAY_P4
001890  /*
001891  ** Compute a string that describes the P4 parameter for an opcode.
001892  ** Use zTemp for any required temporary buffer space.
001893  */
001894  char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){
001895    char *zP4 = 0;
001896    StrAccum x;
001897  
001898    sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
001899    switch( pOp->p4type ){
001900      case P4_KEYINFO: {
001901        int j;
001902        KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
001903        assert( pKeyInfo->aSortFlags!=0 );
001904        sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
001905        for(j=0; j<pKeyInfo->nKeyField; j++){
001906          CollSeq *pColl = pKeyInfo->aColl[j];
001907          const char *zColl = pColl ? pColl->zName : "";
001908          if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
001909          sqlite3_str_appendf(&x, ",%s%s%s",
001910                 (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "",
001911                 (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "",
001912                 zColl);
001913        }
001914        sqlite3_str_append(&x, ")", 1);
001915        break;
001916      }
001917  #ifdef SQLITE_ENABLE_CURSOR_HINTS
001918      case P4_EXPR: {
001919        displayP4Expr(&x, pOp->p4.pExpr);
001920        break;
001921      }
001922  #endif
001923      case P4_COLLSEQ: {
001924        static const char *const encnames[] = {"?", "8", "16LE", "16BE"};
001925        CollSeq *pColl = pOp->p4.pColl;
001926        assert( pColl->enc<4 );
001927        sqlite3_str_appendf(&x, "%.18s-%s", pColl->zName,
001928                            encnames[pColl->enc]);
001929        break;
001930      }
001931      case P4_FUNCDEF: {
001932        FuncDef *pDef = pOp->p4.pFunc;
001933        sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
001934        break;
001935      }
001936      case P4_FUNCCTX: {
001937        FuncDef *pDef = pOp->p4.pCtx->pFunc;
001938        sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
001939        break;
001940      }
001941      case P4_INT64: {
001942        sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
001943        break;
001944      }
001945      case P4_INT32: {
001946        sqlite3_str_appendf(&x, "%d", pOp->p4.i);
001947        break;
001948      }
001949      case P4_REAL: {
001950        sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
001951        break;
001952      }
001953      case P4_MEM: {
001954        Mem *pMem = pOp->p4.pMem;
001955        if( pMem->flags & MEM_Str ){
001956          zP4 = pMem->z;
001957        }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
001958          sqlite3_str_appendf(&x, "%lld", pMem->u.i);
001959        }else if( pMem->flags & MEM_Real ){
001960          sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
001961        }else if( pMem->flags & MEM_Null ){
001962          zP4 = "NULL";
001963        }else{
001964          assert( pMem->flags & MEM_Blob );
001965          zP4 = "(blob)";
001966        }
001967        break;
001968      }
001969  #ifndef SQLITE_OMIT_VIRTUALTABLE
001970      case P4_VTAB: {
001971        sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
001972        sqlite3_str_appendf(&x, "vtab:%p", pVtab);
001973        break;
001974      }
001975  #endif
001976      case P4_INTARRAY: {
001977        u32 i;
001978        u32 *ai = pOp->p4.ai;
001979        u32 n = ai[0];   /* The first element of an INTARRAY is always the
001980                         ** count of the number of elements to follow */
001981        for(i=1; i<=n; i++){
001982          sqlite3_str_appendf(&x, "%c%u", (i==1 ? '[' : ','), ai[i]);
001983        }
001984        sqlite3_str_append(&x, "]", 1);
001985        break;
001986      }
001987      case P4_SUBPROGRAM: {
001988        zP4 = "program";
001989        break;
001990      }
001991      case P4_TABLE: {
001992        zP4 = pOp->p4.pTab->zName;
001993        break;
001994      }
001995      default: {
001996        zP4 = pOp->p4.z;
001997      }
001998    }
001999    if( zP4 ) sqlite3_str_appendall(&x, zP4);
002000    if( (x.accError & SQLITE_NOMEM)!=0 ){
002001      sqlite3OomFault(db);
002002    }
002003    return sqlite3StrAccumFinish(&x);
002004  }
002005  #endif /* VDBE_DISPLAY_P4 */
002006  
002007  /*
002008  ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
002009  **
002010  ** The prepared statements need to know in advance the complete set of
002011  ** attached databases that will be use.  A mask of these databases
002012  ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
002013  ** p->btreeMask of databases that will require a lock.
002014  */
002015  void sqlite3VdbeUsesBtree(Vdbe *p, int i){
002016    assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
002017    assert( i<(int)sizeof(p->btreeMask)*8 );
002018    DbMaskSet(p->btreeMask, i);
002019    if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
002020      DbMaskSet(p->lockMask, i);
002021    }
002022  }
002023  
002024  #if !defined(SQLITE_OMIT_SHARED_CACHE)
002025  /*
002026  ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
002027  ** this routine obtains the mutex associated with each BtShared structure
002028  ** that may be accessed by the VM passed as an argument. In doing so it also
002029  ** sets the BtShared.db member of each of the BtShared structures, ensuring
002030  ** that the correct busy-handler callback is invoked if required.
002031  **
002032  ** If SQLite is not threadsafe but does support shared-cache mode, then
002033  ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
002034  ** of all of BtShared structures accessible via the database handle
002035  ** associated with the VM.
002036  **
002037  ** If SQLite is not threadsafe and does not support shared-cache mode, this
002038  ** function is a no-op.
002039  **
002040  ** The p->btreeMask field is a bitmask of all btrees that the prepared
002041  ** statement p will ever use.  Let N be the number of bits in p->btreeMask
002042  ** corresponding to btrees that use shared cache.  Then the runtime of
002043  ** this routine is N*N.  But as N is rarely more than 1, this should not
002044  ** be a problem.
002045  */
002046  void sqlite3VdbeEnter(Vdbe *p){
002047    int i;
002048    sqlite3 *db;
002049    Db *aDb;
002050    int nDb;
002051    if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
002052    db = p->db;
002053    aDb = db->aDb;
002054    nDb = db->nDb;
002055    for(i=0; i<nDb; i++){
002056      if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
002057        sqlite3BtreeEnter(aDb[i].pBt);
002058      }
002059    }
002060  }
002061  #endif
002062  
002063  #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
002064  /*
002065  ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
002066  */
002067  static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
002068    int i;
002069    sqlite3 *db;
002070    Db *aDb;
002071    int nDb;
002072    db = p->db;
002073    aDb = db->aDb;
002074    nDb = db->nDb;
002075    for(i=0; i<nDb; i++){
002076      if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
002077        sqlite3BtreeLeave(aDb[i].pBt);
002078      }
002079    }
002080  }
002081  void sqlite3VdbeLeave(Vdbe *p){
002082    if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
002083    vdbeLeave(p);
002084  }
002085  #endif
002086  
002087  #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
002088  /*
002089  ** Print a single opcode.  This routine is used for debugging only.
002090  */
002091  void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
002092    char *zP4;
002093    char *zCom;
002094    sqlite3 dummyDb;
002095    static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
002096    if( pOut==0 ) pOut = stdout;
002097    sqlite3BeginBenignMalloc();
002098    dummyDb.mallocFailed = 1;
002099    zP4 = sqlite3VdbeDisplayP4(&dummyDb, pOp);
002100  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
002101    zCom = sqlite3VdbeDisplayComment(0, pOp, zP4);
002102  #else
002103    zCom = 0;
002104  #endif
002105    /* NB:  The sqlite3OpcodeName() function is implemented by code created
002106    ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
002107    ** information from the vdbe.c source text */
002108    fprintf(pOut, zFormat1, pc,
002109        sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3,
002110        zP4 ? zP4 : "", pOp->p5,
002111        zCom ? zCom : ""
002112    );
002113    fflush(pOut);
002114    sqlite3_free(zP4);
002115    sqlite3_free(zCom);
002116    sqlite3EndBenignMalloc();
002117  }
002118  #endif
002119  
002120  /*
002121  ** Initialize an array of N Mem element.
002122  **
002123  ** This is a high-runner, so only those fields that really do need to
002124  ** be initialized are set.  The Mem structure is organized so that
002125  ** the fields that get initialized are nearby and hopefully on the same
002126  ** cache line.
002127  **
002128  **    Mem.flags = flags
002129  **    Mem.db = db
002130  **    Mem.szMalloc = 0
002131  **
002132  ** All other fields of Mem can safely remain uninitialized for now.  They
002133  ** will be initialized before use.
002134  */
002135  static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
002136    if( N>0 ){
002137      do{
002138        p->flags = flags;
002139        p->db = db;
002140        p->szMalloc = 0;
002141  #ifdef SQLITE_DEBUG
002142        p->pScopyFrom = 0;
002143  #endif
002144        p++;
002145      }while( (--N)>0 );
002146    }
002147  }
002148  
002149  /*
002150  ** Release auxiliary memory held in an array of N Mem elements.
002151  **
002152  ** After this routine returns, all Mem elements in the array will still
002153  ** be valid.  Those Mem elements that were not holding auxiliary resources
002154  ** will be unchanged.  Mem elements which had something freed will be
002155  ** set to MEM_Undefined.
002156  */
002157  static void releaseMemArray(Mem *p, int N){
002158    if( p && N ){
002159      Mem *pEnd = &p[N];
002160      sqlite3 *db = p->db;
002161      if( db->pnBytesFreed ){
002162        do{
002163          if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
002164        }while( (++p)<pEnd );
002165        return;
002166      }
002167      do{
002168        assert( (&p[1])==pEnd || p[0].db==p[1].db );
002169        assert( sqlite3VdbeCheckMemInvariants(p) );
002170  
002171        /* This block is really an inlined version of sqlite3VdbeMemRelease()
002172        ** that takes advantage of the fact that the memory cell value is
002173        ** being set to NULL after releasing any dynamic resources.
002174        **
002175        ** The justification for duplicating code is that according to
002176        ** callgrind, this causes a certain test case to hit the CPU 4.7
002177        ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
002178        ** sqlite3MemRelease() were called from here. With -O2, this jumps
002179        ** to 6.6 percent. The test case is inserting 1000 rows into a table
002180        ** with no indexes using a single prepared INSERT statement, bind()
002181        ** and reset(). Inserts are grouped into a transaction.
002182        */
002183        testcase( p->flags & MEM_Agg );
002184        testcase( p->flags & MEM_Dyn );
002185        if( p->flags&(MEM_Agg|MEM_Dyn) ){
002186          testcase( (p->flags & MEM_Dyn)!=0 && p->xDel==sqlite3VdbeFrameMemDel );
002187          sqlite3VdbeMemRelease(p);
002188          p->flags = MEM_Undefined;
002189        }else if( p->szMalloc ){
002190          sqlite3DbNNFreeNN(db, p->zMalloc);
002191          p->szMalloc = 0;
002192          p->flags = MEM_Undefined;
002193        }
002194  #ifdef SQLITE_DEBUG
002195        else{
002196          p->flags = MEM_Undefined;
002197        }
002198  #endif
002199      }while( (++p)<pEnd );
002200    }
002201  }
002202  
002203  #ifdef SQLITE_DEBUG
002204  /*
002205  ** Verify that pFrame is a valid VdbeFrame pointer.  Return true if it is
002206  ** and false if something is wrong.
002207  **
002208  ** This routine is intended for use inside of assert() statements only.
002209  */
002210  int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){
002211    if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
002212    return 1;
002213  }
002214  #endif
002215  
002216  
002217  /*
002218  ** This is a destructor on a Mem object (which is really an sqlite3_value)
002219  ** that deletes the Frame object that is attached to it as a blob.
002220  **
002221  ** This routine does not delete the Frame right away.  It merely adds the
002222  ** frame to a list of frames to be deleted when the Vdbe halts.
002223  */
002224  void sqlite3VdbeFrameMemDel(void *pArg){
002225    VdbeFrame *pFrame = (VdbeFrame*)pArg;
002226    assert( sqlite3VdbeFrameIsValid(pFrame) );
002227    pFrame->pParent = pFrame->v->pDelFrame;
002228    pFrame->v->pDelFrame = pFrame;
002229  }
002230  
002231  #if defined(SQLITE_ENABLE_BYTECODE_VTAB) || !defined(SQLITE_OMIT_EXPLAIN)
002232  /*
002233  ** Locate the next opcode to be displayed in EXPLAIN or EXPLAIN
002234  ** QUERY PLAN output.
002235  **
002236  ** Return SQLITE_ROW on success.  Return SQLITE_DONE if there are no
002237  ** more opcodes to be displayed.
002238  */
002239  int sqlite3VdbeNextOpcode(
002240    Vdbe *p,         /* The statement being explained */
002241    Mem *pSub,       /* Storage for keeping track of subprogram nesting */
002242    int eMode,       /* 0: normal.  1: EQP.  2:  TablesUsed */
002243    int *piPc,       /* IN/OUT: Current rowid.  Overwritten with next rowid */
002244    int *piAddr,     /* OUT: Write index into (*paOp)[] here */
002245    Op **paOp        /* OUT: Write the opcode array here */
002246  ){
002247    int nRow;                            /* Stop when row count reaches this */
002248    int nSub = 0;                        /* Number of sub-vdbes seen so far */
002249    SubProgram **apSub = 0;              /* Array of sub-vdbes */
002250    int i;                               /* Next instruction address */
002251    int rc = SQLITE_OK;                  /* Result code */
002252    Op *aOp = 0;                         /* Opcode array */
002253    int iPc;                             /* Rowid.  Copy of value in *piPc */
002254  
002255    /* When the number of output rows reaches nRow, that means the
002256    ** listing has finished and sqlite3_step() should return SQLITE_DONE.
002257    ** nRow is the sum of the number of rows in the main program, plus
002258    ** the sum of the number of rows in all trigger subprograms encountered
002259    ** so far.  The nRow value will increase as new trigger subprograms are
002260    ** encountered, but p->pc will eventually catch up to nRow.
002261    */
002262    nRow = p->nOp;
002263    if( pSub!=0 ){
002264      if( pSub->flags&MEM_Blob ){
002265        /* pSub is initiallly NULL.  It is initialized to a BLOB by
002266        ** the P4_SUBPROGRAM processing logic below */
002267        nSub = pSub->n/sizeof(Vdbe*);
002268        apSub = (SubProgram **)pSub->z;
002269      }
002270      for(i=0; i<nSub; i++){
002271        nRow += apSub[i]->nOp;
002272      }
002273    }
002274    iPc = *piPc;
002275    while(1){  /* Loop exits via break */
002276      i = iPc++;
002277      if( i>=nRow ){
002278        p->rc = SQLITE_OK;
002279        rc = SQLITE_DONE;
002280        break;
002281      }
002282      if( i<p->nOp ){
002283        /* The rowid is small enough that we are still in the
002284        ** main program. */
002285        aOp = p->aOp;
002286      }else{
002287        /* We are currently listing subprograms.  Figure out which one and
002288        ** pick up the appropriate opcode. */
002289        int j;
002290        i -= p->nOp;
002291        assert( apSub!=0 );
002292        assert( nSub>0 );
002293        for(j=0; i>=apSub[j]->nOp; j++){
002294          i -= apSub[j]->nOp;
002295          assert( i<apSub[j]->nOp || j+1<nSub );
002296        }
002297        aOp = apSub[j]->aOp;
002298      }
002299  
002300      /* When an OP_Program opcode is encounter (the only opcode that has
002301      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
002302      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
002303      ** has not already been seen.
002304      */
002305      if( pSub!=0 && aOp[i].p4type==P4_SUBPROGRAM ){
002306        int nByte = (nSub+1)*sizeof(SubProgram*);
002307        int j;
002308        for(j=0; j<nSub; j++){
002309          if( apSub[j]==aOp[i].p4.pProgram ) break;
002310        }
002311        if( j==nSub ){
002312          p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
002313          if( p->rc!=SQLITE_OK ){
002314            rc = SQLITE_ERROR;
002315            break;
002316          }
002317          apSub = (SubProgram **)pSub->z;
002318          apSub[nSub++] = aOp[i].p4.pProgram;
002319          MemSetTypeFlag(pSub, MEM_Blob);
002320          pSub->n = nSub*sizeof(SubProgram*);
002321          nRow += aOp[i].p4.pProgram->nOp;
002322        }
002323      }
002324      if( eMode==0 ) break;
002325  #ifdef SQLITE_ENABLE_BYTECODE_VTAB
002326      if( eMode==2 ){
002327        Op *pOp = aOp + i;
002328        if( pOp->opcode==OP_OpenRead ) break;
002329        if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;
002330        if( pOp->opcode==OP_ReopenIdx ) break;     
002331      }else
002332  #endif
002333      {
002334        assert( eMode==1 );
002335        if( aOp[i].opcode==OP_Explain ) break;
002336        if( aOp[i].opcode==OP_Init && iPc>1 ) break;
002337      }
002338    }
002339    *piPc = iPc;
002340    *piAddr = i;
002341    *paOp = aOp;
002342    return rc;
002343  }
002344  #endif /* SQLITE_ENABLE_BYTECODE_VTAB || !SQLITE_OMIT_EXPLAIN */
002345  
002346  
002347  /*
002348  ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
002349  ** allocated by the OP_Program opcode in sqlite3VdbeExec().
002350  */
002351  void sqlite3VdbeFrameDelete(VdbeFrame *p){
002352    int i;
002353    Mem *aMem = VdbeFrameMem(p);
002354    VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
002355    assert( sqlite3VdbeFrameIsValid(p) );
002356    for(i=0; i<p->nChildCsr; i++){
002357      if( apCsr[i] ) sqlite3VdbeFreeCursorNN(p->v, apCsr[i]);
002358    }
002359    releaseMemArray(aMem, p->nChildMem);
002360    sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
002361    sqlite3DbFree(p->v->db, p);
002362  }
002363  
002364  #ifndef SQLITE_OMIT_EXPLAIN
002365  /*
002366  ** Give a listing of the program in the virtual machine.
002367  **
002368  ** The interface is the same as sqlite3VdbeExec().  But instead of
002369  ** running the code, it invokes the callback once for each instruction.
002370  ** This feature is used to implement "EXPLAIN".
002371  **
002372  ** When p->explain==1, each instruction is listed.  When
002373  ** p->explain==2, only OP_Explain instructions are listed and these
002374  ** are shown in a different format.  p->explain==2 is used to implement
002375  ** EXPLAIN QUERY PLAN.
002376  ** 2018-04-24:  In p->explain==2 mode, the OP_Init opcodes of triggers
002377  ** are also shown, so that the boundaries between the main program and
002378  ** each trigger are clear.
002379  **
002380  ** When p->explain==1, first the main program is listed, then each of
002381  ** the trigger subprograms are listed one by one.
002382  */
002383  int sqlite3VdbeList(
002384    Vdbe *p                   /* The VDBE */
002385  ){
002386    Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
002387    sqlite3 *db = p->db;                 /* The database connection */
002388    int i;                               /* Loop counter */
002389    int rc = SQLITE_OK;                  /* Return code */
002390    Mem *pMem = &p->aMem[1];             /* First Mem of result set */
002391    int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
002392    Op *aOp;                             /* Array of opcodes */
002393    Op *pOp;                             /* Current opcode */
002394  
002395    assert( p->explain );
002396    assert( p->eVdbeState==VDBE_RUN_STATE );
002397    assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
002398  
002399    /* Even though this opcode does not use dynamic strings for
002400    ** the result, result columns may become dynamic if the user calls
002401    ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
002402    */
002403    releaseMemArray(pMem, 8);
002404  
002405    if( p->rc==SQLITE_NOMEM ){
002406      /* This happens if a malloc() inside a call to sqlite3_column_text() or
002407      ** sqlite3_column_text16() failed.  */
002408      sqlite3OomFault(db);
002409      return SQLITE_ERROR;
002410    }
002411  
002412    if( bListSubprogs ){
002413      /* The first 8 memory cells are used for the result set.  So we will
002414      ** commandeer the 9th cell to use as storage for an array of pointers
002415      ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
002416      ** cells.  */
002417      assert( p->nMem>9 );
002418      pSub = &p->aMem[9];
002419    }else{
002420      pSub = 0;
002421    }
002422  
002423    /* Figure out which opcode is next to display */
002424    rc = sqlite3VdbeNextOpcode(p, pSub, p->explain==2, &p->pc, &i, &aOp);
002425  
002426    if( rc==SQLITE_OK ){
002427      pOp = aOp + i;
002428      if( AtomicLoad(&db->u1.isInterrupted) ){
002429        p->rc = SQLITE_INTERRUPT;
002430        rc = SQLITE_ERROR;
002431        sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
002432      }else{
002433        char *zP4 = sqlite3VdbeDisplayP4(db, pOp);
002434        if( p->explain==2 ){
002435          sqlite3VdbeMemSetInt64(pMem, pOp->p1);
002436          sqlite3VdbeMemSetInt64(pMem+1, pOp->p2);
002437          sqlite3VdbeMemSetInt64(pMem+2, pOp->p3);
002438          sqlite3VdbeMemSetStr(pMem+3, zP4, -1, SQLITE_UTF8, sqlite3_free);
002439          assert( p->nResColumn==4 );
002440        }else{
002441          sqlite3VdbeMemSetInt64(pMem+0, i);
002442          sqlite3VdbeMemSetStr(pMem+1, (char*)sqlite3OpcodeName(pOp->opcode),
002443                               -1, SQLITE_UTF8, SQLITE_STATIC);
002444          sqlite3VdbeMemSetInt64(pMem+2, pOp->p1);
002445          sqlite3VdbeMemSetInt64(pMem+3, pOp->p2);
002446          sqlite3VdbeMemSetInt64(pMem+4, pOp->p3);
002447          /* pMem+5 for p4 is done last */
002448          sqlite3VdbeMemSetInt64(pMem+6, pOp->p5);
002449  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
002450          {
002451            char *zCom = sqlite3VdbeDisplayComment(db, pOp, zP4);
002452            sqlite3VdbeMemSetStr(pMem+7, zCom, -1, SQLITE_UTF8, sqlite3_free);
002453          }
002454  #else
002455          sqlite3VdbeMemSetNull(pMem+7);
002456  #endif
002457          sqlite3VdbeMemSetStr(pMem+5, zP4, -1, SQLITE_UTF8, sqlite3_free);
002458          assert( p->nResColumn==8 );
002459        }
002460        p->pResultRow = pMem;
002461        if( db->mallocFailed ){
002462          p->rc = SQLITE_NOMEM;
002463          rc = SQLITE_ERROR;
002464        }else{
002465          p->rc = SQLITE_OK;
002466          rc = SQLITE_ROW;
002467        }
002468      }
002469    }
002470    return rc;
002471  }
002472  #endif /* SQLITE_OMIT_EXPLAIN */
002473  
002474  #ifdef SQLITE_DEBUG
002475  /*
002476  ** Print the SQL that was used to generate a VDBE program.
002477  */
002478  void sqlite3VdbePrintSql(Vdbe *p){
002479    const char *z = 0;
002480    if( p->zSql ){
002481      z = p->zSql;
002482    }else if( p->nOp>=1 ){
002483      const VdbeOp *pOp = &p->aOp[0];
002484      if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
002485        z = pOp->p4.z;
002486        while( sqlite3Isspace(*z) ) z++;
002487      }
002488    }
002489    if( z ) printf("SQL: [%s]\n", z);
002490  }
002491  #endif
002492  
002493  #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
002494  /*
002495  ** Print an IOTRACE message showing SQL content.
002496  */
002497  void sqlite3VdbeIOTraceSql(Vdbe *p){
002498    int nOp = p->nOp;
002499    VdbeOp *pOp;
002500    if( sqlite3IoTrace==0 ) return;
002501    if( nOp<1 ) return;
002502    pOp = &p->aOp[0];
002503    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
002504      int i, j;
002505      char z[1000];
002506      sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
002507      for(i=0; sqlite3Isspace(z[i]); i++){}
002508      for(j=0; z[i]; i++){
002509        if( sqlite3Isspace(z[i]) ){
002510          if( z[i-1]!=' ' ){
002511            z[j++] = ' ';
002512          }
002513        }else{
002514          z[j++] = z[i];
002515        }
002516      }
002517      z[j] = 0;
002518      sqlite3IoTrace("SQL %s\n", z);
002519    }
002520  }
002521  #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
002522  
002523  /* An instance of this object describes bulk memory available for use
002524  ** by subcomponents of a prepared statement.  Space is allocated out
002525  ** of a ReusableSpace object by the allocSpace() routine below.
002526  */
002527  struct ReusableSpace {
002528    u8 *pSpace;            /* Available memory */
002529    sqlite3_int64 nFree;   /* Bytes of available memory */
002530    sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */
002531  };
002532  
002533  /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
002534  ** from the ReusableSpace object.  Return a pointer to the allocated
002535  ** memory on success.  If insufficient memory is available in the
002536  ** ReusableSpace object, increase the ReusableSpace.nNeeded
002537  ** value by the amount needed and return NULL.
002538  **
002539  ** If pBuf is not initially NULL, that means that the memory has already
002540  ** been allocated by a prior call to this routine, so just return a copy
002541  ** of pBuf and leave ReusableSpace unchanged.
002542  **
002543  ** This allocator is employed to repurpose unused slots at the end of the
002544  ** opcode array of prepared state for other memory needs of the prepared
002545  ** statement.
002546  */
002547  static void *allocSpace(
002548    struct ReusableSpace *p,  /* Bulk memory available for allocation */
002549    void *pBuf,               /* Pointer to a prior allocation */
002550    sqlite3_int64 nByte       /* Bytes of memory needed. */
002551  ){
002552    assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
002553    if( pBuf==0 ){
002554      nByte = ROUND8P(nByte);
002555      if( nByte <= p->nFree ){
002556        p->nFree -= nByte;
002557        pBuf = &p->pSpace[p->nFree];
002558      }else{
002559        p->nNeeded += nByte;
002560      }
002561    }
002562    assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
002563    return pBuf;
002564  }
002565  
002566  /*
002567  ** Rewind the VDBE back to the beginning in preparation for
002568  ** running it.
002569  */
002570  void sqlite3VdbeRewind(Vdbe *p){
002571  #if defined(SQLITE_DEBUG)
002572    int i;
002573  #endif
002574    assert( p!=0 );
002575    assert( p->eVdbeState==VDBE_INIT_STATE
002576         || p->eVdbeState==VDBE_READY_STATE
002577         || p->eVdbeState==VDBE_HALT_STATE );
002578  
002579    /* There should be at least one opcode.
002580    */
002581    assert( p->nOp>0 );
002582  
002583    p->eVdbeState = VDBE_READY_STATE;
002584  
002585  #ifdef SQLITE_DEBUG
002586    for(i=0; i<p->nMem; i++){
002587      assert( p->aMem[i].db==p->db );
002588    }
002589  #endif
002590    p->pc = -1;
002591    p->rc = SQLITE_OK;
002592    p->errorAction = OE_Abort;
002593    p->nChange = 0;
002594    p->cacheCtr = 1;
002595    p->minWriteFileFormat = 255;
002596    p->iStatement = 0;
002597    p->nFkConstraint = 0;
002598  #ifdef VDBE_PROFILE
002599    for(i=0; i<p->nOp; i++){
002600      p->aOp[i].nExec = 0;
002601      p->aOp[i].nCycle = 0;
002602    }
002603  #endif
002604  }
002605  
002606  /*
002607  ** Prepare a virtual machine for execution for the first time after
002608  ** creating the virtual machine.  This involves things such
002609  ** as allocating registers and initializing the program counter.
002610  ** After the VDBE has be prepped, it can be executed by one or more
002611  ** calls to sqlite3VdbeExec(). 
002612  **
002613  ** This function may be called exactly once on each virtual machine.
002614  ** After this routine is called the VM has been "packaged" and is ready
002615  ** to run.  After this routine is called, further calls to
002616  ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
002617  ** the Vdbe from the Parse object that helped generate it so that the
002618  ** the Vdbe becomes an independent entity and the Parse object can be
002619  ** destroyed.
002620  **
002621  ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
002622  ** to its initial state after it has been run.
002623  */
002624  void sqlite3VdbeMakeReady(
002625    Vdbe *p,                       /* The VDBE */
002626    Parse *pParse                  /* Parsing context */
002627  ){
002628    sqlite3 *db;                   /* The database connection */
002629    int nVar;                      /* Number of parameters */
002630    int nMem;                      /* Number of VM memory registers */
002631    int nCursor;                   /* Number of cursors required */
002632    int nArg;                      /* Number of arguments in subprograms */
002633    int n;                         /* Loop counter */
002634    struct ReusableSpace x;        /* Reusable bulk memory */
002635  
002636    assert( p!=0 );
002637    assert( p->nOp>0 );
002638    assert( pParse!=0 );
002639    assert( p->eVdbeState==VDBE_INIT_STATE );
002640    assert( pParse==p->pParse );
002641    p->pVList = pParse->pVList;
002642    pParse->pVList =  0;
002643    db = p->db;
002644    assert( db->mallocFailed==0 );
002645    nVar = pParse->nVar;
002646    nMem = pParse->nMem;
002647    nCursor = pParse->nTab;
002648    nArg = pParse->nMaxArg;
002649   
002650    /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
002651    ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
002652    ** space at the end of aMem[] for cursors 1 and greater.
002653    ** See also: allocateCursor().
002654    */
002655    nMem += nCursor;
002656    if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
002657  
002658    /* Figure out how much reusable memory is available at the end of the
002659    ** opcode array.  This extra memory will be reallocated for other elements
002660    ** of the prepared statement.
002661    */
002662    n = ROUND8P(sizeof(Op)*p->nOp);             /* Bytes of opcode memory used */
002663    x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
002664    assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
002665    x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */
002666    assert( x.nFree>=0 );
002667    assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
002668  
002669    resolveP2Values(p, &nArg);
002670    p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
002671    if( pParse->explain ){
002672      if( nMem<10 ) nMem = 10;
002673      p->explain = pParse->explain;
002674      p->nResColumn = 12 - 4*p->explain;
002675    }
002676    p->expired = 0;
002677  
002678    /* Memory for registers, parameters, cursor, etc, is allocated in one or two
002679    ** passes.  On the first pass, we try to reuse unused memory at the
002680    ** end of the opcode array.  If we are unable to satisfy all memory
002681    ** requirements by reusing the opcode array tail, then the second
002682    ** pass will fill in the remainder using a fresh memory allocation. 
002683    **
002684    ** This two-pass approach that reuses as much memory as possible from
002685    ** the leftover memory at the end of the opcode array.  This can significantly
002686    ** reduce the amount of memory held by a prepared statement.
002687    */
002688    x.nNeeded = 0;
002689    p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
002690    p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
002691    p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
002692    p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
002693    if( x.nNeeded ){
002694      x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
002695      x.nFree = x.nNeeded;
002696      if( !db->mallocFailed ){
002697        p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
002698        p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
002699        p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
002700        p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
002701      }
002702    }
002703  
002704    if( db->mallocFailed ){
002705      p->nVar = 0;
002706      p->nCursor = 0;
002707      p->nMem = 0;
002708    }else{
002709      p->nCursor = nCursor;
002710      p->nVar = (ynVar)nVar;
002711      initMemArray(p->aVar, nVar, db, MEM_Null);
002712      p->nMem = nMem;
002713      initMemArray(p->aMem, nMem, db, MEM_Undefined);
002714      memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
002715    }
002716    sqlite3VdbeRewind(p);
002717  }
002718  
002719  /*
002720  ** Close a VDBE cursor and release all the resources that cursor
002721  ** happens to hold.
002722  */
002723  void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
002724    if( pCx ) sqlite3VdbeFreeCursorNN(p,pCx);
002725  }
002726  static SQLITE_NOINLINE void freeCursorWithCache(Vdbe *p, VdbeCursor *pCx){
002727    VdbeTxtBlbCache *pCache = pCx->pCache;
002728    assert( pCx->colCache );
002729    pCx->colCache = 0;
002730    pCx->pCache = 0;
002731    if( pCache->pCValue ){
002732      sqlite3RCStrUnref(pCache->pCValue);
002733      pCache->pCValue = 0;
002734    }
002735    sqlite3DbFree(p->db, pCache);
002736    sqlite3VdbeFreeCursorNN(p, pCx);
002737  }
002738  void sqlite3VdbeFreeCursorNN(Vdbe *p, VdbeCursor *pCx){
002739    if( pCx->colCache ){
002740      freeCursorWithCache(p, pCx);
002741      return;
002742    }
002743    switch( pCx->eCurType ){
002744      case CURTYPE_SORTER: {
002745        sqlite3VdbeSorterClose(p->db, pCx);
002746        break;
002747      }
002748      case CURTYPE_BTREE: {
002749        assert( pCx->uc.pCursor!=0 );
002750        sqlite3BtreeCloseCursor(pCx->uc.pCursor);
002751        break;
002752      }
002753  #ifndef SQLITE_OMIT_VIRTUALTABLE
002754      case CURTYPE_VTAB: {
002755        sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
002756        const sqlite3_module *pModule = pVCur->pVtab->pModule;
002757        assert( pVCur->pVtab->nRef>0 );
002758        pVCur->pVtab->nRef--;
002759        pModule->xClose(pVCur);
002760        break;
002761      }
002762  #endif
002763    }
002764  }
002765  
002766  /*
002767  ** Close all cursors in the current frame.
002768  */
002769  static void closeCursorsInFrame(Vdbe *p){
002770    int i;
002771    for(i=0; i<p->nCursor; i++){
002772      VdbeCursor *pC = p->apCsr[i];
002773      if( pC ){
002774        sqlite3VdbeFreeCursorNN(p, pC);
002775        p->apCsr[i] = 0;
002776      }
002777    }
002778  }
002779  
002780  /*
002781  ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
002782  ** is used, for example, when a trigger sub-program is halted to restore
002783  ** control to the main program.
002784  */
002785  int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
002786    Vdbe *v = pFrame->v;
002787    closeCursorsInFrame(v);
002788    v->aOp = pFrame->aOp;
002789    v->nOp = pFrame->nOp;
002790    v->aMem = pFrame->aMem;
002791    v->nMem = pFrame->nMem;
002792    v->apCsr = pFrame->apCsr;
002793    v->nCursor = pFrame->nCursor;
002794    v->db->lastRowid = pFrame->lastRowid;
002795    v->nChange = pFrame->nChange;
002796    v->db->nChange = pFrame->nDbChange;
002797    sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
002798    v->pAuxData = pFrame->pAuxData;
002799    pFrame->pAuxData = 0;
002800    return pFrame->pc;
002801  }
002802  
002803  /*
002804  ** Close all cursors.
002805  **
002806  ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
002807  ** cell array. This is necessary as the memory cell array may contain
002808  ** pointers to VdbeFrame objects, which may in turn contain pointers to
002809  ** open cursors.
002810  */
002811  static void closeAllCursors(Vdbe *p){
002812    if( p->pFrame ){
002813      VdbeFrame *pFrame;
002814      for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
002815      sqlite3VdbeFrameRestore(pFrame);
002816      p->pFrame = 0;
002817      p->nFrame = 0;
002818    }
002819    assert( p->nFrame==0 );
002820    closeCursorsInFrame(p);
002821    releaseMemArray(p->aMem, p->nMem);
002822    while( p->pDelFrame ){
002823      VdbeFrame *pDel = p->pDelFrame;
002824      p->pDelFrame = pDel->pParent;
002825      sqlite3VdbeFrameDelete(pDel);
002826    }
002827  
002828    /* Delete any auxdata allocations made by the VM */
002829    if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
002830    assert( p->pAuxData==0 );
002831  }
002832  
002833  /*
002834  ** Set the number of result columns that will be returned by this SQL
002835  ** statement. This is now set at compile time, rather than during
002836  ** execution of the vdbe program so that sqlite3_column_count() can
002837  ** be called on an SQL statement before sqlite3_step().
002838  */
002839  void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
002840    int n;
002841    sqlite3 *db = p->db;
002842  
002843    if( p->nResAlloc ){
002844      releaseMemArray(p->aColName, p->nResAlloc*COLNAME_N);
002845      sqlite3DbFree(db, p->aColName);
002846    }
002847    n = nResColumn*COLNAME_N;
002848    p->nResColumn = p->nResAlloc = (u16)nResColumn;
002849    p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
002850    if( p->aColName==0 ) return;
002851    initMemArray(p->aColName, n, db, MEM_Null);
002852  }
002853  
002854  /*
002855  ** Set the name of the idx'th column to be returned by the SQL statement.
002856  ** zName must be a pointer to a nul terminated string.
002857  **
002858  ** This call must be made after a call to sqlite3VdbeSetNumCols().
002859  **
002860  ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
002861  ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
002862  ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
002863  */
002864  int sqlite3VdbeSetColName(
002865    Vdbe *p,                         /* Vdbe being configured */
002866    int idx,                         /* Index of column zName applies to */
002867    int var,                         /* One of the COLNAME_* constants */
002868    const char *zName,               /* Pointer to buffer containing name */
002869    void (*xDel)(void*)              /* Memory management strategy for zName */
002870  ){
002871    int rc;
002872    Mem *pColName;
002873    assert( idx<p->nResAlloc );
002874    assert( var<COLNAME_N );
002875    if( p->db->mallocFailed ){
002876      assert( !zName || xDel!=SQLITE_DYNAMIC );
002877      return SQLITE_NOMEM_BKPT;
002878    }
002879    assert( p->aColName!=0 );
002880    pColName = &(p->aColName[idx+var*p->nResAlloc]);
002881    rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
002882    assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
002883    return rc;
002884  }
002885  
002886  /*
002887  ** A read or write transaction may or may not be active on database handle
002888  ** db. If a transaction is active, commit it. If there is a
002889  ** write-transaction spanning more than one database file, this routine
002890  ** takes care of the super-journal trickery.
002891  */
002892  static int vdbeCommit(sqlite3 *db, Vdbe *p){
002893    int i;
002894    int nTrans = 0;  /* Number of databases with an active write-transaction
002895                     ** that are candidates for a two-phase commit using a
002896                     ** super-journal */
002897    int rc = SQLITE_OK;
002898    int needXcommit = 0;
002899  
002900  #ifdef SQLITE_OMIT_VIRTUALTABLE
002901    /* With this option, sqlite3VtabSync() is defined to be simply
002902    ** SQLITE_OK so p is not used.
002903    */
002904    UNUSED_PARAMETER(p);
002905  #endif
002906  
002907    /* Before doing anything else, call the xSync() callback for any
002908    ** virtual module tables written in this transaction. This has to
002909    ** be done before determining whether a super-journal file is
002910    ** required, as an xSync() callback may add an attached database
002911    ** to the transaction.
002912    */
002913    rc = sqlite3VtabSync(db, p);
002914  
002915    /* This loop determines (a) if the commit hook should be invoked and
002916    ** (b) how many database files have open write transactions, not
002917    ** including the temp database. (b) is important because if more than
002918    ** one database file has an open write transaction, a super-journal
002919    ** file is required for an atomic commit.
002920    */
002921    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
002922      Btree *pBt = db->aDb[i].pBt;
002923      if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
002924        /* Whether or not a database might need a super-journal depends upon
002925        ** its journal mode (among other things).  This matrix determines which
002926        ** journal modes use a super-journal and which do not */
002927        static const u8 aMJNeeded[] = {
002928          /* DELETE   */  1,
002929          /* PERSIST   */ 1,
002930          /* OFF       */ 0,
002931          /* TRUNCATE  */ 1,
002932          /* MEMORY    */ 0,
002933          /* WAL       */ 0
002934        };
002935        Pager *pPager;   /* Pager associated with pBt */
002936        needXcommit = 1;
002937        sqlite3BtreeEnter(pBt);
002938        pPager = sqlite3BtreePager(pBt);
002939        if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
002940         && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
002941         && sqlite3PagerIsMemdb(pPager)==0
002942        ){
002943          assert( i!=1 );
002944          nTrans++;
002945        }
002946        rc = sqlite3PagerExclusiveLock(pPager);
002947        sqlite3BtreeLeave(pBt);
002948      }
002949    }
002950    if( rc!=SQLITE_OK ){
002951      return rc;
002952    }
002953  
002954    /* If there are any write-transactions at all, invoke the commit hook */
002955    if( needXcommit && db->xCommitCallback ){
002956      rc = db->xCommitCallback(db->pCommitArg);
002957      if( rc ){
002958        return SQLITE_CONSTRAINT_COMMITHOOK;
002959      }
002960    }
002961  
002962    /* The simple case - no more than one database file (not counting the
002963    ** TEMP database) has a transaction active.   There is no need for the
002964    ** super-journal.
002965    **
002966    ** If the return value of sqlite3BtreeGetFilename() is a zero length
002967    ** string, it means the main database is :memory: or a temp file.  In
002968    ** that case we do not support atomic multi-file commits, so use the
002969    ** simple case then too.
002970    */
002971    if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
002972     || nTrans<=1
002973    ){
002974      for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
002975        Btree *pBt = db->aDb[i].pBt;
002976        if( pBt ){
002977          rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
002978        }
002979      }
002980  
002981      /* Do the commit only if all databases successfully complete phase 1.
002982      ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
002983      ** IO error while deleting or truncating a journal file. It is unlikely,
002984      ** but could happen. In this case abandon processing and return the error.
002985      */
002986      for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
002987        Btree *pBt = db->aDb[i].pBt;
002988        if( pBt ){
002989          rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
002990        }
002991      }
002992      if( rc==SQLITE_OK ){
002993        sqlite3VtabCommit(db);
002994      }
002995    }
002996  
002997    /* The complex case - There is a multi-file write-transaction active.
002998    ** This requires a super-journal file to ensure the transaction is
002999    ** committed atomically.
003000    */
003001  #ifndef SQLITE_OMIT_DISKIO
003002    else{
003003      sqlite3_vfs *pVfs = db->pVfs;
003004      char *zSuper = 0;   /* File-name for the super-journal */
003005      char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
003006      sqlite3_file *pSuperJrnl = 0;
003007      i64 offset = 0;
003008      int res;
003009      int retryCount = 0;
003010      int nMainFile;
003011  
003012      /* Select a super-journal file name */
003013      nMainFile = sqlite3Strlen30(zMainFile);
003014      zSuper = sqlite3MPrintf(db, "%.4c%s%.16c", 0,zMainFile,0);
003015      if( zSuper==0 ) return SQLITE_NOMEM_BKPT;
003016      zSuper += 4;
003017      do {
003018        u32 iRandom;
003019        if( retryCount ){
003020          if( retryCount>100 ){
003021            sqlite3_log(SQLITE_FULL, "MJ delete: %s", zSuper);
003022            sqlite3OsDelete(pVfs, zSuper, 0);
003023            break;
003024          }else if( retryCount==1 ){
003025            sqlite3_log(SQLITE_FULL, "MJ collide: %s", zSuper);
003026          }
003027        }
003028        retryCount++;
003029        sqlite3_randomness(sizeof(iRandom), &iRandom);
003030        sqlite3_snprintf(13, &zSuper[nMainFile], "-mj%06X9%02X",
003031                                 (iRandom>>8)&0xffffff, iRandom&0xff);
003032        /* The antipenultimate character of the super-journal name must
003033        ** be "9" to avoid name collisions when using 8+3 filenames. */
003034        assert( zSuper[sqlite3Strlen30(zSuper)-3]=='9' );
003035        sqlite3FileSuffix3(zMainFile, zSuper);
003036        rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
003037      }while( rc==SQLITE_OK && res );
003038      if( rc==SQLITE_OK ){
003039        /* Open the super-journal. */
003040        rc = sqlite3OsOpenMalloc(pVfs, zSuper, &pSuperJrnl,
003041            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
003042            SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_SUPER_JOURNAL, 0
003043        );
003044      }
003045      if( rc!=SQLITE_OK ){
003046        sqlite3DbFree(db, zSuper-4);
003047        return rc;
003048      }
003049  
003050      /* Write the name of each database file in the transaction into the new
003051      ** super-journal file. If an error occurs at this point close
003052      ** and delete the super-journal file. All the individual journal files
003053      ** still have 'null' as the super-journal pointer, so they will roll
003054      ** back independently if a failure occurs.
003055      */
003056      for(i=0; i<db->nDb; i++){
003057        Btree *pBt = db->aDb[i].pBt;
003058        if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
003059          char const *zFile = sqlite3BtreeGetJournalname(pBt);
003060          if( zFile==0 ){
003061            continue;  /* Ignore TEMP and :memory: databases */
003062          }
003063          assert( zFile[0]!=0 );
003064          rc = sqlite3OsWrite(pSuperJrnl, zFile, sqlite3Strlen30(zFile)+1,offset);
003065          offset += sqlite3Strlen30(zFile)+1;
003066          if( rc!=SQLITE_OK ){
003067            sqlite3OsCloseFree(pSuperJrnl);
003068            sqlite3OsDelete(pVfs, zSuper, 0);
003069            sqlite3DbFree(db, zSuper-4);
003070            return rc;
003071          }
003072        }
003073      }
003074  
003075      /* Sync the super-journal file. If the IOCAP_SEQUENTIAL device
003076      ** flag is set this is not required.
003077      */
003078      if( 0==(sqlite3OsDeviceCharacteristics(pSuperJrnl)&SQLITE_IOCAP_SEQUENTIAL)
003079       && SQLITE_OK!=(rc = sqlite3OsSync(pSuperJrnl, SQLITE_SYNC_NORMAL))
003080      ){
003081        sqlite3OsCloseFree(pSuperJrnl);
003082        sqlite3OsDelete(pVfs, zSuper, 0);
003083        sqlite3DbFree(db, zSuper-4);
003084        return rc;
003085      }
003086  
003087      /* Sync all the db files involved in the transaction. The same call
003088      ** sets the super-journal pointer in each individual journal. If
003089      ** an error occurs here, do not delete the super-journal file.
003090      **
003091      ** If the error occurs during the first call to
003092      ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
003093      ** super-journal file will be orphaned. But we cannot delete it,
003094      ** in case the super-journal file name was written into the journal
003095      ** file before the failure occurred.
003096      */
003097      for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
003098        Btree *pBt = db->aDb[i].pBt;
003099        if( pBt ){
003100          rc = sqlite3BtreeCommitPhaseOne(pBt, zSuper);
003101        }
003102      }
003103      sqlite3OsCloseFree(pSuperJrnl);
003104      assert( rc!=SQLITE_BUSY );
003105      if( rc!=SQLITE_OK ){
003106        sqlite3DbFree(db, zSuper-4);
003107        return rc;
003108      }
003109  
003110      /* Delete the super-journal file. This commits the transaction. After
003111      ** doing this the directory is synced again before any individual
003112      ** transaction files are deleted.
003113      */
003114      rc = sqlite3OsDelete(pVfs, zSuper, 1);
003115      sqlite3DbFree(db, zSuper-4);
003116      zSuper = 0;
003117      if( rc ){
003118        return rc;
003119      }
003120  
003121      /* All files and directories have already been synced, so the following
003122      ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
003123      ** deleting or truncating journals. If something goes wrong while
003124      ** this is happening we don't really care. The integrity of the
003125      ** transaction is already guaranteed, but some stray 'cold' journals
003126      ** may be lying around. Returning an error code won't help matters.
003127      */
003128      disable_simulated_io_errors();
003129      sqlite3BeginBenignMalloc();
003130      for(i=0; i<db->nDb; i++){
003131        Btree *pBt = db->aDb[i].pBt;
003132        if( pBt ){
003133          sqlite3BtreeCommitPhaseTwo(pBt, 1);
003134        }
003135      }
003136      sqlite3EndBenignMalloc();
003137      enable_simulated_io_errors();
003138  
003139      sqlite3VtabCommit(db);
003140    }
003141  #endif
003142  
003143    return rc;
003144  }
003145  
003146  /*
003147  ** This routine checks that the sqlite3.nVdbeActive count variable
003148  ** matches the number of vdbe's in the list sqlite3.pVdbe that are
003149  ** currently active. An assertion fails if the two counts do not match.
003150  ** This is an internal self-check only - it is not an essential processing
003151  ** step.
003152  **
003153  ** This is a no-op if NDEBUG is defined.
003154  */
003155  #ifndef NDEBUG
003156  static void checkActiveVdbeCnt(sqlite3 *db){
003157    Vdbe *p;
003158    int cnt = 0;
003159    int nWrite = 0;
003160    int nRead = 0;
003161    p = db->pVdbe;
003162    while( p ){
003163      if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
003164        cnt++;
003165        if( p->readOnly==0 ) nWrite++;
003166        if( p->bIsReader ) nRead++;
003167      }
003168      p = p->pVNext;
003169    }
003170    assert( cnt==db->nVdbeActive );
003171    assert( nWrite==db->nVdbeWrite );
003172    assert( nRead==db->nVdbeRead );
003173  }
003174  #else
003175  #define checkActiveVdbeCnt(x)
003176  #endif
003177  
003178  /*
003179  ** If the Vdbe passed as the first argument opened a statement-transaction,
003180  ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
003181  ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
003182  ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
003183  ** statement transaction is committed.
003184  **
003185  ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
003186  ** Otherwise SQLITE_OK.
003187  */
003188  static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
003189    sqlite3 *const db = p->db;
003190    int rc = SQLITE_OK;
003191    int i;
003192    const int iSavepoint = p->iStatement-1;
003193  
003194    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
003195    assert( db->nStatement>0 );
003196    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
003197  
003198    for(i=0; i<db->nDb; i++){
003199      int rc2 = SQLITE_OK;
003200      Btree *pBt = db->aDb[i].pBt;
003201      if( pBt ){
003202        if( eOp==SAVEPOINT_ROLLBACK ){
003203          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
003204        }
003205        if( rc2==SQLITE_OK ){
003206          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
003207        }
003208        if( rc==SQLITE_OK ){
003209          rc = rc2;
003210        }
003211      }
003212    }
003213    db->nStatement--;
003214    p->iStatement = 0;
003215  
003216    if( rc==SQLITE_OK ){
003217      if( eOp==SAVEPOINT_ROLLBACK ){
003218        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
003219      }
003220      if( rc==SQLITE_OK ){
003221        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
003222      }
003223    }
003224  
003225    /* If the statement transaction is being rolled back, also restore the
003226    ** database handles deferred constraint counter to the value it had when
003227    ** the statement transaction was opened.  */
003228    if( eOp==SAVEPOINT_ROLLBACK ){
003229      db->nDeferredCons = p->nStmtDefCons;
003230      db->nDeferredImmCons = p->nStmtDefImmCons;
003231    }
003232    return rc;
003233  }
003234  int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
003235    if( p->db->nStatement && p->iStatement ){
003236      return vdbeCloseStatement(p, eOp);
003237    }
003238    return SQLITE_OK;
003239  }
003240  
003241  
003242  /*
003243  ** This function is called when a transaction opened by the database
003244  ** handle associated with the VM passed as an argument is about to be
003245  ** committed. If there are outstanding deferred foreign key constraint
003246  ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
003247  **
003248  ** If there are outstanding FK violations and this function returns
003249  ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
003250  ** and write an error message to it. Then return SQLITE_ERROR.
003251  */
003252  #ifndef SQLITE_OMIT_FOREIGN_KEY
003253  int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
003254    sqlite3 *db = p->db;
003255    if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
003256     || (!deferred && p->nFkConstraint>0)
003257    ){
003258      p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
003259      p->errorAction = OE_Abort;
003260      sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
003261      if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ) return SQLITE_ERROR;
003262      return SQLITE_CONSTRAINT_FOREIGNKEY;
003263    }
003264    return SQLITE_OK;
003265  }
003266  #endif
003267  
003268  /*
003269  ** This routine is called the when a VDBE tries to halt.  If the VDBE
003270  ** has made changes and is in autocommit mode, then commit those
003271  ** changes.  If a rollback is needed, then do the rollback.
003272  **
003273  ** This routine is the only way to move the sqlite3eOpenState of a VM from
003274  ** SQLITE_STATE_RUN to SQLITE_STATE_HALT.  It is harmless to
003275  ** call this on a VM that is in the SQLITE_STATE_HALT state.
003276  **
003277  ** Return an error code.  If the commit could not complete because of
003278  ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
003279  ** means the close did not happen and needs to be repeated.
003280  */
003281  int sqlite3VdbeHalt(Vdbe *p){
003282    int rc;                         /* Used to store transient return codes */
003283    sqlite3 *db = p->db;
003284  
003285    /* This function contains the logic that determines if a statement or
003286    ** transaction will be committed or rolled back as a result of the
003287    ** execution of this virtual machine.
003288    **
003289    ** If any of the following errors occur:
003290    **
003291    **     SQLITE_NOMEM
003292    **     SQLITE_IOERR
003293    **     SQLITE_FULL
003294    **     SQLITE_INTERRUPT
003295    **
003296    ** Then the internal cache might have been left in an inconsistent
003297    ** state.  We need to rollback the statement transaction, if there is
003298    ** one, or the complete transaction if there is no statement transaction.
003299    */
003300  
003301    assert( p->eVdbeState==VDBE_RUN_STATE );
003302    if( db->mallocFailed ){
003303      p->rc = SQLITE_NOMEM_BKPT;
003304    }
003305    closeAllCursors(p);
003306    checkActiveVdbeCnt(db);
003307  
003308    /* No commit or rollback needed if the program never started or if the
003309    ** SQL statement does not read or write a database file.  */
003310    if( p->bIsReader ){
003311      int mrc;   /* Primary error code from p->rc */
003312      int eStatementOp = 0;
003313      int isSpecialError;            /* Set to true if a 'special' error */
003314  
003315      /* Lock all btrees used by the statement */
003316      sqlite3VdbeEnter(p);
003317  
003318      /* Check for one of the special errors */
003319      if( p->rc ){
003320        mrc = p->rc & 0xff;
003321        isSpecialError = mrc==SQLITE_NOMEM
003322                      || mrc==SQLITE_IOERR
003323                      || mrc==SQLITE_INTERRUPT
003324                      || mrc==SQLITE_FULL;
003325      }else{
003326        mrc = isSpecialError = 0;
003327      }
003328      if( isSpecialError ){
003329        /* If the query was read-only and the error code is SQLITE_INTERRUPT,
003330        ** no rollback is necessary. Otherwise, at least a savepoint
003331        ** transaction must be rolled back to restore the database to a
003332        ** consistent state.
003333        **
003334        ** Even if the statement is read-only, it is important to perform
003335        ** a statement or transaction rollback operation. If the error
003336        ** occurred while writing to the journal, sub-journal or database
003337        ** file as part of an effort to free up cache space (see function
003338        ** pagerStress() in pager.c), the rollback is required to restore
003339        ** the pager to a consistent state.
003340        */
003341        if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
003342          if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
003343            eStatementOp = SAVEPOINT_ROLLBACK;
003344          }else{
003345            /* We are forced to roll back the active transaction. Before doing
003346            ** so, abort any other statements this handle currently has active.
003347            */
003348            sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
003349            sqlite3CloseSavepoints(db);
003350            db->autoCommit = 1;
003351            p->nChange = 0;
003352          }
003353        }
003354      }
003355  
003356      /* Check for immediate foreign key violations. */
003357      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
003358        (void)sqlite3VdbeCheckFk(p, 0);
003359      }
003360  
003361      /* If the auto-commit flag is set and this is the only active writer
003362      ** VM, then we do either a commit or rollback of the current transaction.
003363      **
003364      ** Note: This block also runs if one of the special errors handled
003365      ** above has occurred.
003366      */
003367      if( !sqlite3VtabInSync(db)
003368       && db->autoCommit
003369       && db->nVdbeWrite==(p->readOnly==0)
003370      ){
003371        if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
003372          rc = sqlite3VdbeCheckFk(p, 1);
003373          if( rc!=SQLITE_OK ){
003374            if( NEVER(p->readOnly) ){
003375              sqlite3VdbeLeave(p);
003376              return SQLITE_ERROR;
003377            }
003378            rc = SQLITE_CONSTRAINT_FOREIGNKEY;
003379          }else if( db->flags & SQLITE_CorruptRdOnly ){
003380            rc = SQLITE_CORRUPT;
003381            db->flags &= ~SQLITE_CorruptRdOnly;
003382          }else{
003383            /* The auto-commit flag is true, the vdbe program was successful
003384            ** or hit an 'OR FAIL' constraint and there are no deferred foreign
003385            ** key constraints to hold up the transaction. This means a commit
003386            ** is required. */
003387            rc = vdbeCommit(db, p);
003388          }
003389          if( rc==SQLITE_BUSY && p->readOnly ){
003390            sqlite3VdbeLeave(p);
003391            return SQLITE_BUSY;
003392          }else if( rc!=SQLITE_OK ){
003393            sqlite3SystemError(db, rc);
003394            p->rc = rc;
003395            sqlite3RollbackAll(db, SQLITE_OK);
003396            p->nChange = 0;
003397          }else{
003398            db->nDeferredCons = 0;
003399            db->nDeferredImmCons = 0;
003400            db->flags &= ~(u64)SQLITE_DeferFKs;
003401            sqlite3CommitInternalChanges(db);
003402          }
003403        }else if( p->rc==SQLITE_SCHEMA && db->nVdbeActive>1 ){
003404          p->nChange = 0;
003405        }else{
003406          sqlite3RollbackAll(db, SQLITE_OK);
003407          p->nChange = 0;
003408        }
003409        db->nStatement = 0;
003410      }else if( eStatementOp==0 ){
003411        if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
003412          eStatementOp = SAVEPOINT_RELEASE;
003413        }else if( p->errorAction==OE_Abort ){
003414          eStatementOp = SAVEPOINT_ROLLBACK;
003415        }else{
003416          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
003417          sqlite3CloseSavepoints(db);
003418          db->autoCommit = 1;
003419          p->nChange = 0;
003420        }
003421      }
003422   
003423      /* If eStatementOp is non-zero, then a statement transaction needs to
003424      ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
003425      ** do so. If this operation returns an error, and the current statement
003426      ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
003427      ** current statement error code.
003428      */
003429      if( eStatementOp ){
003430        rc = sqlite3VdbeCloseStatement(p, eStatementOp);
003431        if( rc ){
003432          if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
003433            p->rc = rc;
003434            sqlite3DbFree(db, p->zErrMsg);
003435            p->zErrMsg = 0;
003436          }
003437          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
003438          sqlite3CloseSavepoints(db);
003439          db->autoCommit = 1;
003440          p->nChange = 0;
003441        }
003442      }
003443   
003444      /* If this was an INSERT, UPDATE or DELETE and no statement transaction
003445      ** has been rolled back, update the database connection change-counter.
003446      */
003447      if( p->changeCntOn ){
003448        if( eStatementOp!=SAVEPOINT_ROLLBACK ){
003449          sqlite3VdbeSetChanges(db, p->nChange);
003450        }else{
003451          sqlite3VdbeSetChanges(db, 0);
003452        }
003453        p->nChange = 0;
003454      }
003455  
003456      /* Release the locks */
003457      sqlite3VdbeLeave(p);
003458    }
003459  
003460    /* We have successfully halted and closed the VM.  Record this fact. */
003461    db->nVdbeActive--;
003462    if( !p->readOnly ) db->nVdbeWrite--;
003463    if( p->bIsReader ) db->nVdbeRead--;
003464    assert( db->nVdbeActive>=db->nVdbeRead );
003465    assert( db->nVdbeRead>=db->nVdbeWrite );
003466    assert( db->nVdbeWrite>=0 );
003467    p->eVdbeState = VDBE_HALT_STATE;
003468    checkActiveVdbeCnt(db);
003469    if( db->mallocFailed ){
003470      p->rc = SQLITE_NOMEM_BKPT;
003471    }
003472  
003473    /* If the auto-commit flag is set to true, then any locks that were held
003474    ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
003475    ** to invoke any required unlock-notify callbacks.
003476    */
003477    if( db->autoCommit ){
003478      sqlite3ConnectionUnlocked(db);
003479    }
003480  
003481    assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
003482    return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
003483  }
003484  
003485  
003486  /*
003487  ** Each VDBE holds the result of the most recent sqlite3_step() call
003488  ** in p->rc.  This routine sets that result back to SQLITE_OK.
003489  */
003490  void sqlite3VdbeResetStepResult(Vdbe *p){
003491    p->rc = SQLITE_OK;
003492  }
003493  
003494  /*
003495  ** Copy the error code and error message belonging to the VDBE passed
003496  ** as the first argument to its database handle (so that they will be
003497  ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
003498  **
003499  ** This function does not clear the VDBE error code or message, just
003500  ** copies them to the database handle.
003501  */
003502  int sqlite3VdbeTransferError(Vdbe *p){
003503    sqlite3 *db = p->db;
003504    int rc = p->rc;
003505    if( p->zErrMsg ){
003506      db->bBenignMalloc++;
003507      sqlite3BeginBenignMalloc();
003508      if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
003509      sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
003510      sqlite3EndBenignMalloc();
003511      db->bBenignMalloc--;
003512    }else if( db->pErr ){
003513      sqlite3ValueSetNull(db->pErr);
003514    }
003515    db->errCode = rc;
003516    db->errByteOffset = -1;
003517    return rc;
003518  }
003519  
003520  #ifdef SQLITE_ENABLE_SQLLOG
003521  /*
003522  ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
003523  ** invoke it.
003524  */
003525  static void vdbeInvokeSqllog(Vdbe *v){
003526    if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
003527      char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
003528      assert( v->db->init.busy==0 );
003529      if( zExpanded ){
003530        sqlite3GlobalConfig.xSqllog(
003531            sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
003532        );
003533        sqlite3DbFree(v->db, zExpanded);
003534      }
003535    }
003536  }
003537  #else
003538  # define vdbeInvokeSqllog(x)
003539  #endif
003540  
003541  /*
003542  ** Clean up a VDBE after execution but do not delete the VDBE just yet.
003543  ** Write any error messages into *pzErrMsg.  Return the result code.
003544  **
003545  ** After this routine is run, the VDBE should be ready to be executed
003546  ** again.
003547  **
003548  ** To look at it another way, this routine resets the state of the
003549  ** virtual machine from VDBE_RUN_STATE or VDBE_HALT_STATE back to
003550  ** VDBE_READY_STATE.
003551  */
003552  int sqlite3VdbeReset(Vdbe *p){
003553  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
003554    int i;
003555  #endif
003556  
003557    sqlite3 *db;
003558    db = p->db;
003559  
003560    /* If the VM did not run to completion or if it encountered an
003561    ** error, then it might not have been halted properly.  So halt
003562    ** it now.
003563    */
003564    if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
003565  
003566    /* If the VDBE has been run even partially, then transfer the error code
003567    ** and error message from the VDBE into the main database structure.  But
003568    ** if the VDBE has just been set to run but has not actually executed any
003569    ** instructions yet, leave the main database error information unchanged.
003570    */
003571    if( p->pc>=0 ){
003572      vdbeInvokeSqllog(p);
003573      if( db->pErr || p->zErrMsg ){
003574        sqlite3VdbeTransferError(p);
003575      }else{
003576        db->errCode = p->rc;
003577      }
003578    }
003579  
003580    /* Reset register contents and reclaim error message memory.
003581    */
003582  #ifdef SQLITE_DEBUG
003583    /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
003584    ** Vdbe.aMem[] arrays have already been cleaned up.  */
003585    if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
003586    if( p->aMem ){
003587      for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
003588    }
003589  #endif
003590    if( p->zErrMsg ){
003591      sqlite3DbFree(db, p->zErrMsg);
003592      p->zErrMsg = 0;
003593    }
003594    p->pResultRow = 0;
003595  #ifdef SQLITE_DEBUG
003596    p->nWrite = 0;
003597  #endif
003598  
003599    /* Save profiling information from this VDBE run.
003600    */
003601  #ifdef VDBE_PROFILE
003602    {
003603      FILE *out = fopen("vdbe_profile.out", "a");
003604      if( out ){
003605        fprintf(out, "---- ");
003606        for(i=0; i<p->nOp; i++){
003607          fprintf(out, "%02x", p->aOp[i].opcode);
003608        }
003609        fprintf(out, "\n");
003610        if( p->zSql ){
003611          char c, pc = 0;
003612          fprintf(out, "-- ");
003613          for(i=0; (c = p->zSql[i])!=0; i++){
003614            if( pc=='\n' ) fprintf(out, "-- ");
003615            putc(c, out);
003616            pc = c;
003617          }
003618          if( pc!='\n' ) fprintf(out, "\n");
003619        }
003620        for(i=0; i<p->nOp; i++){
003621          char zHdr[100];
003622          i64 cnt = p->aOp[i].nExec;
003623          i64 cycles = p->aOp[i].nCycle;
003624          sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
003625             cnt,
003626             cycles,
003627             cnt>0 ? cycles/cnt : 0
003628          );
003629          fprintf(out, "%s", zHdr);
003630          sqlite3VdbePrintOp(out, i, &p->aOp[i]);
003631        }
003632        fclose(out);
003633      }
003634    }
003635  #endif
003636    return p->rc & db->errMask;
003637  }
003638  
003639  /*
003640  ** Clean up and delete a VDBE after execution.  Return an integer which is
003641  ** the result code.  Write any error message text into *pzErrMsg.
003642  */
003643  int sqlite3VdbeFinalize(Vdbe *p){
003644    int rc = SQLITE_OK;
003645    assert( VDBE_RUN_STATE>VDBE_READY_STATE );
003646    assert( VDBE_HALT_STATE>VDBE_READY_STATE );
003647    assert( VDBE_INIT_STATE<VDBE_READY_STATE );
003648    if( p->eVdbeState>=VDBE_READY_STATE ){
003649      rc = sqlite3VdbeReset(p);
003650      assert( (rc & p->db->errMask)==rc );
003651    }
003652    sqlite3VdbeDelete(p);
003653    return rc;
003654  }
003655  
003656  /*
003657  ** If parameter iOp is less than zero, then invoke the destructor for
003658  ** all auxiliary data pointers currently cached by the VM passed as
003659  ** the first argument.
003660  **
003661  ** Or, if iOp is greater than or equal to zero, then the destructor is
003662  ** only invoked for those auxiliary data pointers created by the user
003663  ** function invoked by the OP_Function opcode at instruction iOp of
003664  ** VM pVdbe, and only then if:
003665  **
003666  **    * the associated function parameter is the 32nd or later (counting
003667  **      from left to right), or
003668  **
003669  **    * the corresponding bit in argument mask is clear (where the first
003670  **      function parameter corresponds to bit 0 etc.).
003671  */
003672  void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
003673    while( *pp ){
003674      AuxData *pAux = *pp;
003675      if( (iOp<0)
003676       || (pAux->iAuxOp==iOp
003677            && pAux->iAuxArg>=0
003678            && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
003679      ){
003680        testcase( pAux->iAuxArg==31 );
003681        if( pAux->xDeleteAux ){
003682          pAux->xDeleteAux(pAux->pAux);
003683        }
003684        *pp = pAux->pNextAux;
003685        sqlite3DbFree(db, pAux);
003686      }else{
003687        pp= &pAux->pNextAux;
003688      }
003689    }
003690  }
003691  
003692  /*
003693  ** Free all memory associated with the Vdbe passed as the second argument,
003694  ** except for object itself, which is preserved.
003695  **
003696  ** The difference between this function and sqlite3VdbeDelete() is that
003697  ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
003698  ** the database connection and frees the object itself.
003699  */
003700  static void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
003701    SubProgram *pSub, *pNext;
003702    assert( db!=0 );
003703    assert( p->db==0 || p->db==db );
003704    if( p->aColName ){
003705      releaseMemArray(p->aColName, p->nResAlloc*COLNAME_N);
003706      sqlite3DbNNFreeNN(db, p->aColName);
003707    }
003708    for(pSub=p->pProgram; pSub; pSub=pNext){
003709      pNext = pSub->pNext;
003710      vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
003711      sqlite3DbFree(db, pSub);
003712    }
003713    if( p->eVdbeState!=VDBE_INIT_STATE ){
003714      releaseMemArray(p->aVar, p->nVar);
003715      if( p->pVList ) sqlite3DbNNFreeNN(db, p->pVList);
003716      if( p->pFree ) sqlite3DbNNFreeNN(db, p->pFree);
003717    }
003718    vdbeFreeOpArray(db, p->aOp, p->nOp);
003719    if( p->zSql ) sqlite3DbNNFreeNN(db, p->zSql);
003720  #ifdef SQLITE_ENABLE_NORMALIZE
003721    sqlite3DbFree(db, p->zNormSql);
003722    {
003723      DblquoteStr *pThis, *pNxt;
003724      for(pThis=p->pDblStr; pThis; pThis=pNxt){
003725        pNxt = pThis->pNextStr;
003726        sqlite3DbFree(db, pThis);
003727      }
003728    }
003729  #endif
003730  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
003731    {
003732      int i;
003733      for(i=0; i<p->nScan; i++){
003734        sqlite3DbFree(db, p->aScan[i].zName);
003735      }
003736      sqlite3DbFree(db, p->aScan);
003737    }
003738  #endif
003739  }
003740  
003741  /*
003742  ** Delete an entire VDBE.
003743  */
003744  void sqlite3VdbeDelete(Vdbe *p){
003745    sqlite3 *db;
003746  
003747    assert( p!=0 );
003748    db = p->db;
003749    assert( db!=0 );
003750    assert( sqlite3_mutex_held(db->mutex) );
003751    sqlite3VdbeClearObject(db, p);
003752    if( db->pnBytesFreed==0 ){
003753      assert( p->ppVPrev!=0 );
003754      *p->ppVPrev = p->pVNext;
003755      if( p->pVNext ){
003756        p->pVNext->ppVPrev = p->ppVPrev;
003757      }
003758    }
003759    sqlite3DbNNFreeNN(db, p);
003760  }
003761  
003762  /*
003763  ** The cursor "p" has a pending seek operation that has not yet been
003764  ** carried out.  Seek the cursor now.  If an error occurs, return
003765  ** the appropriate error code.
003766  */
003767  int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor *p){
003768    int res, rc;
003769  #ifdef SQLITE_TEST
003770    extern int sqlite3_search_count;
003771  #endif
003772    assert( p->deferredMoveto );
003773    assert( p->isTable );
003774    assert( p->eCurType==CURTYPE_BTREE );
003775    rc = sqlite3BtreeTableMoveto(p->uc.pCursor, p->movetoTarget, 0, &res);
003776    if( rc ) return rc;
003777    if( res!=0 ) return SQLITE_CORRUPT_BKPT;
003778  #ifdef SQLITE_TEST
003779    sqlite3_search_count++;
003780  #endif
003781    p->deferredMoveto = 0;
003782    p->cacheStatus = CACHE_STALE;
003783    return SQLITE_OK;
003784  }
003785  
003786  /*
003787  ** Something has moved cursor "p" out of place.  Maybe the row it was
003788  ** pointed to was deleted out from under it.  Or maybe the btree was
003789  ** rebalanced.  Whatever the cause, try to restore "p" to the place it
003790  ** is supposed to be pointing.  If the row was deleted out from under the
003791  ** cursor, set the cursor to point to a NULL row.
003792  */
003793  int SQLITE_NOINLINE sqlite3VdbeHandleMovedCursor(VdbeCursor *p){
003794    int isDifferentRow, rc;
003795    assert( p->eCurType==CURTYPE_BTREE );
003796    assert( p->uc.pCursor!=0 );
003797    assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
003798    rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
003799    p->cacheStatus = CACHE_STALE;
003800    if( isDifferentRow ) p->nullRow = 1;
003801    return rc;
003802  }
003803  
003804  /*
003805  ** Check to ensure that the cursor is valid.  Restore the cursor
003806  ** if need be.  Return any I/O error from the restore operation.
003807  */
003808  int sqlite3VdbeCursorRestore(VdbeCursor *p){
003809    assert( p->eCurType==CURTYPE_BTREE || IsNullCursor(p) );
003810    if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
003811      return sqlite3VdbeHandleMovedCursor(p);
003812    }
003813    return SQLITE_OK;
003814  }
003815  
003816  /*
003817  ** The following functions:
003818  **
003819  ** sqlite3VdbeSerialType()
003820  ** sqlite3VdbeSerialTypeLen()
003821  ** sqlite3VdbeSerialLen()
003822  ** sqlite3VdbeSerialPut()  <--- in-lined into OP_MakeRecord as of 2022-04-02
003823  ** sqlite3VdbeSerialGet()
003824  **
003825  ** encapsulate the code that serializes values for storage in SQLite
003826  ** data and index records. Each serialized value consists of a
003827  ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
003828  ** integer, stored as a varint.
003829  **
003830  ** In an SQLite index record, the serial type is stored directly before
003831  ** the blob of data that it corresponds to. In a table record, all serial
003832  ** types are stored at the start of the record, and the blobs of data at
003833  ** the end. Hence these functions allow the caller to handle the
003834  ** serial-type and data blob separately.
003835  **
003836  ** The following table describes the various storage classes for data:
003837  **
003838  **   serial type        bytes of data      type
003839  **   --------------     ---------------    ---------------
003840  **      0                     0            NULL
003841  **      1                     1            signed integer
003842  **      2                     2            signed integer
003843  **      3                     3            signed integer
003844  **      4                     4            signed integer
003845  **      5                     6            signed integer
003846  **      6                     8            signed integer
003847  **      7                     8            IEEE float
003848  **      8                     0            Integer constant 0
003849  **      9                     0            Integer constant 1
003850  **     10,11                               reserved for expansion
003851  **    N>=12 and even       (N-12)/2        BLOB
003852  **    N>=13 and odd        (N-13)/2        text
003853  **
003854  ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
003855  ** of SQLite will not understand those serial types.
003856  */
003857  
003858  #if 0 /* Inlined into the OP_MakeRecord opcode */
003859  /*
003860  ** Return the serial-type for the value stored in pMem.
003861  **
003862  ** This routine might convert a large MEM_IntReal value into MEM_Real.
003863  **
003864  ** 2019-07-11:  The primary user of this subroutine was the OP_MakeRecord
003865  ** opcode in the byte-code engine.  But by moving this routine in-line, we
003866  ** can omit some redundant tests and make that opcode a lot faster.  So
003867  ** this routine is now only used by the STAT3 logic and STAT3 support has
003868  ** ended.  The code is kept here for historical reference only.
003869  */
003870  u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
003871    int flags = pMem->flags;
003872    u32 n;
003873  
003874    assert( pLen!=0 );
003875    if( flags&MEM_Null ){
003876      *pLen = 0;
003877      return 0;
003878    }
003879    if( flags&(MEM_Int|MEM_IntReal) ){
003880      /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
003881  #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
003882      i64 i = pMem->u.i;
003883      u64 u;
003884      testcase( flags & MEM_Int );
003885      testcase( flags & MEM_IntReal );
003886      if( i<0 ){
003887        u = ~i;
003888      }else{
003889        u = i;
003890      }
003891      if( u<=127 ){
003892        if( (i&1)==i && file_format>=4 ){
003893          *pLen = 0;
003894          return 8+(u32)u;
003895        }else{
003896          *pLen = 1;
003897          return 1;
003898        }
003899      }
003900      if( u<=32767 ){ *pLen = 2; return 2; }
003901      if( u<=8388607 ){ *pLen = 3; return 3; }
003902      if( u<=2147483647 ){ *pLen = 4; return 4; }
003903      if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
003904      *pLen = 8;
003905      if( flags&MEM_IntReal ){
003906        /* If the value is IntReal and is going to take up 8 bytes to store
003907        ** as an integer, then we might as well make it an 8-byte floating
003908        ** point value */
003909        pMem->u.r = (double)pMem->u.i;
003910        pMem->flags &= ~MEM_IntReal;
003911        pMem->flags |= MEM_Real;
003912        return 7;
003913      }
003914      return 6;
003915    }
003916    if( flags&MEM_Real ){
003917      *pLen = 8;
003918      return 7;
003919    }
003920    assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
003921    assert( pMem->n>=0 );
003922    n = (u32)pMem->n;
003923    if( flags & MEM_Zero ){
003924      n += pMem->u.nZero;
003925    }
003926    *pLen = n;
003927    return ((n*2) + 12 + ((flags&MEM_Str)!=0));
003928  }
003929  #endif /* inlined into OP_MakeRecord */
003930  
003931  /*
003932  ** The sizes for serial types less than 128
003933  */
003934  const u8 sqlite3SmallTypeSizes[128] = {
003935          /*  0   1   2   3   4   5   6   7   8   9 */  
003936  /*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
003937  /*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
003938  /*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
003939  /*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
003940  /*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
003941  /*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
003942  /*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
003943  /*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
003944  /*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
003945  /*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
003946  /* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
003947  /* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
003948  /* 120 */  54, 54, 55, 55, 56, 56, 57, 57
003949  };
003950  
003951  /*
003952  ** Return the length of the data corresponding to the supplied serial-type.
003953  */
003954  u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
003955    if( serial_type>=128 ){
003956      return (serial_type-12)/2;
003957    }else{
003958      assert( serial_type<12
003959              || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
003960      return sqlite3SmallTypeSizes[serial_type];
003961    }
003962  }
003963  u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
003964    assert( serial_type<128 );
003965    return sqlite3SmallTypeSizes[serial_type]; 
003966  }
003967  
003968  /*
003969  ** If we are on an architecture with mixed-endian floating
003970  ** points (ex: ARM7) then swap the lower 4 bytes with the
003971  ** upper 4 bytes.  Return the result.
003972  **
003973  ** For most architectures, this is a no-op.
003974  **
003975  ** (later):  It is reported to me that the mixed-endian problem
003976  ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
003977  ** that early versions of GCC stored the two words of a 64-bit
003978  ** float in the wrong order.  And that error has been propagated
003979  ** ever since.  The blame is not necessarily with GCC, though.
003980  ** GCC might have just copying the problem from a prior compiler.
003981  ** I am also told that newer versions of GCC that follow a different
003982  ** ABI get the byte order right.
003983  **
003984  ** Developers using SQLite on an ARM7 should compile and run their
003985  ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
003986  ** enabled, some asserts below will ensure that the byte order of
003987  ** floating point values is correct.
003988  **
003989  ** (2007-08-30)  Frank van Vugt has studied this problem closely
003990  ** and has send his findings to the SQLite developers.  Frank
003991  ** writes that some Linux kernels offer floating point hardware
003992  ** emulation that uses only 32-bit mantissas instead of a full
003993  ** 48-bits as required by the IEEE standard.  (This is the
003994  ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
003995  ** byte swapping becomes very complicated.  To avoid problems,
003996  ** the necessary byte swapping is carried out using a 64-bit integer
003997  ** rather than a 64-bit float.  Frank assures us that the code here
003998  ** works for him.  We, the developers, have no way to independently
003999  ** verify this, but Frank seems to know what he is talking about
004000  ** so we trust him.
004001  */
004002  #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
004003  u64 sqlite3FloatSwap(u64 in){
004004    union {
004005      u64 r;
004006      u32 i[2];
004007    } u;
004008    u32 t;
004009  
004010    u.r = in;
004011    t = u.i[0];
004012    u.i[0] = u.i[1];
004013    u.i[1] = t;
004014    return u.r;
004015  }
004016  #endif /* SQLITE_MIXED_ENDIAN_64BIT_FLOAT */
004017  
004018  
004019  /* Input "x" is a sequence of unsigned characters that represent a
004020  ** big-endian integer.  Return the equivalent native integer
004021  */
004022  #define ONE_BYTE_INT(x)    ((i8)(x)[0])
004023  #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
004024  #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
004025  #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
004026  #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
004027  
004028  /*
004029  ** Deserialize the data blob pointed to by buf as serial type serial_type
004030  ** and store the result in pMem.
004031  **
004032  ** This function is implemented as two separate routines for performance.
004033  ** The few cases that require local variables are broken out into a separate
004034  ** routine so that in most cases the overhead of moving the stack pointer
004035  ** is avoided.
004036  */
004037  static void serialGet(
004038    const unsigned char *buf,     /* Buffer to deserialize from */
004039    u32 serial_type,              /* Serial type to deserialize */
004040    Mem *pMem                     /* Memory cell to write value into */
004041  ){
004042    u64 x = FOUR_BYTE_UINT(buf);
004043    u32 y = FOUR_BYTE_UINT(buf+4);
004044    x = (x<<32) + y;
004045    if( serial_type==6 ){
004046      /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
004047      ** twos-complement integer. */
004048      pMem->u.i = *(i64*)&x;
004049      pMem->flags = MEM_Int;
004050      testcase( pMem->u.i<0 );
004051    }else{
004052      /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
004053      ** floating point number. */
004054  #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
004055      /* Verify that integers and floating point values use the same
004056      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
004057      ** defined that 64-bit floating point values really are mixed
004058      ** endian.
004059      */
004060      static const u64 t1 = ((u64)0x3ff00000)<<32;
004061      static const double r1 = 1.0;
004062      u64 t2 = t1;
004063      swapMixedEndianFloat(t2);
004064      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
004065  #endif
004066      assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
004067      swapMixedEndianFloat(x);
004068      memcpy(&pMem->u.r, &x, sizeof(x));
004069      pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;
004070    }
004071  }
004072  static int serialGet7(
004073    const unsigned char *buf,     /* Buffer to deserialize from */
004074    Mem *pMem                     /* Memory cell to write value into */
004075  ){
004076    u64 x = FOUR_BYTE_UINT(buf);
004077    u32 y = FOUR_BYTE_UINT(buf+4);
004078    x = (x<<32) + y;
004079    assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
004080    swapMixedEndianFloat(x);
004081    memcpy(&pMem->u.r, &x, sizeof(x));
004082    if( IsNaN(x) ){
004083      pMem->flags = MEM_Null;
004084      return 1;
004085    }
004086    pMem->flags = MEM_Real;
004087    return 0;
004088  }
004089  void sqlite3VdbeSerialGet(
004090    const unsigned char *buf,     /* Buffer to deserialize from */
004091    u32 serial_type,              /* Serial type to deserialize */
004092    Mem *pMem                     /* Memory cell to write value into */
004093  ){
004094    switch( serial_type ){
004095      case 10: { /* Internal use only: NULL with virtual table
004096                 ** UPDATE no-change flag set */
004097        pMem->flags = MEM_Null|MEM_Zero;
004098        pMem->n = 0;
004099        pMem->u.nZero = 0;
004100        return;
004101      }
004102      case 11:   /* Reserved for future use */
004103      case 0: {  /* Null */
004104        /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
004105        pMem->flags = MEM_Null;
004106        return;
004107      }
004108      case 1: {
004109        /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
004110        ** integer. */
004111        pMem->u.i = ONE_BYTE_INT(buf);
004112        pMem->flags = MEM_Int;
004113        testcase( pMem->u.i<0 );
004114        return;
004115      }
004116      case 2: { /* 2-byte signed integer */
004117        /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
004118        ** twos-complement integer. */
004119        pMem->u.i = TWO_BYTE_INT(buf);
004120        pMem->flags = MEM_Int;
004121        testcase( pMem->u.i<0 );
004122        return;
004123      }
004124      case 3: { /* 3-byte signed integer */
004125        /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
004126        ** twos-complement integer. */
004127        pMem->u.i = THREE_BYTE_INT(buf);
004128        pMem->flags = MEM_Int;
004129        testcase( pMem->u.i<0 );
004130        return;
004131      }
004132      case 4: { /* 4-byte signed integer */
004133        /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
004134        ** twos-complement integer. */
004135        pMem->u.i = FOUR_BYTE_INT(buf);
004136  #ifdef __HP_cc
004137        /* Work around a sign-extension bug in the HP compiler for HP/UX */
004138        if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
004139  #endif
004140        pMem->flags = MEM_Int;
004141        testcase( pMem->u.i<0 );
004142        return;
004143      }
004144      case 5: { /* 6-byte signed integer */
004145        /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
004146        ** twos-complement integer. */
004147        pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
004148        pMem->flags = MEM_Int;
004149        testcase( pMem->u.i<0 );
004150        return;
004151      }
004152      case 6:   /* 8-byte signed integer */
004153      case 7: { /* IEEE floating point */
004154        /* These use local variables, so do them in a separate routine
004155        ** to avoid having to move the frame pointer in the common case */
004156        serialGet(buf,serial_type,pMem);
004157        return;
004158      }
004159      case 8:    /* Integer 0 */
004160      case 9: {  /* Integer 1 */
004161        /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
004162        /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
004163        pMem->u.i = serial_type-8;
004164        pMem->flags = MEM_Int;
004165        return;
004166      }
004167      default: {
004168        /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
004169        ** length.
004170        ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
004171        ** (N-13)/2 bytes in length. */
004172        static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
004173        pMem->z = (char *)buf;
004174        pMem->n = (serial_type-12)/2;
004175        pMem->flags = aFlag[serial_type&1];
004176        return;
004177      }
004178    }
004179    return;
004180  }
004181  /*
004182  ** This routine is used to allocate sufficient space for an UnpackedRecord
004183  ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
004184  ** the first argument is a pointer to KeyInfo structure pKeyInfo.
004185  **
004186  ** The space is either allocated using sqlite3DbMallocRaw() or from within
004187  ** the unaligned buffer passed via the second and third arguments (presumably
004188  ** stack space). If the former, then *ppFree is set to a pointer that should
004189  ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
004190  ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
004191  ** before returning.
004192  **
004193  ** If an OOM error occurs, NULL is returned.
004194  */
004195  UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
004196    KeyInfo *pKeyInfo               /* Description of the record */
004197  ){
004198    UnpackedRecord *p;              /* Unpacked record to return */
004199    int nByte;                      /* Number of bytes required for *p */
004200    nByte = ROUND8P(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
004201    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
004202    if( !p ) return 0;
004203    p->aMem = (Mem*)&((char*)p)[ROUND8P(sizeof(UnpackedRecord))];
004204    assert( pKeyInfo->aSortFlags!=0 );
004205    p->pKeyInfo = pKeyInfo;
004206    p->nField = pKeyInfo->nKeyField + 1;
004207    return p;
004208  }
004209  
004210  /*
004211  ** Given the nKey-byte encoding of a record in pKey[], populate the
004212  ** UnpackedRecord structure indicated by the fourth argument with the
004213  ** contents of the decoded record.
004214  */
004215  void sqlite3VdbeRecordUnpack(
004216    KeyInfo *pKeyInfo,     /* Information about the record format */
004217    int nKey,              /* Size of the binary record */
004218    const void *pKey,      /* The binary record */
004219    UnpackedRecord *p      /* Populate this structure before returning. */
004220  ){
004221    const unsigned char *aKey = (const unsigned char *)pKey;
004222    u32 d;
004223    u32 idx;                        /* Offset in aKey[] to read from */
004224    u16 u;                          /* Unsigned loop counter */
004225    u32 szHdr;
004226    Mem *pMem = p->aMem;
004227  
004228    p->default_rc = 0;
004229    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
004230    idx = getVarint32(aKey, szHdr);
004231    d = szHdr;
004232    u = 0;
004233    while( idx<szHdr && d<=(u32)nKey ){
004234      u32 serial_type;
004235  
004236      idx += getVarint32(&aKey[idx], serial_type);
004237      pMem->enc = pKeyInfo->enc;
004238      pMem->db = pKeyInfo->db;
004239      /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
004240      pMem->szMalloc = 0;
004241      pMem->z = 0;
004242      sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
004243      d += sqlite3VdbeSerialTypeLen(serial_type);
004244      pMem++;
004245      if( (++u)>=p->nField ) break;
004246    }
004247    if( d>(u32)nKey && u ){
004248      assert( CORRUPT_DB );
004249      /* In a corrupt record entry, the last pMem might have been set up using
004250      ** uninitialized memory. Overwrite its value with NULL, to prevent
004251      ** warnings from MSAN. */
004252      sqlite3VdbeMemSetNull(pMem-1);
004253    }
004254    assert( u<=pKeyInfo->nKeyField + 1 );
004255    p->nField = u;
004256  }
004257  
004258  #ifdef SQLITE_DEBUG
004259  /*
004260  ** This function compares two index or table record keys in the same way
004261  ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
004262  ** this function deserializes and compares values using the
004263  ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
004264  ** in assert() statements to ensure that the optimized code in
004265  ** sqlite3VdbeRecordCompare() returns results with these two primitives.
004266  **
004267  ** Return true if the result of comparison is equivalent to desiredResult.
004268  ** Return false if there is a disagreement.
004269  */
004270  static int vdbeRecordCompareDebug(
004271    int nKey1, const void *pKey1, /* Left key */
004272    const UnpackedRecord *pPKey2, /* Right key */
004273    int desiredResult             /* Correct answer */
004274  ){
004275    u32 d1;            /* Offset into aKey[] of next data element */
004276    u32 idx1;          /* Offset into aKey[] of next header element */
004277    u32 szHdr1;        /* Number of bytes in header */
004278    int i = 0;
004279    int rc = 0;
004280    const unsigned char *aKey1 = (const unsigned char *)pKey1;
004281    KeyInfo *pKeyInfo;
004282    Mem mem1;
004283  
004284    pKeyInfo = pPKey2->pKeyInfo;
004285    if( pKeyInfo->db==0 ) return 1;
004286    mem1.enc = pKeyInfo->enc;
004287    mem1.db = pKeyInfo->db;
004288    /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
004289    VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
004290  
004291    /* Compilers may complain that mem1.u.i is potentially uninitialized.
004292    ** We could initialize it, as shown here, to silence those complaints.
004293    ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
004294    ** the unnecessary initialization has a measurable negative performance
004295    ** impact, since this routine is a very high runner.  And so, we choose
004296    ** to ignore the compiler warnings and leave this variable uninitialized.
004297    */
004298    /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
004299   
004300    idx1 = getVarint32(aKey1, szHdr1);
004301    if( szHdr1>98307 ) return SQLITE_CORRUPT;
004302    d1 = szHdr1;
004303    assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
004304    assert( pKeyInfo->aSortFlags!=0 );
004305    assert( pKeyInfo->nKeyField>0 );
004306    assert( idx1<=szHdr1 || CORRUPT_DB );
004307    do{
004308      u32 serial_type1;
004309  
004310      /* Read the serial types for the next element in each key. */
004311      idx1 += getVarint32( aKey1+idx1, serial_type1 );
004312  
004313      /* Verify that there is enough key space remaining to avoid
004314      ** a buffer overread.  The "d1+serial_type1+2" subexpression will
004315      ** always be greater than or equal to the amount of required key space.
004316      ** Use that approximation to avoid the more expensive call to
004317      ** sqlite3VdbeSerialTypeLen() in the common case.
004318      */
004319      if( d1+(u64)serial_type1+2>(u64)nKey1
004320       && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1
004321      ){
004322        if( serial_type1>=1
004323         && serial_type1<=7
004324         && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)<=(u64)nKey1+8
004325         && CORRUPT_DB
004326        ){
004327          return 1;  /* corrupt record not detected by
004328                     ** sqlite3VdbeRecordCompareWithSkip().  Return true
004329                     ** to avoid firing the assert() */
004330        }
004331        break;
004332      }
004333  
004334      /* Extract the values to be compared.
004335      */
004336      sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
004337      d1 += sqlite3VdbeSerialTypeLen(serial_type1);
004338  
004339      /* Do the comparison
004340      */
004341      rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
004342                             pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
004343      if( rc!=0 ){
004344        assert( mem1.szMalloc==0 );  /* See comment below */
004345        if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
004346         && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null))
004347        ){
004348          rc = -rc;
004349        }
004350        if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){
004351          rc = -rc;  /* Invert the result for DESC sort order. */
004352        }
004353        goto debugCompareEnd;
004354      }
004355      i++;
004356    }while( idx1<szHdr1 && i<pPKey2->nField );
004357  
004358    /* No memory allocation is ever used on mem1.  Prove this using
004359    ** the following assert().  If the assert() fails, it indicates a
004360    ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
004361    */
004362    assert( mem1.szMalloc==0 );
004363  
004364    /* rc==0 here means that one of the keys ran out of fields and
004365    ** all the fields up to that point were equal. Return the default_rc
004366    ** value.  */
004367    rc = pPKey2->default_rc;
004368  
004369  debugCompareEnd:
004370    if( desiredResult==0 && rc==0 ) return 1;
004371    if( desiredResult<0 && rc<0 ) return 1;
004372    if( desiredResult>0 && rc>0 ) return 1;
004373    if( CORRUPT_DB ) return 1;
004374    if( pKeyInfo->db->mallocFailed ) return 1;
004375    return 0;
004376  }
004377  #endif
004378  
004379  #ifdef SQLITE_DEBUG
004380  /*
004381  ** Count the number of fields (a.k.a. columns) in the record given by
004382  ** pKey,nKey.  The verify that this count is less than or equal to the
004383  ** limit given by pKeyInfo->nAllField.
004384  **
004385  ** If this constraint is not satisfied, it means that the high-speed
004386  ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
004387  ** not work correctly.  If this assert() ever fires, it probably means
004388  ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
004389  ** incorrectly.
004390  */
004391  static void vdbeAssertFieldCountWithinLimits(
004392    int nKey, const void *pKey,   /* The record to verify */
004393    const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
004394  ){
004395    int nField = 0;
004396    u32 szHdr;
004397    u32 idx;
004398    u32 notUsed;
004399    const unsigned char *aKey = (const unsigned char*)pKey;
004400  
004401    if( CORRUPT_DB ) return;
004402    idx = getVarint32(aKey, szHdr);
004403    assert( nKey>=0 );
004404    assert( szHdr<=(u32)nKey );
004405    while( idx<szHdr ){
004406      idx += getVarint32(aKey+idx, notUsed);
004407      nField++;
004408    }
004409    assert( nField <= pKeyInfo->nAllField );
004410  }
004411  #else
004412  # define vdbeAssertFieldCountWithinLimits(A,B,C)
004413  #endif
004414  
004415  /*
004416  ** Both *pMem1 and *pMem2 contain string values. Compare the two values
004417  ** using the collation sequence pColl. As usual, return a negative , zero
004418  ** or positive value if *pMem1 is less than, equal to or greater than
004419  ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
004420  */
004421  static int vdbeCompareMemString(
004422    const Mem *pMem1,
004423    const Mem *pMem2,
004424    const CollSeq *pColl,
004425    u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
004426  ){
004427    if( pMem1->enc==pColl->enc ){
004428      /* The strings are already in the correct encoding.  Call the
004429       ** comparison function directly */
004430      return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
004431    }else{
004432      int rc;
004433      const void *v1, *v2;
004434      Mem c1;
004435      Mem c2;
004436      sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
004437      sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
004438      sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
004439      sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
004440      v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
004441      v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
004442      if( (v1==0 || v2==0) ){
004443        if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
004444        rc = 0;
004445      }else{
004446        rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
004447      }
004448      sqlite3VdbeMemReleaseMalloc(&c1);
004449      sqlite3VdbeMemReleaseMalloc(&c2);
004450      return rc;
004451    }
004452  }
004453  
004454  /*
004455  ** The input pBlob is guaranteed to be a Blob that is not marked
004456  ** with MEM_Zero.  Return true if it could be a zero-blob.
004457  */
004458  static int isAllZero(const char *z, int n){
004459    int i;
004460    for(i=0; i<n; i++){
004461      if( z[i] ) return 0;
004462    }
004463    return 1;
004464  }
004465  
004466  /*
004467  ** Compare two blobs.  Return negative, zero, or positive if the first
004468  ** is less than, equal to, or greater than the second, respectively.
004469  ** If one blob is a prefix of the other, then the shorter is the lessor.
004470  */
004471  SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
004472    int c;
004473    int n1 = pB1->n;
004474    int n2 = pB2->n;
004475  
004476    /* It is possible to have a Blob value that has some non-zero content
004477    ** followed by zero content.  But that only comes up for Blobs formed
004478    ** by the OP_MakeRecord opcode, and such Blobs never get passed into
004479    ** sqlite3MemCompare(). */
004480    assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
004481    assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
004482  
004483    if( (pB1->flags|pB2->flags) & MEM_Zero ){
004484      if( pB1->flags & pB2->flags & MEM_Zero ){
004485        return pB1->u.nZero - pB2->u.nZero;
004486      }else if( pB1->flags & MEM_Zero ){
004487        if( !isAllZero(pB2->z, pB2->n) ) return -1;
004488        return pB1->u.nZero - n2;
004489      }else{
004490        if( !isAllZero(pB1->z, pB1->n) ) return +1;
004491        return n1 - pB2->u.nZero;
004492      }
004493    }
004494    c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
004495    if( c ) return c;
004496    return n1 - n2;
004497  }
004498  
004499  /* The following two functions are used only within testcase() to prove
004500  ** test coverage.  These functions do no exist for production builds.
004501  ** We must use separate SQLITE_NOINLINE functions here, since otherwise
004502  ** optimizer code movement causes gcov to become very confused.
004503  */
004504  #if  defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
004505  static int SQLITE_NOINLINE doubleLt(double a, double b){ return a<b; }
004506  static int SQLITE_NOINLINE doubleEq(double a, double b){ return a==b; }
004507  #endif
004508  
004509  /*
004510  ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
004511  ** number.  Return negative, zero, or positive if the first (i64) is less than,
004512  ** equal to, or greater than the second (double).
004513  */
004514  int sqlite3IntFloatCompare(i64 i, double r){
004515    if( sqlite3IsNaN(r) ){
004516      /* SQLite considers NaN to be a NULL. And all integer values are greater
004517      ** than NULL */
004518      return 1;
004519    }
004520    if( sqlite3Config.bUseLongDouble ){
004521      LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
004522      testcase( x<r );
004523      testcase( x>r );
004524      testcase( x==r );
004525      return (x<r) ? -1 : (x>r);
004526    }else{
004527      i64 y;
004528      if( r<-9223372036854775808.0 ) return +1;
004529      if( r>=9223372036854775808.0 ) return -1;
004530      y = (i64)r;
004531      if( i<y ) return -1;
004532      if( i>y ) return +1;
004533      testcase( doubleLt(((double)i),r) );
004534      testcase( doubleLt(r,((double)i)) );
004535      testcase( doubleEq(r,((double)i)) );
004536      return (((double)i)<r) ? -1 : (((double)i)>r);
004537    }
004538  }
004539  
004540  /*
004541  ** Compare the values contained by the two memory cells, returning
004542  ** negative, zero or positive if pMem1 is less than, equal to, or greater
004543  ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
004544  ** and reals) sorted numerically, followed by text ordered by the collating
004545  ** sequence pColl and finally blob's ordered by memcmp().
004546  **
004547  ** Two NULL values are considered equal by this function.
004548  */
004549  int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
004550    int f1, f2;
004551    int combined_flags;
004552  
004553    f1 = pMem1->flags;
004554    f2 = pMem2->flags;
004555    combined_flags = f1|f2;
004556    assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
004557  
004558    /* If one value is NULL, it is less than the other. If both values
004559    ** are NULL, return 0.
004560    */
004561    if( combined_flags&MEM_Null ){
004562      return (f2&MEM_Null) - (f1&MEM_Null);
004563    }
004564  
004565    /* At least one of the two values is a number
004566    */
004567    if( combined_flags&(MEM_Int|MEM_Real|MEM_IntReal) ){
004568      testcase( combined_flags & MEM_Int );
004569      testcase( combined_flags & MEM_Real );
004570      testcase( combined_flags & MEM_IntReal );
004571      if( (f1 & f2 & (MEM_Int|MEM_IntReal))!=0 ){
004572        testcase( f1 & f2 & MEM_Int );
004573        testcase( f1 & f2 & MEM_IntReal );
004574        if( pMem1->u.i < pMem2->u.i ) return -1;
004575        if( pMem1->u.i > pMem2->u.i ) return +1;
004576        return 0;
004577      }
004578      if( (f1 & f2 & MEM_Real)!=0 ){
004579        if( pMem1->u.r < pMem2->u.r ) return -1;
004580        if( pMem1->u.r > pMem2->u.r ) return +1;
004581        return 0;
004582      }
004583      if( (f1&(MEM_Int|MEM_IntReal))!=0 ){
004584        testcase( f1 & MEM_Int );
004585        testcase( f1 & MEM_IntReal );
004586        if( (f2&MEM_Real)!=0 ){
004587          return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
004588        }else if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
004589          if( pMem1->u.i < pMem2->u.i ) return -1;
004590          if( pMem1->u.i > pMem2->u.i ) return +1;
004591          return 0;
004592        }else{
004593          return -1;
004594        }
004595      }
004596      if( (f1&MEM_Real)!=0 ){
004597        if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
004598          testcase( f2 & MEM_Int );
004599          testcase( f2 & MEM_IntReal );
004600          return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
004601        }else{
004602          return -1;
004603        }
004604      }
004605      return +1;
004606    }
004607  
004608    /* If one value is a string and the other is a blob, the string is less.
004609    ** If both are strings, compare using the collating functions.
004610    */
004611    if( combined_flags&MEM_Str ){
004612      if( (f1 & MEM_Str)==0 ){
004613        return 1;
004614      }
004615      if( (f2 & MEM_Str)==0 ){
004616        return -1;
004617      }
004618  
004619      assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
004620      assert( pMem1->enc==SQLITE_UTF8 ||
004621              pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
004622  
004623      /* The collation sequence must be defined at this point, even if
004624      ** the user deletes the collation sequence after the vdbe program is
004625      ** compiled (this was not always the case).
004626      */
004627      assert( !pColl || pColl->xCmp );
004628  
004629      if( pColl ){
004630        return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
004631      }
004632      /* If a NULL pointer was passed as the collate function, fall through
004633      ** to the blob case and use memcmp().  */
004634    }
004635  
004636    /* Both values must be blobs.  Compare using memcmp().  */
004637    return sqlite3BlobCompare(pMem1, pMem2);
004638  }
004639  
004640  
004641  /*
004642  ** The first argument passed to this function is a serial-type that
004643  ** corresponds to an integer - all values between 1 and 9 inclusive
004644  ** except 7. The second points to a buffer containing an integer value
004645  ** serialized according to serial_type. This function deserializes
004646  ** and returns the value.
004647  */
004648  static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
004649    u32 y;
004650    assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
004651    switch( serial_type ){
004652      case 0:
004653      case 1:
004654        testcase( aKey[0]&0x80 );
004655        return ONE_BYTE_INT(aKey);
004656      case 2:
004657        testcase( aKey[0]&0x80 );
004658        return TWO_BYTE_INT(aKey);
004659      case 3:
004660        testcase( aKey[0]&0x80 );
004661        return THREE_BYTE_INT(aKey);
004662      case 4: {
004663        testcase( aKey[0]&0x80 );
004664        y = FOUR_BYTE_UINT(aKey);
004665        return (i64)*(int*)&y;
004666      }
004667      case 5: {
004668        testcase( aKey[0]&0x80 );
004669        return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
004670      }
004671      case 6: {
004672        u64 x = FOUR_BYTE_UINT(aKey);
004673        testcase( aKey[0]&0x80 );
004674        x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
004675        return (i64)*(i64*)&x;
004676      }
004677    }
004678  
004679    return (serial_type - 8);
004680  }
004681  
004682  /*
004683  ** This function compares the two table rows or index records
004684  ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
004685  ** or positive integer if key1 is less than, equal to or
004686  ** greater than key2.  The {nKey1, pKey1} key must be a blob
004687  ** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
004688  ** key must be a parsed key such as obtained from
004689  ** sqlite3VdbeParseRecord.
004690  **
004691  ** If argument bSkip is non-zero, it is assumed that the caller has already
004692  ** determined that the first fields of the keys are equal.
004693  **
004694  ** Key1 and Key2 do not have to contain the same number of fields. If all
004695  ** fields that appear in both keys are equal, then pPKey2->default_rc is
004696  ** returned.
004697  **
004698  ** If database corruption is discovered, set pPKey2->errCode to
004699  ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
004700  ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
004701  ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
004702  */
004703  int sqlite3VdbeRecordCompareWithSkip(
004704    int nKey1, const void *pKey1,   /* Left key */
004705    UnpackedRecord *pPKey2,         /* Right key */
004706    int bSkip                       /* If true, skip the first field */
004707  ){
004708    u32 d1;                         /* Offset into aKey[] of next data element */
004709    int i;                          /* Index of next field to compare */
004710    u32 szHdr1;                     /* Size of record header in bytes */
004711    u32 idx1;                       /* Offset of first type in header */
004712    int rc = 0;                     /* Return value */
004713    Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
004714    KeyInfo *pKeyInfo;
004715    const unsigned char *aKey1 = (const unsigned char *)pKey1;
004716    Mem mem1;
004717  
004718    /* If bSkip is true, then the caller has already determined that the first
004719    ** two elements in the keys are equal. Fix the various stack variables so
004720    ** that this routine begins comparing at the second field. */
004721    if( bSkip ){
004722      u32 s1 = aKey1[1];
004723      if( s1<0x80 ){
004724        idx1 = 2;
004725      }else{
004726        idx1 = 1 + sqlite3GetVarint32(&aKey1[1], &s1);
004727      }
004728      szHdr1 = aKey1[0];
004729      d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
004730      i = 1;
004731      pRhs++;
004732    }else{
004733      if( (szHdr1 = aKey1[0])<0x80 ){
004734        idx1 = 1;
004735      }else{
004736        idx1 = sqlite3GetVarint32(aKey1, &szHdr1);
004737      }
004738      d1 = szHdr1;
004739      i = 0;
004740    }
004741    if( d1>(unsigned)nKey1 ){
004742      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
004743      return 0;  /* Corruption */
004744    }
004745  
004746    VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
004747    assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
004748         || CORRUPT_DB );
004749    assert( pPKey2->pKeyInfo->aSortFlags!=0 );
004750    assert( pPKey2->pKeyInfo->nKeyField>0 );
004751    assert( idx1<=szHdr1 || CORRUPT_DB );
004752    while( 1 /*exit-by-break*/ ){
004753      u32 serial_type;
004754  
004755      /* RHS is an integer */
004756      if( pRhs->flags & (MEM_Int|MEM_IntReal) ){
004757        testcase( pRhs->flags & MEM_Int );
004758        testcase( pRhs->flags & MEM_IntReal );
004759        serial_type = aKey1[idx1];
004760        testcase( serial_type==12 );
004761        if( serial_type>=10 ){
004762          rc = serial_type==10 ? -1 : +1;
004763        }else if( serial_type==0 ){
004764          rc = -1;
004765        }else if( serial_type==7 ){
004766          serialGet7(&aKey1[d1], &mem1);
004767          rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
004768        }else{
004769          i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
004770          i64 rhs = pRhs->u.i;
004771          if( lhs<rhs ){
004772            rc = -1;
004773          }else if( lhs>rhs ){
004774            rc = +1;
004775          }
004776        }
004777      }
004778  
004779      /* RHS is real */
004780      else if( pRhs->flags & MEM_Real ){
004781        serial_type = aKey1[idx1];
004782        if( serial_type>=10 ){
004783          /* Serial types 12 or greater are strings and blobs (greater than
004784          ** numbers). Types 10 and 11 are currently "reserved for future
004785          ** use", so it doesn't really matter what the results of comparing
004786          ** them to numeric values are.  */
004787          rc = serial_type==10 ? -1 : +1;
004788        }else if( serial_type==0 ){
004789          rc = -1;
004790        }else{
004791          if( serial_type==7 ){
004792            if( serialGet7(&aKey1[d1], &mem1) ){
004793              rc = -1;  /* mem1 is a NaN */
004794            }else if( mem1.u.r<pRhs->u.r ){
004795              rc = -1;
004796            }else if( mem1.u.r>pRhs->u.r ){
004797              rc = +1;
004798            }else{
004799              assert( rc==0 );
004800            }
004801          }else{
004802            sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
004803            rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
004804          }
004805        }
004806      }
004807  
004808      /* RHS is a string */
004809      else if( pRhs->flags & MEM_Str ){
004810        getVarint32NR(&aKey1[idx1], serial_type);
004811        testcase( serial_type==12 );
004812        if( serial_type<12 ){
004813          rc = -1;
004814        }else if( !(serial_type & 0x01) ){
004815          rc = +1;
004816        }else{
004817          mem1.n = (serial_type - 12) / 2;
004818          testcase( (d1+mem1.n)==(unsigned)nKey1 );
004819          testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
004820          if( (d1+mem1.n) > (unsigned)nKey1
004821           || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
004822          ){
004823            pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
004824            return 0;                /* Corruption */
004825          }else if( pKeyInfo->aColl[i] ){
004826            mem1.enc = pKeyInfo->enc;
004827            mem1.db = pKeyInfo->db;
004828            mem1.flags = MEM_Str;
004829            mem1.z = (char*)&aKey1[d1];
004830            rc = vdbeCompareMemString(
004831                &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
004832            );
004833          }else{
004834            int nCmp = MIN(mem1.n, pRhs->n);
004835            rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
004836            if( rc==0 ) rc = mem1.n - pRhs->n;
004837          }
004838        }
004839      }
004840  
004841      /* RHS is a blob */
004842      else if( pRhs->flags & MEM_Blob ){
004843        assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
004844        getVarint32NR(&aKey1[idx1], serial_type);
004845        testcase( serial_type==12 );
004846        if( serial_type<12 || (serial_type & 0x01) ){
004847          rc = -1;
004848        }else{
004849          int nStr = (serial_type - 12) / 2;
004850          testcase( (d1+nStr)==(unsigned)nKey1 );
004851          testcase( (d1+nStr+1)==(unsigned)nKey1 );
004852          if( (d1+nStr) > (unsigned)nKey1 ){
004853            pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
004854            return 0;                /* Corruption */
004855          }else if( pRhs->flags & MEM_Zero ){
004856            if( !isAllZero((const char*)&aKey1[d1],nStr) ){
004857              rc = 1;
004858            }else{
004859              rc = nStr - pRhs->u.nZero;
004860            }
004861          }else{
004862            int nCmp = MIN(nStr, pRhs->n);
004863            rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
004864            if( rc==0 ) rc = nStr - pRhs->n;
004865          }
004866        }
004867      }
004868  
004869      /* RHS is null */
004870      else{
004871        serial_type = aKey1[idx1];
004872        if( serial_type==0
004873         || serial_type==10
004874         || (serial_type==7 && serialGet7(&aKey1[d1], &mem1)!=0)
004875        ){
004876          assert( rc==0 );
004877        }else{
004878          rc = 1;
004879        }
004880      }
004881  
004882      if( rc!=0 ){
004883        int sortFlags = pPKey2->pKeyInfo->aSortFlags[i];
004884        if( sortFlags ){
004885          if( (sortFlags & KEYINFO_ORDER_BIGNULL)==0
004886           || ((sortFlags & KEYINFO_ORDER_DESC)
004887             !=(serial_type==0 || (pRhs->flags&MEM_Null)))
004888          ){
004889            rc = -rc;
004890          }
004891        }
004892        assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
004893        assert( mem1.szMalloc==0 );  /* See comment below */
004894        return rc;
004895      }
004896  
004897      i++;
004898      if( i==pPKey2->nField ) break;
004899      pRhs++;
004900      d1 += sqlite3VdbeSerialTypeLen(serial_type);
004901      if( d1>(unsigned)nKey1 ) break;
004902      idx1 += sqlite3VarintLen(serial_type);
004903      if( idx1>=(unsigned)szHdr1 ){
004904        pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
004905        return 0;  /* Corrupt index */
004906      }
004907    }
004908  
004909    /* No memory allocation is ever used on mem1.  Prove this using
004910    ** the following assert().  If the assert() fails, it indicates a
004911    ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
004912    assert( mem1.szMalloc==0 );
004913  
004914    /* rc==0 here means that one or both of the keys ran out of fields and
004915    ** all the fields up to that point were equal. Return the default_rc
004916    ** value.  */
004917    assert( CORRUPT_DB
004918         || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
004919         || pPKey2->pKeyInfo->db->mallocFailed
004920    );
004921    pPKey2->eqSeen = 1;
004922    return pPKey2->default_rc;
004923  }
004924  int sqlite3VdbeRecordCompare(
004925    int nKey1, const void *pKey1,   /* Left key */
004926    UnpackedRecord *pPKey2          /* Right key */
004927  ){
004928    return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
004929  }
004930  
004931  
004932  /*
004933  ** This function is an optimized version of sqlite3VdbeRecordCompare()
004934  ** that (a) the first field of pPKey2 is an integer, and (b) the
004935  ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
004936  ** byte (i.e. is less than 128).
004937  **
004938  ** To avoid concerns about buffer overreads, this routine is only used
004939  ** on schemas where the maximum valid header size is 63 bytes or less.
004940  */
004941  static int vdbeRecordCompareInt(
004942    int nKey1, const void *pKey1, /* Left key */
004943    UnpackedRecord *pPKey2        /* Right key */
004944  ){
004945    const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
004946    int serial_type = ((const u8*)pKey1)[1];
004947    int res;
004948    u32 y;
004949    u64 x;
004950    i64 v;
004951    i64 lhs;
004952  
004953    vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
004954    assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
004955    switch( serial_type ){
004956      case 1: { /* 1-byte signed integer */
004957        lhs = ONE_BYTE_INT(aKey);
004958        testcase( lhs<0 );
004959        break;
004960      }
004961      case 2: { /* 2-byte signed integer */
004962        lhs = TWO_BYTE_INT(aKey);
004963        testcase( lhs<0 );
004964        break;
004965      }
004966      case 3: { /* 3-byte signed integer */
004967        lhs = THREE_BYTE_INT(aKey);
004968        testcase( lhs<0 );
004969        break;
004970      }
004971      case 4: { /* 4-byte signed integer */
004972        y = FOUR_BYTE_UINT(aKey);
004973        lhs = (i64)*(int*)&y;
004974        testcase( lhs<0 );
004975        break;
004976      }
004977      case 5: { /* 6-byte signed integer */
004978        lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
004979        testcase( lhs<0 );
004980        break;
004981      }
004982      case 6: { /* 8-byte signed integer */
004983        x = FOUR_BYTE_UINT(aKey);
004984        x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
004985        lhs = *(i64*)&x;
004986        testcase( lhs<0 );
004987        break;
004988      }
004989      case 8:
004990        lhs = 0;
004991        break;
004992      case 9:
004993        lhs = 1;
004994        break;
004995  
004996      /* This case could be removed without changing the results of running
004997      ** this code. Including it causes gcc to generate a faster switch
004998      ** statement (since the range of switch targets now starts at zero and
004999      ** is contiguous) but does not cause any duplicate code to be generated
005000      ** (as gcc is clever enough to combine the two like cases). Other
005001      ** compilers might be similar.  */
005002      case 0: case 7:
005003        return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
005004  
005005      default:
005006        return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
005007    }
005008  
005009    assert( pPKey2->u.i == pPKey2->aMem[0].u.i );
005010    v = pPKey2->u.i;
005011    if( v>lhs ){
005012      res = pPKey2->r1;
005013    }else if( v<lhs ){
005014      res = pPKey2->r2;
005015    }else if( pPKey2->nField>1 ){
005016      /* The first fields of the two keys are equal. Compare the trailing
005017      ** fields.  */
005018      res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
005019    }else{
005020      /* The first fields of the two keys are equal and there are no trailing
005021      ** fields. Return pPKey2->default_rc in this case. */
005022      res = pPKey2->default_rc;
005023      pPKey2->eqSeen = 1;
005024    }
005025  
005026    assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
005027    return res;
005028  }
005029  
005030  /*
005031  ** This function is an optimized version of sqlite3VdbeRecordCompare()
005032  ** that (a) the first field of pPKey2 is a string, that (b) the first field
005033  ** uses the collation sequence BINARY and (c) that the size-of-header varint
005034  ** at the start of (pKey1/nKey1) fits in a single byte.
005035  */
005036  static int vdbeRecordCompareString(
005037    int nKey1, const void *pKey1, /* Left key */
005038    UnpackedRecord *pPKey2        /* Right key */
005039  ){
005040    const u8 *aKey1 = (const u8*)pKey1;
005041    int serial_type;
005042    int res;
005043  
005044    assert( pPKey2->aMem[0].flags & MEM_Str );
005045    assert( pPKey2->aMem[0].n == pPKey2->n );
005046    assert( pPKey2->aMem[0].z == pPKey2->u.z );
005047    vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
005048    serial_type = (signed char)(aKey1[1]);
005049  
005050  vrcs_restart:
005051    if( serial_type<12 ){
005052      if( serial_type<0 ){
005053        sqlite3GetVarint32(&aKey1[1], (u32*)&serial_type);
005054        if( serial_type>=12 ) goto vrcs_restart;
005055        assert( CORRUPT_DB );
005056      }
005057      res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
005058    }else if( !(serial_type & 0x01) ){
005059      res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
005060    }else{
005061      int nCmp;
005062      int nStr;
005063      int szHdr = aKey1[0];
005064  
005065      nStr = (serial_type-12) / 2;
005066      if( (szHdr + nStr) > nKey1 ){
005067        pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
005068        return 0;    /* Corruption */
005069      }
005070      nCmp = MIN( pPKey2->n, nStr );
005071      res = memcmp(&aKey1[szHdr], pPKey2->u.z, nCmp);
005072  
005073      if( res>0 ){
005074        res = pPKey2->r2;
005075      }else if( res<0 ){
005076        res = pPKey2->r1;
005077      }else{
005078        res = nStr - pPKey2->n;
005079        if( res==0 ){
005080          if( pPKey2->nField>1 ){
005081            res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
005082          }else{
005083            res = pPKey2->default_rc;
005084            pPKey2->eqSeen = 1;
005085          }
005086        }else if( res>0 ){
005087          res = pPKey2->r2;
005088        }else{
005089          res = pPKey2->r1;
005090        }
005091      }
005092    }
005093  
005094    assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
005095         || CORRUPT_DB
005096         || pPKey2->pKeyInfo->db->mallocFailed
005097    );
005098    return res;
005099  }
005100  
005101  /*
005102  ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
005103  ** suitable for comparing serialized records to the unpacked record passed
005104  ** as the only argument.
005105  */
005106  RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
005107    /* varintRecordCompareInt() and varintRecordCompareString() both assume
005108    ** that the size-of-header varint that occurs at the start of each record
005109    ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
005110    ** also assumes that it is safe to overread a buffer by at least the
005111    ** maximum possible legal header size plus 8 bytes. Because there is
005112    ** guaranteed to be at least 74 (but not 136) bytes of padding following each
005113    ** buffer passed to varintRecordCompareInt() this makes it convenient to
005114    ** limit the size of the header to 64 bytes in cases where the first field
005115    ** is an integer.
005116    **
005117    ** The easiest way to enforce this limit is to consider only records with
005118    ** 13 fields or less. If the first field is an integer, the maximum legal
005119    ** header size is (12*5 + 1 + 1) bytes.  */
005120    if( p->pKeyInfo->nAllField<=13 ){
005121      int flags = p->aMem[0].flags;
005122      if( p->pKeyInfo->aSortFlags[0] ){
005123        if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){
005124          return sqlite3VdbeRecordCompare;
005125        }
005126        p->r1 = 1;
005127        p->r2 = -1;
005128      }else{
005129        p->r1 = -1;
005130        p->r2 = 1;
005131      }
005132      if( (flags & MEM_Int) ){
005133        p->u.i = p->aMem[0].u.i;
005134        return vdbeRecordCompareInt;
005135      }
005136      testcase( flags & MEM_Real );
005137      testcase( flags & MEM_Null );
005138      testcase( flags & MEM_Blob );
005139      if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0
005140       && p->pKeyInfo->aColl[0]==0
005141      ){
005142        assert( flags & MEM_Str );
005143        p->u.z = p->aMem[0].z;
005144        p->n = p->aMem[0].n;
005145        return vdbeRecordCompareString;
005146      }
005147    }
005148  
005149    return sqlite3VdbeRecordCompare;
005150  }
005151  
005152  /*
005153  ** pCur points at an index entry created using the OP_MakeRecord opcode.
005154  ** Read the rowid (the last field in the record) and store it in *rowid.
005155  ** Return SQLITE_OK if everything works, or an error code otherwise.
005156  **
005157  ** pCur might be pointing to text obtained from a corrupt database file.
005158  ** So the content cannot be trusted.  Do appropriate checks on the content.
005159  */
005160  int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
005161    i64 nCellKey = 0;
005162    int rc;
005163    u32 szHdr;        /* Size of the header */
005164    u32 typeRowid;    /* Serial type of the rowid */
005165    u32 lenRowid;     /* Size of the rowid */
005166    Mem m, v;
005167  
005168    /* Get the size of the index entry.  Only indices entries of less
005169    ** than 2GiB are support - anything large must be database corruption.
005170    ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
005171    ** this code can safely assume that nCellKey is 32-bits 
005172    */
005173    assert( sqlite3BtreeCursorIsValid(pCur) );
005174    nCellKey = sqlite3BtreePayloadSize(pCur);
005175    assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
005176  
005177    /* Read in the complete content of the index entry */
005178    sqlite3VdbeMemInit(&m, db, 0);
005179    rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
005180    if( rc ){
005181      return rc;
005182    }
005183  
005184    /* The index entry must begin with a header size */
005185    getVarint32NR((u8*)m.z, szHdr);
005186    testcase( szHdr==3 );
005187    testcase( szHdr==(u32)m.n );
005188    testcase( szHdr>0x7fffffff );
005189    assert( m.n>=0 );
005190    if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
005191      goto idx_rowid_corruption;
005192    }
005193  
005194    /* The last field of the index should be an integer - the ROWID.
005195    ** Verify that the last entry really is an integer. */
005196    getVarint32NR((u8*)&m.z[szHdr-1], typeRowid);
005197    testcase( typeRowid==1 );
005198    testcase( typeRowid==2 );
005199    testcase( typeRowid==3 );
005200    testcase( typeRowid==4 );
005201    testcase( typeRowid==5 );
005202    testcase( typeRowid==6 );
005203    testcase( typeRowid==8 );
005204    testcase( typeRowid==9 );
005205    if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
005206      goto idx_rowid_corruption;
005207    }
005208    lenRowid = sqlite3SmallTypeSizes[typeRowid];
005209    testcase( (u32)m.n==szHdr+lenRowid );
005210    if( unlikely((u32)m.n<szHdr+lenRowid) ){
005211      goto idx_rowid_corruption;
005212    }
005213  
005214    /* Fetch the integer off the end of the index record */
005215    sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
005216    *rowid = v.u.i;
005217    sqlite3VdbeMemReleaseMalloc(&m);
005218    return SQLITE_OK;
005219  
005220    /* Jump here if database corruption is detected after m has been
005221    ** allocated.  Free the m object and return SQLITE_CORRUPT. */
005222  idx_rowid_corruption:
005223    testcase( m.szMalloc!=0 );
005224    sqlite3VdbeMemReleaseMalloc(&m);
005225    return SQLITE_CORRUPT_BKPT;
005226  }
005227  
005228  /*
005229  ** Compare the key of the index entry that cursor pC is pointing to against
005230  ** the key string in pUnpacked.  Write into *pRes a number
005231  ** that is negative, zero, or positive if pC is less than, equal to,
005232  ** or greater than pUnpacked.  Return SQLITE_OK on success.
005233  **
005234  ** pUnpacked is either created without a rowid or is truncated so that it
005235  ** omits the rowid at the end.  The rowid at the end of the index entry
005236  ** is ignored as well.  Hence, this routine only compares the prefixes
005237  ** of the keys prior to the final rowid, not the entire key.
005238  */
005239  int sqlite3VdbeIdxKeyCompare(
005240    sqlite3 *db,                     /* Database connection */
005241    VdbeCursor *pC,                  /* The cursor to compare against */
005242    UnpackedRecord *pUnpacked,       /* Unpacked version of key */
005243    int *res                         /* Write the comparison result here */
005244  ){
005245    i64 nCellKey = 0;
005246    int rc;
005247    BtCursor *pCur;
005248    Mem m;
005249  
005250    assert( pC->eCurType==CURTYPE_BTREE );
005251    pCur = pC->uc.pCursor;
005252    assert( sqlite3BtreeCursorIsValid(pCur) );
005253    nCellKey = sqlite3BtreePayloadSize(pCur);
005254    /* nCellKey will always be between 0 and 0xffffffff because of the way
005255    ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
005256    if( nCellKey<=0 || nCellKey>0x7fffffff ){
005257      *res = 0;
005258      return SQLITE_CORRUPT_BKPT;
005259    }
005260    sqlite3VdbeMemInit(&m, db, 0);
005261    rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
005262    if( rc ){
005263      return rc;
005264    }
005265    *res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);
005266    sqlite3VdbeMemReleaseMalloc(&m);
005267    return SQLITE_OK;
005268  }
005269  
005270  /*
005271  ** This routine sets the value to be returned by subsequent calls to
005272  ** sqlite3_changes() on the database handle 'db'.
005273  */
005274  void sqlite3VdbeSetChanges(sqlite3 *db, i64 nChange){
005275    assert( sqlite3_mutex_held(db->mutex) );
005276    db->nChange = nChange;
005277    db->nTotalChange += nChange;
005278  }
005279  
005280  /*
005281  ** Set a flag in the vdbe to update the change counter when it is finalised
005282  ** or reset.
005283  */
005284  void sqlite3VdbeCountChanges(Vdbe *v){
005285    v->changeCntOn = 1;
005286  }
005287  
005288  /*
005289  ** Mark every prepared statement associated with a database connection
005290  ** as expired.
005291  **
005292  ** An expired statement means that recompilation of the statement is
005293  ** recommend.  Statements expire when things happen that make their
005294  ** programs obsolete.  Removing user-defined functions or collating
005295  ** sequences, or changing an authorization function are the types of
005296  ** things that make prepared statements obsolete.
005297  **
005298  ** If iCode is 1, then expiration is advisory.  The statement should
005299  ** be reprepared before being restarted, but if it is already running
005300  ** it is allowed to run to completion.
005301  **
005302  ** Internally, this function just sets the Vdbe.expired flag on all
005303  ** prepared statements.  The flag is set to 1 for an immediate expiration
005304  ** and set to 2 for an advisory expiration.
005305  */
005306  void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){
005307    Vdbe *p;
005308    for(p = db->pVdbe; p; p=p->pVNext){
005309      p->expired = iCode+1;
005310    }
005311  }
005312  
005313  /*
005314  ** Return the database associated with the Vdbe.
005315  */
005316  sqlite3 *sqlite3VdbeDb(Vdbe *v){
005317    return v->db;
005318  }
005319  
005320  /*
005321  ** Return the SQLITE_PREPARE flags for a Vdbe.
005322  */
005323  u8 sqlite3VdbePrepareFlags(Vdbe *v){
005324    return v->prepFlags;
005325  }
005326  
005327  /*
005328  ** Return a pointer to an sqlite3_value structure containing the value bound
005329  ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
005330  ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
005331  ** constants) to the value before returning it.
005332  **
005333  ** The returned value must be freed by the caller using sqlite3ValueFree().
005334  */
005335  sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
005336    assert( iVar>0 );
005337    if( v ){
005338      Mem *pMem = &v->aVar[iVar-1];
005339      assert( (v->db->flags & SQLITE_EnableQPSG)==0 
005340           || (v->db->mDbFlags & DBFLAG_InternalFunc)!=0 );
005341      if( 0==(pMem->flags & MEM_Null) ){
005342        sqlite3_value *pRet = sqlite3ValueNew(v->db);
005343        if( pRet ){
005344          sqlite3VdbeMemCopy((Mem *)pRet, pMem);
005345          sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
005346        }
005347        return pRet;
005348      }
005349    }
005350    return 0;
005351  }
005352  
005353  /*
005354  ** Configure SQL variable iVar so that binding a new value to it signals
005355  ** to sqlite3_reoptimize() that re-preparing the statement may result
005356  ** in a better query plan.
005357  */
005358  void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
005359    assert( iVar>0 );
005360    assert( (v->db->flags & SQLITE_EnableQPSG)==0 
005361         || (v->db->mDbFlags & DBFLAG_InternalFunc)!=0 );
005362    if( iVar>=32 ){
005363      v->expmask |= 0x80000000;
005364    }else{
005365      v->expmask |= ((u32)1 << (iVar-1));
005366    }
005367  }
005368  
005369  /*
005370  ** Cause a function to throw an error if it was call from OP_PureFunc
005371  ** rather than OP_Function.
005372  **
005373  ** OP_PureFunc means that the function must be deterministic, and should
005374  ** throw an error if it is given inputs that would make it non-deterministic.
005375  ** This routine is invoked by date/time functions that use non-deterministic
005376  ** features such as 'now'.
005377  */
005378  int sqlite3NotPureFunc(sqlite3_context *pCtx){
005379    const VdbeOp *pOp;
005380  #ifdef SQLITE_ENABLE_STAT4
005381    if( pCtx->pVdbe==0 ) return 1;
005382  #endif
005383    pOp = pCtx->pVdbe->aOp + pCtx->iOp;
005384    if( pOp->opcode==OP_PureFunc ){
005385      const char *zContext;
005386      char *zMsg;
005387      if( pOp->p5 & NC_IsCheck ){
005388        zContext = "a CHECK constraint";
005389      }else if( pOp->p5 & NC_GenCol ){
005390        zContext = "a generated column";
005391      }else{
005392        zContext = "an index";
005393      }
005394      zMsg = sqlite3_mprintf("non-deterministic use of %s() in %s",
005395                             pCtx->pFunc->zName, zContext);
005396      sqlite3_result_error(pCtx, zMsg, -1);
005397      sqlite3_free(zMsg);
005398      return 0;
005399    }
005400    return 1;
005401  }
005402  
005403  #if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
005404  /*
005405  ** This Walker callback is used to help verify that calls to
005406  ** sqlite3BtreeCursorHint() with opcode BTREE_HINT_RANGE have
005407  ** byte-code register values correctly initialized.
005408  */
005409  int sqlite3CursorRangeHintExprCheck(Walker *pWalker, Expr *pExpr){
005410    if( pExpr->op==TK_REGISTER ){
005411      assert( (pWalker->u.aMem[pExpr->iTable].flags & MEM_Undefined)==0 );
005412    }
005413    return WRC_Continue;
005414  }
005415  #endif /* SQLITE_ENABLE_CURSOR_HINTS && SQLITE_DEBUG */
005416  
005417  #ifndef SQLITE_OMIT_VIRTUALTABLE
005418  /*
005419  ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
005420  ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
005421  ** in memory obtained from sqlite3DbMalloc).
005422  */
005423  void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
005424    if( pVtab->zErrMsg ){
005425      sqlite3 *db = p->db;
005426      sqlite3DbFree(db, p->zErrMsg);
005427      p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
005428      sqlite3_free(pVtab->zErrMsg);
005429      pVtab->zErrMsg = 0;
005430    }
005431  }
005432  #endif /* SQLITE_OMIT_VIRTUALTABLE */
005433  
005434  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
005435  
005436  /*
005437  ** If the second argument is not NULL, release any allocations associated
005438  ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
005439  ** structure itself, using sqlite3DbFree().
005440  **
005441  ** This function is used to free UnpackedRecord structures allocated by
005442  ** the vdbeUnpackRecord() function found in vdbeapi.c.
005443  */
005444  static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
005445    assert( db!=0 );
005446    if( p ){
005447      int i;
005448      for(i=0; i<nField; i++){
005449        Mem *pMem = &p->aMem[i];
005450        if( pMem->zMalloc ) sqlite3VdbeMemReleaseMalloc(pMem);
005451      }
005452      sqlite3DbNNFreeNN(db, p);
005453    }
005454  }
005455  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
005456  
005457  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
005458  /*
005459  ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
005460  ** then cursor passed as the second argument should point to the row about
005461  ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
005462  ** the required value will be read from the row the cursor points to.
005463  */
005464  void sqlite3VdbePreUpdateHook(
005465    Vdbe *v,                        /* Vdbe pre-update hook is invoked by */
005466    VdbeCursor *pCsr,               /* Cursor to grab old.* values from */
005467    int op,                         /* SQLITE_INSERT, UPDATE or DELETE */
005468    const char *zDb,                /* Database name */
005469    Table *pTab,                    /* Modified table */
005470    i64 iKey1,                      /* Initial key value */
005471    int iReg,                       /* Register for new.* record */
005472    int iBlobWrite
005473  ){
005474    sqlite3 *db = v->db;
005475    i64 iKey2;
005476    PreUpdate preupdate;
005477    const char *zTbl = pTab->zName;
005478    static const u8 fakeSortOrder = 0;
005479  #ifdef SQLITE_DEBUG
005480    int nRealCol;
005481    if( pTab->tabFlags & TF_WithoutRowid ){
005482      nRealCol = sqlite3PrimaryKeyIndex(pTab)->nColumn;
005483    }else if( pTab->tabFlags & TF_HasVirtual ){
005484      nRealCol = pTab->nNVCol;
005485    }else{
005486      nRealCol = pTab->nCol;
005487    }
005488  #endif
005489  
005490    assert( db->pPreUpdate==0 );
005491    memset(&preupdate, 0, sizeof(PreUpdate));
005492    if( HasRowid(pTab)==0 ){
005493      iKey1 = iKey2 = 0;
005494      preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
005495    }else{
005496      if( op==SQLITE_UPDATE ){
005497        iKey2 = v->aMem[iReg].u.i;
005498      }else{
005499        iKey2 = iKey1;
005500      }
005501    }
005502  
005503    assert( pCsr!=0 );
005504    assert( pCsr->eCurType==CURTYPE_BTREE );
005505    assert( pCsr->nField==nRealCol
005506         || (pCsr->nField==nRealCol+1 && op==SQLITE_DELETE && iReg==-1)
005507    );
005508  
005509    preupdate.v = v;
005510    preupdate.pCsr = pCsr;
005511    preupdate.op = op;
005512    preupdate.iNewReg = iReg;
005513    preupdate.keyinfo.db = db;
005514    preupdate.keyinfo.enc = ENC(db);
005515    preupdate.keyinfo.nKeyField = pTab->nCol;
005516    preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder;
005517    preupdate.iKey1 = iKey1;
005518    preupdate.iKey2 = iKey2;
005519    preupdate.pTab = pTab;
005520    preupdate.iBlobWrite = iBlobWrite;
005521  
005522    db->pPreUpdate = &preupdate;
005523    db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
005524    db->pPreUpdate = 0;
005525    sqlite3DbFree(db, preupdate.aRecord);
005526    vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
005527    vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
005528    if( preupdate.aNew ){
005529      int i;
005530      for(i=0; i<pCsr->nField; i++){
005531        sqlite3VdbeMemRelease(&preupdate.aNew[i]);
005532      }
005533      sqlite3DbNNFreeNN(db, preupdate.aNew);
005534    }
005535  }
005536  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */