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