xref: /sqlite-3.40.0/src/vdbeaux.c (revision 9ec82ff2)
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 static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
2501   sqlite3 *const db = p->db;
2502   int rc = SQLITE_OK;
2503   int i;
2504   const int iSavepoint = p->iStatement-1;
2505 
2506   assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
2507   assert( db->nStatement>0 );
2508   assert( p->iStatement==(db->nStatement+db->nSavepoint) );
2509 
2510   for(i=0; i<db->nDb; i++){
2511     int rc2 = SQLITE_OK;
2512     Btree *pBt = db->aDb[i].pBt;
2513     if( pBt ){
2514       if( eOp==SAVEPOINT_ROLLBACK ){
2515         rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
2516       }
2517       if( rc2==SQLITE_OK ){
2518         rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
2519       }
2520       if( rc==SQLITE_OK ){
2521         rc = rc2;
2522       }
2523     }
2524   }
2525   db->nStatement--;
2526   p->iStatement = 0;
2527 
2528   if( rc==SQLITE_OK ){
2529     if( eOp==SAVEPOINT_ROLLBACK ){
2530       rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
2531     }
2532     if( rc==SQLITE_OK ){
2533       rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
2534     }
2535   }
2536 
2537   /* If the statement transaction is being rolled back, also restore the
2538   ** database handles deferred constraint counter to the value it had when
2539   ** the statement transaction was opened.  */
2540   if( eOp==SAVEPOINT_ROLLBACK ){
2541     db->nDeferredCons = p->nStmtDefCons;
2542     db->nDeferredImmCons = p->nStmtDefImmCons;
2543   }
2544   return rc;
2545 }
2546 int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
2547   if( p->db->nStatement && p->iStatement ){
2548     return vdbeCloseStatement(p, eOp);
2549   }
2550   return SQLITE_OK;
2551 }
2552 
2553 
2554 /*
2555 ** This function is called when a transaction opened by the database
2556 ** handle associated with the VM passed as an argument is about to be
2557 ** committed. If there are outstanding deferred foreign key constraint
2558 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
2559 **
2560 ** If there are outstanding FK violations and this function returns
2561 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
2562 ** and write an error message to it. Then return SQLITE_ERROR.
2563 */
2564 #ifndef SQLITE_OMIT_FOREIGN_KEY
2565 int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
2566   sqlite3 *db = p->db;
2567   if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
2568    || (!deferred && p->nFkConstraint>0)
2569   ){
2570     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
2571     p->errorAction = OE_Abort;
2572     sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
2573     return SQLITE_ERROR;
2574   }
2575   return SQLITE_OK;
2576 }
2577 #endif
2578 
2579 /*
2580 ** This routine is called the when a VDBE tries to halt.  If the VDBE
2581 ** has made changes and is in autocommit mode, then commit those
2582 ** changes.  If a rollback is needed, then do the rollback.
2583 **
2584 ** This routine is the only way to move the state of a VM from
2585 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
2586 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
2587 **
2588 ** Return an error code.  If the commit could not complete because of
2589 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
2590 ** means the close did not happen and needs to be repeated.
2591 */
2592 int sqlite3VdbeHalt(Vdbe *p){
2593   int rc;                         /* Used to store transient return codes */
2594   sqlite3 *db = p->db;
2595 
2596   /* This function contains the logic that determines if a statement or
2597   ** transaction will be committed or rolled back as a result of the
2598   ** execution of this virtual machine.
2599   **
2600   ** If any of the following errors occur:
2601   **
2602   **     SQLITE_NOMEM
2603   **     SQLITE_IOERR
2604   **     SQLITE_FULL
2605   **     SQLITE_INTERRUPT
2606   **
2607   ** Then the internal cache might have been left in an inconsistent
2608   ** state.  We need to rollback the statement transaction, if there is
2609   ** one, or the complete transaction if there is no statement transaction.
2610   */
2611 
2612   if( db->mallocFailed ){
2613     p->rc = SQLITE_NOMEM_BKPT;
2614   }
2615   closeAllCursors(p);
2616   if( p->magic!=VDBE_MAGIC_RUN ){
2617     return SQLITE_OK;
2618   }
2619   checkActiveVdbeCnt(db);
2620 
2621   /* No commit or rollback needed if the program never started or if the
2622   ** SQL statement does not read or write a database file.  */
2623   if( p->pc>=0 && p->bIsReader ){
2624     int mrc;   /* Primary error code from p->rc */
2625     int eStatementOp = 0;
2626     int isSpecialError;            /* Set to true if a 'special' error */
2627 
2628     /* Lock all btrees used by the statement */
2629     sqlite3VdbeEnter(p);
2630 
2631     /* Check for one of the special errors */
2632     mrc = p->rc & 0xff;
2633     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
2634                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
2635     if( isSpecialError ){
2636       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
2637       ** no rollback is necessary. Otherwise, at least a savepoint
2638       ** transaction must be rolled back to restore the database to a
2639       ** consistent state.
2640       **
2641       ** Even if the statement is read-only, it is important to perform
2642       ** a statement or transaction rollback operation. If the error
2643       ** occurred while writing to the journal, sub-journal or database
2644       ** file as part of an effort to free up cache space (see function
2645       ** pagerStress() in pager.c), the rollback is required to restore
2646       ** the pager to a consistent state.
2647       */
2648       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
2649         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
2650           eStatementOp = SAVEPOINT_ROLLBACK;
2651         }else{
2652           /* We are forced to roll back the active transaction. Before doing
2653           ** so, abort any other statements this handle currently has active.
2654           */
2655           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2656           sqlite3CloseSavepoints(db);
2657           db->autoCommit = 1;
2658           p->nChange = 0;
2659         }
2660       }
2661     }
2662 
2663     /* Check for immediate foreign key violations. */
2664     if( p->rc==SQLITE_OK ){
2665       sqlite3VdbeCheckFk(p, 0);
2666     }
2667 
2668     /* If the auto-commit flag is set and this is the only active writer
2669     ** VM, then we do either a commit or rollback of the current transaction.
2670     **
2671     ** Note: This block also runs if one of the special errors handled
2672     ** above has occurred.
2673     */
2674     if( !sqlite3VtabInSync(db)
2675      && db->autoCommit
2676      && db->nVdbeWrite==(p->readOnly==0)
2677     ){
2678       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
2679         rc = sqlite3VdbeCheckFk(p, 1);
2680         if( rc!=SQLITE_OK ){
2681           if( NEVER(p->readOnly) ){
2682             sqlite3VdbeLeave(p);
2683             return SQLITE_ERROR;
2684           }
2685           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
2686         }else{
2687           /* The auto-commit flag is true, the vdbe program was successful
2688           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
2689           ** key constraints to hold up the transaction. This means a commit
2690           ** is required. */
2691           rc = vdbeCommit(db, p);
2692         }
2693         if( rc==SQLITE_BUSY && p->readOnly ){
2694           sqlite3VdbeLeave(p);
2695           return SQLITE_BUSY;
2696         }else if( rc!=SQLITE_OK ){
2697           p->rc = rc;
2698           sqlite3RollbackAll(db, SQLITE_OK);
2699           p->nChange = 0;
2700         }else{
2701           db->nDeferredCons = 0;
2702           db->nDeferredImmCons = 0;
2703           db->flags &= ~SQLITE_DeferFKs;
2704           sqlite3CommitInternalChanges(db);
2705         }
2706       }else{
2707         sqlite3RollbackAll(db, SQLITE_OK);
2708         p->nChange = 0;
2709       }
2710       db->nStatement = 0;
2711     }else if( eStatementOp==0 ){
2712       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
2713         eStatementOp = SAVEPOINT_RELEASE;
2714       }else if( p->errorAction==OE_Abort ){
2715         eStatementOp = SAVEPOINT_ROLLBACK;
2716       }else{
2717         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2718         sqlite3CloseSavepoints(db);
2719         db->autoCommit = 1;
2720         p->nChange = 0;
2721       }
2722     }
2723 
2724     /* If eStatementOp is non-zero, then a statement transaction needs to
2725     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
2726     ** do so. If this operation returns an error, and the current statement
2727     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
2728     ** current statement error code.
2729     */
2730     if( eStatementOp ){
2731       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
2732       if( rc ){
2733         if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
2734           p->rc = rc;
2735           sqlite3DbFree(db, p->zErrMsg);
2736           p->zErrMsg = 0;
2737         }
2738         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2739         sqlite3CloseSavepoints(db);
2740         db->autoCommit = 1;
2741         p->nChange = 0;
2742       }
2743     }
2744 
2745     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
2746     ** has been rolled back, update the database connection change-counter.
2747     */
2748     if( p->changeCntOn ){
2749       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
2750         sqlite3VdbeSetChanges(db, p->nChange);
2751       }else{
2752         sqlite3VdbeSetChanges(db, 0);
2753       }
2754       p->nChange = 0;
2755     }
2756 
2757     /* Release the locks */
2758     sqlite3VdbeLeave(p);
2759   }
2760 
2761   /* We have successfully halted and closed the VM.  Record this fact. */
2762   if( p->pc>=0 ){
2763     db->nVdbeActive--;
2764     if( !p->readOnly ) db->nVdbeWrite--;
2765     if( p->bIsReader ) db->nVdbeRead--;
2766     assert( db->nVdbeActive>=db->nVdbeRead );
2767     assert( db->nVdbeRead>=db->nVdbeWrite );
2768     assert( db->nVdbeWrite>=0 );
2769   }
2770   p->magic = VDBE_MAGIC_HALT;
2771   checkActiveVdbeCnt(db);
2772   if( db->mallocFailed ){
2773     p->rc = SQLITE_NOMEM_BKPT;
2774   }
2775 
2776   /* If the auto-commit flag is set to true, then any locks that were held
2777   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
2778   ** to invoke any required unlock-notify callbacks.
2779   */
2780   if( db->autoCommit ){
2781     sqlite3ConnectionUnlocked(db);
2782   }
2783 
2784   assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
2785   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
2786 }
2787 
2788 
2789 /*
2790 ** Each VDBE holds the result of the most recent sqlite3_step() call
2791 ** in p->rc.  This routine sets that result back to SQLITE_OK.
2792 */
2793 void sqlite3VdbeResetStepResult(Vdbe *p){
2794   p->rc = SQLITE_OK;
2795 }
2796 
2797 /*
2798 ** Copy the error code and error message belonging to the VDBE passed
2799 ** as the first argument to its database handle (so that they will be
2800 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
2801 **
2802 ** This function does not clear the VDBE error code or message, just
2803 ** copies them to the database handle.
2804 */
2805 int sqlite3VdbeTransferError(Vdbe *p){
2806   sqlite3 *db = p->db;
2807   int rc = p->rc;
2808   if( p->zErrMsg ){
2809     db->bBenignMalloc++;
2810     sqlite3BeginBenignMalloc();
2811     if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
2812     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
2813     sqlite3EndBenignMalloc();
2814     db->bBenignMalloc--;
2815     db->errCode = rc;
2816   }else{
2817     sqlite3Error(db, rc);
2818   }
2819   return rc;
2820 }
2821 
2822 #ifdef SQLITE_ENABLE_SQLLOG
2823 /*
2824 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
2825 ** invoke it.
2826 */
2827 static void vdbeInvokeSqllog(Vdbe *v){
2828   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
2829     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
2830     assert( v->db->init.busy==0 );
2831     if( zExpanded ){
2832       sqlite3GlobalConfig.xSqllog(
2833           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
2834       );
2835       sqlite3DbFree(v->db, zExpanded);
2836     }
2837   }
2838 }
2839 #else
2840 # define vdbeInvokeSqllog(x)
2841 #endif
2842 
2843 /*
2844 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
2845 ** Write any error messages into *pzErrMsg.  Return the result code.
2846 **
2847 ** After this routine is run, the VDBE should be ready to be executed
2848 ** again.
2849 **
2850 ** To look at it another way, this routine resets the state of the
2851 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
2852 ** VDBE_MAGIC_INIT.
2853 */
2854 int sqlite3VdbeReset(Vdbe *p){
2855   sqlite3 *db;
2856   db = p->db;
2857 
2858   /* If the VM did not run to completion or if it encountered an
2859   ** error, then it might not have been halted properly.  So halt
2860   ** it now.
2861   */
2862   sqlite3VdbeHalt(p);
2863 
2864   /* If the VDBE has be run even partially, then transfer the error code
2865   ** and error message from the VDBE into the main database structure.  But
2866   ** if the VDBE has just been set to run but has not actually executed any
2867   ** instructions yet, leave the main database error information unchanged.
2868   */
2869   if( p->pc>=0 ){
2870     vdbeInvokeSqllog(p);
2871     sqlite3VdbeTransferError(p);
2872     sqlite3DbFree(db, p->zErrMsg);
2873     p->zErrMsg = 0;
2874     if( p->runOnlyOnce ) p->expired = 1;
2875   }else if( p->rc && p->expired ){
2876     /* The expired flag was set on the VDBE before the first call
2877     ** to sqlite3_step(). For consistency (since sqlite3_step() was
2878     ** called), set the database error in this case as well.
2879     */
2880     sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
2881     sqlite3DbFree(db, p->zErrMsg);
2882     p->zErrMsg = 0;
2883   }
2884 
2885   /* Reclaim all memory used by the VDBE
2886   */
2887   Cleanup(p);
2888 
2889   /* Save profiling information from this VDBE run.
2890   */
2891 #ifdef VDBE_PROFILE
2892   {
2893     FILE *out = fopen("vdbe_profile.out", "a");
2894     if( out ){
2895       int i;
2896       fprintf(out, "---- ");
2897       for(i=0; i<p->nOp; i++){
2898         fprintf(out, "%02x", p->aOp[i].opcode);
2899       }
2900       fprintf(out, "\n");
2901       if( p->zSql ){
2902         char c, pc = 0;
2903         fprintf(out, "-- ");
2904         for(i=0; (c = p->zSql[i])!=0; i++){
2905           if( pc=='\n' ) fprintf(out, "-- ");
2906           putc(c, out);
2907           pc = c;
2908         }
2909         if( pc!='\n' ) fprintf(out, "\n");
2910       }
2911       for(i=0; i<p->nOp; i++){
2912         char zHdr[100];
2913         sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
2914            p->aOp[i].cnt,
2915            p->aOp[i].cycles,
2916            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
2917         );
2918         fprintf(out, "%s", zHdr);
2919         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
2920       }
2921       fclose(out);
2922     }
2923   }
2924 #endif
2925   p->iCurrentTime = 0;
2926   p->magic = VDBE_MAGIC_RESET;
2927   return p->rc & db->errMask;
2928 }
2929 
2930 /*
2931 ** Clean up and delete a VDBE after execution.  Return an integer which is
2932 ** the result code.  Write any error message text into *pzErrMsg.
2933 */
2934 int sqlite3VdbeFinalize(Vdbe *p){
2935   int rc = SQLITE_OK;
2936   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
2937     rc = sqlite3VdbeReset(p);
2938     assert( (rc & p->db->errMask)==rc );
2939   }
2940   sqlite3VdbeDelete(p);
2941   return rc;
2942 }
2943 
2944 /*
2945 ** If parameter iOp is less than zero, then invoke the destructor for
2946 ** all auxiliary data pointers currently cached by the VM passed as
2947 ** the first argument.
2948 **
2949 ** Or, if iOp is greater than or equal to zero, then the destructor is
2950 ** only invoked for those auxiliary data pointers created by the user
2951 ** function invoked by the OP_Function opcode at instruction iOp of
2952 ** VM pVdbe, and only then if:
2953 **
2954 **    * the associated function parameter is the 32nd or later (counting
2955 **      from left to right), or
2956 **
2957 **    * the corresponding bit in argument mask is clear (where the first
2958 **      function parameter corresponds to bit 0 etc.).
2959 */
2960 void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
2961   while( *pp ){
2962     AuxData *pAux = *pp;
2963     if( (iOp<0)
2964      || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
2965     ){
2966       testcase( pAux->iArg==31 );
2967       if( pAux->xDelete ){
2968         pAux->xDelete(pAux->pAux);
2969       }
2970       *pp = pAux->pNext;
2971       sqlite3DbFree(db, pAux);
2972     }else{
2973       pp= &pAux->pNext;
2974     }
2975   }
2976 }
2977 
2978 /*
2979 ** Free all memory associated with the Vdbe passed as the second argument,
2980 ** except for object itself, which is preserved.
2981 **
2982 ** The difference between this function and sqlite3VdbeDelete() is that
2983 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
2984 ** the database connection and frees the object itself.
2985 */
2986 void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
2987   SubProgram *pSub, *pNext;
2988   assert( p->db==0 || p->db==db );
2989   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
2990   for(pSub=p->pProgram; pSub; pSub=pNext){
2991     pNext = pSub->pNext;
2992     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
2993     sqlite3DbFree(db, pSub);
2994   }
2995   if( p->magic!=VDBE_MAGIC_INIT ){
2996     releaseMemArray(p->aVar, p->nVar);
2997     sqlite3DbFree(db, p->pVList);
2998     sqlite3DbFree(db, p->pFree);
2999   }
3000   vdbeFreeOpArray(db, p->aOp, p->nOp);
3001   sqlite3DbFree(db, p->aColName);
3002   sqlite3DbFree(db, p->zSql);
3003 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3004   {
3005     int i;
3006     for(i=0; i<p->nScan; i++){
3007       sqlite3DbFree(db, p->aScan[i].zName);
3008     }
3009     sqlite3DbFree(db, p->aScan);
3010   }
3011 #endif
3012 }
3013 
3014 /*
3015 ** Delete an entire VDBE.
3016 */
3017 void sqlite3VdbeDelete(Vdbe *p){
3018   sqlite3 *db;
3019 
3020   if( NEVER(p==0) ) return;
3021   db = p->db;
3022   assert( sqlite3_mutex_held(db->mutex) );
3023   sqlite3VdbeClearObject(db, p);
3024   if( p->pPrev ){
3025     p->pPrev->pNext = p->pNext;
3026   }else{
3027     assert( db->pVdbe==p );
3028     db->pVdbe = p->pNext;
3029   }
3030   if( p->pNext ){
3031     p->pNext->pPrev = p->pPrev;
3032   }
3033   p->magic = VDBE_MAGIC_DEAD;
3034   p->db = 0;
3035   sqlite3DbFree(db, p);
3036 }
3037 
3038 /*
3039 ** The cursor "p" has a pending seek operation that has not yet been
3040 ** carried out.  Seek the cursor now.  If an error occurs, return
3041 ** the appropriate error code.
3042 */
3043 static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
3044   int res, rc;
3045 #ifdef SQLITE_TEST
3046   extern int sqlite3_search_count;
3047 #endif
3048   assert( p->deferredMoveto );
3049   assert( p->isTable );
3050   assert( p->eCurType==CURTYPE_BTREE );
3051   rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
3052   if( rc ) return rc;
3053   if( res!=0 ) return SQLITE_CORRUPT_BKPT;
3054 #ifdef SQLITE_TEST
3055   sqlite3_search_count++;
3056 #endif
3057   p->deferredMoveto = 0;
3058   p->cacheStatus = CACHE_STALE;
3059   return SQLITE_OK;
3060 }
3061 
3062 /*
3063 ** Something has moved cursor "p" out of place.  Maybe the row it was
3064 ** pointed to was deleted out from under it.  Or maybe the btree was
3065 ** rebalanced.  Whatever the cause, try to restore "p" to the place it
3066 ** is supposed to be pointing.  If the row was deleted out from under the
3067 ** cursor, set the cursor to point to a NULL row.
3068 */
3069 static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
3070   int isDifferentRow, rc;
3071   assert( p->eCurType==CURTYPE_BTREE );
3072   assert( p->uc.pCursor!=0 );
3073   assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
3074   rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
3075   p->cacheStatus = CACHE_STALE;
3076   if( isDifferentRow ) p->nullRow = 1;
3077   return rc;
3078 }
3079 
3080 /*
3081 ** Check to ensure that the cursor is valid.  Restore the cursor
3082 ** if need be.  Return any I/O error from the restore operation.
3083 */
3084 int sqlite3VdbeCursorRestore(VdbeCursor *p){
3085   assert( p->eCurType==CURTYPE_BTREE );
3086   if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
3087     return handleMovedCursor(p);
3088   }
3089   return SQLITE_OK;
3090 }
3091 
3092 /*
3093 ** Make sure the cursor p is ready to read or write the row to which it
3094 ** was last positioned.  Return an error code if an OOM fault or I/O error
3095 ** prevents us from positioning the cursor to its correct position.
3096 **
3097 ** If a MoveTo operation is pending on the given cursor, then do that
3098 ** MoveTo now.  If no move is pending, check to see if the row has been
3099 ** deleted out from under the cursor and if it has, mark the row as
3100 ** a NULL row.
3101 **
3102 ** If the cursor is already pointing to the correct row and that row has
3103 ** not been deleted out from under the cursor, then this routine is a no-op.
3104 */
3105 int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
3106   VdbeCursor *p = *pp;
3107   if( p->eCurType==CURTYPE_BTREE ){
3108     if( p->deferredMoveto ){
3109       int iMap;
3110       if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
3111         *pp = p->pAltCursor;
3112         *piCol = iMap - 1;
3113         return SQLITE_OK;
3114       }
3115       return handleDeferredMoveto(p);
3116     }
3117     if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
3118       return handleMovedCursor(p);
3119     }
3120   }
3121   return SQLITE_OK;
3122 }
3123 
3124 /*
3125 ** The following functions:
3126 **
3127 ** sqlite3VdbeSerialType()
3128 ** sqlite3VdbeSerialTypeLen()
3129 ** sqlite3VdbeSerialLen()
3130 ** sqlite3VdbeSerialPut()
3131 ** sqlite3VdbeSerialGet()
3132 **
3133 ** encapsulate the code that serializes values for storage in SQLite
3134 ** data and index records. Each serialized value consists of a
3135 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
3136 ** integer, stored as a varint.
3137 **
3138 ** In an SQLite index record, the serial type is stored directly before
3139 ** the blob of data that it corresponds to. In a table record, all serial
3140 ** types are stored at the start of the record, and the blobs of data at
3141 ** the end. Hence these functions allow the caller to handle the
3142 ** serial-type and data blob separately.
3143 **
3144 ** The following table describes the various storage classes for data:
3145 **
3146 **   serial type        bytes of data      type
3147 **   --------------     ---------------    ---------------
3148 **      0                     0            NULL
3149 **      1                     1            signed integer
3150 **      2                     2            signed integer
3151 **      3                     3            signed integer
3152 **      4                     4            signed integer
3153 **      5                     6            signed integer
3154 **      6                     8            signed integer
3155 **      7                     8            IEEE float
3156 **      8                     0            Integer constant 0
3157 **      9                     0            Integer constant 1
3158 **     10,11                               reserved for expansion
3159 **    N>=12 and even       (N-12)/2        BLOB
3160 **    N>=13 and odd        (N-13)/2        text
3161 **
3162 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
3163 ** of SQLite will not understand those serial types.
3164 */
3165 
3166 /*
3167 ** Return the serial-type for the value stored in pMem.
3168 */
3169 u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
3170   int flags = pMem->flags;
3171   u32 n;
3172 
3173   assert( pLen!=0 );
3174   if( flags&MEM_Null ){
3175     *pLen = 0;
3176     return 0;
3177   }
3178   if( flags&MEM_Int ){
3179     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
3180 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
3181     i64 i = pMem->u.i;
3182     u64 u;
3183     if( i<0 ){
3184       u = ~i;
3185     }else{
3186       u = i;
3187     }
3188     if( u<=127 ){
3189       if( (i&1)==i && file_format>=4 ){
3190         *pLen = 0;
3191         return 8+(u32)u;
3192       }else{
3193         *pLen = 1;
3194         return 1;
3195       }
3196     }
3197     if( u<=32767 ){ *pLen = 2; return 2; }
3198     if( u<=8388607 ){ *pLen = 3; return 3; }
3199     if( u<=2147483647 ){ *pLen = 4; return 4; }
3200     if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
3201     *pLen = 8;
3202     return 6;
3203   }
3204   if( flags&MEM_Real ){
3205     *pLen = 8;
3206     return 7;
3207   }
3208   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
3209   assert( pMem->n>=0 );
3210   n = (u32)pMem->n;
3211   if( flags & MEM_Zero ){
3212     n += pMem->u.nZero;
3213   }
3214   *pLen = n;
3215   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
3216 }
3217 
3218 /*
3219 ** The sizes for serial types less than 128
3220 */
3221 static const u8 sqlite3SmallTypeSizes[] = {
3222         /*  0   1   2   3   4   5   6   7   8   9 */
3223 /*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
3224 /*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
3225 /*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
3226 /*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
3227 /*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
3228 /*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
3229 /*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
3230 /*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
3231 /*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
3232 /*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
3233 /* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
3234 /* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
3235 /* 120 */  54, 54, 55, 55, 56, 56, 57, 57
3236 };
3237 
3238 /*
3239 ** Return the length of the data corresponding to the supplied serial-type.
3240 */
3241 u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
3242   if( serial_type>=128 ){
3243     return (serial_type-12)/2;
3244   }else{
3245     assert( serial_type<12
3246             || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
3247     return sqlite3SmallTypeSizes[serial_type];
3248   }
3249 }
3250 u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
3251   assert( serial_type<128 );
3252   return sqlite3SmallTypeSizes[serial_type];
3253 }
3254 
3255 /*
3256 ** If we are on an architecture with mixed-endian floating
3257 ** points (ex: ARM7) then swap the lower 4 bytes with the
3258 ** upper 4 bytes.  Return the result.
3259 **
3260 ** For most architectures, this is a no-op.
3261 **
3262 ** (later):  It is reported to me that the mixed-endian problem
3263 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
3264 ** that early versions of GCC stored the two words of a 64-bit
3265 ** float in the wrong order.  And that error has been propagated
3266 ** ever since.  The blame is not necessarily with GCC, though.
3267 ** GCC might have just copying the problem from a prior compiler.
3268 ** I am also told that newer versions of GCC that follow a different
3269 ** ABI get the byte order right.
3270 **
3271 ** Developers using SQLite on an ARM7 should compile and run their
3272 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
3273 ** enabled, some asserts below will ensure that the byte order of
3274 ** floating point values is correct.
3275 **
3276 ** (2007-08-30)  Frank van Vugt has studied this problem closely
3277 ** and has send his findings to the SQLite developers.  Frank
3278 ** writes that some Linux kernels offer floating point hardware
3279 ** emulation that uses only 32-bit mantissas instead of a full
3280 ** 48-bits as required by the IEEE standard.  (This is the
3281 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
3282 ** byte swapping becomes very complicated.  To avoid problems,
3283 ** the necessary byte swapping is carried out using a 64-bit integer
3284 ** rather than a 64-bit float.  Frank assures us that the code here
3285 ** works for him.  We, the developers, have no way to independently
3286 ** verify this, but Frank seems to know what he is talking about
3287 ** so we trust him.
3288 */
3289 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
3290 static u64 floatSwap(u64 in){
3291   union {
3292     u64 r;
3293     u32 i[2];
3294   } u;
3295   u32 t;
3296 
3297   u.r = in;
3298   t = u.i[0];
3299   u.i[0] = u.i[1];
3300   u.i[1] = t;
3301   return u.r;
3302 }
3303 # define swapMixedEndianFloat(X)  X = floatSwap(X)
3304 #else
3305 # define swapMixedEndianFloat(X)
3306 #endif
3307 
3308 /*
3309 ** Write the serialized data blob for the value stored in pMem into
3310 ** buf. It is assumed that the caller has allocated sufficient space.
3311 ** Return the number of bytes written.
3312 **
3313 ** nBuf is the amount of space left in buf[].  The caller is responsible
3314 ** for allocating enough space to buf[] to hold the entire field, exclusive
3315 ** of the pMem->u.nZero bytes for a MEM_Zero value.
3316 **
3317 ** Return the number of bytes actually written into buf[].  The number
3318 ** of bytes in the zero-filled tail is included in the return value only
3319 ** if those bytes were zeroed in buf[].
3320 */
3321 u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
3322   u32 len;
3323 
3324   /* Integer and Real */
3325   if( serial_type<=7 && serial_type>0 ){
3326     u64 v;
3327     u32 i;
3328     if( serial_type==7 ){
3329       assert( sizeof(v)==sizeof(pMem->u.r) );
3330       memcpy(&v, &pMem->u.r, sizeof(v));
3331       swapMixedEndianFloat(v);
3332     }else{
3333       v = pMem->u.i;
3334     }
3335     len = i = sqlite3SmallTypeSizes[serial_type];
3336     assert( i>0 );
3337     do{
3338       buf[--i] = (u8)(v&0xFF);
3339       v >>= 8;
3340     }while( i );
3341     return len;
3342   }
3343 
3344   /* String or blob */
3345   if( serial_type>=12 ){
3346     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
3347              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
3348     len = pMem->n;
3349     if( len>0 ) memcpy(buf, pMem->z, len);
3350     return len;
3351   }
3352 
3353   /* NULL or constants 0 or 1 */
3354   return 0;
3355 }
3356 
3357 /* Input "x" is a sequence of unsigned characters that represent a
3358 ** big-endian integer.  Return the equivalent native integer
3359 */
3360 #define ONE_BYTE_INT(x)    ((i8)(x)[0])
3361 #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
3362 #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
3363 #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
3364 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
3365 
3366 /*
3367 ** Deserialize the data blob pointed to by buf as serial type serial_type
3368 ** and store the result in pMem.  Return the number of bytes read.
3369 **
3370 ** This function is implemented as two separate routines for performance.
3371 ** The few cases that require local variables are broken out into a separate
3372 ** routine so that in most cases the overhead of moving the stack pointer
3373 ** is avoided.
3374 */
3375 static u32 SQLITE_NOINLINE serialGet(
3376   const unsigned char *buf,     /* Buffer to deserialize from */
3377   u32 serial_type,              /* Serial type to deserialize */
3378   Mem *pMem                     /* Memory cell to write value into */
3379 ){
3380   u64 x = FOUR_BYTE_UINT(buf);
3381   u32 y = FOUR_BYTE_UINT(buf+4);
3382   x = (x<<32) + y;
3383   if( serial_type==6 ){
3384     /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
3385     ** twos-complement integer. */
3386     pMem->u.i = *(i64*)&x;
3387     pMem->flags = MEM_Int;
3388     testcase( pMem->u.i<0 );
3389   }else{
3390     /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
3391     ** floating point number. */
3392 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
3393     /* Verify that integers and floating point values use the same
3394     ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
3395     ** defined that 64-bit floating point values really are mixed
3396     ** endian.
3397     */
3398     static const u64 t1 = ((u64)0x3ff00000)<<32;
3399     static const double r1 = 1.0;
3400     u64 t2 = t1;
3401     swapMixedEndianFloat(t2);
3402     assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
3403 #endif
3404     assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
3405     swapMixedEndianFloat(x);
3406     memcpy(&pMem->u.r, &x, sizeof(x));
3407     pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
3408   }
3409   return 8;
3410 }
3411 u32 sqlite3VdbeSerialGet(
3412   const unsigned char *buf,     /* Buffer to deserialize from */
3413   u32 serial_type,              /* Serial type to deserialize */
3414   Mem *pMem                     /* Memory cell to write value into */
3415 ){
3416   switch( serial_type ){
3417     case 10:   /* Reserved for future use */
3418     case 11:   /* Reserved for future use */
3419     case 0: {  /* Null */
3420       /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
3421       pMem->flags = MEM_Null;
3422       break;
3423     }
3424     case 1: {
3425       /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
3426       ** integer. */
3427       pMem->u.i = ONE_BYTE_INT(buf);
3428       pMem->flags = MEM_Int;
3429       testcase( pMem->u.i<0 );
3430       return 1;
3431     }
3432     case 2: { /* 2-byte signed integer */
3433       /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
3434       ** twos-complement integer. */
3435       pMem->u.i = TWO_BYTE_INT(buf);
3436       pMem->flags = MEM_Int;
3437       testcase( pMem->u.i<0 );
3438       return 2;
3439     }
3440     case 3: { /* 3-byte signed integer */
3441       /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
3442       ** twos-complement integer. */
3443       pMem->u.i = THREE_BYTE_INT(buf);
3444       pMem->flags = MEM_Int;
3445       testcase( pMem->u.i<0 );
3446       return 3;
3447     }
3448     case 4: { /* 4-byte signed integer */
3449       /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
3450       ** twos-complement integer. */
3451       pMem->u.i = FOUR_BYTE_INT(buf);
3452 #ifdef __HP_cc
3453       /* Work around a sign-extension bug in the HP compiler for HP/UX */
3454       if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
3455 #endif
3456       pMem->flags = MEM_Int;
3457       testcase( pMem->u.i<0 );
3458       return 4;
3459     }
3460     case 5: { /* 6-byte signed integer */
3461       /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
3462       ** twos-complement integer. */
3463       pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
3464       pMem->flags = MEM_Int;
3465       testcase( pMem->u.i<0 );
3466       return 6;
3467     }
3468     case 6:   /* 8-byte signed integer */
3469     case 7: { /* IEEE floating point */
3470       /* These use local variables, so do them in a separate routine
3471       ** to avoid having to move the frame pointer in the common case */
3472       return serialGet(buf,serial_type,pMem);
3473     }
3474     case 8:    /* Integer 0 */
3475     case 9: {  /* Integer 1 */
3476       /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
3477       /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
3478       pMem->u.i = serial_type-8;
3479       pMem->flags = MEM_Int;
3480       return 0;
3481     }
3482     default: {
3483       /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
3484       ** length.
3485       ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
3486       ** (N-13)/2 bytes in length. */
3487       static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
3488       pMem->z = (char *)buf;
3489       pMem->n = (serial_type-12)/2;
3490       pMem->flags = aFlag[serial_type&1];
3491       return pMem->n;
3492     }
3493   }
3494   return 0;
3495 }
3496 /*
3497 ** This routine is used to allocate sufficient space for an UnpackedRecord
3498 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
3499 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
3500 **
3501 ** The space is either allocated using sqlite3DbMallocRaw() or from within
3502 ** the unaligned buffer passed via the second and third arguments (presumably
3503 ** stack space). If the former, then *ppFree is set to a pointer that should
3504 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
3505 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
3506 ** before returning.
3507 **
3508 ** If an OOM error occurs, NULL is returned.
3509 */
3510 UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
3511   KeyInfo *pKeyInfo               /* Description of the record */
3512 ){
3513   UnpackedRecord *p;              /* Unpacked record to return */
3514   int nByte;                      /* Number of bytes required for *p */
3515   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
3516   p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
3517   if( !p ) return 0;
3518   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
3519   assert( pKeyInfo->aSortOrder!=0 );
3520   p->pKeyInfo = pKeyInfo;
3521   p->nField = pKeyInfo->nField + 1;
3522   return p;
3523 }
3524 
3525 /*
3526 ** Given the nKey-byte encoding of a record in pKey[], populate the
3527 ** UnpackedRecord structure indicated by the fourth argument with the
3528 ** contents of the decoded record.
3529 */
3530 void sqlite3VdbeRecordUnpack(
3531   KeyInfo *pKeyInfo,     /* Information about the record format */
3532   int nKey,              /* Size of the binary record */
3533   const void *pKey,      /* The binary record */
3534   UnpackedRecord *p      /* Populate this structure before returning. */
3535 ){
3536   const unsigned char *aKey = (const unsigned char *)pKey;
3537   int d;
3538   u32 idx;                        /* Offset in aKey[] to read from */
3539   u16 u;                          /* Unsigned loop counter */
3540   u32 szHdr;
3541   Mem *pMem = p->aMem;
3542 
3543   p->default_rc = 0;
3544   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
3545   idx = getVarint32(aKey, szHdr);
3546   d = szHdr;
3547   u = 0;
3548   while( idx<szHdr && d<=nKey ){
3549     u32 serial_type;
3550 
3551     idx += getVarint32(&aKey[idx], serial_type);
3552     pMem->enc = pKeyInfo->enc;
3553     pMem->db = pKeyInfo->db;
3554     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
3555     pMem->szMalloc = 0;
3556     pMem->z = 0;
3557     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
3558     pMem++;
3559     if( (++u)>=p->nField ) break;
3560   }
3561   assert( u<=pKeyInfo->nField + 1 );
3562   p->nField = u;
3563 }
3564 
3565 #if SQLITE_DEBUG
3566 /*
3567 ** This function compares two index or table record keys in the same way
3568 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
3569 ** this function deserializes and compares values using the
3570 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
3571 ** in assert() statements to ensure that the optimized code in
3572 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
3573 **
3574 ** Return true if the result of comparison is equivalent to desiredResult.
3575 ** Return false if there is a disagreement.
3576 */
3577 static int vdbeRecordCompareDebug(
3578   int nKey1, const void *pKey1, /* Left key */
3579   const UnpackedRecord *pPKey2, /* Right key */
3580   int desiredResult             /* Correct answer */
3581 ){
3582   u32 d1;            /* Offset into aKey[] of next data element */
3583   u32 idx1;          /* Offset into aKey[] of next header element */
3584   u32 szHdr1;        /* Number of bytes in header */
3585   int i = 0;
3586   int rc = 0;
3587   const unsigned char *aKey1 = (const unsigned char *)pKey1;
3588   KeyInfo *pKeyInfo;
3589   Mem mem1;
3590 
3591   pKeyInfo = pPKey2->pKeyInfo;
3592   if( pKeyInfo->db==0 ) return 1;
3593   mem1.enc = pKeyInfo->enc;
3594   mem1.db = pKeyInfo->db;
3595   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
3596   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
3597 
3598   /* Compilers may complain that mem1.u.i is potentially uninitialized.
3599   ** We could initialize it, as shown here, to silence those complaints.
3600   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
3601   ** the unnecessary initialization has a measurable negative performance
3602   ** impact, since this routine is a very high runner.  And so, we choose
3603   ** to ignore the compiler warnings and leave this variable uninitialized.
3604   */
3605   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
3606 
3607   idx1 = getVarint32(aKey1, szHdr1);
3608   if( szHdr1>98307 ) return SQLITE_CORRUPT;
3609   d1 = szHdr1;
3610   assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
3611   assert( pKeyInfo->aSortOrder!=0 );
3612   assert( pKeyInfo->nField>0 );
3613   assert( idx1<=szHdr1 || CORRUPT_DB );
3614   do{
3615     u32 serial_type1;
3616 
3617     /* Read the serial types for the next element in each key. */
3618     idx1 += getVarint32( aKey1+idx1, serial_type1 );
3619 
3620     /* Verify that there is enough key space remaining to avoid
3621     ** a buffer overread.  The "d1+serial_type1+2" subexpression will
3622     ** always be greater than or equal to the amount of required key space.
3623     ** Use that approximation to avoid the more expensive call to
3624     ** sqlite3VdbeSerialTypeLen() in the common case.
3625     */
3626     if( d1+serial_type1+2>(u32)nKey1
3627      && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
3628     ){
3629       break;
3630     }
3631 
3632     /* Extract the values to be compared.
3633     */
3634     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
3635 
3636     /* Do the comparison
3637     */
3638     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
3639     if( rc!=0 ){
3640       assert( mem1.szMalloc==0 );  /* See comment below */
3641       if( pKeyInfo->aSortOrder[i] ){
3642         rc = -rc;  /* Invert the result for DESC sort order. */
3643       }
3644       goto debugCompareEnd;
3645     }
3646     i++;
3647   }while( idx1<szHdr1 && i<pPKey2->nField );
3648 
3649   /* No memory allocation is ever used on mem1.  Prove this using
3650   ** the following assert().  If the assert() fails, it indicates a
3651   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
3652   */
3653   assert( mem1.szMalloc==0 );
3654 
3655   /* rc==0 here means that one of the keys ran out of fields and
3656   ** all the fields up to that point were equal. Return the default_rc
3657   ** value.  */
3658   rc = pPKey2->default_rc;
3659 
3660 debugCompareEnd:
3661   if( desiredResult==0 && rc==0 ) return 1;
3662   if( desiredResult<0 && rc<0 ) return 1;
3663   if( desiredResult>0 && rc>0 ) return 1;
3664   if( CORRUPT_DB ) return 1;
3665   if( pKeyInfo->db->mallocFailed ) return 1;
3666   return 0;
3667 }
3668 #endif
3669 
3670 #if SQLITE_DEBUG
3671 /*
3672 ** Count the number of fields (a.k.a. columns) in the record given by
3673 ** pKey,nKey.  The verify that this count is less than or equal to the
3674 ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
3675 **
3676 ** If this constraint is not satisfied, it means that the high-speed
3677 ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
3678 ** not work correctly.  If this assert() ever fires, it probably means
3679 ** that the KeyInfo.nField or KeyInfo.nXField values were computed
3680 ** incorrectly.
3681 */
3682 static void vdbeAssertFieldCountWithinLimits(
3683   int nKey, const void *pKey,   /* The record to verify */
3684   const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
3685 ){
3686   int nField = 0;
3687   u32 szHdr;
3688   u32 idx;
3689   u32 notUsed;
3690   const unsigned char *aKey = (const unsigned char*)pKey;
3691 
3692   if( CORRUPT_DB ) return;
3693   idx = getVarint32(aKey, szHdr);
3694   assert( nKey>=0 );
3695   assert( szHdr<=(u32)nKey );
3696   while( idx<szHdr ){
3697     idx += getVarint32(aKey+idx, notUsed);
3698     nField++;
3699   }
3700   assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
3701 }
3702 #else
3703 # define vdbeAssertFieldCountWithinLimits(A,B,C)
3704 #endif
3705 
3706 /*
3707 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
3708 ** using the collation sequence pColl. As usual, return a negative , zero
3709 ** or positive value if *pMem1 is less than, equal to or greater than
3710 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
3711 */
3712 static int vdbeCompareMemString(
3713   const Mem *pMem1,
3714   const Mem *pMem2,
3715   const CollSeq *pColl,
3716   u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
3717 ){
3718   if( pMem1->enc==pColl->enc ){
3719     /* The strings are already in the correct encoding.  Call the
3720      ** comparison function directly */
3721     return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
3722   }else{
3723     int rc;
3724     const void *v1, *v2;
3725     int n1, n2;
3726     Mem c1;
3727     Mem c2;
3728     sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
3729     sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
3730     sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
3731     sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
3732     v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
3733     n1 = v1==0 ? 0 : c1.n;
3734     v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
3735     n2 = v2==0 ? 0 : c2.n;
3736     rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
3737     if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
3738     sqlite3VdbeMemRelease(&c1);
3739     sqlite3VdbeMemRelease(&c2);
3740     return rc;
3741   }
3742 }
3743 
3744 /*
3745 ** The input pBlob is guaranteed to be a Blob that is not marked
3746 ** with MEM_Zero.  Return true if it could be a zero-blob.
3747 */
3748 static int isAllZero(const char *z, int n){
3749   int i;
3750   for(i=0; i<n; i++){
3751     if( z[i] ) return 0;
3752   }
3753   return 1;
3754 }
3755 
3756 /*
3757 ** Compare two blobs.  Return negative, zero, or positive if the first
3758 ** is less than, equal to, or greater than the second, respectively.
3759 ** If one blob is a prefix of the other, then the shorter is the lessor.
3760 */
3761 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
3762   int c;
3763   int n1 = pB1->n;
3764   int n2 = pB2->n;
3765 
3766   /* It is possible to have a Blob value that has some non-zero content
3767   ** followed by zero content.  But that only comes up for Blobs formed
3768   ** by the OP_MakeRecord opcode, and such Blobs never get passed into
3769   ** sqlite3MemCompare(). */
3770   assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
3771   assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
3772 
3773   if( (pB1->flags|pB2->flags) & MEM_Zero ){
3774     if( pB1->flags & pB2->flags & MEM_Zero ){
3775       return pB1->u.nZero - pB2->u.nZero;
3776     }else if( pB1->flags & MEM_Zero ){
3777       if( !isAllZero(pB2->z, pB2->n) ) return -1;
3778       return pB1->u.nZero - n2;
3779     }else{
3780       if( !isAllZero(pB1->z, pB1->n) ) return +1;
3781       return n1 - pB2->u.nZero;
3782     }
3783   }
3784   c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
3785   if( c ) return c;
3786   return n1 - n2;
3787 }
3788 
3789 /*
3790 ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
3791 ** number.  Return negative, zero, or positive if the first (i64) is less than,
3792 ** equal to, or greater than the second (double).
3793 */
3794 static int sqlite3IntFloatCompare(i64 i, double r){
3795   if( sizeof(LONGDOUBLE_TYPE)>8 ){
3796     LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
3797     if( x<r ) return -1;
3798     if( x>r ) return +1;
3799     return 0;
3800   }else{
3801     i64 y;
3802     double s;
3803     if( r<-9223372036854775808.0 ) return +1;
3804     if( r>9223372036854775807.0 ) return -1;
3805     y = (i64)r;
3806     if( i<y ) return -1;
3807     if( i>y ){
3808       if( y==SMALLEST_INT64 && r>0.0 ) return -1;
3809       return +1;
3810     }
3811     s = (double)i;
3812     if( s<r ) return -1;
3813     if( s>r ) return +1;
3814     return 0;
3815   }
3816 }
3817 
3818 /*
3819 ** Compare the values contained by the two memory cells, returning
3820 ** negative, zero or positive if pMem1 is less than, equal to, or greater
3821 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
3822 ** and reals) sorted numerically, followed by text ordered by the collating
3823 ** sequence pColl and finally blob's ordered by memcmp().
3824 **
3825 ** Two NULL values are considered equal by this function.
3826 */
3827 int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
3828   int f1, f2;
3829   int combined_flags;
3830 
3831   f1 = pMem1->flags;
3832   f2 = pMem2->flags;
3833   combined_flags = f1|f2;
3834   assert( (combined_flags & MEM_RowSet)==0 );
3835 
3836   /* If one value is NULL, it is less than the other. If both values
3837   ** are NULL, return 0.
3838   */
3839   if( combined_flags&MEM_Null ){
3840     return (f2&MEM_Null) - (f1&MEM_Null);
3841   }
3842 
3843   /* At least one of the two values is a number
3844   */
3845   if( combined_flags&(MEM_Int|MEM_Real) ){
3846     if( (f1 & f2 & MEM_Int)!=0 ){
3847       if( pMem1->u.i < pMem2->u.i ) return -1;
3848       if( pMem1->u.i > pMem2->u.i ) return +1;
3849       return 0;
3850     }
3851     if( (f1 & f2 & MEM_Real)!=0 ){
3852       if( pMem1->u.r < pMem2->u.r ) return -1;
3853       if( pMem1->u.r > pMem2->u.r ) return +1;
3854       return 0;
3855     }
3856     if( (f1&MEM_Int)!=0 ){
3857       if( (f2&MEM_Real)!=0 ){
3858         return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
3859       }else{
3860         return -1;
3861       }
3862     }
3863     if( (f1&MEM_Real)!=0 ){
3864       if( (f2&MEM_Int)!=0 ){
3865         return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
3866       }else{
3867         return -1;
3868       }
3869     }
3870     return +1;
3871   }
3872 
3873   /* If one value is a string and the other is a blob, the string is less.
3874   ** If both are strings, compare using the collating functions.
3875   */
3876   if( combined_flags&MEM_Str ){
3877     if( (f1 & MEM_Str)==0 ){
3878       return 1;
3879     }
3880     if( (f2 & MEM_Str)==0 ){
3881       return -1;
3882     }
3883 
3884     assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
3885     assert( pMem1->enc==SQLITE_UTF8 ||
3886             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
3887 
3888     /* The collation sequence must be defined at this point, even if
3889     ** the user deletes the collation sequence after the vdbe program is
3890     ** compiled (this was not always the case).
3891     */
3892     assert( !pColl || pColl->xCmp );
3893 
3894     if( pColl ){
3895       return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
3896     }
3897     /* If a NULL pointer was passed as the collate function, fall through
3898     ** to the blob case and use memcmp().  */
3899   }
3900 
3901   /* Both values must be blobs.  Compare using memcmp().  */
3902   return sqlite3BlobCompare(pMem1, pMem2);
3903 }
3904 
3905 
3906 /*
3907 ** The first argument passed to this function is a serial-type that
3908 ** corresponds to an integer - all values between 1 and 9 inclusive
3909 ** except 7. The second points to a buffer containing an integer value
3910 ** serialized according to serial_type. This function deserializes
3911 ** and returns the value.
3912 */
3913 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
3914   u32 y;
3915   assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
3916   switch( serial_type ){
3917     case 0:
3918     case 1:
3919       testcase( aKey[0]&0x80 );
3920       return ONE_BYTE_INT(aKey);
3921     case 2:
3922       testcase( aKey[0]&0x80 );
3923       return TWO_BYTE_INT(aKey);
3924     case 3:
3925       testcase( aKey[0]&0x80 );
3926       return THREE_BYTE_INT(aKey);
3927     case 4: {
3928       testcase( aKey[0]&0x80 );
3929       y = FOUR_BYTE_UINT(aKey);
3930       return (i64)*(int*)&y;
3931     }
3932     case 5: {
3933       testcase( aKey[0]&0x80 );
3934       return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
3935     }
3936     case 6: {
3937       u64 x = FOUR_BYTE_UINT(aKey);
3938       testcase( aKey[0]&0x80 );
3939       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
3940       return (i64)*(i64*)&x;
3941     }
3942   }
3943 
3944   return (serial_type - 8);
3945 }
3946 
3947 /*
3948 ** This function compares the two table rows or index records
3949 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
3950 ** or positive integer if key1 is less than, equal to or
3951 ** greater than key2.  The {nKey1, pKey1} key must be a blob
3952 ** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
3953 ** key must be a parsed key such as obtained from
3954 ** sqlite3VdbeParseRecord.
3955 **
3956 ** If argument bSkip is non-zero, it is assumed that the caller has already
3957 ** determined that the first fields of the keys are equal.
3958 **
3959 ** Key1 and Key2 do not have to contain the same number of fields. If all
3960 ** fields that appear in both keys are equal, then pPKey2->default_rc is
3961 ** returned.
3962 **
3963 ** If database corruption is discovered, set pPKey2->errCode to
3964 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
3965 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
3966 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
3967 */
3968 int sqlite3VdbeRecordCompareWithSkip(
3969   int nKey1, const void *pKey1,   /* Left key */
3970   UnpackedRecord *pPKey2,         /* Right key */
3971   int bSkip                       /* If true, skip the first field */
3972 ){
3973   u32 d1;                         /* Offset into aKey[] of next data element */
3974   int i;                          /* Index of next field to compare */
3975   u32 szHdr1;                     /* Size of record header in bytes */
3976   u32 idx1;                       /* Offset of first type in header */
3977   int rc = 0;                     /* Return value */
3978   Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
3979   KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
3980   const unsigned char *aKey1 = (const unsigned char *)pKey1;
3981   Mem mem1;
3982 
3983   /* If bSkip is true, then the caller has already determined that the first
3984   ** two elements in the keys are equal. Fix the various stack variables so
3985   ** that this routine begins comparing at the second field. */
3986   if( bSkip ){
3987     u32 s1;
3988     idx1 = 1 + getVarint32(&aKey1[1], s1);
3989     szHdr1 = aKey1[0];
3990     d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
3991     i = 1;
3992     pRhs++;
3993   }else{
3994     idx1 = getVarint32(aKey1, szHdr1);
3995     d1 = szHdr1;
3996     if( d1>(unsigned)nKey1 ){
3997       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
3998       return 0;  /* Corruption */
3999     }
4000     i = 0;
4001   }
4002 
4003   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
4004   assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
4005        || CORRUPT_DB );
4006   assert( pPKey2->pKeyInfo->aSortOrder!=0 );
4007   assert( pPKey2->pKeyInfo->nField>0 );
4008   assert( idx1<=szHdr1 || CORRUPT_DB );
4009   do{
4010     u32 serial_type;
4011 
4012     /* RHS is an integer */
4013     if( pRhs->flags & MEM_Int ){
4014       serial_type = aKey1[idx1];
4015       testcase( serial_type==12 );
4016       if( serial_type>=10 ){
4017         rc = +1;
4018       }else if( serial_type==0 ){
4019         rc = -1;
4020       }else if( serial_type==7 ){
4021         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
4022         rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
4023       }else{
4024         i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
4025         i64 rhs = pRhs->u.i;
4026         if( lhs<rhs ){
4027           rc = -1;
4028         }else if( lhs>rhs ){
4029           rc = +1;
4030         }
4031       }
4032     }
4033 
4034     /* RHS is real */
4035     else if( pRhs->flags & MEM_Real ){
4036       serial_type = aKey1[idx1];
4037       if( serial_type>=10 ){
4038         /* Serial types 12 or greater are strings and blobs (greater than
4039         ** numbers). Types 10 and 11 are currently "reserved for future
4040         ** use", so it doesn't really matter what the results of comparing
4041         ** them to numberic values are.  */
4042         rc = +1;
4043       }else if( serial_type==0 ){
4044         rc = -1;
4045       }else{
4046         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
4047         if( serial_type==7 ){
4048           if( mem1.u.r<pRhs->u.r ){
4049             rc = -1;
4050           }else if( mem1.u.r>pRhs->u.r ){
4051             rc = +1;
4052           }
4053         }else{
4054           rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
4055         }
4056       }
4057     }
4058 
4059     /* RHS is a string */
4060     else if( pRhs->flags & MEM_Str ){
4061       getVarint32(&aKey1[idx1], serial_type);
4062       testcase( serial_type==12 );
4063       if( serial_type<12 ){
4064         rc = -1;
4065       }else if( !(serial_type & 0x01) ){
4066         rc = +1;
4067       }else{
4068         mem1.n = (serial_type - 12) / 2;
4069         testcase( (d1+mem1.n)==(unsigned)nKey1 );
4070         testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
4071         if( (d1+mem1.n) > (unsigned)nKey1 ){
4072           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4073           return 0;                /* Corruption */
4074         }else if( pKeyInfo->aColl[i] ){
4075           mem1.enc = pKeyInfo->enc;
4076           mem1.db = pKeyInfo->db;
4077           mem1.flags = MEM_Str;
4078           mem1.z = (char*)&aKey1[d1];
4079           rc = vdbeCompareMemString(
4080               &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
4081           );
4082         }else{
4083           int nCmp = MIN(mem1.n, pRhs->n);
4084           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
4085           if( rc==0 ) rc = mem1.n - pRhs->n;
4086         }
4087       }
4088     }
4089 
4090     /* RHS is a blob */
4091     else if( pRhs->flags & MEM_Blob ){
4092       assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
4093       getVarint32(&aKey1[idx1], serial_type);
4094       testcase( serial_type==12 );
4095       if( serial_type<12 || (serial_type & 0x01) ){
4096         rc = -1;
4097       }else{
4098         int nStr = (serial_type - 12) / 2;
4099         testcase( (d1+nStr)==(unsigned)nKey1 );
4100         testcase( (d1+nStr+1)==(unsigned)nKey1 );
4101         if( (d1+nStr) > (unsigned)nKey1 ){
4102           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4103           return 0;                /* Corruption */
4104         }else if( pRhs->flags & MEM_Zero ){
4105           if( !isAllZero((const char*)&aKey1[d1],nStr) ){
4106             rc = 1;
4107           }else{
4108             rc = nStr - pRhs->u.nZero;
4109           }
4110         }else{
4111           int nCmp = MIN(nStr, pRhs->n);
4112           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
4113           if( rc==0 ) rc = nStr - pRhs->n;
4114         }
4115       }
4116     }
4117 
4118     /* RHS is null */
4119     else{
4120       serial_type = aKey1[idx1];
4121       rc = (serial_type!=0);
4122     }
4123 
4124     if( rc!=0 ){
4125       if( pKeyInfo->aSortOrder[i] ){
4126         rc = -rc;
4127       }
4128       assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
4129       assert( mem1.szMalloc==0 );  /* See comment below */
4130       return rc;
4131     }
4132 
4133     i++;
4134     pRhs++;
4135     d1 += sqlite3VdbeSerialTypeLen(serial_type);
4136     idx1 += sqlite3VarintLen(serial_type);
4137   }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
4138 
4139   /* No memory allocation is ever used on mem1.  Prove this using
4140   ** the following assert().  If the assert() fails, it indicates a
4141   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
4142   assert( mem1.szMalloc==0 );
4143 
4144   /* rc==0 here means that one or both of the keys ran out of fields and
4145   ** all the fields up to that point were equal. Return the default_rc
4146   ** value.  */
4147   assert( CORRUPT_DB
4148        || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
4149        || pKeyInfo->db->mallocFailed
4150   );
4151   pPKey2->eqSeen = 1;
4152   return pPKey2->default_rc;
4153 }
4154 int sqlite3VdbeRecordCompare(
4155   int nKey1, const void *pKey1,   /* Left key */
4156   UnpackedRecord *pPKey2          /* Right key */
4157 ){
4158   return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
4159 }
4160 
4161 
4162 /*
4163 ** This function is an optimized version of sqlite3VdbeRecordCompare()
4164 ** that (a) the first field of pPKey2 is an integer, and (b) the
4165 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
4166 ** byte (i.e. is less than 128).
4167 **
4168 ** To avoid concerns about buffer overreads, this routine is only used
4169 ** on schemas where the maximum valid header size is 63 bytes or less.
4170 */
4171 static int vdbeRecordCompareInt(
4172   int nKey1, const void *pKey1, /* Left key */
4173   UnpackedRecord *pPKey2        /* Right key */
4174 ){
4175   const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
4176   int serial_type = ((const u8*)pKey1)[1];
4177   int res;
4178   u32 y;
4179   u64 x;
4180   i64 v;
4181   i64 lhs;
4182 
4183   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
4184   assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
4185   switch( serial_type ){
4186     case 1: { /* 1-byte signed integer */
4187       lhs = ONE_BYTE_INT(aKey);
4188       testcase( lhs<0 );
4189       break;
4190     }
4191     case 2: { /* 2-byte signed integer */
4192       lhs = TWO_BYTE_INT(aKey);
4193       testcase( lhs<0 );
4194       break;
4195     }
4196     case 3: { /* 3-byte signed integer */
4197       lhs = THREE_BYTE_INT(aKey);
4198       testcase( lhs<0 );
4199       break;
4200     }
4201     case 4: { /* 4-byte signed integer */
4202       y = FOUR_BYTE_UINT(aKey);
4203       lhs = (i64)*(int*)&y;
4204       testcase( lhs<0 );
4205       break;
4206     }
4207     case 5: { /* 6-byte signed integer */
4208       lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
4209       testcase( lhs<0 );
4210       break;
4211     }
4212     case 6: { /* 8-byte signed integer */
4213       x = FOUR_BYTE_UINT(aKey);
4214       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
4215       lhs = *(i64*)&x;
4216       testcase( lhs<0 );
4217       break;
4218     }
4219     case 8:
4220       lhs = 0;
4221       break;
4222     case 9:
4223       lhs = 1;
4224       break;
4225 
4226     /* This case could be removed without changing the results of running
4227     ** this code. Including it causes gcc to generate a faster switch
4228     ** statement (since the range of switch targets now starts at zero and
4229     ** is contiguous) but does not cause any duplicate code to be generated
4230     ** (as gcc is clever enough to combine the two like cases). Other
4231     ** compilers might be similar.  */
4232     case 0: case 7:
4233       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
4234 
4235     default:
4236       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
4237   }
4238 
4239   v = pPKey2->aMem[0].u.i;
4240   if( v>lhs ){
4241     res = pPKey2->r1;
4242   }else if( v<lhs ){
4243     res = pPKey2->r2;
4244   }else if( pPKey2->nField>1 ){
4245     /* The first fields of the two keys are equal. Compare the trailing
4246     ** fields.  */
4247     res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
4248   }else{
4249     /* The first fields of the two keys are equal and there are no trailing
4250     ** fields. Return pPKey2->default_rc in this case. */
4251     res = pPKey2->default_rc;
4252     pPKey2->eqSeen = 1;
4253   }
4254 
4255   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
4256   return res;
4257 }
4258 
4259 /*
4260 ** This function is an optimized version of sqlite3VdbeRecordCompare()
4261 ** that (a) the first field of pPKey2 is a string, that (b) the first field
4262 ** uses the collation sequence BINARY and (c) that the size-of-header varint
4263 ** at the start of (pKey1/nKey1) fits in a single byte.
4264 */
4265 static int vdbeRecordCompareString(
4266   int nKey1, const void *pKey1, /* Left key */
4267   UnpackedRecord *pPKey2        /* Right key */
4268 ){
4269   const u8 *aKey1 = (const u8*)pKey1;
4270   int serial_type;
4271   int res;
4272 
4273   assert( pPKey2->aMem[0].flags & MEM_Str );
4274   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
4275   getVarint32(&aKey1[1], serial_type);
4276   if( serial_type<12 ){
4277     res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
4278   }else if( !(serial_type & 0x01) ){
4279     res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
4280   }else{
4281     int nCmp;
4282     int nStr;
4283     int szHdr = aKey1[0];
4284 
4285     nStr = (serial_type-12) / 2;
4286     if( (szHdr + nStr) > nKey1 ){
4287       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4288       return 0;    /* Corruption */
4289     }
4290     nCmp = MIN( pPKey2->aMem[0].n, nStr );
4291     res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
4292 
4293     if( res==0 ){
4294       res = nStr - pPKey2->aMem[0].n;
4295       if( res==0 ){
4296         if( pPKey2->nField>1 ){
4297           res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
4298         }else{
4299           res = pPKey2->default_rc;
4300           pPKey2->eqSeen = 1;
4301         }
4302       }else if( res>0 ){
4303         res = pPKey2->r2;
4304       }else{
4305         res = pPKey2->r1;
4306       }
4307     }else if( res>0 ){
4308       res = pPKey2->r2;
4309     }else{
4310       res = pPKey2->r1;
4311     }
4312   }
4313 
4314   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
4315        || CORRUPT_DB
4316        || pPKey2->pKeyInfo->db->mallocFailed
4317   );
4318   return res;
4319 }
4320 
4321 /*
4322 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
4323 ** suitable for comparing serialized records to the unpacked record passed
4324 ** as the only argument.
4325 */
4326 RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
4327   /* varintRecordCompareInt() and varintRecordCompareString() both assume
4328   ** that the size-of-header varint that occurs at the start of each record
4329   ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
4330   ** also assumes that it is safe to overread a buffer by at least the
4331   ** maximum possible legal header size plus 8 bytes. Because there is
4332   ** guaranteed to be at least 74 (but not 136) bytes of padding following each
4333   ** buffer passed to varintRecordCompareInt() this makes it convenient to
4334   ** limit the size of the header to 64 bytes in cases where the first field
4335   ** is an integer.
4336   **
4337   ** The easiest way to enforce this limit is to consider only records with
4338   ** 13 fields or less. If the first field is an integer, the maximum legal
4339   ** header size is (12*5 + 1 + 1) bytes.  */
4340   if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
4341     int flags = p->aMem[0].flags;
4342     if( p->pKeyInfo->aSortOrder[0] ){
4343       p->r1 = 1;
4344       p->r2 = -1;
4345     }else{
4346       p->r1 = -1;
4347       p->r2 = 1;
4348     }
4349     if( (flags & MEM_Int) ){
4350       return vdbeRecordCompareInt;
4351     }
4352     testcase( flags & MEM_Real );
4353     testcase( flags & MEM_Null );
4354     testcase( flags & MEM_Blob );
4355     if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
4356       assert( flags & MEM_Str );
4357       return vdbeRecordCompareString;
4358     }
4359   }
4360 
4361   return sqlite3VdbeRecordCompare;
4362 }
4363 
4364 /*
4365 ** pCur points at an index entry created using the OP_MakeRecord opcode.
4366 ** Read the rowid (the last field in the record) and store it in *rowid.
4367 ** Return SQLITE_OK if everything works, or an error code otherwise.
4368 **
4369 ** pCur might be pointing to text obtained from a corrupt database file.
4370 ** So the content cannot be trusted.  Do appropriate checks on the content.
4371 */
4372 int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
4373   i64 nCellKey = 0;
4374   int rc;
4375   u32 szHdr;        /* Size of the header */
4376   u32 typeRowid;    /* Serial type of the rowid */
4377   u32 lenRowid;     /* Size of the rowid */
4378   Mem m, v;
4379 
4380   /* Get the size of the index entry.  Only indices entries of less
4381   ** than 2GiB are support - anything large must be database corruption.
4382   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
4383   ** this code can safely assume that nCellKey is 32-bits
4384   */
4385   assert( sqlite3BtreeCursorIsValid(pCur) );
4386   nCellKey = sqlite3BtreePayloadSize(pCur);
4387   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
4388 
4389   /* Read in the complete content of the index entry */
4390   sqlite3VdbeMemInit(&m, db, 0);
4391   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
4392   if( rc ){
4393     return rc;
4394   }
4395 
4396   /* The index entry must begin with a header size */
4397   (void)getVarint32((u8*)m.z, szHdr);
4398   testcase( szHdr==3 );
4399   testcase( szHdr==m.n );
4400   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
4401     goto idx_rowid_corruption;
4402   }
4403 
4404   /* The last field of the index should be an integer - the ROWID.
4405   ** Verify that the last entry really is an integer. */
4406   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
4407   testcase( typeRowid==1 );
4408   testcase( typeRowid==2 );
4409   testcase( typeRowid==3 );
4410   testcase( typeRowid==4 );
4411   testcase( typeRowid==5 );
4412   testcase( typeRowid==6 );
4413   testcase( typeRowid==8 );
4414   testcase( typeRowid==9 );
4415   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
4416     goto idx_rowid_corruption;
4417   }
4418   lenRowid = sqlite3SmallTypeSizes[typeRowid];
4419   testcase( (u32)m.n==szHdr+lenRowid );
4420   if( unlikely((u32)m.n<szHdr+lenRowid) ){
4421     goto idx_rowid_corruption;
4422   }
4423 
4424   /* Fetch the integer off the end of the index record */
4425   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
4426   *rowid = v.u.i;
4427   sqlite3VdbeMemRelease(&m);
4428   return SQLITE_OK;
4429 
4430   /* Jump here if database corruption is detected after m has been
4431   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
4432 idx_rowid_corruption:
4433   testcase( m.szMalloc!=0 );
4434   sqlite3VdbeMemRelease(&m);
4435   return SQLITE_CORRUPT_BKPT;
4436 }
4437 
4438 /*
4439 ** Compare the key of the index entry that cursor pC is pointing to against
4440 ** the key string in pUnpacked.  Write into *pRes a number
4441 ** that is negative, zero, or positive if pC is less than, equal to,
4442 ** or greater than pUnpacked.  Return SQLITE_OK on success.
4443 **
4444 ** pUnpacked is either created without a rowid or is truncated so that it
4445 ** omits the rowid at the end.  The rowid at the end of the index entry
4446 ** is ignored as well.  Hence, this routine only compares the prefixes
4447 ** of the keys prior to the final rowid, not the entire key.
4448 */
4449 int sqlite3VdbeIdxKeyCompare(
4450   sqlite3 *db,                     /* Database connection */
4451   VdbeCursor *pC,                  /* The cursor to compare against */
4452   UnpackedRecord *pUnpacked,       /* Unpacked version of key */
4453   int *res                         /* Write the comparison result here */
4454 ){
4455   i64 nCellKey = 0;
4456   int rc;
4457   BtCursor *pCur;
4458   Mem m;
4459 
4460   assert( pC->eCurType==CURTYPE_BTREE );
4461   pCur = pC->uc.pCursor;
4462   assert( sqlite3BtreeCursorIsValid(pCur) );
4463   nCellKey = sqlite3BtreePayloadSize(pCur);
4464   /* nCellKey will always be between 0 and 0xffffffff because of the way
4465   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
4466   if( nCellKey<=0 || nCellKey>0x7fffffff ){
4467     *res = 0;
4468     return SQLITE_CORRUPT_BKPT;
4469   }
4470   sqlite3VdbeMemInit(&m, db, 0);
4471   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
4472   if( rc ){
4473     return rc;
4474   }
4475   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
4476   sqlite3VdbeMemRelease(&m);
4477   return SQLITE_OK;
4478 }
4479 
4480 /*
4481 ** This routine sets the value to be returned by subsequent calls to
4482 ** sqlite3_changes() on the database handle 'db'.
4483 */
4484 void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
4485   assert( sqlite3_mutex_held(db->mutex) );
4486   db->nChange = nChange;
4487   db->nTotalChange += nChange;
4488 }
4489 
4490 /*
4491 ** Set a flag in the vdbe to update the change counter when it is finalised
4492 ** or reset.
4493 */
4494 void sqlite3VdbeCountChanges(Vdbe *v){
4495   v->changeCntOn = 1;
4496 }
4497 
4498 /*
4499 ** Mark every prepared statement associated with a database connection
4500 ** as expired.
4501 **
4502 ** An expired statement means that recompilation of the statement is
4503 ** recommend.  Statements expire when things happen that make their
4504 ** programs obsolete.  Removing user-defined functions or collating
4505 ** sequences, or changing an authorization function are the types of
4506 ** things that make prepared statements obsolete.
4507 */
4508 void sqlite3ExpirePreparedStatements(sqlite3 *db){
4509   Vdbe *p;
4510   for(p = db->pVdbe; p; p=p->pNext){
4511     p->expired = 1;
4512   }
4513 }
4514 
4515 /*
4516 ** Return the database associated with the Vdbe.
4517 */
4518 sqlite3 *sqlite3VdbeDb(Vdbe *v){
4519   return v->db;
4520 }
4521 
4522 /*
4523 ** Return a pointer to an sqlite3_value structure containing the value bound
4524 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
4525 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
4526 ** constants) to the value before returning it.
4527 **
4528 ** The returned value must be freed by the caller using sqlite3ValueFree().
4529 */
4530 sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
4531   assert( iVar>0 );
4532   if( v ){
4533     Mem *pMem = &v->aVar[iVar-1];
4534     if( 0==(pMem->flags & MEM_Null) ){
4535       sqlite3_value *pRet = sqlite3ValueNew(v->db);
4536       if( pRet ){
4537         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
4538         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
4539       }
4540       return pRet;
4541     }
4542   }
4543   return 0;
4544 }
4545 
4546 /*
4547 ** Configure SQL variable iVar so that binding a new value to it signals
4548 ** to sqlite3_reoptimize() that re-preparing the statement may result
4549 ** in a better query plan.
4550 */
4551 void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
4552   assert( iVar>0 );
4553   if( iVar>32 ){
4554     v->expmask = 0xffffffff;
4555   }else{
4556     v->expmask |= ((u32)1 << (iVar-1));
4557   }
4558 }
4559 
4560 #ifndef SQLITE_OMIT_VIRTUALTABLE
4561 /*
4562 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
4563 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
4564 ** in memory obtained from sqlite3DbMalloc).
4565 */
4566 void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
4567   if( pVtab->zErrMsg ){
4568     sqlite3 *db = p->db;
4569     sqlite3DbFree(db, p->zErrMsg);
4570     p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
4571     sqlite3_free(pVtab->zErrMsg);
4572     pVtab->zErrMsg = 0;
4573   }
4574 }
4575 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4576 
4577 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4578 
4579 /*
4580 ** If the second argument is not NULL, release any allocations associated
4581 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
4582 ** structure itself, using sqlite3DbFree().
4583 **
4584 ** This function is used to free UnpackedRecord structures allocated by
4585 ** the vdbeUnpackRecord() function found in vdbeapi.c.
4586 */
4587 static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
4588   if( p ){
4589     int i;
4590     for(i=0; i<nField; i++){
4591       Mem *pMem = &p->aMem[i];
4592       if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
4593     }
4594     sqlite3DbFree(db, p);
4595   }
4596 }
4597 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
4598 
4599 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4600 /*
4601 ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
4602 ** then cursor passed as the second argument should point to the row about
4603 ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
4604 ** the required value will be read from the row the cursor points to.
4605 */
4606 void sqlite3VdbePreUpdateHook(
4607   Vdbe *v,                        /* Vdbe pre-update hook is invoked by */
4608   VdbeCursor *pCsr,               /* Cursor to grab old.* values from */
4609   int op,                         /* SQLITE_INSERT, UPDATE or DELETE */
4610   const char *zDb,                /* Database name */
4611   Table *pTab,                    /* Modified table */
4612   i64 iKey1,                      /* Initial key value */
4613   int iReg                        /* Register for new.* record */
4614 ){
4615   sqlite3 *db = v->db;
4616   i64 iKey2;
4617   PreUpdate preupdate;
4618   const char *zTbl = pTab->zName;
4619   static const u8 fakeSortOrder = 0;
4620 
4621   assert( db->pPreUpdate==0 );
4622   memset(&preupdate, 0, sizeof(PreUpdate));
4623   if( op==SQLITE_UPDATE ){
4624     iKey2 = v->aMem[iReg].u.i;
4625   }else{
4626     iKey2 = iKey1;
4627   }
4628 
4629   assert( pCsr->nField==pTab->nCol
4630        || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
4631   );
4632 
4633   preupdate.v = v;
4634   preupdate.pCsr = pCsr;
4635   preupdate.op = op;
4636   preupdate.iNewReg = iReg;
4637   preupdate.keyinfo.db = db;
4638   preupdate.keyinfo.enc = ENC(db);
4639   preupdate.keyinfo.nField = pTab->nCol;
4640   preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
4641   preupdate.iKey1 = iKey1;
4642   preupdate.iKey2 = iKey2;
4643   preupdate.pTab = pTab;
4644 
4645   db->pPreUpdate = &preupdate;
4646   db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
4647   db->pPreUpdate = 0;
4648   sqlite3DbFree(db, preupdate.aRecord);
4649   vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pUnpacked);
4650   vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pNewUnpacked);
4651   if( preupdate.aNew ){
4652     int i;
4653     for(i=0; i<pCsr->nField; i++){
4654       sqlite3VdbeMemRelease(&preupdate.aNew[i]);
4655     }
4656     sqlite3DbFree(db, preupdate.aNew);
4657   }
4658 }
4659 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
4660