xref: /sqlite-3.40.0/src/vdbeaux.c (revision 545311ee)
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.)  Prior
14 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
15 ** But that file was getting too big so this subroutines were split out.
16 */
17 #include "sqliteInt.h"
18 #include "os.h"
19 #include <ctype.h>
20 #include "vdbeInt.h"
21 
22 
23 /*
24 ** When debugging the code generator in a symbolic debugger, one can
25 ** set the sqlite3_vdbe_addop_trace to 1 and all opcodes will be printed
26 ** as they are added to the instruction stream.
27 */
28 #ifdef SQLITE_DEBUG
29 int sqlite3_vdbe_addop_trace = 0;
30 #endif
31 
32 
33 /*
34 ** Create a new virtual database engine.
35 */
36 Vdbe *sqlite3VdbeCreate(sqlite3 *db){
37   Vdbe *p;
38   p = sqliteMalloc( sizeof(Vdbe) );
39   if( p==0 ) return 0;
40   p->db = db;
41   if( db->pVdbe ){
42     db->pVdbe->pPrev = p;
43   }
44   p->pNext = db->pVdbe;
45   p->pPrev = 0;
46   db->pVdbe = p;
47   p->magic = VDBE_MAGIC_INIT;
48   return p;
49 }
50 
51 /*
52 ** Remember the SQL string for a prepared statement.
53 */
54 void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
55   if( p==0 ) return;
56   assert( p->zSql==0 );
57   p->zSql = sqlite3StrNDup(z, n);
58 }
59 
60 /*
61 ** Return the SQL associated with a prepared statement
62 */
63 const char *sqlite3VdbeGetSql(Vdbe *p){
64   return p->zSql;
65 }
66 
67 /*
68 ** Swap the set of Opcodes between to Vdbe structures.  No
69 ** other parts of either Vdbe structure are changed.
70 */
71 void sqlite3VdbeSwapOps(Vdbe *pA, Vdbe *pB){
72   Op *aOp;
73   int nOp;
74 
75   aOp = pA->aOp;
76   nOp = pA->nOp;
77   pA->aOp = pB->aOp;
78   pA->nOp = pB->nOp;
79   pB->aOp = aOp;
80   pB->nOp = nOp;
81 }
82 
83 /*
84 ** Turn tracing on or off
85 */
86 void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
87   p->trace = trace;
88 }
89 
90 /*
91 ** Resize the Vdbe.aOp array so that it contains at least N
92 ** elements. If the Vdbe is in VDBE_MAGIC_RUN state, then
93 ** the Vdbe.aOp array will be sized to contain exactly N
94 ** elements. Vdbe.nOpAlloc is set to reflect the new size of
95 ** the array.
96 **
97 ** If an out-of-memory error occurs while resizing the array,
98 ** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
99 ** any opcodes already allocated can be correctly deallocated
100 ** along with the rest of the Vdbe).
101 */
102 static void resizeOpArray(Vdbe *p, int N){
103   int runMode = p->magic==VDBE_MAGIC_RUN;
104   if( runMode || p->nOpAlloc<N ){
105     VdbeOp *pNew;
106     int nNew = N + 100*(!runMode);
107     int oldSize = p->nOpAlloc;
108     pNew = sqliteRealloc(p->aOp, nNew*sizeof(Op));
109     if( pNew ){
110       p->nOpAlloc = nNew;
111       p->aOp = pNew;
112       if( nNew>oldSize ){
113         memset(&p->aOp[oldSize], 0, (nNew-oldSize)*sizeof(Op));
114       }
115     }
116   }
117 }
118 
119 /*
120 ** Add a new instruction to the list of instructions current in the
121 ** VDBE.  Return the address of the new instruction.
122 **
123 ** Parameters:
124 **
125 **    p               Pointer to the VDBE
126 **
127 **    op              The opcode for this instruction
128 **
129 **    p1, p2          First two of the three possible operands.
130 **
131 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
132 ** the sqlite3VdbeChangeP3() function to change the value of the P3
133 ** operand.
134 */
135 int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){
136   int i;
137   VdbeOp *pOp;
138 
139   i = p->nOp;
140   p->nOp++;
141   assert( p->magic==VDBE_MAGIC_INIT );
142   if( p->nOpAlloc<=i ){
143     resizeOpArray(p, i+1);
144     if( sqlite3MallocFailed() ){
145       return 0;
146     }
147   }
148   pOp = &p->aOp[i];
149   pOp->opcode = op;
150   pOp->p1 = p1;
151   pOp->p2 = p2;
152   pOp->p3 = 0;
153   pOp->p3type = P3_NOTUSED;
154   p->expired = 0;
155 #ifdef SQLITE_DEBUG
156   if( sqlite3_vdbe_addop_trace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
157 #endif
158   return i;
159 }
160 
161 /*
162 ** Add an opcode that includes the p3 value.
163 */
164 int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){
165   int addr = sqlite3VdbeAddOp(p, op, p1, p2);
166   sqlite3VdbeChangeP3(p, addr, zP3, p3type);
167   return addr;
168 }
169 
170 /*
171 ** Create a new symbolic label for an instruction that has yet to be
172 ** coded.  The symbolic label is really just a negative number.  The
173 ** label can be used as the P2 value of an operation.  Later, when
174 ** the label is resolved to a specific address, the VDBE will scan
175 ** through its operation list and change all values of P2 which match
176 ** the label into the resolved address.
177 **
178 ** The VDBE knows that a P2 value is a label because labels are
179 ** always negative and P2 values are suppose to be non-negative.
180 ** Hence, a negative P2 value is a label that has yet to be resolved.
181 **
182 ** Zero is returned if a malloc() fails.
183 */
184 int sqlite3VdbeMakeLabel(Vdbe *p){
185   int i;
186   i = p->nLabel++;
187   assert( p->magic==VDBE_MAGIC_INIT );
188   if( i>=p->nLabelAlloc ){
189     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
190     sqliteReallocOrFree((void**)&p->aLabel,
191                           p->nLabelAlloc*sizeof(p->aLabel[0]));
192   }
193   if( p->aLabel ){
194     p->aLabel[i] = -1;
195   }
196   return -1-i;
197 }
198 
199 /*
200 ** Resolve label "x" to be the address of the next instruction to
201 ** be inserted.  The parameter "x" must have been obtained from
202 ** a prior call to sqlite3VdbeMakeLabel().
203 */
204 void sqlite3VdbeResolveLabel(Vdbe *p, int x){
205   int j = -1-x;
206   assert( p->magic==VDBE_MAGIC_INIT );
207   assert( j>=0 && j<p->nLabel );
208   if( p->aLabel ){
209     p->aLabel[j] = p->nOp;
210   }
211 }
212 
213 /*
214 ** Return non-zero if opcode 'op' is guarenteed not to push more values
215 ** onto the VDBE stack than it pops off.
216 */
217 static int opcodeNoPush(u8 op){
218   /* The 10 NOPUSH_MASK_n constants are defined in the automatically
219   ** generated header file opcodes.h. Each is a 16-bit bitmask, one
220   ** bit corresponding to each opcode implemented by the virtual
221   ** machine in vdbe.c. The bit is true if the word "no-push" appears
222   ** in a comment on the same line as the "case OP_XXX:" in
223   ** sqlite3VdbeExec() in vdbe.c.
224   **
225   ** If the bit is true, then the corresponding opcode is guarenteed not
226   ** to grow the stack when it is executed. Otherwise, it may grow the
227   ** stack by at most one entry.
228   **
229   ** NOPUSH_MASK_0 corresponds to opcodes 0 to 15. NOPUSH_MASK_1 contains
230   ** one bit for opcodes 16 to 31, and so on.
231   **
232   ** 16-bit bitmasks (rather than 32-bit) are specified in opcodes.h
233   ** because the file is generated by an awk program. Awk manipulates
234   ** all numbers as floating-point and we don't want to risk a rounding
235   ** error if someone builds with an awk that uses (for example) 32-bit
236   ** IEEE floats.
237   */
238   static const u32 masks[5] = {
239     NOPUSH_MASK_0 + (((unsigned)NOPUSH_MASK_1)<<16),
240     NOPUSH_MASK_2 + (((unsigned)NOPUSH_MASK_3)<<16),
241     NOPUSH_MASK_4 + (((unsigned)NOPUSH_MASK_5)<<16),
242     NOPUSH_MASK_6 + (((unsigned)NOPUSH_MASK_7)<<16),
243     NOPUSH_MASK_8 + (((unsigned)NOPUSH_MASK_9)<<16)
244   };
245   assert( op<32*5 );
246   return (masks[op>>5] & (1<<(op&0x1F)));
247 }
248 
249 #ifndef NDEBUG
250 int sqlite3VdbeOpcodeNoPush(u8 op){
251   return opcodeNoPush(op);
252 }
253 #endif
254 
255 /*
256 ** Loop through the program looking for P2 values that are negative.
257 ** Each such value is a label.  Resolve the label by setting the P2
258 ** value to its correct non-zero value.
259 **
260 ** This routine is called once after all opcodes have been inserted.
261 **
262 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
263 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
264 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
265 **
266 ** The integer *pMaxStack is set to the maximum number of vdbe stack
267 ** entries that static analysis reveals this program might need.
268 **
269 ** This routine also does the following optimization:  It scans for
270 ** Halt instructions where P1==SQLITE_CONSTRAINT or P2==OE_Abort or for
271 ** IdxInsert instructions where P2!=0.  If no such instruction is
272 ** found, then every Statement instruction is changed to a Noop.  In
273 ** this way, we avoid creating the statement journal file unnecessarily.
274 */
275 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs, int *pMaxStack){
276   int i;
277   int nMaxArgs = 0;
278   int nMaxStack = p->nOp;
279   Op *pOp;
280   int *aLabel = p->aLabel;
281   int doesStatementRollback = 0;
282   int hasStatementBegin = 0;
283   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
284     u8 opcode = pOp->opcode;
285 
286     if( opcode==OP_Function || opcode==OP_AggStep
287 #ifndef SQLITE_OMIT_VIRTUALTABLE
288         || opcode==OP_VUpdate
289 #endif
290     ){
291       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
292     }else if( opcode==OP_Halt ){
293       if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
294         doesStatementRollback = 1;
295       }
296     }else if( opcode==OP_Statement ){
297       hasStatementBegin = 1;
298     }else if( opcode==OP_VFilter ){
299       int n;
300       assert( p->nOp - i >= 3 );
301       assert( pOp[-2].opcode==OP_Integer );
302       n = pOp[-2].p1;
303       if( n>nMaxArgs ) nMaxArgs = n;
304     }
305     if( opcodeNoPush(opcode) ){
306       nMaxStack--;
307     }
308 
309     if( pOp->p2>=0 ) continue;
310     assert( -1-pOp->p2<p->nLabel );
311     pOp->p2 = aLabel[-1-pOp->p2];
312   }
313   sqliteFree(p->aLabel);
314   p->aLabel = 0;
315 
316   *pMaxFuncArgs = nMaxArgs;
317   *pMaxStack = nMaxStack;
318 
319   /* If we never rollback a statement transaction, then statement
320   ** transactions are not needed.  So change every OP_Statement
321   ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
322   ** which can be expensive on some platforms.
323   */
324   if( hasStatementBegin && !doesStatementRollback ){
325     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
326       if( pOp->opcode==OP_Statement ){
327         pOp->opcode = OP_Noop;
328       }
329     }
330   }
331 }
332 
333 /*
334 ** Return the address of the next instruction to be inserted.
335 */
336 int sqlite3VdbeCurrentAddr(Vdbe *p){
337   assert( p->magic==VDBE_MAGIC_INIT );
338   return p->nOp;
339 }
340 
341 /*
342 ** Add a whole list of operations to the operation stack.  Return the
343 ** address of the first operation added.
344 */
345 int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
346   int addr;
347   assert( p->magic==VDBE_MAGIC_INIT );
348   resizeOpArray(p, p->nOp + nOp);
349   if( sqlite3MallocFailed() ){
350     return 0;
351   }
352   addr = p->nOp;
353   if( nOp>0 ){
354     int i;
355     VdbeOpList const *pIn = aOp;
356     for(i=0; i<nOp; i++, pIn++){
357       int p2 = pIn->p2;
358       VdbeOp *pOut = &p->aOp[i+addr];
359       pOut->opcode = pIn->opcode;
360       pOut->p1 = pIn->p1;
361       pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
362       pOut->p3 = pIn->p3;
363       pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
364 #ifdef SQLITE_DEBUG
365       if( sqlite3_vdbe_addop_trace ){
366         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
367       }
368 #endif
369     }
370     p->nOp += nOp;
371   }
372   return addr;
373 }
374 
375 /*
376 ** Change the value of the P1 operand for a specific instruction.
377 ** This routine is useful when a large program is loaded from a
378 ** static array using sqlite3VdbeAddOpList but we want to make a
379 ** few minor changes to the program.
380 */
381 void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
382   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
383   if( p && addr>=0 && p->nOp>addr && p->aOp ){
384     p->aOp[addr].p1 = val;
385   }
386 }
387 
388 /*
389 ** Change the value of the P2 operand for a specific instruction.
390 ** This routine is useful for setting a jump destination.
391 */
392 void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
393   assert( val>=0 );
394   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
395   if( p && addr>=0 && p->nOp>addr && p->aOp ){
396     p->aOp[addr].p2 = val;
397   }
398 }
399 
400 /*
401 ** Change the P2 operand of instruction addr so that it points to
402 ** the address of the next instruction to be coded.
403 */
404 void sqlite3VdbeJumpHere(Vdbe *p, int addr){
405   sqlite3VdbeChangeP2(p, addr, p->nOp);
406 }
407 
408 
409 /*
410 ** If the input FuncDef structure is ephemeral, then free it.  If
411 ** the FuncDef is not ephermal, then do nothing.
412 */
413 static void freeEphemeralFunction(FuncDef *pDef){
414   if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
415     sqliteFree(pDef);
416   }
417 }
418 
419 /*
420 ** Delete a P3 value if necessary.
421 */
422 static void freeP3(int p3type, void *p3){
423   if( p3 ){
424     switch( p3type ){
425       case P3_DYNAMIC:
426       case P3_KEYINFO:
427       case P3_KEYINFO_HANDOFF: {
428         sqliteFree(p3);
429         break;
430       }
431       case P3_MPRINTF: {
432         sqlite3_free(p3);
433         break;
434       }
435       case P3_VDBEFUNC: {
436         VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
437         freeEphemeralFunction(pVdbeFunc->pFunc);
438         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
439         sqliteFree(pVdbeFunc);
440         break;
441       }
442       case P3_FUNCDEF: {
443         freeEphemeralFunction((FuncDef*)p3);
444         break;
445       }
446       case P3_MEM: {
447         sqlite3ValueFree((sqlite3_value*)p3);
448         break;
449       }
450     }
451   }
452 }
453 
454 
455 /*
456 ** Change N opcodes starting at addr to No-ops.
457 */
458 void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
459   VdbeOp *pOp = &p->aOp[addr];
460   while( N-- ){
461     freeP3(pOp->p3type, pOp->p3);
462     memset(pOp, 0, sizeof(pOp[0]));
463     pOp->opcode = OP_Noop;
464     pOp++;
465   }
466 }
467 
468 /*
469 ** Change the value of the P3 operand for a specific instruction.
470 ** This routine is useful when a large program is loaded from a
471 ** static array using sqlite3VdbeAddOpList but we want to make a
472 ** few minor changes to the program.
473 **
474 ** If n>=0 then the P3 operand is dynamic, meaning that a copy of
475 ** the string is made into memory obtained from sqliteMalloc().
476 ** A value of n==0 means copy bytes of zP3 up to and including the
477 ** first null byte.  If n>0 then copy n+1 bytes of zP3.
478 **
479 ** If n==P3_KEYINFO it means that zP3 is a pointer to a KeyInfo structure.
480 ** A copy is made of the KeyInfo structure into memory obtained from
481 ** sqliteMalloc, to be freed when the Vdbe is finalized.
482 ** n==P3_KEYINFO_HANDOFF indicates that zP3 points to a KeyInfo structure
483 ** stored in memory that the caller has obtained from sqliteMalloc. The
484 ** caller should not free the allocation, it will be freed when the Vdbe is
485 ** finalized.
486 **
487 ** Other values of n (P3_STATIC, P3_COLLSEQ etc.) indicate that zP3 points
488 ** to a string or structure that is guaranteed to exist for the lifetime of
489 ** the Vdbe. In these cases we can just copy the pointer.
490 **
491 ** If addr<0 then change P3 on the most recently inserted instruction.
492 */
493 void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
494   Op *pOp;
495   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
496   if( p==0 || p->aOp==0 || sqlite3MallocFailed() ){
497     if (n != P3_KEYINFO) {
498       freeP3(n, (void*)*(char**)&zP3);
499     }
500     return;
501   }
502   if( addr<0 || addr>=p->nOp ){
503     addr = p->nOp - 1;
504     if( addr<0 ) return;
505   }
506   pOp = &p->aOp[addr];
507   freeP3(pOp->p3type, pOp->p3);
508   pOp->p3 = 0;
509   if( zP3==0 ){
510     pOp->p3 = 0;
511     pOp->p3type = P3_NOTUSED;
512   }else if( n==P3_KEYINFO ){
513     KeyInfo *pKeyInfo;
514     int nField, nByte;
515 
516     nField = ((KeyInfo*)zP3)->nField;
517     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
518     pKeyInfo = sqliteMallocRaw( nByte );
519     pOp->p3 = (char*)pKeyInfo;
520     if( pKeyInfo ){
521       unsigned char *aSortOrder;
522       memcpy(pKeyInfo, zP3, nByte);
523       aSortOrder = pKeyInfo->aSortOrder;
524       if( aSortOrder ){
525         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
526         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
527       }
528       pOp->p3type = P3_KEYINFO;
529     }else{
530       pOp->p3type = P3_NOTUSED;
531     }
532   }else if( n==P3_KEYINFO_HANDOFF ){
533     pOp->p3 = (char*)zP3;
534     pOp->p3type = P3_KEYINFO;
535   }else if( n<0 ){
536     pOp->p3 = (char*)zP3;
537     pOp->p3type = n;
538   }else{
539     if( n==0 ) n = strlen(zP3);
540     pOp->p3 = sqliteStrNDup(zP3, n);
541     pOp->p3type = P3_DYNAMIC;
542   }
543 }
544 
545 #ifndef NDEBUG
546 /*
547 ** Replace the P3 field of the most recently coded instruction with
548 ** comment text.
549 */
550 void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
551   va_list ap;
552   assert( p->nOp>0 );
553   assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0
554           || sqlite3MallocFailed() );
555   va_start(ap, zFormat);
556   sqlite3VdbeChangeP3(p, -1, sqlite3VMPrintf(zFormat, ap), P3_DYNAMIC);
557   va_end(ap);
558 }
559 #endif
560 
561 /*
562 ** Return the opcode for a given address.
563 */
564 VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
565   assert( p->magic==VDBE_MAGIC_INIT );
566   assert( addr>=0 && addr<p->nOp );
567   return &p->aOp[addr];
568 }
569 
570 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
571      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
572 /*
573 ** Compute a string that describes the P3 parameter for an opcode.
574 ** Use zTemp for any required temporary buffer space.
575 */
576 static char *displayP3(Op *pOp, char *zTemp, int nTemp){
577   char *zP3;
578   assert( nTemp>=20 );
579   switch( pOp->p3type ){
580     case P3_KEYINFO: {
581       int i, j;
582       KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3;
583       sprintf(zTemp, "keyinfo(%d", pKeyInfo->nField);
584       i = strlen(zTemp);
585       for(j=0; j<pKeyInfo->nField; j++){
586         CollSeq *pColl = pKeyInfo->aColl[j];
587         if( pColl ){
588           int n = strlen(pColl->zName);
589           if( i+n>nTemp-6 ){
590             strcpy(&zTemp[i],",...");
591             break;
592           }
593           zTemp[i++] = ',';
594           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
595             zTemp[i++] = '-';
596           }
597           strcpy(&zTemp[i], pColl->zName);
598           i += n;
599         }else if( i+4<nTemp-6 ){
600           strcpy(&zTemp[i],",nil");
601           i += 4;
602         }
603       }
604       zTemp[i++] = ')';
605       zTemp[i] = 0;
606       assert( i<nTemp );
607       zP3 = zTemp;
608       break;
609     }
610     case P3_COLLSEQ: {
611       CollSeq *pColl = (CollSeq*)pOp->p3;
612       sprintf(zTemp, "collseq(%.20s)", pColl->zName);
613       zP3 = zTemp;
614       break;
615     }
616     case P3_FUNCDEF: {
617       FuncDef *pDef = (FuncDef*)pOp->p3;
618       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
619       zP3 = zTemp;
620       break;
621     }
622 #ifndef SQLITE_OMIT_VIRTUALTABLE
623     case P3_VTAB: {
624       sqlite3_vtab *pVtab = (sqlite3_vtab*)pOp->p3;
625       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
626       zP3 = zTemp;
627       break;
628     }
629 #endif
630     default: {
631       zP3 = pOp->p3;
632       if( zP3==0 || pOp->opcode==OP_Noop ){
633         zP3 = "";
634       }
635     }
636   }
637   assert( zP3!=0 );
638   return zP3;
639 }
640 #endif
641 
642 
643 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
644 /*
645 ** Print a single opcode.  This routine is used for debugging only.
646 */
647 void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
648   char *zP3;
649   char zPtr[50];
650   static const char *zFormat1 = "%4d %-13s %4d %4d %s\n";
651   if( pOut==0 ) pOut = stdout;
652   zP3 = displayP3(pOp, zPtr, sizeof(zPtr));
653   fprintf(pOut, zFormat1,
654       pc, sqlite3OpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3);
655   fflush(pOut);
656 }
657 #endif
658 
659 /*
660 ** Release an array of N Mem elements
661 */
662 static void releaseMemArray(Mem *p, int N){
663   if( p ){
664     while( N-->0 ){
665       sqlite3VdbeMemRelease(p++);
666     }
667   }
668 }
669 
670 #ifndef SQLITE_OMIT_EXPLAIN
671 /*
672 ** Give a listing of the program in the virtual machine.
673 **
674 ** The interface is the same as sqlite3VdbeExec().  But instead of
675 ** running the code, it invokes the callback once for each instruction.
676 ** This feature is used to implement "EXPLAIN".
677 */
678 int sqlite3VdbeList(
679   Vdbe *p                   /* The VDBE */
680 ){
681   sqlite3 *db = p->db;
682   int i;
683   int rc = SQLITE_OK;
684 
685   assert( p->explain );
686   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
687   assert( db->magic==SQLITE_MAGIC_BUSY );
688   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
689 
690   /* Even though this opcode does not put dynamic strings onto the
691   ** the stack, they may become dynamic if the user calls
692   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
693   */
694   if( p->pTos==&p->aStack[4] ){
695     releaseMemArray(p->aStack, 5);
696   }
697   p->resOnStack = 0;
698 
699   do{
700     i = p->pc++;
701   }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
702   if( i>=p->nOp ){
703     p->rc = SQLITE_OK;
704     rc = SQLITE_DONE;
705   }else if( db->u1.isInterrupted ){
706     p->rc = SQLITE_INTERRUPT;
707     rc = SQLITE_ERROR;
708     sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
709   }else{
710     Op *pOp = &p->aOp[i];
711     Mem *pMem = p->aStack;
712     pMem->flags = MEM_Int;
713     pMem->type = SQLITE_INTEGER;
714     pMem->i = i;                                /* Program counter */
715     pMem++;
716 
717     pMem->flags = MEM_Static|MEM_Str|MEM_Term;
718     pMem->z = sqlite3OpcodeNames[pOp->opcode];  /* Opcode */
719     assert( pMem->z!=0 );
720     pMem->n = strlen(pMem->z);
721     pMem->type = SQLITE_TEXT;
722     pMem->enc = SQLITE_UTF8;
723     pMem++;
724 
725     pMem->flags = MEM_Int;
726     pMem->i = pOp->p1;                          /* P1 */
727     pMem->type = SQLITE_INTEGER;
728     pMem++;
729 
730     pMem->flags = MEM_Int;
731     pMem->i = pOp->p2;                          /* P2 */
732     pMem->type = SQLITE_INTEGER;
733     pMem++;
734 
735     pMem->flags = MEM_Ephem|MEM_Str|MEM_Term;   /* P3 */
736     pMem->z = displayP3(pOp, pMem->zShort, sizeof(pMem->zShort));
737     assert( pMem->z!=0 );
738     pMem->n = strlen(pMem->z);
739     pMem->type = SQLITE_TEXT;
740     pMem->enc = SQLITE_UTF8;
741 
742     p->nResColumn = 5 - 2*(p->explain-1);
743     p->pTos = pMem;
744     p->rc = SQLITE_OK;
745     p->resOnStack = 1;
746     rc = SQLITE_ROW;
747   }
748   return rc;
749 }
750 #endif /* SQLITE_OMIT_EXPLAIN */
751 
752 /*
753 ** Print the SQL that was used to generate a VDBE program.
754 */
755 void sqlite3VdbePrintSql(Vdbe *p){
756 #ifdef SQLITE_DEBUG
757   int nOp = p->nOp;
758   VdbeOp *pOp;
759   if( nOp<1 ) return;
760   pOp = &p->aOp[nOp-1];
761   if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
762     const char *z = pOp->p3;
763     while( isspace(*(u8*)z) ) z++;
764     printf("SQL: [%s]\n", z);
765   }
766 #endif
767 }
768 
769 /*
770 ** Prepare a virtual machine for execution.  This involves things such
771 ** as allocating stack space and initializing the program counter.
772 ** After the VDBE has be prepped, it can be executed by one or more
773 ** calls to sqlite3VdbeExec().
774 **
775 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
776 ** VDBE_MAGIC_RUN.
777 */
778 void sqlite3VdbeMakeReady(
779   Vdbe *p,                       /* The VDBE */
780   int nVar,                      /* Number of '?' see in the SQL statement */
781   int nMem,                      /* Number of memory cells to allocate */
782   int nCursor,                   /* Number of cursors to allocate */
783   int isExplain                  /* True if the EXPLAIN keywords is present */
784 ){
785   int n;
786 
787   assert( p!=0 );
788   assert( p->magic==VDBE_MAGIC_INIT );
789 
790   /* There should be at least one opcode.
791   */
792   assert( p->nOp>0 );
793 
794   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
795    * is because the call to resizeOpArray() below may shrink the
796    * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN
797    * state.
798    */
799   p->magic = VDBE_MAGIC_RUN;
800 
801   /* No instruction ever pushes more than a single element onto the
802   ** stack.  And the stack never grows on successive executions of the
803   ** same loop.  So the total number of instructions is an upper bound
804   ** on the maximum stack depth required.  (Added later:)  The
805   ** resolveP2Values() call computes a tighter upper bound on the
806   ** stack size.
807   **
808   ** Allocation all the stack space we will ever need.
809   */
810   if( p->aStack==0 ){
811     int nArg;       /* Maximum number of args passed to a user function. */
812     int nStack;     /* Maximum number of stack entries required */
813     resolveP2Values(p, &nArg, &nStack);
814     resizeOpArray(p, p->nOp);
815     assert( nVar>=0 );
816     assert( nStack<p->nOp );
817     if( isExplain ){
818       nStack = 10;
819     }
820     p->aStack = sqliteMalloc(
821         nStack*sizeof(p->aStack[0])    /* aStack */
822       + nArg*sizeof(Mem*)              /* apArg */
823       + nVar*sizeof(Mem)               /* aVar */
824       + nVar*sizeof(char*)             /* azVar */
825       + nMem*sizeof(Mem)               /* aMem */
826       + nCursor*sizeof(Cursor*)        /* apCsr */
827     );
828     if( !sqlite3MallocFailed() ){
829       p->aMem = &p->aStack[nStack];
830       p->nMem = nMem;
831       p->aVar = &p->aMem[nMem];
832       p->nVar = nVar;
833       p->okVar = 0;
834       p->apArg = (Mem**)&p->aVar[nVar];
835       p->azVar = (char**)&p->apArg[nArg];
836       p->apCsr = (Cursor**)&p->azVar[nVar];
837       p->nCursor = nCursor;
838       for(n=0; n<nVar; n++){
839         p->aVar[n].flags = MEM_Null;
840       }
841     }
842   }
843   for(n=0; n<p->nMem; n++){
844     p->aMem[n].flags = MEM_Null;
845   }
846 
847 #ifdef SQLITE_DEBUG
848   if( (p->db->flags & SQLITE_VdbeListing)!=0
849     || sqlite3OsFileExists("vdbe_explain")
850   ){
851     int i;
852     printf("VDBE Program Listing:\n");
853     sqlite3VdbePrintSql(p);
854     for(i=0; i<p->nOp; i++){
855       sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
856     }
857   }
858   if( sqlite3OsFileExists("vdbe_trace") ){
859     p->trace = stdout;
860   }
861 #endif
862   p->pTos = &p->aStack[-1];
863   p->pc = -1;
864   p->rc = SQLITE_OK;
865   p->uniqueCnt = 0;
866   p->returnDepth = 0;
867   p->errorAction = OE_Abort;
868   p->popStack =  0;
869   p->explain |= isExplain;
870   p->magic = VDBE_MAGIC_RUN;
871   p->nChange = 0;
872   p->cacheCtr = 1;
873   p->minWriteFileFormat = 255;
874 #ifdef VDBE_PROFILE
875   {
876     int i;
877     for(i=0; i<p->nOp; i++){
878       p->aOp[i].cnt = 0;
879       p->aOp[i].cycles = 0;
880     }
881   }
882 #endif
883 }
884 
885 /*
886 ** Close a cursor and release all the resources that cursor happens
887 ** to hold.
888 */
889 void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
890   if( pCx==0 ){
891     return;
892   }
893   if( pCx->pCursor ){
894     sqlite3BtreeCloseCursor(pCx->pCursor);
895   }
896   if( pCx->pBt ){
897     sqlite3BtreeClose(pCx->pBt);
898   }
899 #ifndef SQLITE_OMIT_VIRTUALTABLE
900   if( pCx->pVtabCursor ){
901     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
902     const sqlite3_module *pModule = pCx->pModule;
903     p->inVtabMethod = 1;
904     sqlite3SafetyOff(p->db);
905     pModule->xClose(pVtabCursor);
906     sqlite3SafetyOn(p->db);
907     p->inVtabMethod = 0;
908   }
909 #endif
910   sqliteFree(pCx->pData);
911   sqliteFree(pCx->aType);
912   sqliteFree(pCx);
913 }
914 
915 /*
916 ** Close all cursors
917 */
918 static void closeAllCursors(Vdbe *p){
919   int i;
920   if( p->apCsr==0 ) return;
921   for(i=0; i<p->nCursor; i++){
922     if( !p->inVtabMethod || (p->apCsr[i] && !p->apCsr[i]->pVtabCursor) ){
923       sqlite3VdbeFreeCursor(p, p->apCsr[i]);
924       p->apCsr[i] = 0;
925     }
926   }
927 }
928 
929 /*
930 ** Clean up the VM after execution.
931 **
932 ** This routine will automatically close any cursors, lists, and/or
933 ** sorters that were left open.  It also deletes the values of
934 ** variables in the aVar[] array.
935 */
936 static void Cleanup(Vdbe *p){
937   int i;
938   if( p->aStack ){
939     releaseMemArray(p->aStack, 1 + (p->pTos - p->aStack));
940     p->pTos = &p->aStack[-1];
941   }
942   closeAllCursors(p);
943   releaseMemArray(p->aMem, p->nMem);
944   sqlite3VdbeFifoClear(&p->sFifo);
945   if( p->contextStack ){
946     for(i=0; i<p->contextStackTop; i++){
947       sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
948     }
949     sqliteFree(p->contextStack);
950   }
951   p->contextStack = 0;
952   p->contextStackDepth = 0;
953   p->contextStackTop = 0;
954   sqliteFree(p->zErrMsg);
955   p->zErrMsg = 0;
956 }
957 
958 /*
959 ** Set the number of result columns that will be returned by this SQL
960 ** statement. This is now set at compile time, rather than during
961 ** execution of the vdbe program so that sqlite3_column_count() can
962 ** be called on an SQL statement before sqlite3_step().
963 */
964 void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
965   Mem *pColName;
966   int n;
967   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
968   sqliteFree(p->aColName);
969   n = nResColumn*COLNAME_N;
970   p->nResColumn = nResColumn;
971   p->aColName = pColName = (Mem*)sqliteMalloc( sizeof(Mem)*n );
972   if( p->aColName==0 ) return;
973   while( n-- > 0 ){
974     (pColName++)->flags = MEM_Null;
975   }
976 }
977 
978 /*
979 ** Set the name of the idx'th column to be returned by the SQL statement.
980 ** zName must be a pointer to a nul terminated string.
981 **
982 ** This call must be made after a call to sqlite3VdbeSetNumCols().
983 **
984 ** If N==P3_STATIC  it means that zName is a pointer to a constant static
985 ** string and we can just copy the pointer. If it is P3_DYNAMIC, then
986 ** the string is freed using sqliteFree() when the vdbe is finished with
987 ** it. Otherwise, N bytes of zName are copied.
988 */
989 int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
990   int rc;
991   Mem *pColName;
992   assert( idx<p->nResColumn );
993   assert( var<COLNAME_N );
994   if( sqlite3MallocFailed() ) return SQLITE_NOMEM;
995   assert( p->aColName!=0 );
996   pColName = &(p->aColName[idx+var*p->nResColumn]);
997   if( N==P3_DYNAMIC || N==P3_STATIC ){
998     rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
999   }else{
1000     rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
1001   }
1002   if( rc==SQLITE_OK && N==P3_DYNAMIC ){
1003     pColName->flags = (pColName->flags&(~MEM_Static))|MEM_Dyn;
1004     pColName->xDel = 0;
1005   }
1006   return rc;
1007 }
1008 
1009 /*
1010 ** A read or write transaction may or may not be active on database handle
1011 ** db. If a transaction is active, commit it. If there is a
1012 ** write-transaction spanning more than one database file, this routine
1013 ** takes care of the master journal trickery.
1014 */
1015 static int vdbeCommit(sqlite3 *db){
1016   int i;
1017   int nTrans = 0;  /* Number of databases with an active write-transaction */
1018   int rc = SQLITE_OK;
1019   int needXcommit = 0;
1020 
1021   /* Before doing anything else, call the xSync() callback for any
1022   ** virtual module tables written in this transaction. This has to
1023   ** be done before determining whether a master journal file is
1024   ** required, as an xSync() callback may add an attached database
1025   ** to the transaction.
1026   */
1027   rc = sqlite3VtabSync(db, rc);
1028   if( rc!=SQLITE_OK ){
1029     return rc;
1030   }
1031 
1032   /* This loop determines (a) if the commit hook should be invoked and
1033   ** (b) how many database files have open write transactions, not
1034   ** including the temp database. (b) is important because if more than
1035   ** one database file has an open write transaction, a master journal
1036   ** file is required for an atomic commit.
1037   */
1038   for(i=0; i<db->nDb; i++){
1039     Btree *pBt = db->aDb[i].pBt;
1040     if( pBt && sqlite3BtreeIsInTrans(pBt) ){
1041       needXcommit = 1;
1042       if( i!=1 ) nTrans++;
1043     }
1044   }
1045 
1046   /* If there are any write-transactions at all, invoke the commit hook */
1047   if( needXcommit && db->xCommitCallback ){
1048     sqlite3SafetyOff(db);
1049     rc = db->xCommitCallback(db->pCommitArg);
1050     sqlite3SafetyOn(db);
1051     if( rc ){
1052       return SQLITE_CONSTRAINT;
1053     }
1054   }
1055 
1056   /* The simple case - no more than one database file (not counting the
1057   ** TEMP database) has a transaction active.   There is no need for the
1058   ** master-journal.
1059   **
1060   ** If the return value of sqlite3BtreeGetFilename() is a zero length
1061   ** string, it means the main database is :memory:.  In that case we do
1062   ** not support atomic multi-file commits, so use the simple case then
1063   ** too.
1064   */
1065   if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
1066     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1067       Btree *pBt = db->aDb[i].pBt;
1068       if( pBt ){
1069         rc = sqlite3BtreeSync(pBt, 0);
1070       }
1071     }
1072 
1073     /* Do the commit only if all databases successfully synced */
1074     if( rc==SQLITE_OK ){
1075       for(i=0; i<db->nDb; i++){
1076         Btree *pBt = db->aDb[i].pBt;
1077         if( pBt ){
1078           sqlite3BtreeCommit(pBt);
1079         }
1080       }
1081       sqlite3VtabCommit(db);
1082     }
1083   }
1084 
1085   /* The complex case - There is a multi-file write-transaction active.
1086   ** This requires a master journal file to ensure the transaction is
1087   ** committed atomicly.
1088   */
1089 #ifndef SQLITE_OMIT_DISKIO
1090   else{
1091     int needSync = 0;
1092     char *zMaster = 0;   /* File-name for the master journal */
1093     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
1094     OsFile *master = 0;
1095 
1096     /* Select a master journal file name */
1097     do {
1098       u32 random;
1099       sqliteFree(zMaster);
1100       sqlite3Randomness(sizeof(random), &random);
1101       zMaster = sqlite3MPrintf("%s-mj%08X", zMainFile, random&0x7fffffff);
1102       if( !zMaster ){
1103         return SQLITE_NOMEM;
1104       }
1105     }while( sqlite3OsFileExists(zMaster) );
1106 
1107     /* Open the master journal. */
1108     rc = sqlite3OsOpenExclusive(zMaster, &master, 0);
1109     if( rc!=SQLITE_OK ){
1110       sqliteFree(zMaster);
1111       return rc;
1112     }
1113 
1114     /* Write the name of each database file in the transaction into the new
1115     ** master journal file. If an error occurs at this point close
1116     ** and delete the master journal file. All the individual journal files
1117     ** still have 'null' as the master journal pointer, so they will roll
1118     ** back independently if a failure occurs.
1119     */
1120     for(i=0; i<db->nDb; i++){
1121       Btree *pBt = db->aDb[i].pBt;
1122       if( i==1 ) continue;   /* Ignore the TEMP database */
1123       if( pBt && sqlite3BtreeIsInTrans(pBt) ){
1124         char const *zFile = sqlite3BtreeGetJournalname(pBt);
1125         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
1126         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
1127           needSync = 1;
1128         }
1129         rc = sqlite3OsWrite(master, zFile, strlen(zFile)+1);
1130         if( rc!=SQLITE_OK ){
1131           sqlite3OsClose(&master);
1132           sqlite3OsDelete(zMaster);
1133           sqliteFree(zMaster);
1134           return rc;
1135         }
1136       }
1137     }
1138 
1139 
1140     /* Sync the master journal file. Before doing this, open the directory
1141     ** the master journal file is store in so that it gets synced too.
1142     */
1143     zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
1144     rc = sqlite3OsOpenDirectory(master, zMainFile);
1145     if( rc!=SQLITE_OK ||
1146           (needSync && (rc=sqlite3OsSync(master,0))!=SQLITE_OK) ){
1147       sqlite3OsClose(&master);
1148       sqlite3OsDelete(zMaster);
1149       sqliteFree(zMaster);
1150       return rc;
1151     }
1152 
1153     /* Sync all the db files involved in the transaction. The same call
1154     ** sets the master journal pointer in each individual journal. If
1155     ** an error occurs here, do not delete the master journal file.
1156     **
1157     ** If the error occurs during the first call to sqlite3BtreeSync(),
1158     ** then there is a chance that the master journal file will be
1159     ** orphaned. But we cannot delete it, in case the master journal
1160     ** file name was written into the journal file before the failure
1161     ** occured.
1162     */
1163     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1164       Btree *pBt = db->aDb[i].pBt;
1165       if( pBt && sqlite3BtreeIsInTrans(pBt) ){
1166         rc = sqlite3BtreeSync(pBt, zMaster);
1167       }
1168     }
1169     sqlite3OsClose(&master);
1170     if( rc!=SQLITE_OK ){
1171       sqliteFree(zMaster);
1172       return rc;
1173     }
1174 
1175     /* Delete the master journal file. This commits the transaction. After
1176     ** doing this the directory is synced again before any individual
1177     ** transaction files are deleted.
1178     */
1179     rc = sqlite3OsDelete(zMaster);
1180     if( rc ){
1181       return rc;
1182     }
1183     sqliteFree(zMaster);
1184     zMaster = 0;
1185     rc = sqlite3OsSyncDirectory(zMainFile);
1186     if( rc!=SQLITE_OK ){
1187       /* This is not good. The master journal file has been deleted, but
1188       ** the directory sync failed. There is no completely safe course of
1189       ** action from here. The individual journals contain the name of the
1190       ** master journal file, but there is no way of knowing if that
1191       ** master journal exists now or if it will exist after the operating
1192       ** system crash that may follow the fsync() failure.
1193       */
1194       return rc;
1195     }
1196 
1197     /* All files and directories have already been synced, so the following
1198     ** calls to sqlite3BtreeCommit() are only closing files and deleting
1199     ** journals. If something goes wrong while this is happening we don't
1200     ** really care. The integrity of the transaction is already guaranteed,
1201     ** but some stray 'cold' journals may be lying around. Returning an
1202     ** error code won't help matters.
1203     */
1204     for(i=0; i<db->nDb; i++){
1205       Btree *pBt = db->aDb[i].pBt;
1206       if( pBt ){
1207         sqlite3BtreeCommit(pBt);
1208       }
1209     }
1210     sqlite3VtabCommit(db);
1211   }
1212 #endif
1213 
1214   return rc;
1215 }
1216 
1217 /*
1218 ** This routine checks that the sqlite3.activeVdbeCnt count variable
1219 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
1220 ** currently active. An assertion fails if the two counts do not match.
1221 ** This is an internal self-check only - it is not an essential processing
1222 ** step.
1223 **
1224 ** This is a no-op if NDEBUG is defined.
1225 */
1226 #ifndef NDEBUG
1227 static void checkActiveVdbeCnt(sqlite3 *db){
1228   Vdbe *p;
1229   int cnt = 0;
1230   p = db->pVdbe;
1231   while( p ){
1232     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
1233       cnt++;
1234     }
1235     p = p->pNext;
1236   }
1237   assert( cnt==db->activeVdbeCnt );
1238 }
1239 #else
1240 #define checkActiveVdbeCnt(x)
1241 #endif
1242 
1243 /*
1244 ** Find every active VM other than pVdbe and change its status to
1245 ** aborted.  This happens when one VM causes a rollback due to an
1246 ** ON CONFLICT ROLLBACK clause (for example).  The other VMs must be
1247 ** aborted so that they do not have data rolled out from underneath
1248 ** them leading to a segfault.
1249 */
1250 void sqlite3AbortOtherActiveVdbes(sqlite3 *db, Vdbe *pExcept){
1251   Vdbe *pOther;
1252   for(pOther=db->pVdbe; pOther; pOther=pOther->pNext){
1253     if( pOther==pExcept ) continue;
1254     if( pOther->magic!=VDBE_MAGIC_RUN || pOther->pc<0 ) continue;
1255     checkActiveVdbeCnt(db);
1256     closeAllCursors(pOther);
1257     checkActiveVdbeCnt(db);
1258     pOther->aborted = 1;
1259   }
1260 }
1261 
1262 /*
1263 ** This routine is called the when a VDBE tries to halt.  If the VDBE
1264 ** has made changes and is in autocommit mode, then commit those
1265 ** changes.  If a rollback is needed, then do the rollback.
1266 **
1267 ** This routine is the only way to move the state of a VM from
1268 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.
1269 **
1270 ** Return an error code.  If the commit could not complete because of
1271 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
1272 ** means the close did not happen and needs to be repeated.
1273 */
1274 int sqlite3VdbeHalt(Vdbe *p){
1275   sqlite3 *db = p->db;
1276   int i;
1277   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
1278   int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */
1279 
1280   /* This function contains the logic that determines if a statement or
1281   ** transaction will be committed or rolled back as a result of the
1282   ** execution of this virtual machine.
1283   **
1284   ** Special errors:
1285   **
1286   **     If an SQLITE_NOMEM error has occured in a statement that writes to
1287   **     the database, then either a statement or transaction must be rolled
1288   **     back to ensure the tree-structures are in a consistent state. A
1289   **     statement transaction is rolled back if one is open, otherwise the
1290   **     entire transaction must be rolled back.
1291   **
1292   **     If an SQLITE_IOERR error has occured in a statement that writes to
1293   **     the database, then the entire transaction must be rolled back. The
1294   **     I/O error may have caused garbage to be written to the journal
1295   **     file. Were the transaction to continue and eventually be rolled
1296   **     back that garbage might end up in the database file.
1297   **
1298   **     In both of the above cases, the Vdbe.errorAction variable is
1299   **     ignored. If the sqlite3.autoCommit flag is false and a transaction
1300   **     is rolled back, it will be set to true.
1301   **
1302   ** Other errors:
1303   **
1304   ** No error:
1305   **
1306   */
1307 
1308   if( sqlite3MallocFailed() ){
1309     p->rc = SQLITE_NOMEM;
1310   }
1311   if( p->magic!=VDBE_MAGIC_RUN ){
1312     /* Already halted.  Nothing to do. */
1313     assert( p->magic==VDBE_MAGIC_HALT );
1314 #ifndef SQLITE_OMIT_VIRTUALTABLE
1315     closeAllCursors(p);
1316 #endif
1317     return SQLITE_OK;
1318   }
1319   closeAllCursors(p);
1320   checkActiveVdbeCnt(db);
1321 
1322   /* No commit or rollback needed if the program never started */
1323   if( p->pc>=0 ){
1324     int mrc;   /* Primary error code from p->rc */
1325     /* Check for one of the special errors - SQLITE_NOMEM or SQLITE_IOERR */
1326     mrc = p->rc & 0xff;
1327     isSpecialError = ((mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR)?1:0);
1328     if( isSpecialError ){
1329       /* This loop does static analysis of the query to see which of the
1330       ** following three categories it falls into:
1331       **
1332       **     Read-only
1333       **     Query with statement journal
1334       **     Query without statement journal
1335       **
1336       ** We could do something more elegant than this static analysis (i.e.
1337       ** store the type of query as part of the compliation phase), but
1338       ** handling malloc() or IO failure is a fairly obscure edge case so
1339       ** this is probably easier. Todo: Might be an opportunity to reduce
1340       ** code size a very small amount though...
1341       */
1342       int isReadOnly = 1;
1343       int isStatement = 0;
1344       assert(p->aOp || p->nOp==0);
1345       for(i=0; i<p->nOp; i++){
1346         switch( p->aOp[i].opcode ){
1347           case OP_Transaction:
1348             isReadOnly = 0;
1349             break;
1350           case OP_Statement:
1351             isStatement = 1;
1352             break;
1353         }
1354       }
1355 
1356       /* If the query was read-only, we need do no rollback at all. Otherwise,
1357       ** proceed with the special handling.
1358       */
1359       if( !isReadOnly ){
1360         if( p->rc==SQLITE_NOMEM && isStatement ){
1361           xFunc = sqlite3BtreeRollbackStmt;
1362         }else{
1363           /* We are forced to roll back the active transaction. Before doing
1364           ** so, abort any other statements this handle currently has active.
1365           */
1366           sqlite3AbortOtherActiveVdbes(db, p);
1367           sqlite3RollbackAll(db);
1368           db->autoCommit = 1;
1369         }
1370       }
1371     }
1372 
1373     /* If the auto-commit flag is set and this is the only active vdbe, then
1374     ** we do either a commit or rollback of the current transaction.
1375     **
1376     ** Note: This block also runs if one of the special errors handled
1377     ** above has occured.
1378     */
1379     if( db->autoCommit && db->activeVdbeCnt==1 ){
1380       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
1381 	/* The auto-commit flag is true, and the vdbe program was
1382         ** successful or hit an 'OR FAIL' constraint. This means a commit
1383         ** is required.
1384         */
1385         int rc = vdbeCommit(db);
1386         if( rc==SQLITE_BUSY ){
1387           return SQLITE_BUSY;
1388         }else if( rc!=SQLITE_OK ){
1389           p->rc = rc;
1390           sqlite3RollbackAll(db);
1391         }else{
1392           sqlite3CommitInternalChanges(db);
1393         }
1394       }else{
1395         sqlite3RollbackAll(db);
1396       }
1397     }else if( !xFunc ){
1398       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
1399         xFunc = sqlite3BtreeCommitStmt;
1400       }else if( p->errorAction==OE_Abort ){
1401         xFunc = sqlite3BtreeRollbackStmt;
1402       }else{
1403         sqlite3AbortOtherActiveVdbes(db, p);
1404         sqlite3RollbackAll(db);
1405         db->autoCommit = 1;
1406       }
1407     }
1408 
1409     /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
1410     ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
1411     ** and the return code is still SQLITE_OK, set the return code to the new
1412     ** error value.
1413     */
1414     assert(!xFunc ||
1415       xFunc==sqlite3BtreeCommitStmt ||
1416       xFunc==sqlite3BtreeRollbackStmt
1417     );
1418     for(i=0; xFunc && i<db->nDb; i++){
1419       int rc;
1420       Btree *pBt = db->aDb[i].pBt;
1421       if( pBt ){
1422         rc = xFunc(pBt);
1423         if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
1424           p->rc = rc;
1425           sqlite3SetString(&p->zErrMsg, 0);
1426         }
1427       }
1428     }
1429 
1430     /* If this was an INSERT, UPDATE or DELETE and the statement was committed,
1431     ** set the change counter.
1432     */
1433     if( p->changeCntOn && p->pc>=0 ){
1434       if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
1435         sqlite3VdbeSetChanges(db, p->nChange);
1436       }else{
1437         sqlite3VdbeSetChanges(db, 0);
1438       }
1439       p->nChange = 0;
1440     }
1441 
1442     /* Rollback or commit any schema changes that occurred. */
1443     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
1444       sqlite3ResetInternalSchema(db, 0);
1445       db->flags = (db->flags | SQLITE_InternChanges);
1446     }
1447   }
1448 
1449   /* We have successfully halted and closed the VM.  Record this fact. */
1450   if( p->pc>=0 ){
1451     db->activeVdbeCnt--;
1452   }
1453   p->magic = VDBE_MAGIC_HALT;
1454   checkActiveVdbeCnt(db);
1455 
1456   return SQLITE_OK;
1457 }
1458 
1459 /*
1460 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
1461 ** Write any error messages into *pzErrMsg.  Return the result code.
1462 **
1463 ** After this routine is run, the VDBE should be ready to be executed
1464 ** again.
1465 **
1466 ** To look at it another way, this routine resets the state of the
1467 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
1468 ** VDBE_MAGIC_INIT.
1469 */
1470 int sqlite3VdbeReset(Vdbe *p){
1471   sqlite3 *db;
1472   if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
1473     sqlite3Error(p->db, SQLITE_MISUSE, 0);
1474     return SQLITE_MISUSE;
1475   }
1476   db = p->db;
1477 
1478   /* If the VM did not run to completion or if it encountered an
1479   ** error, then it might not have been halted properly.  So halt
1480   ** it now.
1481   */
1482   sqlite3SafetyOn(db);
1483   sqlite3VdbeHalt(p);
1484   sqlite3SafetyOff(db);
1485 
1486   /* If the VDBE has be run even partially, then transfer the error code
1487   ** and error message from the VDBE into the main database structure.  But
1488   ** if the VDBE has just been set to run but has not actually executed any
1489   ** instructions yet, leave the main database error information unchanged.
1490   */
1491   if( p->pc>=0 ){
1492     if( p->zErrMsg ){
1493       sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, sqlite3FreeX);
1494       db->errCode = p->rc;
1495       p->zErrMsg = 0;
1496     }else if( p->rc ){
1497       sqlite3Error(db, p->rc, 0);
1498     }else{
1499       sqlite3Error(db, SQLITE_OK, 0);
1500     }
1501   }else if( p->rc && p->expired ){
1502     /* The expired flag was set on the VDBE before the first call
1503     ** to sqlite3_step(). For consistency (since sqlite3_step() was
1504     ** called), set the database error in this case as well.
1505     */
1506     sqlite3Error(db, p->rc, 0);
1507   }
1508 
1509   /* Reclaim all memory used by the VDBE
1510   */
1511   Cleanup(p);
1512 
1513   /* Save profiling information from this VDBE run.
1514   */
1515   assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || !p->aStack );
1516 #ifdef VDBE_PROFILE
1517   {
1518     FILE *out = fopen("vdbe_profile.out", "a");
1519     if( out ){
1520       int i;
1521       fprintf(out, "---- ");
1522       for(i=0; i<p->nOp; i++){
1523         fprintf(out, "%02x", p->aOp[i].opcode);
1524       }
1525       fprintf(out, "\n");
1526       for(i=0; i<p->nOp; i++){
1527         fprintf(out, "%6d %10lld %8lld ",
1528            p->aOp[i].cnt,
1529            p->aOp[i].cycles,
1530            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
1531         );
1532         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
1533       }
1534       fclose(out);
1535     }
1536   }
1537 #endif
1538   p->magic = VDBE_MAGIC_INIT;
1539   p->aborted = 0;
1540   if( p->rc==SQLITE_SCHEMA ){
1541     sqlite3ResetInternalSchema(db, 0);
1542   }
1543   return p->rc & db->errMask;
1544 }
1545 
1546 /*
1547 ** Clean up and delete a VDBE after execution.  Return an integer which is
1548 ** the result code.  Write any error message text into *pzErrMsg.
1549 */
1550 int sqlite3VdbeFinalize(Vdbe *p){
1551   int rc = SQLITE_OK;
1552   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
1553     rc = sqlite3VdbeReset(p);
1554     assert( (rc & p->db->errMask)==rc );
1555   }else if( p->magic!=VDBE_MAGIC_INIT ){
1556     return SQLITE_MISUSE;
1557   }
1558   sqlite3VdbeDelete(p);
1559   return rc;
1560 }
1561 
1562 /*
1563 ** Call the destructor for each auxdata entry in pVdbeFunc for which
1564 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
1565 ** are always destroyed.  To destroy all auxdata entries, call this
1566 ** routine with mask==0.
1567 */
1568 void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
1569   int i;
1570   for(i=0; i<pVdbeFunc->nAux; i++){
1571     struct AuxData *pAux = &pVdbeFunc->apAux[i];
1572     if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
1573       if( pAux->xDelete ){
1574         pAux->xDelete(pAux->pAux);
1575       }
1576       pAux->pAux = 0;
1577     }
1578   }
1579 }
1580 
1581 /*
1582 ** Delete an entire VDBE.
1583 */
1584 void sqlite3VdbeDelete(Vdbe *p){
1585   int i;
1586   if( p==0 ) return;
1587   Cleanup(p);
1588   if( p->pPrev ){
1589     p->pPrev->pNext = p->pNext;
1590   }else{
1591     assert( p->db->pVdbe==p );
1592     p->db->pVdbe = p->pNext;
1593   }
1594   if( p->pNext ){
1595     p->pNext->pPrev = p->pPrev;
1596   }
1597   if( p->aOp ){
1598     for(i=0; i<p->nOp; i++){
1599       Op *pOp = &p->aOp[i];
1600       freeP3(pOp->p3type, pOp->p3);
1601     }
1602     sqliteFree(p->aOp);
1603   }
1604   releaseMemArray(p->aVar, p->nVar);
1605   sqliteFree(p->aLabel);
1606   sqliteFree(p->aStack);
1607   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
1608   sqliteFree(p->aColName);
1609   sqliteFree(p->zSql);
1610   p->magic = VDBE_MAGIC_DEAD;
1611   sqliteFree(p);
1612 }
1613 
1614 /*
1615 ** If a MoveTo operation is pending on the given cursor, then do that
1616 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
1617 ** routine does nothing and returns SQLITE_OK.
1618 */
1619 int sqlite3VdbeCursorMoveto(Cursor *p){
1620   if( p->deferredMoveto ){
1621     int res, rc;
1622 #ifdef SQLITE_TEST
1623     extern int sqlite3_search_count;
1624 #endif
1625     assert( p->isTable );
1626     if( p->isTable ){
1627       rc = sqlite3BtreeMoveto(p->pCursor, 0, p->movetoTarget, &res);
1628     }else{
1629       rc = sqlite3BtreeMoveto(p->pCursor,(char*)&p->movetoTarget,
1630                               sizeof(i64),&res);
1631     }
1632     if( rc ) return rc;
1633     *p->pIncrKey = 0;
1634     p->lastRowid = keyToInt(p->movetoTarget);
1635     p->rowidIsValid = res==0;
1636     if( res<0 ){
1637       rc = sqlite3BtreeNext(p->pCursor, &res);
1638       if( rc ) return rc;
1639     }
1640 #ifdef SQLITE_TEST
1641     sqlite3_search_count++;
1642 #endif
1643     p->deferredMoveto = 0;
1644     p->cacheStatus = CACHE_STALE;
1645   }
1646   return SQLITE_OK;
1647 }
1648 
1649 /*
1650 ** The following functions:
1651 **
1652 ** sqlite3VdbeSerialType()
1653 ** sqlite3VdbeSerialTypeLen()
1654 ** sqlite3VdbeSerialRead()
1655 ** sqlite3VdbeSerialLen()
1656 ** sqlite3VdbeSerialWrite()
1657 **
1658 ** encapsulate the code that serializes values for storage in SQLite
1659 ** data and index records. Each serialized value consists of a
1660 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
1661 ** integer, stored as a varint.
1662 **
1663 ** In an SQLite index record, the serial type is stored directly before
1664 ** the blob of data that it corresponds to. In a table record, all serial
1665 ** types are stored at the start of the record, and the blobs of data at
1666 ** the end. Hence these functions allow the caller to handle the
1667 ** serial-type and data blob seperately.
1668 **
1669 ** The following table describes the various storage classes for data:
1670 **
1671 **   serial type        bytes of data      type
1672 **   --------------     ---------------    ---------------
1673 **      0                     0            NULL
1674 **      1                     1            signed integer
1675 **      2                     2            signed integer
1676 **      3                     3            signed integer
1677 **      4                     4            signed integer
1678 **      5                     6            signed integer
1679 **      6                     8            signed integer
1680 **      7                     8            IEEE float
1681 **      8                     0            Integer constant 0
1682 **      9                     0            Integer constant 1
1683 **     10,11                               reserved for expansion
1684 **    N>=12 and even       (N-12)/2        BLOB
1685 **    N>=13 and odd        (N-13)/2        text
1686 **
1687 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
1688 ** of SQLite will not understand those serial types.
1689 */
1690 
1691 /*
1692 ** Return the serial-type for the value stored in pMem.
1693 */
1694 u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
1695   int flags = pMem->flags;
1696 
1697   if( flags&MEM_Null ){
1698     return 0;
1699   }
1700   if( flags&MEM_Int ){
1701     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
1702 #   define MAX_6BYTE ((((i64)0x00001000)<<32)-1)
1703     i64 i = pMem->i;
1704     u64 u;
1705     if( file_format>=4 && (i&1)==i ){
1706       return 8+i;
1707     }
1708     u = i<0 ? -i : i;
1709     if( u<=127 ) return 1;
1710     if( u<=32767 ) return 2;
1711     if( u<=8388607 ) return 3;
1712     if( u<=2147483647 ) return 4;
1713     if( u<=MAX_6BYTE ) return 5;
1714     return 6;
1715   }
1716   if( flags&MEM_Real ){
1717     return 7;
1718   }
1719   if( flags&MEM_Str ){
1720     int n = pMem->n;
1721     assert( n>=0 );
1722     return ((n*2) + 13);
1723   }
1724   if( flags&MEM_Blob ){
1725     return (pMem->n*2 + 12);
1726   }
1727   return 0;
1728 }
1729 
1730 /*
1731 ** Return the length of the data corresponding to the supplied serial-type.
1732 */
1733 int sqlite3VdbeSerialTypeLen(u32 serial_type){
1734   if( serial_type>=12 ){
1735     return (serial_type-12)/2;
1736   }else{
1737     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
1738     return aSize[serial_type];
1739   }
1740 }
1741 
1742 /*
1743 ** Write the serialized data blob for the value stored in pMem into
1744 ** buf. It is assumed that the caller has allocated sufficient space.
1745 ** Return the number of bytes written.
1746 */
1747 int sqlite3VdbeSerialPut(unsigned char *buf, Mem *pMem, int file_format){
1748   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
1749   int len;
1750 
1751   /* Integer and Real */
1752   if( serial_type<=7 && serial_type>0 ){
1753     u64 v;
1754     int i;
1755     if( serial_type==7 ){
1756       v = *(u64*)&pMem->r;
1757     }else{
1758       v = *(u64*)&pMem->i;
1759     }
1760     len = i = sqlite3VdbeSerialTypeLen(serial_type);
1761     while( i-- ){
1762       buf[i] = (v&0xFF);
1763       v >>= 8;
1764     }
1765     return len;
1766   }
1767 
1768   /* String or blob */
1769   if( serial_type>=12 ){
1770     len = sqlite3VdbeSerialTypeLen(serial_type);
1771     memcpy(buf, pMem->z, len);
1772     return len;
1773   }
1774 
1775   /* NULL or constants 0 or 1 */
1776   return 0;
1777 }
1778 
1779 /*
1780 ** Deserialize the data blob pointed to by buf as serial type serial_type
1781 ** and store the result in pMem.  Return the number of bytes read.
1782 */
1783 int sqlite3VdbeSerialGet(
1784   const unsigned char *buf,     /* Buffer to deserialize from */
1785   u32 serial_type,              /* Serial type to deserialize */
1786   Mem *pMem                     /* Memory cell to write value into */
1787 ){
1788   switch( serial_type ){
1789     case 10:   /* Reserved for future use */
1790     case 11:   /* Reserved for future use */
1791     case 0: {  /* NULL */
1792       pMem->flags = MEM_Null;
1793       break;
1794     }
1795     case 1: { /* 1-byte signed integer */
1796       pMem->i = (signed char)buf[0];
1797       pMem->flags = MEM_Int;
1798       return 1;
1799     }
1800     case 2: { /* 2-byte signed integer */
1801       pMem->i = (((signed char)buf[0])<<8) | buf[1];
1802       pMem->flags = MEM_Int;
1803       return 2;
1804     }
1805     case 3: { /* 3-byte signed integer */
1806       pMem->i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
1807       pMem->flags = MEM_Int;
1808       return 3;
1809     }
1810     case 4: { /* 4-byte signed integer */
1811       pMem->i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
1812       pMem->flags = MEM_Int;
1813       return 4;
1814     }
1815     case 5: { /* 6-byte signed integer */
1816       u64 x = (((signed char)buf[0])<<8) | buf[1];
1817       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
1818       x = (x<<32) | y;
1819       pMem->i = *(i64*)&x;
1820       pMem->flags = MEM_Int;
1821       return 6;
1822     }
1823     case 6:   /* 8-byte signed integer */
1824     case 7: { /* IEEE floating point */
1825       u64 x;
1826       u32 y;
1827 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
1828       /* Verify that integers and floating point values use the same
1829       ** byte order.  The byte order differs on some (broken) architectures.
1830       */
1831       static const u64 t1 = ((u64)0x3ff00000)<<32;
1832       assert( 1.0==*(double*)&t1 );
1833 #endif
1834 
1835       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
1836       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
1837       x = (x<<32) | y;
1838       if( serial_type==6 ){
1839         pMem->i = *(i64*)&x;
1840         pMem->flags = MEM_Int;
1841       }else{
1842         pMem->r = *(double*)&x;
1843         pMem->flags = MEM_Real;
1844       }
1845       return 8;
1846     }
1847     case 8:    /* Integer 0 */
1848     case 9: {  /* Integer 1 */
1849       pMem->i = serial_type-8;
1850       pMem->flags = MEM_Int;
1851       return 0;
1852     }
1853     default: {
1854       int len = (serial_type-12)/2;
1855       pMem->z = (char *)buf;
1856       pMem->n = len;
1857       pMem->xDel = 0;
1858       if( serial_type&0x01 ){
1859         pMem->flags = MEM_Str | MEM_Ephem;
1860       }else{
1861         pMem->flags = MEM_Blob | MEM_Ephem;
1862       }
1863       return len;
1864     }
1865   }
1866   return 0;
1867 }
1868 
1869 /*
1870 ** The header of a record consists of a sequence variable-length integers.
1871 ** These integers are almost always small and are encoded as a single byte.
1872 ** The following macro takes advantage this fact to provide a fast decode
1873 ** of the integers in a record header.  It is faster for the common case
1874 ** where the integer is a single byte.  It is a little slower when the
1875 ** integer is two or more bytes.  But overall it is faster.
1876 **
1877 ** The following expressions are equivalent:
1878 **
1879 **     x = sqlite3GetVarint32( A, &B );
1880 **
1881 **     x = GetVarint( A, B );
1882 **
1883 */
1884 #define GetVarint(A,B)  ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
1885 
1886 /*
1887 ** This function compares the two table rows or index records specified by
1888 ** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
1889 ** or positive integer if {nKey1, pKey1} is less than, equal to or
1890 ** greater than {nKey2, pKey2}.  Both Key1 and Key2 must be byte strings
1891 ** composed by the OP_MakeRecord opcode of the VDBE.
1892 */
1893 int sqlite3VdbeRecordCompare(
1894   void *userData,
1895   int nKey1, const void *pKey1,
1896   int nKey2, const void *pKey2
1897 ){
1898   KeyInfo *pKeyInfo = (KeyInfo*)userData;
1899   u32 d1, d2;          /* Offset into aKey[] of next data element */
1900   u32 idx1, idx2;      /* Offset into aKey[] of next header element */
1901   u32 szHdr1, szHdr2;  /* Number of bytes in header */
1902   int i = 0;
1903   int nField;
1904   int rc = 0;
1905   const unsigned char *aKey1 = (const unsigned char *)pKey1;
1906   const unsigned char *aKey2 = (const unsigned char *)pKey2;
1907 
1908   Mem mem1;
1909   Mem mem2;
1910   mem1.enc = pKeyInfo->enc;
1911   mem2.enc = pKeyInfo->enc;
1912 
1913   idx1 = GetVarint(aKey1, szHdr1);
1914   d1 = szHdr1;
1915   idx2 = GetVarint(aKey2, szHdr2);
1916   d2 = szHdr2;
1917   nField = pKeyInfo->nField;
1918   while( idx1<szHdr1 && idx2<szHdr2 ){
1919     u32 serial_type1;
1920     u32 serial_type2;
1921 
1922     /* Read the serial types for the next element in each key. */
1923     idx1 += GetVarint( aKey1+idx1, serial_type1 );
1924     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
1925     idx2 += GetVarint( aKey2+idx2, serial_type2 );
1926     if( d2>=nKey2 && sqlite3VdbeSerialTypeLen(serial_type2)>0 ) break;
1927 
1928     /* Extract the values to be compared.
1929     */
1930     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
1931     d2 += sqlite3VdbeSerialGet(&aKey2[d2], serial_type2, &mem2);
1932 
1933     /* Do the comparison
1934     */
1935     rc = sqlite3MemCompare(&mem1, &mem2, i<nField ? pKeyInfo->aColl[i] : 0);
1936     if( mem1.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem1);
1937     if( mem2.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem2);
1938     if( rc!=0 ){
1939       break;
1940     }
1941     i++;
1942   }
1943 
1944   /* One of the keys ran out of fields, but all the fields up to that point
1945   ** were equal. If the incrKey flag is true, then the second key is
1946   ** treated as larger.
1947   */
1948   if( rc==0 ){
1949     if( pKeyInfo->incrKey ){
1950       rc = -1;
1951     }else if( d1<nKey1 ){
1952       rc = 1;
1953     }else if( d2<nKey2 ){
1954       rc = -1;
1955     }
1956   }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
1957                && pKeyInfo->aSortOrder[i] ){
1958     rc = -rc;
1959   }
1960 
1961   return rc;
1962 }
1963 
1964 /*
1965 ** The argument is an index entry composed using the OP_MakeRecord opcode.
1966 ** The last entry in this record should be an integer (specifically
1967 ** an integer rowid).  This routine returns the number of bytes in
1968 ** that integer.
1969 */
1970 int sqlite3VdbeIdxRowidLen(const u8 *aKey){
1971   u32 szHdr;        /* Size of the header */
1972   u32 typeRowid;    /* Serial type of the rowid */
1973 
1974   sqlite3GetVarint32(aKey, &szHdr);
1975   sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
1976   return sqlite3VdbeSerialTypeLen(typeRowid);
1977 }
1978 
1979 
1980 /*
1981 ** pCur points at an index entry created using the OP_MakeRecord opcode.
1982 ** Read the rowid (the last field in the record) and store it in *rowid.
1983 ** Return SQLITE_OK if everything works, or an error code otherwise.
1984 */
1985 int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
1986   i64 nCellKey;
1987   int rc;
1988   u32 szHdr;        /* Size of the header */
1989   u32 typeRowid;    /* Serial type of the rowid */
1990   u32 lenRowid;     /* Size of the rowid */
1991   Mem m, v;
1992 
1993   sqlite3BtreeKeySize(pCur, &nCellKey);
1994   if( nCellKey<=0 ){
1995     return SQLITE_CORRUPT_BKPT;
1996   }
1997   rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
1998   if( rc ){
1999     return rc;
2000   }
2001   sqlite3GetVarint32((u8*)m.z, &szHdr);
2002   sqlite3GetVarint32((u8*)&m.z[szHdr-1], &typeRowid);
2003   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
2004   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
2005   *rowid = v.i;
2006   sqlite3VdbeMemRelease(&m);
2007   return SQLITE_OK;
2008 }
2009 
2010 /*
2011 ** Compare the key of the index entry that cursor pC is point to against
2012 ** the key string in pKey (of length nKey).  Write into *pRes a number
2013 ** that is negative, zero, or positive if pC is less than, equal to,
2014 ** or greater than pKey.  Return SQLITE_OK on success.
2015 **
2016 ** pKey is either created without a rowid or is truncated so that it
2017 ** omits the rowid at the end.  The rowid at the end of the index entry
2018 ** is ignored as well.
2019 */
2020 int sqlite3VdbeIdxKeyCompare(
2021   Cursor *pC,                 /* The cursor to compare against */
2022   int nKey, const u8 *pKey,   /* The key to compare */
2023   int *res                    /* Write the comparison result here */
2024 ){
2025   i64 nCellKey;
2026   int rc;
2027   BtCursor *pCur = pC->pCursor;
2028   int lenRowid;
2029   Mem m;
2030 
2031   sqlite3BtreeKeySize(pCur, &nCellKey);
2032   if( nCellKey<=0 ){
2033     *res = 0;
2034     return SQLITE_OK;
2035   }
2036   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
2037   if( rc ){
2038     return rc;
2039   }
2040   lenRowid = sqlite3VdbeIdxRowidLen((u8*)m.z);
2041   *res = sqlite3VdbeRecordCompare(pC->pKeyInfo, m.n-lenRowid, m.z, nKey, pKey);
2042   sqlite3VdbeMemRelease(&m);
2043   return SQLITE_OK;
2044 }
2045 
2046 /*
2047 ** This routine sets the value to be returned by subsequent calls to
2048 ** sqlite3_changes() on the database handle 'db'.
2049 */
2050 void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
2051   db->nChange = nChange;
2052   db->nTotalChange += nChange;
2053 }
2054 
2055 /*
2056 ** Set a flag in the vdbe to update the change counter when it is finalised
2057 ** or reset.
2058 */
2059 void sqlite3VdbeCountChanges(Vdbe *v){
2060   v->changeCntOn = 1;
2061 }
2062 
2063 /*
2064 ** Mark every prepared statement associated with a database connection
2065 ** as expired.
2066 **
2067 ** An expired statement means that recompilation of the statement is
2068 ** recommend.  Statements expire when things happen that make their
2069 ** programs obsolete.  Removing user-defined functions or collating
2070 ** sequences, or changing an authorization function are the types of
2071 ** things that make prepared statements obsolete.
2072 */
2073 void sqlite3ExpirePreparedStatements(sqlite3 *db){
2074   Vdbe *p;
2075   for(p = db->pVdbe; p; p=p->pNext){
2076     p->expired = 1;
2077   }
2078 }
2079 
2080 /*
2081 ** Return the database associated with the Vdbe.
2082 */
2083 sqlite3 *sqlite3VdbeDb(Vdbe *v){
2084   return v->db;
2085 }
2086