Back to index

php5  5.3.10
vdbeaux.c
Go to the documentation of this file.
00001 /*
00002 ** 2003 September 6
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** This file contains code used for creating, destroying, and populating
00013 ** a VDBE (or an "sqlite_vm" as it is known to the outside world.)  Prior
00014 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
00015 ** But that file was getting too big so this subroutines were split out.
00016 */
00017 #include "sqliteInt.h"
00018 #include "os.h"
00019 #include <ctype.h>
00020 #include "vdbeInt.h"
00021 
00022 
00023 /*
00024 ** When debugging the code generator in a symbolic debugger, one can
00025 ** set the sqlite_vdbe_addop_trace to 1 and all opcodes will be printed
00026 ** as they are added to the instruction stream.
00027 */
00028 #ifndef NDEBUG
00029 int sqlite_vdbe_addop_trace = 0;
00030 #endif
00031 
00032 
00033 /*
00034 ** Create a new virtual database engine.
00035 */
00036 Vdbe *sqliteVdbeCreate(sqlite *db){
00037   Vdbe *p;
00038   p = sqliteMalloc( sizeof(Vdbe) );
00039   if( p==0 ) return 0;
00040   p->db = db;
00041   if( db->pVdbe ){
00042     db->pVdbe->pPrev = p;
00043   }
00044   p->pNext = db->pVdbe;
00045   p->pPrev = 0;
00046   db->pVdbe = p;
00047   p->magic = VDBE_MAGIC_INIT;
00048   return p;
00049 }
00050 
00051 /*
00052 ** Turn tracing on or off
00053 */
00054 void sqliteVdbeTrace(Vdbe *p, FILE *trace){
00055   p->trace = trace;
00056 }
00057 
00058 /*
00059 ** Add a new instruction to the list of instructions current in the
00060 ** VDBE.  Return the address of the new instruction.
00061 **
00062 ** Parameters:
00063 **
00064 **    p               Pointer to the VDBE
00065 **
00066 **    op              The opcode for this instruction
00067 **
00068 **    p1, p2          First two of the three possible operands.
00069 **
00070 ** Use the sqliteVdbeResolveLabel() function to fix an address and
00071 ** the sqliteVdbeChangeP3() function to change the value of the P3
00072 ** operand.
00073 */
00074 int sqliteVdbeAddOp(Vdbe *p, int op, int p1, int p2){
00075   int i;
00076   VdbeOp *pOp;
00077 
00078   i = p->nOp;
00079   p->nOp++;
00080   assert( p->magic==VDBE_MAGIC_INIT );
00081   if( i>=p->nOpAlloc ){
00082     int oldSize = p->nOpAlloc;
00083     Op *aNew;
00084     p->nOpAlloc = p->nOpAlloc*2 + 100;
00085     aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
00086     if( aNew==0 ){
00087       p->nOpAlloc = oldSize;
00088       return 0;
00089     }
00090     p->aOp = aNew;
00091     memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
00092   }
00093   pOp = &p->aOp[i];
00094   pOp->opcode = op;
00095   pOp->p1 = p1;
00096   if( p2<0 && (-1-p2)<p->nLabel && p->aLabel[-1-p2]>=0 ){
00097     p2 = p->aLabel[-1-p2];
00098   }
00099   pOp->p2 = p2;
00100   pOp->p3 = 0;
00101   pOp->p3type = P3_NOTUSED;
00102 #ifndef NDEBUG
00103   if( sqlite_vdbe_addop_trace ) sqliteVdbePrintOp(0, i, &p->aOp[i]);
00104 #endif
00105   return i;
00106 }
00107 
00108 /*
00109 ** Add an opcode that includes the p3 value.
00110 */
00111 int sqliteVdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3, int p3type){
00112   int addr = sqliteVdbeAddOp(p, op, p1, p2);
00113   sqliteVdbeChangeP3(p, addr, zP3, p3type);
00114   return addr;
00115 }
00116 
00117 /*
00118 ** Add multiple opcodes.  The list is terminated by an opcode of 0.
00119 */
00120 int sqliteVdbeCode(Vdbe *p, ...){
00121   int addr;
00122   va_list ap;
00123   int opcode, p1, p2;
00124   va_start(ap, p);
00125   addr = p->nOp;
00126   while( (opcode = va_arg(ap,int))!=0 ){
00127     p1 = va_arg(ap,int);
00128     p2 = va_arg(ap,int);
00129     sqliteVdbeAddOp(p, opcode, p1, p2);
00130   }
00131   va_end(ap);
00132   return addr;
00133 }
00134 
00135 
00136 
00137 /*
00138 ** Create a new symbolic label for an instruction that has yet to be
00139 ** coded.  The symbolic label is really just a negative number.  The
00140 ** label can be used as the P2 value of an operation.  Later, when
00141 ** the label is resolved to a specific address, the VDBE will scan
00142 ** through its operation list and change all values of P2 which match
00143 ** the label into the resolved address.
00144 **
00145 ** The VDBE knows that a P2 value is a label because labels are
00146 ** always negative and P2 values are suppose to be non-negative.
00147 ** Hence, a negative P2 value is a label that has yet to be resolved.
00148 */
00149 int sqliteVdbeMakeLabel(Vdbe *p){
00150   int i;
00151   i = p->nLabel++;
00152   assert( p->magic==VDBE_MAGIC_INIT );
00153   if( i>=p->nLabelAlloc ){
00154     int *aNew;
00155     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
00156     aNew = sqliteRealloc( p->aLabel, p->nLabelAlloc*sizeof(p->aLabel[0]));
00157     if( aNew==0 ){
00158       sqliteFree(p->aLabel);
00159     }
00160     p->aLabel = aNew;
00161   }
00162   if( p->aLabel==0 ){
00163     p->nLabel = 0;
00164     p->nLabelAlloc = 0;
00165     return 0;
00166   }
00167   p->aLabel[i] = -1;
00168   return -1-i;
00169 }
00170 
00171 /*
00172 ** Resolve label "x" to be the address of the next instruction to
00173 ** be inserted.  The parameter "x" must have been obtained from
00174 ** a prior call to sqliteVdbeMakeLabel().
00175 */
00176 void sqliteVdbeResolveLabel(Vdbe *p, int x){
00177   int j;
00178   assert( p->magic==VDBE_MAGIC_INIT );
00179   if( x<0 && (-x)<=p->nLabel && p->aOp ){
00180     if( p->aLabel[-1-x]==p->nOp ) return;
00181     assert( p->aLabel[-1-x]<0 );
00182     p->aLabel[-1-x] = p->nOp;
00183     for(j=0; j<p->nOp; j++){
00184       if( p->aOp[j].p2==x ) p->aOp[j].p2 = p->nOp;
00185     }
00186   }
00187 }
00188 
00189 /*
00190 ** Return the address of the next instruction to be inserted.
00191 */
00192 int sqliteVdbeCurrentAddr(Vdbe *p){
00193   assert( p->magic==VDBE_MAGIC_INIT );
00194   return p->nOp;
00195 }
00196 
00197 /*
00198 ** Add a whole list of operations to the operation stack.  Return the
00199 ** address of the first operation added.
00200 */
00201 int sqliteVdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
00202   int addr;
00203   assert( p->magic==VDBE_MAGIC_INIT );
00204   if( p->nOp + nOp >= p->nOpAlloc ){
00205     int oldSize = p->nOpAlloc;
00206     Op *aNew;
00207     p->nOpAlloc = p->nOpAlloc*2 + nOp + 10;
00208     aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
00209     if( aNew==0 ){
00210       p->nOpAlloc = oldSize;
00211       return 0;
00212     }
00213     p->aOp = aNew;
00214     memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
00215   }
00216   addr = p->nOp;
00217   if( nOp>0 ){
00218     int i;
00219     VdbeOpList const *pIn = aOp;
00220     for(i=0; i<nOp; i++, pIn++){
00221       int p2 = pIn->p2;
00222       VdbeOp *pOut = &p->aOp[i+addr];
00223       pOut->opcode = pIn->opcode;
00224       pOut->p1 = pIn->p1;
00225       pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
00226       pOut->p3 = pIn->p3;
00227       pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
00228 #ifndef NDEBUG
00229       if( sqlite_vdbe_addop_trace ){
00230         sqliteVdbePrintOp(0, i+addr, &p->aOp[i+addr]);
00231       }
00232 #endif
00233     }
00234     p->nOp += nOp;
00235   }
00236   return addr;
00237 }
00238 
00239 /*
00240 ** Change the value of the P1 operand for a specific instruction.
00241 ** This routine is useful when a large program is loaded from a
00242 ** static array using sqliteVdbeAddOpList but we want to make a
00243 ** few minor changes to the program.
00244 */
00245 void sqliteVdbeChangeP1(Vdbe *p, int addr, int val){
00246   assert( p->magic==VDBE_MAGIC_INIT );
00247   if( p && addr>=0 && p->nOp>addr && p->aOp ){
00248     p->aOp[addr].p1 = val;
00249   }
00250 }
00251 
00252 /*
00253 ** Change the value of the P2 operand for a specific instruction.
00254 ** This routine is useful for setting a jump destination.
00255 */
00256 void sqliteVdbeChangeP2(Vdbe *p, int addr, int val){
00257   assert( val>=0 );
00258   assert( p->magic==VDBE_MAGIC_INIT );
00259   if( p && addr>=0 && p->nOp>addr && p->aOp ){
00260     p->aOp[addr].p2 = val;
00261   }
00262 }
00263 
00264 /*
00265 ** Change the value of the P3 operand for a specific instruction.
00266 ** This routine is useful when a large program is loaded from a
00267 ** static array using sqliteVdbeAddOpList but we want to make a
00268 ** few minor changes to the program.
00269 **
00270 ** If n>=0 then the P3 operand is dynamic, meaning that a copy of
00271 ** the string is made into memory obtained from sqliteMalloc().
00272 ** A value of n==0 means copy bytes of zP3 up to and including the
00273 ** first null byte.  If n>0 then copy n+1 bytes of zP3.
00274 **
00275 ** If n==P3_STATIC  it means that zP3 is a pointer to a constant static
00276 ** string and we can just copy the pointer.  n==P3_POINTER means zP3 is
00277 ** a pointer to some object other than a string.
00278 **
00279 ** If addr<0 then change P3 on the most recently inserted instruction.
00280 */
00281 void sqliteVdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
00282   Op *pOp;
00283   assert( p->magic==VDBE_MAGIC_INIT );
00284   if( p==0 || p->aOp==0 ) return;
00285   if( addr<0 || addr>=p->nOp ){
00286     addr = p->nOp - 1;
00287     if( addr<0 ) return;
00288   }
00289   pOp = &p->aOp[addr];
00290   if( pOp->p3 && pOp->p3type==P3_DYNAMIC ){
00291     sqliteFree(pOp->p3);
00292     pOp->p3 = 0;
00293   }
00294   if( zP3==0 ){
00295     pOp->p3 = 0;
00296     pOp->p3type = P3_NOTUSED;
00297   }else if( n<0 ){
00298     pOp->p3 = (char*)zP3;
00299     pOp->p3type = n;
00300   }else{
00301     sqliteSetNString(&pOp->p3, zP3, n, 0);
00302     pOp->p3type = P3_DYNAMIC;
00303   }
00304 }
00305 
00306 /*
00307 ** If the P3 operand to the specified instruction appears
00308 ** to be a quoted string token, then this procedure removes 
00309 ** the quotes.
00310 **
00311 ** The quoting operator can be either a grave ascent (ASCII 0x27)
00312 ** or a double quote character (ASCII 0x22).  Two quotes in a row
00313 ** resolve to be a single actual quote character within the string.
00314 */
00315 void sqliteVdbeDequoteP3(Vdbe *p, int addr){
00316   Op *pOp;
00317   assert( p->magic==VDBE_MAGIC_INIT );
00318   if( p->aOp==0 ) return;
00319   if( addr<0 || addr>=p->nOp ){
00320     addr = p->nOp - 1;
00321     if( addr<0 ) return;
00322   }
00323   pOp = &p->aOp[addr];
00324   if( pOp->p3==0 || pOp->p3[0]==0 ) return;
00325   if( pOp->p3type==P3_POINTER ) return;
00326   if( pOp->p3type!=P3_DYNAMIC ){
00327     pOp->p3 = sqliteStrDup(pOp->p3);
00328     pOp->p3type = P3_DYNAMIC;
00329   }
00330   sqliteDequote(pOp->p3);
00331 }
00332 
00333 /*
00334 ** On the P3 argument of the given instruction, change all
00335 ** strings of whitespace characters into a single space and
00336 ** delete leading and trailing whitespace.
00337 */
00338 void sqliteVdbeCompressSpace(Vdbe *p, int addr){
00339   unsigned char *z;
00340   int i, j;
00341   Op *pOp;
00342   assert( p->magic==VDBE_MAGIC_INIT );
00343   if( p->aOp==0 || addr<0 || addr>=p->nOp ) return;
00344   pOp = &p->aOp[addr];
00345   if( pOp->p3type==P3_POINTER ){
00346     return;
00347   }
00348   if( pOp->p3type!=P3_DYNAMIC ){
00349     pOp->p3 = sqliteStrDup(pOp->p3);
00350     pOp->p3type = P3_DYNAMIC;
00351   }
00352   z = (unsigned char*)pOp->p3;
00353   if( z==0 ) return;
00354   i = j = 0;
00355   while( isspace(z[i]) ){ i++; }
00356   while( z[i] ){
00357     if( isspace(z[i]) ){
00358       z[j++] = ' ';
00359       while( isspace(z[++i]) ){}
00360     }else{
00361       z[j++] = z[i++];
00362     }
00363   }
00364   while( j>0 && isspace(z[j-1]) ){ j--; }
00365   z[j] = 0;
00366 }
00367 
00368 /*
00369 ** Search for the current program for the given opcode and P2
00370 ** value.  Return the address plus 1 if found and 0 if not found.
00371 */
00372 int sqliteVdbeFindOp(Vdbe *p, int op, int p2){
00373   int i;
00374   assert( p->magic==VDBE_MAGIC_INIT );
00375   for(i=0; i<p->nOp; i++){
00376     if( p->aOp[i].opcode==op && p->aOp[i].p2==p2 ) return i+1;
00377   }
00378   return 0;
00379 }
00380 
00381 /*
00382 ** Return the opcode for a given address.
00383 */
00384 VdbeOp *sqliteVdbeGetOp(Vdbe *p, int addr){
00385   assert( p->magic==VDBE_MAGIC_INIT );
00386   assert( addr>=0 && addr<p->nOp );
00387   return &p->aOp[addr];
00388 }
00389 
00390 /*
00391 ** The following group or routines are employed by installable functions
00392 ** to return their results.
00393 **
00394 ** The sqlite_set_result_string() routine can be used to return a string
00395 ** value or to return a NULL.  To return a NULL, pass in NULL for zResult.
00396 ** A copy is made of the string before this routine returns so it is safe
00397 ** to pass in an ephemeral string.
00398 **
00399 ** sqlite_set_result_error() works like sqlite_set_result_string() except
00400 ** that it signals a fatal error.  The string argument, if any, is the
00401 ** error message.  If the argument is NULL a generic substitute error message
00402 ** is used.
00403 **
00404 ** The sqlite_set_result_int() and sqlite_set_result_double() set the return
00405 ** value of the user function to an integer or a double.
00406 **
00407 ** These routines are defined here in vdbe.c because they depend on knowing
00408 ** the internals of the sqlite_func structure which is only defined in 
00409 ** this source file.
00410 */
00411 char *sqlite_set_result_string(sqlite_func *p, const char *zResult, int n){
00412   assert( !p->isStep );
00413   if( p->s.flags & MEM_Dyn ){
00414     sqliteFree(p->s.z);
00415   }
00416   if( zResult==0 ){
00417     p->s.flags = MEM_Null;
00418     n = 0;
00419     p->s.z = 0;
00420     p->s.n = 0;
00421   }else{
00422     if( n<0 ) n = strlen(zResult);
00423     if( n<NBFS-1 ){
00424       memcpy(p->s.zShort, zResult, n);
00425       p->s.zShort[n] = 0;
00426       p->s.flags = MEM_Str | MEM_Short;
00427       p->s.z = p->s.zShort;
00428     }else{
00429       p->s.z = sqliteMallocRaw( n+1 );
00430       if( p->s.z ){
00431         memcpy(p->s.z, zResult, n);
00432         p->s.z[n] = 0;
00433       }
00434       p->s.flags = MEM_Str | MEM_Dyn;
00435     }
00436     p->s.n = n+1;
00437   }
00438   return p->s.z;
00439 }
00440 void sqlite_set_result_int(sqlite_func *p, int iResult){
00441   assert( !p->isStep );
00442   if( p->s.flags & MEM_Dyn ){
00443     sqliteFree(p->s.z);
00444   }
00445   p->s.i = iResult;
00446   p->s.flags = MEM_Int;
00447 }
00448 void sqlite_set_result_double(sqlite_func *p, double rResult){
00449   assert( !p->isStep );
00450   if( p->s.flags & MEM_Dyn ){
00451     sqliteFree(p->s.z);
00452   }
00453   p->s.r = rResult;
00454   p->s.flags = MEM_Real;
00455 }
00456 void sqlite_set_result_error(sqlite_func *p, const char *zMsg, int n){
00457   assert( !p->isStep );
00458   sqlite_set_result_string(p, zMsg, n);
00459   p->isError = 1;
00460 }
00461 
00462 /*
00463 ** Extract the user data from a sqlite_func structure and return a
00464 ** pointer to it.
00465 */
00466 void *sqlite_user_data(sqlite_func *p){
00467   assert( p && p->pFunc );
00468   return p->pFunc->pUserData;
00469 }
00470 
00471 /*
00472 ** Allocate or return the aggregate context for a user function.  A new
00473 ** context is allocated on the first call.  Subsequent calls return the
00474 ** same context that was returned on prior calls.
00475 **
00476 ** This routine is defined here in vdbe.c because it depends on knowing
00477 ** the internals of the sqlite_func structure which is only defined in
00478 ** this source file.
00479 */
00480 void *sqlite_aggregate_context(sqlite_func *p, int nByte){
00481   assert( p && p->pFunc && p->pFunc->xStep );
00482   if( p->pAgg==0 ){
00483     if( nByte<=NBFS ){
00484       p->pAgg = (void*)p->s.z;
00485       memset(p->pAgg, 0, nByte);
00486     }else{
00487       p->pAgg = sqliteMalloc( nByte );
00488     }
00489   }
00490   return p->pAgg;
00491 }
00492 
00493 /*
00494 ** Return the number of times the Step function of a aggregate has been 
00495 ** called.
00496 **
00497 ** This routine is defined here in vdbe.c because it depends on knowing
00498 ** the internals of the sqlite_func structure which is only defined in
00499 ** this source file.
00500 */
00501 int sqlite_aggregate_count(sqlite_func *p){
00502   assert( p && p->pFunc && p->pFunc->xStep );
00503   return p->cnt;
00504 }
00505 
00506 #if !defined(NDEBUG) || defined(VDBE_PROFILE)
00507 /*
00508 ** Print a single opcode.  This routine is used for debugging only.
00509 */
00510 void sqliteVdbePrintOp(FILE *pOut, int pc, Op *pOp){
00511   char *zP3;
00512   char zPtr[40];
00513   if( pOp->p3type==P3_POINTER ){
00514     sprintf(zPtr, "ptr(%#lx)", (long)pOp->p3);
00515     zP3 = zPtr;
00516   }else{
00517     zP3 = pOp->p3;
00518   }
00519   if( pOut==0 ) pOut = stdout;
00520   fprintf(pOut,"%4d %-12s %4d %4d %s\n",
00521       pc, sqliteOpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3 ? zP3 : "");
00522   fflush(pOut);
00523 }
00524 #endif
00525 
00526 /*
00527 ** Give a listing of the program in the virtual machine.
00528 **
00529 ** The interface is the same as sqliteVdbeExec().  But instead of
00530 ** running the code, it invokes the callback once for each instruction.
00531 ** This feature is used to implement "EXPLAIN".
00532 */
00533 int sqliteVdbeList(
00534   Vdbe *p                   /* The VDBE */
00535 ){
00536   sqlite *db = p->db;
00537   int i;
00538   int rc = SQLITE_OK;
00539   static char *azColumnNames[] = {
00540      "addr", "opcode", "p1",  "p2",  "p3", 
00541      "int",  "text",   "int", "int", "text",
00542      0
00543   };
00544 
00545   assert( p->popStack==0 );
00546   assert( p->explain );
00547   p->azColName = azColumnNames;
00548   p->azResColumn = p->zArgv;
00549   for(i=0; i<5; i++) p->zArgv[i] = p->aStack[i].zShort;
00550   i = p->pc;
00551   if( i>=p->nOp ){
00552     p->rc = SQLITE_OK;
00553     rc = SQLITE_DONE;
00554   }else if( db->flags & SQLITE_Interrupt ){
00555     db->flags &= ~SQLITE_Interrupt;
00556     if( db->magic!=SQLITE_MAGIC_BUSY ){
00557       p->rc = SQLITE_MISUSE;
00558     }else{
00559       p->rc = SQLITE_INTERRUPT;
00560     }
00561     rc = SQLITE_ERROR;
00562     sqliteSetString(&p->zErrMsg, sqlite_error_string(p->rc), (char*)0);
00563   }else{
00564     sprintf(p->zArgv[0],"%d",i);
00565     sprintf(p->zArgv[2],"%d", p->aOp[i].p1);
00566     sprintf(p->zArgv[3],"%d", p->aOp[i].p2);
00567     if( p->aOp[i].p3type==P3_POINTER ){
00568       sprintf(p->aStack[4].zShort, "ptr(%#lx)", (long)p->aOp[i].p3);
00569       p->zArgv[4] = p->aStack[4].zShort;
00570     }else{
00571       p->zArgv[4] = p->aOp[i].p3;
00572     }
00573     p->zArgv[1] = sqliteOpcodeNames[p->aOp[i].opcode];
00574     p->pc = i+1;
00575     p->azResColumn = p->zArgv;
00576     p->nResColumn = 5;
00577     p->rc = SQLITE_OK;
00578     rc = SQLITE_ROW;
00579   }
00580   return rc;
00581 }
00582 
00583 /*
00584 ** Prepare a virtual machine for execution.  This involves things such
00585 ** as allocating stack space and initializing the program counter.
00586 ** After the VDBE has be prepped, it can be executed by one or more
00587 ** calls to sqliteVdbeExec().  
00588 */
00589 void sqliteVdbeMakeReady(
00590   Vdbe *p,                       /* The VDBE */
00591   int nVar,                      /* Number of '?' see in the SQL statement */
00592   int isExplain                  /* True if the EXPLAIN keywords is present */
00593 ){
00594   int n;
00595 
00596   assert( p!=0 );
00597   assert( p->magic==VDBE_MAGIC_INIT );
00598 
00599   /* Add a HALT instruction to the very end of the program.
00600   */
00601   if( p->nOp==0 || (p->aOp && p->aOp[p->nOp-1].opcode!=OP_Halt) ){
00602     sqliteVdbeAddOp(p, OP_Halt, 0, 0);
00603   }
00604 
00605   /* No instruction ever pushes more than a single element onto the
00606   ** stack.  And the stack never grows on successive executions of the
00607   ** same loop.  So the total number of instructions is an upper bound
00608   ** on the maximum stack depth required.
00609   **
00610   ** Allocation all the stack space we will ever need.
00611   */
00612   if( p->aStack==0 ){
00613     p->nVar = nVar;
00614     assert( nVar>=0 );
00615     n = isExplain ? 10 : p->nOp;
00616     p->aStack = sqliteMalloc(
00617       n*(sizeof(p->aStack[0]) + 2*sizeof(char*))     /* aStack and zArgv */
00618         + p->nVar*(sizeof(char*)+sizeof(int)+1)    /* azVar, anVar, abVar */
00619     );
00620     p->zArgv = (char**)&p->aStack[n];
00621     p->azColName = (char**)&p->zArgv[n];
00622     p->azVar = (char**)&p->azColName[n];
00623     p->anVar = (int*)&p->azVar[p->nVar];
00624     p->abVar = (u8*)&p->anVar[p->nVar];
00625   }
00626 
00627   sqliteHashInit(&p->agg.hash, SQLITE_HASH_BINARY, 0);
00628   p->agg.pSearch = 0;
00629 #ifdef MEMORY_DEBUG
00630   if( sqliteOsFileExists("vdbe_trace") ){
00631     p->trace = stdout;
00632   }
00633 #endif
00634   p->pTos = &p->aStack[-1];
00635   p->pc = 0;
00636   p->rc = SQLITE_OK;
00637   p->uniqueCnt = 0;
00638   p->returnDepth = 0;
00639   p->errorAction = OE_Abort;
00640   p->undoTransOnError = 0;
00641   p->popStack =  0;
00642   p->explain |= isExplain;
00643   p->magic = VDBE_MAGIC_RUN;
00644 #ifdef VDBE_PROFILE
00645   {
00646     int i;
00647     for(i=0; i<p->nOp; i++){
00648       p->aOp[i].cnt = 0;
00649       p->aOp[i].cycles = 0;
00650     }
00651   }
00652 #endif
00653 }
00654 
00655 
00656 /*
00657 ** Remove any elements that remain on the sorter for the VDBE given.
00658 */
00659 void sqliteVdbeSorterReset(Vdbe *p){
00660   while( p->pSort ){
00661     Sorter *pSorter = p->pSort;
00662     p->pSort = pSorter->pNext;
00663     sqliteFree(pSorter->zKey);
00664     sqliteFree(pSorter->pData);
00665     sqliteFree(pSorter);
00666   }
00667 }
00668 
00669 /*
00670 ** Reset an Agg structure.  Delete all its contents. 
00671 **
00672 ** For installable aggregate functions, if the step function has been
00673 ** called, make sure the finalizer function has also been called.  The
00674 ** finalizer might need to free memory that was allocated as part of its
00675 ** private context.  If the finalizer has not been called yet, call it
00676 ** now.
00677 */
00678 void sqliteVdbeAggReset(Agg *pAgg){
00679   int i;
00680   HashElem *p;
00681   for(p = sqliteHashFirst(&pAgg->hash); p; p = sqliteHashNext(p)){
00682     AggElem *pElem = sqliteHashData(p);
00683     assert( pAgg->apFunc!=0 );
00684     for(i=0; i<pAgg->nMem; i++){
00685       Mem *pMem = &pElem->aMem[i];
00686       if( pAgg->apFunc[i] && (pMem->flags & MEM_AggCtx)!=0 ){
00687         sqlite_func ctx;
00688         ctx.pFunc = pAgg->apFunc[i];
00689         ctx.s.flags = MEM_Null;
00690         ctx.pAgg = pMem->z;
00691         ctx.cnt = pMem->i;
00692         ctx.isStep = 0;
00693         ctx.isError = 0;
00694         (*pAgg->apFunc[i]->xFinalize)(&ctx);
00695         if( pMem->z!=0 && pMem->z!=pMem->zShort ){
00696           sqliteFree(pMem->z);
00697         }
00698         if( ctx.s.flags & MEM_Dyn ){
00699           sqliteFree(ctx.s.z);
00700         }
00701       }else if( pMem->flags & MEM_Dyn ){
00702         sqliteFree(pMem->z);
00703       }
00704     }
00705     sqliteFree(pElem);
00706   }
00707   sqliteHashClear(&pAgg->hash);
00708   sqliteFree(pAgg->apFunc);
00709   pAgg->apFunc = 0;
00710   pAgg->pCurrent = 0;
00711   pAgg->pSearch = 0;
00712   pAgg->nMem = 0;
00713 }
00714 
00715 /*
00716 ** Delete a keylist
00717 */
00718 void sqliteVdbeKeylistFree(Keylist *p){
00719   while( p ){
00720     Keylist *pNext = p->pNext;
00721     sqliteFree(p);
00722     p = pNext;
00723   }
00724 }
00725 
00726 /*
00727 ** Close a cursor and release all the resources that cursor happens
00728 ** to hold.
00729 */
00730 void sqliteVdbeCleanupCursor(Cursor *pCx){
00731   if( pCx->pCursor ){
00732     sqliteBtreeCloseCursor(pCx->pCursor);
00733   }
00734   if( pCx->pBt ){
00735     sqliteBtreeClose(pCx->pBt);
00736   }
00737   sqliteFree(pCx->pData);
00738   memset(pCx, 0, sizeof(Cursor));
00739 }
00740 
00741 /*
00742 ** Close all cursors
00743 */
00744 static void closeAllCursors(Vdbe *p){
00745   int i;
00746   for(i=0; i<p->nCursor; i++){
00747     sqliteVdbeCleanupCursor(&p->aCsr[i]);
00748   }
00749   sqliteFree(p->aCsr);
00750   p->aCsr = 0;
00751   p->nCursor = 0;
00752 }
00753 
00754 /*
00755 ** Clean up the VM after execution.
00756 **
00757 ** This routine will automatically close any cursors, lists, and/or
00758 ** sorters that were left open.  It also deletes the values of
00759 ** variables in the azVariable[] array.
00760 */
00761 static void Cleanup(Vdbe *p){
00762   int i;
00763   if( p->aStack ){
00764     Mem *pTos = p->pTos;
00765     while( pTos>=p->aStack ){
00766       if( pTos->flags & MEM_Dyn ){
00767         sqliteFree(pTos->z);
00768       }
00769       pTos--;
00770     }
00771     p->pTos = pTos;
00772   }
00773   closeAllCursors(p);
00774   if( p->aMem ){
00775     for(i=0; i<p->nMem; i++){
00776       if( p->aMem[i].flags & MEM_Dyn ){
00777         sqliteFree(p->aMem[i].z);
00778       }
00779     }
00780   }
00781   sqliteFree(p->aMem);
00782   p->aMem = 0;
00783   p->nMem = 0;
00784   if( p->pList ){
00785     sqliteVdbeKeylistFree(p->pList);
00786     p->pList = 0;
00787   }
00788   sqliteVdbeSorterReset(p);
00789   if( p->pFile ){
00790     if( p->pFile!=stdin ) fclose(p->pFile);
00791     p->pFile = 0;
00792   }
00793   if( p->azField ){
00794     sqliteFree(p->azField);
00795     p->azField = 0;
00796   }
00797   p->nField = 0;
00798   if( p->zLine ){
00799     sqliteFree(p->zLine);
00800     p->zLine = 0;
00801   }
00802   p->nLineAlloc = 0;
00803   sqliteVdbeAggReset(&p->agg);
00804   if( p->aSet ){
00805     for(i=0; i<p->nSet; i++){
00806       sqliteHashClear(&p->aSet[i].hash);
00807     }
00808   }
00809   sqliteFree(p->aSet);
00810   p->aSet = 0;
00811   p->nSet = 0;
00812   if( p->keylistStack ){
00813     int ii;
00814     for(ii = 0; ii < p->keylistStackDepth; ii++){
00815       sqliteVdbeKeylistFree(p->keylistStack[ii]);
00816     }
00817     sqliteFree(p->keylistStack);
00818     p->keylistStackDepth = 0;
00819     p->keylistStack = 0;
00820   }
00821   sqliteFree(p->contextStack);
00822   p->contextStack = 0;
00823   sqliteFree(p->zErrMsg);
00824   p->zErrMsg = 0;
00825 }
00826 
00827 /*
00828 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
00829 ** Write any error messages into *pzErrMsg.  Return the result code.
00830 **
00831 ** After this routine is run, the VDBE should be ready to be executed
00832 ** again.
00833 */
00834 int sqliteVdbeReset(Vdbe *p, char **pzErrMsg){
00835   sqlite *db = p->db;
00836   int i;
00837 
00838   if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
00839     sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
00840     return SQLITE_MISUSE;
00841   }
00842   if( p->zErrMsg ){
00843     if( pzErrMsg && *pzErrMsg==0 ){
00844       *pzErrMsg = p->zErrMsg;
00845     }else{
00846       sqliteFree(p->zErrMsg);
00847     }
00848     p->zErrMsg = 0;
00849   }else if( p->rc ){
00850     sqliteSetString(pzErrMsg, sqlite_error_string(p->rc), (char*)0);
00851   }
00852   Cleanup(p);
00853   if( p->rc!=SQLITE_OK ){
00854     switch( p->errorAction ){
00855       case OE_Abort: {
00856         if( !p->undoTransOnError ){
00857           for(i=0; i<db->nDb; i++){
00858             if( db->aDb[i].pBt ){
00859               sqliteBtreeRollbackCkpt(db->aDb[i].pBt);
00860             }
00861           }
00862           break;
00863         }
00864         /* Fall through to ROLLBACK */
00865       }
00866       case OE_Rollback: {
00867         sqliteRollbackAll(db);
00868         db->flags &= ~SQLITE_InTrans;
00869         db->onError = OE_Default;
00870         break;
00871       }
00872       default: {
00873         if( p->undoTransOnError ){
00874           sqliteRollbackAll(db);
00875           db->flags &= ~SQLITE_InTrans;
00876           db->onError = OE_Default;
00877         }
00878         break;
00879       }
00880     }
00881     sqliteRollbackInternalChanges(db);
00882   }
00883   for(i=0; i<db->nDb; i++){
00884     if( db->aDb[i].pBt && db->aDb[i].inTrans==2 ){
00885       sqliteBtreeCommitCkpt(db->aDb[i].pBt);
00886       db->aDb[i].inTrans = 1;
00887     }
00888   }
00889   assert( p->pTos<&p->aStack[p->pc] || sqlite_malloc_failed==1 );
00890 #ifdef VDBE_PROFILE
00891   {
00892     FILE *out = fopen("vdbe_profile.out", "a");
00893     if( out ){
00894       int i;
00895       fprintf(out, "---- ");
00896       for(i=0; i<p->nOp; i++){
00897         fprintf(out, "%02x", p->aOp[i].opcode);
00898       }
00899       fprintf(out, "\n");
00900       for(i=0; i<p->nOp; i++){
00901         fprintf(out, "%6d %10lld %8lld ",
00902            p->aOp[i].cnt,
00903            p->aOp[i].cycles,
00904            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
00905         );
00906         sqliteVdbePrintOp(out, i, &p->aOp[i]);
00907       }
00908       fclose(out);
00909     }
00910   }
00911 #endif
00912   p->magic = VDBE_MAGIC_INIT;
00913   return p->rc;
00914 }
00915 
00916 /*
00917 ** Clean up and delete a VDBE after execution.  Return an integer which is
00918 ** the result code.  Write any error message text into *pzErrMsg.
00919 */
00920 int sqliteVdbeFinalize(Vdbe *p, char **pzErrMsg){
00921   int rc;
00922   sqlite *db;
00923 
00924   if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
00925     sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
00926     return SQLITE_MISUSE;
00927   }
00928   db = p->db;
00929   rc = sqliteVdbeReset(p, pzErrMsg);
00930   sqliteVdbeDelete(p);
00931   if( db->want_to_close && db->pVdbe==0 ){
00932     sqlite_close(db);
00933   }
00934   if( rc==SQLITE_SCHEMA ){
00935     sqliteResetInternalSchema(db, 0);
00936   }
00937   return rc;
00938 }
00939 
00940 /*
00941 ** Set the values of all variables.  Variable $1 in the original SQL will
00942 ** be the string azValue[0].  $2 will have the value azValue[1].  And
00943 ** so forth.  If a value is out of range (for example $3 when nValue==2)
00944 ** then its value will be NULL.
00945 **
00946 ** This routine overrides any prior call.
00947 */
00948 int sqlite_bind(sqlite_vm *pVm, int i, const char *zVal, int len, int copy){
00949   Vdbe *p = (Vdbe*)pVm;
00950   if( p->magic!=VDBE_MAGIC_RUN || p->pc!=0 ){
00951     return SQLITE_MISUSE;
00952   }
00953   if( i<1 || i>p->nVar ){
00954     return SQLITE_RANGE;
00955   }
00956   i--;
00957   if( p->abVar[i] ){
00958     sqliteFree(p->azVar[i]);
00959   }
00960   if( zVal==0 ){
00961     copy = 0;
00962     len = 0;
00963   }
00964   if( len<0 ){
00965     len = strlen(zVal)+1;
00966   }
00967   if( copy ){
00968     p->azVar[i] = sqliteMalloc( len );
00969     if( p->azVar[i] ) memcpy(p->azVar[i], zVal, len);
00970   }else{
00971     p->azVar[i] = (char*)zVal;
00972   }
00973   p->abVar[i] = copy;
00974   p->anVar[i] = len;
00975   return SQLITE_OK;
00976 }
00977 
00978 
00979 /*
00980 ** Delete an entire VDBE.
00981 */
00982 void sqliteVdbeDelete(Vdbe *p){
00983   int i;
00984   if( p==0 ) return;
00985   Cleanup(p);
00986   if( p->pPrev ){
00987     p->pPrev->pNext = p->pNext;
00988   }else{
00989     assert( p->db->pVdbe==p );
00990     p->db->pVdbe = p->pNext;
00991   }
00992   if( p->pNext ){
00993     p->pNext->pPrev = p->pPrev;
00994   }
00995   p->pPrev = p->pNext = 0;
00996   if( p->nOpAlloc==0 ){
00997     p->aOp = 0;
00998     p->nOp = 0;
00999   }
01000   for(i=0; i<p->nOp; i++){
01001     if( p->aOp[i].p3type==P3_DYNAMIC ){
01002       sqliteFree(p->aOp[i].p3);
01003     }
01004   }
01005   for(i=0; i<p->nVar; i++){
01006     if( p->abVar[i] ) sqliteFree(p->azVar[i]);
01007   }
01008   sqliteFree(p->aOp);
01009   sqliteFree(p->aLabel);
01010   sqliteFree(p->aStack);
01011   p->magic = VDBE_MAGIC_DEAD;
01012   sqliteFree(p);
01013 }
01014 
01015 /*
01016 ** Convert an integer in between the native integer format and
01017 ** the bigEndian format used as the record number for tables.
01018 **
01019 ** The bigEndian format (most significant byte first) is used for
01020 ** record numbers so that records will sort into the correct order
01021 ** even though memcmp() is used to compare the keys.  On machines
01022 ** whose native integer format is little endian (ex: i486) the
01023 ** order of bytes is reversed.  On native big-endian machines
01024 ** (ex: Alpha, Sparc, Motorola) the byte order is the same.
01025 **
01026 ** This function is its own inverse.  In other words
01027 **
01028 **         X == byteSwap(byteSwap(X))
01029 */
01030 int sqliteVdbeByteSwap(int x){
01031   union {
01032      char zBuf[sizeof(int)];
01033      int i;
01034   } ux;
01035   ux.zBuf[3] = x&0xff;
01036   ux.zBuf[2] = (x>>8)&0xff;
01037   ux.zBuf[1] = (x>>16)&0xff;
01038   ux.zBuf[0] = (x>>24)&0xff;
01039   return ux.i;
01040 }
01041 
01042 /*
01043 ** If a MoveTo operation is pending on the given cursor, then do that
01044 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
01045 ** routine does nothing and returns SQLITE_OK.
01046 */
01047 int sqliteVdbeCursorMoveto(Cursor *p){
01048   if( p->deferredMoveto ){
01049     int res;
01050     extern int sqlite_search_count;
01051     sqliteBtreeMoveto(p->pCursor, (char*)&p->movetoTarget, sizeof(int), &res);
01052     p->lastRecno = keyToInt(p->movetoTarget);
01053     p->recnoIsValid = res==0;
01054     if( res<0 ){
01055       sqliteBtreeNext(p->pCursor, &res);
01056     }
01057     sqlite_search_count++;
01058     p->deferredMoveto = 0;
01059   }
01060   return SQLITE_OK;
01061 }