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