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