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