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