• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "sqlite3_stmt" 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 "vdbeInt.h"
19 
20 
21 
22 /*
23 ** When debugging the code generator in a symbolic debugger, one can
24 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
25 ** as they are added to the instruction stream.
26 */
27 #ifdef SQLITE_DEBUG
28 int sqlite3VdbeAddopTrace = 0;
29 #endif
30 
31 
32 /*
33 ** Create a new virtual database engine.
34 */
sqlite3VdbeCreate(sqlite3 * db)35 Vdbe *sqlite3VdbeCreate(sqlite3 *db){
36   Vdbe *p;
37   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
38   if( p==0 ) return 0;
39   p->db = db;
40   if( db->pVdbe ){
41     db->pVdbe->pPrev = p;
42   }
43   p->pNext = db->pVdbe;
44   p->pPrev = 0;
45   db->pVdbe = p;
46   p->magic = VDBE_MAGIC_INIT;
47   return p;
48 }
49 
50 /*
51 ** Remember the SQL string for a prepared statement.
52 */
sqlite3VdbeSetSql(Vdbe * p,const char * z,int n,int isPrepareV2)53 void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
54   assert( isPrepareV2==1 || isPrepareV2==0 );
55   if( p==0 ) return;
56 #ifdef SQLITE_OMIT_TRACE
57   if( !isPrepareV2 ) return;
58 #endif
59   assert( p->zSql==0 );
60   p->zSql = sqlite3DbStrNDup(p->db, z, n);
61   p->isPrepareV2 = (u8)isPrepareV2;
62 }
63 
64 /*
65 ** Return the SQL associated with a prepared statement
66 */
sqlite3_sql(sqlite3_stmt * pStmt)67 const char *sqlite3_sql(sqlite3_stmt *pStmt){
68   Vdbe *p = (Vdbe *)pStmt;
69   return (p && p->isPrepareV2) ? p->zSql : 0;
70 }
71 
72 /*
73 ** Swap all content between two VDBE structures.
74 */
sqlite3VdbeSwap(Vdbe * pA,Vdbe * pB)75 void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
76   Vdbe tmp, *pTmp;
77   char *zTmp;
78   tmp = *pA;
79   *pA = *pB;
80   *pB = tmp;
81   pTmp = pA->pNext;
82   pA->pNext = pB->pNext;
83   pB->pNext = pTmp;
84   pTmp = pA->pPrev;
85   pA->pPrev = pB->pPrev;
86   pB->pPrev = pTmp;
87   zTmp = pA->zSql;
88   pA->zSql = pB->zSql;
89   pB->zSql = zTmp;
90   pB->isPrepareV2 = pA->isPrepareV2;
91 }
92 
93 #ifdef SQLITE_DEBUG
94 /*
95 ** Turn tracing on or off
96 */
sqlite3VdbeTrace(Vdbe * p,FILE * trace)97 void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
98   p->trace = trace;
99 }
100 #endif
101 
102 /*
103 ** Resize the Vdbe.aOp array so that it is at least one op larger than
104 ** it was.
105 **
106 ** If an out-of-memory error occurs while resizing the array, return
107 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
108 ** unchanged (this is so that any opcodes already allocated can be
109 ** correctly deallocated along with the rest of the Vdbe).
110 */
growOpArray(Vdbe * p)111 static int growOpArray(Vdbe *p){
112   VdbeOp *pNew;
113   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
114   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
115   if( pNew ){
116     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
117     p->aOp = pNew;
118   }
119   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
120 }
121 
122 /*
123 ** Add a new instruction to the list of instructions current in the
124 ** VDBE.  Return the address of the new instruction.
125 **
126 ** Parameters:
127 **
128 **    p               Pointer to the VDBE
129 **
130 **    op              The opcode for this instruction
131 **
132 **    p1, p2, p3      Operands
133 **
134 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
135 ** the sqlite3VdbeChangeP4() function to change the value of the P4
136 ** operand.
137 */
sqlite3VdbeAddOp3(Vdbe * p,int op,int p1,int p2,int p3)138 int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
139   int i;
140   VdbeOp *pOp;
141 
142   i = p->nOp;
143   assert( p->magic==VDBE_MAGIC_INIT );
144   assert( op>0 && op<0xff );
145   if( p->nOpAlloc<=i ){
146     if( growOpArray(p) ){
147       return 1;
148     }
149   }
150   p->nOp++;
151   pOp = &p->aOp[i];
152   pOp->opcode = (u8)op;
153   pOp->p5 = 0;
154   pOp->p1 = p1;
155   pOp->p2 = p2;
156   pOp->p3 = p3;
157   pOp->p4.p = 0;
158   pOp->p4type = P4_NOTUSED;
159   p->expired = 0;
160   if( op==OP_ParseSchema ){
161     /* Any program that uses the OP_ParseSchema opcode needs to lock
162     ** all btrees. */
163     int j;
164     for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
165   }
166 #ifdef SQLITE_DEBUG
167   pOp->zComment = 0;
168   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
169 #endif
170 #ifdef VDBE_PROFILE
171   pOp->cycles = 0;
172   pOp->cnt = 0;
173 #endif
174   return i;
175 }
sqlite3VdbeAddOp0(Vdbe * p,int op)176 int sqlite3VdbeAddOp0(Vdbe *p, int op){
177   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
178 }
sqlite3VdbeAddOp1(Vdbe * p,int op,int p1)179 int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
180   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
181 }
sqlite3VdbeAddOp2(Vdbe * p,int op,int p1,int p2)182 int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
183   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
184 }
185 
186 
187 /*
188 ** Add an opcode that includes the p4 value as a pointer.
189 */
sqlite3VdbeAddOp4(Vdbe * p,int op,int p1,int p2,int p3,const char * zP4,int p4type)190 int sqlite3VdbeAddOp4(
191   Vdbe *p,            /* Add the opcode to this VM */
192   int op,             /* The new opcode */
193   int p1,             /* The P1 operand */
194   int p2,             /* The P2 operand */
195   int p3,             /* The P3 operand */
196   const char *zP4,    /* The P4 operand */
197   int p4type          /* P4 operand type */
198 ){
199   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
200   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
201   return addr;
202 }
203 
204 /*
205 ** Add an opcode that includes the p4 value as an integer.
206 */
sqlite3VdbeAddOp4Int(Vdbe * p,int op,int p1,int p2,int p3,int p4)207 int sqlite3VdbeAddOp4Int(
208   Vdbe *p,            /* Add the opcode to this VM */
209   int op,             /* The new opcode */
210   int p1,             /* The P1 operand */
211   int p2,             /* The P2 operand */
212   int p3,             /* The P3 operand */
213   int p4              /* The P4 operand as an integer */
214 ){
215   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
216   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
217   return addr;
218 }
219 
220 /*
221 ** Create a new symbolic label for an instruction that has yet to be
222 ** coded.  The symbolic label is really just a negative number.  The
223 ** label can be used as the P2 value of an operation.  Later, when
224 ** the label is resolved to a specific address, the VDBE will scan
225 ** through its operation list and change all values of P2 which match
226 ** the label into the resolved address.
227 **
228 ** The VDBE knows that a P2 value is a label because labels are
229 ** always negative and P2 values are suppose to be non-negative.
230 ** Hence, a negative P2 value is a label that has yet to be resolved.
231 **
232 ** Zero is returned if a malloc() fails.
233 */
sqlite3VdbeMakeLabel(Vdbe * p)234 int sqlite3VdbeMakeLabel(Vdbe *p){
235   int i;
236   i = p->nLabel++;
237   assert( p->magic==VDBE_MAGIC_INIT );
238   if( i>=p->nLabelAlloc ){
239     int n = p->nLabelAlloc*2 + 5;
240     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
241                                        n*sizeof(p->aLabel[0]));
242     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
243   }
244   if( p->aLabel ){
245     p->aLabel[i] = -1;
246   }
247   return -1-i;
248 }
249 
250 /*
251 ** Resolve label "x" to be the address of the next instruction to
252 ** be inserted.  The parameter "x" must have been obtained from
253 ** a prior call to sqlite3VdbeMakeLabel().
254 */
sqlite3VdbeResolveLabel(Vdbe * p,int x)255 void sqlite3VdbeResolveLabel(Vdbe *p, int x){
256   int j = -1-x;
257   assert( p->magic==VDBE_MAGIC_INIT );
258   assert( j>=0 && j<p->nLabel );
259   if( p->aLabel ){
260     p->aLabel[j] = p->nOp;
261   }
262 }
263 
264 /*
265 ** Mark the VDBE as one that can only be run one time.
266 */
sqlite3VdbeRunOnlyOnce(Vdbe * p)267 void sqlite3VdbeRunOnlyOnce(Vdbe *p){
268   p->runOnlyOnce = 1;
269 }
270 
271 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
272 
273 /*
274 ** The following type and function are used to iterate through all opcodes
275 ** in a Vdbe main program and each of the sub-programs (triggers) it may
276 ** invoke directly or indirectly. It should be used as follows:
277 **
278 **   Op *pOp;
279 **   VdbeOpIter sIter;
280 **
281 **   memset(&sIter, 0, sizeof(sIter));
282 **   sIter.v = v;                            // v is of type Vdbe*
283 **   while( (pOp = opIterNext(&sIter)) ){
284 **     // Do something with pOp
285 **   }
286 **   sqlite3DbFree(v->db, sIter.apSub);
287 **
288 */
289 typedef struct VdbeOpIter VdbeOpIter;
290 struct VdbeOpIter {
291   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
292   SubProgram **apSub;        /* Array of subprograms */
293   int nSub;                  /* Number of entries in apSub */
294   int iAddr;                 /* Address of next instruction to return */
295   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
296 };
opIterNext(VdbeOpIter * p)297 static Op *opIterNext(VdbeOpIter *p){
298   Vdbe *v = p->v;
299   Op *pRet = 0;
300   Op *aOp;
301   int nOp;
302 
303   if( p->iSub<=p->nSub ){
304 
305     if( p->iSub==0 ){
306       aOp = v->aOp;
307       nOp = v->nOp;
308     }else{
309       aOp = p->apSub[p->iSub-1]->aOp;
310       nOp = p->apSub[p->iSub-1]->nOp;
311     }
312     assert( p->iAddr<nOp );
313 
314     pRet = &aOp[p->iAddr];
315     p->iAddr++;
316     if( p->iAddr==nOp ){
317       p->iSub++;
318       p->iAddr = 0;
319     }
320 
321     if( pRet->p4type==P4_SUBPROGRAM ){
322       int nByte = (p->nSub+1)*sizeof(SubProgram*);
323       int j;
324       for(j=0; j<p->nSub; j++){
325         if( p->apSub[j]==pRet->p4.pProgram ) break;
326       }
327       if( j==p->nSub ){
328         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
329         if( !p->apSub ){
330           pRet = 0;
331         }else{
332           p->apSub[p->nSub++] = pRet->p4.pProgram;
333         }
334       }
335     }
336   }
337 
338   return pRet;
339 }
340 
341 /*
342 ** Check if the program stored in the VM associated with pParse may
343 ** throw an ABORT exception (causing the statement, but not entire transaction
344 ** to be rolled back). This condition is true if the main program or any
345 ** sub-programs contains any of the following:
346 **
347 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
348 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
349 **   *  OP_Destroy
350 **   *  OP_VUpdate
351 **   *  OP_VRename
352 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
353 **
354 ** Then check that the value of Parse.mayAbort is true if an
355 ** ABORT may be thrown, or false otherwise. Return true if it does
356 ** match, or false otherwise. This function is intended to be used as
357 ** part of an assert statement in the compiler. Similar to:
358 **
359 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
360 */
sqlite3VdbeAssertMayAbort(Vdbe * v,int mayAbort)361 int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
362   int hasAbort = 0;
363   Op *pOp;
364   VdbeOpIter sIter;
365   memset(&sIter, 0, sizeof(sIter));
366   sIter.v = v;
367 
368   while( (pOp = opIterNext(&sIter))!=0 ){
369     int opcode = pOp->opcode;
370     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
371 #ifndef SQLITE_OMIT_FOREIGN_KEY
372      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
373 #endif
374      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
375       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
376     ){
377       hasAbort = 1;
378       break;
379     }
380   }
381   sqlite3DbFree(v->db, sIter.apSub);
382 
383   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
384   ** If malloc failed, then the while() loop above may not have iterated
385   ** through all opcodes and hasAbort may be set incorrectly. Return
386   ** true for this case to prevent the assert() in the callers frame
387   ** from failing.  */
388   return ( v->db->mallocFailed || hasAbort==mayAbort );
389 }
390 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
391 
392 /*
393 ** Loop through the program looking for P2 values that are negative
394 ** on jump instructions.  Each such value is a label.  Resolve the
395 ** label by setting the P2 value to its correct non-zero value.
396 **
397 ** This routine is called once after all opcodes have been inserted.
398 **
399 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
400 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
401 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
402 **
403 ** The Op.opflags field is set on all opcodes.
404 */
resolveP2Values(Vdbe * p,int * pMaxFuncArgs)405 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
406   int i;
407   int nMaxArgs = *pMaxFuncArgs;
408   Op *pOp;
409   int *aLabel = p->aLabel;
410   p->readOnly = 1;
411   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
412     u8 opcode = pOp->opcode;
413 
414     pOp->opflags = sqlite3OpcodeProperty[opcode];
415     if( opcode==OP_Function || opcode==OP_AggStep ){
416       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
417     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
418       p->readOnly = 0;
419 #ifndef SQLITE_OMIT_VIRTUALTABLE
420     }else if( opcode==OP_VUpdate ){
421       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
422     }else if( opcode==OP_VFilter ){
423       int n;
424       assert( p->nOp - i >= 3 );
425       assert( pOp[-1].opcode==OP_Integer );
426       n = pOp[-1].p1;
427       if( n>nMaxArgs ) nMaxArgs = n;
428 #endif
429     }
430 
431     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
432       assert( -1-pOp->p2<p->nLabel );
433       pOp->p2 = aLabel[-1-pOp->p2];
434     }
435   }
436   sqlite3DbFree(p->db, p->aLabel);
437   p->aLabel = 0;
438 
439   *pMaxFuncArgs = nMaxArgs;
440 }
441 
442 /*
443 ** Return the address of the next instruction to be inserted.
444 */
sqlite3VdbeCurrentAddr(Vdbe * p)445 int sqlite3VdbeCurrentAddr(Vdbe *p){
446   assert( p->magic==VDBE_MAGIC_INIT );
447   return p->nOp;
448 }
449 
450 /*
451 ** This function returns a pointer to the array of opcodes associated with
452 ** the Vdbe passed as the first argument. It is the callers responsibility
453 ** to arrange for the returned array to be eventually freed using the
454 ** vdbeFreeOpArray() function.
455 **
456 ** Before returning, *pnOp is set to the number of entries in the returned
457 ** array. Also, *pnMaxArg is set to the larger of its current value and
458 ** the number of entries in the Vdbe.apArg[] array required to execute the
459 ** returned program.
460 */
sqlite3VdbeTakeOpArray(Vdbe * p,int * pnOp,int * pnMaxArg)461 VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
462   VdbeOp *aOp = p->aOp;
463   assert( aOp && !p->db->mallocFailed );
464 
465   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
466   assert( p->btreeMask==0 );
467 
468   resolveP2Values(p, pnMaxArg);
469   *pnOp = p->nOp;
470   p->aOp = 0;
471   return aOp;
472 }
473 
474 /*
475 ** Add a whole list of operations to the operation stack.  Return the
476 ** address of the first operation added.
477 */
sqlite3VdbeAddOpList(Vdbe * p,int nOp,VdbeOpList const * aOp)478 int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
479   int addr;
480   assert( p->magic==VDBE_MAGIC_INIT );
481   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
482     return 0;
483   }
484   addr = p->nOp;
485   if( ALWAYS(nOp>0) ){
486     int i;
487     VdbeOpList const *pIn = aOp;
488     for(i=0; i<nOp; i++, pIn++){
489       int p2 = pIn->p2;
490       VdbeOp *pOut = &p->aOp[i+addr];
491       pOut->opcode = pIn->opcode;
492       pOut->p1 = pIn->p1;
493       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
494         pOut->p2 = addr + ADDR(p2);
495       }else{
496         pOut->p2 = p2;
497       }
498       pOut->p3 = pIn->p3;
499       pOut->p4type = P4_NOTUSED;
500       pOut->p4.p = 0;
501       pOut->p5 = 0;
502 #ifdef SQLITE_DEBUG
503       pOut->zComment = 0;
504       if( sqlite3VdbeAddopTrace ){
505         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
506       }
507 #endif
508     }
509     p->nOp += nOp;
510   }
511   return addr;
512 }
513 
514 /*
515 ** Change the value of the P1 operand for a specific instruction.
516 ** This routine is useful when a large program is loaded from a
517 ** static array using sqlite3VdbeAddOpList but we want to make a
518 ** few minor changes to the program.
519 */
sqlite3VdbeChangeP1(Vdbe * p,int addr,int val)520 void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
521   assert( p!=0 );
522   assert( addr>=0 );
523   if( p->nOp>addr ){
524     p->aOp[addr].p1 = val;
525   }
526 }
527 
528 /*
529 ** Change the value of the P2 operand for a specific instruction.
530 ** This routine is useful for setting a jump destination.
531 */
sqlite3VdbeChangeP2(Vdbe * p,int addr,int val)532 void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
533   assert( p!=0 );
534   assert( addr>=0 );
535   if( p->nOp>addr ){
536     p->aOp[addr].p2 = val;
537   }
538 }
539 
540 /*
541 ** Change the value of the P3 operand for a specific instruction.
542 */
sqlite3VdbeChangeP3(Vdbe * p,int addr,int val)543 void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
544   assert( p!=0 );
545   assert( addr>=0 );
546   if( p->nOp>addr ){
547     p->aOp[addr].p3 = val;
548   }
549 }
550 
551 /*
552 ** Change the value of the P5 operand for the most recently
553 ** added operation.
554 */
sqlite3VdbeChangeP5(Vdbe * p,u8 val)555 void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
556   assert( p!=0 );
557   if( p->aOp ){
558     assert( p->nOp>0 );
559     p->aOp[p->nOp-1].p5 = val;
560   }
561 }
562 
563 /*
564 ** Change the P2 operand of instruction addr so that it points to
565 ** the address of the next instruction to be coded.
566 */
sqlite3VdbeJumpHere(Vdbe * p,int addr)567 void sqlite3VdbeJumpHere(Vdbe *p, int addr){
568   assert( addr>=0 );
569   sqlite3VdbeChangeP2(p, addr, p->nOp);
570 }
571 
572 
573 /*
574 ** If the input FuncDef structure is ephemeral, then free it.  If
575 ** the FuncDef is not ephermal, then do nothing.
576 */
freeEphemeralFunction(sqlite3 * db,FuncDef * pDef)577 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
578   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
579     sqlite3DbFree(db, pDef);
580   }
581 }
582 
583 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
584 
585 /*
586 ** Delete a P4 value if necessary.
587 */
freeP4(sqlite3 * db,int p4type,void * p4)588 static void freeP4(sqlite3 *db, int p4type, void *p4){
589   if( p4 ){
590     assert( db );
591     switch( p4type ){
592       case P4_REAL:
593       case P4_INT64:
594       case P4_DYNAMIC:
595       case P4_KEYINFO:
596       case P4_INTARRAY:
597       case P4_KEYINFO_HANDOFF: {
598         sqlite3DbFree(db, p4);
599         break;
600       }
601       case P4_MPRINTF: {
602         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
603         break;
604       }
605       case P4_VDBEFUNC: {
606         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
607         freeEphemeralFunction(db, pVdbeFunc->pFunc);
608         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
609         sqlite3DbFree(db, pVdbeFunc);
610         break;
611       }
612       case P4_FUNCDEF: {
613         freeEphemeralFunction(db, (FuncDef*)p4);
614         break;
615       }
616       case P4_MEM: {
617         if( db->pnBytesFreed==0 ){
618           sqlite3ValueFree((sqlite3_value*)p4);
619         }else{
620           Mem *p = (Mem*)p4;
621           sqlite3DbFree(db, p->zMalloc);
622           sqlite3DbFree(db, p);
623         }
624         break;
625       }
626       case P4_VTAB : {
627         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
628         break;
629       }
630     }
631   }
632 }
633 
634 /*
635 ** Free the space allocated for aOp and any p4 values allocated for the
636 ** opcodes contained within. If aOp is not NULL it is assumed to contain
637 ** nOp entries.
638 */
vdbeFreeOpArray(sqlite3 * db,Op * aOp,int nOp)639 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
640   if( aOp ){
641     Op *pOp;
642     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
643       freeP4(db, pOp->p4type, pOp->p4.p);
644 #ifdef SQLITE_DEBUG
645       sqlite3DbFree(db, pOp->zComment);
646 #endif
647     }
648   }
649   sqlite3DbFree(db, aOp);
650 }
651 
652 /*
653 ** Link the SubProgram object passed as the second argument into the linked
654 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
655 ** objects when the VM is no longer required.
656 */
sqlite3VdbeLinkSubProgram(Vdbe * pVdbe,SubProgram * p)657 void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
658   p->pNext = pVdbe->pProgram;
659   pVdbe->pProgram = p;
660 }
661 
662 /*
663 ** Change N opcodes starting at addr to No-ops.
664 */
sqlite3VdbeChangeToNoop(Vdbe * p,int addr,int N)665 void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
666   if( p->aOp ){
667     VdbeOp *pOp = &p->aOp[addr];
668     sqlite3 *db = p->db;
669     while( N-- ){
670       freeP4(db, pOp->p4type, pOp->p4.p);
671       memset(pOp, 0, sizeof(pOp[0]));
672       pOp->opcode = OP_Noop;
673       pOp++;
674     }
675   }
676 }
677 
678 /*
679 ** Change the value of the P4 operand for a specific instruction.
680 ** This routine is useful when a large program is loaded from a
681 ** static array using sqlite3VdbeAddOpList but we want to make a
682 ** few minor changes to the program.
683 **
684 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
685 ** the string is made into memory obtained from sqlite3_malloc().
686 ** A value of n==0 means copy bytes of zP4 up to and including the
687 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
688 **
689 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
690 ** A copy is made of the KeyInfo structure into memory obtained from
691 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
692 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
693 ** stored in memory that the caller has obtained from sqlite3_malloc. The
694 ** caller should not free the allocation, it will be freed when the Vdbe is
695 ** finalized.
696 **
697 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
698 ** to a string or structure that is guaranteed to exist for the lifetime of
699 ** the Vdbe. In these cases we can just copy the pointer.
700 **
701 ** If addr<0 then change P4 on the most recently inserted instruction.
702 */
sqlite3VdbeChangeP4(Vdbe * p,int addr,const char * zP4,int n)703 void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
704   Op *pOp;
705   sqlite3 *db;
706   assert( p!=0 );
707   db = p->db;
708   assert( p->magic==VDBE_MAGIC_INIT );
709   if( p->aOp==0 || db->mallocFailed ){
710     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
711       freeP4(db, n, (void*)*(char**)&zP4);
712     }
713     return;
714   }
715   assert( p->nOp>0 );
716   assert( addr<p->nOp );
717   if( addr<0 ){
718     addr = p->nOp - 1;
719   }
720   pOp = &p->aOp[addr];
721   freeP4(db, pOp->p4type, pOp->p4.p);
722   pOp->p4.p = 0;
723   if( n==P4_INT32 ){
724     /* Note: this cast is safe, because the origin data point was an int
725     ** that was cast to a (const char *). */
726     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
727     pOp->p4type = P4_INT32;
728   }else if( zP4==0 ){
729     pOp->p4.p = 0;
730     pOp->p4type = P4_NOTUSED;
731   }else if( n==P4_KEYINFO ){
732     KeyInfo *pKeyInfo;
733     int nField, nByte;
734 
735     nField = ((KeyInfo*)zP4)->nField;
736     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
737     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
738     pOp->p4.pKeyInfo = pKeyInfo;
739     if( pKeyInfo ){
740       u8 *aSortOrder;
741       memcpy((char*)pKeyInfo, zP4, nByte - nField);
742       aSortOrder = pKeyInfo->aSortOrder;
743       if( aSortOrder ){
744         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
745         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
746       }
747       pOp->p4type = P4_KEYINFO;
748     }else{
749       p->db->mallocFailed = 1;
750       pOp->p4type = P4_NOTUSED;
751     }
752   }else if( n==P4_KEYINFO_HANDOFF ){
753     pOp->p4.p = (void*)zP4;
754     pOp->p4type = P4_KEYINFO;
755   }else if( n==P4_VTAB ){
756     pOp->p4.p = (void*)zP4;
757     pOp->p4type = P4_VTAB;
758     sqlite3VtabLock((VTable *)zP4);
759     assert( ((VTable *)zP4)->db==p->db );
760   }else if( n<0 ){
761     pOp->p4.p = (void*)zP4;
762     pOp->p4type = (signed char)n;
763   }else{
764     if( n==0 ) n = sqlite3Strlen30(zP4);
765     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
766     pOp->p4type = P4_DYNAMIC;
767   }
768 }
769 
770 #ifndef NDEBUG
771 /*
772 ** Change the comment on the the most recently coded instruction.  Or
773 ** insert a No-op and add the comment to that new instruction.  This
774 ** makes the code easier to read during debugging.  None of this happens
775 ** in a production build.
776 */
sqlite3VdbeComment(Vdbe * p,const char * zFormat,...)777 void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
778   va_list ap;
779   if( !p ) return;
780   assert( p->nOp>0 || p->aOp==0 );
781   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
782   if( p->nOp ){
783     char **pz = &p->aOp[p->nOp-1].zComment;
784     va_start(ap, zFormat);
785     sqlite3DbFree(p->db, *pz);
786     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
787     va_end(ap);
788   }
789 }
sqlite3VdbeNoopComment(Vdbe * p,const char * zFormat,...)790 void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
791   va_list ap;
792   if( !p ) return;
793   sqlite3VdbeAddOp0(p, OP_Noop);
794   assert( p->nOp>0 || p->aOp==0 );
795   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
796   if( p->nOp ){
797     char **pz = &p->aOp[p->nOp-1].zComment;
798     va_start(ap, zFormat);
799     sqlite3DbFree(p->db, *pz);
800     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
801     va_end(ap);
802   }
803 }
804 #endif  /* NDEBUG */
805 
806 /*
807 ** Return the opcode for a given address.  If the address is -1, then
808 ** return the most recently inserted opcode.
809 **
810 ** If a memory allocation error has occurred prior to the calling of this
811 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
812 ** is readable but not writable, though it is cast to a writable value.
813 ** The return of a dummy opcode allows the call to continue functioning
814 ** after a OOM fault without having to check to see if the return from
815 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
816 ** dummy will never be written to.  This is verified by code inspection and
817 ** by running with Valgrind.
818 **
819 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
820 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
821 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
822 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
823 ** having to double-check to make sure that the result is non-negative. But
824 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
825 ** check the value of p->nOp-1 before continuing.
826 */
sqlite3VdbeGetOp(Vdbe * p,int addr)827 VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
828   /* C89 specifies that the constant "dummy" will be initialized to all
829   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
830   static const VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
831   assert( p->magic==VDBE_MAGIC_INIT );
832   if( addr<0 ){
833 #ifdef SQLITE_OMIT_TRACE
834     if( p->nOp==0 ) return (VdbeOp*)&dummy;
835 #endif
836     addr = p->nOp - 1;
837   }
838   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
839   if( p->db->mallocFailed ){
840     return (VdbeOp*)&dummy;
841   }else{
842     return &p->aOp[addr];
843   }
844 }
845 
846 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
847      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
848 /*
849 ** Compute a string that describes the P4 parameter for an opcode.
850 ** Use zTemp for any required temporary buffer space.
851 */
displayP4(Op * pOp,char * zTemp,int nTemp)852 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
853   char *zP4 = zTemp;
854   assert( nTemp>=20 );
855   switch( pOp->p4type ){
856     case P4_KEYINFO_STATIC:
857     case P4_KEYINFO: {
858       int i, j;
859       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
860       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
861       i = sqlite3Strlen30(zTemp);
862       for(j=0; j<pKeyInfo->nField; j++){
863         CollSeq *pColl = pKeyInfo->aColl[j];
864         if( pColl ){
865           int n = sqlite3Strlen30(pColl->zName);
866           if( i+n>nTemp-6 ){
867             memcpy(&zTemp[i],",...",4);
868             break;
869           }
870           zTemp[i++] = ',';
871           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
872             zTemp[i++] = '-';
873           }
874           memcpy(&zTemp[i], pColl->zName,n+1);
875           i += n;
876         }else if( i+4<nTemp-6 ){
877           memcpy(&zTemp[i],",nil",4);
878           i += 4;
879         }
880       }
881       zTemp[i++] = ')';
882       zTemp[i] = 0;
883       assert( i<nTemp );
884       break;
885     }
886     case P4_COLLSEQ: {
887       CollSeq *pColl = pOp->p4.pColl;
888       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
889       break;
890     }
891     case P4_FUNCDEF: {
892       FuncDef *pDef = pOp->p4.pFunc;
893       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
894       break;
895     }
896     case P4_INT64: {
897       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
898       break;
899     }
900     case P4_INT32: {
901       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
902       break;
903     }
904     case P4_REAL: {
905       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
906       break;
907     }
908     case P4_MEM: {
909       Mem *pMem = pOp->p4.pMem;
910       assert( (pMem->flags & MEM_Null)==0 );
911       if( pMem->flags & MEM_Str ){
912         zP4 = pMem->z;
913       }else if( pMem->flags & MEM_Int ){
914         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
915       }else if( pMem->flags & MEM_Real ){
916         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
917       }else{
918         assert( pMem->flags & MEM_Blob );
919         zP4 = "(blob)";
920       }
921       break;
922     }
923 #ifndef SQLITE_OMIT_VIRTUALTABLE
924     case P4_VTAB: {
925       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
926       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
927       break;
928     }
929 #endif
930     case P4_INTARRAY: {
931       sqlite3_snprintf(nTemp, zTemp, "intarray");
932       break;
933     }
934     case P4_SUBPROGRAM: {
935       sqlite3_snprintf(nTemp, zTemp, "program");
936       break;
937     }
938     default: {
939       zP4 = pOp->p4.z;
940       if( zP4==0 ){
941         zP4 = zTemp;
942         zTemp[0] = 0;
943       }
944     }
945   }
946   assert( zP4!=0 );
947   return zP4;
948 }
949 #endif
950 
951 /*
952 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
953 **
954 ** The prepared statements need to know in advance the complete set of
955 ** attached databases that they will be using.  A mask of these databases
956 ** is maintained in p->btreeMask and is used for locking and other purposes.
957 */
sqlite3VdbeUsesBtree(Vdbe * p,int i)958 void sqlite3VdbeUsesBtree(Vdbe *p, int i){
959   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
960   assert( i<(int)sizeof(p->btreeMask)*8 );
961   p->btreeMask |= ((yDbMask)1)<<i;
962   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
963     p->lockMask |= ((yDbMask)1)<<i;
964   }
965 }
966 
967 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
968 /*
969 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
970 ** this routine obtains the mutex associated with each BtShared structure
971 ** that may be accessed by the VM passed as an argument. In doing so it also
972 ** sets the BtShared.db member of each of the BtShared structures, ensuring
973 ** that the correct busy-handler callback is invoked if required.
974 **
975 ** If SQLite is not threadsafe but does support shared-cache mode, then
976 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
977 ** of all of BtShared structures accessible via the database handle
978 ** associated with the VM.
979 **
980 ** If SQLite is not threadsafe and does not support shared-cache mode, this
981 ** function is a no-op.
982 **
983 ** The p->btreeMask field is a bitmask of all btrees that the prepared
984 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
985 ** corresponding to btrees that use shared cache.  Then the runtime of
986 ** this routine is N*N.  But as N is rarely more than 1, this should not
987 ** be a problem.
988 */
sqlite3VdbeEnter(Vdbe * p)989 void sqlite3VdbeEnter(Vdbe *p){
990   int i;
991   yDbMask mask;
992   sqlite3 *db;
993   Db *aDb;
994   int nDb;
995   if( p->lockMask==0 ) return;  /* The common case */
996   db = p->db;
997   aDb = db->aDb;
998   nDb = db->nDb;
999   for(i=0, mask=1; i<nDb; i++, mask += mask){
1000     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
1001       sqlite3BtreeEnter(aDb[i].pBt);
1002     }
1003   }
1004 }
1005 #endif
1006 
1007 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
1008 /*
1009 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
1010 */
sqlite3VdbeLeave(Vdbe * p)1011 void sqlite3VdbeLeave(Vdbe *p){
1012   int i;
1013   yDbMask mask;
1014   sqlite3 *db;
1015   Db *aDb;
1016   int nDb;
1017   if( p->lockMask==0 ) return;  /* The common case */
1018   db = p->db;
1019   aDb = db->aDb;
1020   nDb = db->nDb;
1021   for(i=0, mask=1; i<nDb; i++, mask += mask){
1022     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
1023       sqlite3BtreeLeave(aDb[i].pBt);
1024     }
1025   }
1026 }
1027 #endif
1028 
1029 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
1030 /*
1031 ** Print a single opcode.  This routine is used for debugging only.
1032 */
sqlite3VdbePrintOp(FILE * pOut,int pc,Op * pOp)1033 void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
1034   char *zP4;
1035   char zPtr[50];
1036   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
1037   if( pOut==0 ) pOut = stdout;
1038   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
1039   fprintf(pOut, zFormat1, pc,
1040       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
1041 #ifdef SQLITE_DEBUG
1042       pOp->zComment ? pOp->zComment : ""
1043 #else
1044       ""
1045 #endif
1046   );
1047   fflush(pOut);
1048 }
1049 #endif
1050 
1051 /*
1052 ** Release an array of N Mem elements
1053 */
releaseMemArray(Mem * p,int N)1054 static void releaseMemArray(Mem *p, int N){
1055   if( p && N ){
1056     Mem *pEnd;
1057     sqlite3 *db = p->db;
1058     u8 malloc_failed = db->mallocFailed;
1059     if( db->pnBytesFreed ){
1060       for(pEnd=&p[N]; p<pEnd; p++){
1061         sqlite3DbFree(db, p->zMalloc);
1062       }
1063       return;
1064     }
1065     for(pEnd=&p[N]; p<pEnd; p++){
1066       assert( (&p[1])==pEnd || p[0].db==p[1].db );
1067 
1068       /* This block is really an inlined version of sqlite3VdbeMemRelease()
1069       ** that takes advantage of the fact that the memory cell value is
1070       ** being set to NULL after releasing any dynamic resources.
1071       **
1072       ** The justification for duplicating code is that according to
1073       ** callgrind, this causes a certain test case to hit the CPU 4.7
1074       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
1075       ** sqlite3MemRelease() were called from here. With -O2, this jumps
1076       ** to 6.6 percent. The test case is inserting 1000 rows into a table
1077       ** with no indexes using a single prepared INSERT statement, bind()
1078       ** and reset(). Inserts are grouped into a transaction.
1079       */
1080       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
1081         sqlite3VdbeMemRelease(p);
1082       }else if( p->zMalloc ){
1083         sqlite3DbFree(db, p->zMalloc);
1084         p->zMalloc = 0;
1085       }
1086 
1087       p->flags = MEM_Null;
1088     }
1089     db->mallocFailed = malloc_failed;
1090   }
1091 }
1092 
1093 /*
1094 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
1095 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
1096 */
sqlite3VdbeFrameDelete(VdbeFrame * p)1097 void sqlite3VdbeFrameDelete(VdbeFrame *p){
1098   int i;
1099   Mem *aMem = VdbeFrameMem(p);
1100   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
1101   for(i=0; i<p->nChildCsr; i++){
1102     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
1103   }
1104   releaseMemArray(aMem, p->nChildMem);
1105   sqlite3DbFree(p->v->db, p);
1106 }
1107 
1108 #ifndef SQLITE_OMIT_EXPLAIN
1109 /*
1110 ** Give a listing of the program in the virtual machine.
1111 **
1112 ** The interface is the same as sqlite3VdbeExec().  But instead of
1113 ** running the code, it invokes the callback once for each instruction.
1114 ** This feature is used to implement "EXPLAIN".
1115 **
1116 ** When p->explain==1, each instruction is listed.  When
1117 ** p->explain==2, only OP_Explain instructions are listed and these
1118 ** are shown in a different format.  p->explain==2 is used to implement
1119 ** EXPLAIN QUERY PLAN.
1120 **
1121 ** When p->explain==1, first the main program is listed, then each of
1122 ** the trigger subprograms are listed one by one.
1123 */
sqlite3VdbeList(Vdbe * p)1124 int sqlite3VdbeList(
1125   Vdbe *p                   /* The VDBE */
1126 ){
1127   int nRow;                            /* Stop when row count reaches this */
1128   int nSub = 0;                        /* Number of sub-vdbes seen so far */
1129   SubProgram **apSub = 0;              /* Array of sub-vdbes */
1130   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
1131   sqlite3 *db = p->db;                 /* The database connection */
1132   int i;                               /* Loop counter */
1133   int rc = SQLITE_OK;                  /* Return code */
1134   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
1135 
1136   assert( p->explain );
1137   assert( p->magic==VDBE_MAGIC_RUN );
1138   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
1139 
1140   /* Even though this opcode does not use dynamic strings for
1141   ** the result, result columns may become dynamic if the user calls
1142   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
1143   */
1144   releaseMemArray(pMem, 8);
1145 
1146   if( p->rc==SQLITE_NOMEM ){
1147     /* This happens if a malloc() inside a call to sqlite3_column_text() or
1148     ** sqlite3_column_text16() failed.  */
1149     db->mallocFailed = 1;
1150     return SQLITE_ERROR;
1151   }
1152 
1153   /* When the number of output rows reaches nRow, that means the
1154   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
1155   ** nRow is the sum of the number of rows in the main program, plus
1156   ** the sum of the number of rows in all trigger subprograms encountered
1157   ** so far.  The nRow value will increase as new trigger subprograms are
1158   ** encountered, but p->pc will eventually catch up to nRow.
1159   */
1160   nRow = p->nOp;
1161   if( p->explain==1 ){
1162     /* The first 8 memory cells are used for the result set.  So we will
1163     ** commandeer the 9th cell to use as storage for an array of pointers
1164     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
1165     ** cells.  */
1166     assert( p->nMem>9 );
1167     pSub = &p->aMem[9];
1168     if( pSub->flags&MEM_Blob ){
1169       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
1170       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
1171       nSub = pSub->n/sizeof(Vdbe*);
1172       apSub = (SubProgram **)pSub->z;
1173     }
1174     for(i=0; i<nSub; i++){
1175       nRow += apSub[i]->nOp;
1176     }
1177   }
1178 
1179   do{
1180     i = p->pc++;
1181   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
1182   if( i>=nRow ){
1183     p->rc = SQLITE_OK;
1184     rc = SQLITE_DONE;
1185   }else if( db->u1.isInterrupted ){
1186     p->rc = SQLITE_INTERRUPT;
1187     rc = SQLITE_ERROR;
1188     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
1189   }else{
1190     char *z;
1191     Op *pOp;
1192     if( i<p->nOp ){
1193       /* The output line number is small enough that we are still in the
1194       ** main program. */
1195       pOp = &p->aOp[i];
1196     }else{
1197       /* We are currently listing subprograms.  Figure out which one and
1198       ** pick up the appropriate opcode. */
1199       int j;
1200       i -= p->nOp;
1201       for(j=0; i>=apSub[j]->nOp; j++){
1202         i -= apSub[j]->nOp;
1203       }
1204       pOp = &apSub[j]->aOp[i];
1205     }
1206     if( p->explain==1 ){
1207       pMem->flags = MEM_Int;
1208       pMem->type = SQLITE_INTEGER;
1209       pMem->u.i = i;                                /* Program counter */
1210       pMem++;
1211 
1212       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
1213       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
1214       assert( pMem->z!=0 );
1215       pMem->n = sqlite3Strlen30(pMem->z);
1216       pMem->type = SQLITE_TEXT;
1217       pMem->enc = SQLITE_UTF8;
1218       pMem++;
1219 
1220       /* When an OP_Program opcode is encounter (the only opcode that has
1221       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
1222       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
1223       ** has not already been seen.
1224       */
1225       if( pOp->p4type==P4_SUBPROGRAM ){
1226         int nByte = (nSub+1)*sizeof(SubProgram*);
1227         int j;
1228         for(j=0; j<nSub; j++){
1229           if( apSub[j]==pOp->p4.pProgram ) break;
1230         }
1231         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
1232           apSub = (SubProgram **)pSub->z;
1233           apSub[nSub++] = pOp->p4.pProgram;
1234           pSub->flags |= MEM_Blob;
1235           pSub->n = nSub*sizeof(SubProgram*);
1236         }
1237       }
1238     }
1239 
1240     pMem->flags = MEM_Int;
1241     pMem->u.i = pOp->p1;                          /* P1 */
1242     pMem->type = SQLITE_INTEGER;
1243     pMem++;
1244 
1245     pMem->flags = MEM_Int;
1246     pMem->u.i = pOp->p2;                          /* P2 */
1247     pMem->type = SQLITE_INTEGER;
1248     pMem++;
1249 
1250     pMem->flags = MEM_Int;
1251     pMem->u.i = pOp->p3;                          /* P3 */
1252     pMem->type = SQLITE_INTEGER;
1253     pMem++;
1254 
1255     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
1256       assert( p->db->mallocFailed );
1257       return SQLITE_ERROR;
1258     }
1259     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
1260     z = displayP4(pOp, pMem->z, 32);
1261     if( z!=pMem->z ){
1262       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
1263     }else{
1264       assert( pMem->z!=0 );
1265       pMem->n = sqlite3Strlen30(pMem->z);
1266       pMem->enc = SQLITE_UTF8;
1267     }
1268     pMem->type = SQLITE_TEXT;
1269     pMem++;
1270 
1271     if( p->explain==1 ){
1272       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
1273         assert( p->db->mallocFailed );
1274         return SQLITE_ERROR;
1275       }
1276       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
1277       pMem->n = 2;
1278       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
1279       pMem->type = SQLITE_TEXT;
1280       pMem->enc = SQLITE_UTF8;
1281       pMem++;
1282 
1283 #ifdef SQLITE_DEBUG
1284       if( pOp->zComment ){
1285         pMem->flags = MEM_Str|MEM_Term;
1286         pMem->z = pOp->zComment;
1287         pMem->n = sqlite3Strlen30(pMem->z);
1288         pMem->enc = SQLITE_UTF8;
1289         pMem->type = SQLITE_TEXT;
1290       }else
1291 #endif
1292       {
1293         pMem->flags = MEM_Null;                       /* Comment */
1294         pMem->type = SQLITE_NULL;
1295       }
1296     }
1297 
1298     p->nResColumn = 8 - 4*(p->explain-1);
1299     p->rc = SQLITE_OK;
1300     rc = SQLITE_ROW;
1301   }
1302   return rc;
1303 }
1304 #endif /* SQLITE_OMIT_EXPLAIN */
1305 
1306 #ifdef SQLITE_DEBUG
1307 /*
1308 ** Print the SQL that was used to generate a VDBE program.
1309 */
sqlite3VdbePrintSql(Vdbe * p)1310 void sqlite3VdbePrintSql(Vdbe *p){
1311   int nOp = p->nOp;
1312   VdbeOp *pOp;
1313   if( nOp<1 ) return;
1314   pOp = &p->aOp[0];
1315   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
1316     const char *z = pOp->p4.z;
1317     while( sqlite3Isspace(*z) ) z++;
1318     printf("SQL: [%s]\n", z);
1319   }
1320 }
1321 #endif
1322 
1323 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
1324 /*
1325 ** Print an IOTRACE message showing SQL content.
1326 */
sqlite3VdbeIOTraceSql(Vdbe * p)1327 void sqlite3VdbeIOTraceSql(Vdbe *p){
1328   int nOp = p->nOp;
1329   VdbeOp *pOp;
1330   if( sqlite3IoTrace==0 ) return;
1331   if( nOp<1 ) return;
1332   pOp = &p->aOp[0];
1333   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
1334     int i, j;
1335     char z[1000];
1336     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
1337     for(i=0; sqlite3Isspace(z[i]); i++){}
1338     for(j=0; z[i]; i++){
1339       if( sqlite3Isspace(z[i]) ){
1340         if( z[i-1]!=' ' ){
1341           z[j++] = ' ';
1342         }
1343       }else{
1344         z[j++] = z[i];
1345       }
1346     }
1347     z[j] = 0;
1348     sqlite3IoTrace("SQL %s\n", z);
1349   }
1350 }
1351 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
1352 
1353 /*
1354 ** Allocate space from a fixed size buffer and return a pointer to
1355 ** that space.  If insufficient space is available, return NULL.
1356 **
1357 ** The pBuf parameter is the initial value of a pointer which will
1358 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
1359 ** NULL, it means that memory space has already been allocated and that
1360 ** this routine should not allocate any new memory.  When pBuf is not
1361 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
1362 ** is NULL.
1363 **
1364 ** nByte is the number of bytes of space needed.
1365 **
1366 ** *ppFrom points to available space and pEnd points to the end of the
1367 ** available space.  When space is allocated, *ppFrom is advanced past
1368 ** the end of the allocated space.
1369 **
1370 ** *pnByte is a counter of the number of bytes of space that have failed
1371 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
1372 ** request, then increment *pnByte by the amount of the request.
1373 */
allocSpace(void * pBuf,int nByte,u8 ** ppFrom,u8 * pEnd,int * pnByte)1374 static void *allocSpace(
1375   void *pBuf,          /* Where return pointer will be stored */
1376   int nByte,           /* Number of bytes to allocate */
1377   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
1378   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
1379   int *pnByte          /* If allocation cannot be made, increment *pnByte */
1380 ){
1381   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
1382   if( pBuf ) return pBuf;
1383   nByte = ROUND8(nByte);
1384   if( &(*ppFrom)[nByte] <= pEnd ){
1385     pBuf = (void*)*ppFrom;
1386     *ppFrom += nByte;
1387   }else{
1388     *pnByte += nByte;
1389   }
1390   return pBuf;
1391 }
1392 
1393 /*
1394 ** Prepare a virtual machine for execution.  This involves things such
1395 ** as allocating stack space and initializing the program counter.
1396 ** After the VDBE has be prepped, it can be executed by one or more
1397 ** calls to sqlite3VdbeExec().
1398 **
1399 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
1400 ** VDBE_MAGIC_RUN.
1401 **
1402 ** This function may be called more than once on a single virtual machine.
1403 ** The first call is made while compiling the SQL statement. Subsequent
1404 ** calls are made as part of the process of resetting a statement to be
1405 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
1406 ** and isExplain parameters are only passed correct values the first time
1407 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
1408 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
1409 */
sqlite3VdbeMakeReady(Vdbe * p,int nVar,int nMem,int nCursor,int nArg,int isExplain,int usesStmtJournal)1410 void sqlite3VdbeMakeReady(
1411   Vdbe *p,                       /* The VDBE */
1412   int nVar,                      /* Number of '?' see in the SQL statement */
1413   int nMem,                      /* Number of memory cells to allocate */
1414   int nCursor,                   /* Number of cursors to allocate */
1415   int nArg,                      /* Maximum number of args in SubPrograms */
1416   int isExplain,                 /* True if the EXPLAIN keywords is present */
1417   int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
1418 ){
1419   int n;
1420   sqlite3 *db = p->db;
1421 
1422   assert( p!=0 );
1423   assert( p->magic==VDBE_MAGIC_INIT );
1424 
1425   /* There should be at least one opcode.
1426   */
1427   assert( p->nOp>0 );
1428 
1429   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
1430   p->magic = VDBE_MAGIC_RUN;
1431 
1432   /* For each cursor required, also allocate a memory cell. Memory
1433   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
1434   ** the vdbe program. Instead they are used to allocate space for
1435   ** VdbeCursor/BtCursor structures. The blob of memory associated with
1436   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
1437   ** stores the blob of memory associated with cursor 1, etc.
1438   **
1439   ** See also: allocateCursor().
1440   */
1441   nMem += nCursor;
1442 
1443   /* Allocate space for memory registers, SQL variables, VDBE cursors and
1444   ** an array to marshal SQL function arguments in. This is only done the
1445   ** first time this function is called for a given VDBE, not when it is
1446   ** being called from sqlite3_reset() to reset the virtual machine.
1447   */
1448   if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
1449     u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
1450     u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
1451     int nByte;                              /* How much extra memory needed */
1452 
1453     resolveP2Values(p, &nArg);
1454     p->usesStmtJournal = (u8)usesStmtJournal;
1455     if( isExplain && nMem<10 ){
1456       nMem = 10;
1457     }
1458     memset(zCsr, 0, zEnd-zCsr);
1459     zCsr += (zCsr - (u8*)0)&7;
1460     assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
1461 
1462     /* Memory for registers, parameters, cursor, etc, is allocated in two
1463     ** passes.  On the first pass, we try to reuse unused space at the
1464     ** end of the opcode array.  If we are unable to satisfy all memory
1465     ** requirements by reusing the opcode array tail, then the second
1466     ** pass will fill in the rest using a fresh allocation.
1467     **
1468     ** This two-pass approach that reuses as much memory as possible from
1469     ** the leftover space at the end of the opcode array can significantly
1470     ** reduce the amount of memory held by a prepared statement.
1471     */
1472     do {
1473       nByte = 0;
1474       p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
1475       p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
1476       p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
1477       p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
1478       p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
1479                             &zCsr, zEnd, &nByte);
1480       if( nByte ){
1481         p->pFree = sqlite3DbMallocZero(db, nByte);
1482       }
1483       zCsr = p->pFree;
1484       zEnd = &zCsr[nByte];
1485     }while( nByte && !db->mallocFailed );
1486 
1487     p->nCursor = (u16)nCursor;
1488     if( p->aVar ){
1489       p->nVar = (ynVar)nVar;
1490       for(n=0; n<nVar; n++){
1491         p->aVar[n].flags = MEM_Null;
1492         p->aVar[n].db = db;
1493       }
1494     }
1495     if( p->aMem ){
1496       p->aMem--;                      /* aMem[] goes from 1..nMem */
1497       p->nMem = nMem;                 /*       not from 0..nMem-1 */
1498       for(n=1; n<=nMem; n++){
1499         p->aMem[n].flags = MEM_Null;
1500         p->aMem[n].db = db;
1501       }
1502     }
1503   }
1504 #ifdef SQLITE_DEBUG
1505   for(n=1; n<p->nMem; n++){
1506     assert( p->aMem[n].db==db );
1507   }
1508 #endif
1509 
1510   p->pc = -1;
1511   p->rc = SQLITE_OK;
1512   p->errorAction = OE_Abort;
1513   p->explain |= isExplain;
1514   p->magic = VDBE_MAGIC_RUN;
1515   p->nChange = 0;
1516   p->cacheCtr = 1;
1517   p->minWriteFileFormat = 255;
1518   p->iStatement = 0;
1519   p->nFkConstraint = 0;
1520 #ifdef VDBE_PROFILE
1521   {
1522     int i;
1523     for(i=0; i<p->nOp; i++){
1524       p->aOp[i].cnt = 0;
1525       p->aOp[i].cycles = 0;
1526     }
1527   }
1528 #endif
1529 }
1530 
1531 /*
1532 ** Close a VDBE cursor and release all the resources that cursor
1533 ** happens to hold.
1534 */
sqlite3VdbeFreeCursor(Vdbe * p,VdbeCursor * pCx)1535 void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
1536   if( pCx==0 ){
1537     return;
1538   }
1539   if( pCx->pBt ){
1540     sqlite3BtreeClose(pCx->pBt);
1541     /* The pCx->pCursor will be close automatically, if it exists, by
1542     ** the call above. */
1543   }else if( pCx->pCursor ){
1544     sqlite3BtreeCloseCursor(pCx->pCursor);
1545   }
1546 #ifndef SQLITE_OMIT_VIRTUALTABLE
1547   if( pCx->pVtabCursor ){
1548     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
1549     const sqlite3_module *pModule = pCx->pModule;
1550     p->inVtabMethod = 1;
1551     pModule->xClose(pVtabCursor);
1552     p->inVtabMethod = 0;
1553   }
1554 #endif
1555 }
1556 
1557 /*
1558 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
1559 ** is used, for example, when a trigger sub-program is halted to restore
1560 ** control to the main program.
1561 */
sqlite3VdbeFrameRestore(VdbeFrame * pFrame)1562 int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
1563   Vdbe *v = pFrame->v;
1564   v->aOp = pFrame->aOp;
1565   v->nOp = pFrame->nOp;
1566   v->aMem = pFrame->aMem;
1567   v->nMem = pFrame->nMem;
1568   v->apCsr = pFrame->apCsr;
1569   v->nCursor = pFrame->nCursor;
1570   v->db->lastRowid = pFrame->lastRowid;
1571   v->nChange = pFrame->nChange;
1572   return pFrame->pc;
1573 }
1574 
1575 /*
1576 ** Close all cursors.
1577 **
1578 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
1579 ** cell array. This is necessary as the memory cell array may contain
1580 ** pointers to VdbeFrame objects, which may in turn contain pointers to
1581 ** open cursors.
1582 */
closeAllCursors(Vdbe * p)1583 static void closeAllCursors(Vdbe *p){
1584   if( p->pFrame ){
1585     VdbeFrame *pFrame;
1586     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
1587     sqlite3VdbeFrameRestore(pFrame);
1588   }
1589   p->pFrame = 0;
1590   p->nFrame = 0;
1591 
1592   if( p->apCsr ){
1593     int i;
1594     for(i=0; i<p->nCursor; i++){
1595       VdbeCursor *pC = p->apCsr[i];
1596       if( pC ){
1597         sqlite3VdbeFreeCursor(p, pC);
1598         p->apCsr[i] = 0;
1599       }
1600     }
1601   }
1602   if( p->aMem ){
1603     releaseMemArray(&p->aMem[1], p->nMem);
1604   }
1605   while( p->pDelFrame ){
1606     VdbeFrame *pDel = p->pDelFrame;
1607     p->pDelFrame = pDel->pParent;
1608     sqlite3VdbeFrameDelete(pDel);
1609   }
1610 }
1611 
1612 /*
1613 ** Clean up the VM after execution.
1614 **
1615 ** This routine will automatically close any cursors, lists, and/or
1616 ** sorters that were left open.  It also deletes the values of
1617 ** variables in the aVar[] array.
1618 */
Cleanup(Vdbe * p)1619 static void Cleanup(Vdbe *p){
1620   sqlite3 *db = p->db;
1621 
1622 #ifdef SQLITE_DEBUG
1623   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
1624   ** Vdbe.aMem[] arrays have already been cleaned up.  */
1625   int i;
1626   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
1627   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
1628 #endif
1629 
1630   sqlite3DbFree(db, p->zErrMsg);
1631   p->zErrMsg = 0;
1632   p->pResultSet = 0;
1633 }
1634 
1635 /*
1636 ** Set the number of result columns that will be returned by this SQL
1637 ** statement. This is now set at compile time, rather than during
1638 ** execution of the vdbe program so that sqlite3_column_count() can
1639 ** be called on an SQL statement before sqlite3_step().
1640 */
sqlite3VdbeSetNumCols(Vdbe * p,int nResColumn)1641 void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
1642   Mem *pColName;
1643   int n;
1644   sqlite3 *db = p->db;
1645 
1646   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
1647   sqlite3DbFree(db, p->aColName);
1648   n = nResColumn*COLNAME_N;
1649   p->nResColumn = (u16)nResColumn;
1650   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
1651   if( p->aColName==0 ) return;
1652   while( n-- > 0 ){
1653     pColName->flags = MEM_Null;
1654     pColName->db = p->db;
1655     pColName++;
1656   }
1657 }
1658 
1659 /*
1660 ** Set the name of the idx'th column to be returned by the SQL statement.
1661 ** zName must be a pointer to a nul terminated string.
1662 **
1663 ** This call must be made after a call to sqlite3VdbeSetNumCols().
1664 **
1665 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
1666 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
1667 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
1668 */
sqlite3VdbeSetColName(Vdbe * p,int idx,int var,const char * zName,void (* xDel)(void *))1669 int sqlite3VdbeSetColName(
1670   Vdbe *p,                         /* Vdbe being configured */
1671   int idx,                         /* Index of column zName applies to */
1672   int var,                         /* One of the COLNAME_* constants */
1673   const char *zName,               /* Pointer to buffer containing name */
1674   void (*xDel)(void*)              /* Memory management strategy for zName */
1675 ){
1676   int rc;
1677   Mem *pColName;
1678   assert( idx<p->nResColumn );
1679   assert( var<COLNAME_N );
1680   if( p->db->mallocFailed ){
1681     assert( !zName || xDel!=SQLITE_DYNAMIC );
1682     return SQLITE_NOMEM;
1683   }
1684   assert( p->aColName!=0 );
1685   pColName = &(p->aColName[idx+var*p->nResColumn]);
1686   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
1687   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
1688   return rc;
1689 }
1690 
1691 /*
1692 ** A read or write transaction may or may not be active on database handle
1693 ** db. If a transaction is active, commit it. If there is a
1694 ** write-transaction spanning more than one database file, this routine
1695 ** takes care of the master journal trickery.
1696 */
vdbeCommit(sqlite3 * db,Vdbe * p)1697 static int vdbeCommit(sqlite3 *db, Vdbe *p){
1698   int i;
1699   int nTrans = 0;  /* Number of databases with an active write-transaction */
1700   int rc = SQLITE_OK;
1701   int needXcommit = 0;
1702 
1703 #ifdef SQLITE_OMIT_VIRTUALTABLE
1704   /* With this option, sqlite3VtabSync() is defined to be simply
1705   ** SQLITE_OK so p is not used.
1706   */
1707   UNUSED_PARAMETER(p);
1708 #endif
1709 
1710   /* Before doing anything else, call the xSync() callback for any
1711   ** virtual module tables written in this transaction. This has to
1712   ** be done before determining whether a master journal file is
1713   ** required, as an xSync() callback may add an attached database
1714   ** to the transaction.
1715   */
1716   rc = sqlite3VtabSync(db, &p->zErrMsg);
1717 
1718   /* This loop determines (a) if the commit hook should be invoked and
1719   ** (b) how many database files have open write transactions, not
1720   ** including the temp database. (b) is important because if more than
1721   ** one database file has an open write transaction, a master journal
1722   ** file is required for an atomic commit.
1723   */
1724   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1725     Btree *pBt = db->aDb[i].pBt;
1726     if( sqlite3BtreeIsInTrans(pBt) ){
1727       needXcommit = 1;
1728       if( i!=1 ) nTrans++;
1729       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
1730     }
1731   }
1732   if( rc!=SQLITE_OK ){
1733     return rc;
1734   }
1735 
1736   /* If there are any write-transactions at all, invoke the commit hook */
1737   if( needXcommit && db->xCommitCallback ){
1738     rc = db->xCommitCallback(db->pCommitArg);
1739     if( rc ){
1740       return SQLITE_CONSTRAINT;
1741     }
1742   }
1743 
1744   /* The simple case - no more than one database file (not counting the
1745   ** TEMP database) has a transaction active.   There is no need for the
1746   ** master-journal.
1747   **
1748   ** If the return value of sqlite3BtreeGetFilename() is a zero length
1749   ** string, it means the main database is :memory: or a temp file.  In
1750   ** that case we do not support atomic multi-file commits, so use the
1751   ** simple case then too.
1752   */
1753   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
1754    || nTrans<=1
1755   ){
1756     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1757       Btree *pBt = db->aDb[i].pBt;
1758       if( pBt ){
1759         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
1760       }
1761     }
1762 
1763     /* Do the commit only if all databases successfully complete phase 1.
1764     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
1765     ** IO error while deleting or truncating a journal file. It is unlikely,
1766     ** but could happen. In this case abandon processing and return the error.
1767     */
1768     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1769       Btree *pBt = db->aDb[i].pBt;
1770       if( pBt ){
1771         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
1772       }
1773     }
1774     if( rc==SQLITE_OK ){
1775       sqlite3VtabCommit(db);
1776     }
1777   }
1778 
1779   /* The complex case - There is a multi-file write-transaction active.
1780   ** This requires a master journal file to ensure the transaction is
1781   ** committed atomicly.
1782   */
1783 #ifndef SQLITE_OMIT_DISKIO
1784   else{
1785     sqlite3_vfs *pVfs = db->pVfs;
1786     int needSync = 0;
1787     char *zMaster = 0;   /* File-name for the master journal */
1788     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
1789     sqlite3_file *pMaster = 0;
1790     i64 offset = 0;
1791     int res;
1792 
1793     /* Select a master journal file name */
1794     do {
1795       u32 iRandom;
1796       sqlite3DbFree(db, zMaster);
1797       sqlite3_randomness(sizeof(iRandom), &iRandom);
1798       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
1799       if( !zMaster ){
1800         return SQLITE_NOMEM;
1801       }
1802       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
1803     }while( rc==SQLITE_OK && res );
1804     if( rc==SQLITE_OK ){
1805       /* Open the master journal. */
1806       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
1807           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
1808           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
1809       );
1810     }
1811     if( rc!=SQLITE_OK ){
1812       sqlite3DbFree(db, zMaster);
1813       return rc;
1814     }
1815 
1816     /* Write the name of each database file in the transaction into the new
1817     ** master journal file. If an error occurs at this point close
1818     ** and delete the master journal file. All the individual journal files
1819     ** still have 'null' as the master journal pointer, so they will roll
1820     ** back independently if a failure occurs.
1821     */
1822     for(i=0; i<db->nDb; i++){
1823       Btree *pBt = db->aDb[i].pBt;
1824       if( sqlite3BtreeIsInTrans(pBt) ){
1825         char const *zFile = sqlite3BtreeGetJournalname(pBt);
1826         if( zFile==0 ){
1827           continue;  /* Ignore TEMP and :memory: databases */
1828         }
1829         assert( zFile[0]!=0 );
1830         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
1831           needSync = 1;
1832         }
1833         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
1834         offset += sqlite3Strlen30(zFile)+1;
1835         if( rc!=SQLITE_OK ){
1836           sqlite3OsCloseFree(pMaster);
1837           sqlite3OsDelete(pVfs, zMaster, 0);
1838           sqlite3DbFree(db, zMaster);
1839           return rc;
1840         }
1841       }
1842     }
1843 
1844     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
1845     ** flag is set this is not required.
1846     */
1847     if( needSync
1848      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
1849      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
1850     ){
1851       sqlite3OsCloseFree(pMaster);
1852       sqlite3OsDelete(pVfs, zMaster, 0);
1853       sqlite3DbFree(db, zMaster);
1854       return rc;
1855     }
1856 
1857     /* Sync all the db files involved in the transaction. The same call
1858     ** sets the master journal pointer in each individual journal. If
1859     ** an error occurs here, do not delete the master journal file.
1860     **
1861     ** If the error occurs during the first call to
1862     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
1863     ** master journal file will be orphaned. But we cannot delete it,
1864     ** in case the master journal file name was written into the journal
1865     ** file before the failure occurred.
1866     */
1867     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1868       Btree *pBt = db->aDb[i].pBt;
1869       if( pBt ){
1870         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
1871       }
1872     }
1873     sqlite3OsCloseFree(pMaster);
1874     assert( rc!=SQLITE_BUSY );
1875     if( rc!=SQLITE_OK ){
1876       sqlite3DbFree(db, zMaster);
1877       return rc;
1878     }
1879 
1880     /* Delete the master journal file. This commits the transaction. After
1881     ** doing this the directory is synced again before any individual
1882     ** transaction files are deleted.
1883     */
1884     rc = sqlite3OsDelete(pVfs, zMaster, 1);
1885     sqlite3DbFree(db, zMaster);
1886     zMaster = 0;
1887     if( rc ){
1888       return rc;
1889     }
1890 
1891     /* All files and directories have already been synced, so the following
1892     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
1893     ** deleting or truncating journals. If something goes wrong while
1894     ** this is happening we don't really care. The integrity of the
1895     ** transaction is already guaranteed, but some stray 'cold' journals
1896     ** may be lying around. Returning an error code won't help matters.
1897     */
1898     disable_simulated_io_errors();
1899     sqlite3BeginBenignMalloc();
1900     for(i=0; i<db->nDb; i++){
1901       Btree *pBt = db->aDb[i].pBt;
1902       if( pBt ){
1903         sqlite3BtreeCommitPhaseTwo(pBt, 1);
1904       }
1905     }
1906     sqlite3EndBenignMalloc();
1907     enable_simulated_io_errors();
1908 
1909     sqlite3VtabCommit(db);
1910   }
1911 #endif
1912 
1913   return rc;
1914 }
1915 
1916 /*
1917 ** This routine checks that the sqlite3.activeVdbeCnt count variable
1918 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
1919 ** currently active. An assertion fails if the two counts do not match.
1920 ** This is an internal self-check only - it is not an essential processing
1921 ** step.
1922 **
1923 ** This is a no-op if NDEBUG is defined.
1924 */
1925 #ifndef NDEBUG
checkActiveVdbeCnt(sqlite3 * db)1926 static void checkActiveVdbeCnt(sqlite3 *db){
1927   Vdbe *p;
1928   int cnt = 0;
1929   int nWrite = 0;
1930   p = db->pVdbe;
1931   while( p ){
1932     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
1933       cnt++;
1934       if( p->readOnly==0 ) nWrite++;
1935     }
1936     p = p->pNext;
1937   }
1938   assert( cnt==db->activeVdbeCnt );
1939   assert( nWrite==db->writeVdbeCnt );
1940 }
1941 #else
1942 #define checkActiveVdbeCnt(x)
1943 #endif
1944 
1945 /*
1946 ** For every Btree that in database connection db which
1947 ** has been modified, "trip" or invalidate each cursor in
1948 ** that Btree might have been modified so that the cursor
1949 ** can never be used again.  This happens when a rollback
1950 *** occurs.  We have to trip all the other cursors, even
1951 ** cursor from other VMs in different database connections,
1952 ** so that none of them try to use the data at which they
1953 ** were pointing and which now may have been changed due
1954 ** to the rollback.
1955 **
1956 ** Remember that a rollback can delete tables complete and
1957 ** reorder rootpages.  So it is not sufficient just to save
1958 ** the state of the cursor.  We have to invalidate the cursor
1959 ** so that it is never used again.
1960 */
invalidateCursorsOnModifiedBtrees(sqlite3 * db)1961 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
1962   int i;
1963   for(i=0; i<db->nDb; i++){
1964     Btree *p = db->aDb[i].pBt;
1965     if( p && sqlite3BtreeIsInTrans(p) ){
1966       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
1967     }
1968   }
1969 }
1970 
1971 /*
1972 ** If the Vdbe passed as the first argument opened a statement-transaction,
1973 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
1974 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
1975 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
1976 ** statement transaction is commtted.
1977 **
1978 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
1979 ** Otherwise SQLITE_OK.
1980 */
sqlite3VdbeCloseStatement(Vdbe * p,int eOp)1981 int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
1982   sqlite3 *const db = p->db;
1983   int rc = SQLITE_OK;
1984 
1985   /* If p->iStatement is greater than zero, then this Vdbe opened a
1986   ** statement transaction that should be closed here. The only exception
1987   ** is that an IO error may have occured, causing an emergency rollback.
1988   ** In this case (db->nStatement==0), and there is nothing to do.
1989   */
1990   if( db->nStatement && p->iStatement ){
1991     int i;
1992     const int iSavepoint = p->iStatement-1;
1993 
1994     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
1995     assert( db->nStatement>0 );
1996     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
1997 
1998     for(i=0; i<db->nDb; i++){
1999       int rc2 = SQLITE_OK;
2000       Btree *pBt = db->aDb[i].pBt;
2001       if( pBt ){
2002         if( eOp==SAVEPOINT_ROLLBACK ){
2003           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
2004         }
2005         if( rc2==SQLITE_OK ){
2006           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
2007         }
2008         if( rc==SQLITE_OK ){
2009           rc = rc2;
2010         }
2011       }
2012     }
2013     db->nStatement--;
2014     p->iStatement = 0;
2015 
2016     /* If the statement transaction is being rolled back, also restore the
2017     ** database handles deferred constraint counter to the value it had when
2018     ** the statement transaction was opened.  */
2019     if( eOp==SAVEPOINT_ROLLBACK ){
2020       db->nDeferredCons = p->nStmtDefCons;
2021     }
2022   }
2023   return rc;
2024 }
2025 
2026 /*
2027 ** This function is called when a transaction opened by the database
2028 ** handle associated with the VM passed as an argument is about to be
2029 ** committed. If there are outstanding deferred foreign key constraint
2030 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
2031 **
2032 ** If there are outstanding FK violations and this function returns
2033 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
2034 ** an error message to it. Then return SQLITE_ERROR.
2035 */
2036 #ifndef SQLITE_OMIT_FOREIGN_KEY
sqlite3VdbeCheckFk(Vdbe * p,int deferred)2037 int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
2038   sqlite3 *db = p->db;
2039   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
2040     p->rc = SQLITE_CONSTRAINT;
2041     p->errorAction = OE_Abort;
2042     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
2043     return SQLITE_ERROR;
2044   }
2045   return SQLITE_OK;
2046 }
2047 #endif
2048 
2049 /*
2050 ** This routine is called the when a VDBE tries to halt.  If the VDBE
2051 ** has made changes and is in autocommit mode, then commit those
2052 ** changes.  If a rollback is needed, then do the rollback.
2053 **
2054 ** This routine is the only way to move the state of a VM from
2055 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
2056 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
2057 **
2058 ** Return an error code.  If the commit could not complete because of
2059 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
2060 ** means the close did not happen and needs to be repeated.
2061 */
sqlite3VdbeHalt(Vdbe * p)2062 int sqlite3VdbeHalt(Vdbe *p){
2063   int rc;                         /* Used to store transient return codes */
2064   sqlite3 *db = p->db;
2065 
2066   /* This function contains the logic that determines if a statement or
2067   ** transaction will be committed or rolled back as a result of the
2068   ** execution of this virtual machine.
2069   **
2070   ** If any of the following errors occur:
2071   **
2072   **     SQLITE_NOMEM
2073   **     SQLITE_IOERR
2074   **     SQLITE_FULL
2075   **     SQLITE_INTERRUPT
2076   **
2077   ** Then the internal cache might have been left in an inconsistent
2078   ** state.  We need to rollback the statement transaction, if there is
2079   ** one, or the complete transaction if there is no statement transaction.
2080   */
2081 
2082   if( p->db->mallocFailed ){
2083     p->rc = SQLITE_NOMEM;
2084   }
2085   closeAllCursors(p);
2086   if( p->magic!=VDBE_MAGIC_RUN ){
2087     return SQLITE_OK;
2088   }
2089   checkActiveVdbeCnt(db);
2090 
2091   /* No commit or rollback needed if the program never started */
2092   if( p->pc>=0 ){
2093     int mrc;   /* Primary error code from p->rc */
2094     int eStatementOp = 0;
2095     int isSpecialError;            /* Set to true if a 'special' error */
2096 
2097     /* Lock all btrees used by the statement */
2098     sqlite3VdbeEnter(p);
2099 
2100     /* Check for one of the special errors */
2101     mrc = p->rc & 0xff;
2102     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
2103     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
2104                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
2105     if( isSpecialError ){
2106       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
2107       ** no rollback is necessary. Otherwise, at least a savepoint
2108       ** transaction must be rolled back to restore the database to a
2109       ** consistent state.
2110       **
2111       ** Even if the statement is read-only, it is important to perform
2112       ** a statement or transaction rollback operation. If the error
2113       ** occured while writing to the journal, sub-journal or database
2114       ** file as part of an effort to free up cache space (see function
2115       ** pagerStress() in pager.c), the rollback is required to restore
2116       ** the pager to a consistent state.
2117       */
2118       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
2119         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
2120           eStatementOp = SAVEPOINT_ROLLBACK;
2121         }else{
2122           /* We are forced to roll back the active transaction. Before doing
2123           ** so, abort any other statements this handle currently has active.
2124           */
2125           invalidateCursorsOnModifiedBtrees(db);
2126           sqlite3RollbackAll(db);
2127           sqlite3CloseSavepoints(db);
2128           db->autoCommit = 1;
2129         }
2130       }
2131     }
2132 
2133     /* Check for immediate foreign key violations. */
2134     if( p->rc==SQLITE_OK ){
2135       sqlite3VdbeCheckFk(p, 0);
2136     }
2137 
2138     /* If the auto-commit flag is set and this is the only active writer
2139     ** VM, then we do either a commit or rollback of the current transaction.
2140     **
2141     ** Note: This block also runs if one of the special errors handled
2142     ** above has occurred.
2143     */
2144     if( !sqlite3VtabInSync(db)
2145      && db->autoCommit
2146      && db->writeVdbeCnt==(p->readOnly==0)
2147     ){
2148       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
2149         rc = sqlite3VdbeCheckFk(p, 1);
2150         if( rc!=SQLITE_OK ){
2151           if( NEVER(p->readOnly) ){
2152             sqlite3VdbeLeave(p);
2153             return SQLITE_ERROR;
2154           }
2155           rc = SQLITE_CONSTRAINT;
2156         }else{
2157           /* The auto-commit flag is true, the vdbe program was successful
2158           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
2159           ** key constraints to hold up the transaction. This means a commit
2160           ** is required. */
2161           rc = vdbeCommit(db, p);
2162         }
2163         if( rc==SQLITE_BUSY && p->readOnly ){
2164           sqlite3VdbeLeave(p);
2165           return SQLITE_BUSY;
2166         }else if( rc!=SQLITE_OK ){
2167           p->rc = rc;
2168           sqlite3RollbackAll(db);
2169         }else{
2170           db->nDeferredCons = 0;
2171           sqlite3CommitInternalChanges(db);
2172         }
2173       }else{
2174         sqlite3RollbackAll(db);
2175       }
2176       db->nStatement = 0;
2177     }else if( eStatementOp==0 ){
2178       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
2179         eStatementOp = SAVEPOINT_RELEASE;
2180       }else if( p->errorAction==OE_Abort ){
2181         eStatementOp = SAVEPOINT_ROLLBACK;
2182       }else{
2183         invalidateCursorsOnModifiedBtrees(db);
2184         sqlite3RollbackAll(db);
2185         sqlite3CloseSavepoints(db);
2186         db->autoCommit = 1;
2187       }
2188     }
2189 
2190     /* If eStatementOp is non-zero, then a statement transaction needs to
2191     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
2192     ** do so. If this operation returns an error, and the current statement
2193     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
2194     ** current statement error code.
2195     **
2196     ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
2197     ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
2198     ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in
2199     ** the following code.
2200     */
2201     if( eStatementOp ){
2202       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
2203       if( rc ){
2204         assert( eStatementOp==SAVEPOINT_ROLLBACK );
2205         if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
2206           p->rc = rc;
2207           sqlite3DbFree(db, p->zErrMsg);
2208           p->zErrMsg = 0;
2209         }
2210         invalidateCursorsOnModifiedBtrees(db);
2211         sqlite3RollbackAll(db);
2212         sqlite3CloseSavepoints(db);
2213         db->autoCommit = 1;
2214       }
2215     }
2216 
2217     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
2218     ** has been rolled back, update the database connection change-counter.
2219     */
2220     if( p->changeCntOn ){
2221       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
2222         sqlite3VdbeSetChanges(db, p->nChange);
2223       }else{
2224         sqlite3VdbeSetChanges(db, 0);
2225       }
2226       p->nChange = 0;
2227     }
2228 
2229     /* Rollback or commit any schema changes that occurred. */
2230     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
2231       sqlite3ResetInternalSchema(db, -1);
2232       db->flags = (db->flags | SQLITE_InternChanges);
2233     }
2234 
2235     /* Release the locks */
2236     sqlite3VdbeLeave(p);
2237   }
2238 
2239   /* We have successfully halted and closed the VM.  Record this fact. */
2240   if( p->pc>=0 ){
2241     db->activeVdbeCnt--;
2242     if( !p->readOnly ){
2243       db->writeVdbeCnt--;
2244     }
2245     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
2246   }
2247   p->magic = VDBE_MAGIC_HALT;
2248   checkActiveVdbeCnt(db);
2249   if( p->db->mallocFailed ){
2250     p->rc = SQLITE_NOMEM;
2251   }
2252 
2253   /* If the auto-commit flag is set to true, then any locks that were held
2254   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
2255   ** to invoke any required unlock-notify callbacks.
2256   */
2257   if( db->autoCommit ){
2258     sqlite3ConnectionUnlocked(db);
2259   }
2260 
2261   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
2262   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
2263 }
2264 
2265 
2266 /*
2267 ** Each VDBE holds the result of the most recent sqlite3_step() call
2268 ** in p->rc.  This routine sets that result back to SQLITE_OK.
2269 */
sqlite3VdbeResetStepResult(Vdbe * p)2270 void sqlite3VdbeResetStepResult(Vdbe *p){
2271   p->rc = SQLITE_OK;
2272 }
2273 
2274 /*
2275 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
2276 ** Write any error messages into *pzErrMsg.  Return the result code.
2277 **
2278 ** After this routine is run, the VDBE should be ready to be executed
2279 ** again.
2280 **
2281 ** To look at it another way, this routine resets the state of the
2282 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
2283 ** VDBE_MAGIC_INIT.
2284 */
sqlite3VdbeReset(Vdbe * p)2285 int sqlite3VdbeReset(Vdbe *p){
2286   sqlite3 *db;
2287   db = p->db;
2288 
2289   /* If the VM did not run to completion or if it encountered an
2290   ** error, then it might not have been halted properly.  So halt
2291   ** it now.
2292   */
2293   sqlite3VdbeHalt(p);
2294 
2295   /* If the VDBE has be run even partially, then transfer the error code
2296   ** and error message from the VDBE into the main database structure.  But
2297   ** if the VDBE has just been set to run but has not actually executed any
2298   ** instructions yet, leave the main database error information unchanged.
2299   */
2300   if( p->pc>=0 ){
2301     if( p->zErrMsg ){
2302       sqlite3BeginBenignMalloc();
2303       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
2304       sqlite3EndBenignMalloc();
2305       db->errCode = p->rc;
2306       sqlite3DbFree(db, p->zErrMsg);
2307       p->zErrMsg = 0;
2308     }else if( p->rc ){
2309       sqlite3Error(db, p->rc, 0);
2310     }else{
2311       sqlite3Error(db, SQLITE_OK, 0);
2312     }
2313     if( p->runOnlyOnce ) p->expired = 1;
2314   }else if( p->rc && p->expired ){
2315     /* The expired flag was set on the VDBE before the first call
2316     ** to sqlite3_step(). For consistency (since sqlite3_step() was
2317     ** called), set the database error in this case as well.
2318     */
2319     sqlite3Error(db, p->rc, 0);
2320     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
2321     sqlite3DbFree(db, p->zErrMsg);
2322     p->zErrMsg = 0;
2323   }
2324 
2325   /* Reclaim all memory used by the VDBE
2326   */
2327   Cleanup(p);
2328 
2329   /* Save profiling information from this VDBE run.
2330   */
2331 #ifdef VDBE_PROFILE
2332   {
2333     FILE *out = fopen("vdbe_profile.out", "a");
2334     if( out ){
2335       int i;
2336       fprintf(out, "---- ");
2337       for(i=0; i<p->nOp; i++){
2338         fprintf(out, "%02x", p->aOp[i].opcode);
2339       }
2340       fprintf(out, "\n");
2341       for(i=0; i<p->nOp; i++){
2342         fprintf(out, "%6d %10lld %8lld ",
2343            p->aOp[i].cnt,
2344            p->aOp[i].cycles,
2345            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
2346         );
2347         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
2348       }
2349       fclose(out);
2350     }
2351   }
2352 #endif
2353   p->magic = VDBE_MAGIC_INIT;
2354   return p->rc & db->errMask;
2355 }
2356 
2357 /*
2358 ** Clean up and delete a VDBE after execution.  Return an integer which is
2359 ** the result code.  Write any error message text into *pzErrMsg.
2360 */
sqlite3VdbeFinalize(Vdbe * p)2361 int sqlite3VdbeFinalize(Vdbe *p){
2362   int rc = SQLITE_OK;
2363   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
2364     rc = sqlite3VdbeReset(p);
2365     assert( (rc & p->db->errMask)==rc );
2366   }
2367   sqlite3VdbeDelete(p);
2368   return rc;
2369 }
2370 
2371 /*
2372 ** Call the destructor for each auxdata entry in pVdbeFunc for which
2373 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
2374 ** are always destroyed.  To destroy all auxdata entries, call this
2375 ** routine with mask==0.
2376 */
sqlite3VdbeDeleteAuxData(VdbeFunc * pVdbeFunc,int mask)2377 void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
2378   int i;
2379   for(i=0; i<pVdbeFunc->nAux; i++){
2380     struct AuxData *pAux = &pVdbeFunc->apAux[i];
2381     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
2382       if( pAux->xDelete ){
2383         pAux->xDelete(pAux->pAux);
2384       }
2385       pAux->pAux = 0;
2386     }
2387   }
2388 }
2389 
2390 /*
2391 ** Free all memory associated with the Vdbe passed as the second argument.
2392 ** The difference between this function and sqlite3VdbeDelete() is that
2393 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
2394 ** the database connection.
2395 */
sqlite3VdbeDeleteObject(sqlite3 * db,Vdbe * p)2396 void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
2397   SubProgram *pSub, *pNext;
2398   assert( p->db==0 || p->db==db );
2399   releaseMemArray(p->aVar, p->nVar);
2400   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
2401   for(pSub=p->pProgram; pSub; pSub=pNext){
2402     pNext = pSub->pNext;
2403     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
2404     sqlite3DbFree(db, pSub);
2405   }
2406   vdbeFreeOpArray(db, p->aOp, p->nOp);
2407   sqlite3DbFree(db, p->aLabel);
2408   sqlite3DbFree(db, p->aColName);
2409   sqlite3DbFree(db, p->zSql);
2410   sqlite3DbFree(db, p->pFree);
2411   sqlite3DbFree(db, p);
2412 }
2413 
2414 /*
2415 ** Delete an entire VDBE.
2416 */
sqlite3VdbeDelete(Vdbe * p)2417 void sqlite3VdbeDelete(Vdbe *p){
2418   sqlite3 *db;
2419 
2420   if( NEVER(p==0) ) return;
2421   db = p->db;
2422   if( p->pPrev ){
2423     p->pPrev->pNext = p->pNext;
2424   }else{
2425     assert( db->pVdbe==p );
2426     db->pVdbe = p->pNext;
2427   }
2428   if( p->pNext ){
2429     p->pNext->pPrev = p->pPrev;
2430   }
2431   p->magic = VDBE_MAGIC_DEAD;
2432   p->db = 0;
2433   sqlite3VdbeDeleteObject(db, p);
2434 }
2435 
2436 /*
2437 ** Make sure the cursor p is ready to read or write the row to which it
2438 ** was last positioned.  Return an error code if an OOM fault or I/O error
2439 ** prevents us from positioning the cursor to its correct position.
2440 **
2441 ** If a MoveTo operation is pending on the given cursor, then do that
2442 ** MoveTo now.  If no move is pending, check to see if the row has been
2443 ** deleted out from under the cursor and if it has, mark the row as
2444 ** a NULL row.
2445 **
2446 ** If the cursor is already pointing to the correct row and that row has
2447 ** not been deleted out from under the cursor, then this routine is a no-op.
2448 */
sqlite3VdbeCursorMoveto(VdbeCursor * p)2449 int sqlite3VdbeCursorMoveto(VdbeCursor *p){
2450   if( p->deferredMoveto ){
2451     int res, rc;
2452 #ifdef SQLITE_TEST
2453     extern int sqlite3_search_count;
2454 #endif
2455     assert( p->isTable );
2456     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
2457     if( rc ) return rc;
2458     p->lastRowid = p->movetoTarget;
2459     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
2460     p->rowidIsValid = 1;
2461 #ifdef SQLITE_TEST
2462     sqlite3_search_count++;
2463 #endif
2464     p->deferredMoveto = 0;
2465     p->cacheStatus = CACHE_STALE;
2466   }else if( ALWAYS(p->pCursor) ){
2467     int hasMoved;
2468     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
2469     if( rc ) return rc;
2470     if( hasMoved ){
2471       p->cacheStatus = CACHE_STALE;
2472       p->nullRow = 1;
2473     }
2474   }
2475   return SQLITE_OK;
2476 }
2477 
2478 /*
2479 ** The following functions:
2480 **
2481 ** sqlite3VdbeSerialType()
2482 ** sqlite3VdbeSerialTypeLen()
2483 ** sqlite3VdbeSerialLen()
2484 ** sqlite3VdbeSerialPut()
2485 ** sqlite3VdbeSerialGet()
2486 **
2487 ** encapsulate the code that serializes values for storage in SQLite
2488 ** data and index records. Each serialized value consists of a
2489 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
2490 ** integer, stored as a varint.
2491 **
2492 ** In an SQLite index record, the serial type is stored directly before
2493 ** the blob of data that it corresponds to. In a table record, all serial
2494 ** types are stored at the start of the record, and the blobs of data at
2495 ** the end. Hence these functions allow the caller to handle the
2496 ** serial-type and data blob seperately.
2497 **
2498 ** The following table describes the various storage classes for data:
2499 **
2500 **   serial type        bytes of data      type
2501 **   --------------     ---------------    ---------------
2502 **      0                     0            NULL
2503 **      1                     1            signed integer
2504 **      2                     2            signed integer
2505 **      3                     3            signed integer
2506 **      4                     4            signed integer
2507 **      5                     6            signed integer
2508 **      6                     8            signed integer
2509 **      7                     8            IEEE float
2510 **      8                     0            Integer constant 0
2511 **      9                     0            Integer constant 1
2512 **     10,11                               reserved for expansion
2513 **    N>=12 and even       (N-12)/2        BLOB
2514 **    N>=13 and odd        (N-13)/2        text
2515 **
2516 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
2517 ** of SQLite will not understand those serial types.
2518 */
2519 
2520 /*
2521 ** Return the serial-type for the value stored in pMem.
2522 */
sqlite3VdbeSerialType(Mem * pMem,int file_format)2523 u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
2524   int flags = pMem->flags;
2525   int n;
2526 
2527   if( flags&MEM_Null ){
2528     return 0;
2529   }
2530   if( flags&MEM_Int ){
2531     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
2532 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
2533     i64 i = pMem->u.i;
2534     u64 u;
2535     if( file_format>=4 && (i&1)==i ){
2536       return 8+(u32)i;
2537     }
2538     if( i<0 ){
2539       if( i<(-MAX_6BYTE) ) return 6;
2540       /* Previous test prevents:  u = -(-9223372036854775808) */
2541       u = -i;
2542     }else{
2543       u = i;
2544     }
2545     if( u<=127 ) return 1;
2546     if( u<=32767 ) return 2;
2547     if( u<=8388607 ) return 3;
2548     if( u<=2147483647 ) return 4;
2549     if( u<=MAX_6BYTE ) return 5;
2550     return 6;
2551   }
2552   if( flags&MEM_Real ){
2553     return 7;
2554   }
2555   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
2556   n = pMem->n;
2557   if( flags & MEM_Zero ){
2558     n += pMem->u.nZero;
2559   }
2560   assert( n>=0 );
2561   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
2562 }
2563 
2564 /*
2565 ** Return the length of the data corresponding to the supplied serial-type.
2566 */
sqlite3VdbeSerialTypeLen(u32 serial_type)2567 u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
2568   if( serial_type>=12 ){
2569     return (serial_type-12)/2;
2570   }else{
2571     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
2572     return aSize[serial_type];
2573   }
2574 }
2575 
2576 /*
2577 ** If we are on an architecture with mixed-endian floating
2578 ** points (ex: ARM7) then swap the lower 4 bytes with the
2579 ** upper 4 bytes.  Return the result.
2580 **
2581 ** For most architectures, this is a no-op.
2582 **
2583 ** (later):  It is reported to me that the mixed-endian problem
2584 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
2585 ** that early versions of GCC stored the two words of a 64-bit
2586 ** float in the wrong order.  And that error has been propagated
2587 ** ever since.  The blame is not necessarily with GCC, though.
2588 ** GCC might have just copying the problem from a prior compiler.
2589 ** I am also told that newer versions of GCC that follow a different
2590 ** ABI get the byte order right.
2591 **
2592 ** Developers using SQLite on an ARM7 should compile and run their
2593 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
2594 ** enabled, some asserts below will ensure that the byte order of
2595 ** floating point values is correct.
2596 **
2597 ** (2007-08-30)  Frank van Vugt has studied this problem closely
2598 ** and has send his findings to the SQLite developers.  Frank
2599 ** writes that some Linux kernels offer floating point hardware
2600 ** emulation that uses only 32-bit mantissas instead of a full
2601 ** 48-bits as required by the IEEE standard.  (This is the
2602 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
2603 ** byte swapping becomes very complicated.  To avoid problems,
2604 ** the necessary byte swapping is carried out using a 64-bit integer
2605 ** rather than a 64-bit float.  Frank assures us that the code here
2606 ** works for him.  We, the developers, have no way to independently
2607 ** verify this, but Frank seems to know what he is talking about
2608 ** so we trust him.
2609 */
2610 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
floatSwap(u64 in)2611 static u64 floatSwap(u64 in){
2612   union {
2613     u64 r;
2614     u32 i[2];
2615   } u;
2616   u32 t;
2617 
2618   u.r = in;
2619   t = u.i[0];
2620   u.i[0] = u.i[1];
2621   u.i[1] = t;
2622   return u.r;
2623 }
2624 # define swapMixedEndianFloat(X)  X = floatSwap(X)
2625 #else
2626 # define swapMixedEndianFloat(X)
2627 #endif
2628 
2629 /*
2630 ** Write the serialized data blob for the value stored in pMem into
2631 ** buf. It is assumed that the caller has allocated sufficient space.
2632 ** Return the number of bytes written.
2633 **
2634 ** nBuf is the amount of space left in buf[].  nBuf must always be
2635 ** large enough to hold the entire field.  Except, if the field is
2636 ** a blob with a zero-filled tail, then buf[] might be just the right
2637 ** size to hold everything except for the zero-filled tail.  If buf[]
2638 ** is only big enough to hold the non-zero prefix, then only write that
2639 ** prefix into buf[].  But if buf[] is large enough to hold both the
2640 ** prefix and the tail then write the prefix and set the tail to all
2641 ** zeros.
2642 **
2643 ** Return the number of bytes actually written into buf[].  The number
2644 ** of bytes in the zero-filled tail is included in the return value only
2645 ** if those bytes were zeroed in buf[].
2646 */
sqlite3VdbeSerialPut(u8 * buf,int nBuf,Mem * pMem,int file_format)2647 u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
2648   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
2649   u32 len;
2650 
2651   /* Integer and Real */
2652   if( serial_type<=7 && serial_type>0 ){
2653     u64 v;
2654     u32 i;
2655     if( serial_type==7 ){
2656       assert( sizeof(v)==sizeof(pMem->r) );
2657       memcpy(&v, &pMem->r, sizeof(v));
2658       swapMixedEndianFloat(v);
2659     }else{
2660       v = pMem->u.i;
2661     }
2662     len = i = sqlite3VdbeSerialTypeLen(serial_type);
2663     assert( len<=(u32)nBuf );
2664     while( i-- ){
2665       buf[i] = (u8)(v&0xFF);
2666       v >>= 8;
2667     }
2668     return len;
2669   }
2670 
2671   /* String or blob */
2672   if( serial_type>=12 ){
2673     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
2674              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
2675     assert( pMem->n<=nBuf );
2676     len = pMem->n;
2677     memcpy(buf, pMem->z, len);
2678     if( pMem->flags & MEM_Zero ){
2679       len += pMem->u.nZero;
2680       assert( nBuf>=0 );
2681       if( len > (u32)nBuf ){
2682         len = (u32)nBuf;
2683       }
2684       memset(&buf[pMem->n], 0, len-pMem->n);
2685     }
2686     return len;
2687   }
2688 
2689   /* NULL or constants 0 or 1 */
2690   return 0;
2691 }
2692 
2693 /*
2694 ** Deserialize the data blob pointed to by buf as serial type serial_type
2695 ** and store the result in pMem.  Return the number of bytes read.
2696 */
sqlite3VdbeSerialGet(const unsigned char * buf,u32 serial_type,Mem * pMem)2697 u32 sqlite3VdbeSerialGet(
2698   const unsigned char *buf,     /* Buffer to deserialize from */
2699   u32 serial_type,              /* Serial type to deserialize */
2700   Mem *pMem                     /* Memory cell to write value into */
2701 ){
2702   switch( serial_type ){
2703     case 10:   /* Reserved for future use */
2704     case 11:   /* Reserved for future use */
2705     case 0: {  /* NULL */
2706       pMem->flags = MEM_Null;
2707       break;
2708     }
2709     case 1: { /* 1-byte signed integer */
2710       pMem->u.i = (signed char)buf[0];
2711       pMem->flags = MEM_Int;
2712       return 1;
2713     }
2714     case 2: { /* 2-byte signed integer */
2715       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
2716       pMem->flags = MEM_Int;
2717       return 2;
2718     }
2719     case 3: { /* 3-byte signed integer */
2720       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
2721       pMem->flags = MEM_Int;
2722       return 3;
2723     }
2724     case 4: { /* 4-byte signed integer */
2725       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
2726       pMem->flags = MEM_Int;
2727       return 4;
2728     }
2729     case 5: { /* 6-byte signed integer */
2730       u64 x = (((signed char)buf[0])<<8) | buf[1];
2731       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
2732       x = (x<<32) | y;
2733       pMem->u.i = *(i64*)&x;
2734       pMem->flags = MEM_Int;
2735       return 6;
2736     }
2737     case 6:   /* 8-byte signed integer */
2738     case 7: { /* IEEE floating point */
2739       u64 x;
2740       u32 y;
2741 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
2742       /* Verify that integers and floating point values use the same
2743       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
2744       ** defined that 64-bit floating point values really are mixed
2745       ** endian.
2746       */
2747       static const u64 t1 = ((u64)0x3ff00000)<<32;
2748       static const double r1 = 1.0;
2749       u64 t2 = t1;
2750       swapMixedEndianFloat(t2);
2751       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
2752 #endif
2753 
2754       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
2755       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
2756       x = (x<<32) | y;
2757       if( serial_type==6 ){
2758         pMem->u.i = *(i64*)&x;
2759         pMem->flags = MEM_Int;
2760       }else{
2761         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
2762         swapMixedEndianFloat(x);
2763         memcpy(&pMem->r, &x, sizeof(x));
2764         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
2765       }
2766       return 8;
2767     }
2768     case 8:    /* Integer 0 */
2769     case 9: {  /* Integer 1 */
2770       pMem->u.i = serial_type-8;
2771       pMem->flags = MEM_Int;
2772       return 0;
2773     }
2774     default: {
2775       u32 len = (serial_type-12)/2;
2776       pMem->z = (char *)buf;
2777       pMem->n = len;
2778       pMem->xDel = 0;
2779       if( serial_type&0x01 ){
2780         pMem->flags = MEM_Str | MEM_Ephem;
2781       }else{
2782         pMem->flags = MEM_Blob | MEM_Ephem;
2783       }
2784       return len;
2785     }
2786   }
2787   return 0;
2788 }
2789 
2790 
2791 /*
2792 ** Given the nKey-byte encoding of a record in pKey[], parse the
2793 ** record into a UnpackedRecord structure.  Return a pointer to
2794 ** that structure.
2795 **
2796 ** The calling function might provide szSpace bytes of memory
2797 ** space at pSpace.  This space can be used to hold the returned
2798 ** VDbeParsedRecord structure if it is large enough.  If it is
2799 ** not big enough, space is obtained from sqlite3_malloc().
2800 **
2801 ** The returned structure should be closed by a call to
2802 ** sqlite3VdbeDeleteUnpackedRecord().
2803 */
sqlite3VdbeRecordUnpack(KeyInfo * pKeyInfo,int nKey,const void * pKey,char * pSpace,int szSpace)2804 UnpackedRecord *sqlite3VdbeRecordUnpack(
2805   KeyInfo *pKeyInfo,     /* Information about the record format */
2806   int nKey,              /* Size of the binary record */
2807   const void *pKey,      /* The binary record */
2808   char *pSpace,          /* Unaligned space available to hold the object */
2809   int szSpace            /* Size of pSpace[] in bytes */
2810 ){
2811   const unsigned char *aKey = (const unsigned char *)pKey;
2812   UnpackedRecord *p;  /* The unpacked record that we will return */
2813   int nByte;          /* Memory space needed to hold p, in bytes */
2814   int d;
2815   u32 idx;
2816   u16 u;              /* Unsigned loop counter */
2817   u32 szHdr;
2818   Mem *pMem;
2819   int nOff;           /* Increase pSpace by this much to 8-byte align it */
2820 
2821   /*
2822   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
2823   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
2824   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
2825   */
2826   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
2827   pSpace += nOff;
2828   szSpace -= nOff;
2829   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
2830   if( nByte>szSpace ){
2831     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
2832     if( p==0 ) return 0;
2833     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
2834   }else{
2835     p = (UnpackedRecord*)pSpace;
2836     p->flags = UNPACKED_NEED_DESTROY;
2837   }
2838   p->pKeyInfo = pKeyInfo;
2839   p->nField = pKeyInfo->nField + 1;
2840   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
2841   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
2842   idx = getVarint32(aKey, szHdr);
2843   d = szHdr;
2844   u = 0;
2845   while( idx<szHdr && u<p->nField && d<=nKey ){
2846     u32 serial_type;
2847 
2848     idx += getVarint32(&aKey[idx], serial_type);
2849     pMem->enc = pKeyInfo->enc;
2850     pMem->db = pKeyInfo->db;
2851     pMem->flags = 0;
2852     pMem->zMalloc = 0;
2853     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
2854     pMem++;
2855     u++;
2856   }
2857   assert( u<=pKeyInfo->nField + 1 );
2858   p->nField = u;
2859   return (void*)p;
2860 }
2861 
2862 /*
2863 ** This routine destroys a UnpackedRecord object.
2864 */
sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord * p)2865 void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
2866   int i;
2867   Mem *pMem;
2868 
2869   assert( p!=0 );
2870   assert( p->flags & UNPACKED_NEED_DESTROY );
2871   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
2872     /* The unpacked record is always constructed by the
2873     ** sqlite3VdbeUnpackRecord() function above, which makes all
2874     ** strings and blobs static.  And none of the elements are
2875     ** ever transformed, so there is never anything to delete.
2876     */
2877     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
2878   }
2879   if( p->flags & UNPACKED_NEED_FREE ){
2880     sqlite3DbFree(p->pKeyInfo->db, p);
2881   }
2882 }
2883 
2884 /*
2885 ** This function compares the two table rows or index records
2886 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
2887 ** or positive integer if key1 is less than, equal to or
2888 ** greater than key2.  The {nKey1, pKey1} key must be a blob
2889 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
2890 ** key must be a parsed key such as obtained from
2891 ** sqlite3VdbeParseRecord.
2892 **
2893 ** Key1 and Key2 do not have to contain the same number of fields.
2894 ** The key with fewer fields is usually compares less than the
2895 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
2896 ** and the common prefixes are equal, then key1 is less than key2.
2897 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
2898 ** equal, then the keys are considered to be equal and
2899 ** the parts beyond the common prefix are ignored.
2900 **
2901 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
2902 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
2903 ** an index key, and thus ends with a rowid value.  The last byte
2904 ** of the header will therefore be the serial type of the rowid:
2905 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
2906 ** The serial type of the final rowid will always be a single byte.
2907 ** By ignoring this last byte of the header, we force the comparison
2908 ** to ignore the rowid at the end of key1.
2909 */
sqlite3VdbeRecordCompare(int nKey1,const void * pKey1,UnpackedRecord * pPKey2)2910 int sqlite3VdbeRecordCompare(
2911   int nKey1, const void *pKey1, /* Left key */
2912   UnpackedRecord *pPKey2        /* Right key */
2913 ){
2914   int d1;            /* Offset into aKey[] of next data element */
2915   u32 idx1;          /* Offset into aKey[] of next header element */
2916   u32 szHdr1;        /* Number of bytes in header */
2917   int i = 0;
2918   int nField;
2919   int rc = 0;
2920   const unsigned char *aKey1 = (const unsigned char *)pKey1;
2921   KeyInfo *pKeyInfo;
2922   Mem mem1;
2923 
2924   pKeyInfo = pPKey2->pKeyInfo;
2925   mem1.enc = pKeyInfo->enc;
2926   mem1.db = pKeyInfo->db;
2927   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
2928   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
2929 
2930   /* Compilers may complain that mem1.u.i is potentially uninitialized.
2931   ** We could initialize it, as shown here, to silence those complaints.
2932   ** But in fact, mem1.u.i will never actually be used initialized, and doing
2933   ** the unnecessary initialization has a measurable negative performance
2934   ** impact, since this routine is a very high runner.  And so, we choose
2935   ** to ignore the compiler warnings and leave this variable uninitialized.
2936   */
2937   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
2938 
2939   idx1 = getVarint32(aKey1, szHdr1);
2940   d1 = szHdr1;
2941   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
2942     szHdr1--;
2943   }
2944   nField = pKeyInfo->nField;
2945   while( idx1<szHdr1 && i<pPKey2->nField ){
2946     u32 serial_type1;
2947 
2948     /* Read the serial types for the next element in each key. */
2949     idx1 += getVarint32( aKey1+idx1, serial_type1 );
2950     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
2951 
2952     /* Extract the values to be compared.
2953     */
2954     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
2955 
2956     /* Do the comparison
2957     */
2958     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
2959                            i<nField ? pKeyInfo->aColl[i] : 0);
2960     if( rc!=0 ){
2961       assert( mem1.zMalloc==0 );  /* See comment below */
2962 
2963       /* Invert the result if we are using DESC sort order. */
2964       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
2965         rc = -rc;
2966       }
2967 
2968       /* If the PREFIX_SEARCH flag is set and all fields except the final
2969       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
2970       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
2971       ** This is used by the OP_IsUnique opcode.
2972       */
2973       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
2974         assert( idx1==szHdr1 && rc );
2975         assert( mem1.flags & MEM_Int );
2976         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
2977         pPKey2->rowid = mem1.u.i;
2978       }
2979 
2980       return rc;
2981     }
2982     i++;
2983   }
2984 
2985   /* No memory allocation is ever used on mem1.  Prove this using
2986   ** the following assert().  If the assert() fails, it indicates a
2987   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
2988   */
2989   assert( mem1.zMalloc==0 );
2990 
2991   /* rc==0 here means that one of the keys ran out of fields and
2992   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
2993   ** flag is set, then break the tie by treating key2 as larger.
2994   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
2995   ** are considered to be equal.  Otherwise, the longer key is the
2996   ** larger.  As it happens, the pPKey2 will always be the longer
2997   ** if there is a difference.
2998   */
2999   assert( rc==0 );
3000   if( pPKey2->flags & UNPACKED_INCRKEY ){
3001     rc = -1;
3002   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
3003     /* Leave rc==0 */
3004   }else if( idx1<szHdr1 ){
3005     rc = 1;
3006   }
3007   return rc;
3008 }
3009 
3010 
3011 /*
3012 ** pCur points at an index entry created using the OP_MakeRecord opcode.
3013 ** Read the rowid (the last field in the record) and store it in *rowid.
3014 ** Return SQLITE_OK if everything works, or an error code otherwise.
3015 **
3016 ** pCur might be pointing to text obtained from a corrupt database file.
3017 ** So the content cannot be trusted.  Do appropriate checks on the content.
3018 */
sqlite3VdbeIdxRowid(sqlite3 * db,BtCursor * pCur,i64 * rowid)3019 int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
3020   i64 nCellKey = 0;
3021   int rc;
3022   u32 szHdr;        /* Size of the header */
3023   u32 typeRowid;    /* Serial type of the rowid */
3024   u32 lenRowid;     /* Size of the rowid */
3025   Mem m, v;
3026 
3027   UNUSED_PARAMETER(db);
3028 
3029   /* Get the size of the index entry.  Only indices entries of less
3030   ** than 2GiB are support - anything large must be database corruption.
3031   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
3032   ** this code can safely assume that nCellKey is 32-bits
3033   */
3034   assert( sqlite3BtreeCursorIsValid(pCur) );
3035   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
3036   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
3037   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
3038 
3039   /* Read in the complete content of the index entry */
3040   memset(&m, 0, sizeof(m));
3041   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
3042   if( rc ){
3043     return rc;
3044   }
3045 
3046   /* The index entry must begin with a header size */
3047   (void)getVarint32((u8*)m.z, szHdr);
3048   testcase( szHdr==3 );
3049   testcase( szHdr==m.n );
3050   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
3051     goto idx_rowid_corruption;
3052   }
3053 
3054   /* The last field of the index should be an integer - the ROWID.
3055   ** Verify that the last entry really is an integer. */
3056   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
3057   testcase( typeRowid==1 );
3058   testcase( typeRowid==2 );
3059   testcase( typeRowid==3 );
3060   testcase( typeRowid==4 );
3061   testcase( typeRowid==5 );
3062   testcase( typeRowid==6 );
3063   testcase( typeRowid==8 );
3064   testcase( typeRowid==9 );
3065   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
3066     goto idx_rowid_corruption;
3067   }
3068   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
3069   testcase( (u32)m.n==szHdr+lenRowid );
3070   if( unlikely((u32)m.n<szHdr+lenRowid) ){
3071     goto idx_rowid_corruption;
3072   }
3073 
3074   /* Fetch the integer off the end of the index record */
3075   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
3076   *rowid = v.u.i;
3077   sqlite3VdbeMemRelease(&m);
3078   return SQLITE_OK;
3079 
3080   /* Jump here if database corruption is detected after m has been
3081   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
3082 idx_rowid_corruption:
3083   testcase( m.zMalloc!=0 );
3084   sqlite3VdbeMemRelease(&m);
3085   return SQLITE_CORRUPT_BKPT;
3086 }
3087 
3088 /*
3089 ** Compare the key of the index entry that cursor pC is pointing to against
3090 ** the key string in pUnpacked.  Write into *pRes a number
3091 ** that is negative, zero, or positive if pC is less than, equal to,
3092 ** or greater than pUnpacked.  Return SQLITE_OK on success.
3093 **
3094 ** pUnpacked is either created without a rowid or is truncated so that it
3095 ** omits the rowid at the end.  The rowid at the end of the index entry
3096 ** is ignored as well.  Hence, this routine only compares the prefixes
3097 ** of the keys prior to the final rowid, not the entire key.
3098 */
sqlite3VdbeIdxKeyCompare(VdbeCursor * pC,UnpackedRecord * pUnpacked,int * res)3099 int sqlite3VdbeIdxKeyCompare(
3100   VdbeCursor *pC,             /* The cursor to compare against */
3101   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
3102   int *res                    /* Write the comparison result here */
3103 ){
3104   i64 nCellKey = 0;
3105   int rc;
3106   BtCursor *pCur = pC->pCursor;
3107   Mem m;
3108 
3109   assert( sqlite3BtreeCursorIsValid(pCur) );
3110   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
3111   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
3112   /* nCellKey will always be between 0 and 0xffffffff because of the say
3113   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
3114   if( nCellKey<=0 || nCellKey>0x7fffffff ){
3115     *res = 0;
3116     return SQLITE_CORRUPT_BKPT;
3117   }
3118   memset(&m, 0, sizeof(m));
3119   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
3120   if( rc ){
3121     return rc;
3122   }
3123   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
3124   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
3125   sqlite3VdbeMemRelease(&m);
3126   return SQLITE_OK;
3127 }
3128 
3129 /*
3130 ** This routine sets the value to be returned by subsequent calls to
3131 ** sqlite3_changes() on the database handle 'db'.
3132 */
sqlite3VdbeSetChanges(sqlite3 * db,int nChange)3133 void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
3134   assert( sqlite3_mutex_held(db->mutex) );
3135   db->nChange = nChange;
3136   db->nTotalChange += nChange;
3137 }
3138 
3139 /*
3140 ** Set a flag in the vdbe to update the change counter when it is finalised
3141 ** or reset.
3142 */
sqlite3VdbeCountChanges(Vdbe * v)3143 void sqlite3VdbeCountChanges(Vdbe *v){
3144   v->changeCntOn = 1;
3145 }
3146 
3147 /*
3148 ** Mark every prepared statement associated with a database connection
3149 ** as expired.
3150 **
3151 ** An expired statement means that recompilation of the statement is
3152 ** recommend.  Statements expire when things happen that make their
3153 ** programs obsolete.  Removing user-defined functions or collating
3154 ** sequences, or changing an authorization function are the types of
3155 ** things that make prepared statements obsolete.
3156 */
sqlite3ExpirePreparedStatements(sqlite3 * db)3157 void sqlite3ExpirePreparedStatements(sqlite3 *db){
3158   Vdbe *p;
3159   for(p = db->pVdbe; p; p=p->pNext){
3160     p->expired = 1;
3161   }
3162 }
3163 
3164 /*
3165 ** Return the database associated with the Vdbe.
3166 */
sqlite3VdbeDb(Vdbe * v)3167 sqlite3 *sqlite3VdbeDb(Vdbe *v){
3168   return v->db;
3169 }
3170 
3171 /*
3172 ** Return a pointer to an sqlite3_value structure containing the value bound
3173 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
3174 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
3175 ** constants) to the value before returning it.
3176 **
3177 ** The returned value must be freed by the caller using sqlite3ValueFree().
3178 */
sqlite3VdbeGetValue(Vdbe * v,int iVar,u8 aff)3179 sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
3180   assert( iVar>0 );
3181   if( v ){
3182     Mem *pMem = &v->aVar[iVar-1];
3183     if( 0==(pMem->flags & MEM_Null) ){
3184       sqlite3_value *pRet = sqlite3ValueNew(v->db);
3185       if( pRet ){
3186         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
3187         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
3188         sqlite3VdbeMemStoreType((Mem *)pRet);
3189       }
3190       return pRet;
3191     }
3192   }
3193   return 0;
3194 }
3195 
3196 /*
3197 ** Configure SQL variable iVar so that binding a new value to it signals
3198 ** to sqlite3_reoptimize() that re-preparing the statement may result
3199 ** in a better query plan.
3200 */
sqlite3VdbeSetVarmask(Vdbe * v,int iVar)3201 void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
3202   assert( iVar>0 );
3203   if( iVar>32 ){
3204     v->expmask = 0xffffffff;
3205   }else{
3206     v->expmask |= ((u32)1 << (iVar-1));
3207   }
3208 }
3209