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