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