xref: /sqlite-3.40.0/src/vdbe.c (revision 7c68d60b)
1 /*
2 ** Copyright (c) 1999, 2000 D. Richard Hipp
3 **
4 ** This program is free software; you can redistribute it and/or
5 ** modify it under the terms of the GNU General Public
6 ** License as published by the Free Software Foundation; either
7 ** version 2 of the License, or (at your option) any later version.
8 **
9 ** This program is distributed in the hope that it will be useful,
10 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
11 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 ** General Public License for more details.
13 **
14 ** You should have received a copy of the GNU General Public
15 ** License along with this library; if not, write to the
16 ** Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 ** Boston, MA  02111-1307, USA.
18 **
19 ** Author contact information:
20 **   [email protected]
21 **   http://www.hwaci.com/drh/
22 **
23 *************************************************************************
24 ** The code in this file implements the Virtual Database Engine (VDBE)
25 **
26 ** The SQL parser generates a program which is then executed by
27 ** the VDBE to do the work of the SQL statement.  VDBE programs are
28 ** similar in form to assembly language.  The program consists of
29 ** a linear sequence of operations.  Each operation has an opcode
30 ** and 3 operands.  Operands P1 and P2 are integers.  Operand P3
31 ** is a null-terminated string.   The P2 operand must be non-negative.
32 ** Opcodes will typically ignore one or more operands.  Many opcodes
33 ** ignore all three operands.
34 **
35 ** Computation results are stored on a stack.  Each entry on the
36 ** stack is either an integer or a null-terminated string.  An
37 ** inplicit conversion from one type to the other occurs as necessary.
38 **
39 ** Most of the code in this file is taken up by the sqliteVdbeExec()
40 ** function which does the work of interpreting a VDBE program.
41 ** But other routines are also provided to help in building up
42 ** a program instruction by instruction.
43 **
44 ** $Id: vdbe.c,v 1.42 2000/10/11 19:28:53 drh Exp $
45 */
46 #include "sqliteInt.h"
47 #include <unistd.h>
48 #include <ctype.h>
49 
50 /*
51 ** SQL is translated into a sequence of instructions to be
52 ** executed by a virtual machine.  Each instruction is an instance
53 ** of the following structure.
54 */
55 typedef struct VdbeOp Op;
56 
57 /*
58 ** A cursor is a pointer into a database file.  The database file
59 ** can represent either an SQL table or an SQL index.  Each file is
60 ** a bag of key/data pairs.  The cursor can loop over all key/data
61 ** pairs (in an arbitrary order) or it can retrieve a particular
62 ** key/data pair given a copy of the key.
63 **
64 ** Every cursor that the virtual machine has open is represented by an
65 ** instance of the following structure.
66 */
67 struct Cursor {
68   DbbeCursor *pCursor;  /* The cursor structure of the backend */
69   int index;            /* The next index to extract */
70   int keyAsData;        /* The OP_Field command works on key instead of data */
71 };
72 typedef struct Cursor Cursor;
73 
74 /*
75 ** A sorter builds a list of elements to be sorted.  Each element of
76 ** the list is an instance of the following structure.
77 */
78 typedef struct Sorter Sorter;
79 struct Sorter {
80   int nKey;           /* Number of bytes in the key */
81   char *zKey;         /* The key by which we will sort */
82   int nData;          /* Number of bytes in the data */
83   char *pData;        /* The data associated with this key */
84   Sorter *pNext;      /* Next in the list */
85 };
86 
87 /*
88 ** Number of buckets used for merge-sort.
89 */
90 #define NSORT 30
91 
92 /*
93 ** A single level of the stack is an instance of the following
94 ** structure.  Except, string values are stored on a separate
95 ** list of of pointers to character.  The reason for storing
96 ** strings separately is so that they can be easily passed
97 ** to the callback function.
98 */
99 struct Stack {
100   int i;         /* Integer value */
101   int n;         /* Number of characters in string value, including '\0' */
102   int flags;     /* Some combination of STK_Null, STK_Str, STK_Dyn, etc. */
103   double r;      /* Real value */
104 };
105 typedef struct Stack Stack;
106 
107 /*
108 ** Memory cells use the same structure as the stack except that space
109 ** for an arbitrary string is added.
110 */
111 struct Mem {
112   Stack s;       /* All values of the memory cell besides string */
113   char *z;       /* String value for this memory cell */
114 };
115 typedef struct Mem Mem;
116 
117 /*
118 ** Allowed values for Stack.flags
119 */
120 #define STK_Null      0x0001   /* Value is NULL */
121 #define STK_Str       0x0002   /* Value is a string */
122 #define STK_Int       0x0004   /* Value is an integer */
123 #define STK_Real      0x0008   /* Value is a real number */
124 #define STK_Dyn       0x0010   /* Need to call sqliteFree() on zStack[*] */
125 
126 /*
127 ** An Agg structure describes an Aggregator.  Each Agg consists of
128 ** zero or more Aggregator elements (AggElem).  Each AggElem contains
129 ** a key and one or more values.  The values are used in processing
130 ** aggregate functions in a SELECT.  The key is used to implement
131 ** the GROUP BY clause of a select.
132 */
133 typedef struct Agg Agg;
134 typedef struct AggElem AggElem;
135 struct Agg {
136   int nMem;              /* Number of values stored in each AggElem */
137   AggElem *pCurrent;     /* The AggElem currently in focus */
138   int nElem;             /* The number of AggElems */
139   int nHash;             /* Number of slots in apHash[] */
140   AggElem **apHash;      /* A hash array for looking up AggElems by zKey */
141   AggElem *pFirst;       /* A list of all AggElems */
142 };
143 struct AggElem {
144   char *zKey;            /* The key to this AggElem */
145   AggElem *pHash;        /* Next AggElem with the same hash on zKey */
146   AggElem *pNext;        /* Next AggElem in a list of them all */
147   Mem aMem[1];           /* The values for this AggElem */
148 };
149 
150 /*
151 ** A Set structure is used for quick testing to see if a value
152 ** is part of a small set.  Sets are used to implement code like
153 ** this:
154 **            x.y IN ('hi','hoo','hum')
155 */
156 typedef struct Set Set;
157 typedef struct SetElem SetElem;
158 struct Set {
159   SetElem *pAll;         /* All elements of this set */
160   SetElem *apHash[41];   /* A hash array for all elements in this set */
161 };
162 struct SetElem {
163   SetElem *pHash;        /* Next element with the same hash on zKey */
164   SetElem *pNext;        /* Next element in a list of them all */
165   char zKey[1];          /* Value of this key */
166 };
167 
168 /*
169 ** An instance of the virtual machine
170 */
171 struct Vdbe {
172   Dbbe *pBe;          /* Opaque context structure used by DB backend */
173   FILE *trace;        /* Write an execution trace here, if not NULL */
174   int nOp;            /* Number of instructions in the program */
175   int nOpAlloc;       /* Number of slots allocated for aOp[] */
176   Op *aOp;            /* Space to hold the virtual machine's program */
177   int nLabel;         /* Number of labels used */
178   int nLabelAlloc;    /* Number of slots allocated in aLabel[] */
179   int *aLabel;        /* Space to hold the labels */
180   int tos;            /* Index of top of stack */
181   int nStackAlloc;    /* Size of the stack */
182   Stack *aStack;      /* The operand stack, except string values */
183   char **zStack;      /* Text or binary values of the stack */
184   char **azColName;   /* Becomes the 4th parameter to callbacks */
185   int nCursor;        /* Number of slots in aCsr[] */
186   Cursor *aCsr;       /* On element of this array for each open cursor */
187   int nList;          /* Number of slots in apList[] */
188   FILE **apList;      /* An open file for each list */
189   int nSort;          /* Number of slots in apSort[] */
190   Sorter **apSort;    /* An open sorter list */
191   FILE *pFile;        /* At most one open file handler */
192   int nField;         /* Number of file fields */
193   char **azField;     /* Data for each file field */
194   char *zLine;        /* A single line from the input file */
195   int nLineAlloc;     /* Number of spaces allocated for zLine */
196   int nMem;           /* Number of memory locations currently allocated */
197   Mem *aMem;          /* The memory locations */
198   Agg agg;            /* Aggregate information */
199   int nSet;           /* Number of sets allocated */
200   Set *aSet;          /* An array of sets */
201   int nFetch;         /* Number of OP_Fetch instructions executed */
202 };
203 
204 /*
205 ** Create a new virtual database engine.
206 */
207 Vdbe *sqliteVdbeCreate(Dbbe *pBe){
208   Vdbe *p;
209 
210   p = sqliteMalloc( sizeof(Vdbe) );
211   p->pBe = pBe;
212   return p;
213 }
214 
215 /*
216 ** Turn tracing on or off
217 */
218 void sqliteVdbeTrace(Vdbe *p, FILE *trace){
219   p->trace = trace;
220 }
221 
222 /*
223 ** Add a new instruction to the list of instructions current in the
224 ** VDBE.  Return the address of the new instruction.
225 **
226 ** Parameters:
227 **
228 **    p               Pointer to the VDBE
229 **
230 **    op              The opcode for this instruction
231 **
232 **    p1, p2, p3      Three operands.
233 **
234 **    lbl             A symbolic label for this instruction.
235 **
236 ** Symbolic labels are negative numbers that stand for the address
237 ** of instructions that have yet to be coded.  When the instruction
238 ** is coded, its real address is substituted in the p2 field of
239 ** prior and subsequent instructions that have the lbl value in
240 ** their p2 fields.
241 */
242 int sqliteVdbeAddOp(Vdbe *p, int op, int p1, int p2, const char *p3, int lbl){
243   int i, j;
244 
245   i = p->nOp;
246   p->nOp++;
247   if( i>=p->nOpAlloc ){
248     int oldSize = p->nOpAlloc;
249     p->nOpAlloc = p->nOpAlloc*2 + 10;
250     p->aOp = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
251     if( p->aOp==0 ){
252       p->nOp = 0;
253       p->nOpAlloc = 0;
254       return 0;
255     }
256     memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
257   }
258   p->aOp[i].opcode = op;
259   p->aOp[i].p1 = p1;
260   if( p2<0 && (-1-p2)<p->nLabel && p->aLabel[-1-p2]>=0 ){
261     p2 = p->aLabel[-1-p2];
262   }
263   p->aOp[i].p2 = p2;
264   if( p3 && p3[0] ){
265     p->aOp[i].p3 = sqliteStrDup(p3);
266   }else{
267     p->aOp[i].p3 = 0;
268   }
269   if( lbl<0 && (-lbl)<=p->nLabel ){
270     p->aLabel[-1-lbl] = i;
271     for(j=0; j<i; j++){
272       if( p->aOp[j].p2==lbl ) p->aOp[j].p2 = i;
273     }
274   }
275   return i;
276 }
277 
278 /*
279 ** Resolve label "x" to be the address of the next instruction to
280 ** be inserted.
281 */
282 void sqliteVdbeResolveLabel(Vdbe *p, int x){
283   int j;
284   if( x<0 && (-x)<=p->nLabel ){
285     p->aLabel[-1-x] = p->nOp;
286     for(j=0; j<p->nOp; j++){
287       if( p->aOp[j].p2==x ) p->aOp[j].p2 = p->nOp;
288     }
289   }
290 }
291 
292 /*
293 ** Return the address of the next instruction to be inserted.
294 */
295 int sqliteVdbeCurrentAddr(Vdbe *p){
296   return p->nOp;
297 }
298 
299 /*
300 ** Add a whole list of operations to the operation stack.  Return the
301 ** address of the first operation added.
302 */
303 int sqliteVdbeAddOpList(Vdbe *p, int nOp, VdbeOp const *aOp){
304   int addr;
305   if( p->nOp + nOp >= p->nOpAlloc ){
306     int oldSize = p->nOpAlloc;
307     p->nOpAlloc = p->nOpAlloc*2 + nOp + 10;
308     p->aOp = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
309     if( p->aOp==0 ){
310       p->nOp = 0;
311       p->nOpAlloc = 0;
312       return 0;
313     }
314     memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
315   }
316   addr = p->nOp;
317   if( nOp>0 ){
318     int i;
319     for(i=0; i<nOp; i++){
320       int p2 = aOp[i].p2;
321       if( p2<0 ) p2 = addr + ADDR(p2);
322       sqliteVdbeAddOp(p, aOp[i].opcode, aOp[i].p1, p2, aOp[i].p3, 0);
323     }
324   }
325   return addr;
326 }
327 
328 /*
329 ** Change the value of the P3 operand for a specific instruction.
330 ** This routine is useful when a large program is loaded from a
331 ** static array using sqliteVdbeAddOpList but we want to make a
332 ** few minor changes to the program.
333 */
334 void sqliteVdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
335   if( p && addr>=0 && p->nOp>addr && zP3 ){
336     sqliteSetNString(&p->aOp[addr].p3, zP3, n, 0);
337   }
338 }
339 
340 /*
341 ** If the P3 operand to the specified instruction appears
342 ** to be a quoted string token, then this procedure removes
343 ** the quotes.
344 **
345 ** The quoting operator can be either a grave ascent (ASCII 0x27)
346 ** or a double quote character (ASCII 0x22).  Two quotes in a row
347 ** resolve to be a single actual quote character within the string.
348 */
349 void sqliteVdbeDequoteP3(Vdbe *p, int addr){
350   char *z;
351   if( addr<0 || addr>=p->nOp ) return;
352   z = p->aOp[addr].p3;
353   sqliteDequote(z);
354 }
355 
356 /*
357 ** On the P3 argument of the given instruction, change all
358 ** strings of whitespace characters into a single space and
359 ** delete leading and trailing whitespace.
360 */
361 void sqliteVdbeCompressSpace(Vdbe *p, int addr){
362   char *z;
363   int i, j;
364   if( addr<0 || addr>=p->nOp ) return;
365   z = p->aOp[addr].p3;
366   i = j = 0;
367   while( isspace(z[i]) ){ i++; }
368   while( z[i] ){
369     if( isspace(z[i]) ){
370       z[j++] = ' ';
371       while( isspace(z[++i]) ){}
372     }else{
373       z[j++] = z[i++];
374     }
375   }
376   while( i>0 && isspace(z[i-1]) ){
377     z[i-1] = 0;
378     i--;
379   }
380 }
381 
382 /*
383 ** Create a new symbolic label for an instruction that has yet to be
384 ** coded.  The symbolic label is really just a negative number.  The
385 ** label can be used as the P2 value of an operation.  Later, when
386 ** the label is resolved to a specific address, the VDBE will scan
387 ** through its operation list and change all values of P2 which match
388 ** the label into the resolved address.
389 **
390 ** The VDBE knows that a P2 value is a label because labels are
391 ** always negative and P2 values are suppose to be non-negative.
392 ** Hence, a negative P2 value is a label that has yet to be resolved.
393 */
394 int sqliteVdbeMakeLabel(Vdbe *p){
395   int i;
396   i = p->nLabel++;
397   if( i>=p->nLabelAlloc ){
398     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
399     p->aLabel = sqliteRealloc( p->aLabel, p->nLabelAlloc*sizeof(int));
400   }
401   if( p->aLabel==0 ){
402     p->nLabel = 0;
403     p->nLabelAlloc = 0;
404     return 0;
405   }
406   p->aLabel[i] = -1;
407   return -1-i;
408 }
409 
410 /*
411 ** Reset an Agg structure.  Delete all its contents.
412 */
413 static void AggReset(Agg *p){
414   int i;
415   while( p->pFirst ){
416     AggElem *pElem = p->pFirst;
417     p->pFirst = pElem->pNext;
418     for(i=0; i<p->nMem; i++){
419       if( pElem->aMem[i].s.flags & STK_Dyn ){
420         sqliteFree(pElem->aMem[i].z);
421       }
422     }
423     sqliteFree(pElem);
424   }
425   sqliteFree(p->apHash);
426   memset(p, 0, sizeof(*p));
427 }
428 
429 /*
430 ** Add the given AggElem to the hash array
431 */
432 static void AggEnhash(Agg *p, AggElem *pElem){
433   int h = sqliteHashNoCase(pElem->zKey, 0) % p->nHash;
434   pElem->pHash = p->apHash[h];
435   p->apHash[h] = pElem;
436 }
437 
438 /*
439 ** Change the size of the hash array to the amount given.
440 */
441 static void AggRehash(Agg *p, int nHash){
442   int size;
443   AggElem *pElem;
444   if( p->nHash==nHash ) return;
445   size = nHash * sizeof(AggElem*);
446   p->apHash = sqliteRealloc(p->apHash, size );
447   memset(p->apHash, 0, size);
448   p->nHash = nHash;
449   for(pElem=p->pFirst; pElem; pElem=pElem->pNext){
450     AggEnhash(p, pElem);
451   }
452 }
453 
454 /*
455 ** Insert a new element and make it the current element.
456 **
457 ** Return 0 on success and 1 if memory is exhausted.
458 */
459 static int AggInsert(Agg *p, char *zKey){
460   AggElem *pElem;
461   int i;
462   if( p->nHash <= p->nElem*2 ){
463     AggRehash(p, p->nElem*2 + 19);
464   }
465   if( p->nHash==0 ) return 1;
466   pElem = sqliteMalloc( sizeof(AggElem) + strlen(zKey) + 1 +
467                         (p->nMem-1)*sizeof(pElem->aMem[0]) );
468   if( pElem==0 ) return 1;
469   pElem->zKey = (char*)&pElem->aMem[p->nMem];
470   strcpy(pElem->zKey, zKey);
471   AggEnhash(p, pElem);
472   pElem->pNext = p->pFirst;
473   p->pFirst = pElem;
474   p->nElem++;
475   p->pCurrent = pElem;
476   for(i=0; i<p->nMem; i++){
477     pElem->aMem[i].s.flags = STK_Null;
478   }
479   return 0;
480 }
481 
482 /*
483 ** Get the AggElem currently in focus
484 */
485 #define AggInFocus(P)   ((P).pCurrent ? (P).pCurrent : _AggInFocus(&(P)))
486 static AggElem *_AggInFocus(Agg *p){
487   AggElem *pFocus = p->pFirst;
488   if( pFocus ){
489     p->pCurrent = pFocus;
490   }else{
491     AggInsert(p,"");
492     pFocus = p->pCurrent = p->pFirst;
493   }
494   return pFocus;
495 }
496 
497 /*
498 ** Erase all information from a Set
499 */
500 static void SetClear(Set *p){
501   SetElem *pElem, *pNext;
502   for(pElem=p->pAll; pElem; pElem=pNext){
503     pNext = pElem->pNext;
504     sqliteFree(pElem);
505   }
506   memset(p, 0, sizeof(*p));
507 }
508 
509 /*
510 ** Insert a new element into the set
511 */
512 static void SetInsert(Set *p, char *zKey){
513   SetElem *pElem;
514   int h = sqliteHashNoCase(zKey, 0) % ArraySize(p->apHash);
515   for(pElem=p->apHash[h]; pElem; pElem=pElem->pHash){
516     if( strcmp(pElem->zKey, zKey)==0 ) return;
517   }
518   pElem = sqliteMalloc( sizeof(*pElem) + strlen(zKey) );
519   if( pElem==0 ) return;
520   strcpy(pElem->zKey, zKey);
521   pElem->pNext = p->pAll;
522   p->pAll = pElem;
523   pElem->pHash = p->apHash[h];
524   p->apHash[h] = pElem;
525 }
526 
527 /*
528 ** Return TRUE if an element is in the set.  Return FALSE if not.
529 */
530 static int SetTest(Set *p, char *zKey){
531   SetElem *pElem;
532   int h = sqliteHashNoCase(zKey, 0) % ArraySize(p->apHash);
533   for(pElem=p->apHash[h]; pElem; pElem=pElem->pHash){
534     if( strcmp(pElem->zKey, zKey)==0 ) return 1;
535   }
536   return 0;
537 }
538 
539 /*
540 ** Convert the given stack entity into a string if it isn't one
541 ** already.  Return non-zero if we run out of memory.
542 **
543 ** NULLs are converted into an empty string.
544 */
545 #define Stringify(P,I) \
546    ((P->aStack[I].flags & STK_Str)==0 ? hardStringify(P,I) : 0)
547 static int hardStringify(Vdbe *p, int i){
548   char zBuf[30];
549   int fg = p->aStack[i].flags;
550   if( fg & STK_Real ){
551     sprintf(zBuf,"%.15g",p->aStack[i].r);
552   }else if( fg & STK_Int ){
553     sprintf(zBuf,"%d",p->aStack[i].i);
554   }else{
555     p->zStack[i] = "";
556     p->aStack[i].n = 1;
557     p->aStack[i].flags |= STK_Str;
558     return 0;
559   }
560   p->zStack[i] = sqliteStrDup(zBuf);
561   if( p->zStack[i]==0 ) return 1;
562   p->aStack[i].n = strlen(p->zStack[i])+1;
563   p->aStack[i].flags |= STK_Str|STK_Dyn;
564   return 0;
565 }
566 
567 /*
568 ** Release the memory associated with the given stack level
569 */
570 #define Release(P,I)  if((P)->aStack[I].flags&STK_Dyn){ hardRelease(P,I); }
571 static void hardRelease(Vdbe *p, int i){
572   sqliteFree(p->zStack[i]);
573   p->zStack[i] = 0;
574   p->aStack[i].flags &= ~(STK_Str|STK_Dyn);
575 }
576 
577 /*
578 ** Convert the given stack entity into a integer if it isn't one
579 ** already.
580 **
581 ** Any prior string or real representation is invalidated.
582 ** NULLs are converted into 0.
583 */
584 #define Integerify(P,I) \
585     if(((P)->aStack[(I)].flags&STK_Int)==0){ hardIntegerify(P,I); }
586 static void hardIntegerify(Vdbe *p, int i){
587   if( p->aStack[i].flags & STK_Real ){
588     p->aStack[i].i = p->aStack[i].r;
589     Release(p, i);
590   }else if( p->aStack[i].flags & STK_Str ){
591     p->aStack[i].i = atoi(p->zStack[i]);
592     Release(p, i);
593   }else{
594     p->aStack[i].i = 0;
595   }
596   p->aStack[i].flags = STK_Int;
597 }
598 
599 /*
600 ** Get a valid Real representation for the given stack element.
601 **
602 ** Any prior string or integer representation is retained.
603 ** NULLs are converted into 0.0.
604 */
605 #define Realify(P,I) \
606     if(((P)->aStack[(I)].flags&STK_Real)==0){ hardRealify(P,I); }
607 static void hardRealify(Vdbe *p, int i){
608   if( p->aStack[i].flags & STK_Str ){
609     p->aStack[i].r = atof(p->zStack[i]);
610   }else if( p->aStack[i].flags & STK_Int ){
611     p->aStack[i].r = p->aStack[i].i;
612   }else{
613     p->aStack[i].r = 0.0;
614   }
615   p->aStack[i].flags |= STK_Real;
616 }
617 
618 /*
619 ** Pop the stack N times.  Free any memory associated with the
620 ** popped stack elements.
621 */
622 static void PopStack(Vdbe *p, int N){
623   if( p->zStack==0 ) return;
624   while( p->tos>=0 && N-->0 ){
625     int i = p->tos--;
626     if( p->aStack[i].flags & STK_Dyn ){
627       sqliteFree(p->zStack[i]);
628     }
629     p->aStack[i].flags = 0;
630     p->zStack[i] = 0;
631   }
632 }
633 
634 /*
635 ** Make sure space has been allocated to hold at least N
636 ** stack elements.  Allocate additional stack space if
637 ** necessary.
638 **
639 ** Return 0 on success and non-zero if there are memory
640 ** allocation errors.
641 */
642 #define NeedStack(P,N) (((P)->nStackAlloc<=(N)) ? hardNeedStack(P,N) : 0)
643 static int hardNeedStack(Vdbe *p, int N){
644   int oldAlloc;
645   int i;
646   if( N>=p->nStackAlloc ){
647     oldAlloc = p->nStackAlloc;
648     p->nStackAlloc = N + 20;
649     p->aStack = sqliteRealloc(p->aStack, p->nStackAlloc*sizeof(p->aStack[0]));
650     p->zStack = sqliteRealloc(p->zStack, p->nStackAlloc*sizeof(char*));
651     if( p->aStack==0 || p->zStack==0 ){
652       sqliteFree(p->aStack);
653       sqliteFree(p->zStack);
654       p->aStack = 0;
655       p->zStack = 0;
656       p->nStackAlloc = 0;
657       return 1;
658     }
659     for(i=oldAlloc; i<p->nStackAlloc; i++){
660       p->zStack[i] = 0;
661       p->aStack[i].flags = 0;
662     }
663   }
664   return 0;
665 }
666 
667 /*
668 ** Clean up the VM after execution.
669 **
670 ** This routine will automatically close any cursors, list, and/or
671 ** sorters that were left open.
672 */
673 static void Cleanup(Vdbe *p){
674   int i;
675   PopStack(p, p->tos+1);
676   sqliteFree(p->azColName);
677   p->azColName = 0;
678   for(i=0; i<p->nCursor; i++){
679     if( p->aCsr[i].pCursor ){
680       sqliteDbbeCloseCursor(p->aCsr[i].pCursor);
681       p->aCsr[i].pCursor = 0;
682     }
683   }
684   sqliteFree(p->aCsr);
685   p->aCsr = 0;
686   p->nCursor = 0;
687   for(i=0; i<p->nMem; i++){
688     if( p->aMem[i].s.flags & STK_Dyn ){
689       sqliteFree(p->aMem[i].z);
690     }
691   }
692   sqliteFree(p->aMem);
693   p->aMem = 0;
694   p->nMem = 0;
695   for(i=0; i<p->nList; i++){
696     if( p->apList[i] ){
697       sqliteDbbeCloseTempFile(p->pBe, p->apList[i]);
698       p->apList[i] = 0;
699     }
700   }
701   sqliteFree(p->apList);
702   p->apList = 0;
703   p->nList = 0;
704   for(i=0; i<p->nSort; i++){
705     Sorter *pSorter;
706     while( (pSorter = p->apSort[i])!=0 ){
707       p->apSort[i] = pSorter->pNext;
708       sqliteFree(pSorter->zKey);
709       sqliteFree(pSorter->pData);
710       sqliteFree(pSorter);
711     }
712   }
713   sqliteFree(p->apSort);
714   p->apSort = 0;
715   p->nSort = 0;
716   if( p->pFile ){
717     if( p->pFile!=stdin ) fclose(p->pFile);
718     p->pFile = 0;
719   }
720   if( p->azField ){
721     sqliteFree(p->azField);
722     p->azField = 0;
723   }
724   p->nField = 0;
725   if( p->zLine ){
726     sqliteFree(p->zLine);
727     p->zLine = 0;
728   }
729   p->nLineAlloc = 0;
730   AggReset(&p->agg);
731   for(i=0; i<p->nSet; i++){
732     SetClear(&p->aSet[i]);
733   }
734   sqliteFree(p->aSet);
735   p->aSet = 0;
736   p->nSet = 0;
737 }
738 
739 /*
740 ** Delete an entire VDBE.
741 */
742 void sqliteVdbeDelete(Vdbe *p){
743   int i;
744   if( p==0 ) return;
745   Cleanup(p);
746   if( p->nOpAlloc==0 ){
747     p->aOp = 0;
748     p->nOp = 0;
749   }
750   for(i=0; i<p->nOp; i++){
751     sqliteFree(p->aOp[i].p3);
752   }
753   sqliteFree(p->aOp);
754   sqliteFree(p->aLabel);
755   sqliteFree(p->aStack);
756   sqliteFree(p->zStack);
757   sqliteFree(p);
758 }
759 
760 /*
761 ** A translation from opcode numbers to opcode names.  Used for testing
762 ** and debugging only.
763 **
764 ** If any of the numeric OP_ values for opcodes defined in sqliteVdbe.h
765 ** change, be sure to change this array to match.  You can use the
766 ** "opNames.awk" awk script which is part of the source tree to regenerate
767 ** this array, then copy and paste it into this file, if you want.
768 */
769 static char *zOpName[] = { 0,
770   "Open",           "Close",          "Fetch",          "Fcnt",
771   "New",            "Put",            "Distinct",       "Found",
772   "NotFound",       "Delete",         "Field",          "KeyAsData",
773   "Key",            "Rewind",         "Next",           "Destroy",
774   "Reorganize",     "ResetIdx",       "NextIdx",        "PutIdx",
775   "DeleteIdx",      "MemLoad",        "MemStore",       "ListOpen",
776   "ListWrite",      "ListRewind",     "ListRead",       "ListClose",
777   "SortOpen",       "SortPut",        "SortMakeRec",    "SortMakeKey",
778   "Sort",           "SortNext",       "SortKey",        "SortCallback",
779   "SortClose",      "FileOpen",       "FileRead",       "FileField",
780   "FileClose",      "AggReset",       "AggFocus",       "AggIncr",
781   "AggNext",        "AggSet",         "AggGet",         "SetInsert",
782   "SetFound",       "SetNotFound",    "SetClear",       "MakeRecord",
783   "MakeKey",        "Goto",           "If",             "Halt",
784   "ColumnCount",    "ColumnName",     "Callback",       "Integer",
785   "String",         "Null",           "Pop",            "Dup",
786   "Pull",           "Add",            "AddImm",         "Subtract",
787   "Multiply",       "Divide",         "Min",            "Max",
788   "Like",           "Glob",           "Eq",             "Ne",
789   "Lt",             "Le",             "Gt",             "Ge",
790   "IsNull",         "NotNull",        "Negative",       "And",
791   "Or",             "Not",            "Concat",         "Noop",
792   "Strlen",         "Substr",
793 };
794 
795 /*
796 ** Given the name of an opcode, return its number.  Return 0 if
797 ** there is no match.
798 **
799 ** This routine is used for testing and debugging.
800 */
801 int sqliteVdbeOpcode(const char *zName){
802   int i;
803   for(i=1; i<=OP_MAX; i++){
804     if( sqliteStrICmp(zName, zOpName[i])==0 ) return i;
805   }
806   return 0;
807 }
808 
809 /*
810 ** Give a listing of the program in the virtual machine.
811 **
812 ** The interface is the same as sqliteVdbeExec().  But instead of
813 ** running the code, it invokes the callback once for each instruction.
814 ** This feature is used to implement "EXPLAIN".
815 */
816 int sqliteVdbeList(
817   Vdbe *p,                   /* The VDBE */
818   sqlite_callback xCallback, /* The callback */
819   void *pArg,                /* 1st argument to callback */
820   char **pzErrMsg            /* Error msg written here */
821 ){
822   int i, rc;
823   char *azValue[6];
824   char zAddr[20];
825   char zP1[20];
826   char zP2[20];
827   static char *azColumnNames[] = {
828      "addr", "opcode", "p1", "p2", "p3", 0
829   };
830 
831   if( xCallback==0 ) return 0;
832   azValue[0] = zAddr;
833   azValue[2] = zP1;
834   azValue[3] = zP2;
835   azValue[5] = 0;
836   rc = SQLITE_OK;
837   /* if( pzErrMsg ){ *pzErrMsg = 0; } */
838   for(i=0; rc==SQLITE_OK && i<p->nOp; i++){
839     sprintf(zAddr,"%d",i);
840     sprintf(zP1,"%d", p->aOp[i].p1);
841     sprintf(zP2,"%d", p->aOp[i].p2);
842     azValue[4] = p->aOp[i].p3;
843     azValue[1] = zOpName[p->aOp[i].opcode];
844     if( xCallback(pArg, 5, azValue, azColumnNames) ){
845       rc = SQLITE_ABORT;
846     }
847   }
848   return rc;
849 }
850 
851 /*
852 ** The parameters are pointers to the head of two sorted lists
853 ** of Sorter structures.  Merge these two lists together and return
854 ** a single sorted list.  This routine forms the core of the merge-sort
855 ** algorithm.
856 **
857 ** In the case of a tie, left sorts in front of right.
858 */
859 static Sorter *Merge(Sorter *pLeft, Sorter *pRight){
860   Sorter sHead;
861   Sorter *pTail;
862   pTail = &sHead;
863   pTail->pNext = 0;
864   while( pLeft && pRight ){
865     int c = sqliteSortCompare(pLeft->zKey, pRight->zKey);
866     if( c<=0 ){
867       pTail->pNext = pLeft;
868       pLeft = pLeft->pNext;
869     }else{
870       pTail->pNext = pRight;
871       pRight = pRight->pNext;
872     }
873     pTail = pTail->pNext;
874   }
875   if( pLeft ){
876     pTail->pNext = pLeft;
877   }else if( pRight ){
878     pTail->pNext = pRight;
879   }
880   return sHead.pNext;
881 }
882 
883 /*
884 ** Execute the program in the VDBE.
885 **
886 ** If an error occurs, an error message is written to memory obtained
887 ** from sqliteMalloc() and *pzErrMsg is made to point to that memory.
888 ** The return parameter is the number of errors.
889 **
890 ** If the callback every returns non-zero, then the program exits
891 ** immediately.  No error message but the function does return SQLITE_ABORT.
892 **
893 ** A memory allocation error causes this routine to return SQLITE_NOMEM
894 ** and abandon furture processing.
895 **
896 ** Other fatal errors return SQLITE_ERROR.
897 **
898 ** If a database file could not be opened because it is locked by
899 ** another database instance, then the xBusy() callback is invoked
900 ** with pBusyArg as its first argument, the name of the table as the
901 ** second argument, and the number of times the open has been attempted
902 ** as the third argument.  The xBusy() callback will typically wait
903 ** for the database file to be openable, then return.  If xBusy()
904 ** returns non-zero, another attempt is made to open the file.  If
905 ** xBusy() returns zero, or if xBusy is NULL, then execution halts
906 ** and this routine returns SQLITE_BUSY.
907 */
908 int sqliteVdbeExec(
909   Vdbe *p,                   /* The VDBE */
910   sqlite_callback xCallback, /* The callback */
911   void *pArg,                /* 1st argument to callback */
912   char **pzErrMsg,           /* Error msg written here */
913   void *pBusyArg,            /* 1st argument to the busy callback */
914   int (*xBusy)(void*,const char*,int)  /* Called when a file is busy */
915 ){
916   int pc;                    /* The program counter */
917   Op *pOp;                   /* Current operation */
918   int rc;                    /* Value to return */
919   char zBuf[100];            /* Space to sprintf() and integer */
920 
921   p->tos = -1;
922   rc = SQLITE_OK;
923 #ifdef MEMORY_DEBUG
924   if( access("vdbe_trace",0)==0 ){
925     p->trace = stderr;
926   }
927 #endif
928   /* if( pzErrMsg ){ *pzErrMsg = 0; } */
929   for(pc=0; rc==SQLITE_OK && pc<p->nOp && pc>=0; pc++){
930     pOp = &p->aOp[pc];
931 
932     /* Only allow tracing if NDEBUG is not defined.
933     */
934 #ifndef NDEBUG
935     if( p->trace ){
936       fprintf(p->trace,"%4d %-12s %4d %4d %s\n",
937         pc, zOpName[pOp->opcode], pOp->p1, pOp->p2,
938            pOp->p3 ? pOp->p3 : "");
939     }
940 #endif
941 
942     switch( pOp->opcode ){
943       /* Opcode:  Goto P2 * *
944       **
945       ** An unconditional jump to address P2.
946       ** The next instruction executed will be
947       ** the one at index P2 from the beginning of
948       ** the program.
949       */
950       case OP_Goto: {
951         pc = pOp->p2 - 1;
952         break;
953       }
954 
955       /* Opcode:  Halt * * *
956       **
957       ** Exit immediately.  All open DBs, Lists, Sorts, etc are closed
958       ** automatically.
959       */
960       case OP_Halt: {
961         pc = p->nOp-1;
962         break;
963       }
964 
965       /* Opcode: Integer P1 * *
966       **
967       ** The integer value P1 is pushed onto the stack.
968       */
969       case OP_Integer: {
970         int i = ++p->tos;
971         if( NeedStack(p, p->tos) ) goto no_mem;
972         p->aStack[i].i = pOp->p1;
973         p->aStack[i].flags = STK_Int;
974         break;
975       }
976 
977       /* Opcode: String * * P3
978       **
979       ** The string value P3 is pushed onto the stack.
980       */
981       case OP_String: {
982         int i = ++p->tos;
983         char *z;
984         if( NeedStack(p, p->tos) ) goto no_mem;
985         z = pOp->p3;
986         if( z==0 ) z = "";
987         p->zStack[i] = z;
988         p->aStack[i].n = strlen(z) + 1;
989         p->aStack[i].flags = STK_Str;
990         break;
991       }
992 
993       /* Opcode: Null * * *
994       **
995       ** Push a NULL value onto the stack.
996       */
997       case OP_Null: {
998         int i = ++p->tos;
999         if( NeedStack(p, p->tos) ) goto no_mem;
1000         p->zStack[i] = 0;
1001         p->aStack[i].flags = STK_Null;
1002         break;
1003       }
1004 
1005       /* Opcode: Pop P1 * *
1006       **
1007       ** P1 elements are popped off of the top of stack and discarded.
1008       */
1009       case OP_Pop: {
1010         PopStack(p, pOp->p1);
1011         break;
1012       }
1013 
1014       /* Opcode: Dup P1 * *
1015       **
1016       ** A copy of the P1-th element of the stack
1017       ** is made and pushed onto the top of the stack.
1018       ** The top of the stack is element 0.  So the
1019       ** instruction "Dup 0 0 0" will make a copy of the
1020       ** top of the stack.
1021       */
1022       case OP_Dup: {
1023         int i = p->tos - pOp->p1;
1024         int j = ++p->tos;
1025         if( i<0 ) goto not_enough_stack;
1026         if( NeedStack(p, p->tos) ) goto no_mem;
1027         p->aStack[j] = p->aStack[i];
1028         if( p->aStack[i].flags & STK_Dyn ){
1029           p->zStack[j] = sqliteMalloc( p->aStack[j].n );
1030           if( p->zStack[j]==0 ) goto no_mem;
1031           memcpy(p->zStack[j], p->zStack[i], p->aStack[j].n);
1032         }else{
1033           p->zStack[j] = p->zStack[i];
1034         }
1035         break;
1036       }
1037 
1038       /* Opcode: Pull P1 * *
1039       **
1040       ** The P1-th element is removed from its current location on
1041       ** the stack and pushed back on top of the stack.  The
1042       ** top of the stack is element 0, so "Pull 0 0 0" is
1043       ** a no-op.
1044       */
1045       case OP_Pull: {
1046         int from = p->tos - pOp->p1;
1047         int to = p->tos;
1048         int i;
1049         Stack ts;
1050         char *tz;
1051         if( from<0 ) goto not_enough_stack;
1052         ts = p->aStack[from];
1053         tz = p->zStack[from];
1054         for(i=from; i<to; i++){
1055           p->aStack[i] = p->aStack[i+1];
1056           p->zStack[i] = p->zStack[i+1];
1057         }
1058         p->aStack[to] = ts;
1059         p->zStack[to] = tz;
1060         break;
1061       }
1062 
1063       /* Opcode: ColumnCount P1 * *
1064       **
1065       ** Specify the number of column values that will appear in the
1066       ** array passed as the 4th parameter to the callback.  No checking
1067       ** is done.  If this value is wrong, a coredump can result.
1068       */
1069       case OP_ColumnCount: {
1070         p->azColName = sqliteRealloc(p->azColName, (pOp->p1+1)*sizeof(char*));
1071         if( p->azColName==0 ) goto no_mem;
1072         p->azColName[pOp->p1] = 0;
1073         break;
1074       }
1075 
1076       /* Opcode: ColumnName P1 * P3
1077       **
1078       ** P3 becomes the P1-th column name (first is 0).  An array of pointers
1079       ** to all column names is passed as the 4th parameter to the callback.
1080       ** The ColumnCount opcode must be executed first to allocate space to
1081       ** hold the column names.  Failure to do this will likely result in
1082       ** a coredump.
1083       */
1084       case OP_ColumnName: {
1085         p->azColName[pOp->p1] = pOp->p3 ? pOp->p3 : "";
1086         break;
1087       }
1088 
1089       /* Opcode: Callback P1 * *
1090       **
1091       ** Pop P1 values off the stack and form them into an array.  Then
1092       ** invoke the callback function using the newly formed array as the
1093       ** 3rd parameter.
1094       */
1095       case OP_Callback: {
1096         int i = p->tos - pOp->p1 + 1;
1097         int j;
1098         if( i<0 ) goto not_enough_stack;
1099         if( NeedStack(p, p->tos+2) ) goto no_mem;
1100         for(j=i; j<=p->tos; j++){
1101           if( (p->aStack[j].flags & STK_Null)==0 ){
1102             if( Stringify(p, j) ) goto no_mem;
1103           }
1104         }
1105         p->zStack[p->tos+1] = 0;
1106         if( xCallback!=0 ){
1107           if( xCallback(pArg, pOp->p1, &p->zStack[i], p->azColName)!=0 ){
1108             rc = SQLITE_ABORT;
1109           }
1110         }
1111         PopStack(p, pOp->p1);
1112         break;
1113       }
1114 
1115       /* Opcode: Concat P1 P2 P3
1116       **
1117       ** Look at the first P1 elements of the stack.  Append them all
1118       ** together with the lowest element first.  Use P3 as a separator.
1119       ** Put the result on the top of the stack.  The original P1 elements
1120       ** are popped from the stack if P2==0 and retained if P2==1.
1121       **
1122       ** If P3 is NULL, then use no separator.  When P1==1, this routine
1123       ** makes a copy of the top stack element into memory obtained
1124       ** from sqliteMalloc().
1125       */
1126       case OP_Concat: {
1127         char *zNew;
1128         int nByte;
1129         int nField;
1130         int i, j;
1131         char *zSep;
1132         int nSep;
1133 
1134         nField = pOp->p1;
1135         zSep = pOp->p3;
1136         if( zSep==0 ) zSep = "";
1137         nSep = strlen(zSep);
1138         if( p->tos+1<nField ) goto not_enough_stack;
1139         nByte = 1 - nSep;
1140         for(i=p->tos-nField+1; i<=p->tos; i++){
1141           if( p->aStack[i].flags & STK_Null ){
1142             nByte += nSep;
1143           }else{
1144             if( Stringify(p, i) ) goto no_mem;
1145             nByte += p->aStack[i].n - 1 + nSep;
1146           }
1147         }
1148         zNew = sqliteMalloc( nByte );
1149         if( zNew==0 ) goto no_mem;
1150         j = 0;
1151         for(i=p->tos-nField+1; i<=p->tos; i++){
1152           if( (p->aStack[i].flags & STK_Null)==0 ){
1153             memcpy(&zNew[j], p->zStack[i], p->aStack[i].n-1);
1154             j += p->aStack[i].n-1;
1155           }
1156           if( nSep>0 && i<p->tos ){
1157             memcpy(&zNew[j], zSep, nSep);
1158             j += nSep;
1159           }
1160         }
1161         zNew[j] = 0;
1162         if( pOp->p2==0 ) PopStack(p, nField);
1163         NeedStack(p, p->tos+1);
1164         p->tos++;
1165         p->aStack[p->tos].n = nByte;
1166         p->aStack[p->tos].flags = STK_Str|STK_Dyn;
1167         p->zStack[p->tos] = zNew;
1168         break;
1169       }
1170 
1171       /* Opcode: Add * * *
1172       **
1173       ** Pop the top two elements from the stack, add them together,
1174       ** and push the result back onto the stack.  If either element
1175       ** is a string then it is converted to a double using the atof()
1176       ** function before the addition.
1177       */
1178       /* Opcode: Multiply * * *
1179       **
1180       ** Pop the top two elements from the stack, multiply them together,
1181       ** and push the result back onto the stack.  If either element
1182       ** is a string then it is converted to a double using the atof()
1183       ** function before the multiplication.
1184       */
1185       /* Opcode: Subtract * * *
1186       **
1187       ** Pop the top two elements from the stack, subtract the
1188       ** first (what was on top of the stack) from the second (the
1189       ** next on stack)
1190       ** and push the result back onto the stack.  If either element
1191       ** is a string then it is converted to a double using the atof()
1192       ** function before the subtraction.
1193       */
1194       /* Opcode: Divide * * *
1195       **
1196       ** Pop the top two elements from the stack, divide the
1197       ** first (what was on top of the stack) from the second (the
1198       ** next on stack)
1199       ** and push the result back onto the stack.  If either element
1200       ** is a string then it is converted to a double using the atof()
1201       ** function before the division.  Division by zero returns NULL.
1202       */
1203       case OP_Add:
1204       case OP_Subtract:
1205       case OP_Multiply:
1206       case OP_Divide: {
1207         int tos = p->tos;
1208         int nos = tos - 1;
1209         if( nos<0 ) goto not_enough_stack;
1210         if( (p->aStack[tos].flags & p->aStack[nos].flags & STK_Int)==STK_Int ){
1211           int a, b;
1212           a = p->aStack[tos].i;
1213           b = p->aStack[nos].i;
1214           switch( pOp->opcode ){
1215             case OP_Add:         b += a;       break;
1216             case OP_Subtract:    b -= a;       break;
1217             case OP_Multiply:    b *= a;       break;
1218             default: {
1219               if( a==0 ) goto divide_by_zero;
1220               b /= a;
1221               break;
1222             }
1223           }
1224           PopStack(p, 2);
1225           p->tos = nos;
1226           p->aStack[nos].i = b;
1227           p->aStack[nos].flags = STK_Int;
1228         }else{
1229           double a, b;
1230           Realify(p, tos);
1231           Realify(p, nos);
1232           a = p->aStack[tos].r;
1233           b = p->aStack[nos].r;
1234           switch( pOp->opcode ){
1235             case OP_Add:         b += a;       break;
1236             case OP_Subtract:    b -= a;       break;
1237             case OP_Multiply:    b *= a;       break;
1238             default: {
1239               if( a==0.0 ) goto divide_by_zero;
1240               b /= a;
1241               break;
1242             }
1243           }
1244           PopStack(p, 1);
1245           Release(p, nos);
1246           p->aStack[nos].r = b;
1247           p->aStack[nos].flags = STK_Real;
1248         }
1249         break;
1250 
1251       divide_by_zero:
1252         PopStack(p, 2);
1253         p->tos = nos;
1254         p->aStack[nos].flags = STK_Null;
1255         break;
1256       }
1257 
1258       /* Opcode: Max * * *
1259       **
1260       ** Pop the top two elements from the stack then push back the
1261       ** largest of the two.
1262       */
1263       case OP_Max: {
1264         int tos = p->tos;
1265         int nos = tos - 1;
1266         int ft, fn;
1267         int copy = 0;
1268         if( nos<0 ) goto not_enough_stack;
1269         ft = p->aStack[tos].flags;
1270         fn = p->aStack[nos].flags;
1271         if( fn & STK_Null ){
1272           copy = 1;
1273         }else if( (ft & fn & STK_Int)==STK_Int ){
1274           copy = p->aStack[nos].i<p->aStack[tos].i;
1275         }else if( ( (ft|fn) & (STK_Int|STK_Real) ) !=0 ){
1276           Realify(p, tos);
1277           Realify(p, nos);
1278           copy = p->aStack[tos].r>p->aStack[nos].r;
1279         }else{
1280           Stringify(p, tos);
1281           Stringify(p, nos);
1282           copy = sqliteCompare(p->zStack[tos],p->zStack[nos])>0;
1283         }
1284         if( copy ){
1285           Release(p, nos);
1286           p->aStack[nos] = p->aStack[tos];
1287           p->zStack[nos] = p->zStack[tos];
1288           p->zStack[tos] = 0;
1289           p->aStack[tos].flags = 0;
1290         }else{
1291           Release(p, tos);
1292         }
1293         p->tos = nos;
1294         break;
1295       }
1296 
1297       /* Opcode: Min * * *
1298       **
1299       ** Pop the top two elements from the stack then push back the
1300       ** smaller of the two.
1301       */
1302       case OP_Min: {
1303         int tos = p->tos;
1304         int nos = tos - 1;
1305         int ft, fn;
1306         int copy = 0;
1307         if( nos<0 ) goto not_enough_stack;
1308         ft = p->aStack[tos].flags;
1309         fn = p->aStack[nos].flags;
1310         if( fn & STK_Null ){
1311           copy = 1;
1312         }else if( ft & STK_Null ){
1313           copy = 0;
1314         }else if( (ft & fn & STK_Int)==STK_Int ){
1315           copy = p->aStack[nos].i>p->aStack[tos].i;
1316         }else if( ( (ft|fn) & (STK_Int|STK_Real) ) !=0 ){
1317           Realify(p, tos);
1318           Realify(p, nos);
1319           copy = p->aStack[tos].r<p->aStack[nos].r;
1320         }else{
1321           Stringify(p, tos);
1322           Stringify(p, nos);
1323           copy = sqliteCompare(p->zStack[tos],p->zStack[nos])<0;
1324         }
1325         if( copy ){
1326           Release(p, nos);
1327           p->aStack[nos] = p->aStack[tos];
1328           p->zStack[nos] = p->zStack[tos];
1329           p->zStack[tos] = 0;
1330           p->aStack[tos].flags = 0;
1331         }else{
1332           Release(p, tos);
1333         }
1334         p->tos = nos;
1335         break;
1336       }
1337 
1338       /* Opcode: AddImm  P1 * *
1339       **
1340       ** Add the value P1 to whatever is on top of the stack.
1341       */
1342       case OP_AddImm: {
1343         int tos = p->tos;
1344         if( tos<0 ) goto not_enough_stack;
1345         Integerify(p, tos);
1346         p->aStack[tos].i += pOp->p1;
1347         break;
1348       }
1349 
1350       /* Opcode: Eq * P2 *
1351       **
1352       ** Pop the top two elements from the stack.  If they are equal, then
1353       ** jump to instruction P2.  Otherwise, continue to the next instruction.
1354       */
1355       /* Opcode: Ne * P2 *
1356       **
1357       ** Pop the top two elements from the stack.  If they are not equal, then
1358       ** jump to instruction P2.  Otherwise, continue to the next instruction.
1359       */
1360       /* Opcode: Lt * P2 *
1361       **
1362       ** Pop the top two elements from the stack.  If second element (the
1363       ** next on stack) is less than the first (the top of stack), then
1364       ** jump to instruction P2.  Otherwise, continue to the next instruction.
1365       ** In other words, jump if NOS<TOS.
1366       */
1367       /* Opcode: Le * P2 *
1368       **
1369       ** Pop the top two elements from the stack.  If second element (the
1370       ** next on stack) is less than or equal to the first (the top of stack),
1371       ** then jump to instruction P2. In other words, jump if NOS<=TOS.
1372       */
1373       /* Opcode: Gt * P2 *
1374       **
1375       ** Pop the top two elements from the stack.  If second element (the
1376       ** next on stack) is greater than the first (the top of stack),
1377       ** then jump to instruction P2. In other words, jump if NOS>TOS.
1378       */
1379       /* Opcode: Ge * P2 *
1380       **
1381       ** Pop the top two elements from the stack.  If second element (the next
1382       ** on stack) is greater than or equal to the first (the top of stack),
1383       ** then jump to instruction P2. In other words, jump if NOS>=TOS.
1384       */
1385       case OP_Eq:
1386       case OP_Ne:
1387       case OP_Lt:
1388       case OP_Le:
1389       case OP_Gt:
1390       case OP_Ge: {
1391         int tos = p->tos;
1392         int nos = tos - 1;
1393         int c;
1394         int ft, fn;
1395         if( nos<0 ) goto not_enough_stack;
1396         ft = p->aStack[tos].flags;
1397         fn = p->aStack[nos].flags;
1398         if( (ft & fn)==STK_Int ){
1399           c = p->aStack[nos].i - p->aStack[tos].i;
1400         }else{
1401           Stringify(p, tos);
1402           Stringify(p, nos);
1403           c = sqliteCompare(p->zStack[nos], p->zStack[tos]);
1404         }
1405         switch( pOp->opcode ){
1406           case OP_Eq:    c = c==0;     break;
1407           case OP_Ne:    c = c!=0;     break;
1408           case OP_Lt:    c = c<0;      break;
1409           case OP_Le:    c = c<=0;     break;
1410           case OP_Gt:    c = c>0;      break;
1411           default:       c = c>=0;     break;
1412         }
1413         PopStack(p, 2);
1414         if( c ) pc = pOp->p2-1;
1415         break;
1416       }
1417 
1418       /* Opcode: Like P1 P2 *
1419       **
1420       ** Pop the top two elements from the stack.  The top-most is a
1421       ** "like" pattern -- the right operand of the SQL "LIKE" operator.
1422       ** The lower element is the string to compare against the like
1423       ** pattern.  Jump to P2 if the two compare, and fall through without
1424       ** jumping if they do not.  The '%' in the top-most element matches
1425       ** any sequence of zero or more characters in the lower element.  The
1426       ** '_' character in the topmost matches any single character of the
1427       ** lower element.  Case is ignored for this comparison.
1428       **
1429       ** If P1 is not zero, the sense of the test is inverted and we
1430       ** have a "NOT LIKE" operator.  The jump is made if the two values
1431       ** are different.
1432       */
1433       case OP_Like: {
1434         int tos = p->tos;
1435         int nos = tos - 1;
1436         int c;
1437         if( nos<0 ) goto not_enough_stack;
1438         Stringify(p, tos);
1439         Stringify(p, nos);
1440         c = sqliteLikeCompare(p->zStack[tos], p->zStack[nos]);
1441         PopStack(p, 2);
1442         if( pOp->p1 ) c = !c;
1443         if( c ) pc = pOp->p2-1;
1444         break;
1445       }
1446 
1447       /* Opcode: Glob P1 P2 *
1448       **
1449       ** Pop the top two elements from the stack.  The top-most is a
1450       ** "glob" pattern.  The lower element is the string to compare
1451       ** against the glob pattern.
1452       **
1453       ** Jump to P2 if the two compare, and fall through without
1454       ** jumping if they do not.  The '*' in the top-most element matches
1455       ** any sequence of zero or more characters in the lower element.  The
1456       ** '?' character in the topmost matches any single character of the
1457       ** lower element.  [...] matches a range of characters.  [^...]
1458       ** matches any character not in the range.  Case is significant
1459       ** for globs.
1460       **
1461       ** If P1 is not zero, the sense of the test is inverted and we
1462       ** have a "NOT GLOB" operator.  The jump is made if the two values
1463       ** are different.
1464       */
1465       case OP_Glob: {
1466         int tos = p->tos;
1467         int nos = tos - 1;
1468         int c;
1469         if( nos<0 ) goto not_enough_stack;
1470         Stringify(p, tos);
1471         Stringify(p, nos);
1472         c = sqliteGlobCompare(p->zStack[tos], p->zStack[nos]);
1473         PopStack(p, 2);
1474         if( pOp->p1 ) c = !c;
1475         if( c ) pc = pOp->p2-1;
1476         break;
1477       }
1478 
1479       /* Opcode: And * * *
1480       **
1481       ** Pop two values off the stack.  Take the logical AND of the
1482       ** two values and push the resulting boolean value back onto the
1483       ** stack.
1484       */
1485       /* Opcode: Or * * *
1486       **
1487       ** Pop two values off the stack.  Take the logical OR of the
1488       ** two values and push the resulting boolean value back onto the
1489       ** stack.
1490       */
1491       case OP_And:
1492       case OP_Or: {
1493         int tos = p->tos;
1494         int nos = tos - 1;
1495         int c;
1496         if( nos<0 ) goto not_enough_stack;
1497         Integerify(p, tos);
1498         Integerify(p, nos);
1499         if( pOp->opcode==OP_And ){
1500           c = p->aStack[tos].i && p->aStack[nos].i;
1501         }else{
1502           c = p->aStack[tos].i || p->aStack[nos].i;
1503         }
1504         PopStack(p, 2);
1505         p->tos++;
1506         p->aStack[nos].i = c;
1507         p->aStack[nos].flags = STK_Int;
1508         break;
1509       }
1510 
1511       /* Opcode: Negative * * *
1512       **
1513       ** Treat the top of the stack as a numeric quantity.  Replace it
1514       ** with its additive inverse.
1515       */
1516       case OP_Negative: {
1517         int tos;
1518         if( (tos = p->tos)<0 ) goto not_enough_stack;
1519         if( p->aStack[tos].flags & STK_Real ){
1520           Release(p, tos);
1521           p->aStack[tos].r = -p->aStack[tos].r;
1522           p->aStack[tos].flags = STK_Real;
1523         }else if( p->aStack[tos].flags & STK_Int ){
1524           Release(p, tos);
1525           p->aStack[tos].i = -p->aStack[tos].i;
1526           p->aStack[tos].flags = STK_Int;
1527         }else{
1528           Realify(p, tos);
1529           Release(p, tos);
1530           p->aStack[tos].r = -p->aStack[tos].r;
1531           p->aStack[tos].flags = STK_Real;
1532         }
1533         break;
1534       }
1535 
1536       /* Opcode: Not * * *
1537       **
1538       ** Interpret the top of the stack as a boolean value.  Replace it
1539       ** with its complement.
1540       */
1541       case OP_Not: {
1542         int tos = p->tos;
1543         if( p->tos<0 ) goto not_enough_stack;
1544         Integerify(p, tos);
1545         Release(p, tos);
1546         p->aStack[tos].i = !p->aStack[tos].i;
1547         p->aStack[tos].flags = STK_Int;
1548         break;
1549       }
1550 
1551       /* Opcode: Noop * * *
1552       **
1553       ** Do nothing.  This instruction is often useful as a jump
1554       ** destination.
1555       */
1556       case OP_Noop: {
1557         break;
1558       }
1559 
1560       /* Opcode: If * P2 *
1561       **
1562       ** Pop a single boolean from the stack.  If the boolean popped is
1563       ** true, then jump to p2.  Otherwise continue to the next instruction.
1564       ** An integer is false if zero and true otherwise.  A string is
1565       ** false if it has zero length and true otherwise.
1566       */
1567       case OP_If: {
1568         int c;
1569         if( p->tos<0 ) goto not_enough_stack;
1570         Integerify(p, p->tos);
1571         c = p->aStack[p->tos].i;
1572         PopStack(p, 1);
1573         if( c ) pc = pOp->p2-1;
1574         break;
1575       }
1576 
1577       /* Opcode: IsNull * P2 *
1578       **
1579       ** Pop a single value from the stack.  If the value popped is NULL
1580       ** then jump to p2.  Otherwise continue to the next
1581       ** instruction.
1582       */
1583       case OP_IsNull: {
1584         int c;
1585         if( p->tos<0 ) goto not_enough_stack;
1586         c = (p->aStack[p->tos].flags & STK_Null)!=0;
1587         PopStack(p, 1);
1588         if( c ) pc = pOp->p2-1;
1589         break;
1590       }
1591 
1592       /* Opcode: NotNull * P2 *
1593       **
1594       ** Pop a single value from the stack.  If the value popped is not an
1595       ** empty string, then jump to p2.  Otherwise continue to the next
1596       ** instruction.
1597       */
1598       case OP_NotNull: {
1599         int c;
1600         if( p->tos<0 ) goto not_enough_stack;
1601         c = (p->aStack[p->tos].flags & STK_Null)==0;
1602         PopStack(p, 1);
1603         if( c ) pc = pOp->p2-1;
1604         break;
1605       }
1606 
1607       /* Opcode: MakeRecord P1 * *
1608       **
1609       ** Convert the top P1 entries of the stack into a single entry
1610       ** suitable for use as a data record in the database.  To do this
1611       ** all entries (except NULLs) are converted to strings and
1612       ** concatenated.  The null-terminators are preserved by the concatation
1613       ** and serve as a boundry marker between fields.  The lowest entry
1614       ** on the stack is the first in the concatenation and the top of
1615       ** the stack is the last.  After all fields are concatenated, an
1616       ** index header is added.  The index header consists of P1 integers
1617       ** which hold the offset of the beginning of each field from the
1618       ** beginning of the completed record including the header.  The
1619       ** index for NULL entries is 0.
1620       */
1621       case OP_MakeRecord: {
1622         char *zNewRecord;
1623         int nByte;
1624         int nField;
1625         int i, j;
1626         int addr;
1627 
1628         nField = pOp->p1;
1629         if( p->tos+1<nField ) goto not_enough_stack;
1630         nByte = 0;
1631         for(i=p->tos-nField+1; i<=p->tos; i++){
1632           if( (p->aStack[i].flags & STK_Null)==0 ){
1633             if( Stringify(p, i) ) goto no_mem;
1634             nByte += p->aStack[i].n;
1635           }
1636         }
1637         nByte += sizeof(int)*nField;
1638         zNewRecord = sqliteMalloc( nByte );
1639         if( zNewRecord==0 ) goto no_mem;
1640         j = 0;
1641         addr = sizeof(int)*nField;
1642         for(i=p->tos-nField+1; i<=p->tos; i++){
1643           if( p->aStack[i].flags & STK_Null ){
1644             int zero = 0;
1645             memcpy(&zNewRecord[j], (char*)&zero, sizeof(int));
1646           }else{
1647             memcpy(&zNewRecord[j], (char*)&addr, sizeof(int));
1648             addr += p->aStack[i].n;
1649           }
1650           j += sizeof(int);
1651         }
1652         for(i=p->tos-nField+1; i<=p->tos; i++){
1653           if( (p->aStack[i].flags & STK_Null)==0 ){
1654             memcpy(&zNewRecord[j], p->zStack[i], p->aStack[i].n);
1655             j += p->aStack[i].n;
1656           }
1657         }
1658         PopStack(p, nField);
1659         NeedStack(p, p->tos+1);
1660         p->tos++;
1661         p->aStack[p->tos].n = nByte;
1662         p->aStack[p->tos].flags = STK_Str | STK_Dyn;
1663         p->zStack[p->tos] = zNewRecord;
1664         break;
1665       }
1666 
1667       /* Opcode: MakeKey P1 P2 *
1668       **
1669       ** Convert the top P1 entries of the stack into a single entry suitable
1670       ** for use as the key in an index or a sort.  The top P1 records are
1671       ** concatenated with a tab character (ASCII 0x09) used as a record
1672       ** separator.  The entire concatenation is null-terminated.  The
1673       ** lowest entry in the stack is the first field and the top of the
1674       ** stack becomes the last.
1675       **
1676       ** If P2 is not zero, then the original entries remain on the stack
1677       ** and the new key is pushed on top.  If P2 is zero, the original
1678       ** data is popped off the stack first then the new key is pushed
1679       ** back in its place.
1680       **
1681       ** See also the SortMakeKey opcode.
1682       */
1683       case OP_MakeKey: {
1684         char *zNewKey;
1685         int nByte;
1686         int nField;
1687         int i, j;
1688 
1689         nField = pOp->p1;
1690         if( p->tos+1<nField ) goto not_enough_stack;
1691         nByte = 0;
1692         for(i=p->tos-nField+1; i<=p->tos; i++){
1693           if( p->aStack[i].flags & STK_Null ){
1694             nByte++;
1695           }else{
1696             if( Stringify(p, i) ) goto no_mem;
1697             nByte += p->aStack[i].n;
1698           }
1699         }
1700         zNewKey = sqliteMalloc( nByte );
1701         if( zNewKey==0 ) goto no_mem;
1702         j = 0;
1703         for(i=p->tos-nField+1; i<=p->tos; i++){
1704           if( (p->aStack[i].flags & STK_Null)==0 ){
1705             memcpy(&zNewKey[j], p->zStack[i], p->aStack[i].n-1);
1706             j += p->aStack[i].n-1;
1707           }
1708           if( i<p->tos ) zNewKey[j++] = '\t';
1709         }
1710         zNewKey[j] = 0;
1711         if( pOp->p2==0 ) PopStack(p, nField);
1712         NeedStack(p, p->tos+1);
1713         p->tos++;
1714         p->aStack[p->tos].n = nByte;
1715         p->aStack[p->tos].flags = STK_Str|STK_Dyn;
1716         p->zStack[p->tos] = zNewKey;
1717         break;
1718       }
1719 
1720       /* Opcode: Open P1 P2 P3
1721       **
1722       ** Open a new cursor for the database file named P3.  Give the
1723       ** cursor an identifier P1.  The P1 values need not be
1724       ** contiguous but all P1 values should be small integers.  It is
1725       ** an error for P1 to be negative.
1726       **
1727       ** Open readonly if P2==0 and for reading and writing if P2!=0.
1728       ** The file is created if it does not already exist and P2!=0.
1729       ** If there is already another cursor opened with identifier P1,
1730       ** then the old cursor is closed first.  All cursors are
1731       ** automatically closed when the VDBE finishes execution.
1732       **
1733       ** If P3 is null or an empty string, a temporary database file
1734       ** is created.  This temporary database file is automatically
1735       ** deleted when the cursor is closed.
1736       */
1737       case OP_Open: {
1738         int busy = 0;
1739         int i = pOp->p1;
1740         if( i<0 ) goto bad_instruction;
1741         if( i>=p->nCursor ){
1742           int j;
1743           p->aCsr = sqliteRealloc( p->aCsr, (i+1)*sizeof(Cursor) );
1744           if( p->aCsr==0 ){ p->nCursor = 0; goto no_mem; }
1745           for(j=p->nCursor; j<=i; j++) p->aCsr[j].pCursor = 0;
1746           p->nCursor = i+1;
1747         }else if( p->aCsr[i].pCursor ){
1748           sqliteDbbeCloseCursor(p->aCsr[i].pCursor);
1749         }
1750         do {
1751           rc = sqliteDbbeOpenCursor(p->pBe,pOp->p3,pOp->p2,&p->aCsr[i].pCursor);
1752           switch( rc ){
1753             case SQLITE_BUSY: {
1754               if( xBusy==0 || (*xBusy)(pBusyArg, pOp->p3, ++busy)==0 ){
1755                 sqliteSetString(pzErrMsg,"table ", pOp->p3, " is locked", 0);
1756                 busy = 0;
1757               }
1758               break;
1759             }
1760             case SQLITE_PERM: {
1761               sqliteSetString(pzErrMsg, pOp->p2 ? "write" : "read",
1762                 " permission denied for table ", pOp->p3, 0);
1763               break;
1764             }
1765             case SQLITE_READONLY: {
1766               sqliteSetString(pzErrMsg,"table ", pOp->p3,
1767                  " is readonly", 0);
1768               break;
1769             }
1770             case SQLITE_NOMEM: {
1771               goto no_mem;
1772             }
1773             case SQLITE_OK: {
1774               busy = 0;
1775               break;
1776             }
1777           }
1778         }while( busy );
1779         p->aCsr[i].index = 0;
1780         p->aCsr[i].keyAsData = 0;
1781         break;
1782       }
1783 
1784       /* Opcode: Close P1 * *
1785       **
1786       ** Close a cursor previously opened as P1.  If P1 is not
1787       ** currently open, this instruction is a no-op.
1788       */
1789       case OP_Close: {
1790         int i = pOp->p1;
1791         if( i>=0 && i<p->nCursor && p->aCsr[i].pCursor ){
1792           sqliteDbbeCloseCursor(p->aCsr[i].pCursor);
1793           p->aCsr[i].pCursor = 0;
1794         }
1795         break;
1796       }
1797 
1798       /* Opcode: Fetch P1 * *
1799       **
1800       ** Pop the top of the stack and use its value as a key to fetch
1801       ** a record from cursor P1.  The key/data pair is held
1802       ** in the P1 cursor until needed.
1803       */
1804       case OP_Fetch: {
1805         int i = pOp->p1;
1806         int tos = p->tos;
1807         if( tos<0 ) goto not_enough_stack;
1808         if( i>=0 && i<p->nCursor && p->aCsr[i].pCursor ){
1809           if( p->aStack[tos].flags & STK_Int ){
1810             sqliteDbbeFetch(p->aCsr[i].pCursor, sizeof(int),
1811                            (char*)&p->aStack[tos].i);
1812           }else{
1813             if( Stringify(p, tos) ) goto no_mem;
1814             sqliteDbbeFetch(p->aCsr[i].pCursor, p->aStack[tos].n,
1815                            p->zStack[tos]);
1816           }
1817           p->nFetch++;
1818         }
1819         PopStack(p, 1);
1820         break;
1821       }
1822 
1823       /* Opcode: Fcnt * * *
1824       **
1825       ** Push an integer onto the stack which is the total number of
1826       ** OP_Fetch opcodes that have been executed by this virtual machine.
1827       **
1828       ** This instruction is used to implement the special fcnt() function
1829       ** in the SQL dialect that SQLite understands.  fcnt() is used for
1830       ** testing purposes.
1831       */
1832       case OP_Fcnt: {
1833         int i = ++p->tos;
1834         if( NeedStack(p, p->tos) ) goto no_mem;
1835         p->aStack[i].i = p->nFetch;
1836         p->aStack[i].flags = STK_Int;
1837         break;
1838       }
1839 
1840       /* Opcode: Distinct P1 P2 *
1841       **
1842       ** Use the top of the stack as a key.  If a record with that key
1843       ** does not exist in file P1, then jump to P2.  If the record
1844       ** does already exist, then fall thru.  The record is not retrieved.
1845       ** The key is not popped from the stack.
1846       **
1847       ** This operation is similar to NotFound except that this operation
1848       ** does not pop the key from the stack.
1849       */
1850       /* Opcode: Found P1 P2 *
1851       **
1852       ** Use the top of the stack as a key.  If a record with that key
1853       ** does exist in file P1, then jump to P2.  If the record
1854       ** does not exist, then fall thru.  The record is not retrieved.
1855       ** The key is popped from the stack.
1856       */
1857       /* Opcode: NotFound P1 P2 *
1858       **
1859       ** Use the top of the stack as a key.  If a record with that key
1860       ** does not exist in file P1, then jump to P2.  If the record
1861       ** does exist, then fall thru.  The record is not retrieved.
1862       ** The key is popped from the stack.
1863       **
1864       ** The difference between this operation and Distinct is that
1865       ** Distinct does not pop the key from the stack.
1866       */
1867       case OP_Distinct:
1868       case OP_NotFound:
1869       case OP_Found: {
1870         int i = pOp->p1;
1871         int tos = p->tos;
1872         int alreadyExists = 0;
1873         if( tos<0 ) goto not_enough_stack;
1874         if( i>=0 && i<p->nCursor && p->aCsr[i].pCursor ){
1875           if( p->aStack[tos].flags & STK_Int ){
1876             alreadyExists = sqliteDbbeTest(p->aCsr[i].pCursor, sizeof(int),
1877                                           (char*)&p->aStack[tos].i);
1878           }else{
1879             if( Stringify(p, tos) ) goto no_mem;
1880             alreadyExists = sqliteDbbeTest(p->aCsr[i].pCursor,p->aStack[tos].n,
1881                                            p->zStack[tos]);
1882           }
1883         }
1884         if( pOp->opcode==OP_Found ){
1885           if( alreadyExists ) pc = pOp->p2 - 1;
1886         }else{
1887           if( !alreadyExists ) pc = pOp->p2 - 1;
1888         }
1889         if( pOp->opcode!=OP_Distinct ){
1890           PopStack(p, 1);
1891         }
1892         break;
1893       }
1894 
1895       /* Opcode: New P1 * *
1896       **
1897       ** Get a new integer key not previous used by the database file
1898       ** associated with cursor P1 and push it onto the stack.
1899       */
1900       case OP_New: {
1901         int i = pOp->p1;
1902         int v;
1903         if( i<0 || i>=p->nCursor || p->aCsr[i].pCursor==0 ){
1904           v = 0;
1905         }else{
1906           v = sqliteDbbeNew(p->aCsr[i].pCursor);
1907         }
1908         NeedStack(p, p->tos+1);
1909         p->tos++;
1910         p->aStack[p->tos].i = v;
1911         p->aStack[p->tos].flags = STK_Int;
1912         break;
1913       }
1914 
1915       /* Opcode: Put P1 * *
1916       **
1917       ** Write an entry into the database file P1.  A new entry is
1918       ** created if it doesn't already exist, or the data for an existing
1919       ** entry is overwritten.  The data is the value on the top of the
1920       ** stack.  The key is the next value down on the stack.  The stack
1921       ** is popped twice by this instruction.
1922       */
1923       case OP_Put: {
1924         int tos = p->tos;
1925         int nos = p->tos-1;
1926         int i = pOp->p1;
1927         if( nos<0 ) goto not_enough_stack;
1928         if( i>=0 && i<p->nCursor && p->aCsr[i].pCursor!=0 ){
1929           char *zKey;
1930           int nKey;
1931           if( (p->aStack[nos].flags & STK_Int)==0 ){
1932             if( Stringify(p, nos) ) goto no_mem;
1933             nKey = p->aStack[nos].n;
1934             zKey = p->zStack[nos];
1935           }else{
1936             nKey = sizeof(int);
1937             zKey = (char*)&p->aStack[nos].i;
1938           }
1939           sqliteDbbePut(p->aCsr[i].pCursor, nKey, zKey,
1940                         p->aStack[tos].n, p->zStack[tos]);
1941         }
1942         PopStack(p, 2);
1943         break;
1944       }
1945 
1946       /* Opcode: Delete P1 * *
1947       **
1948       ** The top of the stack is a key.  Remove this key and its data
1949       ** from database file P1.  Then pop the stack to discard the key.
1950       */
1951       case OP_Delete: {
1952         int tos = p->tos;
1953         int i = pOp->p1;
1954         if( tos<0 ) goto not_enough_stack;
1955         if( i>=0 && i<p->nCursor && p->aCsr[i].pCursor!=0 ){
1956           char *zKey;
1957           int nKey;
1958           if( p->aStack[tos].flags & STK_Int ){
1959             nKey = sizeof(int);
1960             zKey = (char*)&p->aStack[tos].i;
1961           }else{
1962             if( Stringify(p, tos) ) goto no_mem;
1963             nKey = p->aStack[tos].n;
1964             zKey = p->zStack[tos];
1965           }
1966           sqliteDbbeDelete(p->aCsr[i].pCursor, nKey, zKey);
1967         }
1968         PopStack(p, 1);
1969         break;
1970       }
1971 
1972       /* Opcode: KeyAsData P1 P2 *
1973       **
1974       ** Turn the key-as-data mode for cursor P1 either on (if P2==1) or
1975       ** off (if P2==0).  In key-as-data mode, the OP_Field opcode pulls
1976       ** data off of the key rather than the data.  This is useful for
1977       ** processing compound selects.
1978       */
1979       case OP_KeyAsData: {
1980         int i = pOp->p1;
1981         if( i>=0 && i<p->nCursor && p->aCsr[i].pCursor!=0 ){
1982           p->aCsr[i].keyAsData = pOp->p2;
1983         }
1984         break;
1985       }
1986 
1987       /* Opcode: Field P1 P2 *
1988       **
1989       ** Interpret the data in the most recent fetch from cursor P1
1990       ** is a structure built using the MakeRecord instruction.
1991       ** Push onto the stack the value of the P2-th field of that
1992       ** structure.
1993       **
1994       ** The value pushed is just a pointer to the data in the cursor.
1995       ** The value will go away the next time a record is fetched from P1,
1996       ** or when P1 is closed.  Make a copy of the string (using
1997       ** "Concat 1 0 0") if it needs to persist longer than that.
1998       **
1999       ** If the KeyAsData opcode has previously executed on this cursor,
2000       ** then the field might be extracted from the key rather than the
2001       ** data.
2002       **
2003       ** Viewed from a higher level, this instruction retrieves the
2004       ** data from a single column in a particular row of an SQL table
2005       ** file.  Perhaps the name of this instruction should be
2006       ** "Column" instead of "Field"...
2007       */
2008       case OP_Field: {
2009         int *pAddr;
2010         int amt;
2011         int i = pOp->p1;
2012         int p2 = pOp->p2;
2013         int tos = ++p->tos;
2014         DbbeCursor *pCrsr;
2015         char *z;
2016 
2017         if( NeedStack(p, tos) ) goto no_mem;
2018         if( i>=0 && i<p->nCursor && (pCrsr = p->aCsr[i].pCursor)!=0 ){
2019           if( p->aCsr[i].keyAsData ){
2020             amt = sqliteDbbeKeyLength(pCrsr);
2021             if( amt<=sizeof(int)*(p2+1) ){
2022               p->aStack[tos].flags = STK_Null;
2023               break;
2024             }
2025             pAddr = (int*)sqliteDbbeReadKey(pCrsr, sizeof(int)*p2);
2026             if( *pAddr==0 ){
2027               p->aStack[tos].flags = STK_Null;
2028               break;
2029             }
2030             z = sqliteDbbeReadKey(pCrsr, *pAddr);
2031           }else{
2032             amt = sqliteDbbeDataLength(pCrsr);
2033             if( amt<=sizeof(int)*(p2+1) ){
2034               p->aStack[tos].flags = STK_Null;
2035               break;
2036             }
2037             pAddr = (int*)sqliteDbbeReadData(pCrsr, sizeof(int)*p2);
2038             if( *pAddr==0 ){
2039               p->aStack[tos].flags = STK_Null;
2040               break;
2041             }
2042             z = sqliteDbbeReadData(pCrsr, *pAddr);
2043           }
2044           p->zStack[tos] = z;
2045           p->aStack[tos].n = strlen(z) + 1;
2046           p->aStack[tos].flags = STK_Str;
2047         }
2048         break;
2049       }
2050 
2051       /* Opcode: Key P1 * *
2052       **
2053       ** Push onto the stack an integer which is the first 4 bytes of the
2054       ** the key to the current entry in a sequential scan of the database
2055       ** file P1.  The sequential scan should have been started using the
2056       ** Next opcode.
2057       */
2058       case OP_Key: {
2059         int i = pOp->p1;
2060         int tos = ++p->tos;
2061         DbbeCursor *pCrsr;
2062 
2063         if( NeedStack(p, p->tos) ) goto no_mem;
2064         if( i>=0 && i<p->nCursor && (pCrsr = p->aCsr[i].pCursor)!=0 ){
2065           char *z = sqliteDbbeReadKey(pCrsr, 0);
2066           if( p->aCsr[i].keyAsData ){
2067             p->zStack[tos] = z;
2068             p->aStack[tos].flags = STK_Str;
2069             p->aStack[tos].n = sqliteDbbeKeyLength(pCrsr);
2070           }else{
2071             memcpy(&p->aStack[tos].i, z, sizeof(int));
2072             p->aStack[tos].flags = STK_Int;
2073           }
2074         }
2075         break;
2076       }
2077 
2078       /* Opcode: Rewind P1 * *
2079       **
2080       ** The next use of the Key or Field or Next instruction for P1
2081       ** will refer to the first entry in the database file.
2082       */
2083       case OP_Rewind: {
2084         int i = pOp->p1;
2085         if( i>=0 && i<p->nCursor && p->aCsr[i].pCursor!=0 ){
2086           sqliteDbbeRewind(p->aCsr[i].pCursor);
2087         }
2088         break;
2089       }
2090 
2091       /* Opcode: Next P1 P2 *
2092       **
2093       ** Advance P1 to the next key/data pair in the file.  Or, if there are no
2094       ** more key/data pairs, rewind P1 and jump to location P2.
2095       */
2096       case OP_Next: {
2097         int i = pOp->p1;
2098         if( i>=0 && i<p->nCursor && p->aCsr[i].pCursor!=0 ){
2099           if( sqliteDbbeNextKey(p->aCsr[i].pCursor)==0 ){
2100             pc = pOp->p2 - 1;
2101           }else{
2102             p->nFetch++;
2103           }
2104         }
2105         break;
2106       }
2107 
2108       /* Opcode: ResetIdx P1 * *
2109       **
2110       ** Begin treating the current data in cursor P1 as a bunch of integer
2111       ** keys to records of a (separate) SQL table file.  This instruction
2112       ** causes the new NextIdx instruction push the first integer table
2113       ** key in the data.
2114       */
2115       case OP_ResetIdx: {
2116         int i = pOp->p1;
2117         if( i>=0 && i<p->nCursor ){
2118           p->aCsr[i].index = 0;
2119         }
2120         break;
2121       }
2122 
2123       /* Opcode: NextIdx P1 P2 *
2124       **
2125       ** The P1 cursor points to an SQL index.  The data from the most
2126       ** recent fetch on that cursor consists of a bunch of integers where
2127       ** each integer is the key to a record in an SQL table file.
2128       ** This instruction grabs the next integer table key from the data
2129       ** of P1 and pushes that integer onto the stack.  The first time
2130       ** this instruction is executed after a fetch, the first integer
2131       ** table key is pushed.  Subsequent integer table keys are pushed
2132       ** in each subsequent execution of this instruction.
2133       **
2134       ** If there are no more integer table keys in the data of P1
2135       ** when this instruction is executed, then nothing gets pushed and
2136       ** there is an immediate jump to instruction P2.
2137       */
2138       case OP_NextIdx: {
2139         int i = pOp->p1;
2140         int tos = ++p->tos;
2141         DbbeCursor *pCrsr;
2142 
2143         if( NeedStack(p, p->tos) ) goto no_mem;
2144         p->zStack[tos] = 0;
2145         if( i>=0 && i<p->nCursor && (pCrsr = p->aCsr[i].pCursor)!=0 ){
2146           int *aIdx;
2147           int nIdx;
2148           int j, k;
2149           nIdx = sqliteDbbeDataLength(pCrsr)/sizeof(int);
2150           aIdx = (int*)sqliteDbbeReadData(pCrsr, 0);
2151           if( nIdx>1 ){
2152             k = *(aIdx++);
2153             if( k>nIdx-1 ) k = nIdx-1;
2154           }else{
2155             k = nIdx;
2156           }
2157           for(j=p->aCsr[i].index; j<k; j++){
2158             if( aIdx[j]!=0 ){
2159               p->aStack[tos].i = aIdx[j];
2160               p->aStack[tos].flags = STK_Int;
2161               break;
2162             }
2163           }
2164           if( j>=k ){
2165             j = -1;
2166             pc = pOp->p2 - 1;
2167             PopStack(p, 1);
2168           }
2169           p->aCsr[i].index = j+1;
2170         }
2171         break;
2172       }
2173 
2174       /* Opcode: PutIdx P1 * *
2175       **
2176       ** The top of the stack hold an SQL index key (probably made using the
2177       ** MakeKey instruction) and next on stack holds an integer which
2178       ** the key to an SQL table entry.  Locate the record in cursor P1
2179       ** that has the same key as on the TOS.  Create a new record if
2180       ** necessary.  Then append the integer table key to the data for that
2181       ** record and write it back to the P1 file.
2182       */
2183       case OP_PutIdx: {
2184         int i = pOp->p1;
2185         int tos = p->tos;
2186         int nos = tos - 1;
2187         DbbeCursor *pCrsr;
2188         if( nos<0 ) goto not_enough_stack;
2189         if( i>=0 && i<p->nCursor && (pCrsr = p->aCsr[i].pCursor)!=0 ){
2190           int r;
2191           int newVal;
2192           Integerify(p, nos);
2193           newVal = p->aStack[nos].i;
2194           if( Stringify(p, tos) ) goto no_mem;
2195           r = sqliteDbbeFetch(pCrsr, p->aStack[tos].n, p->zStack[tos]);
2196           if( r==0 ){
2197             /* Create a new record for this index */
2198             sqliteDbbePut(pCrsr, p->aStack[tos].n, p->zStack[tos],
2199                           sizeof(int), (char*)&newVal);
2200           }else{
2201             /* Extend the existing record */
2202             int nIdx;
2203             int *aIdx;
2204             int k;
2205 
2206             nIdx = sqliteDbbeDataLength(pCrsr)/sizeof(int);
2207             if( nIdx==1 ){
2208               aIdx = sqliteMalloc( sizeof(int)*4 );
2209               if( aIdx==0 ) goto no_mem;
2210               aIdx[0] = 2;
2211               sqliteDbbeCopyData(pCrsr, 0, sizeof(int), (char*)&aIdx[1]);
2212               aIdx[2] = newVal;
2213               sqliteDbbePut(pCrsr, p->aStack[tos].n, p->zStack[tos],
2214                     sizeof(int)*4, (char*)aIdx);
2215               sqliteFree(aIdx);
2216             }else{
2217               aIdx = (int*)sqliteDbbeReadData(pCrsr, 0);
2218               k = aIdx[0];
2219               if( k<nIdx-1 ){
2220                 aIdx[k+1] = newVal;
2221                 aIdx[0]++;
2222                 sqliteDbbePut(pCrsr, p->aStack[tos].n, p->zStack[tos],
2223                     sizeof(int)*nIdx, (char*)aIdx);
2224               }else{
2225                 nIdx *= 2;
2226                 aIdx = sqliteMalloc( sizeof(int)*nIdx );
2227                 if( aIdx==0 ) goto no_mem;
2228                 sqliteDbbeCopyData(pCrsr, 0, sizeof(int)*(k+1), (char*)aIdx);
2229                 aIdx[k+1] = newVal;
2230                 aIdx[0]++;
2231                 sqliteDbbePut(pCrsr, p->aStack[tos].n, p->zStack[tos],
2232                       sizeof(int)*nIdx, (char*)aIdx);
2233                 sqliteFree(aIdx);
2234               }
2235             }
2236           }
2237         }
2238         PopStack(p, 2);
2239         break;
2240       }
2241 
2242       /* Opcode: DeleteIdx P1 * *
2243       **
2244       ** The top of the stack is a key and next on stack is integer
2245       ** which is the key to a record in an SQL table.
2246       ** Locate the record in the cursor P1 (P1 represents an SQL index)
2247       ** that has the same key as the top of stack.  Then look through
2248       ** the integer table-keys contained in the data of the P1 record.
2249       ** Remove the integer table-key that matches the NOS and write the
2250       ** revised data back to P1 with the same key.
2251       **
2252       ** If this routine removes the very last integer table-key from
2253       ** the P1 data, then the corresponding P1 record is deleted.
2254       */
2255       case OP_DeleteIdx: {
2256         int i = pOp->p1;
2257         int tos = p->tos;
2258         int nos = tos - 1;
2259         DbbeCursor *pCrsr;
2260         if( nos<0 ) goto not_enough_stack;
2261         if( i>=0 && i<p->nCursor && (pCrsr = p->aCsr[i].pCursor)!=0 ){
2262           int *aIdx;
2263           int nIdx;
2264           int j, k;
2265           int r;
2266           int oldVal;
2267           Integerify(p, nos);
2268           oldVal = p->aStack[nos].i;
2269           if( Stringify(p, tos) ) goto no_mem;
2270           r = sqliteDbbeFetch(pCrsr, p->aStack[tos].n, p->zStack[tos]);
2271           if( r==0 ) break;
2272           nIdx = sqliteDbbeDataLength(pCrsr)/sizeof(int);
2273           aIdx = (int*)sqliteDbbeReadData(pCrsr, 0);
2274           if( (nIdx==1 && aIdx[0]==oldVal) || (aIdx[0]==1 && aIdx[1]==oldVal) ){
2275             sqliteDbbeDelete(pCrsr, p->aStack[tos].n, p->zStack[tos]);
2276           }else{
2277             k = aIdx[0];
2278             for(j=1; j<=k && aIdx[j]!=oldVal; j++){}
2279             if( j>k ) break;
2280             aIdx[j] = aIdx[k];
2281             aIdx[k] = 0;
2282             aIdx[0]--;
2283             if( aIdx[0]*3 + 1 < nIdx ){
2284               nIdx /= 2;
2285             }
2286             sqliteDbbePut(pCrsr, p->aStack[tos].n, p->zStack[tos],
2287                           sizeof(int)*nIdx, (char*)aIdx);
2288           }
2289         }
2290         PopStack(p, 2);
2291         break;
2292       }
2293 
2294       /* Opcode: Destroy * * P3
2295       **
2296       ** Drop the disk file whose name is P3.  All key/data pairs in
2297       ** the file are deleted and the file itself is removed
2298       ** from the disk.
2299       */
2300       case OP_Destroy: {
2301         sqliteDbbeDropTable(p->pBe, pOp->p3);
2302         break;
2303       }
2304 
2305       /* Opcode: Reorganize * * P3
2306       **
2307       ** Compress, optimize, and tidy up the GDBM file named by P3.
2308       */
2309       case OP_Reorganize: {
2310         sqliteDbbeReorganizeTable(p->pBe, pOp->p3);
2311         break;
2312       }
2313 
2314       /* Opcode: ListOpen P1 * *
2315       **
2316       ** Open a file used for temporary storage of integer table keys.  P1
2317       ** will server as a handle to this temporary file for future
2318       ** interactions.  If another temporary file with the P1 handle is
2319       ** already opened, the prior file is closed and a new one opened
2320       ** in its place.
2321       */
2322       case OP_ListOpen: {
2323         int i = pOp->p1;
2324         if( i<0 ) goto bad_instruction;
2325         if( i>=p->nList ){
2326           int j;
2327           p->apList = sqliteRealloc( p->apList, (i+1)*sizeof(FILE*) );
2328           if( p->apList==0 ){ p->nList = 0; goto no_mem; }
2329           for(j=p->nList; j<=i; j++) p->apList[j] = 0;
2330           p->nList = i+1;
2331         }else if( p->apList[i] ){
2332           sqliteDbbeCloseTempFile(p->pBe, p->apList[i]);
2333         }
2334         rc = sqliteDbbeOpenTempFile(p->pBe, &p->apList[i]);
2335         if( rc!=SQLITE_OK ){
2336           sqliteSetString(pzErrMsg, "unable to open a temporary file", 0);
2337         }
2338         break;
2339       }
2340 
2341       /* Opcode: ListWrite P1 * *
2342       **
2343       ** Write the integer on the top of the stack
2344       ** into the temporary storage file P1.
2345       */
2346       case OP_ListWrite: {
2347         int i = pOp->p1;
2348         if( i<0 ) goto bad_instruction;
2349         if( p->tos<0 ) goto not_enough_stack;
2350         if( i<p->nList && p->apList[i]!=0 ){
2351           int val;
2352           Integerify(p, p->tos);
2353           val = p->aStack[p->tos].i;
2354           PopStack(p, 1);
2355           fwrite(&val, sizeof(int), 1, p->apList[i]);
2356         }
2357         break;
2358       }
2359 
2360       /* Opcode: ListRewind P1 * *
2361       **
2362       ** Rewind the temporary buffer P1 back to the beginning.
2363       */
2364       case OP_ListRewind: {
2365         int i = pOp->p1;
2366         if( i<0 ) goto bad_instruction;
2367         if( i<p->nList && p->apList[i]!=0 ){
2368           rewind(p->apList[i]);
2369         }
2370         break;
2371       }
2372 
2373       /* Opcode: ListRead P1 P2 *
2374       **
2375       ** Attempt to read an integer from temporary storage buffer P1
2376       ** and push it onto the stack.  If the storage buffer is empty,
2377       ** push nothing but instead jump to P2.
2378       */
2379       case OP_ListRead: {
2380         int i = pOp->p1;
2381         int val, amt;
2382         if( i<0 || i>=p->nList || p->apList[i]==0 ) goto bad_instruction;
2383         amt = fread(&val, sizeof(int), 1, p->apList[i]);
2384         if( amt==1 ){
2385           p->tos++;
2386           if( NeedStack(p, p->tos) ) goto no_mem;
2387           p->aStack[p->tos].i = val;
2388           p->aStack[p->tos].flags = STK_Int;
2389           p->zStack[p->tos] = 0;
2390         }else{
2391           pc = pOp->p2 - 1;
2392         }
2393         break;
2394       }
2395 
2396       /* Opcode: ListClose P1 * *
2397       **
2398       ** Close the temporary storage buffer and discard its contents.
2399       */
2400       case OP_ListClose: {
2401         int i = pOp->p1;
2402         if( i<0 ) goto bad_instruction;
2403         if( i<p->nList && p->apList[i]!=0 ){
2404           sqliteDbbeCloseTempFile(p->pBe, p->apList[i]);
2405           p->apList[i] = 0;
2406         }
2407         break;
2408       }
2409 
2410       /* Opcode: SortOpen P1 * *
2411       **
2412       ** Create a new sorter with index P1
2413       */
2414       case OP_SortOpen: {
2415         int i = pOp->p1;
2416         if( i<0 ) goto bad_instruction;
2417         if( i>=p->nSort ){
2418           int j;
2419           p->apSort = sqliteRealloc( p->apSort, (i+1)*sizeof(Sorter*) );
2420           if( p->apSort==0 ){ p->nSort = 0; goto no_mem; }
2421           for(j=p->nSort; j<=i; j++) p->apSort[j] = 0;
2422           p->nSort = i+1;
2423         }
2424         break;
2425       }
2426 
2427       /* Opcode: SortPut P1 * *
2428       **
2429       ** The TOS is the key and the NOS is the data.  Pop both from the stack
2430       ** and put them on the sorter.
2431       */
2432       case OP_SortPut: {
2433         int i = pOp->p1;
2434         int tos = p->tos;
2435         int nos = tos - 1;
2436         Sorter *pSorter;
2437         if( i<0 || i>=p->nSort ) goto bad_instruction;
2438         if( tos<1 ) goto not_enough_stack;
2439         if( Stringify(p, tos) || Stringify(p, nos) ) goto no_mem;
2440         pSorter = sqliteMalloc( sizeof(Sorter) );
2441         if( pSorter==0 ) goto no_mem;
2442         pSorter->pNext = p->apSort[i];
2443         p->apSort[i] = pSorter;
2444         pSorter->nKey = p->aStack[tos].n;
2445         pSorter->zKey = p->zStack[tos];
2446         pSorter->nData = p->aStack[nos].n;
2447         pSorter->pData = p->zStack[nos];
2448         p->aStack[tos].flags = 0;
2449         p->aStack[nos].flags = 0;
2450         p->zStack[tos] = 0;
2451         p->zStack[nos] = 0;
2452         p->tos -= 2;
2453         break;
2454       }
2455 
2456       /* Opcode: SortMakeRec P1 * *
2457       **
2458       ** The top P1 elements are the arguments to a callback.  Form these
2459       ** elements into a single data entry that can be stored on a sorter
2460       ** using SortPut and later fed to a callback using SortCallback.
2461       */
2462       case OP_SortMakeRec: {
2463         char *z;
2464         char **azArg;
2465         int nByte;
2466         int nField;
2467         int i, j;
2468 
2469         nField = pOp->p1;
2470         if( p->tos+1<nField ) goto not_enough_stack;
2471         nByte = 0;
2472         for(i=p->tos-nField+1; i<=p->tos; i++){
2473           if( (p->aStack[i].flags & STK_Null)==0 ){
2474             if( Stringify(p, i) ) goto no_mem;
2475             nByte += p->aStack[i].n;
2476           }
2477         }
2478         nByte += sizeof(char*)*(nField+1);
2479         azArg = sqliteMalloc( nByte );
2480         if( azArg==0 ) goto no_mem;
2481         z = (char*)&azArg[nField+1];
2482         for(j=0, i=p->tos-nField+1; i<=p->tos; i++, j++){
2483           if( p->aStack[i].flags & STK_Null ){
2484             azArg[j] = 0;
2485           }else{
2486             azArg[j] = z;
2487             strcpy(z, p->zStack[i]);
2488             z += p->aStack[i].n;
2489           }
2490         }
2491         PopStack(p, nField);
2492         NeedStack(p, p->tos+1);
2493         p->tos++;
2494         p->aStack[p->tos].n = nByte;
2495         p->zStack[p->tos] = (char*)azArg;
2496         p->aStack[p->tos].flags = STK_Str|STK_Dyn;
2497         break;
2498       }
2499 
2500       /* Opcode: SortMakeKey P1 * P3
2501       **
2502       ** Convert the top few entries of the stack into a sort key.  The
2503       ** number of stack entries consumed is the number of characters in
2504       ** the string P3.  One character from P3 is prepended to each entry.
2505       ** The first character of P3 is prepended to the element lowest in
2506       ** the stack and the last character of P3 is appended to the top of
2507       ** the stack.  All stack entries are separated by a \000 character
2508       ** in the result.  The whole key is terminated by two \000 characters
2509       ** in a row.
2510       **
2511       ** See also the MakeKey opcode.
2512       */
2513       case OP_SortMakeKey: {
2514         char *zNewKey;
2515         int nByte;
2516         int nField;
2517         int i, j, k;
2518 
2519         nField = strlen(pOp->p3);
2520         if( p->tos+1<nField ) goto not_enough_stack;
2521         nByte = 1;
2522         for(i=p->tos-nField+1; i<=p->tos; i++){
2523           if( Stringify(p, i) ) goto no_mem;
2524           nByte += p->aStack[i].n+2;
2525         }
2526         zNewKey = sqliteMalloc( nByte );
2527         if( zNewKey==0 ) goto no_mem;
2528         j = 0;
2529         k = 0;
2530         for(i=p->tos-nField+1; i<=p->tos; i++){
2531           zNewKey[j++] = pOp->p3[k++];
2532           memcpy(&zNewKey[j], p->zStack[i], p->aStack[i].n-1);
2533           j += p->aStack[i].n-1;
2534           zNewKey[j++] = 0;
2535         }
2536         zNewKey[j] = 0;
2537         PopStack(p, nField);
2538         NeedStack(p, p->tos+1);
2539         p->tos++;
2540         p->aStack[p->tos].n = nByte;
2541         p->aStack[p->tos].flags = STK_Str|STK_Dyn;
2542         p->zStack[p->tos] = zNewKey;
2543         break;
2544       }
2545 
2546       /* Opcode: Sort P1 * *
2547       **
2548       ** Sort all elements on the given sorter.  The algorithm is a
2549       ** mergesort.
2550       */
2551       case OP_Sort: {
2552         int j;
2553         j = pOp->p1;
2554         if( j<0 ) goto bad_instruction;
2555         if( j<p->nSort ){
2556           int i;
2557           Sorter *pElem;
2558           Sorter *apSorter[NSORT];
2559           for(i=0; i<NSORT; i++){
2560             apSorter[i] = 0;
2561           }
2562           while( p->apSort[j] ){
2563             pElem = p->apSort[j];
2564             p->apSort[j] = pElem->pNext;
2565             pElem->pNext = 0;
2566             for(i=0; i<NSORT-1; i++){
2567               if( apSorter[i]==0 ){
2568                 apSorter[i] = pElem;
2569                 break;
2570               }else{
2571                 pElem = Merge(apSorter[i], pElem);
2572                 apSorter[i] = 0;
2573               }
2574             }
2575             if( i>=NSORT-1 ){
2576               apSorter[NSORT-1] = Merge(apSorter[NSORT-1],pElem);
2577             }
2578           }
2579           pElem = 0;
2580           for(i=0; i<NSORT; i++){
2581             pElem = Merge(apSorter[i], pElem);
2582           }
2583           p->apSort[j] = pElem;
2584         }
2585         break;
2586       }
2587 
2588       /* Opcode: SortNext P1 P2 *
2589       **
2590       ** Push the data for the topmost element in the given sorter onto the
2591       ** stack, then remove the element from the sorter.
2592       */
2593       case OP_SortNext: {
2594         int i = pOp->p1;
2595         if( i<0 ) goto bad_instruction;
2596         if( i<p->nSort && p->apSort[i]!=0 ){
2597           Sorter *pSorter = p->apSort[i];
2598           p->apSort[i] = pSorter->pNext;
2599           p->tos++;
2600           NeedStack(p, p->tos);
2601           p->zStack[p->tos] = pSorter->pData;
2602           p->aStack[p->tos].n = pSorter->nData;
2603           p->aStack[p->tos].flags = STK_Str|STK_Dyn;
2604           sqliteFree(pSorter->zKey);
2605           sqliteFree(pSorter);
2606         }else{
2607           pc = pOp->p2 - 1;
2608         }
2609         break;
2610       }
2611 
2612       /* Opcode: SortKey P1 * *
2613       **
2614       ** Push the key for the topmost element of the sorter onto the stack.
2615       ** But don't change the sorter an any other way.
2616       */
2617       case OP_SortKey: {
2618         int i = pOp->p1;
2619         if( i<0 ) goto bad_instruction;
2620         if( i<p->nSort && p->apSort[i]!=0 ){
2621           Sorter *pSorter = p->apSort[i];
2622           p->tos++;
2623           NeedStack(p, p->tos);
2624           sqliteSetString(&p->zStack[p->tos], pSorter->zKey, 0);
2625           p->aStack[p->tos].n = pSorter->nKey;
2626           p->aStack[p->tos].flags = STK_Str|STK_Dyn;
2627         }
2628         break;
2629       }
2630 
2631       /* Opcode: SortCallback P1 P2 *
2632       **
2633       ** The top of the stack contains a callback record built using
2634       ** the SortMakeRec operation with the same P1 value as this
2635       ** instruction.  Pop this record from the stack and invoke the
2636       ** callback on it.
2637       */
2638       case OP_SortCallback: {
2639         int i = p->tos;
2640         if( i<0 ) goto not_enough_stack;
2641         if( xCallback!=0 ){
2642           if( xCallback(pArg, pOp->p1, (char**)p->zStack[i], p->azColName) ){
2643             rc = SQLITE_ABORT;
2644           }
2645         }
2646         PopStack(p, 1);
2647         break;
2648       }
2649 
2650       /* Opcode: SortClose P1 * *
2651       **
2652       ** Close the given sorter and remove all its elements.
2653       */
2654       case OP_SortClose: {
2655         Sorter *pSorter;
2656         int i = pOp->p1;
2657         if( i<0 ) goto bad_instruction;
2658         if( i<p->nSort ){
2659            while( (pSorter = p->apSort[i])!=0 ){
2660              p->apSort[i] = pSorter->pNext;
2661              sqliteFree(pSorter->zKey);
2662              sqliteFree(pSorter->pData);
2663              sqliteFree(pSorter);
2664            }
2665         }
2666         break;
2667       }
2668 
2669       /* Opcode: FileOpen * * P3
2670       **
2671       ** Open the file named by P3 for reading using the FileRead opcode.
2672       ** If P3 is "stdin" then open standard input for reading.
2673       */
2674       case OP_FileOpen: {
2675         if( pOp->p3==0 ) goto bad_instruction;
2676         if( p->pFile ){
2677           if( p->pFile!=stdin ) fclose(p->pFile);
2678           p->pFile = 0;
2679         }
2680         if( sqliteStrICmp(pOp->p3,"stdin")==0 ){
2681           p->pFile = stdin;
2682         }else{
2683           p->pFile = fopen(pOp->p3, "r");
2684         }
2685         if( p->pFile==0 ){
2686           sqliteSetString(pzErrMsg,"unable to open file: ", pOp->p3, 0);
2687           rc = SQLITE_ERROR;
2688           goto cleanup;
2689         }
2690         break;
2691       }
2692 
2693       /* Opcode: FileClose * * *
2694       **
2695       ** Close a file previously opened using FileOpen.  This is a no-op
2696       ** if there is no prior FileOpen call.
2697       */
2698       case OP_FileClose: {
2699         if( p->pFile ){
2700           if( p->pFile!=stdin ) fclose(p->pFile);
2701           p->pFile = 0;
2702         }
2703         if( p->azField ){
2704           sqliteFree(p->azField);
2705           p->azField = 0;
2706         }
2707         p->nField = 0;
2708         if( p->zLine ){
2709           sqliteFree(p->zLine);
2710           p->zLine = 0;
2711         }
2712         p->nLineAlloc = 0;
2713         break;
2714       }
2715 
2716       /* Opcode: FileRead P1 P2 P3
2717       **
2718       ** Read a single line of input from the open file (the file opened using
2719       ** FileOpen).  If we reach end-of-file, jump immediately to P2.  If
2720       ** we are able to get another line, split the line apart using P3 as
2721       ** a delimiter.  There should be P1 fields.  If the input line contains
2722       ** more than P1 fields, ignore the excess.  If the input line contains
2723       ** fewer than P1 fields, assume the remaining fields contain an
2724       ** empty string.
2725       */
2726       case OP_FileRead: {
2727         int n, eol, nField, i, c, nDelim;
2728         char *zDelim, *z;
2729         if( p->pFile==0 ) goto fileread_jump;
2730         nField = pOp->p1;
2731         if( nField<=0 ) goto fileread_jump;
2732         if( nField!=p->nField || p->azField==0 ){
2733           p->azField = sqliteRealloc(p->azField, sizeof(char*)*nField+1);
2734           if( p->azField==0 ){
2735             p->nField = 0;
2736             goto fileread_jump;
2737           }
2738           p->nField = nField;
2739         }
2740         n = 0;
2741         eol = 0;
2742         while( eol==0 ){
2743           if( p->zLine==0 || n+200>p->nLineAlloc ){
2744             p->nLineAlloc = p->nLineAlloc*2 + 300;
2745             p->zLine = sqliteRealloc(p->zLine, p->nLineAlloc);
2746             if( p->zLine==0 ){
2747               p->nLineAlloc = 0;
2748               goto fileread_jump;
2749             }
2750           }
2751           if( fgets(&p->zLine[n], p->nLineAlloc-n, p->pFile)==0 ){
2752             eol = 1;
2753             p->zLine[n] = 0;
2754           }else{
2755             while( p->zLine[n] ){ n++; }
2756             if( n>0 && p->zLine[n-1]=='\n' ){
2757               n--;
2758               p->zLine[n] = 0;
2759               eol = 1;
2760             }
2761           }
2762         }
2763         if( n==0 ) goto fileread_jump;
2764         z = p->zLine;
2765         if( z[0]=='\\' && z[1]=='.' && z[2]==0 ){
2766           goto fileread_jump;
2767         }
2768         zDelim = pOp->p3;
2769         if( zDelim==0 ) zDelim = "\t";
2770         c = zDelim[0];
2771         nDelim = strlen(zDelim);
2772         p->azField[0] = z;
2773         for(i=1; *z!=0 && i<=nField; i++){
2774           int from, to;
2775           from = to = 0;
2776           while( z[from] ){
2777             if( z[from]=='\\' && z[from+1]!=0 ){
2778               z[to++] = z[from+1];
2779               from += 2;
2780               continue;
2781             }
2782             if( z[from]==c && strncmp(&z[from],zDelim,nDelim)==0 ) break;
2783             z[to++] = z[from++];
2784           }
2785           if( z[from] ){
2786             z[to] = 0;
2787             z += from + nDelim;
2788             if( i<nField ) p->azField[i] = z;
2789           }else{
2790             z[to] = 0;
2791             z = "";
2792           }
2793         }
2794         while( i<nField ){
2795           p->azField[i++] = "";
2796         }
2797         break;
2798 
2799         /* If we reach end-of-file, or if anything goes wrong, jump here.
2800         ** This code will cause a jump to P2 */
2801       fileread_jump:
2802         pc = pOp->p2 - 1;
2803         break;
2804       }
2805 
2806       /* Opcode: FileField P1 * *
2807       **
2808       ** Push onto the stack the P1-th field of the most recently read line
2809       ** from the input file.
2810       */
2811       case OP_FileField: {
2812         int i = pOp->p1;
2813         char *z;
2814         if( NeedStack(p, p->tos+1) ) goto no_mem;
2815         if( i>=0 && i<p->nField && p->azField ){
2816           z = p->azField[i];
2817         }else{
2818           z = 0;
2819         }
2820         if( z==0 ) z = "";
2821         p->tos++;
2822         p->aStack[p->tos].n = strlen(z) + 1;
2823         p->zStack[p->tos] = z;
2824         p->aStack[p->tos].flags = STK_Str;
2825         break;
2826       }
2827 
2828       /* Opcode: MemStore P1 * *
2829       **
2830       ** Pop a single value of the stack and store that value into memory
2831       ** location P1.  P1 should be a small integer since space is allocated
2832       ** for all memory locations between 0 and P1 inclusive.
2833       */
2834       case OP_MemStore: {
2835         int i = pOp->p1;
2836         int tos = p->tos;
2837         Mem *pMem;
2838         char *zOld;
2839         if( tos<0 ) goto not_enough_stack;
2840         if( i>=p->nMem ){
2841           int nOld = p->nMem;
2842           p->nMem = i + 5;
2843           p->aMem = sqliteRealloc(p->aMem, p->nMem*sizeof(p->aMem[0]));
2844           if( p->aMem==0 ) goto no_mem;
2845           if( nOld<p->nMem ){
2846             memset(&p->aMem[nOld], 0, sizeof(p->aMem[0])*(p->nMem-nOld));
2847           }
2848         }
2849         pMem = &p->aMem[i];
2850         if( pMem->s.flags & STK_Dyn ){
2851           zOld = pMem->z;
2852         }else{
2853           zOld = 0;
2854         }
2855         pMem->s = p->aStack[tos];
2856         if( pMem->s.flags & STK_Str ){
2857           pMem->z = sqliteStrNDup(p->zStack[tos], pMem->s.n);
2858           pMem->s.flags |= STK_Dyn;
2859         }
2860         if( zOld ) sqliteFree(zOld);
2861         PopStack(p, 1);
2862         break;
2863       }
2864 
2865       /* Opcode: MemLoad P1 * *
2866       **
2867       ** Push a copy of the value in memory location P1 onto the stack.
2868       */
2869       case OP_MemLoad: {
2870         int tos = ++p->tos;
2871         int i = pOp->p1;
2872         if( NeedStack(p, tos) ) goto no_mem;
2873         if( i<0 || i>=p->nMem ){
2874           p->aStack[tos].flags = STK_Null;
2875           p->zStack[tos] = 0;
2876         }else{
2877           p->aStack[tos] = p->aMem[i].s;
2878           if( p->aStack[tos].flags & STK_Str ){
2879             char *z = sqliteMalloc(p->aStack[tos].n);
2880             if( z==0 ) goto no_mem;
2881             memcpy(z, p->aMem[i].z, p->aStack[tos].n);
2882             p->zStack[tos] = z;
2883             p->aStack[tos].flags |= STK_Dyn;
2884           }
2885         }
2886         break;
2887       }
2888 
2889       /* Opcode: AggReset * P2 *
2890       **
2891       ** Reset the aggregator so that it no longer contains any data.
2892       ** Future aggregator elements will contain P2 values each.
2893       */
2894       case OP_AggReset: {
2895         AggReset(&p->agg);
2896         p->agg.nMem = pOp->p2;
2897         break;
2898       }
2899 
2900       /* Opcode: AggFocus * P2 *
2901       **
2902       ** Pop the top of the stack and use that as an aggregator key.  If
2903       ** an aggregator with that same key already exists, then make the
2904       ** aggregator the current aggregator and jump to P2.  If no aggregator
2905       ** with the given key exists, create one and make it current but
2906       ** do not jump.
2907       **
2908       ** The order of aggregator opcodes is important.  The order is:
2909       ** AggReset AggFocus AggNext.  In other words, you must execute
2910       ** AggReset first, then zero or more AggFocus operations, then
2911       ** zero or more AggNext operations.  You must not execute an AggFocus
2912       ** in between an AggNext and an AggReset.
2913       */
2914       case OP_AggFocus: {
2915         int tos = p->tos;
2916         AggElem *pElem;
2917         char *zKey;
2918         int nKey;
2919 
2920         if( tos<0 ) goto not_enough_stack;
2921         Stringify(p, tos);
2922         zKey = p->zStack[tos];
2923         nKey = p->aStack[tos].n;
2924         if( p->agg.nHash<=0 ){
2925           pElem = 0;
2926         }else{
2927           int h = sqliteHashNoCase(zKey, nKey-1) % p->agg.nHash;
2928           for(pElem=p->agg.apHash[h]; pElem; pElem=pElem->pHash){
2929             if( strcmp(pElem->zKey, zKey)==0 ) break;
2930           }
2931         }
2932         if( pElem ){
2933           p->agg.pCurrent = pElem;
2934           pc = pOp->p2 - 1;
2935         }else{
2936           AggInsert(&p->agg, zKey);
2937         }
2938         PopStack(p, 1);
2939         break;
2940       }
2941 
2942       /* Opcode: AggIncr P1 P2 *
2943       **
2944       ** Increase the integer value in the P2-th field of the aggregate
2945       ** element current in focus by an amount P1.
2946       */
2947       case OP_AggIncr: {
2948         AggElem *pFocus = AggInFocus(p->agg);
2949         int i = pOp->p2;
2950         if( pFocus==0 ) goto no_mem;
2951         if( i>=0 && i<p->agg.nMem ){
2952           Mem *pMem = &pFocus->aMem[i];
2953           if( pMem->s.flags!=STK_Int ){
2954             if( pMem->s.flags & STK_Int ){
2955               /* Do nothing */
2956             }else if( pMem->s.flags & STK_Real ){
2957               pMem->s.i = pMem->s.r;
2958             }else if( pMem->s.flags & STK_Str ){
2959               pMem->s.i = atoi(pMem->z);
2960             }else{
2961               pMem->s.i = 0;
2962             }
2963             if( pMem->s.flags & STK_Dyn ) sqliteFree(pMem->z);
2964             pMem->z = 0;
2965             pMem->s.flags = STK_Int;
2966           }
2967           pMem->s.i += pOp->p1;
2968         }
2969         break;
2970       }
2971 
2972       /* Opcode: AggSet * P2 *
2973       **
2974       ** Move the top of the stack into the P2-th field of the current
2975       ** aggregate.  String values are duplicated into new memory.
2976       */
2977       case OP_AggSet: {
2978         AggElem *pFocus = AggInFocus(p->agg);
2979         int i = pOp->p2;
2980         int tos = p->tos;
2981         if( tos<0 ) goto not_enough_stack;
2982         if( pFocus==0 ) goto no_mem;
2983         if( i>=0 && i<p->agg.nMem ){
2984           Mem *pMem = &pFocus->aMem[i];
2985           char *zOld;
2986           if( pMem->s.flags & STK_Dyn ){
2987             zOld = pMem->z;
2988           }else{
2989             zOld = 0;
2990           }
2991           pMem->s = p->aStack[tos];
2992           if( pMem->s.flags & STK_Str ){
2993             pMem->z = sqliteMalloc( p->aStack[tos].n );
2994             if( pMem->z==0 ) goto no_mem;
2995             memcpy(pMem->z, p->zStack[tos], pMem->s.n);
2996             pMem->s.flags |= STK_Str|STK_Dyn;
2997           }
2998           if( zOld ) sqliteFree(zOld);
2999         }
3000         PopStack(p, 1);
3001         break;
3002       }
3003 
3004       /* Opcode: AggGet * P2 *
3005       **
3006       ** Push a new entry onto the stack which is a copy of the P2-th field
3007       ** of the current aggregate.  Strings are not duplicated so
3008       ** string values will be ephemeral.
3009       */
3010       case OP_AggGet: {
3011         AggElem *pFocus = AggInFocus(p->agg);
3012         int i = pOp->p2;
3013         int tos = ++p->tos;
3014         if( NeedStack(p, tos) ) goto no_mem;
3015         if( pFocus==0 ) goto no_mem;
3016         if( i>=0 && i<p->agg.nMem ){
3017           Mem *pMem = &pFocus->aMem[i];
3018           p->aStack[tos] = pMem->s;
3019           p->zStack[tos] = pMem->z;
3020           p->aStack[tos].flags &= ~STK_Dyn;
3021         }
3022         break;
3023       }
3024 
3025       /* Opcode: AggNext * P2 *
3026       **
3027       ** Make the next aggregate value the current aggregate.  The prior
3028       ** aggregate is deleted.  If all aggregate values have been consumed,
3029       ** jump to P2.
3030       **
3031       ** The order of aggregator opcodes is important.  The order is:
3032       ** AggReset AggFocus AggNext.  In other words, you must execute
3033       ** AggReset first, then zero or more AggFocus operations, then
3034       ** zero or more AggNext operations.  You must not execute an AggFocus
3035       ** in between an AggNext and an AggReset.
3036       */
3037       case OP_AggNext: {
3038         if( p->agg.nHash ){
3039           p->agg.nHash = 0;
3040           sqliteFree(p->agg.apHash);
3041           p->agg.apHash = 0;
3042           p->agg.pCurrent = p->agg.pFirst;
3043         }else if( p->agg.pCurrent==p->agg.pFirst && p->agg.pCurrent!=0 ){
3044           int i;
3045           AggElem *pElem = p->agg.pCurrent;
3046           for(i=0; i<p->agg.nMem; i++){
3047             if( pElem->aMem[i].s.flags & STK_Dyn ){
3048               sqliteFree(pElem->aMem[i].z);
3049             }
3050           }
3051           p->agg.pCurrent = p->agg.pFirst = pElem->pNext;
3052           sqliteFree(pElem);
3053           p->agg.nElem--;
3054         }
3055         if( p->agg.pCurrent==0 ){
3056           pc = pOp->p2-1;
3057         }
3058         break;
3059       }
3060 
3061       /* Opcode: SetClear P1 * *
3062       **
3063       ** Remove all elements from the P1-th Set.
3064       */
3065       case OP_SetClear: {
3066         int i = pOp->p1;
3067         if( i>=0 && i<p->nSet ){
3068           SetClear(&p->aSet[i]);
3069         }
3070         break;
3071       }
3072 
3073       /* Opcode: SetInsert P1 * P3
3074       **
3075       ** If Set P1 does not exist then create it.  Then insert value
3076       ** P3 into that set.  If P3 is NULL, then insert the top of the
3077       ** stack into the set.
3078       */
3079       case OP_SetInsert: {
3080         int i = pOp->p1;
3081         if( p->nSet<=i ){
3082           p->aSet = sqliteRealloc(p->aSet, (i+1)*sizeof(p->aSet[0]) );
3083           if( p->aSet==0 ) goto no_mem;
3084           memset(&p->aSet[p->nSet], 0, sizeof(p->aSet[0])*(i+1 - p->nSet));
3085           p->nSet = i+1;
3086         }
3087         if( pOp->p3 ){
3088           SetInsert(&p->aSet[i], pOp->p3);
3089         }else{
3090           int tos = p->tos;
3091           if( tos<0 ) goto not_enough_stack;
3092           Stringify(p, tos);
3093           SetInsert(&p->aSet[i], p->zStack[tos]);
3094           PopStack(p, 1);
3095         }
3096         break;
3097       }
3098 
3099       /* Opcode: SetFound P1 P2 *
3100       **
3101       ** Pop the stack once and compare the value popped off with the
3102       ** contents of set P1.  If the element popped exists in set P1,
3103       ** then jump to P2.  Otherwise fall through.
3104       */
3105       case OP_SetFound: {
3106         int i = pOp->p1;
3107         int tos = p->tos;
3108         if( tos<0 ) goto not_enough_stack;
3109         Stringify(p, tos);
3110         if( i>=0 && i<p->nSet && SetTest(&p->aSet[i], p->zStack[tos]) ){
3111           pc = pOp->p2 - 1;
3112         }
3113         PopStack(p, 1);
3114         break;
3115       }
3116 
3117       /* Opcode: SetNotFound P1 P2 *
3118       **
3119       ** Pop the stack once and compare the value popped off with the
3120       ** contents of set P1.  If the element popped does not exists in
3121       ** set P1, then jump to P2.  Otherwise fall through.
3122       */
3123       case OP_SetNotFound: {
3124         int i = pOp->p1;
3125         int tos = p->tos;
3126         if( tos<0 ) goto not_enough_stack;
3127         Stringify(p, tos);
3128         if( i>=0 && i<p->nSet && !SetTest(&p->aSet[i], p->zStack[tos]) ){
3129           pc = pOp->p2 - 1;
3130         }
3131         PopStack(p, 1);
3132         break;
3133       }
3134 
3135       /* Opcode: Length * * *
3136       **
3137       ** Interpret the top of the stack as a string.  Replace the top of
3138       ** stack with an integer which is the length of the string.
3139       */
3140       case OP_Strlen: {
3141         int tos = p->tos;
3142         int len;
3143         if( tos<0 ) goto not_enough_stack;
3144         Stringify(p, tos);
3145         len = p->aStack[tos].n-1;
3146         PopStack(p, 1);
3147         p->tos++;
3148         p->aStack[tos].i = len;
3149         p->aStack[tos].flags = STK_Int;
3150         break;
3151       }
3152 
3153       /* Opcode: Substr P1 P2 *
3154       **
3155       ** This operation pops between 1 and 3 elements from the stack and
3156       ** pushes back a single element.  The bottom-most element popped from
3157       ** the stack is a string and the element pushed back is also a string.
3158       ** The other two elements popped are integers.  The integers are taken
3159       ** from the stack only if P1 and/or P2 are 0.  When P1 or P2 are
3160       ** not zero, the value of the operand is used rather than the integer
3161       ** from the stack.  In the sequel, we will use P1 and P2 to describe
3162       ** the two integers, even if those integers are really taken from the
3163       ** stack.
3164       **
3165       ** The string pushed back onto the stack is a substring of the string
3166       ** that was popped.  There are P2 characters in the substring.  The
3167       ** first character of the substring is the P1-th character of the
3168       ** original string where the left-most character is 1 (not 0).  If P1
3169       ** is negative, then counting begins at the right instead of at the
3170       ** left.
3171       */
3172       case OP_Substr: {
3173         int cnt;
3174         int start;
3175         int n;
3176         char *z;
3177 
3178         if( pOp->p2==0 ){
3179           if( p->tos<0 ) goto not_enough_stack;
3180           Integerify(p, p->tos);
3181           cnt = p->aStack[p->tos].i;
3182           PopStack(p, 1);
3183         }else{
3184           cnt = pOp->p2;
3185         }
3186         if( pOp->p1==0 ){
3187           if( p->tos<0 ) goto not_enough_stack;
3188           Integerify(p, p->tos);
3189           start = p->aStack[p->tos].i - 1;
3190           PopStack(p, 1);
3191         }else{
3192           start = pOp->p1 - 1;
3193         }
3194         if( p->tos<0 ) goto not_enough_stack;
3195         Stringify(p, p->tos);
3196         n = p->aStack[p->tos].n - 1;
3197         if( start<0 ){
3198           start += n + 1;
3199           if( start<0 ){
3200             cnt += start;
3201             start = 0;
3202           }
3203         }
3204         if( start>n ){
3205           start = n;
3206         }
3207         if( cnt<0 ) cnt = 0;
3208         if( cnt > n ){
3209           cnt = n;
3210         }
3211         z = sqliteMalloc( cnt+1 );
3212         if( z==0 ) goto no_mem;
3213         strncpy(z, &p->zStack[p->tos][start], cnt);
3214         z[cnt] = 0;
3215         PopStack(p, 1);
3216         p->tos++;
3217         p->zStack[p->tos] = z;
3218         p->aStack[p->tos].n = cnt + 1;
3219         p->aStack[p->tos].flags = STK_Str|STK_Dyn;
3220         break;
3221       }
3222 
3223       /* An other opcode is illegal...
3224       */
3225       default: {
3226         sprintf(zBuf,"%d",pOp->opcode);
3227         sqliteSetString(pzErrMsg, "unknown opcode ", zBuf, 0);
3228         rc = SQLITE_INTERNAL;
3229         break;
3230       }
3231     }
3232 
3233     /* The following code adds nothing to the actual functionality
3234     ** of the program.  It is only here for testing and debugging.
3235     ** On the other hand, it does burn CPU cycles every time through
3236     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
3237     */
3238 #ifndef NDEBUG
3239     if( pc<-1 || pc>=p->nOp ){
3240       sqliteSetString(pzErrMsg, "jump destination out of range", 0);
3241       rc = SQLITE_INTERNAL;
3242     }
3243     if( p->trace && p->tos>=0 ){
3244       int i;
3245       fprintf(p->trace, "Stack:");
3246       for(i=p->tos; i>=0 && i>p->tos-5; i--){
3247         if( p->aStack[i].flags & STK_Null ){
3248           fprintf(p->trace, " NULL");
3249         }else if( p->aStack[i].flags & STK_Int ){
3250           fprintf(p->trace, " i:%d", p->aStack[i].i);
3251         }else if( p->aStack[i].flags & STK_Real ){
3252           fprintf(p->trace, " r:%g", p->aStack[i].r);
3253         }else if( p->aStack[i].flags & STK_Str ){
3254           if( p->aStack[i].flags & STK_Dyn ){
3255             fprintf(p->trace, " z:[%.11s]", p->zStack[i]);
3256           }else{
3257             fprintf(p->trace, " s:[%.11s]", p->zStack[i]);
3258           }
3259         }else{
3260           fprintf(p->trace, " ???");
3261         }
3262       }
3263       fprintf(p->trace,"\n");
3264     }
3265 #endif
3266   }
3267 
3268 cleanup:
3269   Cleanup(p);
3270   return rc;
3271 
3272   /* Jump to here if a malloc() fails.  It's hard to get a malloc()
3273   ** to fail on a modern VM computer, so this code is untested.
3274   */
3275 no_mem:
3276   Cleanup(p);
3277   sqliteSetString(pzErrMsg, "out or memory", 0);
3278   return 1;
3279 
3280   /* Jump to here if a operator is encountered that requires more stack
3281   ** operands than are currently available on the stack.
3282   */
3283 not_enough_stack:
3284   sprintf(zBuf,"%d",pc);
3285   sqliteSetString(pzErrMsg, "too few operands on stack at ", zBuf, 0);
3286   rc = SQLITE_INTERNAL;
3287   goto cleanup;
3288 
3289   /* Jump here if an illegal or illformed instruction is executed.
3290   */
3291 bad_instruction:
3292   sprintf(zBuf,"%d",pc);
3293   sqliteSetString(pzErrMsg, "illegal operation at ", zBuf, 0);
3294   rc = SQLITE_INTERNAL;
3295   goto cleanup;
3296 }
3297