xref: /sqlite-3.40.0/src/vdbeaux.c (revision ef5ecb41)
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 #ifndef NDEBUG
29 int sqlite3_vdbe_addop_trace = 0;
30 #endif
31 
32 
33 /*
34 ** Create a new virtual database engine.
35 */
36 Vdbe *sqlite3VdbeCreate(sqlite *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 ** Turn tracing on or off
53 */
54 void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
55   p->trace = trace;
56 }
57 
58 /*
59 ** Add a new instruction to the list of instructions current in the
60 ** VDBE.  Return the address of the new instruction.
61 **
62 ** Parameters:
63 **
64 **    p               Pointer to the VDBE
65 **
66 **    op              The opcode for this instruction
67 **
68 **    p1, p2          First two of the three possible operands.
69 **
70 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
71 ** the sqlite3VdbeChangeP3() function to change the value of the P3
72 ** operand.
73 */
74 int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){
75   int i;
76   VdbeOp *pOp;
77 
78   i = p->nOp;
79   p->nOp++;
80   assert( p->magic==VDBE_MAGIC_INIT );
81   if( i>=p->nOpAlloc ){
82     int oldSize = p->nOpAlloc;
83     Op *aNew;
84     p->nOpAlloc = p->nOpAlloc*2 + 100;
85     aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
86     if( aNew==0 ){
87       p->nOpAlloc = oldSize;
88       return 0;
89     }
90     p->aOp = aNew;
91     memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
92   }
93   pOp = &p->aOp[i];
94   pOp->opcode = op;
95   pOp->p1 = p1;
96   if( p2<0 && (-1-p2)<p->nLabel && p->aLabel[-1-p2]>=0 ){
97     p2 = p->aLabel[-1-p2];
98   }
99   pOp->p2 = p2;
100   pOp->p3 = 0;
101   pOp->p3type = P3_NOTUSED;
102 #ifndef NDEBUG
103   pOp->zComment = 0;
104   if( sqlite3_vdbe_addop_trace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
105 #endif
106   return i;
107 }
108 
109 /*
110 ** Add an opcode that includes the p3 value.
111 */
112 int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){
113   int addr = sqlite3VdbeAddOp(p, op, p1, p2);
114   sqlite3VdbeChangeP3(p, addr, zP3, p3type);
115   return addr;
116 }
117 
118 /*
119 ** Add multiple opcodes.  The list is terminated by an opcode of 0.
120 */
121 int sqlite3VdbeCode(Vdbe *p, ...){
122   int addr;
123   va_list ap;
124   int opcode, p1, p2;
125   va_start(ap, p);
126   addr = p->nOp;
127   while( (opcode = va_arg(ap,int))!=0 ){
128     p1 = va_arg(ap,int);
129     p2 = va_arg(ap,int);
130     sqlite3VdbeAddOp(p, opcode, p1, p2);
131   }
132   va_end(ap);
133   return addr;
134 }
135 
136 
137 
138 /*
139 ** Create a new symbolic label for an instruction that has yet to be
140 ** coded.  The symbolic label is really just a negative number.  The
141 ** label can be used as the P2 value of an operation.  Later, when
142 ** the label is resolved to a specific address, the VDBE will scan
143 ** through its operation list and change all values of P2 which match
144 ** the label into the resolved address.
145 **
146 ** The VDBE knows that a P2 value is a label because labels are
147 ** always negative and P2 values are suppose to be non-negative.
148 ** Hence, a negative P2 value is a label that has yet to be resolved.
149 */
150 int sqlite3VdbeMakeLabel(Vdbe *p){
151   int i;
152   i = p->nLabel++;
153   assert( p->magic==VDBE_MAGIC_INIT );
154   if( i>=p->nLabelAlloc ){
155     int *aNew;
156     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
157     aNew = sqliteRealloc( p->aLabel, p->nLabelAlloc*sizeof(p->aLabel[0]));
158     if( aNew==0 ){
159       sqliteFree(p->aLabel);
160     }
161     p->aLabel = aNew;
162   }
163   if( p->aLabel==0 ){
164     p->nLabel = 0;
165     p->nLabelAlloc = 0;
166     return 0;
167   }
168   p->aLabel[i] = -1;
169   return -1-i;
170 }
171 
172 /*
173 ** Resolve label "x" to be the address of the next instruction to
174 ** be inserted.  The parameter "x" must have been obtained from
175 ** a prior call to sqlite3VdbeMakeLabel().
176 */
177 void sqlite3VdbeResolveLabel(Vdbe *p, int x){
178   int j;
179   assert( p->magic==VDBE_MAGIC_INIT );
180   if( x<0 && (-x)<=p->nLabel && p->aOp ){
181     if( p->aLabel[-1-x]==p->nOp ) return;
182     assert( p->aLabel[-1-x]<0 );
183     p->aLabel[-1-x] = p->nOp;
184     for(j=0; j<p->nOp; j++){
185       if( p->aOp[j].p2==x ) p->aOp[j].p2 = p->nOp;
186     }
187   }
188 }
189 
190 /*
191 ** Return the address of the next instruction to be inserted.
192 */
193 int sqlite3VdbeCurrentAddr(Vdbe *p){
194   assert( p->magic==VDBE_MAGIC_INIT );
195   return p->nOp;
196 }
197 
198 /*
199 ** Add a whole list of operations to the operation stack.  Return the
200 ** address of the first operation added.
201 */
202 int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
203   int addr;
204   assert( p->magic==VDBE_MAGIC_INIT );
205   if( p->nOp + nOp >= p->nOpAlloc ){
206     int oldSize = p->nOpAlloc;
207     Op *aNew;
208     p->nOpAlloc = p->nOpAlloc*2 + nOp + 10;
209     aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
210     if( aNew==0 ){
211       p->nOpAlloc = oldSize;
212       return 0;
213     }
214     p->aOp = aNew;
215     memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
216   }
217   addr = p->nOp;
218   if( nOp>0 ){
219     int i;
220     VdbeOpList const *pIn = aOp;
221     for(i=0; i<nOp; i++, pIn++){
222       int p2 = pIn->p2;
223       VdbeOp *pOut = &p->aOp[i+addr];
224       pOut->opcode = pIn->opcode;
225       pOut->p1 = pIn->p1;
226       pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
227       pOut->p3 = pIn->p3;
228       pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
229 #ifndef NDEBUG
230       pOut->zComment = 0;
231       if( sqlite3_vdbe_addop_trace ){
232         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
233       }
234 #endif
235     }
236     p->nOp += nOp;
237   }
238   return addr;
239 }
240 
241 /*
242 ** Change the value of the P1 operand for a specific instruction.
243 ** This routine is useful when a large program is loaded from a
244 ** static array using sqlite3VdbeAddOpList but we want to make a
245 ** few minor changes to the program.
246 */
247 void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
248   assert( p->magic==VDBE_MAGIC_INIT );
249   if( p && addr>=0 && p->nOp>addr && p->aOp ){
250     p->aOp[addr].p1 = val;
251   }
252 }
253 
254 /*
255 ** Change the value of the P2 operand for a specific instruction.
256 ** This routine is useful for setting a jump destination.
257 */
258 void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
259   assert( val>=0 );
260   assert( p->magic==VDBE_MAGIC_INIT );
261   if( p && addr>=0 && p->nOp>addr && p->aOp ){
262     p->aOp[addr].p2 = val;
263   }
264 }
265 
266 /*
267 ** Change the value of the P3 operand for a specific instruction.
268 ** This routine is useful when a large program is loaded from a
269 ** static array using sqlite3VdbeAddOpList but we want to make a
270 ** few minor changes to the program.
271 **
272 ** If n>=0 then the P3 operand is dynamic, meaning that a copy of
273 ** the string is made into memory obtained from sqliteMalloc().
274 ** A value of n==0 means copy bytes of zP3 up to and including the
275 ** first null byte.  If n>0 then copy n+1 bytes of zP3.
276 **
277 ** If n==P3_STATIC  it means that zP3 is a pointer to a constant static
278 ** string and we can just copy the pointer.  n==P3_POINTER means zP3 is
279 ** a pointer to some object other than a string.  n==P3_COLLSEQ and
280 ** n==P3_KEYINFO mean that zP3 is a pointer to a CollSeq or KeyInfo
281 ** structure.  A copy is made of KeyInfo structures into memory obtained
282 ** from sqliteMalloc.
283 **
284 ** If addr<0 then change P3 on the most recently inserted instruction.
285 */
286 void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
287   Op *pOp;
288   assert( p->magic==VDBE_MAGIC_INIT );
289   if( p==0 || p->aOp==0 ) return;
290   if( addr<0 || addr>=p->nOp ){
291     addr = p->nOp - 1;
292     if( addr<0 ) return;
293   }
294   pOp = &p->aOp[addr];
295   if( pOp->p3 && pOp->p3type==P3_DYNAMIC ){
296     sqliteFree(pOp->p3);
297     pOp->p3 = 0;
298   }
299   if( zP3==0 ){
300     pOp->p3 = 0;
301     pOp->p3type = P3_NOTUSED;
302   }else if( n==P3_KEYINFO ){
303     KeyInfo *pKeyInfo;
304     int nField, nByte;
305     nField = ((KeyInfo*)zP3)->nField;
306     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]);
307     pKeyInfo = sqliteMalloc( nByte );
308     pOp->p3 = (char*)pKeyInfo;
309     if( pKeyInfo ){
310       memcpy(pKeyInfo, zP3, nByte);
311       pOp->p3type = P3_KEYINFO;
312     }else{
313       pOp->p3type = P3_NOTUSED;
314     }
315   }else if( n==P3_KEYINFO_HANDOFF ){
316     pOp->p3 = (char*)zP3;
317     pOp->p3type = P3_KEYINFO;
318   }else if( n<0 ){
319     pOp->p3 = (char*)zP3;
320     pOp->p3type = n;
321   }else{
322     sqlite3SetNString(&pOp->p3, zP3, n, 0);
323     pOp->p3type = P3_DYNAMIC;
324   }
325 }
326 
327 /*
328 ** If the P3 operand to the specified instruction appears
329 ** to be a quoted string token, then this procedure removes
330 ** the quotes.
331 **
332 ** The quoting operator can be either a grave ascent (ASCII 0x27)
333 ** or a double quote character (ASCII 0x22).  Two quotes in a row
334 ** resolve to be a single actual quote character within the string.
335 */
336 void sqlite3VdbeDequoteP3(Vdbe *p, int addr){
337   Op *pOp;
338   assert( p->magic==VDBE_MAGIC_INIT );
339   if( p->aOp==0 ) return;
340   if( addr<0 || addr>=p->nOp ){
341     addr = p->nOp - 1;
342     if( addr<0 ) return;
343   }
344   pOp = &p->aOp[addr];
345   if( pOp->p3==0 || pOp->p3[0]==0 ) return;
346   if( pOp->p3type==P3_STATIC ){
347     pOp->p3 = sqliteStrDup(pOp->p3);
348     pOp->p3type = P3_DYNAMIC;
349   }
350   assert( pOp->p3type==P3_DYNAMIC );
351   sqlite3Dequote(pOp->p3);
352 }
353 
354 /*
355 ** On the P3 argument of the given instruction, change all
356 ** strings of whitespace characters into a single space and
357 ** delete leading and trailing whitespace.
358 */
359 void sqlite3VdbeCompressSpace(Vdbe *p, int addr){
360   unsigned char *z;
361   int i, j;
362   Op *pOp;
363   assert( p->magic==VDBE_MAGIC_INIT );
364   if( p->aOp==0 || addr<0 || addr>=p->nOp ) return;
365   pOp = &p->aOp[addr];
366   if( pOp->p3type==P3_STATIC ){
367     pOp->p3 = sqliteStrDup(pOp->p3);
368     pOp->p3type = P3_DYNAMIC;
369   }
370   assert( pOp->p3type==P3_DYNAMIC );
371   z = (unsigned char*)pOp->p3;
372   if( z==0 ) return;
373   i = j = 0;
374   while( isspace(z[i]) ){ i++; }
375   while( z[i] ){
376     if( isspace(z[i]) ){
377       z[j++] = ' ';
378       while( isspace(z[++i]) ){}
379     }else{
380       z[j++] = z[i++];
381     }
382   }
383   while( j>0 && isspace(z[j-1]) ){ j--; }
384   z[j] = 0;
385 }
386 
387 #ifndef NDEBUG
388 /*
389 ** Add comment text to the most recently inserted opcode
390 */
391 void sqlite3VdbeAddComment(Vdbe *p, const char *zFormat, ...){
392   va_list ap;
393   VdbeOp *pOp;
394   char *zText;
395   va_start(ap, zFormat);
396   zText = sqlite3_vmprintf(zFormat, ap);
397   va_end(ap);
398   pOp = &p->aOp[p->nOp-1];
399   sqliteFree(pOp->zComment);
400   pOp->zComment = zText;
401 }
402 #endif
403 
404 /*
405 ** Search the current program starting at instruction addr for the given
406 ** opcode and P2 value.  Return the address plus 1 if found and 0 if not
407 ** found.
408 */
409 int sqlite3VdbeFindOp(Vdbe *p, int addr, int op, int p2){
410   int i;
411   assert( p->magic==VDBE_MAGIC_INIT );
412   for(i=addr; i<p->nOp; i++){
413     if( p->aOp[i].opcode==op && p->aOp[i].p2==p2 ) return i+1;
414   }
415   return 0;
416 }
417 
418 /*
419 ** Return the opcode for a given address.
420 */
421 VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
422   assert( p->magic==VDBE_MAGIC_INIT );
423   assert( addr>=0 && addr<p->nOp );
424   return &p->aOp[addr];
425 }
426 
427 /*
428 ** Compute a string that describes the P3 parameter for an opcode.
429 ** Use zTemp for any required temporary buffer space.
430 */
431 static char *displayP3(Op *pOp, char *zTemp, int nTemp){
432   char *zP3;
433   assert( nTemp>=20 );
434   switch( pOp->p3type ){
435     case P3_POINTER: {
436       sprintf(zTemp, "ptr(%#x)", (int)pOp->p3);
437       zP3 = zTemp;
438       break;
439     }
440     case P3_KEYINFO: {
441       int i, j;
442       KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3;
443       sprintf(zTemp, "keyinfo(%d", pKeyInfo->nField);
444       i = strlen(zTemp);
445       for(j=0; j<pKeyInfo->nField; j++){
446         CollSeq *pColl = pKeyInfo->aColl[j];
447         if( pColl ){
448           int n = strlen(pColl->zName);
449           if( i+n>nTemp-6 ){
450             strcpy(&zTemp[i],",...");
451             break;
452           }
453           zTemp[i++] = ',';
454           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
455             zTemp[i++] = '-';
456           }
457           strcpy(&zTemp[i], pColl->zName);
458           i += n;
459         }else if( i+4<nTemp-6 ){
460           strcpy(&zTemp[i],",nil");
461           i += 4;
462         }
463       }
464       zTemp[i++] = ')';
465       zTemp[i] = 0;
466       assert( i<nTemp );
467       zP3 = zTemp;
468       break;
469     }
470     case P3_COLLSEQ: {
471       CollSeq *pColl = (CollSeq*)pOp->p3;
472       sprintf(zTemp, "collseq(%.20s)", pColl->zName);
473       zP3 = zTemp;
474       break;
475     }
476     case P3_FUNCDEF: {
477       FuncDef *pDef = (FuncDef*)pOp->p3;
478       char zNum[30];
479       sprintf(zTemp, "%.*s", nTemp, pDef->zName);
480       sprintf(zNum,"(%d)", pDef->nArg);
481       if( strlen(zTemp)+strlen(zNum)+1<=nTemp ){
482         strcat(zTemp, zNum);
483       }
484       zP3 = zTemp;
485       break;
486     }
487     default: {
488       zP3 = pOp->p3;
489       if( zP3==0 ){
490         zP3 = "";
491       }
492     }
493   }
494   return zP3;
495 }
496 
497 
498 #if !defined(NDEBUG) || defined(VDBE_PROFILE)
499 /*
500 ** Print a single opcode.  This routine is used for debugging only.
501 */
502 void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
503   char *zP3;
504   char zPtr[50];
505   static const char *zFormat1 = "%4d %-13s %4d %4d %s\n";
506   static const char *zFormat2 = "%4d %-13s %4d %4d %-20s -- %s\n";
507   if( pOut==0 ) pOut = stdout;
508   zP3 = displayP3(pOp, zPtr, sizeof(zPtr));
509 #ifdef NDEBUG
510   fprintf(pOut, zFormat1,
511       pc, sqlite3OpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3);
512 #else
513   fprintf(pOut, pOp->zComment ? zFormat2 : zFormat1,
514       pc, sqlite3OpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3,pOp->zComment);
515 #endif
516   fflush(pOut);
517 }
518 #endif
519 
520 /*
521 ** Give a listing of the program in the virtual machine.
522 **
523 ** The interface is the same as sqlite3VdbeExec().  But instead of
524 ** running the code, it invokes the callback once for each instruction.
525 ** This feature is used to implement "EXPLAIN".
526 */
527 int sqlite3VdbeList(
528   Vdbe *p                   /* The VDBE */
529 ){
530   sqlite *db = p->db;
531   int i;
532   int rc = SQLITE_OK;
533   static char *azColumnNames[] = {
534      "addr", "opcode", "p1",  "p2",  "p3",
535      "int",  "text",   "int", "int", "text",
536      0
537   };
538 
539   assert( p->explain );
540 
541   /* Even though this opcode does not put dynamic strings onto the
542   ** the stack, they may become dynamic if the user calls
543   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
544   */
545   if( p->pTos==&p->aStack[4] ){
546     for(i=0; i<5; i++){
547       if( p->aStack[i].flags & MEM_Dyn ){
548         sqliteFree(p->aStack[i].z);
549       }
550       p->aStack[i].flags = 0;
551     }
552   }
553 
554   p->azColName = azColumnNames;
555   p->resOnStack = 0;
556 
557   i = p->pc++;
558   if( i>=p->nOp ){
559     p->rc = SQLITE_OK;
560     rc = SQLITE_DONE;
561   }else if( db->flags & SQLITE_Interrupt ){
562     db->flags &= ~SQLITE_Interrupt;
563     if( db->magic!=SQLITE_MAGIC_BUSY ){
564       p->rc = SQLITE_MISUSE;
565     }else{
566       p->rc = SQLITE_INTERRUPT;
567     }
568     rc = SQLITE_ERROR;
569     sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
570   }else{
571     Op *pOp = &p->aOp[i];
572     Mem *pMem = p->aStack;
573     pMem->flags = MEM_Int;
574     pMem->type = SQLITE_INTEGER;
575     pMem->i = i;                                /* Program counter */
576     pMem++;
577 
578     pMem->flags = MEM_Static|MEM_Str|MEM_Term;
579     pMem->z = sqlite3OpcodeNames[pOp->opcode];  /* Opcode */
580     pMem->n = strlen(pMem->z);
581     pMem->type = SQLITE_TEXT;
582     pMem->enc = TEXT_Utf8;
583     pMem++;
584 
585     pMem->flags = MEM_Int;
586     pMem->i = pOp->p1;                          /* P1 */
587     pMem->type = SQLITE_INTEGER;
588     pMem++;
589 
590     pMem->flags = MEM_Int;
591     pMem->i = pOp->p2;                          /* P2 */
592     pMem->type = SQLITE_INTEGER;
593     pMem++;
594 
595     pMem->flags = MEM_Short|MEM_Str|MEM_Term;   /* P3 */
596     pMem->z = displayP3(pOp, pMem->zShort, sizeof(pMem->zShort));
597     pMem->type = SQLITE_TEXT;
598     pMem->enc = TEXT_Utf8;
599 
600     p->nResColumn = 5;
601     p->pTos = pMem;
602     p->rc = SQLITE_OK;
603     p->resOnStack = 1;
604     rc = SQLITE_ROW;
605   }
606   return rc;
607 }
608 
609 /*
610 ** Prepare a virtual machine for execution.  This involves things such
611 ** as allocating stack space and initializing the program counter.
612 ** After the VDBE has be prepped, it can be executed by one or more
613 ** calls to sqlite3VdbeExec().
614 */
615 void sqlite3VdbeMakeReady(
616   Vdbe *p,                       /* The VDBE */
617   int nVar,                      /* Number of '?' see in the SQL statement */
618   int isExplain                  /* True if the EXPLAIN keywords is present */
619 ){
620   int n;
621 
622   assert( p!=0 );
623   assert( p->magic==VDBE_MAGIC_INIT );
624 
625   /* Add a HALT instruction to the very end of the program.
626   */
627   if( p->nOp==0 || (p->aOp && p->aOp[p->nOp-1].opcode!=OP_Halt) ){
628     sqlite3VdbeAddOp(p, OP_Halt, 0, 0);
629   }
630 
631   /* No instruction ever pushes more than a single element onto the
632   ** stack.  And the stack never grows on successive executions of the
633   ** same loop.  So the total number of instructions is an upper bound
634   ** on the maximum stack depth required.
635   **
636   ** Allocation all the stack space we will ever need.
637   */
638   if( p->aStack==0 ){
639     p->nVar = nVar;
640     assert( nVar>=0 );
641     n = isExplain ? 10 : p->nOp;
642     p->aStack = sqliteMalloc(
643       n*(sizeof(p->aStack[0])+sizeof(Mem*)+sizeof(char*)) /* aStack, apArg */
644       + p->nVar*sizeof(Mem)                          /* apVar */
645     );
646     p->apArg = (Mem **)&p->aStack[n];
647     p->azColName = (char**)&p->apArg[n];
648     p->apVar = (Mem *)&p->azColName[n];
649     for(n=0; n<p->nVar; n++){
650       p->apVar[n].flags = MEM_Null;
651     }
652   }
653 
654   sqlite3HashInit(&p->agg.hash, SQLITE_HASH_BINARY, 0);
655   p->agg.pSearch = 0;
656 #ifdef SQLITE_DEBUG
657   if( (p->db->flags & SQLITE_VdbeListing)!=0
658     || sqlite3OsFileExists("vdbe_explain")
659   ){
660     int i;
661     printf("VDBE Program Listing:\n");
662     for(i=0; i<p->nOp; i++){
663       sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
664     }
665   }
666   if( sqlite3OsFileExists("vdbe_trace") ){
667     printf("VDBE Execution Trace:\n");
668     p->trace = stdout;
669   }
670 #endif
671   p->pTos = &p->aStack[-1];
672   p->pc = -1;
673   p->rc = SQLITE_OK;
674   p->uniqueCnt = 0;
675   p->returnDepth = 0;
676   p->errorAction = OE_Abort;
677   p->popStack =  0;
678   p->explain |= isExplain;
679   p->magic = VDBE_MAGIC_RUN;
680 #ifdef VDBE_PROFILE
681   {
682     int i;
683     for(i=0; i<p->nOp; i++){
684       p->aOp[i].cnt = 0;
685       p->aOp[i].cycles = 0;
686     }
687   }
688 #endif
689 }
690 
691 
692 /*
693 ** Remove any elements that remain on the sorter for the VDBE given.
694 */
695 void sqlite3VdbeSorterReset(Vdbe *p){
696   while( p->pSort ){
697     Sorter *pSorter = p->pSort;
698     p->pSort = pSorter->pNext;
699     sqliteFree(pSorter->zKey);
700     sqliteFree(pSorter->pData);
701     sqliteFree(pSorter);
702   }
703 }
704 
705 /*
706 ** Reset an Agg structure.  Delete all its contents.
707 **
708 ** For installable aggregate functions, if the step function has been
709 ** called, make sure the finalizer function has also been called.  The
710 ** finalizer might need to free memory that was allocated as part of its
711 ** private context.  If the finalizer has not been called yet, call it
712 ** now.
713 */
714 void sqlite3VdbeAggReset(Agg *pAgg){
715   int i;
716   HashElem *p;
717   for(p = sqliteHashFirst(&pAgg->hash); p; p = sqliteHashNext(p)){
718     AggElem *pElem = sqliteHashData(p);
719     assert( pAgg->apFunc!=0 );
720     for(i=0; i<pAgg->nMem; i++){
721       Mem *pMem = &pElem->aMem[i];
722       if( pAgg->apFunc[i] && (pMem->flags & MEM_AggCtx)!=0 ){
723         sqlite3_context ctx;
724         ctx.pFunc = pAgg->apFunc[i];
725         ctx.s.flags = MEM_Null;
726         ctx.pAgg = pMem->z;
727         ctx.cnt = pMem->i;
728         ctx.isStep = 0;
729         ctx.isError = 0;
730         (*pAgg->apFunc[i]->xFinalize)(&ctx);
731         if( pMem->z!=0 && pMem->z!=pMem->zShort ){
732           sqliteFree(pMem->z);
733         }
734         if( ctx.s.flags & MEM_Dyn ){
735           sqliteFree(ctx.s.z);
736         }
737       }else if( pMem->flags & MEM_Dyn ){
738         sqliteFree(pMem->z);
739       }
740     }
741     sqliteFree(pElem);
742   }
743   sqlite3HashClear(&pAgg->hash);
744   sqliteFree(pAgg->apFunc);
745   pAgg->apFunc = 0;
746   pAgg->pCurrent = 0;
747   pAgg->pSearch = 0;
748   pAgg->nMem = 0;
749 }
750 
751 /*
752 ** Delete a keylist
753 */
754 void sqlite3VdbeKeylistFree(Keylist *p){
755   while( p ){
756     Keylist *pNext = p->pNext;
757     sqliteFree(p);
758     p = pNext;
759   }
760 }
761 
762 /*
763 ** Close a cursor and release all the resources that cursor happens
764 ** to hold.
765 */
766 void sqlite3VdbeCleanupCursor(Cursor *pCx){
767   if( pCx->pCursor ){
768     sqlite3BtreeCloseCursor(pCx->pCursor);
769   }
770   if( pCx->pBt ){
771     sqlite3BtreeClose(pCx->pBt);
772   }
773   sqliteFree(pCx->pData);
774   sqliteFree(pCx->aType);
775   memset(pCx, 0, sizeof(*pCx));
776 }
777 
778 /*
779 ** Close all cursors
780 */
781 static void closeAllCursors(Vdbe *p){
782   int i;
783   for(i=0; i<p->nCursor; i++){
784     Cursor *pC = p->apCsr[i];
785     sqlite3VdbeCleanupCursor(pC);
786     sqliteFree(pC);
787   }
788   sqliteFree(p->apCsr);
789   p->apCsr = 0;
790   p->nCursor = 0;
791 }
792 
793 /*
794 ** Clean up the VM after execution.
795 **
796 ** This routine will automatically close any cursors, lists, and/or
797 ** sorters that were left open.  It also deletes the values of
798 ** variables in the aVar[] array.
799 */
800 static void Cleanup(Vdbe *p){
801   int i;
802   if( p->aStack ){
803     Mem *pTos = p->pTos;
804     while( pTos>=p->aStack ){
805       if( pTos->flags & MEM_Dyn ){
806         sqliteFree(pTos->z);
807       }
808       pTos--;
809     }
810     p->pTos = pTos;
811   }
812   closeAllCursors(p);
813   if( p->aMem ){
814     for(i=0; i<p->nMem; i++){
815       if( p->aMem[i].flags & MEM_Dyn ){
816         sqliteFree(p->aMem[i].z);
817       }
818     }
819   }
820   sqliteFree(p->aMem);
821   p->aMem = 0;
822   p->nMem = 0;
823   if( p->pList ){
824     sqlite3VdbeKeylistFree(p->pList);
825     p->pList = 0;
826   }
827   sqlite3VdbeSorterReset(p);
828   if( p->pFile ){
829     if( p->pFile!=stdin ) fclose(p->pFile);
830     p->pFile = 0;
831   }
832   if( p->azField ){
833     sqliteFree(p->azField);
834     p->azField = 0;
835   }
836   p->nField = 0;
837   if( p->zLine ){
838     sqliteFree(p->zLine);
839     p->zLine = 0;
840   }
841   p->nLineAlloc = 0;
842   sqlite3VdbeAggReset(&p->agg);
843   if( p->keylistStack ){
844     int ii;
845     for(ii = 0; ii < p->keylistStackDepth; ii++){
846       sqlite3VdbeKeylistFree(p->keylistStack[ii]);
847     }
848     sqliteFree(p->keylistStack);
849     p->keylistStackDepth = 0;
850     p->keylistStack = 0;
851   }
852   sqliteFree(p->contextStack);
853   p->contextStack = 0;
854   sqliteFree(p->zErrMsg);
855   p->zErrMsg = 0;
856 }
857 
858 /*
859 ** Set the number of result columns that will be returned by this SQL
860 ** statement. This is now set at compile time, rather than during
861 ** execution of the vdbe program so that sqlite3_column_count() can
862 ** be called on an SQL statement before sqlite3_step().
863 */
864 void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
865   assert( 0==p->nResColumn );
866   p->nResColumn = nResColumn;
867 }
868 
869 /*
870 ** Set the name of the idx'th column to be returned by the SQL statement.
871 ** zName must be a pointer to a nul terminated string.
872 **
873 ** This call must be made after a call to sqlite3VdbeSetNumCols().
874 **
875 ** Parameter N may be either P3_DYNAMIC or P3_STATIC.
876 */
877 int sqlite3VdbeSetColName(Vdbe *p, int idx, const char *zName, int N){
878   int rc;
879   Mem *pColName;
880   assert( idx<(2*p->nResColumn) );
881 
882   /* If the Vdbe.aColName array has not yet been allocated, allocate
883   ** it now.
884   */
885   if( !p->aColName ){
886     int i;
887     p->aColName = (Mem *)sqliteMalloc(sizeof(Mem)*p->nResColumn*2);
888     if( !p->aColName ){
889       return SQLITE_NOMEM;
890     }
891     for(i=0; i<(2*p->nResColumn); i++){
892       p->aColName[i].flags = MEM_Null;
893     }
894   }
895 
896   pColName = &(p->aColName[idx]);
897   if( N==0 ){
898     rc = sqlite3VdbeMemSetStr(pColName, zName, -1, TEXT_Utf8, 1);
899   }else{
900     rc = sqlite3VdbeMemSetStr(pColName, zName, N, TEXT_Utf8, N>0);
901   }
902   if( rc==SQLITE_OK && N==P3_DYNAMIC ){
903     pColName->flags = (pColName->flags&(~MEM_Static))|MEM_Dyn;
904   }
905   return rc;
906 }
907 
908 /*
909 ** A read or write transaction may or may not be active on database handle
910 ** db. If a transaction is active, commit it. If there is a
911 ** write-transaction spanning more than one database file, this routine
912 ** takes care of the master journal trickery.
913 */
914 static int vdbeCommit(sqlite *db){
915   int i;
916   int nTrans = 0;  /* Number of databases with an active write-transaction */
917   int rc = SQLITE_OK;
918   int needXcommit = 0;
919 
920   for(i=0; i<db->nDb; i++){
921     Btree *pBt = db->aDb[i].pBt;
922     if( pBt && sqlite3BtreeIsInTrans(pBt) ){
923       needXcommit = 1;
924       if( i!=1 ) nTrans++;
925     }
926   }
927 
928   /* If there are any write-transactions at all, invoke the commit hook */
929   if( needXcommit && db->xCommitCallback ){
930     if( db->xCommitCallback(db->pCommitArg) ){
931       return SQLITE_CONSTRAINT;
932     }
933   }
934 
935   /* The simple case - no more than one database file (not counting the TEMP
936   ** database) has a transaction active.   There is no need for the
937   ** master-journal.
938   **
939   ** if db->nMaster==0, it means the main database is :memory:.  In that case
940   ** we do not support atomic multi-file commits, so use the simple case then
941   ** too.
942   */
943   if( db->nMaster<=0 || nTrans<=1 ){
944     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
945       Btree *pBt = db->aDb[i].pBt;
946       if( pBt ){
947         rc = sqlite3BtreeSync(pBt, 0);
948       }
949     }
950 
951     /* Do the commit only if all databases successfully synced */
952     if( rc==SQLITE_OK ){
953       for(i=0; i<db->nDb; i++){
954         Btree *pBt = db->aDb[i].pBt;
955         if( pBt ){
956           sqlite3BtreeCommit(pBt);
957         }
958       }
959     }
960   }
961 
962   /* The complex case - There is a multi-file write-transaction active.
963   ** This requires a master journal file to ensure the transaction is
964   ** committed atomicly.
965   */
966   else{
967     char *zMaster = 0;   /* File-name for the master journal */
968     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
969     OsFile master;
970 
971     /* Select a master journal file name */
972     do {
973       u32 random;
974       sqliteFree(zMaster);
975       sqlite3Randomness(sizeof(random), &random);
976       zMaster = sqlite3MPrintf("%s-mj%08X", zMainFile, random&0x7fffffff);
977       if( !zMaster ){
978         return SQLITE_NOMEM;
979       }
980     }while( sqlite3OsFileExists(zMaster) );
981 
982     /* Open the master journal. */
983     assert( strlen(zMaster)<db->nMaster );
984     rc = sqlite3OsOpenExclusive(zMaster, &master, 0);
985     if( rc!=SQLITE_OK ){
986       sqliteFree(zMaster);
987       return rc;
988     }
989 
990     /* Write the name of each database file in the transaction into the new
991     ** master journal file. If an error occurs at this point close
992     ** and delete the master journal file. All the individual journal files
993     ** still have 'null' as the master journal pointer, so they will roll
994     ** back independantly if a failure occurs.
995     */
996     for(i=0; i<db->nDb; i++){
997       Btree *pBt = db->aDb[i].pBt;
998       if( i==1 ) continue;   /* Ignore the TEMP database */
999       if( pBt && sqlite3BtreeIsInTrans(pBt) ){
1000         char const *zFile = sqlite3BtreeGetFilename(pBt);
1001         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
1002         rc = sqlite3OsWrite(&master, zFile, strlen(zFile)+1);
1003         if( rc!=SQLITE_OK ){
1004           sqlite3OsClose(&master);
1005           sqlite3OsDelete(zMaster);
1006           sqliteFree(zMaster);
1007           return rc;
1008         }
1009       }
1010     }
1011 
1012     /* Sync the master journal file */
1013     rc = sqlite3OsSync(&master);
1014     sqlite3OsClose(&master);
1015 
1016     /* FIXME:  Sync the directory that contains the master journal to
1017     ** make sure the i-node is up to date. */
1018 
1019     /* Sync all the db files involved in the transaction. The same call
1020     ** sets the master journal pointer in each individual journal. If
1021     ** an error occurs here, do not delete the master journal file.
1022     **
1023     ** If the error occurs during the first call to sqlite3BtreeSync(),
1024     ** then there is a chance that the master journal file will be
1025     ** orphaned. But we cannot delete it, in case the master journal
1026     ** file name was written into the journal file before the failure
1027     ** occured.
1028     */
1029     for(i=0; i<db->nDb; i++){
1030       Btree *pBt = db->aDb[i].pBt;
1031       if( pBt && sqlite3BtreeIsInTrans(pBt) ){
1032         rc = sqlite3BtreeSync(pBt, zMaster);
1033         if( rc!=SQLITE_OK ){
1034           sqliteFree(zMaster);
1035           return rc;
1036         }
1037       }
1038     }
1039     sqliteFree(zMaster);
1040     zMaster = 0;
1041 
1042     /* Delete the master journal file. This commits the transaction. */
1043     rc = sqlite3OsDelete(zMaster);
1044     assert( rc==SQLITE_OK );
1045 
1046     /* All files and directories have already been synced, so the following
1047     ** calls to sqlite3BtreeCommit() are only closing files and deleting
1048     ** journals. If something goes wrong while this is happening we don't
1049     ** really care. The integrity of the transaction is already guarenteed,
1050     ** but some stray 'cold' journals may be lying around. Returning an
1051     ** error code won't help matters.
1052     */
1053     for(i=0; i<db->nDb; i++){
1054       Btree *pBt = db->aDb[i].pBt;
1055       if( pBt ){
1056         sqlite3BtreeCommit(pBt);
1057       }
1058     }
1059   }
1060   return rc;
1061 }
1062 
1063 /*
1064 ** This routine checks that the sqlite3.activeVdbeCnt count variable
1065 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
1066 ** currently active. An assertion fails if the two counts do not match.
1067 **
1068 ** This is a no-op if NDEBUG is defined.
1069 */
1070 #ifndef NDEBUG
1071 static void checkActiveVdbeCnt(sqlite *db){
1072   Vdbe *p;
1073   int cnt = 0;
1074 
1075   p = db->pVdbe;
1076   while( p ){
1077     if( (p->magic==VDBE_MAGIC_RUN && p->pc>=0) || p->magic==VDBE_MAGIC_HALT ){
1078       cnt++;
1079     }
1080     p = p->pNext;
1081   }
1082 
1083   assert( cnt==db->activeVdbeCnt );
1084 }
1085 #else
1086 #define checkActiveVdbeCnt(x)
1087 #endif
1088 
1089 /*
1090 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
1091 ** Write any error messages into *pzErrMsg.  Return the result code.
1092 **
1093 ** After this routine is run, the VDBE should be ready to be executed
1094 ** again.
1095 */
1096 int sqlite3VdbeReset(Vdbe *p, char **pzErrMsg){
1097   sqlite *db = p->db;
1098   int i;
1099   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
1100 
1101   if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
1102     sqlite3SetString(pzErrMsg, sqlite3ErrStr(SQLITE_MISUSE), (char*)0);
1103     sqlite3Error(p->db, SQLITE_MISUSE, 0 ,0);
1104     db->activeVdbeCnt--;
1105     return SQLITE_MISUSE;
1106   }
1107   if( p->zErrMsg ){
1108     sqlite3Error(p->db, p->rc, "%s", p->zErrMsg, 0);
1109     if( pzErrMsg && *pzErrMsg==0 ){
1110       *pzErrMsg = p->zErrMsg;
1111     }else{
1112       sqliteFree(p->zErrMsg);
1113     }
1114     p->zErrMsg = 0;
1115   }else if( p->rc ){
1116     sqlite3SetString(pzErrMsg, sqlite3ErrStr(p->rc), (char*)0);
1117     sqlite3Error(p->db, p->rc, 0);
1118   }else{
1119     sqlite3Error(p->db, SQLITE_OK, 0);
1120   }
1121   Cleanup(p);
1122 
1123   /* What is done now depends on the exit status of the vdbe, the value of
1124   ** the sqlite.autoCommit flag and whether or not there are any other
1125   ** queries in progress. A transaction or statement transaction may need
1126   ** to be committed or rolled back on each open database file.
1127   */
1128   checkActiveVdbeCnt(db);
1129   if( db->autoCommit && db->activeVdbeCnt==1 ){
1130     if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
1131       /* The auto-commit flag is true, there are no other active queries
1132       ** using this handle and the vdbe program was successful or hit an
1133       ** 'OR FAIL' constraint. This means a commit is required, which is
1134       ** handled a little differently from the other options.
1135       */
1136       p->rc = vdbeCommit(db);
1137       if( p->rc!=SQLITE_OK ){
1138         sqlite3Error(p->db, p->rc, 0);
1139         if( p->rc==SQLITE_BUSY && p->autoCommitOn ){
1140           /* If we just now have turned autocommit on (meaning we just have
1141           ** finished executing a COMMIT command) but the commit fails due
1142           ** to lock contention, autocommit back off.  This gives the user
1143           ** the opportunity to try again after the lock that was preventing
1144           ** the commit has cleared. */
1145           db->autoCommit = 0;
1146         }else{
1147           /* If the command just executed was not a COMMIT command, then
1148           ** rollback whatever the results of that command were */
1149           xFunc = sqlite3BtreeRollback;
1150         }
1151       }
1152     }else{
1153       xFunc = sqlite3BtreeRollback;
1154     }
1155   }else{
1156     if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
1157       xFunc = sqlite3BtreeCommitStmt;
1158     }else if( p->errorAction==OE_Abort ){
1159       xFunc = sqlite3BtreeRollbackStmt;
1160     }else{
1161       xFunc = sqlite3BtreeRollback;
1162       db->autoCommit = 1;
1163     }
1164   }
1165   p->autoCommitOn = 0;
1166 
1167   /* If xFunc is not NULL, then it is one of sqlite3BtreeRollback,
1168   ** sqlite3BtreeRollbackStmt or sqlite3BtreeCommitStmt. Call it once on
1169   ** each backend. If an error occurs and the return code is still
1170   ** SQLITE_OK, set the return code to the new error value.
1171   */
1172   for(i=0; xFunc && i<db->nDb; i++){
1173     int rc;
1174     Btree *pBt = db->aDb[i].pBt;
1175     if( pBt ){
1176       rc = xFunc(pBt);
1177       if( p->rc==SQLITE_OK ) p->rc = rc;
1178     }
1179   }
1180 
1181 
1182   if( p->rc!=SQLITE_OK ){
1183     sqlite3RollbackInternalChanges(db);
1184   }
1185 
1186   if( (p->magic==VDBE_MAGIC_RUN && p->pc>=0) || p->magic==VDBE_MAGIC_HALT ){
1187     db->activeVdbeCnt--;
1188   }
1189 
1190   assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || sqlite3_malloc_failed==1 );
1191 #ifdef VDBE_PROFILE
1192   {
1193     FILE *out = fopen("vdbe_profile.out", "a");
1194     if( out ){
1195       int i;
1196       fprintf(out, "---- ");
1197       for(i=0; i<p->nOp; i++){
1198         fprintf(out, "%02x", p->aOp[i].opcode);
1199       }
1200       fprintf(out, "\n");
1201       for(i=0; i<p->nOp; i++){
1202         fprintf(out, "%6d %10lld %8lld ",
1203            p->aOp[i].cnt,
1204            p->aOp[i].cycles,
1205            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
1206         );
1207         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
1208       }
1209       fclose(out);
1210     }
1211   }
1212 #endif
1213   p->magic = VDBE_MAGIC_INIT;
1214   return p->rc;
1215 }
1216 
1217 /*
1218 ** Clean up and delete a VDBE after execution.  Return an integer which is
1219 ** the result code.  Write any error message text into *pzErrMsg.
1220 */
1221 int sqlite3VdbeFinalize(Vdbe *p, char **pzErrMsg){
1222   int rc;
1223   sqlite *db;
1224 
1225   if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
1226     sqlite3SetString(pzErrMsg, sqlite3ErrStr(SQLITE_MISUSE), (char*)0);
1227     if( p->magic==VDBE_MAGIC_INIT ){
1228       sqlite3Error(p->db, SQLITE_MISUSE, 0);
1229     }
1230     return SQLITE_MISUSE;
1231   }
1232   db = p->db;
1233   rc = sqlite3VdbeReset(p, pzErrMsg);
1234   sqlite3VdbeDelete(p);
1235   if( db->want_to_close && db->pVdbe==0 ){
1236     sqlite3_close(db);
1237   }
1238   if( rc==SQLITE_SCHEMA ){
1239     sqlite3ResetInternalSchema(db, 0);
1240   }
1241   return rc;
1242 }
1243 
1244 /*
1245 ** Delete an entire VDBE.
1246 */
1247 void sqlite3VdbeDelete(Vdbe *p){
1248   int i;
1249   if( p==0 ) return;
1250   Cleanup(p);
1251   if( p->pPrev ){
1252     p->pPrev->pNext = p->pNext;
1253   }else{
1254     assert( p->db->pVdbe==p );
1255     p->db->pVdbe = p->pNext;
1256   }
1257   if( p->pNext ){
1258     p->pNext->pPrev = p->pPrev;
1259   }
1260   p->pPrev = p->pNext = 0;
1261   if( p->nOpAlloc==0 ){
1262     p->aOp = 0;
1263     p->nOp = 0;
1264   }
1265   for(i=0; i<p->nOp; i++){
1266     Op *pOp = &p->aOp[i];
1267     if( pOp->p3type==P3_DYNAMIC || pOp->p3type==P3_KEYINFO ){
1268       sqliteFree(pOp->p3);
1269     }
1270     if( pOp->p3type==P3_VDBEFUNC ){
1271       int j;
1272       VdbeFunc *pVdbeFunc = (VdbeFunc *)pOp->p3;
1273       for(j=0; j<pVdbeFunc->nAux; j++){
1274         struct AuxData *pAuxData = &pVdbeFunc->apAux[j];
1275         if( pAuxData->pAux && pAuxData->xDelete ){
1276           pAuxData->xDelete(pAuxData->pAux);
1277         }
1278       }
1279       sqliteFree(pVdbeFunc);
1280     }
1281 #ifndef NDEBUG
1282     sqliteFree(pOp->zComment);
1283 #endif
1284   }
1285   for(i=0; i<p->nVar; i++){
1286     if( p->apVar[i].flags&MEM_Dyn ){
1287       sqliteFree(p->apVar[i].z);
1288     }
1289   }
1290   if( p->azColName16 ){
1291     for(i=0; i<p->nResColumn; i++){
1292       if( p->azColName16[i] ) sqliteFree(p->azColName16[i]);
1293     }
1294     sqliteFree(p->azColName16);
1295   }
1296   sqliteFree(p->aOp);
1297   sqliteFree(p->aLabel);
1298   sqliteFree(p->aStack);
1299   p->magic = VDBE_MAGIC_DEAD;
1300   sqliteFree(p);
1301 }
1302 
1303 /*
1304 ** If a MoveTo operation is pending on the given cursor, then do that
1305 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
1306 ** routine does nothing and returns SQLITE_OK.
1307 */
1308 int sqlite3VdbeCursorMoveto(Cursor *p){
1309   if( p->deferredMoveto ){
1310     int res;
1311     extern int sqlite3_search_count;
1312     assert( p->intKey );
1313     if( p->intKey ){
1314       sqlite3BtreeMoveto(p->pCursor, 0, p->movetoTarget, &res);
1315     }else{
1316       sqlite3BtreeMoveto(p->pCursor,(char*)&p->movetoTarget,sizeof(i64),&res);
1317     }
1318     *p->pIncrKey = 0;
1319     p->lastRecno = keyToInt(p->movetoTarget);
1320     p->recnoIsValid = res==0;
1321     if( res<0 ){
1322       sqlite3BtreeNext(p->pCursor, &res);
1323     }
1324     sqlite3_search_count++;
1325     p->deferredMoveto = 0;
1326     p->cacheValid = 0;
1327   }
1328   return SQLITE_OK;
1329 }
1330 
1331 /*
1332 ** The following functions:
1333 **
1334 ** sqlite3VdbeSerialType()
1335 ** sqlite3VdbeSerialTypeLen()
1336 ** sqlite3VdbeSerialRead()
1337 ** sqlite3VdbeSerialLen()
1338 ** sqlite3VdbeSerialWrite()
1339 **
1340 ** encapsulate the code that serializes values for storage in SQLite
1341 ** data and index records. Each serialized value consists of a
1342 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
1343 ** integer, stored as a varint.
1344 **
1345 ** In an SQLite index record, the serial type is stored directly before
1346 ** the blob of data that it corresponds to. In a table record, all serial
1347 ** types are stored at the start of the record, and the blobs of data at
1348 ** the end. Hence these functions allow the caller to handle the
1349 ** serial-type and data blob seperately.
1350 **
1351 ** The following table describes the various storage classes for data:
1352 **
1353 **   serial type        bytes of data      type
1354 **   --------------     ---------------    ---------------
1355 **      0                     0            NULL
1356 **      1                     1            signed integer
1357 **      2                     2            signed integer
1358 **      3                     3            signed integer
1359 **      4                     4            signed integer
1360 **      5                     6            signed integer
1361 **      6                     8            signed integer
1362 **      7                     8            IEEE float
1363 **     8-11                                reserved for expansion
1364 **    N>=12 and even       (N-12)/2        BLOB
1365 **    N>=13 and odd        (N-13)/2        text
1366 **
1367 */
1368 
1369 /*
1370 ** Return the serial-type for the value stored in pMem.
1371 */
1372 u32 sqlite3VdbeSerialType(Mem *pMem){
1373   int flags = pMem->flags;
1374 
1375   if( flags&MEM_Null ){
1376     return 0;
1377   }
1378   if( flags&MEM_Int ){
1379     /* Figure out whether to use 1, 2, 4 or 8 bytes. */
1380     i64 i = pMem->i;
1381     if( i>=-127 && i<=127 ) return 1;
1382     if( i>=-32767 && i<=32767 ) return 2;
1383     if( i>=-8388607 && i<=8388607 ) return 3;
1384     if( i>=-2147483647 && i<=2147483647 ) return 4;
1385     if( i>=-140737488355328L && i<=140737488355328L ) return 5;
1386     return 6;
1387   }
1388   if( flags&MEM_Real ){
1389     return 7;
1390   }
1391   if( flags&MEM_Str ){
1392     int n = pMem->n;
1393     assert( n>=0 );
1394     return ((n*2) + 13);
1395   }
1396   if( flags&MEM_Blob ){
1397     return (pMem->n*2 + 12);
1398   }
1399   return 0;
1400 }
1401 
1402 /*
1403 ** Return the length of the data corresponding to the supplied serial-type.
1404 */
1405 int sqlite3VdbeSerialTypeLen(u32 serial_type){
1406   if( serial_type>=12 ){
1407     return (serial_type-12)/2;
1408   }else{
1409     static u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
1410     return aSize[serial_type];
1411   }
1412 }
1413 
1414 /*
1415 ** Write the serialized data blob for the value stored in pMem into
1416 ** buf. It is assumed that the caller has allocated sufficient space.
1417 ** Return the number of bytes written.
1418 */
1419 int sqlite3VdbeSerialPut(unsigned char *buf, Mem *pMem){
1420   u32 serial_type = sqlite3VdbeSerialType(pMem);
1421   int len;
1422 
1423   /* NULL */
1424   if( serial_type==0 ){
1425     return 0;
1426   }
1427 
1428   /* Integer and Real */
1429   if( serial_type<=7 ){
1430     u64 v;
1431     int i;
1432     if( serial_type==7 ){
1433       v = *(u64*)&pMem->r;
1434     }else{
1435       v = *(u64*)&pMem->i;
1436     }
1437     len = i = sqlite3VdbeSerialTypeLen(serial_type);
1438     while( i-- ){
1439       buf[i] = (v&0xFF);
1440       v >>= 8;
1441     }
1442     return len;
1443   }
1444 
1445   /* String or blob */
1446   assert( serial_type>=12 );
1447   len = sqlite3VdbeSerialTypeLen(serial_type);
1448   memcpy(buf, pMem->z, len);
1449   return len;
1450 }
1451 
1452 /*
1453 ** Deserialize the data blob pointed to by buf as serial type serial_type
1454 ** and store the result in pMem.  Return the number of bytes read.
1455 */
1456 int sqlite3VdbeSerialGet(
1457   const unsigned char *buf,     /* Buffer to deserialize from */
1458   u32 serial_type,              /* Serial type to deserialize */
1459   Mem *pMem                     /* Memory cell to write value into */
1460 ){
1461   int len;
1462 
1463   if( serial_type==0 ){
1464     /* NULL */
1465     pMem->flags = MEM_Null;
1466     return 0;
1467   }
1468   len = sqlite3VdbeSerialTypeLen(serial_type);
1469   if( serial_type<=7 ){
1470     /* Integer and Real */
1471     if( serial_type<=4 ){
1472       /* 32-bit integer type.  This is handled by a special case for
1473       ** performance reasons. */
1474       int v = buf[0];
1475       int n;
1476       if( v&0x80 ){
1477         v |= -256;
1478       }
1479       for(n=1; n<len; n++){
1480         v = (v<<8) | buf[n];
1481       }
1482       pMem->flags = MEM_Int;
1483       pMem->i = v;
1484       return n;
1485     }else{
1486       u64 v = 0;
1487       int n;
1488 
1489       if( buf[0]&0x80 ){
1490         v = -1;
1491       }
1492       for(n=0; n<len; n++){
1493         v = (v<<8) | buf[n];
1494       }
1495       if( serial_type==7 ){
1496         pMem->flags = MEM_Real;
1497         pMem->r = *(double*)&v;
1498       }else{
1499         pMem->flags = MEM_Int;
1500         pMem->i = *(i64*)&v;
1501       }
1502     }
1503   }else{
1504     /* String or blob */
1505     assert( serial_type>=12 );
1506     pMem->z = (char *)buf;
1507     pMem->n = len;
1508     if( serial_type&0x01 ){
1509       pMem->flags = MEM_Str | MEM_Ephem;
1510     }else{
1511       pMem->flags = MEM_Blob | MEM_Ephem;
1512     }
1513   }
1514   return len;
1515 }
1516 
1517 /*
1518 ** This function compares the two table rows or index records specified by
1519 ** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
1520 ** or positive integer if {nKey1, pKey1} is less than, equal to or
1521 ** greater than {nKey2, pKey2}.  Both Key1 and Key2 must be byte strings
1522 ** composed by the OP_MakeRecord opcode of the VDBE.
1523 */
1524 int sqlite3VdbeRecordCompare(
1525   void *userData,
1526   int nKey1, const void *pKey1,
1527   int nKey2, const void *pKey2
1528 ){
1529   KeyInfo *pKeyInfo = (KeyInfo*)userData;
1530   u32 d1, d2;          /* Offset into aKey[] of next data element */
1531   u32 idx1, idx2;      /* Offset into aKey[] of next header element */
1532   u32 szHdr1, szHdr2;  /* Number of bytes in header */
1533   int i = 0;
1534   int nField;
1535   int rc = 0;
1536   const unsigned char *aKey1 = (const unsigned char *)pKey1;
1537   const unsigned char *aKey2 = (const unsigned char *)pKey2;
1538 
1539   Mem mem1;
1540   Mem mem2;
1541   mem1.enc = pKeyInfo->enc;
1542   mem2.enc = pKeyInfo->enc;
1543 
1544   idx1 = sqlite3GetVarint32(pKey1, &szHdr1);
1545   d1 = szHdr1;
1546   idx2 = sqlite3GetVarint32(pKey2, &szHdr2);
1547   d2 = szHdr2;
1548   nField = pKeyInfo->nField;
1549   while( idx1<szHdr1 && idx2<szHdr2 ){
1550     u32 serial_type1;
1551     u32 serial_type2;
1552 
1553     /* Read the serial types for the next element in each key. */
1554     idx1 += sqlite3GetVarint32(&aKey1[idx1], &serial_type1);
1555     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
1556     idx2 += sqlite3GetVarint32(&aKey2[idx2], &serial_type2);
1557     if( d2>=nKey2 && sqlite3VdbeSerialTypeLen(serial_type2)>0 ) break;
1558 
1559     /* Assert that there is enough space left in each key for the blob of
1560     ** data to go with the serial type just read. This assert may fail if
1561     ** the file is corrupted.  Then read the value from each key into mem1
1562     ** and mem2 respectively.
1563     */
1564     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
1565     d2 += sqlite3VdbeSerialGet(&aKey2[d2], serial_type2, &mem2);
1566 
1567     rc = sqlite3MemCompare(&mem1, &mem2, i<nField ? pKeyInfo->aColl[i] : 0);
1568     if( mem1.flags&MEM_Dyn ){
1569       sqliteFree(mem1.z);
1570     }
1571     if( mem2.flags&MEM_Dyn ){
1572       sqliteFree(mem2.z);
1573     }
1574     if( rc!=0 ){
1575       break;
1576     }
1577     i++;
1578   }
1579 
1580   /* One of the keys ran out of fields, but all the fields up to that point
1581   ** were equal. If the incrKey flag is true, then the second key is
1582   ** treated as larger.
1583   */
1584   if( rc==0 ){
1585     if( pKeyInfo->incrKey ){
1586       rc = -1;
1587     }else if( d1<nKey1 ){
1588       rc = 1;
1589     }else if( d2<nKey2 ){
1590       rc = -1;
1591     }
1592   }
1593 
1594   if( pKeyInfo->aSortOrder && i<pKeyInfo->nField && pKeyInfo->aSortOrder[i] ){
1595     rc = -rc;
1596   }
1597 
1598   return rc;
1599 }
1600 
1601 /*
1602 ** The argument is an index entry composed using the OP_MakeRecord opcode.
1603 ** The last entry in this record should be an integer (specifically
1604 ** an integer rowid).  This routine returns the number of bytes in
1605 ** that integer.
1606 */
1607 int sqlite3VdbeIdxRowidLen(int nKey, const u8 *aKey){
1608   u32 szHdr;        /* Size of the header */
1609   u32 typeRowid;    /* Serial type of the rowid */
1610 
1611   sqlite3GetVarint32(aKey, &szHdr);
1612   sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
1613   return sqlite3VdbeSerialTypeLen(typeRowid);
1614 }
1615 
1616 
1617 /*
1618 ** pCur points at an index entry created using the OP_MakeRecord opcode.
1619 ** Read the rowid (the last field in the record) and store it in *rowid.
1620 ** Return SQLITE_OK if everything works, or an error code otherwise.
1621 */
1622 int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
1623   u64 nCellKey;
1624   int rc;
1625   u32 szHdr;        /* Size of the header */
1626   u32 typeRowid;    /* Serial type of the rowid */
1627   u32 lenRowid;     /* Size of the rowid */
1628   Mem m, v;
1629 
1630   sqlite3BtreeKeySize(pCur, &nCellKey);
1631   if( nCellKey<=0 ){
1632     return SQLITE_CORRUPT;
1633   }
1634   rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
1635   if( rc ){
1636     return rc;
1637   }
1638   sqlite3GetVarint32(m.z, &szHdr);
1639   sqlite3GetVarint32(&m.z[szHdr-1], &typeRowid);
1640   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
1641   sqlite3VdbeSerialGet(&m.z[m.n-lenRowid], typeRowid, &v);
1642   *rowid = v.i;
1643   if( m.flags & MEM_Dyn ){
1644     sqliteFree(m.z);
1645   }
1646   return SQLITE_OK;
1647 }
1648 
1649 /*
1650 ** Compare the key of the index entry that cursor pC is point to against
1651 ** the key string in pKey (of length nKey).  Write into *pRes a number
1652 ** that is negative, zero, or positive if pC is less than, equal to,
1653 ** or greater than pKey.  Return SQLITE_OK on success.
1654 **
1655 ** pKey is either created without a rowid or is truncated so that it
1656 ** omits the rowid at the end.  The rowid at the end of the index entry
1657 ** is ignored as well.
1658 */
1659 int sqlite3VdbeIdxKeyCompare(
1660   Cursor *pC,                 /* The cursor to compare against */
1661   int nKey, const u8 *pKey,   /* The key to compare */
1662   int *res                    /* Write the comparison result here */
1663 ){
1664   u64 nCellKey;
1665   int rc;
1666   BtCursor *pCur = pC->pCursor;
1667   int lenRowid;
1668   Mem m;
1669 
1670   sqlite3BtreeKeySize(pCur, &nCellKey);
1671   if( nCellKey<=0 ){
1672     *res = 0;
1673     return SQLITE_OK;
1674   }
1675   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
1676   if( rc ){
1677     return rc;
1678   }
1679   lenRowid = sqlite3VdbeIdxRowidLen(m.n, m.z);
1680   *res = sqlite3VdbeRecordCompare(pC->pKeyInfo, m.n-lenRowid, m.z, nKey, pKey);
1681   if( m.flags & MEM_Dyn ){
1682     sqliteFree(m.z);
1683   }
1684   return SQLITE_OK;
1685 }
1686