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