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