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