xref: /sqlite-3.40.0/src/vdbeaux.c (revision ef480d37)
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.)
14 */
15 #include "sqliteInt.h"
16 #include "vdbeInt.h"
17 
18 /*
19 ** Create a new virtual database engine.
20 */
21 Vdbe *sqlite3VdbeCreate(Parse *pParse){
22   sqlite3 *db = pParse->db;
23   Vdbe *p;
24   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
25   if( p==0 ) return 0;
26   p->db = db;
27   if( db->pVdbe ){
28     db->pVdbe->pPrev = p;
29   }
30   p->pNext = db->pVdbe;
31   p->pPrev = 0;
32   db->pVdbe = p;
33   p->magic = VDBE_MAGIC_INIT;
34   p->pParse = pParse;
35   assert( pParse->aLabel==0 );
36   assert( pParse->nLabel==0 );
37   assert( pParse->nOpAlloc==0 );
38   assert( pParse->szOpAlloc==0 );
39   return p;
40 }
41 
42 /*
43 ** Change the error string stored in Vdbe.zErrMsg
44 */
45 void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
46   va_list ap;
47   sqlite3DbFree(p->db, p->zErrMsg);
48   va_start(ap, zFormat);
49   p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
50   va_end(ap);
51 }
52 
53 /*
54 ** Remember the SQL string for a prepared statement.
55 */
56 void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
57   assert( isPrepareV2==1 || isPrepareV2==0 );
58   if( p==0 ) return;
59 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
60   if( !isPrepareV2 ) return;
61 #endif
62   assert( p->zSql==0 );
63   p->zSql = sqlite3DbStrNDup(p->db, z, n);
64   p->isPrepareV2 = (u8)isPrepareV2;
65 }
66 
67 /*
68 ** Return the SQL associated with a prepared statement
69 */
70 const char *sqlite3_sql(sqlite3_stmt *pStmt){
71   Vdbe *p = (Vdbe *)pStmt;
72   return p ? p->zSql : 0;
73 }
74 
75 /*
76 ** Swap all content between two VDBE structures.
77 */
78 void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
79   Vdbe tmp, *pTmp;
80   char *zTmp;
81   tmp = *pA;
82   *pA = *pB;
83   *pB = tmp;
84   pTmp = pA->pNext;
85   pA->pNext = pB->pNext;
86   pB->pNext = pTmp;
87   pTmp = pA->pPrev;
88   pA->pPrev = pB->pPrev;
89   pB->pPrev = pTmp;
90   zTmp = pA->zSql;
91   pA->zSql = pB->zSql;
92   pB->zSql = zTmp;
93   pB->isPrepareV2 = pA->isPrepareV2;
94 }
95 
96 /*
97 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
98 ** than its current size. nOp is guaranteed to be less than or equal
99 ** to 1024/sizeof(Op).
100 **
101 ** If an out-of-memory error occurs while resizing the array, return
102 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
103 ** unchanged (this is so that any opcodes already allocated can be
104 ** correctly deallocated along with the rest of the Vdbe).
105 */
106 static int growOpArray(Vdbe *v, int nOp){
107   VdbeOp *pNew;
108   Parse *p = v->pParse;
109 
110   /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
111   ** more frequent reallocs and hence provide more opportunities for
112   ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
113   ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
114   ** by the minimum* amount required until the size reaches 512.  Normal
115   ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
116   ** size of the op array or add 1KB of space, whichever is smaller. */
117 #ifdef SQLITE_TEST_REALLOC_STRESS
118   int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
119 #else
120   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
121   UNUSED_PARAMETER(nOp);
122 #endif
123 
124   assert( nOp<=(1024/sizeof(Op)) );
125   assert( nNew>=(p->nOpAlloc+nOp) );
126   pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
127   if( pNew ){
128     p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
129     p->nOpAlloc = p->szOpAlloc/sizeof(Op);
130     v->aOp = pNew;
131   }
132   return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
133 }
134 
135 #ifdef SQLITE_DEBUG
136 /* This routine is just a convenient place to set a breakpoint that will
137 ** fire after each opcode is inserted and displayed using
138 ** "PRAGMA vdbe_addoptrace=on".
139 */
140 static void test_addop_breakpoint(void){
141   static int n = 0;
142   n++;
143 }
144 #endif
145 
146 /*
147 ** Add a new instruction to the list of instructions current in the
148 ** VDBE.  Return the address of the new instruction.
149 **
150 ** Parameters:
151 **
152 **    p               Pointer to the VDBE
153 **
154 **    op              The opcode for this instruction
155 **
156 **    p1, p2, p3      Operands
157 **
158 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
159 ** the sqlite3VdbeChangeP4() function to change the value of the P4
160 ** operand.
161 */
162 static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
163   assert( p->pParse->nOpAlloc<=p->nOp );
164   if( growOpArray(p, 1) ) return 1;
165   assert( p->pParse->nOpAlloc>p->nOp );
166   return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
167 }
168 int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
169   int i;
170   VdbeOp *pOp;
171 
172   i = p->nOp;
173   assert( p->magic==VDBE_MAGIC_INIT );
174   assert( op>=0 && op<0xff );
175   if( p->pParse->nOpAlloc<=i ){
176     return growOp3(p, op, p1, p2, p3);
177   }
178   p->nOp++;
179   pOp = &p->aOp[i];
180   pOp->opcode = (u8)op;
181   pOp->p5 = 0;
182   pOp->p1 = p1;
183   pOp->p2 = p2;
184   pOp->p3 = p3;
185   pOp->p4.p = 0;
186   pOp->p4type = P4_NOTUSED;
187 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
188   pOp->zComment = 0;
189 #endif
190 #ifdef SQLITE_DEBUG
191   if( p->db->flags & SQLITE_VdbeAddopTrace ){
192     int jj, kk;
193     Parse *pParse = p->pParse;
194     for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
195       struct yColCache *x = pParse->aColCache + jj;
196       if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
197       printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
198       kk++;
199     }
200     if( kk ) printf("\n");
201     sqlite3VdbePrintOp(0, i, &p->aOp[i]);
202     test_addop_breakpoint();
203   }
204 #endif
205 #ifdef VDBE_PROFILE
206   pOp->cycles = 0;
207   pOp->cnt = 0;
208 #endif
209 #ifdef SQLITE_VDBE_COVERAGE
210   pOp->iSrcLine = 0;
211 #endif
212   return i;
213 }
214 int sqlite3VdbeAddOp0(Vdbe *p, int op){
215   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
216 }
217 int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
218   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
219 }
220 int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
221   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
222 }
223 
224 /* Generate code for an unconditional jump to instruction iDest
225 */
226 int sqlite3VdbeGoto(Vdbe *p, int iDest){
227   return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
228 }
229 
230 /* Generate code to cause the string zStr to be loaded into
231 ** register iDest
232 */
233 int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
234   return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
235 }
236 
237 /*
238 ** Generate code that initializes multiple registers to string or integer
239 ** constants.  The registers begin with iDest and increase consecutively.
240 ** One register is initialized for each characgter in zTypes[].  For each
241 ** "s" character in zTypes[], the register is a string if the argument is
242 ** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
243 ** in zTypes[], the register is initialized to an integer.
244 */
245 void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
246   va_list ap;
247   int i;
248   char c;
249   va_start(ap, zTypes);
250   for(i=0; (c = zTypes[i])!=0; i++){
251     if( c=='s' ){
252       const char *z = va_arg(ap, const char*);
253       sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0);
254     }else{
255       assert( c=='i' );
256       sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
257     }
258   }
259   va_end(ap);
260 }
261 
262 /*
263 ** Add an opcode that includes the p4 value as a pointer.
264 */
265 int sqlite3VdbeAddOp4(
266   Vdbe *p,            /* Add the opcode to this VM */
267   int op,             /* The new opcode */
268   int p1,             /* The P1 operand */
269   int p2,             /* The P2 operand */
270   int p3,             /* The P3 operand */
271   const char *zP4,    /* The P4 operand */
272   int p4type          /* P4 operand type */
273 ){
274   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
275   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
276   return addr;
277 }
278 
279 /*
280 ** Add an opcode that includes the p4 value with a P4_INT64 or
281 ** P4_REAL type.
282 */
283 int sqlite3VdbeAddOp4Dup8(
284   Vdbe *p,            /* Add the opcode to this VM */
285   int op,             /* The new opcode */
286   int p1,             /* The P1 operand */
287   int p2,             /* The P2 operand */
288   int p3,             /* The P3 operand */
289   const u8 *zP4,      /* The P4 operand */
290   int p4type          /* P4 operand type */
291 ){
292   char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
293   if( p4copy ) memcpy(p4copy, zP4, 8);
294   return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
295 }
296 
297 /*
298 ** Add an OP_ParseSchema opcode.  This routine is broken out from
299 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
300 ** as having been used.
301 **
302 ** The zWhere string must have been obtained from sqlite3_malloc().
303 ** This routine will take ownership of the allocated memory.
304 */
305 void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
306   int j;
307   sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
308   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
309 }
310 
311 /*
312 ** Add an opcode that includes the p4 value as an integer.
313 */
314 int sqlite3VdbeAddOp4Int(
315   Vdbe *p,            /* Add the opcode to this VM */
316   int op,             /* The new opcode */
317   int p1,             /* The P1 operand */
318   int p2,             /* The P2 operand */
319   int p3,             /* The P3 operand */
320   int p4              /* The P4 operand as an integer */
321 ){
322   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
323   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
324   return addr;
325 }
326 
327 /* Insert the end of a co-routine
328 */
329 void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
330   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
331 
332   /* Clear the temporary register cache, thereby ensuring that each
333   ** co-routine has its own independent set of registers, because co-routines
334   ** might expect their registers to be preserved across an OP_Yield, and
335   ** that could cause problems if two or more co-routines are using the same
336   ** temporary register.
337   */
338   v->pParse->nTempReg = 0;
339   v->pParse->nRangeReg = 0;
340 }
341 
342 /*
343 ** Create a new symbolic label for an instruction that has yet to be
344 ** coded.  The symbolic label is really just a negative number.  The
345 ** label can be used as the P2 value of an operation.  Later, when
346 ** the label is resolved to a specific address, the VDBE will scan
347 ** through its operation list and change all values of P2 which match
348 ** the label into the resolved address.
349 **
350 ** The VDBE knows that a P2 value is a label because labels are
351 ** always negative and P2 values are suppose to be non-negative.
352 ** Hence, a negative P2 value is a label that has yet to be resolved.
353 **
354 ** Zero is returned if a malloc() fails.
355 */
356 int sqlite3VdbeMakeLabel(Vdbe *v){
357   Parse *p = v->pParse;
358   int i = p->nLabel++;
359   assert( v->magic==VDBE_MAGIC_INIT );
360   if( (i & (i-1))==0 ){
361     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
362                                        (i*2+1)*sizeof(p->aLabel[0]));
363   }
364   if( p->aLabel ){
365     p->aLabel[i] = -1;
366   }
367   return ADDR(i);
368 }
369 
370 /*
371 ** Resolve label "x" to be the address of the next instruction to
372 ** be inserted.  The parameter "x" must have been obtained from
373 ** a prior call to sqlite3VdbeMakeLabel().
374 */
375 void sqlite3VdbeResolveLabel(Vdbe *v, int x){
376   Parse *p = v->pParse;
377   int j = ADDR(x);
378   assert( v->magic==VDBE_MAGIC_INIT );
379   assert( j<p->nLabel );
380   assert( j>=0 );
381   if( p->aLabel ){
382     p->aLabel[j] = v->nOp;
383   }
384   p->iFixedOp = v->nOp - 1;
385 }
386 
387 /*
388 ** Mark the VDBE as one that can only be run one time.
389 */
390 void sqlite3VdbeRunOnlyOnce(Vdbe *p){
391   p->runOnlyOnce = 1;
392 }
393 
394 /*
395 ** Mark the VDBE as one that can only be run multiple times.
396 */
397 void sqlite3VdbeReusable(Vdbe *p){
398   p->runOnlyOnce = 0;
399 }
400 
401 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
402 
403 /*
404 ** The following type and function are used to iterate through all opcodes
405 ** in a Vdbe main program and each of the sub-programs (triggers) it may
406 ** invoke directly or indirectly. It should be used as follows:
407 **
408 **   Op *pOp;
409 **   VdbeOpIter sIter;
410 **
411 **   memset(&sIter, 0, sizeof(sIter));
412 **   sIter.v = v;                            // v is of type Vdbe*
413 **   while( (pOp = opIterNext(&sIter)) ){
414 **     // Do something with pOp
415 **   }
416 **   sqlite3DbFree(v->db, sIter.apSub);
417 **
418 */
419 typedef struct VdbeOpIter VdbeOpIter;
420 struct VdbeOpIter {
421   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
422   SubProgram **apSub;        /* Array of subprograms */
423   int nSub;                  /* Number of entries in apSub */
424   int iAddr;                 /* Address of next instruction to return */
425   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
426 };
427 static Op *opIterNext(VdbeOpIter *p){
428   Vdbe *v = p->v;
429   Op *pRet = 0;
430   Op *aOp;
431   int nOp;
432 
433   if( p->iSub<=p->nSub ){
434 
435     if( p->iSub==0 ){
436       aOp = v->aOp;
437       nOp = v->nOp;
438     }else{
439       aOp = p->apSub[p->iSub-1]->aOp;
440       nOp = p->apSub[p->iSub-1]->nOp;
441     }
442     assert( p->iAddr<nOp );
443 
444     pRet = &aOp[p->iAddr];
445     p->iAddr++;
446     if( p->iAddr==nOp ){
447       p->iSub++;
448       p->iAddr = 0;
449     }
450 
451     if( pRet->p4type==P4_SUBPROGRAM ){
452       int nByte = (p->nSub+1)*sizeof(SubProgram*);
453       int j;
454       for(j=0; j<p->nSub; j++){
455         if( p->apSub[j]==pRet->p4.pProgram ) break;
456       }
457       if( j==p->nSub ){
458         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
459         if( !p->apSub ){
460           pRet = 0;
461         }else{
462           p->apSub[p->nSub++] = pRet->p4.pProgram;
463         }
464       }
465     }
466   }
467 
468   return pRet;
469 }
470 
471 /*
472 ** Check if the program stored in the VM associated with pParse may
473 ** throw an ABORT exception (causing the statement, but not entire transaction
474 ** to be rolled back). This condition is true if the main program or any
475 ** sub-programs contains any of the following:
476 **
477 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
478 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
479 **   *  OP_Destroy
480 **   *  OP_VUpdate
481 **   *  OP_VRename
482 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
483 **   *  OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
484 **
485 ** Then check that the value of Parse.mayAbort is true if an
486 ** ABORT may be thrown, or false otherwise. Return true if it does
487 ** match, or false otherwise. This function is intended to be used as
488 ** part of an assert statement in the compiler. Similar to:
489 **
490 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
491 */
492 int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
493   int hasAbort = 0;
494   int hasFkCounter = 0;
495   int hasCreateTable = 0;
496   int hasInitCoroutine = 0;
497   Op *pOp;
498   VdbeOpIter sIter;
499   memset(&sIter, 0, sizeof(sIter));
500   sIter.v = v;
501 
502   while( (pOp = opIterNext(&sIter))!=0 ){
503     int opcode = pOp->opcode;
504     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
505      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
506       && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
507     ){
508       hasAbort = 1;
509       break;
510     }
511     if( opcode==OP_CreateTable ) hasCreateTable = 1;
512     if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
513 #ifndef SQLITE_OMIT_FOREIGN_KEY
514     if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
515       hasFkCounter = 1;
516     }
517 #endif
518   }
519   sqlite3DbFree(v->db, sIter.apSub);
520 
521   /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
522   ** If malloc failed, then the while() loop above may not have iterated
523   ** through all opcodes and hasAbort may be set incorrectly. Return
524   ** true for this case to prevent the assert() in the callers frame
525   ** from failing.  */
526   return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
527               || (hasCreateTable && hasInitCoroutine) );
528 }
529 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
530 
531 /*
532 ** This routine is called after all opcodes have been inserted.  It loops
533 ** through all the opcodes and fixes up some details.
534 **
535 ** (1) For each jump instruction with a negative P2 value (a label)
536 **     resolve the P2 value to an actual address.
537 **
538 ** (2) Compute the maximum number of arguments used by any SQL function
539 **     and store that value in *pMaxFuncArgs.
540 **
541 ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
542 **     indicate what the prepared statement actually does.
543 **
544 ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
545 **
546 ** (5) Reclaim the memory allocated for storing labels.
547 */
548 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
549   int i;
550   int nMaxArgs = *pMaxFuncArgs;
551   Op *pOp;
552   Parse *pParse = p->pParse;
553   int *aLabel = pParse->aLabel;
554   p->readOnly = 1;
555   p->bIsReader = 0;
556   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
557     u8 opcode = pOp->opcode;
558 
559     /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
560     ** cases from this switch! */
561     switch( opcode ){
562       case OP_Transaction: {
563         if( pOp->p2!=0 ) p->readOnly = 0;
564         /* fall thru */
565       }
566       case OP_AutoCommit:
567       case OP_Savepoint: {
568         p->bIsReader = 1;
569         break;
570       }
571 #ifndef SQLITE_OMIT_WAL
572       case OP_Checkpoint:
573 #endif
574       case OP_Vacuum:
575       case OP_JournalMode: {
576         p->readOnly = 0;
577         p->bIsReader = 1;
578         break;
579       }
580 #ifndef SQLITE_OMIT_VIRTUALTABLE
581       case OP_VUpdate: {
582         if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
583         break;
584       }
585       case OP_VFilter: {
586         int n;
587         assert( p->nOp - i >= 3 );
588         assert( pOp[-1].opcode==OP_Integer );
589         n = pOp[-1].p1;
590         if( n>nMaxArgs ) nMaxArgs = n;
591         break;
592       }
593 #endif
594       case OP_Next:
595       case OP_NextIfOpen:
596       case OP_SorterNext: {
597         pOp->p4.xAdvance = sqlite3BtreeNext;
598         pOp->p4type = P4_ADVANCE;
599         break;
600       }
601       case OP_Prev:
602       case OP_PrevIfOpen: {
603         pOp->p4.xAdvance = sqlite3BtreePrevious;
604         pOp->p4type = P4_ADVANCE;
605         break;
606       }
607     }
608 
609     pOp->opflags = sqlite3OpcodeProperty[opcode];
610     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
611       assert( ADDR(pOp->p2)<pParse->nLabel );
612       pOp->p2 = aLabel[ADDR(pOp->p2)];
613     }
614   }
615   sqlite3DbFree(p->db, pParse->aLabel);
616   pParse->aLabel = 0;
617   pParse->nLabel = 0;
618   *pMaxFuncArgs = nMaxArgs;
619   assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
620 }
621 
622 /*
623 ** Return the address of the next instruction to be inserted.
624 */
625 int sqlite3VdbeCurrentAddr(Vdbe *p){
626   assert( p->magic==VDBE_MAGIC_INIT );
627   return p->nOp;
628 }
629 
630 /*
631 ** Verify that at least N opcode slots are available in p without
632 ** having to malloc for more space (except when compiled using
633 ** SQLITE_TEST_REALLOC_STRESS).  This interface is used during testing
634 ** to verify that certain calls to sqlite3VdbeAddOpList() can never
635 ** fail due to a OOM fault and hence that the return value from
636 ** sqlite3VdbeAddOpList() will always be non-NULL.
637 */
638 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
639 void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
640   assert( p->nOp + N <= p->pParse->nOpAlloc );
641 }
642 #endif
643 
644 /*
645 ** This function returns a pointer to the array of opcodes associated with
646 ** the Vdbe passed as the first argument. It is the callers responsibility
647 ** to arrange for the returned array to be eventually freed using the
648 ** vdbeFreeOpArray() function.
649 **
650 ** Before returning, *pnOp is set to the number of entries in the returned
651 ** array. Also, *pnMaxArg is set to the larger of its current value and
652 ** the number of entries in the Vdbe.apArg[] array required to execute the
653 ** returned program.
654 */
655 VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
656   VdbeOp *aOp = p->aOp;
657   assert( aOp && !p->db->mallocFailed );
658 
659   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
660   assert( DbMaskAllZero(p->btreeMask) );
661 
662   resolveP2Values(p, pnMaxArg);
663   *pnOp = p->nOp;
664   p->aOp = 0;
665   return aOp;
666 }
667 
668 /*
669 ** Add a whole list of operations to the operation stack.  Return a
670 ** pointer to the first operation inserted.
671 **
672 ** Non-zero P2 arguments to jump instructions are automatically adjusted
673 ** so that the jump target is relative to the first operation inserted.
674 */
675 VdbeOp *sqlite3VdbeAddOpList(
676   Vdbe *p,                     /* Add opcodes to the prepared statement */
677   int nOp,                     /* Number of opcodes to add */
678   VdbeOpList const *aOp,       /* The opcodes to be added */
679   int iLineno                  /* Source-file line number of first opcode */
680 ){
681   int i;
682   VdbeOp *pOut, *pFirst;
683   assert( nOp>0 );
684   assert( p->magic==VDBE_MAGIC_INIT );
685   if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
686     return 0;
687   }
688   pFirst = pOut = &p->aOp[p->nOp];
689   for(i=0; i<nOp; i++, aOp++, pOut++){
690     pOut->opcode = aOp->opcode;
691     pOut->p1 = aOp->p1;
692     pOut->p2 = aOp->p2;
693     assert( aOp->p2>=0 );
694     if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
695       pOut->p2 += p->nOp;
696     }
697     pOut->p3 = aOp->p3;
698     pOut->p4type = P4_NOTUSED;
699     pOut->p4.p = 0;
700     pOut->p5 = 0;
701 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
702     pOut->zComment = 0;
703 #endif
704 #ifdef SQLITE_VDBE_COVERAGE
705     pOut->iSrcLine = iLineno+i;
706 #else
707     (void)iLineno;
708 #endif
709 #ifdef SQLITE_DEBUG
710     if( p->db->flags & SQLITE_VdbeAddopTrace ){
711       sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
712     }
713 #endif
714   }
715   p->nOp += nOp;
716   return pFirst;
717 }
718 
719 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
720 /*
721 ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
722 */
723 void sqlite3VdbeScanStatus(
724   Vdbe *p,                        /* VM to add scanstatus() to */
725   int addrExplain,                /* Address of OP_Explain (or 0) */
726   int addrLoop,                   /* Address of loop counter */
727   int addrVisit,                  /* Address of rows visited counter */
728   LogEst nEst,                    /* Estimated number of output rows */
729   const char *zName               /* Name of table or index being scanned */
730 ){
731   int nByte = (p->nScan+1) * sizeof(ScanStatus);
732   ScanStatus *aNew;
733   aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
734   if( aNew ){
735     ScanStatus *pNew = &aNew[p->nScan++];
736     pNew->addrExplain = addrExplain;
737     pNew->addrLoop = addrLoop;
738     pNew->addrVisit = addrVisit;
739     pNew->nEst = nEst;
740     pNew->zName = sqlite3DbStrDup(p->db, zName);
741     p->aScan = aNew;
742   }
743 }
744 #endif
745 
746 
747 /*
748 ** Change the value of the opcode, or P1, P2, P3, or P5 operands
749 ** for a specific instruction.
750 */
751 void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
752   sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
753 }
754 void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
755   sqlite3VdbeGetOp(p,addr)->p1 = val;
756 }
757 void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
758   sqlite3VdbeGetOp(p,addr)->p2 = val;
759 }
760 void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
761   sqlite3VdbeGetOp(p,addr)->p3 = val;
762 }
763 void sqlite3VdbeChangeP5(Vdbe *p, u8 p5){
764   if( !p->db->mallocFailed ) p->aOp[p->nOp-1].p5 = p5;
765 }
766 
767 /*
768 ** Change the P2 operand of instruction addr so that it points to
769 ** the address of the next instruction to be coded.
770 */
771 void sqlite3VdbeJumpHere(Vdbe *p, int addr){
772   p->pParse->iFixedOp = p->nOp - 1;
773   sqlite3VdbeChangeP2(p, addr, p->nOp);
774 }
775 
776 
777 /*
778 ** If the input FuncDef structure is ephemeral, then free it.  If
779 ** the FuncDef is not ephermal, then do nothing.
780 */
781 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
782   if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
783     sqlite3DbFree(db, pDef);
784   }
785 }
786 
787 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
788 
789 /*
790 ** Delete a P4 value if necessary.
791 */
792 static void freeP4(sqlite3 *db, int p4type, void *p4){
793   if( p4 ){
794     assert( db );
795     switch( p4type ){
796       case P4_FUNCCTX: {
797         freeEphemeralFunction(db, ((sqlite3_context*)p4)->pFunc);
798         /* Fall through into the next case */
799       }
800       case P4_REAL:
801       case P4_INT64:
802       case P4_DYNAMIC:
803       case P4_INTARRAY: {
804         sqlite3DbFree(db, p4);
805         break;
806       }
807       case P4_KEYINFO: {
808         if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
809         break;
810       }
811 #ifdef SQLITE_ENABLE_CURSOR_HINTS
812       case P4_EXPR: {
813         sqlite3ExprDelete(db, (Expr*)p4);
814         break;
815       }
816 #endif
817       case P4_MPRINTF: {
818         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
819         break;
820       }
821       case P4_FUNCDEF: {
822         freeEphemeralFunction(db, (FuncDef*)p4);
823         break;
824       }
825       case P4_MEM: {
826         if( db->pnBytesFreed==0 ){
827           sqlite3ValueFree((sqlite3_value*)p4);
828         }else{
829           Mem *p = (Mem*)p4;
830           if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
831           sqlite3DbFree(db, p);
832         }
833         break;
834       }
835       case P4_VTAB : {
836         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
837         break;
838       }
839     }
840   }
841 }
842 
843 /*
844 ** Free the space allocated for aOp and any p4 values allocated for the
845 ** opcodes contained within. If aOp is not NULL it is assumed to contain
846 ** nOp entries.
847 */
848 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
849   if( aOp ){
850     Op *pOp;
851     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
852       if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p);
853 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
854       sqlite3DbFree(db, pOp->zComment);
855 #endif
856     }
857   }
858   sqlite3DbFree(db, aOp);
859 }
860 
861 /*
862 ** Link the SubProgram object passed as the second argument into the linked
863 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
864 ** objects when the VM is no longer required.
865 */
866 void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
867   p->pNext = pVdbe->pProgram;
868   pVdbe->pProgram = p;
869 }
870 
871 /*
872 ** Change the opcode at addr into OP_Noop
873 */
874 int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
875   VdbeOp *pOp;
876   if( p->db->mallocFailed ) return 0;
877   assert( addr>=0 && addr<p->nOp );
878   pOp = &p->aOp[addr];
879   freeP4(p->db, pOp->p4type, pOp->p4.p);
880   pOp->p4type = P4_NOTUSED;
881   pOp->p4.z = 0;
882   pOp->opcode = OP_Noop;
883   return 1;
884 }
885 
886 /*
887 ** If the last opcode is "op" and it is not a jump destination,
888 ** then remove it.  Return true if and only if an opcode was removed.
889 */
890 int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
891   if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
892     return sqlite3VdbeChangeToNoop(p, p->nOp-1);
893   }else{
894     return 0;
895   }
896 }
897 
898 /*
899 ** Change the value of the P4 operand for a specific instruction.
900 ** This routine is useful when a large program is loaded from a
901 ** static array using sqlite3VdbeAddOpList but we want to make a
902 ** few minor changes to the program.
903 **
904 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
905 ** the string is made into memory obtained from sqlite3_malloc().
906 ** A value of n==0 means copy bytes of zP4 up to and including the
907 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
908 **
909 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
910 ** to a string or structure that is guaranteed to exist for the lifetime of
911 ** the Vdbe. In these cases we can just copy the pointer.
912 **
913 ** If addr<0 then change P4 on the most recently inserted instruction.
914 */
915 static void SQLITE_NOINLINE vdbeChangeP4Full(
916   Vdbe *p,
917   Op *pOp,
918   const char *zP4,
919   int n
920 ){
921   if( pOp->p4type ){
922     freeP4(p->db, pOp->p4type, pOp->p4.p);
923     pOp->p4type = 0;
924     pOp->p4.p = 0;
925   }
926   if( n<0 ){
927     sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
928   }else{
929     if( n==0 ) n = sqlite3Strlen30(zP4);
930     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
931     pOp->p4type = P4_DYNAMIC;
932   }
933 }
934 void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
935   Op *pOp;
936   sqlite3 *db;
937   assert( p!=0 );
938   db = p->db;
939   assert( p->magic==VDBE_MAGIC_INIT );
940   assert( p->aOp!=0 || db->mallocFailed );
941   if( db->mallocFailed ){
942     if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
943     return;
944   }
945   assert( p->nOp>0 );
946   assert( addr<p->nOp );
947   if( addr<0 ){
948     addr = p->nOp - 1;
949   }
950   pOp = &p->aOp[addr];
951   if( n>=0 || pOp->p4type ){
952     vdbeChangeP4Full(p, pOp, zP4, n);
953     return;
954   }
955   if( n==P4_INT32 ){
956     /* Note: this cast is safe, because the origin data point was an int
957     ** that was cast to a (const char *). */
958     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
959     pOp->p4type = P4_INT32;
960   }else if( zP4!=0 ){
961     assert( n<0 );
962     pOp->p4.p = (void*)zP4;
963     pOp->p4type = (signed char)n;
964     if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
965   }
966 }
967 
968 /*
969 ** Set the P4 on the most recently added opcode to the KeyInfo for the
970 ** index given.
971 */
972 void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
973   Vdbe *v = pParse->pVdbe;
974   assert( v!=0 );
975   assert( pIdx!=0 );
976   sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
977                       P4_KEYINFO);
978 }
979 
980 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
981 /*
982 ** Change the comment on the most recently coded instruction.  Or
983 ** insert a No-op and add the comment to that new instruction.  This
984 ** makes the code easier to read during debugging.  None of this happens
985 ** in a production build.
986 */
987 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
988   assert( p->nOp>0 || p->aOp==0 );
989   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
990   if( p->nOp ){
991     assert( p->aOp );
992     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
993     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
994   }
995 }
996 void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
997   va_list ap;
998   if( p ){
999     va_start(ap, zFormat);
1000     vdbeVComment(p, zFormat, ap);
1001     va_end(ap);
1002   }
1003 }
1004 void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
1005   va_list ap;
1006   if( p ){
1007     sqlite3VdbeAddOp0(p, OP_Noop);
1008     va_start(ap, zFormat);
1009     vdbeVComment(p, zFormat, ap);
1010     va_end(ap);
1011   }
1012 }
1013 #endif  /* NDEBUG */
1014 
1015 #ifdef SQLITE_VDBE_COVERAGE
1016 /*
1017 ** Set the value if the iSrcLine field for the previously coded instruction.
1018 */
1019 void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
1020   sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
1021 }
1022 #endif /* SQLITE_VDBE_COVERAGE */
1023 
1024 /*
1025 ** Return the opcode for a given address.  If the address is -1, then
1026 ** return the most recently inserted opcode.
1027 **
1028 ** If a memory allocation error has occurred prior to the calling of this
1029 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
1030 ** is readable but not writable, though it is cast to a writable value.
1031 ** The return of a dummy opcode allows the call to continue functioning
1032 ** after an OOM fault without having to check to see if the return from
1033 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
1034 ** dummy will never be written to.  This is verified by code inspection and
1035 ** by running with Valgrind.
1036 */
1037 VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
1038   /* C89 specifies that the constant "dummy" will be initialized to all
1039   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
1040   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
1041   assert( p->magic==VDBE_MAGIC_INIT );
1042   if( addr<0 ){
1043     addr = p->nOp - 1;
1044   }
1045   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
1046   if( p->db->mallocFailed ){
1047     return (VdbeOp*)&dummy;
1048   }else{
1049     return &p->aOp[addr];
1050   }
1051 }
1052 
1053 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
1054 /*
1055 ** Return an integer value for one of the parameters to the opcode pOp
1056 ** determined by character c.
1057 */
1058 static int translateP(char c, const Op *pOp){
1059   if( c=='1' ) return pOp->p1;
1060   if( c=='2' ) return pOp->p2;
1061   if( c=='3' ) return pOp->p3;
1062   if( c=='4' ) return pOp->p4.i;
1063   return pOp->p5;
1064 }
1065 
1066 /*
1067 ** Compute a string for the "comment" field of a VDBE opcode listing.
1068 **
1069 ** The Synopsis: field in comments in the vdbe.c source file gets converted
1070 ** to an extra string that is appended to the sqlite3OpcodeName().  In the
1071 ** absence of other comments, this synopsis becomes the comment on the opcode.
1072 ** Some translation occurs:
1073 **
1074 **       "PX"      ->  "r[X]"
1075 **       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
1076 **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
1077 **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
1078 */
1079 static int displayComment(
1080   const Op *pOp,     /* The opcode to be commented */
1081   const char *zP4,   /* Previously obtained value for P4 */
1082   char *zTemp,       /* Write result here */
1083   int nTemp          /* Space available in zTemp[] */
1084 ){
1085   const char *zOpName;
1086   const char *zSynopsis;
1087   int nOpName;
1088   int ii, jj;
1089   zOpName = sqlite3OpcodeName(pOp->opcode);
1090   nOpName = sqlite3Strlen30(zOpName);
1091   if( zOpName[nOpName+1] ){
1092     int seenCom = 0;
1093     char c;
1094     zSynopsis = zOpName += nOpName + 1;
1095     for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
1096       if( c=='P' ){
1097         c = zSynopsis[++ii];
1098         if( c=='4' ){
1099           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
1100         }else if( c=='X' ){
1101           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
1102           seenCom = 1;
1103         }else{
1104           int v1 = translateP(c, pOp);
1105           int v2;
1106           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
1107           if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
1108             ii += 3;
1109             jj += sqlite3Strlen30(zTemp+jj);
1110             v2 = translateP(zSynopsis[ii], pOp);
1111             if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
1112               ii += 2;
1113               v2++;
1114             }
1115             if( v2>1 ){
1116               sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
1117             }
1118           }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
1119             ii += 4;
1120           }
1121         }
1122         jj += sqlite3Strlen30(zTemp+jj);
1123       }else{
1124         zTemp[jj++] = c;
1125       }
1126     }
1127     if( !seenCom && jj<nTemp-5 && pOp->zComment ){
1128       sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
1129       jj += sqlite3Strlen30(zTemp+jj);
1130     }
1131     if( jj<nTemp ) zTemp[jj] = 0;
1132   }else if( pOp->zComment ){
1133     sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
1134     jj = sqlite3Strlen30(zTemp);
1135   }else{
1136     zTemp[0] = 0;
1137     jj = 0;
1138   }
1139   return jj;
1140 }
1141 #endif /* SQLITE_DEBUG */
1142 
1143 #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
1144 /*
1145 ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
1146 ** that can be displayed in the P4 column of EXPLAIN output.
1147 */
1148 static void displayP4Expr(StrAccum *p, Expr *pExpr){
1149   const char *zOp = 0;
1150   switch( pExpr->op ){
1151     case TK_STRING:
1152       sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
1153       break;
1154     case TK_INTEGER:
1155       sqlite3XPrintf(p, "%d", pExpr->u.iValue);
1156       break;
1157     case TK_NULL:
1158       sqlite3XPrintf(p, "NULL");
1159       break;
1160     case TK_REGISTER: {
1161       sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
1162       break;
1163     }
1164     case TK_COLUMN: {
1165       if( pExpr->iColumn<0 ){
1166         sqlite3XPrintf(p, "rowid");
1167       }else{
1168         sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
1169       }
1170       break;
1171     }
1172     case TK_LT:      zOp = "LT";      break;
1173     case TK_LE:      zOp = "LE";      break;
1174     case TK_GT:      zOp = "GT";      break;
1175     case TK_GE:      zOp = "GE";      break;
1176     case TK_NE:      zOp = "NE";      break;
1177     case TK_EQ:      zOp = "EQ";      break;
1178     case TK_IS:      zOp = "IS";      break;
1179     case TK_ISNOT:   zOp = "ISNOT";   break;
1180     case TK_AND:     zOp = "AND";     break;
1181     case TK_OR:      zOp = "OR";      break;
1182     case TK_PLUS:    zOp = "ADD";     break;
1183     case TK_STAR:    zOp = "MUL";     break;
1184     case TK_MINUS:   zOp = "SUB";     break;
1185     case TK_REM:     zOp = "REM";     break;
1186     case TK_BITAND:  zOp = "BITAND";  break;
1187     case TK_BITOR:   zOp = "BITOR";   break;
1188     case TK_SLASH:   zOp = "DIV";     break;
1189     case TK_LSHIFT:  zOp = "LSHIFT";  break;
1190     case TK_RSHIFT:  zOp = "RSHIFT";  break;
1191     case TK_CONCAT:  zOp = "CONCAT";  break;
1192     case TK_UMINUS:  zOp = "MINUS";   break;
1193     case TK_UPLUS:   zOp = "PLUS";    break;
1194     case TK_BITNOT:  zOp = "BITNOT";  break;
1195     case TK_NOT:     zOp = "NOT";     break;
1196     case TK_ISNULL:  zOp = "ISNULL";  break;
1197     case TK_NOTNULL: zOp = "NOTNULL"; break;
1198 
1199     default:
1200       sqlite3XPrintf(p, "%s", "expr");
1201       break;
1202   }
1203 
1204   if( zOp ){
1205     sqlite3XPrintf(p, "%s(", zOp);
1206     displayP4Expr(p, pExpr->pLeft);
1207     if( pExpr->pRight ){
1208       sqlite3StrAccumAppend(p, ",", 1);
1209       displayP4Expr(p, pExpr->pRight);
1210     }
1211     sqlite3StrAccumAppend(p, ")", 1);
1212   }
1213 }
1214 #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
1215 
1216 
1217 #if VDBE_DISPLAY_P4
1218 /*
1219 ** Compute a string that describes the P4 parameter for an opcode.
1220 ** Use zTemp for any required temporary buffer space.
1221 */
1222 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
1223   char *zP4 = zTemp;
1224   StrAccum x;
1225   assert( nTemp>=20 );
1226   sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
1227   switch( pOp->p4type ){
1228     case P4_KEYINFO: {
1229       int j;
1230       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
1231       assert( pKeyInfo->aSortOrder!=0 );
1232       sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField);
1233       for(j=0; j<pKeyInfo->nField; j++){
1234         CollSeq *pColl = pKeyInfo->aColl[j];
1235         const char *zColl = pColl ? pColl->zName : "";
1236         if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
1237         sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
1238       }
1239       sqlite3StrAccumAppend(&x, ")", 1);
1240       break;
1241     }
1242 #ifdef SQLITE_ENABLE_CURSOR_HINTS
1243     case P4_EXPR: {
1244       displayP4Expr(&x, pOp->p4.pExpr);
1245       break;
1246     }
1247 #endif
1248     case P4_COLLSEQ: {
1249       CollSeq *pColl = pOp->p4.pColl;
1250       sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
1251       break;
1252     }
1253     case P4_FUNCDEF: {
1254       FuncDef *pDef = pOp->p4.pFunc;
1255       sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
1256       break;
1257     }
1258 #ifdef SQLITE_DEBUG
1259     case P4_FUNCCTX: {
1260       FuncDef *pDef = pOp->p4.pCtx->pFunc;
1261       sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
1262       break;
1263     }
1264 #endif
1265     case P4_INT64: {
1266       sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
1267       break;
1268     }
1269     case P4_INT32: {
1270       sqlite3XPrintf(&x, "%d", pOp->p4.i);
1271       break;
1272     }
1273     case P4_REAL: {
1274       sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
1275       break;
1276     }
1277     case P4_MEM: {
1278       Mem *pMem = pOp->p4.pMem;
1279       if( pMem->flags & MEM_Str ){
1280         zP4 = pMem->z;
1281       }else if( pMem->flags & MEM_Int ){
1282         sqlite3XPrintf(&x, "%lld", pMem->u.i);
1283       }else if( pMem->flags & MEM_Real ){
1284         sqlite3XPrintf(&x, "%.16g", pMem->u.r);
1285       }else if( pMem->flags & MEM_Null ){
1286         zP4 = "NULL";
1287       }else{
1288         assert( pMem->flags & MEM_Blob );
1289         zP4 = "(blob)";
1290       }
1291       break;
1292     }
1293 #ifndef SQLITE_OMIT_VIRTUALTABLE
1294     case P4_VTAB: {
1295       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
1296       sqlite3XPrintf(&x, "vtab:%p", pVtab);
1297       break;
1298     }
1299 #endif
1300     case P4_INTARRAY: {
1301       int i;
1302       int *ai = pOp->p4.ai;
1303       int n = ai[0];   /* The first element of an INTARRAY is always the
1304                        ** count of the number of elements to follow */
1305       for(i=1; i<n; i++){
1306         sqlite3XPrintf(&x, ",%d", ai[i]);
1307       }
1308       zTemp[0] = '[';
1309       sqlite3StrAccumAppend(&x, "]", 1);
1310       break;
1311     }
1312     case P4_SUBPROGRAM: {
1313       sqlite3XPrintf(&x, "program");
1314       break;
1315     }
1316     case P4_ADVANCE: {
1317       zTemp[0] = 0;
1318       break;
1319     }
1320     default: {
1321       zP4 = pOp->p4.z;
1322       if( zP4==0 ){
1323         zP4 = zTemp;
1324         zTemp[0] = 0;
1325       }
1326     }
1327   }
1328   sqlite3StrAccumFinish(&x);
1329   assert( zP4!=0 );
1330   return zP4;
1331 }
1332 #endif /* VDBE_DISPLAY_P4 */
1333 
1334 /*
1335 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
1336 **
1337 ** The prepared statements need to know in advance the complete set of
1338 ** attached databases that will be use.  A mask of these databases
1339 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
1340 ** p->btreeMask of databases that will require a lock.
1341 */
1342 void sqlite3VdbeUsesBtree(Vdbe *p, int i){
1343   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
1344   assert( i<(int)sizeof(p->btreeMask)*8 );
1345   DbMaskSet(p->btreeMask, i);
1346   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
1347     DbMaskSet(p->lockMask, i);
1348   }
1349 }
1350 
1351 #if !defined(SQLITE_OMIT_SHARED_CACHE)
1352 /*
1353 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
1354 ** this routine obtains the mutex associated with each BtShared structure
1355 ** that may be accessed by the VM passed as an argument. In doing so it also
1356 ** sets the BtShared.db member of each of the BtShared structures, ensuring
1357 ** that the correct busy-handler callback is invoked if required.
1358 **
1359 ** If SQLite is not threadsafe but does support shared-cache mode, then
1360 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
1361 ** of all of BtShared structures accessible via the database handle
1362 ** associated with the VM.
1363 **
1364 ** If SQLite is not threadsafe and does not support shared-cache mode, this
1365 ** function is a no-op.
1366 **
1367 ** The p->btreeMask field is a bitmask of all btrees that the prepared
1368 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
1369 ** corresponding to btrees that use shared cache.  Then the runtime of
1370 ** this routine is N*N.  But as N is rarely more than 1, this should not
1371 ** be a problem.
1372 */
1373 void sqlite3VdbeEnter(Vdbe *p){
1374   int i;
1375   sqlite3 *db;
1376   Db *aDb;
1377   int nDb;
1378   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
1379   db = p->db;
1380   aDb = db->aDb;
1381   nDb = db->nDb;
1382   for(i=0; i<nDb; i++){
1383     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
1384       sqlite3BtreeEnter(aDb[i].pBt);
1385     }
1386   }
1387 }
1388 #endif
1389 
1390 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
1391 /*
1392 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
1393 */
1394 static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
1395   int i;
1396   sqlite3 *db;
1397   Db *aDb;
1398   int nDb;
1399   db = p->db;
1400   aDb = db->aDb;
1401   nDb = db->nDb;
1402   for(i=0; i<nDb; i++){
1403     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
1404       sqlite3BtreeLeave(aDb[i].pBt);
1405     }
1406   }
1407 }
1408 void sqlite3VdbeLeave(Vdbe *p){
1409   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
1410   vdbeLeave(p);
1411 }
1412 #endif
1413 
1414 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
1415 /*
1416 ** Print a single opcode.  This routine is used for debugging only.
1417 */
1418 void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
1419   char *zP4;
1420   char zPtr[50];
1421   char zCom[100];
1422   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
1423   if( pOut==0 ) pOut = stdout;
1424   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
1425 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1426   displayComment(pOp, zP4, zCom, sizeof(zCom));
1427 #else
1428   zCom[0] = 0;
1429 #endif
1430   /* NB:  The sqlite3OpcodeName() function is implemented by code created
1431   ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
1432   ** information from the vdbe.c source text */
1433   fprintf(pOut, zFormat1, pc,
1434       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
1435       zCom
1436   );
1437   fflush(pOut);
1438 }
1439 #endif
1440 
1441 /*
1442 ** Release an array of N Mem elements
1443 */
1444 static void releaseMemArray(Mem *p, int N){
1445   if( p && N ){
1446     Mem *pEnd = &p[N];
1447     sqlite3 *db = p->db;
1448     if( db->pnBytesFreed ){
1449       do{
1450         if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
1451       }while( (++p)<pEnd );
1452       return;
1453     }
1454     do{
1455       assert( (&p[1])==pEnd || p[0].db==p[1].db );
1456       assert( sqlite3VdbeCheckMemInvariants(p) );
1457 
1458       /* This block is really an inlined version of sqlite3VdbeMemRelease()
1459       ** that takes advantage of the fact that the memory cell value is
1460       ** being set to NULL after releasing any dynamic resources.
1461       **
1462       ** The justification for duplicating code is that according to
1463       ** callgrind, this causes a certain test case to hit the CPU 4.7
1464       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
1465       ** sqlite3MemRelease() were called from here. With -O2, this jumps
1466       ** to 6.6 percent. The test case is inserting 1000 rows into a table
1467       ** with no indexes using a single prepared INSERT statement, bind()
1468       ** and reset(). Inserts are grouped into a transaction.
1469       */
1470       testcase( p->flags & MEM_Agg );
1471       testcase( p->flags & MEM_Dyn );
1472       testcase( p->flags & MEM_Frame );
1473       testcase( p->flags & MEM_RowSet );
1474       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
1475         sqlite3VdbeMemRelease(p);
1476       }else if( p->szMalloc ){
1477         sqlite3DbFree(db, p->zMalloc);
1478         p->szMalloc = 0;
1479       }
1480 
1481       p->flags = MEM_Undefined;
1482     }while( (++p)<pEnd );
1483   }
1484 }
1485 
1486 /*
1487 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
1488 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
1489 */
1490 void sqlite3VdbeFrameDelete(VdbeFrame *p){
1491   int i;
1492   Mem *aMem = VdbeFrameMem(p);
1493   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
1494   for(i=0; i<p->nChildCsr; i++){
1495     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
1496   }
1497   releaseMemArray(aMem, p->nChildMem);
1498   sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
1499   sqlite3DbFree(p->v->db, p);
1500 }
1501 
1502 #ifndef SQLITE_OMIT_EXPLAIN
1503 /*
1504 ** Give a listing of the program in the virtual machine.
1505 **
1506 ** The interface is the same as sqlite3VdbeExec().  But instead of
1507 ** running the code, it invokes the callback once for each instruction.
1508 ** This feature is used to implement "EXPLAIN".
1509 **
1510 ** When p->explain==1, each instruction is listed.  When
1511 ** p->explain==2, only OP_Explain instructions are listed and these
1512 ** are shown in a different format.  p->explain==2 is used to implement
1513 ** EXPLAIN QUERY PLAN.
1514 **
1515 ** When p->explain==1, first the main program is listed, then each of
1516 ** the trigger subprograms are listed one by one.
1517 */
1518 int sqlite3VdbeList(
1519   Vdbe *p                   /* The VDBE */
1520 ){
1521   int nRow;                            /* Stop when row count reaches this */
1522   int nSub = 0;                        /* Number of sub-vdbes seen so far */
1523   SubProgram **apSub = 0;              /* Array of sub-vdbes */
1524   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
1525   sqlite3 *db = p->db;                 /* The database connection */
1526   int i;                               /* Loop counter */
1527   int rc = SQLITE_OK;                  /* Return code */
1528   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
1529 
1530   assert( p->explain );
1531   assert( p->magic==VDBE_MAGIC_RUN );
1532   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
1533 
1534   /* Even though this opcode does not use dynamic strings for
1535   ** the result, result columns may become dynamic if the user calls
1536   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
1537   */
1538   releaseMemArray(pMem, 8);
1539   p->pResultSet = 0;
1540 
1541   if( p->rc==SQLITE_NOMEM_BKPT ){
1542     /* This happens if a malloc() inside a call to sqlite3_column_text() or
1543     ** sqlite3_column_text16() failed.  */
1544     sqlite3OomFault(db);
1545     return SQLITE_ERROR;
1546   }
1547 
1548   /* When the number of output rows reaches nRow, that means the
1549   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
1550   ** nRow is the sum of the number of rows in the main program, plus
1551   ** the sum of the number of rows in all trigger subprograms encountered
1552   ** so far.  The nRow value will increase as new trigger subprograms are
1553   ** encountered, but p->pc will eventually catch up to nRow.
1554   */
1555   nRow = p->nOp;
1556   if( p->explain==1 ){
1557     /* The first 8 memory cells are used for the result set.  So we will
1558     ** commandeer the 9th cell to use as storage for an array of pointers
1559     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
1560     ** cells.  */
1561     assert( p->nMem>9 );
1562     pSub = &p->aMem[9];
1563     if( pSub->flags&MEM_Blob ){
1564       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
1565       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
1566       nSub = pSub->n/sizeof(Vdbe*);
1567       apSub = (SubProgram **)pSub->z;
1568     }
1569     for(i=0; i<nSub; i++){
1570       nRow += apSub[i]->nOp;
1571     }
1572   }
1573 
1574   do{
1575     i = p->pc++;
1576   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
1577   if( i>=nRow ){
1578     p->rc = SQLITE_OK;
1579     rc = SQLITE_DONE;
1580   }else if( db->u1.isInterrupted ){
1581     p->rc = SQLITE_INTERRUPT;
1582     rc = SQLITE_ERROR;
1583     sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
1584   }else{
1585     char *zP4;
1586     Op *pOp;
1587     if( i<p->nOp ){
1588       /* The output line number is small enough that we are still in the
1589       ** main program. */
1590       pOp = &p->aOp[i];
1591     }else{
1592       /* We are currently listing subprograms.  Figure out which one and
1593       ** pick up the appropriate opcode. */
1594       int j;
1595       i -= p->nOp;
1596       for(j=0; i>=apSub[j]->nOp; j++){
1597         i -= apSub[j]->nOp;
1598       }
1599       pOp = &apSub[j]->aOp[i];
1600     }
1601     if( p->explain==1 ){
1602       pMem->flags = MEM_Int;
1603       pMem->u.i = i;                                /* Program counter */
1604       pMem++;
1605 
1606       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
1607       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
1608       assert( pMem->z!=0 );
1609       pMem->n = sqlite3Strlen30(pMem->z);
1610       pMem->enc = SQLITE_UTF8;
1611       pMem++;
1612 
1613       /* When an OP_Program opcode is encounter (the only opcode that has
1614       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
1615       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
1616       ** has not already been seen.
1617       */
1618       if( pOp->p4type==P4_SUBPROGRAM ){
1619         int nByte = (nSub+1)*sizeof(SubProgram*);
1620         int j;
1621         for(j=0; j<nSub; j++){
1622           if( apSub[j]==pOp->p4.pProgram ) break;
1623         }
1624         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
1625           apSub = (SubProgram **)pSub->z;
1626           apSub[nSub++] = pOp->p4.pProgram;
1627           pSub->flags |= MEM_Blob;
1628           pSub->n = nSub*sizeof(SubProgram*);
1629         }
1630       }
1631     }
1632 
1633     pMem->flags = MEM_Int;
1634     pMem->u.i = pOp->p1;                          /* P1 */
1635     pMem++;
1636 
1637     pMem->flags = MEM_Int;
1638     pMem->u.i = pOp->p2;                          /* P2 */
1639     pMem++;
1640 
1641     pMem->flags = MEM_Int;
1642     pMem->u.i = pOp->p3;                          /* P3 */
1643     pMem++;
1644 
1645     if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
1646       assert( p->db->mallocFailed );
1647       return SQLITE_ERROR;
1648     }
1649     pMem->flags = MEM_Str|MEM_Term;
1650     zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
1651     if( zP4!=pMem->z ){
1652       sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
1653     }else{
1654       assert( pMem->z!=0 );
1655       pMem->n = sqlite3Strlen30(pMem->z);
1656       pMem->enc = SQLITE_UTF8;
1657     }
1658     pMem++;
1659 
1660     if( p->explain==1 ){
1661       if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
1662         assert( p->db->mallocFailed );
1663         return SQLITE_ERROR;
1664       }
1665       pMem->flags = MEM_Str|MEM_Term;
1666       pMem->n = 2;
1667       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
1668       pMem->enc = SQLITE_UTF8;
1669       pMem++;
1670 
1671 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1672       if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
1673         assert( p->db->mallocFailed );
1674         return SQLITE_ERROR;
1675       }
1676       pMem->flags = MEM_Str|MEM_Term;
1677       pMem->n = displayComment(pOp, zP4, pMem->z, 500);
1678       pMem->enc = SQLITE_UTF8;
1679 #else
1680       pMem->flags = MEM_Null;                       /* Comment */
1681 #endif
1682     }
1683 
1684     p->nResColumn = 8 - 4*(p->explain-1);
1685     p->pResultSet = &p->aMem[1];
1686     p->rc = SQLITE_OK;
1687     rc = SQLITE_ROW;
1688   }
1689   return rc;
1690 }
1691 #endif /* SQLITE_OMIT_EXPLAIN */
1692 
1693 #ifdef SQLITE_DEBUG
1694 /*
1695 ** Print the SQL that was used to generate a VDBE program.
1696 */
1697 void sqlite3VdbePrintSql(Vdbe *p){
1698   const char *z = 0;
1699   if( p->zSql ){
1700     z = p->zSql;
1701   }else if( p->nOp>=1 ){
1702     const VdbeOp *pOp = &p->aOp[0];
1703     if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
1704       z = pOp->p4.z;
1705       while( sqlite3Isspace(*z) ) z++;
1706     }
1707   }
1708   if( z ) printf("SQL: [%s]\n", z);
1709 }
1710 #endif
1711 
1712 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
1713 /*
1714 ** Print an IOTRACE message showing SQL content.
1715 */
1716 void sqlite3VdbeIOTraceSql(Vdbe *p){
1717   int nOp = p->nOp;
1718   VdbeOp *pOp;
1719   if( sqlite3IoTrace==0 ) return;
1720   if( nOp<1 ) return;
1721   pOp = &p->aOp[0];
1722   if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
1723     int i, j;
1724     char z[1000];
1725     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
1726     for(i=0; sqlite3Isspace(z[i]); i++){}
1727     for(j=0; z[i]; i++){
1728       if( sqlite3Isspace(z[i]) ){
1729         if( z[i-1]!=' ' ){
1730           z[j++] = ' ';
1731         }
1732       }else{
1733         z[j++] = z[i];
1734       }
1735     }
1736     z[j] = 0;
1737     sqlite3IoTrace("SQL %s\n", z);
1738   }
1739 }
1740 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
1741 
1742 /* An instance of this object describes bulk memory available for use
1743 ** by subcomponents of a prepared statement.  Space is allocated out
1744 ** of a ReusableSpace object by the allocSpace() routine below.
1745 */
1746 struct ReusableSpace {
1747   u8 *pSpace;          /* Available memory */
1748   int nFree;           /* Bytes of available memory */
1749   int nNeeded;         /* Total bytes that could not be allocated */
1750 };
1751 
1752 /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
1753 ** from the ReusableSpace object.  Return a pointer to the allocated
1754 ** memory on success.  If insufficient memory is available in the
1755 ** ReusableSpace object, increase the ReusableSpace.nNeeded
1756 ** value by the amount needed and return NULL.
1757 **
1758 ** If pBuf is not initially NULL, that means that the memory has already
1759 ** been allocated by a prior call to this routine, so just return a copy
1760 ** of pBuf and leave ReusableSpace unchanged.
1761 **
1762 ** This allocator is employed to repurpose unused slots at the end of the
1763 ** opcode array of prepared state for other memory needs of the prepared
1764 ** statement.
1765 */
1766 static void *allocSpace(
1767   struct ReusableSpace *p,  /* Bulk memory available for allocation */
1768   void *pBuf,               /* Pointer to a prior allocation */
1769   int nByte                 /* Bytes of memory needed */
1770 ){
1771   assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
1772   if( pBuf==0 ){
1773     nByte = ROUND8(nByte);
1774     if( nByte <= p->nFree ){
1775       p->nFree -= nByte;
1776       pBuf = &p->pSpace[p->nFree];
1777     }else{
1778       p->nNeeded += nByte;
1779     }
1780   }
1781   assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
1782   return pBuf;
1783 }
1784 
1785 /*
1786 ** Rewind the VDBE back to the beginning in preparation for
1787 ** running it.
1788 */
1789 void sqlite3VdbeRewind(Vdbe *p){
1790 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
1791   int i;
1792 #endif
1793   assert( p!=0 );
1794   assert( p->magic==VDBE_MAGIC_INIT );
1795 
1796   /* There should be at least one opcode.
1797   */
1798   assert( p->nOp>0 );
1799 
1800   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
1801   p->magic = VDBE_MAGIC_RUN;
1802 
1803 #ifdef SQLITE_DEBUG
1804   for(i=0; i<p->nMem; i++){
1805     assert( p->aMem[i].db==p->db );
1806   }
1807 #endif
1808   p->pc = -1;
1809   p->rc = SQLITE_OK;
1810   p->errorAction = OE_Abort;
1811   p->nChange = 0;
1812   p->cacheCtr = 1;
1813   p->minWriteFileFormat = 255;
1814   p->iStatement = 0;
1815   p->nFkConstraint = 0;
1816 #ifdef VDBE_PROFILE
1817   for(i=0; i<p->nOp; i++){
1818     p->aOp[i].cnt = 0;
1819     p->aOp[i].cycles = 0;
1820   }
1821 #endif
1822 }
1823 
1824 /*
1825 ** Prepare a virtual machine for execution for the first time after
1826 ** creating the virtual machine.  This involves things such
1827 ** as allocating registers and initializing the program counter.
1828 ** After the VDBE has be prepped, it can be executed by one or more
1829 ** calls to sqlite3VdbeExec().
1830 **
1831 ** This function may be called exactly once on each virtual machine.
1832 ** After this routine is called the VM has been "packaged" and is ready
1833 ** to run.  After this routine is called, further calls to
1834 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
1835 ** the Vdbe from the Parse object that helped generate it so that the
1836 ** the Vdbe becomes an independent entity and the Parse object can be
1837 ** destroyed.
1838 **
1839 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
1840 ** to its initial state after it has been run.
1841 */
1842 void sqlite3VdbeMakeReady(
1843   Vdbe *p,                       /* The VDBE */
1844   Parse *pParse                  /* Parsing context */
1845 ){
1846   sqlite3 *db;                   /* The database connection */
1847   int nVar;                      /* Number of parameters */
1848   int nMem;                      /* Number of VM memory registers */
1849   int nCursor;                   /* Number of cursors required */
1850   int nArg;                      /* Number of arguments in subprograms */
1851   int nOnce;                     /* Number of OP_Once instructions */
1852   int n;                         /* Loop counter */
1853   struct ReusableSpace x;        /* Reusable bulk memory */
1854 
1855   assert( p!=0 );
1856   assert( p->nOp>0 );
1857   assert( pParse!=0 );
1858   assert( p->magic==VDBE_MAGIC_INIT );
1859   assert( pParse==p->pParse );
1860   db = p->db;
1861   assert( db->mallocFailed==0 );
1862   nVar = pParse->nVar;
1863   nMem = pParse->nMem;
1864   nCursor = pParse->nTab;
1865   nArg = pParse->nMaxArg;
1866   nOnce = pParse->nOnce;
1867   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
1868 
1869   /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
1870   ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
1871   ** space at the end of aMem[] for cursors 1 and greater.
1872   ** See also: allocateCursor().
1873   */
1874   nMem += nCursor;
1875   if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
1876 
1877   /* Figure out how much reusable memory is available at the end of the
1878   ** opcode array.  This extra memory will be reallocated for other elements
1879   ** of the prepared statement.
1880   */
1881   n = ROUND8(sizeof(Op)*p->nOp);              /* Bytes of opcode memory used */
1882   x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
1883   assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
1884   x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */
1885   assert( x.nFree>=0 );
1886   if( x.nFree>0 ){
1887     memset(x.pSpace, 0, x.nFree);
1888     assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
1889   }
1890 
1891   resolveP2Values(p, &nArg);
1892   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
1893   if( pParse->explain && nMem<10 ){
1894     nMem = 10;
1895   }
1896   p->expired = 0;
1897 
1898   /* Memory for registers, parameters, cursor, etc, is allocated in one or two
1899   ** passes.  On the first pass, we try to reuse unused memory at the
1900   ** end of the opcode array.  If we are unable to satisfy all memory
1901   ** requirements by reusing the opcode array tail, then the second
1902   ** pass will fill in the remainder using a fresh memory allocation.
1903   **
1904   ** This two-pass approach that reuses as much memory as possible from
1905   ** the leftover memory at the end of the opcode array.  This can significantly
1906   ** reduce the amount of memory held by a prepared statement.
1907   */
1908   do {
1909     x.nNeeded = 0;
1910     p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
1911     p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
1912     p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
1913     p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
1914     p->aOnceFlag = allocSpace(&x, p->aOnceFlag, nOnce);
1915 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
1916     p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
1917 #endif
1918     if( x.nNeeded==0 ) break;
1919     x.pSpace = p->pFree = sqlite3DbMallocZero(db, x.nNeeded);
1920     x.nFree = x.nNeeded;
1921   }while( !db->mallocFailed );
1922 
1923   p->nCursor = nCursor;
1924   p->nOnceFlag = nOnce;
1925   if( p->aVar ){
1926     p->nVar = (ynVar)nVar;
1927     for(n=0; n<nVar; n++){
1928       p->aVar[n].flags = MEM_Null;
1929       p->aVar[n].db = db;
1930     }
1931   }
1932   p->nzVar = pParse->nzVar;
1933   p->azVar = pParse->azVar;
1934   pParse->nzVar =  0;
1935   pParse->azVar = 0;
1936   if( p->aMem ){
1937     p->nMem = nMem;
1938     for(n=0; n<nMem; n++){
1939       p->aMem[n].flags = MEM_Undefined;
1940       p->aMem[n].db = db;
1941     }
1942   }
1943   p->explain = pParse->explain;
1944   sqlite3VdbeRewind(p);
1945 }
1946 
1947 /*
1948 ** Close a VDBE cursor and release all the resources that cursor
1949 ** happens to hold.
1950 */
1951 void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
1952   if( pCx==0 ){
1953     return;
1954   }
1955   assert( pCx->pBt==0 || pCx->eCurType==CURTYPE_BTREE );
1956   switch( pCx->eCurType ){
1957     case CURTYPE_SORTER: {
1958       sqlite3VdbeSorterClose(p->db, pCx);
1959       break;
1960     }
1961     case CURTYPE_BTREE: {
1962       if( pCx->pBt ){
1963         sqlite3BtreeClose(pCx->pBt);
1964         /* The pCx->pCursor will be close automatically, if it exists, by
1965         ** the call above. */
1966       }else{
1967         assert( pCx->uc.pCursor!=0 );
1968         sqlite3BtreeCloseCursor(pCx->uc.pCursor);
1969       }
1970       break;
1971     }
1972 #ifndef SQLITE_OMIT_VIRTUALTABLE
1973     case CURTYPE_VTAB: {
1974       sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
1975       const sqlite3_module *pModule = pVCur->pVtab->pModule;
1976       assert( pVCur->pVtab->nRef>0 );
1977       pVCur->pVtab->nRef--;
1978       pModule->xClose(pVCur);
1979       break;
1980     }
1981 #endif
1982   }
1983 }
1984 
1985 /*
1986 ** Close all cursors in the current frame.
1987 */
1988 static void closeCursorsInFrame(Vdbe *p){
1989   if( p->apCsr ){
1990     int i;
1991     for(i=0; i<p->nCursor; i++){
1992       VdbeCursor *pC = p->apCsr[i];
1993       if( pC ){
1994         sqlite3VdbeFreeCursor(p, pC);
1995         p->apCsr[i] = 0;
1996       }
1997     }
1998   }
1999 }
2000 
2001 /*
2002 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
2003 ** is used, for example, when a trigger sub-program is halted to restore
2004 ** control to the main program.
2005 */
2006 int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
2007   Vdbe *v = pFrame->v;
2008   closeCursorsInFrame(v);
2009 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2010   v->anExec = pFrame->anExec;
2011 #endif
2012   v->aOnceFlag = pFrame->aOnceFlag;
2013   v->nOnceFlag = pFrame->nOnceFlag;
2014   v->aOp = pFrame->aOp;
2015   v->nOp = pFrame->nOp;
2016   v->aMem = pFrame->aMem;
2017   v->nMem = pFrame->nMem;
2018   v->apCsr = pFrame->apCsr;
2019   v->nCursor = pFrame->nCursor;
2020   v->db->lastRowid = pFrame->lastRowid;
2021   v->nChange = pFrame->nChange;
2022   v->db->nChange = pFrame->nDbChange;
2023   sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
2024   v->pAuxData = pFrame->pAuxData;
2025   pFrame->pAuxData = 0;
2026   return pFrame->pc;
2027 }
2028 
2029 /*
2030 ** Close all cursors.
2031 **
2032 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
2033 ** cell array. This is necessary as the memory cell array may contain
2034 ** pointers to VdbeFrame objects, which may in turn contain pointers to
2035 ** open cursors.
2036 */
2037 static void closeAllCursors(Vdbe *p){
2038   if( p->pFrame ){
2039     VdbeFrame *pFrame;
2040     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
2041     sqlite3VdbeFrameRestore(pFrame);
2042     p->pFrame = 0;
2043     p->nFrame = 0;
2044   }
2045   assert( p->nFrame==0 );
2046   closeCursorsInFrame(p);
2047   if( p->aMem ){
2048     releaseMemArray(p->aMem, p->nMem);
2049   }
2050   while( p->pDelFrame ){
2051     VdbeFrame *pDel = p->pDelFrame;
2052     p->pDelFrame = pDel->pParent;
2053     sqlite3VdbeFrameDelete(pDel);
2054   }
2055 
2056   /* Delete any auxdata allocations made by the VM */
2057   if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
2058   assert( p->pAuxData==0 );
2059 }
2060 
2061 /*
2062 ** Clean up the VM after a single run.
2063 */
2064 static void Cleanup(Vdbe *p){
2065   sqlite3 *db = p->db;
2066 
2067 #ifdef SQLITE_DEBUG
2068   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
2069   ** Vdbe.aMem[] arrays have already been cleaned up.  */
2070   int i;
2071   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
2072   if( p->aMem ){
2073     for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
2074   }
2075 #endif
2076 
2077   sqlite3DbFree(db, p->zErrMsg);
2078   p->zErrMsg = 0;
2079   p->pResultSet = 0;
2080 }
2081 
2082 /*
2083 ** Set the number of result columns that will be returned by this SQL
2084 ** statement. This is now set at compile time, rather than during
2085 ** execution of the vdbe program so that sqlite3_column_count() can
2086 ** be called on an SQL statement before sqlite3_step().
2087 */
2088 void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
2089   Mem *pColName;
2090   int n;
2091   sqlite3 *db = p->db;
2092 
2093   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
2094   sqlite3DbFree(db, p->aColName);
2095   n = nResColumn*COLNAME_N;
2096   p->nResColumn = (u16)nResColumn;
2097   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
2098   if( p->aColName==0 ) return;
2099   while( n-- > 0 ){
2100     pColName->flags = MEM_Null;
2101     pColName->db = p->db;
2102     pColName++;
2103   }
2104 }
2105 
2106 /*
2107 ** Set the name of the idx'th column to be returned by the SQL statement.
2108 ** zName must be a pointer to a nul terminated string.
2109 **
2110 ** This call must be made after a call to sqlite3VdbeSetNumCols().
2111 **
2112 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
2113 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
2114 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
2115 */
2116 int sqlite3VdbeSetColName(
2117   Vdbe *p,                         /* Vdbe being configured */
2118   int idx,                         /* Index of column zName applies to */
2119   int var,                         /* One of the COLNAME_* constants */
2120   const char *zName,               /* Pointer to buffer containing name */
2121   void (*xDel)(void*)              /* Memory management strategy for zName */
2122 ){
2123   int rc;
2124   Mem *pColName;
2125   assert( idx<p->nResColumn );
2126   assert( var<COLNAME_N );
2127   if( p->db->mallocFailed ){
2128     assert( !zName || xDel!=SQLITE_DYNAMIC );
2129     return SQLITE_NOMEM_BKPT;
2130   }
2131   assert( p->aColName!=0 );
2132   pColName = &(p->aColName[idx+var*p->nResColumn]);
2133   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
2134   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
2135   return rc;
2136 }
2137 
2138 /*
2139 ** A read or write transaction may or may not be active on database handle
2140 ** db. If a transaction is active, commit it. If there is a
2141 ** write-transaction spanning more than one database file, this routine
2142 ** takes care of the master journal trickery.
2143 */
2144 static int vdbeCommit(sqlite3 *db, Vdbe *p){
2145   int i;
2146   int nTrans = 0;  /* Number of databases with an active write-transaction
2147                    ** that are candidates for a two-phase commit using a
2148                    ** master-journal */
2149   int rc = SQLITE_OK;
2150   int needXcommit = 0;
2151 
2152 #ifdef SQLITE_OMIT_VIRTUALTABLE
2153   /* With this option, sqlite3VtabSync() is defined to be simply
2154   ** SQLITE_OK so p is not used.
2155   */
2156   UNUSED_PARAMETER(p);
2157 #endif
2158 
2159   /* Before doing anything else, call the xSync() callback for any
2160   ** virtual module tables written in this transaction. This has to
2161   ** be done before determining whether a master journal file is
2162   ** required, as an xSync() callback may add an attached database
2163   ** to the transaction.
2164   */
2165   rc = sqlite3VtabSync(db, p);
2166 
2167   /* This loop determines (a) if the commit hook should be invoked and
2168   ** (b) how many database files have open write transactions, not
2169   ** including the temp database. (b) is important because if more than
2170   ** one database file has an open write transaction, a master journal
2171   ** file is required for an atomic commit.
2172   */
2173   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2174     Btree *pBt = db->aDb[i].pBt;
2175     if( sqlite3BtreeIsInTrans(pBt) ){
2176       /* Whether or not a database might need a master journal depends upon
2177       ** its journal mode (among other things).  This matrix determines which
2178       ** journal modes use a master journal and which do not */
2179       static const u8 aMJNeeded[] = {
2180         /* DELETE   */  1,
2181         /* PERSIST   */ 1,
2182         /* OFF       */ 0,
2183         /* TRUNCATE  */ 1,
2184         /* MEMORY    */ 0,
2185         /* WAL       */ 0
2186       };
2187       Pager *pPager;   /* Pager associated with pBt */
2188       needXcommit = 1;
2189       sqlite3BtreeEnter(pBt);
2190       pPager = sqlite3BtreePager(pBt);
2191       if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
2192        && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
2193       ){
2194         assert( i!=1 );
2195         nTrans++;
2196       }
2197       rc = sqlite3PagerExclusiveLock(pPager);
2198       sqlite3BtreeLeave(pBt);
2199     }
2200   }
2201   if( rc!=SQLITE_OK ){
2202     return rc;
2203   }
2204 
2205   /* If there are any write-transactions at all, invoke the commit hook */
2206   if( needXcommit && db->xCommitCallback ){
2207     rc = db->xCommitCallback(db->pCommitArg);
2208     if( rc ){
2209       return SQLITE_CONSTRAINT_COMMITHOOK;
2210     }
2211   }
2212 
2213   /* The simple case - no more than one database file (not counting the
2214   ** TEMP database) has a transaction active.   There is no need for the
2215   ** master-journal.
2216   **
2217   ** If the return value of sqlite3BtreeGetFilename() is a zero length
2218   ** string, it means the main database is :memory: or a temp file.  In
2219   ** that case we do not support atomic multi-file commits, so use the
2220   ** simple case then too.
2221   */
2222   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
2223    || nTrans<=1
2224   ){
2225     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2226       Btree *pBt = db->aDb[i].pBt;
2227       if( pBt ){
2228         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
2229       }
2230     }
2231 
2232     /* Do the commit only if all databases successfully complete phase 1.
2233     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
2234     ** IO error while deleting or truncating a journal file. It is unlikely,
2235     ** but could happen. In this case abandon processing and return the error.
2236     */
2237     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2238       Btree *pBt = db->aDb[i].pBt;
2239       if( pBt ){
2240         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
2241       }
2242     }
2243     if( rc==SQLITE_OK ){
2244       sqlite3VtabCommit(db);
2245     }
2246   }
2247 
2248   /* The complex case - There is a multi-file write-transaction active.
2249   ** This requires a master journal file to ensure the transaction is
2250   ** committed atomically.
2251   */
2252 #ifndef SQLITE_OMIT_DISKIO
2253   else{
2254     sqlite3_vfs *pVfs = db->pVfs;
2255     char *zMaster = 0;   /* File-name for the master journal */
2256     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
2257     sqlite3_file *pMaster = 0;
2258     i64 offset = 0;
2259     int res;
2260     int retryCount = 0;
2261     int nMainFile;
2262 
2263     /* Select a master journal file name */
2264     nMainFile = sqlite3Strlen30(zMainFile);
2265     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
2266     if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
2267     do {
2268       u32 iRandom;
2269       if( retryCount ){
2270         if( retryCount>100 ){
2271           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
2272           sqlite3OsDelete(pVfs, zMaster, 0);
2273           break;
2274         }else if( retryCount==1 ){
2275           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
2276         }
2277       }
2278       retryCount++;
2279       sqlite3_randomness(sizeof(iRandom), &iRandom);
2280       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
2281                                (iRandom>>8)&0xffffff, iRandom&0xff);
2282       /* The antipenultimate character of the master journal name must
2283       ** be "9" to avoid name collisions when using 8+3 filenames. */
2284       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
2285       sqlite3FileSuffix3(zMainFile, zMaster);
2286       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
2287     }while( rc==SQLITE_OK && res );
2288     if( rc==SQLITE_OK ){
2289       /* Open the master journal. */
2290       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
2291           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
2292           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
2293       );
2294     }
2295     if( rc!=SQLITE_OK ){
2296       sqlite3DbFree(db, zMaster);
2297       return rc;
2298     }
2299 
2300     /* Write the name of each database file in the transaction into the new
2301     ** master journal file. If an error occurs at this point close
2302     ** and delete the master journal file. All the individual journal files
2303     ** still have 'null' as the master journal pointer, so they will roll
2304     ** back independently if a failure occurs.
2305     */
2306     for(i=0; i<db->nDb; i++){
2307       Btree *pBt = db->aDb[i].pBt;
2308       if( sqlite3BtreeIsInTrans(pBt) ){
2309         char const *zFile = sqlite3BtreeGetJournalname(pBt);
2310         if( zFile==0 ){
2311           continue;  /* Ignore TEMP and :memory: databases */
2312         }
2313         assert( zFile[0]!=0 );
2314         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
2315         offset += sqlite3Strlen30(zFile)+1;
2316         if( rc!=SQLITE_OK ){
2317           sqlite3OsCloseFree(pMaster);
2318           sqlite3OsDelete(pVfs, zMaster, 0);
2319           sqlite3DbFree(db, zMaster);
2320           return rc;
2321         }
2322       }
2323     }
2324 
2325     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
2326     ** flag is set this is not required.
2327     */
2328     if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
2329      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
2330     ){
2331       sqlite3OsCloseFree(pMaster);
2332       sqlite3OsDelete(pVfs, zMaster, 0);
2333       sqlite3DbFree(db, zMaster);
2334       return rc;
2335     }
2336 
2337     /* Sync all the db files involved in the transaction. The same call
2338     ** sets the master journal pointer in each individual journal. If
2339     ** an error occurs here, do not delete the master journal file.
2340     **
2341     ** If the error occurs during the first call to
2342     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
2343     ** master journal file will be orphaned. But we cannot delete it,
2344     ** in case the master journal file name was written into the journal
2345     ** file before the failure occurred.
2346     */
2347     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2348       Btree *pBt = db->aDb[i].pBt;
2349       if( pBt ){
2350         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
2351       }
2352     }
2353     sqlite3OsCloseFree(pMaster);
2354     assert( rc!=SQLITE_BUSY );
2355     if( rc!=SQLITE_OK ){
2356       sqlite3DbFree(db, zMaster);
2357       return rc;
2358     }
2359 
2360     /* Delete the master journal file. This commits the transaction. After
2361     ** doing this the directory is synced again before any individual
2362     ** transaction files are deleted.
2363     */
2364     rc = sqlite3OsDelete(pVfs, zMaster, 1);
2365     sqlite3DbFree(db, zMaster);
2366     zMaster = 0;
2367     if( rc ){
2368       return rc;
2369     }
2370 
2371     /* All files and directories have already been synced, so the following
2372     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
2373     ** deleting or truncating journals. If something goes wrong while
2374     ** this is happening we don't really care. The integrity of the
2375     ** transaction is already guaranteed, but some stray 'cold' journals
2376     ** may be lying around. Returning an error code won't help matters.
2377     */
2378     disable_simulated_io_errors();
2379     sqlite3BeginBenignMalloc();
2380     for(i=0; i<db->nDb; i++){
2381       Btree *pBt = db->aDb[i].pBt;
2382       if( pBt ){
2383         sqlite3BtreeCommitPhaseTwo(pBt, 1);
2384       }
2385     }
2386     sqlite3EndBenignMalloc();
2387     enable_simulated_io_errors();
2388 
2389     sqlite3VtabCommit(db);
2390   }
2391 #endif
2392 
2393   return rc;
2394 }
2395 
2396 /*
2397 ** This routine checks that the sqlite3.nVdbeActive count variable
2398 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
2399 ** currently active. An assertion fails if the two counts do not match.
2400 ** This is an internal self-check only - it is not an essential processing
2401 ** step.
2402 **
2403 ** This is a no-op if NDEBUG is defined.
2404 */
2405 #ifndef NDEBUG
2406 static void checkActiveVdbeCnt(sqlite3 *db){
2407   Vdbe *p;
2408   int cnt = 0;
2409   int nWrite = 0;
2410   int nRead = 0;
2411   p = db->pVdbe;
2412   while( p ){
2413     if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
2414       cnt++;
2415       if( p->readOnly==0 ) nWrite++;
2416       if( p->bIsReader ) nRead++;
2417     }
2418     p = p->pNext;
2419   }
2420   assert( cnt==db->nVdbeActive );
2421   assert( nWrite==db->nVdbeWrite );
2422   assert( nRead==db->nVdbeRead );
2423 }
2424 #else
2425 #define checkActiveVdbeCnt(x)
2426 #endif
2427 
2428 /*
2429 ** If the Vdbe passed as the first argument opened a statement-transaction,
2430 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
2431 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
2432 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
2433 ** statement transaction is committed.
2434 **
2435 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
2436 ** Otherwise SQLITE_OK.
2437 */
2438 int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
2439   sqlite3 *const db = p->db;
2440   int rc = SQLITE_OK;
2441 
2442   /* If p->iStatement is greater than zero, then this Vdbe opened a
2443   ** statement transaction that should be closed here. The only exception
2444   ** is that an IO error may have occurred, causing an emergency rollback.
2445   ** In this case (db->nStatement==0), and there is nothing to do.
2446   */
2447   if( db->nStatement && p->iStatement ){
2448     int i;
2449     const int iSavepoint = p->iStatement-1;
2450 
2451     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
2452     assert( db->nStatement>0 );
2453     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
2454 
2455     for(i=0; i<db->nDb; i++){
2456       int rc2 = SQLITE_OK;
2457       Btree *pBt = db->aDb[i].pBt;
2458       if( pBt ){
2459         if( eOp==SAVEPOINT_ROLLBACK ){
2460           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
2461         }
2462         if( rc2==SQLITE_OK ){
2463           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
2464         }
2465         if( rc==SQLITE_OK ){
2466           rc = rc2;
2467         }
2468       }
2469     }
2470     db->nStatement--;
2471     p->iStatement = 0;
2472 
2473     if( rc==SQLITE_OK ){
2474       if( eOp==SAVEPOINT_ROLLBACK ){
2475         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
2476       }
2477       if( rc==SQLITE_OK ){
2478         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
2479       }
2480     }
2481 
2482     /* If the statement transaction is being rolled back, also restore the
2483     ** database handles deferred constraint counter to the value it had when
2484     ** the statement transaction was opened.  */
2485     if( eOp==SAVEPOINT_ROLLBACK ){
2486       db->nDeferredCons = p->nStmtDefCons;
2487       db->nDeferredImmCons = p->nStmtDefImmCons;
2488     }
2489   }
2490   return rc;
2491 }
2492 
2493 /*
2494 ** This function is called when a transaction opened by the database
2495 ** handle associated with the VM passed as an argument is about to be
2496 ** committed. If there are outstanding deferred foreign key constraint
2497 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
2498 **
2499 ** If there are outstanding FK violations and this function returns
2500 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
2501 ** and write an error message to it. Then return SQLITE_ERROR.
2502 */
2503 #ifndef SQLITE_OMIT_FOREIGN_KEY
2504 int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
2505   sqlite3 *db = p->db;
2506   if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
2507    || (!deferred && p->nFkConstraint>0)
2508   ){
2509     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
2510     p->errorAction = OE_Abort;
2511     sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
2512     return SQLITE_ERROR;
2513   }
2514   return SQLITE_OK;
2515 }
2516 #endif
2517 
2518 /*
2519 ** This routine is called the when a VDBE tries to halt.  If the VDBE
2520 ** has made changes and is in autocommit mode, then commit those
2521 ** changes.  If a rollback is needed, then do the rollback.
2522 **
2523 ** This routine is the only way to move the state of a VM from
2524 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
2525 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
2526 **
2527 ** Return an error code.  If the commit could not complete because of
2528 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
2529 ** means the close did not happen and needs to be repeated.
2530 */
2531 int sqlite3VdbeHalt(Vdbe *p){
2532   int rc;                         /* Used to store transient return codes */
2533   sqlite3 *db = p->db;
2534 
2535   /* This function contains the logic that determines if a statement or
2536   ** transaction will be committed or rolled back as a result of the
2537   ** execution of this virtual machine.
2538   **
2539   ** If any of the following errors occur:
2540   **
2541   **     SQLITE_NOMEM
2542   **     SQLITE_IOERR
2543   **     SQLITE_FULL
2544   **     SQLITE_INTERRUPT
2545   **
2546   ** Then the internal cache might have been left in an inconsistent
2547   ** state.  We need to rollback the statement transaction, if there is
2548   ** one, or the complete transaction if there is no statement transaction.
2549   */
2550 
2551   if( db->mallocFailed ){
2552     p->rc = SQLITE_NOMEM_BKPT;
2553   }
2554   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
2555   closeAllCursors(p);
2556   if( p->magic!=VDBE_MAGIC_RUN ){
2557     return SQLITE_OK;
2558   }
2559   checkActiveVdbeCnt(db);
2560 
2561   /* No commit or rollback needed if the program never started or if the
2562   ** SQL statement does not read or write a database file.  */
2563   if( p->pc>=0 && p->bIsReader ){
2564     int mrc;   /* Primary error code from p->rc */
2565     int eStatementOp = 0;
2566     int isSpecialError;            /* Set to true if a 'special' error */
2567 
2568     /* Lock all btrees used by the statement */
2569     sqlite3VdbeEnter(p);
2570 
2571     /* Check for one of the special errors */
2572     mrc = p->rc & 0xff;
2573     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
2574                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
2575     if( isSpecialError ){
2576       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
2577       ** no rollback is necessary. Otherwise, at least a savepoint
2578       ** transaction must be rolled back to restore the database to a
2579       ** consistent state.
2580       **
2581       ** Even if the statement is read-only, it is important to perform
2582       ** a statement or transaction rollback operation. If the error
2583       ** occurred while writing to the journal, sub-journal or database
2584       ** file as part of an effort to free up cache space (see function
2585       ** pagerStress() in pager.c), the rollback is required to restore
2586       ** the pager to a consistent state.
2587       */
2588       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
2589         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
2590           eStatementOp = SAVEPOINT_ROLLBACK;
2591         }else{
2592           /* We are forced to roll back the active transaction. Before doing
2593           ** so, abort any other statements this handle currently has active.
2594           */
2595           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2596           sqlite3CloseSavepoints(db);
2597           db->autoCommit = 1;
2598           p->nChange = 0;
2599         }
2600       }
2601     }
2602 
2603     /* Check for immediate foreign key violations. */
2604     if( p->rc==SQLITE_OK ){
2605       sqlite3VdbeCheckFk(p, 0);
2606     }
2607 
2608     /* If the auto-commit flag is set and this is the only active writer
2609     ** VM, then we do either a commit or rollback of the current transaction.
2610     **
2611     ** Note: This block also runs if one of the special errors handled
2612     ** above has occurred.
2613     */
2614     if( !sqlite3VtabInSync(db)
2615      && db->autoCommit
2616      && db->nVdbeWrite==(p->readOnly==0)
2617     ){
2618       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
2619         rc = sqlite3VdbeCheckFk(p, 1);
2620         if( rc!=SQLITE_OK ){
2621           if( NEVER(p->readOnly) ){
2622             sqlite3VdbeLeave(p);
2623             return SQLITE_ERROR;
2624           }
2625           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
2626         }else{
2627           /* The auto-commit flag is true, the vdbe program was successful
2628           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
2629           ** key constraints to hold up the transaction. This means a commit
2630           ** is required. */
2631           rc = vdbeCommit(db, p);
2632         }
2633         if( rc==SQLITE_BUSY && p->readOnly ){
2634           sqlite3VdbeLeave(p);
2635           return SQLITE_BUSY;
2636         }else if( rc!=SQLITE_OK ){
2637           p->rc = rc;
2638           sqlite3RollbackAll(db, SQLITE_OK);
2639           p->nChange = 0;
2640         }else{
2641           db->nDeferredCons = 0;
2642           db->nDeferredImmCons = 0;
2643           db->flags &= ~SQLITE_DeferFKs;
2644           sqlite3CommitInternalChanges(db);
2645         }
2646       }else{
2647         sqlite3RollbackAll(db, SQLITE_OK);
2648         p->nChange = 0;
2649       }
2650       db->nStatement = 0;
2651     }else if( eStatementOp==0 ){
2652       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
2653         eStatementOp = SAVEPOINT_RELEASE;
2654       }else if( p->errorAction==OE_Abort ){
2655         eStatementOp = SAVEPOINT_ROLLBACK;
2656       }else{
2657         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2658         sqlite3CloseSavepoints(db);
2659         db->autoCommit = 1;
2660         p->nChange = 0;
2661       }
2662     }
2663 
2664     /* If eStatementOp is non-zero, then a statement transaction needs to
2665     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
2666     ** do so. If this operation returns an error, and the current statement
2667     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
2668     ** current statement error code.
2669     */
2670     if( eStatementOp ){
2671       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
2672       if( rc ){
2673         if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
2674           p->rc = rc;
2675           sqlite3DbFree(db, p->zErrMsg);
2676           p->zErrMsg = 0;
2677         }
2678         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2679         sqlite3CloseSavepoints(db);
2680         db->autoCommit = 1;
2681         p->nChange = 0;
2682       }
2683     }
2684 
2685     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
2686     ** has been rolled back, update the database connection change-counter.
2687     */
2688     if( p->changeCntOn ){
2689       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
2690         sqlite3VdbeSetChanges(db, p->nChange);
2691       }else{
2692         sqlite3VdbeSetChanges(db, 0);
2693       }
2694       p->nChange = 0;
2695     }
2696 
2697     /* Release the locks */
2698     sqlite3VdbeLeave(p);
2699   }
2700 
2701   /* We have successfully halted and closed the VM.  Record this fact. */
2702   if( p->pc>=0 ){
2703     db->nVdbeActive--;
2704     if( !p->readOnly ) db->nVdbeWrite--;
2705     if( p->bIsReader ) db->nVdbeRead--;
2706     assert( db->nVdbeActive>=db->nVdbeRead );
2707     assert( db->nVdbeRead>=db->nVdbeWrite );
2708     assert( db->nVdbeWrite>=0 );
2709   }
2710   p->magic = VDBE_MAGIC_HALT;
2711   checkActiveVdbeCnt(db);
2712   if( db->mallocFailed ){
2713     p->rc = SQLITE_NOMEM_BKPT;
2714   }
2715 
2716   /* If the auto-commit flag is set to true, then any locks that were held
2717   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
2718   ** to invoke any required unlock-notify callbacks.
2719   */
2720   if( db->autoCommit ){
2721     sqlite3ConnectionUnlocked(db);
2722   }
2723 
2724   assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
2725   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
2726 }
2727 
2728 
2729 /*
2730 ** Each VDBE holds the result of the most recent sqlite3_step() call
2731 ** in p->rc.  This routine sets that result back to SQLITE_OK.
2732 */
2733 void sqlite3VdbeResetStepResult(Vdbe *p){
2734   p->rc = SQLITE_OK;
2735 }
2736 
2737 /*
2738 ** Copy the error code and error message belonging to the VDBE passed
2739 ** as the first argument to its database handle (so that they will be
2740 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
2741 **
2742 ** This function does not clear the VDBE error code or message, just
2743 ** copies them to the database handle.
2744 */
2745 int sqlite3VdbeTransferError(Vdbe *p){
2746   sqlite3 *db = p->db;
2747   int rc = p->rc;
2748   if( p->zErrMsg ){
2749     db->bBenignMalloc++;
2750     sqlite3BeginBenignMalloc();
2751     if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
2752     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
2753     sqlite3EndBenignMalloc();
2754     db->bBenignMalloc--;
2755     db->errCode = rc;
2756   }else{
2757     sqlite3Error(db, rc);
2758   }
2759   return rc;
2760 }
2761 
2762 #ifdef SQLITE_ENABLE_SQLLOG
2763 /*
2764 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
2765 ** invoke it.
2766 */
2767 static void vdbeInvokeSqllog(Vdbe *v){
2768   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
2769     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
2770     assert( v->db->init.busy==0 );
2771     if( zExpanded ){
2772       sqlite3GlobalConfig.xSqllog(
2773           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
2774       );
2775       sqlite3DbFree(v->db, zExpanded);
2776     }
2777   }
2778 }
2779 #else
2780 # define vdbeInvokeSqllog(x)
2781 #endif
2782 
2783 /*
2784 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
2785 ** Write any error messages into *pzErrMsg.  Return the result code.
2786 **
2787 ** After this routine is run, the VDBE should be ready to be executed
2788 ** again.
2789 **
2790 ** To look at it another way, this routine resets the state of the
2791 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
2792 ** VDBE_MAGIC_INIT.
2793 */
2794 int sqlite3VdbeReset(Vdbe *p){
2795   sqlite3 *db;
2796   db = p->db;
2797 
2798   /* If the VM did not run to completion or if it encountered an
2799   ** error, then it might not have been halted properly.  So halt
2800   ** it now.
2801   */
2802   sqlite3VdbeHalt(p);
2803 
2804   /* If the VDBE has be run even partially, then transfer the error code
2805   ** and error message from the VDBE into the main database structure.  But
2806   ** if the VDBE has just been set to run but has not actually executed any
2807   ** instructions yet, leave the main database error information unchanged.
2808   */
2809   if( p->pc>=0 ){
2810     vdbeInvokeSqllog(p);
2811     sqlite3VdbeTransferError(p);
2812     sqlite3DbFree(db, p->zErrMsg);
2813     p->zErrMsg = 0;
2814     if( p->runOnlyOnce ) p->expired = 1;
2815   }else if( p->rc && p->expired ){
2816     /* The expired flag was set on the VDBE before the first call
2817     ** to sqlite3_step(). For consistency (since sqlite3_step() was
2818     ** called), set the database error in this case as well.
2819     */
2820     sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
2821     sqlite3DbFree(db, p->zErrMsg);
2822     p->zErrMsg = 0;
2823   }
2824 
2825   /* Reclaim all memory used by the VDBE
2826   */
2827   Cleanup(p);
2828 
2829   /* Save profiling information from this VDBE run.
2830   */
2831 #ifdef VDBE_PROFILE
2832   {
2833     FILE *out = fopen("vdbe_profile.out", "a");
2834     if( out ){
2835       int i;
2836       fprintf(out, "---- ");
2837       for(i=0; i<p->nOp; i++){
2838         fprintf(out, "%02x", p->aOp[i].opcode);
2839       }
2840       fprintf(out, "\n");
2841       if( p->zSql ){
2842         char c, pc = 0;
2843         fprintf(out, "-- ");
2844         for(i=0; (c = p->zSql[i])!=0; i++){
2845           if( pc=='\n' ) fprintf(out, "-- ");
2846           putc(c, out);
2847           pc = c;
2848         }
2849         if( pc!='\n' ) fprintf(out, "\n");
2850       }
2851       for(i=0; i<p->nOp; i++){
2852         char zHdr[100];
2853         sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
2854            p->aOp[i].cnt,
2855            p->aOp[i].cycles,
2856            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
2857         );
2858         fprintf(out, "%s", zHdr);
2859         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
2860       }
2861       fclose(out);
2862     }
2863   }
2864 #endif
2865   p->iCurrentTime = 0;
2866   p->magic = VDBE_MAGIC_INIT;
2867   return p->rc & db->errMask;
2868 }
2869 
2870 /*
2871 ** Clean up and delete a VDBE after execution.  Return an integer which is
2872 ** the result code.  Write any error message text into *pzErrMsg.
2873 */
2874 int sqlite3VdbeFinalize(Vdbe *p){
2875   int rc = SQLITE_OK;
2876   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
2877     rc = sqlite3VdbeReset(p);
2878     assert( (rc & p->db->errMask)==rc );
2879   }
2880   sqlite3VdbeDelete(p);
2881   return rc;
2882 }
2883 
2884 /*
2885 ** If parameter iOp is less than zero, then invoke the destructor for
2886 ** all auxiliary data pointers currently cached by the VM passed as
2887 ** the first argument.
2888 **
2889 ** Or, if iOp is greater than or equal to zero, then the destructor is
2890 ** only invoked for those auxiliary data pointers created by the user
2891 ** function invoked by the OP_Function opcode at instruction iOp of
2892 ** VM pVdbe, and only then if:
2893 **
2894 **    * the associated function parameter is the 32nd or later (counting
2895 **      from left to right), or
2896 **
2897 **    * the corresponding bit in argument mask is clear (where the first
2898 **      function parameter corresponds to bit 0 etc.).
2899 */
2900 void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
2901   while( *pp ){
2902     AuxData *pAux = *pp;
2903     if( (iOp<0)
2904      || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
2905     ){
2906       testcase( pAux->iArg==31 );
2907       if( pAux->xDelete ){
2908         pAux->xDelete(pAux->pAux);
2909       }
2910       *pp = pAux->pNext;
2911       sqlite3DbFree(db, pAux);
2912     }else{
2913       pp= &pAux->pNext;
2914     }
2915   }
2916 }
2917 
2918 /*
2919 ** Free all memory associated with the Vdbe passed as the second argument,
2920 ** except for object itself, which is preserved.
2921 **
2922 ** The difference between this function and sqlite3VdbeDelete() is that
2923 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
2924 ** the database connection and frees the object itself.
2925 */
2926 void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
2927   SubProgram *pSub, *pNext;
2928   int i;
2929   assert( p->db==0 || p->db==db );
2930   releaseMemArray(p->aVar, p->nVar);
2931   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
2932   for(pSub=p->pProgram; pSub; pSub=pNext){
2933     pNext = pSub->pNext;
2934     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
2935     sqlite3DbFree(db, pSub);
2936   }
2937   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
2938   sqlite3DbFree(db, p->azVar);
2939   vdbeFreeOpArray(db, p->aOp, p->nOp);
2940   sqlite3DbFree(db, p->aColName);
2941   sqlite3DbFree(db, p->zSql);
2942   sqlite3DbFree(db, p->pFree);
2943 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2944   for(i=0; i<p->nScan; i++){
2945     sqlite3DbFree(db, p->aScan[i].zName);
2946   }
2947   sqlite3DbFree(db, p->aScan);
2948 #endif
2949 }
2950 
2951 /*
2952 ** Delete an entire VDBE.
2953 */
2954 void sqlite3VdbeDelete(Vdbe *p){
2955   sqlite3 *db;
2956 
2957   if( NEVER(p==0) ) return;
2958   db = p->db;
2959   assert( sqlite3_mutex_held(db->mutex) );
2960   sqlite3VdbeClearObject(db, p);
2961   if( p->pPrev ){
2962     p->pPrev->pNext = p->pNext;
2963   }else{
2964     assert( db->pVdbe==p );
2965     db->pVdbe = p->pNext;
2966   }
2967   if( p->pNext ){
2968     p->pNext->pPrev = p->pPrev;
2969   }
2970   p->magic = VDBE_MAGIC_DEAD;
2971   p->db = 0;
2972   sqlite3DbFree(db, p);
2973 }
2974 
2975 /*
2976 ** The cursor "p" has a pending seek operation that has not yet been
2977 ** carried out.  Seek the cursor now.  If an error occurs, return
2978 ** the appropriate error code.
2979 */
2980 static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
2981   int res, rc;
2982 #ifdef SQLITE_TEST
2983   extern int sqlite3_search_count;
2984 #endif
2985   assert( p->deferredMoveto );
2986   assert( p->isTable );
2987   assert( p->eCurType==CURTYPE_BTREE );
2988   rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
2989   if( rc ) return rc;
2990   if( res!=0 ) return SQLITE_CORRUPT_BKPT;
2991 #ifdef SQLITE_TEST
2992   sqlite3_search_count++;
2993 #endif
2994   p->deferredMoveto = 0;
2995   p->cacheStatus = CACHE_STALE;
2996   return SQLITE_OK;
2997 }
2998 
2999 /*
3000 ** Something has moved cursor "p" out of place.  Maybe the row it was
3001 ** pointed to was deleted out from under it.  Or maybe the btree was
3002 ** rebalanced.  Whatever the cause, try to restore "p" to the place it
3003 ** is supposed to be pointing.  If the row was deleted out from under the
3004 ** cursor, set the cursor to point to a NULL row.
3005 */
3006 static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
3007   int isDifferentRow, rc;
3008   assert( p->eCurType==CURTYPE_BTREE );
3009   assert( p->uc.pCursor!=0 );
3010   assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
3011   rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
3012   p->cacheStatus = CACHE_STALE;
3013   if( isDifferentRow ) p->nullRow = 1;
3014   return rc;
3015 }
3016 
3017 /*
3018 ** Check to ensure that the cursor is valid.  Restore the cursor
3019 ** if need be.  Return any I/O error from the restore operation.
3020 */
3021 int sqlite3VdbeCursorRestore(VdbeCursor *p){
3022   assert( p->eCurType==CURTYPE_BTREE );
3023   if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
3024     return handleMovedCursor(p);
3025   }
3026   return SQLITE_OK;
3027 }
3028 
3029 /*
3030 ** Make sure the cursor p is ready to read or write the row to which it
3031 ** was last positioned.  Return an error code if an OOM fault or I/O error
3032 ** prevents us from positioning the cursor to its correct position.
3033 **
3034 ** If a MoveTo operation is pending on the given cursor, then do that
3035 ** MoveTo now.  If no move is pending, check to see if the row has been
3036 ** deleted out from under the cursor and if it has, mark the row as
3037 ** a NULL row.
3038 **
3039 ** If the cursor is already pointing to the correct row and that row has
3040 ** not been deleted out from under the cursor, then this routine is a no-op.
3041 */
3042 int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
3043   VdbeCursor *p = *pp;
3044   if( p->eCurType==CURTYPE_BTREE ){
3045     if( p->deferredMoveto ){
3046       int iMap;
3047       if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
3048         *pp = p->pAltCursor;
3049         *piCol = iMap - 1;
3050         return SQLITE_OK;
3051       }
3052       return handleDeferredMoveto(p);
3053     }
3054     if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
3055       return handleMovedCursor(p);
3056     }
3057   }
3058   return SQLITE_OK;
3059 }
3060 
3061 /*
3062 ** The following functions:
3063 **
3064 ** sqlite3VdbeSerialType()
3065 ** sqlite3VdbeSerialTypeLen()
3066 ** sqlite3VdbeSerialLen()
3067 ** sqlite3VdbeSerialPut()
3068 ** sqlite3VdbeSerialGet()
3069 **
3070 ** encapsulate the code that serializes values for storage in SQLite
3071 ** data and index records. Each serialized value consists of a
3072 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
3073 ** integer, stored as a varint.
3074 **
3075 ** In an SQLite index record, the serial type is stored directly before
3076 ** the blob of data that it corresponds to. In a table record, all serial
3077 ** types are stored at the start of the record, and the blobs of data at
3078 ** the end. Hence these functions allow the caller to handle the
3079 ** serial-type and data blob separately.
3080 **
3081 ** The following table describes the various storage classes for data:
3082 **
3083 **   serial type        bytes of data      type
3084 **   --------------     ---------------    ---------------
3085 **      0                     0            NULL
3086 **      1                     1            signed integer
3087 **      2                     2            signed integer
3088 **      3                     3            signed integer
3089 **      4                     4            signed integer
3090 **      5                     6            signed integer
3091 **      6                     8            signed integer
3092 **      7                     8            IEEE float
3093 **      8                     0            Integer constant 0
3094 **      9                     0            Integer constant 1
3095 **     10,11                               reserved for expansion
3096 **    N>=12 and even       (N-12)/2        BLOB
3097 **    N>=13 and odd        (N-13)/2        text
3098 **
3099 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
3100 ** of SQLite will not understand those serial types.
3101 */
3102 
3103 /*
3104 ** Return the serial-type for the value stored in pMem.
3105 */
3106 u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
3107   int flags = pMem->flags;
3108   u32 n;
3109 
3110   assert( pLen!=0 );
3111   if( flags&MEM_Null ){
3112     *pLen = 0;
3113     return 0;
3114   }
3115   if( flags&MEM_Int ){
3116     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
3117 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
3118     i64 i = pMem->u.i;
3119     u64 u;
3120     if( i<0 ){
3121       u = ~i;
3122     }else{
3123       u = i;
3124     }
3125     if( u<=127 ){
3126       if( (i&1)==i && file_format>=4 ){
3127         *pLen = 0;
3128         return 8+(u32)u;
3129       }else{
3130         *pLen = 1;
3131         return 1;
3132       }
3133     }
3134     if( u<=32767 ){ *pLen = 2; return 2; }
3135     if( u<=8388607 ){ *pLen = 3; return 3; }
3136     if( u<=2147483647 ){ *pLen = 4; return 4; }
3137     if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
3138     *pLen = 8;
3139     return 6;
3140   }
3141   if( flags&MEM_Real ){
3142     *pLen = 8;
3143     return 7;
3144   }
3145   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
3146   assert( pMem->n>=0 );
3147   n = (u32)pMem->n;
3148   if( flags & MEM_Zero ){
3149     n += pMem->u.nZero;
3150   }
3151   *pLen = n;
3152   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
3153 }
3154 
3155 /*
3156 ** The sizes for serial types less than 128
3157 */
3158 static const u8 sqlite3SmallTypeSizes[] = {
3159         /*  0   1   2   3   4   5   6   7   8   9 */
3160 /*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
3161 /*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
3162 /*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
3163 /*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
3164 /*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
3165 /*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
3166 /*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
3167 /*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
3168 /*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
3169 /*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
3170 /* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
3171 /* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
3172 /* 120 */  54, 54, 55, 55, 56, 56, 57, 57
3173 };
3174 
3175 /*
3176 ** Return the length of the data corresponding to the supplied serial-type.
3177 */
3178 u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
3179   if( serial_type>=128 ){
3180     return (serial_type-12)/2;
3181   }else{
3182     assert( serial_type<12
3183             || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
3184     return sqlite3SmallTypeSizes[serial_type];
3185   }
3186 }
3187 u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
3188   assert( serial_type<128 );
3189   return sqlite3SmallTypeSizes[serial_type];
3190 }
3191 
3192 /*
3193 ** If we are on an architecture with mixed-endian floating
3194 ** points (ex: ARM7) then swap the lower 4 bytes with the
3195 ** upper 4 bytes.  Return the result.
3196 **
3197 ** For most architectures, this is a no-op.
3198 **
3199 ** (later):  It is reported to me that the mixed-endian problem
3200 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
3201 ** that early versions of GCC stored the two words of a 64-bit
3202 ** float in the wrong order.  And that error has been propagated
3203 ** ever since.  The blame is not necessarily with GCC, though.
3204 ** GCC might have just copying the problem from a prior compiler.
3205 ** I am also told that newer versions of GCC that follow a different
3206 ** ABI get the byte order right.
3207 **
3208 ** Developers using SQLite on an ARM7 should compile and run their
3209 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
3210 ** enabled, some asserts below will ensure that the byte order of
3211 ** floating point values is correct.
3212 **
3213 ** (2007-08-30)  Frank van Vugt has studied this problem closely
3214 ** and has send his findings to the SQLite developers.  Frank
3215 ** writes that some Linux kernels offer floating point hardware
3216 ** emulation that uses only 32-bit mantissas instead of a full
3217 ** 48-bits as required by the IEEE standard.  (This is the
3218 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
3219 ** byte swapping becomes very complicated.  To avoid problems,
3220 ** the necessary byte swapping is carried out using a 64-bit integer
3221 ** rather than a 64-bit float.  Frank assures us that the code here
3222 ** works for him.  We, the developers, have no way to independently
3223 ** verify this, but Frank seems to know what he is talking about
3224 ** so we trust him.
3225 */
3226 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
3227 static u64 floatSwap(u64 in){
3228   union {
3229     u64 r;
3230     u32 i[2];
3231   } u;
3232   u32 t;
3233 
3234   u.r = in;
3235   t = u.i[0];
3236   u.i[0] = u.i[1];
3237   u.i[1] = t;
3238   return u.r;
3239 }
3240 # define swapMixedEndianFloat(X)  X = floatSwap(X)
3241 #else
3242 # define swapMixedEndianFloat(X)
3243 #endif
3244 
3245 /*
3246 ** Write the serialized data blob for the value stored in pMem into
3247 ** buf. It is assumed that the caller has allocated sufficient space.
3248 ** Return the number of bytes written.
3249 **
3250 ** nBuf is the amount of space left in buf[].  The caller is responsible
3251 ** for allocating enough space to buf[] to hold the entire field, exclusive
3252 ** of the pMem->u.nZero bytes for a MEM_Zero value.
3253 **
3254 ** Return the number of bytes actually written into buf[].  The number
3255 ** of bytes in the zero-filled tail is included in the return value only
3256 ** if those bytes were zeroed in buf[].
3257 */
3258 u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
3259   u32 len;
3260 
3261   /* Integer and Real */
3262   if( serial_type<=7 && serial_type>0 ){
3263     u64 v;
3264     u32 i;
3265     if( serial_type==7 ){
3266       assert( sizeof(v)==sizeof(pMem->u.r) );
3267       memcpy(&v, &pMem->u.r, sizeof(v));
3268       swapMixedEndianFloat(v);
3269     }else{
3270       v = pMem->u.i;
3271     }
3272     len = i = sqlite3SmallTypeSizes[serial_type];
3273     assert( i>0 );
3274     do{
3275       buf[--i] = (u8)(v&0xFF);
3276       v >>= 8;
3277     }while( i );
3278     return len;
3279   }
3280 
3281   /* String or blob */
3282   if( serial_type>=12 ){
3283     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
3284              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
3285     len = pMem->n;
3286     if( len>0 ) memcpy(buf, pMem->z, len);
3287     return len;
3288   }
3289 
3290   /* NULL or constants 0 or 1 */
3291   return 0;
3292 }
3293 
3294 /* Input "x" is a sequence of unsigned characters that represent a
3295 ** big-endian integer.  Return the equivalent native integer
3296 */
3297 #define ONE_BYTE_INT(x)    ((i8)(x)[0])
3298 #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
3299 #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
3300 #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
3301 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
3302 
3303 /*
3304 ** Deserialize the data blob pointed to by buf as serial type serial_type
3305 ** and store the result in pMem.  Return the number of bytes read.
3306 **
3307 ** This function is implemented as two separate routines for performance.
3308 ** The few cases that require local variables are broken out into a separate
3309 ** routine so that in most cases the overhead of moving the stack pointer
3310 ** is avoided.
3311 */
3312 static u32 SQLITE_NOINLINE serialGet(
3313   const unsigned char *buf,     /* Buffer to deserialize from */
3314   u32 serial_type,              /* Serial type to deserialize */
3315   Mem *pMem                     /* Memory cell to write value into */
3316 ){
3317   u64 x = FOUR_BYTE_UINT(buf);
3318   u32 y = FOUR_BYTE_UINT(buf+4);
3319   x = (x<<32) + y;
3320   if( serial_type==6 ){
3321     /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
3322     ** twos-complement integer. */
3323     pMem->u.i = *(i64*)&x;
3324     pMem->flags = MEM_Int;
3325     testcase( pMem->u.i<0 );
3326   }else{
3327     /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
3328     ** floating point number. */
3329 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
3330     /* Verify that integers and floating point values use the same
3331     ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
3332     ** defined that 64-bit floating point values really are mixed
3333     ** endian.
3334     */
3335     static const u64 t1 = ((u64)0x3ff00000)<<32;
3336     static const double r1 = 1.0;
3337     u64 t2 = t1;
3338     swapMixedEndianFloat(t2);
3339     assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
3340 #endif
3341     assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
3342     swapMixedEndianFloat(x);
3343     memcpy(&pMem->u.r, &x, sizeof(x));
3344     pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
3345   }
3346   return 8;
3347 }
3348 u32 sqlite3VdbeSerialGet(
3349   const unsigned char *buf,     /* Buffer to deserialize from */
3350   u32 serial_type,              /* Serial type to deserialize */
3351   Mem *pMem                     /* Memory cell to write value into */
3352 ){
3353   switch( serial_type ){
3354     case 10:   /* Reserved for future use */
3355     case 11:   /* Reserved for future use */
3356     case 0: {  /* Null */
3357       /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
3358       pMem->flags = MEM_Null;
3359       break;
3360     }
3361     case 1: {
3362       /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
3363       ** integer. */
3364       pMem->u.i = ONE_BYTE_INT(buf);
3365       pMem->flags = MEM_Int;
3366       testcase( pMem->u.i<0 );
3367       return 1;
3368     }
3369     case 2: { /* 2-byte signed integer */
3370       /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
3371       ** twos-complement integer. */
3372       pMem->u.i = TWO_BYTE_INT(buf);
3373       pMem->flags = MEM_Int;
3374       testcase( pMem->u.i<0 );
3375       return 2;
3376     }
3377     case 3: { /* 3-byte signed integer */
3378       /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
3379       ** twos-complement integer. */
3380       pMem->u.i = THREE_BYTE_INT(buf);
3381       pMem->flags = MEM_Int;
3382       testcase( pMem->u.i<0 );
3383       return 3;
3384     }
3385     case 4: { /* 4-byte signed integer */
3386       /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
3387       ** twos-complement integer. */
3388       pMem->u.i = FOUR_BYTE_INT(buf);
3389 #ifdef __HP_cc
3390       /* Work around a sign-extension bug in the HP compiler for HP/UX */
3391       if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
3392 #endif
3393       pMem->flags = MEM_Int;
3394       testcase( pMem->u.i<0 );
3395       return 4;
3396     }
3397     case 5: { /* 6-byte signed integer */
3398       /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
3399       ** twos-complement integer. */
3400       pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
3401       pMem->flags = MEM_Int;
3402       testcase( pMem->u.i<0 );
3403       return 6;
3404     }
3405     case 6:   /* 8-byte signed integer */
3406     case 7: { /* IEEE floating point */
3407       /* These use local variables, so do them in a separate routine
3408       ** to avoid having to move the frame pointer in the common case */
3409       return serialGet(buf,serial_type,pMem);
3410     }
3411     case 8:    /* Integer 0 */
3412     case 9: {  /* Integer 1 */
3413       /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
3414       /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
3415       pMem->u.i = serial_type-8;
3416       pMem->flags = MEM_Int;
3417       return 0;
3418     }
3419     default: {
3420       /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
3421       ** length.
3422       ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
3423       ** (N-13)/2 bytes in length. */
3424       static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
3425       pMem->z = (char *)buf;
3426       pMem->n = (serial_type-12)/2;
3427       pMem->flags = aFlag[serial_type&1];
3428       return pMem->n;
3429     }
3430   }
3431   return 0;
3432 }
3433 /*
3434 ** This routine is used to allocate sufficient space for an UnpackedRecord
3435 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
3436 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
3437 **
3438 ** The space is either allocated using sqlite3DbMallocRaw() or from within
3439 ** the unaligned buffer passed via the second and third arguments (presumably
3440 ** stack space). If the former, then *ppFree is set to a pointer that should
3441 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
3442 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
3443 ** before returning.
3444 **
3445 ** If an OOM error occurs, NULL is returned.
3446 */
3447 UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
3448   KeyInfo *pKeyInfo,              /* Description of the record */
3449   char *pSpace,                   /* Unaligned space available */
3450   int szSpace,                    /* Size of pSpace[] in bytes */
3451   char **ppFree                   /* OUT: Caller should free this pointer */
3452 ){
3453   UnpackedRecord *p;              /* Unpacked record to return */
3454   int nOff;                       /* Increment pSpace by nOff to align it */
3455   int nByte;                      /* Number of bytes required for *p */
3456 
3457   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
3458   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
3459   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
3460   */
3461   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
3462   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
3463   if( nByte>szSpace+nOff ){
3464     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
3465     *ppFree = (char *)p;
3466     if( !p ) return 0;
3467   }else{
3468     p = (UnpackedRecord*)&pSpace[nOff];
3469     *ppFree = 0;
3470   }
3471 
3472   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
3473   assert( pKeyInfo->aSortOrder!=0 );
3474   p->pKeyInfo = pKeyInfo;
3475   p->nField = pKeyInfo->nField + 1;
3476   return p;
3477 }
3478 
3479 /*
3480 ** Given the nKey-byte encoding of a record in pKey[], populate the
3481 ** UnpackedRecord structure indicated by the fourth argument with the
3482 ** contents of the decoded record.
3483 */
3484 void sqlite3VdbeRecordUnpack(
3485   KeyInfo *pKeyInfo,     /* Information about the record format */
3486   int nKey,              /* Size of the binary record */
3487   const void *pKey,      /* The binary record */
3488   UnpackedRecord *p      /* Populate this structure before returning. */
3489 ){
3490   const unsigned char *aKey = (const unsigned char *)pKey;
3491   int d;
3492   u32 idx;                        /* Offset in aKey[] to read from */
3493   u16 u;                          /* Unsigned loop counter */
3494   u32 szHdr;
3495   Mem *pMem = p->aMem;
3496 
3497   p->default_rc = 0;
3498   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
3499   idx = getVarint32(aKey, szHdr);
3500   d = szHdr;
3501   u = 0;
3502   while( idx<szHdr && d<=nKey ){
3503     u32 serial_type;
3504 
3505     idx += getVarint32(&aKey[idx], serial_type);
3506     pMem->enc = pKeyInfo->enc;
3507     pMem->db = pKeyInfo->db;
3508     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
3509     pMem->szMalloc = 0;
3510     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
3511     pMem++;
3512     if( (++u)>=p->nField ) break;
3513   }
3514   assert( u<=pKeyInfo->nField + 1 );
3515   p->nField = u;
3516 }
3517 
3518 #if SQLITE_DEBUG
3519 /*
3520 ** This function compares two index or table record keys in the same way
3521 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
3522 ** this function deserializes and compares values using the
3523 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
3524 ** in assert() statements to ensure that the optimized code in
3525 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
3526 **
3527 ** Return true if the result of comparison is equivalent to desiredResult.
3528 ** Return false if there is a disagreement.
3529 */
3530 static int vdbeRecordCompareDebug(
3531   int nKey1, const void *pKey1, /* Left key */
3532   const UnpackedRecord *pPKey2, /* Right key */
3533   int desiredResult             /* Correct answer */
3534 ){
3535   u32 d1;            /* Offset into aKey[] of next data element */
3536   u32 idx1;          /* Offset into aKey[] of next header element */
3537   u32 szHdr1;        /* Number of bytes in header */
3538   int i = 0;
3539   int rc = 0;
3540   const unsigned char *aKey1 = (const unsigned char *)pKey1;
3541   KeyInfo *pKeyInfo;
3542   Mem mem1;
3543 
3544   pKeyInfo = pPKey2->pKeyInfo;
3545   if( pKeyInfo->db==0 ) return 1;
3546   mem1.enc = pKeyInfo->enc;
3547   mem1.db = pKeyInfo->db;
3548   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
3549   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
3550 
3551   /* Compilers may complain that mem1.u.i is potentially uninitialized.
3552   ** We could initialize it, as shown here, to silence those complaints.
3553   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
3554   ** the unnecessary initialization has a measurable negative performance
3555   ** impact, since this routine is a very high runner.  And so, we choose
3556   ** to ignore the compiler warnings and leave this variable uninitialized.
3557   */
3558   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
3559 
3560   idx1 = getVarint32(aKey1, szHdr1);
3561   if( szHdr1>98307 ) return SQLITE_CORRUPT;
3562   d1 = szHdr1;
3563   assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
3564   assert( pKeyInfo->aSortOrder!=0 );
3565   assert( pKeyInfo->nField>0 );
3566   assert( idx1<=szHdr1 || CORRUPT_DB );
3567   do{
3568     u32 serial_type1;
3569 
3570     /* Read the serial types for the next element in each key. */
3571     idx1 += getVarint32( aKey1+idx1, serial_type1 );
3572 
3573     /* Verify that there is enough key space remaining to avoid
3574     ** a buffer overread.  The "d1+serial_type1+2" subexpression will
3575     ** always be greater than or equal to the amount of required key space.
3576     ** Use that approximation to avoid the more expensive call to
3577     ** sqlite3VdbeSerialTypeLen() in the common case.
3578     */
3579     if( d1+serial_type1+2>(u32)nKey1
3580      && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
3581     ){
3582       break;
3583     }
3584 
3585     /* Extract the values to be compared.
3586     */
3587     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
3588 
3589     /* Do the comparison
3590     */
3591     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
3592     if( rc!=0 ){
3593       assert( mem1.szMalloc==0 );  /* See comment below */
3594       if( pKeyInfo->aSortOrder[i] ){
3595         rc = -rc;  /* Invert the result for DESC sort order. */
3596       }
3597       goto debugCompareEnd;
3598     }
3599     i++;
3600   }while( idx1<szHdr1 && i<pPKey2->nField );
3601 
3602   /* No memory allocation is ever used on mem1.  Prove this using
3603   ** the following assert().  If the assert() fails, it indicates a
3604   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
3605   */
3606   assert( mem1.szMalloc==0 );
3607 
3608   /* rc==0 here means that one of the keys ran out of fields and
3609   ** all the fields up to that point were equal. Return the default_rc
3610   ** value.  */
3611   rc = pPKey2->default_rc;
3612 
3613 debugCompareEnd:
3614   if( desiredResult==0 && rc==0 ) return 1;
3615   if( desiredResult<0 && rc<0 ) return 1;
3616   if( desiredResult>0 && rc>0 ) return 1;
3617   if( CORRUPT_DB ) return 1;
3618   if( pKeyInfo->db->mallocFailed ) return 1;
3619   return 0;
3620 }
3621 #endif
3622 
3623 #if SQLITE_DEBUG
3624 /*
3625 ** Count the number of fields (a.k.a. columns) in the record given by
3626 ** pKey,nKey.  The verify that this count is less than or equal to the
3627 ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
3628 **
3629 ** If this constraint is not satisfied, it means that the high-speed
3630 ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
3631 ** not work correctly.  If this assert() ever fires, it probably means
3632 ** that the KeyInfo.nField or KeyInfo.nXField values were computed
3633 ** incorrectly.
3634 */
3635 static void vdbeAssertFieldCountWithinLimits(
3636   int nKey, const void *pKey,   /* The record to verify */
3637   const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
3638 ){
3639   int nField = 0;
3640   u32 szHdr;
3641   u32 idx;
3642   u32 notUsed;
3643   const unsigned char *aKey = (const unsigned char*)pKey;
3644 
3645   if( CORRUPT_DB ) return;
3646   idx = getVarint32(aKey, szHdr);
3647   assert( nKey>=0 );
3648   assert( szHdr<=(u32)nKey );
3649   while( idx<szHdr ){
3650     idx += getVarint32(aKey+idx, notUsed);
3651     nField++;
3652   }
3653   assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
3654 }
3655 #else
3656 # define vdbeAssertFieldCountWithinLimits(A,B,C)
3657 #endif
3658 
3659 /*
3660 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
3661 ** using the collation sequence pColl. As usual, return a negative , zero
3662 ** or positive value if *pMem1 is less than, equal to or greater than
3663 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
3664 */
3665 static int vdbeCompareMemString(
3666   const Mem *pMem1,
3667   const Mem *pMem2,
3668   const CollSeq *pColl,
3669   u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
3670 ){
3671   if( pMem1->enc==pColl->enc ){
3672     /* The strings are already in the correct encoding.  Call the
3673      ** comparison function directly */
3674     return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
3675   }else{
3676     int rc;
3677     const void *v1, *v2;
3678     int n1, n2;
3679     Mem c1;
3680     Mem c2;
3681     sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
3682     sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
3683     sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
3684     sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
3685     v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
3686     n1 = v1==0 ? 0 : c1.n;
3687     v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
3688     n2 = v2==0 ? 0 : c2.n;
3689     rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
3690     if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
3691     sqlite3VdbeMemRelease(&c1);
3692     sqlite3VdbeMemRelease(&c2);
3693     return rc;
3694   }
3695 }
3696 
3697 /*
3698 ** Compare two blobs.  Return negative, zero, or positive if the first
3699 ** is less than, equal to, or greater than the second, respectively.
3700 ** If one blob is a prefix of the other, then the shorter is the lessor.
3701 */
3702 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
3703   int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
3704   if( c ) return c;
3705   return pB1->n - pB2->n;
3706 }
3707 
3708 /*
3709 ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
3710 ** number.  Return negative, zero, or positive if the first (i64) is less than,
3711 ** equal to, or greater than the second (double).
3712 */
3713 static int sqlite3IntFloatCompare(i64 i, double r){
3714   if( sizeof(LONGDOUBLE_TYPE)>8 ){
3715     LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
3716     if( x<r ) return -1;
3717     if( x>r ) return +1;
3718     return 0;
3719   }else{
3720     i64 y;
3721     double s;
3722     if( r<-9223372036854775808.0 ) return +1;
3723     if( r>9223372036854775807.0 ) return -1;
3724     y = (i64)r;
3725     if( i<y ) return -1;
3726     if( i>y ){
3727       if( y==SMALLEST_INT64 && r>0.0 ) return -1;
3728       return +1;
3729     }
3730     s = (double)i;
3731     if( s<r ) return -1;
3732     if( s>r ) return +1;
3733     return 0;
3734   }
3735 }
3736 
3737 /*
3738 ** Compare the values contained by the two memory cells, returning
3739 ** negative, zero or positive if pMem1 is less than, equal to, or greater
3740 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
3741 ** and reals) sorted numerically, followed by text ordered by the collating
3742 ** sequence pColl and finally blob's ordered by memcmp().
3743 **
3744 ** Two NULL values are considered equal by this function.
3745 */
3746 int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
3747   int f1, f2;
3748   int combined_flags;
3749 
3750   f1 = pMem1->flags;
3751   f2 = pMem2->flags;
3752   combined_flags = f1|f2;
3753   assert( (combined_flags & MEM_RowSet)==0 );
3754 
3755   /* If one value is NULL, it is less than the other. If both values
3756   ** are NULL, return 0.
3757   */
3758   if( combined_flags&MEM_Null ){
3759     return (f2&MEM_Null) - (f1&MEM_Null);
3760   }
3761 
3762   /* At least one of the two values is a number
3763   */
3764   if( combined_flags&(MEM_Int|MEM_Real) ){
3765     if( (f1 & f2 & MEM_Int)!=0 ){
3766       if( pMem1->u.i < pMem2->u.i ) return -1;
3767       if( pMem1->u.i > pMem2->u.i ) return +1;
3768       return 0;
3769     }
3770     if( (f1 & f2 & MEM_Real)!=0 ){
3771       if( pMem1->u.r < pMem2->u.r ) return -1;
3772       if( pMem1->u.r > pMem2->u.r ) return +1;
3773       return 0;
3774     }
3775     if( (f1&MEM_Int)!=0 ){
3776       if( (f2&MEM_Real)!=0 ){
3777         return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
3778       }else{
3779         return -1;
3780       }
3781     }
3782     if( (f1&MEM_Real)!=0 ){
3783       if( (f2&MEM_Int)!=0 ){
3784         return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
3785       }else{
3786         return -1;
3787       }
3788     }
3789     return +1;
3790   }
3791 
3792   /* If one value is a string and the other is a blob, the string is less.
3793   ** If both are strings, compare using the collating functions.
3794   */
3795   if( combined_flags&MEM_Str ){
3796     if( (f1 & MEM_Str)==0 ){
3797       return 1;
3798     }
3799     if( (f2 & MEM_Str)==0 ){
3800       return -1;
3801     }
3802 
3803     assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
3804     assert( pMem1->enc==SQLITE_UTF8 ||
3805             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
3806 
3807     /* The collation sequence must be defined at this point, even if
3808     ** the user deletes the collation sequence after the vdbe program is
3809     ** compiled (this was not always the case).
3810     */
3811     assert( !pColl || pColl->xCmp );
3812 
3813     if( pColl ){
3814       return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
3815     }
3816     /* If a NULL pointer was passed as the collate function, fall through
3817     ** to the blob case and use memcmp().  */
3818   }
3819 
3820   /* Both values must be blobs.  Compare using memcmp().  */
3821   return sqlite3BlobCompare(pMem1, pMem2);
3822 }
3823 
3824 
3825 /*
3826 ** The first argument passed to this function is a serial-type that
3827 ** corresponds to an integer - all values between 1 and 9 inclusive
3828 ** except 7. The second points to a buffer containing an integer value
3829 ** serialized according to serial_type. This function deserializes
3830 ** and returns the value.
3831 */
3832 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
3833   u32 y;
3834   assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
3835   switch( serial_type ){
3836     case 0:
3837     case 1:
3838       testcase( aKey[0]&0x80 );
3839       return ONE_BYTE_INT(aKey);
3840     case 2:
3841       testcase( aKey[0]&0x80 );
3842       return TWO_BYTE_INT(aKey);
3843     case 3:
3844       testcase( aKey[0]&0x80 );
3845       return THREE_BYTE_INT(aKey);
3846     case 4: {
3847       testcase( aKey[0]&0x80 );
3848       y = FOUR_BYTE_UINT(aKey);
3849       return (i64)*(int*)&y;
3850     }
3851     case 5: {
3852       testcase( aKey[0]&0x80 );
3853       return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
3854     }
3855     case 6: {
3856       u64 x = FOUR_BYTE_UINT(aKey);
3857       testcase( aKey[0]&0x80 );
3858       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
3859       return (i64)*(i64*)&x;
3860     }
3861   }
3862 
3863   return (serial_type - 8);
3864 }
3865 
3866 /*
3867 ** This function compares the two table rows or index records
3868 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
3869 ** or positive integer if key1 is less than, equal to or
3870 ** greater than key2.  The {nKey1, pKey1} key must be a blob
3871 ** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
3872 ** key must be a parsed key such as obtained from
3873 ** sqlite3VdbeParseRecord.
3874 **
3875 ** If argument bSkip is non-zero, it is assumed that the caller has already
3876 ** determined that the first fields of the keys are equal.
3877 **
3878 ** Key1 and Key2 do not have to contain the same number of fields. If all
3879 ** fields that appear in both keys are equal, then pPKey2->default_rc is
3880 ** returned.
3881 **
3882 ** If database corruption is discovered, set pPKey2->errCode to
3883 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
3884 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
3885 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
3886 */
3887 int sqlite3VdbeRecordCompareWithSkip(
3888   int nKey1, const void *pKey1,   /* Left key */
3889   UnpackedRecord *pPKey2,         /* Right key */
3890   int bSkip                       /* If true, skip the first field */
3891 ){
3892   u32 d1;                         /* Offset into aKey[] of next data element */
3893   int i;                          /* Index of next field to compare */
3894   u32 szHdr1;                     /* Size of record header in bytes */
3895   u32 idx1;                       /* Offset of first type in header */
3896   int rc = 0;                     /* Return value */
3897   Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
3898   KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
3899   const unsigned char *aKey1 = (const unsigned char *)pKey1;
3900   Mem mem1;
3901 
3902   /* If bSkip is true, then the caller has already determined that the first
3903   ** two elements in the keys are equal. Fix the various stack variables so
3904   ** that this routine begins comparing at the second field. */
3905   if( bSkip ){
3906     u32 s1;
3907     idx1 = 1 + getVarint32(&aKey1[1], s1);
3908     szHdr1 = aKey1[0];
3909     d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
3910     i = 1;
3911     pRhs++;
3912   }else{
3913     idx1 = getVarint32(aKey1, szHdr1);
3914     d1 = szHdr1;
3915     if( d1>(unsigned)nKey1 ){
3916       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
3917       return 0;  /* Corruption */
3918     }
3919     i = 0;
3920   }
3921 
3922   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
3923   assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
3924        || CORRUPT_DB );
3925   assert( pPKey2->pKeyInfo->aSortOrder!=0 );
3926   assert( pPKey2->pKeyInfo->nField>0 );
3927   assert( idx1<=szHdr1 || CORRUPT_DB );
3928   do{
3929     u32 serial_type;
3930 
3931     /* RHS is an integer */
3932     if( pRhs->flags & MEM_Int ){
3933       serial_type = aKey1[idx1];
3934       testcase( serial_type==12 );
3935       if( serial_type>=10 ){
3936         rc = +1;
3937       }else if( serial_type==0 ){
3938         rc = -1;
3939       }else if( serial_type==7 ){
3940         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
3941         rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
3942       }else{
3943         i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
3944         i64 rhs = pRhs->u.i;
3945         if( lhs<rhs ){
3946           rc = -1;
3947         }else if( lhs>rhs ){
3948           rc = +1;
3949         }
3950       }
3951     }
3952 
3953     /* RHS is real */
3954     else if( pRhs->flags & MEM_Real ){
3955       serial_type = aKey1[idx1];
3956       if( serial_type>=10 ){
3957         /* Serial types 12 or greater are strings and blobs (greater than
3958         ** numbers). Types 10 and 11 are currently "reserved for future
3959         ** use", so it doesn't really matter what the results of comparing
3960         ** them to numberic values are.  */
3961         rc = +1;
3962       }else if( serial_type==0 ){
3963         rc = -1;
3964       }else{
3965         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
3966         if( serial_type==7 ){
3967           if( mem1.u.r<pRhs->u.r ){
3968             rc = -1;
3969           }else if( mem1.u.r>pRhs->u.r ){
3970             rc = +1;
3971           }
3972         }else{
3973           rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
3974         }
3975       }
3976     }
3977 
3978     /* RHS is a string */
3979     else if( pRhs->flags & MEM_Str ){
3980       getVarint32(&aKey1[idx1], serial_type);
3981       testcase( serial_type==12 );
3982       if( serial_type<12 ){
3983         rc = -1;
3984       }else if( !(serial_type & 0x01) ){
3985         rc = +1;
3986       }else{
3987         mem1.n = (serial_type - 12) / 2;
3988         testcase( (d1+mem1.n)==(unsigned)nKey1 );
3989         testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
3990         if( (d1+mem1.n) > (unsigned)nKey1 ){
3991           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
3992           return 0;                /* Corruption */
3993         }else if( pKeyInfo->aColl[i] ){
3994           mem1.enc = pKeyInfo->enc;
3995           mem1.db = pKeyInfo->db;
3996           mem1.flags = MEM_Str;
3997           mem1.z = (char*)&aKey1[d1];
3998           rc = vdbeCompareMemString(
3999               &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
4000           );
4001         }else{
4002           int nCmp = MIN(mem1.n, pRhs->n);
4003           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
4004           if( rc==0 ) rc = mem1.n - pRhs->n;
4005         }
4006       }
4007     }
4008 
4009     /* RHS is a blob */
4010     else if( pRhs->flags & MEM_Blob ){
4011       getVarint32(&aKey1[idx1], serial_type);
4012       testcase( serial_type==12 );
4013       if( serial_type<12 || (serial_type & 0x01) ){
4014         rc = -1;
4015       }else{
4016         int nStr = (serial_type - 12) / 2;
4017         testcase( (d1+nStr)==(unsigned)nKey1 );
4018         testcase( (d1+nStr+1)==(unsigned)nKey1 );
4019         if( (d1+nStr) > (unsigned)nKey1 ){
4020           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4021           return 0;                /* Corruption */
4022         }else{
4023           int nCmp = MIN(nStr, pRhs->n);
4024           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
4025           if( rc==0 ) rc = nStr - pRhs->n;
4026         }
4027       }
4028     }
4029 
4030     /* RHS is null */
4031     else{
4032       serial_type = aKey1[idx1];
4033       rc = (serial_type!=0);
4034     }
4035 
4036     if( rc!=0 ){
4037       if( pKeyInfo->aSortOrder[i] ){
4038         rc = -rc;
4039       }
4040       assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
4041       assert( mem1.szMalloc==0 );  /* See comment below */
4042       return rc;
4043     }
4044 
4045     i++;
4046     pRhs++;
4047     d1 += sqlite3VdbeSerialTypeLen(serial_type);
4048     idx1 += sqlite3VarintLen(serial_type);
4049   }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
4050 
4051   /* No memory allocation is ever used on mem1.  Prove this using
4052   ** the following assert().  If the assert() fails, it indicates a
4053   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
4054   assert( mem1.szMalloc==0 );
4055 
4056   /* rc==0 here means that one or both of the keys ran out of fields and
4057   ** all the fields up to that point were equal. Return the default_rc
4058   ** value.  */
4059   assert( CORRUPT_DB
4060        || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
4061        || pKeyInfo->db->mallocFailed
4062   );
4063   pPKey2->eqSeen = 1;
4064   return pPKey2->default_rc;
4065 }
4066 int sqlite3VdbeRecordCompare(
4067   int nKey1, const void *pKey1,   /* Left key */
4068   UnpackedRecord *pPKey2          /* Right key */
4069 ){
4070   return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
4071 }
4072 
4073 
4074 /*
4075 ** This function is an optimized version of sqlite3VdbeRecordCompare()
4076 ** that (a) the first field of pPKey2 is an integer, and (b) the
4077 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
4078 ** byte (i.e. is less than 128).
4079 **
4080 ** To avoid concerns about buffer overreads, this routine is only used
4081 ** on schemas where the maximum valid header size is 63 bytes or less.
4082 */
4083 static int vdbeRecordCompareInt(
4084   int nKey1, const void *pKey1, /* Left key */
4085   UnpackedRecord *pPKey2        /* Right key */
4086 ){
4087   const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
4088   int serial_type = ((const u8*)pKey1)[1];
4089   int res;
4090   u32 y;
4091   u64 x;
4092   i64 v = pPKey2->aMem[0].u.i;
4093   i64 lhs;
4094 
4095   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
4096   assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
4097   switch( serial_type ){
4098     case 1: { /* 1-byte signed integer */
4099       lhs = ONE_BYTE_INT(aKey);
4100       testcase( lhs<0 );
4101       break;
4102     }
4103     case 2: { /* 2-byte signed integer */
4104       lhs = TWO_BYTE_INT(aKey);
4105       testcase( lhs<0 );
4106       break;
4107     }
4108     case 3: { /* 3-byte signed integer */
4109       lhs = THREE_BYTE_INT(aKey);
4110       testcase( lhs<0 );
4111       break;
4112     }
4113     case 4: { /* 4-byte signed integer */
4114       y = FOUR_BYTE_UINT(aKey);
4115       lhs = (i64)*(int*)&y;
4116       testcase( lhs<0 );
4117       break;
4118     }
4119     case 5: { /* 6-byte signed integer */
4120       lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
4121       testcase( lhs<0 );
4122       break;
4123     }
4124     case 6: { /* 8-byte signed integer */
4125       x = FOUR_BYTE_UINT(aKey);
4126       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
4127       lhs = *(i64*)&x;
4128       testcase( lhs<0 );
4129       break;
4130     }
4131     case 8:
4132       lhs = 0;
4133       break;
4134     case 9:
4135       lhs = 1;
4136       break;
4137 
4138     /* This case could be removed without changing the results of running
4139     ** this code. Including it causes gcc to generate a faster switch
4140     ** statement (since the range of switch targets now starts at zero and
4141     ** is contiguous) but does not cause any duplicate code to be generated
4142     ** (as gcc is clever enough to combine the two like cases). Other
4143     ** compilers might be similar.  */
4144     case 0: case 7:
4145       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
4146 
4147     default:
4148       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
4149   }
4150 
4151   if( v>lhs ){
4152     res = pPKey2->r1;
4153   }else if( v<lhs ){
4154     res = pPKey2->r2;
4155   }else if( pPKey2->nField>1 ){
4156     /* The first fields of the two keys are equal. Compare the trailing
4157     ** fields.  */
4158     res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
4159   }else{
4160     /* The first fields of the two keys are equal and there are no trailing
4161     ** fields. Return pPKey2->default_rc in this case. */
4162     res = pPKey2->default_rc;
4163     pPKey2->eqSeen = 1;
4164   }
4165 
4166   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
4167   return res;
4168 }
4169 
4170 /*
4171 ** This function is an optimized version of sqlite3VdbeRecordCompare()
4172 ** that (a) the first field of pPKey2 is a string, that (b) the first field
4173 ** uses the collation sequence BINARY and (c) that the size-of-header varint
4174 ** at the start of (pKey1/nKey1) fits in a single byte.
4175 */
4176 static int vdbeRecordCompareString(
4177   int nKey1, const void *pKey1, /* Left key */
4178   UnpackedRecord *pPKey2        /* Right key */
4179 ){
4180   const u8 *aKey1 = (const u8*)pKey1;
4181   int serial_type;
4182   int res;
4183 
4184   assert( pPKey2->aMem[0].flags & MEM_Str );
4185   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
4186   getVarint32(&aKey1[1], serial_type);
4187   if( serial_type<12 ){
4188     res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
4189   }else if( !(serial_type & 0x01) ){
4190     res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
4191   }else{
4192     int nCmp;
4193     int nStr;
4194     int szHdr = aKey1[0];
4195 
4196     nStr = (serial_type-12) / 2;
4197     if( (szHdr + nStr) > nKey1 ){
4198       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4199       return 0;    /* Corruption */
4200     }
4201     nCmp = MIN( pPKey2->aMem[0].n, nStr );
4202     res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
4203 
4204     if( res==0 ){
4205       res = nStr - pPKey2->aMem[0].n;
4206       if( res==0 ){
4207         if( pPKey2->nField>1 ){
4208           res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
4209         }else{
4210           res = pPKey2->default_rc;
4211           pPKey2->eqSeen = 1;
4212         }
4213       }else if( res>0 ){
4214         res = pPKey2->r2;
4215       }else{
4216         res = pPKey2->r1;
4217       }
4218     }else if( res>0 ){
4219       res = pPKey2->r2;
4220     }else{
4221       res = pPKey2->r1;
4222     }
4223   }
4224 
4225   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
4226        || CORRUPT_DB
4227        || pPKey2->pKeyInfo->db->mallocFailed
4228   );
4229   return res;
4230 }
4231 
4232 /*
4233 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
4234 ** suitable for comparing serialized records to the unpacked record passed
4235 ** as the only argument.
4236 */
4237 RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
4238   /* varintRecordCompareInt() and varintRecordCompareString() both assume
4239   ** that the size-of-header varint that occurs at the start of each record
4240   ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
4241   ** also assumes that it is safe to overread a buffer by at least the
4242   ** maximum possible legal header size plus 8 bytes. Because there is
4243   ** guaranteed to be at least 74 (but not 136) bytes of padding following each
4244   ** buffer passed to varintRecordCompareInt() this makes it convenient to
4245   ** limit the size of the header to 64 bytes in cases where the first field
4246   ** is an integer.
4247   **
4248   ** The easiest way to enforce this limit is to consider only records with
4249   ** 13 fields or less. If the first field is an integer, the maximum legal
4250   ** header size is (12*5 + 1 + 1) bytes.  */
4251   if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
4252     int flags = p->aMem[0].flags;
4253     if( p->pKeyInfo->aSortOrder[0] ){
4254       p->r1 = 1;
4255       p->r2 = -1;
4256     }else{
4257       p->r1 = -1;
4258       p->r2 = 1;
4259     }
4260     if( (flags & MEM_Int) ){
4261       return vdbeRecordCompareInt;
4262     }
4263     testcase( flags & MEM_Real );
4264     testcase( flags & MEM_Null );
4265     testcase( flags & MEM_Blob );
4266     if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
4267       assert( flags & MEM_Str );
4268       return vdbeRecordCompareString;
4269     }
4270   }
4271 
4272   return sqlite3VdbeRecordCompare;
4273 }
4274 
4275 /*
4276 ** pCur points at an index entry created using the OP_MakeRecord opcode.
4277 ** Read the rowid (the last field in the record) and store it in *rowid.
4278 ** Return SQLITE_OK if everything works, or an error code otherwise.
4279 **
4280 ** pCur might be pointing to text obtained from a corrupt database file.
4281 ** So the content cannot be trusted.  Do appropriate checks on the content.
4282 */
4283 int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
4284   i64 nCellKey = 0;
4285   int rc;
4286   u32 szHdr;        /* Size of the header */
4287   u32 typeRowid;    /* Serial type of the rowid */
4288   u32 lenRowid;     /* Size of the rowid */
4289   Mem m, v;
4290 
4291   /* Get the size of the index entry.  Only indices entries of less
4292   ** than 2GiB are support - anything large must be database corruption.
4293   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
4294   ** this code can safely assume that nCellKey is 32-bits
4295   */
4296   assert( sqlite3BtreeCursorIsValid(pCur) );
4297   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
4298   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
4299   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
4300 
4301   /* Read in the complete content of the index entry */
4302   sqlite3VdbeMemInit(&m, db, 0);
4303   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
4304   if( rc ){
4305     return rc;
4306   }
4307 
4308   /* The index entry must begin with a header size */
4309   (void)getVarint32((u8*)m.z, szHdr);
4310   testcase( szHdr==3 );
4311   testcase( szHdr==m.n );
4312   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
4313     goto idx_rowid_corruption;
4314   }
4315 
4316   /* The last field of the index should be an integer - the ROWID.
4317   ** Verify that the last entry really is an integer. */
4318   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
4319   testcase( typeRowid==1 );
4320   testcase( typeRowid==2 );
4321   testcase( typeRowid==3 );
4322   testcase( typeRowid==4 );
4323   testcase( typeRowid==5 );
4324   testcase( typeRowid==6 );
4325   testcase( typeRowid==8 );
4326   testcase( typeRowid==9 );
4327   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
4328     goto idx_rowid_corruption;
4329   }
4330   lenRowid = sqlite3SmallTypeSizes[typeRowid];
4331   testcase( (u32)m.n==szHdr+lenRowid );
4332   if( unlikely((u32)m.n<szHdr+lenRowid) ){
4333     goto idx_rowid_corruption;
4334   }
4335 
4336   /* Fetch the integer off the end of the index record */
4337   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
4338   *rowid = v.u.i;
4339   sqlite3VdbeMemRelease(&m);
4340   return SQLITE_OK;
4341 
4342   /* Jump here if database corruption is detected after m has been
4343   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
4344 idx_rowid_corruption:
4345   testcase( m.szMalloc!=0 );
4346   sqlite3VdbeMemRelease(&m);
4347   return SQLITE_CORRUPT_BKPT;
4348 }
4349 
4350 /*
4351 ** Compare the key of the index entry that cursor pC is pointing to against
4352 ** the key string in pUnpacked.  Write into *pRes a number
4353 ** that is negative, zero, or positive if pC is less than, equal to,
4354 ** or greater than pUnpacked.  Return SQLITE_OK on success.
4355 **
4356 ** pUnpacked is either created without a rowid or is truncated so that it
4357 ** omits the rowid at the end.  The rowid at the end of the index entry
4358 ** is ignored as well.  Hence, this routine only compares the prefixes
4359 ** of the keys prior to the final rowid, not the entire key.
4360 */
4361 int sqlite3VdbeIdxKeyCompare(
4362   sqlite3 *db,                     /* Database connection */
4363   VdbeCursor *pC,                  /* The cursor to compare against */
4364   UnpackedRecord *pUnpacked,       /* Unpacked version of key */
4365   int *res                         /* Write the comparison result here */
4366 ){
4367   i64 nCellKey = 0;
4368   int rc;
4369   BtCursor *pCur;
4370   Mem m;
4371 
4372   assert( pC->eCurType==CURTYPE_BTREE );
4373   pCur = pC->uc.pCursor;
4374   assert( sqlite3BtreeCursorIsValid(pCur) );
4375   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
4376   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
4377   /* nCellKey will always be between 0 and 0xffffffff because of the way
4378   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
4379   if( nCellKey<=0 || nCellKey>0x7fffffff ){
4380     *res = 0;
4381     return SQLITE_CORRUPT_BKPT;
4382   }
4383   sqlite3VdbeMemInit(&m, db, 0);
4384   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
4385   if( rc ){
4386     return rc;
4387   }
4388   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
4389   sqlite3VdbeMemRelease(&m);
4390   return SQLITE_OK;
4391 }
4392 
4393 /*
4394 ** This routine sets the value to be returned by subsequent calls to
4395 ** sqlite3_changes() on the database handle 'db'.
4396 */
4397 void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
4398   assert( sqlite3_mutex_held(db->mutex) );
4399   db->nChange = nChange;
4400   db->nTotalChange += nChange;
4401 }
4402 
4403 /*
4404 ** Set a flag in the vdbe to update the change counter when it is finalised
4405 ** or reset.
4406 */
4407 void sqlite3VdbeCountChanges(Vdbe *v){
4408   v->changeCntOn = 1;
4409 }
4410 
4411 /*
4412 ** Mark every prepared statement associated with a database connection
4413 ** as expired.
4414 **
4415 ** An expired statement means that recompilation of the statement is
4416 ** recommend.  Statements expire when things happen that make their
4417 ** programs obsolete.  Removing user-defined functions or collating
4418 ** sequences, or changing an authorization function are the types of
4419 ** things that make prepared statements obsolete.
4420 */
4421 void sqlite3ExpirePreparedStatements(sqlite3 *db){
4422   Vdbe *p;
4423   for(p = db->pVdbe; p; p=p->pNext){
4424     p->expired = 1;
4425   }
4426 }
4427 
4428 /*
4429 ** Return the database associated with the Vdbe.
4430 */
4431 sqlite3 *sqlite3VdbeDb(Vdbe *v){
4432   return v->db;
4433 }
4434 
4435 /*
4436 ** Return a pointer to an sqlite3_value structure containing the value bound
4437 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
4438 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
4439 ** constants) to the value before returning it.
4440 **
4441 ** The returned value must be freed by the caller using sqlite3ValueFree().
4442 */
4443 sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
4444   assert( iVar>0 );
4445   if( v ){
4446     Mem *pMem = &v->aVar[iVar-1];
4447     if( 0==(pMem->flags & MEM_Null) ){
4448       sqlite3_value *pRet = sqlite3ValueNew(v->db);
4449       if( pRet ){
4450         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
4451         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
4452       }
4453       return pRet;
4454     }
4455   }
4456   return 0;
4457 }
4458 
4459 /*
4460 ** Configure SQL variable iVar so that binding a new value to it signals
4461 ** to sqlite3_reoptimize() that re-preparing the statement may result
4462 ** in a better query plan.
4463 */
4464 void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
4465   assert( iVar>0 );
4466   if( iVar>32 ){
4467     v->expmask = 0xffffffff;
4468   }else{
4469     v->expmask |= ((u32)1 << (iVar-1));
4470   }
4471 }
4472 
4473 #ifndef SQLITE_OMIT_VIRTUALTABLE
4474 /*
4475 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
4476 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
4477 ** in memory obtained from sqlite3DbMalloc).
4478 */
4479 void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
4480   if( pVtab->zErrMsg ){
4481     sqlite3 *db = p->db;
4482     sqlite3DbFree(db, p->zErrMsg);
4483     p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
4484     sqlite3_free(pVtab->zErrMsg);
4485     pVtab->zErrMsg = 0;
4486   }
4487 }
4488 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4489