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.)
14 */
15 #include "sqliteInt.h"
16 #include "vdbeInt.h"
17 
18 /*
19 ** Create a new virtual database engine.
20 */
sqlite3VdbeCreate(Parse * pParse)21 Vdbe *sqlite3VdbeCreate(Parse *pParse){
22   sqlite3 *db = pParse->db;
23   Vdbe *p;
24   p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
25   if( p==0 ) return 0;
26   memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
27   p->db = db;
28   if( db->pVdbe ){
29     db->pVdbe->pPrev = p;
30   }
31   p->pNext = db->pVdbe;
32   p->pPrev = 0;
33   db->pVdbe = p;
34   p->magic = VDBE_MAGIC_INIT;
35   p->pParse = pParse;
36   assert( pParse->aLabel==0 );
37   assert( pParse->nLabel==0 );
38   assert( pParse->nOpAlloc==0 );
39   assert( pParse->szOpAlloc==0 );
40   return p;
41 }
42 
43 /*
44 ** Change the error string stored in Vdbe.zErrMsg
45 */
sqlite3VdbeError(Vdbe * p,const char * zFormat,...)46 void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
47   va_list ap;
48   sqlite3DbFree(p->db, p->zErrMsg);
49   va_start(ap, zFormat);
50   p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
51   va_end(ap);
52 }
53 
54 /*
55 ** Remember the SQL string for a prepared statement.
56 */
sqlite3VdbeSetSql(Vdbe * p,const char * z,int n,u8 prepFlags)57 void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
58   if( p==0 ) return;
59   p->prepFlags = prepFlags;
60   if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
61     p->expmask = 0;
62   }
63   assert( p->zSql==0 );
64   p->zSql = sqlite3DbStrNDup(p->db, z, n);
65 }
66 
67 /*
68 ** Swap all content between two VDBE structures.
69 */
sqlite3VdbeSwap(Vdbe * pA,Vdbe * pB)70 void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
71   Vdbe tmp, *pTmp;
72   char *zTmp;
73   assert( pA->db==pB->db );
74   tmp = *pA;
75   *pA = *pB;
76   *pB = tmp;
77   pTmp = pA->pNext;
78   pA->pNext = pB->pNext;
79   pB->pNext = pTmp;
80   pTmp = pA->pPrev;
81   pA->pPrev = pB->pPrev;
82   pB->pPrev = pTmp;
83   zTmp = pA->zSql;
84   pA->zSql = pB->zSql;
85   pB->zSql = zTmp;
86   pB->expmask = pA->expmask;
87   pB->prepFlags = pA->prepFlags;
88   memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
89   pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
90 }
91 
92 /*
93 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
94 ** than its current size. nOp is guaranteed to be less than or equal
95 ** to 1024/sizeof(Op).
96 **
97 ** If an out-of-memory error occurs while resizing the array, return
98 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
99 ** unchanged (this is so that any opcodes already allocated can be
100 ** correctly deallocated along with the rest of the Vdbe).
101 */
growOpArray(Vdbe * v,int nOp)102 static int growOpArray(Vdbe *v, int nOp){
103   VdbeOp *pNew;
104   Parse *p = v->pParse;
105 
106   /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
107   ** more frequent reallocs and hence provide more opportunities for
108   ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
109   ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
110   ** by the minimum* amount required until the size reaches 512.  Normal
111   ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
112   ** size of the op array or add 1KB of space, whichever is smaller. */
113 #ifdef SQLITE_TEST_REALLOC_STRESS
114   int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
115 #else
116   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
117   UNUSED_PARAMETER(nOp);
118 #endif
119 
120   /* Ensure that the size of a VDBE does not grow too large */
121   if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
122     sqlite3OomFault(p->db);
123     return SQLITE_NOMEM;
124   }
125 
126   assert( nOp<=(1024/sizeof(Op)) );
127   assert( nNew>=(p->nOpAlloc+nOp) );
128   pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
129   if( pNew ){
130     p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
131     p->nOpAlloc = p->szOpAlloc/sizeof(Op);
132     v->aOp = pNew;
133   }
134   return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
135 }
136 
137 #ifdef SQLITE_DEBUG
138 /* This routine is just a convenient place to set a breakpoint that will
139 ** fire after each opcode is inserted and displayed using
140 ** "PRAGMA vdbe_addoptrace=on".
141 */
test_addop_breakpoint(void)142 static void test_addop_breakpoint(void){
143   static int n = 0;
144   n++;
145 }
146 #endif
147 
148 /*
149 ** Add a new instruction to the list of instructions current in the
150 ** VDBE.  Return the address of the new instruction.
151 **
152 ** Parameters:
153 **
154 **    p               Pointer to the VDBE
155 **
156 **    op              The opcode for this instruction
157 **
158 **    p1, p2, p3      Operands
159 **
160 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
161 ** the sqlite3VdbeChangeP4() function to change the value of the P4
162 ** operand.
163 */
growOp3(Vdbe * p,int op,int p1,int p2,int p3)164 static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
165   assert( p->pParse->nOpAlloc<=p->nOp );
166   if( growOpArray(p, 1) ) return 1;
167   assert( p->pParse->nOpAlloc>p->nOp );
168   return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
169 }
sqlite3VdbeAddOp3(Vdbe * p,int op,int p1,int p2,int p3)170 int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
171   int i;
172   VdbeOp *pOp;
173 
174   i = p->nOp;
175   assert( p->magic==VDBE_MAGIC_INIT );
176   assert( op>=0 && op<0xff );
177   if( p->pParse->nOpAlloc<=i ){
178     return growOp3(p, op, p1, p2, p3);
179   }
180   p->nOp++;
181   pOp = &p->aOp[i];
182   pOp->opcode = (u8)op;
183   pOp->p5 = 0;
184   pOp->p1 = p1;
185   pOp->p2 = p2;
186   pOp->p3 = p3;
187   pOp->p4.p = 0;
188   pOp->p4type = P4_NOTUSED;
189 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
190   pOp->zComment = 0;
191 #endif
192 #ifdef SQLITE_DEBUG
193   if( p->db->flags & SQLITE_VdbeAddopTrace ){
194     int jj, kk;
195     Parse *pParse = p->pParse;
196     for(jj=kk=0; jj<pParse->nColCache; jj++){
197       struct yColCache *x = pParse->aColCache + jj;
198       printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
199       kk++;
200     }
201     if( kk ) printf("\n");
202     sqlite3VdbePrintOp(0, i, &p->aOp[i]);
203     test_addop_breakpoint();
204   }
205 #endif
206 #ifdef VDBE_PROFILE
207   pOp->cycles = 0;
208   pOp->cnt = 0;
209 #endif
210 #ifdef SQLITE_VDBE_COVERAGE
211   pOp->iSrcLine = 0;
212 #endif
213   return i;
214 }
sqlite3VdbeAddOp0(Vdbe * p,int op)215 int sqlite3VdbeAddOp0(Vdbe *p, int op){
216   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
217 }
sqlite3VdbeAddOp1(Vdbe * p,int op,int p1)218 int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
219   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
220 }
sqlite3VdbeAddOp2(Vdbe * p,int op,int p1,int p2)221 int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
222   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
223 }
224 
225 /* Generate code for an unconditional jump to instruction iDest
226 */
sqlite3VdbeGoto(Vdbe * p,int iDest)227 int sqlite3VdbeGoto(Vdbe *p, int iDest){
228   return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
229 }
230 
231 /* Generate code to cause the string zStr to be loaded into
232 ** register iDest
233 */
sqlite3VdbeLoadString(Vdbe * p,int iDest,const char * zStr)234 int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
235   return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
236 }
237 
238 /*
239 ** Generate code that initializes multiple registers to string or integer
240 ** constants.  The registers begin with iDest and increase consecutively.
241 ** One register is initialized for each characgter in zTypes[].  For each
242 ** "s" character in zTypes[], the register is a string if the argument is
243 ** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
244 ** in zTypes[], the register is initialized to an integer.
245 **
246 ** If the input string does not end with "X" then an OP_ResultRow instruction
247 ** is generated for the values inserted.
248 */
sqlite3VdbeMultiLoad(Vdbe * p,int iDest,const char * zTypes,...)249 void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
250   va_list ap;
251   int i;
252   char c;
253   va_start(ap, zTypes);
254   for(i=0; (c = zTypes[i])!=0; i++){
255     if( c=='s' ){
256       const char *z = va_arg(ap, const char*);
257       sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
258     }else if( c=='i' ){
259       sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
260     }else{
261       goto skip_op_resultrow;
262     }
263   }
264   sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
265 skip_op_resultrow:
266   va_end(ap);
267 }
268 
269 /*
270 ** Add an opcode that includes the p4 value as a pointer.
271 */
sqlite3VdbeAddOp4(Vdbe * p,int op,int p1,int p2,int p3,const char * zP4,int p4type)272 int sqlite3VdbeAddOp4(
273   Vdbe *p,            /* Add the opcode to this VM */
274   int op,             /* The new opcode */
275   int p1,             /* The P1 operand */
276   int p2,             /* The P2 operand */
277   int p3,             /* The P3 operand */
278   const char *zP4,    /* The P4 operand */
279   int p4type          /* P4 operand type */
280 ){
281   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
282   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
283   return addr;
284 }
285 
286 /*
287 ** Add an opcode that includes the p4 value with a P4_INT64 or
288 ** P4_REAL type.
289 */
sqlite3VdbeAddOp4Dup8(Vdbe * p,int op,int p1,int p2,int p3,const u8 * zP4,int p4type)290 int sqlite3VdbeAddOp4Dup8(
291   Vdbe *p,            /* Add the opcode to this VM */
292   int op,             /* The new opcode */
293   int p1,             /* The P1 operand */
294   int p2,             /* The P2 operand */
295   int p3,             /* The P3 operand */
296   const u8 *zP4,      /* The P4 operand */
297   int p4type          /* P4 operand type */
298 ){
299   char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
300   if( p4copy ) memcpy(p4copy, zP4, 8);
301   return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
302 }
303 
304 /*
305 ** Add an OP_ParseSchema opcode.  This routine is broken out from
306 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
307 ** as having been used.
308 **
309 ** The zWhere string must have been obtained from sqlite3_malloc().
310 ** This routine will take ownership of the allocated memory.
311 */
sqlite3VdbeAddParseSchemaOp(Vdbe * p,int iDb,char * zWhere)312 void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
313   int j;
314   sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
315   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
316 }
317 
318 /*
319 ** Add an opcode that includes the p4 value as an integer.
320 */
sqlite3VdbeAddOp4Int(Vdbe * p,int op,int p1,int p2,int p3,int p4)321 int sqlite3VdbeAddOp4Int(
322   Vdbe *p,            /* Add the opcode to this VM */
323   int op,             /* The new opcode */
324   int p1,             /* The P1 operand */
325   int p2,             /* The P2 operand */
326   int p3,             /* The P3 operand */
327   int p4              /* The P4 operand as an integer */
328 ){
329   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
330   if( p->db->mallocFailed==0 ){
331     VdbeOp *pOp = &p->aOp[addr];
332     pOp->p4type = P4_INT32;
333     pOp->p4.i = p4;
334   }
335   return addr;
336 }
337 
338 /* Insert the end of a co-routine
339 */
sqlite3VdbeEndCoroutine(Vdbe * v,int regYield)340 void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
341   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
342 
343   /* Clear the temporary register cache, thereby ensuring that each
344   ** co-routine has its own independent set of registers, because co-routines
345   ** might expect their registers to be preserved across an OP_Yield, and
346   ** that could cause problems if two or more co-routines are using the same
347   ** temporary register.
348   */
349   v->pParse->nTempReg = 0;
350   v->pParse->nRangeReg = 0;
351 }
352 
353 /*
354 ** Create a new symbolic label for an instruction that has yet to be
355 ** coded.  The symbolic label is really just a negative number.  The
356 ** label can be used as the P2 value of an operation.  Later, when
357 ** the label is resolved to a specific address, the VDBE will scan
358 ** through its operation list and change all values of P2 which match
359 ** the label into the resolved address.
360 **
361 ** The VDBE knows that a P2 value is a label because labels are
362 ** always negative and P2 values are suppose to be non-negative.
363 ** Hence, a negative P2 value is a label that has yet to be resolved.
364 **
365 ** Zero is returned if a malloc() fails.
366 */
sqlite3VdbeMakeLabel(Vdbe * v)367 int sqlite3VdbeMakeLabel(Vdbe *v){
368   Parse *p = v->pParse;
369   int i = p->nLabel++;
370   assert( v->magic==VDBE_MAGIC_INIT );
371   if( (i & (i-1))==0 ){
372     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
373                                        (i*2+1)*sizeof(p->aLabel[0]));
374   }
375   if( p->aLabel ){
376     p->aLabel[i] = -1;
377   }
378   return ADDR(i);
379 }
380 
381 /*
382 ** Resolve label "x" to be the address of the next instruction to
383 ** be inserted.  The parameter "x" must have been obtained from
384 ** a prior call to sqlite3VdbeMakeLabel().
385 */
sqlite3VdbeResolveLabel(Vdbe * v,int x)386 void sqlite3VdbeResolveLabel(Vdbe *v, int x){
387   Parse *p = v->pParse;
388   int j = ADDR(x);
389   assert( v->magic==VDBE_MAGIC_INIT );
390   assert( j<p->nLabel );
391   assert( j>=0 );
392   if( p->aLabel ){
393     p->aLabel[j] = v->nOp;
394   }
395 }
396 
397 /*
398 ** Mark the VDBE as one that can only be run one time.
399 */
sqlite3VdbeRunOnlyOnce(Vdbe * p)400 void sqlite3VdbeRunOnlyOnce(Vdbe *p){
401   p->runOnlyOnce = 1;
402 }
403 
404 /*
405 ** Mark the VDBE as one that can only be run multiple times.
406 */
sqlite3VdbeReusable(Vdbe * p)407 void sqlite3VdbeReusable(Vdbe *p){
408   p->runOnlyOnce = 0;
409 }
410 
411 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
412 
413 /*
414 ** The following type and function are used to iterate through all opcodes
415 ** in a Vdbe main program and each of the sub-programs (triggers) it may
416 ** invoke directly or indirectly. It should be used as follows:
417 **
418 **   Op *pOp;
419 **   VdbeOpIter sIter;
420 **
421 **   memset(&sIter, 0, sizeof(sIter));
422 **   sIter.v = v;                            // v is of type Vdbe*
423 **   while( (pOp = opIterNext(&sIter)) ){
424 **     // Do something with pOp
425 **   }
426 **   sqlite3DbFree(v->db, sIter.apSub);
427 **
428 */
429 typedef struct VdbeOpIter VdbeOpIter;
430 struct VdbeOpIter {
431   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
432   SubProgram **apSub;        /* Array of subprograms */
433   int nSub;                  /* Number of entries in apSub */
434   int iAddr;                 /* Address of next instruction to return */
435   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
436 };
opIterNext(VdbeOpIter * p)437 static Op *opIterNext(VdbeOpIter *p){
438   Vdbe *v = p->v;
439   Op *pRet = 0;
440   Op *aOp;
441   int nOp;
442 
443   if( p->iSub<=p->nSub ){
444 
445     if( p->iSub==0 ){
446       aOp = v->aOp;
447       nOp = v->nOp;
448     }else{
449       aOp = p->apSub[p->iSub-1]->aOp;
450       nOp = p->apSub[p->iSub-1]->nOp;
451     }
452     assert( p->iAddr<nOp );
453 
454     pRet = &aOp[p->iAddr];
455     p->iAddr++;
456     if( p->iAddr==nOp ){
457       p->iSub++;
458       p->iAddr = 0;
459     }
460 
461     if( pRet->p4type==P4_SUBPROGRAM ){
462       int nByte = (p->nSub+1)*sizeof(SubProgram*);
463       int j;
464       for(j=0; j<p->nSub; j++){
465         if( p->apSub[j]==pRet->p4.pProgram ) break;
466       }
467       if( j==p->nSub ){
468         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
469         if( !p->apSub ){
470           pRet = 0;
471         }else{
472           p->apSub[p->nSub++] = pRet->p4.pProgram;
473         }
474       }
475     }
476   }
477 
478   return pRet;
479 }
480 
481 /*
482 ** Check if the program stored in the VM associated with pParse may
483 ** throw an ABORT exception (causing the statement, but not entire transaction
484 ** to be rolled back). This condition is true if the main program or any
485 ** sub-programs contains any of the following:
486 **
487 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
488 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
489 **   *  OP_Destroy
490 **   *  OP_VUpdate
491 **   *  OP_VRename
492 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
493 **   *  OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
494 **
495 ** Then check that the value of Parse.mayAbort is true if an
496 ** ABORT may be thrown, or false otherwise. Return true if it does
497 ** match, or false otherwise. This function is intended to be used as
498 ** part of an assert statement in the compiler. Similar to:
499 **
500 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
501 */
sqlite3VdbeAssertMayAbort(Vdbe * v,int mayAbort)502 int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
503   int hasAbort = 0;
504   int hasFkCounter = 0;
505   int hasCreateTable = 0;
506   int hasInitCoroutine = 0;
507   Op *pOp;
508   VdbeOpIter sIter;
509   memset(&sIter, 0, sizeof(sIter));
510   sIter.v = v;
511 
512   while( (pOp = opIterNext(&sIter))!=0 ){
513     int opcode = pOp->opcode;
514     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
515      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
516       && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
517     ){
518       hasAbort = 1;
519       break;
520     }
521     if( opcode==OP_CreateTable ) hasCreateTable = 1;
522     if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
523 #ifndef SQLITE_OMIT_FOREIGN_KEY
524     if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
525       hasFkCounter = 1;
526     }
527 #endif
528   }
529   sqlite3DbFree(v->db, sIter.apSub);
530 
531   /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
532   ** If malloc failed, then the while() loop above may not have iterated
533   ** through all opcodes and hasAbort may be set incorrectly. Return
534   ** true for this case to prevent the assert() in the callers frame
535   ** from failing.  */
536   return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
537               || (hasCreateTable && hasInitCoroutine) );
538 }
539 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
540 
541 /*
542 ** This routine is called after all opcodes have been inserted.  It loops
543 ** through all the opcodes and fixes up some details.
544 **
545 ** (1) For each jump instruction with a negative P2 value (a label)
546 **     resolve the P2 value to an actual address.
547 **
548 ** (2) Compute the maximum number of arguments used by any SQL function
549 **     and store that value in *pMaxFuncArgs.
550 **
551 ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
552 **     indicate what the prepared statement actually does.
553 **
554 ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
555 **
556 ** (5) Reclaim the memory allocated for storing labels.
557 **
558 ** This routine will only function correctly if the mkopcodeh.tcl generator
559 ** script numbers the opcodes correctly.  Changes to this routine must be
560 ** coordinated with changes to mkopcodeh.tcl.
561 */
resolveP2Values(Vdbe * p,int * pMaxFuncArgs)562 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
563   int nMaxArgs = *pMaxFuncArgs;
564   Op *pOp;
565   Parse *pParse = p->pParse;
566   int *aLabel = pParse->aLabel;
567   p->readOnly = 1;
568   p->bIsReader = 0;
569   pOp = &p->aOp[p->nOp-1];
570   while(1){
571 
572     /* Only JUMP opcodes and the short list of special opcodes in the switch
573     ** below need to be considered.  The mkopcodeh.tcl generator script groups
574     ** all these opcodes together near the front of the opcode list.  Skip
575     ** any opcode that does not need processing by virtual of the fact that
576     ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
577     */
578     if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
579       /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
580       ** cases from this switch! */
581       switch( pOp->opcode ){
582         case OP_Transaction: {
583           if( pOp->p2!=0 ) p->readOnly = 0;
584           /* fall thru */
585         }
586         case OP_AutoCommit:
587         case OP_Savepoint: {
588           p->bIsReader = 1;
589           break;
590         }
591 #ifndef SQLITE_OMIT_WAL
592         case OP_Checkpoint:
593 #endif
594         case OP_Vacuum:
595         case OP_JournalMode: {
596           p->readOnly = 0;
597           p->bIsReader = 1;
598           break;
599         }
600 #ifndef SQLITE_OMIT_VIRTUALTABLE
601         case OP_VUpdate: {
602           if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
603           break;
604         }
605         case OP_VFilter: {
606           int n;
607           assert( (pOp - p->aOp) >= 3 );
608           assert( pOp[-1].opcode==OP_Integer );
609           n = pOp[-1].p1;
610           if( n>nMaxArgs ) nMaxArgs = n;
611           break;
612         }
613 #endif
614         case OP_Next:
615         case OP_NextIfOpen:
616         case OP_SorterNext: {
617           pOp->p4.xAdvance = sqlite3BtreeNext;
618           pOp->p4type = P4_ADVANCE;
619           break;
620         }
621         case OP_Prev:
622         case OP_PrevIfOpen: {
623           pOp->p4.xAdvance = sqlite3BtreePrevious;
624           pOp->p4type = P4_ADVANCE;
625           break;
626         }
627       }
628       if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){
629         assert( ADDR(pOp->p2)<pParse->nLabel );
630         pOp->p2 = aLabel[ADDR(pOp->p2)];
631       }
632     }
633     if( pOp==p->aOp ) break;
634     pOp--;
635   }
636   sqlite3DbFree(p->db, pParse->aLabel);
637   pParse->aLabel = 0;
638   pParse->nLabel = 0;
639   *pMaxFuncArgs = nMaxArgs;
640   assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
641 }
642 
643 /*
644 ** Return the address of the next instruction to be inserted.
645 */
sqlite3VdbeCurrentAddr(Vdbe * p)646 int sqlite3VdbeCurrentAddr(Vdbe *p){
647   assert( p->magic==VDBE_MAGIC_INIT );
648   return p->nOp;
649 }
650 
651 /*
652 ** Verify that at least N opcode slots are available in p without
653 ** having to malloc for more space (except when compiled using
654 ** SQLITE_TEST_REALLOC_STRESS).  This interface is used during testing
655 ** to verify that certain calls to sqlite3VdbeAddOpList() can never
656 ** fail due to a OOM fault and hence that the return value from
657 ** sqlite3VdbeAddOpList() will always be non-NULL.
658 */
659 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
sqlite3VdbeVerifyNoMallocRequired(Vdbe * p,int N)660 void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
661   assert( p->nOp + N <= p->pParse->nOpAlloc );
662 }
663 #endif
664 
665 /*
666 ** Verify that the VM passed as the only argument does not contain
667 ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
668 ** by code in pragma.c to ensure that the implementation of certain
669 ** pragmas comports with the flags specified in the mkpragmatab.tcl
670 ** script.
671 */
672 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
sqlite3VdbeVerifyNoResultRow(Vdbe * p)673 void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
674   int i;
675   for(i=0; i<p->nOp; i++){
676     assert( p->aOp[i].opcode!=OP_ResultRow );
677   }
678 }
679 #endif
680 
681 /*
682 ** This function returns a pointer to the array of opcodes associated with
683 ** the Vdbe passed as the first argument. It is the callers responsibility
684 ** to arrange for the returned array to be eventually freed using the
685 ** vdbeFreeOpArray() function.
686 **
687 ** Before returning, *pnOp is set to the number of entries in the returned
688 ** array. Also, *pnMaxArg is set to the larger of its current value and
689 ** the number of entries in the Vdbe.apArg[] array required to execute the
690 ** returned program.
691 */
sqlite3VdbeTakeOpArray(Vdbe * p,int * pnOp,int * pnMaxArg)692 VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
693   VdbeOp *aOp = p->aOp;
694   assert( aOp && !p->db->mallocFailed );
695 
696   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
697   assert( DbMaskAllZero(p->btreeMask) );
698 
699   resolveP2Values(p, pnMaxArg);
700   *pnOp = p->nOp;
701   p->aOp = 0;
702   return aOp;
703 }
704 
705 /*
706 ** Add a whole list of operations to the operation stack.  Return a
707 ** pointer to the first operation inserted.
708 **
709 ** Non-zero P2 arguments to jump instructions are automatically adjusted
710 ** so that the jump target is relative to the first operation inserted.
711 */
sqlite3VdbeAddOpList(Vdbe * p,int nOp,VdbeOpList const * aOp,int iLineno)712 VdbeOp *sqlite3VdbeAddOpList(
713   Vdbe *p,                     /* Add opcodes to the prepared statement */
714   int nOp,                     /* Number of opcodes to add */
715   VdbeOpList const *aOp,       /* The opcodes to be added */
716   int iLineno                  /* Source-file line number of first opcode */
717 ){
718   int i;
719   VdbeOp *pOut, *pFirst;
720   assert( nOp>0 );
721   assert( p->magic==VDBE_MAGIC_INIT );
722   if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
723     return 0;
724   }
725   pFirst = pOut = &p->aOp[p->nOp];
726   for(i=0; i<nOp; i++, aOp++, pOut++){
727     pOut->opcode = aOp->opcode;
728     pOut->p1 = aOp->p1;
729     pOut->p2 = aOp->p2;
730     assert( aOp->p2>=0 );
731     if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
732       pOut->p2 += p->nOp;
733     }
734     pOut->p3 = aOp->p3;
735     pOut->p4type = P4_NOTUSED;
736     pOut->p4.p = 0;
737     pOut->p5 = 0;
738 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
739     pOut->zComment = 0;
740 #endif
741 #ifdef SQLITE_VDBE_COVERAGE
742     pOut->iSrcLine = iLineno+i;
743 #else
744     (void)iLineno;
745 #endif
746 #ifdef SQLITE_DEBUG
747     if( p->db->flags & SQLITE_VdbeAddopTrace ){
748       sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
749     }
750 #endif
751   }
752   p->nOp += nOp;
753   return pFirst;
754 }
755 
756 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
757 /*
758 ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
759 */
sqlite3VdbeScanStatus(Vdbe * p,int addrExplain,int addrLoop,int addrVisit,LogEst nEst,const char * zName)760 void sqlite3VdbeScanStatus(
761   Vdbe *p,                        /* VM to add scanstatus() to */
762   int addrExplain,                /* Address of OP_Explain (or 0) */
763   int addrLoop,                   /* Address of loop counter */
764   int addrVisit,                  /* Address of rows visited counter */
765   LogEst nEst,                    /* Estimated number of output rows */
766   const char *zName               /* Name of table or index being scanned */
767 ){
768   int nByte = (p->nScan+1) * sizeof(ScanStatus);
769   ScanStatus *aNew;
770   aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
771   if( aNew ){
772     ScanStatus *pNew = &aNew[p->nScan++];
773     pNew->addrExplain = addrExplain;
774     pNew->addrLoop = addrLoop;
775     pNew->addrVisit = addrVisit;
776     pNew->nEst = nEst;
777     pNew->zName = sqlite3DbStrDup(p->db, zName);
778     p->aScan = aNew;
779   }
780 }
781 #endif
782 
783 
784 /*
785 ** Change the value of the opcode, or P1, P2, P3, or P5 operands
786 ** for a specific instruction.
787 */
sqlite3VdbeChangeOpcode(Vdbe * p,u32 addr,u8 iNewOpcode)788 void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
789   sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
790 }
sqlite3VdbeChangeP1(Vdbe * p,u32 addr,int val)791 void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
792   sqlite3VdbeGetOp(p,addr)->p1 = val;
793 }
sqlite3VdbeChangeP2(Vdbe * p,u32 addr,int val)794 void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
795   sqlite3VdbeGetOp(p,addr)->p2 = val;
796 }
sqlite3VdbeChangeP3(Vdbe * p,u32 addr,int val)797 void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
798   sqlite3VdbeGetOp(p,addr)->p3 = val;
799 }
sqlite3VdbeChangeP5(Vdbe * p,u16 p5)800 void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
801   assert( p->nOp>0 || p->db->mallocFailed );
802   if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
803 }
804 
805 /*
806 ** Change the P2 operand of instruction addr so that it points to
807 ** the address of the next instruction to be coded.
808 */
sqlite3VdbeJumpHere(Vdbe * p,int addr)809 void sqlite3VdbeJumpHere(Vdbe *p, int addr){
810   sqlite3VdbeChangeP2(p, addr, p->nOp);
811 }
812 
813 
814 /*
815 ** If the input FuncDef structure is ephemeral, then free it.  If
816 ** the FuncDef is not ephermal, then do nothing.
817 */
freeEphemeralFunction(sqlite3 * db,FuncDef * pDef)818 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
819   if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
820     sqlite3DbFreeNN(db, pDef);
821   }
822 }
823 
824 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
825 
826 /*
827 ** Delete a P4 value if necessary.
828 */
freeP4Mem(sqlite3 * db,Mem * p)829 static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
830   if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
831   sqlite3DbFreeNN(db, p);
832 }
freeP4FuncCtx(sqlite3 * db,sqlite3_context * p)833 static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
834   freeEphemeralFunction(db, p->pFunc);
835  sqlite3DbFreeNN(db, p);
836 }
freeP4(sqlite3 * db,int p4type,void * p4)837 static void freeP4(sqlite3 *db, int p4type, void *p4){
838   assert( db );
839   switch( p4type ){
840     case P4_FUNCCTX: {
841       freeP4FuncCtx(db, (sqlite3_context*)p4);
842       break;
843     }
844     case P4_REAL:
845     case P4_INT64:
846     case P4_DYNAMIC:
847     case P4_INTARRAY: {
848       sqlite3DbFree(db, p4);
849       break;
850     }
851     case P4_KEYINFO: {
852       if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
853       break;
854     }
855 #ifdef SQLITE_ENABLE_CURSOR_HINTS
856     case P4_EXPR: {
857       sqlite3ExprDelete(db, (Expr*)p4);
858       break;
859     }
860 #endif
861     case P4_FUNCDEF: {
862       freeEphemeralFunction(db, (FuncDef*)p4);
863       break;
864     }
865     case P4_MEM: {
866       if( db->pnBytesFreed==0 ){
867         sqlite3ValueFree((sqlite3_value*)p4);
868       }else{
869         freeP4Mem(db, (Mem*)p4);
870       }
871       break;
872     }
873     case P4_VTAB : {
874       if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
875       break;
876     }
877   }
878 }
879 
880 /*
881 ** Free the space allocated for aOp and any p4 values allocated for the
882 ** opcodes contained within. If aOp is not NULL it is assumed to contain
883 ** nOp entries.
884 */
vdbeFreeOpArray(sqlite3 * db,Op * aOp,int nOp)885 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
886   if( aOp ){
887     Op *pOp;
888     for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
889       if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
890 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
891       sqlite3DbFree(db, pOp->zComment);
892 #endif
893     }
894     sqlite3DbFreeNN(db, aOp);
895   }
896 }
897 
898 /*
899 ** Link the SubProgram object passed as the second argument into the linked
900 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
901 ** objects when the VM is no longer required.
902 */
sqlite3VdbeLinkSubProgram(Vdbe * pVdbe,SubProgram * p)903 void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
904   p->pNext = pVdbe->pProgram;
905   pVdbe->pProgram = p;
906 }
907 
908 /*
909 ** Change the opcode at addr into OP_Noop
910 */
sqlite3VdbeChangeToNoop(Vdbe * p,int addr)911 int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
912   VdbeOp *pOp;
913   if( p->db->mallocFailed ) return 0;
914   assert( addr>=0 && addr<p->nOp );
915   pOp = &p->aOp[addr];
916   freeP4(p->db, pOp->p4type, pOp->p4.p);
917   pOp->p4type = P4_NOTUSED;
918   pOp->p4.z = 0;
919   pOp->opcode = OP_Noop;
920   return 1;
921 }
922 
923 /*
924 ** If the last opcode is "op" and it is not a jump destination,
925 ** then remove it.  Return true if and only if an opcode was removed.
926 */
sqlite3VdbeDeletePriorOpcode(Vdbe * p,u8 op)927 int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
928   if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
929     return sqlite3VdbeChangeToNoop(p, p->nOp-1);
930   }else{
931     return 0;
932   }
933 }
934 
935 /*
936 ** Change the value of the P4 operand for a specific instruction.
937 ** This routine is useful when a large program is loaded from a
938 ** static array using sqlite3VdbeAddOpList but we want to make a
939 ** few minor changes to the program.
940 **
941 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
942 ** the string is made into memory obtained from sqlite3_malloc().
943 ** A value of n==0 means copy bytes of zP4 up to and including the
944 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
945 **
946 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
947 ** to a string or structure that is guaranteed to exist for the lifetime of
948 ** the Vdbe. In these cases we can just copy the pointer.
949 **
950 ** If addr<0 then change P4 on the most recently inserted instruction.
951 */
vdbeChangeP4Full(Vdbe * p,Op * pOp,const char * zP4,int n)952 static void SQLITE_NOINLINE vdbeChangeP4Full(
953   Vdbe *p,
954   Op *pOp,
955   const char *zP4,
956   int n
957 ){
958   if( pOp->p4type ){
959     freeP4(p->db, pOp->p4type, pOp->p4.p);
960     pOp->p4type = 0;
961     pOp->p4.p = 0;
962   }
963   if( n<0 ){
964     sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
965   }else{
966     if( n==0 ) n = sqlite3Strlen30(zP4);
967     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
968     pOp->p4type = P4_DYNAMIC;
969   }
970 }
sqlite3VdbeChangeP4(Vdbe * p,int addr,const char * zP4,int n)971 void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
972   Op *pOp;
973   sqlite3 *db;
974   assert( p!=0 );
975   db = p->db;
976   assert( p->magic==VDBE_MAGIC_INIT );
977   assert( p->aOp!=0 || db->mallocFailed );
978   if( db->mallocFailed ){
979     if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
980     return;
981   }
982   assert( p->nOp>0 );
983   assert( addr<p->nOp );
984   if( addr<0 ){
985     addr = p->nOp - 1;
986   }
987   pOp = &p->aOp[addr];
988   if( n>=0 || pOp->p4type ){
989     vdbeChangeP4Full(p, pOp, zP4, n);
990     return;
991   }
992   if( n==P4_INT32 ){
993     /* Note: this cast is safe, because the origin data point was an int
994     ** that was cast to a (const char *). */
995     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
996     pOp->p4type = P4_INT32;
997   }else if( zP4!=0 ){
998     assert( n<0 );
999     pOp->p4.p = (void*)zP4;
1000     pOp->p4type = (signed char)n;
1001     if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
1002   }
1003 }
1004 
1005 /*
1006 ** Change the P4 operand of the most recently coded instruction
1007 ** to the value defined by the arguments.  This is a high-speed
1008 ** version of sqlite3VdbeChangeP4().
1009 **
1010 ** The P4 operand must not have been previously defined.  And the new
1011 ** P4 must not be P4_INT32.  Use sqlite3VdbeChangeP4() in either of
1012 ** those cases.
1013 */
sqlite3VdbeAppendP4(Vdbe * p,void * pP4,int n)1014 void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
1015   VdbeOp *pOp;
1016   assert( n!=P4_INT32 && n!=P4_VTAB );
1017   assert( n<=0 );
1018   if( p->db->mallocFailed ){
1019     freeP4(p->db, n, pP4);
1020   }else{
1021     assert( pP4!=0 );
1022     assert( p->nOp>0 );
1023     pOp = &p->aOp[p->nOp-1];
1024     assert( pOp->p4type==P4_NOTUSED );
1025     pOp->p4type = n;
1026     pOp->p4.p = pP4;
1027   }
1028 }
1029 
1030 /*
1031 ** Set the P4 on the most recently added opcode to the KeyInfo for the
1032 ** index given.
1033 */
sqlite3VdbeSetP4KeyInfo(Parse * pParse,Index * pIdx)1034 void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
1035   Vdbe *v = pParse->pVdbe;
1036   KeyInfo *pKeyInfo;
1037   assert( v!=0 );
1038   assert( pIdx!=0 );
1039   pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
1040   if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
1041 }
1042 
1043 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1044 /*
1045 ** Change the comment on the most recently coded instruction.  Or
1046 ** insert a No-op and add the comment to that new instruction.  This
1047 ** makes the code easier to read during debugging.  None of this happens
1048 ** in a production build.
1049 */
vdbeVComment(Vdbe * p,const char * zFormat,va_list ap)1050 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
1051   assert( p->nOp>0 || p->aOp==0 );
1052   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
1053   if( p->nOp ){
1054     assert( p->aOp );
1055     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
1056     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
1057   }
1058 }
sqlite3VdbeComment(Vdbe * p,const char * zFormat,...)1059 void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
1060   va_list ap;
1061   if( p ){
1062     va_start(ap, zFormat);
1063     vdbeVComment(p, zFormat, ap);
1064     va_end(ap);
1065   }
1066 }
sqlite3VdbeNoopComment(Vdbe * p,const char * zFormat,...)1067 void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
1068   va_list ap;
1069   if( p ){
1070     sqlite3VdbeAddOp0(p, OP_Noop);
1071     va_start(ap, zFormat);
1072     vdbeVComment(p, zFormat, ap);
1073     va_end(ap);
1074   }
1075 }
1076 #endif  /* NDEBUG */
1077 
1078 #ifdef SQLITE_VDBE_COVERAGE
1079 /*
1080 ** Set the value if the iSrcLine field for the previously coded instruction.
1081 */
sqlite3VdbeSetLineNumber(Vdbe * v,int iLine)1082 void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
1083   sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
1084 }
1085 #endif /* SQLITE_VDBE_COVERAGE */
1086 
1087 /*
1088 ** Return the opcode for a given address.  If the address is -1, then
1089 ** return the most recently inserted opcode.
1090 **
1091 ** If a memory allocation error has occurred prior to the calling of this
1092 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
1093 ** is readable but not writable, though it is cast to a writable value.
1094 ** The return of a dummy opcode allows the call to continue functioning
1095 ** after an OOM fault without having to check to see if the return from
1096 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
1097 ** dummy will never be written to.  This is verified by code inspection and
1098 ** by running with Valgrind.
1099 */
sqlite3VdbeGetOp(Vdbe * p,int addr)1100 VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
1101   /* C89 specifies that the constant "dummy" will be initialized to all
1102   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
1103   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
1104   assert( p->magic==VDBE_MAGIC_INIT );
1105   if( addr<0 ){
1106     addr = p->nOp - 1;
1107   }
1108   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
1109   if( p->db->mallocFailed ){
1110     return (VdbeOp*)&dummy;
1111   }else{
1112     return &p->aOp[addr];
1113   }
1114 }
1115 
1116 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
1117 /*
1118 ** Return an integer value for one of the parameters to the opcode pOp
1119 ** determined by character c.
1120 */
translateP(char c,const Op * pOp)1121 static int translateP(char c, const Op *pOp){
1122   if( c=='1' ) return pOp->p1;
1123   if( c=='2' ) return pOp->p2;
1124   if( c=='3' ) return pOp->p3;
1125   if( c=='4' ) return pOp->p4.i;
1126   return pOp->p5;
1127 }
1128 
1129 /*
1130 ** Compute a string for the "comment" field of a VDBE opcode listing.
1131 **
1132 ** The Synopsis: field in comments in the vdbe.c source file gets converted
1133 ** to an extra string that is appended to the sqlite3OpcodeName().  In the
1134 ** absence of other comments, this synopsis becomes the comment on the opcode.
1135 ** Some translation occurs:
1136 **
1137 **       "PX"      ->  "r[X]"
1138 **       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
1139 **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
1140 **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
1141 */
displayComment(const Op * pOp,const char * zP4,char * zTemp,int nTemp)1142 static int displayComment(
1143   const Op *pOp,     /* The opcode to be commented */
1144   const char *zP4,   /* Previously obtained value for P4 */
1145   char *zTemp,       /* Write result here */
1146   int nTemp          /* Space available in zTemp[] */
1147 ){
1148   const char *zOpName;
1149   const char *zSynopsis;
1150   int nOpName;
1151   int ii, jj;
1152   char zAlt[50];
1153   zOpName = sqlite3OpcodeName(pOp->opcode);
1154   nOpName = sqlite3Strlen30(zOpName);
1155   if( zOpName[nOpName+1] ){
1156     int seenCom = 0;
1157     char c;
1158     zSynopsis = zOpName += nOpName + 1;
1159     if( strncmp(zSynopsis,"IF ",3)==0 ){
1160       if( pOp->p5 & SQLITE_STOREP2 ){
1161         sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
1162       }else{
1163         sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
1164       }
1165       zSynopsis = zAlt;
1166     }
1167     for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
1168       if( c=='P' ){
1169         c = zSynopsis[++ii];
1170         if( c=='4' ){
1171           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
1172         }else if( c=='X' ){
1173           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
1174           seenCom = 1;
1175         }else{
1176           int v1 = translateP(c, pOp);
1177           int v2;
1178           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
1179           if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
1180             ii += 3;
1181             jj += sqlite3Strlen30(zTemp+jj);
1182             v2 = translateP(zSynopsis[ii], pOp);
1183             if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
1184               ii += 2;
1185               v2++;
1186             }
1187             if( v2>1 ){
1188               sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
1189             }
1190           }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
1191             ii += 4;
1192           }
1193         }
1194         jj += sqlite3Strlen30(zTemp+jj);
1195       }else{
1196         zTemp[jj++] = c;
1197       }
1198     }
1199     if( !seenCom && jj<nTemp-5 && pOp->zComment ){
1200       sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
1201       jj += sqlite3Strlen30(zTemp+jj);
1202     }
1203     if( jj<nTemp ) zTemp[jj] = 0;
1204   }else if( pOp->zComment ){
1205     sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
1206     jj = sqlite3Strlen30(zTemp);
1207   }else{
1208     zTemp[0] = 0;
1209     jj = 0;
1210   }
1211   return jj;
1212 }
1213 #endif /* SQLITE_DEBUG */
1214 
1215 #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
1216 /*
1217 ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
1218 ** that can be displayed in the P4 column of EXPLAIN output.
1219 */
displayP4Expr(StrAccum * p,Expr * pExpr)1220 static void displayP4Expr(StrAccum *p, Expr *pExpr){
1221   const char *zOp = 0;
1222   switch( pExpr->op ){
1223     case TK_STRING:
1224       sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
1225       break;
1226     case TK_INTEGER:
1227       sqlite3XPrintf(p, "%d", pExpr->u.iValue);
1228       break;
1229     case TK_NULL:
1230       sqlite3XPrintf(p, "NULL");
1231       break;
1232     case TK_REGISTER: {
1233       sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
1234       break;
1235     }
1236     case TK_COLUMN: {
1237       if( pExpr->iColumn<0 ){
1238         sqlite3XPrintf(p, "rowid");
1239       }else{
1240         sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
1241       }
1242       break;
1243     }
1244     case TK_LT:      zOp = "LT";      break;
1245     case TK_LE:      zOp = "LE";      break;
1246     case TK_GT:      zOp = "GT";      break;
1247     case TK_GE:      zOp = "GE";      break;
1248     case TK_NE:      zOp = "NE";      break;
1249     case TK_EQ:      zOp = "EQ";      break;
1250     case TK_IS:      zOp = "IS";      break;
1251     case TK_ISNOT:   zOp = "ISNOT";   break;
1252     case TK_AND:     zOp = "AND";     break;
1253     case TK_OR:      zOp = "OR";      break;
1254     case TK_PLUS:    zOp = "ADD";     break;
1255     case TK_STAR:    zOp = "MUL";     break;
1256     case TK_MINUS:   zOp = "SUB";     break;
1257     case TK_REM:     zOp = "REM";     break;
1258     case TK_BITAND:  zOp = "BITAND";  break;
1259     case TK_BITOR:   zOp = "BITOR";   break;
1260     case TK_SLASH:   zOp = "DIV";     break;
1261     case TK_LSHIFT:  zOp = "LSHIFT";  break;
1262     case TK_RSHIFT:  zOp = "RSHIFT";  break;
1263     case TK_CONCAT:  zOp = "CONCAT";  break;
1264     case TK_UMINUS:  zOp = "MINUS";   break;
1265     case TK_UPLUS:   zOp = "PLUS";    break;
1266     case TK_BITNOT:  zOp = "BITNOT";  break;
1267     case TK_NOT:     zOp = "NOT";     break;
1268     case TK_ISNULL:  zOp = "ISNULL";  break;
1269     case TK_NOTNULL: zOp = "NOTNULL"; break;
1270 
1271     default:
1272       sqlite3XPrintf(p, "%s", "expr");
1273       break;
1274   }
1275 
1276   if( zOp ){
1277     sqlite3XPrintf(p, "%s(", zOp);
1278     displayP4Expr(p, pExpr->pLeft);
1279     if( pExpr->pRight ){
1280       sqlite3StrAccumAppend(p, ",", 1);
1281       displayP4Expr(p, pExpr->pRight);
1282     }
1283     sqlite3StrAccumAppend(p, ")", 1);
1284   }
1285 }
1286 #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
1287 
1288 
1289 #if VDBE_DISPLAY_P4
1290 /*
1291 ** Compute a string that describes the P4 parameter for an opcode.
1292 ** Use zTemp for any required temporary buffer space.
1293 */
displayP4(Op * pOp,char * zTemp,int nTemp)1294 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
1295   char *zP4 = zTemp;
1296   StrAccum x;
1297   assert( nTemp>=20 );
1298   sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
1299   switch( pOp->p4type ){
1300     case P4_KEYINFO: {
1301       int j;
1302       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
1303       assert( pKeyInfo->aSortOrder!=0 );
1304       sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField);
1305       for(j=0; j<pKeyInfo->nField; j++){
1306         CollSeq *pColl = pKeyInfo->aColl[j];
1307         const char *zColl = pColl ? pColl->zName : "";
1308         if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
1309         sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
1310       }
1311       sqlite3StrAccumAppend(&x, ")", 1);
1312       break;
1313     }
1314 #ifdef SQLITE_ENABLE_CURSOR_HINTS
1315     case P4_EXPR: {
1316       displayP4Expr(&x, pOp->p4.pExpr);
1317       break;
1318     }
1319 #endif
1320     case P4_COLLSEQ: {
1321       CollSeq *pColl = pOp->p4.pColl;
1322       sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
1323       break;
1324     }
1325     case P4_FUNCDEF: {
1326       FuncDef *pDef = pOp->p4.pFunc;
1327       sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
1328       break;
1329     }
1330 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
1331     case P4_FUNCCTX: {
1332       FuncDef *pDef = pOp->p4.pCtx->pFunc;
1333       sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
1334       break;
1335     }
1336 #endif
1337     case P4_INT64: {
1338       sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
1339       break;
1340     }
1341     case P4_INT32: {
1342       sqlite3XPrintf(&x, "%d", pOp->p4.i);
1343       break;
1344     }
1345     case P4_REAL: {
1346       sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
1347       break;
1348     }
1349     case P4_MEM: {
1350       Mem *pMem = pOp->p4.pMem;
1351       if( pMem->flags & MEM_Str ){
1352         zP4 = pMem->z;
1353       }else if( pMem->flags & MEM_Int ){
1354         sqlite3XPrintf(&x, "%lld", pMem->u.i);
1355       }else if( pMem->flags & MEM_Real ){
1356         sqlite3XPrintf(&x, "%.16g", pMem->u.r);
1357       }else if( pMem->flags & MEM_Null ){
1358         zP4 = "NULL";
1359       }else{
1360         assert( pMem->flags & MEM_Blob );
1361         zP4 = "(blob)";
1362       }
1363       break;
1364     }
1365 #ifndef SQLITE_OMIT_VIRTUALTABLE
1366     case P4_VTAB: {
1367       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
1368       sqlite3XPrintf(&x, "vtab:%p", pVtab);
1369       break;
1370     }
1371 #endif
1372     case P4_INTARRAY: {
1373       int i;
1374       int *ai = pOp->p4.ai;
1375       int n = ai[0];   /* The first element of an INTARRAY is always the
1376                        ** count of the number of elements to follow */
1377       for(i=1; i<n; i++){
1378         sqlite3XPrintf(&x, ",%d", ai[i]);
1379       }
1380       zTemp[0] = '[';
1381       sqlite3StrAccumAppend(&x, "]", 1);
1382       break;
1383     }
1384     case P4_SUBPROGRAM: {
1385       sqlite3XPrintf(&x, "program");
1386       break;
1387     }
1388     case P4_ADVANCE: {
1389       zTemp[0] = 0;
1390       break;
1391     }
1392     case P4_TABLE: {
1393       sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
1394       break;
1395     }
1396     default: {
1397       zP4 = pOp->p4.z;
1398       if( zP4==0 ){
1399         zP4 = zTemp;
1400         zTemp[0] = 0;
1401       }
1402     }
1403   }
1404   sqlite3StrAccumFinish(&x);
1405   assert( zP4!=0 );
1406   return zP4;
1407 }
1408 #endif /* VDBE_DISPLAY_P4 */
1409 
1410 /*
1411 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
1412 **
1413 ** The prepared statements need to know in advance the complete set of
1414 ** attached databases that will be use.  A mask of these databases
1415 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
1416 ** p->btreeMask of databases that will require a lock.
1417 */
sqlite3VdbeUsesBtree(Vdbe * p,int i)1418 void sqlite3VdbeUsesBtree(Vdbe *p, int i){
1419   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
1420   assert( i<(int)sizeof(p->btreeMask)*8 );
1421   DbMaskSet(p->btreeMask, i);
1422   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
1423     DbMaskSet(p->lockMask, i);
1424   }
1425 }
1426 
1427 #if !defined(SQLITE_OMIT_SHARED_CACHE)
1428 /*
1429 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
1430 ** this routine obtains the mutex associated with each BtShared structure
1431 ** that may be accessed by the VM passed as an argument. In doing so it also
1432 ** sets the BtShared.db member of each of the BtShared structures, ensuring
1433 ** that the correct busy-handler callback is invoked if required.
1434 **
1435 ** If SQLite is not threadsafe but does support shared-cache mode, then
1436 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
1437 ** of all of BtShared structures accessible via the database handle
1438 ** associated with the VM.
1439 **
1440 ** If SQLite is not threadsafe and does not support shared-cache mode, this
1441 ** function is a no-op.
1442 **
1443 ** The p->btreeMask field is a bitmask of all btrees that the prepared
1444 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
1445 ** corresponding to btrees that use shared cache.  Then the runtime of
1446 ** this routine is N*N.  But as N is rarely more than 1, this should not
1447 ** be a problem.
1448 */
sqlite3VdbeEnter(Vdbe * p)1449 void sqlite3VdbeEnter(Vdbe *p){
1450   int i;
1451   sqlite3 *db;
1452   Db *aDb;
1453   int nDb;
1454   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
1455   db = p->db;
1456   aDb = db->aDb;
1457   nDb = db->nDb;
1458   for(i=0; i<nDb; i++){
1459     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
1460       sqlite3BtreeEnter(aDb[i].pBt);
1461     }
1462   }
1463 }
1464 #endif
1465 
1466 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
1467 /*
1468 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
1469 */
vdbeLeave(Vdbe * p)1470 static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
1471   int i;
1472   sqlite3 *db;
1473   Db *aDb;
1474   int nDb;
1475   db = p->db;
1476   aDb = db->aDb;
1477   nDb = db->nDb;
1478   for(i=0; i<nDb; i++){
1479     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
1480       sqlite3BtreeLeave(aDb[i].pBt);
1481     }
1482   }
1483 }
sqlite3VdbeLeave(Vdbe * p)1484 void sqlite3VdbeLeave(Vdbe *p){
1485   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
1486   vdbeLeave(p);
1487 }
1488 #endif
1489 
1490 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
1491 /*
1492 ** Print a single opcode.  This routine is used for debugging only.
1493 */
sqlite3VdbePrintOp(FILE * pOut,int pc,Op * pOp)1494 void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
1495   char *zP4;
1496   char zPtr[50];
1497   char zCom[100];
1498   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
1499   if( pOut==0 ) pOut = stdout;
1500   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
1501 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1502   displayComment(pOp, zP4, zCom, sizeof(zCom));
1503 #else
1504   zCom[0] = 0;
1505 #endif
1506   /* NB:  The sqlite3OpcodeName() function is implemented by code created
1507   ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
1508   ** information from the vdbe.c source text */
1509   fprintf(pOut, zFormat1, pc,
1510       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
1511       zCom
1512   );
1513   fflush(pOut);
1514 }
1515 #endif
1516 
1517 /*
1518 ** Initialize an array of N Mem element.
1519 */
initMemArray(Mem * p,int N,sqlite3 * db,u16 flags)1520 static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
1521   while( (N--)>0 ){
1522     p->db = db;
1523     p->flags = flags;
1524     p->szMalloc = 0;
1525 #ifdef SQLITE_DEBUG
1526     p->pScopyFrom = 0;
1527 #endif
1528     p++;
1529   }
1530 }
1531 
1532 /*
1533 ** Release an array of N Mem elements
1534 */
releaseMemArray(Mem * p,int N)1535 static void releaseMemArray(Mem *p, int N){
1536   if( p && N ){
1537     Mem *pEnd = &p[N];
1538     sqlite3 *db = p->db;
1539     if( db->pnBytesFreed ){
1540       do{
1541         if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
1542       }while( (++p)<pEnd );
1543       return;
1544     }
1545     do{
1546       assert( (&p[1])==pEnd || p[0].db==p[1].db );
1547       assert( sqlite3VdbeCheckMemInvariants(p) );
1548 
1549       /* This block is really an inlined version of sqlite3VdbeMemRelease()
1550       ** that takes advantage of the fact that the memory cell value is
1551       ** being set to NULL after releasing any dynamic resources.
1552       **
1553       ** The justification for duplicating code is that according to
1554       ** callgrind, this causes a certain test case to hit the CPU 4.7
1555       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
1556       ** sqlite3MemRelease() were called from here. With -O2, this jumps
1557       ** to 6.6 percent. The test case is inserting 1000 rows into a table
1558       ** with no indexes using a single prepared INSERT statement, bind()
1559       ** and reset(). Inserts are grouped into a transaction.
1560       */
1561       testcase( p->flags & MEM_Agg );
1562       testcase( p->flags & MEM_Dyn );
1563       testcase( p->flags & MEM_Frame );
1564       testcase( p->flags & MEM_RowSet );
1565       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
1566         sqlite3VdbeMemRelease(p);
1567       }else if( p->szMalloc ){
1568         sqlite3DbFreeNN(db, p->zMalloc);
1569         p->szMalloc = 0;
1570       }
1571 
1572       p->flags = MEM_Undefined;
1573     }while( (++p)<pEnd );
1574   }
1575 }
1576 
1577 /*
1578 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
1579 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
1580 */
sqlite3VdbeFrameDelete(VdbeFrame * p)1581 void sqlite3VdbeFrameDelete(VdbeFrame *p){
1582   int i;
1583   Mem *aMem = VdbeFrameMem(p);
1584   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
1585   for(i=0; i<p->nChildCsr; i++){
1586     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
1587   }
1588   releaseMemArray(aMem, p->nChildMem);
1589   sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
1590   sqlite3DbFree(p->v->db, p);
1591 }
1592 
1593 #ifndef SQLITE_OMIT_EXPLAIN
1594 /*
1595 ** Give a listing of the program in the virtual machine.
1596 **
1597 ** The interface is the same as sqlite3VdbeExec().  But instead of
1598 ** running the code, it invokes the callback once for each instruction.
1599 ** This feature is used to implement "EXPLAIN".
1600 **
1601 ** When p->explain==1, each instruction is listed.  When
1602 ** p->explain==2, only OP_Explain instructions are listed and these
1603 ** are shown in a different format.  p->explain==2 is used to implement
1604 ** EXPLAIN QUERY PLAN.
1605 **
1606 ** When p->explain==1, first the main program is listed, then each of
1607 ** the trigger subprograms are listed one by one.
1608 */
sqlite3VdbeList(Vdbe * p)1609 int sqlite3VdbeList(
1610   Vdbe *p                   /* The VDBE */
1611 ){
1612   int nRow;                            /* Stop when row count reaches this */
1613   int nSub = 0;                        /* Number of sub-vdbes seen so far */
1614   SubProgram **apSub = 0;              /* Array of sub-vdbes */
1615   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
1616   sqlite3 *db = p->db;                 /* The database connection */
1617   int i;                               /* Loop counter */
1618   int rc = SQLITE_OK;                  /* Return code */
1619   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
1620 
1621   assert( p->explain );
1622   assert( p->magic==VDBE_MAGIC_RUN );
1623   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
1624 
1625   /* Even though this opcode does not use dynamic strings for
1626   ** the result, result columns may become dynamic if the user calls
1627   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
1628   */
1629   releaseMemArray(pMem, 8);
1630   p->pResultSet = 0;
1631 
1632   if( p->rc==SQLITE_NOMEM_BKPT ){
1633     /* This happens if a malloc() inside a call to sqlite3_column_text() or
1634     ** sqlite3_column_text16() failed.  */
1635     sqlite3OomFault(db);
1636     return SQLITE_ERROR;
1637   }
1638 
1639   /* When the number of output rows reaches nRow, that means the
1640   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
1641   ** nRow is the sum of the number of rows in the main program, plus
1642   ** the sum of the number of rows in all trigger subprograms encountered
1643   ** so far.  The nRow value will increase as new trigger subprograms are
1644   ** encountered, but p->pc will eventually catch up to nRow.
1645   */
1646   nRow = p->nOp;
1647   if( p->explain==1 ){
1648     /* The first 8 memory cells are used for the result set.  So we will
1649     ** commandeer the 9th cell to use as storage for an array of pointers
1650     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
1651     ** cells.  */
1652     assert( p->nMem>9 );
1653     pSub = &p->aMem[9];
1654     if( pSub->flags&MEM_Blob ){
1655       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
1656       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
1657       nSub = pSub->n/sizeof(Vdbe*);
1658       apSub = (SubProgram **)pSub->z;
1659     }
1660     for(i=0; i<nSub; i++){
1661       nRow += apSub[i]->nOp;
1662     }
1663   }
1664 
1665   do{
1666     i = p->pc++;
1667   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
1668   if( i>=nRow ){
1669     p->rc = SQLITE_OK;
1670     rc = SQLITE_DONE;
1671   }else if( db->u1.isInterrupted ){
1672     p->rc = SQLITE_INTERRUPT;
1673     rc = SQLITE_ERROR;
1674     sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
1675   }else{
1676     char *zP4;
1677     Op *pOp;
1678     if( i<p->nOp ){
1679       /* The output line number is small enough that we are still in the
1680       ** main program. */
1681       pOp = &p->aOp[i];
1682     }else{
1683       /* We are currently listing subprograms.  Figure out which one and
1684       ** pick up the appropriate opcode. */
1685       int j;
1686       i -= p->nOp;
1687       for(j=0; i>=apSub[j]->nOp; j++){
1688         i -= apSub[j]->nOp;
1689       }
1690       pOp = &apSub[j]->aOp[i];
1691     }
1692     if( p->explain==1 ){
1693       pMem->flags = MEM_Int;
1694       pMem->u.i = i;                                /* Program counter */
1695       pMem++;
1696 
1697       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
1698       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
1699       assert( pMem->z!=0 );
1700       pMem->n = sqlite3Strlen30(pMem->z);
1701       pMem->enc = SQLITE_UTF8;
1702       pMem++;
1703 
1704       /* When an OP_Program opcode is encounter (the only opcode that has
1705       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
1706       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
1707       ** has not already been seen.
1708       */
1709       if( pOp->p4type==P4_SUBPROGRAM ){
1710         int nByte = (nSub+1)*sizeof(SubProgram*);
1711         int j;
1712         for(j=0; j<nSub; j++){
1713           if( apSub[j]==pOp->p4.pProgram ) break;
1714         }
1715         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
1716           apSub = (SubProgram **)pSub->z;
1717           apSub[nSub++] = pOp->p4.pProgram;
1718           pSub->flags |= MEM_Blob;
1719           pSub->n = nSub*sizeof(SubProgram*);
1720         }
1721       }
1722     }
1723 
1724     pMem->flags = MEM_Int;
1725     pMem->u.i = pOp->p1;                          /* P1 */
1726     pMem++;
1727 
1728     pMem->flags = MEM_Int;
1729     pMem->u.i = pOp->p2;                          /* P2 */
1730     pMem++;
1731 
1732     pMem->flags = MEM_Int;
1733     pMem->u.i = pOp->p3;                          /* P3 */
1734     pMem++;
1735 
1736     if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
1737       assert( p->db->mallocFailed );
1738       return SQLITE_ERROR;
1739     }
1740     pMem->flags = MEM_Str|MEM_Term;
1741     zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
1742     if( zP4!=pMem->z ){
1743       pMem->n = 0;
1744       sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
1745     }else{
1746       assert( pMem->z!=0 );
1747       pMem->n = sqlite3Strlen30(pMem->z);
1748       pMem->enc = SQLITE_UTF8;
1749     }
1750     pMem++;
1751 
1752     if( p->explain==1 ){
1753       if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
1754         assert( p->db->mallocFailed );
1755         return SQLITE_ERROR;
1756       }
1757       pMem->flags = MEM_Str|MEM_Term;
1758       pMem->n = 2;
1759       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
1760       pMem->enc = SQLITE_UTF8;
1761       pMem++;
1762 
1763 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1764       if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
1765         assert( p->db->mallocFailed );
1766         return SQLITE_ERROR;
1767       }
1768       pMem->flags = MEM_Str|MEM_Term;
1769       pMem->n = displayComment(pOp, zP4, pMem->z, 500);
1770       pMem->enc = SQLITE_UTF8;
1771 #else
1772       pMem->flags = MEM_Null;                       /* Comment */
1773 #endif
1774     }
1775 
1776     p->nResColumn = 8 - 4*(p->explain-1);
1777     p->pResultSet = &p->aMem[1];
1778     p->rc = SQLITE_OK;
1779     rc = SQLITE_ROW;
1780   }
1781   return rc;
1782 }
1783 #endif /* SQLITE_OMIT_EXPLAIN */
1784 
1785 #ifdef SQLITE_DEBUG
1786 /*
1787 ** Print the SQL that was used to generate a VDBE program.
1788 */
sqlite3VdbePrintSql(Vdbe * p)1789 void sqlite3VdbePrintSql(Vdbe *p){
1790   const char *z = 0;
1791   if( p->zSql ){
1792     z = p->zSql;
1793   }else if( p->nOp>=1 ){
1794     const VdbeOp *pOp = &p->aOp[0];
1795     if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
1796       z = pOp->p4.z;
1797       while( sqlite3Isspace(*z) ) z++;
1798     }
1799   }
1800   if( z ) printf("SQL: [%s]\n", z);
1801 }
1802 #endif
1803 
1804 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
1805 /*
1806 ** Print an IOTRACE message showing SQL content.
1807 */
sqlite3VdbeIOTraceSql(Vdbe * p)1808 void sqlite3VdbeIOTraceSql(Vdbe *p){
1809   int nOp = p->nOp;
1810   VdbeOp *pOp;
1811   if( sqlite3IoTrace==0 ) return;
1812   if( nOp<1 ) return;
1813   pOp = &p->aOp[0];
1814   if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
1815     int i, j;
1816     char z[1000];
1817     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
1818     for(i=0; sqlite3Isspace(z[i]); i++){}
1819     for(j=0; z[i]; i++){
1820       if( sqlite3Isspace(z[i]) ){
1821         if( z[i-1]!=' ' ){
1822           z[j++] = ' ';
1823         }
1824       }else{
1825         z[j++] = z[i];
1826       }
1827     }
1828     z[j] = 0;
1829     sqlite3IoTrace("SQL %s\n", z);
1830   }
1831 }
1832 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
1833 
1834 /* An instance of this object describes bulk memory available for use
1835 ** by subcomponents of a prepared statement.  Space is allocated out
1836 ** of a ReusableSpace object by the allocSpace() routine below.
1837 */
1838 struct ReusableSpace {
1839   u8 *pSpace;          /* Available memory */
1840   int nFree;           /* Bytes of available memory */
1841   int nNeeded;         /* Total bytes that could not be allocated */
1842 };
1843 
1844 /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
1845 ** from the ReusableSpace object.  Return a pointer to the allocated
1846 ** memory on success.  If insufficient memory is available in the
1847 ** ReusableSpace object, increase the ReusableSpace.nNeeded
1848 ** value by the amount needed and return NULL.
1849 **
1850 ** If pBuf is not initially NULL, that means that the memory has already
1851 ** been allocated by a prior call to this routine, so just return a copy
1852 ** of pBuf and leave ReusableSpace unchanged.
1853 **
1854 ** This allocator is employed to repurpose unused slots at the end of the
1855 ** opcode array of prepared state for other memory needs of the prepared
1856 ** statement.
1857 */
allocSpace(struct ReusableSpace * p,void * pBuf,int nByte)1858 static void *allocSpace(
1859   struct ReusableSpace *p,  /* Bulk memory available for allocation */
1860   void *pBuf,               /* Pointer to a prior allocation */
1861   int nByte                 /* Bytes of memory needed */
1862 ){
1863   assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
1864   if( pBuf==0 ){
1865     nByte = ROUND8(nByte);
1866     if( nByte <= p->nFree ){
1867       p->nFree -= nByte;
1868       pBuf = &p->pSpace[p->nFree];
1869     }else{
1870       p->nNeeded += nByte;
1871     }
1872   }
1873   assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
1874   return pBuf;
1875 }
1876 
1877 /*
1878 ** Rewind the VDBE back to the beginning in preparation for
1879 ** running it.
1880 */
sqlite3VdbeRewind(Vdbe * p)1881 void sqlite3VdbeRewind(Vdbe *p){
1882 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
1883   int i;
1884 #endif
1885   assert( p!=0 );
1886   assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
1887 
1888   /* There should be at least one opcode.
1889   */
1890   assert( p->nOp>0 );
1891 
1892   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
1893   p->magic = VDBE_MAGIC_RUN;
1894 
1895 #ifdef SQLITE_DEBUG
1896   for(i=0; i<p->nMem; i++){
1897     assert( p->aMem[i].db==p->db );
1898   }
1899 #endif
1900   p->pc = -1;
1901   p->rc = SQLITE_OK;
1902   p->errorAction = OE_Abort;
1903   p->nChange = 0;
1904   p->cacheCtr = 1;
1905   p->minWriteFileFormat = 255;
1906   p->iStatement = 0;
1907   p->nFkConstraint = 0;
1908 #ifdef VDBE_PROFILE
1909   for(i=0; i<p->nOp; i++){
1910     p->aOp[i].cnt = 0;
1911     p->aOp[i].cycles = 0;
1912   }
1913 #endif
1914 }
1915 
1916 /*
1917 ** Prepare a virtual machine for execution for the first time after
1918 ** creating the virtual machine.  This involves things such
1919 ** as allocating registers and initializing the program counter.
1920 ** After the VDBE has be prepped, it can be executed by one or more
1921 ** calls to sqlite3VdbeExec().
1922 **
1923 ** This function may be called exactly once on each virtual machine.
1924 ** After this routine is called the VM has been "packaged" and is ready
1925 ** to run.  After this routine is called, further calls to
1926 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
1927 ** the Vdbe from the Parse object that helped generate it so that the
1928 ** the Vdbe becomes an independent entity and the Parse object can be
1929 ** destroyed.
1930 **
1931 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
1932 ** to its initial state after it has been run.
1933 */
sqlite3VdbeMakeReady(Vdbe * p,Parse * pParse)1934 void sqlite3VdbeMakeReady(
1935   Vdbe *p,                       /* The VDBE */
1936   Parse *pParse                  /* Parsing context */
1937 ){
1938   sqlite3 *db;                   /* The database connection */
1939   int nVar;                      /* Number of parameters */
1940   int nMem;                      /* Number of VM memory registers */
1941   int nCursor;                   /* Number of cursors required */
1942   int nArg;                      /* Number of arguments in subprograms */
1943   int n;                         /* Loop counter */
1944   struct ReusableSpace x;        /* Reusable bulk memory */
1945 
1946   assert( p!=0 );
1947   assert( p->nOp>0 );
1948   assert( pParse!=0 );
1949   assert( p->magic==VDBE_MAGIC_INIT );
1950   assert( pParse==p->pParse );
1951   db = p->db;
1952   assert( db->mallocFailed==0 );
1953   nVar = pParse->nVar;
1954   nMem = pParse->nMem;
1955   nCursor = pParse->nTab;
1956   nArg = pParse->nMaxArg;
1957 
1958   /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
1959   ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
1960   ** space at the end of aMem[] for cursors 1 and greater.
1961   ** See also: allocateCursor().
1962   */
1963   nMem += nCursor;
1964   if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
1965 
1966   /* Figure out how much reusable memory is available at the end of the
1967   ** opcode array.  This extra memory will be reallocated for other elements
1968   ** of the prepared statement.
1969   */
1970   n = ROUND8(sizeof(Op)*p->nOp);              /* Bytes of opcode memory used */
1971   x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
1972   assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
1973   x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */
1974   assert( x.nFree>=0 );
1975   assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
1976 
1977   resolveP2Values(p, &nArg);
1978   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
1979   if( pParse->explain && nMem<10 ){
1980     nMem = 10;
1981   }
1982   p->expired = 0;
1983 
1984   /* Memory for registers, parameters, cursor, etc, is allocated in one or two
1985   ** passes.  On the first pass, we try to reuse unused memory at the
1986   ** end of the opcode array.  If we are unable to satisfy all memory
1987   ** requirements by reusing the opcode array tail, then the second
1988   ** pass will fill in the remainder using a fresh memory allocation.
1989   **
1990   ** This two-pass approach that reuses as much memory as possible from
1991   ** the leftover memory at the end of the opcode array.  This can significantly
1992   ** reduce the amount of memory held by a prepared statement.
1993   */
1994   do {
1995     x.nNeeded = 0;
1996     p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
1997     p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
1998     p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
1999     p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
2000 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2001     p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
2002 #endif
2003     if( x.nNeeded==0 ) break;
2004     x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
2005     x.nFree = x.nNeeded;
2006   }while( !db->mallocFailed );
2007 
2008   p->pVList = pParse->pVList;
2009   pParse->pVList =  0;
2010   p->explain = pParse->explain;
2011   if( db->mallocFailed ){
2012     p->nVar = 0;
2013     p->nCursor = 0;
2014     p->nMem = 0;
2015   }else{
2016     p->nCursor = nCursor;
2017     p->nVar = (ynVar)nVar;
2018     initMemArray(p->aVar, nVar, db, MEM_Null);
2019     p->nMem = nMem;
2020     initMemArray(p->aMem, nMem, db, MEM_Undefined);
2021     memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
2022 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2023     memset(p->anExec, 0, p->nOp*sizeof(i64));
2024 #endif
2025   }
2026   sqlite3VdbeRewind(p);
2027 }
2028 
2029 /*
2030 ** Close a VDBE cursor and release all the resources that cursor
2031 ** happens to hold.
2032 */
sqlite3VdbeFreeCursor(Vdbe * p,VdbeCursor * pCx)2033 void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
2034   if( pCx==0 ){
2035     return;
2036   }
2037   assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
2038   switch( pCx->eCurType ){
2039     case CURTYPE_SORTER: {
2040       sqlite3VdbeSorterClose(p->db, pCx);
2041       break;
2042     }
2043     case CURTYPE_BTREE: {
2044       if( pCx->isEphemeral ){
2045         if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
2046         /* The pCx->pCursor will be close automatically, if it exists, by
2047         ** the call above. */
2048       }else{
2049         assert( pCx->uc.pCursor!=0 );
2050         sqlite3BtreeCloseCursor(pCx->uc.pCursor);
2051       }
2052       break;
2053     }
2054 #ifndef SQLITE_OMIT_VIRTUALTABLE
2055     case CURTYPE_VTAB: {
2056       sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
2057       const sqlite3_module *pModule = pVCur->pVtab->pModule;
2058       assert( pVCur->pVtab->nRef>0 );
2059       pVCur->pVtab->nRef--;
2060       pModule->xClose(pVCur);
2061       break;
2062     }
2063 #endif
2064   }
2065 }
2066 
2067 /*
2068 ** Close all cursors in the current frame.
2069 */
closeCursorsInFrame(Vdbe * p)2070 static void closeCursorsInFrame(Vdbe *p){
2071   if( p->apCsr ){
2072     int i;
2073     for(i=0; i<p->nCursor; i++){
2074       VdbeCursor *pC = p->apCsr[i];
2075       if( pC ){
2076         sqlite3VdbeFreeCursor(p, pC);
2077         p->apCsr[i] = 0;
2078       }
2079     }
2080   }
2081 }
2082 
2083 /*
2084 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
2085 ** is used, for example, when a trigger sub-program is halted to restore
2086 ** control to the main program.
2087 */
sqlite3VdbeFrameRestore(VdbeFrame * pFrame)2088 int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
2089   Vdbe *v = pFrame->v;
2090   closeCursorsInFrame(v);
2091 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2092   v->anExec = pFrame->anExec;
2093 #endif
2094   v->aOp = pFrame->aOp;
2095   v->nOp = pFrame->nOp;
2096   v->aMem = pFrame->aMem;
2097   v->nMem = pFrame->nMem;
2098   v->apCsr = pFrame->apCsr;
2099   v->nCursor = pFrame->nCursor;
2100   v->db->lastRowid = pFrame->lastRowid;
2101   v->nChange = pFrame->nChange;
2102   v->db->nChange = pFrame->nDbChange;
2103   sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
2104   v->pAuxData = pFrame->pAuxData;
2105   pFrame->pAuxData = 0;
2106   return pFrame->pc;
2107 }
2108 
2109 /*
2110 ** Close all cursors.
2111 **
2112 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
2113 ** cell array. This is necessary as the memory cell array may contain
2114 ** pointers to VdbeFrame objects, which may in turn contain pointers to
2115 ** open cursors.
2116 */
closeAllCursors(Vdbe * p)2117 static void closeAllCursors(Vdbe *p){
2118   if( p->pFrame ){
2119     VdbeFrame *pFrame;
2120     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
2121     sqlite3VdbeFrameRestore(pFrame);
2122     p->pFrame = 0;
2123     p->nFrame = 0;
2124   }
2125   assert( p->nFrame==0 );
2126   closeCursorsInFrame(p);
2127   if( p->aMem ){
2128     releaseMemArray(p->aMem, p->nMem);
2129   }
2130   while( p->pDelFrame ){
2131     VdbeFrame *pDel = p->pDelFrame;
2132     p->pDelFrame = pDel->pParent;
2133     sqlite3VdbeFrameDelete(pDel);
2134   }
2135 
2136   /* Delete any auxdata allocations made by the VM */
2137   if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
2138   assert( p->pAuxData==0 );
2139 }
2140 
2141 /*
2142 ** Clean up the VM after a single run.
2143 */
Cleanup(Vdbe * p)2144 static void Cleanup(Vdbe *p){
2145   sqlite3 *db = p->db;
2146 
2147 #ifdef SQLITE_DEBUG
2148   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
2149   ** Vdbe.aMem[] arrays have already been cleaned up.  */
2150   int i;
2151   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
2152   if( p->aMem ){
2153     for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
2154   }
2155 #endif
2156 
2157   sqlite3DbFree(db, p->zErrMsg);
2158   p->zErrMsg = 0;
2159   p->pResultSet = 0;
2160 }
2161 
2162 /*
2163 ** Set the number of result columns that will be returned by this SQL
2164 ** statement. This is now set at compile time, rather than during
2165 ** execution of the vdbe program so that sqlite3_column_count() can
2166 ** be called on an SQL statement before sqlite3_step().
2167 */
sqlite3VdbeSetNumCols(Vdbe * p,int nResColumn)2168 void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
2169   int n;
2170   sqlite3 *db = p->db;
2171 
2172   if( p->nResColumn ){
2173     releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
2174     sqlite3DbFree(db, p->aColName);
2175   }
2176   n = nResColumn*COLNAME_N;
2177   p->nResColumn = (u16)nResColumn;
2178   p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
2179   if( p->aColName==0 ) return;
2180   initMemArray(p->aColName, n, db, MEM_Null);
2181 }
2182 
2183 /*
2184 ** Set the name of the idx'th column to be returned by the SQL statement.
2185 ** zName must be a pointer to a nul terminated string.
2186 **
2187 ** This call must be made after a call to sqlite3VdbeSetNumCols().
2188 **
2189 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
2190 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
2191 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
2192 */
sqlite3VdbeSetColName(Vdbe * p,int idx,int var,const char * zName,void (* xDel)(void *))2193 int sqlite3VdbeSetColName(
2194   Vdbe *p,                         /* Vdbe being configured */
2195   int idx,                         /* Index of column zName applies to */
2196   int var,                         /* One of the COLNAME_* constants */
2197   const char *zName,               /* Pointer to buffer containing name */
2198   void (*xDel)(void*)              /* Memory management strategy for zName */
2199 ){
2200   int rc;
2201   Mem *pColName;
2202   assert( idx<p->nResColumn );
2203   assert( var<COLNAME_N );
2204   if( p->db->mallocFailed ){
2205     assert( !zName || xDel!=SQLITE_DYNAMIC );
2206     return SQLITE_NOMEM_BKPT;
2207   }
2208   assert( p->aColName!=0 );
2209   pColName = &(p->aColName[idx+var*p->nResColumn]);
2210   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
2211   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
2212   return rc;
2213 }
2214 
2215 /*
2216 ** A read or write transaction may or may not be active on database handle
2217 ** db. If a transaction is active, commit it. If there is a
2218 ** write-transaction spanning more than one database file, this routine
2219 ** takes care of the master journal trickery.
2220 */
vdbeCommit(sqlite3 * db,Vdbe * p)2221 static int vdbeCommit(sqlite3 *db, Vdbe *p){
2222   int i;
2223   int nTrans = 0;  /* Number of databases with an active write-transaction
2224                    ** that are candidates for a two-phase commit using a
2225                    ** master-journal */
2226   int rc = SQLITE_OK;
2227   int needXcommit = 0;
2228 
2229 #ifdef SQLITE_OMIT_VIRTUALTABLE
2230   /* With this option, sqlite3VtabSync() is defined to be simply
2231   ** SQLITE_OK so p is not used.
2232   */
2233   UNUSED_PARAMETER(p);
2234 #endif
2235 
2236   /* Before doing anything else, call the xSync() callback for any
2237   ** virtual module tables written in this transaction. This has to
2238   ** be done before determining whether a master journal file is
2239   ** required, as an xSync() callback may add an attached database
2240   ** to the transaction.
2241   */
2242   rc = sqlite3VtabSync(db, p);
2243 
2244   /* This loop determines (a) if the commit hook should be invoked and
2245   ** (b) how many database files have open write transactions, not
2246   ** including the temp database. (b) is important because if more than
2247   ** one database file has an open write transaction, a master journal
2248   ** file is required for an atomic commit.
2249   */
2250   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2251     Btree *pBt = db->aDb[i].pBt;
2252     if( sqlite3BtreeIsInTrans(pBt) ){
2253       /* Whether or not a database might need a master journal depends upon
2254       ** its journal mode (among other things).  This matrix determines which
2255       ** journal modes use a master journal and which do not */
2256       static const u8 aMJNeeded[] = {
2257         /* DELETE   */  1,
2258         /* PERSIST   */ 1,
2259         /* OFF       */ 0,
2260         /* TRUNCATE  */ 1,
2261         /* MEMORY    */ 0,
2262         /* WAL       */ 0
2263       };
2264       Pager *pPager;   /* Pager associated with pBt */
2265       needXcommit = 1;
2266       sqlite3BtreeEnter(pBt);
2267       pPager = sqlite3BtreePager(pBt);
2268       if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
2269        && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
2270       ){
2271         assert( i!=1 );
2272         nTrans++;
2273       }
2274       rc = sqlite3PagerExclusiveLock(pPager);
2275       sqlite3BtreeLeave(pBt);
2276     }
2277   }
2278   if( rc!=SQLITE_OK ){
2279     return rc;
2280   }
2281 
2282   /* If there are any write-transactions at all, invoke the commit hook */
2283   if( needXcommit && db->xCommitCallback ){
2284     rc = db->xCommitCallback(db->pCommitArg);
2285     if( rc ){
2286       return SQLITE_CONSTRAINT_COMMITHOOK;
2287     }
2288   }
2289 
2290   /* The simple case - no more than one database file (not counting the
2291   ** TEMP database) has a transaction active.   There is no need for the
2292   ** master-journal.
2293   **
2294   ** If the return value of sqlite3BtreeGetFilename() is a zero length
2295   ** string, it means the main database is :memory: or a temp file.  In
2296   ** that case we do not support atomic multi-file commits, so use the
2297   ** simple case then too.
2298   */
2299   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
2300    || nTrans<=1
2301   ){
2302     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2303       Btree *pBt = db->aDb[i].pBt;
2304       if( pBt ){
2305         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
2306       }
2307     }
2308 
2309     /* Do the commit only if all databases successfully complete phase 1.
2310     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
2311     ** IO error while deleting or truncating a journal file. It is unlikely,
2312     ** but could happen. In this case abandon processing and return the error.
2313     */
2314     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2315       Btree *pBt = db->aDb[i].pBt;
2316       if( pBt ){
2317         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
2318       }
2319     }
2320     if( rc==SQLITE_OK ){
2321       sqlite3VtabCommit(db);
2322     }
2323   }
2324 
2325   /* The complex case - There is a multi-file write-transaction active.
2326   ** This requires a master journal file to ensure the transaction is
2327   ** committed atomically.
2328   */
2329 #ifndef SQLITE_OMIT_DISKIO
2330   else{
2331     sqlite3_vfs *pVfs = db->pVfs;
2332     char *zMaster = 0;   /* File-name for the master journal */
2333     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
2334     sqlite3_file *pMaster = 0;
2335     i64 offset = 0;
2336     int res;
2337     int retryCount = 0;
2338     int nMainFile;
2339 
2340     /* Select a master journal file name */
2341     nMainFile = sqlite3Strlen30(zMainFile);
2342     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
2343     if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
2344     do {
2345       u32 iRandom;
2346       if( retryCount ){
2347         if( retryCount>100 ){
2348           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
2349           sqlite3OsDelete(pVfs, zMaster, 0);
2350           break;
2351         }else if( retryCount==1 ){
2352           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
2353         }
2354       }
2355       retryCount++;
2356       sqlite3_randomness(sizeof(iRandom), &iRandom);
2357       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
2358                                (iRandom>>8)&0xffffff, iRandom&0xff);
2359       /* The antipenultimate character of the master journal name must
2360       ** be "9" to avoid name collisions when using 8+3 filenames. */
2361       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
2362       sqlite3FileSuffix3(zMainFile, zMaster);
2363       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
2364     }while( rc==SQLITE_OK && res );
2365     if( rc==SQLITE_OK ){
2366       /* Open the master journal. */
2367       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
2368           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
2369           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
2370       );
2371     }
2372     if( rc!=SQLITE_OK ){
2373       sqlite3DbFree(db, zMaster);
2374       return rc;
2375     }
2376 
2377     /* Write the name of each database file in the transaction into the new
2378     ** master journal file. If an error occurs at this point close
2379     ** and delete the master journal file. All the individual journal files
2380     ** still have 'null' as the master journal pointer, so they will roll
2381     ** back independently if a failure occurs.
2382     */
2383     for(i=0; i<db->nDb; i++){
2384       Btree *pBt = db->aDb[i].pBt;
2385       if( sqlite3BtreeIsInTrans(pBt) ){
2386         char const *zFile = sqlite3BtreeGetJournalname(pBt);
2387         if( zFile==0 ){
2388           continue;  /* Ignore TEMP and :memory: databases */
2389         }
2390         assert( zFile[0]!=0 );
2391         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
2392         offset += sqlite3Strlen30(zFile)+1;
2393         if( rc!=SQLITE_OK ){
2394           sqlite3OsCloseFree(pMaster);
2395           sqlite3OsDelete(pVfs, zMaster, 0);
2396           sqlite3DbFree(db, zMaster);
2397           return rc;
2398         }
2399       }
2400     }
2401 
2402     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
2403     ** flag is set this is not required.
2404     */
2405     if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
2406      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
2407     ){
2408       sqlite3OsCloseFree(pMaster);
2409       sqlite3OsDelete(pVfs, zMaster, 0);
2410       sqlite3DbFree(db, zMaster);
2411       return rc;
2412     }
2413 
2414     /* Sync all the db files involved in the transaction. The same call
2415     ** sets the master journal pointer in each individual journal. If
2416     ** an error occurs here, do not delete the master journal file.
2417     **
2418     ** If the error occurs during the first call to
2419     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
2420     ** master journal file will be orphaned. But we cannot delete it,
2421     ** in case the master journal file name was written into the journal
2422     ** file before the failure occurred.
2423     */
2424     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2425       Btree *pBt = db->aDb[i].pBt;
2426       if( pBt ){
2427         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
2428       }
2429     }
2430     sqlite3OsCloseFree(pMaster);
2431     assert( rc!=SQLITE_BUSY );
2432     if( rc!=SQLITE_OK ){
2433       sqlite3DbFree(db, zMaster);
2434       return rc;
2435     }
2436 
2437     /* Delete the master journal file. This commits the transaction. After
2438     ** doing this the directory is synced again before any individual
2439     ** transaction files are deleted.
2440     */
2441     rc = sqlite3OsDelete(pVfs, zMaster, 1);
2442     sqlite3DbFree(db, zMaster);
2443     zMaster = 0;
2444     if( rc ){
2445       return rc;
2446     }
2447 
2448     /* All files and directories have already been synced, so the following
2449     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
2450     ** deleting or truncating journals. If something goes wrong while
2451     ** this is happening we don't really care. The integrity of the
2452     ** transaction is already guaranteed, but some stray 'cold' journals
2453     ** may be lying around. Returning an error code won't help matters.
2454     */
2455     disable_simulated_io_errors();
2456     sqlite3BeginBenignMalloc();
2457     for(i=0; i<db->nDb; i++){
2458       Btree *pBt = db->aDb[i].pBt;
2459       if( pBt ){
2460         sqlite3BtreeCommitPhaseTwo(pBt, 1);
2461       }
2462     }
2463     sqlite3EndBenignMalloc();
2464     enable_simulated_io_errors();
2465 
2466     sqlite3VtabCommit(db);
2467   }
2468 #endif
2469 
2470   return rc;
2471 }
2472 
2473 /*
2474 ** This routine checks that the sqlite3.nVdbeActive count variable
2475 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
2476 ** currently active. An assertion fails if the two counts do not match.
2477 ** This is an internal self-check only - it is not an essential processing
2478 ** step.
2479 **
2480 ** This is a no-op if NDEBUG is defined.
2481 */
2482 #ifndef NDEBUG
checkActiveVdbeCnt(sqlite3 * db)2483 static void checkActiveVdbeCnt(sqlite3 *db){
2484   Vdbe *p;
2485   int cnt = 0;
2486   int nWrite = 0;
2487   int nRead = 0;
2488   p = db->pVdbe;
2489   while( p ){
2490     if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
2491       cnt++;
2492       if( p->readOnly==0 ) nWrite++;
2493       if( p->bIsReader ) nRead++;
2494     }
2495     p = p->pNext;
2496   }
2497   assert( cnt==db->nVdbeActive );
2498   assert( nWrite==db->nVdbeWrite );
2499   assert( nRead==db->nVdbeRead );
2500 }
2501 #else
2502 #define checkActiveVdbeCnt(x)
2503 #endif
2504 
2505 /*
2506 ** If the Vdbe passed as the first argument opened a statement-transaction,
2507 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
2508 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
2509 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
2510 ** statement transaction is committed.
2511 **
2512 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
2513 ** Otherwise SQLITE_OK.
2514 */
vdbeCloseStatement(Vdbe * p,int eOp)2515 static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
2516   sqlite3 *const db = p->db;
2517   int rc = SQLITE_OK;
2518   int i;
2519   const int iSavepoint = p->iStatement-1;
2520 
2521   assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
2522   assert( db->nStatement>0 );
2523   assert( p->iStatement==(db->nStatement+db->nSavepoint) );
2524 
2525   for(i=0; i<db->nDb; i++){
2526     int rc2 = SQLITE_OK;
2527     Btree *pBt = db->aDb[i].pBt;
2528     if( pBt ){
2529       if( eOp==SAVEPOINT_ROLLBACK ){
2530         rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
2531       }
2532       if( rc2==SQLITE_OK ){
2533         rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
2534       }
2535       if( rc==SQLITE_OK ){
2536         rc = rc2;
2537       }
2538     }
2539   }
2540   db->nStatement--;
2541   p->iStatement = 0;
2542 
2543   if( rc==SQLITE_OK ){
2544     if( eOp==SAVEPOINT_ROLLBACK ){
2545       rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
2546     }
2547     if( rc==SQLITE_OK ){
2548       rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
2549     }
2550   }
2551 
2552   /* If the statement transaction is being rolled back, also restore the
2553   ** database handles deferred constraint counter to the value it had when
2554   ** the statement transaction was opened.  */
2555   if( eOp==SAVEPOINT_ROLLBACK ){
2556     db->nDeferredCons = p->nStmtDefCons;
2557     db->nDeferredImmCons = p->nStmtDefImmCons;
2558   }
2559   return rc;
2560 }
sqlite3VdbeCloseStatement(Vdbe * p,int eOp)2561 int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
2562   if( p->db->nStatement && p->iStatement ){
2563     return vdbeCloseStatement(p, eOp);
2564   }
2565   return SQLITE_OK;
2566 }
2567 
2568 
2569 /*
2570 ** This function is called when a transaction opened by the database
2571 ** handle associated with the VM passed as an argument is about to be
2572 ** committed. If there are outstanding deferred foreign key constraint
2573 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
2574 **
2575 ** If there are outstanding FK violations and this function returns
2576 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
2577 ** and write an error message to it. Then return SQLITE_ERROR.
2578 */
2579 #ifndef SQLITE_OMIT_FOREIGN_KEY
sqlite3VdbeCheckFk(Vdbe * p,int deferred)2580 int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
2581   sqlite3 *db = p->db;
2582   if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
2583    || (!deferred && p->nFkConstraint>0)
2584   ){
2585     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
2586     p->errorAction = OE_Abort;
2587     sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
2588     return SQLITE_ERROR;
2589   }
2590   return SQLITE_OK;
2591 }
2592 #endif
2593 
2594 /*
2595 ** This routine is called the when a VDBE tries to halt.  If the VDBE
2596 ** has made changes and is in autocommit mode, then commit those
2597 ** changes.  If a rollback is needed, then do the rollback.
2598 **
2599 ** This routine is the only way to move the state of a VM from
2600 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
2601 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
2602 **
2603 ** Return an error code.  If the commit could not complete because of
2604 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
2605 ** means the close did not happen and needs to be repeated.
2606 */
sqlite3VdbeHalt(Vdbe * p)2607 int sqlite3VdbeHalt(Vdbe *p){
2608   int rc;                         /* Used to store transient return codes */
2609   sqlite3 *db = p->db;
2610 
2611   /* This function contains the logic that determines if a statement or
2612   ** transaction will be committed or rolled back as a result of the
2613   ** execution of this virtual machine.
2614   **
2615   ** If any of the following errors occur:
2616   **
2617   **     SQLITE_NOMEM
2618   **     SQLITE_IOERR
2619   **     SQLITE_FULL
2620   **     SQLITE_INTERRUPT
2621   **
2622   ** Then the internal cache might have been left in an inconsistent
2623   ** state.  We need to rollback the statement transaction, if there is
2624   ** one, or the complete transaction if there is no statement transaction.
2625   */
2626 
2627   if( p->magic!=VDBE_MAGIC_RUN ){
2628     return SQLITE_OK;
2629   }
2630   if( db->mallocFailed ){
2631     p->rc = SQLITE_NOMEM_BKPT;
2632   }
2633   closeAllCursors(p);
2634   checkActiveVdbeCnt(db);
2635 
2636   /* No commit or rollback needed if the program never started or if the
2637   ** SQL statement does not read or write a database file.  */
2638   if( p->pc>=0 && p->bIsReader ){
2639     int mrc;   /* Primary error code from p->rc */
2640     int eStatementOp = 0;
2641     int isSpecialError;            /* Set to true if a 'special' error */
2642 
2643     /* Lock all btrees used by the statement */
2644     sqlite3VdbeEnter(p);
2645 
2646     /* Check for one of the special errors */
2647     mrc = p->rc & 0xff;
2648     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
2649                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
2650     if( isSpecialError ){
2651       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
2652       ** no rollback is necessary. Otherwise, at least a savepoint
2653       ** transaction must be rolled back to restore the database to a
2654       ** consistent state.
2655       **
2656       ** Even if the statement is read-only, it is important to perform
2657       ** a statement or transaction rollback operation. If the error
2658       ** occurred while writing to the journal, sub-journal or database
2659       ** file as part of an effort to free up cache space (see function
2660       ** pagerStress() in pager.c), the rollback is required to restore
2661       ** the pager to a consistent state.
2662       */
2663       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
2664         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
2665           eStatementOp = SAVEPOINT_ROLLBACK;
2666         }else{
2667           /* We are forced to roll back the active transaction. Before doing
2668           ** so, abort any other statements this handle currently has active.
2669           */
2670           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2671           sqlite3CloseSavepoints(db);
2672           db->autoCommit = 1;
2673           p->nChange = 0;
2674         }
2675       }
2676     }
2677 
2678     /* Check for immediate foreign key violations. */
2679     if( p->rc==SQLITE_OK ){
2680       sqlite3VdbeCheckFk(p, 0);
2681     }
2682 
2683     /* If the auto-commit flag is set and this is the only active writer
2684     ** VM, then we do either a commit or rollback of the current transaction.
2685     **
2686     ** Note: This block also runs if one of the special errors handled
2687     ** above has occurred.
2688     */
2689     if( !sqlite3VtabInSync(db)
2690      && db->autoCommit
2691      && db->nVdbeWrite==(p->readOnly==0)
2692     ){
2693       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
2694         rc = sqlite3VdbeCheckFk(p, 1);
2695         if( rc!=SQLITE_OK ){
2696           if( NEVER(p->readOnly) ){
2697             sqlite3VdbeLeave(p);
2698             return SQLITE_ERROR;
2699           }
2700           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
2701         }else{
2702           /* The auto-commit flag is true, the vdbe program was successful
2703           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
2704           ** key constraints to hold up the transaction. This means a commit
2705           ** is required. */
2706           rc = vdbeCommit(db, p);
2707         }
2708         if( rc==SQLITE_BUSY && p->readOnly ){
2709           sqlite3VdbeLeave(p);
2710           return SQLITE_BUSY;
2711         }else if( rc!=SQLITE_OK ){
2712           p->rc = rc;
2713           sqlite3RollbackAll(db, SQLITE_OK);
2714           p->nChange = 0;
2715         }else{
2716           db->nDeferredCons = 0;
2717           db->nDeferredImmCons = 0;
2718           db->flags &= ~SQLITE_DeferFKs;
2719           sqlite3CommitInternalChanges(db);
2720         }
2721       }else{
2722         sqlite3RollbackAll(db, SQLITE_OK);
2723         p->nChange = 0;
2724       }
2725       db->nStatement = 0;
2726     }else if( eStatementOp==0 ){
2727       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
2728         eStatementOp = SAVEPOINT_RELEASE;
2729       }else if( p->errorAction==OE_Abort ){
2730         eStatementOp = SAVEPOINT_ROLLBACK;
2731       }else{
2732         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2733         sqlite3CloseSavepoints(db);
2734         db->autoCommit = 1;
2735         p->nChange = 0;
2736       }
2737     }
2738 
2739     /* If eStatementOp is non-zero, then a statement transaction needs to
2740     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
2741     ** do so. If this operation returns an error, and the current statement
2742     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
2743     ** current statement error code.
2744     */
2745     if( eStatementOp ){
2746       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
2747       if( rc ){
2748         if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
2749           p->rc = rc;
2750           sqlite3DbFree(db, p->zErrMsg);
2751           p->zErrMsg = 0;
2752         }
2753         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2754         sqlite3CloseSavepoints(db);
2755         db->autoCommit = 1;
2756         p->nChange = 0;
2757       }
2758     }
2759 
2760     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
2761     ** has been rolled back, update the database connection change-counter.
2762     */
2763     if( p->changeCntOn ){
2764       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
2765         sqlite3VdbeSetChanges(db, p->nChange);
2766       }else{
2767         sqlite3VdbeSetChanges(db, 0);
2768       }
2769       p->nChange = 0;
2770     }
2771 
2772     /* Release the locks */
2773     sqlite3VdbeLeave(p);
2774   }
2775 
2776   /* We have successfully halted and closed the VM.  Record this fact. */
2777   if( p->pc>=0 ){
2778     db->nVdbeActive--;
2779     if( !p->readOnly ) db->nVdbeWrite--;
2780     if( p->bIsReader ) db->nVdbeRead--;
2781     assert( db->nVdbeActive>=db->nVdbeRead );
2782     assert( db->nVdbeRead>=db->nVdbeWrite );
2783     assert( db->nVdbeWrite>=0 );
2784   }
2785   p->magic = VDBE_MAGIC_HALT;
2786   checkActiveVdbeCnt(db);
2787   if( db->mallocFailed ){
2788     p->rc = SQLITE_NOMEM_BKPT;
2789   }
2790 
2791   /* If the auto-commit flag is set to true, then any locks that were held
2792   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
2793   ** to invoke any required unlock-notify callbacks.
2794   */
2795   if( db->autoCommit ){
2796     sqlite3ConnectionUnlocked(db);
2797   }
2798 
2799   assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
2800   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
2801 }
2802 
2803 
2804 /*
2805 ** Each VDBE holds the result of the most recent sqlite3_step() call
2806 ** in p->rc.  This routine sets that result back to SQLITE_OK.
2807 */
sqlite3VdbeResetStepResult(Vdbe * p)2808 void sqlite3VdbeResetStepResult(Vdbe *p){
2809   p->rc = SQLITE_OK;
2810 }
2811 
2812 /*
2813 ** Copy the error code and error message belonging to the VDBE passed
2814 ** as the first argument to its database handle (so that they will be
2815 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
2816 **
2817 ** This function does not clear the VDBE error code or message, just
2818 ** copies them to the database handle.
2819 */
sqlite3VdbeTransferError(Vdbe * p)2820 int sqlite3VdbeTransferError(Vdbe *p){
2821   sqlite3 *db = p->db;
2822   int rc = p->rc;
2823   if( p->zErrMsg ){
2824     db->bBenignMalloc++;
2825     sqlite3BeginBenignMalloc();
2826     if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
2827     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
2828     sqlite3EndBenignMalloc();
2829     db->bBenignMalloc--;
2830   }else if( db->pErr ){
2831     sqlite3ValueSetNull(db->pErr);
2832   }
2833   db->errCode = rc;
2834   return rc;
2835 }
2836 
2837 #ifdef SQLITE_ENABLE_SQLLOG
2838 /*
2839 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
2840 ** invoke it.
2841 */
vdbeInvokeSqllog(Vdbe * v)2842 static void vdbeInvokeSqllog(Vdbe *v){
2843   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
2844     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
2845     assert( v->db->init.busy==0 );
2846     if( zExpanded ){
2847       sqlite3GlobalConfig.xSqllog(
2848           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
2849       );
2850       sqlite3DbFree(v->db, zExpanded);
2851     }
2852   }
2853 }
2854 #else
2855 # define vdbeInvokeSqllog(x)
2856 #endif
2857 
2858 /*
2859 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
2860 ** Write any error messages into *pzErrMsg.  Return the result code.
2861 **
2862 ** After this routine is run, the VDBE should be ready to be executed
2863 ** again.
2864 **
2865 ** To look at it another way, this routine resets the state of the
2866 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
2867 ** VDBE_MAGIC_INIT.
2868 */
sqlite3VdbeReset(Vdbe * p)2869 int sqlite3VdbeReset(Vdbe *p){
2870   sqlite3 *db;
2871   db = p->db;
2872 
2873   /* If the VM did not run to completion or if it encountered an
2874   ** error, then it might not have been halted properly.  So halt
2875   ** it now.
2876   */
2877   sqlite3VdbeHalt(p);
2878 
2879   /* If the VDBE has be run even partially, then transfer the error code
2880   ** and error message from the VDBE into the main database structure.  But
2881   ** if the VDBE has just been set to run but has not actually executed any
2882   ** instructions yet, leave the main database error information unchanged.
2883   */
2884   if( p->pc>=0 ){
2885     vdbeInvokeSqllog(p);
2886     sqlite3VdbeTransferError(p);
2887     sqlite3DbFree(db, p->zErrMsg);
2888     p->zErrMsg = 0;
2889     if( p->runOnlyOnce ) p->expired = 1;
2890   }else if( p->rc && p->expired ){
2891     /* The expired flag was set on the VDBE before the first call
2892     ** to sqlite3_step(). For consistency (since sqlite3_step() was
2893     ** called), set the database error in this case as well.
2894     */
2895     sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
2896     sqlite3DbFree(db, p->zErrMsg);
2897     p->zErrMsg = 0;
2898   }
2899 
2900   /* Reclaim all memory used by the VDBE
2901   */
2902   Cleanup(p);
2903 
2904   /* Save profiling information from this VDBE run.
2905   */
2906 #ifdef VDBE_PROFILE
2907   {
2908     FILE *out = fopen("vdbe_profile.out", "a");
2909     if( out ){
2910       int i;
2911       fprintf(out, "---- ");
2912       for(i=0; i<p->nOp; i++){
2913         fprintf(out, "%02x", p->aOp[i].opcode);
2914       }
2915       fprintf(out, "\n");
2916       if( p->zSql ){
2917         char c, pc = 0;
2918         fprintf(out, "-- ");
2919         for(i=0; (c = p->zSql[i])!=0; i++){
2920           if( pc=='\n' ) fprintf(out, "-- ");
2921           putc(c, out);
2922           pc = c;
2923         }
2924         if( pc!='\n' ) fprintf(out, "\n");
2925       }
2926       for(i=0; i<p->nOp; i++){
2927         char zHdr[100];
2928         sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
2929            p->aOp[i].cnt,
2930            p->aOp[i].cycles,
2931            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
2932         );
2933         fprintf(out, "%s", zHdr);
2934         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
2935       }
2936       fclose(out);
2937     }
2938   }
2939 #endif
2940   p->magic = VDBE_MAGIC_RESET;
2941   return p->rc & db->errMask;
2942 }
2943 
2944 /*
2945 ** Clean up and delete a VDBE after execution.  Return an integer which is
2946 ** the result code.  Write any error message text into *pzErrMsg.
2947 */
sqlite3VdbeFinalize(Vdbe * p)2948 int sqlite3VdbeFinalize(Vdbe *p){
2949   int rc = SQLITE_OK;
2950   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
2951     rc = sqlite3VdbeReset(p);
2952     assert( (rc & p->db->errMask)==rc );
2953   }
2954   sqlite3VdbeDelete(p);
2955   return rc;
2956 }
2957 
2958 /*
2959 ** If parameter iOp is less than zero, then invoke the destructor for
2960 ** all auxiliary data pointers currently cached by the VM passed as
2961 ** the first argument.
2962 **
2963 ** Or, if iOp is greater than or equal to zero, then the destructor is
2964 ** only invoked for those auxiliary data pointers created by the user
2965 ** function invoked by the OP_Function opcode at instruction iOp of
2966 ** VM pVdbe, and only then if:
2967 **
2968 **    * the associated function parameter is the 32nd or later (counting
2969 **      from left to right), or
2970 **
2971 **    * the corresponding bit in argument mask is clear (where the first
2972 **      function parameter corresponds to bit 0 etc.).
2973 */
sqlite3VdbeDeleteAuxData(sqlite3 * db,AuxData ** pp,int iOp,int mask)2974 void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
2975   while( *pp ){
2976     AuxData *pAux = *pp;
2977     if( (iOp<0)
2978      || (pAux->iAuxOp==iOp
2979           && pAux->iAuxArg>=0
2980           && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
2981     ){
2982       testcase( pAux->iAuxArg==31 );
2983       if( pAux->xDeleteAux ){
2984         pAux->xDeleteAux(pAux->pAux);
2985       }
2986       *pp = pAux->pNextAux;
2987       sqlite3DbFree(db, pAux);
2988     }else{
2989       pp= &pAux->pNextAux;
2990     }
2991   }
2992 }
2993 
2994 /*
2995 ** Free all memory associated with the Vdbe passed as the second argument,
2996 ** except for object itself, which is preserved.
2997 **
2998 ** The difference between this function and sqlite3VdbeDelete() is that
2999 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
3000 ** the database connection and frees the object itself.
3001 */
sqlite3VdbeClearObject(sqlite3 * db,Vdbe * p)3002 void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
3003   SubProgram *pSub, *pNext;
3004   assert( p->db==0 || p->db==db );
3005   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
3006   for(pSub=p->pProgram; pSub; pSub=pNext){
3007     pNext = pSub->pNext;
3008     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
3009     sqlite3DbFree(db, pSub);
3010   }
3011   if( p->magic!=VDBE_MAGIC_INIT ){
3012     releaseMemArray(p->aVar, p->nVar);
3013     sqlite3DbFree(db, p->pVList);
3014     sqlite3DbFree(db, p->pFree);
3015   }
3016   vdbeFreeOpArray(db, p->aOp, p->nOp);
3017   sqlite3DbFree(db, p->aColName);
3018   sqlite3DbFree(db, p->zSql);
3019 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3020   {
3021     int i;
3022     for(i=0; i<p->nScan; i++){
3023       sqlite3DbFree(db, p->aScan[i].zName);
3024     }
3025     sqlite3DbFree(db, p->aScan);
3026   }
3027 #endif
3028 }
3029 
3030 /*
3031 ** Delete an entire VDBE.
3032 */
sqlite3VdbeDelete(Vdbe * p)3033 void sqlite3VdbeDelete(Vdbe *p){
3034   sqlite3 *db;
3035 
3036   if( NEVER(p==0) ) return;
3037   db = p->db;
3038   assert( sqlite3_mutex_held(db->mutex) );
3039   sqlite3VdbeClearObject(db, p);
3040   if( p->pPrev ){
3041     p->pPrev->pNext = p->pNext;
3042   }else{
3043     assert( db->pVdbe==p );
3044     db->pVdbe = p->pNext;
3045   }
3046   if( p->pNext ){
3047     p->pNext->pPrev = p->pPrev;
3048   }
3049   p->magic = VDBE_MAGIC_DEAD;
3050   p->db = 0;
3051   sqlite3DbFreeNN(db, p);
3052 }
3053 
3054 /*
3055 ** The cursor "p" has a pending seek operation that has not yet been
3056 ** carried out.  Seek the cursor now.  If an error occurs, return
3057 ** the appropriate error code.
3058 */
handleDeferredMoveto(VdbeCursor * p)3059 static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
3060   int res, rc;
3061 #ifdef SQLITE_TEST
3062   extern int sqlite3_search_count;
3063 #endif
3064   assert( p->deferredMoveto );
3065   assert( p->isTable );
3066   assert( p->eCurType==CURTYPE_BTREE );
3067   rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
3068   if( rc ) return rc;
3069   if( res!=0 ) return SQLITE_CORRUPT_BKPT;
3070 #ifdef SQLITE_TEST
3071   sqlite3_search_count++;
3072 #endif
3073   p->deferredMoveto = 0;
3074   p->cacheStatus = CACHE_STALE;
3075   return SQLITE_OK;
3076 }
3077 
3078 /*
3079 ** Something has moved cursor "p" out of place.  Maybe the row it was
3080 ** pointed to was deleted out from under it.  Or maybe the btree was
3081 ** rebalanced.  Whatever the cause, try to restore "p" to the place it
3082 ** is supposed to be pointing.  If the row was deleted out from under the
3083 ** cursor, set the cursor to point to a NULL row.
3084 */
handleMovedCursor(VdbeCursor * p)3085 static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
3086   int isDifferentRow, rc;
3087   assert( p->eCurType==CURTYPE_BTREE );
3088   assert( p->uc.pCursor!=0 );
3089   assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
3090   rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
3091   p->cacheStatus = CACHE_STALE;
3092   if( isDifferentRow ) p->nullRow = 1;
3093   return rc;
3094 }
3095 
3096 /*
3097 ** Check to ensure that the cursor is valid.  Restore the cursor
3098 ** if need be.  Return any I/O error from the restore operation.
3099 */
sqlite3VdbeCursorRestore(VdbeCursor * p)3100 int sqlite3VdbeCursorRestore(VdbeCursor *p){
3101   assert( p->eCurType==CURTYPE_BTREE );
3102   if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
3103     return handleMovedCursor(p);
3104   }
3105   return SQLITE_OK;
3106 }
3107 
3108 /*
3109 ** Make sure the cursor p is ready to read or write the row to which it
3110 ** was last positioned.  Return an error code if an OOM fault or I/O error
3111 ** prevents us from positioning the cursor to its correct position.
3112 **
3113 ** If a MoveTo operation is pending on the given cursor, then do that
3114 ** MoveTo now.  If no move is pending, check to see if the row has been
3115 ** deleted out from under the cursor and if it has, mark the row as
3116 ** a NULL row.
3117 **
3118 ** If the cursor is already pointing to the correct row and that row has
3119 ** not been deleted out from under the cursor, then this routine is a no-op.
3120 */
sqlite3VdbeCursorMoveto(VdbeCursor ** pp,int * piCol)3121 int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
3122   VdbeCursor *p = *pp;
3123   if( p->eCurType==CURTYPE_BTREE ){
3124     if( p->deferredMoveto ){
3125       int iMap;
3126       if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
3127         *pp = p->pAltCursor;
3128         *piCol = iMap - 1;
3129         return SQLITE_OK;
3130       }
3131       return handleDeferredMoveto(p);
3132     }
3133     if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
3134       return handleMovedCursor(p);
3135     }
3136   }
3137   return SQLITE_OK;
3138 }
3139 
3140 /*
3141 ** The following functions:
3142 **
3143 ** sqlite3VdbeSerialType()
3144 ** sqlite3VdbeSerialTypeLen()
3145 ** sqlite3VdbeSerialLen()
3146 ** sqlite3VdbeSerialPut()
3147 ** sqlite3VdbeSerialGet()
3148 **
3149 ** encapsulate the code that serializes values for storage in SQLite
3150 ** data and index records. Each serialized value consists of a
3151 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
3152 ** integer, stored as a varint.
3153 **
3154 ** In an SQLite index record, the serial type is stored directly before
3155 ** the blob of data that it corresponds to. In a table record, all serial
3156 ** types are stored at the start of the record, and the blobs of data at
3157 ** the end. Hence these functions allow the caller to handle the
3158 ** serial-type and data blob separately.
3159 **
3160 ** The following table describes the various storage classes for data:
3161 **
3162 **   serial type        bytes of data      type
3163 **   --------------     ---------------    ---------------
3164 **      0                     0            NULL
3165 **      1                     1            signed integer
3166 **      2                     2            signed integer
3167 **      3                     3            signed integer
3168 **      4                     4            signed integer
3169 **      5                     6            signed integer
3170 **      6                     8            signed integer
3171 **      7                     8            IEEE float
3172 **      8                     0            Integer constant 0
3173 **      9                     0            Integer constant 1
3174 **     10,11                               reserved for expansion
3175 **    N>=12 and even       (N-12)/2        BLOB
3176 **    N>=13 and odd        (N-13)/2        text
3177 **
3178 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
3179 ** of SQLite will not understand those serial types.
3180 */
3181 
3182 /*
3183 ** Return the serial-type for the value stored in pMem.
3184 */
sqlite3VdbeSerialType(Mem * pMem,int file_format,u32 * pLen)3185 u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
3186   int flags = pMem->flags;
3187   u32 n;
3188 
3189   assert( pLen!=0 );
3190   if( flags&MEM_Null ){
3191     *pLen = 0;
3192     return 0;
3193   }
3194   if( flags&MEM_Int ){
3195     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
3196 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
3197     i64 i = pMem->u.i;
3198     u64 u;
3199     if( i<0 ){
3200       u = ~i;
3201     }else{
3202       u = i;
3203     }
3204     if( u<=127 ){
3205       if( (i&1)==i && file_format>=4 ){
3206         *pLen = 0;
3207         return 8+(u32)u;
3208       }else{
3209         *pLen = 1;
3210         return 1;
3211       }
3212     }
3213     if( u<=32767 ){ *pLen = 2; return 2; }
3214     if( u<=8388607 ){ *pLen = 3; return 3; }
3215     if( u<=2147483647 ){ *pLen = 4; return 4; }
3216     if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
3217     *pLen = 8;
3218     return 6;
3219   }
3220   if( flags&MEM_Real ){
3221     *pLen = 8;
3222     return 7;
3223   }
3224   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
3225   assert( pMem->n>=0 );
3226   n = (u32)pMem->n;
3227   if( flags & MEM_Zero ){
3228     n += pMem->u.nZero;
3229   }
3230   *pLen = n;
3231   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
3232 }
3233 
3234 /*
3235 ** The sizes for serial types less than 128
3236 */
3237 static const u8 sqlite3SmallTypeSizes[] = {
3238         /*  0   1   2   3   4   5   6   7   8   9 */
3239 /*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
3240 /*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
3241 /*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
3242 /*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
3243 /*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
3244 /*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
3245 /*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
3246 /*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
3247 /*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
3248 /*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
3249 /* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
3250 /* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
3251 /* 120 */  54, 54, 55, 55, 56, 56, 57, 57
3252 };
3253 
3254 /*
3255 ** Return the length of the data corresponding to the supplied serial-type.
3256 */
sqlite3VdbeSerialTypeLen(u32 serial_type)3257 u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
3258   if( serial_type>=128 ){
3259     return (serial_type-12)/2;
3260   }else{
3261     assert( serial_type<12
3262             || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
3263     return sqlite3SmallTypeSizes[serial_type];
3264   }
3265 }
sqlite3VdbeOneByteSerialTypeLen(u8 serial_type)3266 u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
3267   assert( serial_type<128 );
3268   return sqlite3SmallTypeSizes[serial_type];
3269 }
3270 
3271 /*
3272 ** If we are on an architecture with mixed-endian floating
3273 ** points (ex: ARM7) then swap the lower 4 bytes with the
3274 ** upper 4 bytes.  Return the result.
3275 **
3276 ** For most architectures, this is a no-op.
3277 **
3278 ** (later):  It is reported to me that the mixed-endian problem
3279 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
3280 ** that early versions of GCC stored the two words of a 64-bit
3281 ** float in the wrong order.  And that error has been propagated
3282 ** ever since.  The blame is not necessarily with GCC, though.
3283 ** GCC might have just copying the problem from a prior compiler.
3284 ** I am also told that newer versions of GCC that follow a different
3285 ** ABI get the byte order right.
3286 **
3287 ** Developers using SQLite on an ARM7 should compile and run their
3288 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
3289 ** enabled, some asserts below will ensure that the byte order of
3290 ** floating point values is correct.
3291 **
3292 ** (2007-08-30)  Frank van Vugt has studied this problem closely
3293 ** and has send his findings to the SQLite developers.  Frank
3294 ** writes that some Linux kernels offer floating point hardware
3295 ** emulation that uses only 32-bit mantissas instead of a full
3296 ** 48-bits as required by the IEEE standard.  (This is the
3297 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
3298 ** byte swapping becomes very complicated.  To avoid problems,
3299 ** the necessary byte swapping is carried out using a 64-bit integer
3300 ** rather than a 64-bit float.  Frank assures us that the code here
3301 ** works for him.  We, the developers, have no way to independently
3302 ** verify this, but Frank seems to know what he is talking about
3303 ** so we trust him.
3304 */
3305 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
floatSwap(u64 in)3306 static u64 floatSwap(u64 in){
3307   union {
3308     u64 r;
3309     u32 i[2];
3310   } u;
3311   u32 t;
3312 
3313   u.r = in;
3314   t = u.i[0];
3315   u.i[0] = u.i[1];
3316   u.i[1] = t;
3317   return u.r;
3318 }
3319 # define swapMixedEndianFloat(X)  X = floatSwap(X)
3320 #else
3321 # define swapMixedEndianFloat(X)
3322 #endif
3323 
3324 /*
3325 ** Write the serialized data blob for the value stored in pMem into
3326 ** buf. It is assumed that the caller has allocated sufficient space.
3327 ** Return the number of bytes written.
3328 **
3329 ** nBuf is the amount of space left in buf[].  The caller is responsible
3330 ** for allocating enough space to buf[] to hold the entire field, exclusive
3331 ** of the pMem->u.nZero bytes for a MEM_Zero value.
3332 **
3333 ** Return the number of bytes actually written into buf[].  The number
3334 ** of bytes in the zero-filled tail is included in the return value only
3335 ** if those bytes were zeroed in buf[].
3336 */
sqlite3VdbeSerialPut(u8 * buf,Mem * pMem,u32 serial_type)3337 u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
3338   u32 len;
3339 
3340   /* Integer and Real */
3341   if( serial_type<=7 && serial_type>0 ){
3342     u64 v;
3343     u32 i;
3344     if( serial_type==7 ){
3345       assert( sizeof(v)==sizeof(pMem->u.r) );
3346       memcpy(&v, &pMem->u.r, sizeof(v));
3347       swapMixedEndianFloat(v);
3348     }else{
3349       v = pMem->u.i;
3350     }
3351     len = i = sqlite3SmallTypeSizes[serial_type];
3352     assert( i>0 );
3353     do{
3354       buf[--i] = (u8)(v&0xFF);
3355       v >>= 8;
3356     }while( i );
3357     return len;
3358   }
3359 
3360   /* String or blob */
3361   if( serial_type>=12 ){
3362     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
3363              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
3364     len = pMem->n;
3365     if( len>0 ) memcpy(buf, pMem->z, len);
3366     return len;
3367   }
3368 
3369   /* NULL or constants 0 or 1 */
3370   return 0;
3371 }
3372 
3373 /* Input "x" is a sequence of unsigned characters that represent a
3374 ** big-endian integer.  Return the equivalent native integer
3375 */
3376 #define ONE_BYTE_INT(x)    ((i8)(x)[0])
3377 #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
3378 #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
3379 #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
3380 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
3381 
3382 /*
3383 ** Deserialize the data blob pointed to by buf as serial type serial_type
3384 ** and store the result in pMem.  Return the number of bytes read.
3385 **
3386 ** This function is implemented as two separate routines for performance.
3387 ** The few cases that require local variables are broken out into a separate
3388 ** routine so that in most cases the overhead of moving the stack pointer
3389 ** is avoided.
3390 */
serialGet(const unsigned char * buf,u32 serial_type,Mem * pMem)3391 static u32 SQLITE_NOINLINE serialGet(
3392   const unsigned char *buf,     /* Buffer to deserialize from */
3393   u32 serial_type,              /* Serial type to deserialize */
3394   Mem *pMem                     /* Memory cell to write value into */
3395 ){
3396   u64 x = FOUR_BYTE_UINT(buf);
3397   u32 y = FOUR_BYTE_UINT(buf+4);
3398   x = (x<<32) + y;
3399   if( serial_type==6 ){
3400     /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
3401     ** twos-complement integer. */
3402     pMem->u.i = *(i64*)&x;
3403     pMem->flags = MEM_Int;
3404     testcase( pMem->u.i<0 );
3405   }else{
3406     /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
3407     ** floating point number. */
3408 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
3409     /* Verify that integers and floating point values use the same
3410     ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
3411     ** defined that 64-bit floating point values really are mixed
3412     ** endian.
3413     */
3414     static const u64 t1 = ((u64)0x3ff00000)<<32;
3415     static const double r1 = 1.0;
3416     u64 t2 = t1;
3417     swapMixedEndianFloat(t2);
3418     assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
3419 #endif
3420     assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
3421     swapMixedEndianFloat(x);
3422     memcpy(&pMem->u.r, &x, sizeof(x));
3423     pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
3424   }
3425   return 8;
3426 }
sqlite3VdbeSerialGet(const unsigned char * buf,u32 serial_type,Mem * pMem)3427 u32 sqlite3VdbeSerialGet(
3428   const unsigned char *buf,     /* Buffer to deserialize from */
3429   u32 serial_type,              /* Serial type to deserialize */
3430   Mem *pMem                     /* Memory cell to write value into */
3431 ){
3432   switch( serial_type ){
3433     case 10:   /* Reserved for future use */
3434     case 11:   /* Reserved for future use */
3435     case 0: {  /* Null */
3436       /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
3437       pMem->flags = MEM_Null;
3438       break;
3439     }
3440     case 1: {
3441       /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
3442       ** integer. */
3443       pMem->u.i = ONE_BYTE_INT(buf);
3444       pMem->flags = MEM_Int;
3445       testcase( pMem->u.i<0 );
3446       return 1;
3447     }
3448     case 2: { /* 2-byte signed integer */
3449       /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
3450       ** twos-complement integer. */
3451       pMem->u.i = TWO_BYTE_INT(buf);
3452       pMem->flags = MEM_Int;
3453       testcase( pMem->u.i<0 );
3454       return 2;
3455     }
3456     case 3: { /* 3-byte signed integer */
3457       /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
3458       ** twos-complement integer. */
3459       pMem->u.i = THREE_BYTE_INT(buf);
3460       pMem->flags = MEM_Int;
3461       testcase( pMem->u.i<0 );
3462       return 3;
3463     }
3464     case 4: { /* 4-byte signed integer */
3465       /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
3466       ** twos-complement integer. */
3467       pMem->u.i = FOUR_BYTE_INT(buf);
3468 #ifdef __HP_cc
3469       /* Work around a sign-extension bug in the HP compiler for HP/UX */
3470       if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
3471 #endif
3472       pMem->flags = MEM_Int;
3473       testcase( pMem->u.i<0 );
3474       return 4;
3475     }
3476     case 5: { /* 6-byte signed integer */
3477       /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
3478       ** twos-complement integer. */
3479       pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
3480       pMem->flags = MEM_Int;
3481       testcase( pMem->u.i<0 );
3482       return 6;
3483     }
3484     case 6:   /* 8-byte signed integer */
3485     case 7: { /* IEEE floating point */
3486       /* These use local variables, so do them in a separate routine
3487       ** to avoid having to move the frame pointer in the common case */
3488       return serialGet(buf,serial_type,pMem);
3489     }
3490     case 8:    /* Integer 0 */
3491     case 9: {  /* Integer 1 */
3492       /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
3493       /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
3494       pMem->u.i = serial_type-8;
3495       pMem->flags = MEM_Int;
3496       return 0;
3497     }
3498     default: {
3499       /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
3500       ** length.
3501       ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
3502       ** (N-13)/2 bytes in length. */
3503       static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
3504       pMem->z = (char *)buf;
3505       pMem->n = (serial_type-12)/2;
3506       pMem->flags = aFlag[serial_type&1];
3507       return pMem->n;
3508     }
3509   }
3510   return 0;
3511 }
3512 /*
3513 ** This routine is used to allocate sufficient space for an UnpackedRecord
3514 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
3515 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
3516 **
3517 ** The space is either allocated using sqlite3DbMallocRaw() or from within
3518 ** the unaligned buffer passed via the second and third arguments (presumably
3519 ** stack space). If the former, then *ppFree is set to a pointer that should
3520 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
3521 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
3522 ** before returning.
3523 **
3524 ** If an OOM error occurs, NULL is returned.
3525 */
sqlite3VdbeAllocUnpackedRecord(KeyInfo * pKeyInfo)3526 UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
3527   KeyInfo *pKeyInfo               /* Description of the record */
3528 ){
3529   UnpackedRecord *p;              /* Unpacked record to return */
3530   int nByte;                      /* Number of bytes required for *p */
3531   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
3532   p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
3533   if( !p ) return 0;
3534   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
3535   assert( pKeyInfo->aSortOrder!=0 );
3536   p->pKeyInfo = pKeyInfo;
3537   p->nField = pKeyInfo->nField + 1;
3538   return p;
3539 }
3540 
3541 /*
3542 ** Given the nKey-byte encoding of a record in pKey[], populate the
3543 ** UnpackedRecord structure indicated by the fourth argument with the
3544 ** contents of the decoded record.
3545 */
sqlite3VdbeRecordUnpack(KeyInfo * pKeyInfo,int nKey,const void * pKey,UnpackedRecord * p)3546 void sqlite3VdbeRecordUnpack(
3547   KeyInfo *pKeyInfo,     /* Information about the record format */
3548   int nKey,              /* Size of the binary record */
3549   const void *pKey,      /* The binary record */
3550   UnpackedRecord *p      /* Populate this structure before returning. */
3551 ){
3552   const unsigned char *aKey = (const unsigned char *)pKey;
3553   int d;
3554   u32 idx;                        /* Offset in aKey[] to read from */
3555   u16 u;                          /* Unsigned loop counter */
3556   u32 szHdr;
3557   Mem *pMem = p->aMem;
3558 
3559   p->default_rc = 0;
3560   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
3561   idx = getVarint32(aKey, szHdr);
3562   d = szHdr;
3563   u = 0;
3564   while( idx<szHdr && d<=nKey ){
3565     u32 serial_type;
3566 
3567     idx += getVarint32(&aKey[idx], serial_type);
3568     pMem->enc = pKeyInfo->enc;
3569     pMem->db = pKeyInfo->db;
3570     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
3571     pMem->szMalloc = 0;
3572     pMem->z = 0;
3573     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
3574     pMem++;
3575     if( (++u)>=p->nField ) break;
3576   }
3577   assert( u<=pKeyInfo->nField + 1 );
3578   p->nField = u;
3579 }
3580 
3581 #ifdef SQLITE_DEBUG
3582 /*
3583 ** This function compares two index or table record keys in the same way
3584 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
3585 ** this function deserializes and compares values using the
3586 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
3587 ** in assert() statements to ensure that the optimized code in
3588 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
3589 **
3590 ** Return true if the result of comparison is equivalent to desiredResult.
3591 ** Return false if there is a disagreement.
3592 */
vdbeRecordCompareDebug(int nKey1,const void * pKey1,const UnpackedRecord * pPKey2,int desiredResult)3593 static int vdbeRecordCompareDebug(
3594   int nKey1, const void *pKey1, /* Left key */
3595   const UnpackedRecord *pPKey2, /* Right key */
3596   int desiredResult             /* Correct answer */
3597 ){
3598   u32 d1;            /* Offset into aKey[] of next data element */
3599   u32 idx1;          /* Offset into aKey[] of next header element */
3600   u32 szHdr1;        /* Number of bytes in header */
3601   int i = 0;
3602   int rc = 0;
3603   const unsigned char *aKey1 = (const unsigned char *)pKey1;
3604   KeyInfo *pKeyInfo;
3605   Mem mem1;
3606 
3607   pKeyInfo = pPKey2->pKeyInfo;
3608   if( pKeyInfo->db==0 ) return 1;
3609   mem1.enc = pKeyInfo->enc;
3610   mem1.db = pKeyInfo->db;
3611   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
3612   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
3613 
3614   /* Compilers may complain that mem1.u.i is potentially uninitialized.
3615   ** We could initialize it, as shown here, to silence those complaints.
3616   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
3617   ** the unnecessary initialization has a measurable negative performance
3618   ** impact, since this routine is a very high runner.  And so, we choose
3619   ** to ignore the compiler warnings and leave this variable uninitialized.
3620   */
3621   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
3622 
3623   idx1 = getVarint32(aKey1, szHdr1);
3624   if( szHdr1>98307 ) return SQLITE_CORRUPT;
3625   d1 = szHdr1;
3626   assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
3627   assert( pKeyInfo->aSortOrder!=0 );
3628   assert( pKeyInfo->nField>0 );
3629   assert( idx1<=szHdr1 || CORRUPT_DB );
3630   do{
3631     u32 serial_type1;
3632 
3633     /* Read the serial types for the next element in each key. */
3634     idx1 += getVarint32( aKey1+idx1, serial_type1 );
3635 
3636     /* Verify that there is enough key space remaining to avoid
3637     ** a buffer overread.  The "d1+serial_type1+2" subexpression will
3638     ** always be greater than or equal to the amount of required key space.
3639     ** Use that approximation to avoid the more expensive call to
3640     ** sqlite3VdbeSerialTypeLen() in the common case.
3641     */
3642     if( d1+serial_type1+2>(u32)nKey1
3643      && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
3644     ){
3645       break;
3646     }
3647 
3648     /* Extract the values to be compared.
3649     */
3650     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
3651 
3652     /* Do the comparison
3653     */
3654     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
3655     if( rc!=0 ){
3656       assert( mem1.szMalloc==0 );  /* See comment below */
3657       if( pKeyInfo->aSortOrder[i] ){
3658         rc = -rc;  /* Invert the result for DESC sort order. */
3659       }
3660       goto debugCompareEnd;
3661     }
3662     i++;
3663   }while( idx1<szHdr1 && i<pPKey2->nField );
3664 
3665   /* No memory allocation is ever used on mem1.  Prove this using
3666   ** the following assert().  If the assert() fails, it indicates a
3667   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
3668   */
3669   assert( mem1.szMalloc==0 );
3670 
3671   /* rc==0 here means that one of the keys ran out of fields and
3672   ** all the fields up to that point were equal. Return the default_rc
3673   ** value.  */
3674   rc = pPKey2->default_rc;
3675 
3676 debugCompareEnd:
3677   if( desiredResult==0 && rc==0 ) return 1;
3678   if( desiredResult<0 && rc<0 ) return 1;
3679   if( desiredResult>0 && rc>0 ) return 1;
3680   if( CORRUPT_DB ) return 1;
3681   if( pKeyInfo->db->mallocFailed ) return 1;
3682   return 0;
3683 }
3684 #endif
3685 
3686 #ifdef SQLITE_DEBUG
3687 /*
3688 ** Count the number of fields (a.k.a. columns) in the record given by
3689 ** pKey,nKey.  The verify that this count is less than or equal to the
3690 ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
3691 **
3692 ** If this constraint is not satisfied, it means that the high-speed
3693 ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
3694 ** not work correctly.  If this assert() ever fires, it probably means
3695 ** that the KeyInfo.nField or KeyInfo.nXField values were computed
3696 ** incorrectly.
3697 */
vdbeAssertFieldCountWithinLimits(int nKey,const void * pKey,const KeyInfo * pKeyInfo)3698 static void vdbeAssertFieldCountWithinLimits(
3699   int nKey, const void *pKey,   /* The record to verify */
3700   const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
3701 ){
3702   int nField = 0;
3703   u32 szHdr;
3704   u32 idx;
3705   u32 notUsed;
3706   const unsigned char *aKey = (const unsigned char*)pKey;
3707 
3708   if( CORRUPT_DB ) return;
3709   idx = getVarint32(aKey, szHdr);
3710   assert( nKey>=0 );
3711   assert( szHdr<=(u32)nKey );
3712   while( idx<szHdr ){
3713     idx += getVarint32(aKey+idx, notUsed);
3714     nField++;
3715   }
3716   assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
3717 }
3718 #else
3719 # define vdbeAssertFieldCountWithinLimits(A,B,C)
3720 #endif
3721 
3722 /*
3723 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
3724 ** using the collation sequence pColl. As usual, return a negative , zero
3725 ** or positive value if *pMem1 is less than, equal to or greater than
3726 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
3727 */
vdbeCompareMemString(const Mem * pMem1,const Mem * pMem2,const CollSeq * pColl,u8 * prcErr)3728 static int vdbeCompareMemString(
3729   const Mem *pMem1,
3730   const Mem *pMem2,
3731   const CollSeq *pColl,
3732   u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
3733 ){
3734   if( pMem1->enc==pColl->enc ){
3735     /* The strings are already in the correct encoding.  Call the
3736      ** comparison function directly */
3737     return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
3738   }else{
3739     int rc;
3740     const void *v1, *v2;
3741     Mem c1;
3742     Mem c2;
3743     sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
3744     sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
3745     sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
3746     sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
3747     v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
3748     v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
3749     if( (v1==0 || v2==0) ){
3750       if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
3751       rc = 0;
3752     }else{
3753       rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
3754     }
3755     sqlite3VdbeMemRelease(&c1);
3756     sqlite3VdbeMemRelease(&c2);
3757     return rc;
3758   }
3759 }
3760 
3761 /*
3762 ** The input pBlob is guaranteed to be a Blob that is not marked
3763 ** with MEM_Zero.  Return true if it could be a zero-blob.
3764 */
isAllZero(const char * z,int n)3765 static int isAllZero(const char *z, int n){
3766   int i;
3767   for(i=0; i<n; i++){
3768     if( z[i] ) return 0;
3769   }
3770   return 1;
3771 }
3772 
3773 /*
3774 ** Compare two blobs.  Return negative, zero, or positive if the first
3775 ** is less than, equal to, or greater than the second, respectively.
3776 ** If one blob is a prefix of the other, then the shorter is the lessor.
3777 */
sqlite3BlobCompare(const Mem * pB1,const Mem * pB2)3778 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
3779   int c;
3780   int n1 = pB1->n;
3781   int n2 = pB2->n;
3782 
3783   /* It is possible to have a Blob value that has some non-zero content
3784   ** followed by zero content.  But that only comes up for Blobs formed
3785   ** by the OP_MakeRecord opcode, and such Blobs never get passed into
3786   ** sqlite3MemCompare(). */
3787   assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
3788   assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
3789 
3790   if( (pB1->flags|pB2->flags) & MEM_Zero ){
3791     if( pB1->flags & pB2->flags & MEM_Zero ){
3792       return pB1->u.nZero - pB2->u.nZero;
3793     }else if( pB1->flags & MEM_Zero ){
3794       if( !isAllZero(pB2->z, pB2->n) ) return -1;
3795       return pB1->u.nZero - n2;
3796     }else{
3797       if( !isAllZero(pB1->z, pB1->n) ) return +1;
3798       return n1 - pB2->u.nZero;
3799     }
3800   }
3801   c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
3802   if( c ) return c;
3803   return n1 - n2;
3804 }
3805 
3806 /*
3807 ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
3808 ** number.  Return negative, zero, or positive if the first (i64) is less than,
3809 ** equal to, or greater than the second (double).
3810 */
sqlite3IntFloatCompare(i64 i,double r)3811 static int sqlite3IntFloatCompare(i64 i, double r){
3812   if( sizeof(LONGDOUBLE_TYPE)>8 ){
3813     LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
3814     if( x<r ) return -1;
3815     if( x>r ) return +1;
3816     return 0;
3817   }else{
3818     i64 y;
3819     double s;
3820     if( r<-9223372036854775808.0 ) return +1;
3821     if( r>9223372036854775807.0 ) return -1;
3822     y = (i64)r;
3823     if( i<y ) return -1;
3824     if( i>y ){
3825       if( y==SMALLEST_INT64 && r>0.0 ) return -1;
3826       return +1;
3827     }
3828     s = (double)i;
3829     if( s<r ) return -1;
3830     if( s>r ) return +1;
3831     return 0;
3832   }
3833 }
3834 
3835 /*
3836 ** Compare the values contained by the two memory cells, returning
3837 ** negative, zero or positive if pMem1 is less than, equal to, or greater
3838 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
3839 ** and reals) sorted numerically, followed by text ordered by the collating
3840 ** sequence pColl and finally blob's ordered by memcmp().
3841 **
3842 ** Two NULL values are considered equal by this function.
3843 */
sqlite3MemCompare(const Mem * pMem1,const Mem * pMem2,const CollSeq * pColl)3844 int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
3845   int f1, f2;
3846   int combined_flags;
3847 
3848   f1 = pMem1->flags;
3849   f2 = pMem2->flags;
3850   combined_flags = f1|f2;
3851   assert( (combined_flags & MEM_RowSet)==0 );
3852 
3853   /* If one value is NULL, it is less than the other. If both values
3854   ** are NULL, return 0.
3855   */
3856   if( combined_flags&MEM_Null ){
3857     return (f2&MEM_Null) - (f1&MEM_Null);
3858   }
3859 
3860   /* At least one of the two values is a number
3861   */
3862   if( combined_flags&(MEM_Int|MEM_Real) ){
3863     if( (f1 & f2 & MEM_Int)!=0 ){
3864       if( pMem1->u.i < pMem2->u.i ) return -1;
3865       if( pMem1->u.i > pMem2->u.i ) return +1;
3866       return 0;
3867     }
3868     if( (f1 & f2 & MEM_Real)!=0 ){
3869       if( pMem1->u.r < pMem2->u.r ) return -1;
3870       if( pMem1->u.r > pMem2->u.r ) return +1;
3871       return 0;
3872     }
3873     if( (f1&MEM_Int)!=0 ){
3874       if( (f2&MEM_Real)!=0 ){
3875         return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
3876       }else{
3877         return -1;
3878       }
3879     }
3880     if( (f1&MEM_Real)!=0 ){
3881       if( (f2&MEM_Int)!=0 ){
3882         return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
3883       }else{
3884         return -1;
3885       }
3886     }
3887     return +1;
3888   }
3889 
3890   /* If one value is a string and the other is a blob, the string is less.
3891   ** If both are strings, compare using the collating functions.
3892   */
3893   if( combined_flags&MEM_Str ){
3894     if( (f1 & MEM_Str)==0 ){
3895       return 1;
3896     }
3897     if( (f2 & MEM_Str)==0 ){
3898       return -1;
3899     }
3900 
3901     assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
3902     assert( pMem1->enc==SQLITE_UTF8 ||
3903             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
3904 
3905     /* The collation sequence must be defined at this point, even if
3906     ** the user deletes the collation sequence after the vdbe program is
3907     ** compiled (this was not always the case).
3908     */
3909     assert( !pColl || pColl->xCmp );
3910 
3911     if( pColl ){
3912       return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
3913     }
3914     /* If a NULL pointer was passed as the collate function, fall through
3915     ** to the blob case and use memcmp().  */
3916   }
3917 
3918   /* Both values must be blobs.  Compare using memcmp().  */
3919   return sqlite3BlobCompare(pMem1, pMem2);
3920 }
3921 
3922 
3923 /*
3924 ** The first argument passed to this function is a serial-type that
3925 ** corresponds to an integer - all values between 1 and 9 inclusive
3926 ** except 7. The second points to a buffer containing an integer value
3927 ** serialized according to serial_type. This function deserializes
3928 ** and returns the value.
3929 */
vdbeRecordDecodeInt(u32 serial_type,const u8 * aKey)3930 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
3931   u32 y;
3932   assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
3933   switch( serial_type ){
3934     case 0:
3935     case 1:
3936       testcase( aKey[0]&0x80 );
3937       return ONE_BYTE_INT(aKey);
3938     case 2:
3939       testcase( aKey[0]&0x80 );
3940       return TWO_BYTE_INT(aKey);
3941     case 3:
3942       testcase( aKey[0]&0x80 );
3943       return THREE_BYTE_INT(aKey);
3944     case 4: {
3945       testcase( aKey[0]&0x80 );
3946       y = FOUR_BYTE_UINT(aKey);
3947       return (i64)*(int*)&y;
3948     }
3949     case 5: {
3950       testcase( aKey[0]&0x80 );
3951       return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
3952     }
3953     case 6: {
3954       u64 x = FOUR_BYTE_UINT(aKey);
3955       testcase( aKey[0]&0x80 );
3956       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
3957       return (i64)*(i64*)&x;
3958     }
3959   }
3960 
3961   return (serial_type - 8);
3962 }
3963 
3964 /*
3965 ** This function compares the two table rows or index records
3966 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
3967 ** or positive integer if key1 is less than, equal to or
3968 ** greater than key2.  The {nKey1, pKey1} key must be a blob
3969 ** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
3970 ** key must be a parsed key such as obtained from
3971 ** sqlite3VdbeParseRecord.
3972 **
3973 ** If argument bSkip is non-zero, it is assumed that the caller has already
3974 ** determined that the first fields of the keys are equal.
3975 **
3976 ** Key1 and Key2 do not have to contain the same number of fields. If all
3977 ** fields that appear in both keys are equal, then pPKey2->default_rc is
3978 ** returned.
3979 **
3980 ** If database corruption is discovered, set pPKey2->errCode to
3981 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
3982 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
3983 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
3984 */
sqlite3VdbeRecordCompareWithSkip(int nKey1,const void * pKey1,UnpackedRecord * pPKey2,int bSkip)3985 int sqlite3VdbeRecordCompareWithSkip(
3986   int nKey1, const void *pKey1,   /* Left key */
3987   UnpackedRecord *pPKey2,         /* Right key */
3988   int bSkip                       /* If true, skip the first field */
3989 ){
3990   u32 d1;                         /* Offset into aKey[] of next data element */
3991   int i;                          /* Index of next field to compare */
3992   u32 szHdr1;                     /* Size of record header in bytes */
3993   u32 idx1;                       /* Offset of first type in header */
3994   int rc = 0;                     /* Return value */
3995   Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
3996   KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
3997   const unsigned char *aKey1 = (const unsigned char *)pKey1;
3998   Mem mem1;
3999 
4000   /* If bSkip is true, then the caller has already determined that the first
4001   ** two elements in the keys are equal. Fix the various stack variables so
4002   ** that this routine begins comparing at the second field. */
4003   if( bSkip ){
4004     u32 s1;
4005     idx1 = 1 + getVarint32(&aKey1[1], s1);
4006     szHdr1 = aKey1[0];
4007     d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
4008     i = 1;
4009     pRhs++;
4010   }else{
4011     idx1 = getVarint32(aKey1, szHdr1);
4012     d1 = szHdr1;
4013     if( d1>(unsigned)nKey1 ){
4014       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4015       return 0;  /* Corruption */
4016     }
4017     i = 0;
4018   }
4019 
4020   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
4021   assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
4022        || CORRUPT_DB );
4023   assert( pPKey2->pKeyInfo->aSortOrder!=0 );
4024   assert( pPKey2->pKeyInfo->nField>0 );
4025   assert( idx1<=szHdr1 || CORRUPT_DB );
4026   do{
4027     u32 serial_type;
4028 
4029     /* RHS is an integer */
4030     if( pRhs->flags & MEM_Int ){
4031       serial_type = aKey1[idx1];
4032       testcase( serial_type==12 );
4033       if( serial_type>=10 ){
4034         rc = +1;
4035       }else if( serial_type==0 ){
4036         rc = -1;
4037       }else if( serial_type==7 ){
4038         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
4039         rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
4040       }else{
4041         i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
4042         i64 rhs = pRhs->u.i;
4043         if( lhs<rhs ){
4044           rc = -1;
4045         }else if( lhs>rhs ){
4046           rc = +1;
4047         }
4048       }
4049     }
4050 
4051     /* RHS is real */
4052     else if( pRhs->flags & MEM_Real ){
4053       serial_type = aKey1[idx1];
4054       if( serial_type>=10 ){
4055         /* Serial types 12 or greater are strings and blobs (greater than
4056         ** numbers). Types 10 and 11 are currently "reserved for future
4057         ** use", so it doesn't really matter what the results of comparing
4058         ** them to numberic values are.  */
4059         rc = +1;
4060       }else if( serial_type==0 ){
4061         rc = -1;
4062       }else{
4063         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
4064         if( serial_type==7 ){
4065           if( mem1.u.r<pRhs->u.r ){
4066             rc = -1;
4067           }else if( mem1.u.r>pRhs->u.r ){
4068             rc = +1;
4069           }
4070         }else{
4071           rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
4072         }
4073       }
4074     }
4075 
4076     /* RHS is a string */
4077     else if( pRhs->flags & MEM_Str ){
4078       getVarint32(&aKey1[idx1], serial_type);
4079       testcase( serial_type==12 );
4080       if( serial_type<12 ){
4081         rc = -1;
4082       }else if( !(serial_type & 0x01) ){
4083         rc = +1;
4084       }else{
4085         mem1.n = (serial_type - 12) / 2;
4086         testcase( (d1+mem1.n)==(unsigned)nKey1 );
4087         testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
4088         if( (d1+mem1.n) > (unsigned)nKey1 ){
4089           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4090           return 0;                /* Corruption */
4091         }else if( pKeyInfo->aColl[i] ){
4092           mem1.enc = pKeyInfo->enc;
4093           mem1.db = pKeyInfo->db;
4094           mem1.flags = MEM_Str;
4095           mem1.z = (char*)&aKey1[d1];
4096           rc = vdbeCompareMemString(
4097               &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
4098           );
4099         }else{
4100           int nCmp = MIN(mem1.n, pRhs->n);
4101           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
4102           if( rc==0 ) rc = mem1.n - pRhs->n;
4103         }
4104       }
4105     }
4106 
4107     /* RHS is a blob */
4108     else if( pRhs->flags & MEM_Blob ){
4109       assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
4110       getVarint32(&aKey1[idx1], serial_type);
4111       testcase( serial_type==12 );
4112       if( serial_type<12 || (serial_type & 0x01) ){
4113         rc = -1;
4114       }else{
4115         int nStr = (serial_type - 12) / 2;
4116         testcase( (d1+nStr)==(unsigned)nKey1 );
4117         testcase( (d1+nStr+1)==(unsigned)nKey1 );
4118         if( (d1+nStr) > (unsigned)nKey1 ){
4119           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4120           return 0;                /* Corruption */
4121         }else if( pRhs->flags & MEM_Zero ){
4122           if( !isAllZero((const char*)&aKey1[d1],nStr) ){
4123             rc = 1;
4124           }else{
4125             rc = nStr - pRhs->u.nZero;
4126           }
4127         }else{
4128           int nCmp = MIN(nStr, pRhs->n);
4129           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
4130           if( rc==0 ) rc = nStr - pRhs->n;
4131         }
4132       }
4133     }
4134 
4135     /* RHS is null */
4136     else{
4137       serial_type = aKey1[idx1];
4138       rc = (serial_type!=0);
4139     }
4140 
4141     if( rc!=0 ){
4142       if( pKeyInfo->aSortOrder[i] ){
4143         rc = -rc;
4144       }
4145       assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
4146       assert( mem1.szMalloc==0 );  /* See comment below */
4147       return rc;
4148     }
4149 
4150     i++;
4151     pRhs++;
4152     d1 += sqlite3VdbeSerialTypeLen(serial_type);
4153     idx1 += sqlite3VarintLen(serial_type);
4154   }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
4155 
4156   /* No memory allocation is ever used on mem1.  Prove this using
4157   ** the following assert().  If the assert() fails, it indicates a
4158   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
4159   assert( mem1.szMalloc==0 );
4160 
4161   /* rc==0 here means that one or both of the keys ran out of fields and
4162   ** all the fields up to that point were equal. Return the default_rc
4163   ** value.  */
4164   assert( CORRUPT_DB
4165        || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
4166        || pKeyInfo->db->mallocFailed
4167   );
4168   pPKey2->eqSeen = 1;
4169   return pPKey2->default_rc;
4170 }
sqlite3VdbeRecordCompare(int nKey1,const void * pKey1,UnpackedRecord * pPKey2)4171 int sqlite3VdbeRecordCompare(
4172   int nKey1, const void *pKey1,   /* Left key */
4173   UnpackedRecord *pPKey2          /* Right key */
4174 ){
4175   return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
4176 }
4177 
4178 
4179 /*
4180 ** This function is an optimized version of sqlite3VdbeRecordCompare()
4181 ** that (a) the first field of pPKey2 is an integer, and (b) the
4182 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
4183 ** byte (i.e. is less than 128).
4184 **
4185 ** To avoid concerns about buffer overreads, this routine is only used
4186 ** on schemas where the maximum valid header size is 63 bytes or less.
4187 */
vdbeRecordCompareInt(int nKey1,const void * pKey1,UnpackedRecord * pPKey2)4188 static int vdbeRecordCompareInt(
4189   int nKey1, const void *pKey1, /* Left key */
4190   UnpackedRecord *pPKey2        /* Right key */
4191 ){
4192   const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
4193   int serial_type = ((const u8*)pKey1)[1];
4194   int res;
4195   u32 y;
4196   u64 x;
4197   i64 v;
4198   i64 lhs;
4199 
4200   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
4201   assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
4202   switch( serial_type ){
4203     case 1: { /* 1-byte signed integer */
4204       lhs = ONE_BYTE_INT(aKey);
4205       testcase( lhs<0 );
4206       break;
4207     }
4208     case 2: { /* 2-byte signed integer */
4209       lhs = TWO_BYTE_INT(aKey);
4210       testcase( lhs<0 );
4211       break;
4212     }
4213     case 3: { /* 3-byte signed integer */
4214       lhs = THREE_BYTE_INT(aKey);
4215       testcase( lhs<0 );
4216       break;
4217     }
4218     case 4: { /* 4-byte signed integer */
4219       y = FOUR_BYTE_UINT(aKey);
4220       lhs = (i64)*(int*)&y;
4221       testcase( lhs<0 );
4222       break;
4223     }
4224     case 5: { /* 6-byte signed integer */
4225       lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
4226       testcase( lhs<0 );
4227       break;
4228     }
4229     case 6: { /* 8-byte signed integer */
4230       x = FOUR_BYTE_UINT(aKey);
4231       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
4232       lhs = *(i64*)&x;
4233       testcase( lhs<0 );
4234       break;
4235     }
4236     case 8:
4237       lhs = 0;
4238       break;
4239     case 9:
4240       lhs = 1;
4241       break;
4242 
4243     /* This case could be removed without changing the results of running
4244     ** this code. Including it causes gcc to generate a faster switch
4245     ** statement (since the range of switch targets now starts at zero and
4246     ** is contiguous) but does not cause any duplicate code to be generated
4247     ** (as gcc is clever enough to combine the two like cases). Other
4248     ** compilers might be similar.  */
4249     case 0: case 7:
4250       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
4251 
4252     default:
4253       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
4254   }
4255 
4256   v = pPKey2->aMem[0].u.i;
4257   if( v>lhs ){
4258     res = pPKey2->r1;
4259   }else if( v<lhs ){
4260     res = pPKey2->r2;
4261   }else if( pPKey2->nField>1 ){
4262     /* The first fields of the two keys are equal. Compare the trailing
4263     ** fields.  */
4264     res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
4265   }else{
4266     /* The first fields of the two keys are equal and there are no trailing
4267     ** fields. Return pPKey2->default_rc in this case. */
4268     res = pPKey2->default_rc;
4269     pPKey2->eqSeen = 1;
4270   }
4271 
4272   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
4273   return res;
4274 }
4275 
4276 /*
4277 ** This function is an optimized version of sqlite3VdbeRecordCompare()
4278 ** that (a) the first field of pPKey2 is a string, that (b) the first field
4279 ** uses the collation sequence BINARY and (c) that the size-of-header varint
4280 ** at the start of (pKey1/nKey1) fits in a single byte.
4281 */
vdbeRecordCompareString(int nKey1,const void * pKey1,UnpackedRecord * pPKey2)4282 static int vdbeRecordCompareString(
4283   int nKey1, const void *pKey1, /* Left key */
4284   UnpackedRecord *pPKey2        /* Right key */
4285 ){
4286   const u8 *aKey1 = (const u8*)pKey1;
4287   int serial_type;
4288   int res;
4289 
4290   assert( pPKey2->aMem[0].flags & MEM_Str );
4291   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
4292   getVarint32(&aKey1[1], serial_type);
4293   if( serial_type<12 ){
4294     res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
4295   }else if( !(serial_type & 0x01) ){
4296     res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
4297   }else{
4298     int nCmp;
4299     int nStr;
4300     int szHdr = aKey1[0];
4301 
4302     nStr = (serial_type-12) / 2;
4303     if( (szHdr + nStr) > nKey1 ){
4304       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4305       return 0;    /* Corruption */
4306     }
4307     nCmp = MIN( pPKey2->aMem[0].n, nStr );
4308     res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
4309 
4310     if( res==0 ){
4311       res = nStr - pPKey2->aMem[0].n;
4312       if( res==0 ){
4313         if( pPKey2->nField>1 ){
4314           res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
4315         }else{
4316           res = pPKey2->default_rc;
4317           pPKey2->eqSeen = 1;
4318         }
4319       }else if( res>0 ){
4320         res = pPKey2->r2;
4321       }else{
4322         res = pPKey2->r1;
4323       }
4324     }else if( res>0 ){
4325       res = pPKey2->r2;
4326     }else{
4327       res = pPKey2->r1;
4328     }
4329   }
4330 
4331   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
4332        || CORRUPT_DB
4333        || pPKey2->pKeyInfo->db->mallocFailed
4334   );
4335   return res;
4336 }
4337 
4338 /*
4339 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
4340 ** suitable for comparing serialized records to the unpacked record passed
4341 ** as the only argument.
4342 */
sqlite3VdbeFindCompare(UnpackedRecord * p)4343 RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
4344   /* varintRecordCompareInt() and varintRecordCompareString() both assume
4345   ** that the size-of-header varint that occurs at the start of each record
4346   ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
4347   ** also assumes that it is safe to overread a buffer by at least the
4348   ** maximum possible legal header size plus 8 bytes. Because there is
4349   ** guaranteed to be at least 74 (but not 136) bytes of padding following each
4350   ** buffer passed to varintRecordCompareInt() this makes it convenient to
4351   ** limit the size of the header to 64 bytes in cases where the first field
4352   ** is an integer.
4353   **
4354   ** The easiest way to enforce this limit is to consider only records with
4355   ** 13 fields or less. If the first field is an integer, the maximum legal
4356   ** header size is (12*5 + 1 + 1) bytes.  */
4357   if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
4358     int flags = p->aMem[0].flags;
4359     if( p->pKeyInfo->aSortOrder[0] ){
4360       p->r1 = 1;
4361       p->r2 = -1;
4362     }else{
4363       p->r1 = -1;
4364       p->r2 = 1;
4365     }
4366     if( (flags & MEM_Int) ){
4367       return vdbeRecordCompareInt;
4368     }
4369     testcase( flags & MEM_Real );
4370     testcase( flags & MEM_Null );
4371     testcase( flags & MEM_Blob );
4372     if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
4373       assert( flags & MEM_Str );
4374       return vdbeRecordCompareString;
4375     }
4376   }
4377 
4378   return sqlite3VdbeRecordCompare;
4379 }
4380 
4381 /*
4382 ** pCur points at an index entry created using the OP_MakeRecord opcode.
4383 ** Read the rowid (the last field in the record) and store it in *rowid.
4384 ** Return SQLITE_OK if everything works, or an error code otherwise.
4385 **
4386 ** pCur might be pointing to text obtained from a corrupt database file.
4387 ** So the content cannot be trusted.  Do appropriate checks on the content.
4388 */
sqlite3VdbeIdxRowid(sqlite3 * db,BtCursor * pCur,i64 * rowid)4389 int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
4390   i64 nCellKey = 0;
4391   int rc;
4392   u32 szHdr;        /* Size of the header */
4393   u32 typeRowid;    /* Serial type of the rowid */
4394   u32 lenRowid;     /* Size of the rowid */
4395   Mem m, v;
4396 
4397   /* Get the size of the index entry.  Only indices entries of less
4398   ** than 2GiB are support - anything large must be database corruption.
4399   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
4400   ** this code can safely assume that nCellKey is 32-bits
4401   */
4402   assert( sqlite3BtreeCursorIsValid(pCur) );
4403   nCellKey = sqlite3BtreePayloadSize(pCur);
4404   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
4405 
4406   /* Read in the complete content of the index entry */
4407   sqlite3VdbeMemInit(&m, db, 0);
4408   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
4409   if( rc ){
4410     return rc;
4411   }
4412 
4413   /* The index entry must begin with a header size */
4414   (void)getVarint32((u8*)m.z, szHdr);
4415   testcase( szHdr==3 );
4416   testcase( szHdr==m.n );
4417   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
4418     goto idx_rowid_corruption;
4419   }
4420 
4421   /* The last field of the index should be an integer - the ROWID.
4422   ** Verify that the last entry really is an integer. */
4423   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
4424   testcase( typeRowid==1 );
4425   testcase( typeRowid==2 );
4426   testcase( typeRowid==3 );
4427   testcase( typeRowid==4 );
4428   testcase( typeRowid==5 );
4429   testcase( typeRowid==6 );
4430   testcase( typeRowid==8 );
4431   testcase( typeRowid==9 );
4432   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
4433     goto idx_rowid_corruption;
4434   }
4435   lenRowid = sqlite3SmallTypeSizes[typeRowid];
4436   testcase( (u32)m.n==szHdr+lenRowid );
4437   if( unlikely((u32)m.n<szHdr+lenRowid) ){
4438     goto idx_rowid_corruption;
4439   }
4440 
4441   /* Fetch the integer off the end of the index record */
4442   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
4443   *rowid = v.u.i;
4444   sqlite3VdbeMemRelease(&m);
4445   return SQLITE_OK;
4446 
4447   /* Jump here if database corruption is detected after m has been
4448   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
4449 idx_rowid_corruption:
4450   testcase( m.szMalloc!=0 );
4451   sqlite3VdbeMemRelease(&m);
4452   return SQLITE_CORRUPT_BKPT;
4453 }
4454 
4455 /*
4456 ** Compare the key of the index entry that cursor pC is pointing to against
4457 ** the key string in pUnpacked.  Write into *pRes a number
4458 ** that is negative, zero, or positive if pC is less than, equal to,
4459 ** or greater than pUnpacked.  Return SQLITE_OK on success.
4460 **
4461 ** pUnpacked is either created without a rowid or is truncated so that it
4462 ** omits the rowid at the end.  The rowid at the end of the index entry
4463 ** is ignored as well.  Hence, this routine only compares the prefixes
4464 ** of the keys prior to the final rowid, not the entire key.
4465 */
sqlite3VdbeIdxKeyCompare(sqlite3 * db,VdbeCursor * pC,UnpackedRecord * pUnpacked,int * res)4466 int sqlite3VdbeIdxKeyCompare(
4467   sqlite3 *db,                     /* Database connection */
4468   VdbeCursor *pC,                  /* The cursor to compare against */
4469   UnpackedRecord *pUnpacked,       /* Unpacked version of key */
4470   int *res                         /* Write the comparison result here */
4471 ){
4472   i64 nCellKey = 0;
4473   int rc;
4474   BtCursor *pCur;
4475   Mem m;
4476 
4477   assert( pC->eCurType==CURTYPE_BTREE );
4478   pCur = pC->uc.pCursor;
4479   assert( sqlite3BtreeCursorIsValid(pCur) );
4480   nCellKey = sqlite3BtreePayloadSize(pCur);
4481   /* nCellKey will always be between 0 and 0xffffffff because of the way
4482   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
4483   if( nCellKey<=0 || nCellKey>0x7fffffff ){
4484     *res = 0;
4485     return SQLITE_CORRUPT_BKPT;
4486   }
4487   sqlite3VdbeMemInit(&m, db, 0);
4488   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
4489   if( rc ){
4490     return rc;
4491   }
4492   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
4493   sqlite3VdbeMemRelease(&m);
4494   return SQLITE_OK;
4495 }
4496 
4497 /*
4498 ** This routine sets the value to be returned by subsequent calls to
4499 ** sqlite3_changes() on the database handle 'db'.
4500 */
sqlite3VdbeSetChanges(sqlite3 * db,int nChange)4501 void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
4502   assert( sqlite3_mutex_held(db->mutex) );
4503   db->nChange = nChange;
4504   db->nTotalChange += nChange;
4505 }
4506 
4507 /*
4508 ** Set a flag in the vdbe to update the change counter when it is finalised
4509 ** or reset.
4510 */
sqlite3VdbeCountChanges(Vdbe * v)4511 void sqlite3VdbeCountChanges(Vdbe *v){
4512   v->changeCntOn = 1;
4513 }
4514 
4515 /*
4516 ** Mark every prepared statement associated with a database connection
4517 ** as expired.
4518 **
4519 ** An expired statement means that recompilation of the statement is
4520 ** recommend.  Statements expire when things happen that make their
4521 ** programs obsolete.  Removing user-defined functions or collating
4522 ** sequences, or changing an authorization function are the types of
4523 ** things that make prepared statements obsolete.
4524 */
sqlite3ExpirePreparedStatements(sqlite3 * db)4525 void sqlite3ExpirePreparedStatements(sqlite3 *db){
4526   Vdbe *p;
4527   for(p = db->pVdbe; p; p=p->pNext){
4528     p->expired = 1;
4529   }
4530 }
4531 
4532 /*
4533 ** Return the database associated with the Vdbe.
4534 */
sqlite3VdbeDb(Vdbe * v)4535 sqlite3 *sqlite3VdbeDb(Vdbe *v){
4536   return v->db;
4537 }
4538 
4539 /*
4540 ** Return the SQLITE_PREPARE flags for a Vdbe.
4541 */
sqlite3VdbePrepareFlags(Vdbe * v)4542 u8 sqlite3VdbePrepareFlags(Vdbe *v){
4543   return v->prepFlags;
4544 }
4545 
4546 /*
4547 ** Return a pointer to an sqlite3_value structure containing the value bound
4548 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
4549 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
4550 ** constants) to the value before returning it.
4551 **
4552 ** The returned value must be freed by the caller using sqlite3ValueFree().
4553 */
sqlite3VdbeGetBoundValue(Vdbe * v,int iVar,u8 aff)4554 sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
4555   assert( iVar>0 );
4556   if( v ){
4557     Mem *pMem = &v->aVar[iVar-1];
4558     assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
4559     if( 0==(pMem->flags & MEM_Null) ){
4560       sqlite3_value *pRet = sqlite3ValueNew(v->db);
4561       if( pRet ){
4562         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
4563         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
4564       }
4565       return pRet;
4566     }
4567   }
4568   return 0;
4569 }
4570 
4571 /*
4572 ** Configure SQL variable iVar so that binding a new value to it signals
4573 ** to sqlite3_reoptimize() that re-preparing the statement may result
4574 ** in a better query plan.
4575 */
sqlite3VdbeSetVarmask(Vdbe * v,int iVar)4576 void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
4577   assert( iVar>0 );
4578   assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
4579   if( iVar>=32 ){
4580     v->expmask |= 0x80000000;
4581   }else{
4582     v->expmask |= ((u32)1 << (iVar-1));
4583   }
4584 }
4585 
4586 /*
4587 ** Cause a function to throw an error if it was call from OP_PureFunc
4588 ** rather than OP_Function.
4589 **
4590 ** OP_PureFunc means that the function must be deterministic, and should
4591 ** throw an error if it is given inputs that would make it non-deterministic.
4592 ** This routine is invoked by date/time functions that use non-deterministic
4593 ** features such as 'now'.
4594 */
sqlite3NotPureFunc(sqlite3_context * pCtx)4595 int sqlite3NotPureFunc(sqlite3_context *pCtx){
4596 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
4597   if( pCtx->pVdbe==0 ) return 1;
4598 #endif
4599   if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
4600     sqlite3_result_error(pCtx,
4601        "non-deterministic function in index expression or CHECK constraint",
4602        -1);
4603     return 0;
4604   }
4605   return 1;
4606 }
4607 
4608 #ifndef SQLITE_OMIT_VIRTUALTABLE
4609 /*
4610 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
4611 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
4612 ** in memory obtained from sqlite3DbMalloc).
4613 */
sqlite3VtabImportErrmsg(Vdbe * p,sqlite3_vtab * pVtab)4614 void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
4615   if( pVtab->zErrMsg ){
4616     sqlite3 *db = p->db;
4617     sqlite3DbFree(db, p->zErrMsg);
4618     p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
4619     sqlite3_free(pVtab->zErrMsg);
4620     pVtab->zErrMsg = 0;
4621   }
4622 }
4623 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4624 
4625 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4626 
4627 /*
4628 ** If the second argument is not NULL, release any allocations associated
4629 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
4630 ** structure itself, using sqlite3DbFree().
4631 **
4632 ** This function is used to free UnpackedRecord structures allocated by
4633 ** the vdbeUnpackRecord() function found in vdbeapi.c.
4634 */
vdbeFreeUnpacked(sqlite3 * db,int nField,UnpackedRecord * p)4635 static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
4636   if( p ){
4637     int i;
4638     for(i=0; i<nField; i++){
4639       Mem *pMem = &p->aMem[i];
4640       if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
4641     }
4642     sqlite3DbFreeNN(db, p);
4643   }
4644 }
4645 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
4646 
4647 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4648 /*
4649 ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
4650 ** then cursor passed as the second argument should point to the row about
4651 ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
4652 ** the required value will be read from the row the cursor points to.
4653 */
sqlite3VdbePreUpdateHook(Vdbe * v,VdbeCursor * pCsr,int op,const char * zDb,Table * pTab,i64 iKey1,int iReg)4654 void sqlite3VdbePreUpdateHook(
4655   Vdbe *v,                        /* Vdbe pre-update hook is invoked by */
4656   VdbeCursor *pCsr,               /* Cursor to grab old.* values from */
4657   int op,                         /* SQLITE_INSERT, UPDATE or DELETE */
4658   const char *zDb,                /* Database name */
4659   Table *pTab,                    /* Modified table */
4660   i64 iKey1,                      /* Initial key value */
4661   int iReg                        /* Register for new.* record */
4662 ){
4663   sqlite3 *db = v->db;
4664   i64 iKey2;
4665   PreUpdate preupdate;
4666   const char *zTbl = pTab->zName;
4667   static const u8 fakeSortOrder = 0;
4668 
4669   assert( db->pPreUpdate==0 );
4670   memset(&preupdate, 0, sizeof(PreUpdate));
4671   if( HasRowid(pTab)==0 ){
4672     iKey1 = iKey2 = 0;
4673     preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
4674   }else{
4675     if( op==SQLITE_UPDATE ){
4676       iKey2 = v->aMem[iReg].u.i;
4677     }else{
4678       iKey2 = iKey1;
4679     }
4680   }
4681 
4682   assert( pCsr->nField==pTab->nCol
4683        || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
4684   );
4685 
4686   preupdate.v = v;
4687   preupdate.pCsr = pCsr;
4688   preupdate.op = op;
4689   preupdate.iNewReg = iReg;
4690   preupdate.keyinfo.db = db;
4691   preupdate.keyinfo.enc = ENC(db);
4692   preupdate.keyinfo.nField = pTab->nCol;
4693   preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
4694   preupdate.iKey1 = iKey1;
4695   preupdate.iKey2 = iKey2;
4696   preupdate.pTab = pTab;
4697 
4698   db->pPreUpdate = &preupdate;
4699   db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
4700   db->pPreUpdate = 0;
4701   sqlite3DbFree(db, preupdate.aRecord);
4702   vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pUnpacked);
4703   vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pNewUnpacked);
4704   if( preupdate.aNew ){
4705     int i;
4706     for(i=0; i<pCsr->nField; i++){
4707       sqlite3VdbeMemRelease(&preupdate.aNew[i]);
4708     }
4709     sqlite3DbFreeNN(db, preupdate.aNew);
4710   }
4711 }
4712 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
4713