xref: /sqlite-3.40.0/src/vdbeaux.c (revision 60176fa9)
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   if( rc!=SQLITE_OK ){
1650     return rc;
1651   }
1652 
1653   /* This loop determines (a) if the commit hook should be invoked and
1654   ** (b) how many database files have open write transactions, not
1655   ** including the temp database. (b) is important because if more than
1656   ** one database file has an open write transaction, a master journal
1657   ** file is required for an atomic commit.
1658   */
1659   for(i=0; i<db->nDb; i++){
1660     Btree *pBt = db->aDb[i].pBt;
1661     if( sqlite3BtreeIsInTrans(pBt) ){
1662       needXcommit = 1;
1663       if( i!=1 ) nTrans++;
1664     }
1665   }
1666 
1667   /* If there are any write-transactions at all, invoke the commit hook */
1668   if( needXcommit && db->xCommitCallback ){
1669     rc = db->xCommitCallback(db->pCommitArg);
1670     if( rc ){
1671       return SQLITE_CONSTRAINT;
1672     }
1673   }
1674 
1675   /* The simple case - no more than one database file (not counting the
1676   ** TEMP database) has a transaction active.   There is no need for the
1677   ** master-journal.
1678   **
1679   ** If the return value of sqlite3BtreeGetFilename() is a zero length
1680   ** string, it means the main database is :memory: or a temp file.  In
1681   ** that case we do not support atomic multi-file commits, so use the
1682   ** simple case then too.
1683   */
1684   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
1685    || nTrans<=1
1686   ){
1687     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1688       Btree *pBt = db->aDb[i].pBt;
1689       if( pBt ){
1690         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
1691       }
1692     }
1693 
1694     /* Do the commit only if all databases successfully complete phase 1.
1695     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
1696     ** IO error while deleting or truncating a journal file. It is unlikely,
1697     ** but could happen. In this case abandon processing and return the error.
1698     */
1699     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1700       Btree *pBt = db->aDb[i].pBt;
1701       if( pBt ){
1702         rc = sqlite3BtreeCommitPhaseTwo(pBt);
1703       }
1704     }
1705     if( rc==SQLITE_OK ){
1706       sqlite3VtabCommit(db);
1707     }
1708   }
1709 
1710   /* The complex case - There is a multi-file write-transaction active.
1711   ** This requires a master journal file to ensure the transaction is
1712   ** committed atomicly.
1713   */
1714 #ifndef SQLITE_OMIT_DISKIO
1715   else{
1716     sqlite3_vfs *pVfs = db->pVfs;
1717     int needSync = 0;
1718     char *zMaster = 0;   /* File-name for the master journal */
1719     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
1720     sqlite3_file *pMaster = 0;
1721     i64 offset = 0;
1722     int res;
1723 
1724     /* Select a master journal file name */
1725     do {
1726       u32 iRandom;
1727       sqlite3DbFree(db, zMaster);
1728       sqlite3_randomness(sizeof(iRandom), &iRandom);
1729       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
1730       if( !zMaster ){
1731         return SQLITE_NOMEM;
1732       }
1733       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
1734     }while( rc==SQLITE_OK && res );
1735     if( rc==SQLITE_OK ){
1736       /* Open the master journal. */
1737       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
1738           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
1739           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
1740       );
1741     }
1742     if( rc!=SQLITE_OK ){
1743       sqlite3DbFree(db, zMaster);
1744       return rc;
1745     }
1746 
1747     /* Write the name of each database file in the transaction into the new
1748     ** master journal file. If an error occurs at this point close
1749     ** and delete the master journal file. All the individual journal files
1750     ** still have 'null' as the master journal pointer, so they will roll
1751     ** back independently if a failure occurs.
1752     */
1753     for(i=0; i<db->nDb; i++){
1754       Btree *pBt = db->aDb[i].pBt;
1755       if( sqlite3BtreeIsInTrans(pBt) ){
1756         char const *zFile = sqlite3BtreeGetJournalname(pBt);
1757         if( zFile==0 || zFile[0]==0 ){
1758           continue;  /* Ignore TEMP and :memory: databases */
1759         }
1760         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
1761           needSync = 1;
1762         }
1763         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
1764         offset += sqlite3Strlen30(zFile)+1;
1765         if( rc!=SQLITE_OK ){
1766           sqlite3OsCloseFree(pMaster);
1767           sqlite3OsDelete(pVfs, zMaster, 0);
1768           sqlite3DbFree(db, zMaster);
1769           return rc;
1770         }
1771       }
1772     }
1773 
1774     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
1775     ** flag is set this is not required.
1776     */
1777     if( needSync
1778      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
1779      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
1780     ){
1781       sqlite3OsCloseFree(pMaster);
1782       sqlite3OsDelete(pVfs, zMaster, 0);
1783       sqlite3DbFree(db, zMaster);
1784       return rc;
1785     }
1786 
1787     /* Sync all the db files involved in the transaction. The same call
1788     ** sets the master journal pointer in each individual journal. If
1789     ** an error occurs here, do not delete the master journal file.
1790     **
1791     ** If the error occurs during the first call to
1792     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
1793     ** master journal file will be orphaned. But we cannot delete it,
1794     ** in case the master journal file name was written into the journal
1795     ** file before the failure occurred.
1796     */
1797     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1798       Btree *pBt = db->aDb[i].pBt;
1799       if( pBt ){
1800         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
1801       }
1802     }
1803     sqlite3OsCloseFree(pMaster);
1804     if( rc!=SQLITE_OK ){
1805       sqlite3DbFree(db, zMaster);
1806       return rc;
1807     }
1808 
1809     /* Delete the master journal file. This commits the transaction. After
1810     ** doing this the directory is synced again before any individual
1811     ** transaction files are deleted.
1812     */
1813     rc = sqlite3OsDelete(pVfs, zMaster, 1);
1814     sqlite3DbFree(db, zMaster);
1815     zMaster = 0;
1816     if( rc ){
1817       return rc;
1818     }
1819 
1820     /* All files and directories have already been synced, so the following
1821     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
1822     ** deleting or truncating journals. If something goes wrong while
1823     ** this is happening we don't really care. The integrity of the
1824     ** transaction is already guaranteed, but some stray 'cold' journals
1825     ** may be lying around. Returning an error code won't help matters.
1826     */
1827     disable_simulated_io_errors();
1828     sqlite3BeginBenignMalloc();
1829     for(i=0; i<db->nDb; i++){
1830       Btree *pBt = db->aDb[i].pBt;
1831       if( pBt ){
1832         sqlite3BtreeCommitPhaseTwo(pBt);
1833       }
1834     }
1835     sqlite3EndBenignMalloc();
1836     enable_simulated_io_errors();
1837 
1838     sqlite3VtabCommit(db);
1839   }
1840 #endif
1841 
1842   return rc;
1843 }
1844 
1845 /*
1846 ** This routine checks that the sqlite3.activeVdbeCnt count variable
1847 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
1848 ** currently active. An assertion fails if the two counts do not match.
1849 ** This is an internal self-check only - it is not an essential processing
1850 ** step.
1851 **
1852 ** This is a no-op if NDEBUG is defined.
1853 */
1854 #ifndef NDEBUG
1855 static void checkActiveVdbeCnt(sqlite3 *db){
1856   Vdbe *p;
1857   int cnt = 0;
1858   int nWrite = 0;
1859   p = db->pVdbe;
1860   while( p ){
1861     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
1862       cnt++;
1863       if( p->readOnly==0 ) nWrite++;
1864     }
1865     p = p->pNext;
1866   }
1867   assert( cnt==db->activeVdbeCnt );
1868   assert( nWrite==db->writeVdbeCnt );
1869 }
1870 #else
1871 #define checkActiveVdbeCnt(x)
1872 #endif
1873 
1874 /*
1875 ** For every Btree that in database connection db which
1876 ** has been modified, "trip" or invalidate each cursor in
1877 ** that Btree might have been modified so that the cursor
1878 ** can never be used again.  This happens when a rollback
1879 *** occurs.  We have to trip all the other cursors, even
1880 ** cursor from other VMs in different database connections,
1881 ** so that none of them try to use the data at which they
1882 ** were pointing and which now may have been changed due
1883 ** to the rollback.
1884 **
1885 ** Remember that a rollback can delete tables complete and
1886 ** reorder rootpages.  So it is not sufficient just to save
1887 ** the state of the cursor.  We have to invalidate the cursor
1888 ** so that it is never used again.
1889 */
1890 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
1891   int i;
1892   for(i=0; i<db->nDb; i++){
1893     Btree *p = db->aDb[i].pBt;
1894     if( p && sqlite3BtreeIsInTrans(p) ){
1895       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
1896     }
1897   }
1898 }
1899 
1900 /*
1901 ** If the Vdbe passed as the first argument opened a statement-transaction,
1902 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
1903 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
1904 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
1905 ** statement transaction is commtted.
1906 **
1907 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
1908 ** Otherwise SQLITE_OK.
1909 */
1910 int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
1911   sqlite3 *const db = p->db;
1912   int rc = SQLITE_OK;
1913 
1914   /* If p->iStatement is greater than zero, then this Vdbe opened a
1915   ** statement transaction that should be closed here. The only exception
1916   ** is that an IO error may have occured, causing an emergency rollback.
1917   ** In this case (db->nStatement==0), and there is nothing to do.
1918   */
1919   if( db->nStatement && p->iStatement ){
1920     int i;
1921     const int iSavepoint = p->iStatement-1;
1922 
1923     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
1924     assert( db->nStatement>0 );
1925     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
1926 
1927     for(i=0; i<db->nDb; i++){
1928       int rc2 = SQLITE_OK;
1929       Btree *pBt = db->aDb[i].pBt;
1930       if( pBt ){
1931         if( eOp==SAVEPOINT_ROLLBACK ){
1932           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
1933         }
1934         if( rc2==SQLITE_OK ){
1935           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
1936         }
1937         if( rc==SQLITE_OK ){
1938           rc = rc2;
1939         }
1940       }
1941     }
1942     db->nStatement--;
1943     p->iStatement = 0;
1944 
1945     /* If the statement transaction is being rolled back, also restore the
1946     ** database handles deferred constraint counter to the value it had when
1947     ** the statement transaction was opened.  */
1948     if( eOp==SAVEPOINT_ROLLBACK ){
1949       db->nDeferredCons = p->nStmtDefCons;
1950     }
1951   }
1952   return rc;
1953 }
1954 
1955 /*
1956 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
1957 ** this routine obtains the mutex associated with each BtShared structure
1958 ** that may be accessed by the VM passed as an argument. In doing so it
1959 ** sets the BtShared.db member of each of the BtShared structures, ensuring
1960 ** that the correct busy-handler callback is invoked if required.
1961 **
1962 ** If SQLite is not threadsafe but does support shared-cache mode, then
1963 ** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
1964 ** of all of BtShared structures accessible via the database handle
1965 ** associated with the VM. Of course only a subset of these structures
1966 ** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
1967 ** that subset out, but there is no advantage to doing so.
1968 **
1969 ** If SQLite is not threadsafe and does not support shared-cache mode, this
1970 ** function is a no-op.
1971 */
1972 #ifndef SQLITE_OMIT_SHARED_CACHE
1973 void sqlite3VdbeMutexArrayEnter(Vdbe *p){
1974 #if SQLITE_THREADSAFE
1975   sqlite3BtreeMutexArrayEnter(&p->aMutex);
1976 #else
1977   sqlite3BtreeEnterAll(p->db);
1978 #endif
1979 }
1980 #endif
1981 
1982 /*
1983 ** This function is called when a transaction opened by the database
1984 ** handle associated with the VM passed as an argument is about to be
1985 ** committed. If there are outstanding deferred foreign key constraint
1986 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
1987 **
1988 ** If there are outstanding FK violations and this function returns
1989 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
1990 ** an error message to it. Then return SQLITE_ERROR.
1991 */
1992 #ifndef SQLITE_OMIT_FOREIGN_KEY
1993 int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
1994   sqlite3 *db = p->db;
1995   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
1996     p->rc = SQLITE_CONSTRAINT;
1997     p->errorAction = OE_Abort;
1998     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
1999     return SQLITE_ERROR;
2000   }
2001   return SQLITE_OK;
2002 }
2003 #endif
2004 
2005 /*
2006 ** This routine is called the when a VDBE tries to halt.  If the VDBE
2007 ** has made changes and is in autocommit mode, then commit those
2008 ** changes.  If a rollback is needed, then do the rollback.
2009 **
2010 ** This routine is the only way to move the state of a VM from
2011 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
2012 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
2013 **
2014 ** Return an error code.  If the commit could not complete because of
2015 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
2016 ** means the close did not happen and needs to be repeated.
2017 */
2018 int sqlite3VdbeHalt(Vdbe *p){
2019   int rc;                         /* Used to store transient return codes */
2020   sqlite3 *db = p->db;
2021 
2022   /* This function contains the logic that determines if a statement or
2023   ** transaction will be committed or rolled back as a result of the
2024   ** execution of this virtual machine.
2025   **
2026   ** If any of the following errors occur:
2027   **
2028   **     SQLITE_NOMEM
2029   **     SQLITE_IOERR
2030   **     SQLITE_FULL
2031   **     SQLITE_INTERRUPT
2032   **
2033   ** Then the internal cache might have been left in an inconsistent
2034   ** state.  We need to rollback the statement transaction, if there is
2035   ** one, or the complete transaction if there is no statement transaction.
2036   */
2037 
2038   if( p->db->mallocFailed ){
2039     p->rc = SQLITE_NOMEM;
2040   }
2041   closeAllCursors(p);
2042   if( p->magic!=VDBE_MAGIC_RUN ){
2043     return SQLITE_OK;
2044   }
2045   checkActiveVdbeCnt(db);
2046 
2047   /* No commit or rollback needed if the program never started */
2048   if( p->pc>=0 ){
2049     int mrc;   /* Primary error code from p->rc */
2050     int eStatementOp = 0;
2051     int isSpecialError;            /* Set to true if a 'special' error */
2052 
2053     /* Lock all btrees used by the statement */
2054     sqlite3VdbeMutexArrayEnter(p);
2055 
2056     /* Check for one of the special errors */
2057     mrc = p->rc & 0xff;
2058     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
2059     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
2060                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
2061     if( isSpecialError ){
2062       /* If the query was read-only, we need do no rollback at all. Otherwise,
2063       ** proceed with the special handling.
2064       */
2065       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
2066         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
2067           eStatementOp = SAVEPOINT_ROLLBACK;
2068         }else{
2069           /* We are forced to roll back the active transaction. Before doing
2070           ** so, abort any other statements this handle currently has active.
2071           */
2072           invalidateCursorsOnModifiedBtrees(db);
2073           sqlite3RollbackAll(db);
2074           sqlite3CloseSavepoints(db);
2075           db->autoCommit = 1;
2076         }
2077       }
2078     }
2079 
2080     /* Check for immediate foreign key violations. */
2081     if( p->rc==SQLITE_OK ){
2082       sqlite3VdbeCheckFk(p, 0);
2083     }
2084 
2085     /* If the auto-commit flag is set and this is the only active writer
2086     ** VM, then we do either a commit or rollback of the current transaction.
2087     **
2088     ** Note: This block also runs if one of the special errors handled
2089     ** above has occurred.
2090     */
2091     if( !sqlite3VtabInSync(db)
2092      && db->autoCommit
2093      && db->writeVdbeCnt==(p->readOnly==0)
2094     ){
2095       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
2096         if( sqlite3VdbeCheckFk(p, 1) ){
2097           sqlite3BtreeMutexArrayLeave(&p->aMutex);
2098           return SQLITE_ERROR;
2099         }
2100         /* The auto-commit flag is true, the vdbe program was successful
2101         ** or hit an 'OR FAIL' constraint and there are no deferred foreign
2102         ** key constraints to hold up the transaction. This means a commit
2103         ** is required.  */
2104         rc = vdbeCommit(db, p);
2105         if( rc==SQLITE_BUSY ){
2106           sqlite3BtreeMutexArrayLeave(&p->aMutex);
2107           return SQLITE_BUSY;
2108         }else if( rc!=SQLITE_OK ){
2109           p->rc = rc;
2110           sqlite3RollbackAll(db);
2111         }else{
2112           db->nDeferredCons = 0;
2113           sqlite3CommitInternalChanges(db);
2114         }
2115       }else{
2116         sqlite3RollbackAll(db);
2117       }
2118       db->nStatement = 0;
2119     }else if( eStatementOp==0 ){
2120       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
2121         eStatementOp = SAVEPOINT_RELEASE;
2122       }else if( p->errorAction==OE_Abort ){
2123         eStatementOp = SAVEPOINT_ROLLBACK;
2124       }else{
2125         invalidateCursorsOnModifiedBtrees(db);
2126         sqlite3RollbackAll(db);
2127         sqlite3CloseSavepoints(db);
2128         db->autoCommit = 1;
2129       }
2130     }
2131 
2132     /* If eStatementOp is non-zero, then a statement transaction needs to
2133     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
2134     ** do so. If this operation returns an error, and the current statement
2135     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
2136     ** current statement error code.
2137     **
2138     ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
2139     ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
2140     ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in
2141     ** the following code.
2142     */
2143     if( eStatementOp ){
2144       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
2145       if( rc ){
2146         assert( eStatementOp==SAVEPOINT_ROLLBACK );
2147         if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
2148           p->rc = rc;
2149           sqlite3DbFree(db, p->zErrMsg);
2150           p->zErrMsg = 0;
2151         }
2152         invalidateCursorsOnModifiedBtrees(db);
2153         sqlite3RollbackAll(db);
2154         sqlite3CloseSavepoints(db);
2155         db->autoCommit = 1;
2156       }
2157     }
2158 
2159     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
2160     ** has been rolled back, update the database connection change-counter.
2161     */
2162     if( p->changeCntOn ){
2163       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
2164         sqlite3VdbeSetChanges(db, p->nChange);
2165       }else{
2166         sqlite3VdbeSetChanges(db, 0);
2167       }
2168       p->nChange = 0;
2169     }
2170 
2171     /* Rollback or commit any schema changes that occurred. */
2172     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
2173       sqlite3ResetInternalSchema(db, 0);
2174       db->flags = (db->flags | SQLITE_InternChanges);
2175     }
2176 
2177     /* Release the locks */
2178     sqlite3BtreeMutexArrayLeave(&p->aMutex);
2179   }
2180 
2181   /* We have successfully halted and closed the VM.  Record this fact. */
2182   if( p->pc>=0 ){
2183     db->activeVdbeCnt--;
2184     if( !p->readOnly ){
2185       db->writeVdbeCnt--;
2186     }
2187     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
2188   }
2189   p->magic = VDBE_MAGIC_HALT;
2190   checkActiveVdbeCnt(db);
2191   if( p->db->mallocFailed ){
2192     p->rc = SQLITE_NOMEM;
2193   }
2194 
2195   /* If the auto-commit flag is set to true, then any locks that were held
2196   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
2197   ** to invoke any required unlock-notify callbacks.
2198   */
2199   if( db->autoCommit ){
2200     sqlite3ConnectionUnlocked(db);
2201   }
2202 
2203   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
2204   return SQLITE_OK;
2205 }
2206 
2207 
2208 /*
2209 ** Each VDBE holds the result of the most recent sqlite3_step() call
2210 ** in p->rc.  This routine sets that result back to SQLITE_OK.
2211 */
2212 void sqlite3VdbeResetStepResult(Vdbe *p){
2213   p->rc = SQLITE_OK;
2214 }
2215 
2216 /*
2217 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
2218 ** Write any error messages into *pzErrMsg.  Return the result code.
2219 **
2220 ** After this routine is run, the VDBE should be ready to be executed
2221 ** again.
2222 **
2223 ** To look at it another way, this routine resets the state of the
2224 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
2225 ** VDBE_MAGIC_INIT.
2226 */
2227 int sqlite3VdbeReset(Vdbe *p){
2228   sqlite3 *db;
2229   db = p->db;
2230 
2231   /* If the VM did not run to completion or if it encountered an
2232   ** error, then it might not have been halted properly.  So halt
2233   ** it now.
2234   */
2235   sqlite3VdbeHalt(p);
2236 
2237   /* If the VDBE has be run even partially, then transfer the error code
2238   ** and error message from the VDBE into the main database structure.  But
2239   ** if the VDBE has just been set to run but has not actually executed any
2240   ** instructions yet, leave the main database error information unchanged.
2241   */
2242   if( p->pc>=0 ){
2243     if( p->zErrMsg ){
2244       sqlite3BeginBenignMalloc();
2245       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
2246       sqlite3EndBenignMalloc();
2247       db->errCode = p->rc;
2248       sqlite3DbFree(db, p->zErrMsg);
2249       p->zErrMsg = 0;
2250     }else if( p->rc ){
2251       sqlite3Error(db, p->rc, 0);
2252     }else{
2253       sqlite3Error(db, SQLITE_OK, 0);
2254     }
2255     if( p->runOnlyOnce ) p->expired = 1;
2256   }else if( p->rc && p->expired ){
2257     /* The expired flag was set on the VDBE before the first call
2258     ** to sqlite3_step(). For consistency (since sqlite3_step() was
2259     ** called), set the database error in this case as well.
2260     */
2261     sqlite3Error(db, p->rc, 0);
2262     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
2263     sqlite3DbFree(db, p->zErrMsg);
2264     p->zErrMsg = 0;
2265   }
2266 
2267   /* Reclaim all memory used by the VDBE
2268   */
2269   Cleanup(p);
2270 
2271   /* Save profiling information from this VDBE run.
2272   */
2273 #ifdef VDBE_PROFILE
2274   {
2275     FILE *out = fopen("vdbe_profile.out", "a");
2276     if( out ){
2277       int i;
2278       fprintf(out, "---- ");
2279       for(i=0; i<p->nOp; i++){
2280         fprintf(out, "%02x", p->aOp[i].opcode);
2281       }
2282       fprintf(out, "\n");
2283       for(i=0; i<p->nOp; i++){
2284         fprintf(out, "%6d %10lld %8lld ",
2285            p->aOp[i].cnt,
2286            p->aOp[i].cycles,
2287            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
2288         );
2289         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
2290       }
2291       fclose(out);
2292     }
2293   }
2294 #endif
2295   p->magic = VDBE_MAGIC_INIT;
2296   return p->rc & db->errMask;
2297 }
2298 
2299 /*
2300 ** Clean up and delete a VDBE after execution.  Return an integer which is
2301 ** the result code.  Write any error message text into *pzErrMsg.
2302 */
2303 int sqlite3VdbeFinalize(Vdbe *p){
2304   int rc = SQLITE_OK;
2305   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
2306     rc = sqlite3VdbeReset(p);
2307     assert( (rc & p->db->errMask)==rc );
2308   }
2309   sqlite3VdbeDelete(p);
2310   return rc;
2311 }
2312 
2313 /*
2314 ** Call the destructor for each auxdata entry in pVdbeFunc for which
2315 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
2316 ** are always destroyed.  To destroy all auxdata entries, call this
2317 ** routine with mask==0.
2318 */
2319 void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
2320   int i;
2321   for(i=0; i<pVdbeFunc->nAux; i++){
2322     struct AuxData *pAux = &pVdbeFunc->apAux[i];
2323     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
2324       if( pAux->xDelete ){
2325         pAux->xDelete(pAux->pAux);
2326       }
2327       pAux->pAux = 0;
2328     }
2329   }
2330 }
2331 
2332 /*
2333 ** Free all memory associated with the Vdbe passed as the second argument.
2334 ** The difference between this function and sqlite3VdbeDelete() is that
2335 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
2336 ** the database connection.
2337 */
2338 void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
2339   SubProgram *pSub, *pNext;
2340   assert( p->db==0 || p->db==db );
2341   releaseMemArray(p->aVar, p->nVar);
2342   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
2343   for(pSub=p->pProgram; pSub; pSub=pNext){
2344     pNext = pSub->pNext;
2345     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
2346     sqlite3DbFree(db, pSub);
2347   }
2348   vdbeFreeOpArray(db, p->aOp, p->nOp);
2349   sqlite3DbFree(db, p->aLabel);
2350   sqlite3DbFree(db, p->aColName);
2351   sqlite3DbFree(db, p->zSql);
2352   sqlite3DbFree(db, p->pFree);
2353   sqlite3DbFree(db, p);
2354 }
2355 
2356 /*
2357 ** Delete an entire VDBE.
2358 */
2359 void sqlite3VdbeDelete(Vdbe *p){
2360   sqlite3 *db;
2361 
2362   if( NEVER(p==0) ) return;
2363   db = p->db;
2364   if( p->pPrev ){
2365     p->pPrev->pNext = p->pNext;
2366   }else{
2367     assert( db->pVdbe==p );
2368     db->pVdbe = p->pNext;
2369   }
2370   if( p->pNext ){
2371     p->pNext->pPrev = p->pPrev;
2372   }
2373   p->magic = VDBE_MAGIC_DEAD;
2374   p->db = 0;
2375   sqlite3VdbeDeleteObject(db, p);
2376 }
2377 
2378 /*
2379 ** Make sure the cursor p is ready to read or write the row to which it
2380 ** was last positioned.  Return an error code if an OOM fault or I/O error
2381 ** prevents us from positioning the cursor to its correct position.
2382 **
2383 ** If a MoveTo operation is pending on the given cursor, then do that
2384 ** MoveTo now.  If no move is pending, check to see if the row has been
2385 ** deleted out from under the cursor and if it has, mark the row as
2386 ** a NULL row.
2387 **
2388 ** If the cursor is already pointing to the correct row and that row has
2389 ** not been deleted out from under the cursor, then this routine is a no-op.
2390 */
2391 int sqlite3VdbeCursorMoveto(VdbeCursor *p){
2392   if( p->deferredMoveto ){
2393     int res, rc;
2394 #ifdef SQLITE_TEST
2395     extern int sqlite3_search_count;
2396 #endif
2397     assert( p->isTable );
2398     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
2399     if( rc ) return rc;
2400     p->lastRowid = p->movetoTarget;
2401     p->rowidIsValid = ALWAYS(res==0) ?1:0;
2402     if( NEVER(res<0) ){
2403       rc = sqlite3BtreeNext(p->pCursor, &res);
2404       if( rc ) return rc;
2405     }
2406 #ifdef SQLITE_TEST
2407     sqlite3_search_count++;
2408 #endif
2409     p->deferredMoveto = 0;
2410     p->cacheStatus = CACHE_STALE;
2411   }else if( ALWAYS(p->pCursor) ){
2412     int hasMoved;
2413     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
2414     if( rc ) return rc;
2415     if( hasMoved ){
2416       p->cacheStatus = CACHE_STALE;
2417       p->nullRow = 1;
2418     }
2419   }
2420   return SQLITE_OK;
2421 }
2422 
2423 /*
2424 ** The following functions:
2425 **
2426 ** sqlite3VdbeSerialType()
2427 ** sqlite3VdbeSerialTypeLen()
2428 ** sqlite3VdbeSerialLen()
2429 ** sqlite3VdbeSerialPut()
2430 ** sqlite3VdbeSerialGet()
2431 **
2432 ** encapsulate the code that serializes values for storage in SQLite
2433 ** data and index records. Each serialized value consists of a
2434 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
2435 ** integer, stored as a varint.
2436 **
2437 ** In an SQLite index record, the serial type is stored directly before
2438 ** the blob of data that it corresponds to. In a table record, all serial
2439 ** types are stored at the start of the record, and the blobs of data at
2440 ** the end. Hence these functions allow the caller to handle the
2441 ** serial-type and data blob seperately.
2442 **
2443 ** The following table describes the various storage classes for data:
2444 **
2445 **   serial type        bytes of data      type
2446 **   --------------     ---------------    ---------------
2447 **      0                     0            NULL
2448 **      1                     1            signed integer
2449 **      2                     2            signed integer
2450 **      3                     3            signed integer
2451 **      4                     4            signed integer
2452 **      5                     6            signed integer
2453 **      6                     8            signed integer
2454 **      7                     8            IEEE float
2455 **      8                     0            Integer constant 0
2456 **      9                     0            Integer constant 1
2457 **     10,11                               reserved for expansion
2458 **    N>=12 and even       (N-12)/2        BLOB
2459 **    N>=13 and odd        (N-13)/2        text
2460 **
2461 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
2462 ** of SQLite will not understand those serial types.
2463 */
2464 
2465 /*
2466 ** Return the serial-type for the value stored in pMem.
2467 */
2468 u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
2469   int flags = pMem->flags;
2470   int n;
2471 
2472   if( flags&MEM_Null ){
2473     return 0;
2474   }
2475   if( flags&MEM_Int ){
2476     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
2477 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
2478     i64 i = pMem->u.i;
2479     u64 u;
2480     if( file_format>=4 && (i&1)==i ){
2481       return 8+(u32)i;
2482     }
2483     u = i<0 ? -i : i;
2484     if( u<=127 ) return 1;
2485     if( u<=32767 ) return 2;
2486     if( u<=8388607 ) return 3;
2487     if( u<=2147483647 ) return 4;
2488     if( u<=MAX_6BYTE ) return 5;
2489     return 6;
2490   }
2491   if( flags&MEM_Real ){
2492     return 7;
2493   }
2494   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
2495   n = pMem->n;
2496   if( flags & MEM_Zero ){
2497     n += pMem->u.nZero;
2498   }
2499   assert( n>=0 );
2500   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
2501 }
2502 
2503 /*
2504 ** Return the length of the data corresponding to the supplied serial-type.
2505 */
2506 u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
2507   if( serial_type>=12 ){
2508     return (serial_type-12)/2;
2509   }else{
2510     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
2511     return aSize[serial_type];
2512   }
2513 }
2514 
2515 /*
2516 ** If we are on an architecture with mixed-endian floating
2517 ** points (ex: ARM7) then swap the lower 4 bytes with the
2518 ** upper 4 bytes.  Return the result.
2519 **
2520 ** For most architectures, this is a no-op.
2521 **
2522 ** (later):  It is reported to me that the mixed-endian problem
2523 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
2524 ** that early versions of GCC stored the two words of a 64-bit
2525 ** float in the wrong order.  And that error has been propagated
2526 ** ever since.  The blame is not necessarily with GCC, though.
2527 ** GCC might have just copying the problem from a prior compiler.
2528 ** I am also told that newer versions of GCC that follow a different
2529 ** ABI get the byte order right.
2530 **
2531 ** Developers using SQLite on an ARM7 should compile and run their
2532 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
2533 ** enabled, some asserts below will ensure that the byte order of
2534 ** floating point values is correct.
2535 **
2536 ** (2007-08-30)  Frank van Vugt has studied this problem closely
2537 ** and has send his findings to the SQLite developers.  Frank
2538 ** writes that some Linux kernels offer floating point hardware
2539 ** emulation that uses only 32-bit mantissas instead of a full
2540 ** 48-bits as required by the IEEE standard.  (This is the
2541 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
2542 ** byte swapping becomes very complicated.  To avoid problems,
2543 ** the necessary byte swapping is carried out using a 64-bit integer
2544 ** rather than a 64-bit float.  Frank assures us that the code here
2545 ** works for him.  We, the developers, have no way to independently
2546 ** verify this, but Frank seems to know what he is talking about
2547 ** so we trust him.
2548 */
2549 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
2550 static u64 floatSwap(u64 in){
2551   union {
2552     u64 r;
2553     u32 i[2];
2554   } u;
2555   u32 t;
2556 
2557   u.r = in;
2558   t = u.i[0];
2559   u.i[0] = u.i[1];
2560   u.i[1] = t;
2561   return u.r;
2562 }
2563 # define swapMixedEndianFloat(X)  X = floatSwap(X)
2564 #else
2565 # define swapMixedEndianFloat(X)
2566 #endif
2567 
2568 /*
2569 ** Write the serialized data blob for the value stored in pMem into
2570 ** buf. It is assumed that the caller has allocated sufficient space.
2571 ** Return the number of bytes written.
2572 **
2573 ** nBuf is the amount of space left in buf[].  nBuf must always be
2574 ** large enough to hold the entire field.  Except, if the field is
2575 ** a blob with a zero-filled tail, then buf[] might be just the right
2576 ** size to hold everything except for the zero-filled tail.  If buf[]
2577 ** is only big enough to hold the non-zero prefix, then only write that
2578 ** prefix into buf[].  But if buf[] is large enough to hold both the
2579 ** prefix and the tail then write the prefix and set the tail to all
2580 ** zeros.
2581 **
2582 ** Return the number of bytes actually written into buf[].  The number
2583 ** of bytes in the zero-filled tail is included in the return value only
2584 ** if those bytes were zeroed in buf[].
2585 */
2586 u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
2587   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
2588   u32 len;
2589 
2590   /* Integer and Real */
2591   if( serial_type<=7 && serial_type>0 ){
2592     u64 v;
2593     u32 i;
2594     if( serial_type==7 ){
2595       assert( sizeof(v)==sizeof(pMem->r) );
2596       memcpy(&v, &pMem->r, sizeof(v));
2597       swapMixedEndianFloat(v);
2598     }else{
2599       v = pMem->u.i;
2600     }
2601     len = i = sqlite3VdbeSerialTypeLen(serial_type);
2602     assert( len<=(u32)nBuf );
2603     while( i-- ){
2604       buf[i] = (u8)(v&0xFF);
2605       v >>= 8;
2606     }
2607     return len;
2608   }
2609 
2610   /* String or blob */
2611   if( serial_type>=12 ){
2612     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
2613              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
2614     assert( pMem->n<=nBuf );
2615     len = pMem->n;
2616     memcpy(buf, pMem->z, len);
2617     if( pMem->flags & MEM_Zero ){
2618       len += pMem->u.nZero;
2619       assert( nBuf>=0 );
2620       if( len > (u32)nBuf ){
2621         len = (u32)nBuf;
2622       }
2623       memset(&buf[pMem->n], 0, len-pMem->n);
2624     }
2625     return len;
2626   }
2627 
2628   /* NULL or constants 0 or 1 */
2629   return 0;
2630 }
2631 
2632 /*
2633 ** Deserialize the data blob pointed to by buf as serial type serial_type
2634 ** and store the result in pMem.  Return the number of bytes read.
2635 */
2636 u32 sqlite3VdbeSerialGet(
2637   const unsigned char *buf,     /* Buffer to deserialize from */
2638   u32 serial_type,              /* Serial type to deserialize */
2639   Mem *pMem                     /* Memory cell to write value into */
2640 ){
2641   switch( serial_type ){
2642     case 10:   /* Reserved for future use */
2643     case 11:   /* Reserved for future use */
2644     case 0: {  /* NULL */
2645       pMem->flags = MEM_Null;
2646       break;
2647     }
2648     case 1: { /* 1-byte signed integer */
2649       pMem->u.i = (signed char)buf[0];
2650       pMem->flags = MEM_Int;
2651       return 1;
2652     }
2653     case 2: { /* 2-byte signed integer */
2654       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
2655       pMem->flags = MEM_Int;
2656       return 2;
2657     }
2658     case 3: { /* 3-byte signed integer */
2659       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
2660       pMem->flags = MEM_Int;
2661       return 3;
2662     }
2663     case 4: { /* 4-byte signed integer */
2664       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
2665       pMem->flags = MEM_Int;
2666       return 4;
2667     }
2668     case 5: { /* 6-byte signed integer */
2669       u64 x = (((signed char)buf[0])<<8) | buf[1];
2670       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
2671       x = (x<<32) | y;
2672       pMem->u.i = *(i64*)&x;
2673       pMem->flags = MEM_Int;
2674       return 6;
2675     }
2676     case 6:   /* 8-byte signed integer */
2677     case 7: { /* IEEE floating point */
2678       u64 x;
2679       u32 y;
2680 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
2681       /* Verify that integers and floating point values use the same
2682       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
2683       ** defined that 64-bit floating point values really are mixed
2684       ** endian.
2685       */
2686       static const u64 t1 = ((u64)0x3ff00000)<<32;
2687       static const double r1 = 1.0;
2688       u64 t2 = t1;
2689       swapMixedEndianFloat(t2);
2690       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
2691 #endif
2692 
2693       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
2694       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
2695       x = (x<<32) | y;
2696       if( serial_type==6 ){
2697         pMem->u.i = *(i64*)&x;
2698         pMem->flags = MEM_Int;
2699       }else{
2700         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
2701         swapMixedEndianFloat(x);
2702         memcpy(&pMem->r, &x, sizeof(x));
2703         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
2704       }
2705       return 8;
2706     }
2707     case 8:    /* Integer 0 */
2708     case 9: {  /* Integer 1 */
2709       pMem->u.i = serial_type-8;
2710       pMem->flags = MEM_Int;
2711       return 0;
2712     }
2713     default: {
2714       u32 len = (serial_type-12)/2;
2715       pMem->z = (char *)buf;
2716       pMem->n = len;
2717       pMem->xDel = 0;
2718       if( serial_type&0x01 ){
2719         pMem->flags = MEM_Str | MEM_Ephem;
2720       }else{
2721         pMem->flags = MEM_Blob | MEM_Ephem;
2722       }
2723       return len;
2724     }
2725   }
2726   return 0;
2727 }
2728 
2729 
2730 /*
2731 ** Given the nKey-byte encoding of a record in pKey[], parse the
2732 ** record into a UnpackedRecord structure.  Return a pointer to
2733 ** that structure.
2734 **
2735 ** The calling function might provide szSpace bytes of memory
2736 ** space at pSpace.  This space can be used to hold the returned
2737 ** VDbeParsedRecord structure if it is large enough.  If it is
2738 ** not big enough, space is obtained from sqlite3_malloc().
2739 **
2740 ** The returned structure should be closed by a call to
2741 ** sqlite3VdbeDeleteUnpackedRecord().
2742 */
2743 UnpackedRecord *sqlite3VdbeRecordUnpack(
2744   KeyInfo *pKeyInfo,     /* Information about the record format */
2745   int nKey,              /* Size of the binary record */
2746   const void *pKey,      /* The binary record */
2747   char *pSpace,          /* Unaligned space available to hold the object */
2748   int szSpace            /* Size of pSpace[] in bytes */
2749 ){
2750   const unsigned char *aKey = (const unsigned char *)pKey;
2751   UnpackedRecord *p;  /* The unpacked record that we will return */
2752   int nByte;          /* Memory space needed to hold p, in bytes */
2753   int d;
2754   u32 idx;
2755   u16 u;              /* Unsigned loop counter */
2756   u32 szHdr;
2757   Mem *pMem;
2758   int nOff;           /* Increase pSpace by this much to 8-byte align it */
2759 
2760   /*
2761   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
2762   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
2763   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
2764   */
2765   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
2766   pSpace += nOff;
2767   szSpace -= nOff;
2768   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
2769   if( nByte>szSpace ){
2770     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
2771     if( p==0 ) return 0;
2772     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
2773   }else{
2774     p = (UnpackedRecord*)pSpace;
2775     p->flags = UNPACKED_NEED_DESTROY;
2776   }
2777   p->pKeyInfo = pKeyInfo;
2778   p->nField = pKeyInfo->nField + 1;
2779   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
2780   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
2781   idx = getVarint32(aKey, szHdr);
2782   d = szHdr;
2783   u = 0;
2784   while( idx<szHdr && u<p->nField && d<=nKey ){
2785     u32 serial_type;
2786 
2787     idx += getVarint32(&aKey[idx], serial_type);
2788     pMem->enc = pKeyInfo->enc;
2789     pMem->db = pKeyInfo->db;
2790     pMem->flags = 0;
2791     pMem->zMalloc = 0;
2792     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
2793     pMem++;
2794     u++;
2795   }
2796   assert( u<=pKeyInfo->nField + 1 );
2797   p->nField = u;
2798   return (void*)p;
2799 }
2800 
2801 /*
2802 ** This routine destroys a UnpackedRecord object.
2803 */
2804 void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
2805   int i;
2806   Mem *pMem;
2807 
2808   assert( p!=0 );
2809   assert( p->flags & UNPACKED_NEED_DESTROY );
2810   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
2811     /* The unpacked record is always constructed by the
2812     ** sqlite3VdbeUnpackRecord() function above, which makes all
2813     ** strings and blobs static.  And none of the elements are
2814     ** ever transformed, so there is never anything to delete.
2815     */
2816     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
2817   }
2818   if( p->flags & UNPACKED_NEED_FREE ){
2819     sqlite3DbFree(p->pKeyInfo->db, p);
2820   }
2821 }
2822 
2823 /*
2824 ** This function compares the two table rows or index records
2825 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
2826 ** or positive integer if key1 is less than, equal to or
2827 ** greater than key2.  The {nKey1, pKey1} key must be a blob
2828 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
2829 ** key must be a parsed key such as obtained from
2830 ** sqlite3VdbeParseRecord.
2831 **
2832 ** Key1 and Key2 do not have to contain the same number of fields.
2833 ** The key with fewer fields is usually compares less than the
2834 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
2835 ** and the common prefixes are equal, then key1 is less than key2.
2836 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
2837 ** equal, then the keys are considered to be equal and
2838 ** the parts beyond the common prefix are ignored.
2839 **
2840 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
2841 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
2842 ** an index key, and thus ends with a rowid value.  The last byte
2843 ** of the header will therefore be the serial type of the rowid:
2844 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
2845 ** The serial type of the final rowid will always be a single byte.
2846 ** By ignoring this last byte of the header, we force the comparison
2847 ** to ignore the rowid at the end of key1.
2848 */
2849 int sqlite3VdbeRecordCompare(
2850   int nKey1, const void *pKey1, /* Left key */
2851   UnpackedRecord *pPKey2        /* Right key */
2852 ){
2853   int d1;            /* Offset into aKey[] of next data element */
2854   u32 idx1;          /* Offset into aKey[] of next header element */
2855   u32 szHdr1;        /* Number of bytes in header */
2856   int i = 0;
2857   int nField;
2858   int rc = 0;
2859   const unsigned char *aKey1 = (const unsigned char *)pKey1;
2860   KeyInfo *pKeyInfo;
2861   Mem mem1;
2862 
2863   pKeyInfo = pPKey2->pKeyInfo;
2864   mem1.enc = pKeyInfo->enc;
2865   mem1.db = pKeyInfo->db;
2866   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
2867   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
2868 
2869   /* Compilers may complain that mem1.u.i is potentially uninitialized.
2870   ** We could initialize it, as shown here, to silence those complaints.
2871   ** But in fact, mem1.u.i will never actually be used initialized, and doing
2872   ** the unnecessary initialization has a measurable negative performance
2873   ** impact, since this routine is a very high runner.  And so, we choose
2874   ** to ignore the compiler warnings and leave this variable uninitialized.
2875   */
2876   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
2877 
2878   idx1 = getVarint32(aKey1, szHdr1);
2879   d1 = szHdr1;
2880   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
2881     szHdr1--;
2882   }
2883   nField = pKeyInfo->nField;
2884   while( idx1<szHdr1 && i<pPKey2->nField ){
2885     u32 serial_type1;
2886 
2887     /* Read the serial types for the next element in each key. */
2888     idx1 += getVarint32( aKey1+idx1, serial_type1 );
2889     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
2890 
2891     /* Extract the values to be compared.
2892     */
2893     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
2894 
2895     /* Do the comparison
2896     */
2897     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
2898                            i<nField ? pKeyInfo->aColl[i] : 0);
2899     if( rc!=0 ){
2900       assert( mem1.zMalloc==0 );  /* See comment below */
2901 
2902       /* Invert the result if we are using DESC sort order. */
2903       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
2904         rc = -rc;
2905       }
2906 
2907       /* If the PREFIX_SEARCH flag is set and all fields except the final
2908       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
2909       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
2910       ** This is used by the OP_IsUnique opcode.
2911       */
2912       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
2913         assert( idx1==szHdr1 && rc );
2914         assert( mem1.flags & MEM_Int );
2915         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
2916         pPKey2->rowid = mem1.u.i;
2917       }
2918 
2919       return rc;
2920     }
2921     i++;
2922   }
2923 
2924   /* No memory allocation is ever used on mem1.  Prove this using
2925   ** the following assert().  If the assert() fails, it indicates a
2926   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
2927   */
2928   assert( mem1.zMalloc==0 );
2929 
2930   /* rc==0 here means that one of the keys ran out of fields and
2931   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
2932   ** flag is set, then break the tie by treating key2 as larger.
2933   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
2934   ** are considered to be equal.  Otherwise, the longer key is the
2935   ** larger.  As it happens, the pPKey2 will always be the longer
2936   ** if there is a difference.
2937   */
2938   assert( rc==0 );
2939   if( pPKey2->flags & UNPACKED_INCRKEY ){
2940     rc = -1;
2941   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
2942     /* Leave rc==0 */
2943   }else if( idx1<szHdr1 ){
2944     rc = 1;
2945   }
2946   return rc;
2947 }
2948 
2949 
2950 /*
2951 ** pCur points at an index entry created using the OP_MakeRecord opcode.
2952 ** Read the rowid (the last field in the record) and store it in *rowid.
2953 ** Return SQLITE_OK if everything works, or an error code otherwise.
2954 **
2955 ** pCur might be pointing to text obtained from a corrupt database file.
2956 ** So the content cannot be trusted.  Do appropriate checks on the content.
2957 */
2958 int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
2959   i64 nCellKey = 0;
2960   int rc;
2961   u32 szHdr;        /* Size of the header */
2962   u32 typeRowid;    /* Serial type of the rowid */
2963   u32 lenRowid;     /* Size of the rowid */
2964   Mem m, v;
2965 
2966   UNUSED_PARAMETER(db);
2967 
2968   /* Get the size of the index entry.  Only indices entries of less
2969   ** than 2GiB are support - anything large must be database corruption.
2970   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
2971   ** this code can safely assume that nCellKey is 32-bits
2972   */
2973   assert( sqlite3BtreeCursorIsValid(pCur) );
2974   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
2975   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
2976   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
2977 
2978   /* Read in the complete content of the index entry */
2979   memset(&m, 0, sizeof(m));
2980   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
2981   if( rc ){
2982     return rc;
2983   }
2984 
2985   /* The index entry must begin with a header size */
2986   (void)getVarint32((u8*)m.z, szHdr);
2987   testcase( szHdr==3 );
2988   testcase( szHdr==m.n );
2989   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
2990     goto idx_rowid_corruption;
2991   }
2992 
2993   /* The last field of the index should be an integer - the ROWID.
2994   ** Verify that the last entry really is an integer. */
2995   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
2996   testcase( typeRowid==1 );
2997   testcase( typeRowid==2 );
2998   testcase( typeRowid==3 );
2999   testcase( typeRowid==4 );
3000   testcase( typeRowid==5 );
3001   testcase( typeRowid==6 );
3002   testcase( typeRowid==8 );
3003   testcase( typeRowid==9 );
3004   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
3005     goto idx_rowid_corruption;
3006   }
3007   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
3008   testcase( (u32)m.n==szHdr+lenRowid );
3009   if( unlikely((u32)m.n<szHdr+lenRowid) ){
3010     goto idx_rowid_corruption;
3011   }
3012 
3013   /* Fetch the integer off the end of the index record */
3014   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
3015   *rowid = v.u.i;
3016   sqlite3VdbeMemRelease(&m);
3017   return SQLITE_OK;
3018 
3019   /* Jump here if database corruption is detected after m has been
3020   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
3021 idx_rowid_corruption:
3022   testcase( m.zMalloc!=0 );
3023   sqlite3VdbeMemRelease(&m);
3024   return SQLITE_CORRUPT_BKPT;
3025 }
3026 
3027 /*
3028 ** Compare the key of the index entry that cursor pC is pointing to against
3029 ** the key string in pUnpacked.  Write into *pRes a number
3030 ** that is negative, zero, or positive if pC is less than, equal to,
3031 ** or greater than pUnpacked.  Return SQLITE_OK on success.
3032 **
3033 ** pUnpacked is either created without a rowid or is truncated so that it
3034 ** omits the rowid at the end.  The rowid at the end of the index entry
3035 ** is ignored as well.  Hence, this routine only compares the prefixes
3036 ** of the keys prior to the final rowid, not the entire key.
3037 */
3038 int sqlite3VdbeIdxKeyCompare(
3039   VdbeCursor *pC,             /* The cursor to compare against */
3040   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
3041   int *res                    /* Write the comparison result here */
3042 ){
3043   i64 nCellKey = 0;
3044   int rc;
3045   BtCursor *pCur = pC->pCursor;
3046   Mem m;
3047 
3048   assert( sqlite3BtreeCursorIsValid(pCur) );
3049   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
3050   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
3051   /* nCellKey will always be between 0 and 0xffffffff because of the say
3052   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
3053   if( nCellKey<=0 || nCellKey>0x7fffffff ){
3054     *res = 0;
3055     return SQLITE_CORRUPT_BKPT;
3056   }
3057   memset(&m, 0, sizeof(m));
3058   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
3059   if( rc ){
3060     return rc;
3061   }
3062   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
3063   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
3064   sqlite3VdbeMemRelease(&m);
3065   return SQLITE_OK;
3066 }
3067 
3068 /*
3069 ** This routine sets the value to be returned by subsequent calls to
3070 ** sqlite3_changes() on the database handle 'db'.
3071 */
3072 void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
3073   assert( sqlite3_mutex_held(db->mutex) );
3074   db->nChange = nChange;
3075   db->nTotalChange += nChange;
3076 }
3077 
3078 /*
3079 ** Set a flag in the vdbe to update the change counter when it is finalised
3080 ** or reset.
3081 */
3082 void sqlite3VdbeCountChanges(Vdbe *v){
3083   v->changeCntOn = 1;
3084 }
3085 
3086 /*
3087 ** Mark every prepared statement associated with a database connection
3088 ** as expired.
3089 **
3090 ** An expired statement means that recompilation of the statement is
3091 ** recommend.  Statements expire when things happen that make their
3092 ** programs obsolete.  Removing user-defined functions or collating
3093 ** sequences, or changing an authorization function are the types of
3094 ** things that make prepared statements obsolete.
3095 */
3096 void sqlite3ExpirePreparedStatements(sqlite3 *db){
3097   Vdbe *p;
3098   for(p = db->pVdbe; p; p=p->pNext){
3099     p->expired = 1;
3100   }
3101 }
3102 
3103 /*
3104 ** Return the database associated with the Vdbe.
3105 */
3106 sqlite3 *sqlite3VdbeDb(Vdbe *v){
3107   return v->db;
3108 }
3109 
3110 /*
3111 ** Return a pointer to an sqlite3_value structure containing the value bound
3112 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
3113 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
3114 ** constants) to the value before returning it.
3115 **
3116 ** The returned value must be freed by the caller using sqlite3ValueFree().
3117 */
3118 sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
3119   assert( iVar>0 );
3120   if( v ){
3121     Mem *pMem = &v->aVar[iVar-1];
3122     if( 0==(pMem->flags & MEM_Null) ){
3123       sqlite3_value *pRet = sqlite3ValueNew(v->db);
3124       if( pRet ){
3125         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
3126         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
3127         sqlite3VdbeMemStoreType((Mem *)pRet);
3128       }
3129       return pRet;
3130     }
3131   }
3132   return 0;
3133 }
3134 
3135 /*
3136 ** Configure SQL variable iVar so that binding a new value to it signals
3137 ** to sqlite3_reoptimize() that re-preparing the statement may result
3138 ** in a better query plan.
3139 */
3140 void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
3141   assert( iVar>0 );
3142   if( iVar>32 ){
3143     v->expmask = 0xffffffff;
3144   }else{
3145     v->expmask |= ((u32)1 << (iVar-1));
3146   }
3147 }
3148