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 : */
36 1496 : Vdbe *sqliteVdbeCreate(sqlite *db){
37 : Vdbe *p;
38 1496 : p = sqliteMalloc( sizeof(Vdbe) );
39 1496 : if( p==0 ) return 0;
40 1496 : p->db = db;
41 1496 : if( db->pVdbe ){
42 105 : db->pVdbe->pPrev = p;
43 : }
44 1496 : p->pNext = db->pVdbe;
45 1496 : p->pPrev = 0;
46 1496 : db->pVdbe = p;
47 1496 : p->magic = VDBE_MAGIC_INIT;
48 1496 : return p;
49 : }
50 :
51 : /*
52 : ** Turn tracing on or off
53 : */
54 1196 : void sqliteVdbeTrace(Vdbe *p, FILE *trace){
55 1196 : p->trace = trace;
56 1196 : }
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 : */
74 19670 : int sqliteVdbeAddOp(Vdbe *p, int op, int p1, int p2){
75 : int i;
76 : VdbeOp *pOp;
77 :
78 19670 : i = p->nOp;
79 19670 : p->nOp++;
80 : assert( p->magic==VDBE_MAGIC_INIT );
81 19670 : if( i>=p->nOpAlloc ){
82 1496 : int oldSize = p->nOpAlloc;
83 : Op *aNew;
84 1496 : p->nOpAlloc = p->nOpAlloc*2 + 100;
85 1496 : aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
86 1496 : if( aNew==0 ){
87 0 : p->nOpAlloc = oldSize;
88 0 : return 0;
89 : }
90 1496 : p->aOp = aNew;
91 1496 : memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
92 : }
93 19670 : pOp = &p->aOp[i];
94 19670 : pOp->opcode = op;
95 19670 : pOp->p1 = p1;
96 19670 : if( p2<0 && (-1-p2)<p->nLabel && p->aLabel[-1-p2]>=0 ){
97 0 : p2 = p->aLabel[-1-p2];
98 : }
99 19670 : pOp->p2 = p2;
100 19670 : pOp->p3 = 0;
101 19670 : pOp->p3type = P3_NOTUSED;
102 : #ifndef NDEBUG
103 : if( sqlite_vdbe_addop_trace ) sqliteVdbePrintOp(0, i, &p->aOp[i]);
104 : #endif
105 19670 : return i;
106 : }
107 :
108 : /*
109 : ** Add an opcode that includes the p3 value.
110 : */
111 5552 : int sqliteVdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3, int p3type){
112 5552 : int addr = sqliteVdbeAddOp(p, op, p1, p2);
113 5552 : sqliteVdbeChangeP3(p, addr, zP3, p3type);
114 5552 : return addr;
115 : }
116 :
117 : /*
118 : ** Add multiple opcodes. The list is terminated by an opcode of 0.
119 : */
120 0 : int sqliteVdbeCode(Vdbe *p, ...){
121 : int addr;
122 : va_list ap;
123 : int opcode, p1, p2;
124 0 : va_start(ap, p);
125 0 : addr = p->nOp;
126 0 : while( (opcode = va_arg(ap,int))!=0 ){
127 0 : p1 = va_arg(ap,int);
128 0 : p2 = va_arg(ap,int);
129 0 : sqliteVdbeAddOp(p, opcode, p1, p2);
130 : }
131 0 : va_end(ap);
132 0 : 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 : */
149 1855 : int sqliteVdbeMakeLabel(Vdbe *p){
150 : int i;
151 1855 : i = p->nLabel++;
152 : assert( p->magic==VDBE_MAGIC_INIT );
153 1855 : if( i>=p->nLabelAlloc ){
154 : int *aNew;
155 785 : p->nLabelAlloc = p->nLabelAlloc*2 + 10;
156 785 : aNew = sqliteRealloc( p->aLabel, p->nLabelAlloc*sizeof(p->aLabel[0]));
157 785 : if( aNew==0 ){
158 0 : sqliteFree(p->aLabel);
159 : }
160 785 : p->aLabel = aNew;
161 : }
162 1855 : if( p->aLabel==0 ){
163 0 : p->nLabel = 0;
164 0 : p->nLabelAlloc = 0;
165 0 : return 0;
166 : }
167 1855 : p->aLabel[i] = -1;
168 1855 : 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 : */
176 1855 : void sqliteVdbeResolveLabel(Vdbe *p, int x){
177 : int j;
178 : assert( p->magic==VDBE_MAGIC_INIT );
179 1855 : if( x<0 && (-x)<=p->nLabel && p->aOp ){
180 1855 : if( p->aLabel[-1-x]==p->nOp ) return;
181 : assert( p->aLabel[-1-x]<0 );
182 1855 : p->aLabel[-1-x] = p->nOp;
183 35466 : for(j=0; j<p->nOp; j++){
184 33611 : 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 : */
192 797 : int sqliteVdbeCurrentAddr(Vdbe *p){
193 : assert( p->magic==VDBE_MAGIC_INIT );
194 797 : 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 : */
201 2 : int sqliteVdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
202 : int addr;
203 : assert( p->magic==VDBE_MAGIC_INIT );
204 2 : if( p->nOp + nOp >= p->nOpAlloc ){
205 0 : int oldSize = p->nOpAlloc;
206 : Op *aNew;
207 0 : p->nOpAlloc = p->nOpAlloc*2 + nOp + 10;
208 0 : aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
209 0 : if( aNew==0 ){
210 0 : p->nOpAlloc = oldSize;
211 0 : return 0;
212 : }
213 0 : p->aOp = aNew;
214 0 : memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
215 : }
216 2 : addr = p->nOp;
217 2 : if( nOp>0 ){
218 : int i;
219 2 : VdbeOpList const *pIn = aOp;
220 18 : for(i=0; i<nOp; i++, pIn++){
221 16 : int p2 = pIn->p2;
222 16 : VdbeOp *pOut = &p->aOp[i+addr];
223 16 : pOut->opcode = pIn->opcode;
224 16 : pOut->p1 = pIn->p1;
225 16 : pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
226 16 : pOut->p3 = pIn->p3;
227 16 : 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 2 : p->nOp += nOp;
235 : }
236 2 : 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 : */
245 0 : void sqliteVdbeChangeP1(Vdbe *p, int addr, int val){
246 : assert( p->magic==VDBE_MAGIC_INIT );
247 0 : if( p && addr>=0 && p->nOp>addr && p->aOp ){
248 0 : p->aOp[addr].p1 = val;
249 : }
250 0 : }
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 : */
256 417 : void sqliteVdbeChangeP2(Vdbe *p, int addr, int val){
257 : assert( val>=0 );
258 : assert( p->magic==VDBE_MAGIC_INIT );
259 417 : if( p && addr>=0 && p->nOp>addr && p->aOp ){
260 417 : p->aOp[addr].p2 = val;
261 : }
262 417 : }
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 : */
281 6861 : void sqliteVdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
282 : Op *pOp;
283 : assert( p->magic==VDBE_MAGIC_INIT );
284 6861 : if( p==0 || p->aOp==0 ) return;
285 6861 : if( addr<0 || addr>=p->nOp ){
286 1307 : addr = p->nOp - 1;
287 1307 : if( addr<0 ) return;
288 : }
289 6861 : pOp = &p->aOp[addr];
290 6861 : if( pOp->p3 && pOp->p3type==P3_DYNAMIC ){
291 0 : sqliteFree(pOp->p3);
292 0 : pOp->p3 = 0;
293 : }
294 6861 : if( zP3==0 ){
295 14 : pOp->p3 = 0;
296 14 : pOp->p3type = P3_NOTUSED;
297 6847 : }else if( n<0 ){
298 1371 : pOp->p3 = (char*)zP3;
299 1371 : pOp->p3type = n;
300 : }else{
301 5476 : sqliteSetNString(&pOp->p3, zP3, n, 0);
302 5476 : 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 : */
315 906 : void sqliteVdbeDequoteP3(Vdbe *p, int addr){
316 : Op *pOp;
317 : assert( p->magic==VDBE_MAGIC_INIT );
318 906 : if( p->aOp==0 ) return;
319 906 : if( addr<0 || addr>=p->nOp ){
320 906 : addr = p->nOp - 1;
321 906 : if( addr<0 ) return;
322 : }
323 906 : pOp = &p->aOp[addr];
324 906 : if( pOp->p3==0 || pOp->p3[0]==0 ) return;
325 906 : if( pOp->p3type==P3_POINTER ) return;
326 906 : if( pOp->p3type!=P3_DYNAMIC ){
327 0 : pOp->p3 = sqliteStrDup(pOp->p3);
328 0 : pOp->p3type = P3_DYNAMIC;
329 : }
330 906 : 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 : */
338 1897 : 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 1897 : if( p->aOp==0 || addr<0 || addr>=p->nOp ) return;
344 1897 : pOp = &p->aOp[addr];
345 1897 : if( pOp->p3type==P3_POINTER ){
346 0 : return;
347 : }
348 1897 : if( pOp->p3type!=P3_DYNAMIC ){
349 0 : pOp->p3 = sqliteStrDup(pOp->p3);
350 0 : pOp->p3type = P3_DYNAMIC;
351 : }
352 1897 : z = (unsigned char*)pOp->p3;
353 1897 : if( z==0 ) return;
354 1897 : i = j = 0;
355 1897 : while( isspace(z[i]) ){ i++; }
356 11116 : while( z[i] ){
357 7322 : if( isspace(z[i]) ){
358 6 : z[j++] = ' ';
359 6 : while( isspace(z[++i]) ){}
360 : }else{
361 7316 : z[j++] = z[i++];
362 : }
363 : }
364 1897 : while( j>0 && isspace(z[j-1]) ){ j--; }
365 1897 : 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 : */
372 0 : int sqliteVdbeFindOp(Vdbe *p, int op, int p2){
373 : int i;
374 : assert( p->magic==VDBE_MAGIC_INIT );
375 0 : for(i=0; i<p->nOp; i++){
376 0 : if( p->aOp[i].opcode==op && p->aOp[i].p2==p2 ) return i+1;
377 : }
378 0 : return 0;
379 : }
380 :
381 : /*
382 : ** Return the opcode for a given address.
383 : */
384 0 : VdbeOp *sqliteVdbeGetOp(Vdbe *p, int addr){
385 : assert( p->magic==VDBE_MAGIC_INIT );
386 : assert( addr>=0 && addr<p->nOp );
387 0 : 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 : */
411 12 : char *sqlite_set_result_string(sqlite_func *p, const char *zResult, int n){
412 : assert( !p->isStep );
413 12 : if( p->s.flags & MEM_Dyn ){
414 0 : sqliteFree(p->s.z);
415 : }
416 12 : if( zResult==0 ){
417 2 : p->s.flags = MEM_Null;
418 2 : n = 0;
419 2 : p->s.z = 0;
420 2 : p->s.n = 0;
421 : }else{
422 10 : if( n<0 ) n = strlen(zResult);
423 10 : if( n<NBFS-1 ){
424 9 : memcpy(p->s.zShort, zResult, n);
425 9 : p->s.zShort[n] = 0;
426 9 : p->s.flags = MEM_Str | MEM_Short;
427 9 : p->s.z = p->s.zShort;
428 : }else{
429 1 : p->s.z = sqliteMallocRaw( n+1 );
430 1 : if( p->s.z ){
431 1 : memcpy(p->s.z, zResult, n);
432 1 : p->s.z[n] = 0;
433 : }
434 1 : p->s.flags = MEM_Str | MEM_Dyn;
435 : }
436 10 : p->s.n = n+1;
437 : }
438 12 : return p->s.z;
439 : }
440 13 : void sqlite_set_result_int(sqlite_func *p, int iResult){
441 : assert( !p->isStep );
442 13 : if( p->s.flags & MEM_Dyn ){
443 0 : sqliteFree(p->s.z);
444 : }
445 13 : p->s.i = iResult;
446 13 : p->s.flags = MEM_Int;
447 13 : }
448 0 : void sqlite_set_result_double(sqlite_func *p, double rResult){
449 : assert( !p->isStep );
450 0 : if( p->s.flags & MEM_Dyn ){
451 0 : sqliteFree(p->s.z);
452 : }
453 0 : p->s.r = rResult;
454 0 : p->s.flags = MEM_Real;
455 0 : }
456 1 : void sqlite_set_result_error(sqlite_func *p, const char *zMsg, int n){
457 : assert( !p->isStep );
458 1 : sqlite_set_result_string(p, zMsg, n);
459 1 : p->isError = 1;
460 1 : }
461 :
462 : /*
463 : ** Extract the user data from a sqlite_func structure and return a
464 : ** pointer to it.
465 : */
466 8 : void *sqlite_user_data(sqlite_func *p){
467 : assert( p && p->pFunc );
468 8 : 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 : */
480 60 : void *sqlite_aggregate_context(sqlite_func *p, int nByte){
481 : assert( p && p->pFunc && p->pFunc->xStep );
482 60 : if( p->pAgg==0 ){
483 14 : if( nByte<=NBFS ){
484 14 : p->pAgg = (void*)p->s.z;
485 14 : memset(p->pAgg, 0, nByte);
486 : }else{
487 0 : p->pAgg = sqliteMalloc( nByte );
488 : }
489 : }
490 60 : 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 : */
501 0 : int sqlite_aggregate_count(sqlite_func *p){
502 : assert( p && p->pFunc && p->pFunc->xStep );
503 0 : 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 : */
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 : */
533 : int sqliteVdbeList(
534 : Vdbe *p /* The VDBE */
535 0 : ){
536 0 : sqlite *db = p->db;
537 : int i;
538 0 : 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 0 : p->azColName = azColumnNames;
548 0 : p->azResColumn = p->zArgv;
549 0 : for(i=0; i<5; i++) p->zArgv[i] = p->aStack[i].zShort;
550 0 : i = p->pc;
551 0 : if( i>=p->nOp ){
552 0 : p->rc = SQLITE_OK;
553 0 : rc = SQLITE_DONE;
554 0 : }else if( db->flags & SQLITE_Interrupt ){
555 0 : db->flags &= ~SQLITE_Interrupt;
556 0 : if( db->magic!=SQLITE_MAGIC_BUSY ){
557 0 : p->rc = SQLITE_MISUSE;
558 : }else{
559 0 : p->rc = SQLITE_INTERRUPT;
560 : }
561 0 : rc = SQLITE_ERROR;
562 0 : sqliteSetString(&p->zErrMsg, sqlite_error_string(p->rc), (char*)0);
563 : }else{
564 0 : sprintf(p->zArgv[0],"%d",i);
565 0 : sprintf(p->zArgv[2],"%d", p->aOp[i].p1);
566 0 : sprintf(p->zArgv[3],"%d", p->aOp[i].p2);
567 0 : if( p->aOp[i].p3type==P3_POINTER ){
568 0 : sprintf(p->aStack[4].zShort, "ptr(%#lx)", (long)p->aOp[i].p3);
569 0 : p->zArgv[4] = p->aStack[4].zShort;
570 : }else{
571 0 : p->zArgv[4] = p->aOp[i].p3;
572 : }
573 0 : p->zArgv[1] = sqliteOpcodeNames[p->aOp[i].opcode];
574 0 : p->pc = i+1;
575 0 : p->azResColumn = p->zArgv;
576 0 : p->nResColumn = 5;
577 0 : p->rc = SQLITE_OK;
578 0 : rc = SQLITE_ROW;
579 : }
580 0 : 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 : */
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 1341 : ){
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 1341 : if( p->nOp==0 || (p->aOp && p->aOp[p->nOp-1].opcode!=OP_Halt) ){
602 893 : 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 1341 : if( p->aStack==0 ){
613 1196 : p->nVar = nVar;
614 : assert( nVar>=0 );
615 1196 : n = isExplain ? 10 : p->nOp;
616 1196 : 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 1196 : p->zArgv = (char**)&p->aStack[n];
621 1196 : p->azColName = (char**)&p->zArgv[n];
622 1196 : p->azVar = (char**)&p->azColName[n];
623 1196 : p->anVar = (int*)&p->azVar[p->nVar];
624 1196 : p->abVar = (u8*)&p->anVar[p->nVar];
625 : }
626 :
627 1341 : sqliteHashInit(&p->agg.hash, SQLITE_HASH_BINARY, 0);
628 1341 : p->agg.pSearch = 0;
629 : #ifdef MEMORY_DEBUG
630 : if( sqliteOsFileExists("vdbe_trace") ){
631 : p->trace = stdout;
632 : }
633 : #endif
634 1341 : p->pTos = &p->aStack[-1];
635 1341 : p->pc = 0;
636 1341 : p->rc = SQLITE_OK;
637 1341 : p->uniqueCnt = 0;
638 1341 : p->returnDepth = 0;
639 1341 : p->errorAction = OE_Abort;
640 1341 : p->undoTransOnError = 0;
641 1341 : p->popStack = 0;
642 1341 : p->explain |= isExplain;
643 1341 : 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 1341 : }
654 :
655 :
656 : /*
657 : ** Remove any elements that remain on the sorter for the VDBE given.
658 : */
659 2693 : void sqliteVdbeSorterReset(Vdbe *p){
660 5386 : while( p->pSort ){
661 0 : Sorter *pSorter = p->pSort;
662 0 : p->pSort = pSorter->pNext;
663 0 : sqliteFree(pSorter->zKey);
664 0 : sqliteFree(pSorter->pData);
665 0 : sqliteFree(pSorter);
666 : }
667 2693 : }
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 : */
678 2707 : void sqliteVdbeAggReset(Agg *pAgg){
679 : int i;
680 : HashElem *p;
681 2721 : for(p = sqliteHashFirst(&pAgg->hash); p; p = sqliteHashNext(p)){
682 14 : AggElem *pElem = sqliteHashData(p);
683 : assert( pAgg->apFunc!=0 );
684 28 : for(i=0; i<pAgg->nMem; i++){
685 14 : Mem *pMem = &pElem->aMem[i];
686 14 : if( pAgg->apFunc[i] && (pMem->flags & MEM_AggCtx)!=0 ){
687 : sqlite_func ctx;
688 0 : ctx.pFunc = pAgg->apFunc[i];
689 0 : ctx.s.flags = MEM_Null;
690 0 : ctx.pAgg = pMem->z;
691 0 : ctx.cnt = pMem->i;
692 0 : ctx.isStep = 0;
693 0 : ctx.isError = 0;
694 0 : (*pAgg->apFunc[i]->xFinalize)(&ctx);
695 0 : if( pMem->z!=0 && pMem->z!=pMem->zShort ){
696 0 : sqliteFree(pMem->z);
697 : }
698 0 : if( ctx.s.flags & MEM_Dyn ){
699 0 : sqliteFree(ctx.s.z);
700 : }
701 14 : }else if( pMem->flags & MEM_Dyn ){
702 0 : sqliteFree(pMem->z);
703 : }
704 : }
705 14 : sqliteFree(pElem);
706 : }
707 2707 : sqliteHashClear(&pAgg->hash);
708 2707 : sqliteFree(pAgg->apFunc);
709 2707 : pAgg->apFunc = 0;
710 2707 : pAgg->pCurrent = 0;
711 2707 : pAgg->pSearch = 0;
712 2707 : pAgg->nMem = 0;
713 2707 : }
714 :
715 : /*
716 : ** Delete a keylist
717 : */
718 0 : void sqliteVdbeKeylistFree(Keylist *p){
719 0 : while( p ){
720 0 : Keylist *pNext = p->pNext;
721 0 : sqliteFree(p);
722 0 : p = pNext;
723 : }
724 0 : }
725 :
726 : /*
727 : ** Close a cursor and release all the resources that cursor happens
728 : ** to hold.
729 : */
730 3209 : void sqliteVdbeCleanupCursor(Cursor *pCx){
731 3209 : if( pCx->pCursor ){
732 1078 : sqliteBtreeCloseCursor(pCx->pCursor);
733 : }
734 3209 : if( pCx->pBt ){
735 0 : sqliteBtreeClose(pCx->pBt);
736 : }
737 3209 : sqliteFree(pCx->pData);
738 3209 : memset(pCx, 0, sizeof(Cursor));
739 3209 : }
740 :
741 : /*
742 : ** Close all cursors
743 : */
744 2693 : static void closeAllCursors(Vdbe *p){
745 : int i;
746 3768 : for(i=0; i<p->nCursor; i++){
747 1075 : sqliteVdbeCleanupCursor(&p->aCsr[i]);
748 : }
749 2693 : sqliteFree(p->aCsr);
750 2693 : p->aCsr = 0;
751 2693 : p->nCursor = 0;
752 2693 : }
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 : */
761 2693 : static void Cleanup(Vdbe *p){
762 : int i;
763 2693 : if( p->aStack ){
764 2393 : Mem *pTos = p->pTos;
765 4926 : while( pTos>=p->aStack ){
766 140 : if( pTos->flags & MEM_Dyn ){
767 1 : sqliteFree(pTos->z);
768 : }
769 140 : pTos--;
770 : }
771 2393 : p->pTos = pTos;
772 : }
773 2693 : closeAllCursors(p);
774 2693 : if( p->aMem ){
775 273 : for(i=0; i<p->nMem; i++){
776 229 : if( p->aMem[i].flags & MEM_Dyn ){
777 0 : sqliteFree(p->aMem[i].z);
778 : }
779 : }
780 : }
781 2693 : sqliteFree(p->aMem);
782 2693 : p->aMem = 0;
783 2693 : p->nMem = 0;
784 2693 : if( p->pList ){
785 0 : sqliteVdbeKeylistFree(p->pList);
786 0 : p->pList = 0;
787 : }
788 2693 : sqliteVdbeSorterReset(p);
789 2693 : if( p->pFile ){
790 0 : if( p->pFile!=stdin ) fclose(p->pFile);
791 0 : p->pFile = 0;
792 : }
793 2693 : if( p->azField ){
794 0 : sqliteFree(p->azField);
795 0 : p->azField = 0;
796 : }
797 2693 : p->nField = 0;
798 2693 : if( p->zLine ){
799 0 : sqliteFree(p->zLine);
800 0 : p->zLine = 0;
801 : }
802 2693 : p->nLineAlloc = 0;
803 2693 : sqliteVdbeAggReset(&p->agg);
804 2693 : if( p->aSet ){
805 0 : for(i=0; i<p->nSet; i++){
806 0 : sqliteHashClear(&p->aSet[i].hash);
807 : }
808 : }
809 2693 : sqliteFree(p->aSet);
810 2693 : p->aSet = 0;
811 2693 : p->nSet = 0;
812 2693 : if( p->keylistStack ){
813 : int ii;
814 0 : for(ii = 0; ii < p->keylistStackDepth; ii++){
815 0 : sqliteVdbeKeylistFree(p->keylistStack[ii]);
816 : }
817 0 : sqliteFree(p->keylistStack);
818 0 : p->keylistStackDepth = 0;
819 0 : p->keylistStack = 0;
820 : }
821 2693 : sqliteFree(p->contextStack);
822 2693 : p->contextStack = 0;
823 2693 : sqliteFree(p->zErrMsg);
824 2693 : p->zErrMsg = 0;
825 2693 : }
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 : */
834 1269 : int sqliteVdbeReset(Vdbe *p, char **pzErrMsg){
835 1269 : sqlite *db = p->db;
836 : int i;
837 :
838 1269 : if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
839 0 : sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
840 0 : return SQLITE_MISUSE;
841 : }
842 1269 : if( p->zErrMsg ){
843 2 : if( pzErrMsg && *pzErrMsg==0 ){
844 1 : *pzErrMsg = p->zErrMsg;
845 : }else{
846 0 : sqliteFree(p->zErrMsg);
847 : }
848 1 : p->zErrMsg = 0;
849 1268 : }else if( p->rc ){
850 0 : sqliteSetString(pzErrMsg, sqlite_error_string(p->rc), (char*)0);
851 : }
852 1269 : Cleanup(p);
853 1269 : if( p->rc!=SQLITE_OK ){
854 1 : switch( p->errorAction ){
855 : case OE_Abort: {
856 1 : if( !p->undoTransOnError ){
857 3 : for(i=0; i<db->nDb; i++){
858 2 : if( db->aDb[i].pBt ){
859 2 : sqliteBtreeRollbackCkpt(db->aDb[i].pBt);
860 : }
861 : }
862 1 : break;
863 : }
864 : /* Fall through to ROLLBACK */
865 : }
866 : case OE_Rollback: {
867 0 : sqliteRollbackAll(db);
868 0 : db->flags &= ~SQLITE_InTrans;
869 0 : db->onError = OE_Default;
870 0 : break;
871 : }
872 : default: {
873 0 : if( p->undoTransOnError ){
874 0 : sqliteRollbackAll(db);
875 0 : db->flags &= ~SQLITE_InTrans;
876 0 : db->onError = OE_Default;
877 : }
878 : break;
879 : }
880 : }
881 1 : sqliteRollbackInternalChanges(db);
882 : }
883 3807 : for(i=0; i<db->nDb; i++){
884 2538 : if( db->aDb[i].pBt && db->aDb[i].inTrans==2 ){
885 0 : sqliteBtreeCommitCkpt(db->aDb[i].pBt);
886 0 : 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 1269 : p->magic = VDBE_MAGIC_INIT;
913 1269 : 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 : */
920 1124 : int sqliteVdbeFinalize(Vdbe *p, char **pzErrMsg){
921 : int rc;
922 : sqlite *db;
923 :
924 1124 : if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
925 0 : sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
926 0 : return SQLITE_MISUSE;
927 : }
928 1124 : db = p->db;
929 1124 : rc = sqliteVdbeReset(p, pzErrMsg);
930 1124 : sqliteVdbeDelete(p);
931 1124 : if( db->want_to_close && db->pVdbe==0 ){
932 0 : sqlite_close(db);
933 : }
934 1124 : if( rc==SQLITE_SCHEMA ){
935 0 : sqliteResetInternalSchema(db, 0);
936 : }
937 1124 : 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 : */
948 0 : int sqlite_bind(sqlite_vm *pVm, int i, const char *zVal, int len, int copy){
949 0 : Vdbe *p = (Vdbe*)pVm;
950 0 : if( p->magic!=VDBE_MAGIC_RUN || p->pc!=0 ){
951 0 : return SQLITE_MISUSE;
952 : }
953 0 : if( i<1 || i>p->nVar ){
954 0 : return SQLITE_RANGE;
955 : }
956 0 : i--;
957 0 : if( p->abVar[i] ){
958 0 : sqliteFree(p->azVar[i]);
959 : }
960 0 : if( zVal==0 ){
961 0 : copy = 0;
962 0 : len = 0;
963 : }
964 0 : if( len<0 ){
965 0 : len = strlen(zVal)+1;
966 : }
967 0 : if( copy ){
968 0 : p->azVar[i] = sqliteMalloc( len );
969 0 : if( p->azVar[i] ) memcpy(p->azVar[i], zVal, len);
970 : }else{
971 0 : p->azVar[i] = (char*)zVal;
972 : }
973 0 : p->abVar[i] = copy;
974 0 : p->anVar[i] = len;
975 0 : return SQLITE_OK;
976 : }
977 :
978 :
979 : /*
980 : ** Delete an entire VDBE.
981 : */
982 1424 : void sqliteVdbeDelete(Vdbe *p){
983 : int i;
984 1424 : if( p==0 ) return;
985 1424 : Cleanup(p);
986 1424 : if( p->pPrev ){
987 9 : p->pPrev->pNext = p->pNext;
988 : }else{
989 : assert( p->db->pVdbe==p );
990 1415 : p->db->pVdbe = p->pNext;
991 : }
992 1424 : if( p->pNext ){
993 49 : p->pNext->pPrev = p->pPrev;
994 : }
995 1424 : p->pPrev = p->pNext = 0;
996 1424 : if( p->nOpAlloc==0 ){
997 0 : p->aOp = 0;
998 0 : p->nOp = 0;
999 : }
1000 19455 : for(i=0; i<p->nOp; i++){
1001 18031 : if( p->aOp[i].p3type==P3_DYNAMIC ){
1002 5226 : sqliteFree(p->aOp[i].p3);
1003 : }
1004 : }
1005 1424 : for(i=0; i<p->nVar; i++){
1006 0 : if( p->abVar[i] ) sqliteFree(p->azVar[i]);
1007 : }
1008 1424 : sqliteFree(p->aOp);
1009 1424 : sqliteFree(p->aLabel);
1010 1424 : sqliteFree(p->aStack);
1011 1424 : p->magic = VDBE_MAGIC_DEAD;
1012 1424 : 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 : */
1030 1090 : int sqliteVdbeByteSwap(int x){
1031 : union {
1032 : char zBuf[sizeof(int)];
1033 : int i;
1034 : } ux;
1035 1090 : ux.zBuf[3] = x&0xff;
1036 1090 : ux.zBuf[2] = (x>>8)&0xff;
1037 1090 : ux.zBuf[1] = (x>>16)&0xff;
1038 1090 : ux.zBuf[0] = (x>>24)&0xff;
1039 1090 : 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 : */
1047 992 : int sqliteVdbeCursorMoveto(Cursor *p){
1048 992 : if( p->deferredMoveto ){
1049 : int res;
1050 : extern int sqlite_search_count;
1051 77 : sqliteBtreeMoveto(p->pCursor, (char*)&p->movetoTarget, sizeof(int), &res);
1052 77 : p->lastRecno = keyToInt(p->movetoTarget);
1053 77 : p->recnoIsValid = res==0;
1054 77 : if( res<0 ){
1055 0 : sqliteBtreeNext(p->pCursor, &res);
1056 : }
1057 77 : sqlite_search_count++;
1058 77 : p->deferredMoveto = 0;
1059 : }
1060 992 : return SQLITE_OK;
1061 : }
|