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