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