xref: /titanic_52/usr/src/lib/libsqlite/src/vdbeaux.c (revision c5c4113dfcabb1eed3d4bdf7609de5170027a794)
1 
2 #pragma ident	"%Z%%M%	%I%	%E% SMI"
3 
4 /*
5 ** 2003 September 6
6 **
7 ** The author disclaims copyright to this source code.  In place of
8 ** a legal notice, here is a blessing:
9 **
10 **    May you do good and not evil.
11 **    May you find forgiveness for yourself and forgive others.
12 **    May you share freely, never taking more than you give.
13 **
14 *************************************************************************
15 ** This file contains code used for creating, destroying, and populating
16 ** a VDBE (or an "sqlite_vm" as it is known to the outside world.)  Prior
17 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
18 ** But that file was getting too big so this subroutines were split out.
19 */
20 #include "sqliteInt.h"
21 #include "os.h"
22 #include <ctype.h>
23 #include "vdbeInt.h"
24 
25 
26 /*
27 ** When debugging the code generator in a symbolic debugger, one can
28 ** set the sqlite_vdbe_addop_trace to 1 and all opcodes will be printed
29 ** as they are added to the instruction stream.
30 */
31 #ifndef NDEBUG
32 int sqlite_vdbe_addop_trace = 0;
33 #endif
34 
35 
36 /*
37 ** Create a new virtual database engine.
38 */
39 Vdbe *sqliteVdbeCreate(sqlite *db){
40   Vdbe *p;
41   p = sqliteMalloc( sizeof(Vdbe) );
42   if( p==0 ) return 0;
43   p->db = db;
44   if( db->pVdbe ){
45     db->pVdbe->pPrev = p;
46   }
47   p->pNext = db->pVdbe;
48   p->pPrev = 0;
49   db->pVdbe = p;
50   p->magic = VDBE_MAGIC_INIT;
51   return p;
52 }
53 
54 /*
55 ** Turn tracing on or off
56 */
57 void sqliteVdbeTrace(Vdbe *p, FILE *trace){
58   p->trace = trace;
59 }
60 
61 /*
62 ** Add a new instruction to the list of instructions current in the
63 ** VDBE.  Return the address of the new instruction.
64 **
65 ** Parameters:
66 **
67 **    p               Pointer to the VDBE
68 **
69 **    op              The opcode for this instruction
70 **
71 **    p1, p2          First two of the three possible operands.
72 **
73 ** Use the sqliteVdbeResolveLabel() function to fix an address and
74 ** the sqliteVdbeChangeP3() function to change the value of the P3
75 ** operand.
76 */
77 int sqliteVdbeAddOp(Vdbe *p, int op, int p1, int p2){
78   int i;
79   VdbeOp *pOp;
80 
81   i = p->nOp;
82   p->nOp++;
83   assert( p->magic==VDBE_MAGIC_INIT );
84   if( i>=p->nOpAlloc ){
85     int oldSize = p->nOpAlloc;
86     Op *aNew;
87     p->nOpAlloc = p->nOpAlloc*2 + 100;
88     aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
89     if( aNew==0 ){
90       p->nOpAlloc = oldSize;
91       return 0;
92     }
93     p->aOp = aNew;
94     memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
95   }
96   pOp = &p->aOp[i];
97   pOp->opcode = op;
98   pOp->p1 = p1;
99   if( p2<0 && (-1-p2)<p->nLabel && p->aLabel[-1-p2]>=0 ){
100     p2 = p->aLabel[-1-p2];
101   }
102   pOp->p2 = p2;
103   pOp->p3 = 0;
104   pOp->p3type = P3_NOTUSED;
105 #ifndef NDEBUG
106   if( sqlite_vdbe_addop_trace ) sqliteVdbePrintOp(0, i, &p->aOp[i]);
107 #endif
108   return i;
109 }
110 
111 /*
112 ** Add an opcode that includes the p3 value.
113 */
114 int sqliteVdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3, int p3type){
115   int addr = sqliteVdbeAddOp(p, op, p1, p2);
116   sqliteVdbeChangeP3(p, addr, zP3, p3type);
117   return addr;
118 }
119 
120 /*
121 ** Add multiple opcodes.  The list is terminated by an opcode of 0.
122 */
123 int sqliteVdbeCode(Vdbe *p, ...){
124   int addr;
125   va_list ap;
126   int opcode, p1, p2;
127   va_start(ap, p);
128   addr = p->nOp;
129   while( (opcode = va_arg(ap,int))!=0 ){
130     p1 = va_arg(ap,int);
131     p2 = va_arg(ap,int);
132     sqliteVdbeAddOp(p, opcode, p1, p2);
133   }
134   va_end(ap);
135   return addr;
136 }
137 
138 
139 
140 /*
141 ** Create a new symbolic label for an instruction that has yet to be
142 ** coded.  The symbolic label is really just a negative number.  The
143 ** label can be used as the P2 value of an operation.  Later, when
144 ** the label is resolved to a specific address, the VDBE will scan
145 ** through its operation list and change all values of P2 which match
146 ** the label into the resolved address.
147 **
148 ** The VDBE knows that a P2 value is a label because labels are
149 ** always negative and P2 values are suppose to be non-negative.
150 ** Hence, a negative P2 value is a label that has yet to be resolved.
151 */
152 int sqliteVdbeMakeLabel(Vdbe *p){
153   int i;
154   i = p->nLabel++;
155   assert( p->magic==VDBE_MAGIC_INIT );
156   if( i>=p->nLabelAlloc ){
157     int *aNew;
158     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
159     aNew = sqliteRealloc( p->aLabel, p->nLabelAlloc*sizeof(p->aLabel[0]));
160     if( aNew==0 ){
161       sqliteFree(p->aLabel);
162     }
163     p->aLabel = aNew;
164   }
165   if( p->aLabel==0 ){
166     p->nLabel = 0;
167     p->nLabelAlloc = 0;
168     return 0;
169   }
170   p->aLabel[i] = -1;
171   return -1-i;
172 }
173 
174 /*
175 ** Resolve label "x" to be the address of the next instruction to
176 ** be inserted.  The parameter "x" must have been obtained from
177 ** a prior call to sqliteVdbeMakeLabel().
178 */
179 void sqliteVdbeResolveLabel(Vdbe *p, int x){
180   int j;
181   assert( p->magic==VDBE_MAGIC_INIT );
182   if( x<0 && (-x)<=p->nLabel && p->aOp ){
183     if( p->aLabel[-1-x]==p->nOp ) return;
184     assert( p->aLabel[-1-x]<0 );
185     p->aLabel[-1-x] = p->nOp;
186     for(j=0; j<p->nOp; j++){
187       if( p->aOp[j].p2==x ) p->aOp[j].p2 = p->nOp;
188     }
189   }
190 }
191 
192 /*
193 ** Return the address of the next instruction to be inserted.
194 */
195 int sqliteVdbeCurrentAddr(Vdbe *p){
196   assert( p->magic==VDBE_MAGIC_INIT );
197   return p->nOp;
198 }
199 
200 /*
201 ** Add a whole list of operations to the operation stack.  Return the
202 ** address of the first operation added.
203 */
204 int sqliteVdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
205   int addr;
206   assert( p->magic==VDBE_MAGIC_INIT );
207   if( p->nOp + nOp >= p->nOpAlloc ){
208     int oldSize = p->nOpAlloc;
209     Op *aNew;
210     p->nOpAlloc = p->nOpAlloc*2 + nOp + 10;
211     aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
212     if( aNew==0 ){
213       p->nOpAlloc = oldSize;
214       return 0;
215     }
216     p->aOp = aNew;
217     memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
218   }
219   addr = p->nOp;
220   if( nOp>0 ){
221     int i;
222     VdbeOpList const *pIn = aOp;
223     for(i=0; i<nOp; i++, pIn++){
224       int p2 = pIn->p2;
225       VdbeOp *pOut = &p->aOp[i+addr];
226       pOut->opcode = pIn->opcode;
227       pOut->p1 = pIn->p1;
228       pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
229       pOut->p3 = pIn->p3;
230       pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
231 #ifndef NDEBUG
232       if( sqlite_vdbe_addop_trace ){
233         sqliteVdbePrintOp(0, i+addr, &p->aOp[i+addr]);
234       }
235 #endif
236     }
237     p->nOp += nOp;
238   }
239   return addr;
240 }
241 
242 /*
243 ** Change the value of the P1 operand for a specific instruction.
244 ** This routine is useful when a large program is loaded from a
245 ** static array using sqliteVdbeAddOpList but we want to make a
246 ** few minor changes to the program.
247 */
248 void sqliteVdbeChangeP1(Vdbe *p, int addr, int val){
249   assert( p->magic==VDBE_MAGIC_INIT );
250   if( p && addr>=0 && p->nOp>addr && p->aOp ){
251     p->aOp[addr].p1 = val;
252   }
253 }
254 
255 /*
256 ** Change the value of the P2 operand for a specific instruction.
257 ** This routine is useful for setting a jump destination.
258 */
259 void sqliteVdbeChangeP2(Vdbe *p, int addr, int val){
260   assert( val>=0 );
261   assert( p->magic==VDBE_MAGIC_INIT );
262   if( p && addr>=0 && p->nOp>addr && p->aOp ){
263     p->aOp[addr].p2 = val;
264   }
265 }
266 
267 /*
268 ** Change the value of the P3 operand for a specific instruction.
269 ** This routine is useful when a large program is loaded from a
270 ** static array using sqliteVdbeAddOpList but we want to make a
271 ** few minor changes to the program.
272 **
273 ** If n>=0 then the P3 operand is dynamic, meaning that a copy of
274 ** the string is made into memory obtained from sqliteMalloc().
275 ** A value of n==0 means copy bytes of zP3 up to and including the
276 ** first null byte.  If n>0 then copy n+1 bytes of zP3.
277 **
278 ** If n==P3_STATIC  it means that zP3 is a pointer to a constant static
279 ** string and we can just copy the pointer.  n==P3_POINTER means zP3 is
280 ** a pointer to some object other than a string.
281 **
282 ** If addr<0 then change P3 on the most recently inserted instruction.
283 */
284 void sqliteVdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
285   Op *pOp;
286   assert( p->magic==VDBE_MAGIC_INIT );
287   if( p==0 || p->aOp==0 ) return;
288   if( addr<0 || addr>=p->nOp ){
289     addr = p->nOp - 1;
290     if( addr<0 ) return;
291   }
292   pOp = &p->aOp[addr];
293   if( pOp->p3 && pOp->p3type==P3_DYNAMIC ){
294     sqliteFree(pOp->p3);
295     pOp->p3 = 0;
296   }
297   if( zP3==0 ){
298     pOp->p3 = 0;
299     pOp->p3type = P3_NOTUSED;
300   }else if( n<0 ){
301     pOp->p3 = (char*)zP3;
302     pOp->p3type = n;
303   }else{
304     sqliteSetNString(&pOp->p3, zP3, n, 0);
305     pOp->p3type = P3_DYNAMIC;
306   }
307 }
308 
309 /*
310 ** If the P3 operand to the specified instruction appears
311 ** to be a quoted string token, then this procedure removes
312 ** the quotes.
313 **
314 ** The quoting operator can be either a grave ascent (ASCII 0x27)
315 ** or a double quote character (ASCII 0x22).  Two quotes in a row
316 ** resolve to be a single actual quote character within the string.
317 */
318 void sqliteVdbeDequoteP3(Vdbe *p, int addr){
319   Op *pOp;
320   assert( p->magic==VDBE_MAGIC_INIT );
321   if( p->aOp==0 ) return;
322   if( addr<0 || addr>=p->nOp ){
323     addr = p->nOp - 1;
324     if( addr<0 ) return;
325   }
326   pOp = &p->aOp[addr];
327   if( pOp->p3==0 || pOp->p3[0]==0 ) return;
328   if( pOp->p3type==P3_POINTER ) return;
329   if( pOp->p3type!=P3_DYNAMIC ){
330     pOp->p3 = sqliteStrDup(pOp->p3);
331     pOp->p3type = P3_DYNAMIC;
332   }
333   sqliteDequote(pOp->p3);
334 }
335 
336 /*
337 ** On the P3 argument of the given instruction, change all
338 ** strings of whitespace characters into a single space and
339 ** delete leading and trailing whitespace.
340 */
341 void sqliteVdbeCompressSpace(Vdbe *p, int addr){
342   unsigned char *z;
343   int i, j;
344   Op *pOp;
345   assert( p->magic==VDBE_MAGIC_INIT );
346   if( p->aOp==0 || addr<0 || addr>=p->nOp ) return;
347   pOp = &p->aOp[addr];
348   if( pOp->p3type==P3_POINTER ){
349     return;
350   }
351   if( pOp->p3type!=P3_DYNAMIC ){
352     pOp->p3 = sqliteStrDup(pOp->p3);
353     pOp->p3type = P3_DYNAMIC;
354   }
355   z = (unsigned char*)pOp->p3;
356   if( z==0 ) return;
357   i = j = 0;
358   while( isspace(z[i]) ){ i++; }
359   while( z[i] ){
360     if( isspace(z[i]) ){
361       z[j++] = ' ';
362       while( isspace(z[++i]) ){}
363     }else{
364       z[j++] = z[i++];
365     }
366   }
367   while( j>0 && isspace(z[j-1]) ){ j--; }
368   z[j] = 0;
369 }
370 
371 /*
372 ** Search for the current program for the given opcode and P2
373 ** value.  Return the address plus 1 if found and 0 if not found.
374 */
375 int sqliteVdbeFindOp(Vdbe *p, int op, int p2){
376   int i;
377   assert( p->magic==VDBE_MAGIC_INIT );
378   for(i=0; i<p->nOp; i++){
379     if( p->aOp[i].opcode==op && p->aOp[i].p2==p2 ) return i+1;
380   }
381   return 0;
382 }
383 
384 /*
385 ** Return the opcode for a given address.
386 */
387 VdbeOp *sqliteVdbeGetOp(Vdbe *p, int addr){
388   assert( p->magic==VDBE_MAGIC_INIT );
389   assert( addr>=0 && addr<p->nOp );
390   return &p->aOp[addr];
391 }
392 
393 /*
394 ** The following group or routines are employed by installable functions
395 ** to return their results.
396 **
397 ** The sqlite_set_result_string() routine can be used to return a string
398 ** value or to return a NULL.  To return a NULL, pass in NULL for zResult.
399 ** A copy is made of the string before this routine returns so it is safe
400 ** to pass in an ephemeral string.
401 **
402 ** sqlite_set_result_error() works like sqlite_set_result_string() except
403 ** that it signals a fatal error.  The string argument, if any, is the
404 ** error message.  If the argument is NULL a generic substitute error message
405 ** is used.
406 **
407 ** The sqlite_set_result_int() and sqlite_set_result_double() set the return
408 ** value of the user function to an integer or a double.
409 **
410 ** These routines are defined here in vdbe.c because they depend on knowing
411 ** the internals of the sqlite_func structure which is only defined in
412 ** this source file.
413 */
414 char *sqlite_set_result_string(sqlite_func *p, const char *zResult, int n){
415   assert( !p->isStep );
416   if( p->s.flags & MEM_Dyn ){
417     sqliteFree(p->s.z);
418   }
419   if( zResult==0 ){
420     p->s.flags = MEM_Null;
421     n = 0;
422     p->s.z = 0;
423     p->s.n = 0;
424   }else{
425     if( n<0 ) n = strlen(zResult);
426     if( n<NBFS-1 ){
427       memcpy(p->s.zShort, zResult, n);
428       p->s.zShort[n] = 0;
429       p->s.flags = MEM_Str | MEM_Short;
430       p->s.z = p->s.zShort;
431     }else{
432       p->s.z = sqliteMallocRaw( n+1 );
433       if( p->s.z ){
434         memcpy(p->s.z, zResult, n);
435         p->s.z[n] = 0;
436       }
437       p->s.flags = MEM_Str | MEM_Dyn;
438     }
439     p->s.n = n+1;
440   }
441   return p->s.z;
442 }
443 void sqlite_set_result_int(sqlite_func *p, int iResult){
444   assert( !p->isStep );
445   if( p->s.flags & MEM_Dyn ){
446     sqliteFree(p->s.z);
447   }
448   p->s.i = iResult;
449   p->s.flags = MEM_Int;
450 }
451 void sqlite_set_result_double(sqlite_func *p, double rResult){
452   assert( !p->isStep );
453   if( p->s.flags & MEM_Dyn ){
454     sqliteFree(p->s.z);
455   }
456   p->s.r = rResult;
457   p->s.flags = MEM_Real;
458 }
459 void sqlite_set_result_error(sqlite_func *p, const char *zMsg, int n){
460   assert( !p->isStep );
461   sqlite_set_result_string(p, zMsg, n);
462   p->isError = 1;
463 }
464 
465 /*
466 ** Extract the user data from a sqlite_func structure and return a
467 ** pointer to it.
468 */
469 void *sqlite_user_data(sqlite_func *p){
470   assert( p && p->pFunc );
471   return p->pFunc->pUserData;
472 }
473 
474 /*
475 ** Allocate or return the aggregate context for a user function.  A new
476 ** context is allocated on the first call.  Subsequent calls return the
477 ** same context that was returned on prior calls.
478 **
479 ** This routine is defined here in vdbe.c because it depends on knowing
480 ** the internals of the sqlite_func structure which is only defined in
481 ** this source file.
482 */
483 void *sqlite_aggregate_context(sqlite_func *p, int nByte){
484   assert( p && p->pFunc && p->pFunc->xStep );
485   if( p->pAgg==0 ){
486     if( nByte<=NBFS ){
487       p->pAgg = (void*)p->s.z;
488       memset(p->pAgg, 0, nByte);
489     }else{
490       p->pAgg = sqliteMalloc( nByte );
491     }
492   }
493   return p->pAgg;
494 }
495 
496 /*
497 ** Return the number of times the Step function of a aggregate has been
498 ** called.
499 **
500 ** This routine is defined here in vdbe.c because it depends on knowing
501 ** the internals of the sqlite_func structure which is only defined in
502 ** this source file.
503 */
504 int sqlite_aggregate_count(sqlite_func *p){
505   assert( p && p->pFunc && p->pFunc->xStep );
506   return p->cnt;
507 }
508 
509 #if !defined(NDEBUG) || defined(VDBE_PROFILE)
510 /*
511 ** Print a single opcode.  This routine is used for debugging only.
512 */
513 void sqliteVdbePrintOp(FILE *pOut, int pc, Op *pOp){
514   char *zP3;
515   char zPtr[40];
516   if( pOp->p3type==P3_POINTER ){
517     sprintf(zPtr, "ptr(%#lx)", (long)pOp->p3);
518     zP3 = zPtr;
519   }else{
520     zP3 = pOp->p3;
521   }
522   if( pOut==0 ) pOut = stdout;
523   fprintf(pOut,"%4d %-12s %4d %4d %s\n",
524       pc, sqliteOpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3 ? zP3 : "");
525   fflush(pOut);
526 }
527 #endif
528 
529 /*
530 ** Give a listing of the program in the virtual machine.
531 **
532 ** The interface is the same as sqliteVdbeExec().  But instead of
533 ** running the code, it invokes the callback once for each instruction.
534 ** This feature is used to implement "EXPLAIN".
535 */
536 int sqliteVdbeList(
537   Vdbe *p                   /* The VDBE */
538 ){
539   sqlite *db = p->db;
540   int i;
541   int rc = SQLITE_OK;
542   static char *azColumnNames[] = {
543      "addr", "opcode", "p1",  "p2",  "p3",
544      "int",  "text",   "int", "int", "text",
545      0
546   };
547 
548   assert( p->popStack==0 );
549   assert( p->explain );
550   p->azColName = azColumnNames;
551   p->azResColumn = p->zArgv;
552   for(i=0; i<5; i++) p->zArgv[i] = p->aStack[i].zShort;
553   i = p->pc;
554   if( i>=p->nOp ){
555     p->rc = SQLITE_OK;
556     rc = SQLITE_DONE;
557   }else if( db->flags & SQLITE_Interrupt ){
558     db->flags &= ~SQLITE_Interrupt;
559     if( db->magic!=SQLITE_MAGIC_BUSY ){
560       p->rc = SQLITE_MISUSE;
561     }else{
562       p->rc = SQLITE_INTERRUPT;
563     }
564     rc = SQLITE_ERROR;
565     sqliteSetString(&p->zErrMsg, sqlite_error_string(p->rc), (char*)0);
566   }else{
567     sprintf(p->zArgv[0],"%d",i);
568     sprintf(p->zArgv[2],"%d", p->aOp[i].p1);
569     sprintf(p->zArgv[3],"%d", p->aOp[i].p2);
570     if( p->aOp[i].p3type==P3_POINTER ){
571       sprintf(p->aStack[4].zShort, "ptr(%#lx)", (long)p->aOp[i].p3);
572       p->zArgv[4] = p->aStack[4].zShort;
573     }else{
574       p->zArgv[4] = p->aOp[i].p3;
575     }
576     p->zArgv[1] = sqliteOpcodeNames[p->aOp[i].opcode];
577     p->pc = i+1;
578     p->azResColumn = p->zArgv;
579     p->nResColumn = 5;
580     p->rc = SQLITE_OK;
581     rc = SQLITE_ROW;
582   }
583   return rc;
584 }
585 
586 /*
587 ** Prepare a virtual machine for execution.  This involves things such
588 ** as allocating stack space and initializing the program counter.
589 ** After the VDBE has be prepped, it can be executed by one or more
590 ** calls to sqliteVdbeExec().
591 */
592 void sqliteVdbeMakeReady(
593   Vdbe *p,                       /* The VDBE */
594   int nVar,                      /* Number of '?' see in the SQL statement */
595   int isExplain                  /* True if the EXPLAIN keywords is present */
596 ){
597   int n;
598 
599   assert( p!=0 );
600   assert( p->magic==VDBE_MAGIC_INIT );
601 
602   /* Add a HALT instruction to the very end of the program.
603   */
604   if( p->nOp==0 || (p->aOp && p->aOp[p->nOp-1].opcode!=OP_Halt) ){
605     sqliteVdbeAddOp(p, OP_Halt, 0, 0);
606   }
607 
608   /* No instruction ever pushes more than a single element onto the
609   ** stack.  And the stack never grows on successive executions of the
610   ** same loop.  So the total number of instructions is an upper bound
611   ** on the maximum stack depth required.
612   **
613   ** Allocation all the stack space we will ever need.
614   */
615   if( p->aStack==0 ){
616     p->nVar = nVar;
617     assert( nVar>=0 );
618     n = isExplain ? 10 : p->nOp;
619     p->aStack = sqliteMalloc(
620       n*(sizeof(p->aStack[0]) + 2*sizeof(char*))     /* aStack and zArgv */
621         + p->nVar*(sizeof(char*)+sizeof(int)+1)    /* azVar, anVar, abVar */
622     );
623     p->zArgv = (char**)&p->aStack[n];
624     p->azColName = (char**)&p->zArgv[n];
625     p->azVar = (char**)&p->azColName[n];
626     p->anVar = (int*)&p->azVar[p->nVar];
627     p->abVar = (u8*)&p->anVar[p->nVar];
628   }
629 
630   sqliteHashInit(&p->agg.hash, SQLITE_HASH_BINARY, 0);
631   p->agg.pSearch = 0;
632 #ifdef MEMORY_DEBUG
633   if( sqliteOsFileExists("vdbe_trace") ){
634     p->trace = stdout;
635   }
636 #endif
637   p->pTos = &p->aStack[-1];
638   p->pc = 0;
639   p->rc = SQLITE_OK;
640   p->uniqueCnt = 0;
641   p->returnDepth = 0;
642   p->errorAction = OE_Abort;
643   p->undoTransOnError = 0;
644   p->popStack =  0;
645   p->explain |= isExplain;
646   p->magic = VDBE_MAGIC_RUN;
647 #ifdef VDBE_PROFILE
648   {
649     int i;
650     for(i=0; i<p->nOp; i++){
651       p->aOp[i].cnt = 0;
652       p->aOp[i].cycles = 0;
653     }
654   }
655 #endif
656 }
657 
658 
659 /*
660 ** Remove any elements that remain on the sorter for the VDBE given.
661 */
662 void sqliteVdbeSorterReset(Vdbe *p){
663   while( p->pSort ){
664     Sorter *pSorter = p->pSort;
665     p->pSort = pSorter->pNext;
666     sqliteFree(pSorter->zKey);
667     sqliteFree(pSorter->pData);
668     sqliteFree(pSorter);
669   }
670 }
671 
672 /*
673 ** Reset an Agg structure.  Delete all its contents.
674 **
675 ** For installable aggregate functions, if the step function has been
676 ** called, make sure the finalizer function has also been called.  The
677 ** finalizer might need to free memory that was allocated as part of its
678 ** private context.  If the finalizer has not been called yet, call it
679 ** now.
680 */
681 void sqliteVdbeAggReset(Agg *pAgg){
682   int i;
683   HashElem *p;
684   for(p = sqliteHashFirst(&pAgg->hash); p; p = sqliteHashNext(p)){
685     AggElem *pElem = sqliteHashData(p);
686     assert( pAgg->apFunc!=0 );
687     for(i=0; i<pAgg->nMem; i++){
688       Mem *pMem = &pElem->aMem[i];
689       if( pAgg->apFunc[i] && (pMem->flags & MEM_AggCtx)!=0 ){
690         sqlite_func ctx;
691         ctx.pFunc = pAgg->apFunc[i];
692         ctx.s.flags = MEM_Null;
693         ctx.pAgg = pMem->z;
694         ctx.cnt = pMem->i;
695         ctx.isStep = 0;
696         ctx.isError = 0;
697         (*pAgg->apFunc[i]->xFinalize)(&ctx);
698         if( pMem->z!=0 && pMem->z!=pMem->zShort ){
699           sqliteFree(pMem->z);
700         }
701         if( ctx.s.flags & MEM_Dyn ){
702           sqliteFree(ctx.s.z);
703         }
704       }else if( pMem->flags & MEM_Dyn ){
705         sqliteFree(pMem->z);
706       }
707     }
708     sqliteFree(pElem);
709   }
710   sqliteHashClear(&pAgg->hash);
711   sqliteFree(pAgg->apFunc);
712   pAgg->apFunc = 0;
713   pAgg->pCurrent = 0;
714   pAgg->pSearch = 0;
715   pAgg->nMem = 0;
716 }
717 
718 /*
719 ** Delete a keylist
720 */
721 void sqliteVdbeKeylistFree(Keylist *p){
722   while( p ){
723     Keylist *pNext = p->pNext;
724     sqliteFree(p);
725     p = pNext;
726   }
727 }
728 
729 /*
730 ** Close a cursor and release all the resources that cursor happens
731 ** to hold.
732 */
733 void sqliteVdbeCleanupCursor(Cursor *pCx){
734   if( pCx->pCursor ){
735     sqliteBtreeCloseCursor(pCx->pCursor);
736   }
737   if( pCx->pBt ){
738     sqliteBtreeClose(pCx->pBt);
739   }
740   sqliteFree(pCx->pData);
741   memset(pCx, 0, sizeof(Cursor));
742 }
743 
744 /*
745 ** Close all cursors
746 */
747 static void closeAllCursors(Vdbe *p){
748   int i;
749   for(i=0; i<p->nCursor; i++){
750     sqliteVdbeCleanupCursor(&p->aCsr[i]);
751   }
752   sqliteFree(p->aCsr);
753   p->aCsr = 0;
754   p->nCursor = 0;
755 }
756 
757 /*
758 ** Clean up the VM after execution.
759 **
760 ** This routine will automatically close any cursors, lists, and/or
761 ** sorters that were left open.  It also deletes the values of
762 ** variables in the azVariable[] array.
763 */
764 static void Cleanup(Vdbe *p){
765   int i;
766   if( p->aStack ){
767     Mem *pTos = p->pTos;
768     while( pTos>=p->aStack ){
769       if( pTos->flags & MEM_Dyn ){
770         sqliteFree(pTos->z);
771       }
772       pTos--;
773     }
774     p->pTos = pTos;
775   }
776   closeAllCursors(p);
777   if( p->aMem ){
778     for(i=0; i<p->nMem; i++){
779       if( p->aMem[i].flags & MEM_Dyn ){
780         sqliteFree(p->aMem[i].z);
781       }
782     }
783   }
784   sqliteFree(p->aMem);
785   p->aMem = 0;
786   p->nMem = 0;
787   if( p->pList ){
788     sqliteVdbeKeylistFree(p->pList);
789     p->pList = 0;
790   }
791   sqliteVdbeSorterReset(p);
792   if( p->pFile ){
793     if( p->pFile!=stdin ) fclose(p->pFile);
794     p->pFile = 0;
795   }
796   if( p->azField ){
797     sqliteFree(p->azField);
798     p->azField = 0;
799   }
800   p->nField = 0;
801   if( p->zLine ){
802     sqliteFree(p->zLine);
803     p->zLine = 0;
804   }
805   p->nLineAlloc = 0;
806   sqliteVdbeAggReset(&p->agg);
807   if( p->aSet ){
808     for(i=0; i<p->nSet; i++){
809       sqliteHashClear(&p->aSet[i].hash);
810     }
811   }
812   sqliteFree(p->aSet);
813   p->aSet = 0;
814   p->nSet = 0;
815   if( p->keylistStack ){
816     int ii;
817     for(ii = 0; ii < p->keylistStackDepth; ii++){
818       sqliteVdbeKeylistFree(p->keylistStack[ii]);
819     }
820     sqliteFree(p->keylistStack);
821     p->keylistStackDepth = 0;
822     p->keylistStack = 0;
823   }
824   sqliteFree(p->contextStack);
825   p->contextStack = 0;
826   sqliteFree(p->zErrMsg);
827   p->zErrMsg = 0;
828 }
829 
830 /*
831 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
832 ** Write any error messages into *pzErrMsg.  Return the result code.
833 **
834 ** After this routine is run, the VDBE should be ready to be executed
835 ** again.
836 */
837 int sqliteVdbeReset(Vdbe *p, char **pzErrMsg){
838   sqlite *db = p->db;
839   int i;
840 
841   if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
842     sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
843     return SQLITE_MISUSE;
844   }
845   if( p->zErrMsg ){
846     if( pzErrMsg && *pzErrMsg==0 ){
847       *pzErrMsg = p->zErrMsg;
848     }else{
849       sqliteFree(p->zErrMsg);
850     }
851     p->zErrMsg = 0;
852   }else if( p->rc ){
853     sqliteSetString(pzErrMsg, sqlite_error_string(p->rc), (char*)0);
854   }
855   Cleanup(p);
856   if( p->rc!=SQLITE_OK ){
857     switch( p->errorAction ){
858       case OE_Abort: {
859         if( !p->undoTransOnError ){
860           for(i=0; i<db->nDb; i++){
861             if( db->aDb[i].pBt ){
862               sqliteBtreeRollbackCkpt(db->aDb[i].pBt);
863             }
864           }
865           break;
866         }
867         /* Fall through to ROLLBACK */
868       }
869       case OE_Rollback: {
870         sqliteRollbackAll(db);
871         db->flags &= ~SQLITE_InTrans;
872         db->onError = OE_Default;
873         break;
874       }
875       default: {
876         if( p->undoTransOnError ){
877           sqliteRollbackAll(db);
878           db->flags &= ~SQLITE_InTrans;
879           db->onError = OE_Default;
880         }
881         break;
882       }
883     }
884     sqliteRollbackInternalChanges(db);
885   }
886   for(i=0; i<db->nDb; i++){
887     if( db->aDb[i].pBt && db->aDb[i].inTrans==2 ){
888       sqliteBtreeCommitCkpt(db->aDb[i].pBt);
889       db->aDb[i].inTrans = 1;
890     }
891   }
892   assert( p->pTos<&p->aStack[p->pc] || sqlite_malloc_failed==1 );
893 #ifdef VDBE_PROFILE
894   {
895     FILE *out = fopen("vdbe_profile.out", "a");
896     if( out ){
897       int i;
898       fprintf(out, "---- ");
899       for(i=0; i<p->nOp; i++){
900         fprintf(out, "%02x", p->aOp[i].opcode);
901       }
902       fprintf(out, "\n");
903       for(i=0; i<p->nOp; i++){
904         fprintf(out, "%6d %10lld %8lld ",
905            p->aOp[i].cnt,
906            p->aOp[i].cycles,
907            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
908         );
909         sqliteVdbePrintOp(out, i, &p->aOp[i]);
910       }
911       fclose(out);
912     }
913   }
914 #endif
915   p->magic = VDBE_MAGIC_INIT;
916   return p->rc;
917 }
918 
919 /*
920 ** Clean up and delete a VDBE after execution.  Return an integer which is
921 ** the result code.  Write any error message text into *pzErrMsg.
922 */
923 int sqliteVdbeFinalize(Vdbe *p, char **pzErrMsg){
924   int rc;
925   sqlite *db;
926 
927   if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
928     sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
929     return SQLITE_MISUSE;
930   }
931   db = p->db;
932   rc = sqliteVdbeReset(p, pzErrMsg);
933   sqliteVdbeDelete(p);
934   if( db->want_to_close && db->pVdbe==0 ){
935     sqlite_close(db);
936   }
937   if( rc==SQLITE_SCHEMA ){
938     sqliteResetInternalSchema(db, 0);
939   }
940   return rc;
941 }
942 
943 /*
944 ** Set the values of all variables.  Variable $1 in the original SQL will
945 ** be the string azValue[0].  $2 will have the value azValue[1].  And
946 ** so forth.  If a value is out of range (for example $3 when nValue==2)
947 ** then its value will be NULL.
948 **
949 ** This routine overrides any prior call.
950 */
951 int sqlite_bind(sqlite_vm *pVm, int i, const char *zVal, int len, int copy){
952   Vdbe *p = (Vdbe*)pVm;
953   if( p->magic!=VDBE_MAGIC_RUN || p->pc!=0 ){
954     return SQLITE_MISUSE;
955   }
956   if( i<1 || i>p->nVar ){
957     return SQLITE_RANGE;
958   }
959   i--;
960   if( p->abVar[i] ){
961     sqliteFree(p->azVar[i]);
962   }
963   if( zVal==0 ){
964     copy = 0;
965     len = 0;
966   }
967   if( len<0 ){
968     len = strlen(zVal)+1;
969   }
970   if( copy ){
971     p->azVar[i] = sqliteMalloc( len );
972     if( p->azVar[i] ) memcpy(p->azVar[i], zVal, len);
973   }else{
974     p->azVar[i] = (char*)zVal;
975   }
976   p->abVar[i] = copy;
977   p->anVar[i] = len;
978   return SQLITE_OK;
979 }
980 
981 
982 /*
983 ** Delete an entire VDBE.
984 */
985 void sqliteVdbeDelete(Vdbe *p){
986   int i;
987   if( p==0 ) return;
988   Cleanup(p);
989   if( p->pPrev ){
990     p->pPrev->pNext = p->pNext;
991   }else{
992     assert( p->db->pVdbe==p );
993     p->db->pVdbe = p->pNext;
994   }
995   if( p->pNext ){
996     p->pNext->pPrev = p->pPrev;
997   }
998   p->pPrev = p->pNext = 0;
999   if( p->nOpAlloc==0 ){
1000     p->aOp = 0;
1001     p->nOp = 0;
1002   }
1003   for(i=0; i<p->nOp; i++){
1004     if( p->aOp[i].p3type==P3_DYNAMIC ){
1005       sqliteFree(p->aOp[i].p3);
1006     }
1007   }
1008   for(i=0; i<p->nVar; i++){
1009     if( p->abVar[i] ) sqliteFree(p->azVar[i]);
1010   }
1011   sqliteFree(p->aOp);
1012   sqliteFree(p->aLabel);
1013   sqliteFree(p->aStack);
1014   p->magic = VDBE_MAGIC_DEAD;
1015   sqliteFree(p);
1016 }
1017 
1018 /*
1019 ** Convert an integer in between the native integer format and
1020 ** the bigEndian format used as the record number for tables.
1021 **
1022 ** The bigEndian format (most significant byte first) is used for
1023 ** record numbers so that records will sort into the correct order
1024 ** even though memcmp() is used to compare the keys.  On machines
1025 ** whose native integer format is little endian (ex: i486) the
1026 ** order of bytes is reversed.  On native big-endian machines
1027 ** (ex: Alpha, Sparc, Motorola) the byte order is the same.
1028 **
1029 ** This function is its own inverse.  In other words
1030 **
1031 **         X == byteSwap(byteSwap(X))
1032 */
1033 int sqliteVdbeByteSwap(int x){
1034   union {
1035      char zBuf[sizeof(int)];
1036      int i;
1037   } ux;
1038   ux.zBuf[3] = x&0xff;
1039   ux.zBuf[2] = (x>>8)&0xff;
1040   ux.zBuf[1] = (x>>16)&0xff;
1041   ux.zBuf[0] = (x>>24)&0xff;
1042   return ux.i;
1043 }
1044 
1045 /*
1046 ** If a MoveTo operation is pending on the given cursor, then do that
1047 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
1048 ** routine does nothing and returns SQLITE_OK.
1049 */
1050 int sqliteVdbeCursorMoveto(Cursor *p){
1051   if( p->deferredMoveto ){
1052     int res;
1053     extern int sqlite_search_count;
1054     sqliteBtreeMoveto(p->pCursor, (char*)&p->movetoTarget, sizeof(int), &res);
1055     p->lastRecno = keyToInt(p->movetoTarget);
1056     p->recnoIsValid = res==0;
1057     if( res<0 ){
1058       sqliteBtreeNext(p->pCursor, &res);
1059     }
1060     sqlite_search_count++;
1061     p->deferredMoveto = 0;
1062   }
1063   return SQLITE_OK;
1064 }
1065