Back to index

lightning-sunbird  0.9+nobinonly
vdbeaux.c
Go to the documentation of this file.
00001 /*
00002 ** 2003 September 6
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** This file contains code used for creating, destroying, and populating
00013 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
00014 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
00015 ** But that file was getting too big so this subroutines were split out.
00016 */
00017 #include "sqliteInt.h"
00018 #include "os.h"
00019 #include <ctype.h>
00020 #include "vdbeInt.h"
00021 
00022 
00023 /*
00024 ** When debugging the code generator in a symbolic debugger, one can
00025 ** set the sqlite3_vdbe_addop_trace to 1 and all opcodes will be printed
00026 ** as they are added to the instruction stream.
00027 */
00028 #ifdef SQLITE_DEBUG
00029 int sqlite3_vdbe_addop_trace = 0;
00030 #endif
00031 
00032 
00033 /*
00034 ** Create a new virtual database engine.
00035 */
00036 Vdbe *sqlite3VdbeCreate(sqlite3 *db){
00037   Vdbe *p;
00038   p = sqliteMalloc( sizeof(Vdbe) );
00039   if( p==0 ) return 0;
00040   p->db = db;
00041   if( db->pVdbe ){
00042     db->pVdbe->pPrev = p;
00043   }
00044   p->pNext = db->pVdbe;
00045   p->pPrev = 0;
00046   db->pVdbe = p;
00047   p->magic = VDBE_MAGIC_INIT;
00048   return p;
00049 }
00050 
00051 /*
00052 ** Turn tracing on or off
00053 */
00054 void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
00055   p->trace = trace;
00056 }
00057 
00058 /*
00059 ** Resize the Vdbe.aOp array so that it contains at least N
00060 ** elements. If the Vdbe is in VDBE_MAGIC_RUN state, then
00061 ** the Vdbe.aOp array will be sized to contain exactly N
00062 ** elements. Vdbe.nOpAlloc is set to reflect the new size of
00063 ** the array.
00064 **
00065 ** If an out-of-memory error occurs while resizing the array,
00066 ** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
00067 ** any opcodes already allocated can be correctly deallocated
00068 ** along with the rest of the Vdbe).
00069 */
00070 static void resizeOpArray(Vdbe *p, int N){
00071   int runMode = p->magic==VDBE_MAGIC_RUN;
00072   if( runMode || p->nOpAlloc<N ){
00073     VdbeOp *pNew;
00074     int nNew = N + 100*(!runMode);
00075     int oldSize = p->nOpAlloc;
00076     pNew = sqliteRealloc(p->aOp, nNew*sizeof(Op));
00077     if( pNew ){
00078       p->nOpAlloc = nNew;
00079       p->aOp = pNew;
00080       if( nNew>oldSize ){
00081         memset(&p->aOp[oldSize], 0, (nNew-oldSize)*sizeof(Op));
00082       }
00083     }
00084   }
00085 }
00086 
00087 /*
00088 ** Add a new instruction to the list of instructions current in the
00089 ** VDBE.  Return the address of the new instruction.
00090 **
00091 ** Parameters:
00092 **
00093 **    p               Pointer to the VDBE
00094 **
00095 **    op              The opcode for this instruction
00096 **
00097 **    p1, p2          First two of the three possible operands.
00098 **
00099 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
00100 ** the sqlite3VdbeChangeP3() function to change the value of the P3
00101 ** operand.
00102 */
00103 int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){
00104   int i;
00105   VdbeOp *pOp;
00106 
00107   i = p->nOp;
00108   p->nOp++;
00109   assert( p->magic==VDBE_MAGIC_INIT );
00110   if( p->nOpAlloc<=i ){
00111     resizeOpArray(p, i+1);
00112     if( sqlite3MallocFailed() ){
00113       return 0;
00114     }
00115   }
00116   pOp = &p->aOp[i];
00117   pOp->opcode = op;
00118   pOp->p1 = p1;
00119   pOp->p2 = p2;
00120   pOp->p3 = 0;
00121   pOp->p3type = P3_NOTUSED;
00122   p->expired = 0;
00123 #ifdef SQLITE_DEBUG
00124   if( sqlite3_vdbe_addop_trace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
00125 #endif
00126   return i;
00127 }
00128 
00129 /*
00130 ** Add an opcode that includes the p3 value.
00131 */
00132 int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){
00133   int addr = sqlite3VdbeAddOp(p, op, p1, p2);
00134   sqlite3VdbeChangeP3(p, addr, zP3, p3type);
00135   return addr;
00136 }
00137 
00138 /*
00139 ** Create a new symbolic label for an instruction that has yet to be
00140 ** coded.  The symbolic label is really just a negative number.  The
00141 ** label can be used as the P2 value of an operation.  Later, when
00142 ** the label is resolved to a specific address, the VDBE will scan
00143 ** through its operation list and change all values of P2 which match
00144 ** the label into the resolved address.
00145 **
00146 ** The VDBE knows that a P2 value is a label because labels are
00147 ** always negative and P2 values are suppose to be non-negative.
00148 ** Hence, a negative P2 value is a label that has yet to be resolved.
00149 **
00150 ** Zero is returned if a malloc() fails.
00151 */
00152 int sqlite3VdbeMakeLabel(Vdbe *p){
00153   int i;
00154   i = p->nLabel++;
00155   assert( p->magic==VDBE_MAGIC_INIT );
00156   if( i>=p->nLabelAlloc ){
00157     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
00158     sqliteReallocOrFree((void**)&p->aLabel,
00159                           p->nLabelAlloc*sizeof(p->aLabel[0]));
00160   }
00161   if( p->aLabel ){
00162     p->aLabel[i] = -1;
00163   }
00164   return -1-i;
00165 }
00166 
00167 /*
00168 ** Resolve label "x" to be the address of the next instruction to
00169 ** be inserted.  The parameter "x" must have been obtained from
00170 ** a prior call to sqlite3VdbeMakeLabel().
00171 */
00172 void sqlite3VdbeResolveLabel(Vdbe *p, int x){
00173   int j = -1-x;
00174   assert( p->magic==VDBE_MAGIC_INIT );
00175   assert( j>=0 && j<p->nLabel );
00176   if( p->aLabel ){
00177     p->aLabel[j] = p->nOp;
00178   }
00179 }
00180 
00181 /*
00182 ** Return non-zero if opcode 'op' is guarenteed not to push more values
00183 ** onto the VDBE stack than it pops off.
00184 */
00185 static int opcodeNoPush(u8 op){
00186   /* The 10 NOPUSH_MASK_n constants are defined in the automatically
00187   ** generated header file opcodes.h. Each is a 16-bit bitmask, one
00188   ** bit corresponding to each opcode implemented by the virtual
00189   ** machine in vdbe.c. The bit is true if the word "no-push" appears
00190   ** in a comment on the same line as the "case OP_XXX:" in 
00191   ** sqlite3VdbeExec() in vdbe.c.
00192   **
00193   ** If the bit is true, then the corresponding opcode is guarenteed not
00194   ** to grow the stack when it is executed. Otherwise, it may grow the
00195   ** stack by at most one entry.
00196   **
00197   ** NOPUSH_MASK_0 corresponds to opcodes 0 to 15. NOPUSH_MASK_1 contains
00198   ** one bit for opcodes 16 to 31, and so on.
00199   **
00200   ** 16-bit bitmasks (rather than 32-bit) are specified in opcodes.h 
00201   ** because the file is generated by an awk program. Awk manipulates
00202   ** all numbers as floating-point and we don't want to risk a rounding
00203   ** error if someone builds with an awk that uses (for example) 32-bit 
00204   ** IEEE floats.
00205   */ 
00206   static const u32 masks[5] = {
00207     NOPUSH_MASK_0 + (((unsigned)NOPUSH_MASK_1)<<16),
00208     NOPUSH_MASK_2 + (((unsigned)NOPUSH_MASK_3)<<16),
00209     NOPUSH_MASK_4 + (((unsigned)NOPUSH_MASK_5)<<16),
00210     NOPUSH_MASK_6 + (((unsigned)NOPUSH_MASK_7)<<16),
00211     NOPUSH_MASK_8 + (((unsigned)NOPUSH_MASK_9)<<16)
00212   };
00213   assert( op<32*5 );
00214   return (masks[op>>5] & (1<<(op&0x1F)));
00215 }
00216 
00217 #ifndef NDEBUG
00218 int sqlite3VdbeOpcodeNoPush(u8 op){
00219   return opcodeNoPush(op);
00220 }
00221 #endif
00222 
00223 /*
00224 ** Loop through the program looking for P2 values that are negative.
00225 ** Each such value is a label.  Resolve the label by setting the P2
00226 ** value to its correct non-zero value.
00227 **
00228 ** This routine is called once after all opcodes have been inserted.
00229 **
00230 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
00231 ** to an OP_Function or OP_AggStep opcode. This is used by 
00232 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
00233 **
00234 ** The integer *pMaxStack is set to the maximum number of vdbe stack
00235 ** entries that static analysis reveals this program might need.
00236 **
00237 ** This routine also does the following optimization:  It scans for
00238 ** Halt instructions where P1==SQLITE_CONSTRAINT or P2==OE_Abort or for
00239 ** IdxInsert instructions where P2!=0.  If no such instruction is
00240 ** found, then every Statement instruction is changed to a Noop.  In
00241 ** this way, we avoid creating the statement journal file unnecessarily.
00242 */
00243 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs, int *pMaxStack){
00244   int i;
00245   int nMaxArgs = 0;
00246   int nMaxStack = p->nOp;
00247   Op *pOp;
00248   int *aLabel = p->aLabel;
00249   int doesStatementRollback = 0;
00250   int hasStatementBegin = 0;
00251   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
00252     u8 opcode = pOp->opcode;
00253 
00254     if( opcode==OP_Function || opcode==OP_AggStep ){
00255       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
00256     }else if( opcode==OP_Halt ){
00257       if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
00258         doesStatementRollback = 1;
00259       }
00260     }else if( opcode==OP_IdxInsert ){
00261       if( pOp->p2 ){
00262         doesStatementRollback = 1;
00263       }
00264     }else if( opcode==OP_Statement ){
00265       hasStatementBegin = 1;
00266     }
00267 
00268     if( opcodeNoPush(opcode) ){
00269       nMaxStack--;
00270     }
00271 
00272     if( pOp->p2>=0 ) continue;
00273     assert( -1-pOp->p2<p->nLabel );
00274     pOp->p2 = aLabel[-1-pOp->p2];
00275   }
00276   sqliteFree(p->aLabel);
00277   p->aLabel = 0;
00278 
00279   *pMaxFuncArgs = nMaxArgs;
00280   *pMaxStack = nMaxStack;
00281 
00282   /* If we never rollback a statement transaction, then statement
00283   ** transactions are not needed.  So change every OP_Statement
00284   ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
00285   ** which can be expensive on some platforms.
00286   */
00287   if( hasStatementBegin && !doesStatementRollback ){
00288     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
00289       if( pOp->opcode==OP_Statement ){
00290         pOp->opcode = OP_Noop;
00291       }
00292     }
00293   }
00294 }
00295 
00296 /*
00297 ** Return the address of the next instruction to be inserted.
00298 */
00299 int sqlite3VdbeCurrentAddr(Vdbe *p){
00300   assert( p->magic==VDBE_MAGIC_INIT );
00301   return p->nOp;
00302 }
00303 
00304 /*
00305 ** Add a whole list of operations to the operation stack.  Return the
00306 ** address of the first operation added.
00307 */
00308 int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
00309   int addr;
00310   assert( p->magic==VDBE_MAGIC_INIT );
00311   resizeOpArray(p, p->nOp + nOp);
00312   if( sqlite3MallocFailed() ){
00313     return 0;
00314   }
00315   addr = p->nOp;
00316   if( nOp>0 ){
00317     int i;
00318     VdbeOpList const *pIn = aOp;
00319     for(i=0; i<nOp; i++, pIn++){
00320       int p2 = pIn->p2;
00321       VdbeOp *pOut = &p->aOp[i+addr];
00322       pOut->opcode = pIn->opcode;
00323       pOut->p1 = pIn->p1;
00324       pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
00325       pOut->p3 = pIn->p3;
00326       pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
00327 #ifdef SQLITE_DEBUG
00328       if( sqlite3_vdbe_addop_trace ){
00329         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
00330       }
00331 #endif
00332     }
00333     p->nOp += nOp;
00334   }
00335   return addr;
00336 }
00337 
00338 /*
00339 ** Change the value of the P1 operand for a specific instruction.
00340 ** This routine is useful when a large program is loaded from a
00341 ** static array using sqlite3VdbeAddOpList but we want to make a
00342 ** few minor changes to the program.
00343 */
00344 void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
00345   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
00346   if( p && addr>=0 && p->nOp>addr && p->aOp ){
00347     p->aOp[addr].p1 = val;
00348   }
00349 }
00350 
00351 /*
00352 ** Change the value of the P2 operand for a specific instruction.
00353 ** This routine is useful for setting a jump destination.
00354 */
00355 void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
00356   assert( val>=0 );
00357   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
00358   if( p && addr>=0 && p->nOp>addr && p->aOp ){
00359     p->aOp[addr].p2 = val;
00360   }
00361 }
00362 
00363 /*
00364 ** Change the P2 operand of instruction addr so that it points to
00365 ** the address of the next instruction to be coded.
00366 */
00367 void sqlite3VdbeJumpHere(Vdbe *p, int addr){
00368   sqlite3VdbeChangeP2(p, addr, p->nOp);
00369 }
00370 
00371 /*
00372 ** Delete a P3 value if necessary.
00373 */
00374 static void freeP3(int p3type, void *p3){
00375   if( p3 ){
00376     switch( p3type ){
00377       case P3_DYNAMIC:
00378       case P3_KEYINFO:
00379       case P3_KEYINFO_HANDOFF: {
00380         sqliteFree(p3);
00381         break;
00382       }
00383       case P3_VDBEFUNC: {
00384         VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
00385         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
00386         sqliteFree(pVdbeFunc);
00387         break;
00388       }
00389       case P3_MEM: {
00390         sqlite3ValueFree((sqlite3_value*)p3);
00391         break;
00392       }
00393     }
00394   }
00395 }
00396 
00397 
00398 /*
00399 ** Change N opcodes starting at addr to No-ops.
00400 */
00401 void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
00402   VdbeOp *pOp = &p->aOp[addr];
00403   while( N-- ){
00404     freeP3(pOp->p3type, pOp->p3);
00405     memset(pOp, 0, sizeof(pOp[0]));
00406     pOp->opcode = OP_Noop;
00407     pOp++;
00408   }
00409 }
00410 
00411 /*
00412 ** Change the value of the P3 operand for a specific instruction.
00413 ** This routine is useful when a large program is loaded from a
00414 ** static array using sqlite3VdbeAddOpList but we want to make a
00415 ** few minor changes to the program.
00416 **
00417 ** If n>=0 then the P3 operand is dynamic, meaning that a copy of
00418 ** the string is made into memory obtained from sqliteMalloc().
00419 ** A value of n==0 means copy bytes of zP3 up to and including the
00420 ** first null byte.  If n>0 then copy n+1 bytes of zP3.
00421 **
00422 ** If n==P3_KEYINFO it means that zP3 is a pointer to a KeyInfo structure.
00423 ** A copy is made of the KeyInfo structure into memory obtained from
00424 ** sqliteMalloc, to be freed when the Vdbe is finalized.
00425 ** n==P3_KEYINFO_HANDOFF indicates that zP3 points to a KeyInfo structure
00426 ** stored in memory that the caller has obtained from sqliteMalloc. The 
00427 ** caller should not free the allocation, it will be freed when the Vdbe is
00428 ** finalized.
00429 ** 
00430 ** Other values of n (P3_STATIC, P3_COLLSEQ etc.) indicate that zP3 points
00431 ** to a string or structure that is guaranteed to exist for the lifetime of
00432 ** the Vdbe. In these cases we can just copy the pointer.
00433 **
00434 ** If addr<0 then change P3 on the most recently inserted instruction.
00435 */
00436 void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
00437   Op *pOp;
00438   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
00439   if( p==0 || p->aOp==0 || sqlite3MallocFailed() ){
00440     if (n != P3_KEYINFO) {
00441       freeP3(n, (void*)*(char**)&zP3);
00442     }
00443     return;
00444   }
00445   if( addr<0 || addr>=p->nOp ){
00446     addr = p->nOp - 1;
00447     if( addr<0 ) return;
00448   }
00449   pOp = &p->aOp[addr];
00450   freeP3(pOp->p3type, pOp->p3);
00451   pOp->p3 = 0;
00452   if( zP3==0 ){
00453     pOp->p3 = 0;
00454     pOp->p3type = P3_NOTUSED;
00455   }else if( n==P3_KEYINFO ){
00456     KeyInfo *pKeyInfo;
00457     int nField, nByte;
00458 
00459     nField = ((KeyInfo*)zP3)->nField;
00460     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
00461     pKeyInfo = sqliteMallocRaw( nByte );
00462     pOp->p3 = (char*)pKeyInfo;
00463     if( pKeyInfo ){
00464       unsigned char *aSortOrder;
00465       memcpy(pKeyInfo, zP3, nByte);
00466       aSortOrder = pKeyInfo->aSortOrder;
00467       if( aSortOrder ){
00468         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
00469         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
00470       }
00471       pOp->p3type = P3_KEYINFO;
00472     }else{
00473       pOp->p3type = P3_NOTUSED;
00474     }
00475   }else if( n==P3_KEYINFO_HANDOFF ){
00476     pOp->p3 = (char*)zP3;
00477     pOp->p3type = P3_KEYINFO;
00478   }else if( n<0 ){
00479     pOp->p3 = (char*)zP3;
00480     pOp->p3type = n;
00481   }else{
00482     if( n==0 ) n = strlen(zP3);
00483     pOp->p3 = sqliteStrNDup(zP3, n);
00484     pOp->p3type = P3_DYNAMIC;
00485   }
00486 }
00487 
00488 #ifndef NDEBUG
00489 /*
00490 ** Replace the P3 field of the most recently coded instruction with
00491 ** comment text.
00492 */
00493 void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
00494   va_list ap;
00495   assert( p->nOp>0 );
00496   assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0 
00497           || sqlite3MallocFailed() );
00498   va_start(ap, zFormat);
00499   sqlite3VdbeChangeP3(p, -1, sqlite3VMPrintf(zFormat, ap), P3_DYNAMIC);
00500   va_end(ap);
00501 }
00502 #endif
00503 
00504 /*
00505 ** Return the opcode for a given address.
00506 */
00507 VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
00508   assert( p->magic==VDBE_MAGIC_INIT );
00509   assert( addr>=0 && addr<p->nOp );
00510   return &p->aOp[addr];
00511 }
00512 
00513 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
00514      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
00515 /*
00516 ** Compute a string that describes the P3 parameter for an opcode.
00517 ** Use zTemp for any required temporary buffer space.
00518 */
00519 static char *displayP3(Op *pOp, char *zTemp, int nTemp){
00520   char *zP3;
00521   assert( nTemp>=20 );
00522   switch( pOp->p3type ){
00523     case P3_KEYINFO: {
00524       int i, j;
00525       KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3;
00526       sprintf(zTemp, "keyinfo(%d", pKeyInfo->nField);
00527       i = strlen(zTemp);
00528       for(j=0; j<pKeyInfo->nField; j++){
00529         CollSeq *pColl = pKeyInfo->aColl[j];
00530         if( pColl ){
00531           int n = strlen(pColl->zName);
00532           if( i+n>nTemp-6 ){
00533             strcpy(&zTemp[i],",...");
00534             break;
00535           }
00536           zTemp[i++] = ',';
00537           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
00538             zTemp[i++] = '-';
00539           }
00540           strcpy(&zTemp[i], pColl->zName);
00541           i += n;
00542         }else if( i+4<nTemp-6 ){
00543           strcpy(&zTemp[i],",nil");
00544           i += 4;
00545         }
00546       }
00547       zTemp[i++] = ')';
00548       zTemp[i] = 0;
00549       assert( i<nTemp );
00550       zP3 = zTemp;
00551       break;
00552     }
00553     case P3_COLLSEQ: {
00554       CollSeq *pColl = (CollSeq*)pOp->p3;
00555       sprintf(zTemp, "collseq(%.20s)", pColl->zName);
00556       zP3 = zTemp;
00557       break;
00558     }
00559     case P3_FUNCDEF: {
00560       FuncDef *pDef = (FuncDef*)pOp->p3;
00561       char zNum[30];
00562       sprintf(zTemp, "%.*s", nTemp, pDef->zName);
00563       sprintf(zNum,"(%d)", pDef->nArg);
00564       if( strlen(zTemp)+strlen(zNum)+1<=nTemp ){
00565         strcat(zTemp, zNum);
00566       }
00567       zP3 = zTemp;
00568       break;
00569     }
00570     default: {
00571       zP3 = pOp->p3;
00572       if( zP3==0 || pOp->opcode==OP_Noop ){
00573         zP3 = "";
00574       }
00575     }
00576   }
00577   return zP3;
00578 }
00579 #endif
00580 
00581 
00582 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
00583 /*
00584 ** Print a single opcode.  This routine is used for debugging only.
00585 */
00586 void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
00587   char *zP3;
00588   char zPtr[50];
00589   static const char *zFormat1 = "%4d %-13s %4d %4d %s\n";
00590   if( pOut==0 ) pOut = stdout;
00591   zP3 = displayP3(pOp, zPtr, sizeof(zPtr));
00592   fprintf(pOut, zFormat1,
00593       pc, sqlite3OpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3);
00594   fflush(pOut);
00595 }
00596 #endif
00597 
00598 /*
00599 ** Release an array of N Mem elements
00600 */
00601 static void releaseMemArray(Mem *p, int N){
00602   if( p ){
00603     while( N-->0 ){
00604       sqlite3VdbeMemRelease(p++);
00605     }
00606   }
00607 }
00608 
00609 #ifndef SQLITE_OMIT_EXPLAIN
00610 /*
00611 ** Give a listing of the program in the virtual machine.
00612 **
00613 ** The interface is the same as sqlite3VdbeExec().  But instead of
00614 ** running the code, it invokes the callback once for each instruction.
00615 ** This feature is used to implement "EXPLAIN".
00616 */
00617 int sqlite3VdbeList(
00618   Vdbe *p                   /* The VDBE */
00619 ){
00620   sqlite3 *db = p->db;
00621   int i;
00622   int rc = SQLITE_OK;
00623 
00624   assert( p->explain );
00625   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
00626   assert( db->magic==SQLITE_MAGIC_BUSY );
00627   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
00628 
00629   /* Even though this opcode does not put dynamic strings onto the
00630   ** the stack, they may become dynamic if the user calls
00631   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
00632   */
00633   if( p->pTos==&p->aStack[4] ){
00634     releaseMemArray(p->aStack, 5);
00635   }
00636   p->resOnStack = 0;
00637 
00638   do{
00639     i = p->pc++;
00640   }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
00641   if( i>=p->nOp ){
00642     p->rc = SQLITE_OK;
00643     rc = SQLITE_DONE;
00644   }else if( db->flags & SQLITE_Interrupt ){
00645     db->flags &= ~SQLITE_Interrupt;
00646     p->rc = SQLITE_INTERRUPT;
00647     rc = SQLITE_ERROR;
00648     sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
00649   }else{
00650     Op *pOp = &p->aOp[i];
00651     Mem *pMem = p->aStack;
00652     pMem->flags = MEM_Int;
00653     pMem->type = SQLITE_INTEGER;
00654     pMem->i = i;                                /* Program counter */
00655     pMem++;
00656 
00657     pMem->flags = MEM_Static|MEM_Str|MEM_Term;
00658     pMem->z = sqlite3OpcodeNames[pOp->opcode];  /* Opcode */
00659     pMem->n = strlen(pMem->z);
00660     pMem->type = SQLITE_TEXT;
00661     pMem->enc = SQLITE_UTF8;
00662     pMem++;
00663 
00664     pMem->flags = MEM_Int;
00665     pMem->i = pOp->p1;                          /* P1 */
00666     pMem->type = SQLITE_INTEGER;
00667     pMem++;
00668 
00669     pMem->flags = MEM_Int;
00670     pMem->i = pOp->p2;                          /* P2 */
00671     pMem->type = SQLITE_INTEGER;
00672     pMem++;
00673 
00674     pMem->flags = MEM_Ephem|MEM_Str|MEM_Term;   /* P3 */
00675     pMem->z = displayP3(pOp, pMem->zShort, sizeof(pMem->zShort));
00676     pMem->n = strlen(pMem->z);
00677     pMem->type = SQLITE_TEXT;
00678     pMem->enc = SQLITE_UTF8;
00679 
00680     p->nResColumn = 5 - 2*(p->explain-1);
00681     p->pTos = pMem;
00682     p->rc = SQLITE_OK;
00683     p->resOnStack = 1;
00684     rc = SQLITE_ROW;
00685   }
00686   return rc;
00687 }
00688 #endif /* SQLITE_OMIT_EXPLAIN */
00689 
00690 /*
00691 ** Print the SQL that was used to generate a VDBE program.
00692 */
00693 void sqlite3VdbePrintSql(Vdbe *p){
00694 #ifdef SQLITE_DEBUG
00695   int nOp = p->nOp;
00696   VdbeOp *pOp;
00697   if( nOp<1 ) return;
00698   pOp = &p->aOp[nOp-1];
00699   if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
00700     const char *z = pOp->p3;
00701     while( isspace(*(u8*)z) ) z++;
00702     printf("SQL: [%s]\n", z);
00703   }
00704 #endif
00705 }
00706 
00707 /*
00708 ** Prepare a virtual machine for execution.  This involves things such
00709 ** as allocating stack space and initializing the program counter.
00710 ** After the VDBE has be prepped, it can be executed by one or more
00711 ** calls to sqlite3VdbeExec().  
00712 **
00713 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
00714 ** VDBE_MAGIC_RUN.
00715 */
00716 void sqlite3VdbeMakeReady(
00717   Vdbe *p,                       /* The VDBE */
00718   int nVar,                      /* Number of '?' see in the SQL statement */
00719   int nMem,                      /* Number of memory cells to allocate */
00720   int nCursor,                   /* Number of cursors to allocate */
00721   int isExplain                  /* True if the EXPLAIN keywords is present */
00722 ){
00723   int n;
00724 
00725   assert( p!=0 );
00726   assert( p->magic==VDBE_MAGIC_INIT );
00727 
00728   /* There should be at least one opcode.
00729   */
00730   assert( p->nOp>0 );
00731 
00732   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
00733    * is because the call to resizeOpArray() below may shrink the
00734    * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN 
00735    * state.
00736    */
00737   p->magic = VDBE_MAGIC_RUN;
00738 
00739   /* No instruction ever pushes more than a single element onto the
00740   ** stack.  And the stack never grows on successive executions of the
00741   ** same loop.  So the total number of instructions is an upper bound
00742   ** on the maximum stack depth required.  (Added later:)  The
00743   ** resolveP2Values() call computes a tighter upper bound on the
00744   ** stack size.
00745   **
00746   ** Allocation all the stack space we will ever need.
00747   */
00748   if( p->aStack==0 ){
00749     int nArg;       /* Maximum number of args passed to a user function. */
00750     int nStack;     /* Maximum number of stack entries required */
00751     resolveP2Values(p, &nArg, &nStack);
00752     resizeOpArray(p, p->nOp);
00753     assert( nVar>=0 );
00754     assert( nStack<p->nOp );
00755     nStack = isExplain ? 10 : nStack;
00756     p->aStack = sqliteMalloc(
00757         nStack*sizeof(p->aStack[0])    /* aStack */
00758       + nArg*sizeof(Mem*)              /* apArg */
00759       + nVar*sizeof(Mem)               /* aVar */
00760       + nVar*sizeof(char*)             /* azVar */
00761       + nMem*sizeof(Mem)               /* aMem */
00762       + nCursor*sizeof(Cursor*)        /* apCsr */
00763     );
00764     if( !sqlite3MallocFailed() ){
00765       p->aMem = &p->aStack[nStack];
00766       p->nMem = nMem;
00767       p->aVar = &p->aMem[nMem];
00768       p->nVar = nVar;
00769       p->okVar = 0;
00770       p->apArg = (Mem**)&p->aVar[nVar];
00771       p->azVar = (char**)&p->apArg[nArg];
00772       p->apCsr = (Cursor**)&p->azVar[nVar];
00773       p->nCursor = nCursor;
00774       for(n=0; n<nVar; n++){
00775         p->aVar[n].flags = MEM_Null;
00776       }
00777     }
00778   }
00779   for(n=0; n<p->nMem; n++){
00780     p->aMem[n].flags = MEM_Null;
00781   }
00782 
00783 #ifdef SQLITE_DEBUG
00784   if( (p->db->flags & SQLITE_VdbeListing)!=0
00785     || sqlite3OsFileExists("vdbe_explain")
00786   ){
00787     int i;
00788     printf("VDBE Program Listing:\n");
00789     sqlite3VdbePrintSql(p);
00790     for(i=0; i<p->nOp; i++){
00791       sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
00792     }
00793   }
00794   if( sqlite3OsFileExists("vdbe_trace") ){
00795     p->trace = stdout;
00796   }
00797 #endif
00798   p->pTos = &p->aStack[-1];
00799   p->pc = -1;
00800   p->rc = SQLITE_OK;
00801   p->uniqueCnt = 0;
00802   p->returnDepth = 0;
00803   p->errorAction = OE_Abort;
00804   p->popStack =  0;
00805   p->explain |= isExplain;
00806   p->magic = VDBE_MAGIC_RUN;
00807   p->nChange = 0;
00808   p->cacheCtr = 1;
00809   p->minWriteFileFormat = 255;
00810 #ifdef VDBE_PROFILE
00811   {
00812     int i;
00813     for(i=0; i<p->nOp; i++){
00814       p->aOp[i].cnt = 0;
00815       p->aOp[i].cycles = 0;
00816     }
00817   }
00818 #endif
00819 }
00820 
00821 /*
00822 ** Close a cursor and release all the resources that cursor happens
00823 ** to hold.
00824 */
00825 void sqlite3VdbeFreeCursor(Cursor *pCx){
00826   if( pCx==0 ){
00827     return;
00828   }
00829   if( pCx->pCursor ){
00830     sqlite3BtreeCloseCursor(pCx->pCursor);
00831   }
00832   if( pCx->pBt ){
00833     sqlite3BtreeClose(pCx->pBt);
00834   }
00835   sqliteFree(pCx->pData);
00836   sqliteFree(pCx->aType);
00837   sqliteFree(pCx);
00838 }
00839 
00840 /*
00841 ** Close all cursors
00842 */
00843 static void closeAllCursors(Vdbe *p){
00844   int i;
00845   if( p->apCsr==0 ) return;
00846   for(i=0; i<p->nCursor; i++){
00847     sqlite3VdbeFreeCursor(p->apCsr[i]);
00848     p->apCsr[i] = 0;
00849   }
00850 }
00851 
00852 /*
00853 ** Clean up the VM after execution.
00854 **
00855 ** This routine will automatically close any cursors, lists, and/or
00856 ** sorters that were left open.  It also deletes the values of
00857 ** variables in the aVar[] array.
00858 */
00859 static void Cleanup(Vdbe *p){
00860   int i;
00861   if( p->aStack ){
00862     releaseMemArray(p->aStack, 1 + (p->pTos - p->aStack));
00863     p->pTos = &p->aStack[-1];
00864   }
00865   closeAllCursors(p);
00866   releaseMemArray(p->aMem, p->nMem);
00867   sqlite3VdbeFifoClear(&p->sFifo);
00868   if( p->contextStack ){
00869     for(i=0; i<p->contextStackTop; i++){
00870       sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
00871     }
00872     sqliteFree(p->contextStack);
00873   }
00874   p->contextStack = 0;
00875   p->contextStackDepth = 0;
00876   p->contextStackTop = 0;
00877   sqliteFree(p->zErrMsg);
00878   p->zErrMsg = 0;
00879 }
00880 
00881 /*
00882 ** Set the number of result columns that will be returned by this SQL
00883 ** statement. This is now set at compile time, rather than during
00884 ** execution of the vdbe program so that sqlite3_column_count() can
00885 ** be called on an SQL statement before sqlite3_step().
00886 */
00887 void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
00888   Mem *pColName;
00889   int n;
00890   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
00891   sqliteFree(p->aColName);
00892   n = nResColumn*COLNAME_N;
00893   p->nResColumn = nResColumn;
00894   p->aColName = pColName = (Mem*)sqliteMalloc( sizeof(Mem)*n );
00895   if( p->aColName==0 ) return;
00896   while( n-- > 0 ){
00897     (pColName++)->flags = MEM_Null;
00898   }
00899 }
00900 
00901 /*
00902 ** Set the name of the idx'th column to be returned by the SQL statement.
00903 ** zName must be a pointer to a nul terminated string.
00904 **
00905 ** This call must be made after a call to sqlite3VdbeSetNumCols().
00906 **
00907 ** If N==P3_STATIC  it means that zName is a pointer to a constant static
00908 ** string and we can just copy the pointer. If it is P3_DYNAMIC, then 
00909 ** the string is freed using sqliteFree() when the vdbe is finished with
00910 ** it. Otherwise, N bytes of zName are copied.
00911 */
00912 int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
00913   int rc;
00914   Mem *pColName;
00915   assert( idx<p->nResColumn );
00916   assert( var<COLNAME_N );
00917   if( sqlite3MallocFailed() ) return SQLITE_NOMEM;
00918   assert( p->aColName!=0 );
00919   pColName = &(p->aColName[idx+var*p->nResColumn]);
00920   if( N==P3_DYNAMIC || N==P3_STATIC ){
00921     rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
00922   }else{
00923     rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
00924   }
00925   if( rc==SQLITE_OK && N==P3_DYNAMIC ){
00926     pColName->flags = (pColName->flags&(~MEM_Static))|MEM_Dyn;
00927     pColName->xDel = 0;
00928   }
00929   return rc;
00930 }
00931 
00932 /*
00933 ** A read or write transaction may or may not be active on database handle
00934 ** db. If a transaction is active, commit it. If there is a
00935 ** write-transaction spanning more than one database file, this routine
00936 ** takes care of the master journal trickery.
00937 */
00938 static int vdbeCommit(sqlite3 *db){
00939   int i;
00940   int nTrans = 0;  /* Number of databases with an active write-transaction */
00941   int rc = SQLITE_OK;
00942   int needXcommit = 0;
00943 
00944   for(i=0; i<db->nDb; i++){ 
00945     Btree *pBt = db->aDb[i].pBt;
00946     if( pBt && sqlite3BtreeIsInTrans(pBt) ){
00947       needXcommit = 1;
00948       if( i!=1 ) nTrans++;
00949     }
00950   }
00951 
00952   /* If there are any write-transactions at all, invoke the commit hook */
00953   if( needXcommit && db->xCommitCallback ){
00954     sqlite3SafetyOff(db);
00955     rc = db->xCommitCallback(db->pCommitArg);
00956     sqlite3SafetyOn(db);
00957     if( rc ){
00958       return SQLITE_CONSTRAINT;
00959     }
00960   }
00961 
00962   /* The simple case - no more than one database file (not counting the
00963   ** TEMP database) has a transaction active.   There is no need for the
00964   ** master-journal.
00965   **
00966   ** If the return value of sqlite3BtreeGetFilename() is a zero length
00967   ** string, it means the main database is :memory:.  In that case we do
00968   ** not support atomic multi-file commits, so use the simple case then
00969   ** too.
00970   */
00971   if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
00972     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
00973       Btree *pBt = db->aDb[i].pBt;
00974       if( pBt ){
00975         rc = sqlite3BtreeSync(pBt, 0);
00976       }
00977     }
00978 
00979     /* Do the commit only if all databases successfully synced */
00980     if( rc==SQLITE_OK ){
00981       for(i=0; i<db->nDb; i++){
00982         Btree *pBt = db->aDb[i].pBt;
00983         if( pBt ){
00984           sqlite3BtreeCommit(pBt);
00985         }
00986       }
00987     }
00988   }
00989 
00990   /* The complex case - There is a multi-file write-transaction active.
00991   ** This requires a master journal file to ensure the transaction is
00992   ** committed atomicly.
00993   */
00994 #ifndef SQLITE_OMIT_DISKIO
00995   else{
00996     int needSync = 0;
00997     char *zMaster = 0;   /* File-name for the master journal */
00998     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
00999     OsFile *master = 0;
01000 
01001     /* Select a master journal file name */
01002     do {
01003       u32 random;
01004       sqliteFree(zMaster);
01005       sqlite3Randomness(sizeof(random), &random);
01006       zMaster = sqlite3MPrintf("%s-mj%08X", zMainFile, random&0x7fffffff);
01007       if( !zMaster ){
01008         return SQLITE_NOMEM;
01009       }
01010     }while( sqlite3OsFileExists(zMaster) );
01011 
01012     /* Open the master journal. */
01013     rc = sqlite3OsOpenExclusive(zMaster, &master, 0);
01014     if( rc!=SQLITE_OK ){
01015       sqliteFree(zMaster);
01016       return rc;
01017     }
01018  
01019     /* Write the name of each database file in the transaction into the new
01020     ** master journal file. If an error occurs at this point close
01021     ** and delete the master journal file. All the individual journal files
01022     ** still have 'null' as the master journal pointer, so they will roll
01023     ** back independently if a failure occurs.
01024     */
01025     for(i=0; i<db->nDb; i++){ 
01026       Btree *pBt = db->aDb[i].pBt;
01027       if( i==1 ) continue;   /* Ignore the TEMP database */
01028       if( pBt && sqlite3BtreeIsInTrans(pBt) ){
01029         char const *zFile = sqlite3BtreeGetJournalname(pBt);
01030         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
01031         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
01032           needSync = 1;
01033         }
01034         rc = sqlite3OsWrite(master, zFile, strlen(zFile)+1);
01035         if( rc!=SQLITE_OK ){
01036           sqlite3OsClose(&master);
01037           sqlite3OsDelete(zMaster);
01038           sqliteFree(zMaster);
01039           return rc;
01040         }
01041       }
01042     }
01043 
01044 
01045     /* Sync the master journal file. Before doing this, open the directory
01046     ** the master journal file is store in so that it gets synced too.
01047     */
01048     zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
01049     rc = sqlite3OsOpenDirectory(master, zMainFile);
01050     if( rc!=SQLITE_OK ||
01051           (needSync && (rc=sqlite3OsSync(master,0))!=SQLITE_OK) ){
01052       sqlite3OsClose(&master);
01053       sqlite3OsDelete(zMaster);
01054       sqliteFree(zMaster);
01055       return rc;
01056     }
01057 
01058     /* Sync all the db files involved in the transaction. The same call
01059     ** sets the master journal pointer in each individual journal. If
01060     ** an error occurs here, do not delete the master journal file.
01061     **
01062     ** If the error occurs during the first call to sqlite3BtreeSync(),
01063     ** then there is a chance that the master journal file will be
01064     ** orphaned. But we cannot delete it, in case the master journal
01065     ** file name was written into the journal file before the failure
01066     ** occured.
01067     */
01068     for(i=0; i<db->nDb; i++){ 
01069       Btree *pBt = db->aDb[i].pBt;
01070       if( pBt && sqlite3BtreeIsInTrans(pBt) ){
01071         rc = sqlite3BtreeSync(pBt, zMaster);
01072         if( rc!=SQLITE_OK ){
01073           sqlite3OsClose(&master);
01074           sqliteFree(zMaster);
01075           return rc;
01076         }
01077       }
01078     }
01079     sqlite3OsClose(&master);
01080 
01081     /* Delete the master journal file. This commits the transaction. After
01082     ** doing this the directory is synced again before any individual
01083     ** transaction files are deleted.
01084     */
01085     rc = sqlite3OsDelete(zMaster);
01086     assert( rc==SQLITE_OK );
01087     sqliteFree(zMaster);
01088     zMaster = 0;
01089     rc = sqlite3OsSyncDirectory(zMainFile);
01090     if( rc!=SQLITE_OK ){
01091       /* This is not good. The master journal file has been deleted, but
01092       ** the directory sync failed. There is no completely safe course of
01093       ** action from here. The individual journals contain the name of the
01094       ** master journal file, but there is no way of knowing if that
01095       ** master journal exists now or if it will exist after the operating
01096       ** system crash that may follow the fsync() failure.
01097       */
01098       return rc;
01099     }
01100 
01101     /* All files and directories have already been synced, so the following
01102     ** calls to sqlite3BtreeCommit() are only closing files and deleting
01103     ** journals. If something goes wrong while this is happening we don't
01104     ** really care. The integrity of the transaction is already guaranteed,
01105     ** but some stray 'cold' journals may be lying around. Returning an
01106     ** error code won't help matters.
01107     */
01108     for(i=0; i<db->nDb; i++){ 
01109       Btree *pBt = db->aDb[i].pBt;
01110       if( pBt ){
01111         sqlite3BtreeCommit(pBt);
01112       }
01113     }
01114   }
01115 #endif
01116 
01117   return rc;
01118 }
01119 
01120 /*
01121 ** Find every active VM other than pVdbe and change its status to
01122 ** aborted.  This happens when one VM causes a rollback due to an
01123 ** ON CONFLICT ROLLBACK clause (for example).  The other VMs must be
01124 ** aborted so that they do not have data rolled out from underneath
01125 ** them leading to a segfault.
01126 */
01127 void sqlite3AbortOtherActiveVdbes(sqlite3 *db, Vdbe *pExcept){
01128   Vdbe *pOther;
01129   for(pOther=db->pVdbe; pOther; pOther=pOther->pNext){
01130     if( pOther==pExcept ) continue;
01131     if( pOther->magic!=VDBE_MAGIC_RUN || pOther->pc<0 ) continue;
01132     closeAllCursors(pOther);
01133     pOther->aborted = 1;
01134   }
01135 }
01136 
01137 /* 
01138 ** This routine checks that the sqlite3.activeVdbeCnt count variable
01139 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
01140 ** currently active. An assertion fails if the two counts do not match.
01141 ** This is an internal self-check only - it is not an essential processing
01142 ** step.
01143 **
01144 ** This is a no-op if NDEBUG is defined.
01145 */
01146 #ifndef NDEBUG
01147 static void checkActiveVdbeCnt(sqlite3 *db){
01148   Vdbe *p;
01149   int cnt = 0;
01150   p = db->pVdbe;
01151   while( p ){
01152     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
01153       cnt++;
01154     }
01155     p = p->pNext;
01156   }
01157   assert( cnt==db->activeVdbeCnt );
01158 }
01159 #else
01160 #define checkActiveVdbeCnt(x)
01161 #endif
01162 
01163 /*
01164 ** This routine is called the when a VDBE tries to halt.  If the VDBE
01165 ** has made changes and is in autocommit mode, then commit those
01166 ** changes.  If a rollback is needed, then do the rollback.
01167 **
01168 ** This routine is the only way to move the state of a VM from
01169 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.
01170 **
01171 ** Return an error code.  If the commit could not complete because of
01172 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
01173 ** means the close did not happen and needs to be repeated.
01174 */
01175 int sqlite3VdbeHalt(Vdbe *p){
01176   sqlite3 *db = p->db;
01177   int i;
01178   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
01179   int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */
01180 
01181   /* This function contains the logic that determines if a statement or
01182   ** transaction will be committed or rolled back as a result of the
01183   ** execution of this virtual machine. 
01184   **
01185   ** Special errors:
01186   **
01187   **     If an SQLITE_NOMEM error has occured in a statement that writes to
01188   **     the database, then either a statement or transaction must be rolled
01189   **     back to ensure the tree-structures are in a consistent state. A
01190   **     statement transaction is rolled back if one is open, otherwise the
01191   **     entire transaction must be rolled back.
01192   **
01193   **     If an SQLITE_IOERR error has occured in a statement that writes to
01194   **     the database, then the entire transaction must be rolled back. The
01195   **     I/O error may have caused garbage to be written to the journal 
01196   **     file. Were the transaction to continue and eventually be rolled 
01197   **     back that garbage might end up in the database file.
01198   **     
01199   **     In both of the above cases, the Vdbe.errorAction variable is 
01200   **     ignored. If the sqlite3.autoCommit flag is false and a transaction
01201   **     is rolled back, it will be set to true.
01202   **
01203   ** Other errors:
01204   **
01205   ** No error:
01206   **
01207   */
01208 
01209   if( sqlite3MallocFailed() ){
01210     p->rc = SQLITE_NOMEM;
01211   }
01212   if( p->magic!=VDBE_MAGIC_RUN ){
01213     /* Already halted.  Nothing to do. */
01214     assert( p->magic==VDBE_MAGIC_HALT );
01215     return SQLITE_OK;
01216   }
01217   closeAllCursors(p);
01218   checkActiveVdbeCnt(db);
01219 
01220   /* No commit or rollback needed if the program never started */
01221   if( p->pc>=0 ){
01222 
01223     /* Check for one of the special errors - SQLITE_NOMEM or SQLITE_IOERR */
01224     isSpecialError = ((p->rc==SQLITE_NOMEM || p->rc==SQLITE_IOERR)?1:0);
01225     if( isSpecialError ){
01226       /* This loop does static analysis of the query to see which of the
01227       ** following three categories it falls into:
01228       **
01229       **     Read-only
01230       **     Query with statement journal
01231       **     Query without statement journal
01232       **
01233       ** We could do something more elegant than this static analysis (i.e.
01234       ** store the type of query as part of the compliation phase), but 
01235       ** handling malloc() or IO failure is a fairly obscure edge case so 
01236       ** this is probably easier. Todo: Might be an opportunity to reduce 
01237       ** code size a very small amount though...
01238       */
01239       int isReadOnly = 1;
01240       int isStatement = 0;
01241       assert(p->aOp || p->nOp==0);
01242       for(i=0; i<p->nOp; i++){ 
01243         switch( p->aOp[i].opcode ){
01244           case OP_Transaction:
01245             isReadOnly = 0;
01246             break;
01247           case OP_Statement:
01248             isStatement = 1;
01249             break;
01250         }
01251       }
01252   
01253       /* If the query was read-only, we need do no rollback at all. Otherwise,
01254       ** proceed with the special handling.
01255       */
01256       if( !isReadOnly ){
01257         if( p->rc==SQLITE_NOMEM && isStatement ){
01258           xFunc = sqlite3BtreeRollbackStmt;
01259         }else{
01260           /* We are forced to roll back the active transaction. Before doing
01261           ** so, abort any other statements this handle currently has active.
01262           */
01263           sqlite3AbortOtherActiveVdbes(db, p);
01264           sqlite3RollbackAll(db);
01265           db->autoCommit = 1;
01266         }
01267       }
01268     }
01269   
01270     /* If the auto-commit flag is set and this is the only active vdbe, then
01271     ** we do either a commit or rollback of the current transaction. 
01272     **
01273     ** Note: This block also runs if one of the special errors handled 
01274     ** above has occured. 
01275     */
01276     if( db->autoCommit && db->activeVdbeCnt==1 ){
01277       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
01278        /* The auto-commit flag is true, and the vdbe program was 
01279         ** successful or hit an 'OR FAIL' constraint. This means a commit 
01280         ** is required.
01281         */
01282         int rc = vdbeCommit(db);
01283         if( rc==SQLITE_BUSY ){
01284           return SQLITE_BUSY;
01285         }else if( rc!=SQLITE_OK ){
01286           p->rc = rc;
01287           sqlite3RollbackAll(db);
01288         }else{
01289           sqlite3CommitInternalChanges(db);
01290         }
01291       }else{
01292         sqlite3RollbackAll(db);
01293       }
01294     }else if( !xFunc ){
01295       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
01296         xFunc = sqlite3BtreeCommitStmt;
01297       }else if( p->errorAction==OE_Abort ){
01298         xFunc = sqlite3BtreeRollbackStmt;
01299       }else{
01300         sqlite3AbortOtherActiveVdbes(db, p);
01301         sqlite3RollbackAll(db);
01302         db->autoCommit = 1;
01303       }
01304     }
01305   
01306     /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
01307     ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
01308     ** and the return code is still SQLITE_OK, set the return code to the new
01309     ** error value.
01310     */
01311     assert(!xFunc ||
01312       xFunc==sqlite3BtreeCommitStmt ||
01313       xFunc==sqlite3BtreeRollbackStmt
01314     );
01315     for(i=0; xFunc && i<db->nDb; i++){ 
01316       int rc;
01317       Btree *pBt = db->aDb[i].pBt;
01318       if( pBt ){
01319         rc = xFunc(pBt);
01320         if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
01321           p->rc = rc;
01322           sqlite3SetString(&p->zErrMsg, 0);
01323         }
01324       }
01325     }
01326   
01327     /* If this was an INSERT, UPDATE or DELETE and the statement was committed, 
01328     ** set the change counter. 
01329     */
01330     if( p->changeCntOn && p->pc>=0 ){
01331       if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
01332         sqlite3VdbeSetChanges(db, p->nChange);
01333       }else{
01334         sqlite3VdbeSetChanges(db, 0);
01335       }
01336       p->nChange = 0;
01337     }
01338   
01339     /* Rollback or commit any schema changes that occurred. */
01340     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
01341       sqlite3ResetInternalSchema(db, 0);
01342       db->flags = (db->flags | SQLITE_InternChanges);
01343     }
01344   }
01345 
01346   /* We have successfully halted and closed the VM.  Record this fact. */
01347   if( p->pc>=0 ){
01348     db->activeVdbeCnt--;
01349   }
01350   p->magic = VDBE_MAGIC_HALT;
01351   checkActiveVdbeCnt(db);
01352 
01353   return SQLITE_OK;
01354 }
01355 
01356 /*
01357 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
01358 ** Write any error messages into *pzErrMsg.  Return the result code.
01359 **
01360 ** After this routine is run, the VDBE should be ready to be executed
01361 ** again.
01362 **
01363 ** To look at it another way, this routine resets the state of the
01364 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
01365 ** VDBE_MAGIC_INIT.
01366 */
01367 int sqlite3VdbeReset(Vdbe *p){
01368   if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
01369     sqlite3Error(p->db, SQLITE_MISUSE, 0);
01370     return SQLITE_MISUSE;
01371   }
01372 
01373   /* If the VM did not run to completion or if it encountered an
01374   ** error, then it might not have been halted properly.  So halt
01375   ** it now.
01376   */
01377   sqlite3VdbeHalt(p);
01378 
01379   /* If the VDBE has be run even partially, then transfer the error code
01380   ** and error message from the VDBE into the main database structure.  But
01381   ** if the VDBE has just been set to run but has not actually executed any
01382   ** instructions yet, leave the main database error information unchanged.
01383   */
01384   if( p->pc>=0 ){
01385     if( p->zErrMsg ){
01386       sqlite3* db = p->db;
01387       sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, sqlite3FreeX);
01388       db->errCode = p->rc;
01389       p->zErrMsg = 0;
01390     }else if( p->rc ){
01391       sqlite3Error(p->db, p->rc, 0);
01392     }else{
01393       sqlite3Error(p->db, SQLITE_OK, 0);
01394     }
01395   }else if( p->rc && p->expired ){
01396     /* The expired flag was set on the VDBE before the first call
01397     ** to sqlite3_step(). For consistency (since sqlite3_step() was
01398     ** called), set the database error in this case as well.
01399     */
01400     sqlite3Error(p->db, p->rc, 0);
01401   }
01402 
01403   /* Reclaim all memory used by the VDBE
01404   */
01405   Cleanup(p);
01406 
01407   /* Save profiling information from this VDBE run.
01408   */
01409   assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || !p->aStack );
01410 #ifdef VDBE_PROFILE
01411   {
01412     FILE *out = fopen("vdbe_profile.out", "a");
01413     if( out ){
01414       int i;
01415       fprintf(out, "---- ");
01416       for(i=0; i<p->nOp; i++){
01417         fprintf(out, "%02x", p->aOp[i].opcode);
01418       }
01419       fprintf(out, "\n");
01420       for(i=0; i<p->nOp; i++){
01421         fprintf(out, "%6d %10lld %8lld ",
01422            p->aOp[i].cnt,
01423            p->aOp[i].cycles,
01424            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
01425         );
01426         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
01427       }
01428       fclose(out);
01429     }
01430   }
01431 #endif
01432   p->magic = VDBE_MAGIC_INIT;
01433   p->aborted = 0;
01434   if( p->rc==SQLITE_SCHEMA ){
01435     sqlite3ResetInternalSchema(p->db, 0);
01436   }
01437   return p->rc;
01438 }
01439  
01440 /*
01441 ** Clean up and delete a VDBE after execution.  Return an integer which is
01442 ** the result code.  Write any error message text into *pzErrMsg.
01443 */
01444 int sqlite3VdbeFinalize(Vdbe *p){
01445   int rc = SQLITE_OK;
01446 
01447   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
01448     rc = sqlite3VdbeReset(p);
01449   }else if( p->magic!=VDBE_MAGIC_INIT ){
01450     return SQLITE_MISUSE;
01451   }
01452   sqlite3VdbeDelete(p);
01453   return rc;
01454 }
01455 
01456 /*
01457 ** Call the destructor for each auxdata entry in pVdbeFunc for which
01458 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
01459 ** are always destroyed.  To destroy all auxdata entries, call this
01460 ** routine with mask==0.
01461 */
01462 void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
01463   int i;
01464   for(i=0; i<pVdbeFunc->nAux; i++){
01465     struct AuxData *pAux = &pVdbeFunc->apAux[i];
01466     if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
01467       if( pAux->xDelete ){
01468         pAux->xDelete(pAux->pAux);
01469       }
01470       pAux->pAux = 0;
01471     }
01472   }
01473 }
01474 
01475 /*
01476 ** Delete an entire VDBE.
01477 */
01478 void sqlite3VdbeDelete(Vdbe *p){
01479   int i;
01480   if( p==0 ) return;
01481   Cleanup(p);
01482   if( p->pPrev ){
01483     p->pPrev->pNext = p->pNext;
01484   }else{
01485     assert( p->db->pVdbe==p );
01486     p->db->pVdbe = p->pNext;
01487   }
01488   if( p->pNext ){
01489     p->pNext->pPrev = p->pPrev;
01490   }
01491   if( p->aOp ){
01492     for(i=0; i<p->nOp; i++){
01493       Op *pOp = &p->aOp[i];
01494       freeP3(pOp->p3type, pOp->p3);
01495     }
01496     sqliteFree(p->aOp);
01497   }
01498   releaseMemArray(p->aVar, p->nVar);
01499   sqliteFree(p->aLabel);
01500   sqliteFree(p->aStack);
01501   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
01502   sqliteFree(p->aColName);
01503   p->magic = VDBE_MAGIC_DEAD;
01504   sqliteFree(p);
01505 }
01506 
01507 /*
01508 ** If a MoveTo operation is pending on the given cursor, then do that
01509 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
01510 ** routine does nothing and returns SQLITE_OK.
01511 */
01512 int sqlite3VdbeCursorMoveto(Cursor *p){
01513   if( p->deferredMoveto ){
01514     int res, rc;
01515     extern int sqlite3_search_count;
01516     assert( p->isTable );
01517     if( p->isTable ){
01518       rc = sqlite3BtreeMoveto(p->pCursor, 0, p->movetoTarget, &res);
01519     }else{
01520       rc = sqlite3BtreeMoveto(p->pCursor,(char*)&p->movetoTarget,
01521                               sizeof(i64),&res);
01522     }
01523     if( rc ) return rc;
01524     *p->pIncrKey = 0;
01525     p->lastRowid = keyToInt(p->movetoTarget);
01526     p->rowidIsValid = res==0;
01527     if( res<0 ){
01528       rc = sqlite3BtreeNext(p->pCursor, &res);
01529       if( rc ) return rc;
01530     }
01531     sqlite3_search_count++;
01532     p->deferredMoveto = 0;
01533     p->cacheStatus = CACHE_STALE;
01534   }
01535   return SQLITE_OK;
01536 }
01537 
01538 /*
01539 ** The following functions:
01540 **
01541 ** sqlite3VdbeSerialType()
01542 ** sqlite3VdbeSerialTypeLen()
01543 ** sqlite3VdbeSerialRead()
01544 ** sqlite3VdbeSerialLen()
01545 ** sqlite3VdbeSerialWrite()
01546 **
01547 ** encapsulate the code that serializes values for storage in SQLite
01548 ** data and index records. Each serialized value consists of a
01549 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
01550 ** integer, stored as a varint.
01551 **
01552 ** In an SQLite index record, the serial type is stored directly before
01553 ** the blob of data that it corresponds to. In a table record, all serial
01554 ** types are stored at the start of the record, and the blobs of data at
01555 ** the end. Hence these functions allow the caller to handle the
01556 ** serial-type and data blob seperately.
01557 **
01558 ** The following table describes the various storage classes for data:
01559 **
01560 **   serial type        bytes of data      type
01561 **   --------------     ---------------    ---------------
01562 **      0                     0            NULL
01563 **      1                     1            signed integer
01564 **      2                     2            signed integer
01565 **      3                     3            signed integer
01566 **      4                     4            signed integer
01567 **      5                     6            signed integer
01568 **      6                     8            signed integer
01569 **      7                     8            IEEE float
01570 **      8                     0            Integer constant 0
01571 **      9                     0            Integer constant 1
01572 **     10,11                               reserved for expansion
01573 **    N>=12 and even       (N-12)/2        BLOB
01574 **    N>=13 and odd        (N-13)/2        text
01575 **
01576 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
01577 ** of SQLite will not understand those serial types.
01578 */
01579 
01580 /*
01581 ** Return the serial-type for the value stored in pMem.
01582 */
01583 u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
01584   int flags = pMem->flags;
01585 
01586   if( flags&MEM_Null ){
01587     return 0;
01588   }
01589   if( flags&MEM_Int ){
01590     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
01591 #   define MAX_6BYTE ((((i64)0x00001000)<<32)-1)
01592     i64 i = pMem->i;
01593     u64 u;
01594     if( file_format>=4 && (i&1)==i ){
01595       return 8+i;
01596     }
01597     u = i<0 ? -i : i;
01598     if( u<=127 ) return 1;
01599     if( u<=32767 ) return 2;
01600     if( u<=8388607 ) return 3;
01601     if( u<=2147483647 ) return 4;
01602     if( u<=MAX_6BYTE ) return 5;
01603     return 6;
01604   }
01605   if( flags&MEM_Real ){
01606     return 7;
01607   }
01608   if( flags&MEM_Str ){
01609     int n = pMem->n;
01610     assert( n>=0 );
01611     return ((n*2) + 13);
01612   }
01613   if( flags&MEM_Blob ){
01614     return (pMem->n*2 + 12);
01615   }
01616   return 0;
01617 }
01618 
01619 /*
01620 ** Return the length of the data corresponding to the supplied serial-type.
01621 */
01622 int sqlite3VdbeSerialTypeLen(u32 serial_type){
01623   if( serial_type>=12 ){
01624     return (serial_type-12)/2;
01625   }else{
01626     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
01627     return aSize[serial_type];
01628   }
01629 }
01630 
01631 /*
01632 ** Write the serialized data blob for the value stored in pMem into 
01633 ** buf. It is assumed that the caller has allocated sufficient space.
01634 ** Return the number of bytes written.
01635 */ 
01636 int sqlite3VdbeSerialPut(unsigned char *buf, Mem *pMem, int file_format){
01637   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
01638   int len;
01639 
01640   /* Integer and Real */
01641   if( serial_type<=7 && serial_type>0 ){
01642     u64 v;
01643     int i;
01644     if( serial_type==7 ){
01645       v = *(u64*)&pMem->r;
01646     }else{
01647       v = *(u64*)&pMem->i;
01648     }
01649     len = i = sqlite3VdbeSerialTypeLen(serial_type);
01650     while( i-- ){
01651       buf[i] = (v&0xFF);
01652       v >>= 8;
01653     }
01654     return len;
01655   }
01656 
01657   /* String or blob */
01658   if( serial_type>=12 ){
01659     len = sqlite3VdbeSerialTypeLen(serial_type);
01660     memcpy(buf, pMem->z, len);
01661     return len;
01662   }
01663 
01664   /* NULL or constants 0 or 1 */
01665   return 0;
01666 }
01667 
01668 /*
01669 ** Deserialize the data blob pointed to by buf as serial type serial_type
01670 ** and store the result in pMem.  Return the number of bytes read.
01671 */ 
01672 int sqlite3VdbeSerialGet(
01673   const unsigned char *buf,     /* Buffer to deserialize from */
01674   u32 serial_type,              /* Serial type to deserialize */
01675   Mem *pMem                     /* Memory cell to write value into */
01676 ){
01677   switch( serial_type ){
01678     case 10:   /* Reserved for future use */
01679     case 11:   /* Reserved for future use */
01680     case 0: {  /* NULL */
01681       pMem->flags = MEM_Null;
01682       break;
01683     }
01684     case 1: { /* 1-byte signed integer */
01685       pMem->i = (signed char)buf[0];
01686       pMem->flags = MEM_Int;
01687       return 1;
01688     }
01689     case 2: { /* 2-byte signed integer */
01690       pMem->i = (((signed char)buf[0])<<8) | buf[1];
01691       pMem->flags = MEM_Int;
01692       return 2;
01693     }
01694     case 3: { /* 3-byte signed integer */
01695       pMem->i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
01696       pMem->flags = MEM_Int;
01697       return 3;
01698     }
01699     case 4: { /* 4-byte signed integer */
01700       pMem->i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
01701       pMem->flags = MEM_Int;
01702       return 4;
01703     }
01704     case 5: { /* 6-byte signed integer */
01705       u64 x = (((signed char)buf[0])<<8) | buf[1];
01706       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
01707       x = (x<<32) | y;
01708       pMem->i = *(i64*)&x;
01709       pMem->flags = MEM_Int;
01710       return 6;
01711     }
01712     case 6:   /* 8-byte signed integer */
01713     case 7: { /* IEEE floating point */
01714       u64 x;
01715       u32 y;
01716 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
01717       /* Verify that integers and floating point values use the same
01718       ** byte order.  The byte order differs on some (broken) architectures.
01719       */
01720       static const u64 t1 = ((u64)0x3ff00000)<<32;
01721       assert( 1.0==*(double*)&t1 );
01722 #endif
01723 
01724       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
01725       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
01726       x = (x<<32) | y;
01727       if( serial_type==6 ){
01728         pMem->i = *(i64*)&x;
01729         pMem->flags = MEM_Int;
01730       }else{
01731         pMem->r = *(double*)&x;
01732         pMem->flags = MEM_Real;
01733       }
01734       return 8;
01735     }
01736     case 8:    /* Integer 0 */
01737     case 9: {  /* Integer 1 */
01738       pMem->i = serial_type-8;
01739       pMem->flags = MEM_Int;
01740       return 0;
01741     }
01742     default: {
01743       int len = (serial_type-12)/2;
01744       pMem->z = (char *)buf;
01745       pMem->n = len;
01746       pMem->xDel = 0;
01747       if( serial_type&0x01 ){
01748         pMem->flags = MEM_Str | MEM_Ephem;
01749       }else{
01750         pMem->flags = MEM_Blob | MEM_Ephem;
01751       }
01752       return len;
01753     }
01754   }
01755   return 0;
01756 }
01757 
01758 /*
01759 ** The header of a record consists of a sequence variable-length integers.
01760 ** These integers are almost always small and are encoded as a single byte.
01761 ** The following macro takes advantage this fact to provide a fast decode
01762 ** of the integers in a record header.  It is faster for the common case
01763 ** where the integer is a single byte.  It is a little slower when the
01764 ** integer is two or more bytes.  But overall it is faster.
01765 **
01766 ** The following expressions are equivalent:
01767 **
01768 **     x = sqlite3GetVarint32( A, &B );
01769 **
01770 **     x = GetVarint( A, B );
01771 **
01772 */
01773 #define GetVarint(A,B)  ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
01774 
01775 /*
01776 ** This function compares the two table rows or index records specified by 
01777 ** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
01778 ** or positive integer if {nKey1, pKey1} is less than, equal to or 
01779 ** greater than {nKey2, pKey2}.  Both Key1 and Key2 must be byte strings
01780 ** composed by the OP_MakeRecord opcode of the VDBE.
01781 */
01782 int sqlite3VdbeRecordCompare(
01783   void *userData,
01784   int nKey1, const void *pKey1, 
01785   int nKey2, const void *pKey2
01786 ){
01787   KeyInfo *pKeyInfo = (KeyInfo*)userData;
01788   u32 d1, d2;          /* Offset into aKey[] of next data element */
01789   u32 idx1, idx2;      /* Offset into aKey[] of next header element */
01790   u32 szHdr1, szHdr2;  /* Number of bytes in header */
01791   int i = 0;
01792   int nField;
01793   int rc = 0;
01794   const unsigned char *aKey1 = (const unsigned char *)pKey1;
01795   const unsigned char *aKey2 = (const unsigned char *)pKey2;
01796 
01797   Mem mem1;
01798   Mem mem2;
01799   mem1.enc = pKeyInfo->enc;
01800   mem2.enc = pKeyInfo->enc;
01801   
01802   idx1 = GetVarint(aKey1, szHdr1);
01803   d1 = szHdr1;
01804   idx2 = GetVarint(aKey2, szHdr2);
01805   d2 = szHdr2;
01806   nField = pKeyInfo->nField;
01807   while( idx1<szHdr1 && idx2<szHdr2 ){
01808     u32 serial_type1;
01809     u32 serial_type2;
01810 
01811     /* Read the serial types for the next element in each key. */
01812     idx1 += GetVarint( aKey1+idx1, serial_type1 );
01813     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
01814     idx2 += GetVarint( aKey2+idx2, serial_type2 );
01815     if( d2>=nKey2 && sqlite3VdbeSerialTypeLen(serial_type2)>0 ) break;
01816 
01817     /* Assert that there is enough space left in each key for the blob of
01818     ** data to go with the serial type just read. This assert may fail if
01819     ** the file is corrupted.  Then read the value from each key into mem1
01820     ** and mem2 respectively.
01821     */
01822     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
01823     d2 += sqlite3VdbeSerialGet(&aKey2[d2], serial_type2, &mem2);
01824 
01825     rc = sqlite3MemCompare(&mem1, &mem2, i<nField ? pKeyInfo->aColl[i] : 0);
01826     if( mem1.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem1);
01827     if( mem2.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem2);
01828     if( rc!=0 ){
01829       break;
01830     }
01831     i++;
01832   }
01833 
01834   /* One of the keys ran out of fields, but all the fields up to that point
01835   ** were equal. If the incrKey flag is true, then the second key is
01836   ** treated as larger.
01837   */
01838   if( rc==0 ){
01839     if( pKeyInfo->incrKey ){
01840       rc = -1;
01841     }else if( d1<nKey1 ){
01842       rc = 1;
01843     }else if( d2<nKey2 ){
01844       rc = -1;
01845     }
01846   }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
01847                && pKeyInfo->aSortOrder[i] ){
01848     rc = -rc;
01849   }
01850 
01851   return rc;
01852 }
01853 
01854 /*
01855 ** The argument is an index entry composed using the OP_MakeRecord opcode.
01856 ** The last entry in this record should be an integer (specifically
01857 ** an integer rowid).  This routine returns the number of bytes in
01858 ** that integer.
01859 */
01860 int sqlite3VdbeIdxRowidLen(const u8 *aKey){
01861   u32 szHdr;        /* Size of the header */
01862   u32 typeRowid;    /* Serial type of the rowid */
01863 
01864   sqlite3GetVarint32(aKey, &szHdr);
01865   sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
01866   return sqlite3VdbeSerialTypeLen(typeRowid);
01867 }
01868   
01869 
01870 /*
01871 ** pCur points at an index entry created using the OP_MakeRecord opcode.
01872 ** Read the rowid (the last field in the record) and store it in *rowid.
01873 ** Return SQLITE_OK if everything works, or an error code otherwise.
01874 */
01875 int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
01876   i64 nCellKey;
01877   int rc;
01878   u32 szHdr;        /* Size of the header */
01879   u32 typeRowid;    /* Serial type of the rowid */
01880   u32 lenRowid;     /* Size of the rowid */
01881   Mem m, v;
01882 
01883   sqlite3BtreeKeySize(pCur, &nCellKey);
01884   if( nCellKey<=0 ){
01885     return SQLITE_CORRUPT_BKPT;
01886   }
01887   rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
01888   if( rc ){
01889     return rc;
01890   }
01891   sqlite3GetVarint32((u8*)m.z, &szHdr);
01892   sqlite3GetVarint32((u8*)&m.z[szHdr-1], &typeRowid);
01893   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
01894   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
01895   *rowid = v.i;
01896   sqlite3VdbeMemRelease(&m);
01897   return SQLITE_OK;
01898 }
01899 
01900 /*
01901 ** Compare the key of the index entry that cursor pC is point to against
01902 ** the key string in pKey (of length nKey).  Write into *pRes a number
01903 ** that is negative, zero, or positive if pC is less than, equal to,
01904 ** or greater than pKey.  Return SQLITE_OK on success.
01905 **
01906 ** pKey is either created without a rowid or is truncated so that it
01907 ** omits the rowid at the end.  The rowid at the end of the index entry
01908 ** is ignored as well.
01909 */
01910 int sqlite3VdbeIdxKeyCompare(
01911   Cursor *pC,                 /* The cursor to compare against */
01912   int nKey, const u8 *pKey,   /* The key to compare */
01913   int *res                    /* Write the comparison result here */
01914 ){
01915   i64 nCellKey;
01916   int rc;
01917   BtCursor *pCur = pC->pCursor;
01918   int lenRowid;
01919   Mem m;
01920 
01921   sqlite3BtreeKeySize(pCur, &nCellKey);
01922   if( nCellKey<=0 ){
01923     *res = 0;
01924     return SQLITE_OK;
01925   }
01926   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
01927   if( rc ){
01928     return rc;
01929   }
01930   lenRowid = sqlite3VdbeIdxRowidLen((u8*)m.z);
01931   *res = sqlite3VdbeRecordCompare(pC->pKeyInfo, m.n-lenRowid, m.z, nKey, pKey);
01932   sqlite3VdbeMemRelease(&m);
01933   return SQLITE_OK;
01934 }
01935 
01936 /*
01937 ** This routine sets the value to be returned by subsequent calls to
01938 ** sqlite3_changes() on the database handle 'db'. 
01939 */
01940 void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
01941   db->nChange = nChange;
01942   db->nTotalChange += nChange;
01943 }
01944 
01945 /*
01946 ** Set a flag in the vdbe to update the change counter when it is finalised
01947 ** or reset.
01948 */
01949 void sqlite3VdbeCountChanges(Vdbe *v){
01950   v->changeCntOn = 1;
01951 }
01952 
01953 /*
01954 ** Mark every prepared statement associated with a database connection
01955 ** as expired.
01956 **
01957 ** An expired statement means that recompilation of the statement is
01958 ** recommend.  Statements expire when things happen that make their
01959 ** programs obsolete.  Removing user-defined functions or collating
01960 ** sequences, or changing an authorization function are the types of
01961 ** things that make prepared statements obsolete.
01962 */
01963 void sqlite3ExpirePreparedStatements(sqlite3 *db){
01964   Vdbe *p;
01965   for(p = db->pVdbe; p; p=p->pNext){
01966     p->expired = 1;
01967   }
01968 }
01969 
01970 /*
01971 ** Return the database associated with the Vdbe.
01972 */
01973 sqlite3 *sqlite3VdbeDb(Vdbe *v){
01974   return v->db;
01975 }