extensions/sqlite/sqlite-source/vdbeaux.c
author David Anderson <dvander@alliedmods.net>
Mon Mar 17 01:09:28 2008 +0000 (2008-03-17)
changeset 1941 54539fa4e51f
parent 1645 27307df4d711
permissions -rw-r--r--
bumped versions
     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 <ctype.h>
    19 #include "vdbeInt.h"
    20 
    21 
    22 
    23 /*
    24 ** When debugging the code generator in a symbolic debugger, one can
    25 ** set the sqlite3_vdbe_addop_trace to 1 and all opcodes will be printed
    26 ** as they are added to the instruction stream.
    27 */
    28 #ifdef SQLITE_DEBUG
    29 int sqlite3_vdbe_addop_trace = 0;
    30 #endif
    31 
    32 
    33 /*
    34 ** Create a new virtual database engine.
    35 */
    36 Vdbe *sqlite3VdbeCreate(sqlite3 *db){
    37   Vdbe *p;
    38   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
    39   if( p==0 ) return 0;
    40   p->db = db;
    41   if( db->pVdbe ){
    42     db->pVdbe->pPrev = p;
    43   }
    44   p->pNext = db->pVdbe;
    45   p->pPrev = 0;
    46   db->pVdbe = p;
    47   p->magic = VDBE_MAGIC_INIT;
    48   return p;
    49 }
    50 
    51 /*
    52 ** Remember the SQL string for a prepared statement.
    53 */
    54 void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
    55   if( p==0 ) return;
    56   assert( p->zSql==0 );
    57   p->zSql = sqlite3DbStrNDup(p->db, z, n);
    58 }
    59 
    60 /*
    61 ** Return the SQL associated with a prepared statement
    62 */
    63 const char *sqlite3VdbeGetSql(Vdbe *p){
    64   return p->zSql;
    65 }
    66 
    67 /*
    68 ** Swap all content between two VDBE structures.
    69 */
    70 void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
    71   Vdbe tmp, *pTmp;
    72   char *zTmp;
    73   int nTmp;
    74   tmp = *pA;
    75   *pA = *pB;
    76   *pB = tmp;
    77   pTmp = pA->pNext;
    78   pA->pNext = pB->pNext;
    79   pB->pNext = pTmp;
    80   pTmp = pA->pPrev;
    81   pA->pPrev = pB->pPrev;
    82   pB->pPrev = pTmp;
    83   zTmp = pA->zSql;
    84   pA->zSql = pB->zSql;
    85   pB->zSql = zTmp;
    86   nTmp = pA->nSql;
    87   pA->nSql = pB->nSql;
    88   pB->nSql = nTmp;
    89 }
    90 
    91 #ifdef SQLITE_DEBUG
    92 /*
    93 ** Turn tracing on or off
    94 */
    95 void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
    96   p->trace = trace;
    97 }
    98 #endif
    99 
   100 /*
   101 ** Resize the Vdbe.aOp array so that it contains at least N
   102 ** elements. If the Vdbe is in VDBE_MAGIC_RUN state, then
   103 ** the Vdbe.aOp array will be sized to contain exactly N
   104 ** elements. Vdbe.nOpAlloc is set to reflect the new size of
   105 ** the array.
   106 **
   107 ** If an out-of-memory error occurs while resizing the array,
   108 ** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
   109 ** any opcodes already allocated can be correctly deallocated
   110 ** along with the rest of the Vdbe).
   111 */
   112 static void resizeOpArray(Vdbe *p, int N){
   113   int runMode = p->magic==VDBE_MAGIC_RUN;
   114   if( runMode || p->nOpAlloc<N ){
   115     VdbeOp *pNew;
   116     int nNew = N + 100*(!runMode);
   117     int oldSize = p->nOpAlloc;
   118     pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
   119     if( pNew ){
   120       p->nOpAlloc = nNew;
   121       p->aOp = pNew;
   122       if( nNew>oldSize ){
   123         memset(&p->aOp[oldSize], 0, (nNew-oldSize)*sizeof(Op));
   124       }
   125     }
   126   }
   127 }
   128 
   129 /*
   130 ** Add a new instruction to the list of instructions current in the
   131 ** VDBE.  Return the address of the new instruction.
   132 **
   133 ** Parameters:
   134 **
   135 **    p               Pointer to the VDBE
   136 **
   137 **    op              The opcode for this instruction
   138 **
   139 **    p1, p2          First two of the three possible operands.
   140 **
   141 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
   142 ** the sqlite3VdbeChangeP3() function to change the value of the P3
   143 ** operand.
   144 */
   145 int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){
   146   int i;
   147   VdbeOp *pOp;
   148 
   149   i = p->nOp;
   150   assert( p->magic==VDBE_MAGIC_INIT );
   151   if( p->nOpAlloc<=i ){
   152     resizeOpArray(p, i+1);
   153     if( p->db->mallocFailed ){
   154       return 0;
   155     }
   156   }
   157   p->nOp++;
   158   pOp = &p->aOp[i];
   159   pOp->opcode = op;
   160   pOp->p1 = p1;
   161   pOp->p2 = p2;
   162   pOp->p3 = 0;
   163   pOp->p3type = P3_NOTUSED;
   164   p->expired = 0;
   165 #ifdef SQLITE_DEBUG
   166   if( sqlite3_vdbe_addop_trace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
   167 #endif
   168   return i;
   169 }
   170 
   171 /*
   172 ** Add an opcode that includes the p3 value.
   173 */
   174 int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){
   175   int addr = sqlite3VdbeAddOp(p, op, p1, p2);
   176   sqlite3VdbeChangeP3(p, addr, zP3, p3type);
   177   return addr;
   178 }
   179 
   180 /*
   181 ** Create a new symbolic label for an instruction that has yet to be
   182 ** coded.  The symbolic label is really just a negative number.  The
   183 ** label can be used as the P2 value of an operation.  Later, when
   184 ** the label is resolved to a specific address, the VDBE will scan
   185 ** through its operation list and change all values of P2 which match
   186 ** the label into the resolved address.
   187 **
   188 ** The VDBE knows that a P2 value is a label because labels are
   189 ** always negative and P2 values are suppose to be non-negative.
   190 ** Hence, a negative P2 value is a label that has yet to be resolved.
   191 **
   192 ** Zero is returned if a malloc() fails.
   193 */
   194 int sqlite3VdbeMakeLabel(Vdbe *p){
   195   int i;
   196   i = p->nLabel++;
   197   assert( p->magic==VDBE_MAGIC_INIT );
   198   if( i>=p->nLabelAlloc ){
   199     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
   200     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
   201                                     p->nLabelAlloc*sizeof(p->aLabel[0]));
   202   }
   203   if( p->aLabel ){
   204     p->aLabel[i] = -1;
   205   }
   206   return -1-i;
   207 }
   208 
   209 /*
   210 ** Resolve label "x" to be the address of the next instruction to
   211 ** be inserted.  The parameter "x" must have been obtained from
   212 ** a prior call to sqlite3VdbeMakeLabel().
   213 */
   214 void sqlite3VdbeResolveLabel(Vdbe *p, int x){
   215   int j = -1-x;
   216   assert( p->magic==VDBE_MAGIC_INIT );
   217   assert( j>=0 && j<p->nLabel );
   218   if( p->aLabel ){
   219     p->aLabel[j] = p->nOp;
   220   }
   221 }
   222 
   223 /*
   224 ** Return non-zero if opcode 'op' is guarenteed not to push more values
   225 ** onto the VDBE stack than it pops off.
   226 */
   227 static int opcodeNoPush(u8 op){
   228   /* The 10 NOPUSH_MASK_n constants are defined in the automatically
   229   ** generated header file opcodes.h. Each is a 16-bit bitmask, one
   230   ** bit corresponding to each opcode implemented by the virtual
   231   ** machine in vdbe.c. The bit is true if the word "no-push" appears
   232   ** in a comment on the same line as the "case OP_XXX:" in 
   233   ** sqlite3VdbeExec() in vdbe.c.
   234   **
   235   ** If the bit is true, then the corresponding opcode is guarenteed not
   236   ** to grow the stack when it is executed. Otherwise, it may grow the
   237   ** stack by at most one entry.
   238   **
   239   ** NOPUSH_MASK_0 corresponds to opcodes 0 to 15. NOPUSH_MASK_1 contains
   240   ** one bit for opcodes 16 to 31, and so on.
   241   **
   242   ** 16-bit bitmasks (rather than 32-bit) are specified in opcodes.h 
   243   ** because the file is generated by an awk program. Awk manipulates
   244   ** all numbers as floating-point and we don't want to risk a rounding
   245   ** error if someone builds with an awk that uses (for example) 32-bit 
   246   ** IEEE floats.
   247   */ 
   248   static const u32 masks[5] = {
   249     NOPUSH_MASK_0 + (((unsigned)NOPUSH_MASK_1)<<16),
   250     NOPUSH_MASK_2 + (((unsigned)NOPUSH_MASK_3)<<16),
   251     NOPUSH_MASK_4 + (((unsigned)NOPUSH_MASK_5)<<16),
   252     NOPUSH_MASK_6 + (((unsigned)NOPUSH_MASK_7)<<16),
   253     NOPUSH_MASK_8 + (((unsigned)NOPUSH_MASK_9)<<16)
   254   };
   255   assert( op<32*5 );
   256   return (masks[op>>5] & (1<<(op&0x1F)));
   257 }
   258 
   259 #ifndef NDEBUG
   260 int sqlite3VdbeOpcodeNoPush(u8 op){
   261   return opcodeNoPush(op);
   262 }
   263 #endif
   264 
   265 /*
   266 ** Loop through the program looking for P2 values that are negative.
   267 ** Each such value is a label.  Resolve the label by setting the P2
   268 ** value to its correct non-zero value.
   269 **
   270 ** This routine is called once after all opcodes have been inserted.
   271 **
   272 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
   273 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
   274 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
   275 **
   276 ** The integer *pMaxStack is set to the maximum number of vdbe stack
   277 ** entries that static analysis reveals this program might need.
   278 **
   279 ** This routine also does the following optimization:  It scans for
   280 ** Halt instructions where P1==SQLITE_CONSTRAINT or P2==OE_Abort or for
   281 ** IdxInsert instructions where P2!=0.  If no such instruction is
   282 ** found, then every Statement instruction is changed to a Noop.  In
   283 ** this way, we avoid creating the statement journal file unnecessarily.
   284 */
   285 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs, int *pMaxStack){
   286   int i;
   287   int nMaxArgs = 0;
   288   int nMaxStack = p->nOp;
   289   Op *pOp;
   290   int *aLabel = p->aLabel;
   291   int doesStatementRollback = 0;
   292   int hasStatementBegin = 0;
   293   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
   294     u8 opcode = pOp->opcode;
   295 
   296     if( opcode==OP_Function || opcode==OP_AggStep 
   297 #ifndef SQLITE_OMIT_VIRTUALTABLE
   298         || opcode==OP_VUpdate
   299 #endif
   300     ){
   301       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
   302     }
   303     if( opcode==OP_Halt ){
   304       if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
   305         doesStatementRollback = 1;
   306       }
   307     }else if( opcode==OP_Statement ){
   308       hasStatementBegin = 1;
   309 #ifndef SQLITE_OMIT_VIRTUALTABLE
   310     }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
   311       doesStatementRollback = 1;
   312     }else if( opcode==OP_VFilter ){
   313       int n;
   314       assert( p->nOp - i >= 3 );
   315       assert( pOp[-2].opcode==OP_Integer );
   316       n = pOp[-2].p1;
   317       if( n>nMaxArgs ) nMaxArgs = n;
   318 #endif
   319     }
   320     if( opcodeNoPush(opcode) ){
   321       nMaxStack--;
   322     }
   323 
   324     if( pOp->p2>=0 ) continue;
   325     assert( -1-pOp->p2<p->nLabel );
   326     pOp->p2 = aLabel[-1-pOp->p2];
   327   }
   328   sqlite3_free(p->aLabel);
   329   p->aLabel = 0;
   330 
   331   *pMaxFuncArgs = nMaxArgs;
   332   *pMaxStack = nMaxStack;
   333 
   334   /* If we never rollback a statement transaction, then statement
   335   ** transactions are not needed.  So change every OP_Statement
   336   ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
   337   ** which can be expensive on some platforms.
   338   */
   339   if( hasStatementBegin && !doesStatementRollback ){
   340     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
   341       if( pOp->opcode==OP_Statement ){
   342         pOp->opcode = OP_Noop;
   343       }
   344     }
   345   }
   346 }
   347 
   348 /*
   349 ** Return the address of the next instruction to be inserted.
   350 */
   351 int sqlite3VdbeCurrentAddr(Vdbe *p){
   352   assert( p->magic==VDBE_MAGIC_INIT );
   353   return p->nOp;
   354 }
   355 
   356 /*
   357 ** Add a whole list of operations to the operation stack.  Return the
   358 ** address of the first operation added.
   359 */
   360 int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
   361   int addr;
   362   assert( p->magic==VDBE_MAGIC_INIT );
   363   resizeOpArray(p, p->nOp + nOp);
   364   if( p->db->mallocFailed ){
   365     return 0;
   366   }
   367   addr = p->nOp;
   368   if( nOp>0 ){
   369     int i;
   370     VdbeOpList const *pIn = aOp;
   371     for(i=0; i<nOp; i++, pIn++){
   372       int p2 = pIn->p2;
   373       VdbeOp *pOut = &p->aOp[i+addr];
   374       pOut->opcode = pIn->opcode;
   375       pOut->p1 = pIn->p1;
   376       pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
   377       pOut->p3 = pIn->p3;
   378       pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
   379 #ifdef SQLITE_DEBUG
   380       if( sqlite3_vdbe_addop_trace ){
   381         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
   382       }
   383 #endif
   384     }
   385     p->nOp += nOp;
   386   }
   387   return addr;
   388 }
   389 
   390 /*
   391 ** Change the value of the P1 operand for a specific instruction.
   392 ** This routine is useful when a large program is loaded from a
   393 ** static array using sqlite3VdbeAddOpList but we want to make a
   394 ** few minor changes to the program.
   395 */
   396 void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
   397   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
   398   if( p && addr>=0 && p->nOp>addr && p->aOp ){
   399     p->aOp[addr].p1 = val;
   400   }
   401 }
   402 
   403 /*
   404 ** Change the value of the P2 operand for a specific instruction.
   405 ** This routine is useful for setting a jump destination.
   406 */
   407 void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
   408   assert( val>=0 );
   409   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
   410   if( p && addr>=0 && p->nOp>addr && p->aOp ){
   411     p->aOp[addr].p2 = val;
   412   }
   413 }
   414 
   415 /*
   416 ** Change the P2 operand of instruction addr so that it points to
   417 ** the address of the next instruction to be coded.
   418 */
   419 void sqlite3VdbeJumpHere(Vdbe *p, int addr){
   420   sqlite3VdbeChangeP2(p, addr, p->nOp);
   421 }
   422 
   423 
   424 /*
   425 ** If the input FuncDef structure is ephemeral, then free it.  If
   426 ** the FuncDef is not ephermal, then do nothing.
   427 */
   428 static void freeEphemeralFunction(FuncDef *pDef){
   429   if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
   430     sqlite3_free(pDef);
   431   }
   432 }
   433 
   434 /*
   435 ** Delete a P3 value if necessary.
   436 */
   437 static void freeP3(int p3type, void *p3){
   438   if( p3 ){
   439     switch( p3type ){
   440       case P3_DYNAMIC:
   441       case P3_KEYINFO:
   442       case P3_KEYINFO_HANDOFF: {
   443         sqlite3_free(p3);
   444         break;
   445       }
   446       case P3_MPRINTF: {
   447         sqlite3_free(p3);
   448         break;
   449       }
   450       case P3_VDBEFUNC: {
   451         VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
   452         freeEphemeralFunction(pVdbeFunc->pFunc);
   453         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
   454         sqlite3_free(pVdbeFunc);
   455         break;
   456       }
   457       case P3_FUNCDEF: {
   458         freeEphemeralFunction((FuncDef*)p3);
   459         break;
   460       }
   461       case P3_MEM: {
   462         sqlite3ValueFree((sqlite3_value*)p3);
   463         break;
   464       }
   465     }
   466   }
   467 }
   468 
   469 
   470 /*
   471 ** Change N opcodes starting at addr to No-ops.
   472 */
   473 void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
   474   if( p && p->aOp ){
   475     VdbeOp *pOp = &p->aOp[addr];
   476     while( N-- ){
   477       freeP3(pOp->p3type, pOp->p3);
   478       memset(pOp, 0, sizeof(pOp[0]));
   479       pOp->opcode = OP_Noop;
   480       pOp++;
   481     }
   482   }
   483 }
   484 
   485 /*
   486 ** Change the value of the P3 operand for a specific instruction.
   487 ** This routine is useful when a large program is loaded from a
   488 ** static array using sqlite3VdbeAddOpList but we want to make a
   489 ** few minor changes to the program.
   490 **
   491 ** If n>=0 then the P3 operand is dynamic, meaning that a copy of
   492 ** the string is made into memory obtained from sqlite3_malloc().
   493 ** A value of n==0 means copy bytes of zP3 up to and including the
   494 ** first null byte.  If n>0 then copy n+1 bytes of zP3.
   495 **
   496 ** If n==P3_KEYINFO it means that zP3 is a pointer to a KeyInfo structure.
   497 ** A copy is made of the KeyInfo structure into memory obtained from
   498 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
   499 ** n==P3_KEYINFO_HANDOFF indicates that zP3 points to a KeyInfo structure
   500 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
   501 ** caller should not free the allocation, it will be freed when the Vdbe is
   502 ** finalized.
   503 ** 
   504 ** Other values of n (P3_STATIC, P3_COLLSEQ etc.) indicate that zP3 points
   505 ** to a string or structure that is guaranteed to exist for the lifetime of
   506 ** the Vdbe. In these cases we can just copy the pointer.
   507 **
   508 ** If addr<0 then change P3 on the most recently inserted instruction.
   509 */
   510 void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
   511   Op *pOp;
   512   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
   513   if( p==0 || p->aOp==0 || p->db->mallocFailed ){
   514     if (n != P3_KEYINFO) {
   515       freeP3(n, (void*)*(char**)&zP3);
   516     }
   517     return;
   518   }
   519   if( addr<0 || addr>=p->nOp ){
   520     addr = p->nOp - 1;
   521     if( addr<0 ) return;
   522   }
   523   pOp = &p->aOp[addr];
   524   freeP3(pOp->p3type, pOp->p3);
   525   pOp->p3 = 0;
   526   if( zP3==0 ){
   527     pOp->p3 = 0;
   528     pOp->p3type = P3_NOTUSED;
   529   }else if( n==P3_KEYINFO ){
   530     KeyInfo *pKeyInfo;
   531     int nField, nByte;
   532 
   533     nField = ((KeyInfo*)zP3)->nField;
   534     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
   535     pKeyInfo = sqlite3_malloc( nByte );
   536     pOp->p3 = (char*)pKeyInfo;
   537     if( pKeyInfo ){
   538       unsigned char *aSortOrder;
   539       memcpy(pKeyInfo, zP3, nByte);
   540       aSortOrder = pKeyInfo->aSortOrder;
   541       if( aSortOrder ){
   542         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
   543         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
   544       }
   545       pOp->p3type = P3_KEYINFO;
   546     }else{
   547       p->db->mallocFailed = 1;
   548       pOp->p3type = P3_NOTUSED;
   549     }
   550   }else if( n==P3_KEYINFO_HANDOFF ){
   551     pOp->p3 = (char*)zP3;
   552     pOp->p3type = P3_KEYINFO;
   553   }else if( n<0 ){
   554     pOp->p3 = (char*)zP3;
   555     pOp->p3type = n;
   556   }else{
   557     if( n==0 ) n = strlen(zP3);
   558     pOp->p3 = sqlite3DbStrNDup(p->db, zP3, n);
   559     pOp->p3type = P3_DYNAMIC;
   560   }
   561 }
   562 
   563 #ifndef NDEBUG
   564 /*
   565 ** Replace the P3 field of the most recently coded instruction with
   566 ** comment text.
   567 */
   568 void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
   569   va_list ap;
   570   assert( p->nOp>0 || p->aOp==0 );
   571   assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0 || p->db->mallocFailed );
   572   va_start(ap, zFormat);
   573   sqlite3VdbeChangeP3(p, -1, sqlite3VMPrintf(p->db, zFormat, ap), P3_DYNAMIC);
   574   va_end(ap);
   575 }
   576 #endif
   577 
   578 /*
   579 ** Return the opcode for a given address.
   580 */
   581 VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
   582   assert( p->magic==VDBE_MAGIC_INIT );
   583   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
   584   return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
   585 }
   586 
   587 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
   588      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   589 /*
   590 ** Compute a string that describes the P3 parameter for an opcode.
   591 ** Use zTemp for any required temporary buffer space.
   592 */
   593 static char *displayP3(Op *pOp, char *zTemp, int nTemp){
   594   char *zP3;
   595   assert( nTemp>=20 );
   596   switch( pOp->p3type ){
   597     case P3_KEYINFO: {
   598       int i, j;
   599       KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3;
   600       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
   601       i = strlen(zTemp);
   602       for(j=0; j<pKeyInfo->nField; j++){
   603         CollSeq *pColl = pKeyInfo->aColl[j];
   604         if( pColl ){
   605           int n = strlen(pColl->zName);
   606           if( i+n>nTemp-6 ){
   607             memcpy(&zTemp[i],",...",4);
   608             break;
   609           }
   610           zTemp[i++] = ',';
   611           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
   612             zTemp[i++] = '-';
   613           }
   614           memcpy(&zTemp[i], pColl->zName,n+1);
   615           i += n;
   616         }else if( i+4<nTemp-6 ){
   617           memcpy(&zTemp[i],",nil",4);
   618           i += 4;
   619         }
   620       }
   621       zTemp[i++] = ')';
   622       zTemp[i] = 0;
   623       assert( i<nTemp );
   624       zP3 = zTemp;
   625       break;
   626     }
   627     case P3_COLLSEQ: {
   628       CollSeq *pColl = (CollSeq*)pOp->p3;
   629       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
   630       zP3 = zTemp;
   631       break;
   632     }
   633     case P3_FUNCDEF: {
   634       FuncDef *pDef = (FuncDef*)pOp->p3;
   635       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
   636       zP3 = zTemp;
   637       break;
   638     }
   639 #ifndef SQLITE_OMIT_VIRTUALTABLE
   640     case P3_VTAB: {
   641       sqlite3_vtab *pVtab = (sqlite3_vtab*)pOp->p3;
   642       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
   643       zP3 = zTemp;
   644       break;
   645     }
   646 #endif
   647     default: {
   648       zP3 = pOp->p3;
   649       if( zP3==0 || pOp->opcode==OP_Noop ){
   650         zP3 = "";
   651       }
   652     }
   653   }
   654   assert( zP3!=0 );
   655   return zP3;
   656 }
   657 #endif
   658 
   659 /*
   660 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
   661 **
   662 */
   663 void sqlite3VdbeUsesBtree(Vdbe *p, int i){
   664   int mask;
   665   assert( i>=0 && i<p->db->nDb );
   666   assert( i<sizeof(p->btreeMask)*8 );
   667   mask = 1<<i;
   668   if( (p->btreeMask & mask)==0 ){
   669     p->btreeMask |= mask;
   670     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
   671   }
   672 }
   673 
   674 
   675 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   676 /*
   677 ** Print a single opcode.  This routine is used for debugging only.
   678 */
   679 void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
   680   char *zP3;
   681   char zPtr[50];
   682   static const char *zFormat1 = "%4d %-13s %4d %4d %s\n";
   683   if( pOut==0 ) pOut = stdout;
   684   zP3 = displayP3(pOp, zPtr, sizeof(zPtr));
   685   fprintf(pOut, zFormat1,
   686       pc, sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, zP3);
   687   fflush(pOut);
   688 }
   689 #endif
   690 
   691 /*
   692 ** Release an array of N Mem elements
   693 */
   694 static void releaseMemArray(Mem *p, int N){
   695   if( p ){
   696     while( N-->0 ){
   697       assert( N<2 || p[0].db==p[1].db );
   698       sqlite3VdbeMemRelease(p++);
   699     }
   700   }
   701 }
   702 
   703 #ifndef SQLITE_OMIT_EXPLAIN
   704 /*
   705 ** Give a listing of the program in the virtual machine.
   706 **
   707 ** The interface is the same as sqlite3VdbeExec().  But instead of
   708 ** running the code, it invokes the callback once for each instruction.
   709 ** This feature is used to implement "EXPLAIN".
   710 */
   711 int sqlite3VdbeList(
   712   Vdbe *p                   /* The VDBE */
   713 ){
   714   sqlite3 *db = p->db;
   715   int i;
   716   int rc = SQLITE_OK;
   717 
   718   assert( p->explain );
   719   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
   720   assert( db->magic==SQLITE_MAGIC_BUSY );
   721   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
   722 
   723   /* Even though this opcode does not put dynamic strings onto the
   724   ** the stack, they may become dynamic if the user calls
   725   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
   726   */
   727   if( p->pTos==&p->aStack[4] ){
   728     releaseMemArray(p->aStack, 5);
   729   }
   730   p->resOnStack = 0;
   731 
   732   do{
   733     i = p->pc++;
   734   }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
   735   if( i>=p->nOp ){
   736     p->rc = SQLITE_OK;
   737     rc = SQLITE_DONE;
   738   }else if( db->u1.isInterrupted ){
   739     p->rc = SQLITE_INTERRUPT;
   740     rc = SQLITE_ERROR;
   741     sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
   742   }else{
   743     Op *pOp = &p->aOp[i];
   744     Mem *pMem = p->aStack;
   745     pMem->flags = MEM_Int;
   746     pMem->type = SQLITE_INTEGER;
   747     pMem->u.i = i;                                /* Program counter */
   748     pMem++;
   749 
   750     pMem->flags = MEM_Static|MEM_Str|MEM_Term;
   751     pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
   752     assert( pMem->z!=0 );
   753     pMem->n = strlen(pMem->z);
   754     pMem->type = SQLITE_TEXT;
   755     pMem->enc = SQLITE_UTF8;
   756     pMem++;
   757 
   758     pMem->flags = MEM_Int;
   759     pMem->u.i = pOp->p1;                          /* P1 */
   760     pMem->type = SQLITE_INTEGER;
   761     pMem++;
   762 
   763     pMem->flags = MEM_Int;
   764     pMem->u.i = pOp->p2;                          /* P2 */
   765     pMem->type = SQLITE_INTEGER;
   766     pMem++;
   767 
   768     pMem->flags = MEM_Ephem|MEM_Str|MEM_Term;   /* P3 */
   769     pMem->z = displayP3(pOp, pMem->zShort, sizeof(pMem->zShort));
   770     assert( pMem->z!=0 );
   771     pMem->n = strlen(pMem->z);
   772     pMem->type = SQLITE_TEXT;
   773     pMem->enc = SQLITE_UTF8;
   774 
   775     p->nResColumn = 5 - 2*(p->explain-1);
   776     p->pTos = pMem;
   777     p->rc = SQLITE_OK;
   778     p->resOnStack = 1;
   779     rc = SQLITE_ROW;
   780   }
   781   return rc;
   782 }
   783 #endif /* SQLITE_OMIT_EXPLAIN */
   784 
   785 #ifdef SQLITE_DEBUG
   786 /*
   787 ** Print the SQL that was used to generate a VDBE program.
   788 */
   789 void sqlite3VdbePrintSql(Vdbe *p){
   790   int nOp = p->nOp;
   791   VdbeOp *pOp;
   792   if( nOp<1 ) return;
   793   pOp = &p->aOp[nOp-1];
   794   if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
   795     const char *z = pOp->p3;
   796     while( isspace(*(u8*)z) ) z++;
   797     printf("SQL: [%s]\n", z);
   798   }
   799 }
   800 #endif
   801 
   802 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   803 /*
   804 ** Print an IOTRACE message showing SQL content.
   805 */
   806 void sqlite3VdbeIOTraceSql(Vdbe *p){
   807   int nOp = p->nOp;
   808   VdbeOp *pOp;
   809   if( sqlite3_io_trace==0 ) return;
   810   if( nOp<1 ) return;
   811   pOp = &p->aOp[nOp-1];
   812   if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
   813     int i, j;
   814     char z[1000];
   815     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p3);
   816     for(i=0; isspace((unsigned char)z[i]); i++){}
   817     for(j=0; z[i]; i++){
   818       if( isspace((unsigned char)z[i]) ){
   819         if( z[i-1]!=' ' ){
   820           z[j++] = ' ';
   821         }
   822       }else{
   823         z[j++] = z[i];
   824       }
   825     }
   826     z[j] = 0;
   827     sqlite3_io_trace("SQL %s\n", z);
   828   }
   829 }
   830 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
   831 
   832 
   833 /*
   834 ** Prepare a virtual machine for execution.  This involves things such
   835 ** as allocating stack space and initializing the program counter.
   836 ** After the VDBE has be prepped, it can be executed by one or more
   837 ** calls to sqlite3VdbeExec().  
   838 **
   839 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
   840 ** VDBE_MAGIC_RUN.
   841 */
   842 void sqlite3VdbeMakeReady(
   843   Vdbe *p,                       /* The VDBE */
   844   int nVar,                      /* Number of '?' see in the SQL statement */
   845   int nMem,                      /* Number of memory cells to allocate */
   846   int nCursor,                   /* Number of cursors to allocate */
   847   int isExplain                  /* True if the EXPLAIN keywords is present */
   848 ){
   849   int n;
   850   sqlite3 *db = p->db;
   851 
   852   assert( p!=0 );
   853   assert( p->magic==VDBE_MAGIC_INIT );
   854 
   855   /* There should be at least one opcode.
   856   */
   857   assert( p->nOp>0 );
   858 
   859   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
   860    * is because the call to resizeOpArray() below may shrink the
   861    * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN 
   862    * state.
   863    */
   864   p->magic = VDBE_MAGIC_RUN;
   865 
   866   /* No instruction ever pushes more than a single element onto the
   867   ** stack.  And the stack never grows on successive executions of the
   868   ** same loop.  So the total number of instructions is an upper bound
   869   ** on the maximum stack depth required.  (Added later:)  The
   870   ** resolveP2Values() call computes a tighter upper bound on the
   871   ** stack size.
   872   **
   873   ** Allocation all the stack space we will ever need.
   874   */
   875   if( p->aStack==0 ){
   876     int nArg;       /* Maximum number of args passed to a user function. */
   877     int nStack;     /* Maximum number of stack entries required */
   878     resolveP2Values(p, &nArg, &nStack);
   879     resizeOpArray(p, p->nOp);
   880     assert( nVar>=0 );
   881     assert( nStack<p->nOp );
   882     if( isExplain ){
   883       nStack = 10;
   884     }
   885     p->aStack = sqlite3DbMallocZero(db,
   886         nStack*sizeof(p->aStack[0])    /* aStack */
   887       + nArg*sizeof(Mem*)              /* apArg */
   888       + nVar*sizeof(Mem)               /* aVar */
   889       + nVar*sizeof(char*)             /* azVar */
   890       + nMem*sizeof(Mem)               /* aMem */
   891       + nCursor*sizeof(Cursor*)        /* apCsr */
   892     );
   893     if( !db->mallocFailed ){
   894       p->aMem = &p->aStack[nStack];
   895       p->nMem = nMem;
   896       p->aVar = &p->aMem[nMem];
   897       p->nVar = nVar;
   898       p->okVar = 0;
   899       p->apArg = (Mem**)&p->aVar[nVar];
   900       p->azVar = (char**)&p->apArg[nArg];
   901       p->apCsr = (Cursor**)&p->azVar[nVar];
   902       p->nCursor = nCursor;
   903       for(n=0; n<nVar; n++){
   904         p->aVar[n].flags = MEM_Null;
   905         p->aVar[n].db = db;
   906       }
   907       for(n=0; n<nStack; n++){
   908         p->aStack[n].db = db;
   909       }
   910     }
   911   }
   912   for(n=0; n<p->nMem; n++){
   913     p->aMem[n].flags = MEM_Null;
   914     p->aMem[n].db = db;
   915   }
   916 
   917   p->pTos = &p->aStack[-1];
   918   p->pc = -1;
   919   p->rc = SQLITE_OK;
   920   p->uniqueCnt = 0;
   921   p->returnDepth = 0;
   922   p->errorAction = OE_Abort;
   923   p->popStack =  0;
   924   p->explain |= isExplain;
   925   p->magic = VDBE_MAGIC_RUN;
   926   p->nChange = 0;
   927   p->cacheCtr = 1;
   928   p->minWriteFileFormat = 255;
   929   p->openedStatement = 0;
   930 #ifdef VDBE_PROFILE
   931   {
   932     int i;
   933     for(i=0; i<p->nOp; i++){
   934       p->aOp[i].cnt = 0;
   935       p->aOp[i].cycles = 0;
   936     }
   937   }
   938 #endif
   939 }
   940 
   941 /*
   942 ** Close a VDBE cursor and release all the resources that cursor happens
   943 ** to hold.
   944 */
   945 void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
   946   if( pCx==0 ){
   947     return;
   948   }
   949   if( pCx->pCursor ){
   950     sqlite3BtreeCloseCursor(pCx->pCursor);
   951   }
   952   if( pCx->pBt ){
   953     sqlite3BtreeClose(pCx->pBt);
   954   }
   955 #ifndef SQLITE_OMIT_VIRTUALTABLE
   956   if( pCx->pVtabCursor ){
   957     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
   958     const sqlite3_module *pModule = pCx->pModule;
   959     p->inVtabMethod = 1;
   960     sqlite3SafetyOff(p->db);
   961     pModule->xClose(pVtabCursor);
   962     sqlite3SafetyOn(p->db);
   963     p->inVtabMethod = 0;
   964   }
   965 #endif
   966   sqlite3_free(pCx->pData);
   967   sqlite3_free(pCx->aType);
   968   sqlite3_free(pCx);
   969 }
   970 
   971 /*
   972 ** Close all cursors except for VTab cursors that are currently
   973 ** in use.
   974 */
   975 static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
   976   int i;
   977   if( p->apCsr==0 ) return;
   978   for(i=0; i<p->nCursor; i++){
   979     Cursor *pC = p->apCsr[i];
   980     if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
   981       sqlite3VdbeFreeCursor(p, pC);
   982       p->apCsr[i] = 0;
   983     }
   984   }
   985 }
   986 
   987 /*
   988 ** Clean up the VM after execution.
   989 **
   990 ** This routine will automatically close any cursors, lists, and/or
   991 ** sorters that were left open.  It also deletes the values of
   992 ** variables in the aVar[] array.
   993 */
   994 static void Cleanup(Vdbe *p){
   995   int i;
   996   if( p->aStack ){
   997     releaseMemArray(p->aStack, 1 + (p->pTos - p->aStack));
   998     p->pTos = &p->aStack[-1];
   999   }
  1000   closeAllCursorsExceptActiveVtabs(p);
  1001   releaseMemArray(p->aMem, p->nMem);
  1002   sqlite3VdbeFifoClear(&p->sFifo);
  1003   if( p->contextStack ){
  1004     for(i=0; i<p->contextStackTop; i++){
  1005       sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
  1006     }
  1007     sqlite3_free(p->contextStack);
  1008   }
  1009   p->contextStack = 0;
  1010   p->contextStackDepth = 0;
  1011   p->contextStackTop = 0;
  1012   sqlite3_free(p->zErrMsg);
  1013   p->zErrMsg = 0;
  1014   p->resOnStack = 0;
  1015 }
  1016 
  1017 /*
  1018 ** Set the number of result columns that will be returned by this SQL
  1019 ** statement. This is now set at compile time, rather than during
  1020 ** execution of the vdbe program so that sqlite3_column_count() can
  1021 ** be called on an SQL statement before sqlite3_step().
  1022 */
  1023 void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  1024   Mem *pColName;
  1025   int n;
  1026 
  1027   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  1028   sqlite3_free(p->aColName);
  1029   n = nResColumn*COLNAME_N;
  1030   p->nResColumn = nResColumn;
  1031   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(p->db, sizeof(Mem)*n );
  1032   if( p->aColName==0 ) return;
  1033   while( n-- > 0 ){
  1034     pColName->flags = MEM_Null;
  1035     pColName->db = p->db;
  1036     pColName++;
  1037   }
  1038 }
  1039 
  1040 /*
  1041 ** Set the name of the idx'th column to be returned by the SQL statement.
  1042 ** zName must be a pointer to a nul terminated string.
  1043 **
  1044 ** This call must be made after a call to sqlite3VdbeSetNumCols().
  1045 **
  1046 ** If N==P3_STATIC  it means that zName is a pointer to a constant static
  1047 ** string and we can just copy the pointer. If it is P3_DYNAMIC, then 
  1048 ** the string is freed using sqlite3_free() when the vdbe is finished with
  1049 ** it. Otherwise, N bytes of zName are copied.
  1050 */
  1051 int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
  1052   int rc;
  1053   Mem *pColName;
  1054   assert( idx<p->nResColumn );
  1055   assert( var<COLNAME_N );
  1056   if( p->db->mallocFailed ) return SQLITE_NOMEM;
  1057   assert( p->aColName!=0 );
  1058   pColName = &(p->aColName[idx+var*p->nResColumn]);
  1059   if( N==P3_DYNAMIC || N==P3_STATIC ){
  1060     rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
  1061   }else{
  1062     rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
  1063   }
  1064   if( rc==SQLITE_OK && N==P3_DYNAMIC ){
  1065     pColName->flags = (pColName->flags&(~MEM_Static))|MEM_Dyn;
  1066     pColName->xDel = 0;
  1067   }
  1068   return rc;
  1069 }
  1070 
  1071 /*
  1072 ** A read or write transaction may or may not be active on database handle
  1073 ** db. If a transaction is active, commit it. If there is a
  1074 ** write-transaction spanning more than one database file, this routine
  1075 ** takes care of the master journal trickery.
  1076 */
  1077 static int vdbeCommit(sqlite3 *db){
  1078   int i;
  1079   int nTrans = 0;  /* Number of databases with an active write-transaction */
  1080   int rc = SQLITE_OK;
  1081   int needXcommit = 0;
  1082 
  1083   /* Before doing anything else, call the xSync() callback for any
  1084   ** virtual module tables written in this transaction. This has to
  1085   ** be done before determining whether a master journal file is 
  1086   ** required, as an xSync() callback may add an attached database
  1087   ** to the transaction.
  1088   */
  1089   rc = sqlite3VtabSync(db, rc);
  1090   if( rc!=SQLITE_OK ){
  1091     return rc;
  1092   }
  1093 
  1094   /* This loop determines (a) if the commit hook should be invoked and
  1095   ** (b) how many database files have open write transactions, not 
  1096   ** including the temp database. (b) is important because if more than 
  1097   ** one database file has an open write transaction, a master journal
  1098   ** file is required for an atomic commit.
  1099   */ 
  1100   for(i=0; i<db->nDb; i++){ 
  1101     Btree *pBt = db->aDb[i].pBt;
  1102     if( sqlite3BtreeIsInTrans(pBt) ){
  1103       needXcommit = 1;
  1104       if( i!=1 ) nTrans++;
  1105     }
  1106   }
  1107 
  1108   /* If there are any write-transactions at all, invoke the commit hook */
  1109   if( needXcommit && db->xCommitCallback ){
  1110     sqlite3SafetyOff(db);
  1111     rc = db->xCommitCallback(db->pCommitArg);
  1112     sqlite3SafetyOn(db);
  1113     if( rc ){
  1114       return SQLITE_CONSTRAINT;
  1115     }
  1116   }
  1117 
  1118   /* The simple case - no more than one database file (not counting the
  1119   ** TEMP database) has a transaction active.   There is no need for the
  1120   ** master-journal.
  1121   **
  1122   ** If the return value of sqlite3BtreeGetFilename() is a zero length
  1123   ** string, it means the main database is :memory:.  In that case we do
  1124   ** not support atomic multi-file commits, so use the simple case then
  1125   ** too.
  1126   */
  1127   if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
  1128     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
  1129       Btree *pBt = db->aDb[i].pBt;
  1130       if( pBt ){
  1131         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  1132       }
  1133     }
  1134 
  1135     /* Do the commit only if all databases successfully complete phase 1. 
  1136     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  1137     ** IO error while deleting or truncating a journal file. It is unlikely,
  1138     ** but could happen. In this case abandon processing and return the error.
  1139     */
  1140     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  1141       Btree *pBt = db->aDb[i].pBt;
  1142       if( pBt ){
  1143         rc = sqlite3BtreeCommitPhaseTwo(pBt);
  1144       }
  1145     }
  1146     if( rc==SQLITE_OK ){
  1147       sqlite3VtabCommit(db);
  1148     }
  1149   }
  1150 
  1151   /* The complex case - There is a multi-file write-transaction active.
  1152   ** This requires a master journal file to ensure the transaction is
  1153   ** committed atomicly.
  1154   */
  1155 #ifndef SQLITE_OMIT_DISKIO
  1156   else{
  1157     sqlite3_vfs *pVfs = db->pVfs;
  1158     int needSync = 0;
  1159     char *zMaster = 0;   /* File-name for the master journal */
  1160     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  1161     sqlite3_file *pMaster = 0;
  1162     i64 offset = 0;
  1163 
  1164     /* Select a master journal file name */
  1165     do {
  1166       u32 random;
  1167       sqlite3_free(zMaster);
  1168       sqlite3Randomness(sizeof(random), &random);
  1169       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, random&0x7fffffff);
  1170       if( !zMaster ){
  1171         return SQLITE_NOMEM;
  1172       }
  1173     }while( sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS) );
  1174 
  1175     /* Open the master journal. */
  1176     rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
  1177         SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  1178         SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  1179     );
  1180     if( rc!=SQLITE_OK ){
  1181       sqlite3_free(zMaster);
  1182       return rc;
  1183     }
  1184  
  1185     /* Write the name of each database file in the transaction into the new
  1186     ** master journal file. If an error occurs at this point close
  1187     ** and delete the master journal file. All the individual journal files
  1188     ** still have 'null' as the master journal pointer, so they will roll
  1189     ** back independently if a failure occurs.
  1190     */
  1191     for(i=0; i<db->nDb; i++){
  1192       Btree *pBt = db->aDb[i].pBt;
  1193       if( i==1 ) continue;   /* Ignore the TEMP database */
  1194       if( sqlite3BtreeIsInTrans(pBt) ){
  1195         char const *zFile = sqlite3BtreeGetJournalname(pBt);
  1196         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
  1197         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  1198           needSync = 1;
  1199         }
  1200         rc = sqlite3OsWrite(pMaster, zFile, strlen(zFile)+1, offset);
  1201         offset += strlen(zFile)+1;
  1202         if( rc!=SQLITE_OK ){
  1203           sqlite3OsCloseFree(pMaster);
  1204           sqlite3OsDelete(pVfs, zMaster, 0);
  1205           sqlite3_free(zMaster);
  1206           return rc;
  1207         }
  1208       }
  1209     }
  1210 
  1211     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  1212     ** flag is set this is not required.
  1213     */
  1214     zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
  1215     if( (needSync 
  1216      && (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
  1217      && (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){
  1218       sqlite3OsCloseFree(pMaster);
  1219       sqlite3OsDelete(pVfs, zMaster, 0);
  1220       sqlite3_free(zMaster);
  1221       return rc;
  1222     }
  1223 
  1224     /* Sync all the db files involved in the transaction. The same call
  1225     ** sets the master journal pointer in each individual journal. If
  1226     ** an error occurs here, do not delete the master journal file.
  1227     **
  1228     ** If the error occurs during the first call to
  1229     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  1230     ** master journal file will be orphaned. But we cannot delete it,
  1231     ** in case the master journal file name was written into the journal
  1232     ** file before the failure occured.
  1233     */
  1234     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
  1235       Btree *pBt = db->aDb[i].pBt;
  1236       if( pBt ){
  1237         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  1238       }
  1239     }
  1240     sqlite3OsCloseFree(pMaster);
  1241     if( rc!=SQLITE_OK ){
  1242       sqlite3_free(zMaster);
  1243       return rc;
  1244     }
  1245 
  1246     /* Delete the master journal file. This commits the transaction. After
  1247     ** doing this the directory is synced again before any individual
  1248     ** transaction files are deleted.
  1249     */
  1250     rc = sqlite3OsDelete(pVfs, zMaster, 1);
  1251     sqlite3_free(zMaster);
  1252     zMaster = 0;
  1253     if( rc ){
  1254       return rc;
  1255     }
  1256 
  1257     /* All files and directories have already been synced, so the following
  1258     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  1259     ** deleting or truncating journals. If something goes wrong while
  1260     ** this is happening we don't really care. The integrity of the
  1261     ** transaction is already guaranteed, but some stray 'cold' journals
  1262     ** may be lying around. Returning an error code won't help matters.
  1263     */
  1264     disable_simulated_io_errors();
  1265     for(i=0; i<db->nDb; i++){ 
  1266       Btree *pBt = db->aDb[i].pBt;
  1267       if( pBt ){
  1268         sqlite3BtreeCommitPhaseTwo(pBt);
  1269       }
  1270     }
  1271     enable_simulated_io_errors();
  1272 
  1273     sqlite3VtabCommit(db);
  1274   }
  1275 #endif
  1276 
  1277   return rc;
  1278 }
  1279 
  1280 /* 
  1281 ** This routine checks that the sqlite3.activeVdbeCnt count variable
  1282 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  1283 ** currently active. An assertion fails if the two counts do not match.
  1284 ** This is an internal self-check only - it is not an essential processing
  1285 ** step.
  1286 **
  1287 ** This is a no-op if NDEBUG is defined.
  1288 */
  1289 #ifndef NDEBUG
  1290 static void checkActiveVdbeCnt(sqlite3 *db){
  1291   Vdbe *p;
  1292   int cnt = 0;
  1293   p = db->pVdbe;
  1294   while( p ){
  1295     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
  1296       cnt++;
  1297     }
  1298     p = p->pNext;
  1299   }
  1300   assert( cnt==db->activeVdbeCnt );
  1301 }
  1302 #else
  1303 #define checkActiveVdbeCnt(x)
  1304 #endif
  1305 
  1306 /*
  1307 ** For every Btree that in database connection db which 
  1308 ** has been modified, "trip" or invalidate each cursor in
  1309 ** that Btree might have been modified so that the cursor
  1310 ** can never be used again.  This happens when a rollback
  1311 *** occurs.  We have to trip all the other cursors, even
  1312 ** cursor from other VMs in different database connections,
  1313 ** so that none of them try to use the data at which they
  1314 ** were pointing and which now may have been changed due
  1315 ** to the rollback.
  1316 **
  1317 ** Remember that a rollback can delete tables complete and
  1318 ** reorder rootpages.  So it is not sufficient just to save
  1319 ** the state of the cursor.  We have to invalidate the cursor
  1320 ** so that it is never used again.
  1321 */
  1322 void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
  1323   int i;
  1324   for(i=0; i<db->nDb; i++){
  1325     Btree *p = db->aDb[i].pBt;
  1326     if( p && sqlite3BtreeIsInTrans(p) ){
  1327       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
  1328     }
  1329   }
  1330 }
  1331 
  1332 /*
  1333 ** This routine is called the when a VDBE tries to halt.  If the VDBE
  1334 ** has made changes and is in autocommit mode, then commit those
  1335 ** changes.  If a rollback is needed, then do the rollback.
  1336 **
  1337 ** This routine is the only way to move the state of a VM from
  1338 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
  1339 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  1340 **
  1341 ** Return an error code.  If the commit could not complete because of
  1342 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
  1343 ** means the close did not happen and needs to be repeated.
  1344 */
  1345 int sqlite3VdbeHalt(Vdbe *p){
  1346   sqlite3 *db = p->db;
  1347   int i;
  1348   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
  1349   int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */
  1350 
  1351   /* This function contains the logic that determines if a statement or
  1352   ** transaction will be committed or rolled back as a result of the
  1353   ** execution of this virtual machine. 
  1354   **
  1355   ** If any of the following errors occur:
  1356   **
  1357   **     SQLITE_NOMEM
  1358   **     SQLITE_IOERR
  1359   **     SQLITE_FULL
  1360   **     SQLITE_INTERRUPT
  1361   **
  1362   ** Then the internal cache might have been left in an inconsistent
  1363   ** state.  We need to rollback the statement transaction, if there is
  1364   ** one, or the complete transaction if there is no statement transaction.
  1365   */
  1366 
  1367   if( p->db->mallocFailed ){
  1368     p->rc = SQLITE_NOMEM;
  1369   }
  1370   closeAllCursorsExceptActiveVtabs(p);
  1371   if( p->magic!=VDBE_MAGIC_RUN ){
  1372     return SQLITE_OK;
  1373   }
  1374   checkActiveVdbeCnt(db);
  1375 
  1376   /* No commit or rollback needed if the program never started */
  1377   if( p->pc>=0 ){
  1378     int mrc;   /* Primary error code from p->rc */
  1379 
  1380     /* Lock all btrees used by the statement */
  1381     sqlite3BtreeMutexArrayEnter(&p->aMutex);
  1382 
  1383     /* Check for one of the special errors */
  1384     mrc = p->rc & 0xff;
  1385     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  1386                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL ;
  1387     if( isSpecialError ){
  1388       /* This loop does static analysis of the query to see which of the
  1389       ** following three categories it falls into:
  1390       **
  1391       **     Read-only
  1392       **     Query with statement journal
  1393       **     Query without statement journal
  1394       **
  1395       ** We could do something more elegant than this static analysis (i.e.
  1396       ** store the type of query as part of the compliation phase), but 
  1397       ** handling malloc() or IO failure is a fairly obscure edge case so 
  1398       ** this is probably easier. Todo: Might be an opportunity to reduce 
  1399       ** code size a very small amount though...
  1400       */
  1401       int notReadOnly = 0;
  1402       int isStatement = 0;
  1403       assert(p->aOp || p->nOp==0);
  1404       for(i=0; i<p->nOp; i++){ 
  1405         switch( p->aOp[i].opcode ){
  1406           case OP_Transaction:
  1407             notReadOnly |= p->aOp[i].p2;
  1408             break;
  1409           case OP_Statement:
  1410             isStatement = 1;
  1411             break;
  1412         }
  1413       }
  1414 
  1415    
  1416       /* If the query was read-only, we need do no rollback at all. Otherwise,
  1417       ** proceed with the special handling.
  1418       */
  1419       if( notReadOnly || mrc!=SQLITE_INTERRUPT ){
  1420         if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
  1421           xFunc = sqlite3BtreeRollbackStmt;
  1422           p->rc = SQLITE_BUSY;
  1423         } else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && isStatement ){
  1424           xFunc = sqlite3BtreeRollbackStmt;
  1425         }else{
  1426           /* We are forced to roll back the active transaction. Before doing
  1427           ** so, abort any other statements this handle currently has active.
  1428           */
  1429           invalidateCursorsOnModifiedBtrees(db);
  1430           sqlite3RollbackAll(db);
  1431           db->autoCommit = 1;
  1432         }
  1433       }
  1434     }
  1435   
  1436     /* If the auto-commit flag is set and this is the only active vdbe, then
  1437     ** we do either a commit or rollback of the current transaction. 
  1438     **
  1439     ** Note: This block also runs if one of the special errors handled 
  1440     ** above has occured. 
  1441     */
  1442     if( db->autoCommit && db->activeVdbeCnt==1 ){
  1443       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  1444         /* The auto-commit flag is true, and the vdbe program was 
  1445         ** successful or hit an 'OR FAIL' constraint. This means a commit 
  1446         ** is required.
  1447         */
  1448         int rc = vdbeCommit(db);
  1449         if( rc==SQLITE_BUSY ){
  1450           sqlite3BtreeMutexArrayLeave(&p->aMutex);
  1451           return SQLITE_BUSY;
  1452         }else if( rc!=SQLITE_OK ){
  1453           p->rc = rc;
  1454           sqlite3RollbackAll(db);
  1455         }else{
  1456           sqlite3CommitInternalChanges(db);
  1457         }
  1458       }else{
  1459         sqlite3RollbackAll(db);
  1460       }
  1461     }else if( !xFunc ){
  1462       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  1463         if( p->openedStatement ){
  1464           xFunc = sqlite3BtreeCommitStmt;
  1465         } 
  1466       }else if( p->errorAction==OE_Abort ){
  1467         xFunc = sqlite3BtreeRollbackStmt;
  1468       }else{
  1469         invalidateCursorsOnModifiedBtrees(db);
  1470         sqlite3RollbackAll(db);
  1471         db->autoCommit = 1;
  1472       }
  1473     }
  1474   
  1475     /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
  1476     ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
  1477     ** and the return code is still SQLITE_OK, set the return code to the new
  1478     ** error value.
  1479     */
  1480     assert(!xFunc ||
  1481       xFunc==sqlite3BtreeCommitStmt ||
  1482       xFunc==sqlite3BtreeRollbackStmt
  1483     );
  1484     for(i=0; xFunc && i<db->nDb; i++){ 
  1485       int rc;
  1486       Btree *pBt = db->aDb[i].pBt;
  1487       if( pBt ){
  1488         rc = xFunc(pBt);
  1489         if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
  1490           p->rc = rc;
  1491           sqlite3SetString(&p->zErrMsg, 0);
  1492         }
  1493       }
  1494     }
  1495   
  1496     /* If this was an INSERT, UPDATE or DELETE and the statement was committed, 
  1497     ** set the change counter. 
  1498     */
  1499     if( p->changeCntOn && p->pc>=0 ){
  1500       if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
  1501         sqlite3VdbeSetChanges(db, p->nChange);
  1502       }else{
  1503         sqlite3VdbeSetChanges(db, 0);
  1504       }
  1505       p->nChange = 0;
  1506     }
  1507   
  1508     /* Rollback or commit any schema changes that occurred. */
  1509     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
  1510       sqlite3ResetInternalSchema(db, 0);
  1511       db->flags = (db->flags | SQLITE_InternChanges);
  1512     }
  1513 
  1514     /* Release the locks */
  1515     sqlite3BtreeMutexArrayLeave(&p->aMutex);
  1516   }
  1517 
  1518   /* We have successfully halted and closed the VM.  Record this fact. */
  1519   if( p->pc>=0 ){
  1520     db->activeVdbeCnt--;
  1521   }
  1522   p->magic = VDBE_MAGIC_HALT;
  1523   checkActiveVdbeCnt(db);
  1524   if( p->db->mallocFailed ){
  1525     p->rc = SQLITE_NOMEM;
  1526   }
  1527   checkActiveVdbeCnt(db);
  1528 
  1529   return SQLITE_OK;
  1530 }
  1531 
  1532 
  1533 /*
  1534 ** Each VDBE holds the result of the most recent sqlite3_step() call
  1535 ** in p->rc.  This routine sets that result back to SQLITE_OK.
  1536 */
  1537 void sqlite3VdbeResetStepResult(Vdbe *p){
  1538   p->rc = SQLITE_OK;
  1539 }
  1540 
  1541 /*
  1542 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  1543 ** Write any error messages into *pzErrMsg.  Return the result code.
  1544 **
  1545 ** After this routine is run, the VDBE should be ready to be executed
  1546 ** again.
  1547 **
  1548 ** To look at it another way, this routine resets the state of the
  1549 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  1550 ** VDBE_MAGIC_INIT.
  1551 */
  1552 int sqlite3VdbeReset(Vdbe *p){
  1553   sqlite3 *db;
  1554   db = p->db;
  1555 
  1556   /* If the VM did not run to completion or if it encountered an
  1557   ** error, then it might not have been halted properly.  So halt
  1558   ** it now.
  1559   */
  1560   sqlite3SafetyOn(db);
  1561   sqlite3VdbeHalt(p);
  1562   sqlite3SafetyOff(db);
  1563 
  1564   /* If the VDBE has be run even partially, then transfer the error code
  1565   ** and error message from the VDBE into the main database structure.  But
  1566   ** if the VDBE has just been set to run but has not actually executed any
  1567   ** instructions yet, leave the main database error information unchanged.
  1568   */
  1569   if( p->pc>=0 ){
  1570     if( p->zErrMsg ){
  1571       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,sqlite3_free);
  1572       db->errCode = p->rc;
  1573       p->zErrMsg = 0;
  1574     }else if( p->rc ){
  1575       sqlite3Error(db, p->rc, 0);
  1576     }else{
  1577       sqlite3Error(db, SQLITE_OK, 0);
  1578     }
  1579   }else if( p->rc && p->expired ){
  1580     /* The expired flag was set on the VDBE before the first call
  1581     ** to sqlite3_step(). For consistency (since sqlite3_step() was
  1582     ** called), set the database error in this case as well.
  1583     */
  1584     sqlite3Error(db, p->rc, 0);
  1585   }
  1586 
  1587   /* Reclaim all memory used by the VDBE
  1588   */
  1589   Cleanup(p);
  1590 
  1591   /* Save profiling information from this VDBE run.
  1592   */
  1593   assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || !p->aStack );
  1594 #ifdef VDBE_PROFILE
  1595   {
  1596     FILE *out = fopen("vdbe_profile.out", "a");
  1597     if( out ){
  1598       int i;
  1599       fprintf(out, "---- ");
  1600       for(i=0; i<p->nOp; i++){
  1601         fprintf(out, "%02x", p->aOp[i].opcode);
  1602       }
  1603       fprintf(out, "\n");
  1604       for(i=0; i<p->nOp; i++){
  1605         fprintf(out, "%6d %10lld %8lld ",
  1606            p->aOp[i].cnt,
  1607            p->aOp[i].cycles,
  1608            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  1609         );
  1610         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  1611       }
  1612       fclose(out);
  1613     }
  1614   }
  1615 #endif
  1616   p->magic = VDBE_MAGIC_INIT;
  1617   p->aborted = 0;
  1618   return p->rc & db->errMask;
  1619 }
  1620  
  1621 /*
  1622 ** Clean up and delete a VDBE after execution.  Return an integer which is
  1623 ** the result code.  Write any error message text into *pzErrMsg.
  1624 */
  1625 int sqlite3VdbeFinalize(Vdbe *p){
  1626   int rc = SQLITE_OK;
  1627   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  1628     rc = sqlite3VdbeReset(p);
  1629     assert( (rc & p->db->errMask)==rc );
  1630   }else if( p->magic!=VDBE_MAGIC_INIT ){
  1631     return SQLITE_MISUSE;
  1632   }
  1633   sqlite3VdbeDelete(p);
  1634   return rc;
  1635 }
  1636 
  1637 /*
  1638 ** Call the destructor for each auxdata entry in pVdbeFunc for which
  1639 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
  1640 ** are always destroyed.  To destroy all auxdata entries, call this
  1641 ** routine with mask==0.
  1642 */
  1643 void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
  1644   int i;
  1645   for(i=0; i<pVdbeFunc->nAux; i++){
  1646     struct AuxData *pAux = &pVdbeFunc->apAux[i];
  1647     if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
  1648       if( pAux->xDelete ){
  1649         pAux->xDelete(pAux->pAux);
  1650       }
  1651       pAux->pAux = 0;
  1652     }
  1653   }
  1654 }
  1655 
  1656 /*
  1657 ** Delete an entire VDBE.
  1658 */
  1659 void sqlite3VdbeDelete(Vdbe *p){
  1660   int i;
  1661   if( p==0 ) return;
  1662   Cleanup(p);
  1663   if( p->pPrev ){
  1664     p->pPrev->pNext = p->pNext;
  1665   }else{
  1666     assert( p->db->pVdbe==p );
  1667     p->db->pVdbe = p->pNext;
  1668   }
  1669   if( p->pNext ){
  1670     p->pNext->pPrev = p->pPrev;
  1671   }
  1672   if( p->aOp ){
  1673     for(i=0; i<p->nOp; i++){
  1674       Op *pOp = &p->aOp[i];
  1675       freeP3(pOp->p3type, pOp->p3);
  1676     }
  1677     sqlite3_free(p->aOp);
  1678   }
  1679   releaseMemArray(p->aVar, p->nVar);
  1680   sqlite3_free(p->aLabel);
  1681   sqlite3_free(p->aStack);
  1682   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  1683   sqlite3_free(p->aColName);
  1684   sqlite3_free(p->zSql);
  1685   p->magic = VDBE_MAGIC_DEAD;
  1686   sqlite3_free(p);
  1687 }
  1688 
  1689 /*
  1690 ** If a MoveTo operation is pending on the given cursor, then do that
  1691 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
  1692 ** routine does nothing and returns SQLITE_OK.
  1693 */
  1694 int sqlite3VdbeCursorMoveto(Cursor *p){
  1695   if( p->deferredMoveto ){
  1696     int res, rc;
  1697 #ifdef SQLITE_TEST
  1698     extern int sqlite3_search_count;
  1699 #endif
  1700     assert( p->isTable );
  1701     rc = sqlite3BtreeMoveto(p->pCursor, 0, p->movetoTarget, 0, &res);
  1702     if( rc ) return rc;
  1703     *p->pIncrKey = 0;
  1704     p->lastRowid = keyToInt(p->movetoTarget);
  1705     p->rowidIsValid = res==0;
  1706     if( res<0 ){
  1707       rc = sqlite3BtreeNext(p->pCursor, &res);
  1708       if( rc ) return rc;
  1709     }
  1710 #ifdef SQLITE_TEST
  1711     sqlite3_search_count++;
  1712 #endif
  1713     p->deferredMoveto = 0;
  1714     p->cacheStatus = CACHE_STALE;
  1715   }
  1716   return SQLITE_OK;
  1717 }
  1718 
  1719 /*
  1720 ** The following functions:
  1721 **
  1722 ** sqlite3VdbeSerialType()
  1723 ** sqlite3VdbeSerialTypeLen()
  1724 ** sqlite3VdbeSerialRead()
  1725 ** sqlite3VdbeSerialLen()
  1726 ** sqlite3VdbeSerialWrite()
  1727 **
  1728 ** encapsulate the code that serializes values for storage in SQLite
  1729 ** data and index records. Each serialized value consists of a
  1730 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  1731 ** integer, stored as a varint.
  1732 **
  1733 ** In an SQLite index record, the serial type is stored directly before
  1734 ** the blob of data that it corresponds to. In a table record, all serial
  1735 ** types are stored at the start of the record, and the blobs of data at
  1736 ** the end. Hence these functions allow the caller to handle the
  1737 ** serial-type and data blob seperately.
  1738 **
  1739 ** The following table describes the various storage classes for data:
  1740 **
  1741 **   serial type        bytes of data      type
  1742 **   --------------     ---------------    ---------------
  1743 **      0                     0            NULL
  1744 **      1                     1            signed integer
  1745 **      2                     2            signed integer
  1746 **      3                     3            signed integer
  1747 **      4                     4            signed integer
  1748 **      5                     6            signed integer
  1749 **      6                     8            signed integer
  1750 **      7                     8            IEEE float
  1751 **      8                     0            Integer constant 0
  1752 **      9                     0            Integer constant 1
  1753 **     10,11                               reserved for expansion
  1754 **    N>=12 and even       (N-12)/2        BLOB
  1755 **    N>=13 and odd        (N-13)/2        text
  1756 **
  1757 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
  1758 ** of SQLite will not understand those serial types.
  1759 */
  1760 
  1761 /*
  1762 ** Return the serial-type for the value stored in pMem.
  1763 */
  1764 u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  1765   int flags = pMem->flags;
  1766   int n;
  1767 
  1768   if( flags&MEM_Null ){
  1769     return 0;
  1770   }
  1771   if( flags&MEM_Int ){
  1772     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  1773 #   define MAX_6BYTE ((((i64)0x00001000)<<32)-1)
  1774     i64 i = pMem->u.i;
  1775     u64 u;
  1776     if( file_format>=4 && (i&1)==i ){
  1777       return 8+i;
  1778     }
  1779     u = i<0 ? -i : i;
  1780     if( u<=127 ) return 1;
  1781     if( u<=32767 ) return 2;
  1782     if( u<=8388607 ) return 3;
  1783     if( u<=2147483647 ) return 4;
  1784     if( u<=MAX_6BYTE ) return 5;
  1785     return 6;
  1786   }
  1787   if( flags&MEM_Real ){
  1788     return 7;
  1789   }
  1790   assert( flags&(MEM_Str|MEM_Blob) );
  1791   n = pMem->n;
  1792   if( flags & MEM_Zero ){
  1793     n += pMem->u.i;
  1794   }
  1795   assert( n>=0 );
  1796   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  1797 }
  1798 
  1799 /*
  1800 ** Return the length of the data corresponding to the supplied serial-type.
  1801 */
  1802 int sqlite3VdbeSerialTypeLen(u32 serial_type){
  1803   if( serial_type>=12 ){
  1804     return (serial_type-12)/2;
  1805   }else{
  1806     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  1807     return aSize[serial_type];
  1808   }
  1809 }
  1810 
  1811 /*
  1812 ** If we are on an architecture with mixed-endian floating 
  1813 ** points (ex: ARM7) then swap the lower 4 bytes with the 
  1814 ** upper 4 bytes.  Return the result.
  1815 **
  1816 ** For most architectures, this is a no-op.
  1817 **
  1818 ** (later):  It is reported to me that the mixed-endian problem
  1819 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
  1820 ** that early versions of GCC stored the two words of a 64-bit
  1821 ** float in the wrong order.  And that error has been propagated
  1822 ** ever since.  The blame is not necessarily with GCC, though.
  1823 ** GCC might have just copying the problem from a prior compiler.
  1824 ** I am also told that newer versions of GCC that follow a different
  1825 ** ABI get the byte order right.
  1826 **
  1827 ** Developers using SQLite on an ARM7 should compile and run their
  1828 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
  1829 ** enabled, some asserts below will ensure that the byte order of
  1830 ** floating point values is correct.
  1831 **
  1832 ** (2007-08-30)  Frank van Vugt has studied this problem closely
  1833 ** and has send his findings to the SQLite developers.  Frank
  1834 ** writes that some Linux kernels offer floating point hardware
  1835 ** emulation that uses only 32-bit mantissas instead of a full 
  1836 ** 48-bits as required by the IEEE standard.  (This is the
  1837 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
  1838 ** byte swapping becomes very complicated.  To avoid problems,
  1839 ** the necessary byte swapping is carried out using a 64-bit integer
  1840 ** rather than a 64-bit float.  Frank assures us that the code here
  1841 ** works for him.  We, the developers, have no way to independently
  1842 ** verify this, but Frank seems to know what he is talking about
  1843 ** so we trust him.
  1844 */
  1845 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  1846 static u64 floatSwap(u64 in){
  1847   union {
  1848     u64 r;
  1849     u32 i[2];
  1850   } u;
  1851   u32 t;
  1852 
  1853   u.r = in;
  1854   t = u.i[0];
  1855   u.i[0] = u.i[1];
  1856   u.i[1] = t;
  1857   return u.r;
  1858 }
  1859 # define swapMixedEndianFloat(X)  X = floatSwap(X)
  1860 #else
  1861 # define swapMixedEndianFloat(X)
  1862 #endif
  1863 
  1864 /*
  1865 ** Write the serialized data blob for the value stored in pMem into 
  1866 ** buf. It is assumed that the caller has allocated sufficient space.
  1867 ** Return the number of bytes written.
  1868 **
  1869 ** nBuf is the amount of space left in buf[].  nBuf must always be
  1870 ** large enough to hold the entire field.  Except, if the field is
  1871 ** a blob with a zero-filled tail, then buf[] might be just the right
  1872 ** size to hold everything except for the zero-filled tail.  If buf[]
  1873 ** is only big enough to hold the non-zero prefix, then only write that
  1874 ** prefix into buf[].  But if buf[] is large enough to hold both the
  1875 ** prefix and the tail then write the prefix and set the tail to all
  1876 ** zeros.
  1877 **
  1878 ** Return the number of bytes actually written into buf[].  The number
  1879 ** of bytes in the zero-filled tail is included in the return value only
  1880 ** if those bytes were zeroed in buf[].
  1881 */ 
  1882 int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
  1883   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
  1884   int len;
  1885 
  1886   /* Integer and Real */
  1887   if( serial_type<=7 && serial_type>0 ){
  1888     u64 v;
  1889     int i;
  1890     if( serial_type==7 ){
  1891       assert( sizeof(v)==sizeof(pMem->r) );
  1892       memcpy(&v, &pMem->r, sizeof(v));
  1893       swapMixedEndianFloat(v);
  1894     }else{
  1895       v = pMem->u.i;
  1896     }
  1897     len = i = sqlite3VdbeSerialTypeLen(serial_type);
  1898     assert( len<=nBuf );
  1899     while( i-- ){
  1900       buf[i] = (v&0xFF);
  1901       v >>= 8;
  1902     }
  1903     return len;
  1904   }
  1905 
  1906   /* String or blob */
  1907   if( serial_type>=12 ){
  1908     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
  1909              == sqlite3VdbeSerialTypeLen(serial_type) );
  1910     assert( pMem->n<=nBuf );
  1911     len = pMem->n;
  1912     memcpy(buf, pMem->z, len);
  1913     if( pMem->flags & MEM_Zero ){
  1914       len += pMem->u.i;
  1915       if( len>nBuf ){
  1916         len = nBuf;
  1917       }
  1918       memset(&buf[pMem->n], 0, len-pMem->n);
  1919     }
  1920     return len;
  1921   }
  1922 
  1923   /* NULL or constants 0 or 1 */
  1924   return 0;
  1925 }
  1926 
  1927 /*
  1928 ** Deserialize the data blob pointed to by buf as serial type serial_type
  1929 ** and store the result in pMem.  Return the number of bytes read.
  1930 */ 
  1931 int sqlite3VdbeSerialGet(
  1932   const unsigned char *buf,     /* Buffer to deserialize from */
  1933   u32 serial_type,              /* Serial type to deserialize */
  1934   Mem *pMem                     /* Memory cell to write value into */
  1935 ){
  1936   switch( serial_type ){
  1937     case 10:   /* Reserved for future use */
  1938     case 11:   /* Reserved for future use */
  1939     case 0: {  /* NULL */
  1940       pMem->flags = MEM_Null;
  1941       break;
  1942     }
  1943     case 1: { /* 1-byte signed integer */
  1944       pMem->u.i = (signed char)buf[0];
  1945       pMem->flags = MEM_Int;
  1946       return 1;
  1947     }
  1948     case 2: { /* 2-byte signed integer */
  1949       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
  1950       pMem->flags = MEM_Int;
  1951       return 2;
  1952     }
  1953     case 3: { /* 3-byte signed integer */
  1954       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
  1955       pMem->flags = MEM_Int;
  1956       return 3;
  1957     }
  1958     case 4: { /* 4-byte signed integer */
  1959       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  1960       pMem->flags = MEM_Int;
  1961       return 4;
  1962     }
  1963     case 5: { /* 6-byte signed integer */
  1964       u64 x = (((signed char)buf[0])<<8) | buf[1];
  1965       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
  1966       x = (x<<32) | y;
  1967       pMem->u.i = *(i64*)&x;
  1968       pMem->flags = MEM_Int;
  1969       return 6;
  1970     }
  1971     case 6:   /* 8-byte signed integer */
  1972     case 7: { /* IEEE floating point */
  1973       u64 x;
  1974       u32 y;
  1975 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  1976       /* Verify that integers and floating point values use the same
  1977       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  1978       ** defined that 64-bit floating point values really are mixed
  1979       ** endian.
  1980       */
  1981       static const u64 t1 = ((u64)0x3ff00000)<<32;
  1982       static const double r1 = 1.0;
  1983       u64 t2 = t1;
  1984       swapMixedEndianFloat(t2);
  1985       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  1986 #endif
  1987 
  1988       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  1989       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
  1990       x = (x<<32) | y;
  1991       if( serial_type==6 ){
  1992         pMem->u.i = *(i64*)&x;
  1993         pMem->flags = MEM_Int;
  1994       }else{
  1995         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
  1996         swapMixedEndianFloat(x);
  1997         memcpy(&pMem->r, &x, sizeof(x));
  1998         pMem->flags = MEM_Real;
  1999       }
  2000       return 8;
  2001     }
  2002     case 8:    /* Integer 0 */
  2003     case 9: {  /* Integer 1 */
  2004       pMem->u.i = serial_type-8;
  2005       pMem->flags = MEM_Int;
  2006       return 0;
  2007     }
  2008     default: {
  2009       int len = (serial_type-12)/2;
  2010       pMem->z = (char *)buf;
  2011       pMem->n = len;
  2012       pMem->xDel = 0;
  2013       if( serial_type&0x01 ){
  2014         pMem->flags = MEM_Str | MEM_Ephem;
  2015       }else{
  2016         pMem->flags = MEM_Blob | MEM_Ephem;
  2017       }
  2018       return len;
  2019     }
  2020   }
  2021   return 0;
  2022 }
  2023 
  2024 /*
  2025 ** The header of a record consists of a sequence variable-length integers.
  2026 ** These integers are almost always small and are encoded as a single byte.
  2027 ** The following macro takes advantage this fact to provide a fast decode
  2028 ** of the integers in a record header.  It is faster for the common case
  2029 ** where the integer is a single byte.  It is a little slower when the
  2030 ** integer is two or more bytes.  But overall it is faster.
  2031 **
  2032 ** The following expressions are equivalent:
  2033 **
  2034 **     x = sqlite3GetVarint32( A, &B );
  2035 **
  2036 **     x = GetVarint( A, B );
  2037 **
  2038 */
  2039 #define GetVarint(A,B)  ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
  2040 
  2041 /*
  2042 ** This function compares the two table rows or index records specified by 
  2043 ** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
  2044 ** or positive integer if {nKey1, pKey1} is less than, equal to or 
  2045 ** greater than {nKey2, pKey2}.  Both Key1 and Key2 must be byte strings
  2046 ** composed by the OP_MakeRecord opcode of the VDBE.
  2047 */
  2048 int sqlite3VdbeRecordCompare(
  2049   void *userData,
  2050   int nKey1, const void *pKey1, 
  2051   int nKey2, const void *pKey2
  2052 ){
  2053   KeyInfo *pKeyInfo = (KeyInfo*)userData;
  2054   u32 d1, d2;          /* Offset into aKey[] of next data element */
  2055   u32 idx1, idx2;      /* Offset into aKey[] of next header element */
  2056   u32 szHdr1, szHdr2;  /* Number of bytes in header */
  2057   int i = 0;
  2058   int nField;
  2059   int rc = 0;
  2060   const unsigned char *aKey1 = (const unsigned char *)pKey1;
  2061   const unsigned char *aKey2 = (const unsigned char *)pKey2;
  2062 
  2063   Mem mem1;
  2064   Mem mem2;
  2065   mem1.enc = pKeyInfo->enc;
  2066   mem1.db = pKeyInfo->db;
  2067   mem2.enc = pKeyInfo->enc;
  2068   mem2.db = pKeyInfo->db;
  2069   
  2070   idx1 = GetVarint(aKey1, szHdr1);
  2071   d1 = szHdr1;
  2072   idx2 = GetVarint(aKey2, szHdr2);
  2073   d2 = szHdr2;
  2074   nField = pKeyInfo->nField;
  2075   while( idx1<szHdr1 && idx2<szHdr2 ){
  2076     u32 serial_type1;
  2077     u32 serial_type2;
  2078 
  2079     /* Read the serial types for the next element in each key. */
  2080     idx1 += GetVarint( aKey1+idx1, serial_type1 );
  2081     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
  2082     idx2 += GetVarint( aKey2+idx2, serial_type2 );
  2083     if( d2>=nKey2 && sqlite3VdbeSerialTypeLen(serial_type2)>0 ) break;
  2084 
  2085     /* Extract the values to be compared.
  2086     */
  2087     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  2088     d2 += sqlite3VdbeSerialGet(&aKey2[d2], serial_type2, &mem2);
  2089 
  2090     /* Do the comparison
  2091     */
  2092     rc = sqlite3MemCompare(&mem1, &mem2, i<nField ? pKeyInfo->aColl[i] : 0);
  2093     if( mem1.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem1);
  2094     if( mem2.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem2);
  2095     if( rc!=0 ){
  2096       break;
  2097     }
  2098     i++;
  2099   }
  2100 
  2101   /* One of the keys ran out of fields, but all the fields up to that point
  2102   ** were equal. If the incrKey flag is true, then the second key is
  2103   ** treated as larger.
  2104   */
  2105   if( rc==0 ){
  2106     if( pKeyInfo->incrKey ){
  2107       rc = -1;
  2108     }else if( d1<nKey1 ){
  2109       rc = 1;
  2110     }else if( d2<nKey2 ){
  2111       rc = -1;
  2112     }
  2113   }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
  2114                && pKeyInfo->aSortOrder[i] ){
  2115     rc = -rc;
  2116   }
  2117 
  2118   return rc;
  2119 }
  2120 
  2121 /*
  2122 ** The argument is an index entry composed using the OP_MakeRecord opcode.
  2123 ** The last entry in this record should be an integer (specifically
  2124 ** an integer rowid).  This routine returns the number of bytes in
  2125 ** that integer.
  2126 */
  2127 int sqlite3VdbeIdxRowidLen(const u8 *aKey){
  2128   u32 szHdr;        /* Size of the header */
  2129   u32 typeRowid;    /* Serial type of the rowid */
  2130 
  2131   sqlite3GetVarint32(aKey, &szHdr);
  2132   sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
  2133   return sqlite3VdbeSerialTypeLen(typeRowid);
  2134 }
  2135   
  2136 
  2137 /*
  2138 ** pCur points at an index entry created using the OP_MakeRecord opcode.
  2139 ** Read the rowid (the last field in the record) and store it in *rowid.
  2140 ** Return SQLITE_OK if everything works, or an error code otherwise.
  2141 */
  2142 int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
  2143   i64 nCellKey = 0;
  2144   int rc;
  2145   u32 szHdr;        /* Size of the header */
  2146   u32 typeRowid;    /* Serial type of the rowid */
  2147   u32 lenRowid;     /* Size of the rowid */
  2148   Mem m, v;
  2149 
  2150   sqlite3BtreeKeySize(pCur, &nCellKey);
  2151   if( nCellKey<=0 ){
  2152     return SQLITE_CORRUPT_BKPT;
  2153   }
  2154   rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
  2155   if( rc ){
  2156     return rc;
  2157   }
  2158   sqlite3GetVarint32((u8*)m.z, &szHdr);
  2159   sqlite3GetVarint32((u8*)&m.z[szHdr-1], &typeRowid);
  2160   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  2161   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  2162   *rowid = v.u.i;
  2163   sqlite3VdbeMemRelease(&m);
  2164   return SQLITE_OK;
  2165 }
  2166 
  2167 /*
  2168 ** Compare the key of the index entry that cursor pC is point to against
  2169 ** the key string in pKey (of length nKey).  Write into *pRes a number
  2170 ** that is negative, zero, or positive if pC is less than, equal to,
  2171 ** or greater than pKey.  Return SQLITE_OK on success.
  2172 **
  2173 ** pKey is either created without a rowid or is truncated so that it
  2174 ** omits the rowid at the end.  The rowid at the end of the index entry
  2175 ** is ignored as well.
  2176 */
  2177 int sqlite3VdbeIdxKeyCompare(
  2178   Cursor *pC,                 /* The cursor to compare against */
  2179   int nKey, const u8 *pKey,   /* The key to compare */
  2180   int *res                    /* Write the comparison result here */
  2181 ){
  2182   i64 nCellKey = 0;
  2183   int rc;
  2184   BtCursor *pCur = pC->pCursor;
  2185   int lenRowid;
  2186   Mem m;
  2187 
  2188   sqlite3BtreeKeySize(pCur, &nCellKey);
  2189   if( nCellKey<=0 ){
  2190     *res = 0;
  2191     return SQLITE_OK;
  2192   }
  2193   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
  2194   if( rc ){
  2195     return rc;
  2196   }
  2197   lenRowid = sqlite3VdbeIdxRowidLen((u8*)m.z);
  2198   *res = sqlite3VdbeRecordCompare(pC->pKeyInfo, m.n-lenRowid, m.z, nKey, pKey);
  2199   sqlite3VdbeMemRelease(&m);
  2200   return SQLITE_OK;
  2201 }
  2202 
  2203 /*
  2204 ** This routine sets the value to be returned by subsequent calls to
  2205 ** sqlite3_changes() on the database handle 'db'. 
  2206 */
  2207 void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  2208   assert( sqlite3_mutex_held(db->mutex) );
  2209   db->nChange = nChange;
  2210   db->nTotalChange += nChange;
  2211 }
  2212 
  2213 /*
  2214 ** Set a flag in the vdbe to update the change counter when it is finalised
  2215 ** or reset.
  2216 */
  2217 void sqlite3VdbeCountChanges(Vdbe *v){
  2218   v->changeCntOn = 1;
  2219 }
  2220 
  2221 /*
  2222 ** Mark every prepared statement associated with a database connection
  2223 ** as expired.
  2224 **
  2225 ** An expired statement means that recompilation of the statement is
  2226 ** recommend.  Statements expire when things happen that make their
  2227 ** programs obsolete.  Removing user-defined functions or collating
  2228 ** sequences, or changing an authorization function are the types of
  2229 ** things that make prepared statements obsolete.
  2230 */
  2231 void sqlite3ExpirePreparedStatements(sqlite3 *db){
  2232   Vdbe *p;
  2233   for(p = db->pVdbe; p; p=p->pNext){
  2234     p->expired = 1;
  2235   }
  2236 }
  2237 
  2238 /*
  2239 ** Return the database associated with the Vdbe.
  2240 */
  2241 sqlite3 *sqlite3VdbeDb(Vdbe *v){
  2242   return v->db;
  2243 }