Annotation of embedaddon/sqlite3/src/vdbeaux.c, revision 1.1

1.1     ! misho       1: /*
        !             2: ** 2003 September 6
        !             3: **
        !             4: ** The author disclaims copyright to this source code.  In place of
        !             5: ** a legal notice, here is a blessing:
        !             6: **
        !             7: **    May you do good and not evil.
        !             8: **    May you find forgiveness for yourself and forgive others.
        !             9: **    May you share freely, never taking more than you give.
        !            10: **
        !            11: *************************************************************************
        !            12: ** This file contains code used for creating, destroying, and populating
        !            13: ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
        !            14: ** to version 2.8.7, all this code was combined into the vdbe.c source file.
        !            15: ** But that file was getting too big so this subroutines were split out.
        !            16: */
        !            17: #include "sqliteInt.h"
        !            18: #include "vdbeInt.h"
        !            19: 
        !            20: 
        !            21: 
        !            22: /*
        !            23: ** When debugging the code generator in a symbolic debugger, one can
        !            24: ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
        !            25: ** as they are added to the instruction stream.
        !            26: */
        !            27: #ifdef SQLITE_DEBUG
        !            28: int sqlite3VdbeAddopTrace = 0;
        !            29: #endif
        !            30: 
        !            31: 
        !            32: /*
        !            33: ** Create a new virtual database engine.
        !            34: */
        !            35: Vdbe *sqlite3VdbeCreate(sqlite3 *db){
        !            36:   Vdbe *p;
        !            37:   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
        !            38:   if( p==0 ) return 0;
        !            39:   p->db = db;
        !            40:   if( db->pVdbe ){
        !            41:     db->pVdbe->pPrev = p;
        !            42:   }
        !            43:   p->pNext = db->pVdbe;
        !            44:   p->pPrev = 0;
        !            45:   db->pVdbe = p;
        !            46:   p->magic = VDBE_MAGIC_INIT;
        !            47:   return p;
        !            48: }
        !            49: 
        !            50: /*
        !            51: ** Remember the SQL string for a prepared statement.
        !            52: */
        !            53: void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
        !            54:   assert( isPrepareV2==1 || isPrepareV2==0 );
        !            55:   if( p==0 ) return;
        !            56: #ifdef SQLITE_OMIT_TRACE
        !            57:   if( !isPrepareV2 ) return;
        !            58: #endif
        !            59:   assert( p->zSql==0 );
        !            60:   p->zSql = sqlite3DbStrNDup(p->db, z, n);
        !            61:   p->isPrepareV2 = (u8)isPrepareV2;
        !            62: }
        !            63: 
        !            64: /*
        !            65: ** Return the SQL associated with a prepared statement
        !            66: */
        !            67: const char *sqlite3_sql(sqlite3_stmt *pStmt){
        !            68:   Vdbe *p = (Vdbe *)pStmt;
        !            69:   return (p && p->isPrepareV2) ? p->zSql : 0;
        !            70: }
        !            71: 
        !            72: /*
        !            73: ** Swap all content between two VDBE structures.
        !            74: */
        !            75: void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
        !            76:   Vdbe tmp, *pTmp;
        !            77:   char *zTmp;
        !            78:   tmp = *pA;
        !            79:   *pA = *pB;
        !            80:   *pB = tmp;
        !            81:   pTmp = pA->pNext;
        !            82:   pA->pNext = pB->pNext;
        !            83:   pB->pNext = pTmp;
        !            84:   pTmp = pA->pPrev;
        !            85:   pA->pPrev = pB->pPrev;
        !            86:   pB->pPrev = pTmp;
        !            87:   zTmp = pA->zSql;
        !            88:   pA->zSql = pB->zSql;
        !            89:   pB->zSql = zTmp;
        !            90:   pB->isPrepareV2 = pA->isPrepareV2;
        !            91: }
        !            92: 
        !            93: #ifdef SQLITE_DEBUG
        !            94: /*
        !            95: ** Turn tracing on or off
        !            96: */
        !            97: void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
        !            98:   p->trace = trace;
        !            99: }
        !           100: #endif
        !           101: 
        !           102: /*
        !           103: ** Resize the Vdbe.aOp array so that it is at least one op larger than 
        !           104: ** it was.
        !           105: **
        !           106: ** If an out-of-memory error occurs while resizing the array, return
        !           107: ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
        !           108: ** unchanged (this is so that any opcodes already allocated can be 
        !           109: ** correctly deallocated along with the rest of the Vdbe).
        !           110: */
        !           111: static int growOpArray(Vdbe *p){
        !           112:   VdbeOp *pNew;
        !           113:   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
        !           114:   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
        !           115:   if( pNew ){
        !           116:     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
        !           117:     p->aOp = pNew;
        !           118:   }
        !           119:   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
        !           120: }
        !           121: 
        !           122: /*
        !           123: ** Add a new instruction to the list of instructions current in the
        !           124: ** VDBE.  Return the address of the new instruction.
        !           125: **
        !           126: ** Parameters:
        !           127: **
        !           128: **    p               Pointer to the VDBE
        !           129: **
        !           130: **    op              The opcode for this instruction
        !           131: **
        !           132: **    p1, p2, p3      Operands
        !           133: **
        !           134: ** Use the sqlite3VdbeResolveLabel() function to fix an address and
        !           135: ** the sqlite3VdbeChangeP4() function to change the value of the P4
        !           136: ** operand.
        !           137: */
        !           138: int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
        !           139:   int i;
        !           140:   VdbeOp *pOp;
        !           141: 
        !           142:   i = p->nOp;
        !           143:   assert( p->magic==VDBE_MAGIC_INIT );
        !           144:   assert( op>0 && op<0xff );
        !           145:   if( p->nOpAlloc<=i ){
        !           146:     if( growOpArray(p) ){
        !           147:       return 1;
        !           148:     }
        !           149:   }
        !           150:   p->nOp++;
        !           151:   pOp = &p->aOp[i];
        !           152:   pOp->opcode = (u8)op;
        !           153:   pOp->p5 = 0;
        !           154:   pOp->p1 = p1;
        !           155:   pOp->p2 = p2;
        !           156:   pOp->p3 = p3;
        !           157:   pOp->p4.p = 0;
        !           158:   pOp->p4type = P4_NOTUSED;
        !           159: #ifdef SQLITE_DEBUG
        !           160:   pOp->zComment = 0;
        !           161:   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
        !           162: #endif
        !           163: #ifdef VDBE_PROFILE
        !           164:   pOp->cycles = 0;
        !           165:   pOp->cnt = 0;
        !           166: #endif
        !           167:   return i;
        !           168: }
        !           169: int sqlite3VdbeAddOp0(Vdbe *p, int op){
        !           170:   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
        !           171: }
        !           172: int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
        !           173:   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
        !           174: }
        !           175: int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
        !           176:   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
        !           177: }
        !           178: 
        !           179: 
        !           180: /*
        !           181: ** Add an opcode that includes the p4 value as a pointer.
        !           182: */
        !           183: int sqlite3VdbeAddOp4(
        !           184:   Vdbe *p,            /* Add the opcode to this VM */
        !           185:   int op,             /* The new opcode */
        !           186:   int p1,             /* The P1 operand */
        !           187:   int p2,             /* The P2 operand */
        !           188:   int p3,             /* The P3 operand */
        !           189:   const char *zP4,    /* The P4 operand */
        !           190:   int p4type          /* P4 operand type */
        !           191: ){
        !           192:   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
        !           193:   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
        !           194:   return addr;
        !           195: }
        !           196: 
        !           197: /*
        !           198: ** Add an OP_ParseSchema opcode.  This routine is broken out from
        !           199: ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
        !           200: ** as having been used.
        !           201: **
        !           202: ** The zWhere string must have been obtained from sqlite3_malloc().
        !           203: ** This routine will take ownership of the allocated memory.
        !           204: */
        !           205: void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
        !           206:   int j;
        !           207:   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
        !           208:   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
        !           209:   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
        !           210: }
        !           211: 
        !           212: /*
        !           213: ** Add an opcode that includes the p4 value as an integer.
        !           214: */
        !           215: int sqlite3VdbeAddOp4Int(
        !           216:   Vdbe *p,            /* Add the opcode to this VM */
        !           217:   int op,             /* The new opcode */
        !           218:   int p1,             /* The P1 operand */
        !           219:   int p2,             /* The P2 operand */
        !           220:   int p3,             /* The P3 operand */
        !           221:   int p4              /* The P4 operand as an integer */
        !           222: ){
        !           223:   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
        !           224:   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
        !           225:   return addr;
        !           226: }
        !           227: 
        !           228: /*
        !           229: ** Create a new symbolic label for an instruction that has yet to be
        !           230: ** coded.  The symbolic label is really just a negative number.  The
        !           231: ** label can be used as the P2 value of an operation.  Later, when
        !           232: ** the label is resolved to a specific address, the VDBE will scan
        !           233: ** through its operation list and change all values of P2 which match
        !           234: ** the label into the resolved address.
        !           235: **
        !           236: ** The VDBE knows that a P2 value is a label because labels are
        !           237: ** always negative and P2 values are suppose to be non-negative.
        !           238: ** Hence, a negative P2 value is a label that has yet to be resolved.
        !           239: **
        !           240: ** Zero is returned if a malloc() fails.
        !           241: */
        !           242: int sqlite3VdbeMakeLabel(Vdbe *p){
        !           243:   int i;
        !           244:   i = p->nLabel++;
        !           245:   assert( p->magic==VDBE_MAGIC_INIT );
        !           246:   if( i>=p->nLabelAlloc ){
        !           247:     int n = p->nLabelAlloc*2 + 5;
        !           248:     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
        !           249:                                        n*sizeof(p->aLabel[0]));
        !           250:     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
        !           251:   }
        !           252:   if( p->aLabel ){
        !           253:     p->aLabel[i] = -1;
        !           254:   }
        !           255:   return -1-i;
        !           256: }
        !           257: 
        !           258: /*
        !           259: ** Resolve label "x" to be the address of the next instruction to
        !           260: ** be inserted.  The parameter "x" must have been obtained from
        !           261: ** a prior call to sqlite3VdbeMakeLabel().
        !           262: */
        !           263: void sqlite3VdbeResolveLabel(Vdbe *p, int x){
        !           264:   int j = -1-x;
        !           265:   assert( p->magic==VDBE_MAGIC_INIT );
        !           266:   assert( j>=0 && j<p->nLabel );
        !           267:   if( p->aLabel ){
        !           268:     p->aLabel[j] = p->nOp;
        !           269:   }
        !           270: }
        !           271: 
        !           272: /*
        !           273: ** Mark the VDBE as one that can only be run one time.
        !           274: */
        !           275: void sqlite3VdbeRunOnlyOnce(Vdbe *p){
        !           276:   p->runOnlyOnce = 1;
        !           277: }
        !           278: 
        !           279: #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
        !           280: 
        !           281: /*
        !           282: ** The following type and function are used to iterate through all opcodes
        !           283: ** in a Vdbe main program and each of the sub-programs (triggers) it may 
        !           284: ** invoke directly or indirectly. It should be used as follows:
        !           285: **
        !           286: **   Op *pOp;
        !           287: **   VdbeOpIter sIter;
        !           288: **
        !           289: **   memset(&sIter, 0, sizeof(sIter));
        !           290: **   sIter.v = v;                            // v is of type Vdbe* 
        !           291: **   while( (pOp = opIterNext(&sIter)) ){
        !           292: **     // Do something with pOp
        !           293: **   }
        !           294: **   sqlite3DbFree(v->db, sIter.apSub);
        !           295: ** 
        !           296: */
        !           297: typedef struct VdbeOpIter VdbeOpIter;
        !           298: struct VdbeOpIter {
        !           299:   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
        !           300:   SubProgram **apSub;        /* Array of subprograms */
        !           301:   int nSub;                  /* Number of entries in apSub */
        !           302:   int iAddr;                 /* Address of next instruction to return */
        !           303:   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
        !           304: };
        !           305: static Op *opIterNext(VdbeOpIter *p){
        !           306:   Vdbe *v = p->v;
        !           307:   Op *pRet = 0;
        !           308:   Op *aOp;
        !           309:   int nOp;
        !           310: 
        !           311:   if( p->iSub<=p->nSub ){
        !           312: 
        !           313:     if( p->iSub==0 ){
        !           314:       aOp = v->aOp;
        !           315:       nOp = v->nOp;
        !           316:     }else{
        !           317:       aOp = p->apSub[p->iSub-1]->aOp;
        !           318:       nOp = p->apSub[p->iSub-1]->nOp;
        !           319:     }
        !           320:     assert( p->iAddr<nOp );
        !           321: 
        !           322:     pRet = &aOp[p->iAddr];
        !           323:     p->iAddr++;
        !           324:     if( p->iAddr==nOp ){
        !           325:       p->iSub++;
        !           326:       p->iAddr = 0;
        !           327:     }
        !           328:   
        !           329:     if( pRet->p4type==P4_SUBPROGRAM ){
        !           330:       int nByte = (p->nSub+1)*sizeof(SubProgram*);
        !           331:       int j;
        !           332:       for(j=0; j<p->nSub; j++){
        !           333:         if( p->apSub[j]==pRet->p4.pProgram ) break;
        !           334:       }
        !           335:       if( j==p->nSub ){
        !           336:         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
        !           337:         if( !p->apSub ){
        !           338:           pRet = 0;
        !           339:         }else{
        !           340:           p->apSub[p->nSub++] = pRet->p4.pProgram;
        !           341:         }
        !           342:       }
        !           343:     }
        !           344:   }
        !           345: 
        !           346:   return pRet;
        !           347: }
        !           348: 
        !           349: /*
        !           350: ** Check if the program stored in the VM associated with pParse may
        !           351: ** throw an ABORT exception (causing the statement, but not entire transaction
        !           352: ** to be rolled back). This condition is true if the main program or any
        !           353: ** sub-programs contains any of the following:
        !           354: **
        !           355: **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
        !           356: **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
        !           357: **   *  OP_Destroy
        !           358: **   *  OP_VUpdate
        !           359: **   *  OP_VRename
        !           360: **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
        !           361: **
        !           362: ** Then check that the value of Parse.mayAbort is true if an
        !           363: ** ABORT may be thrown, or false otherwise. Return true if it does
        !           364: ** match, or false otherwise. This function is intended to be used as
        !           365: ** part of an assert statement in the compiler. Similar to:
        !           366: **
        !           367: **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
        !           368: */
        !           369: int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
        !           370:   int hasAbort = 0;
        !           371:   Op *pOp;
        !           372:   VdbeOpIter sIter;
        !           373:   memset(&sIter, 0, sizeof(sIter));
        !           374:   sIter.v = v;
        !           375: 
        !           376:   while( (pOp = opIterNext(&sIter))!=0 ){
        !           377:     int opcode = pOp->opcode;
        !           378:     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
        !           379: #ifndef SQLITE_OMIT_FOREIGN_KEY
        !           380:      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
        !           381: #endif
        !           382:      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
        !           383:       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
        !           384:     ){
        !           385:       hasAbort = 1;
        !           386:       break;
        !           387:     }
        !           388:   }
        !           389:   sqlite3DbFree(v->db, sIter.apSub);
        !           390: 
        !           391:   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
        !           392:   ** If malloc failed, then the while() loop above may not have iterated
        !           393:   ** through all opcodes and hasAbort may be set incorrectly. Return
        !           394:   ** true for this case to prevent the assert() in the callers frame
        !           395:   ** from failing.  */
        !           396:   return ( v->db->mallocFailed || hasAbort==mayAbort );
        !           397: }
        !           398: #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
        !           399: 
        !           400: /*
        !           401: ** Loop through the program looking for P2 values that are negative
        !           402: ** on jump instructions.  Each such value is a label.  Resolve the
        !           403: ** label by setting the P2 value to its correct non-zero value.
        !           404: **
        !           405: ** This routine is called once after all opcodes have been inserted.
        !           406: **
        !           407: ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
        !           408: ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
        !           409: ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
        !           410: **
        !           411: ** The Op.opflags field is set on all opcodes.
        !           412: */
        !           413: static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
        !           414:   int i;
        !           415:   int nMaxArgs = *pMaxFuncArgs;
        !           416:   Op *pOp;
        !           417:   int *aLabel = p->aLabel;
        !           418:   p->readOnly = 1;
        !           419:   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
        !           420:     u8 opcode = pOp->opcode;
        !           421: 
        !           422:     pOp->opflags = sqlite3OpcodeProperty[opcode];
        !           423:     if( opcode==OP_Function || opcode==OP_AggStep ){
        !           424:       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
        !           425:     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
        !           426:       p->readOnly = 0;
        !           427: #ifndef SQLITE_OMIT_VIRTUALTABLE
        !           428:     }else if( opcode==OP_VUpdate ){
        !           429:       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
        !           430:     }else if( opcode==OP_VFilter ){
        !           431:       int n;
        !           432:       assert( p->nOp - i >= 3 );
        !           433:       assert( pOp[-1].opcode==OP_Integer );
        !           434:       n = pOp[-1].p1;
        !           435:       if( n>nMaxArgs ) nMaxArgs = n;
        !           436: #endif
        !           437:     }else if( opcode==OP_Next || opcode==OP_SorterNext ){
        !           438:       pOp->p4.xAdvance = sqlite3BtreeNext;
        !           439:       pOp->p4type = P4_ADVANCE;
        !           440:     }else if( opcode==OP_Prev ){
        !           441:       pOp->p4.xAdvance = sqlite3BtreePrevious;
        !           442:       pOp->p4type = P4_ADVANCE;
        !           443:     }
        !           444: 
        !           445:     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
        !           446:       assert( -1-pOp->p2<p->nLabel );
        !           447:       pOp->p2 = aLabel[-1-pOp->p2];
        !           448:     }
        !           449:   }
        !           450:   sqlite3DbFree(p->db, p->aLabel);
        !           451:   p->aLabel = 0;
        !           452: 
        !           453:   *pMaxFuncArgs = nMaxArgs;
        !           454: }
        !           455: 
        !           456: /*
        !           457: ** Return the address of the next instruction to be inserted.
        !           458: */
        !           459: int sqlite3VdbeCurrentAddr(Vdbe *p){
        !           460:   assert( p->magic==VDBE_MAGIC_INIT );
        !           461:   return p->nOp;
        !           462: }
        !           463: 
        !           464: /*
        !           465: ** This function returns a pointer to the array of opcodes associated with
        !           466: ** the Vdbe passed as the first argument. It is the callers responsibility
        !           467: ** to arrange for the returned array to be eventually freed using the 
        !           468: ** vdbeFreeOpArray() function.
        !           469: **
        !           470: ** Before returning, *pnOp is set to the number of entries in the returned
        !           471: ** array. Also, *pnMaxArg is set to the larger of its current value and 
        !           472: ** the number of entries in the Vdbe.apArg[] array required to execute the 
        !           473: ** returned program.
        !           474: */
        !           475: VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
        !           476:   VdbeOp *aOp = p->aOp;
        !           477:   assert( aOp && !p->db->mallocFailed );
        !           478: 
        !           479:   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
        !           480:   assert( p->btreeMask==0 );
        !           481: 
        !           482:   resolveP2Values(p, pnMaxArg);
        !           483:   *pnOp = p->nOp;
        !           484:   p->aOp = 0;
        !           485:   return aOp;
        !           486: }
        !           487: 
        !           488: /*
        !           489: ** Add a whole list of operations to the operation stack.  Return the
        !           490: ** address of the first operation added.
        !           491: */
        !           492: int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
        !           493:   int addr;
        !           494:   assert( p->magic==VDBE_MAGIC_INIT );
        !           495:   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
        !           496:     return 0;
        !           497:   }
        !           498:   addr = p->nOp;
        !           499:   if( ALWAYS(nOp>0) ){
        !           500:     int i;
        !           501:     VdbeOpList const *pIn = aOp;
        !           502:     for(i=0; i<nOp; i++, pIn++){
        !           503:       int p2 = pIn->p2;
        !           504:       VdbeOp *pOut = &p->aOp[i+addr];
        !           505:       pOut->opcode = pIn->opcode;
        !           506:       pOut->p1 = pIn->p1;
        !           507:       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
        !           508:         pOut->p2 = addr + ADDR(p2);
        !           509:       }else{
        !           510:         pOut->p2 = p2;
        !           511:       }
        !           512:       pOut->p3 = pIn->p3;
        !           513:       pOut->p4type = P4_NOTUSED;
        !           514:       pOut->p4.p = 0;
        !           515:       pOut->p5 = 0;
        !           516: #ifdef SQLITE_DEBUG
        !           517:       pOut->zComment = 0;
        !           518:       if( sqlite3VdbeAddopTrace ){
        !           519:         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
        !           520:       }
        !           521: #endif
        !           522:     }
        !           523:     p->nOp += nOp;
        !           524:   }
        !           525:   return addr;
        !           526: }
        !           527: 
        !           528: /*
        !           529: ** Change the value of the P1 operand for a specific instruction.
        !           530: ** This routine is useful when a large program is loaded from a
        !           531: ** static array using sqlite3VdbeAddOpList but we want to make a
        !           532: ** few minor changes to the program.
        !           533: */
        !           534: void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
        !           535:   assert( p!=0 );
        !           536:   if( ((u32)p->nOp)>addr ){
        !           537:     p->aOp[addr].p1 = val;
        !           538:   }
        !           539: }
        !           540: 
        !           541: /*
        !           542: ** Change the value of the P2 operand for a specific instruction.
        !           543: ** This routine is useful for setting a jump destination.
        !           544: */
        !           545: void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
        !           546:   assert( p!=0 );
        !           547:   if( ((u32)p->nOp)>addr ){
        !           548:     p->aOp[addr].p2 = val;
        !           549:   }
        !           550: }
        !           551: 
        !           552: /*
        !           553: ** Change the value of the P3 operand for a specific instruction.
        !           554: */
        !           555: void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
        !           556:   assert( p!=0 );
        !           557:   if( ((u32)p->nOp)>addr ){
        !           558:     p->aOp[addr].p3 = val;
        !           559:   }
        !           560: }
        !           561: 
        !           562: /*
        !           563: ** Change the value of the P5 operand for the most recently
        !           564: ** added operation.
        !           565: */
        !           566: void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
        !           567:   assert( p!=0 );
        !           568:   if( p->aOp ){
        !           569:     assert( p->nOp>0 );
        !           570:     p->aOp[p->nOp-1].p5 = val;
        !           571:   }
        !           572: }
        !           573: 
        !           574: /*
        !           575: ** Change the P2 operand of instruction addr so that it points to
        !           576: ** the address of the next instruction to be coded.
        !           577: */
        !           578: void sqlite3VdbeJumpHere(Vdbe *p, int addr){
        !           579:   assert( addr>=0 || p->db->mallocFailed );
        !           580:   if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
        !           581: }
        !           582: 
        !           583: 
        !           584: /*
        !           585: ** If the input FuncDef structure is ephemeral, then free it.  If
        !           586: ** the FuncDef is not ephermal, then do nothing.
        !           587: */
        !           588: static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
        !           589:   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
        !           590:     sqlite3DbFree(db, pDef);
        !           591:   }
        !           592: }
        !           593: 
        !           594: static void vdbeFreeOpArray(sqlite3 *, Op *, int);
        !           595: 
        !           596: /*
        !           597: ** Delete a P4 value if necessary.
        !           598: */
        !           599: static void freeP4(sqlite3 *db, int p4type, void *p4){
        !           600:   if( p4 ){
        !           601:     assert( db );
        !           602:     switch( p4type ){
        !           603:       case P4_REAL:
        !           604:       case P4_INT64:
        !           605:       case P4_DYNAMIC:
        !           606:       case P4_KEYINFO:
        !           607:       case P4_INTARRAY:
        !           608:       case P4_KEYINFO_HANDOFF: {
        !           609:         sqlite3DbFree(db, p4);
        !           610:         break;
        !           611:       }
        !           612:       case P4_MPRINTF: {
        !           613:         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
        !           614:         break;
        !           615:       }
        !           616:       case P4_VDBEFUNC: {
        !           617:         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
        !           618:         freeEphemeralFunction(db, pVdbeFunc->pFunc);
        !           619:         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
        !           620:         sqlite3DbFree(db, pVdbeFunc);
        !           621:         break;
        !           622:       }
        !           623:       case P4_FUNCDEF: {
        !           624:         freeEphemeralFunction(db, (FuncDef*)p4);
        !           625:         break;
        !           626:       }
        !           627:       case P4_MEM: {
        !           628:         if( db->pnBytesFreed==0 ){
        !           629:           sqlite3ValueFree((sqlite3_value*)p4);
        !           630:         }else{
        !           631:           Mem *p = (Mem*)p4;
        !           632:           sqlite3DbFree(db, p->zMalloc);
        !           633:           sqlite3DbFree(db, p);
        !           634:         }
        !           635:         break;
        !           636:       }
        !           637:       case P4_VTAB : {
        !           638:         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
        !           639:         break;
        !           640:       }
        !           641:     }
        !           642:   }
        !           643: }
        !           644: 
        !           645: /*
        !           646: ** Free the space allocated for aOp and any p4 values allocated for the
        !           647: ** opcodes contained within. If aOp is not NULL it is assumed to contain 
        !           648: ** nOp entries. 
        !           649: */
        !           650: static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
        !           651:   if( aOp ){
        !           652:     Op *pOp;
        !           653:     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
        !           654:       freeP4(db, pOp->p4type, pOp->p4.p);
        !           655: #ifdef SQLITE_DEBUG
        !           656:       sqlite3DbFree(db, pOp->zComment);
        !           657: #endif     
        !           658:     }
        !           659:   }
        !           660:   sqlite3DbFree(db, aOp);
        !           661: }
        !           662: 
        !           663: /*
        !           664: ** Link the SubProgram object passed as the second argument into the linked
        !           665: ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
        !           666: ** objects when the VM is no longer required.
        !           667: */
        !           668: void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
        !           669:   p->pNext = pVdbe->pProgram;
        !           670:   pVdbe->pProgram = p;
        !           671: }
        !           672: 
        !           673: /*
        !           674: ** Change the opcode at addr into OP_Noop
        !           675: */
        !           676: void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
        !           677:   if( p->aOp ){
        !           678:     VdbeOp *pOp = &p->aOp[addr];
        !           679:     sqlite3 *db = p->db;
        !           680:     freeP4(db, pOp->p4type, pOp->p4.p);
        !           681:     memset(pOp, 0, sizeof(pOp[0]));
        !           682:     pOp->opcode = OP_Noop;
        !           683:   }
        !           684: }
        !           685: 
        !           686: /*
        !           687: ** Change the value of the P4 operand for a specific instruction.
        !           688: ** This routine is useful when a large program is loaded from a
        !           689: ** static array using sqlite3VdbeAddOpList but we want to make a
        !           690: ** few minor changes to the program.
        !           691: **
        !           692: ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
        !           693: ** the string is made into memory obtained from sqlite3_malloc().
        !           694: ** A value of n==0 means copy bytes of zP4 up to and including the
        !           695: ** first null byte.  If n>0 then copy n+1 bytes of zP4.
        !           696: **
        !           697: ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
        !           698: ** A copy is made of the KeyInfo structure into memory obtained from
        !           699: ** sqlite3_malloc, to be freed when the Vdbe is finalized.
        !           700: ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
        !           701: ** stored in memory that the caller has obtained from sqlite3_malloc. The 
        !           702: ** caller should not free the allocation, it will be freed when the Vdbe is
        !           703: ** finalized.
        !           704: ** 
        !           705: ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
        !           706: ** to a string or structure that is guaranteed to exist for the lifetime of
        !           707: ** the Vdbe. In these cases we can just copy the pointer.
        !           708: **
        !           709: ** If addr<0 then change P4 on the most recently inserted instruction.
        !           710: */
        !           711: void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
        !           712:   Op *pOp;
        !           713:   sqlite3 *db;
        !           714:   assert( p!=0 );
        !           715:   db = p->db;
        !           716:   assert( p->magic==VDBE_MAGIC_INIT );
        !           717:   if( p->aOp==0 || db->mallocFailed ){
        !           718:     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
        !           719:       freeP4(db, n, (void*)*(char**)&zP4);
        !           720:     }
        !           721:     return;
        !           722:   }
        !           723:   assert( p->nOp>0 );
        !           724:   assert( addr<p->nOp );
        !           725:   if( addr<0 ){
        !           726:     addr = p->nOp - 1;
        !           727:   }
        !           728:   pOp = &p->aOp[addr];
        !           729:   freeP4(db, pOp->p4type, pOp->p4.p);
        !           730:   pOp->p4.p = 0;
        !           731:   if( n==P4_INT32 ){
        !           732:     /* Note: this cast is safe, because the origin data point was an int
        !           733:     ** that was cast to a (const char *). */
        !           734:     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
        !           735:     pOp->p4type = P4_INT32;
        !           736:   }else if( zP4==0 ){
        !           737:     pOp->p4.p = 0;
        !           738:     pOp->p4type = P4_NOTUSED;
        !           739:   }else if( n==P4_KEYINFO ){
        !           740:     KeyInfo *pKeyInfo;
        !           741:     int nField, nByte;
        !           742: 
        !           743:     nField = ((KeyInfo*)zP4)->nField;
        !           744:     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
        !           745:     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
        !           746:     pOp->p4.pKeyInfo = pKeyInfo;
        !           747:     if( pKeyInfo ){
        !           748:       u8 *aSortOrder;
        !           749:       memcpy((char*)pKeyInfo, zP4, nByte - nField);
        !           750:       aSortOrder = pKeyInfo->aSortOrder;
        !           751:       if( aSortOrder ){
        !           752:         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
        !           753:         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
        !           754:       }
        !           755:       pOp->p4type = P4_KEYINFO;
        !           756:     }else{
        !           757:       p->db->mallocFailed = 1;
        !           758:       pOp->p4type = P4_NOTUSED;
        !           759:     }
        !           760:   }else if( n==P4_KEYINFO_HANDOFF ){
        !           761:     pOp->p4.p = (void*)zP4;
        !           762:     pOp->p4type = P4_KEYINFO;
        !           763:   }else if( n==P4_VTAB ){
        !           764:     pOp->p4.p = (void*)zP4;
        !           765:     pOp->p4type = P4_VTAB;
        !           766:     sqlite3VtabLock((VTable *)zP4);
        !           767:     assert( ((VTable *)zP4)->db==p->db );
        !           768:   }else if( n<0 ){
        !           769:     pOp->p4.p = (void*)zP4;
        !           770:     pOp->p4type = (signed char)n;
        !           771:   }else{
        !           772:     if( n==0 ) n = sqlite3Strlen30(zP4);
        !           773:     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
        !           774:     pOp->p4type = P4_DYNAMIC;
        !           775:   }
        !           776: }
        !           777: 
        !           778: #ifndef NDEBUG
        !           779: /*
        !           780: ** Change the comment on the the most recently coded instruction.  Or
        !           781: ** insert a No-op and add the comment to that new instruction.  This
        !           782: ** makes the code easier to read during debugging.  None of this happens
        !           783: ** in a production build.
        !           784: */
        !           785: static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
        !           786:   assert( p->nOp>0 || p->aOp==0 );
        !           787:   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
        !           788:   if( p->nOp ){
        !           789:     assert( p->aOp );
        !           790:     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
        !           791:     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
        !           792:   }
        !           793: }
        !           794: void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
        !           795:   va_list ap;
        !           796:   if( p ){
        !           797:     va_start(ap, zFormat);
        !           798:     vdbeVComment(p, zFormat, ap);
        !           799:     va_end(ap);
        !           800:   }
        !           801: }
        !           802: void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
        !           803:   va_list ap;
        !           804:   if( p ){
        !           805:     sqlite3VdbeAddOp0(p, OP_Noop);
        !           806:     va_start(ap, zFormat);
        !           807:     vdbeVComment(p, zFormat, ap);
        !           808:     va_end(ap);
        !           809:   }
        !           810: }
        !           811: #endif  /* NDEBUG */
        !           812: 
        !           813: /*
        !           814: ** Return the opcode for a given address.  If the address is -1, then
        !           815: ** return the most recently inserted opcode.
        !           816: **
        !           817: ** If a memory allocation error has occurred prior to the calling of this
        !           818: ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
        !           819: ** is readable but not writable, though it is cast to a writable value.
        !           820: ** The return of a dummy opcode allows the call to continue functioning
        !           821: ** after a OOM fault without having to check to see if the return from 
        !           822: ** this routine is a valid pointer.  But because the dummy.opcode is 0,
        !           823: ** dummy will never be written to.  This is verified by code inspection and
        !           824: ** by running with Valgrind.
        !           825: **
        !           826: ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
        !           827: ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
        !           828: ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
        !           829: ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
        !           830: ** having to double-check to make sure that the result is non-negative. But
        !           831: ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
        !           832: ** check the value of p->nOp-1 before continuing.
        !           833: */
        !           834: VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
        !           835:   /* C89 specifies that the constant "dummy" will be initialized to all
        !           836:   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
        !           837:   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
        !           838:   assert( p->magic==VDBE_MAGIC_INIT );
        !           839:   if( addr<0 ){
        !           840: #ifdef SQLITE_OMIT_TRACE
        !           841:     if( p->nOp==0 ) return (VdbeOp*)&dummy;
        !           842: #endif
        !           843:     addr = p->nOp - 1;
        !           844:   }
        !           845:   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
        !           846:   if( p->db->mallocFailed ){
        !           847:     return (VdbeOp*)&dummy;
        !           848:   }else{
        !           849:     return &p->aOp[addr];
        !           850:   }
        !           851: }
        !           852: 
        !           853: #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
        !           854:      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
        !           855: /*
        !           856: ** Compute a string that describes the P4 parameter for an opcode.
        !           857: ** Use zTemp for any required temporary buffer space.
        !           858: */
        !           859: static char *displayP4(Op *pOp, char *zTemp, int nTemp){
        !           860:   char *zP4 = zTemp;
        !           861:   assert( nTemp>=20 );
        !           862:   switch( pOp->p4type ){
        !           863:     case P4_KEYINFO_STATIC:
        !           864:     case P4_KEYINFO: {
        !           865:       int i, j;
        !           866:       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
        !           867:       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
        !           868:       i = sqlite3Strlen30(zTemp);
        !           869:       for(j=0; j<pKeyInfo->nField; j++){
        !           870:         CollSeq *pColl = pKeyInfo->aColl[j];
        !           871:         if( pColl ){
        !           872:           int n = sqlite3Strlen30(pColl->zName);
        !           873:           if( i+n>nTemp-6 ){
        !           874:             memcpy(&zTemp[i],",...",4);
        !           875:             break;
        !           876:           }
        !           877:           zTemp[i++] = ',';
        !           878:           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
        !           879:             zTemp[i++] = '-';
        !           880:           }
        !           881:           memcpy(&zTemp[i], pColl->zName,n+1);
        !           882:           i += n;
        !           883:         }else if( i+4<nTemp-6 ){
        !           884:           memcpy(&zTemp[i],",nil",4);
        !           885:           i += 4;
        !           886:         }
        !           887:       }
        !           888:       zTemp[i++] = ')';
        !           889:       zTemp[i] = 0;
        !           890:       assert( i<nTemp );
        !           891:       break;
        !           892:     }
        !           893:     case P4_COLLSEQ: {
        !           894:       CollSeq *pColl = pOp->p4.pColl;
        !           895:       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
        !           896:       break;
        !           897:     }
        !           898:     case P4_FUNCDEF: {
        !           899:       FuncDef *pDef = pOp->p4.pFunc;
        !           900:       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
        !           901:       break;
        !           902:     }
        !           903:     case P4_INT64: {
        !           904:       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
        !           905:       break;
        !           906:     }
        !           907:     case P4_INT32: {
        !           908:       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
        !           909:       break;
        !           910:     }
        !           911:     case P4_REAL: {
        !           912:       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
        !           913:       break;
        !           914:     }
        !           915:     case P4_MEM: {
        !           916:       Mem *pMem = pOp->p4.pMem;
        !           917:       if( pMem->flags & MEM_Str ){
        !           918:         zP4 = pMem->z;
        !           919:       }else if( pMem->flags & MEM_Int ){
        !           920:         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
        !           921:       }else if( pMem->flags & MEM_Real ){
        !           922:         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
        !           923:       }else if( pMem->flags & MEM_Null ){
        !           924:         sqlite3_snprintf(nTemp, zTemp, "NULL");
        !           925:       }else{
        !           926:         assert( pMem->flags & MEM_Blob );
        !           927:         zP4 = "(blob)";
        !           928:       }
        !           929:       break;
        !           930:     }
        !           931: #ifndef SQLITE_OMIT_VIRTUALTABLE
        !           932:     case P4_VTAB: {
        !           933:       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
        !           934:       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
        !           935:       break;
        !           936:     }
        !           937: #endif
        !           938:     case P4_INTARRAY: {
        !           939:       sqlite3_snprintf(nTemp, zTemp, "intarray");
        !           940:       break;
        !           941:     }
        !           942:     case P4_SUBPROGRAM: {
        !           943:       sqlite3_snprintf(nTemp, zTemp, "program");
        !           944:       break;
        !           945:     }
        !           946:     case P4_ADVANCE: {
        !           947:       zTemp[0] = 0;
        !           948:       break;
        !           949:     }
        !           950:     default: {
        !           951:       zP4 = pOp->p4.z;
        !           952:       if( zP4==0 ){
        !           953:         zP4 = zTemp;
        !           954:         zTemp[0] = 0;
        !           955:       }
        !           956:     }
        !           957:   }
        !           958:   assert( zP4!=0 );
        !           959:   return zP4;
        !           960: }
        !           961: #endif
        !           962: 
        !           963: /*
        !           964: ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
        !           965: **
        !           966: ** The prepared statements need to know in advance the complete set of
        !           967: ** attached databases that will be use.  A mask of these databases
        !           968: ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
        !           969: ** p->btreeMask of databases that will require a lock.
        !           970: */
        !           971: void sqlite3VdbeUsesBtree(Vdbe *p, int i){
        !           972:   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
        !           973:   assert( i<(int)sizeof(p->btreeMask)*8 );
        !           974:   p->btreeMask |= ((yDbMask)1)<<i;
        !           975:   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
        !           976:     p->lockMask |= ((yDbMask)1)<<i;
        !           977:   }
        !           978: }
        !           979: 
        !           980: #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
        !           981: /*
        !           982: ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
        !           983: ** this routine obtains the mutex associated with each BtShared structure
        !           984: ** that may be accessed by the VM passed as an argument. In doing so it also
        !           985: ** sets the BtShared.db member of each of the BtShared structures, ensuring
        !           986: ** that the correct busy-handler callback is invoked if required.
        !           987: **
        !           988: ** If SQLite is not threadsafe but does support shared-cache mode, then
        !           989: ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
        !           990: ** of all of BtShared structures accessible via the database handle 
        !           991: ** associated with the VM.
        !           992: **
        !           993: ** If SQLite is not threadsafe and does not support shared-cache mode, this
        !           994: ** function is a no-op.
        !           995: **
        !           996: ** The p->btreeMask field is a bitmask of all btrees that the prepared 
        !           997: ** statement p will ever use.  Let N be the number of bits in p->btreeMask
        !           998: ** corresponding to btrees that use shared cache.  Then the runtime of
        !           999: ** this routine is N*N.  But as N is rarely more than 1, this should not
        !          1000: ** be a problem.
        !          1001: */
        !          1002: void sqlite3VdbeEnter(Vdbe *p){
        !          1003:   int i;
        !          1004:   yDbMask mask;
        !          1005:   sqlite3 *db;
        !          1006:   Db *aDb;
        !          1007:   int nDb;
        !          1008:   if( p->lockMask==0 ) return;  /* The common case */
        !          1009:   db = p->db;
        !          1010:   aDb = db->aDb;
        !          1011:   nDb = db->nDb;
        !          1012:   for(i=0, mask=1; i<nDb; i++, mask += mask){
        !          1013:     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
        !          1014:       sqlite3BtreeEnter(aDb[i].pBt);
        !          1015:     }
        !          1016:   }
        !          1017: }
        !          1018: #endif
        !          1019: 
        !          1020: #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
        !          1021: /*
        !          1022: ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
        !          1023: */
        !          1024: void sqlite3VdbeLeave(Vdbe *p){
        !          1025:   int i;
        !          1026:   yDbMask mask;
        !          1027:   sqlite3 *db;
        !          1028:   Db *aDb;
        !          1029:   int nDb;
        !          1030:   if( p->lockMask==0 ) return;  /* The common case */
        !          1031:   db = p->db;
        !          1032:   aDb = db->aDb;
        !          1033:   nDb = db->nDb;
        !          1034:   for(i=0, mask=1; i<nDb; i++, mask += mask){
        !          1035:     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
        !          1036:       sqlite3BtreeLeave(aDb[i].pBt);
        !          1037:     }
        !          1038:   }
        !          1039: }
        !          1040: #endif
        !          1041: 
        !          1042: #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
        !          1043: /*
        !          1044: ** Print a single opcode.  This routine is used for debugging only.
        !          1045: */
        !          1046: void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
        !          1047:   char *zP4;
        !          1048:   char zPtr[50];
        !          1049:   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
        !          1050:   if( pOut==0 ) pOut = stdout;
        !          1051:   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
        !          1052:   fprintf(pOut, zFormat1, pc, 
        !          1053:       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
        !          1054: #ifdef SQLITE_DEBUG
        !          1055:       pOp->zComment ? pOp->zComment : ""
        !          1056: #else
        !          1057:       ""
        !          1058: #endif
        !          1059:   );
        !          1060:   fflush(pOut);
        !          1061: }
        !          1062: #endif
        !          1063: 
        !          1064: /*
        !          1065: ** Release an array of N Mem elements
        !          1066: */
        !          1067: static void releaseMemArray(Mem *p, int N){
        !          1068:   if( p && N ){
        !          1069:     Mem *pEnd;
        !          1070:     sqlite3 *db = p->db;
        !          1071:     u8 malloc_failed = db->mallocFailed;
        !          1072:     if( db->pnBytesFreed ){
        !          1073:       for(pEnd=&p[N]; p<pEnd; p++){
        !          1074:         sqlite3DbFree(db, p->zMalloc);
        !          1075:       }
        !          1076:       return;
        !          1077:     }
        !          1078:     for(pEnd=&p[N]; p<pEnd; p++){
        !          1079:       assert( (&p[1])==pEnd || p[0].db==p[1].db );
        !          1080: 
        !          1081:       /* This block is really an inlined version of sqlite3VdbeMemRelease()
        !          1082:       ** that takes advantage of the fact that the memory cell value is 
        !          1083:       ** being set to NULL after releasing any dynamic resources.
        !          1084:       **
        !          1085:       ** The justification for duplicating code is that according to 
        !          1086:       ** callgrind, this causes a certain test case to hit the CPU 4.7 
        !          1087:       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
        !          1088:       ** sqlite3MemRelease() were called from here. With -O2, this jumps
        !          1089:       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
        !          1090:       ** with no indexes using a single prepared INSERT statement, bind() 
        !          1091:       ** and reset(). Inserts are grouped into a transaction.
        !          1092:       */
        !          1093:       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
        !          1094:         sqlite3VdbeMemRelease(p);
        !          1095:       }else if( p->zMalloc ){
        !          1096:         sqlite3DbFree(db, p->zMalloc);
        !          1097:         p->zMalloc = 0;
        !          1098:       }
        !          1099: 
        !          1100:       p->flags = MEM_Invalid;
        !          1101:     }
        !          1102:     db->mallocFailed = malloc_failed;
        !          1103:   }
        !          1104: }
        !          1105: 
        !          1106: /*
        !          1107: ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
        !          1108: ** allocated by the OP_Program opcode in sqlite3VdbeExec().
        !          1109: */
        !          1110: void sqlite3VdbeFrameDelete(VdbeFrame *p){
        !          1111:   int i;
        !          1112:   Mem *aMem = VdbeFrameMem(p);
        !          1113:   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
        !          1114:   for(i=0; i<p->nChildCsr; i++){
        !          1115:     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
        !          1116:   }
        !          1117:   releaseMemArray(aMem, p->nChildMem);
        !          1118:   sqlite3DbFree(p->v->db, p);
        !          1119: }
        !          1120: 
        !          1121: #ifndef SQLITE_OMIT_EXPLAIN
        !          1122: /*
        !          1123: ** Give a listing of the program in the virtual machine.
        !          1124: **
        !          1125: ** The interface is the same as sqlite3VdbeExec().  But instead of
        !          1126: ** running the code, it invokes the callback once for each instruction.
        !          1127: ** This feature is used to implement "EXPLAIN".
        !          1128: **
        !          1129: ** When p->explain==1, each instruction is listed.  When
        !          1130: ** p->explain==2, only OP_Explain instructions are listed and these
        !          1131: ** are shown in a different format.  p->explain==2 is used to implement
        !          1132: ** EXPLAIN QUERY PLAN.
        !          1133: **
        !          1134: ** When p->explain==1, first the main program is listed, then each of
        !          1135: ** the trigger subprograms are listed one by one.
        !          1136: */
        !          1137: int sqlite3VdbeList(
        !          1138:   Vdbe *p                   /* The VDBE */
        !          1139: ){
        !          1140:   int nRow;                            /* Stop when row count reaches this */
        !          1141:   int nSub = 0;                        /* Number of sub-vdbes seen so far */
        !          1142:   SubProgram **apSub = 0;              /* Array of sub-vdbes */
        !          1143:   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
        !          1144:   sqlite3 *db = p->db;                 /* The database connection */
        !          1145:   int i;                               /* Loop counter */
        !          1146:   int rc = SQLITE_OK;                  /* Return code */
        !          1147:   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
        !          1148: 
        !          1149:   assert( p->explain );
        !          1150:   assert( p->magic==VDBE_MAGIC_RUN );
        !          1151:   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
        !          1152: 
        !          1153:   /* Even though this opcode does not use dynamic strings for
        !          1154:   ** the result, result columns may become dynamic if the user calls
        !          1155:   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
        !          1156:   */
        !          1157:   releaseMemArray(pMem, 8);
        !          1158:   p->pResultSet = 0;
        !          1159: 
        !          1160:   if( p->rc==SQLITE_NOMEM ){
        !          1161:     /* This happens if a malloc() inside a call to sqlite3_column_text() or
        !          1162:     ** sqlite3_column_text16() failed.  */
        !          1163:     db->mallocFailed = 1;
        !          1164:     return SQLITE_ERROR;
        !          1165:   }
        !          1166: 
        !          1167:   /* When the number of output rows reaches nRow, that means the
        !          1168:   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
        !          1169:   ** nRow is the sum of the number of rows in the main program, plus
        !          1170:   ** the sum of the number of rows in all trigger subprograms encountered
        !          1171:   ** so far.  The nRow value will increase as new trigger subprograms are
        !          1172:   ** encountered, but p->pc will eventually catch up to nRow.
        !          1173:   */
        !          1174:   nRow = p->nOp;
        !          1175:   if( p->explain==1 ){
        !          1176:     /* The first 8 memory cells are used for the result set.  So we will
        !          1177:     ** commandeer the 9th cell to use as storage for an array of pointers
        !          1178:     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
        !          1179:     ** cells.  */
        !          1180:     assert( p->nMem>9 );
        !          1181:     pSub = &p->aMem[9];
        !          1182:     if( pSub->flags&MEM_Blob ){
        !          1183:       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
        !          1184:       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
        !          1185:       nSub = pSub->n/sizeof(Vdbe*);
        !          1186:       apSub = (SubProgram **)pSub->z;
        !          1187:     }
        !          1188:     for(i=0; i<nSub; i++){
        !          1189:       nRow += apSub[i]->nOp;
        !          1190:     }
        !          1191:   }
        !          1192: 
        !          1193:   do{
        !          1194:     i = p->pc++;
        !          1195:   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
        !          1196:   if( i>=nRow ){
        !          1197:     p->rc = SQLITE_OK;
        !          1198:     rc = SQLITE_DONE;
        !          1199:   }else if( db->u1.isInterrupted ){
        !          1200:     p->rc = SQLITE_INTERRUPT;
        !          1201:     rc = SQLITE_ERROR;
        !          1202:     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
        !          1203:   }else{
        !          1204:     char *z;
        !          1205:     Op *pOp;
        !          1206:     if( i<p->nOp ){
        !          1207:       /* The output line number is small enough that we are still in the
        !          1208:       ** main program. */
        !          1209:       pOp = &p->aOp[i];
        !          1210:     }else{
        !          1211:       /* We are currently listing subprograms.  Figure out which one and
        !          1212:       ** pick up the appropriate opcode. */
        !          1213:       int j;
        !          1214:       i -= p->nOp;
        !          1215:       for(j=0; i>=apSub[j]->nOp; j++){
        !          1216:         i -= apSub[j]->nOp;
        !          1217:       }
        !          1218:       pOp = &apSub[j]->aOp[i];
        !          1219:     }
        !          1220:     if( p->explain==1 ){
        !          1221:       pMem->flags = MEM_Int;
        !          1222:       pMem->type = SQLITE_INTEGER;
        !          1223:       pMem->u.i = i;                                /* Program counter */
        !          1224:       pMem++;
        !          1225:   
        !          1226:       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
        !          1227:       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
        !          1228:       assert( pMem->z!=0 );
        !          1229:       pMem->n = sqlite3Strlen30(pMem->z);
        !          1230:       pMem->type = SQLITE_TEXT;
        !          1231:       pMem->enc = SQLITE_UTF8;
        !          1232:       pMem++;
        !          1233: 
        !          1234:       /* When an OP_Program opcode is encounter (the only opcode that has
        !          1235:       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
        !          1236:       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
        !          1237:       ** has not already been seen.
        !          1238:       */
        !          1239:       if( pOp->p4type==P4_SUBPROGRAM ){
        !          1240:         int nByte = (nSub+1)*sizeof(SubProgram*);
        !          1241:         int j;
        !          1242:         for(j=0; j<nSub; j++){
        !          1243:           if( apSub[j]==pOp->p4.pProgram ) break;
        !          1244:         }
        !          1245:         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
        !          1246:           apSub = (SubProgram **)pSub->z;
        !          1247:           apSub[nSub++] = pOp->p4.pProgram;
        !          1248:           pSub->flags |= MEM_Blob;
        !          1249:           pSub->n = nSub*sizeof(SubProgram*);
        !          1250:         }
        !          1251:       }
        !          1252:     }
        !          1253: 
        !          1254:     pMem->flags = MEM_Int;
        !          1255:     pMem->u.i = pOp->p1;                          /* P1 */
        !          1256:     pMem->type = SQLITE_INTEGER;
        !          1257:     pMem++;
        !          1258: 
        !          1259:     pMem->flags = MEM_Int;
        !          1260:     pMem->u.i = pOp->p2;                          /* P2 */
        !          1261:     pMem->type = SQLITE_INTEGER;
        !          1262:     pMem++;
        !          1263: 
        !          1264:     pMem->flags = MEM_Int;
        !          1265:     pMem->u.i = pOp->p3;                          /* P3 */
        !          1266:     pMem->type = SQLITE_INTEGER;
        !          1267:     pMem++;
        !          1268: 
        !          1269:     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
        !          1270:       assert( p->db->mallocFailed );
        !          1271:       return SQLITE_ERROR;
        !          1272:     }
        !          1273:     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
        !          1274:     z = displayP4(pOp, pMem->z, 32);
        !          1275:     if( z!=pMem->z ){
        !          1276:       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
        !          1277:     }else{
        !          1278:       assert( pMem->z!=0 );
        !          1279:       pMem->n = sqlite3Strlen30(pMem->z);
        !          1280:       pMem->enc = SQLITE_UTF8;
        !          1281:     }
        !          1282:     pMem->type = SQLITE_TEXT;
        !          1283:     pMem++;
        !          1284: 
        !          1285:     if( p->explain==1 ){
        !          1286:       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
        !          1287:         assert( p->db->mallocFailed );
        !          1288:         return SQLITE_ERROR;
        !          1289:       }
        !          1290:       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
        !          1291:       pMem->n = 2;
        !          1292:       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
        !          1293:       pMem->type = SQLITE_TEXT;
        !          1294:       pMem->enc = SQLITE_UTF8;
        !          1295:       pMem++;
        !          1296:   
        !          1297: #ifdef SQLITE_DEBUG
        !          1298:       if( pOp->zComment ){
        !          1299:         pMem->flags = MEM_Str|MEM_Term;
        !          1300:         pMem->z = pOp->zComment;
        !          1301:         pMem->n = sqlite3Strlen30(pMem->z);
        !          1302:         pMem->enc = SQLITE_UTF8;
        !          1303:         pMem->type = SQLITE_TEXT;
        !          1304:       }else
        !          1305: #endif
        !          1306:       {
        !          1307:         pMem->flags = MEM_Null;                       /* Comment */
        !          1308:         pMem->type = SQLITE_NULL;
        !          1309:       }
        !          1310:     }
        !          1311: 
        !          1312:     p->nResColumn = 8 - 4*(p->explain-1);
        !          1313:     p->pResultSet = &p->aMem[1];
        !          1314:     p->rc = SQLITE_OK;
        !          1315:     rc = SQLITE_ROW;
        !          1316:   }
        !          1317:   return rc;
        !          1318: }
        !          1319: #endif /* SQLITE_OMIT_EXPLAIN */
        !          1320: 
        !          1321: #ifdef SQLITE_DEBUG
        !          1322: /*
        !          1323: ** Print the SQL that was used to generate a VDBE program.
        !          1324: */
        !          1325: void sqlite3VdbePrintSql(Vdbe *p){
        !          1326:   int nOp = p->nOp;
        !          1327:   VdbeOp *pOp;
        !          1328:   if( nOp<1 ) return;
        !          1329:   pOp = &p->aOp[0];
        !          1330:   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
        !          1331:     const char *z = pOp->p4.z;
        !          1332:     while( sqlite3Isspace(*z) ) z++;
        !          1333:     printf("SQL: [%s]\n", z);
        !          1334:   }
        !          1335: }
        !          1336: #endif
        !          1337: 
        !          1338: #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
        !          1339: /*
        !          1340: ** Print an IOTRACE message showing SQL content.
        !          1341: */
        !          1342: void sqlite3VdbeIOTraceSql(Vdbe *p){
        !          1343:   int nOp = p->nOp;
        !          1344:   VdbeOp *pOp;
        !          1345:   if( sqlite3IoTrace==0 ) return;
        !          1346:   if( nOp<1 ) return;
        !          1347:   pOp = &p->aOp[0];
        !          1348:   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
        !          1349:     int i, j;
        !          1350:     char z[1000];
        !          1351:     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
        !          1352:     for(i=0; sqlite3Isspace(z[i]); i++){}
        !          1353:     for(j=0; z[i]; i++){
        !          1354:       if( sqlite3Isspace(z[i]) ){
        !          1355:         if( z[i-1]!=' ' ){
        !          1356:           z[j++] = ' ';
        !          1357:         }
        !          1358:       }else{
        !          1359:         z[j++] = z[i];
        !          1360:       }
        !          1361:     }
        !          1362:     z[j] = 0;
        !          1363:     sqlite3IoTrace("SQL %s\n", z);
        !          1364:   }
        !          1365: }
        !          1366: #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
        !          1367: 
        !          1368: /*
        !          1369: ** Allocate space from a fixed size buffer and return a pointer to
        !          1370: ** that space.  If insufficient space is available, return NULL.
        !          1371: **
        !          1372: ** The pBuf parameter is the initial value of a pointer which will
        !          1373: ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
        !          1374: ** NULL, it means that memory space has already been allocated and that
        !          1375: ** this routine should not allocate any new memory.  When pBuf is not
        !          1376: ** NULL simply return pBuf.  Only allocate new memory space when pBuf
        !          1377: ** is NULL.
        !          1378: **
        !          1379: ** nByte is the number of bytes of space needed.
        !          1380: **
        !          1381: ** *ppFrom points to available space and pEnd points to the end of the
        !          1382: ** available space.  When space is allocated, *ppFrom is advanced past
        !          1383: ** the end of the allocated space.
        !          1384: **
        !          1385: ** *pnByte is a counter of the number of bytes of space that have failed
        !          1386: ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
        !          1387: ** request, then increment *pnByte by the amount of the request.
        !          1388: */
        !          1389: static void *allocSpace(
        !          1390:   void *pBuf,          /* Where return pointer will be stored */
        !          1391:   int nByte,           /* Number of bytes to allocate */
        !          1392:   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
        !          1393:   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
        !          1394:   int *pnByte          /* If allocation cannot be made, increment *pnByte */
        !          1395: ){
        !          1396:   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
        !          1397:   if( pBuf ) return pBuf;
        !          1398:   nByte = ROUND8(nByte);
        !          1399:   if( &(*ppFrom)[nByte] <= pEnd ){
        !          1400:     pBuf = (void*)*ppFrom;
        !          1401:     *ppFrom += nByte;
        !          1402:   }else{
        !          1403:     *pnByte += nByte;
        !          1404:   }
        !          1405:   return pBuf;
        !          1406: }
        !          1407: 
        !          1408: /*
        !          1409: ** Rewind the VDBE back to the beginning in preparation for
        !          1410: ** running it.
        !          1411: */
        !          1412: void sqlite3VdbeRewind(Vdbe *p){
        !          1413: #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
        !          1414:   int i;
        !          1415: #endif
        !          1416:   assert( p!=0 );
        !          1417:   assert( p->magic==VDBE_MAGIC_INIT );
        !          1418: 
        !          1419:   /* There should be at least one opcode.
        !          1420:   */
        !          1421:   assert( p->nOp>0 );
        !          1422: 
        !          1423:   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
        !          1424:   p->magic = VDBE_MAGIC_RUN;
        !          1425: 
        !          1426: #ifdef SQLITE_DEBUG
        !          1427:   for(i=1; i<p->nMem; i++){
        !          1428:     assert( p->aMem[i].db==p->db );
        !          1429:   }
        !          1430: #endif
        !          1431:   p->pc = -1;
        !          1432:   p->rc = SQLITE_OK;
        !          1433:   p->errorAction = OE_Abort;
        !          1434:   p->magic = VDBE_MAGIC_RUN;
        !          1435:   p->nChange = 0;
        !          1436:   p->cacheCtr = 1;
        !          1437:   p->minWriteFileFormat = 255;
        !          1438:   p->iStatement = 0;
        !          1439:   p->nFkConstraint = 0;
        !          1440: #ifdef VDBE_PROFILE
        !          1441:   for(i=0; i<p->nOp; i++){
        !          1442:     p->aOp[i].cnt = 0;
        !          1443:     p->aOp[i].cycles = 0;
        !          1444:   }
        !          1445: #endif
        !          1446: }
        !          1447: 
        !          1448: /*
        !          1449: ** Prepare a virtual machine for execution for the first time after
        !          1450: ** creating the virtual machine.  This involves things such
        !          1451: ** as allocating stack space and initializing the program counter.
        !          1452: ** After the VDBE has be prepped, it can be executed by one or more
        !          1453: ** calls to sqlite3VdbeExec().  
        !          1454: **
        !          1455: ** This function may be called exact once on a each virtual machine.
        !          1456: ** After this routine is called the VM has been "packaged" and is ready
        !          1457: ** to run.  After this routine is called, futher calls to 
        !          1458: ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
        !          1459: ** the Vdbe from the Parse object that helped generate it so that the
        !          1460: ** the Vdbe becomes an independent entity and the Parse object can be
        !          1461: ** destroyed.
        !          1462: **
        !          1463: ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
        !          1464: ** to its initial state after it has been run.
        !          1465: */
        !          1466: void sqlite3VdbeMakeReady(
        !          1467:   Vdbe *p,                       /* The VDBE */
        !          1468:   Parse *pParse                  /* Parsing context */
        !          1469: ){
        !          1470:   sqlite3 *db;                   /* The database connection */
        !          1471:   int nVar;                      /* Number of parameters */
        !          1472:   int nMem;                      /* Number of VM memory registers */
        !          1473:   int nCursor;                   /* Number of cursors required */
        !          1474:   int nArg;                      /* Number of arguments in subprograms */
        !          1475:   int nOnce;                     /* Number of OP_Once instructions */
        !          1476:   int n;                         /* Loop counter */
        !          1477:   u8 *zCsr;                      /* Memory available for allocation */
        !          1478:   u8 *zEnd;                      /* First byte past allocated memory */
        !          1479:   int nByte;                     /* How much extra memory is needed */
        !          1480: 
        !          1481:   assert( p!=0 );
        !          1482:   assert( p->nOp>0 );
        !          1483:   assert( pParse!=0 );
        !          1484:   assert( p->magic==VDBE_MAGIC_INIT );
        !          1485:   db = p->db;
        !          1486:   assert( db->mallocFailed==0 );
        !          1487:   nVar = pParse->nVar;
        !          1488:   nMem = pParse->nMem;
        !          1489:   nCursor = pParse->nTab;
        !          1490:   nArg = pParse->nMaxArg;
        !          1491:   nOnce = pParse->nOnce;
        !          1492:   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
        !          1493:   
        !          1494:   /* For each cursor required, also allocate a memory cell. Memory
        !          1495:   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
        !          1496:   ** the vdbe program. Instead they are used to allocate space for
        !          1497:   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
        !          1498:   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
        !          1499:   ** stores the blob of memory associated with cursor 1, etc.
        !          1500:   **
        !          1501:   ** See also: allocateCursor().
        !          1502:   */
        !          1503:   nMem += nCursor;
        !          1504: 
        !          1505:   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
        !          1506:   ** an array to marshal SQL function arguments in.
        !          1507:   */
        !          1508:   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
        !          1509:   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
        !          1510: 
        !          1511:   resolveP2Values(p, &nArg);
        !          1512:   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
        !          1513:   if( pParse->explain && nMem<10 ){
        !          1514:     nMem = 10;
        !          1515:   }
        !          1516:   memset(zCsr, 0, zEnd-zCsr);
        !          1517:   zCsr += (zCsr - (u8*)0)&7;
        !          1518:   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
        !          1519:   p->expired = 0;
        !          1520: 
        !          1521:   /* Memory for registers, parameters, cursor, etc, is allocated in two
        !          1522:   ** passes.  On the first pass, we try to reuse unused space at the 
        !          1523:   ** end of the opcode array.  If we are unable to satisfy all memory
        !          1524:   ** requirements by reusing the opcode array tail, then the second
        !          1525:   ** pass will fill in the rest using a fresh allocation.  
        !          1526:   **
        !          1527:   ** This two-pass approach that reuses as much memory as possible from
        !          1528:   ** the leftover space at the end of the opcode array can significantly
        !          1529:   ** reduce the amount of memory held by a prepared statement.
        !          1530:   */
        !          1531:   do {
        !          1532:     nByte = 0;
        !          1533:     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
        !          1534:     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
        !          1535:     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
        !          1536:     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
        !          1537:     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
        !          1538:                           &zCsr, zEnd, &nByte);
        !          1539:     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
        !          1540:     if( nByte ){
        !          1541:       p->pFree = sqlite3DbMallocZero(db, nByte);
        !          1542:     }
        !          1543:     zCsr = p->pFree;
        !          1544:     zEnd = &zCsr[nByte];
        !          1545:   }while( nByte && !db->mallocFailed );
        !          1546: 
        !          1547:   p->nCursor = (u16)nCursor;
        !          1548:   p->nOnceFlag = nOnce;
        !          1549:   if( p->aVar ){
        !          1550:     p->nVar = (ynVar)nVar;
        !          1551:     for(n=0; n<nVar; n++){
        !          1552:       p->aVar[n].flags = MEM_Null;
        !          1553:       p->aVar[n].db = db;
        !          1554:     }
        !          1555:   }
        !          1556:   if( p->azVar ){
        !          1557:     p->nzVar = pParse->nzVar;
        !          1558:     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
        !          1559:     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
        !          1560:   }
        !          1561:   if( p->aMem ){
        !          1562:     p->aMem--;                      /* aMem[] goes from 1..nMem */
        !          1563:     p->nMem = nMem;                 /*       not from 0..nMem-1 */
        !          1564:     for(n=1; n<=nMem; n++){
        !          1565:       p->aMem[n].flags = MEM_Invalid;
        !          1566:       p->aMem[n].db = db;
        !          1567:     }
        !          1568:   }
        !          1569:   p->explain = pParse->explain;
        !          1570:   sqlite3VdbeRewind(p);
        !          1571: }
        !          1572: 
        !          1573: /*
        !          1574: ** Close a VDBE cursor and release all the resources that cursor 
        !          1575: ** happens to hold.
        !          1576: */
        !          1577: void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
        !          1578:   if( pCx==0 ){
        !          1579:     return;
        !          1580:   }
        !          1581:   sqlite3VdbeSorterClose(p->db, pCx);
        !          1582:   if( pCx->pBt ){
        !          1583:     sqlite3BtreeClose(pCx->pBt);
        !          1584:     /* The pCx->pCursor will be close automatically, if it exists, by
        !          1585:     ** the call above. */
        !          1586:   }else if( pCx->pCursor ){
        !          1587:     sqlite3BtreeCloseCursor(pCx->pCursor);
        !          1588:   }
        !          1589: #ifndef SQLITE_OMIT_VIRTUALTABLE
        !          1590:   if( pCx->pVtabCursor ){
        !          1591:     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
        !          1592:     const sqlite3_module *pModule = pCx->pModule;
        !          1593:     p->inVtabMethod = 1;
        !          1594:     pModule->xClose(pVtabCursor);
        !          1595:     p->inVtabMethod = 0;
        !          1596:   }
        !          1597: #endif
        !          1598: }
        !          1599: 
        !          1600: /*
        !          1601: ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
        !          1602: ** is used, for example, when a trigger sub-program is halted to restore
        !          1603: ** control to the main program.
        !          1604: */
        !          1605: int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
        !          1606:   Vdbe *v = pFrame->v;
        !          1607:   v->aOnceFlag = pFrame->aOnceFlag;
        !          1608:   v->nOnceFlag = pFrame->nOnceFlag;
        !          1609:   v->aOp = pFrame->aOp;
        !          1610:   v->nOp = pFrame->nOp;
        !          1611:   v->aMem = pFrame->aMem;
        !          1612:   v->nMem = pFrame->nMem;
        !          1613:   v->apCsr = pFrame->apCsr;
        !          1614:   v->nCursor = pFrame->nCursor;
        !          1615:   v->db->lastRowid = pFrame->lastRowid;
        !          1616:   v->nChange = pFrame->nChange;
        !          1617:   return pFrame->pc;
        !          1618: }
        !          1619: 
        !          1620: /*
        !          1621: ** Close all cursors.
        !          1622: **
        !          1623: ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
        !          1624: ** cell array. This is necessary as the memory cell array may contain
        !          1625: ** pointers to VdbeFrame objects, which may in turn contain pointers to
        !          1626: ** open cursors.
        !          1627: */
        !          1628: static void closeAllCursors(Vdbe *p){
        !          1629:   if( p->pFrame ){
        !          1630:     VdbeFrame *pFrame;
        !          1631:     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
        !          1632:     sqlite3VdbeFrameRestore(pFrame);
        !          1633:   }
        !          1634:   p->pFrame = 0;
        !          1635:   p->nFrame = 0;
        !          1636: 
        !          1637:   if( p->apCsr ){
        !          1638:     int i;
        !          1639:     for(i=0; i<p->nCursor; i++){
        !          1640:       VdbeCursor *pC = p->apCsr[i];
        !          1641:       if( pC ){
        !          1642:         sqlite3VdbeFreeCursor(p, pC);
        !          1643:         p->apCsr[i] = 0;
        !          1644:       }
        !          1645:     }
        !          1646:   }
        !          1647:   if( p->aMem ){
        !          1648:     releaseMemArray(&p->aMem[1], p->nMem);
        !          1649:   }
        !          1650:   while( p->pDelFrame ){
        !          1651:     VdbeFrame *pDel = p->pDelFrame;
        !          1652:     p->pDelFrame = pDel->pParent;
        !          1653:     sqlite3VdbeFrameDelete(pDel);
        !          1654:   }
        !          1655: }
        !          1656: 
        !          1657: /*
        !          1658: ** Clean up the VM after execution.
        !          1659: **
        !          1660: ** This routine will automatically close any cursors, lists, and/or
        !          1661: ** sorters that were left open.  It also deletes the values of
        !          1662: ** variables in the aVar[] array.
        !          1663: */
        !          1664: static void Cleanup(Vdbe *p){
        !          1665:   sqlite3 *db = p->db;
        !          1666: 
        !          1667: #ifdef SQLITE_DEBUG
        !          1668:   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
        !          1669:   ** Vdbe.aMem[] arrays have already been cleaned up.  */
        !          1670:   int i;
        !          1671:   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
        !          1672:   if( p->aMem ){
        !          1673:     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
        !          1674:   }
        !          1675: #endif
        !          1676: 
        !          1677:   sqlite3DbFree(db, p->zErrMsg);
        !          1678:   p->zErrMsg = 0;
        !          1679:   p->pResultSet = 0;
        !          1680: }
        !          1681: 
        !          1682: /*
        !          1683: ** Set the number of result columns that will be returned by this SQL
        !          1684: ** statement. This is now set at compile time, rather than during
        !          1685: ** execution of the vdbe program so that sqlite3_column_count() can
        !          1686: ** be called on an SQL statement before sqlite3_step().
        !          1687: */
        !          1688: void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
        !          1689:   Mem *pColName;
        !          1690:   int n;
        !          1691:   sqlite3 *db = p->db;
        !          1692: 
        !          1693:   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
        !          1694:   sqlite3DbFree(db, p->aColName);
        !          1695:   n = nResColumn*COLNAME_N;
        !          1696:   p->nResColumn = (u16)nResColumn;
        !          1697:   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
        !          1698:   if( p->aColName==0 ) return;
        !          1699:   while( n-- > 0 ){
        !          1700:     pColName->flags = MEM_Null;
        !          1701:     pColName->db = p->db;
        !          1702:     pColName++;
        !          1703:   }
        !          1704: }
        !          1705: 
        !          1706: /*
        !          1707: ** Set the name of the idx'th column to be returned by the SQL statement.
        !          1708: ** zName must be a pointer to a nul terminated string.
        !          1709: **
        !          1710: ** This call must be made after a call to sqlite3VdbeSetNumCols().
        !          1711: **
        !          1712: ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
        !          1713: ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
        !          1714: ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
        !          1715: */
        !          1716: int sqlite3VdbeSetColName(
        !          1717:   Vdbe *p,                         /* Vdbe being configured */
        !          1718:   int idx,                         /* Index of column zName applies to */
        !          1719:   int var,                         /* One of the COLNAME_* constants */
        !          1720:   const char *zName,               /* Pointer to buffer containing name */
        !          1721:   void (*xDel)(void*)              /* Memory management strategy for zName */
        !          1722: ){
        !          1723:   int rc;
        !          1724:   Mem *pColName;
        !          1725:   assert( idx<p->nResColumn );
        !          1726:   assert( var<COLNAME_N );
        !          1727:   if( p->db->mallocFailed ){
        !          1728:     assert( !zName || xDel!=SQLITE_DYNAMIC );
        !          1729:     return SQLITE_NOMEM;
        !          1730:   }
        !          1731:   assert( p->aColName!=0 );
        !          1732:   pColName = &(p->aColName[idx+var*p->nResColumn]);
        !          1733:   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
        !          1734:   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
        !          1735:   return rc;
        !          1736: }
        !          1737: 
        !          1738: /*
        !          1739: ** A read or write transaction may or may not be active on database handle
        !          1740: ** db. If a transaction is active, commit it. If there is a
        !          1741: ** write-transaction spanning more than one database file, this routine
        !          1742: ** takes care of the master journal trickery.
        !          1743: */
        !          1744: static int vdbeCommit(sqlite3 *db, Vdbe *p){
        !          1745:   int i;
        !          1746:   int nTrans = 0;  /* Number of databases with an active write-transaction */
        !          1747:   int rc = SQLITE_OK;
        !          1748:   int needXcommit = 0;
        !          1749: 
        !          1750: #ifdef SQLITE_OMIT_VIRTUALTABLE
        !          1751:   /* With this option, sqlite3VtabSync() is defined to be simply 
        !          1752:   ** SQLITE_OK so p is not used. 
        !          1753:   */
        !          1754:   UNUSED_PARAMETER(p);
        !          1755: #endif
        !          1756: 
        !          1757:   /* Before doing anything else, call the xSync() callback for any
        !          1758:   ** virtual module tables written in this transaction. This has to
        !          1759:   ** be done before determining whether a master journal file is 
        !          1760:   ** required, as an xSync() callback may add an attached database
        !          1761:   ** to the transaction.
        !          1762:   */
        !          1763:   rc = sqlite3VtabSync(db, &p->zErrMsg);
        !          1764: 
        !          1765:   /* This loop determines (a) if the commit hook should be invoked and
        !          1766:   ** (b) how many database files have open write transactions, not 
        !          1767:   ** including the temp database. (b) is important because if more than 
        !          1768:   ** one database file has an open write transaction, a master journal
        !          1769:   ** file is required for an atomic commit.
        !          1770:   */ 
        !          1771:   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
        !          1772:     Btree *pBt = db->aDb[i].pBt;
        !          1773:     if( sqlite3BtreeIsInTrans(pBt) ){
        !          1774:       needXcommit = 1;
        !          1775:       if( i!=1 ) nTrans++;
        !          1776:       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
        !          1777:     }
        !          1778:   }
        !          1779:   if( rc!=SQLITE_OK ){
        !          1780:     return rc;
        !          1781:   }
        !          1782: 
        !          1783:   /* If there are any write-transactions at all, invoke the commit hook */
        !          1784:   if( needXcommit && db->xCommitCallback ){
        !          1785:     rc = db->xCommitCallback(db->pCommitArg);
        !          1786:     if( rc ){
        !          1787:       return SQLITE_CONSTRAINT;
        !          1788:     }
        !          1789:   }
        !          1790: 
        !          1791:   /* The simple case - no more than one database file (not counting the
        !          1792:   ** TEMP database) has a transaction active.   There is no need for the
        !          1793:   ** master-journal.
        !          1794:   **
        !          1795:   ** If the return value of sqlite3BtreeGetFilename() is a zero length
        !          1796:   ** string, it means the main database is :memory: or a temp file.  In 
        !          1797:   ** that case we do not support atomic multi-file commits, so use the 
        !          1798:   ** simple case then too.
        !          1799:   */
        !          1800:   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
        !          1801:    || nTrans<=1
        !          1802:   ){
        !          1803:     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
        !          1804:       Btree *pBt = db->aDb[i].pBt;
        !          1805:       if( pBt ){
        !          1806:         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
        !          1807:       }
        !          1808:     }
        !          1809: 
        !          1810:     /* Do the commit only if all databases successfully complete phase 1. 
        !          1811:     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
        !          1812:     ** IO error while deleting or truncating a journal file. It is unlikely,
        !          1813:     ** but could happen. In this case abandon processing and return the error.
        !          1814:     */
        !          1815:     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
        !          1816:       Btree *pBt = db->aDb[i].pBt;
        !          1817:       if( pBt ){
        !          1818:         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
        !          1819:       }
        !          1820:     }
        !          1821:     if( rc==SQLITE_OK ){
        !          1822:       sqlite3VtabCommit(db);
        !          1823:     }
        !          1824:   }
        !          1825: 
        !          1826:   /* The complex case - There is a multi-file write-transaction active.
        !          1827:   ** This requires a master journal file to ensure the transaction is
        !          1828:   ** committed atomicly.
        !          1829:   */
        !          1830: #ifndef SQLITE_OMIT_DISKIO
        !          1831:   else{
        !          1832:     sqlite3_vfs *pVfs = db->pVfs;
        !          1833:     int needSync = 0;
        !          1834:     char *zMaster = 0;   /* File-name for the master journal */
        !          1835:     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
        !          1836:     sqlite3_file *pMaster = 0;
        !          1837:     i64 offset = 0;
        !          1838:     int res;
        !          1839:     int retryCount = 0;
        !          1840:     int nMainFile;
        !          1841: 
        !          1842:     /* Select a master journal file name */
        !          1843:     nMainFile = sqlite3Strlen30(zMainFile);
        !          1844:     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
        !          1845:     if( zMaster==0 ) return SQLITE_NOMEM;
        !          1846:     do {
        !          1847:       u32 iRandom;
        !          1848:       if( retryCount ){
        !          1849:         if( retryCount>100 ){
        !          1850:           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
        !          1851:           sqlite3OsDelete(pVfs, zMaster, 0);
        !          1852:           break;
        !          1853:         }else if( retryCount==1 ){
        !          1854:           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
        !          1855:         }
        !          1856:       }
        !          1857:       retryCount++;
        !          1858:       sqlite3_randomness(sizeof(iRandom), &iRandom);
        !          1859:       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
        !          1860:                                (iRandom>>8)&0xffffff, iRandom&0xff);
        !          1861:       /* The antipenultimate character of the master journal name must
        !          1862:       ** be "9" to avoid name collisions when using 8+3 filenames. */
        !          1863:       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
        !          1864:       sqlite3FileSuffix3(zMainFile, zMaster);
        !          1865:       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
        !          1866:     }while( rc==SQLITE_OK && res );
        !          1867:     if( rc==SQLITE_OK ){
        !          1868:       /* Open the master journal. */
        !          1869:       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
        !          1870:           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
        !          1871:           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
        !          1872:       );
        !          1873:     }
        !          1874:     if( rc!=SQLITE_OK ){
        !          1875:       sqlite3DbFree(db, zMaster);
        !          1876:       return rc;
        !          1877:     }
        !          1878:  
        !          1879:     /* Write the name of each database file in the transaction into the new
        !          1880:     ** master journal file. If an error occurs at this point close
        !          1881:     ** and delete the master journal file. All the individual journal files
        !          1882:     ** still have 'null' as the master journal pointer, so they will roll
        !          1883:     ** back independently if a failure occurs.
        !          1884:     */
        !          1885:     for(i=0; i<db->nDb; i++){
        !          1886:       Btree *pBt = db->aDb[i].pBt;
        !          1887:       if( sqlite3BtreeIsInTrans(pBt) ){
        !          1888:         char const *zFile = sqlite3BtreeGetJournalname(pBt);
        !          1889:         if( zFile==0 ){
        !          1890:           continue;  /* Ignore TEMP and :memory: databases */
        !          1891:         }
        !          1892:         assert( zFile[0]!=0 );
        !          1893:         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
        !          1894:           needSync = 1;
        !          1895:         }
        !          1896:         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
        !          1897:         offset += sqlite3Strlen30(zFile)+1;
        !          1898:         if( rc!=SQLITE_OK ){
        !          1899:           sqlite3OsCloseFree(pMaster);
        !          1900:           sqlite3OsDelete(pVfs, zMaster, 0);
        !          1901:           sqlite3DbFree(db, zMaster);
        !          1902:           return rc;
        !          1903:         }
        !          1904:       }
        !          1905:     }
        !          1906: 
        !          1907:     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
        !          1908:     ** flag is set this is not required.
        !          1909:     */
        !          1910:     if( needSync 
        !          1911:      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
        !          1912:      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
        !          1913:     ){
        !          1914:       sqlite3OsCloseFree(pMaster);
        !          1915:       sqlite3OsDelete(pVfs, zMaster, 0);
        !          1916:       sqlite3DbFree(db, zMaster);
        !          1917:       return rc;
        !          1918:     }
        !          1919: 
        !          1920:     /* Sync all the db files involved in the transaction. The same call
        !          1921:     ** sets the master journal pointer in each individual journal. If
        !          1922:     ** an error occurs here, do not delete the master journal file.
        !          1923:     **
        !          1924:     ** If the error occurs during the first call to
        !          1925:     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
        !          1926:     ** master journal file will be orphaned. But we cannot delete it,
        !          1927:     ** in case the master journal file name was written into the journal
        !          1928:     ** file before the failure occurred.
        !          1929:     */
        !          1930:     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
        !          1931:       Btree *pBt = db->aDb[i].pBt;
        !          1932:       if( pBt ){
        !          1933:         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
        !          1934:       }
        !          1935:     }
        !          1936:     sqlite3OsCloseFree(pMaster);
        !          1937:     assert( rc!=SQLITE_BUSY );
        !          1938:     if( rc!=SQLITE_OK ){
        !          1939:       sqlite3DbFree(db, zMaster);
        !          1940:       return rc;
        !          1941:     }
        !          1942: 
        !          1943:     /* Delete the master journal file. This commits the transaction. After
        !          1944:     ** doing this the directory is synced again before any individual
        !          1945:     ** transaction files are deleted.
        !          1946:     */
        !          1947:     rc = sqlite3OsDelete(pVfs, zMaster, 1);
        !          1948:     sqlite3DbFree(db, zMaster);
        !          1949:     zMaster = 0;
        !          1950:     if( rc ){
        !          1951:       return rc;
        !          1952:     }
        !          1953: 
        !          1954:     /* All files and directories have already been synced, so the following
        !          1955:     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
        !          1956:     ** deleting or truncating journals. If something goes wrong while
        !          1957:     ** this is happening we don't really care. The integrity of the
        !          1958:     ** transaction is already guaranteed, but some stray 'cold' journals
        !          1959:     ** may be lying around. Returning an error code won't help matters.
        !          1960:     */
        !          1961:     disable_simulated_io_errors();
        !          1962:     sqlite3BeginBenignMalloc();
        !          1963:     for(i=0; i<db->nDb; i++){ 
        !          1964:       Btree *pBt = db->aDb[i].pBt;
        !          1965:       if( pBt ){
        !          1966:         sqlite3BtreeCommitPhaseTwo(pBt, 1);
        !          1967:       }
        !          1968:     }
        !          1969:     sqlite3EndBenignMalloc();
        !          1970:     enable_simulated_io_errors();
        !          1971: 
        !          1972:     sqlite3VtabCommit(db);
        !          1973:   }
        !          1974: #endif
        !          1975: 
        !          1976:   return rc;
        !          1977: }
        !          1978: 
        !          1979: /* 
        !          1980: ** This routine checks that the sqlite3.activeVdbeCnt count variable
        !          1981: ** matches the number of vdbe's in the list sqlite3.pVdbe that are
        !          1982: ** currently active. An assertion fails if the two counts do not match.
        !          1983: ** This is an internal self-check only - it is not an essential processing
        !          1984: ** step.
        !          1985: **
        !          1986: ** This is a no-op if NDEBUG is defined.
        !          1987: */
        !          1988: #ifndef NDEBUG
        !          1989: static void checkActiveVdbeCnt(sqlite3 *db){
        !          1990:   Vdbe *p;
        !          1991:   int cnt = 0;
        !          1992:   int nWrite = 0;
        !          1993:   p = db->pVdbe;
        !          1994:   while( p ){
        !          1995:     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
        !          1996:       cnt++;
        !          1997:       if( p->readOnly==0 ) nWrite++;
        !          1998:     }
        !          1999:     p = p->pNext;
        !          2000:   }
        !          2001:   assert( cnt==db->activeVdbeCnt );
        !          2002:   assert( nWrite==db->writeVdbeCnt );
        !          2003: }
        !          2004: #else
        !          2005: #define checkActiveVdbeCnt(x)
        !          2006: #endif
        !          2007: 
        !          2008: /*
        !          2009: ** For every Btree that in database connection db which 
        !          2010: ** has been modified, "trip" or invalidate each cursor in
        !          2011: ** that Btree might have been modified so that the cursor
        !          2012: ** can never be used again.  This happens when a rollback
        !          2013: *** occurs.  We have to trip all the other cursors, even
        !          2014: ** cursor from other VMs in different database connections,
        !          2015: ** so that none of them try to use the data at which they
        !          2016: ** were pointing and which now may have been changed due
        !          2017: ** to the rollback.
        !          2018: **
        !          2019: ** Remember that a rollback can delete tables complete and
        !          2020: ** reorder rootpages.  So it is not sufficient just to save
        !          2021: ** the state of the cursor.  We have to invalidate the cursor
        !          2022: ** so that it is never used again.
        !          2023: */
        !          2024: static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
        !          2025:   int i;
        !          2026:   for(i=0; i<db->nDb; i++){
        !          2027:     Btree *p = db->aDb[i].pBt;
        !          2028:     if( p && sqlite3BtreeIsInTrans(p) ){
        !          2029:       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
        !          2030:     }
        !          2031:   }
        !          2032: }
        !          2033: 
        !          2034: /*
        !          2035: ** If the Vdbe passed as the first argument opened a statement-transaction,
        !          2036: ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
        !          2037: ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
        !          2038: ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
        !          2039: ** statement transaction is commtted.
        !          2040: **
        !          2041: ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
        !          2042: ** Otherwise SQLITE_OK.
        !          2043: */
        !          2044: int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
        !          2045:   sqlite3 *const db = p->db;
        !          2046:   int rc = SQLITE_OK;
        !          2047: 
        !          2048:   /* If p->iStatement is greater than zero, then this Vdbe opened a 
        !          2049:   ** statement transaction that should be closed here. The only exception
        !          2050:   ** is that an IO error may have occured, causing an emergency rollback.
        !          2051:   ** In this case (db->nStatement==0), and there is nothing to do.
        !          2052:   */
        !          2053:   if( db->nStatement && p->iStatement ){
        !          2054:     int i;
        !          2055:     const int iSavepoint = p->iStatement-1;
        !          2056: 
        !          2057:     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
        !          2058:     assert( db->nStatement>0 );
        !          2059:     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
        !          2060: 
        !          2061:     for(i=0; i<db->nDb; i++){ 
        !          2062:       int rc2 = SQLITE_OK;
        !          2063:       Btree *pBt = db->aDb[i].pBt;
        !          2064:       if( pBt ){
        !          2065:         if( eOp==SAVEPOINT_ROLLBACK ){
        !          2066:           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
        !          2067:         }
        !          2068:         if( rc2==SQLITE_OK ){
        !          2069:           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
        !          2070:         }
        !          2071:         if( rc==SQLITE_OK ){
        !          2072:           rc = rc2;
        !          2073:         }
        !          2074:       }
        !          2075:     }
        !          2076:     db->nStatement--;
        !          2077:     p->iStatement = 0;
        !          2078: 
        !          2079:     if( rc==SQLITE_OK ){
        !          2080:       if( eOp==SAVEPOINT_ROLLBACK ){
        !          2081:         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
        !          2082:       }
        !          2083:       if( rc==SQLITE_OK ){
        !          2084:         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
        !          2085:       }
        !          2086:     }
        !          2087: 
        !          2088:     /* If the statement transaction is being rolled back, also restore the 
        !          2089:     ** database handles deferred constraint counter to the value it had when 
        !          2090:     ** the statement transaction was opened.  */
        !          2091:     if( eOp==SAVEPOINT_ROLLBACK ){
        !          2092:       db->nDeferredCons = p->nStmtDefCons;
        !          2093:     }
        !          2094:   }
        !          2095:   return rc;
        !          2096: }
        !          2097: 
        !          2098: /*
        !          2099: ** This function is called when a transaction opened by the database 
        !          2100: ** handle associated with the VM passed as an argument is about to be 
        !          2101: ** committed. If there are outstanding deferred foreign key constraint
        !          2102: ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
        !          2103: **
        !          2104: ** If there are outstanding FK violations and this function returns 
        !          2105: ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
        !          2106: ** an error message to it. Then return SQLITE_ERROR.
        !          2107: */
        !          2108: #ifndef SQLITE_OMIT_FOREIGN_KEY
        !          2109: int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
        !          2110:   sqlite3 *db = p->db;
        !          2111:   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
        !          2112:     p->rc = SQLITE_CONSTRAINT;
        !          2113:     p->errorAction = OE_Abort;
        !          2114:     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
        !          2115:     return SQLITE_ERROR;
        !          2116:   }
        !          2117:   return SQLITE_OK;
        !          2118: }
        !          2119: #endif
        !          2120: 
        !          2121: /*
        !          2122: ** This routine is called the when a VDBE tries to halt.  If the VDBE
        !          2123: ** has made changes and is in autocommit mode, then commit those
        !          2124: ** changes.  If a rollback is needed, then do the rollback.
        !          2125: **
        !          2126: ** This routine is the only way to move the state of a VM from
        !          2127: ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
        !          2128: ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
        !          2129: **
        !          2130: ** Return an error code.  If the commit could not complete because of
        !          2131: ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
        !          2132: ** means the close did not happen and needs to be repeated.
        !          2133: */
        !          2134: int sqlite3VdbeHalt(Vdbe *p){
        !          2135:   int rc;                         /* Used to store transient return codes */
        !          2136:   sqlite3 *db = p->db;
        !          2137: 
        !          2138:   /* This function contains the logic that determines if a statement or
        !          2139:   ** transaction will be committed or rolled back as a result of the
        !          2140:   ** execution of this virtual machine. 
        !          2141:   **
        !          2142:   ** If any of the following errors occur:
        !          2143:   **
        !          2144:   **     SQLITE_NOMEM
        !          2145:   **     SQLITE_IOERR
        !          2146:   **     SQLITE_FULL
        !          2147:   **     SQLITE_INTERRUPT
        !          2148:   **
        !          2149:   ** Then the internal cache might have been left in an inconsistent
        !          2150:   ** state.  We need to rollback the statement transaction, if there is
        !          2151:   ** one, or the complete transaction if there is no statement transaction.
        !          2152:   */
        !          2153: 
        !          2154:   if( p->db->mallocFailed ){
        !          2155:     p->rc = SQLITE_NOMEM;
        !          2156:   }
        !          2157:   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
        !          2158:   closeAllCursors(p);
        !          2159:   if( p->magic!=VDBE_MAGIC_RUN ){
        !          2160:     return SQLITE_OK;
        !          2161:   }
        !          2162:   checkActiveVdbeCnt(db);
        !          2163: 
        !          2164:   /* No commit or rollback needed if the program never started */
        !          2165:   if( p->pc>=0 ){
        !          2166:     int mrc;   /* Primary error code from p->rc */
        !          2167:     int eStatementOp = 0;
        !          2168:     int isSpecialError;            /* Set to true if a 'special' error */
        !          2169: 
        !          2170:     /* Lock all btrees used by the statement */
        !          2171:     sqlite3VdbeEnter(p);
        !          2172: 
        !          2173:     /* Check for one of the special errors */
        !          2174:     mrc = p->rc & 0xff;
        !          2175:     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
        !          2176:     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
        !          2177:                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
        !          2178:     if( isSpecialError ){
        !          2179:       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
        !          2180:       ** no rollback is necessary. Otherwise, at least a savepoint 
        !          2181:       ** transaction must be rolled back to restore the database to a 
        !          2182:       ** consistent state.
        !          2183:       **
        !          2184:       ** Even if the statement is read-only, it is important to perform
        !          2185:       ** a statement or transaction rollback operation. If the error 
        !          2186:       ** occured while writing to the journal, sub-journal or database
        !          2187:       ** file as part of an effort to free up cache space (see function
        !          2188:       ** pagerStress() in pager.c), the rollback is required to restore 
        !          2189:       ** the pager to a consistent state.
        !          2190:       */
        !          2191:       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
        !          2192:         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
        !          2193:           eStatementOp = SAVEPOINT_ROLLBACK;
        !          2194:         }else{
        !          2195:           /* We are forced to roll back the active transaction. Before doing
        !          2196:           ** so, abort any other statements this handle currently has active.
        !          2197:           */
        !          2198:           invalidateCursorsOnModifiedBtrees(db);
        !          2199:           sqlite3RollbackAll(db);
        !          2200:           sqlite3CloseSavepoints(db);
        !          2201:           db->autoCommit = 1;
        !          2202:         }
        !          2203:       }
        !          2204:     }
        !          2205: 
        !          2206:     /* Check for immediate foreign key violations. */
        !          2207:     if( p->rc==SQLITE_OK ){
        !          2208:       sqlite3VdbeCheckFk(p, 0);
        !          2209:     }
        !          2210:   
        !          2211:     /* If the auto-commit flag is set and this is the only active writer 
        !          2212:     ** VM, then we do either a commit or rollback of the current transaction. 
        !          2213:     **
        !          2214:     ** Note: This block also runs if one of the special errors handled 
        !          2215:     ** above has occurred. 
        !          2216:     */
        !          2217:     if( !sqlite3VtabInSync(db) 
        !          2218:      && db->autoCommit 
        !          2219:      && db->writeVdbeCnt==(p->readOnly==0) 
        !          2220:     ){
        !          2221:       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
        !          2222:         rc = sqlite3VdbeCheckFk(p, 1);
        !          2223:         if( rc!=SQLITE_OK ){
        !          2224:           if( NEVER(p->readOnly) ){
        !          2225:             sqlite3VdbeLeave(p);
        !          2226:             return SQLITE_ERROR;
        !          2227:           }
        !          2228:           rc = SQLITE_CONSTRAINT;
        !          2229:         }else{ 
        !          2230:           /* The auto-commit flag is true, the vdbe program was successful 
        !          2231:           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
        !          2232:           ** key constraints to hold up the transaction. This means a commit 
        !          2233:           ** is required. */
        !          2234:           rc = vdbeCommit(db, p);
        !          2235:         }
        !          2236:         if( rc==SQLITE_BUSY && p->readOnly ){
        !          2237:           sqlite3VdbeLeave(p);
        !          2238:           return SQLITE_BUSY;
        !          2239:         }else if( rc!=SQLITE_OK ){
        !          2240:           p->rc = rc;
        !          2241:           sqlite3RollbackAll(db);
        !          2242:         }else{
        !          2243:           db->nDeferredCons = 0;
        !          2244:           sqlite3CommitInternalChanges(db);
        !          2245:         }
        !          2246:       }else{
        !          2247:         sqlite3RollbackAll(db);
        !          2248:       }
        !          2249:       db->nStatement = 0;
        !          2250:     }else if( eStatementOp==0 ){
        !          2251:       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
        !          2252:         eStatementOp = SAVEPOINT_RELEASE;
        !          2253:       }else if( p->errorAction==OE_Abort ){
        !          2254:         eStatementOp = SAVEPOINT_ROLLBACK;
        !          2255:       }else{
        !          2256:         invalidateCursorsOnModifiedBtrees(db);
        !          2257:         sqlite3RollbackAll(db);
        !          2258:         sqlite3CloseSavepoints(db);
        !          2259:         db->autoCommit = 1;
        !          2260:       }
        !          2261:     }
        !          2262:   
        !          2263:     /* If eStatementOp is non-zero, then a statement transaction needs to
        !          2264:     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
        !          2265:     ** do so. If this operation returns an error, and the current statement
        !          2266:     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
        !          2267:     ** current statement error code.
        !          2268:     */
        !          2269:     if( eStatementOp ){
        !          2270:       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
        !          2271:       if( rc ){
        !          2272:         if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){
        !          2273:           p->rc = rc;
        !          2274:           sqlite3DbFree(db, p->zErrMsg);
        !          2275:           p->zErrMsg = 0;
        !          2276:         }
        !          2277:         invalidateCursorsOnModifiedBtrees(db);
        !          2278:         sqlite3RollbackAll(db);
        !          2279:         sqlite3CloseSavepoints(db);
        !          2280:         db->autoCommit = 1;
        !          2281:       }
        !          2282:     }
        !          2283:   
        !          2284:     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
        !          2285:     ** has been rolled back, update the database connection change-counter. 
        !          2286:     */
        !          2287:     if( p->changeCntOn ){
        !          2288:       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
        !          2289:         sqlite3VdbeSetChanges(db, p->nChange);
        !          2290:       }else{
        !          2291:         sqlite3VdbeSetChanges(db, 0);
        !          2292:       }
        !          2293:       p->nChange = 0;
        !          2294:     }
        !          2295:   
        !          2296:     /* Rollback or commit any schema changes that occurred. */
        !          2297:     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
        !          2298:       sqlite3ResetInternalSchema(db, -1);
        !          2299:       db->flags = (db->flags | SQLITE_InternChanges);
        !          2300:     }
        !          2301: 
        !          2302:     /* Release the locks */
        !          2303:     sqlite3VdbeLeave(p);
        !          2304:   }
        !          2305: 
        !          2306:   /* We have successfully halted and closed the VM.  Record this fact. */
        !          2307:   if( p->pc>=0 ){
        !          2308:     db->activeVdbeCnt--;
        !          2309:     if( !p->readOnly ){
        !          2310:       db->writeVdbeCnt--;
        !          2311:     }
        !          2312:     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
        !          2313:   }
        !          2314:   p->magic = VDBE_MAGIC_HALT;
        !          2315:   checkActiveVdbeCnt(db);
        !          2316:   if( p->db->mallocFailed ){
        !          2317:     p->rc = SQLITE_NOMEM;
        !          2318:   }
        !          2319: 
        !          2320:   /* If the auto-commit flag is set to true, then any locks that were held
        !          2321:   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
        !          2322:   ** to invoke any required unlock-notify callbacks.
        !          2323:   */
        !          2324:   if( db->autoCommit ){
        !          2325:     sqlite3ConnectionUnlocked(db);
        !          2326:   }
        !          2327: 
        !          2328:   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
        !          2329:   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
        !          2330: }
        !          2331: 
        !          2332: 
        !          2333: /*
        !          2334: ** Each VDBE holds the result of the most recent sqlite3_step() call
        !          2335: ** in p->rc.  This routine sets that result back to SQLITE_OK.
        !          2336: */
        !          2337: void sqlite3VdbeResetStepResult(Vdbe *p){
        !          2338:   p->rc = SQLITE_OK;
        !          2339: }
        !          2340: 
        !          2341: /*
        !          2342: ** Copy the error code and error message belonging to the VDBE passed
        !          2343: ** as the first argument to its database handle (so that they will be 
        !          2344: ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
        !          2345: **
        !          2346: ** This function does not clear the VDBE error code or message, just
        !          2347: ** copies them to the database handle.
        !          2348: */
        !          2349: int sqlite3VdbeTransferError(Vdbe *p){
        !          2350:   sqlite3 *db = p->db;
        !          2351:   int rc = p->rc;
        !          2352:   if( p->zErrMsg ){
        !          2353:     u8 mallocFailed = db->mallocFailed;
        !          2354:     sqlite3BeginBenignMalloc();
        !          2355:     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
        !          2356:     sqlite3EndBenignMalloc();
        !          2357:     db->mallocFailed = mallocFailed;
        !          2358:     db->errCode = rc;
        !          2359:   }else{
        !          2360:     sqlite3Error(db, rc, 0);
        !          2361:   }
        !          2362:   return rc;
        !          2363: }
        !          2364: 
        !          2365: /*
        !          2366: ** Clean up a VDBE after execution but do not delete the VDBE just yet.
        !          2367: ** Write any error messages into *pzErrMsg.  Return the result code.
        !          2368: **
        !          2369: ** After this routine is run, the VDBE should be ready to be executed
        !          2370: ** again.
        !          2371: **
        !          2372: ** To look at it another way, this routine resets the state of the
        !          2373: ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
        !          2374: ** VDBE_MAGIC_INIT.
        !          2375: */
        !          2376: int sqlite3VdbeReset(Vdbe *p){
        !          2377:   sqlite3 *db;
        !          2378:   db = p->db;
        !          2379: 
        !          2380:   /* If the VM did not run to completion or if it encountered an
        !          2381:   ** error, then it might not have been halted properly.  So halt
        !          2382:   ** it now.
        !          2383:   */
        !          2384:   sqlite3VdbeHalt(p);
        !          2385: 
        !          2386:   /* If the VDBE has be run even partially, then transfer the error code
        !          2387:   ** and error message from the VDBE into the main database structure.  But
        !          2388:   ** if the VDBE has just been set to run but has not actually executed any
        !          2389:   ** instructions yet, leave the main database error information unchanged.
        !          2390:   */
        !          2391:   if( p->pc>=0 ){
        !          2392:     sqlite3VdbeTransferError(p);
        !          2393:     sqlite3DbFree(db, p->zErrMsg);
        !          2394:     p->zErrMsg = 0;
        !          2395:     if( p->runOnlyOnce ) p->expired = 1;
        !          2396:   }else if( p->rc && p->expired ){
        !          2397:     /* The expired flag was set on the VDBE before the first call
        !          2398:     ** to sqlite3_step(). For consistency (since sqlite3_step() was
        !          2399:     ** called), set the database error in this case as well.
        !          2400:     */
        !          2401:     sqlite3Error(db, p->rc, 0);
        !          2402:     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
        !          2403:     sqlite3DbFree(db, p->zErrMsg);
        !          2404:     p->zErrMsg = 0;
        !          2405:   }
        !          2406: 
        !          2407:   /* Reclaim all memory used by the VDBE
        !          2408:   */
        !          2409:   Cleanup(p);
        !          2410: 
        !          2411:   /* Save profiling information from this VDBE run.
        !          2412:   */
        !          2413: #ifdef VDBE_PROFILE
        !          2414:   {
        !          2415:     FILE *out = fopen("vdbe_profile.out", "a");
        !          2416:     if( out ){
        !          2417:       int i;
        !          2418:       fprintf(out, "---- ");
        !          2419:       for(i=0; i<p->nOp; i++){
        !          2420:         fprintf(out, "%02x", p->aOp[i].opcode);
        !          2421:       }
        !          2422:       fprintf(out, "\n");
        !          2423:       for(i=0; i<p->nOp; i++){
        !          2424:         fprintf(out, "%6d %10lld %8lld ",
        !          2425:            p->aOp[i].cnt,
        !          2426:            p->aOp[i].cycles,
        !          2427:            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
        !          2428:         );
        !          2429:         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
        !          2430:       }
        !          2431:       fclose(out);
        !          2432:     }
        !          2433:   }
        !          2434: #endif
        !          2435:   p->magic = VDBE_MAGIC_INIT;
        !          2436:   return p->rc & db->errMask;
        !          2437: }
        !          2438:  
        !          2439: /*
        !          2440: ** Clean up and delete a VDBE after execution.  Return an integer which is
        !          2441: ** the result code.  Write any error message text into *pzErrMsg.
        !          2442: */
        !          2443: int sqlite3VdbeFinalize(Vdbe *p){
        !          2444:   int rc = SQLITE_OK;
        !          2445:   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
        !          2446:     rc = sqlite3VdbeReset(p);
        !          2447:     assert( (rc & p->db->errMask)==rc );
        !          2448:   }
        !          2449:   sqlite3VdbeDelete(p);
        !          2450:   return rc;
        !          2451: }
        !          2452: 
        !          2453: /*
        !          2454: ** Call the destructor for each auxdata entry in pVdbeFunc for which
        !          2455: ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
        !          2456: ** are always destroyed.  To destroy all auxdata entries, call this
        !          2457: ** routine with mask==0.
        !          2458: */
        !          2459: void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
        !          2460:   int i;
        !          2461:   for(i=0; i<pVdbeFunc->nAux; i++){
        !          2462:     struct AuxData *pAux = &pVdbeFunc->apAux[i];
        !          2463:     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
        !          2464:       if( pAux->xDelete ){
        !          2465:         pAux->xDelete(pAux->pAux);
        !          2466:       }
        !          2467:       pAux->pAux = 0;
        !          2468:     }
        !          2469:   }
        !          2470: }
        !          2471: 
        !          2472: /*
        !          2473: ** Free all memory associated with the Vdbe passed as the second argument.
        !          2474: ** The difference between this function and sqlite3VdbeDelete() is that
        !          2475: ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
        !          2476: ** the database connection.
        !          2477: */
        !          2478: void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
        !          2479:   SubProgram *pSub, *pNext;
        !          2480:   int i;
        !          2481:   assert( p->db==0 || p->db==db );
        !          2482:   releaseMemArray(p->aVar, p->nVar);
        !          2483:   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
        !          2484:   for(pSub=p->pProgram; pSub; pSub=pNext){
        !          2485:     pNext = pSub->pNext;
        !          2486:     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
        !          2487:     sqlite3DbFree(db, pSub);
        !          2488:   }
        !          2489:   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
        !          2490:   vdbeFreeOpArray(db, p->aOp, p->nOp);
        !          2491:   sqlite3DbFree(db, p->aLabel);
        !          2492:   sqlite3DbFree(db, p->aColName);
        !          2493:   sqlite3DbFree(db, p->zSql);
        !          2494:   sqlite3DbFree(db, p->pFree);
        !          2495: #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
        !          2496:   sqlite3DbFree(db, p->zExplain);
        !          2497:   sqlite3DbFree(db, p->pExplain);
        !          2498: #endif
        !          2499:   sqlite3DbFree(db, p);
        !          2500: }
        !          2501: 
        !          2502: /*
        !          2503: ** Delete an entire VDBE.
        !          2504: */
        !          2505: void sqlite3VdbeDelete(Vdbe *p){
        !          2506:   sqlite3 *db;
        !          2507: 
        !          2508:   if( NEVER(p==0) ) return;
        !          2509:   db = p->db;
        !          2510:   if( p->pPrev ){
        !          2511:     p->pPrev->pNext = p->pNext;
        !          2512:   }else{
        !          2513:     assert( db->pVdbe==p );
        !          2514:     db->pVdbe = p->pNext;
        !          2515:   }
        !          2516:   if( p->pNext ){
        !          2517:     p->pNext->pPrev = p->pPrev;
        !          2518:   }
        !          2519:   p->magic = VDBE_MAGIC_DEAD;
        !          2520:   p->db = 0;
        !          2521:   sqlite3VdbeDeleteObject(db, p);
        !          2522: }
        !          2523: 
        !          2524: /*
        !          2525: ** Make sure the cursor p is ready to read or write the row to which it
        !          2526: ** was last positioned.  Return an error code if an OOM fault or I/O error
        !          2527: ** prevents us from positioning the cursor to its correct position.
        !          2528: **
        !          2529: ** If a MoveTo operation is pending on the given cursor, then do that
        !          2530: ** MoveTo now.  If no move is pending, check to see if the row has been
        !          2531: ** deleted out from under the cursor and if it has, mark the row as
        !          2532: ** a NULL row.
        !          2533: **
        !          2534: ** If the cursor is already pointing to the correct row and that row has
        !          2535: ** not been deleted out from under the cursor, then this routine is a no-op.
        !          2536: */
        !          2537: int sqlite3VdbeCursorMoveto(VdbeCursor *p){
        !          2538:   if( p->deferredMoveto ){
        !          2539:     int res, rc;
        !          2540: #ifdef SQLITE_TEST
        !          2541:     extern int sqlite3_search_count;
        !          2542: #endif
        !          2543:     assert( p->isTable );
        !          2544:     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
        !          2545:     if( rc ) return rc;
        !          2546:     p->lastRowid = p->movetoTarget;
        !          2547:     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
        !          2548:     p->rowidIsValid = 1;
        !          2549: #ifdef SQLITE_TEST
        !          2550:     sqlite3_search_count++;
        !          2551: #endif
        !          2552:     p->deferredMoveto = 0;
        !          2553:     p->cacheStatus = CACHE_STALE;
        !          2554:   }else if( ALWAYS(p->pCursor) ){
        !          2555:     int hasMoved;
        !          2556:     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
        !          2557:     if( rc ) return rc;
        !          2558:     if( hasMoved ){
        !          2559:       p->cacheStatus = CACHE_STALE;
        !          2560:       p->nullRow = 1;
        !          2561:     }
        !          2562:   }
        !          2563:   return SQLITE_OK;
        !          2564: }
        !          2565: 
        !          2566: /*
        !          2567: ** The following functions:
        !          2568: **
        !          2569: ** sqlite3VdbeSerialType()
        !          2570: ** sqlite3VdbeSerialTypeLen()
        !          2571: ** sqlite3VdbeSerialLen()
        !          2572: ** sqlite3VdbeSerialPut()
        !          2573: ** sqlite3VdbeSerialGet()
        !          2574: **
        !          2575: ** encapsulate the code that serializes values for storage in SQLite
        !          2576: ** data and index records. Each serialized value consists of a
        !          2577: ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
        !          2578: ** integer, stored as a varint.
        !          2579: **
        !          2580: ** In an SQLite index record, the serial type is stored directly before
        !          2581: ** the blob of data that it corresponds to. In a table record, all serial
        !          2582: ** types are stored at the start of the record, and the blobs of data at
        !          2583: ** the end. Hence these functions allow the caller to handle the
        !          2584: ** serial-type and data blob seperately.
        !          2585: **
        !          2586: ** The following table describes the various storage classes for data:
        !          2587: **
        !          2588: **   serial type        bytes of data      type
        !          2589: **   --------------     ---------------    ---------------
        !          2590: **      0                     0            NULL
        !          2591: **      1                     1            signed integer
        !          2592: **      2                     2            signed integer
        !          2593: **      3                     3            signed integer
        !          2594: **      4                     4            signed integer
        !          2595: **      5                     6            signed integer
        !          2596: **      6                     8            signed integer
        !          2597: **      7                     8            IEEE float
        !          2598: **      8                     0            Integer constant 0
        !          2599: **      9                     0            Integer constant 1
        !          2600: **     10,11                               reserved for expansion
        !          2601: **    N>=12 and even       (N-12)/2        BLOB
        !          2602: **    N>=13 and odd        (N-13)/2        text
        !          2603: **
        !          2604: ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
        !          2605: ** of SQLite will not understand those serial types.
        !          2606: */
        !          2607: 
        !          2608: /*
        !          2609: ** Return the serial-type for the value stored in pMem.
        !          2610: */
        !          2611: u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
        !          2612:   int flags = pMem->flags;
        !          2613:   int n;
        !          2614: 
        !          2615:   if( flags&MEM_Null ){
        !          2616:     return 0;
        !          2617:   }
        !          2618:   if( flags&MEM_Int ){
        !          2619:     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
        !          2620: #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
        !          2621:     i64 i = pMem->u.i;
        !          2622:     u64 u;
        !          2623:     if( file_format>=4 && (i&1)==i ){
        !          2624:       return 8+(u32)i;
        !          2625:     }
        !          2626:     if( i<0 ){
        !          2627:       if( i<(-MAX_6BYTE) ) return 6;
        !          2628:       /* Previous test prevents:  u = -(-9223372036854775808) */
        !          2629:       u = -i;
        !          2630:     }else{
        !          2631:       u = i;
        !          2632:     }
        !          2633:     if( u<=127 ) return 1;
        !          2634:     if( u<=32767 ) return 2;
        !          2635:     if( u<=8388607 ) return 3;
        !          2636:     if( u<=2147483647 ) return 4;
        !          2637:     if( u<=MAX_6BYTE ) return 5;
        !          2638:     return 6;
        !          2639:   }
        !          2640:   if( flags&MEM_Real ){
        !          2641:     return 7;
        !          2642:   }
        !          2643:   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
        !          2644:   n = pMem->n;
        !          2645:   if( flags & MEM_Zero ){
        !          2646:     n += pMem->u.nZero;
        !          2647:   }
        !          2648:   assert( n>=0 );
        !          2649:   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
        !          2650: }
        !          2651: 
        !          2652: /*
        !          2653: ** Return the length of the data corresponding to the supplied serial-type.
        !          2654: */
        !          2655: u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
        !          2656:   if( serial_type>=12 ){
        !          2657:     return (serial_type-12)/2;
        !          2658:   }else{
        !          2659:     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
        !          2660:     return aSize[serial_type];
        !          2661:   }
        !          2662: }
        !          2663: 
        !          2664: /*
        !          2665: ** If we are on an architecture with mixed-endian floating 
        !          2666: ** points (ex: ARM7) then swap the lower 4 bytes with the 
        !          2667: ** upper 4 bytes.  Return the result.
        !          2668: **
        !          2669: ** For most architectures, this is a no-op.
        !          2670: **
        !          2671: ** (later):  It is reported to me that the mixed-endian problem
        !          2672: ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
        !          2673: ** that early versions of GCC stored the two words of a 64-bit
        !          2674: ** float in the wrong order.  And that error has been propagated
        !          2675: ** ever since.  The blame is not necessarily with GCC, though.
        !          2676: ** GCC might have just copying the problem from a prior compiler.
        !          2677: ** I am also told that newer versions of GCC that follow a different
        !          2678: ** ABI get the byte order right.
        !          2679: **
        !          2680: ** Developers using SQLite on an ARM7 should compile and run their
        !          2681: ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
        !          2682: ** enabled, some asserts below will ensure that the byte order of
        !          2683: ** floating point values is correct.
        !          2684: **
        !          2685: ** (2007-08-30)  Frank van Vugt has studied this problem closely
        !          2686: ** and has send his findings to the SQLite developers.  Frank
        !          2687: ** writes that some Linux kernels offer floating point hardware
        !          2688: ** emulation that uses only 32-bit mantissas instead of a full 
        !          2689: ** 48-bits as required by the IEEE standard.  (This is the
        !          2690: ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
        !          2691: ** byte swapping becomes very complicated.  To avoid problems,
        !          2692: ** the necessary byte swapping is carried out using a 64-bit integer
        !          2693: ** rather than a 64-bit float.  Frank assures us that the code here
        !          2694: ** works for him.  We, the developers, have no way to independently
        !          2695: ** verify this, but Frank seems to know what he is talking about
        !          2696: ** so we trust him.
        !          2697: */
        !          2698: #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
        !          2699: static u64 floatSwap(u64 in){
        !          2700:   union {
        !          2701:     u64 r;
        !          2702:     u32 i[2];
        !          2703:   } u;
        !          2704:   u32 t;
        !          2705: 
        !          2706:   u.r = in;
        !          2707:   t = u.i[0];
        !          2708:   u.i[0] = u.i[1];
        !          2709:   u.i[1] = t;
        !          2710:   return u.r;
        !          2711: }
        !          2712: # define swapMixedEndianFloat(X)  X = floatSwap(X)
        !          2713: #else
        !          2714: # define swapMixedEndianFloat(X)
        !          2715: #endif
        !          2716: 
        !          2717: /*
        !          2718: ** Write the serialized data blob for the value stored in pMem into 
        !          2719: ** buf. It is assumed that the caller has allocated sufficient space.
        !          2720: ** Return the number of bytes written.
        !          2721: **
        !          2722: ** nBuf is the amount of space left in buf[].  nBuf must always be
        !          2723: ** large enough to hold the entire field.  Except, if the field is
        !          2724: ** a blob with a zero-filled tail, then buf[] might be just the right
        !          2725: ** size to hold everything except for the zero-filled tail.  If buf[]
        !          2726: ** is only big enough to hold the non-zero prefix, then only write that
        !          2727: ** prefix into buf[].  But if buf[] is large enough to hold both the
        !          2728: ** prefix and the tail then write the prefix and set the tail to all
        !          2729: ** zeros.
        !          2730: **
        !          2731: ** Return the number of bytes actually written into buf[].  The number
        !          2732: ** of bytes in the zero-filled tail is included in the return value only
        !          2733: ** if those bytes were zeroed in buf[].
        !          2734: */ 
        !          2735: u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
        !          2736:   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
        !          2737:   u32 len;
        !          2738: 
        !          2739:   /* Integer and Real */
        !          2740:   if( serial_type<=7 && serial_type>0 ){
        !          2741:     u64 v;
        !          2742:     u32 i;
        !          2743:     if( serial_type==7 ){
        !          2744:       assert( sizeof(v)==sizeof(pMem->r) );
        !          2745:       memcpy(&v, &pMem->r, sizeof(v));
        !          2746:       swapMixedEndianFloat(v);
        !          2747:     }else{
        !          2748:       v = pMem->u.i;
        !          2749:     }
        !          2750:     len = i = sqlite3VdbeSerialTypeLen(serial_type);
        !          2751:     assert( len<=(u32)nBuf );
        !          2752:     while( i-- ){
        !          2753:       buf[i] = (u8)(v&0xFF);
        !          2754:       v >>= 8;
        !          2755:     }
        !          2756:     return len;
        !          2757:   }
        !          2758: 
        !          2759:   /* String or blob */
        !          2760:   if( serial_type>=12 ){
        !          2761:     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
        !          2762:              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
        !          2763:     assert( pMem->n<=nBuf );
        !          2764:     len = pMem->n;
        !          2765:     memcpy(buf, pMem->z, len);
        !          2766:     if( pMem->flags & MEM_Zero ){
        !          2767:       len += pMem->u.nZero;
        !          2768:       assert( nBuf>=0 );
        !          2769:       if( len > (u32)nBuf ){
        !          2770:         len = (u32)nBuf;
        !          2771:       }
        !          2772:       memset(&buf[pMem->n], 0, len-pMem->n);
        !          2773:     }
        !          2774:     return len;
        !          2775:   }
        !          2776: 
        !          2777:   /* NULL or constants 0 or 1 */
        !          2778:   return 0;
        !          2779: }
        !          2780: 
        !          2781: /*
        !          2782: ** Deserialize the data blob pointed to by buf as serial type serial_type
        !          2783: ** and store the result in pMem.  Return the number of bytes read.
        !          2784: */ 
        !          2785: u32 sqlite3VdbeSerialGet(
        !          2786:   const unsigned char *buf,     /* Buffer to deserialize from */
        !          2787:   u32 serial_type,              /* Serial type to deserialize */
        !          2788:   Mem *pMem                     /* Memory cell to write value into */
        !          2789: ){
        !          2790:   switch( serial_type ){
        !          2791:     case 10:   /* Reserved for future use */
        !          2792:     case 11:   /* Reserved for future use */
        !          2793:     case 0: {  /* NULL */
        !          2794:       pMem->flags = MEM_Null;
        !          2795:       break;
        !          2796:     }
        !          2797:     case 1: { /* 1-byte signed integer */
        !          2798:       pMem->u.i = (signed char)buf[0];
        !          2799:       pMem->flags = MEM_Int;
        !          2800:       return 1;
        !          2801:     }
        !          2802:     case 2: { /* 2-byte signed integer */
        !          2803:       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
        !          2804:       pMem->flags = MEM_Int;
        !          2805:       return 2;
        !          2806:     }
        !          2807:     case 3: { /* 3-byte signed integer */
        !          2808:       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
        !          2809:       pMem->flags = MEM_Int;
        !          2810:       return 3;
        !          2811:     }
        !          2812:     case 4: { /* 4-byte signed integer */
        !          2813:       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
        !          2814:       pMem->flags = MEM_Int;
        !          2815:       return 4;
        !          2816:     }
        !          2817:     case 5: { /* 6-byte signed integer */
        !          2818:       u64 x = (((signed char)buf[0])<<8) | buf[1];
        !          2819:       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
        !          2820:       x = (x<<32) | y;
        !          2821:       pMem->u.i = *(i64*)&x;
        !          2822:       pMem->flags = MEM_Int;
        !          2823:       return 6;
        !          2824:     }
        !          2825:     case 6:   /* 8-byte signed integer */
        !          2826:     case 7: { /* IEEE floating point */
        !          2827:       u64 x;
        !          2828:       u32 y;
        !          2829: #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
        !          2830:       /* Verify that integers and floating point values use the same
        !          2831:       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
        !          2832:       ** defined that 64-bit floating point values really are mixed
        !          2833:       ** endian.
        !          2834:       */
        !          2835:       static const u64 t1 = ((u64)0x3ff00000)<<32;
        !          2836:       static const double r1 = 1.0;
        !          2837:       u64 t2 = t1;
        !          2838:       swapMixedEndianFloat(t2);
        !          2839:       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
        !          2840: #endif
        !          2841: 
        !          2842:       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
        !          2843:       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
        !          2844:       x = (x<<32) | y;
        !          2845:       if( serial_type==6 ){
        !          2846:         pMem->u.i = *(i64*)&x;
        !          2847:         pMem->flags = MEM_Int;
        !          2848:       }else{
        !          2849:         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
        !          2850:         swapMixedEndianFloat(x);
        !          2851:         memcpy(&pMem->r, &x, sizeof(x));
        !          2852:         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
        !          2853:       }
        !          2854:       return 8;
        !          2855:     }
        !          2856:     case 8:    /* Integer 0 */
        !          2857:     case 9: {  /* Integer 1 */
        !          2858:       pMem->u.i = serial_type-8;
        !          2859:       pMem->flags = MEM_Int;
        !          2860:       return 0;
        !          2861:     }
        !          2862:     default: {
        !          2863:       u32 len = (serial_type-12)/2;
        !          2864:       pMem->z = (char *)buf;
        !          2865:       pMem->n = len;
        !          2866:       pMem->xDel = 0;
        !          2867:       if( serial_type&0x01 ){
        !          2868:         pMem->flags = MEM_Str | MEM_Ephem;
        !          2869:       }else{
        !          2870:         pMem->flags = MEM_Blob | MEM_Ephem;
        !          2871:       }
        !          2872:       return len;
        !          2873:     }
        !          2874:   }
        !          2875:   return 0;
        !          2876: }
        !          2877: 
        !          2878: /*
        !          2879: ** This routine is used to allocate sufficient space for an UnpackedRecord
        !          2880: ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
        !          2881: ** the first argument is a pointer to KeyInfo structure pKeyInfo.
        !          2882: **
        !          2883: ** The space is either allocated using sqlite3DbMallocRaw() or from within
        !          2884: ** the unaligned buffer passed via the second and third arguments (presumably
        !          2885: ** stack space). If the former, then *ppFree is set to a pointer that should
        !          2886: ** be eventually freed by the caller using sqlite3DbFree(). Or, if the 
        !          2887: ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
        !          2888: ** before returning.
        !          2889: **
        !          2890: ** If an OOM error occurs, NULL is returned.
        !          2891: */
        !          2892: UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
        !          2893:   KeyInfo *pKeyInfo,              /* Description of the record */
        !          2894:   char *pSpace,                   /* Unaligned space available */
        !          2895:   int szSpace,                    /* Size of pSpace[] in bytes */
        !          2896:   char **ppFree                   /* OUT: Caller should free this pointer */
        !          2897: ){
        !          2898:   UnpackedRecord *p;              /* Unpacked record to return */
        !          2899:   int nOff;                       /* Increment pSpace by nOff to align it */
        !          2900:   int nByte;                      /* Number of bytes required for *p */
        !          2901: 
        !          2902:   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
        !          2903:   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
        !          2904:   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
        !          2905:   */
        !          2906:   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
        !          2907:   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
        !          2908:   if( nByte>szSpace+nOff ){
        !          2909:     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
        !          2910:     *ppFree = (char *)p;
        !          2911:     if( !p ) return 0;
        !          2912:   }else{
        !          2913:     p = (UnpackedRecord*)&pSpace[nOff];
        !          2914:     *ppFree = 0;
        !          2915:   }
        !          2916: 
        !          2917:   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
        !          2918:   p->pKeyInfo = pKeyInfo;
        !          2919:   p->nField = pKeyInfo->nField + 1;
        !          2920:   return p;
        !          2921: }
        !          2922: 
        !          2923: /*
        !          2924: ** Given the nKey-byte encoding of a record in pKey[], populate the 
        !          2925: ** UnpackedRecord structure indicated by the fourth argument with the
        !          2926: ** contents of the decoded record.
        !          2927: */ 
        !          2928: void sqlite3VdbeRecordUnpack(
        !          2929:   KeyInfo *pKeyInfo,     /* Information about the record format */
        !          2930:   int nKey,              /* Size of the binary record */
        !          2931:   const void *pKey,      /* The binary record */
        !          2932:   UnpackedRecord *p      /* Populate this structure before returning. */
        !          2933: ){
        !          2934:   const unsigned char *aKey = (const unsigned char *)pKey;
        !          2935:   int d; 
        !          2936:   u32 idx;                        /* Offset in aKey[] to read from */
        !          2937:   u16 u;                          /* Unsigned loop counter */
        !          2938:   u32 szHdr;
        !          2939:   Mem *pMem = p->aMem;
        !          2940: 
        !          2941:   p->flags = 0;
        !          2942:   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
        !          2943:   idx = getVarint32(aKey, szHdr);
        !          2944:   d = szHdr;
        !          2945:   u = 0;
        !          2946:   while( idx<szHdr && u<p->nField && d<=nKey ){
        !          2947:     u32 serial_type;
        !          2948: 
        !          2949:     idx += getVarint32(&aKey[idx], serial_type);
        !          2950:     pMem->enc = pKeyInfo->enc;
        !          2951:     pMem->db = pKeyInfo->db;
        !          2952:     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
        !          2953:     pMem->zMalloc = 0;
        !          2954:     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
        !          2955:     pMem++;
        !          2956:     u++;
        !          2957:   }
        !          2958:   assert( u<=pKeyInfo->nField + 1 );
        !          2959:   p->nField = u;
        !          2960: }
        !          2961: 
        !          2962: /*
        !          2963: ** This function compares the two table rows or index records
        !          2964: ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
        !          2965: ** or positive integer if key1 is less than, equal to or 
        !          2966: ** greater than key2.  The {nKey1, pKey1} key must be a blob
        !          2967: ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
        !          2968: ** key must be a parsed key such as obtained from
        !          2969: ** sqlite3VdbeParseRecord.
        !          2970: **
        !          2971: ** Key1 and Key2 do not have to contain the same number of fields.
        !          2972: ** The key with fewer fields is usually compares less than the 
        !          2973: ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
        !          2974: ** and the common prefixes are equal, then key1 is less than key2.
        !          2975: ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
        !          2976: ** equal, then the keys are considered to be equal and
        !          2977: ** the parts beyond the common prefix are ignored.
        !          2978: */
        !          2979: int sqlite3VdbeRecordCompare(
        !          2980:   int nKey1, const void *pKey1, /* Left key */
        !          2981:   UnpackedRecord *pPKey2        /* Right key */
        !          2982: ){
        !          2983:   int d1;            /* Offset into aKey[] of next data element */
        !          2984:   u32 idx1;          /* Offset into aKey[] of next header element */
        !          2985:   u32 szHdr1;        /* Number of bytes in header */
        !          2986:   int i = 0;
        !          2987:   int nField;
        !          2988:   int rc = 0;
        !          2989:   const unsigned char *aKey1 = (const unsigned char *)pKey1;
        !          2990:   KeyInfo *pKeyInfo;
        !          2991:   Mem mem1;
        !          2992: 
        !          2993:   pKeyInfo = pPKey2->pKeyInfo;
        !          2994:   mem1.enc = pKeyInfo->enc;
        !          2995:   mem1.db = pKeyInfo->db;
        !          2996:   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
        !          2997:   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
        !          2998: 
        !          2999:   /* Compilers may complain that mem1.u.i is potentially uninitialized.
        !          3000:   ** We could initialize it, as shown here, to silence those complaints.
        !          3001:   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
        !          3002:   ** the unnecessary initialization has a measurable negative performance
        !          3003:   ** impact, since this routine is a very high runner.  And so, we choose
        !          3004:   ** to ignore the compiler warnings and leave this variable uninitialized.
        !          3005:   */
        !          3006:   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
        !          3007:   
        !          3008:   idx1 = getVarint32(aKey1, szHdr1);
        !          3009:   d1 = szHdr1;
        !          3010:   nField = pKeyInfo->nField;
        !          3011:   while( idx1<szHdr1 && i<pPKey2->nField ){
        !          3012:     u32 serial_type1;
        !          3013: 
        !          3014:     /* Read the serial types for the next element in each key. */
        !          3015:     idx1 += getVarint32( aKey1+idx1, serial_type1 );
        !          3016:     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
        !          3017: 
        !          3018:     /* Extract the values to be compared.
        !          3019:     */
        !          3020:     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
        !          3021: 
        !          3022:     /* Do the comparison
        !          3023:     */
        !          3024:     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
        !          3025:                            i<nField ? pKeyInfo->aColl[i] : 0);
        !          3026:     if( rc!=0 ){
        !          3027:       assert( mem1.zMalloc==0 );  /* See comment below */
        !          3028: 
        !          3029:       /* Invert the result if we are using DESC sort order. */
        !          3030:       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
        !          3031:         rc = -rc;
        !          3032:       }
        !          3033:     
        !          3034:       /* If the PREFIX_SEARCH flag is set and all fields except the final
        !          3035:       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
        !          3036:       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
        !          3037:       ** This is used by the OP_IsUnique opcode.
        !          3038:       */
        !          3039:       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
        !          3040:         assert( idx1==szHdr1 && rc );
        !          3041:         assert( mem1.flags & MEM_Int );
        !          3042:         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
        !          3043:         pPKey2->rowid = mem1.u.i;
        !          3044:       }
        !          3045:     
        !          3046:       return rc;
        !          3047:     }
        !          3048:     i++;
        !          3049:   }
        !          3050: 
        !          3051:   /* No memory allocation is ever used on mem1.  Prove this using
        !          3052:   ** the following assert().  If the assert() fails, it indicates a
        !          3053:   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
        !          3054:   */
        !          3055:   assert( mem1.zMalloc==0 );
        !          3056: 
        !          3057:   /* rc==0 here means that one of the keys ran out of fields and
        !          3058:   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
        !          3059:   ** flag is set, then break the tie by treating key2 as larger.
        !          3060:   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
        !          3061:   ** are considered to be equal.  Otherwise, the longer key is the 
        !          3062:   ** larger.  As it happens, the pPKey2 will always be the longer
        !          3063:   ** if there is a difference.
        !          3064:   */
        !          3065:   assert( rc==0 );
        !          3066:   if( pPKey2->flags & UNPACKED_INCRKEY ){
        !          3067:     rc = -1;
        !          3068:   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
        !          3069:     /* Leave rc==0 */
        !          3070:   }else if( idx1<szHdr1 ){
        !          3071:     rc = 1;
        !          3072:   }
        !          3073:   return rc;
        !          3074: }
        !          3075:  
        !          3076: 
        !          3077: /*
        !          3078: ** pCur points at an index entry created using the OP_MakeRecord opcode.
        !          3079: ** Read the rowid (the last field in the record) and store it in *rowid.
        !          3080: ** Return SQLITE_OK if everything works, or an error code otherwise.
        !          3081: **
        !          3082: ** pCur might be pointing to text obtained from a corrupt database file.
        !          3083: ** So the content cannot be trusted.  Do appropriate checks on the content.
        !          3084: */
        !          3085: int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
        !          3086:   i64 nCellKey = 0;
        !          3087:   int rc;
        !          3088:   u32 szHdr;        /* Size of the header */
        !          3089:   u32 typeRowid;    /* Serial type of the rowid */
        !          3090:   u32 lenRowid;     /* Size of the rowid */
        !          3091:   Mem m, v;
        !          3092: 
        !          3093:   UNUSED_PARAMETER(db);
        !          3094: 
        !          3095:   /* Get the size of the index entry.  Only indices entries of less
        !          3096:   ** than 2GiB are support - anything large must be database corruption.
        !          3097:   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
        !          3098:   ** this code can safely assume that nCellKey is 32-bits  
        !          3099:   */
        !          3100:   assert( sqlite3BtreeCursorIsValid(pCur) );
        !          3101:   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
        !          3102:   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
        !          3103:   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
        !          3104: 
        !          3105:   /* Read in the complete content of the index entry */
        !          3106:   memset(&m, 0, sizeof(m));
        !          3107:   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
        !          3108:   if( rc ){
        !          3109:     return rc;
        !          3110:   }
        !          3111: 
        !          3112:   /* The index entry must begin with a header size */
        !          3113:   (void)getVarint32((u8*)m.z, szHdr);
        !          3114:   testcase( szHdr==3 );
        !          3115:   testcase( szHdr==m.n );
        !          3116:   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
        !          3117:     goto idx_rowid_corruption;
        !          3118:   }
        !          3119: 
        !          3120:   /* The last field of the index should be an integer - the ROWID.
        !          3121:   ** Verify that the last entry really is an integer. */
        !          3122:   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
        !          3123:   testcase( typeRowid==1 );
        !          3124:   testcase( typeRowid==2 );
        !          3125:   testcase( typeRowid==3 );
        !          3126:   testcase( typeRowid==4 );
        !          3127:   testcase( typeRowid==5 );
        !          3128:   testcase( typeRowid==6 );
        !          3129:   testcase( typeRowid==8 );
        !          3130:   testcase( typeRowid==9 );
        !          3131:   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
        !          3132:     goto idx_rowid_corruption;
        !          3133:   }
        !          3134:   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
        !          3135:   testcase( (u32)m.n==szHdr+lenRowid );
        !          3136:   if( unlikely((u32)m.n<szHdr+lenRowid) ){
        !          3137:     goto idx_rowid_corruption;
        !          3138:   }
        !          3139: 
        !          3140:   /* Fetch the integer off the end of the index record */
        !          3141:   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
        !          3142:   *rowid = v.u.i;
        !          3143:   sqlite3VdbeMemRelease(&m);
        !          3144:   return SQLITE_OK;
        !          3145: 
        !          3146:   /* Jump here if database corruption is detected after m has been
        !          3147:   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
        !          3148: idx_rowid_corruption:
        !          3149:   testcase( m.zMalloc!=0 );
        !          3150:   sqlite3VdbeMemRelease(&m);
        !          3151:   return SQLITE_CORRUPT_BKPT;
        !          3152: }
        !          3153: 
        !          3154: /*
        !          3155: ** Compare the key of the index entry that cursor pC is pointing to against
        !          3156: ** the key string in pUnpacked.  Write into *pRes a number
        !          3157: ** that is negative, zero, or positive if pC is less than, equal to,
        !          3158: ** or greater than pUnpacked.  Return SQLITE_OK on success.
        !          3159: **
        !          3160: ** pUnpacked is either created without a rowid or is truncated so that it
        !          3161: ** omits the rowid at the end.  The rowid at the end of the index entry
        !          3162: ** is ignored as well.  Hence, this routine only compares the prefixes 
        !          3163: ** of the keys prior to the final rowid, not the entire key.
        !          3164: */
        !          3165: int sqlite3VdbeIdxKeyCompare(
        !          3166:   VdbeCursor *pC,             /* The cursor to compare against */
        !          3167:   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
        !          3168:   int *res                    /* Write the comparison result here */
        !          3169: ){
        !          3170:   i64 nCellKey = 0;
        !          3171:   int rc;
        !          3172:   BtCursor *pCur = pC->pCursor;
        !          3173:   Mem m;
        !          3174: 
        !          3175:   assert( sqlite3BtreeCursorIsValid(pCur) );
        !          3176:   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
        !          3177:   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
        !          3178:   /* nCellKey will always be between 0 and 0xffffffff because of the say
        !          3179:   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
        !          3180:   if( nCellKey<=0 || nCellKey>0x7fffffff ){
        !          3181:     *res = 0;
        !          3182:     return SQLITE_CORRUPT_BKPT;
        !          3183:   }
        !          3184:   memset(&m, 0, sizeof(m));
        !          3185:   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
        !          3186:   if( rc ){
        !          3187:     return rc;
        !          3188:   }
        !          3189:   assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
        !          3190:   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
        !          3191:   sqlite3VdbeMemRelease(&m);
        !          3192:   return SQLITE_OK;
        !          3193: }
        !          3194: 
        !          3195: /*
        !          3196: ** This routine sets the value to be returned by subsequent calls to
        !          3197: ** sqlite3_changes() on the database handle 'db'. 
        !          3198: */
        !          3199: void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
        !          3200:   assert( sqlite3_mutex_held(db->mutex) );
        !          3201:   db->nChange = nChange;
        !          3202:   db->nTotalChange += nChange;
        !          3203: }
        !          3204: 
        !          3205: /*
        !          3206: ** Set a flag in the vdbe to update the change counter when it is finalised
        !          3207: ** or reset.
        !          3208: */
        !          3209: void sqlite3VdbeCountChanges(Vdbe *v){
        !          3210:   v->changeCntOn = 1;
        !          3211: }
        !          3212: 
        !          3213: /*
        !          3214: ** Mark every prepared statement associated with a database connection
        !          3215: ** as expired.
        !          3216: **
        !          3217: ** An expired statement means that recompilation of the statement is
        !          3218: ** recommend.  Statements expire when things happen that make their
        !          3219: ** programs obsolete.  Removing user-defined functions or collating
        !          3220: ** sequences, or changing an authorization function are the types of
        !          3221: ** things that make prepared statements obsolete.
        !          3222: */
        !          3223: void sqlite3ExpirePreparedStatements(sqlite3 *db){
        !          3224:   Vdbe *p;
        !          3225:   for(p = db->pVdbe; p; p=p->pNext){
        !          3226:     p->expired = 1;
        !          3227:   }
        !          3228: }
        !          3229: 
        !          3230: /*
        !          3231: ** Return the database associated with the Vdbe.
        !          3232: */
        !          3233: sqlite3 *sqlite3VdbeDb(Vdbe *v){
        !          3234:   return v->db;
        !          3235: }
        !          3236: 
        !          3237: /*
        !          3238: ** Return a pointer to an sqlite3_value structure containing the value bound
        !          3239: ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
        !          3240: ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
        !          3241: ** constants) to the value before returning it.
        !          3242: **
        !          3243: ** The returned value must be freed by the caller using sqlite3ValueFree().
        !          3244: */
        !          3245: sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
        !          3246:   assert( iVar>0 );
        !          3247:   if( v ){
        !          3248:     Mem *pMem = &v->aVar[iVar-1];
        !          3249:     if( 0==(pMem->flags & MEM_Null) ){
        !          3250:       sqlite3_value *pRet = sqlite3ValueNew(v->db);
        !          3251:       if( pRet ){
        !          3252:         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
        !          3253:         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
        !          3254:         sqlite3VdbeMemStoreType((Mem *)pRet);
        !          3255:       }
        !          3256:       return pRet;
        !          3257:     }
        !          3258:   }
        !          3259:   return 0;
        !          3260: }
        !          3261: 
        !          3262: /*
        !          3263: ** Configure SQL variable iVar so that binding a new value to it signals
        !          3264: ** to sqlite3_reoptimize() that re-preparing the statement may result
        !          3265: ** in a better query plan.
        !          3266: */
        !          3267: void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
        !          3268:   assert( iVar>0 );
        !          3269:   if( iVar>32 ){
        !          3270:     v->expmask = 0xffffffff;
        !          3271:   }else{
        !          3272:     v->expmask |= ((u32)1 << (iVar-1));
        !          3273:   }
        !          3274: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>