xref: /sqlite-3.40.0/src/vdbeaux.c (revision 4dcbdbff)
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 "os.h"
19 #include <ctype.h>
20 #include "vdbeInt.h"
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 = sqliteMalloc( 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 ** Turn tracing on or off
53 */
54 void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
55   p->trace = trace;
56 }
57 
58 /*
59 ** Resize the Vdbe.aOp array so that it contains at least N
60 ** elements. If the Vdbe is in VDBE_MAGIC_RUN state, then
61 ** the Vdbe.aOp array will be sized to contain exactly N
62 ** elements.
63 */
64 static void resizeOpArray(Vdbe *p, int N){
65   if( p->magic==VDBE_MAGIC_RUN ){
66     assert( N==p->nOp );
67     p->nOpAlloc = N;
68     p->aOp = sqliteRealloc(p->aOp, N*sizeof(Op));
69   }else if( p->nOpAlloc<N ){
70     int oldSize = p->nOpAlloc;
71     p->nOpAlloc = N+100;
72     p->aOp = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
73     if( p->aOp ){
74       memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
75     }
76   }
77 }
78 
79 /*
80 ** Add a new instruction to the list of instructions current in the
81 ** VDBE.  Return the address of the new instruction.
82 **
83 ** Parameters:
84 **
85 **    p               Pointer to the VDBE
86 **
87 **    op              The opcode for this instruction
88 **
89 **    p1, p2          First two of the three possible operands.
90 **
91 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
92 ** the sqlite3VdbeChangeP3() function to change the value of the P3
93 ** operand.
94 */
95 int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){
96   int i;
97   VdbeOp *pOp;
98 
99   i = p->nOp;
100   p->nOp++;
101   assert( p->magic==VDBE_MAGIC_INIT );
102   resizeOpArray(p, i+1);
103   if( p->aOp==0 ){
104     return 0;
105   }
106   pOp = &p->aOp[i];
107   pOp->opcode = op;
108   pOp->p1 = p1;
109   pOp->p2 = p2;
110   pOp->p3 = 0;
111   pOp->p3type = P3_NOTUSED;
112 #ifdef SQLITE_DEBUG
113   if( sqlite3_vdbe_addop_trace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
114 #endif
115   return i;
116 }
117 
118 /*
119 ** Add an opcode that includes the p3 value.
120 */
121 int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){
122   int addr = sqlite3VdbeAddOp(p, op, p1, p2);
123   sqlite3VdbeChangeP3(p, addr, zP3, p3type);
124   return addr;
125 }
126 
127 /*
128 ** Create a new symbolic label for an instruction that has yet to be
129 ** coded.  The symbolic label is really just a negative number.  The
130 ** label can be used as the P2 value of an operation.  Later, when
131 ** the label is resolved to a specific address, the VDBE will scan
132 ** through its operation list and change all values of P2 which match
133 ** the label into the resolved address.
134 **
135 ** The VDBE knows that a P2 value is a label because labels are
136 ** always negative and P2 values are suppose to be non-negative.
137 ** Hence, a negative P2 value is a label that has yet to be resolved.
138 **
139 ** Zero is returned if a malloc() fails.
140 */
141 int sqlite3VdbeMakeLabel(Vdbe *p){
142   int i;
143   i = p->nLabel++;
144   assert( p->magic==VDBE_MAGIC_INIT );
145   if( i>=p->nLabelAlloc ){
146     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
147     p->aLabel = sqliteRealloc( p->aLabel, p->nLabelAlloc*sizeof(p->aLabel[0]));
148   }
149   if( p->aLabel ){
150     p->aLabel[i] = -1;
151   }
152   return -1-i;
153 }
154 
155 /*
156 ** Resolve label "x" to be the address of the next instruction to
157 ** be inserted.  The parameter "x" must have been obtained from
158 ** a prior call to sqlite3VdbeMakeLabel().
159 */
160 void sqlite3VdbeResolveLabel(Vdbe *p, int x){
161   int j = -1-x;
162   assert( p->magic==VDBE_MAGIC_INIT );
163   assert( j>=0 && j<p->nLabel );
164   if( p->aLabel ){
165     p->aLabel[j] = p->nOp;
166   }
167 }
168 
169 /*
170 ** Return non-zero if opcode 'op' is guarenteed not to push more values
171 ** onto the VDBE stack than it pops off.
172 */
173 static int opcodeNoPush(u8 op){
174   /* The 10 NOPUSH_MASK_n constants are defined in the automatically
175   ** generated header file opcodes.h. Each is a 16-bit bitmask, one
176   ** bit corresponding to each opcode implemented by the virtual
177   ** machine in vdbe.c. The bit is true if the word "no-push" appears
178   ** in a comment on the same line as the "case OP_XXX:" in
179   ** sqlite3VdbeExec() in vdbe.c.
180   **
181   ** If the bit is true, then the corresponding opcode is guarenteed not
182   ** to grow the stack when it is executed. Otherwise, it may grow the
183   ** stack by at most one entry.
184   **
185   ** NOPUSH_MASK_0 corresponds to opcodes 0 to 15. NOPUSH_MASK_1 contains
186   ** one bit for opcodes 16 to 31, and so on.
187   **
188   ** 16-bit bitmasks (rather than 32-bit) are specified in opcodes.h
189   ** because the file is generated by an awk program. Awk manipulates
190   ** all numbers as floating-point and we don't want to risk a rounding
191   ** error if someone builds with an awk that uses (for example) 32-bit
192   ** IEEE floats.
193   */
194   static const u32 masks[5] = {
195     NOPUSH_MASK_0 + (NOPUSH_MASK_1<<16),
196     NOPUSH_MASK_2 + (NOPUSH_MASK_3<<16),
197     NOPUSH_MASK_4 + (NOPUSH_MASK_5<<16),
198     NOPUSH_MASK_6 + (NOPUSH_MASK_7<<16),
199     NOPUSH_MASK_8 + (NOPUSH_MASK_9<<16)
200   };
201   return (masks[op>>5] & (1<<(op&0x1F)));
202 }
203 
204 #ifndef NDEBUG
205 int sqlite3VdbeOpcodeNoPush(u8 op){
206   return opcodeNoPush(op);
207 }
208 #endif
209 
210 /*
211 ** Loop through the program looking for P2 values that are negative.
212 ** Each such value is a label.  Resolve the label by setting the P2
213 ** value to its correct non-zero value.
214 **
215 ** This routine is called once after all opcodes have been inserted.
216 **
217 ** Variable *pMaxFuncArgs is set to the maximum value of any P1 argument
218 ** to an OP_Function or P2 to an OP_AggFunc opcode. This is used by
219 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
220 **
221 ** The integer *pMaxStack is set to the maximum number of vdbe stack
222 ** entries that static analysis reveals this program might need.
223 **
224 ** This routine also does the following optimization:  It scans for
225 ** Halt instructions where P1==SQLITE_CONSTRAINT or P2==OE_Abort or for
226 ** IdxInsert instructions where P2!=0.  If no such instruction is
227 ** found, then every Statement instruction is changed to a Noop.  In
228 ** this way, we avoid creating the statement journal file unnecessarily.
229 */
230 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs, int *pMaxStack){
231   int i;
232   int nMaxArgs = 0;
233   int nMaxStack = p->nOp;
234   Op *pOp;
235   int *aLabel = p->aLabel;
236   int doesStatementRollback = 0;
237   int hasStatementBegin = 0;
238   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
239     u8 opcode = pOp->opcode;
240 
241     /* Todo: Maybe OP_AggFunc should change to use P1 in the same
242      * way as OP_Function.
243      */
244     if( opcode==OP_Function ){
245       if( pOp->p1>nMaxArgs ) nMaxArgs = pOp->p1;
246     }else if( opcode==OP_AggFunc ){
247       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
248     }else if( opcode==OP_Halt ){
249       if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
250         doesStatementRollback = 1;
251       }
252     }else if( opcode==OP_IdxInsert ){
253       if( pOp->p2 ){
254         doesStatementRollback = 1;
255       }
256     }else if( opcode==OP_Statement ){
257       hasStatementBegin = 1;
258     }
259 
260     if( opcodeNoPush(opcode) ){
261       nMaxStack--;
262     }
263 
264     if( pOp->p2>=0 ) continue;
265     assert( -1-pOp->p2<p->nLabel );
266     pOp->p2 = aLabel[-1-pOp->p2];
267   }
268   sqliteFree(p->aLabel);
269   p->aLabel = 0;
270 
271   *pMaxFuncArgs = nMaxArgs;
272   *pMaxStack = nMaxStack;
273 
274   /* If we never rollback a statement transaction, then statement
275   ** transactions are not needed.  So change every OP_Statement
276   ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
277   ** which can be expensive on some platforms.
278   */
279   if( hasStatementBegin && !doesStatementRollback ){
280     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
281       if( pOp->opcode==OP_Statement ){
282         pOp->opcode = OP_Noop;
283       }
284     }
285   }
286 }
287 
288 /*
289 ** Return the address of the next instruction to be inserted.
290 */
291 int sqlite3VdbeCurrentAddr(Vdbe *p){
292   assert( p->magic==VDBE_MAGIC_INIT );
293   return p->nOp;
294 }
295 
296 /*
297 ** Add a whole list of operations to the operation stack.  Return the
298 ** address of the first operation added.
299 */
300 int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
301   int addr;
302   assert( p->magic==VDBE_MAGIC_INIT );
303   resizeOpArray(p, p->nOp + nOp);
304   if( p->aOp==0 ){
305     return 0;
306   }
307   addr = p->nOp;
308   if( nOp>0 ){
309     int i;
310     VdbeOpList const *pIn = aOp;
311     for(i=0; i<nOp; i++, pIn++){
312       int p2 = pIn->p2;
313       VdbeOp *pOut = &p->aOp[i+addr];
314       pOut->opcode = pIn->opcode;
315       pOut->p1 = pIn->p1;
316       pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
317       pOut->p3 = pIn->p3;
318       pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
319 #ifdef SQLITE_DEBUG
320       if( sqlite3_vdbe_addop_trace ){
321         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
322       }
323 #endif
324     }
325     p->nOp += nOp;
326   }
327   return addr;
328 }
329 
330 /*
331 ** Change the value of the P1 operand for a specific instruction.
332 ** This routine is useful when a large program is loaded from a
333 ** static array using sqlite3VdbeAddOpList but we want to make a
334 ** few minor changes to the program.
335 */
336 void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
337   assert( p->magic==VDBE_MAGIC_INIT );
338   if( p && addr>=0 && p->nOp>addr && p->aOp ){
339     p->aOp[addr].p1 = val;
340   }
341 }
342 
343 /*
344 ** Change the value of the P2 operand for a specific instruction.
345 ** This routine is useful for setting a jump destination.
346 */
347 void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
348   assert( val>=0 );
349   assert( p->magic==VDBE_MAGIC_INIT );
350   if( p && addr>=0 && p->nOp>addr && p->aOp ){
351     p->aOp[addr].p2 = val;
352   }
353 }
354 
355 /*
356 ** Change the value of the P3 operand for a specific instruction.
357 ** This routine is useful when a large program is loaded from a
358 ** static array using sqlite3VdbeAddOpList but we want to make a
359 ** few minor changes to the program.
360 **
361 ** If n>=0 then the P3 operand is dynamic, meaning that a copy of
362 ** the string is made into memory obtained from sqliteMalloc().
363 ** A value of n==0 means copy bytes of zP3 up to and including the
364 ** first null byte.  If n>0 then copy n+1 bytes of zP3.
365 **
366 ** If n==P3_KEYINFO it means that zP3 is a pointer to a KeyInfo structure.
367 ** A copy is made of the KeyInfo structure into memory obtained from
368 ** sqliteMalloc, to be freed when the Vdbe is finalized.
369 ** n==P3_KEYINFO_HANDOFF indicates that zP3 points to a KeyInfo structure
370 ** stored in memory that the caller has obtained from sqliteMalloc. The
371 ** caller should not free the allocation, it will be freed when the Vdbe is
372 ** finalized.
373 **
374 ** Other values of n (P3_STATIC, P3_COLLSEQ etc.) indicate that zP3 points
375 ** to a string or structure that is guaranteed to exist for the lifetime of
376 ** the Vdbe. In these cases we can just copy the pointer.
377 **
378 ** If addr<0 then change P3 on the most recently inserted instruction.
379 */
380 void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
381   Op *pOp;
382   assert( p->magic==VDBE_MAGIC_INIT );
383   if( p==0 || p->aOp==0 ){
384     if( n==P3_DYNAMIC || n==P3_KEYINFO_HANDOFF ){
385       sqliteFree((void*)zP3);
386     }
387     if( n==P3_MEM ){
388       sqlite3ValueFree((sqlite3_value *)zP3);
389     }
390     return;
391   }
392   if( addr<0 || addr>=p->nOp ){
393     addr = p->nOp - 1;
394     if( addr<0 ) return;
395   }
396   pOp = &p->aOp[addr];
397   if( pOp->p3 && pOp->p3type==P3_DYNAMIC ){
398     sqliteFree(pOp->p3);
399     pOp->p3 = 0;
400   }
401   if( zP3==0 ){
402     pOp->p3 = 0;
403     pOp->p3type = P3_NOTUSED;
404   }else if( n==P3_KEYINFO ){
405     KeyInfo *pKeyInfo;
406     int nField, nByte;
407     nField = ((KeyInfo*)zP3)->nField;
408     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]);
409     pKeyInfo = sqliteMallocRaw( nByte );
410     pOp->p3 = (char*)pKeyInfo;
411     if( pKeyInfo ){
412       memcpy(pKeyInfo, zP3, nByte);
413       pOp->p3type = P3_KEYINFO;
414     }else{
415       pOp->p3type = P3_NOTUSED;
416     }
417   }else if( n==P3_KEYINFO_HANDOFF ){
418     pOp->p3 = (char*)zP3;
419     pOp->p3type = P3_KEYINFO;
420   }else if( n<0 ){
421     pOp->p3 = (char*)zP3;
422     pOp->p3type = n;
423   }else{
424     if( n==0 ) n = strlen(zP3);
425     pOp->p3 = sqliteStrNDup(zP3, n);
426     pOp->p3type = P3_DYNAMIC;
427   }
428 }
429 
430 #ifndef NDEBUG
431 /*
432 ** Replace the P3 field of the most recently coded instruction with
433 ** comment text.
434 */
435 void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
436   va_list ap;
437   assert( p->nOp>0 );
438   assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0 );
439   va_start(ap, zFormat);
440   sqlite3VdbeChangeP3(p, -1, sqlite3VMPrintf(zFormat, ap), P3_DYNAMIC);
441   va_end(ap);
442 }
443 #endif
444 
445 /*
446 ** If the P3 operand to the specified instruction appears
447 ** to be a quoted string token, then this procedure removes
448 ** the quotes.
449 **
450 ** The quoting operator can be either a grave ascent (ASCII 0x27)
451 ** or a double quote character (ASCII 0x22).  Two quotes in a row
452 ** resolve to be a single actual quote character within the string.
453 */
454 void sqlite3VdbeDequoteP3(Vdbe *p, int addr){
455   Op *pOp;
456   assert( p->magic==VDBE_MAGIC_INIT );
457   if( p->aOp==0 ) return;
458   if( addr<0 || addr>=p->nOp ){
459     addr = p->nOp - 1;
460     if( addr<0 ) return;
461   }
462   pOp = &p->aOp[addr];
463   if( pOp->p3==0 || pOp->p3[0]==0 ) return;
464   if( pOp->p3type==P3_STATIC ){
465     pOp->p3 = sqliteStrDup(pOp->p3);
466     pOp->p3type = P3_DYNAMIC;
467   }
468   assert( pOp->p3type==P3_DYNAMIC );
469   sqlite3Dequote(pOp->p3);
470 }
471 
472 /*
473 ** Search the current program starting at instruction addr for the given
474 ** opcode and P2 value.  Return the address plus 1 if found and 0 if not
475 ** found.
476 */
477 int sqlite3VdbeFindOp(Vdbe *p, int addr, int op, int p2){
478   int i;
479   assert( p->magic==VDBE_MAGIC_INIT );
480   for(i=addr; i<p->nOp; i++){
481     if( p->aOp[i].opcode==op && p->aOp[i].p2==p2 ) return i+1;
482   }
483   return 0;
484 }
485 
486 /*
487 ** Return the opcode for a given address.
488 */
489 VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
490   assert( p->magic==VDBE_MAGIC_INIT );
491   assert( addr>=0 && addr<p->nOp );
492   return &p->aOp[addr];
493 }
494 
495 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
496      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
497 /*
498 ** Compute a string that describes the P3 parameter for an opcode.
499 ** Use zTemp for any required temporary buffer space.
500 */
501 static char *displayP3(Op *pOp, char *zTemp, int nTemp){
502   char *zP3;
503   assert( nTemp>=20 );
504   switch( pOp->p3type ){
505     case P3_KEYINFO: {
506       int i, j;
507       KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3;
508       sprintf(zTemp, "keyinfo(%d", pKeyInfo->nField);
509       i = strlen(zTemp);
510       for(j=0; j<pKeyInfo->nField; j++){
511         CollSeq *pColl = pKeyInfo->aColl[j];
512         if( pColl ){
513           int n = strlen(pColl->zName);
514           if( i+n>nTemp-6 ){
515             strcpy(&zTemp[i],",...");
516             break;
517           }
518           zTemp[i++] = ',';
519           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
520             zTemp[i++] = '-';
521           }
522           strcpy(&zTemp[i], pColl->zName);
523           i += n;
524         }else if( i+4<nTemp-6 ){
525           strcpy(&zTemp[i],",nil");
526           i += 4;
527         }
528       }
529       zTemp[i++] = ')';
530       zTemp[i] = 0;
531       assert( i<nTemp );
532       zP3 = zTemp;
533       break;
534     }
535     case P3_COLLSEQ: {
536       CollSeq *pColl = (CollSeq*)pOp->p3;
537       sprintf(zTemp, "collseq(%.20s)", pColl->zName);
538       zP3 = zTemp;
539       break;
540     }
541     case P3_FUNCDEF: {
542       FuncDef *pDef = (FuncDef*)pOp->p3;
543       char zNum[30];
544       sprintf(zTemp, "%.*s", nTemp, pDef->zName);
545       sprintf(zNum,"(%d)", pDef->nArg);
546       if( strlen(zTemp)+strlen(zNum)+1<=nTemp ){
547         strcat(zTemp, zNum);
548       }
549       zP3 = zTemp;
550       break;
551     }
552     default: {
553       zP3 = pOp->p3;
554       if( zP3==0 || pOp->opcode==OP_Noop ){
555         zP3 = "";
556       }
557     }
558   }
559   return zP3;
560 }
561 #endif
562 
563 
564 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
565 /*
566 ** Print a single opcode.  This routine is used for debugging only.
567 */
568 void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
569   char *zP3;
570   char zPtr[50];
571   static const char *zFormat1 = "%4d %-13s %4d %4d %s\n";
572   if( pOut==0 ) pOut = stdout;
573   zP3 = displayP3(pOp, zPtr, sizeof(zPtr));
574   fprintf(pOut, zFormat1,
575       pc, sqlite3OpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3);
576   fflush(pOut);
577 }
578 #endif
579 
580 /*
581 ** Release an array of N Mem elements
582 */
583 static void releaseMemArray(Mem *p, int N){
584   if( p ){
585     while( N-->0 ){
586       sqlite3VdbeMemRelease(p++);
587     }
588   }
589 }
590 
591 #ifndef SQLITE_OMIT_EXPLAIN
592 /*
593 ** Give a listing of the program in the virtual machine.
594 **
595 ** The interface is the same as sqlite3VdbeExec().  But instead of
596 ** running the code, it invokes the callback once for each instruction.
597 ** This feature is used to implement "EXPLAIN".
598 */
599 int sqlite3VdbeList(
600   Vdbe *p                   /* The VDBE */
601 ){
602   sqlite3 *db = p->db;
603   int i;
604   int rc = SQLITE_OK;
605 
606   assert( p->explain );
607   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
608   assert( db->magic==SQLITE_MAGIC_BUSY );
609   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
610 
611   /* Even though this opcode does not put dynamic strings onto the
612   ** the stack, they may become dynamic if the user calls
613   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
614   */
615   if( p->pTos==&p->aStack[4] ){
616     releaseMemArray(p->aStack, 5);
617   }
618   p->resOnStack = 0;
619 
620 
621   i = p->pc++;
622   if( i>=p->nOp ){
623     p->rc = SQLITE_OK;
624     rc = SQLITE_DONE;
625   }else if( db->flags & SQLITE_Interrupt ){
626     db->flags &= ~SQLITE_Interrupt;
627     p->rc = SQLITE_INTERRUPT;
628     rc = SQLITE_ERROR;
629     sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
630   }else{
631     Op *pOp = &p->aOp[i];
632     Mem *pMem = p->aStack;
633     pMem->flags = MEM_Int;
634     pMem->type = SQLITE_INTEGER;
635     pMem->i = i;                                /* Program counter */
636     pMem++;
637 
638     pMem->flags = MEM_Static|MEM_Str|MEM_Term;
639     pMem->z = sqlite3OpcodeNames[pOp->opcode];  /* Opcode */
640     pMem->n = strlen(pMem->z);
641     pMem->type = SQLITE_TEXT;
642     pMem->enc = SQLITE_UTF8;
643     pMem++;
644 
645     pMem->flags = MEM_Int;
646     pMem->i = pOp->p1;                          /* P1 */
647     pMem->type = SQLITE_INTEGER;
648     pMem++;
649 
650     pMem->flags = MEM_Int;
651     pMem->i = pOp->p2;                          /* P2 */
652     pMem->type = SQLITE_INTEGER;
653     pMem++;
654 
655     pMem->flags = MEM_Short|MEM_Str|MEM_Term;   /* P3 */
656     pMem->z = displayP3(pOp, pMem->zShort, sizeof(pMem->zShort));
657     pMem->type = SQLITE_TEXT;
658     pMem->enc = SQLITE_UTF8;
659 
660     p->nResColumn = 5;
661     p->pTos = pMem;
662     p->rc = SQLITE_OK;
663     p->resOnStack = 1;
664     rc = SQLITE_ROW;
665   }
666   return rc;
667 }
668 #endif /* SQLITE_OMIT_EXPLAIN */
669 
670 /*
671 ** Print the SQL that was used to generate a VDBE program.
672 */
673 void sqlite3VdbePrintSql(Vdbe *p){
674 #ifdef SQLITE_DEBUG
675   int nOp = p->nOp;
676   VdbeOp *pOp;
677   if( nOp<1 ) return;
678   pOp = &p->aOp[nOp-1];
679   if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
680     const char *z = pOp->p3;
681     while( isspace(*(u8*)z) ) z++;
682     printf("SQL: [%s]\n", z);
683   }
684 #endif
685 }
686 
687 /*
688 ** Prepare a virtual machine for execution.  This involves things such
689 ** as allocating stack space and initializing the program counter.
690 ** After the VDBE has be prepped, it can be executed by one or more
691 ** calls to sqlite3VdbeExec().
692 **
693 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
694 ** VDBE_MAGIC_RUN.
695 */
696 void sqlite3VdbeMakeReady(
697   Vdbe *p,                       /* The VDBE */
698   int nVar,                      /* Number of '?' see in the SQL statement */
699   int nMem,                      /* Number of memory cells to allocate */
700   int nCursor,                   /* Number of cursors to allocate */
701   int nAgg,                      /* Number of aggregate contexts required */
702   int isExplain                  /* True if the EXPLAIN keywords is present */
703 ){
704   int n;
705 
706   assert( p!=0 );
707   assert( p->magic==VDBE_MAGIC_INIT );
708 
709   /* There should be at least one opcode.
710   */
711   assert( p->nOp>0 );
712 
713   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
714    * is because the call to resizeOpArray() below may shrink the
715    * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN
716    * state.
717    */
718   p->magic = VDBE_MAGIC_RUN;
719 
720   /* No instruction ever pushes more than a single element onto the
721   ** stack.  And the stack never grows on successive executions of the
722   ** same loop.  So the total number of instructions is an upper bound
723   ** on the maximum stack depth required.  (Added later:)  The
724   ** resolveP2Values() call computes a tighter upper bound on the
725   ** stack size.
726   **
727   ** Allocation all the stack space we will ever need.
728   */
729   if( p->aStack==0 ){
730     int nArg;       /* Maximum number of args passed to a user function. */
731     int nStack;     /* Maximum number of stack entries required */
732     resolveP2Values(p, &nArg, &nStack);
733     resizeOpArray(p, p->nOp);
734     assert( nVar>=0 );
735     assert( nStack<p->nOp );
736     nStack = isExplain ? 10 : nStack;
737     p->aStack = sqliteMalloc(
738         nStack*sizeof(p->aStack[0])    /* aStack */
739       + nArg*sizeof(Mem*)              /* apArg */
740       + nVar*sizeof(Mem)               /* aVar */
741       + nVar*sizeof(char*)             /* azVar */
742       + nMem*sizeof(Mem)               /* aMem */
743       + nCursor*sizeof(Cursor*)        /* apCsr */
744       + nAgg*sizeof(Agg)               /* Aggregate contexts */
745     );
746     if( !sqlite3_malloc_failed ){
747       p->aMem = &p->aStack[nStack];
748       p->nMem = nMem;
749       p->aVar = &p->aMem[nMem];
750       p->nVar = nVar;
751       p->okVar = 0;
752       p->apArg = (Mem**)&p->aVar[nVar];
753       p->azVar = (char**)&p->apArg[nArg];
754       p->apCsr = (Cursor**)&p->azVar[nVar];
755       if( nAgg>0 ){
756         p->nAgg = nAgg;
757         p->apAgg = (Agg*)&p->apCsr[nCursor];
758       }
759       p->nCursor = nCursor;
760       for(n=0; n<nVar; n++){
761         p->aVar[n].flags = MEM_Null;
762       }
763     }
764   }
765   p->pAgg = p->apAgg;
766   for(n=0; n<p->nMem; n++){
767     p->aMem[n].flags = MEM_Null;
768   }
769 
770 #ifdef SQLITE_DEBUG
771   if( (p->db->flags & SQLITE_VdbeListing)!=0
772     || sqlite3OsFileExists("vdbe_explain")
773   ){
774     int i;
775     printf("VDBE Program Listing:\n");
776     sqlite3VdbePrintSql(p);
777     for(i=0; i<p->nOp; i++){
778       sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
779     }
780   }
781   if( sqlite3OsFileExists("vdbe_trace") ){
782     p->trace = stdout;
783   }
784 #endif
785   p->pTos = &p->aStack[-1];
786   p->pc = -1;
787   p->rc = SQLITE_OK;
788   p->uniqueCnt = 0;
789   p->returnDepth = 0;
790   p->errorAction = OE_Abort;
791   p->popStack =  0;
792   p->explain |= isExplain;
793   p->magic = VDBE_MAGIC_RUN;
794   p->nChange = 0;
795 #ifdef VDBE_PROFILE
796   {
797     int i;
798     for(i=0; i<p->nOp; i++){
799       p->aOp[i].cnt = 0;
800       p->aOp[i].cycles = 0;
801     }
802   }
803 #endif
804 }
805 
806 
807 /*
808 ** Remove any elements that remain on the sorter for the VDBE given.
809 */
810 void sqlite3VdbeSorterReset(Vdbe *p){
811   while( p->pSort ){
812     Sorter *pSorter = p->pSort;
813     p->pSort = pSorter->pNext;
814     sqliteFree(pSorter->zKey);
815     sqlite3VdbeMemRelease(&pSorter->data);
816     sqliteFree(pSorter);
817   }
818   p->pSortTail = 0;
819 }
820 
821 /*
822 ** Free all resources allociated with AggElem pElem, an element of
823 ** aggregate pAgg.
824 */
825 static void freeAggElem(AggElem *pElem, Agg *pAgg){
826   int i;
827   for(i=0; i<pAgg->nMem; i++){
828     Mem *pMem = &pElem->aMem[i];
829     if( pAgg->apFunc && pAgg->apFunc[i] && (pMem->flags & MEM_AggCtx)!=0 ){
830       sqlite3_context ctx;
831       ctx.pFunc = pAgg->apFunc[i];
832       ctx.s.flags = MEM_Null;
833       ctx.pAgg = pMem->z;
834       ctx.cnt = pMem->i;
835       ctx.isError = 0;
836       (*ctx.pFunc->xFinalize)(&ctx);
837       pMem->z = ctx.pAgg;
838       if( pMem->z!=0 && pMem->z!=pMem->zShort ){
839         sqliteFree(pMem->z);
840       }
841       sqlite3VdbeMemRelease(&ctx.s);
842     }else{
843       sqlite3VdbeMemRelease(pMem);
844     }
845   }
846   sqliteFree(pElem);
847 }
848 
849 /*
850 ** Reset an Agg structure.  Delete all its contents.
851 **
852 ** For installable aggregate functions, if the step function has been
853 ** called, make sure the finalizer function has also been called.  The
854 ** finalizer might need to free memory that was allocated as part of its
855 ** private context.  If the finalizer has not been called yet, call it
856 ** now.
857 **
858 ** If db is NULL, then this is being called from sqliteVdbeReset(). In
859 ** this case clean up all references to the temp-table used for
860 ** aggregates (if it was ever opened).
861 **
862 ** If db is not NULL, then this is being called from with an OP_AggReset
863 ** opcode. Open the temp-table, if it has not already been opened and
864 ** delete the contents of the table used for aggregate information, ready
865 ** for the next round of aggregate processing.
866 */
867 int sqlite3VdbeAggReset(sqlite3 *db, Agg *pAgg, KeyInfo *pKeyInfo){
868   int rc = 0;
869   BtCursor *pCsr;
870 
871   if( !pAgg ) return SQLITE_OK;
872   pCsr = pAgg->pCsr;
873   assert( (pCsr && pAgg->nTab>0) || (!pCsr && pAgg->nTab==0)
874          || sqlite3_malloc_failed );
875 
876   /* If pCsr is not NULL, then the table used for aggregate information
877   ** is open. Loop through it and free the AggElem* structure pointed at
878   ** by each entry. If the finalizer has not been called for an AggElem,
879   ** do that too. Finally, clear the btree table itself.
880   */
881   if( pCsr ){
882     int res;
883     assert( pAgg->pBtree );
884     assert( pAgg->nTab>0 );
885 
886     rc=sqlite3BtreeFirst(pCsr, &res);
887     while( res==0 && rc==SQLITE_OK ){
888       AggElem *pElem;
889       rc = sqlite3BtreeData(pCsr, 0, sizeof(AggElem*), (char *)&pElem);
890       if( rc!=SQLITE_OK ){
891         return rc;
892       }
893       assert( pAgg->apFunc!=0 );
894       freeAggElem(pElem, pAgg);
895       rc=sqlite3BtreeNext(pCsr, &res);
896     }
897     if( rc!=SQLITE_OK ){
898       return rc;
899     }
900 
901     sqlite3BtreeCloseCursor(pCsr);
902     sqlite3BtreeClearTable(pAgg->pBtree, pAgg->nTab);
903   }else{
904     /* The cursor may not be open because the aggregator was never used,
905     ** or it could be that it was used but there was no GROUP BY clause.
906     */
907     if( pAgg->pCurrent ){
908       freeAggElem(pAgg->pCurrent, pAgg);
909     }
910   }
911 
912   /* If db is not NULL and we have not yet and we have not yet opened
913   ** the temporary btree then do so and create the table to store aggregate
914   ** information.
915   **
916   ** If db is NULL, then close the temporary btree if it is open.
917   */
918   if( db ){
919     if( !pAgg->pBtree ){
920       assert( pAgg->nTab==0 );
921 #ifndef SQLITE_OMIT_MEMORYDB
922       rc = sqlite3BtreeFactory(db, ":memory:", 0, TEMP_PAGES, &pAgg->pBtree);
923 #else
924       rc = sqlite3BtreeFactory(db, 0, 0, TEMP_PAGES, &pAgg->pBtree);
925 #endif
926       if( rc!=SQLITE_OK ) return rc;
927       sqlite3BtreeBeginTrans(pAgg->pBtree, 1);
928       rc = sqlite3BtreeCreateTable(pAgg->pBtree, &pAgg->nTab, 0);
929       if( rc!=SQLITE_OK ) return rc;
930     }
931     assert( pAgg->nTab!=0 );
932 
933     rc = sqlite3BtreeCursor(pAgg->pBtree, pAgg->nTab, 1,
934         sqlite3VdbeRecordCompare, pKeyInfo, &pAgg->pCsr);
935     if( rc!=SQLITE_OK ) return rc;
936   }else{
937     if( pAgg->pBtree ){
938       sqlite3BtreeClose(pAgg->pBtree);
939       pAgg->pBtree = 0;
940       pAgg->nTab = 0;
941     }
942     pAgg->pCsr = 0;
943   }
944 
945   if( pAgg->apFunc ){
946     sqliteFree(pAgg->apFunc);
947     pAgg->apFunc = 0;
948   }
949   pAgg->pCurrent = 0;
950   pAgg->nMem = 0;
951   pAgg->searching = 0;
952   return SQLITE_OK;
953 }
954 
955 /*
956 ** Close a cursor and release all the resources that cursor happens
957 ** to hold.
958 */
959 void sqlite3VdbeFreeCursor(Cursor *pCx){
960   if( pCx==0 ){
961     return;
962   }
963   if( pCx->pCursor ){
964     sqlite3BtreeCloseCursor(pCx->pCursor);
965   }
966   if( pCx->pBt ){
967     sqlite3BtreeClose(pCx->pBt);
968   }
969   sqliteFree(pCx->pData);
970   sqliteFree(pCx->aType);
971   sqliteFree(pCx);
972 }
973 
974 /*
975 ** Close all cursors
976 */
977 static void closeAllCursors(Vdbe *p){
978   int i;
979   if( p->apCsr==0 ) return;
980   for(i=0; i<p->nCursor; i++){
981     sqlite3VdbeFreeCursor(p->apCsr[i]);
982     p->apCsr[i] = 0;
983   }
984 }
985 
986 /*
987 ** Clean up the VM after execution.
988 **
989 ** This routine will automatically close any cursors, lists, and/or
990 ** sorters that were left open.  It also deletes the values of
991 ** variables in the aVar[] array.
992 */
993 static void Cleanup(Vdbe *p){
994   int i;
995   if( p->aStack ){
996     releaseMemArray(p->aStack, 1 + (p->pTos - p->aStack));
997     p->pTos = &p->aStack[-1];
998   }
999   closeAllCursors(p);
1000   releaseMemArray(p->aMem, p->nMem);
1001   sqlite3VdbeFifoClear(&p->sFifo);
1002   if( p->contextStack ){
1003     for(i=0; i<p->contextStackTop; i++){
1004       sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
1005     }
1006     sqliteFree(p->contextStack);
1007   }
1008   sqlite3VdbeSorterReset(p);
1009   for(i=0; i<p->nAgg; i++){
1010     sqlite3VdbeAggReset(0, &p->apAgg[i], 0);
1011   }
1012   p->contextStack = 0;
1013   p->contextStackDepth = 0;
1014   p->contextStackTop = 0;
1015   sqliteFree(p->zErrMsg);
1016   p->zErrMsg = 0;
1017 }
1018 
1019 /*
1020 ** Set the number of result columns that will be returned by this SQL
1021 ** statement. This is now set at compile time, rather than during
1022 ** execution of the vdbe program so that sqlite3_column_count() can
1023 ** be called on an SQL statement before sqlite3_step().
1024 */
1025 void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
1026   Mem *pColName;
1027   int n;
1028   assert( 0==p->nResColumn );
1029   p->nResColumn = nResColumn;
1030   n = nResColumn*2;
1031   p->aColName = pColName = (Mem*)sqliteMalloc( sizeof(Mem)*n );
1032   if( p->aColName==0 ) return;
1033   while( n-- > 0 ){
1034     (pColName++)->flags = MEM_Null;
1035   }
1036 }
1037 
1038 /*
1039 ** Set the name of the idx'th column to be returned by the SQL statement.
1040 ** zName must be a pointer to a nul terminated string.
1041 **
1042 ** This call must be made after a call to sqlite3VdbeSetNumCols().
1043 **
1044 ** If N==P3_STATIC  it means that zName is a pointer to a constant static
1045 ** string and we can just copy the pointer. If it is P3_DYNAMIC, then
1046 ** the string is freed using sqliteFree() when the vdbe is finished with
1047 ** it. Otherwise, N bytes of zName are copied.
1048 */
1049 int sqlite3VdbeSetColName(Vdbe *p, int idx, const char *zName, int N){
1050   int rc;
1051   Mem *pColName;
1052   assert( idx<(2*p->nResColumn) );
1053   if( sqlite3_malloc_failed ) return SQLITE_NOMEM;
1054   assert( p->aColName!=0 );
1055   pColName = &(p->aColName[idx]);
1056   if( N==P3_DYNAMIC || N==P3_STATIC ){
1057     rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
1058   }else{
1059     rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
1060   }
1061   if( rc==SQLITE_OK && N==P3_DYNAMIC ){
1062     pColName->flags = (pColName->flags&(~MEM_Static))|MEM_Dyn;
1063     pColName->xDel = 0;
1064   }
1065   return rc;
1066 }
1067 
1068 /*
1069 ** A read or write transaction may or may not be active on database handle
1070 ** db. If a transaction is active, commit it. If there is a
1071 ** write-transaction spanning more than one database file, this routine
1072 ** takes care of the master journal trickery.
1073 */
1074 static int vdbeCommit(sqlite3 *db){
1075   int i;
1076   int nTrans = 0;  /* Number of databases with an active write-transaction */
1077   int rc = SQLITE_OK;
1078   int needXcommit = 0;
1079 
1080   for(i=0; i<db->nDb; i++){
1081     Btree *pBt = db->aDb[i].pBt;
1082     if( pBt && sqlite3BtreeIsInTrans(pBt) ){
1083       needXcommit = 1;
1084       if( i!=1 ) nTrans++;
1085     }
1086   }
1087 
1088   /* If there are any write-transactions at all, invoke the commit hook */
1089   if( needXcommit && db->xCommitCallback ){
1090     int rc;
1091     sqlite3SafetyOff(db);
1092     rc = db->xCommitCallback(db->pCommitArg);
1093     sqlite3SafetyOn(db);
1094     if( rc ){
1095       return SQLITE_CONSTRAINT;
1096     }
1097   }
1098 
1099   /* The simple case - no more than one database file (not counting the
1100   ** TEMP database) has a transaction active.   There is no need for the
1101   ** master-journal.
1102   **
1103   ** If the return value of sqlite3BtreeGetFilename() is a zero length
1104   ** string, it means the main database is :memory:.  In that case we do
1105   ** not support atomic multi-file commits, so use the simple case then
1106   ** too.
1107   */
1108   if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
1109     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1110       Btree *pBt = db->aDb[i].pBt;
1111       if( pBt ){
1112         rc = sqlite3BtreeSync(pBt, 0);
1113       }
1114     }
1115 
1116     /* Do the commit only if all databases successfully synced */
1117     if( rc==SQLITE_OK ){
1118       for(i=0; i<db->nDb; i++){
1119         Btree *pBt = db->aDb[i].pBt;
1120         if( pBt ){
1121           sqlite3BtreeCommit(pBt);
1122         }
1123       }
1124     }
1125   }
1126 
1127   /* The complex case - There is a multi-file write-transaction active.
1128   ** This requires a master journal file to ensure the transaction is
1129   ** committed atomicly.
1130   */
1131 #ifndef SQLITE_OMIT_DISKIO
1132   else{
1133     char *zMaster = 0;   /* File-name for the master journal */
1134     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
1135     OsFile master;
1136 
1137     /* Select a master journal file name */
1138     do {
1139       u32 random;
1140       sqliteFree(zMaster);
1141       sqlite3Randomness(sizeof(random), &random);
1142       zMaster = sqlite3MPrintf("%s-mj%08X", zMainFile, random&0x7fffffff);
1143       if( !zMaster ){
1144         return SQLITE_NOMEM;
1145       }
1146     }while( sqlite3OsFileExists(zMaster) );
1147 
1148     /* Open the master journal. */
1149     memset(&master, 0, sizeof(master));
1150     rc = sqlite3OsOpenExclusive(zMaster, &master, 0);
1151     if( rc!=SQLITE_OK ){
1152       sqliteFree(zMaster);
1153       return rc;
1154     }
1155 
1156     /* Write the name of each database file in the transaction into the new
1157     ** master journal file. If an error occurs at this point close
1158     ** and delete the master journal file. All the individual journal files
1159     ** still have 'null' as the master journal pointer, so they will roll
1160     ** back independently if a failure occurs.
1161     */
1162     for(i=0; i<db->nDb; i++){
1163       Btree *pBt = db->aDb[i].pBt;
1164       if( i==1 ) continue;   /* Ignore the TEMP database */
1165       if( pBt && sqlite3BtreeIsInTrans(pBt) ){
1166         char const *zFile = sqlite3BtreeGetJournalname(pBt);
1167         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
1168         rc = sqlite3OsWrite(&master, zFile, strlen(zFile)+1);
1169         if( rc!=SQLITE_OK ){
1170           sqlite3OsClose(&master);
1171           sqlite3OsDelete(zMaster);
1172           sqliteFree(zMaster);
1173           return rc;
1174         }
1175       }
1176     }
1177 
1178 
1179     /* Sync the master journal file. Before doing this, open the directory
1180     ** the master journal file is store in so that it gets synced too.
1181     */
1182     zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
1183     rc = sqlite3OsOpenDirectory(zMainFile, &master);
1184     if( rc!=SQLITE_OK || (rc = sqlite3OsSync(&master))!=SQLITE_OK ){
1185       sqlite3OsClose(&master);
1186       sqlite3OsDelete(zMaster);
1187       sqliteFree(zMaster);
1188       return rc;
1189     }
1190 
1191     /* Sync all the db files involved in the transaction. The same call
1192     ** sets the master journal pointer in each individual journal. If
1193     ** an error occurs here, do not delete the master journal file.
1194     **
1195     ** If the error occurs during the first call to sqlite3BtreeSync(),
1196     ** then there is a chance that the master journal file will be
1197     ** orphaned. But we cannot delete it, in case the master journal
1198     ** file name was written into the journal file before the failure
1199     ** occured.
1200     */
1201     for(i=0; i<db->nDb; i++){
1202       Btree *pBt = db->aDb[i].pBt;
1203       if( pBt && sqlite3BtreeIsInTrans(pBt) ){
1204         rc = sqlite3BtreeSync(pBt, zMaster);
1205         if( rc!=SQLITE_OK ){
1206           sqlite3OsClose(&master);
1207           sqliteFree(zMaster);
1208           return rc;
1209         }
1210       }
1211     }
1212     sqlite3OsClose(&master);
1213 
1214     /* Delete the master journal file. This commits the transaction. After
1215     ** doing this the directory is synced again before any individual
1216     ** transaction files are deleted.
1217     */
1218     rc = sqlite3OsDelete(zMaster);
1219     assert( rc==SQLITE_OK );
1220     sqliteFree(zMaster);
1221     zMaster = 0;
1222     rc = sqlite3OsSyncDirectory(zMainFile);
1223     if( rc!=SQLITE_OK ){
1224       /* This is not good. The master journal file has been deleted, but
1225       ** the directory sync failed. There is no completely safe course of
1226       ** action from here. The individual journals contain the name of the
1227       ** master journal file, but there is no way of knowing if that
1228       ** master journal exists now or if it will exist after the operating
1229       ** system crash that may follow the fsync() failure.
1230       */
1231       return rc;
1232     }
1233 
1234     /* All files and directories have already been synced, so the following
1235     ** calls to sqlite3BtreeCommit() are only closing files and deleting
1236     ** journals. If something goes wrong while this is happening we don't
1237     ** really care. The integrity of the transaction is already guaranteed,
1238     ** but some stray 'cold' journals may be lying around. Returning an
1239     ** error code won't help matters.
1240     */
1241     for(i=0; i<db->nDb; i++){
1242       Btree *pBt = db->aDb[i].pBt;
1243       if( pBt ){
1244         sqlite3BtreeCommit(pBt);
1245       }
1246     }
1247   }
1248 #endif
1249 
1250   return rc;
1251 }
1252 
1253 /*
1254 ** Find every active VM other than pVdbe and change its status to
1255 ** aborted.  This happens when one VM causes a rollback due to an
1256 ** ON CONFLICT ROLLBACK clause (for example).  The other VMs must be
1257 ** aborted so that they do not have data rolled out from underneath
1258 ** them leading to a segfault.
1259 */
1260 static void abortOtherActiveVdbes(Vdbe *pVdbe){
1261   Vdbe *pOther;
1262   for(pOther=pVdbe->db->pVdbe; pOther; pOther=pOther->pNext){
1263     if( pOther==pVdbe ) continue;
1264     if( pOther->magic!=VDBE_MAGIC_RUN || pOther->pc<0 ) continue;
1265     closeAllCursors(pOther);
1266     pOther->aborted = 1;
1267   }
1268 }
1269 
1270 /*
1271 ** This routine checks that the sqlite3.activeVdbeCnt count variable
1272 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
1273 ** currently active. An assertion fails if the two counts do not match.
1274 ** This is an internal self-check only - it is not an essential processing
1275 ** step.
1276 **
1277 ** This is a no-op if NDEBUG is defined.
1278 */
1279 #ifndef NDEBUG
1280 static void checkActiveVdbeCnt(sqlite3 *db){
1281   Vdbe *p;
1282   int cnt = 0;
1283   p = db->pVdbe;
1284   while( p ){
1285     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
1286       cnt++;
1287     }
1288     p = p->pNext;
1289   }
1290   assert( cnt==db->activeVdbeCnt );
1291 }
1292 #else
1293 #define checkActiveVdbeCnt(x)
1294 #endif
1295 
1296 /*
1297 ** This routine is called the when a VDBE tries to halt.  If the VDBE
1298 ** has made changes and is in autocommit mode, then commit those
1299 ** changes.  If a rollback is needed, then do the rollback.
1300 **
1301 ** This routine is the only way to move the state of a VM from
1302 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.
1303 **
1304 ** Return an error code.  If the commit could not complete because of
1305 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
1306 ** means the close did not happen and needs to be repeated.
1307 */
1308 int sqlite3VdbeHalt(Vdbe *p){
1309   sqlite3 *db = p->db;
1310   int i;
1311   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
1312 
1313   if( p->magic!=VDBE_MAGIC_RUN ){
1314     /* Already halted.  Nothing to do. */
1315     assert( p->magic==VDBE_MAGIC_HALT );
1316     return SQLITE_OK;
1317   }
1318   closeAllCursors(p);
1319   checkActiveVdbeCnt(db);
1320   if( p->pc<0 ){
1321     /* No commit or rollback needed if the program never started */
1322   }else if( db->autoCommit && db->activeVdbeCnt==1 ){
1323     if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
1324       /* The auto-commit flag is true, there are no other active queries
1325       ** using this handle and the vdbe program was successful or hit an
1326       ** 'OR FAIL' constraint. This means a commit is required.
1327       */
1328       int rc = vdbeCommit(db);
1329       if( rc==SQLITE_BUSY ){
1330         return SQLITE_BUSY;
1331       }else if( rc!=SQLITE_OK ){
1332         p->rc = rc;
1333         xFunc = sqlite3BtreeRollback;
1334       }
1335     }else{
1336       xFunc = sqlite3BtreeRollback;
1337     }
1338   }else{
1339     if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
1340       xFunc = sqlite3BtreeCommitStmt;
1341     }else if( p->errorAction==OE_Abort ){
1342       xFunc = sqlite3BtreeRollbackStmt;
1343     }else{
1344       xFunc = sqlite3BtreeRollback;
1345       db->autoCommit = 1;
1346       abortOtherActiveVdbes(p);
1347     }
1348   }
1349 
1350   /* If xFunc is not NULL, then it is one of sqlite3BtreeRollback,
1351   ** sqlite3BtreeRollbackStmt or sqlite3BtreeCommitStmt. Call it once on
1352   ** each backend. If an error occurs and the return code is still
1353   ** SQLITE_OK, set the return code to the new error value.
1354   */
1355   for(i=0; xFunc && i<db->nDb; i++){
1356     int rc;
1357     Btree *pBt = db->aDb[i].pBt;
1358     if( pBt ){
1359       rc = xFunc(pBt);
1360       if( p->rc==SQLITE_OK ) p->rc = rc;
1361     }
1362   }
1363 
1364   /* If this was an INSERT, UPDATE or DELETE, set the change counter. */
1365   if( p->changeCntOn && p->pc>=0 ){
1366     if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
1367       sqlite3VdbeSetChanges(db, p->nChange);
1368     }else{
1369       sqlite3VdbeSetChanges(db, 0);
1370     }
1371     p->nChange = 0;
1372   }
1373 
1374   /* Rollback or commit any schema changes that occurred. */
1375   if( p->rc!=SQLITE_OK ){
1376     sqlite3RollbackInternalChanges(db);
1377   }else if( db->flags & SQLITE_InternChanges ){
1378     sqlite3CommitInternalChanges(db);
1379   }
1380 
1381   /* We have successfully halted and closed the VM.  Record this fact. */
1382   if( p->pc>=0 ){
1383     db->activeVdbeCnt--;
1384   }
1385   p->magic = VDBE_MAGIC_HALT;
1386   checkActiveVdbeCnt(db);
1387 
1388   return SQLITE_OK;
1389 }
1390 
1391 /*
1392 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
1393 ** Write any error messages into *pzErrMsg.  Return the result code.
1394 **
1395 ** After this routine is run, the VDBE should be ready to be executed
1396 ** again.
1397 **
1398 ** To look at it another way, this routine resets the state of the
1399 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
1400 ** VDBE_MAGIC_INIT.
1401 */
1402 int sqlite3VdbeReset(Vdbe *p){
1403   if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
1404     sqlite3Error(p->db, SQLITE_MISUSE, 0);
1405     return SQLITE_MISUSE;
1406   }
1407 
1408   /* If the VM did not run to completion or if it encountered an
1409   ** error, then it might not have been halted properly.  So halt
1410   ** it now.
1411   */
1412   sqlite3VdbeHalt(p);
1413 
1414   /* If the VDBE has be run even partially, then transfer the error code
1415   ** and error message from the VDBE into the main database structure.  But
1416   ** if the VDBE has just been set to run but has not actually executed any
1417   ** instructions yet, leave the main database error information unchanged.
1418   */
1419   if( p->pc>=0 ){
1420     if( p->zErrMsg ){
1421       sqlite3Error(p->db, p->rc, "%s", p->zErrMsg);
1422       sqliteFree(p->zErrMsg);
1423       p->zErrMsg = 0;
1424     }else if( p->rc ){
1425       sqlite3Error(p->db, p->rc, 0);
1426     }else{
1427       sqlite3Error(p->db, SQLITE_OK, 0);
1428     }
1429   }else if( p->rc && p->expired ){
1430     /* The expired flag was set on the VDBE before the first call
1431     ** to sqlite3_step(). For consistency (since sqlite3_step() was
1432     ** called), set the database error in this case as well.
1433     */
1434     sqlite3Error(p->db, p->rc, 0);
1435   }
1436 
1437   /* Reclaim all memory used by the VDBE
1438   */
1439   Cleanup(p);
1440 
1441   /* Save profiling information from this VDBE run.
1442   */
1443   assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || sqlite3_malloc_failed==1 );
1444 #ifdef VDBE_PROFILE
1445   {
1446     FILE *out = fopen("vdbe_profile.out", "a");
1447     if( out ){
1448       int i;
1449       fprintf(out, "---- ");
1450       for(i=0; i<p->nOp; i++){
1451         fprintf(out, "%02x", p->aOp[i].opcode);
1452       }
1453       fprintf(out, "\n");
1454       for(i=0; i<p->nOp; i++){
1455         fprintf(out, "%6d %10lld %8lld ",
1456            p->aOp[i].cnt,
1457            p->aOp[i].cycles,
1458            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
1459         );
1460         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
1461       }
1462       fclose(out);
1463     }
1464   }
1465 #endif
1466   p->magic = VDBE_MAGIC_INIT;
1467   p->aborted = 0;
1468   if( p->rc==SQLITE_SCHEMA ){
1469     sqlite3ResetInternalSchema(p->db, 0);
1470   }
1471   return p->rc;
1472 }
1473 
1474 /*
1475 ** Clean up and delete a VDBE after execution.  Return an integer which is
1476 ** the result code.  Write any error message text into *pzErrMsg.
1477 */
1478 int sqlite3VdbeFinalize(Vdbe *p){
1479   int rc = SQLITE_OK;
1480 
1481   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
1482     rc = sqlite3VdbeReset(p);
1483   }else if( p->magic!=VDBE_MAGIC_INIT ){
1484     return SQLITE_MISUSE;
1485   }
1486   sqlite3VdbeDelete(p);
1487   return rc;
1488 }
1489 
1490 /*
1491 ** Call the destructor for each auxdata entry in pVdbeFunc for which
1492 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
1493 ** are always destroyed.  To destroy all auxdata entries, call this
1494 ** routine with mask==0.
1495 */
1496 void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
1497   int i;
1498   for(i=0; i<pVdbeFunc->nAux; i++){
1499     struct AuxData *pAux = &pVdbeFunc->apAux[i];
1500     if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
1501       if( pAux->xDelete ){
1502         pAux->xDelete(pAux->pAux);
1503       }
1504       pAux->pAux = 0;
1505     }
1506   }
1507 }
1508 
1509 /*
1510 ** Delete an entire VDBE.
1511 */
1512 void sqlite3VdbeDelete(Vdbe *p){
1513   int i;
1514   if( p==0 ) return;
1515   Cleanup(p);
1516   if( p->pPrev ){
1517     p->pPrev->pNext = p->pNext;
1518   }else{
1519     assert( p->db->pVdbe==p );
1520     p->db->pVdbe = p->pNext;
1521   }
1522   if( p->pNext ){
1523     p->pNext->pPrev = p->pPrev;
1524   }
1525   if( p->aOp ){
1526     for(i=0; i<p->nOp; i++){
1527       Op *pOp = &p->aOp[i];
1528       if( pOp->p3type==P3_DYNAMIC || pOp->p3type==P3_KEYINFO ){
1529         sqliteFree(pOp->p3);
1530       }
1531       if( pOp->p3type==P3_VDBEFUNC ){
1532         VdbeFunc *pVdbeFunc = (VdbeFunc *)pOp->p3;
1533         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
1534         sqliteFree(pVdbeFunc);
1535       }
1536       if( pOp->p3type==P3_MEM ){
1537         sqlite3ValueFree((sqlite3_value*)pOp->p3);
1538       }
1539     }
1540     sqliteFree(p->aOp);
1541   }
1542   releaseMemArray(p->aVar, p->nVar);
1543   sqliteFree(p->aLabel);
1544   sqliteFree(p->aStack);
1545   releaseMemArray(p->aColName, p->nResColumn*2);
1546   sqliteFree(p->aColName);
1547   p->magic = VDBE_MAGIC_DEAD;
1548   sqliteFree(p);
1549 }
1550 
1551 /*
1552 ** If a MoveTo operation is pending on the given cursor, then do that
1553 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
1554 ** routine does nothing and returns SQLITE_OK.
1555 */
1556 int sqlite3VdbeCursorMoveto(Cursor *p){
1557   if( p->deferredMoveto ){
1558     int res, rc;
1559     extern int sqlite3_search_count;
1560     assert( p->isTable );
1561     if( p->isTable ){
1562       rc = sqlite3BtreeMoveto(p->pCursor, 0, p->movetoTarget, &res);
1563     }else{
1564       rc = sqlite3BtreeMoveto(p->pCursor,(char*)&p->movetoTarget,
1565                               sizeof(i64),&res);
1566     }
1567     if( rc ) return rc;
1568     *p->pIncrKey = 0;
1569     p->lastRowid = keyToInt(p->movetoTarget);
1570     p->rowidIsValid = res==0;
1571     if( res<0 ){
1572       rc = sqlite3BtreeNext(p->pCursor, &res);
1573       if( rc ) return rc;
1574     }
1575     sqlite3_search_count++;
1576     p->deferredMoveto = 0;
1577     p->cacheValid = 0;
1578   }
1579   return SQLITE_OK;
1580 }
1581 
1582 /*
1583 ** The following functions:
1584 **
1585 ** sqlite3VdbeSerialType()
1586 ** sqlite3VdbeSerialTypeLen()
1587 ** sqlite3VdbeSerialRead()
1588 ** sqlite3VdbeSerialLen()
1589 ** sqlite3VdbeSerialWrite()
1590 **
1591 ** encapsulate the code that serializes values for storage in SQLite
1592 ** data and index records. Each serialized value consists of a
1593 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
1594 ** integer, stored as a varint.
1595 **
1596 ** In an SQLite index record, the serial type is stored directly before
1597 ** the blob of data that it corresponds to. In a table record, all serial
1598 ** types are stored at the start of the record, and the blobs of data at
1599 ** the end. Hence these functions allow the caller to handle the
1600 ** serial-type and data blob seperately.
1601 **
1602 ** The following table describes the various storage classes for data:
1603 **
1604 **   serial type        bytes of data      type
1605 **   --------------     ---------------    ---------------
1606 **      0                     0            NULL
1607 **      1                     1            signed integer
1608 **      2                     2            signed integer
1609 **      3                     3            signed integer
1610 **      4                     4            signed integer
1611 **      5                     6            signed integer
1612 **      6                     8            signed integer
1613 **      7                     8            IEEE float
1614 **     8-11                                reserved for expansion
1615 **    N>=12 and even       (N-12)/2        BLOB
1616 **    N>=13 and odd        (N-13)/2        text
1617 **
1618 */
1619 
1620 /*
1621 ** Return the serial-type for the value stored in pMem.
1622 */
1623 u32 sqlite3VdbeSerialType(Mem *pMem){
1624   int flags = pMem->flags;
1625 
1626   if( flags&MEM_Null ){
1627     return 0;
1628   }
1629   if( flags&MEM_Int ){
1630     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
1631 #   define MAX_6BYTE ((((i64)0x00001000)<<32)-1)
1632     i64 i = pMem->i;
1633     u64 u = i<0 ? -i : i;
1634     if( u<=127 ) return 1;
1635     if( u<=32767 ) return 2;
1636     if( u<=8388607 ) return 3;
1637     if( u<=2147483647 ) return 4;
1638     if( u<=MAX_6BYTE ) return 5;
1639     return 6;
1640   }
1641   if( flags&MEM_Real ){
1642     return 7;
1643   }
1644   if( flags&MEM_Str ){
1645     int n = pMem->n;
1646     assert( n>=0 );
1647     return ((n*2) + 13);
1648   }
1649   if( flags&MEM_Blob ){
1650     return (pMem->n*2 + 12);
1651   }
1652   return 0;
1653 }
1654 
1655 /*
1656 ** Return the length of the data corresponding to the supplied serial-type.
1657 */
1658 int sqlite3VdbeSerialTypeLen(u32 serial_type){
1659   if( serial_type>=12 ){
1660     return (serial_type-12)/2;
1661   }else{
1662     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
1663     return aSize[serial_type];
1664   }
1665 }
1666 
1667 /*
1668 ** Write the serialized data blob for the value stored in pMem into
1669 ** buf. It is assumed that the caller has allocated sufficient space.
1670 ** Return the number of bytes written.
1671 */
1672 int sqlite3VdbeSerialPut(unsigned char *buf, Mem *pMem){
1673   u32 serial_type = sqlite3VdbeSerialType(pMem);
1674   int len;
1675 
1676   /* NULL */
1677   if( serial_type==0 ){
1678     return 0;
1679   }
1680 
1681   /* Integer and Real */
1682   if( serial_type<=7 ){
1683     u64 v;
1684     int i;
1685     if( serial_type==7 ){
1686       v = *(u64*)&pMem->r;
1687     }else{
1688       v = *(u64*)&pMem->i;
1689     }
1690     len = i = sqlite3VdbeSerialTypeLen(serial_type);
1691     while( i-- ){
1692       buf[i] = (v&0xFF);
1693       v >>= 8;
1694     }
1695     return len;
1696   }
1697 
1698   /* String or blob */
1699   assert( serial_type>=12 );
1700   len = sqlite3VdbeSerialTypeLen(serial_type);
1701   memcpy(buf, pMem->z, len);
1702   return len;
1703 }
1704 
1705 /*
1706 ** Deserialize the data blob pointed to by buf as serial type serial_type
1707 ** and store the result in pMem.  Return the number of bytes read.
1708 */
1709 int sqlite3VdbeSerialGet(
1710   const unsigned char *buf,     /* Buffer to deserialize from */
1711   u32 serial_type,              /* Serial type to deserialize */
1712   Mem *pMem                     /* Memory cell to write value into */
1713 ){
1714   switch( serial_type ){
1715     case 8:    /* Reserved for future use */
1716     case 9:    /* Reserved for future use */
1717     case 10:   /* Reserved for future use */
1718     case 11:   /* Reserved for future use */
1719     case 0: {  /* NULL */
1720       pMem->flags = MEM_Null;
1721       break;
1722     }
1723     case 1: { /* 1-byte signed integer */
1724       pMem->i = (signed char)buf[0];
1725       pMem->flags = MEM_Int;
1726       return 1;
1727     }
1728     case 2: { /* 2-byte signed integer */
1729       pMem->i = (((signed char)buf[0])<<8) | buf[1];
1730       pMem->flags = MEM_Int;
1731       return 2;
1732     }
1733     case 3: { /* 3-byte signed integer */
1734       pMem->i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
1735       pMem->flags = MEM_Int;
1736       return 3;
1737     }
1738     case 4: { /* 4-byte signed integer */
1739       pMem->i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
1740       pMem->flags = MEM_Int;
1741       return 4;
1742     }
1743     case 5: { /* 6-byte signed integer */
1744       u64 x = (((signed char)buf[0])<<8) | buf[1];
1745       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
1746       x = (x<<32) | y;
1747       pMem->i = *(i64*)&x;
1748       pMem->flags = MEM_Int;
1749       return 6;
1750     }
1751     case 6:   /* 6-byte signed integer */
1752     case 7: { /* IEEE floating point */
1753       u64 x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
1754       u32 y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
1755       x = (x<<32) | y;
1756       if( serial_type==6 ){
1757         pMem->i = *(i64*)&x;
1758         pMem->flags = MEM_Int;
1759       }else{
1760         pMem->r = *(double*)&x;
1761         pMem->flags = MEM_Real;
1762       }
1763       return 8;
1764     }
1765     default: {
1766       int len = (serial_type-12)/2;
1767       pMem->z = (char *)buf;
1768       pMem->n = len;
1769       pMem->xDel = 0;
1770       if( serial_type&0x01 ){
1771         pMem->flags = MEM_Str | MEM_Ephem;
1772       }else{
1773         pMem->flags = MEM_Blob | MEM_Ephem;
1774       }
1775       return len;
1776     }
1777   }
1778   return 0;
1779 }
1780 
1781 /*
1782 ** This function compares the two table rows or index records specified by
1783 ** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
1784 ** or positive integer if {nKey1, pKey1} is less than, equal to or
1785 ** greater than {nKey2, pKey2}.  Both Key1 and Key2 must be byte strings
1786 ** composed by the OP_MakeRecord opcode of the VDBE.
1787 */
1788 int sqlite3VdbeRecordCompare(
1789   void *userData,
1790   int nKey1, const void *pKey1,
1791   int nKey2, const void *pKey2
1792 ){
1793   KeyInfo *pKeyInfo = (KeyInfo*)userData;
1794   u32 d1, d2;          /* Offset into aKey[] of next data element */
1795   u32 idx1, idx2;      /* Offset into aKey[] of next header element */
1796   u32 szHdr1, szHdr2;  /* Number of bytes in header */
1797   int i = 0;
1798   int nField;
1799   int rc = 0;
1800   const unsigned char *aKey1 = (const unsigned char *)pKey1;
1801   const unsigned char *aKey2 = (const unsigned char *)pKey2;
1802 
1803   Mem mem1;
1804   Mem mem2;
1805   mem1.enc = pKeyInfo->enc;
1806   mem2.enc = pKeyInfo->enc;
1807 
1808   idx1 = sqlite3GetVarint32(pKey1, &szHdr1);
1809   d1 = szHdr1;
1810   idx2 = sqlite3GetVarint32(pKey2, &szHdr2);
1811   d2 = szHdr2;
1812   nField = pKeyInfo->nField;
1813   while( idx1<szHdr1 && idx2<szHdr2 ){
1814     u32 serial_type1;
1815     u32 serial_type2;
1816 
1817     /* Read the serial types for the next element in each key. */
1818     idx1 += sqlite3GetVarint32(&aKey1[idx1], &serial_type1);
1819     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
1820     idx2 += sqlite3GetVarint32(&aKey2[idx2], &serial_type2);
1821     if( d2>=nKey2 && sqlite3VdbeSerialTypeLen(serial_type2)>0 ) break;
1822 
1823     /* Assert that there is enough space left in each key for the blob of
1824     ** data to go with the serial type just read. This assert may fail if
1825     ** the file is corrupted.  Then read the value from each key into mem1
1826     ** and mem2 respectively.
1827     */
1828     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
1829     d2 += sqlite3VdbeSerialGet(&aKey2[d2], serial_type2, &mem2);
1830 
1831     rc = sqlite3MemCompare(&mem1, &mem2, i<nField ? pKeyInfo->aColl[i] : 0);
1832     if( mem1.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem1);
1833     if( mem2.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem2);
1834     if( rc!=0 ){
1835       break;
1836     }
1837     i++;
1838   }
1839 
1840   /* One of the keys ran out of fields, but all the fields up to that point
1841   ** were equal. If the incrKey flag is true, then the second key is
1842   ** treated as larger.
1843   */
1844   if( rc==0 ){
1845     if( pKeyInfo->incrKey ){
1846       rc = -1;
1847     }else if( d1<nKey1 ){
1848       rc = 1;
1849     }else if( d2<nKey2 ){
1850       rc = -1;
1851     }
1852   }
1853 
1854   if( pKeyInfo->aSortOrder && i<pKeyInfo->nField && pKeyInfo->aSortOrder[i] ){
1855     rc = -rc;
1856   }
1857 
1858   return rc;
1859 }
1860 
1861 /*
1862 ** The argument is an index entry composed using the OP_MakeRecord opcode.
1863 ** The last entry in this record should be an integer (specifically
1864 ** an integer rowid).  This routine returns the number of bytes in
1865 ** that integer.
1866 */
1867 int sqlite3VdbeIdxRowidLen(int nKey, const u8 *aKey){
1868   u32 szHdr;        /* Size of the header */
1869   u32 typeRowid;    /* Serial type of the rowid */
1870 
1871   sqlite3GetVarint32(aKey, &szHdr);
1872   sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
1873   return sqlite3VdbeSerialTypeLen(typeRowid);
1874 }
1875 
1876 
1877 /*
1878 ** pCur points at an index entry created using the OP_MakeRecord opcode.
1879 ** Read the rowid (the last field in the record) and store it in *rowid.
1880 ** Return SQLITE_OK if everything works, or an error code otherwise.
1881 */
1882 int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
1883   i64 nCellKey;
1884   int rc;
1885   u32 szHdr;        /* Size of the header */
1886   u32 typeRowid;    /* Serial type of the rowid */
1887   u32 lenRowid;     /* Size of the rowid */
1888   Mem m, v;
1889 
1890   sqlite3BtreeKeySize(pCur, &nCellKey);
1891   if( nCellKey<=0 ){
1892     return SQLITE_CORRUPT;
1893   }
1894   rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
1895   if( rc ){
1896     return rc;
1897   }
1898   sqlite3GetVarint32(m.z, &szHdr);
1899   sqlite3GetVarint32(&m.z[szHdr-1], &typeRowid);
1900   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
1901   sqlite3VdbeSerialGet(&m.z[m.n-lenRowid], typeRowid, &v);
1902   *rowid = v.i;
1903   sqlite3VdbeMemRelease(&m);
1904   return SQLITE_OK;
1905 }
1906 
1907 /*
1908 ** Compare the key of the index entry that cursor pC is point to against
1909 ** the key string in pKey (of length nKey).  Write into *pRes a number
1910 ** that is negative, zero, or positive if pC is less than, equal to,
1911 ** or greater than pKey.  Return SQLITE_OK on success.
1912 **
1913 ** pKey is either created without a rowid or is truncated so that it
1914 ** omits the rowid at the end.  The rowid at the end of the index entry
1915 ** is ignored as well.
1916 */
1917 int sqlite3VdbeIdxKeyCompare(
1918   Cursor *pC,                 /* The cursor to compare against */
1919   int nKey, const u8 *pKey,   /* The key to compare */
1920   int *res                    /* Write the comparison result here */
1921 ){
1922   i64 nCellKey;
1923   int rc;
1924   BtCursor *pCur = pC->pCursor;
1925   int lenRowid;
1926   Mem m;
1927 
1928   sqlite3BtreeKeySize(pCur, &nCellKey);
1929   if( nCellKey<=0 ){
1930     *res = 0;
1931     return SQLITE_OK;
1932   }
1933   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
1934   if( rc ){
1935     return rc;
1936   }
1937   lenRowid = sqlite3VdbeIdxRowidLen(m.n, m.z);
1938   *res = sqlite3VdbeRecordCompare(pC->pKeyInfo, m.n-lenRowid, m.z, nKey, pKey);
1939   sqlite3VdbeMemRelease(&m);
1940   return SQLITE_OK;
1941 }
1942 
1943 /*
1944 ** This routine sets the value to be returned by subsequent calls to
1945 ** sqlite3_changes() on the database handle 'db'.
1946 */
1947 void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
1948   db->nChange = nChange;
1949   db->nTotalChange += nChange;
1950 }
1951 
1952 /*
1953 ** Set a flag in the vdbe to update the change counter when it is finalised
1954 ** or reset.
1955 */
1956 void sqlite3VdbeCountChanges(Vdbe *v){
1957   v->changeCntOn = 1;
1958 }
1959 
1960 /*
1961 ** Mark every prepared statement associated with a database connection
1962 ** as expired.
1963 **
1964 ** An expired statement means that recompilation of the statement is
1965 ** recommend.  Statements expire when things happen that make their
1966 ** programs obsolete.  Removing user-defined functions or collating
1967 ** sequences, or changing an authorization function are the types of
1968 ** things that make prepared statements obsolete.
1969 */
1970 void sqlite3ExpirePreparedStatements(sqlite3 *db){
1971   Vdbe *p;
1972   for(p = db->pVdbe; p; p=p->pNext){
1973     p->expired = 1;
1974   }
1975 }
1976 
1977 /*
1978 ** Return the database associated with the Vdbe.
1979 */
1980 sqlite3 *sqlite3VdbeDb(Vdbe *v){
1981   return v->db;
1982 }
1983