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