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